From 25de91321b6e25a41a9958e43dd3abf46eaa700d Mon Sep 17 00:00:00 2001 From: jefftj86 Date: Thu, 29 Oct 2026 22:03:34 -0700 Subject: [PATCH 1/5] feat: publish encrypted local workbench Add explicit encrypted startup, adoption and recovery with native-owned custody. Preserve readable-export boundaries and current platform qualification limits. Publish instruction history, bounded file discovery, Markdown review and exact saved-revision compilation continuity. Retain newer public integration modules and keep historical recovery source unmounted. --- .github/workflows/source-checks.yml | 37 +- Cargo.lock | 1 + Cargo.toml | 4 +- README.md | 107 +- apps/desktop/Cargo.lock | 14 + apps/desktop/Cargo.toml | 36 +- apps/desktop/build.rs | 8 + .../desktop/capabilities/source-analysis.json | 10 +- .../cases.v1.json | 11 + .../tauri.conf.json | 22 + .../cases.v1.json | 466 +++ .../tauri.conf.json | 76 + .../native-exit-qualification/tauri.conf.json | 29 + apps/desktop/native-input/Cargo.toml | 17 + apps/desktop/native-input/src/lib.rs | 219 ++ apps/desktop/native-input/src/macos.rs | 278 ++ apps/desktop/native-input/src/tests.rs | 180 ++ apps/desktop/src/cloud_models.rs | 13 + apps/desktop/src/cloud_models_tests.rs | 2 +- apps/desktop/src/composition.rs | 4 +- apps/desktop/src/data_controls.rs | 148 + apps/desktop/src/encrypted_recovery.rs | 364 +++ apps/desktop/src/encrypted_recovery_tests.rs | 130 + apps/desktop/src/main.rs | 290 +- .../src/native_credential_qualification.rs | 597 ++++ .../desktop/src/native_encrypted_case_plan.rs | 647 +++++ .../src/native_encrypted_qualification.rs | 1143 ++++++++ apps/desktop/src/native_encrypted_seeds.rs | 377 +++ apps/desktop/src/native_exit_qualification.rs | 441 +++ apps/desktop/src/openshell_credential.rs | 120 + .../desktop/src/openshell_credential_tests.rs | 803 ++++++ apps/desktop/src/openshell_host.rs | 340 ++- apps/desktop/src/openshell_host_tests.rs | 781 ++++- apps/desktop/src/openshell_native_input.rs | 238 ++ apps/desktop/src/openshell_session_view.rs | 450 +++ .../src/openshell_session_view_tests.rs | 956 +++++++ apps/desktop/src/source_collection.rs | 157 ++ apps/desktop/src/workspace_adoption.rs | 1421 ++++++++++ .../src/workspace_adoption_owner_tests.rs | 169 ++ apps/desktop/src/workspace_adoption_record.rs | 172 ++ .../src/workspace_adoption_record_tests.rs | 304 ++ apps/desktop/src/workspace_adoption_tests.rs | 2510 +++++++++++++++++ apps/desktop/src/workspace_close.rs | 41 +- apps/desktop/src/workspace_close_control.rs | 161 ++ .../src/workspace_close_control_tests.rs | 159 ++ .../src/workspace_empty_provisioning_tests.rs | 802 ++++++ apps/desktop/src/workspace_failure.rs | 12 +- .../src/workspace_managed_bootstrap_tests.rs | 627 ++++ .../desktop/src/workspace_native_bootstrap.rs | 190 ++ .../src/workspace_native_bootstrap_tests.rs | 1289 +++++++++ apps/desktop/src/workspace_recovery.rs | 248 +- .../src/workspace_recovery_file_tests.rs | 510 ++++ apps/desktop/src/workspace_reopen.rs | 56 +- apps/desktop/src/workspace_session.rs | 100 +- apps/desktop/src/workspace_setup.rs | 137 +- apps/desktop/src/workspace_setup_tests.rs | 156 +- apps/desktop/src/workspace_source_access.rs | 472 +++- .../src/workspace_source_access_tests.rs | 60 +- apps/desktop/src/workspace_startup.rs | 668 +++++ apps/desktop/src/workspace_startup_host.rs | 1618 +++++++++++ .../src/workspace_startup_host_tests.rs | 459 +++ .../src/workspace_startup_owner_tests.rs | 232 ++ apps/desktop/src/workspace_startup_tests.rs | 775 +++++ .../src/workspace_workflow_access_tests.rs | 4 +- crates/rangoon-cli/src/main.rs | 4 +- crates/rangoon-cli/tests/bundle.rs | 4 +- crates/rangoon-compile/src/bundle_tests.rs | 4 +- crates/rangoon-compose/src/lib.rs | 22 +- crates/rangoon-host/Cargo.toml | 1 + crates/rangoon-host/src/lib.rs | 16 +- crates/rangoon-host/src/source_collection.rs | 266 ++ crates/rangoon-host/src/source_inventory.rs | 915 ++++++ .../src/lnsat_evidence.rs | 80 +- .../src/lnsat_request_record.rs | 4 +- .../src/openshell_observation.rs | 23 +- .../tests/lnsat_evidence.rs | 151 +- crates/rangoon-language/tests/d0a.rs | 2 +- crates/rangoon-model-cloud/src/check_wire.rs | 2 +- crates/rangoon-model-cloud/src/transport.rs | 8 +- crates/rangoon-model-cloud/src/wire.rs | 8 +- crates/rangoon-model-local/src/transport.rs | 8 +- crates/rangoon-model-session/src/cloud.rs | 9 +- crates/rangoon-model-session/src/lib.rs | 9 +- crates/rangoon-openshell-client/src/lib.rs | 76 +- crates/rangoon-ops/src/approvals.rs | 36 +- crates/rangoon-ops/src/delegations.rs | 8 +- crates/rangoon-ops/src/lifecycle.rs | 98 +- crates/rangoon-ops/src/operator_view.rs | 23 +- crates/rangoon-ops/src/operator_view_tests.rs | 84 + crates/rangoon-ops/src/projection.rs | 52 +- crates/rangoon-ops/src/relationship_tests.rs | 157 ++ crates/rangoon-ops/src/relationships.rs | 16 +- .../rangoon-ops/tests/operator_view_parity.rs | 122 +- crates/rangoon-recovery/Cargo.lock | 1256 +++++++++ crates/rangoon-recovery/Cargo.toml | 21 + crates/rangoon-recovery/README.md | 25 + crates/rangoon-recovery/src/lib.rs | 206 ++ crates/rangoon-recovery/tests/envelope.rs | 280 ++ .../tests/fixtures/reference-age-v1.json | 9 + .../rangoon-store/src/composition_backup.rs | 6 +- .../rangoon-store/src/composition_records.rs | 18 +- crates/rangoon-store/src/encryption.rs | 2 +- .../rangoon-store/src/instruction_history.rs | 890 ++++++ .../src/instruction_history_backup.rs | 277 ++ .../src/instruction_history_tests.rs | 1145 ++++++++ crates/rangoon-store/src/lib.rs | 43 +- crates/rangoon-store/src/recovery_copy.rs | 122 + .../rangoon-store/src/recovery_copy_tests.rs | 171 ++ crates/rangoon-store/src/workflow_backup.rs | 303 +- .../src/workflow_backup_tests.rs | 2 +- crates/rangoon-store/src/workflow_deletion.rs | 7 +- .../rangoon-store/src/workflow_mutations.rs | 36 +- crates/rangoon-store/src/workflow_recovery.rs | 214 +- crates/rangoon-store/src/workflow_saves.rs | 4 +- crates/rangoon-store/src/workflow_views.rs | 6 +- .../src/workspace_adoption_tests.rs | 386 +++ .../src/workspace_capture_tests.rs | 420 +++ docs/application-architecture.md | 129 +- docs/continue.md | 284 +- docs/customer-zero-gap-analysis.md | 106 + docs/desktop-spike.md | 6 +- docs/development.md | 1824 +++++++++++- docs/encrypted-workspace.md | 687 ++++- docs/export-handoff.md | 2 +- docs/focused-workbench-site-brief.md | 50 + docs/instruction-bundle.md | 2 +- docs/intent.md | 270 +- docs/lnsat-evidence-connector.md | 42 +- docs/model-cloud-custody.md | 2 +- docs/openhands-comparison.md | 76 + docs/openshell-observation-connector.md | 242 +- docs/operations-control-plane.md | 10 +- docs/operations-local-window.md | 2 +- docs/plan.md | 106 +- docs/product-experience.md | 218 ++ docs/provider-interoperability.md | 19 + docs/reviewer-guide.md | 17 +- docs/system-audit.md | 107 + docs/target-loader-qualification.md | 165 +- docs/visual-system.md | 11 + docs/workflow-definitions.md | 2 +- docs/workflow-records.md | 2 +- .../phase8-public-main-f669181a.json | 4 +- .../synthetic-decision-view-v1.json | 1 + .../synthetic-decision-window-v1.json | 1 + preview/agent-files-model.mjs | 264 ++ preview/agent-files-view.mjs | 158 ++ preview/agent-files.css | 33 + preview/analysis-model.mjs | 32 +- preview/analyze.css | 23 + preview/analyze.html | 4 + preview/analyze.mjs | 460 ++- preview/assets/foundations/provenance.json | 18 + preview/assets/foundations/vusl-logo.png | Bin 0 -> 1025861 bytes preview/authority-view.mjs | 5 +- preview/compilation-model.mjs | 51 +- preview/compilation-view.mjs | 25 +- preview/composition-view.mjs | 183 +- preview/composition.css | 52 + preview/desktop-startup-model.mjs | 156 + preview/desktop-startup-session.mjs | 216 ++ preview/desktop-startup-view.mjs | 89 + preview/desktop-startup.css | 2 + preview/engine-view.mjs | 4 +- preview/engine.css | 1 + preview/foundation-marks.mjs | 31 + preview/foundations.css | 198 ++ preview/markdown-find.mjs | 178 ++ preview/markdown-review.css | 19 + preview/markdown-review.mjs | 145 + preview/operations-model.mjs | 36 +- preview/operations-view.mjs | 16 +- preview/operations.css | 9 + preview/remote-inventory-model.mjs | 165 ++ preview/skill-compile-handoff.mjs | 37 + preview/skills-model.mjs | 14 + preview/skills-view.mjs | 86 +- preview/technical-details.mjs | 6 + preview/workbench-navigation.mjs | 14 +- preview/workbench-refinement.css | 115 + preview/workbench-shell.css | 22 + preview/workspace-lock-model.mjs | 32 +- preview/workspace-lock-view.mjs | 59 +- preview/workspace-model.mjs | 91 +- preview/workspace-view.mjs | 180 +- preview/workspace.css | 4 +- rust-toolchain.toml | 4 + scripts/check-source-rust.mjs | 225 +- scripts/qa-agent-files.mjs | 85 + scripts/qa-composition-interaction.mjs | 60 + scripts/qa-desktop-startup.mjs | 264 ++ scripts/qa-skills-interaction.mjs | 83 + scripts/qa-workspace-lock.mjs | 7 + scripts/qualify-native-credential.py | 600 ++++ scripts/qualify-native-encrypted.py | 989 +++++++ scripts/qualify-native-exit.py | 207 ++ scripts/qualify-target-isolation.py | 274 ++ scripts/validate-vision.mjs | 23 +- tests/agent-files-model.test.mjs | 181 ++ tests/agent-files-view.test.mjs | 211 ++ tests/analysis.test.mjs | 29 +- tests/authority-view.test.mjs | 7 + tests/check-source-rust.test.mjs | 149 + tests/compilation-model.test.mjs | 107 + tests/compilation-view.test.mjs | 36 +- tests/composition-view.test.mjs | 174 +- tests/desktop-startup-model.test.mjs | 146 + tests/desktop-startup-session.test.mjs | 267 ++ tests/desktop-startup-view.test.mjs | 66 + tests/engine.test.mjs | 4 + tests/fixtures/remote-inventory.v1.json | 150 + tests/fixtures/target-isolation-probe.c | 60 + tests/foundation-marks.test.mjs | 70 + tests/markdown-find.test.mjs | 74 + tests/markdown-review.test.mjs | 96 + tests/operations-model.test.mjs | 155 + tests/operations-parity.test.mjs | 73 +- tests/operations-view.test.mjs | 40 + tests/qualify_native_credential_test.py | 876 ++++++ tests/qualify_native_encrypted_test.py | 863 ++++++ tests/qualify_target_isolation_test.py | 193 ++ tests/remote-inventory-model.test.mjs | 198 ++ tests/skill-compile-handoff.test.mjs | 62 + tests/skills-model.test.mjs | 49 + tests/skills-view.test.mjs | 62 +- tests/term-help.test.mjs | 5 +- tests/vendor-marks.test.mjs | 2 +- tests/workbench-navigation.test.mjs | 18 +- tests/workspace-close-quit.test.mjs | 96 + tests/workspace-encrypted-recovery.test.mjs | 157 ++ tests/workspace-lock-model.test.mjs | 174 ++ tests/workspace-lock-view.test.mjs | 26 +- tests/workspace-model.test.mjs | 71 +- tests/workspace-requests.test.mjs | 32 + tests/workspace-save-disclosure.test.mjs | 45 + tests/workspace-view-purge.test.mjs | 125 + 236 files changed, 45623 insertions(+), 892 deletions(-) create mode 100644 apps/desktop/native-credential-qualification/cases.v1.json create mode 100644 apps/desktop/native-credential-qualification/tauri.conf.json create mode 100644 apps/desktop/native-encrypted-qualification/cases.v1.json create mode 100644 apps/desktop/native-encrypted-qualification/tauri.conf.json create mode 100644 apps/desktop/native-exit-qualification/tauri.conf.json create mode 100644 apps/desktop/native-input/Cargo.toml create mode 100644 apps/desktop/native-input/src/lib.rs create mode 100644 apps/desktop/native-input/src/macos.rs create mode 100644 apps/desktop/native-input/src/tests.rs create mode 100644 apps/desktop/src/encrypted_recovery.rs create mode 100644 apps/desktop/src/encrypted_recovery_tests.rs create mode 100644 apps/desktop/src/native_credential_qualification.rs create mode 100644 apps/desktop/src/native_encrypted_case_plan.rs create mode 100644 apps/desktop/src/native_encrypted_qualification.rs create mode 100644 apps/desktop/src/native_encrypted_seeds.rs create mode 100644 apps/desktop/src/native_exit_qualification.rs create mode 100644 apps/desktop/src/openshell_credential.rs create mode 100644 apps/desktop/src/openshell_credential_tests.rs create mode 100644 apps/desktop/src/openshell_native_input.rs create mode 100644 apps/desktop/src/openshell_session_view.rs create mode 100644 apps/desktop/src/openshell_session_view_tests.rs create mode 100644 apps/desktop/src/source_collection.rs create mode 100644 apps/desktop/src/workspace_adoption.rs create mode 100644 apps/desktop/src/workspace_adoption_owner_tests.rs create mode 100644 apps/desktop/src/workspace_adoption_record.rs create mode 100644 apps/desktop/src/workspace_adoption_record_tests.rs create mode 100644 apps/desktop/src/workspace_adoption_tests.rs create mode 100644 apps/desktop/src/workspace_empty_provisioning_tests.rs create mode 100644 apps/desktop/src/workspace_managed_bootstrap_tests.rs create mode 100644 apps/desktop/src/workspace_native_bootstrap.rs create mode 100644 apps/desktop/src/workspace_native_bootstrap_tests.rs create mode 100644 apps/desktop/src/workspace_recovery_file_tests.rs create mode 100644 apps/desktop/src/workspace_startup.rs create mode 100644 apps/desktop/src/workspace_startup_host.rs create mode 100644 apps/desktop/src/workspace_startup_host_tests.rs create mode 100644 apps/desktop/src/workspace_startup_owner_tests.rs create mode 100644 apps/desktop/src/workspace_startup_tests.rs create mode 100644 crates/rangoon-host/src/source_collection.rs create mode 100644 crates/rangoon-host/src/source_inventory.rs create mode 100644 crates/rangoon-recovery/Cargo.lock create mode 100644 crates/rangoon-recovery/Cargo.toml create mode 100644 crates/rangoon-recovery/README.md create mode 100644 crates/rangoon-recovery/src/lib.rs create mode 100644 crates/rangoon-recovery/tests/envelope.rs create mode 100644 crates/rangoon-recovery/tests/fixtures/reference-age-v1.json create mode 100644 crates/rangoon-store/src/instruction_history.rs create mode 100644 crates/rangoon-store/src/instruction_history_backup.rs create mode 100644 crates/rangoon-store/src/instruction_history_tests.rs create mode 100644 crates/rangoon-store/src/recovery_copy.rs create mode 100644 crates/rangoon-store/src/recovery_copy_tests.rs create mode 100644 crates/rangoon-store/src/workspace_adoption_tests.rs create mode 100644 crates/rangoon-store/src/workspace_capture_tests.rs create mode 100644 docs/customer-zero-gap-analysis.md create mode 100644 docs/focused-workbench-site-brief.md create mode 100644 docs/openhands-comparison.md create mode 100644 fixtures/operations/synthetic-decision-view-v1.json create mode 100644 fixtures/operations/synthetic-decision-window-v1.json create mode 100644 preview/agent-files-model.mjs create mode 100644 preview/agent-files-view.mjs create mode 100644 preview/agent-files.css create mode 100644 preview/assets/foundations/provenance.json create mode 100644 preview/assets/foundations/vusl-logo.png create mode 100644 preview/desktop-startup-model.mjs create mode 100644 preview/desktop-startup-session.mjs create mode 100644 preview/desktop-startup-view.mjs create mode 100644 preview/desktop-startup.css create mode 100644 preview/foundation-marks.mjs create mode 100644 preview/foundations.css create mode 100644 preview/markdown-find.mjs create mode 100644 preview/markdown-review.css create mode 100644 preview/markdown-review.mjs create mode 100644 preview/remote-inventory-model.mjs create mode 100644 preview/skill-compile-handoff.mjs create mode 100644 preview/technical-details.mjs create mode 100644 preview/workbench-refinement.css create mode 100644 rust-toolchain.toml create mode 100644 scripts/qa-agent-files.mjs create mode 100644 scripts/qa-composition-interaction.mjs create mode 100644 scripts/qa-desktop-startup.mjs create mode 100644 scripts/qa-skills-interaction.mjs create mode 100644 scripts/qualify-native-credential.py create mode 100644 scripts/qualify-native-encrypted.py create mode 100644 scripts/qualify-native-exit.py create mode 100644 scripts/qualify-target-isolation.py create mode 100644 tests/agent-files-model.test.mjs create mode 100644 tests/agent-files-view.test.mjs create mode 100644 tests/check-source-rust.test.mjs create mode 100644 tests/desktop-startup-model.test.mjs create mode 100644 tests/desktop-startup-session.test.mjs create mode 100644 tests/desktop-startup-view.test.mjs create mode 100644 tests/fixtures/remote-inventory.v1.json create mode 100644 tests/fixtures/target-isolation-probe.c create mode 100644 tests/foundation-marks.test.mjs create mode 100644 tests/markdown-find.test.mjs create mode 100644 tests/markdown-review.test.mjs create mode 100644 tests/qualify_native_credential_test.py create mode 100644 tests/qualify_native_encrypted_test.py create mode 100644 tests/qualify_target_isolation_test.py create mode 100644 tests/remote-inventory-model.test.mjs create mode 100644 tests/skill-compile-handoff.test.mjs create mode 100644 tests/workspace-close-quit.test.mjs create mode 100644 tests/workspace-encrypted-recovery.test.mjs create mode 100644 tests/workspace-save-disclosure.test.mjs diff --git a/.github/workflows/source-checks.yml b/.github/workflows/source-checks.yml index 45b2511..496ac0d 100644 --- a/.github/workflows/source-checks.yml +++ b/.github/workflows/source-checks.yml @@ -8,6 +8,10 @@ on: permissions: contents: read +env: + RANGOON_RUST_VERSION: '1.99.1' + RUSTUP_AUTO_INSTALL: '0' + concurrency: group: source-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true @@ -25,16 +29,15 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - name: Install the minimum supported source toolchain - run: rustup toolchain install 1.85.0 --profile minimal --component rustfmt --component clippy - - name: Toolchain evidence - run: rustup run 1.85.0 rustc -vV - - name: Format - run: cargo +1.85.0 fmt --all -- --check - - name: Tests - run: cargo +1.85.0 test --workspace --locked - - name: Clippy - run: cargo +1.85.0 clippy --workspace --all-targets --locked -- -D warnings + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: '24.21.0' + - name: Check Rust version coherence before provisioning + run: node scripts/check-source-rust.mjs --check-config + - name: Install the pinned Rust toolchain + run: rustup toolchain install ${{ env.RANGOON_RUST_VERSION }} --profile minimal --component rustfmt --component clippy + - name: Core toolchain coherence, format, tests and Clippy + run: node scripts/check-source-rust.mjs preview: name: Preview and review artifacts @@ -63,15 +66,17 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: '24.21.0' + - name: Check Rust version coherence before provisioning + run: node scripts/check-source-rust.mjs --check-config - name: Linux WebView build dependencies if: runner.os == 'Linux' run: | sudo apt-get update sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev - name: Desktop toolchain - run: rustup toolchain install 1.98.0 --profile minimal --component rustfmt --component clippy - - run: cargo +1.98.0 fmt --manifest-path apps/desktop/Cargo.toml -- --check - - run: cargo +1.98.0 test --manifest-path apps/desktop/Cargo.toml --locked - - run: cargo +1.98.0 clippy --manifest-path apps/desktop/Cargo.toml --all-targets --locked -- -D warnings - - name: Build native executable without installers - run: cargo +1.98.0 build --manifest-path apps/desktop/Cargo.toml --locked + run: rustup toolchain install ${{ env.RANGOON_RUST_VERSION }} --profile minimal --component rustfmt --component clippy + - name: Desktop toolchain coherence, format, tests, Clippy and native build without installers + run: node scripts/check-source-rust.mjs --desktop diff --git a/Cargo.lock b/Cargo.lock index d85cdb0..6658b23 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -795,6 +795,7 @@ dependencies = [ "rangoon-compile", "rangoon-domain", "rangoon-import", + "rustix", "serde", "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index d220e70..5532359 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,13 +1,13 @@ [workspace] members = ["crates/rangoon-domain", "crates/rangoon-import", "crates/rangoon-cli", "crates/rangoon-host", "crates/rangoon-store", "crates/rangoon-engine", "crates/rangoon-compose", "crates/rangoon-compile", "crates/rangoon-model-assistance", "crates/rangoon-model-local", "crates/rangoon-model-session", "crates/rangoon-model-cloud", "crates/rangoon-workflow", "crates/rangoon-ops", "crates/rangoon-integrations", "crates/rangoon-language", "crates/rangoon-openshell-client"] -exclude = ["apps/desktop"] +exclude = ["apps/desktop", "crates/rangoon-recovery"] resolver = "3" [workspace.package] license = "Apache-2.0" version = "0.1.0-dev" edition = "2024" -rust-version = "1.85" +rust-version = "1.99.1" publish = false repository = "https://github.com/hypler-dev/rangoon" diff --git a/README.md b/README.md index 4fb9427..083d479 100644 --- a/README.md +++ b/README.md @@ -11,11 +11,11 @@ Turn scattered `AGENTS.md`, `CLAUDE.md`, `SKILL.md` and project instructions int The desktop application is named **Rangoon**; Rangoon.si is the product wordmark. **Superintelligence (super intelligence, SI)** describes the long-term direction, not a claim of current superintelligence or guaranteed autonomous safety. The free open-source desktop workbench is Apache-2.0. macOS, Windows and Linux remain the initial desktop release targets; team/cloud/enterprise operation is a later stage. -**Current status:** experimental native source workbench with real persistence, immutable skill/workflow revisions, composition, compilation/export/inspection, and explicitly consented advisory model paths. Production storage and portable recovery backups are still plaintext. Optional SQLCipher, native Owner/key custody, typed command routing and coordinated native/renderer close/purge are implemented source and tests. Durable E1c-1 checkpoints/reconciliation and source-free setup/unlock renderer controls are implemented; qualified encrypted factory mounting, Legacy adoption and platform checks still gate an encrypted desktop. No live agent executor, scheduler, authority adapter or plugin runtime is mounted. +**Current status:** an experimental native workbench with persistence, immutable skill/workflow revisions, composition, compilation/export/inspection and explicitly consented advisory model paths. The ordinary desktop source enables encrypted-workspace startup by default, with explicit setup/unlock and no plaintext fallback. Encrypted recovery has dated disposable macOS evidence, including recovery into a fresh independently keyed workspace and restart. Windows startup/custody/recovery remains unsupported in the current implementation; Linux GUI/custody and packaged release qualification remain open. Original instruction files and deliberately readable exports are outside workspace encryption. No live agent executor, scheduler, authority adapter or plugin runtime is mounted. -The [October 16 architecture and usability checkpoint](docs/system-audit.md#october-16-architecture-and-usability-drift-checkpoint) updates the [October 15 whole-system audit](docs/system-audit.md#october-15-whole-system-audit-and-completion-map). The [completion plan](docs/plan.md#october-15-audit-completion-sequence) puts recovery, installed local tasks and usable editing ahead of more disconnected demonstrations. The [development ledger](docs/development.md) records exact validation and limits. Source tests, checksums, model reviews and source CI do not establish runtime enforcement, target-loader compatibility, desktop support or certification. +The [October 29 whole-application audit](docs/system-audit.md#october-29-whole-application-viability-and-drift-audit) reconciles current source against earlier architecture and usability checkpoints. The [completion plan](docs/plan.md#october-15-audit-completion-sequence) puts recovery, installed local tasks and usable editing ahead of more disconnected demonstrations. The [development ledger](docs/development.md) records exact validation and limits. Source tests, checksums, model reviews and source CI do not establish runtime enforcement, target-loader compatibility, desktop support or certification. -**Review today:** [the reviewer guide](docs/reviewer-guide.md) provides a short design/source task and a disposable-data native task. Browser samples and playgrounds are synthetic. The local Operations window reads one selected report and shows unverified observations; it is not a live feed. Production workspace data and portable backups remain plaintext, so external testers should not import private projects. Broader desktop beta and three-OS release support have separate qualification gates. +**Review today:** [the reviewer guide](docs/reviewer-guide.md) provides a short design/source task and a disposable-data native task. Browser samples and playgrounds are synthetic. The local Operations window reads one selected report and shows unverified observations; it is not a live feed. Use disposable data in an explicitly isolated review profile. Earlier macOS recovery evidence does not qualify the current working tree, normal-profile migration or every platform. Broader desktop beta and three-OS release support have separate qualification gates. A fresh macOS development binary exposed and then passed a repair for a startup lifecycle panic caused by registering a native failure anchor before Tauri `setup`. The [native startup receipt](docs/development.md#native-startup-lifecycle-repair--october-16-2026) records the direct-binary smoke, source checks and independent review. Installed GUI task qualification remains open. @@ -25,6 +25,18 @@ Approval management, redacted correlated telemetry and live operations visualiza The [cross-runtime operator-record target](docs/operations-control-plane.md#cross-runtime-operator-record-acceptance-target) defines what Rangoon must show for denied, approved, changed, repeated and uncertain actions. It prioritizes read-only OpenShell observations for this goal while LNSAT evidence remains an independent later gate. No live cross-runtime record exists today. +## Application source update — October 29, 2026 + +This update brings the current local workbench into one source snapshot: encrypted default startup and recovery, instruction-history persistence, native lifecycle hardening, bounded Agent files and folder metadata, Markdown review/find, and exact saved-skill handoff to Compile. It preserves the newer public LNSAT offline inspection modules and independent VUSL direction. Rust manifests, local checks and source CI use the same **1.99.1** toolchain. + +Folder browsing returns metadata; inspecting content still requires an explicit file selection. Remote inventory remains an offline contract, live providers/execution remain unavailable, and a desktop release still needs current-artifact and platform qualification. Original instruction files and deliberately readable exports remain outside workspace encryption. The [full publication receipt](docs/development.md#full-application-source-publication--october-29-2026) records validation, independent review, exclusions and the next native workflow milestone. + +## Local workflow checkpoint — October 29, 2026 + +**Open in Compile** carries a selected saved skill revision directly from Skills into Compile through an exact native read. Historical selection stays pinned; compilation, format choice and export remain explicit. Dirty edits for that skill, conflicts and pending requests block the handoff with recovery guidance. Navigation and Lock invalidate late reads. This slice has source-test evidence; the full-publication receipt records its additional synthetic rendered checks. Native task qualification remains separate. [Receipt and next steps](docs/development.md#cw-1-saved-revision-compile-handoff--october-29-2026). + +Agent files already has bounded native folder metadata selection, source inspection and IDE-style Markdown review. Folder rows still require a separate explicit file selection to inspect content; persistent tags/indexing, remote transport and copying/applying instructions remain future work. The immediate completion order is a repeatable isolated native workflow, safe row-inspection custody, then one qualified external target. A custom executor, scheduler or larger demonstration catalog is not required for that local milestone. + ## Engineering checkpoint — October 18, 2026 This source update brings the independent integration contracts and lifecycle work together while preserving the useful local workbench. The [publication receipt](docs/development.md#research-and-source-publication--october-18-2026) records checks and remaining gates. @@ -40,8 +52,11 @@ The [transcript-backed research and primary-source audit](docs/harness-research- ## Contents -- [Engineering checkpoint](#engineering-checkpoint--october-18-2026) -- [VUSL protocol design and conformance](docs/vusl.md) +- [VUSL consumer direction and retained research](docs/vusl.md) + +- [Current application source update](#application-source-update--october-29-2026) +- [Current local workflow checkpoint](#local-workflow-checkpoint--october-29-2026) +- [Historical engineering checkpoint](#engineering-checkpoint--october-18-2026) - [Research and completion priorities](docs/harness-research-20261018.md) - [Review Rangoon now](docs/reviewer-guide.md) - [Product and feature status](#product-and-feature-status) @@ -66,7 +81,7 @@ The [transcript-backed research and primary-source audit](docs/harness-research- ## Product and feature status -The [current audit matrix](docs/system-audit.md#reconciled-capability-inventory) separates implemented behavior, missing qualification and planned integrations. Shared task navigation, compact themed headers, optional terminology help, retained skill drafts, workflow edit recovery, saved-summary search and flexible library/canvas/inspector docks are already implemented. Their completed receipts remain in the ledger; do not rebuild them from older planning paragraphs. +The [current audit matrix](docs/system-audit.md#capability-and-boundary-inventory) separates implemented behavior, missing qualification and planned integrations. Shared task navigation, compact themed headers, optional terminology help, retained skill drafts, workflow edit recovery, saved-summary search and flexible library/canvas/inspector docks are already implemented. Their completed receipts remain in the ledger; do not rebuild them from older planning paragraphs. The material/node-editor grammar applies to Rangoon modules: a searchable library, direct canvas and properties/provenance inspector, with context actions, keyboard alternatives and explicit save/review boundaries. The current workflow connection controls need clearer eligibility and refusal recovery. Keep 3D and animated flow as optional inspection surfaces; the separate playgrounds are explicitly synthetic and cannot substitute for real runtime data. Native task, all-three-OS and rendered accessibility qualification remain distinct from browser fixtures. @@ -81,7 +96,7 @@ The intended users are developers managing agent configuration, platform teams m | Local workspace | SQLite source snapshots; explicit save, deduplication, reanalysis on reopen | Broader project/workspace model and platform qualification | | Skills | Source-section derivation, immutable revisions, history comparison, local content review, versioned provenance, loaded-summary search and Review/Origin filters | Explicit-root discovery, persistent organization, compatibility, distribution and collaboration | | Decompose/Merge/Split | Real native editor routes, local saved-source/revision filtering and direct composition canvas: drag/drop, click-to-connect, contextual/keyboard actions, bounded undo/redo, exact recipes/coverage, new/append destinations, retained previews, atomic storage, and schema 3 recovery | Complete advanced GUI/failure qualification and Windows/Linux interactive evidence | -| Data controls | Inventory, plaintext portable backup, additive restore, dependency-aware logical deletion; optional keyed store and native Owner/key custody, complete typed routing and close/purge source; source-free native setup/unlock renderer controls; production remains Legacy | Qualified encrypted factory mount and OS sheet, safe Legacy adoption, encrypted archives, retention policy and platform qualification; durable E1c-1 checkpoints/reconciliation are implemented source | +| Data controls | Managed encrypted startup, inventory, explicit setup/unlock/lock, encrypted recovery copy, explicit older-backup import, additive restore and dependency-aware logical deletion; selected disposable macOS recovery evidence | Current-artifact and normal-profile qualification, Windows implementation, Linux GUI/custody, retention/rotation and package release; instruction-file apply/restore remains separate | | Engine integration | Explicit unavailable LNSAT action port; offline D2a OpenShell mapper and D3a LNSAT evidence decoder; unmounted OpenShell read-client/native custody source with synthetic-peer tests | Real-target/authentication/native qualification, connected readback and O3 detail; production Start remains unavailable | | Model assistance | M1a pure pack/validation, session-only local custody, native local workbench, and native cloud orchestration are implemented. Cloud exposes ten bounded main/review commands, explicit capability configuration, retained full-envelope credential pairing, source-free GET checks, fixed-origin TLS, final parented OS consent, and pre/post freshness checks; outputs remain inert and advisory | Real provider compatibility, tokenizer/accounting, proposal application, three-OS GUI, security and release qualification remain open; M1b/V1 are incomplete | | Workflows | Pure typed definitions and structural validation; durable schema-4 history/recovery; six native authoring commands; real saved-library/canvas/inspector source with local workflow/function filtering, separate control/data wires, six described node types, exact capability pins, draft/validated saves, historical reads and comparison | Native save/restart/history/stale-state GUI qualification across all three OSs; run records and execution remain future work. The separate design preview remains synthetic | @@ -97,7 +112,7 @@ The atomic composition store and native integration reached public source throug Authority Inspect now reveals the selected inspector when navigating within the authority screen, including repeated selection, while preserving the in-memory plan. This is a focus correction, not a provider action. -The [October 9 feature review](docs/product-experience.md#feature-gap-matrix-current-source-truth) is historical. Native routing and coordinated close/drain/purge source were completed afterward. E1c-1 now implements durable write-ahead checkpoints and explicit reconciliation. The current engineering priority is explicit setup/unlock, safe Legacy adoption and qualified local source-to-export/restart outcomes; additional provider catalogs and runtime breadth do not substitute for that work. Production storage/backups remain plaintext, all authority adapters are unavailable, and native three-OS and release gates remain open. The [October 15 assessment](docs/system-audit.md#october-15-whole-system-audit-and-completion-map) and [development ledger](docs/development.md) own current truth. +The [October 9 feature review](docs/product-experience.md#feature-gap-matrix-current-source-truth) is historical. Managed startup, coordinated close/drain/purge, durable recovery and encrypted backups were implemented afterward. Current priorities are a repeatable isolated native source-to-export/restart task, recovery on the actual artifact and safe folder-row inspection. Additional provider catalogs do not substitute for that proof. Live authority adapters remain unavailable, Windows needs implementation, and three-OS/package release gates remain open. The [October 29 assessment](docs/system-audit.md#october-29-whole-application-viability-and-drift-audit) and [development ledger](docs/development.md) own current truth. ## Architecture @@ -212,49 +227,27 @@ The report contains original source text and is not redacted telemetry. See the Selection and analysis are in-memory operations. **Save locally** persists a source snapshot explicitly. Identical basename and bytes deduplicate; a changed basename or content produces another source identity. Original selected files are never rewritten. -The desktop stores data beneath its OS app-local directory at `source-workspace/workspace.sqlite3`. The renderer cannot choose that location. Listing a missing workspace does not create it. Reopening a source reanalyzes its bytes and checks stored identity, digest, and length. +The native startup coordinator owns the OS app-local anchor and its `managed-workspace` directory; the older `source-workspace` location is inspected separately for explicit Legacy-copy handling. The renderer cannot choose database paths. Inspecting a missing layout does not create it; setup requires a distinct native action. Reopening a source reanalyzes its bytes and checks stored identity, digest and length. ### Database confidentiality and integrity -**The mounted desktop workspace is still Legacy plaintext.** Native setup resolves the application-local `source-workspace` directory and constructs `SourceAccess::legacy`; the Managed constructor is test-only. SQLite content and explicitly selected portable backups are readable to an actor who obtains those files. Unix directory/file modes reduce local exposure but do not encrypt copied data. Current source does not claim encrypted desktop adoption, authenticated authorship, rollback prevention or secure erasure. - -The optional `encrypted-sqlite` store feature uses the pinned SQLCipher profile: `4.14.0 community`, 4096-byte pages, enabled HMAC, zero plaintext header, HMAC-SHA512/PBKDF2-HMAC-SHA512 profile checks and the SQLCipher-4 iteration setting. The trusted host supplies a 32-byte raw key and owns entropy, custody and recovery; this is not a user password derivation interface. Only OpenSSL/CommonCrypto provider labels are accepted, with actual platform qualification separate. Owned key/hex buffers zeroize and have no debug/serialization representation; SQLite/parser, caller and OS copies are outside that guarantee. Cipher logging is disabled before key SQL, and temporary SQLite storage is restricted to memory. - -A keyed connection checks file alignment, cipher integrity and schema access to force lazy wrong-key validation. Unsupported profile/backend, plaintext under a keyed open, corruption, truncation or appended bytes fail closed. The no-feature build refuses encryption before disk work. Store operations retain existing exact record/digest, schema, size, transaction, dependency and no-overwrite checks. A digest proves internal consistency, not a trusted author or protection from replacement by an older valid database. - -The existing native Owner binds workspace/key identity and supplies typed source, capability, workflow, composition, compiler and data-control services. SourceAccess routes command families through shared admission and callback custody, exact retained plans and generation-bound delivery. Model preparation, credential/prompt consent and selected-file callbacks participate in the same lifetime boundary. Global close first closes admission, cancels/drains work, purges native and renderer/controller/DOM retained content and receives the exact renderer acknowledgment before a completed managed-lock claim. These mechanisms are implemented source/tests; they are not mounted encrypted storage or a generic memory-erasure guarantee. Legacy reports encrypted close unavailable honestly. +Ordinary desktop source enables `encrypted-workspace` by default. Native bootstrap installs deferred Managed services over the OS app-local anchor; missing backend/anchor or unsupported startup stays unavailable rather than silently opening Legacy plaintext. The library's `encrypted-sqlite` feature remains optional for other callers, and explicit Legacy regression/compatibility paths remain in source. These are different configurations, not a runtime fallback. -E1c-1 adds bounded durable operation evidence in two nonsecret fixed-size slots. Pending is synchronized and reread before source/empty setup or any managed source, capability, workflow, composition, restore or deletion write. The other slot records a verified host observation or explicit reconciliation without destroying Pending during a torn completion write. Sequences and native attempt/workspace IDs stay exact; unknown or contradictory states fail closed. Normal successful restart remains usable through explicit unlock. A stored terminal observation describes the native storage result, never proof that an IPC caller or person saw it; no operation is automatically replayed. +SQLCipher uses the pinned `4.14.0 community` profile: 4096-byte pages, enabled per-page HMAC, zero plaintext header, HMAC-SHA512/PBKDF2-HMAC-SHA512 profile checks and the SQLCipher-4 iteration setting. The host supplies a 32-byte raw key and owns entropy, custody and recovery; this is not a user-password derivation interface. A keyed connection forces schema access and cipher integrity validation before accepting wrong-key, corrupted, truncated or incompatible input. Temporary SQLite storage is memory-only. Native-owned key buffers zeroize; that does not prove erasure of allocator, parser, SQLite or OS copies. -Explicit trusted-host recovery inspection reads the existing key and authenticates the actual full inventory without unlocking, creating keys or changing user content. A one-attempt confirmation revalidates the retained records, directory/key custody and state ID, then changes recovery/binding metadata only and leaves the workspace locked. Qualified narrow single-slot damage can be explicitly repaired; both-invalid, linked, oversized, mismatched or unauthenticatable states stay closed. Recovery metadata is neither an authenticated audit log nor rollback protection. The [E1c-1 protocol](docs/encrypted-workspace.md#durable-operation-protocol-e1c-1) and [completion receipt](docs/development.md#durable-encrypted-recovery-e1c-1--october-15-2026) distinguish source evidence from remaining process-kill/disk-full, actual vault/GUI and three-OS filesystem qualification. +SourceAccess, Owner and the shared admission gate route source, capability, workflow, composition, compiler and data controls through typed native services. Exact generation checks reject stale callers. Close first fences admission, drains actual callbacks, releases native custody and purges renderer/controller/DOM state; a completed UI lock requires the matching acknowledgment. Cancel alone does not prove that a picker closed or an operation had no effect. A compromised unlocked process or administrator can still obtain readable content; encryption at rest cannot repair that trust boundary. -E1c-2a extends the shared native admission gate with closed-control custody. Setup/unlock callbacks and retained recovery inspections can hold a non-clonable native lease while ordinary source, edit and model lanes stay closed. Cancellation advances the generation without erasing outstanding callback counts; reopening remains blocked until their actual owners finish. This is a tested prerequisite, not a mounted setup/unlock interface. The [closed-control contract](docs/encrypted-workspace.md#closed-native-control-custody-e1c-2a) and [receipt](docs/development.md#closed-native-control-custody-e1c-2a--october-15-2026) record the behavior and remaining host integration. +Durable Pending/observation slots and retained plans distinguish committed, refused and uncertain operations across restart. Recovery revalidates actual layout, key custody and full records before an explicit confirmation. Lost keys never cause silent regeneration; contradictory or unauthenticatable state stays closed. Content hashes and review labels do not authenticate authorship or prevent replay of an older valid database. [Storage contract](docs/encrypted-workspace.md) and [dated development evidence](docs/development.md) retain the individual implementation and failure-case history. -E1c-2b adds a private typed control seam over the existing SourceAccess/Owner. Starting a control replaces the old close cycle and release memo before key access. Empty setup/unlock confirmation can resume only the current verified Owner; recovery reconciliation remains locked. Cancellation preserves real callback custody; failed or abandoned controls lock Owner before releasing it. Normal routing and stale close-ticket cleanup serialize against cycle replacement. This seam remains unmounted: native coordinator state, system-consent commands, protection UI and Legacy adoption still need integration and qualification. See the [control contract](docs/encrypted-workspace.md#typed-close-cycle-control-transitions-e1c-2b) and [receipt](docs/development.md#typed-close-cycle-transitions-e1c-2b--october-15-2026). +### Encrypted setup and management -E1c-2c integrates those controls into the existing native close supervisor. Native and source transitions share exact attempt identity; active callbacks and retained recovery controls remain Closing. Actual callback finalizers drop Owner/key custody before native cleanup even if their IPC waiter disappears. Old cancellation and purge acknowledgments cannot apply to a new operation; poison permits cleanup only. This remains an internal source prerequisite: no setup/unlock command, production constructor or automatic plaintext migration is enabled. The [supervisor contract](docs/encrypted-workspace.md#native-supervisor-control-ownership-e1c-2c) and [receipt](docs/development.md#native-supervisor-control-ownership-e1c-2c--october-15-2026) define qualification and remaining work. +First interactive setup creates a new encrypted workspace under the user's OS account after native confirmation. Existing Legacy data follows an explicit verified-copy flow; it is not silently converted or overwritten. Unlock, interrupted-setup recovery and Lock use the same native lifecycle boundary. No cloud account, model, LNSAT or other engine is required. Installer elevation must not own the workspace key. -E1c-2d implements native failure-driven closure: a managed Owner failure closes admission and purges retained native work even when its IPC waiter disappears. Cleanup observes actual source/model/credential callback custody, marshals window cleanup to the native event loop and stops conservatively when drain state is unknowable. Existing redacted locked/recovery/stale-plan errors are preserved without returning stale successful payloads or reentering storage. Renderer failure wake/reload, production encrypted setup and plaintext migration remain unavailable. E1c-2e adds atomic admission for an exact previously observed Gate generation, with count-free observation and stale-caller rejection across resume. Native source tests pass; E1c-2f now binds native client identifiers at the actual admission of all 45 ordinary commands, before model session mutation. Fresh renderer bootstrap supplies a private header; old requests stay rejected after resume. Native/renderer source checks and independent review pass. E1c-2g adds main-window native setup/unlock commands with exact close-cycle checks, fresh purge acknowledgment, private native previews and explicit OS-consent wiring. Blocking workers retain actual custody through cancellation and result consumption; only successful resume requests a fresh document reload. The production host remains Legacy, so these controls refuse there. E1c-2h adds a source-tested read-only, vault-free layout classifier that separates empty, locked, busy, recovery and unavailable metadata states before protection UI routing. It returns no paths or identities and does not prove key availability or tamper resistance. See the [layout receipt](docs/development.md#read-only-layout-inspection-e1c-2h--october-15-2026). Protection UI, native failure wake/reload, qualified encrypted mounting and explicit plaintext import remain unfinished; existing data is not converted automatically. See the [control-command receipt](docs/development.md#closed-cycle-control-commands-e1c-2g--october-15-2026). See the [routing receipt](docs/development.md#native-request-generation-routing-e1c-2f--october-15-2026). See the [caller-generation contract](docs/encrypted-workspace.md#atomic-caller-generation-admission-e1c-2e). See the [failure-closure contract](docs/encrypted-workspace.md#failure-driven-native-closure-e1c-2d) and [receipt](docs/development.md#failure-driven-native-closure-e1c-2d--october-15-2026). +The Workspace surface exposes setup/unlock/lock, inventory, encrypted backup and explicit restore. Technical diagnostics and detailed limits stay in advanced disclosures. A future workspace-management CLI must use the same custody, exclusive ownership and domain receipts; there is no general workspace CLI, arbitrary SQL interface, hidden unlock or privilege granted by a presentation mode today. Rotation and broader retention tooling remain open. -E1c-2i adds a local main-window protection-state command over the read-only layout classifier. Only an exact fully completed managed Locked cycle may inspect metadata; a changed cycle discards the result. Its finite result contains no paths or new identifiers and grants no setup or execution authority. The current production Legacy host reports `legacy` without reading encrypted metadata. See the [routing contract](docs/encrypted-workspace.md#native-protection-state-routing-e1c-2i) and [current receipt](docs/development.md#native-protection-state-routing-e1c-2i--october-15-2026). Native progress without a renderer, failure wake, protection controls, encrypted factory qualification and explicit legacy import still gate the transition away from plaintext. +[E1d-2 recovery](docs/encrypted-workspace.md#e1d-2-native-sqlcipher-recovery-copy--october-25-2026) uses a canonical encrypted workspace image and a separate native-selected recovery key file. The October 25 disposable macOS run covered backup, original test-key removal, restore into a fresh independently keyed workspace, distinct-process reopen and exact test-slot cleanup. It did not qualify normal-profile adoption, the current artifact, Windows/Linux or release packaging. The recovery key file is itself unencrypted: protect it like a password and store it separately; anyone with both files can read the backup. -E1c-2j extends native close progress beyond the fatal-failure path. An explicit managed close wakes the weak native supervisor so actual callback drain, native cleanup and key release can finish while the application event loop remains alive, without relying on renderer polling or acknowledgment. Actual main-window destruction fences and cancels managed access before a best-effort wake. If it is the last window, Tauri may exit before drain completes; that stop is not cleanup proof. A separate exit-hold gate must address this before encrypted activation. Native completion never supplies renderer purge acknowledgment or a Locked UI claim. See the [contract](docs/encrypted-workspace.md#renderer-independent-native-close-progress-e1c-2j) and [receipt](docs/development.md#renderer-independent-native-close-progress-e1c-2j--october-15-2026). - -E1c-2k adds a Managed-only last-window exit hold. Ordinary Tauri exit requests are prevented while the native close drains actual callbacks; a clean process exit is requested only after the current close attempt proves healthy native cleanup and key release. A stopped, unknown or unhealthy outcome instead requests a distinct nonzero recovery exit. This is a source-tested process-lifetime prerequisite, not a production encrypted workspace: Tauri restart, forced termination, real three-OS GUI behavior, renderer purge acknowledgment, setup/protection UX, qualified encrypted mounting and explicit Legacy import still require separate work. See the [exit-hold contract](docs/encrypted-workspace.md#last-window-native-exit-hold-e1c-2k) and [receipt](docs/development.md#last-window-native-exit-hold-e1c-2k--october-15-2026). - -E1c-2l adds a source-free closed-workspace screen to the real workbench. Native `absent` offers empty setup; `locked` offers unlock; busy, recovery, unavailable and Legacy do not offer setup or unlock. A user action must validate the observed C0, prepare a distinct C1, freshly purge renderer state, acknowledge that exact cycle, and reach an exact native `opened` result before a full reload. Managed-open observation also purges and acknowledges an observed native close. These are renderer/source and synthetic-browser results, not proof of native OS sheet behavior or production encryption. Browser and Legacy authoring remain usable. See the [renderer control contract](docs/encrypted-workspace.md#source-free-renderer-protection-controls-e1c-2l) and [receipt](docs/development.md#source-free-renderer-protection-controls-e1c-2l--october-16-2026). - -Managed native plaintext-backup export is refused before picker/data access until encrypted recovery is qualified. Portable recovery encryption needs a separate format/key/recovery contract; ordinary readable instruction exports remain explicit selected outputs outside database confidentiality. Setup/unlock, failure-driven close/reload, native durable-recovery qualification, safe Legacy handling, encrypted archives and packaged all-three-OS evidence must pass before changing the production default. See the [encrypted workspace contract](docs/encrypted-workspace.md) and [current audit](docs/system-audit.md#october-15-whole-system-audit-and-completion-map). - -### Planned encrypted setup and management - -The empty-store prerequisite provides `Workspace::initialize_empty_encrypted()` and native `Owner::prepare_create_empty()`: a real zero-record encrypted database, initialized only on a keyed handle and an exclusively new destination. Existing database files and SQLite sidecars are refused, never adopted or overwritten. Native setup retains a distinct one-shot action and authenticates the empty inventory before marking its binding ready; selected-source creation remains available. This removes the need to fabricate a starter instruction file. E1c-2l now presents a closed renderer setup/unlock screen, but the production Legacy backend cannot use it. See [E1b-2b8](docs/encrypted-workspace.md#e1b-2b8-empty-encrypted-provisioning) and the [development ledger](docs/development.md) for named checks and remaining adoption gates. - -The intended installation experience provisions an encrypted local workspace at first interactive launch under the user's OS account, after explicit review and confirmation. It needs no model, cloud account or LNSAT. Installer elevation must not own the database key. New setup never silently falls back to plaintext; existing plaintext workspaces require a separately verified migration. The source now preserves selected-source creation and supports empty setup before import; production setup/unlock, native recovery qualification, failure-driven close/reload and platform qualification remain required before activation. - -Simple is the proposed default: setup, unlock/lock, import, save and clear data-management guidance. Advanced adds storage/cipher diagnostics, provenance, dependency-aware retention/deletion and qualified recovery tools over the same typed services. Future CLI management uses the same custody/refusal and domain-receipt contracts, with exclusive workspace ownership and explicit consent; no raw keys, arbitrary SQL, hidden unlock or broad unsafe override. Mode selection changes presentation, not privileges. - -**A source-free setup/unlock screen is implemented, but the installed encrypted first-run flow and workspace CLI commands remain planned; current desktop storage and backups remain plaintext.** Recovery, rotation and encrypted portable archives require their own implementation and qualification; ordinary instruction exports remain plaintext. See the [installation flow, state table, management matrix and ordered implementation packets](docs/encrypted-workspace.md#installation-first-run-setup-and-management-surfaces), with review/validation evidence in the [development ledger](docs/development.md). +Windows startup and key-file recovery currently return unsupported/refusal states, rather than merely lacking a test receipt. Linux and macOS each still need their applicable current-artifact, GUI, custody and package checks. The Managed host refuses the older plaintext whole-workspace backup export. Older plaintext backup import remains explicit. Original source files and intentionally readable instruction-bundle exports are not encrypted by this workspace and retain their own disclosure/consent boundaries. ### Capabilities, revisions, and review @@ -456,7 +449,7 @@ The portable [`rangoon-model-session::cloud`](crates/rangoon-model-session/src/c Closed `rangoon.cloud-selection.v1`, `rangoon.cloud-send.v1` and `rangoon.cloud-cancel.v1` inputs have independent schema tags and random `cloud-prepared:`/`cloud-run:` handle namespaces. A prepared view exposes the exact outer body, byte length, SHA-256, model, fixed origin, credential revision, dependencies and separate inner context pack. Changed credential revisions change request identity. A successful claim consumes the handle once; profile replacement, clear, cancellation and a new preparation invalidate obsolete work. Read-only freshness checks compare exact content, dependency identity and observed capability heads. -Portable custody remains network-free and authority-free. Native `apps/desktop/src/cloud_models.rs` now calls the adapter through explicit capability-configured commands, pairs full credential envelopes to retained preparations, holds shared model/credential leases, performs source-free GET checks, requires final OS consent, and applies pre/post freshness gates. The module and native results grant no execution or LNSAT authority; SQLite remains plaintext. Provider compatibility and full cross-platform qualification remain open. See the [cloud session contract](docs/model-cloud-session.md) and [native cloud contract](docs/model-cloud-native.md). +Portable custody remains network-free and authority-free. Native `apps/desktop/src/cloud_models.rs` now calls the adapter through explicit capability-configured commands, pairs full credential envelopes to retained preparations, holds shared model/credential leases, performs source-free GET checks, requires final OS consent, and applies pre/post freshness gates. The module and native results grant no execution or LNSAT authority; model requests remain explicit disclosures outside database-at-rest confidentiality. Provider compatibility and full cross-platform qualification remain open. See the [cloud session contract](docs/model-cloud-session.md) and [native cloud contract](docs/model-cloud-native.md). ## Backup, restore, and deletion @@ -464,9 +457,11 @@ The native Workspace surface provides real inventory, export through a save pick ### Portable backup -Native export uses the complete version-aware store: V2 for schemas 1–3 and V3 for schema 4. V3 includes workflow owners, exact canonical revisions, node positions, parent chains and saved timestamps alongside source bytes, skill histories, reviews, recipes, applications and live provenance. V1 and V2 backups retain their original interpretation and remain accepted by the versioned restore path. Unsaved editor drafts and transient native preview handles are not backup records. +The ordinary Managed workflow creates an encrypted recovery copy through native selection and consent. `rangoon.recovery.sqlcipher.v1` contains a canonical SQLCipher image, bounded at 64 MiB, with an independent 32-byte recovery key selected through a strict owner-only key file. Native code builds encrypted staging, closes and reopens it, validates cipher/domain integrity, exclusively writes and syncs the selected output, then rereads that actual ciphertext and compares the complete records before reporting success. Keys, paths and replacement originals do not enter renderer requests. A post-write uncertainty is reported as uncertainty, never a false Cancel or an automatic retry. + +The separate recovery key file is unencrypted and required to restore. Keep it protected and apart from the backup; the pair discloses the contents. This protects stored recovery data, not an unlocked or compromised host, original files or readable instruction exports. Recovery does not authenticate the sender, restore execution authority or establish freshness against rollback. -V2 and V3 use versioned magic headers, bounded canonical JSON manifests, ordered raw payload segments, and SHA-256 trailers. Limits are 2 MiB for the manifest, 68 MiB for the complete archive, and 64 MiB for aggregate raw payload. Reconstructed SQLite allocation must independently fit the database ceiling. The archive is plaintext; its digest is not a signature or encryption. +Older V1/V2/V3 plaintext codecs remain explicit compatibility paths. V2/V3 preserve source, capability and composition records; V3 additionally preserves workflow history. Their canonical manifests and SHA-256 trailers provide internal consistency, not encryption or signatures. Managed native plaintext export is refused. Older plaintext import remains an explicit selected-file operation under More recovery options; it does not make that input confidential. Unsaved drafts and transient preview handles are not backup records. ### Additive restore @@ -486,7 +481,7 @@ Deleting a workflow removes its owner and complete immutable history only. It do The Data route and existing six native commands now adopt `rangoon.workspace-data.v2`, `rangoon.restore-plan.v2` and `rangoon.deletion-plan.v2` together. Source, skill and workflow owners remain separate; capability revision and workflow revision totals are never combined. The renderer rejects older/unknown shapes, contradictory validated-intent observations and impossible counts. It renders escaped bounded labels, local dependency observations and explicit Inspect/Delete actions without implying a workflow editor or execution exists. A workflow-only restore is actionable; a no-additions preview checks every record count. Native commands retain opaque archives/private plans and accept selectors rather than renderer-supplied impact or SQL. -This source adoption can restore schema-4 archives through explicit native selection and confirmation. It registers no workflow creation/save command. Existing local analysis, skills and composition drafts stay usable; workflow deletion is never treated as source deletion. Native session and synthetic renderer evidence are distinct from interactive OS picker/IPC qualification. See [native controls](docs/workflow-native-controls.md) and the [development ledger](docs/development.md) for exact checks and remaining GUI gates. +These DTOs retain explicit native selection and confirmation for compatible archives; workflow authoring is a separate command family. Encrypted recovery uses the same retained restore-plan checks, and a truly empty destination preserves the complete canonical record set. Nonempty destinations retain additive union/conflict semantics. Workflow deletion is never treated as source deletion. Source tests, synthetic renderer results and dated native picker evidence remain distinct. See [native controls](docs/workflow-native-controls.md) and the [development ledger](docs/development.md) for exact checks and remaining GUI gates. Deletion is logical removal, not secure erasure. See [workspace data controls](docs/workspace-data-controls.md) and [composition recovery](docs/composition-recovery.md) for exact archive encoding, dependency closure, stale-state checks, and failure tests. @@ -537,14 +532,14 @@ SQLite connections disable trusted schema, use rollback-journal `DELETE` mode an ### Limits of the present design -**The database and exported backups are unencrypted.** A party with sufficient filesystem access can read them. A writer able to replace the store can recompute its unkeyed hashes; internal consistency does not establish authentic authorship, an untampered history, or freshness after rollback. Local review labels and wall-clock timestamps are unauthenticated. +**Encrypted storage protects locked data, not a compromised authorized consumer.** The default Managed source and encrypted recovery copy protect their respective stored bytes. Original files, older plaintext backup inputs, readable instruction exports and unlocked/model-delivered content remain outside that protection. A recovery key file must be secured separately. Consistency hashes do not establish authorship; even an authenticated encrypted image can be replaced with an older valid image. Local review labels and wall-clock timestamps remain unauthenticated. Provider requests require the explicit configured model path, retained payload review and native consent described above. There are no automatic background source uploads. Analysis output and backups contain source content, so publishing those artifacts can disclose that content. Logical deletion cannot promise removal from backups, filesystem snapshots, or storage media. ### Proposed hardening sequence 1. Define the threat model: accidental corruption, offline theft, another local account, malicious same-user software, rollback, and a compromised unlocked process require different controls. -2. Adopt the optional keyed SQLite backend through explicit native consent, exclusive key/session custody and create/unlock/lock controls. Qualify real OS stores on all three platforms; require verified migration, key-loss recovery, rotation and encrypted backups without silent plaintext fallback. +2. Qualify the implemented Managed startup and encrypted recovery on each actual target artifact and OS. Complete Windows custody/startup/recovery support, Linux GUI/custody, normal-profile adoption and rotation without weakening no-plaintext-fallback behavior. 3. Add authenticated history that binds operations, identities, sequence, and prior state using protected key material. Keep consistency hashes for content addressing; do not relabel them as authentication. 4. Design independently stored checkpoints for rollback detection. Stronger enterprise evidence may require an external witness; restoring all local state together cannot be made reliably fresh by another file beside the database. 5. Fail closed on integrity failures, preserve recoverable evidence, and offer explicit recovery rather than silently creating a new empty store. @@ -562,7 +557,7 @@ Approval management, telemetry and dynamic operations visualization are core pro Planned operations surfaces include scoped gateway/rule configuration, approval chains, mandatory human duties, explicitly bounded agent delegation, expiry/escalation/revocation/emergency suspension, an approval inbox, agent inventory and authority assignments. Agents cannot grant themselves broader authority. Telemetry must redact sensitive payloads and correlate request/attempt/trace IDs, exact policy versions, approvals, resource access, costs, latency, outcomes and failures. A live graph and timeline connect agents, workflows, tools, resources, gateways, approvers and engines, with filters, exact evidence drill-down and inert historical replay. -These are accepted product requirements, **not implemented runtime features**. Shared closed records, deterministic projections and adapter conformance precede activation. Per-operation coverage must distinguish unavailable, advisory, partially mediated and fully mediated paths; “universal” never means blanket enforcement. Current engine transport remains unavailable, workspace SQLite remains plaintext, and telemetry is not an authenticated audit log. See the [operations control-plane contract](docs/operations-control-plane.md) for responsibility boundaries, state machines, privacy, failure handling and O1–O5 acceptance gates; exact source/runtime evidence belongs in the [development ledger](docs/development.md). +These are accepted product requirements, **not implemented runtime features**. Shared closed records, deterministic projections and adapter conformance precede activation. Per-operation coverage must distinguish unavailable, advisory, partially mediated and fully mediated paths; “universal” never means blanket enforcement. Live engine operation remains unavailable, workspace encryption does not authenticate telemetry, and these observations are not an authenticated audit log. See the [operations control-plane contract](docs/operations-control-plane.md) for responsibility boundaries, state machines, privacy, failure handling and O1–O5 acceptance gates; exact source/runtime evidence belongs in the [development ledger](docs/development.md). An optional curator may use a small local or explicitly consented advanced model to flag semantic risk, missing context and possible intent/action mismatch for @@ -661,7 +656,7 @@ Inspection has a 1 MiB output ceiling and separate 8,192-reference, matching-ord ### Local operations window (O2 first slice) -The desktop workbench now has an Operations window route. Its native command opens a parented picker only after the operator chooses a local JSON file. A dedicated host reader bounds that file at 2 MiB, refuses nonregular files and final-component links, and passes the exact bytes through all five O1 inspectors. Rust constructs a separate `rangoon.ops.operator-view.v1` allowlist before IPC. It exposes display ordinals, closed reported values, diagnostics and reference status, but not original IDs, source text, paths, digests, external references or free-form errors. The native operation holds a read-only selection lease; Clear or Managed close discards stale picker/read results and the renderer purges the retained view. The current production Legacy workspace has no lock operation; this route remains memory-only there. +The desktop workbench now has an Operations window route. Its native command opens a parented picker only after the operator chooses a local JSON file. A dedicated host reader bounds that file at 2 MiB, refuses nonregular files and final-component links, and passes the exact bytes through all five O1 inspectors. Rust constructs a separate `rangoon.ops.operator-view.v1` allowlist before IPC. It exposes display ordinals, closed reported values, diagnostics and reference status, but not original IDs, source text, paths, digests, external references or free-form errors. The native operation holds a read-only selection lease; Clear or Managed close discards stale picker/read results and the renderer purges the retained view. The route remains memory-only, participates in Managed close/purge and does not persist a telemetry history. The screen keeps a record library, filtered observation timeline, declared-topology outline and selected-item inspector. A compact count strip leads to those working panels; a closed Reported decisions disclosure holds the detailed breakdown. Empty-window, filter-no-match and fixed recovery messages are distinct. Its truth labels stay `authority: none`, `authenticity: unverified`, `eligibility: unknown`, `execution: unavailable`, `outcome: unknown` and `coverage: unknown`. Offline decision analytics count reported evaluation, approval-decision, authorization and attempt values in separate groups, each with its own observed-record denominator. A zero count means no matching record in the selected file; it says nothing about total system activity. O1 has no model-advice record, authenticated producer, confirmed human identity or independently observed effect, so model accuracy, real approval, enforcement and outcome rates cannot be inferred. A future advisory record and O3 authenticated, redacted, encrypted ingress are required before live model decision history or analytics. @@ -729,8 +724,8 @@ Adapter work requires a supported artifact, exact typed request/result contracts ### Requirements - Node.js 20+ for the local preview and Node tests; no npm dependency installation is required. -- Rust 1.85+ for the edition-2024 core workspace. CI pins its minimum toolchain explicitly. -- Rust 1.98 and host-native prerequisites for the separate desktop workspace: Xcode command-line tools on macOS, Microsoft C++ tools/WebView2 on Windows, or the documented WebKitGTK dependencies on Linux. See [desktop setup](docs/desktop-spike.md#run-from-source). +- Rust 1.99.1 for both the edition-2024 core and separate desktop workspaces, pinned in `rust-toolchain.toml` and both Cargo manifests. This aligns the compiler floor with VUSL; it does not add or qualify a VUSL consumer dependency. +- Host-native prerequisites for the separate desktop workspace: Xcode command-line tools on macOS, Microsoft C++ tools/WebView2 on Windows, or the documented WebKitGTK dependencies on Linux. See [desktop setup](docs/desktop-spike.md#run-from-source). ```sh git clone https://github.com/hypler-dev/rangoon.git @@ -779,14 +774,14 @@ The next-phase [target-loader investigation](docs/target-loader-qualification.md ### Native desktop workbench ```sh -cargo +1.98.0 run --manifest-path apps/desktop/Cargo.toml --locked +cargo +1.99.1 run --manifest-path apps/desktop/Cargo.toml --locked ``` Choose `fixtures/contracts/AGENTS.md` for a first run. Inspect the report, explicitly save it, derive a skill from a section, edit/review a revision, then quit and reopen saved data. Open Decompose to work from a saved source, Merge to combine two saved skill revisions, or Split to divide one saved revision. Inspect the exact native preview before acknowledging and saving. Backup and restore controls are in Workspace. Installer bundling is disabled; this command runs a development executable. ## Validation and platform support -For local minimum-toolchain source validation, install Rust 1.85.0 with rustfmt and Clippy, then run `node scripts/check-source-rust.mjs`. The script resolves the toolchain's Cargo path, pins compiler/documentation executables and subprocess PATH, prints and verifies Cargo/rustc/Clippy versions, then runs formatting, workspace tests and warnings-denied Clippy. It rejects environment compiler-wrapper overrides and disables file-configured compiler wrappers for its child processes without changing configuration files. This avoids a Homebrew `cargo-clippy` overriding the requested rustup toolchain. `CARGO_TARGET_DIR` may select an isolated build cache; the separate desktop workspace retains its own Rust requirement. +For pinned source validation, provision Rust 1.99.1 with rustfmt and Clippy, then run `node scripts/check-source-rust.mjs` for core or add `--desktop` for the native workspace. The script reads the root toolchain pin, requires both Cargo floors and any CI version to match, pins compiler/documentation executables and subprocess PATH, and verifies all seven tool identities (rustc, rustdoc, Cargo, rustfmt, cargo-fmt, cargo-clippy and clippy-driver) before formatting, tests and warnings-denied Clippy; the desktop plan also builds its executable without installers. `--check-config` checks version coherence without starting compiler tools. An already provisioned isolated compiler can be selected with `--toolchain-bin /absolute/path/to/bin`; missing tools fail without installation. Compiler-wrapper overrides are rejected and file-configured wrappers are disabled only for child processes. `CARGO_TARGET_DIR` may select an isolated build cache. Historical 1.85/1.98 receipts remain evidence for their original bytes and compilers, not validation of this new pin. | Evidence | What it establishes | What it does not establish | | --- | --- | --- | @@ -805,10 +800,10 @@ The [vision build rule](AGENTS.md) keeps the original eight screens as the struc npm run build:check node scripts/validate-review.mjs node scripts/check-source-rust.mjs -cargo +1.98.0 fmt --manifest-path apps/desktop/Cargo.toml -- --check -cargo +1.98.0 test --manifest-path apps/desktop/Cargo.toml --locked -cargo +1.98.0 clippy --manifest-path apps/desktop/Cargo.toml --all-targets --locked -- -D warnings -cargo +1.98.0 build --manifest-path apps/desktop/Cargo.toml --locked +cargo +1.99.1 fmt --manifest-path apps/desktop/Cargo.toml -- --check +cargo +1.99.1 test --manifest-path apps/desktop/Cargo.toml --locked +cargo +1.99.1 clippy --manifest-path apps/desktop/Cargo.toml --all-targets --locked -- -D warnings +cargo +1.99.1 build --manifest-path apps/desktop/Cargo.toml --locked git diff --check ``` diff --git a/apps/desktop/Cargo.lock b/apps/desktop/Cargo.lock index b1a32c2..656595b 100644 --- a/apps/desktop/Cargo.lock +++ b/apps/desktop/Cargo.lock @@ -3230,6 +3230,7 @@ dependencies = [ "rangoon-model-cloud", "rangoon-model-local", "rangoon-model-session", + "rangoon-native-credential-input", "rangoon-openshell-client", "rangoon-ops", "rangoon-store", @@ -3269,6 +3270,7 @@ dependencies = [ "rangoon-compile", "rangoon-domain", "rangoon-import", + "rustix", "serde", ] @@ -3337,6 +3339,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "rangoon-native-credential-input" +version = "0.1.0-dev" +dependencies = [ + "block2", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "tauri", + "zeroize", +] + [[package]] name = "rangoon-openshell-client" version = "0.1.0-dev" diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index ee60c0c..6928f67 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -3,11 +3,11 @@ license = "Apache-2.0" name = "rangoon-desktop" version = "0.1.0-dev" edition = "2024" -rust-version = "1.98" +rust-version = "1.99.1" publish = false repository = "https://github.com/hypler-dev/rangoon" -# Keep native WebView dependencies out of the portable Rust 1.85 core workspace. +# Keep native WebView dependencies separate from the portable core workspace. [workspace] resolver = "3" @@ -16,6 +16,7 @@ tauri-build = "=2.7.1" [dependencies] tauri = "=2.12.1" +rangoon-native-credential-input = { path = "native-input" } tauri-plugin-dialog = "=2.8.1" rangoon-host = { path = "../../crates/rangoon-host" } rangoon-ops = { path = "../../crates/rangoon-ops" } @@ -33,7 +34,7 @@ sha2 = "=0.11.0" rangoon-model-session = { path = "../../crates/rangoon-model-session" } rangoon-model-cloud = { path = "../../crates/rangoon-model-cloud" } rangoon-model-local = { path = "../../crates/rangoon-model-local" } -tokio = { version = "=1.53.2", default-features = false, features = ["sync"] } +tokio = { version = "=1.53.2", default-features = false, features = ["sync", "rt", "net", "time"] } serde = { version = "=1.0.229", features = ["derive"] } zeroize = "=1.9.0" @@ -57,6 +58,33 @@ rangoon-openshell-client = { path = "../../crates/rangoon-openshell-client", fea tokio = { version = "=1.53.2", default-features = false, features = ["macros", "rt-multi-thread"] } [features] -default = ["custom-protocol"] +native-credential-qualification = ["tauri/unstable"] +native-exit-qualification = [] +native-encrypted-qualification = [] +default = ["custom-protocol", "encrypted-workspace"] custom-protocol = ["tauri/custom-protocol"] encrypted-workspace = ["rangoon-store/encrypted-sqlite"] + +# Explicit custom test executable; ordinary cargo test never launches it. +[[test]] +name = "native-exit-qualification" +path = "src/main.rs" +harness = false +test = false +required-features = ["native-exit-qualification", "encrypted-workspace"] + +# Explicit real-renderer encrypted qualification; never an ordinary test entry. +[[test]] +name = "native-encrypted-qualification" +path = "src/main.rs" +harness = false +test = false +required-features = ["native-encrypted-qualification", "encrypted-workspace"] + +# Explicit parented native entry qualification; ordinary tests never launch it. +[[test]] +name = "native-credential-qualification" +path = "src/main.rs" +harness = false +test = false +required-features = ["native-credential-qualification", "encrypted-workspace"] diff --git a/apps/desktop/build.rs b/apps/desktop/build.rs index 4dadd7a..8c4a48f 100644 --- a/apps/desktop/build.rs +++ b/apps/desktop/build.rs @@ -1,6 +1,9 @@ fn main() { tauri_build::try_build(tauri_build::Attributes::new().app_manifest( tauri_build::AppManifest::new().commands(&[ + "workspace_startup_status", + "workspace_startup_action", + "workspace_startup_quit", "get_workspace_close_state", "get_workspace_control_state", "get_workspace_protection_state", @@ -11,6 +14,8 @@ fn main() { "begin_workspace_close", "acknowledge_workspace_purge", "select_and_analyze", + "select_and_inspect_sources", + "select_and_list_sources", "select_and_inspect_operations", "list_snapshots", "save_analysis", @@ -28,6 +33,9 @@ fn main() { "inspect_instruction_bundle", "get_workspace_data", "export_workspace_backup", + "create_workspace_recovery_key", + "export_encrypted_workspace_backup", + "prepare_encrypted_workspace_restore", "prepare_workspace_restore", "restore_workspace_backup", "inspect_workspace_deletion", diff --git a/apps/desktop/capabilities/source-analysis.json b/apps/desktop/capabilities/source-analysis.json index ddc0637..d0e87f6 100644 --- a/apps/desktop/capabilities/source-analysis.json +++ b/apps/desktop/capabilities/source-analysis.json @@ -1,11 +1,14 @@ { "identifier": "source-analysis", - "description": "The local main workbench can inspect and save sources, inspect one bounded operations window through a native picker and privacy-minimized read-only view, derive and review inert skills, compose inert skills from saved inputs, inspect compiled instruction text, explicitly export or inspect plaintext instruction bundles, manage local backups and record deletion, author immutable inert workflow revisions, inspect inert engine status, and read source-free encrypted layout status and request native-confirmed empty encrypted setup or unlock when a qualified managed host is available. Renderer-supplied paths, SQL and engine requests are never accepted.", + "description": "The local main workbench can inspect and save sources, explicitly list bounded metadata from a native-selected folder without reading its contents, inspect one bounded operations window through a native picker and privacy-minimized read-only view, derive and review inert skills, compose inert skills from saved inputs, inspect compiled instruction text, explicitly export or inspect plaintext instruction bundles, manage local backups and record deletion, author immutable inert workflow revisions, inspect inert engine status, and read source-free encrypted layout status and request native-confirmed empty encrypted setup or unlock when a qualified managed host is available. Renderer-supplied paths, SQL and engine requests are never accepted.", "windows": [ "main" ], "local": true, "permissions": [ + "allow-workspace-startup-status", + "allow-workspace-startup-action", + "allow-workspace-startup-quit", "allow-get-workspace-close-state", "allow-get-workspace-control-state", "allow-get-workspace-protection-state", @@ -16,6 +19,8 @@ "allow-begin-workspace-close", "allow-acknowledge-workspace-purge", "allow-select-and-analyze", + "allow-select-and-inspect-sources", + "allow-select-and-list-sources", "allow-select-and-inspect-operations", "allow-list-snapshots", "allow-save-analysis", @@ -33,6 +38,9 @@ "allow-inspect-instruction-bundle", "allow-get-workspace-data", "allow-export-workspace-backup", + "allow-create-workspace-recovery-key", + "allow-export-encrypted-workspace-backup", + "allow-prepare-encrypted-workspace-restore", "allow-prepare-workspace-restore", "allow-restore-workspace-backup", "allow-inspect-workspace-deletion", diff --git a/apps/desktop/native-credential-qualification/cases.v1.json b/apps/desktop/native-credential-qualification/cases.v1.json new file mode 100644 index 0000000..50880d2 --- /dev/null +++ b/apps/desktop/native-credential-qualification/cases.v1.json @@ -0,0 +1,11 @@ +{ + "schema": "rangoon.native-credential-cases.v1", + "cases": [ + { "id": "accept-read" }, + { "id": "cancel-review" }, + { "id": "stop-queued" }, + { "id": "stop-open" }, + { "id": "expire-open" }, + { "id": "parent-close" } + ] +} diff --git a/apps/desktop/native-credential-qualification/tauri.conf.json b/apps/desktop/native-credential-qualification/tauri.conf.json new file mode 100644 index 0000000..599603e --- /dev/null +++ b/apps/desktop/native-credential-qualification/tauri.conf.json @@ -0,0 +1,22 @@ +{ + "productName": "Rangoon Native Credential Qualification", + "version": "0.1.0-dev", + "identifier": "ai.rangoon.native-credential-qualification", + "build": {}, + "app": { + "withGlobalTauri": false, + "windows": [], + "security": { + "csp": "default-src 'none'", + "capabilities": [{ + "identifier": "c1-no-permissions", + "description": "Disposable native parent only; no webview or IPC grants.", + "local": false, + "windows": [], + "webviews": [], + "permissions": [] + }] + } + }, + "bundle": { "active": false, "icon": ["../icons/32x32.png"] } +} diff --git a/apps/desktop/native-encrypted-qualification/cases.v1.json b/apps/desktop/native-encrypted-qualification/cases.v1.json new file mode 100644 index 0000000..10528de --- /dev/null +++ b/apps/desktop/native-encrypted-qualification/cases.v1.json @@ -0,0 +1,466 @@ +{ + "schemaVersion": "rangoon.e1c5c.case-plan.v1", + "roots": [ + "cold-cancel", + "authoring", + "interrupted-setup", + "anchor-failure", + "cleanup-failure", + "window-failure", + "legacy-empty", + "legacy-rich", + "legacy-review", + "legacy-copy", + "recovery-empty", + "recovery-parity", + "recovery-selection", + "legacy-rich-provisioning" + ], + "cases": [ + { + "name": "cold-cancel", + "root": "cold-cancel", + "prerequisite": { + "kind": "initial" + }, + "seed": "none", + "expectation": "cold_cancel" + }, + { + "name": "cold-relaunch", + "root": "cold-cancel", + "prerequisite": { + "kind": "completed", + "case": "cold-cancel" + }, + "seed": "none", + "expectation": "cold_relaunch" + }, + { + "name": "authoring", + "root": "authoring", + "prerequisite": { + "kind": "initial" + }, + "seed": "none", + "expectation": "authoring" + }, + { + "name": "relaunch", + "root": "authoring", + "prerequisite": { + "kind": "completed", + "case": "authoring" + }, + "seed": "none", + "expectation": "relaunch" + }, + { + "name": "export", + "root": "authoring", + "prerequisite": { + "kind": "completed", + "case": "relaunch" + }, + "seed": "none", + "expectation": "export" + }, + { + "name": "lose-key", + "root": "authoring", + "prerequisite": { + "kind": "completed", + "case": "export" + }, + "seed": "none", + "expectation": "lose_key" + }, + { + "name": "missing-key", + "root": "authoring", + "prerequisite": { + "kind": "completed", + "case": "lose-key" + }, + "seed": "none", + "expectation": "missing_key" + }, + { + "name": "busy-owner", + "root": "authoring", + "prerequisite": { + "kind": "running", + "case": "authoring" + }, + "seed": "none", + "expectation": "busy_owner" + }, + { + "name": "interrupted-setup", + "root": "interrupted-setup", + "prerequisite": { + "kind": "initial" + }, + "seed": "none", + "expectation": "interrupted_setup" + }, + { + "name": "interrupted-relaunch", + "root": "interrupted-setup", + "prerequisite": { + "kind": "completed", + "case": "interrupted-setup" + }, + "seed": "none", + "expectation": "interrupted_relaunch" + }, + { + "name": "anchor-failure", + "root": "anchor-failure", + "prerequisite": { + "kind": "initial" + }, + "seed": "none", + "expectation": "anchor_failure" + }, + { + "name": "cleanup-failure", + "root": "cleanup-failure", + "prerequisite": { + "kind": "initial" + }, + "seed": "none", + "expectation": "cleanup_failure" + }, + { + "name": "window-failure", + "root": "window-failure", + "prerequisite": { + "kind": "initial" + }, + "seed": "none", + "expectation": "window_failure" + }, + { + "name": "legacy-empty-copy", + "root": "legacy-empty", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_empty", + "expectation": "legacy_copy" + }, + { + "name": "legacy-empty-verify", + "root": "legacy-empty", + "prerequisite": { + "kind": "completed", + "case": "legacy-empty-copy" + }, + "seed": "none", + "expectation": "legacy_verify" + }, + { + "name": "legacy-empty-relaunch", + "root": "legacy-empty", + "prerequisite": { + "kind": "completed", + "case": "legacy-empty-verify" + }, + "seed": "none", + "expectation": "legacy_relaunch" + }, + { + "name": "legacy-rich-copy", + "root": "legacy-rich", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "legacy_copy" + }, + { + "name": "legacy-rich-verify-cancel", + "root": "legacy-rich", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-copy" + }, + "seed": "none", + "expectation": "legacy_verify_cancel" + }, + { + "name": "legacy-rich-verify", + "root": "legacy-rich", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-verify-cancel" + }, + "seed": "none", + "expectation": "legacy_verify" + }, + { + "name": "legacy-rich-relaunch", + "root": "legacy-rich", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-verify" + }, + "seed": "none", + "expectation": "legacy_relaunch" + }, + { + "name": "legacy-review-cancel", + "root": "legacy-review", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "legacy_review_cancel" + }, + { + "name": "legacy-review-relaunch", + "root": "legacy-review", + "prerequisite": { + "kind": "completed", + "case": "legacy-review-cancel" + }, + "seed": "none", + "expectation": "legacy_review_relaunch" + }, + { + "name": "legacy-copy-cancel", + "root": "legacy-copy", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "legacy_copy_cancel" + }, + { + "name": "legacy-copy-relaunch", + "root": "legacy-copy", + "prerequisite": { + "kind": "completed", + "case": "legacy-copy-cancel" + }, + "seed": "none", + "expectation": "legacy_review_relaunch" + }, + { + "name": "recovery-empty-crash", + "root": "recovery-empty", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "crash_empty_target" + }, + { + "name": "recovery-empty-cancel", + "root": "recovery-empty", + "prerequisite": { + "kind": "completed", + "case": "recovery-empty-crash" + }, + "seed": "none", + "expectation": "recovery_inspect_cancel" + }, + { + "name": "recovery-empty-resume", + "root": "recovery-empty", + "prerequisite": { + "kind": "completed", + "case": "recovery-empty-cancel" + }, + "seed": "none", + "expectation": "recovery_restore" + }, + { + "name": "recovery-empty-verify", + "root": "recovery-empty", + "prerequisite": { + "kind": "completed", + "case": "recovery-empty-resume" + }, + "seed": "none", + "expectation": "legacy_verify" + }, + { + "name": "recovery-empty-relaunch", + "root": "recovery-empty", + "prerequisite": { + "kind": "completed", + "case": "recovery-empty-verify" + }, + "seed": "none", + "expectation": "legacy_relaunch" + }, + { + "name": "recovery-parity-crash", + "root": "recovery-parity", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "crash_matching_target" + }, + { + "name": "recovery-parity-cancel", + "root": "recovery-parity", + "prerequisite": { + "kind": "completed", + "case": "recovery-parity-crash" + }, + "seed": "none", + "expectation": "recovery_record_cancel" + }, + { + "name": "recovery-parity-resume", + "root": "recovery-parity", + "prerequisite": { + "kind": "completed", + "case": "recovery-parity-cancel" + }, + "seed": "none", + "expectation": "recovery_record_copied" + }, + { + "name": "recovery-parity-verify", + "root": "recovery-parity", + "prerequisite": { + "kind": "completed", + "case": "recovery-parity-resume" + }, + "seed": "none", + "expectation": "legacy_verify" + }, + { + "name": "recovery-parity-relaunch", + "root": "recovery-parity", + "prerequisite": { + "kind": "completed", + "case": "recovery-parity-verify" + }, + "seed": "none", + "expectation": "legacy_relaunch" + }, + { + "name": "recovery-selection-copy", + "root": "recovery-selection", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "legacy_copy" + }, + { + "name": "recovery-selection-crash", + "root": "recovery-selection", + "prerequisite": { + "kind": "completed", + "case": "recovery-selection-copy" + }, + "seed": "none", + "expectation": "crash_reopened" + }, + { + "name": "recovery-selection-cancel", + "root": "recovery-selection", + "prerequisite": { + "kind": "completed", + "case": "recovery-selection-crash" + }, + "seed": "none", + "expectation": "recovery_selection_cancel" + }, + { + "name": "recovery-selection-resume", + "root": "recovery-selection", + "prerequisite": { + "kind": "completed", + "case": "recovery-selection-cancel" + }, + "seed": "none", + "expectation": "recovery_complete_selection" + }, + { + "name": "recovery-selection-relaunch", + "root": "recovery-selection", + "prerequisite": { + "kind": "completed", + "case": "recovery-selection-resume" + }, + "seed": "none", + "expectation": "legacy_relaunch" + }, + { + "name": "legacy-rich-provisioning-crash", + "root": "legacy-rich-provisioning", + "prerequisite": { + "kind": "initial" + }, + "seed": "legacy_rich", + "expectation": "interrupted_provisioning" + }, + { + "name": "legacy-rich-provisioning-inspect-cancel", + "root": "legacy-rich-provisioning", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-provisioning-crash" + }, + "seed": "none", + "expectation": "recovery_inspect_cancel" + }, + { + "name": "legacy-rich-provisioning-initialize-cancel", + "root": "legacy-rich-provisioning", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-provisioning-inspect-cancel" + }, + "seed": "none", + "expectation": "recovery_initialize_empty_cancel" + }, + { + "name": "legacy-rich-provisioning-resume", + "root": "legacy-rich-provisioning", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-provisioning-initialize-cancel" + }, + "seed": "none", + "expectation": "recovery_initialize_empty_restore" + }, + { + "name": "legacy-rich-provisioning-verify", + "root": "legacy-rich-provisioning", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-provisioning-resume" + }, + "seed": "none", + "expectation": "legacy_verify" + }, + { + "name": "legacy-rich-provisioning-relaunch", + "root": "legacy-rich-provisioning", + "prerequisite": { + "kind": "completed", + "case": "legacy-rich-provisioning-verify" + }, + "seed": "none", + "expectation": "legacy_relaunch" + }, + { + "name": "cleanup", + "root": "authoring", + "prerequisite": { + "kind": "all_stopped" + }, + "seed": "none", + "expectation": "cleanup" + } + ] +} diff --git a/apps/desktop/native-encrypted-qualification/tauri.conf.json b/apps/desktop/native-encrypted-qualification/tauri.conf.json new file mode 100644 index 0000000..a48b8fa --- /dev/null +++ b/apps/desktop/native-encrypted-qualification/tauri.conf.json @@ -0,0 +1,76 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "Rangoon Encrypted Qualification", + "version": "0.1.0-dev", + "identifier": "si.rangoon.encrypted-qualification", + "build": { + "frontendDist": "../../../preview" + }, + "app": { + "withGlobalTauri": true, + "windows": [], + "security": { + "csp": "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' asset: http://asset.localhost; font-src 'self'; connect-src ipc: http://ipc.localhost; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'", + "capabilities": [ + { + "identifier": "e1c4-local-authoring", + "description": "Disposable native encryption qualification; local lifecycle and authoring only.", + "local": true, + "windows": [ + "main" + ], + "permissions": [ + "allow-workspace-startup-status", + "allow-workspace-startup-action", + "allow-workspace-startup-quit", + "allow-get-workspace-close-state", + "allow-get-workspace-control-state", + "allow-get-workspace-protection-state", + "allow-prepare-workspace-control", + "allow-confirm-workspace-control", + "allow-cancel-workspace-control", + "allow-get-workspace-request-state", + "allow-begin-workspace-close", + "allow-acknowledge-workspace-purge", + "allow-select-and-analyze", + "allow-list-snapshots", + "allow-save-analysis", + "allow-open-snapshot", + "allow-read-composition-source", + "allow-clear-analysis", + "allow-get-engine-status", + "allow-list-capabilities", + "allow-open-capability", + "allow-create-capability", + "allow-revise-capability", + "allow-review-capability", + "allow-compile-capability", + "allow-export-instruction-bundle", + "allow-inspect-instruction-bundle", + "allow-get-workspace-data", + "allow-export-workspace-backup", + "allow-create-workspace-recovery-key", + "allow-export-encrypted-workspace-backup", + "allow-prepare-encrypted-workspace-restore", + "allow-prepare-workspace-restore", + "allow-restore-workspace-backup", + "allow-preview-composition", + "allow-commit-composition", + "allow-list-workflows", + "allow-open-workflow", + "allow-begin-workflow-draft", + "allow-inspect-workflow-save", + "allow-commit-workflow-save", + "allow-clear-workflow-draft" + ] + } + ] + } + }, + "bundle": { + "active": false, + "icon": [ + "../icons/32x32.png" + ] + } +} diff --git a/apps/desktop/native-exit-qualification/tauri.conf.json b/apps/desktop/native-exit-qualification/tauri.conf.json new file mode 100644 index 0000000..03e0640 --- /dev/null +++ b/apps/desktop/native-exit-qualification/tauri.conf.json @@ -0,0 +1,29 @@ +{ + "productName": "Rangoon Native Exit Qualification", + "version": "0.1.0-dev", + "identifier": "ai.rangoon.native-exit-qualification", + "build": {}, + "app": { + "withGlobalTauri": false, + "windows": [], + "security": { + "csp": "default-src 'none'", + "capabilities": [ + { + "identifier": "nx06-no-permissions", + "description": "Inert test-only selector; no IPC or webview grants.", + "local": false, + "windows": [], + "webviews": [], + "permissions": [] + } + ] + } + }, + "bundle": { + "active": false, + "icon": [ + "../icons/32x32.png" + ] + } +} diff --git a/apps/desktop/native-input/Cargo.toml b/apps/desktop/native-input/Cargo.toml new file mode 100644 index 0000000..f0e3b16 --- /dev/null +++ b/apps/desktop/native-input/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "rangoon-native-credential-input" +version = "0.1.0-dev" +edition = "2024" +rust-version = "1.99.1" +license = "Apache-2.0" +publish = false + +[dependencies] +tauri = { version = "=2.12.1", default-features = false } +zeroize = "=1.9.0" + +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = "=0.6.4" +objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSString", "NSGeometry"] } +objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSAlert", "NSApplication", "NSButton", "NSControl", "NSResponder", "NSSecureTextField", "NSTextField", "NSView", "NSWindow", "block2"] } +block2 = "=0.6.2" diff --git a/apps/desktop/native-input/src/lib.rs b/apps/desktop/native-input/src/lib.rs new file mode 100644 index 0000000..f33bef0 --- /dev/null +++ b/apps/desktop/native-input/src/lib.rs @@ -0,0 +1,219 @@ +//! Unmounted native review and secret entry. The caller owns consent scope, +//! generation and admission; this crate owns only native widget lifetimes. +//! Toolkit copies are outside the Rust allocation cleanup guarantee. +#![deny(unsafe_code)] + +use std::sync::Arc; +use tauri::{Runtime, Window}; +#[cfg(any(test, target_os = "macos"))] +use zeroize::Zeroize; +use zeroize::Zeroizing; + +#[cfg(target_os = "macos")] +mod macos; + +pub const MAX_SECRET_BYTES: usize = 16 * 1024; + +/// Fixed, payload-free diagnostics for humans and structured callers. No +/// secret, target, toolkit exception or provider response enters these fields. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum InputError { + Unavailable, + Busy, + Cancelled, + Expired, + InvalidInput, + ParentClosed, +} + +impl InputError { + pub const fn code(self) -> &'static str { + match self { + Self::Unavailable => "native_input_unavailable", + Self::Busy => "native_input_busy", + Self::Cancelled => "native_input_cancelled", + Self::Expired => "native_input_expired", + Self::InvalidInput => "native_input_invalid", + Self::ParentClosed => "native_parent_closed", + } + } + + pub const fn message(self) -> &'static str { + match self { + Self::Unavailable => "Native access entry is unavailable.", + Self::Busy => "Another native dialog is still open.", + Self::Cancelled => "Access entry was stopped locally.", + Self::Expired => "This access review expired.", + Self::InvalidInput => "Enter one nonempty header-compatible line, up to 16 KiB.", + Self::ParentClosed => "The initiating window closed.", + } + } + + pub const fn recovery(self) -> &'static str { + match self { + Self::Unavailable => { + "Keep working locally; use a qualified native backend for access entry." + } + Self::Busy => "Finish or cancel the existing dialog before reviewing again.", + Self::Cancelled | Self::Expired | Self::InvalidInput => { + "Start a new explicit access review if another read is needed." + } + Self::ParentClosed => "Reopen the task and start a new access review.", + } + } +} + +/// The existing host supplies a generation/cancellation/deadline check. This +/// is not a second session registry or permission to acquire a credential. +pub trait InputGuard: Send + Sync + 'static { + fn check(&self) -> Result<(), InputError>; + + /// Payload-free observation only after native review dispatch succeeds. + /// This acknowledges queue acceptance, not visible UI or authorization. + fn review_queued(&self) {} + + /// Payload-free observation after the native sheet and secure field have + /// been presented. This notification is not consent or authorization. + fn input_presented(&self) {} +} + +/// Only nonsecret, already selected target metadata. Validation happens again +/// before presentation so a caller cannot turn review text into arbitrary UI. +#[derive(Clone)] +pub struct ReviewDisplay { + pub origin: String, + pub selected_peer: String, + pub installation: String, + pub workspace: String, + pub sandbox: String, + pub product_version: String, + pub root_sha256: String, + pub peer_sha256: String, + pub method: ReadMethod, +} + +#[derive(Clone, Copy)] +pub enum ReadMethod { + ProtectedCheck, + PolicyStatus, + RecentLogs, + RecentWatch, +} + +#[cfg(any(test, target_os = "macos"))] +impl ReadMethod { + fn label(self) -> &'static str { + match self { + Self::ProtectedCheck => "Protected read check", + Self::PolicyStatus => "Policy status and revision metadata", + Self::RecentLogs => "Recent redacted log window", + Self::RecentWatch => "Bounded recent watch window (up to 30 seconds)", + } + } +} + +#[cfg(any(test, target_os = "macos"))] +impl ReviewDisplay { + fn validate(&self) -> Result<(), InputError> { + for (value, bound) in [ + (&self.origin, 512), + (&self.selected_peer, 64), + (&self.installation, 128), + (&self.workspace, 128), + (&self.sandbox, 128), + (&self.product_version, 32), + ] { + if value.is_empty() + || value.len() > bound + || !value.bytes().all(|b| (0x20..=0x7e).contains(&b)) + { + return Err(InputError::InvalidInput); + } + } + if [&self.root_sha256, &self.peer_sha256] + .into_iter() + .any(|s| s.len() != 64 || !s.bytes().all(|b| b.is_ascii_hexdigit())) + { + return Err(InputError::InvalidInput); + } + Ok(()) + } + + fn text(&self) -> String { + format!( + "OpenShell {}\nTarget: {}\nSelected peer: {}\nInstallation: {}\nWorkspace: {}\nSandbox: {}\nRead: {}\nRoot SHA-256: {}\nPeer SHA-256: {}\n\nOne attempt, within the original 120-second review deadline. Result stays in this session. No action execution or approval is granted. Credentials are entered in the next native step and are not saved.", + self.product_version, + self.origin, + self.selected_peer, + self.installation, + self.workspace, + self.sandbox, + self.method.label(), + self.root_sha256, + self.peer_sha256 + ) + } +} + +/// Move-only Rust cleanup custody. No Debug, Clone, serialization or secret +/// accessor for display. The native control is cleared before this is returned. +pub struct SecretInput(Zeroizing); + +impl SecretInput { + #[cfg(any(test, target_os = "macos"))] + fn new(mut value: Zeroizing) -> Result { + if value.is_empty() + || value.len() > MAX_SECRET_BYTES + || !value.bytes().all(|b| (0x20..=0x7e).contains(&b)) + { + value.zeroize(); + return Err(InputError::InvalidInput); + } + Ok(Self(value)) + } + + pub fn into_value(self) -> Zeroizing { + self.0 + } +} + +/// Blocking worker-side call. Never invoke on the native main thread. Success +/// can only follow the actual native review completion callback. +pub fn confirm( + parent: Window, + display: ReviewDisplay, + guard: Arc, +) -> Result<(), InputError> { + #[cfg(target_os = "macos")] + { + display.validate()?; + guard.check()?; + macos::confirm(parent, display.text(), guard) + } + #[cfg(not(target_os = "macos"))] + { + let _ = (parent, display, guard); + Err(InputError::Unavailable) + } +} + +/// Call only after exact native confirmation under the same retained host +/// flight. This function grants no claim or engine authorization itself. +pub fn acquire( + parent: Window, + guard: Arc, +) -> Result { + #[cfg(target_os = "macos")] + { + guard.check()?; + macos::acquire(parent, guard) + } + #[cfg(not(target_os = "macos"))] + { + let _ = (parent, guard); + Err(InputError::Unavailable) + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/desktop/native-input/src/macos.rs b/apps/desktop/native-input/src/macos.rs new file mode 100644 index 0000000..bf929c1 --- /dev/null +++ b/apps/desktop/native-input/src/macos.rs @@ -0,0 +1,278 @@ +//! UI references never leave the native main thread. The thread-local slot +//! retains widgets only; the caller's existing Host owns all authorization, +//! selection, deadlines, cancellation and workspace admission. +use super::{InputError, InputGuard, MAX_SECRET_BYTES, SecretInput}; +use block2::RcBlock; +use objc2::{MainThreadMarker, rc::Retained}; +use objc2_app_kit::{NSAlert, NSModalResponse, NSSecureTextField, NSWindow}; +use objc2_foundation::{NSSize, NSString}; +use std::{ + cell::RefCell, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; +use tauri::{Manager, Runtime, Window}; +use zeroize::Zeroizing; + +static NEXT_ID: AtomicU64 = AtomicU64::new(1); +thread_local! { + static UI: RefCell> = const { RefCell::new(None) }; +} + +struct UiState { + id: u64, + parent: Retained, + alert: Retained, + field: Option>, + guard: Arc, + completed: mpsc::Sender>, +} + +enum Request { + Review(String), + Credential, +} + +enum Reply { + Confirmed, + Credential(SecretInput), +} + +pub(super) fn confirm( + parent: Window, + text: String, + guard: Arc, +) -> Result<(), InputError> { + match request(parent, Request::Review(text), guard)? { + Reply::Confirmed => Ok(()), + Reply::Credential(_) => Err(InputError::Unavailable), + } +} + +pub(super) fn acquire( + parent: Window, + guard: Arc, +) -> Result { + match request(parent, Request::Credential, guard)? { + Reply::Credential(value) => Ok(value), + Reply::Confirmed => Err(InputError::Unavailable), + } +} + +/// All callers are trusted native worker callbacks. Reject a main-thread call +/// rather than blocking the very loop needed for native completion. +fn request( + parent: Window, + request: Request, + guard: Arc, +) -> Result { + if MainThreadMarker::new().is_some() { + return Err(InputError::Unavailable); + } + guard.check()?; + let id = NEXT_ID + .try_update(Ordering::AcqRel, Ordering::Acquire, |v| v.checked_add(1)) + .map_err(|_| InputError::Unavailable)?; + let (tx, rx) = mpsc::channel(); + let is_review = matches!(&request, Request::Review(_)); + let ui_parent = parent.clone(); + let ui_guard = Arc::clone(&guard); + parent + .run_on_main_thread(move || present(ui_parent, request, id, ui_guard, tx)) + .map_err(|_| InputError::Unavailable)?; + if is_review { + guard.review_queued(); + } + let mut dismissal_requested = false; + let result = loop { + match rx.recv_timeout(Duration::from_millis(20)) { + Ok(value) => break value, + Err(mpsc::RecvTimeoutError::Disconnected) => break Err(InputError::Unavailable), + Err(mpsc::RecvTimeoutError::Timeout) => { + if !dismissal_requested && guard.check().is_err() { + // A queued presentation checks the same guard. An open one + // is dismissed only by its own retained parent/alert pair. + if parent.run_on_main_thread(move || dismiss(id)).is_ok() { + dismissal_requested = true; + } + } + } + } + }; + // Sending a completion from inside the native block is not proof that the + // block has returned. Queue a second turn FROM THIS WORKER. It cannot run + // inline on the main thread and acknowledges the prior callback's return. + let (ack_tx, ack_rx) = mpsc::channel(); + let queued = parent.app_handle().run_on_main_thread(move || { + let _ = ack_tx.send(()); + }); + if queued.is_err() || ack_rx.recv().is_err() { + drop(result); + // Runtime loss is not proven cleanup. Keep caller admission retained; + // the owned qualification process has an independent bounded timeout. + loop { + std::thread::park(); + } + } + guard.check()?; + result +} + +fn present( + window: Window, + request: Request, + id: u64, + guard: Arc, + completed: mpsc::Sender>, +) { + let Some(mtm) = MainThreadMarker::new() else { + let _ = completed.send(Err(InputError::Unavailable)); + return; + }; + if let Err(error) = guard.check() { + let _ = completed.send(Err(error)); + return; + } + if UI.with(|slot| slot.borrow().is_some()) { + let _ = completed.send(Err(InputError::Busy)); + return; + } + let parent = match retain_parent(&window, mtm) { + Ok(parent) => parent, + Err(error) => { + let _ = completed.send(Err(error)); + return; + } + }; + if !parent.isVisible() { + let _ = completed.send(Err(InputError::ParentClosed)); + return; + } + if parent.attachedSheet().is_some() { + let _ = completed.send(Err(InputError::Busy)); + return; + } + let alert = NSAlert::new(mtm); + let field = match request { + Request::Review(text) => { + alert.setMessageText(&NSString::from_str("Review system access")); + alert.setInformativeText(&NSString::from_str(&text)); + alert.addButtonWithTitle(&NSString::from_str("Continue")); + None + } + Request::Credential => { + alert.setMessageText(&NSString::from_str("Read once with OpenShell")); + alert.setInformativeText(&NSString::from_str("Enter the credential for the system you just reviewed. It is used for this one read and is not saved. Cancel leaves local work available.")); + alert.addButtonWithTitle(&NSString::from_str("Read once")); + let field = NSSecureTextField::new(mtm); + field.setFrameSize(NSSize::new(360.0, 28.0)); + field.setUsesSingleLineMode(true); + field.setPlaceholderString(Some(&NSString::from_str( + "Credential — one line, up to 16 KiB", + ))); + field.setStringValue(&NSString::from_str("")); + alert.setAccessoryView(Some(&field)); + Some(field) + } + }; + alert.addButtonWithTitle(&NSString::from_str("Cancel")); + let callback = RcBlock::new(move |response: NSModalResponse| complete(id, response)); + UI.with(|slot| { + *slot.borrow_mut() = Some(UiState { + id, + parent: parent.clone(), + alert: alert.clone(), + field, + guard, + completed, + }) + }); + alert.beginSheetModalForWindow_completionHandler(&parent, Some(&callback)); + let focus = UI.with(|slot| { + slot.borrow().as_ref().filter(|s| s.id == id).and_then(|s| { + s.field + .as_ref() + .map(|field| (s.alert.clone(), field.clone(), Arc::clone(&s.guard))) + }) + }); + if let Some((alert, field, guard)) = focus { + alert.window().makeFirstResponder(Some(&field)); + // Observe only after beginSheet and field setup. Release the TLS + // borrow before invoking caller code; a queued request is not open UI. + guard.input_presented(); + } +} + +/// The only direct native pointer operation in this crate. The pointer is +/// obtained from a trusted Tauri Window on the native main thread, never IPC. +#[allow(unsafe_code)] +fn retain_parent( + window: &Window, + _mtm: MainThreadMarker, +) -> Result, InputError> { + let pointer = window.ns_window().map_err(|_| InputError::ParentClosed)?; + // SAFETY: Tauri's pinned ns_window implementation returns the actual + // autoreleased NSWindow associated with this Window's native view. This + // call and retain occur on the main thread before its autorelease pool can + // drain. Retained owns the extra reference; it remains in main-thread-only + // UiState and is dropped there. No pointer or UI object crosses threads. + unsafe { Retained::retain(pointer.cast::()) }.ok_or(InputError::ParentClosed) +} + +fn dismiss(id: u64) { + let owned = UI.with(|slot| { + slot.borrow() + .as_ref() + .filter(|s| s.id == id) + .map(|s| (s.parent.clone(), s.alert.clone())) + }); + if let Some((parent, alert)) = owned { + // Release the RefCell borrow before AppKit can call completion. + parent.endSheet_returnCode(&alert.window(), 1001); + } +} + +fn complete(id: u64, response: NSModalResponse) { + let state = UI.with(|slot| { + let mut slot = slot.borrow_mut(); + if slot.as_ref().is_some_and(|s| s.id == id) { + slot.take() + } else { + None + } + }); + let Some(state) = state else { + return; + }; // duplicate/late completion + let result = match state.guard.check() { + Err(error) => Err(error), + Ok(()) if response != 1000 => Err(InputError::Cancelled), + Ok(()) => match &state.field { + None => Ok(Reply::Confirmed), + Some(field) => { + state.alert.window().makeFirstResponder(None); + let native = field.stringValue(); + if native.length() > MAX_SECRET_BYTES { + Err(InputError::InvalidInput) + } else { + SecretInput::new(Zeroizing::new(native.to_string())).map(Reply::Credential) + } + } + }, + }; + if let Some(field) = &state.field { + state.alert.window().makeFirstResponder(None); + field.setStringValue(&NSString::from_str("")); + field.setEditable(false); + state.alert.setAccessoryView(None); + } + let completed = state.completed.clone(); + let final_guard = Arc::clone(&state.guard); + drop(state); // owned widget/parent references released on this thread + let result = final_guard.check().and(result); + let _ = completed.send(result); // send failure drops/clears owned secret +} diff --git a/apps/desktop/native-input/src/tests.rs b/apps/desktop/native-input/src/tests.rs new file mode 100644 index 0000000..0d7424e --- /dev/null +++ b/apps/desktop/native-input/src/tests.rs @@ -0,0 +1,180 @@ +use super::*; +use zeroize::Zeroizing; + +macro_rules! assert_not_impl { + ($owner:ty: $trait:path) => { + const _: fn() = || { + trait AmbiguousIfImpl { + fn marker() {} + } + impl AmbiguousIfImpl<()> for T {} + struct Invalid; + impl AmbiguousIfImpl for T {} + let _ = <$owner as AmbiguousIfImpl<_>>::marker; + }; + }; +} + +assert_not_impl!(SecretInput: Clone); +assert_not_impl!(SecretInput: std::fmt::Debug); + +fn review_display() -> ReviewDisplay { + ReviewDisplay { + origin: "https://openshell.example.test".into(), + selected_peer: "peer-01".into(), + installation: "example-installation".into(), + workspace: "example-workspace".into(), + sandbox: "example-sandbox".into(), + product_version: "1.2.3".into(), + root_sha256: "a".repeat(64), + peer_sha256: "B".repeat(64), + method: ReadMethod::ProtectedCheck, + } +} + +#[test] +fn review_display_accepts_exact_bounded_metadata_and_formats_it_readably() { + let display = review_display(); + assert_eq!(display.validate(), Ok(())); + assert_eq!( + display.text(), + "OpenShell 1.2.3\nTarget: https://openshell.example.test\nSelected peer: peer-01\nInstallation: example-installation\nWorkspace: example-workspace\nSandbox: example-sandbox\nRead: Protected read check\nRoot SHA-256: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\nPeer SHA-256: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\nOne attempt, within the original 120-second review deadline. Result stays in this session. No action execution or approval is granted. Credentials are entered in the next native step and are not saved." + ); +} + +#[test] +fn review_display_rejects_empty_overbound_and_control_metadata() { + let mut display = review_display(); + display.origin.clear(); + assert_eq!(display.validate(), Err(InputError::InvalidInput)); + + let mut display = review_display(); + display.origin = "a".repeat(513); + assert_eq!(display.validate(), Err(InputError::InvalidInput)); + + let updates: [fn(&mut ReviewDisplay); 6] = [ + |display: &mut ReviewDisplay| display.selected_peer = "a".repeat(65), + |display: &mut ReviewDisplay| display.installation = "a".repeat(129), + |display: &mut ReviewDisplay| display.workspace = "a".repeat(129), + |display: &mut ReviewDisplay| display.sandbox = "a".repeat(129), + |display: &mut ReviewDisplay| display.product_version = "a".repeat(33), + |display: &mut ReviewDisplay| display.workspace = "bad\nworkspace".into(), + ]; + for update in updates { + let mut display = review_display(); + update(&mut display); + assert_eq!(display.validate(), Err(InputError::InvalidInput)); + } +} + +#[test] +fn review_display_requires_exact_hex_pins_and_method_labels() { + let mut display = review_display(); + display.root_sha256 = "C".repeat(63); + assert_eq!(display.validate(), Err(InputError::InvalidInput)); + + let mut display = review_display(); + display.peer_sha256 = "c".repeat(65); + assert_eq!(display.validate(), Err(InputError::InvalidInput)); + + let mut display = review_display(); + display.root_sha256.replace_range(63.., "g"); + assert_eq!(display.validate(), Err(InputError::InvalidInput)); + + assert_eq!(ReadMethod::ProtectedCheck.label(), "Protected read check"); + assert_eq!( + ReadMethod::PolicyStatus.label(), + "Policy status and revision metadata" + ); + assert_eq!(ReadMethod::RecentLogs.label(), "Recent redacted log window"); + assert_eq!( + ReadMethod::RecentWatch.label(), + "Bounded recent watch window (up to 30 seconds)" + ); +} + +#[test] +fn secret_input_rejects_invalid_values_without_trimming_accepted_values() { + let retained = SecretInput::new(Zeroizing::new(" token ".into())).unwrap(); + assert_eq!(retained.into_value().as_str(), " token "); + + let maximum = "a".repeat(MAX_SECRET_BYTES); + assert_eq!( + SecretInput::new(Zeroizing::new(maximum.clone())) + .unwrap() + .into_value() + .as_str(), + maximum + ); + + for value in [ + "".into(), + "a".repeat(MAX_SECRET_BYTES + 1), + "non-ascii-ñ".into(), + "line\nbreak".into(), + "tab\tvalue".into(), + "delete\u{7f}value".into(), + ] { + assert!(matches!( + SecretInput::new(Zeroizing::new(value)), + Err(InputError::InvalidInput) + )); + } +} + +#[test] +fn input_errors_are_fixed_distinct_and_nonsecret() { + let diagnostics = [ + ( + InputError::Unavailable, + "native_input_unavailable", + "Native access entry is unavailable.", + "Keep working locally; use a qualified native backend for access entry.", + ), + ( + InputError::Busy, + "native_input_busy", + "Another native dialog is still open.", + "Finish or cancel the existing dialog before reviewing again.", + ), + ( + InputError::Cancelled, + "native_input_cancelled", + "Access entry was stopped locally.", + "Start a new explicit access review if another read is needed.", + ), + ( + InputError::Expired, + "native_input_expired", + "This access review expired.", + "Start a new explicit access review if another read is needed.", + ), + ( + InputError::InvalidInput, + "native_input_invalid", + "Enter one nonempty header-compatible line, up to 16 KiB.", + "Start a new explicit access review if another read is needed.", + ), + ( + InputError::ParentClosed, + "native_parent_closed", + "The initiating window closed.", + "Reopen the task and start a new access review.", + ), + ]; + for (error, code, message, recovery) in diagnostics { + assert_eq!(error.code(), code); + assert_eq!(error.message(), message); + assert_eq!(error.recovery(), recovery); + assert!(!error.code().contains("token")); + assert!(!error.message().contains("token")); + assert!(!error.recovery().contains("token")); + } + for (index, (error, ..)) in diagnostics.iter().enumerate() { + assert!( + !diagnostics[..index] + .iter() + .any(|(previous, ..)| previous.code() == error.code()) + ); + } +} diff --git a/apps/desktop/src/cloud_models.rs b/apps/desktop/src/cloud_models.rs index 9329544..28aa864 100644 --- a/apps/desktop/src/cloud_models.rs +++ b/apps/desktop/src/cloud_models.rs @@ -35,6 +35,19 @@ struct Envelope { secret: Secret, } impl NativeCloud { + /// Isolated qualification fault: exercise the unchanged native purge result. + #[cfg(all(test, feature = "native-exit-qualification"))] + pub(crate) fn poison_for_native_exit_qualification(&self) { + let state = Arc::clone(&self.state); + let result = std::thread::spawn(move || { + let _guard = state.lock().expect("fixture mutex"); + panic!("nx06 fixture poison"); + }) + .join(); + assert!(result.is_err()); + assert!(self.state.is_poisoned()); + } + pub(super) fn purge_for_workspace_close(&self) -> crate::workspace_close::Cleanup { let (session, state_healthy) = { let (mut state, healthy) = match self.state.lock() { diff --git a/apps/desktop/src/cloud_models_tests.rs b/apps/desktop/src/cloud_models_tests.rs index 98bfce9..dcea07d 100644 --- a/apps/desktop/src/cloud_models_tests.rs +++ b/apps/desktop/src/cloud_models_tests.rs @@ -8,7 +8,7 @@ struct Fixture(std::path::PathBuf); impl Fixture { fn new() -> Self { let sequence = NEXT_FIXTURE - .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| { + .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| { value.checked_add(1) }) .expect("cloud fixture sequence exhausted"); diff --git a/apps/desktop/src/composition.rs b/apps/desktop/src/composition.rs index d2c2a33..39f4ae7 100644 --- a/apps/desktop/src/composition.rs +++ b/apps/desktop/src/composition.rs @@ -25,7 +25,7 @@ struct IssuedPreview { // copies are never used as mutation input. pub(super) enum CompositionHandle { Legacy(Arc), - #[cfg(all(test, feature = "encrypted-workspace"))] + #[cfg(feature = "encrypted-workspace")] Managed(String), } @@ -40,7 +40,7 @@ impl RoutedCompositionPreview { handle: CompositionHandle::Legacy(Arc::new(prepared)), } } - #[cfg(all(test, feature = "encrypted-workspace"))] + #[cfg(feature = "encrypted-workspace")] pub(super) fn managed( prepared: rangoon_desktop::workspace_session::CompositionConfirmation, ) -> Self { diff --git a/apps/desktop/src/data_controls.rs b/apps/desktop/src/data_controls.rs index 9025fae..0a16053 100644 --- a/apps/desktop/src/data_controls.rs +++ b/apps/desktop/src/data_controls.rs @@ -236,11 +236,18 @@ impl NativeRecordKind { pub enum DataResult { Loaded { workspace: WorkspaceData, + encrypted_recovery_supported: bool, }, Exported { backup_id: String, byte_length: usize, }, + RecoveryKeyCreated, + EncryptedExported { + format: &'static str, + backup_id: String, + byte_length: usize, + }, Cancelled, RestoreReady { plan: RestorePlan, @@ -315,6 +322,147 @@ fn pick(app: &AppHandle, exporting: bool) -> Result, .transpose() } +fn pick_recovery( + app: &AppHandle, + key: bool, + saving: bool, +) -> Result, PublicError> { + let window = app.get_webview_window("main").ok_or(PublicError { + code: "workspace_unavailable", + message: "The native recovery picker is unavailable.", + })?; + let (label, extension, name, title) = match (key, saving) { + (true, true) => ( + "Rangoon recovery key", + "rangoon-key", + "Rangoon.rangoon-key", + "Save recovery key separately from your backup", + ), + (true, false) => ( + "Rangoon recovery key", + "rangoon-key", + "Rangoon.rangoon-key", + "Choose the recovery key for this backup", + ), + (false, true) => ( + "Encrypted Rangoon backup", + "rangoon-encrypted", + "Rangoon.rangoon-encrypted", + "Save encrypted workspace backup", + ), + (false, false) => ( + "Encrypted Rangoon backup", + "rangoon-encrypted", + "Rangoon.rangoon-encrypted", + "Choose encrypted workspace backup", + ), + }; + let dialog = app + .dialog() + .file() + .set_parent(&window) + .add_filter(label, &[extension]) + .set_title(title); + let selected = if saving { + dialog.set_file_name(name).blocking_save_file() + } else { + dialog.blocking_pick_file() + }; + selected + .map(|value| { + value + .into_path() + .map_err(|_| crate::encrypted_recovery::invalid()) + }) + .transpose() +} + +#[tauri::command] +pub async fn create_workspace_recovery_key( + workspace: crate::workspace_requests::WorkspaceRequest, + app: AppHandle, +) -> DataResult { + let operation = match app + .state::() + .for_request(&workspace) + .begin_file() + { + Ok(op) => op, + Err(error) => return admission(error), + }; + match tauri::async_runtime::spawn_blocking(move || { + operation.create_recovery_key(|| pick_recovery(&app, true, true)) + }) + .await + { + Ok(completed) => completed.deliver(), + Err(_) => DataResult::Failed { + error: PublicError { + code: "workspace_recovery_output_uncertain", + message: "Key creation did not return a confirmed result. A secret key file may remain; inspect your selected location before retrying.", + }, + }, + } +} +#[tauri::command] +pub async fn export_encrypted_workspace_backup( + workspace: crate::workspace_requests::WorkspaceRequest, + app: AppHandle, +) -> DataResult { + let operation = match app + .state::() + .for_request(&workspace) + .begin_file() + { + Ok(op) => op, + Err(error) => return admission(error), + }; + match tauri::async_runtime::spawn_blocking(move || { + operation.export_encrypted_backup( + || pick_recovery(&app, true, false), + || pick_recovery(&app, false, true), + crate::encrypted_recovery::write_cipher, + crate::encrypted_recovery::read_cipher, + ) + }) + .await + { + Ok(completed) => completed.deliver(), + Err(_) => DataResult::Failed { + error: PublicError { + code: "workspace_recovery_output_uncertain", + message: "Backup did not return a confirmed result. A file may remain; inspect your selected output and use a new name before retrying.", + }, + }, + } +} +#[tauri::command] +pub async fn prepare_encrypted_workspace_restore( + workspace: crate::workspace_requests::WorkspaceRequest, + app: AppHandle, +) -> DataResult { + let access = app.state::().for_request(&workspace); + let operation = match access.begin_file() { + Ok(op) => op, + Err(error) => return admission(error), + }; + match tauri::async_runtime::spawn_blocking(move || { + operation.prepare_encrypted_restore( + || pick_recovery(&app, false, false), + || pick_recovery(&app, true, false), + crate::encrypted_recovery::read_cipher, + ) + }) + .await + { + Ok(completed) => completed.deliver(), + Err(_) => { + access.purge_data_controls(); + failure(StoreError::Unavailable) + } + } +} + #[tauri::command] pub async fn get_workspace_data( workspace: crate::workspace_requests::WorkspaceRequest, diff --git a/apps/desktop/src/encrypted_recovery.rs b/apps/desktop/src/encrypted_recovery.rs new file mode 100644 index 0000000..7f2ec26 --- /dev/null +++ b/apps/desktop/src/encrypted_recovery.rs @@ -0,0 +1,364 @@ +//! Native-only recovery key custody and private encrypted staging. No IPC keys/paths. +use rangoon_host::PublicError; +use rangoon_store::WorkspaceBackup; +use std::path::Path; +#[cfg(all(unix, feature = "encrypted-workspace"))] +use zeroize::Zeroizing; + +pub(super) const FORMAT: &str = "rangoon.recovery.sqlcipher.v1"; +#[cfg(all(unix, feature = "encrypted-workspace"))] +pub(super) const MAX_BYTES: u64 = 64 * 1024 * 1024; +#[cfg(all(unix, feature = "encrypted-workspace"))] +const KEY_PREFIX: &[u8] = b"RANGOON-RECOVERY-KEY-V1\n"; +#[cfg(feature = "encrypted-workspace")] +pub(crate) fn supported() -> bool { + cfg!(all(unix, feature = "encrypted-workspace")) +} +pub(crate) fn invalid() -> PublicError { + PublicError { + code: "workspace_recovery_invalid", + message: "The recovery file or key could not be verified. The workspace was not restored. Check the selected files and their permissions.", + } +} +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn uncertain() -> PublicError { + PublicError { + code: "workspace_recovery_output_uncertain", + message: "The file could not be verified after writing. A file may remain; inspect your selected output and use a new name before retrying.", + } +} +#[cfg(all(unix, feature = "encrypted-workspace"))] +pub(super) struct RecoveryKey(Zeroizing<[u8; 32]>); +#[cfg(not(all(unix, feature = "encrypted-workspace")))] +pub(super) enum RecoveryKey {} +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +std::thread_local! { + static DECODE_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static ENCODE_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +pub(super) fn encode_calls() -> usize { + ENCODE_CALLS.get() +} +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReadPhase { + BeforeOpen, + AfterRead, +} +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +type ReadProbe = (ReadPhase, Box); +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +std::thread_local! { static READ_PROBE: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +fn read_probe(phase: ReadPhase) { + let action = READ_PROBE.with(|slot| { + let mut slot = slot.borrow_mut(); + if slot.as_ref().is_some_and(|(at, _)| *at == phase) { + slot.take() + } else { + None + } + }); + if let Some((_, action)) = action { + action(); + } +} +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +pub(super) fn decode_calls() -> usize { + DECODE_CALLS.get() +} +impl std::fmt::Debug for RecoveryKey { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("RecoveryKey()") + } +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +mod platform { + use super::*; + use rangoon_store::{Workspace, WorkspaceKey}; + use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + path::PathBuf, + }; + + struct Stage { + path: PathBuf, + held: File, + original: fs::Metadata, + } + impl Stage { + fn new() -> Result { + let mut random = [0u8; 16]; + getrandom::fill(&mut random).map_err(|_| invalid())?; + let name: String = random.iter().map(|b| format!("{b:02x}")).collect(); + let path = std::env::temp_dir() + .canonicalize() + .map_err(|_| invalid())? + .join(format!("rangoon-recovery-{name}")); + fs::DirBuilder::new() + .mode(0o700) + .create(&path) + .map_err(|_| invalid())?; + let held = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(&path) + .map_err(|_| invalid())?; + let original = held.metadata().map_err(|_| invalid())?; + let stage = Self { + path, + held, + original, + }; + stage.check()?; + Ok(stage) + } + fn check(&self) -> Result<(), PublicError> { + let current = fs::symlink_metadata(&self.path).map_err(|_| invalid())?; + let held = self.held.metadata().map_err(|_| invalid())?; + if !current.is_dir() + || current.mode() & 0o777 != 0o700 + || current.uid() != self.original.uid() + || !same(¤t, &held) + || !same(¤t, &self.original) + { + return Err(invalid()); + } + Ok(()) + } + fn cleanup(&self) -> Result<(), PublicError> { + self.check()?; + for suffix in ["", "-journal", "-wal", "-shm"] { + let path = self.path.join(format!("workspace.sqlite3{suffix}")); + match fs::symlink_metadata(&path) { + Ok(meta) + if meta.is_file() + && meta.uid() == self.original.uid() + && meta.nlink() == 1 => + { + self.check()?; + fs::remove_file(path).map_err(|_| invalid())?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + _ => return Err(invalid()), + } + } + self.check()?; + fs::remove_dir(&self.path).map_err(|_| invalid()) + } + } + impl Drop for Stage { + fn drop(&mut self) { + let _ = self.cleanup(); + } + } + fn same(a: &fs::Metadata, b: &fs::Metadata) -> bool { + a.dev() == b.dev() && a.ino() == b.ino() + } + fn stable(a: &fs::Metadata, b: &fs::Metadata) -> bool { + same(a, b) + && a.len() == b.len() + && a.mtime() == b.mtime() + && a.mtime_nsec() == b.mtime_nsec() + && a.ctime() == b.ctime() + && a.ctime_nsec() == b.ctime_nsec() + && a.mode() == b.mode() + && a.uid() == b.uid() + && a.nlink() == b.nlink() + } + fn with_stage( + action: impl FnOnce(&Stage) -> Result, + ) -> Result { + let stage = Stage::new()?; + let result = action(&stage); + // Explicit cleanup is part of the result, including unsuccessful attempts. + stage.cleanup().map_err(|_| PublicError{code:"workspace_recovery_cleanup_failed",message:"Private recovery staging could not be removed. Recovery did not return a verified result; inspect temporary-file permissions before retrying."})?; + result + } + fn read( + path: &Path, + limit: u64, + owner: Option, + ) -> Result>, PublicError> { + let before = fs::symlink_metadata(path).map_err(|_| invalid())?; + if !before.is_file() + || before.len() == 0 + || before.len() > limit + || before.nlink() != 1 + || owner.is_some_and(|uid| before.uid() != uid || before.mode() & 0o077 != 0) + { + return Err(invalid()); + } + #[cfg(test)] + read_probe(ReadPhase::BeforeOpen); + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + .map_err(|_| invalid())?; + let opened = file.metadata().map_err(|_| invalid())?; + if !stable(&before, &opened) { + return Err(invalid()); + } + let mut bytes = Zeroizing::new(Vec::new()); + (&mut file) + .take(limit + 1) + .read_to_end(&mut bytes) + .map_err(|_| invalid())?; + #[cfg(test)] + read_probe(ReadPhase::AfterRead); + let after = file.metadata().map_err(|_| invalid())?; + let named = fs::symlink_metadata(path).map_err(|_| invalid())?; + if !stable(&opened, &after) + || !stable(&opened, &named) + || bytes.len() as u64 != opened.len() + { + return Err(invalid()); + } + Ok(bytes) + } + fn write(path: &Path, bytes: &[u8]) -> Result<(), PublicError> { + let mut file=OpenOptions::new().read(true).write(true).create_new(true).mode(0o600).custom_flags(libc::O_NOFOLLOW|libc::O_NONBLOCK).open(path).map_err(|_|PublicError{code:"workspace_recovery_output_unavailable",message:"The output could not be created. Choose a new file name; existing files are never overwritten."})?; + let original = file.metadata().map_err(|_| uncertain())?; + file.write_all(bytes) + .and_then(|_| file.sync_all()) + .map_err(|_| uncertain())?; + let after = file.metadata().map_err(|_| uncertain())?; + let named = fs::symlink_metadata(path).map_err(|_| uncertain())?; + if !same(&original, &after) + || !stable(&after, &named) + || after.len() != bytes.len() as u64 + || !after.is_file() + || after.nlink() != 1 + || after.mode() & 0o077 != 0 + { + return Err(uncertain()); + } + Ok(()) + } + pub(crate) fn read_key(path: &Path) -> Result { + with_stage(|stage| { + let bytes = read(path, 128, Some(stage.original.uid()))?; + if bytes.len() != KEY_PREFIX.len() + 65 + || !bytes.starts_with(KEY_PREFIX) + || bytes.last() != Some(&b'\n') + { + return Err(invalid()); + } + let hex = &bytes[KEY_PREFIX.len()..bytes.len() - 1]; + let mut key = Zeroizing::new([0; 32]); + for (i, pair) in hex.as_chunks::<2>().0.iter().enumerate() { + fn nibble(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + _ => None, + } + } + key[i] = (nibble(pair[0]).ok_or_else(invalid)? << 4) + | nibble(pair[1]).ok_or_else(invalid)?; + } + Ok(RecoveryKey(key)) + }) + } + pub(crate) fn create_key(path: &Path) -> Result<(), PublicError> { + let mut key = Zeroizing::new([0u8; 32]); + getrandom::fill(key.as_mut()).map_err(|_| invalid())?; + let mut bytes = Zeroizing::new(Vec::with_capacity(KEY_PREFIX.len() + 65)); + bytes.extend_from_slice(KEY_PREFIX); + const HEX: &[u8; 16] = b"0123456789abcdef"; + for byte in key.iter() { + bytes.push(HEX[(byte >> 4) as usize]); + bytes.push(HEX[(byte & 15) as usize]); + } + bytes.push(b'\n'); + write(path, &bytes)?; + let reread = read_key(path).map_err(|_| uncertain())?; + if *reread.0 != *key { + return Err(uncertain()); + } + Ok(()) + } + pub(crate) fn encode( + backup: &WorkspaceBackup, + key: &RecoveryKey, + ) -> Result, PublicError> { + #[cfg(test)] + ENCODE_CALLS.set(ENCODE_CALLS.get() + 1); + with_stage(|stage| { + stage.check()?; + let workspace = + Workspace::encrypted(stage.path.clone(), WorkspaceKey::from_bytes(*key.0)) + .map_err(|_| invalid())?; + let bytes = workspace + .create_encrypted_recovery_copy(backup) + .map_err(|_| invalid())?; + stage.check()?; + Ok(bytes) + }) + } + pub(crate) fn decode(bytes: &[u8], key: &RecoveryKey) -> Result { + #[cfg(test)] + DECODE_CALLS.set(DECODE_CALLS.get() + 1); + if bytes.is_empty() || bytes.len() as u64 > MAX_BYTES || !bytes.len().is_multiple_of(4096) { + return Err(invalid()); + } + with_stage(|stage| { + stage.check()?; + write(&stage.path.join("workspace.sqlite3"), bytes)?; + let workspace = + Workspace::encrypted(stage.path.clone(), WorkspaceKey::from_bytes(*key.0)) + .map_err(|_| invalid())?; + let backup = workspace + .inspect_encrypted_recovery_copy(bytes.len() as u64) + .map_err(|_| invalid())?; + stage.check()?; + Ok(backup) + }) + } + pub(crate) fn read_cipher(path: &Path) -> Result, PublicError> { + Ok(read(path, MAX_BYTES, None)?.to_vec()) + } + pub(crate) fn write_cipher(path: &Path, bytes: &[u8]) -> Result<(), PublicError> { + if bytes.is_empty() || bytes.len() as u64 > MAX_BYTES { + return Err(invalid()); + } + write(path, bytes) + } +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +pub(super) use platform::{create_key, decode, encode, read_cipher, read_key, write_cipher}; + +#[cfg(not(all(unix, feature = "encrypted-workspace")))] +mod unsupported { + use super::*; + pub(crate) fn create_key(_: &Path) -> Result<(), PublicError> { + Err(invalid()) + } + pub(crate) fn read_key(_: &Path) -> Result { + Err(invalid()) + } + pub(crate) fn encode(_: &WorkspaceBackup, _: &RecoveryKey) -> Result, PublicError> { + Err(invalid()) + } + pub(crate) fn decode(_: &[u8], _: &RecoveryKey) -> Result { + Err(invalid()) + } + pub(crate) fn read_cipher(_: &Path) -> Result, PublicError> { + Err(invalid()) + } + pub(crate) fn write_cipher(_: &Path, _: &[u8]) -> Result<(), PublicError> { + Err(invalid()) + } +} +#[cfg(not(all(unix, feature = "encrypted-workspace")))] +pub(super) use unsupported::{create_key, decode, encode, read_cipher, read_key, write_cipher}; + +#[cfg(all(test, unix, feature = "encrypted-workspace"))] +#[path = "encrypted_recovery_tests.rs"] +mod tests; diff --git a/apps/desktop/src/encrypted_recovery_tests.rs b/apps/desktop/src/encrypted_recovery_tests.rs new file mode 100644 index 0000000..469d9a5 --- /dev/null +++ b/apps/desktop/src/encrypted_recovery_tests.rs @@ -0,0 +1,130 @@ +use super::*; + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn recovery_secret_debug_and_receipt_do_not_serialize_key_material() { + let key = RecoveryKey(Zeroizing::new([87; 32])); + assert_eq!(format!("{key:?}"), "RecoveryKey()"); + assert_eq!(FORMAT, "rangoon.recovery.sqlcipher.v1"); +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +mod unix { + use super::*; + #[test] + fn selected_key_and_cipher_replacement_before_open_or_after_read_refuses() { + for phase in [ReadPhase::BeforeOpen, ReadPhase::AfterRead] { + for key in [false, true] { + let root = TestRoot::new("recovery-selected-swap"); + let path = root.0.join("selected"); + if key { + create_key(&path).unwrap(); + } else { + write_cipher(&path, &[17; 4096]).unwrap(); + } + let replacement = root.0.join("replacement"); + fs::copy(&path, &replacement).unwrap(); + fs::set_permissions(&replacement, fs::Permissions::from_mode(0o600)).unwrap(); + let selected = path.clone(); + READ_PROBE.with(|slot| { + *slot.borrow_mut() = Some(( + phase, + Box::new(move || { + fs::rename(replacement, selected).unwrap(); + }), + )) + }); + if key { + assert!(read_key(&path).is_err()); + } else { + assert!(read_cipher(&path).is_err()); + } + assert!(READ_PROBE.with(|slot| slot.borrow().is_none())); + } + } + } + struct TestRoot(std::path::PathBuf); + impl TestRoot { + fn new(label: &str) -> Self { + let mut nonce = [0; 16]; + getrandom::fill(&mut nonce).unwrap(); + let suffix: String = nonce.iter().map(|b| format!("{b:02x}")).collect(); + let path = std::env::temp_dir().join(format!("{label}-{suffix}")); + fs::create_dir(&path).unwrap(); + Self(path.canonicalize().unwrap()) + } + } + impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + use std::{ + fs, + os::unix::fs::{PermissionsExt, symlink}, + }; + + #[test] + fn key_files_are_bounded_private_exact_and_never_overwritten() { + let root = TestRoot::new("recovery-key"); + let path = root.0.join("recovery.rangoon-key"); + create_key(&path).unwrap(); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + let original = Zeroizing::new(fs::read(&path).unwrap()); + assert!(read_key(&path).is_ok()); + assert!(create_key(&path).is_err()); + assert_eq!(fs::read(&path).unwrap(), *original); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_key(&path).is_err()); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + let alias = root.0.join("alias"); + symlink(&path, &alias).unwrap(); + assert!(read_key(&alias).is_err()); + fs::remove_file(&alias).unwrap(); + fs::hard_link(&path, &alias).unwrap(); + assert!(read_key(&path).is_err()); + fs::remove_file(alias).unwrap(); + for bytes in [b"".as_slice(), b"RANGOON-RECOVERY-KEY-V2\n", &[b'0'; 129]] { + fs::write(&path, bytes).unwrap(); + assert!(read_key(&path).is_err()); + } + } + + #[test] + fn private_cipher_staging_roundtrip_wrong_keys_trailing_pages_and_no_overwrite() { + let root = TestRoot::new("recovery-codec"); + let store = rangoon_store::Workspace::new(root.0.join("source")); + let report = + rangoon_import::analyze("AGENTS.md", b"# Rules\nSynthetic recovery sentinel\n") + .unwrap(); + store.save_v1(&report).unwrap(); + let archive = store.export_workflow_backup().unwrap(); + let backup = WorkspaceBackup::decode(&archive).unwrap(); + let key = RecoveryKey(Zeroizing::new([23; 32])); + let bytes = encode(&backup, &key).unwrap(); + assert!( + decode(&bytes, &key) + .unwrap() + .same_recovery_records(&backup) + .unwrap() + ); + assert!(decode(&bytes, &RecoveryKey(Zeroizing::new([24; 32]))).is_err()); + let path = root.0.join("backup.rangoon-encrypted"); + write_cipher(&path, &bytes).unwrap(); + assert!(write_cipher(&path, &bytes).is_err()); + assert_eq!(read_cipher(&path).unwrap(), bytes); + for alteration in 0..3 { + let mut bad = bytes.clone(); + match alteration { + 0 => bad[100] ^= 1, + 1 => bad.extend_from_slice(&[0; 4096]), + _ => bad.push(0), + } + assert!(decode(&bad, &key).is_err()); + } + assert!(decode(b"RANGOON-BACKUP-V3\n", &key).is_err()); + } +} diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index b21ef53..bd24d0e 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -1,8 +1,18 @@ #![forbid(unsafe_code)] +// The explicit harness=false target reuses this entry's private native state. +// Rust omits #[test] bodies there, leaving ordinary unit-fixture imports and +// helpers unused. Normal builds/tests keep their strict lint policy; the new +// qualification module denies warnings independently. +#![cfg_attr( + all(test, feature = "native-credential-qualification"), + allow(dead_code, unused_imports) +)] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use rangoon_desktop::workspace_lifecycle::{Error as GateError, Gate, Lane, Lease}; +mod source_collection; +use source_collection::{select_and_inspect_sources, select_and_list_sources}; mod workflows; use workflows::{ begin_workflow_draft, clear_workflow_draft, commit_workflow_save, inspect_workflow_save, @@ -14,13 +24,21 @@ use compilation::compile_capability; mod composition; use composition::{commit_composition, preview_composition}; mod data_controls; +mod encrypted_recovery; use data_controls::{ - delete_workspace_record, export_workspace_backup, get_workspace_data, - inspect_workspace_deletion, prepare_workspace_restore, restore_workspace_backup, + create_workspace_recovery_key, delete_workspace_record, export_encrypted_workspace_backup, + export_workspace_backup, get_workspace_data, inspect_workspace_deletion, + prepare_encrypted_workspace_restore, prepare_workspace_restore, restore_workspace_backup, }; mod instruction_bundles; use instruction_bundles::{export_instruction_bundle, inspect_instruction_bundle}; mod operations; +// Native-owned startup classification and conversion custody. +#[cfg(feature = "encrypted-workspace")] +mod workspace_adoption; +#[cfg(feature = "encrypted-workspace")] +mod workspace_startup; +mod workspace_startup_host; use operations::select_and_inspect_operations; mod cloud_credentials; mod cloud_custody; @@ -50,10 +68,11 @@ use rangoon_store::Workspace; use rangoon_store::{SnapshotMetadata, StoreError}; use serde::Serialize; mod workspace_close; +mod workspace_native_bootstrap; mod workspace_requests; use workspace_requests::get_workspace_request_state; mod workspace_source_access; -use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder}; +use tauri::{AppHandle, Manager, WebviewWindow}; use tauri_plugin_dialog::DialogExt; use workspace_close::setup::{ cancel_workspace_control, confirm_workspace_control, get_workspace_control_state, @@ -63,6 +82,9 @@ use workspace_close::{ WorkspaceClose, acknowledge_workspace_purge, begin_workspace_close, get_workspace_close_state, }; use workspace_source_access::SourceAccess; +use workspace_startup_host::{ + workspace_startup_action, workspace_startup_quit, workspace_startup_status, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum AdmissionError { @@ -199,7 +221,8 @@ fn dispatch_read( action() })) } -/// Uses the same private source state in Builder setup and synthetic fixtures. +/// Legacy content regressions only. Ordinary startup never selects plaintext. +#[cfg(test)] fn source_state(gate: &Gate, root: Result) -> SourceAccess { SourceAccess::legacy(gate.clone(), root) } @@ -320,10 +343,103 @@ pub(crate) fn parented_review_window_size( review_window_size(work_area, target) } +#[cfg(all(test, feature = "native-credential-qualification"))] +use openshell_host::native_credential_qualification; +#[cfg(all(test, feature = "native-exit-qualification"))] +use openshell_host::native_exit_qualification; +#[cfg(all(test, target_os = "macos"))] +mod native_encrypted_case_plan; +#[cfg(all(test, feature = "native-encrypted-qualification"))] +mod native_encrypted_qualification; +#[cfg(all(test, target_os = "macos"))] +mod native_encrypted_seeds; + +#[cfg(all( + test, + any( + all( + feature = "native-exit-qualification", + feature = "native-encrypted-qualification" + ), + all( + feature = "native-exit-qualification", + feature = "native-credential-qualification" + ), + all( + feature = "native-encrypted-qualification", + feature = "native-credential-qualification" + ) + ) +))] +fn main() { + eprintln!("qualification: ambiguous target features"); + std::process::exit(64); +} + +#[cfg(all( + test, + feature = "native-exit-qualification", + not(any( + feature = "native-encrypted-qualification", + feature = "native-credential-qualification" + )) +))] +fn main() { + native_exit_qualification::run(); +} + +#[cfg(all( + test, + feature = "native-encrypted-qualification", + not(any( + feature = "native-exit-qualification", + feature = "native-credential-qualification" + )) +))] +fn main() { + native_encrypted_qualification::run(); +} + +#[cfg(all( + test, + feature = "native-credential-qualification", + not(any( + feature = "native-exit-qualification", + feature = "native-encrypted-qualification" + )) +))] fn main() { + native_credential_qualification::run(); +} + +#[cfg(not(all( + test, + any( + feature = "native-exit-qualification", + feature = "native-encrypted-qualification", + feature = "native-credential-qualification" + ) +)))] +fn main() { + let app = desktop_builder() + .setup(|app| { + let anchor = app + .path() + .app_local_data_dir() + .map_err(|_| StoreError::Unavailable); + workspace_native_bootstrap::install_workbench_state(app.handle(), anchor) + .map_err(|_| std::io::Error::other("workspace services unavailable"))?; + Ok(()) + }) + .build(tauri::generate_context!()) + .expect("could not start Rangoon desktop"); + run_workbench(app); +} + +/// Identical states, handlers and window hooks for product and qualification. +fn desktop_builder() -> tauri::Builder { let (gate, model_flight) = admission_state(); - let openshell_exit_waiter = workspace_close::failure::CallbackWaiter::default(); - let app = tauri::Builder::default() + tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) .manage(gate.clone()) .manage(NativeModel::default()) @@ -332,12 +448,23 @@ fn main() { .manage(cloud_custody::Custody::with_gate(gate.clone())) .manage(openshell_host::Host::new(gate.clone())) .on_window_event(|window, event| { + if matches!( + event, + tauri::WindowEvent::CloseRequested { .. } | tauri::WindowEvent::Destroyed + ) { + window + .state::() + .parent_closed(window.label()); + } workspace_close::window_event(window, event); models::window_event(window, event); cloud_models::window_event(window, event); cloud_credentials::window_event(window, event); }) .invoke_handler(tauri::generate_handler![ + workspace_startup_status, + workspace_startup_action, + workspace_startup_quit, get_workspace_close_state, get_workspace_control_state, get_workspace_protection_state, @@ -348,6 +475,8 @@ fn main() { begin_workspace_close, acknowledge_workspace_purge, select_and_analyze, + select_and_inspect_sources, + select_and_list_sources, select_and_inspect_operations, list_snapshots, save_analysis, @@ -365,6 +494,9 @@ fn main() { inspect_instruction_bundle, get_workspace_data, export_workspace_backup, + create_workspace_recovery_key, + export_encrypted_workspace_backup, + prepare_encrypted_workspace_restore, prepare_workspace_restore, restore_workspace_backup, inspect_workspace_deletion, @@ -404,81 +536,97 @@ fn main() { confirm_local_model_review, cancel_local_model_review, ]) - .setup(|app| { - let root = app - .path() - .app_local_data_dir() - .map(|path| path.join("source-workspace")) - .map_err(|_| StoreError::Unavailable); - app.manage(source_state(app.state::().inner(), root)); - app.manage(WorkspaceClose::new( - app.state::().inner().clone(), - )); - let work_area = app.primary_monitor().ok().flatten().map(|monitor| { - ( - monitor.work_area().size.width, - monitor.work_area().size.height, - monitor.scale_factor(), - ) - }); - let (initial_width, initial_height) = initial_window_size(work_area); - WebviewWindowBuilder::new(app, "main", WebviewUrl::App("analyze.html".into())) - .title("Rangoon") - .inner_size(initial_width, initial_height) - .min_inner_size(320.0, 480.0) - .center() - .on_navigation(bundled_navigation) - .build()?; - Ok(()) - }) - .build(tauri::generate_context!()) - .expect("could not start Rangoon desktop"); - // Tauri runs setup on Ready, after build. SourceAccess and WorkspaceClose - // are registered there, so install the lifetime anchor only after setup. - // It belongs to the event loop, outside managed state; SourceAccess retains - // only a weak host notifier and cannot keep it alive. +} + +/// Setup has registered all native states before Ready. The anchor is owned by +/// this event-loop closure, and remains alive until the actual Exit callback. +fn run_workbench(app: tauri::App) { let mut failure_anchor = None; + let openshell_exit_waiter = workspace_close::failure::CallbackWaiter::default(); app.run(move |app, event| { - if matches!(&event, tauri::RunEvent::Ready) { - failure_anchor = workspace_close::failure::install(app); + #[cfg(all(test, feature = "native-encrypted-qualification"))] + if matches!(event, tauri::RunEvent::Ready) { + native_encrypted_qualification::before_ready(app); } - if let tauri::RunEvent::ExitRequested { code, api, .. } = &event { - let cancel = || app.state::().cancel_and_check_exit(); - let action = match failure_anchor.as_ref() { - Some(anchor) => anchor.exit_request(*code, cancel), - None => workspace_close::failure::route_exit_request(*code, None, cancel), - }; - match action { - workspace_close::failure::ExitAction::Pass => {} - workspace_close::failure::ExitAction::Prevent => api.prevent_exit(), - workspace_close::failure::ExitAction::PreventAndWait => { - api.prevent_exit(); - let checking = app.clone(); - let exiting = app.clone(); - openshell_exit_waiter.spawn( - *code, - move || { - checking - .state::() - .cancel_and_check_exit() - }, - move |code| exiting.exit(code), - ); - } - workspace_close::failure::ExitAction::PreventAndStart => { - api.prevent_exit(); - if let Some(anchor) = failure_anchor.as_ref() { - anchor.begin_exit_close(); - } - } + coordinate_native_event(app, &event, &mut failure_anchor, &openshell_exit_waiter); + if matches!(event, tauri::RunEvent::Ready) { + let result = + workspace_native_bootstrap::present_workbench(app, failure_anchor.is_some()); + #[cfg(all(test, feature = "native-encrypted-qualification"))] + native_encrypted_qualification::after_ready( + app, + failure_anchor.is_some(), + result.is_ok(), + ); + if result.is_err() { + eprintln!("rangoon: desktop startup failed"); + app.exit(workspace_close::failure::RECOVERY_EXIT_CODE); } } + #[cfg(all(test, feature = "native-encrypted-qualification"))] if matches!(event, tauri::RunEvent::Exit) { - failure_anchor.take(); + native_encrypted_qualification::exited(app); } }); } +/// One native lifecycle path for the product and the isolated qualification target. +fn coordinate_native_event( + app: &AppHandle, + event: &tauri::RunEvent, + failure_anchor: &mut Option, + openshell_exit_waiter: &workspace_close::failure::CallbackWaiter, +) { + if matches!(event, tauri::RunEvent::Ready) { + *failure_anchor = workspace_close::failure::install(app); + #[cfg(all(test, feature = "native-exit-qualification"))] + native_exit_qualification::ready(app, failure_anchor.is_some()); + } + if let tauri::RunEvent::ExitRequested { code, api, .. } = event { + let cancel = || app.state::().cancel_and_check_exit(); + let action = match failure_anchor.as_ref() { + Some(anchor) => anchor.exit_request(*code, cancel), + None => workspace_close::failure::route_exit_request(*code, None, cancel), + }; + #[cfg(all(test, feature = "native-exit-qualification"))] + native_exit_qualification::exit_action(app, *code, action); + match action { + workspace_close::failure::ExitAction::Pass => {} + workspace_close::failure::ExitAction::Prevent => api.prevent_exit(), + workspace_close::failure::ExitAction::PreventAndWait => { + api.prevent_exit(); + let checking = app.clone(); + let exiting = app.clone(); + #[cfg(all(test, feature = "native-exit-qualification"))] + let mut probe = native_exit_qualification::WaitProbe::default(); + openshell_exit_waiter.spawn( + *code, + move || { + let drained = checking + .state::() + .cancel_and_check_exit(); + #[cfg(all(test, feature = "native-exit-qualification"))] + probe.checked(drained); + drained + }, + move |code| exiting.exit(code), + ); + } + workspace_close::failure::ExitAction::PreventAndStart => { + api.prevent_exit(); + if let Some(anchor) = failure_anchor.as_ref() { + anchor.begin_exit_close(); + } + } + } + } + if matches!(event, tauri::RunEvent::Exit) { + #[cfg(all(test, feature = "native-exit-qualification"))] + native_exit_qualification::exited(); + failure_anchor.take(); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/apps/desktop/src/native_credential_qualification.rs b/apps/desktop/src/native_credential_qualification.rs new file mode 100644 index 0000000..ca07c28 --- /dev/null +++ b/apps/desktop/src/native_credential_qualification.rs @@ -0,0 +1,597 @@ +//! Explicit no-webview native C1 qualification. Dummy credentials and a +//! generated loopback TLS peer only. Never an ordinary application entry. +#![deny(warnings)] +#[cfg(not(target_os = "macos"))] +pub(crate) fn run() { + eprintln!("native_credential_unavailable"); + std::process::exit(64); +} + +#[cfg(target_os = "macos")] +pub(crate) use macos::run; + +#[cfg(target_os = "macos")] +mod macos { + use super::super::*; + use rangoon_openshell_client::synthetic_peer::{ + SyntheticPeer, SyntheticRpc, SyntheticScenario, + }; + use serde_json::{Value, json}; + use std::{ + io::{Read, Write}, + sync::{OnceLock, mpsc}, + time::{Duration, Instant}, + }; + use tauri::{ + Manager, Window, + utils::config::{CapabilityEntry, Config, Csp}, + }; + + const CASES: [&str; 6] = [ + "accept-read", + "cancel-review", + "stop-queued", + "stop-open", + "expire-open", + "parent-close", + ]; + static CASE: OnceLock = OnceLock::new(); + static NONCE: OnceLock = OnceLock::new(); + static EVENTS: Mutex = Mutex::new(0); + static FINISHED: AtomicBool = AtomicBool::new(false); + + fn context_label(case: &str, nonce: &str) -> String { + format!("c1-{case}-{nonce}") + } + + fn case_context() -> String { + context_label(CASE.get().expect("case"), NONCE.get().expect("nonce")) + } + + #[test] + fn native_case_context_keeps_full_case_and_nonce() { + let nonce = "0123456789abcdef0123456789abcdef"; + for case in CASES { + let context = context_label(case, nonce); + assert_eq!(context, format!("c1-{case}-{nonce}")); + assert!(context.len() <= 128); + assert_ne!(context, context_label(case, &"f".repeat(32))); + } + } + + // Stop and expiry are independent qualification cases. Refuse a Stop + // control near the original selection deadline instead of allowing an + // expired attempt to masquerade as a Stop-only native result. + fn timely_stop(deadline: Instant, now: Instant) -> bool { + deadline.saturating_duration_since(now) >= Duration::from_secs(10) + } + + fn stop_returned_before_expiry(deadline: Instant, now: Instant) -> bool { + now < deadline + } + + #[test] + fn native_stop_timing_accepts_exact_margin_without_renewing_deadline() { + let now = Instant::now(); + assert!(timely_stop(now + Duration::from_secs(10), now)); + assert!(timely_stop(now + Duration::from_secs(120), now)); + } + + #[test] + fn native_stop_timing_rejects_insufficient_and_expired_margin() { + let now = Instant::now(); + assert!(!timely_stop(now + Duration::from_millis(9_999), now)); + assert!(!timely_stop(now, now)); + assert!(!timely_stop(now - Duration::from_secs(1), now)); + } + + #[test] + fn native_stop_return_rejects_exact_expiry_and_later() { + let deadline = Instant::now(); + assert!(stop_returned_before_expiry( + deadline, + deadline - Duration::from_nanos(1) + )); + assert!(!stop_returned_before_expiry(deadline, deadline)); + assert!(!stop_returned_before_expiry( + deadline, + deadline + Duration::from_nanos(1) + )); + } + + fn emit(event: &'static str, fields: Value) { + let mut sequence = EVENTS.lock().expect("fixed event lock"); + *sequence += 1; + let line = serde_json::to_vec(&json!({ + "schema":"rangoon.native-credential-qualification.v2", + "case":CASE.get().expect("case"),"nonce":NONCE.get().expect("nonce"), + "sequence":*sequence,"event":event,"fields":fields, + })) + .expect("fixed event encoding"); + assert!( + *sequence <= 128 && line.len() <= 8192, + "fixed evidence bound" + ); + let mut stdout = std::io::stdout().lock(); + stdout.write_all(&line).expect("event write"); + stdout.write_all(b"\n").expect("event line"); + stdout.flush().expect("event flush"); + } + + fn context_valid(config: &Config, assets_empty: bool) -> bool { + config.identifier == "ai.rangoon.native-credential-qualification" + && !config.bundle.active + && !config.app.with_global_tauri + && config.app.windows.is_empty() + && matches!( + config.app.security.csp.as_ref(), + Some(Csp::Policy(policy)) if policy == "default-src 'none'" + ) + && matches!( + config.app.security.capabilities.as_slice(), + [CapabilityEntry::Inlined(capability)] + if capability.identifier == "c1-no-permissions" + && !capability.local + && capability.remote.is_none() + && capability.windows.is_empty() + && capability.webviews.is_empty() + && capability.permissions.is_empty() + ) + && config.build.dev_url.is_none() + && config.build.frontend_dist.is_none() + && assets_empty + } + + fn qualification_context() -> tauri::Context { + tauri::generate_context!( + "native-credential-qualification/tauri.conf.json", + test = true, + assets = tauri::utils::assets::EmbeddedAssets::new( + tauri::utils::assets::phf::Map::new(), + &[], + tauri::utils::assets::phf::Map::new() + ) + ) + } + + #[test] + fn generated_native_context_is_inert_despite_omitted_empty_capability_lists() { + let context = qualification_context(); + assert!(context_valid( + context.config(), + context.assets.iter().next().is_none() + )); + // Pinned Tauri omits these empty vectors when serializing. Safety must + // inspect the actual typed configuration, not serialization presence. + let serialized = serde_json::to_value(context.config()).unwrap(); + let capability = &serialized["app"]["security"]["capabilities"][0]; + assert!(capability.get("windows").is_none()); + assert!(capability.get("webviews").is_none()); + assert_eq!(capability["permissions"], json!([])); + } + + #[test] + fn generated_native_context_rejects_each_capability_and_surface_expansion() { + fn capability(config: &mut Config) -> &mut tauri::utils::acl::capability::Capability { + let CapabilityEntry::Inlined(capability) = &mut config.app.security.capabilities[0] + else { + panic!("fixture must have inline capability"); + }; + capability + } + let context = qualification_context(); + let baseline = context.config(); + assert!(context_valid(baseline, true)); + let mutations: [fn(&mut Config); 18] = [ + |c| c.identifier = "ai.rangoon.other".into(), + |c| c.bundle.active = true, + |c| c.app.with_global_tauri = true, + |c| c.app.windows.push(Default::default()), + |c| c.app.security.csp = None, + |c| c.app.security.csp = Some(Csp::Policy("default-src *".into())), + |c| c.app.security.capabilities.clear(), + |c| c.app.security.capabilities[0] = CapabilityEntry::Reference("other".into()), + |c| { + c.app + .security + .capabilities + .push(c.app.security.capabilities[0].clone()) + }, + |c| capability(c).identifier = "other".into(), + |c| capability(c).local = true, + |c| { + capability(c).remote = Some( + serde_json::from_value(json!({"urls":["https://example.invalid"]})).unwrap(), + ) + }, + |c| capability(c).windows.push("*".into()), + |c| capability(c).webviews.push("*".into()), + |c| { + capability(c) + .permissions + .push(serde_json::from_value(json!("core:default")).unwrap()) + }, + |c| c.build.dev_url = Some("https://example.invalid".parse().unwrap()), + |c| c.build.frontend_dist = Some(serde_json::from_value(json!("../preview")).unwrap()), + |c| c.app.security.csp = Some(Csp::DirectiveMap(Default::default())), + ]; + for (index, mutate) in mutations.into_iter().enumerate() { + let mut changed = baseline.clone(); + mutate(&mut changed); + assert!(!context_valid(&changed, true), "unsafe mutation {index}"); + } + assert!( + !context_valid(baseline, false), + "embedded assets must stay empty" + ); + } + + fn stop_with_drain( + host: &Host, + gate: &Gate, + ) -> (HostStatus, rangoon_desktop::workspace_lifecycle::Drain) { + let status = host.stop(); + let drain = gate.request_drain().expect("memory stop drain"); + (status, drain) + } + + #[test] + fn native_stop_proof_retains_real_host_callback_through_drain() { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let peer = runtime + .block_on(SyntheticPeer::start(SyntheticScenario::Healthy)) + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let workspace = WorkspaceRequest::Managed(Arc::new(gate.observe_open().unwrap())); + let target = ProposedTarget::new( + peer.origin().to_owned(), + peer.selected_peer(), + "c1-synthetic".into(), + "workspace-1".into(), + "sandbox-1".into(), + peer.root_der().to_vec(), + peer.leaf_der().to_vec(), + ) + .unwrap(); + let review = host + .prepare( + &workspace, + target, + ReadKind::RecentLogs, + Retention::SessionOnly, + ) + .unwrap(); + let (entered, began) = mpsc::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_callback( + &review.id, + None, + CallbackStart::NativeReview, + Some("test-parent".into()), + move |_, _, _, _, _| { + entered.send(()).unwrap(); + let _ = held.recv(); + Err(ClientError::Cancelled) + }, + ), + HostStatus::Running + ); + began.recv_timeout(Duration::from_secs(2)).unwrap(); + // A read callback does not occupy the independent Exclusive lane. + // Drain quiescence, not unrelated lane admission, proves custody. + drop(gate.begin(Lane::Exclusive).unwrap()); + let (status, drain) = stop_with_drain(&host, &gate); + assert_eq!(status, HostStatus::Closing); + assert!(!drain.is_quiescent().unwrap()); + assert!(gate.begin(Lane::Read).is_err()); + assert!(gate.begin(Lane::Exclusive).is_err()); + release.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while host.status() == HostStatus::Closing && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + assert_eq!(host.status(), HostStatus::Cancelled); + assert!(drain.is_quiescent().unwrap()); + assert!(peer.calls().unwrap().is_empty()); + assert!(host.cancel_and_check_exit()); + runtime.block_on(peer.shutdown()).unwrap(); + } + + pub(crate) fn run() { + let args: Vec<_> = std::env::args().skip(1).take(5).collect(); + if args.len() != 4 + || args[0] != "--case" + || !CASES.contains(&args[1].as_str()) + || args[2] != "--nonce" + || args[3].len() != 32 + || !args[3] + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + eprintln!("native_credential_invalid_case"); + std::process::exit(64); + } + CASE.set(args[1].clone()).expect("one case"); + NONCE.set(args[3].clone()).expect("one nonce"); + let plan: Value = serde_json::from_str(include_str!( + "../native-credential-qualification/cases.v1.json" + )) + .expect("compiled plan"); + assert_eq!( + plan, + json!({"schema":"rangoon.native-credential-cases.v1", "cases":CASES.map(|id| json!({"id":id}))}) + ); + let context = qualification_context(); + assert!( + context_valid(context.config(), context.assets.iter().next().is_none()), + "native_credential_unsafe_context" + ); + let gate = Gate::new(); + let app = tauri::Builder::default() + .manage(Host::new(gate.clone())) + .on_window_event(|window, event| { + if matches!( + event, + tauri::WindowEvent::CloseRequested { .. } | tauri::WindowEvent::Destroyed + ) { + window.state::().parent_closed(window.label()); + } + }) + .setup(move |app| { + let title = format!("Rangoon C1-M {}", case_context()); + let parent = tauri::WindowBuilder::new(app, "c1-native-parent") + .title(title) + .inner_size(820.0, 680.0) + .build()?; + let host = app.state::().inner().clone(); + std::thread::Builder::new() + .name("rangoon-c1-qualification".into()) + .spawn(move || { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + qualify(parent, host, gate) + })) + .is_err() + { + eprintln!("native_credential_case_failed"); + std::process::exit(70); + } + })?; + Ok(()) + }) + .build(context) + .expect("isolated native context"); + app.run(|app, event| { + if let tauri::RunEvent::ExitRequested { api, .. } = event + && (!FINISHED.load(Ordering::Acquire) + || !app.state::().cancel_and_check_exit()) + { + api.prevent_exit(); + } + }); + } + + struct MainHold { + release: mpsc::Sender<()>, + } + fn hold_main(parent: &Window) -> MainHold { + let (release, held) = mpsc::channel(); + let (entered, began) = mpsc::channel(); + parent + .run_on_main_thread(move || { + emit("main_held", json!({})); + let _ = entered.send(()); + let _ = held.recv(); // only owned test main loop, not production UI + emit("main_released", json!({})); + }) + .expect("queue owned hold"); + began + .recv_timeout(Duration::from_secs(5)) + .expect("owned hold entered"); + MainHold { release } + } + + fn commands() -> mpsc::Receiver { + let (tx, rx) = mpsc::sync_channel(8); + std::thread::spawn(move || { + let stdin = std::io::stdin(); + let mut input = stdin.lock(); + loop { + let mut line = Vec::new(); + let mut terminated = false; + for byte in input.by_ref().bytes().take(65) { + let byte = byte.expect("fixed control input"); + if byte == b'\n' { + terminated = true; + break; + } + line.push(byte); + } + if line.is_empty() && !terminated { + return; + } + assert!(terminated && line.len() <= 64, "fixed control bound"); + let line = String::from_utf8(line).expect("fixed control encoding"); + assert!( + [ + "stop", + "hold-main", + "release-main", + "close-parent", + "finish" + ] + .contains(&line.as_str()), + "fixed control command" + ); + tx.try_send(line).expect("fixed control capacity"); + } + }); + rx + } + + fn qualify(parent: Window, host: Host, gate: Gate) { + let case = CASE.get().expect("case").as_str(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("synthetic runtime"); + let peer = runtime + .block_on(SyntheticPeer::start(SyntheticScenario::Healthy)) + .expect("generated local peer"); + let workspace = + WorkspaceRequest::Managed(Arc::new(gate.observe_open().expect("memory generation"))); + let target = ProposedTarget::new( + peer.origin().to_owned(), + peer.selected_peer(), + case_context(), + "workspace-1".into(), + "sandbox-1".into(), + peer.root_der().to_vec(), + peer.leaf_der().to_vec(), + ) + .expect("synthetic target"); + let commands = commands(); + emit( + "ready", + json!({"parentLabel":"c1-native-parent", "pid":std::process::id(), "context":case_context()}), + ); + let mut hold = (case == "stop-queued").then(|| hold_main(&parent)); + let review = host + .prepare( + &workspace, + target, + ReadKind::RecentLogs, + Retention::SessionOnly, + ) + .expect("memory review"); + let review_deadline = { + let state = host.state.lock().expect("owned Host state"); + let pending = state.pending.as_ref().expect("owned pending review"); + assert_eq!(pending.review().id, review.id); + pending.selection().deadline + }; + let observer = Arc::new(|phase: native_input::NativePhase| { + emit("phase", json!({"phase":phase.code()})) + }); + assert_eq!( + native_input::begin_observed(&host, &review.id, parent.clone(), observer), + HostStatus::Running + ); + let started = Instant::now(); + let mut stop_drain = None; + loop { + if let Ok(command) = commands.try_recv() { + emit("command_received", json!({"command":command})); + match command.as_str() { + "hold-main" if case == "stop-open" && hold.is_none() => { + hold = Some(hold_main(&parent)) + } + "release-main" => hold + .take() + .expect("owned held main") + .release + .send(()) + .expect("release owned main"), + "stop" if ["stop-queued", "stop-open"].contains(&case) && hold.is_some() => { + assert!(stop_drain.is_none(), "one stop drain per case"); + assert!( + timely_stop(review_deadline, Instant::now()), + "native_credential_late_stop" + ); + let (status, drain) = stop_with_drain(&host, &gate); + assert!( + stop_returned_before_expiry(review_deadline, Instant::now()), + "native_credential_stop_missed_deadline" + ); + let retained = !drain.is_quiescent().expect("memory stop drain state"); + stop_drain = Some(drain); + assert_eq!(status, HostStatus::Closing); + assert!(retained, "native callback custody retained"); + // The fixed test-event field denotes retained custody. + // Stop itself does not close unrelated workspace lanes. + emit("stopping", json!({"status":"closing", "admitted":retained})); + } + "close-parent" if case == "parent-close" => { + parent.close().expect("close owned parent") + } + _ => panic!("native_credential_wrong_control"), + } + } + let status = host.status(); + if !matches!(status, HostStatus::Running | HostStatus::Closing) { + assert!( + hold.is_none(), + "native completion cannot precede held main release" + ); + let observation = host.completed_observation(&workspace, &review.id).is_some(); + let calls = peer.calls().expect("synthetic call ledger"); + let counts = [ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::GetSandboxLogs, + ] + .map(|rpc| calls.iter().filter(|call| **call == rpc).count()); + let (label, code) = match status { + HostStatus::Completed => ("completed", None), + HostStatus::Cancelled => ("cancelled", Some("cancelled")), + HostStatus::Error(ClientError::CredentialLeaseExpired) => { + ("error", Some("credential_lease_expired")) + } + _ => panic!("native_credential_unexpected_outcome"), + }; + match case { + "accept-read" => { + assert_eq!(status, HostStatus::Completed); + assert!(observation); + assert_eq!(counts, [1, 1, 1]); + assert_eq!(calls.len(), 3); + } + "expire-open" => { + assert_eq!( + status, + HostStatus::Error(ClientError::CredentialLeaseExpired) + ); + assert!(started.elapsed() >= Duration::from_secs(119)); + assert!(!observation); + assert!(calls.is_empty()); + } + _ => { + assert_eq!(status, HostStatus::Cancelled); + assert!(!observation); + assert!(calls.is_empty()); + } + } + emit( + "result", + json!({"status":label,"code":code,"observation":observation, + "rpcCounts":{"health":counts[0],"policyStatus":counts[1],"logs":counts[2]}, + "authority":"none","execution":"unavailable","outcome":"unknown"}), + ); + runtime + .block_on(peer.shutdown()) + .expect("synthetic shutdown"); + drop(runtime); + assert!(host.cancel_and_check_exit()); + let drain = stop_drain + .take() + .unwrap_or_else(|| gate.request_drain().expect("memory drain")); + assert!(drain.is_quiescent().expect("memory drain state")); + emit("exit", json!({"code":0,"clean":true})); + FINISHED.store(true, Ordering::Release); + parent.app_handle().exit(0); + return; + } + assert!( + started.elapsed() <= Duration::from_secs(185), + "native_credential_case_timeout" + ); + std::thread::sleep(Duration::from_millis(10)); + } + } +} diff --git a/apps/desktop/src/native_encrypted_case_plan.rs b/apps/desktop/src/native_encrypted_case_plan.rs new file mode 100644 index 0000000..18fd010 --- /dev/null +++ b/apps/desktop/src/native_encrypted_case_plan.rs @@ -0,0 +1,647 @@ +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +const MAX_BYTES: usize = 16_384; +const MAX_ROOTS: usize = 32; +const MAX_CASES: usize = 64; +const SCHEMA_VERSION: &str = "rangoon.e1c5c.case-plan.v1"; + +pub(crate) const BYTES: &[u8] = include_bytes!("../native-encrypted-qualification/cases.v1.json"); + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(crate) struct CasePlan { + schema_version: String, + pub roots: Vec, + pub cases: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Case { + pub name: String, + pub root: String, + pub prerequisite: Prerequisite, + pub seed: Seed, + pub expectation: Expectation, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Seed { + None, + LegacyEmpty, + LegacyRich, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub(crate) enum Prerequisite { + Initial {}, + Completed { case: String }, + Running { case: String }, + AllStopped {}, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Expectation { + ColdCancel, + ColdRelaunch, + Authoring, + Relaunch, + Export, + LoseKey, + MissingKey, + BusyOwner, + InterruptedSetup, + InterruptedRelaunch, + InterruptedProvisioning, + AnchorFailure, + CleanupFailure, + WindowFailure, + LegacyCopy, + LegacyVerify, + LegacyRelaunch, + LegacyVerifyCancel, + LegacyReviewCancel, + LegacyReviewRelaunch, + LegacyCopyCancel, + CrashEmptyTarget, + CrashMatchingTarget, + CrashReopened, + RecoveryInspectCancel, + RecoveryInitializeEmptyCancel, + RecoveryInitializeEmptyRestore, + RecoveryRecordCancel, + RecoverySelectionCancel, + RecoveryRestore, + RecoveryRecordCopied, + RecoveryCompleteSelection, + Cleanup, +} + +impl Expectation { + pub(crate) fn adoption_checkpoint(self) -> Option<(&'static str, &'static str)> { + match self { + Self::CrashEmptyTarget => Some(("destination", "after_confirm")), + Self::CrashMatchingTarget => Some(("destination", "after_restore")), + Self::CrashReopened => Some(("verification", "before_selection")), + _ => None, + } + } +} + +impl CasePlan { + pub(crate) fn case(&self, name: &str) -> Option<&Case> { + self.cases.iter().find(|case| case.name == name) + } + + pub(crate) fn seed_for_root(&self, root: &str) -> Option { + self.cases + .iter() + .find(|case| { + case.root == root && matches!(case.prerequisite, Prerequisite::Initial { .. }) + }) + .map(|case| case.seed) + } +} + +pub(crate) fn embedded() -> Result { + parse(BYTES) +} + +pub(crate) fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(()); + } + let plan = serde_json::from_slice::(bytes).map_err(|_| ())?; + if plan.schema_version != SCHEMA_VERSION + || !(1..=MAX_ROOTS).contains(&plan.roots.len()) + || !(1..=MAX_CASES).contains(&plan.cases.len()) + { + return Err(()); + } + validate(&plan)?; + Ok(plan) +} + +fn validate(plan: &CasePlan) -> Result<(), ()> { + let mut roots = BTreeSet::new(); + for root in &plan.roots { + valid_id(root)?; + if !roots.insert(root.as_str()) { + return Err(()); + } + } + + let mut names = BTreeSet::new(); + let mut initial_roots = BTreeSet::new(); + for (index, case) in plan.cases.iter().enumerate() { + valid_id(&case.name)?; + valid_id(&case.root)?; + if !roots.contains(case.root.as_str()) || !names.insert(case.name.as_str()) { + return Err(()); + } + + match &case.prerequisite { + Prerequisite::Initial { .. } => { + if !initial_roots.insert(case.root.as_str()) { + return Err(()); + } + } + Prerequisite::AllStopped { .. } => { + if case.seed != Seed::None { + return Err(()); + } + } + Prerequisite::Completed { case: required } + | Prerequisite::Running { case: required } => { + valid_id(required)?; + if case.seed != Seed::None { + return Err(()); + } + let Some(previous) = plan.cases[..index] + .iter() + .find(|previous| previous.name == *required) + else { + return Err(()); + }; + if previous.root != case.root { + return Err(()); + } + } + } + } + + if initial_roots.len() != roots.len() || !roots.iter().all(|root| initial_roots.contains(root)) + { + return Err(()); + } + Ok(()) +} + +fn valid_id(value: &str) -> Result<(), ()> { + let bytes = value.as_bytes(); + if !(1..=48).contains(&bytes.len()) + || !bytes[0].is_ascii_lowercase() + || bytes.last() == Some(&b'-') + || bytes.windows(2).any(|pair| pair == b"--") + || bytes + .iter() + .any(|byte| !byte.is_ascii_lowercase() && !byte.is_ascii_digit() && *byte != b'-') + { + return Err(()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use sha2::{Digest, Sha256}; + + const VERSION: &str = "rangoon.e1c5c.case-plan.v1"; + + fn plan(roots: &str, cases: &str) -> String { + format!(r#"{{"schemaVersion":"{VERSION}","roots":{roots},"cases":{cases}}}"#) + } + + fn case(name: &str, root: &str, prerequisite: &str, seed: &str) -> String { + format!( + r#"{{"name":"{name}","root":"{root}","prerequisite":{prerequisite},"seed":"{seed}","expectation":"cold_cancel"}}"# + ) + } + + fn valid_one_case() -> String { + plan( + "[\"root\"]", + &format!( + "[{}]", + case("first", "root", r#"{"kind":"initial"}"#, "none") + ), + ) + } + + #[test] + fn embedded_profile_matches_full_serialized_projection() { + let parsed = embedded().expect("frozen profile parses"); + let frozen = serde_json::from_slice::(BYTES).expect("frozen JSON"); + let projection = serde_json::to_value(&parsed).expect("case plan serializes"); + + assert_eq!(projection, frozen); + assert_eq!(parsed.roots.len(), 14); + assert_eq!(parsed.cases.len(), 46); + assert_eq!( + parsed.case("legacy-rich-verify").map(|case| case.seed), + Some(Seed::None) + ); + assert_eq!( + parsed.seed_for_root("legacy-empty"), + Some(Seed::LegacyEmpty) + ); + assert_eq!( + parsed.seed_for_root("legacy-rich-provisioning"), + Some(Seed::LegacyRich) + ); + assert_eq!(parsed.seed_for_root("missing"), None); + } + + #[test] + fn retains_original_capacity_beyond_embedded_profile_and_refuses_excess() { + let mut roots: Vec<_> = (0..32).map(|index| format!("root-{index}")).collect(); + let initial: Vec<_> = (0..32) + .map(|index| { + case( + &format!("initial-{index}"), + &roots[index], + r#"{"kind":"initial"}"#, + "none", + ) + }) + .collect(); + let mut cases = initial.clone(); + for index in 32..64 { + cases.push(case( + &format!("follow-{index}"), + "root-0", + r#"{"kind":"completed","case":"initial-0"}"#, + "none", + )); + } + let capacity = plan( + &serde_json::to_string(&roots).unwrap(), + &format!("[{}]", cases.join(",")), + ); + assert!(capacity.len() <= MAX_BYTES); + assert!(parse(capacity.as_bytes()).is_ok()); + cases.push(case( + "excess-case", + "root-0", + r#"{"kind":"completed","case":"initial-0"}"#, + "none", + )); + assert!( + parse( + plan( + &serde_json::to_string(&roots).unwrap(), + &format!("[{}]", cases.join(",")) + ) + .as_bytes() + ) + .is_err() + ); + roots.push("excess-root".into()); + let mut cases = initial; + cases.push(case( + "excess-initial", + "excess-root", + r#"{"kind":"initial"}"#, + "none", + )); + assert!( + parse( + plan( + &serde_json::to_string(&roots).unwrap(), + &format!("[{}]", cases.join(",")) + ) + .as_bytes() + ) + .is_err() + ); + } + + #[test] + fn preserves_the_prior_forty_cases_and_adds_the_reviewed_provisioning_chain() { + let parsed = embedded().expect("frozen profile parses"); + let prior: Vec<_> = parsed + .cases + .iter() + .filter(|case| case.root != "legacy-rich-provisioning") + .collect(); + assert_eq!(prior.len(), 40); + assert_eq!( + Sha256::digest(serde_json::to_vec(&prior).unwrap()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(), + "16dc0ab838334cecaba0815a6c270f0066bfa8c2f39de77eea4e51a3d5bfad5b" + ); + + for (name, prerequisite, seed, expectation) in [ + ( + "legacy-rich-provisioning-crash", + Prerequisite::Initial {}, + Seed::LegacyRich, + Expectation::InterruptedProvisioning, + ), + ( + "legacy-rich-provisioning-inspect-cancel", + Prerequisite::Completed { + case: "legacy-rich-provisioning-crash".into(), + }, + Seed::None, + Expectation::RecoveryInspectCancel, + ), + ( + "legacy-rich-provisioning-initialize-cancel", + Prerequisite::Completed { + case: "legacy-rich-provisioning-inspect-cancel".into(), + }, + Seed::None, + Expectation::RecoveryInitializeEmptyCancel, + ), + ( + "legacy-rich-provisioning-resume", + Prerequisite::Completed { + case: "legacy-rich-provisioning-initialize-cancel".into(), + }, + Seed::None, + Expectation::RecoveryInitializeEmptyRestore, + ), + ( + "legacy-rich-provisioning-verify", + Prerequisite::Completed { + case: "legacy-rich-provisioning-resume".into(), + }, + Seed::None, + Expectation::LegacyVerify, + ), + ( + "legacy-rich-provisioning-relaunch", + Prerequisite::Completed { + case: "legacy-rich-provisioning-verify".into(), + }, + Seed::None, + Expectation::LegacyRelaunch, + ), + ] { + let case = parsed.case(name).unwrap(); + assert_eq!(case.root, "legacy-rich-provisioning"); + assert_eq!(case.prerequisite, prerequisite); + assert_eq!(case.seed, seed); + assert_eq!(case.expectation, expectation); + } + } + + #[test] + fn maps_only_closed_crash_expectations_to_adoption_checkpoints() { + assert_eq!( + Expectation::CrashEmptyTarget.adoption_checkpoint(), + Some(("destination", "after_confirm")) + ); + assert_eq!( + Expectation::CrashMatchingTarget.adoption_checkpoint(), + Some(("destination", "after_restore")) + ); + assert_eq!( + Expectation::CrashReopened.adoption_checkpoint(), + Some(("verification", "before_selection")) + ); + + for expectation in [ + Expectation::ColdCancel, + Expectation::ColdRelaunch, + Expectation::Authoring, + Expectation::Relaunch, + Expectation::Export, + Expectation::LoseKey, + Expectation::MissingKey, + Expectation::BusyOwner, + Expectation::InterruptedSetup, + Expectation::InterruptedRelaunch, + Expectation::InterruptedProvisioning, + Expectation::AnchorFailure, + Expectation::CleanupFailure, + Expectation::WindowFailure, + Expectation::LegacyCopy, + Expectation::LegacyVerify, + Expectation::LegacyRelaunch, + Expectation::LegacyVerifyCancel, + Expectation::LegacyReviewCancel, + Expectation::LegacyReviewRelaunch, + Expectation::LegacyCopyCancel, + Expectation::RecoveryInspectCancel, + Expectation::RecoveryInitializeEmptyCancel, + Expectation::RecoveryInitializeEmptyRestore, + Expectation::RecoveryRecordCancel, + Expectation::RecoverySelectionCancel, + Expectation::RecoveryRestore, + Expectation::RecoveryRecordCopied, + Expectation::RecoveryCompleteSelection, + Expectation::Cleanup, + ] { + assert_eq!(expectation.adoption_checkpoint(), None, "{expectation:?}"); + } + } + + #[test] + fn rejects_versions_trailing_bytes_and_oversize_input() { + assert!( + parse( + valid_one_case() + .replace(VERSION, "rangoon.e1c5c.case-plan.v2") + .as_bytes() + ) + .is_err() + ); + assert!(parse(format!("{} x", valid_one_case()).as_bytes()).is_err()); + assert!(parse(&vec![b' '; MAX_BYTES + 1]).is_err()); + } + + #[test] + fn rejects_bad_identifiers() { + for value in ["A", "a-", "a--b", "a_b", "a b", &"a".repeat(49)] { + let document = plan( + &format!("[\"{value}\"]"), + &format!( + "[{}]", + case("first", value, r#"{"kind":"initial"}"#, "none") + ), + ); + assert!(parse(document.as_bytes()).is_err(), "{value}"); + } + } + + #[test] + fn rejects_root_and_case_count_limits() { + assert!(parse(plan("[]", "[]").as_bytes()).is_err()); + let roots = (0..33) + .map(|index| format!("\"r{index}\"")) + .collect::>() + .join(","); + assert!(parse(plan(&format!("[{roots}]"), "[]").as_bytes()).is_err()); + + let mut cases = Vec::new(); + for index in 0..65 { + let prerequisite = if index == 0 { + r#"{"kind":"initial"}"#.to_owned() + } else { + format!(r#"{{"kind":"completed","case":"c{}"}}"#, index - 1) + }; + cases.push(case(&format!("c{index}"), "root", &prerequisite, "none")); + } + assert!(parse(plan("[\"root\"]", &format!("[{}]", cases.join(","))).as_bytes()).is_err()); + } + + #[test] + fn rejects_duplicate_json_keys_roots_and_cases() { + assert!(parse( + format!( + r#"{{"schemaVersion":"{VERSION}","schemaVersion":"{VERSION}","roots":["root"],"cases":[{}]}}"#, + case("first", "root", r#"{"kind":"initial"}"#, "none") + ) + .as_bytes() + ) + .is_err()); + assert!(parse(plan("[\"root\",\"root\"]", "[]").as_bytes()).is_err()); + let cases = format!( + "[{},{}]", + case("first", "root", r#"{"kind":"initial"}"#, "none"), + case("first", "root", r#"{"kind":"all_stopped"}"#, "none") + ); + assert!(parse(plan("[\"root\"]", &cases).as_bytes()).is_err()); + + assert!(parse( + plan( + "[\"root\"]", + r#"[{"name":"first","root":"root","prerequisite":{"kind":"initial","kind":"initial"},"seed":"none","expectation":"cold_cancel"}]"#, + ) + .as_bytes() + ) + .is_err()); + let repeated_case = format!( + "[{},{}]", + case("first", "root", r#"{"kind":"initial"}"#, "none"), + r#"{"name":"second","root":"root","prerequisite":{"kind":"completed","case":"first","case":"first"},"seed":"none","expectation":"cold_cancel"}"#, + ); + assert!(parse(plan("[\"root\"]", &repeated_case).as_bytes()).is_err()); + assert!(parse( + format!( + r#"{{"schemaVersion":"{VERSION}","schema\u0056ersion":"{VERSION}","roots":["root"],"cases":[{}]}}"#, + case("first", "root", r#"{"kind":"initial"}"#, "none") + ) + .as_bytes() + ) + .is_err()); + } + + #[test] + fn rejects_unknown_missing_and_wrong_typed_fields() { + assert!(parse( + plan( + "[\"root\"]", + r#"[{"name":"first","root":"root","prerequisite":{"kind":"initial"},"seed":"none","expectation":"cold_cancel","extra":true}]"#, + ) + .as_bytes() + ) + .is_err()); + assert!(parse( + plan( + "[\"root\"]", + r#"[{"name":"first","root":"root","prerequisite":{"kind":"initial"},"seed":"none"}]"#, + ) + .as_bytes() + ) + .is_err()); + assert!(parse( + plan( + "[\"root\"]", + r#"[{"name":false,"root":"root","prerequisite":{"kind":"initial"},"seed":"none","expectation":"cold_cancel"}]"#, + ) + .as_bytes() + ) + .is_err()); + } + + #[test] + fn rejects_bad_prerequisite_shapes_and_seed_misuse() { + assert!(parse( + plan( + "[\"root\"]", + r#"[{"name":"first","root":"root","prerequisite":{"kind":"initial","case":"nope"},"seed":"none","expectation":"cold_cancel"}]"#, + ) + .as_bytes() + ) + .is_err()); + assert!( + parse( + plan( + "[\"root\"]", + &format!( + "[{},{}]", + case("first", "root", r#"{"kind":"initial"}"#, "none"), + case( + "later", + "root", + r#"{"kind":"completed","case":"first"}"#, + "legacy_rich" + ) + ), + ) + .as_bytes() + ) + .is_err() + ); + } + + #[test] + fn rejects_unreferenced_roots_forward_refs_cycles_and_cross_root_refs() { + assert!( + parse( + plan( + "[\"root\",\"unused\"]", + &format!( + "[{}]", + case("first", "root", r#"{"kind":"initial"}"#, "none") + ) + ) + .as_bytes() + ) + .is_err() + ); + + let forward = format!( + "[{},{}]", + case( + "first", + "root", + r#"{"kind":"completed","case":"later"}"#, + "none" + ), + case("later", "root", r#"{"kind":"initial"}"#, "none") + ); + assert!(parse(plan("[\"root\"]", &forward).as_bytes()).is_err()); + + let cycle = format!( + "[{},{}]", + case( + "first", + "root", + r#"{"kind":"completed","case":"second"}"#, + "none" + ), + case( + "second", + "root", + r#"{"kind":"completed","case":"first"}"#, + "none" + ) + ); + assert!(parse(plan("[\"root\"]", &cycle).as_bytes()).is_err()); + + let cross_root = format!( + "[{},{},{}]", + case("left", "left", r#"{"kind":"initial"}"#, "none"), + case("right", "right", r#"{"kind":"initial"}"#, "none"), + case( + "joined", + "left", + r#"{"kind":"completed","case":"right"}"#, + "none" + ) + ); + assert!(parse(plan("[\"left\",\"right\"]", &cross_root).as_bytes()).is_err()); + } +} diff --git a/apps/desktop/src/native_encrypted_qualification.rs b/apps/desktop/src/native_encrypted_qualification.rs new file mode 100644 index 0000000..c45fdf0 --- /dev/null +++ b/apps/desktop/src/native_encrypted_qualification.rs @@ -0,0 +1,1143 @@ +//! Explicit E1c-4 target. No entry, fault selector, or key deletion in product builds. +#[cfg(not(target_os = "macos"))] +pub(crate) fn run() { + eprintln!("e1c4: macOS qualification only"); + std::process::exit(78); +} +#[cfg(not(target_os = "macos"))] +pub(crate) fn case_is(_: &str) -> bool { + false +} +#[cfg(not(target_os = "macos"))] +pub(crate) fn before_ready(_: &tauri::AppHandle) {} +#[cfg(not(target_os = "macos"))] +pub(crate) fn after_ready(_: &tauri::AppHandle, _: bool, _: bool) {} +#[cfg(not(target_os = "macos"))] +pub(crate) fn exited(_: &tauri::AppHandle) {} +#[cfg(target_os = "macos")] +pub(crate) use macos::{ + adoption_checkpoint, after_ready, before_ready, case_is, consent_observed, exited, run, + startup_observed, startup_vault, +}; + +#[cfg(target_os = "macos")] +mod macos { + use crate::{SourceAccess, WorkspaceClose}; + use crate::{native_encrypted_case_plan as cases, native_encrypted_seeds as seeds}; + use cases::{CasePlan, Expectation, Prerequisite, Seed}; + use keyring_core::api::CredentialStoreApi; + use rangoon_desktop::{ + workspace_keys::{Error, OsSlot, Store, WorkspaceId}, + workspace_session::Vault, + }; + use serde::Deserialize; + use serde_json::{Value, json}; + use sha2::{Digest, Sha256}; + use std::{ + collections::BTreeMap, + fs::{self, File, OpenOptions}, + io::{BufRead, Read, Write}, + os::unix::fs::{MetadataExt, OpenOptionsExt}, + path::{Path, PathBuf}, + sync::{ + Arc, Condvar, Mutex, OnceLock, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, + time::{Duration, Instant}, + }; + use tauri::{AppHandle, Manager}; + use zeroize::Zeroizing; + + const IDENTIFIER: &str = "si.rangoon.encrypted-qualification"; + const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' asset: http://asset.localhost; font-src 'self'; connect-src ipc: http://ipc.localhost; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'"; + const PERMISSIONS: &[&str] = &[ + "allow-workspace-startup-status", + "allow-workspace-startup-action", + "allow-workspace-startup-quit", + "allow-get-workspace-close-state", + "allow-get-workspace-control-state", + "allow-get-workspace-protection-state", + "allow-prepare-workspace-control", + "allow-confirm-workspace-control", + "allow-cancel-workspace-control", + "allow-get-workspace-request-state", + "allow-begin-workspace-close", + "allow-acknowledge-workspace-purge", + "allow-select-and-analyze", + "allow-list-snapshots", + "allow-save-analysis", + "allow-open-snapshot", + "allow-read-composition-source", + "allow-clear-analysis", + "allow-get-engine-status", + "allow-list-capabilities", + "allow-open-capability", + "allow-create-capability", + "allow-revise-capability", + "allow-review-capability", + "allow-compile-capability", + "allow-export-instruction-bundle", + "allow-inspect-instruction-bundle", + "allow-get-workspace-data", + "allow-export-workspace-backup", + "allow-create-workspace-recovery-key", + "allow-export-encrypted-workspace-backup", + "allow-prepare-encrypted-workspace-restore", + "allow-prepare-workspace-restore", + "allow-restore-workspace-backup", + "allow-preview-composition", + "allow-commit-composition", + "allow-list-workflows", + "allow-open-workflow", + "allow-begin-workflow-draft", + "allow-inspect-workflow-save", + "allow-commit-workflow-save", + "allow-clear-workflow-draft", + ]; + static RUN: OnceLock = OnceLock::new(); + static ORIGINAL: OnceLock = OnceLock::new(); + static EVENTS: Mutex = Mutex::new(0); + static EXITED: AtomicBool = AtomicBool::new(false); + static OPENS: AtomicU64 = AtomicU64::new(0); + static READS: AtomicU64 = AtomicU64::new(0); + static WRITES: AtomicU64 = AtomicU64::new(0); + static ADOPTION_HELD: AtomicBool = AtomicBool::new(false); + + // The barrier delays one genuine read before OS custody. No keys or results + // are retained here, and ordinary builds do not include this module. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum ReadPhase { + Idle, + Armed, + Holding, + Released, + Finished, + Failed, + } + struct ReadBarrier { + phase: Mutex, + wake: Condvar, + } + impl ReadBarrier { + const fn new() -> Self { + Self { + phase: Mutex::new(ReadPhase::Idle), + wake: Condvar::new(), + } + } + fn arm(&self, observed: impl FnOnce()) -> Result<(), ()> { + let mut phase = self.phase.lock().map_err(|_| ())?; + if *phase != ReadPhase::Idle { + return Err(()); + } + *phase = ReadPhase::Armed; + observed(); + Ok(()) + } + fn release(&self, observed: impl FnOnce()) -> Result<(), ()> { + let mut phase = self.phase.lock().map_err(|_| ())?; + if *phase != ReadPhase::Holding { + return Err(()); + } + observed(); + *phase = ReadPhase::Released; + self.wake.notify_all(); + Ok(()) + } + fn wait(&self, timeout: Duration, held: impl FnOnce()) -> Result { + let mut phase = self.phase.lock().map_err(|_| ())?; + match *phase { + ReadPhase::Idle | ReadPhase::Finished => return Ok(false), + ReadPhase::Armed => *phase = ReadPhase::Holding, + _ => return Err(()), + } + let deadline = Instant::now() + timeout; + held(); + while *phase == ReadPhase::Holding { + let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { + *phase = ReadPhase::Failed; + return Err(()); + }; + let (next, _) = self.wake.wait_timeout(phase, remaining).map_err(|_| ())?; + phase = next; + } + if *phase != ReadPhase::Released || Instant::now() >= deadline { + *phase = ReadPhase::Failed; + return Err(()); + } + *phase = ReadPhase::Finished; + Ok(true) + } + } + static READ_BARRIER: ReadBarrier = ReadBarrier::new(); + + #[test] + fn q3_barrier_requires_hold_release_and_is_one_shot() { + let barrier = Arc::new(ReadBarrier::new()); + assert_eq!( + barrier.wait(Duration::ZERO, || panic!("not armed")), + Ok(false) + ); + assert!(barrier.release(|| {}).is_err()); + barrier.arm(|| {}).unwrap(); + assert!(barrier.arm(|| {}).is_err()); + assert!(barrier.release(|| {}).is_err()); + let (tx, rx) = std::sync::mpsc::channel(); + let worker = barrier.clone(); + let held = std::thread::spawn(move || { + worker.wait(Duration::from_secs(5), || tx.send(()).unwrap()) + }); + rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert!(barrier.wait(Duration::ZERO, || {}).is_err()); + barrier.release(|| {}).unwrap(); + assert_eq!(held.join().unwrap(), Ok(true)); + assert!(barrier.release(|| {}).is_err()); + assert!(barrier.arm(|| {}).is_err()); + assert_eq!( + barrier.wait(Duration::ZERO, || panic!("already used")), + Ok(false) + ); + } + #[test] + fn q3_barrier_timeout_and_poison_never_resume_a_read() { + let barrier = ReadBarrier::new(); + barrier.arm(|| {}).unwrap(); + assert!(barrier.wait(Duration::ZERO, || {}).is_err()); + assert!(barrier.release(|| {}).is_err()); + assert!(barrier.wait(Duration::from_secs(1), || {}).is_err()); + let poisoned = ReadBarrier::new(); + let _ = std::panic::catch_unwind(|| { + let _guard = poisoned.phase.lock().unwrap(); + panic!("synthetic poison"); + }); + assert!(poisoned.arm(|| {}).is_err()); + assert!(poisoned.release(|| {}).is_err()); + assert!(poisoned.wait(Duration::ZERO, || {}).is_err()); + } + + #[derive(Clone, Deserialize)] + #[serde(deny_unknown_fields)] + struct Identity { + dev: u64, + ino: u64, + uid: u32, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Manifest { + schema: String, + nonce: String, + #[serde(rename = "casePlanSha256")] + case_plan_sha256: String, + directory: Identity, + roots: BTreeMap, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Permit { + schema: String, + nonce: String, + case: String, + prior: Option, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct SlotRecord { + schema: String, + nonce: String, + root: String, + workspace_id: String, + } + struct Run { + nonce: String, + case: String, + directory: PathBuf, + manifest: Manifest, + plan: CasePlan, + } + + fn refuse(message: &'static str, code: i32) -> ! { + eprintln!("e1c4: {message}"); + std::process::exit(code); + } + fn emit(event: &'static str, fields: Value) { + let mut seq = EVENTS + .lock() + .unwrap_or_else(|_| refuse("event failure", 70)); + *seq += 1; + let record = json!({"schema":"rangoon.e1c4.event.v1", "seq":*seq, "pid":std::process::id(), "case":RUN.get().map(|r|r.case.as_str()), "event":event, "fields":fields}); + let line = serde_json::to_vec(&record).unwrap_or_else(|_| refuse("event failure", 70)); + if line.len() > 8192 || *seq > 512 { + refuse("event bound", 70); + } + let mut out = std::io::stdout().lock(); + if out + .write_all(&line) + .and_then(|_| out.write_all(b"\n")) + .and_then(|_| out.flush()) + .is_err() + { + refuse("event output unavailable", 70); + } + } + fn hex_nonce(value: &str) -> bool { + value.len() == 32 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + } + fn same_directory(path: &Path, id: &Identity) -> bool { + fs::symlink_metadata(path).is_ok_and(|m| { + m.is_dir() + && !m.file_type().is_symlink() + && m.dev() == id.dev + && m.ino() == id.ino + && m.uid() == id.uid + && m.mode() & 0o777 == 0o700 + }) + } + fn read_record(path: &Path, uid: u32) -> Result { + let before = fs::symlink_metadata(path).map_err(|_| ())?; + if !before.is_file() + || before.file_type().is_symlink() + || before.uid() != uid + || before.mode() & 0o777 != 0o600 + || before.nlink() != 1 + || before.len() > 16384 + { + return Err(()); + } + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .map_err(|_| ())?; + let after = file.metadata().map_err(|_| ())?; + if before.dev() != after.dev() || before.ino() != after.ino() { + return Err(()); + } + let mut bytes = Vec::new(); + file.take(16385).read_to_end(&mut bytes).map_err(|_| ())?; + if bytes.len() > 16384 { + return Err(()); + } + serde_json::from_slice(&bytes).map_err(|_| ()) + } + fn write_new(path: &Path, value: &Value) -> Result<(), ()> { + let bytes = serde_json::to_vec(value).map_err(|_| ())?; + if bytes.len() > 16384 { + return Err(()); + } + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .map_err(|_| ())?; + file.write_all(&bytes) + .and_then(|_| file.sync_all()) + .map_err(|_| ())?; + File::open(path.parent().ok_or(())?) + .and_then(|d| d.sync_all()) + .map_err(|_| ()) + } + fn plan_digest() -> String { + Sha256::digest(cases::BYTES) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } + impl Run { + fn validate(&self) -> Result<(), ()> { + if !same_directory(&self.directory, &self.manifest.directory) { + return Err(()); + } + for (name, id) in &self.manifest.roots { + if id.uid != self.manifest.directory.uid + || !same_directory(&self.directory.join(name), id) + { + return Err(()); + } + } + Ok(()) + } + fn root(&self) -> PathBuf { + self.directory.join(self.root_name()) + } + fn case_spec(&self) -> &cases::Case { + self.plan + .case(&self.case) + .unwrap_or_else(|| refuse("case plan mismatch", 64)) + } + fn root_name(&self) -> &str { + &self.case_spec().root + } + fn identifier(&self) -> String { + format!("{IDENTIFIER}.{}", self.nonce) + } + fn registry(&self, root: &str) -> PathBuf { + self.directory.join(format!("slot-{root}.json")) + } + fn slot(&self, root: &str) -> Result { + self.validate()?; + let record: SlotRecord = + read_record(&self.registry(root), self.manifest.directory.uid)?; + if record.schema != "rangoon.e1c4.slot.v1" + || record.nonce != self.nonce + || record.root != root + || WorkspaceId::parse(&record.workspace_id).is_err() + { + return Err(()); + } + Ok(record) + } + } + fn prepare_run(args: &[String]) -> Result { + let plan = cases::embedded()?; + if args.len() != 2 || !hex_nonce(&args[0]) || plan.case(&args[1]).is_none() { + return Err(()); + } + let base = std::env::temp_dir().canonicalize().map_err(|_| ())?; + let directory = base.join(format!("rangoon-e1c4-{}", args[0])); + let meta = fs::symlink_metadata(&directory).map_err(|_| ())?; + if !meta.is_dir() || meta.file_type().is_symlink() || meta.mode() & 0o777 != 0o700 { + return Err(()); + } + let manifest: Manifest = read_record(&directory.join("manifest.json"), meta.uid())?; + if manifest.schema != "rangoon.e1c4.run.v2" + || manifest.nonce != args[0] + || manifest.case_plan_sha256 != plan_digest() + || manifest.roots.len() != plan.roots.len() + || !plan + .roots + .iter() + .all(|name| manifest.roots.contains_key(name)) + { + return Err(()); + } + let run = Run { + nonce: args[0].clone(), + case: args[1].clone(), + directory, + manifest, + plan, + }; + run.validate()?; + let permit: Permit = read_record( + &run.directory.join(format!("permit-{}.json", run.case)), + meta.uid(), + )?; + if permit.schema != "rangoon.e1c4.permit.v1" + || permit.nonce != run.nonce + || permit.case != run.case + { + return Err(()); + } + let expected = match &run.case_spec().prerequisite { + Prerequisite::Initial { .. } => None, + Prerequisite::Completed { case } => Some(case.clone()), + Prerequisite::Running { case } => Some(format!("{case}-running")), + Prerequisite::AllStopped { .. } => Some("children-stopped".to_owned()), + }; + if permit.prior != expected { + return Err(()); + } + if expected.is_none() && fs::read_dir(run.root()).map_err(|_| ())?.next().is_some() { + return Err(()); + } + write_new( + &run.directory.join(format!("claimed-{}.json", run.case)), + &json!({"pid":std::process::id(),"case":run.case}), + )?; + Ok(run) + } + pub(crate) fn case_is(value: &str) -> bool { + RUN.get().is_some_and(|r| r.case == value) + } + + struct CountingVault(crate::workspace_native_bootstrap::OsVault); + pub(crate) fn startup_vault() -> impl Vault + Send { + let run = RUN + .get() + .unwrap_or_else(|| refuse("qualification run unavailable", 64)); + if run.validate().is_err() { + refuse("qualification root changed", 64); + } + CountingVault(crate::workspace_native_bootstrap::OsVault::new( + run.identifier(), + )) + } + struct CountingSlot(OsSlot); + impl Vault for CountingVault { + type Slot = CountingSlot; + fn open(&self, identity: &WorkspaceId) -> Result { + RUN.get() + .ok_or(Error::Unavailable)? + .validate() + .map_err(|_| Error::Unavailable)?; + OPENS.fetch_add(1, Ordering::SeqCst); + self.0.open(identity).map(CountingSlot) + } + } + impl Store for CountingSlot { + fn identity(&self) -> &WorkspaceId { + self.0.identity() + } + fn read(&self) -> Result>>, Error> { + let held = READ_BARRIER + .wait(Duration::from_secs(120), || { + emit("read_barrier_held", json!({"beforeOsRead":true})); + }) + .map_err(|()| { + emit("read_barrier_failed", json!({})); + Error::Unavailable + })?; + READS.fetch_add(1, Ordering::SeqCst); + let result = self.0.read(); + if held { + emit( + "read_barrier_read_returned", + json!({"present":result.as_ref().is_ok_and(|value|value.is_some())}), + ); + } + result + } + fn write(&self, envelope: &[u8]) -> Result<(), Error> { + let run = RUN.get().ok_or(Error::Unavailable)?; + run.validate().map_err(|_| Error::Unavailable)?; + let root = run.root_name(); + // create_key has checked absence. Record the exact native-created + // selector durably before an OS write whose outcome could be uncertain. + write_new( + &run.registry(root), + &json!({"schema":"rangoon.e1c4.slot.v1", "nonce":run.nonce, + "root":root, "workspace_id":self.identity().as_hex()}), + ) + .map_err(|_| Error::Unavailable)?; + WRITES.fetch_add(1, Ordering::SeqCst); + let result = self.0.write(envelope); + emit( + "slot_write", + json!({"workspaceId":self.identity().as_hex(),"succeeded":result.is_ok()}), + ); + let interrupted_copy = + run.case_spec().expectation == Expectation::InterruptedProvisioning; + if result.is_ok() && (case_is("interrupted-setup") || interrupted_copy) { + let mut fields = json!({"afterRealKeyWrite":true}); + if interrupted_copy { + fields["vaultOpens"] = json!(OPENS.load(Ordering::SeqCst)); + fields["vaultReads"] = json!(READS.load(Ordering::SeqCst)); + fields["vaultWrites"] = json!(WRITES.load(Ordering::SeqCst)); + } + emit("provisioning_barrier", fields); + // Only the parent-owned child is terminated. Never return to + // Owner or manufacture a completed setup after this barrier. + let deadline = Instant::now() + Duration::from_secs(120); + while let Some(remaining) = deadline.checked_duration_since(Instant::now()) { + std::thread::park_timeout(remaining); + } + emit("provisioning_barrier_timeout", json!({})); + return Err(Error::WriteUncertain); + } + result + } + } + /// Pause only after the shared adoption core reports the selected durable + /// boundary. Do not reopen its journal/Owner while their locks are held. + pub(crate) fn adoption_checkpoint(stage: &str, boundary: &str) -> Result<(), ()> { + let Some(run) = RUN.get() else { + return Ok(()); + }; + if run.case_spec().expectation.adoption_checkpoint() != Some((stage, boundary)) { + return Ok(()); + } + run.validate()?; + if ADOPTION_HELD.swap(true, Ordering::SeqCst) { + return Err(()); + } + emit( + "adoption_barrier", + json!({"stage":stage,"boundary":boundary, + "vaultOpens":OPENS.load(Ordering::SeqCst), + "vaultReads":READS.load(Ordering::SeqCst), + "vaultWrites":WRITES.load(Ordering::SeqCst)}), + ); + let deadline = Instant::now() + Duration::from_secs(120); + while let Some(remaining) = deadline.checked_duration_since(Instant::now()) { + // Spurious wakeups never continue the interrupted operation. + std::thread::park_timeout(remaining); + } + emit("adoption_barrier_timeout", json!({})); + Err(()) + } + + fn delete_slots(run: &Run) -> Result<(), ()> { + let roots: Vec<&str> = if run.case == "lose-key" { + vec!["authoring"] + } else { + run.plan.roots.iter().map(String::as_str).collect() + }; + for root in roots { + match fs::symlink_metadata(run.registry(root)) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound && run.case == "cleanup" => { + continue; + } + Err(_) => return Err(()), + Ok(_) => {} + } + let slot = run.slot(root).map_err(|()| { + emit( + "slot_registry_refused", + json!({"root":root,"registry":format!("slot-{root}.json")}), + ); + })?; + let service = format!("{}.encrypted-workspace-key.v1", run.identifier()); + let account = format!("workspace-{}", slot.workspace_id); + OPENS.fetch_add(1, Ordering::SeqCst); + emit( + "slot_delete_attempt", + json!({"root":root,"service":service,"account":account,"vaultOpens":OPENS.load(Ordering::SeqCst)}), + ); + let entry = apple_native_keyring_store::keychain::Store::new() + .and_then(|store|store.build(&service, &account, None)) + .map_err(|_| { + emit("slot_cleanup_failed", json!({"root":root,"service":service,"account":account,"operation":"open_exact_entry"})); + })?; + match entry.delete_credential() { + Ok(()) => {} + Err(keyring_core::Error::NoEntry) if run.case == "cleanup" => {} + Err(_) => { + emit( + "slot_cleanup_failed", + json!({"root":root,"service":service,"account":account,"operation":"delete"}), + ); + return Err(()); + } + } + READS.fetch_add(1, Ordering::SeqCst); + emit( + "slot_absence_check", + json!({"root":root,"service":service,"account":account,"vaultReads":READS.load(Ordering::SeqCst)}), + ); + match entry.get_secret() { + Err(keyring_core::Error::NoEntry) => {} + Ok(secret) => { + let _secret = Zeroizing::new(secret); + emit( + "slot_cleanup_failed", + json!({"root":root,"service":service,"account":account,"operation":"confirm_absence"}), + ); + return Err(()); + } + Err(_) => { + emit( + "slot_cleanup_failed", + json!({"root":root,"service":service,"account":account,"operation":"confirm_absence"}), + ); + return Err(()); + } + } + emit( + "slot_absent", + json!({"root":root,"service":service,"account":account}), + ); + } + Ok(()) + } + fn valid_context(config: &Value, assets: bool) -> bool { + let Some(caps) = config + .pointer("/app/security/capabilities") + .and_then(Value::as_array) + else { + return false; + }; + config["identifier"] == IDENTIFIER + && config["bundle"]["active"] == false + && config["app"]["withGlobalTauri"] == true + && config["app"]["windows"] + .as_array() + .is_some_and(Vec::is_empty) + && config["app"]["security"]["csp"] == CSP + && config["build"]["frontendDist"] == "../../../preview" + && [ + "devUrl", + "beforeDevCommand", + "beforeBuildCommand", + "beforeBundleCommand", + ] + .iter() + .all(|k| config["build"].get(k).is_none_or(Value::is_null)) + && config + .get("plugins") + .is_none_or(|p| p.as_object().is_some_and(|o| o.is_empty())) + && caps.len() == 1 + && caps[0]["identifier"] == "e1c4-local-authoring" + && caps[0]["local"] == true + && caps[0]["windows"] == json!(["main"]) + && caps[0] + .get("webviews") + .is_none_or(|v| v.as_array().is_some_and(Vec::is_empty)) + && caps[0].get("remote").is_none_or(Value::is_null) + && caps[0]["permissions"] == json!(PERMISSIONS) + && assets + } + fn check_context(context: &tauri::Context) { + let config = serde_json::to_value(context.config()) + .unwrap_or_else(|_| refuse("context unavailable", 70)); + let assets = context.assets().iter().next().is_some(); + if !valid_context(&config, assets) { + refuse("context isolation failed", 70); + } + for (pointer, bad) in [ + ("/identifier", json!("ai.rangoon.studio.dev")), + ("/app/security/capabilities", json!(["source-analysis"])), + ("/app/security/csp", json!("default-src *")), + ("/app/security/capabilities/0/windows", json!(["*"])), + ( + "/app/security/capabilities/0/permissions", + json!(["allow-send-cloud-model"]), + ), + ("/bundle/active", json!(true)), + ] { + let mut altered = config.clone(); + *altered + .pointer_mut(pointer) + .unwrap_or_else(|| refuse("context test unavailable", 70)) = bad; + if valid_context(&altered, assets) { + refuse("context negative check failed", 70); + } + } + if valid_context(&config, false) { + refuse("assets negative check failed", 70); + } + emit( + "context_validated", + json!({"identifier":IDENTIFIER,"permissions":PERMISSIONS.len(),"negativeChecks":7,"embeddedWorkbench":true}), + ); + } + pub(crate) fn run() { + std::panic::set_hook(Box::new(|_| eprintln!("e1c4: qualification panic"))); + let args: Vec<_> = std::env::args().skip(1).take(4).collect(); + let run = + prepare_run(&args).unwrap_or_else(|_| refuse("invalid run, phase, or directory", 64)); + RUN.set(run).unwrap_or_else(|_| refuse("duplicate run", 70)); + let run = RUN.get().unwrap_or_else(|| refuse("run unavailable", 70)); + emit( + "started", + json!({"nonce":run.nonce,"root":run.root_name(),"casePlanSha256":plan_digest(),"credentialService":format!("{}.encrypted-workspace-key.v1",run.identifier())}), + ); + if case_is("lose-key") || case_is("cleanup") { + if delete_slots(run).is_err() { + refuse("exact test slot cleanup failed; inspect registry", 74); + } + emit("cleanup_complete", json!({})); + return; + } + prepare_original(run) + .unwrap_or_else(|_| refuse("disposable original unavailable or changed", 74)); + let context = tauri::generate_context!("native-encrypted-qualification/tauri.conf.json"); + check_context(&context); + let app = crate::desktop_builder().setup(|app| { + let Some(run) = RUN.get() else { refuse("qualification run unavailable",64); }; + if run.validate().is_err() { refuse("qualification root changed",64); } + crate::workspace_native_bootstrap::install_startup_state(app.handle(), run.root(), startup_vault()) + .unwrap_or_else(|_| refuse("qualification services unavailable", 70)); + emit("os_directories",json!({"appData":app.path().app_data_dir().ok(),"appLocalData":app.path().app_local_data_dir().ok(),"appCache":app.path().app_cache_dir().ok()})); + Ok(()) + }).build(context); + match app { + Ok(app) => crate::run_workbench(app), + Err(_) => refuse("native build or Owner unavailable", 4), + } + } + pub(crate) fn before_ready(app: &AppHandle) { + if case_is("anchor-failure") + && app + .state::() + .set_failure_notifier(Arc::new(|| {})) + .is_err() + { + refuse("fault setup failed", 70); + } + } + fn observation(app: &AppHandle) -> Value { + let close = app.state::(); + let source = app.state::(); + let request = serde_json::to_value(source.request_view()).unwrap_or(Value::Null); + json!({"close":close.inspect(|drained|crate::workspace_close::native_cleanup(app,drained)), + "protection":crate::workspace_close::setup::ProtectionResponse::observe(&close), + "requestState":request["state"],"storage":request["storage"],"clientPresent":request["clientId"].is_string(), + "failedClosed":source.failure_latched(),"clean":close.clean_native_completion(), + "vaultOpens":OPENS.load(Ordering::SeqCst),"vaultReads":READS.load(Ordering::SeqCst),"vaultWrites":WRITES.load(Ordering::SeqCst)}) + } + pub(crate) fn startup_observed(app: &AppHandle, view: &crate::workspace_startup_host::View) { + let view = serde_json::to_value(view) + .unwrap_or_else(|_| refuse("startup observation unavailable", 70)); + let state = view + .get("state") + .and_then(Value::as_str) + .unwrap_or_else(|| refuse("startup observation invalid", 70)); + emit( + "startup", + json!({"state":state,"copyPhase":view["copyPhase"],"retainedOriginal":view["retainedOriginal"],"observation":observation(app)}), + ); + } + + fn prepare_original(run: &Run) -> Result<(), ()> { + let kind = run.plan.seed_for_root(run.root_name()).ok_or(())?; + if kind == Seed::None { + return Ok(()); + } + run.validate()?; + let path = run + .directory + .join(format!("original-{}.json", run.root_name())); + let original = if matches!(run.case_spec().prerequisite, Prerequisite::Initial { .. }) { + let original = seeds::seed(&run.root(), kind)?; + write_new(&path, &serde_json::to_value(&original).map_err(|_| ())?)?; + original + } else { + let baseline: seeds::Original = read_record(&path, run.manifest.directory.uid)?; + if seeds::observe(&run.root())? != baseline { + return Err(()); + } + baseline + }; + emit( + "original_before", + serde_json::to_value(&original).map_err(|_| ())?, + ); + ORIGINAL.set(original).map_err(|_| ()) + } + + pub(crate) fn consent_observed( + purpose: &'static str, + consent: crate::workspace_close::setup::Consent, + ) { + use crate::workspace_close::setup::Consent; + if ![ + "create_empty", + "unlock", + "copy_existing", + "verify_copy", + "recovery_inspect", + "recovery_initialize_empty", + "recovery_reconcile", + "recovery_unlock", + "recovery_restore", + "recovery_record_copied", + "recovery_complete_selection", + ] + .contains(&purpose) + { + refuse("invalid consent observation", 70); + } + let outcome = match consent { + Consent::Approved => "approved", + Consent::Cancelled => "cancelled", + Consent::Unavailable => "unavailable", + }; + emit("consent", json!({"purpose":purpose,"outcome":outcome})); + } + // Fixed test-only WebView script. The parent cannot supply JavaScript or + // payloads. Only finite classifications cross the evaluation callback. + const HEADER_PROBE: &str = r#"(() => { + globalThis.__rangoonQ3HeaderProbe = 'pending'; + const client = __CLIENT_JSON__; + const options = client === null ? undefined : {headers: {'x-rangoon-workspace-client': client}}; + Promise.resolve().then(() => window.__TAURI__.core.invoke('list_snapshots', {}, options)).then(result => { + const keys = value => value && typeof value === 'object' && !Array.isArray(value) + ? Object.keys(value).sort().join(',') : ''; + const refused = keys(result) === 'error,outcome' && result.outcome === 'failed' + && keys(result.error) === 'code,message' && result.error.code === 'workspace_unavailable' + && typeof result.error.message === 'string'; + const listed = keys(result) === 'outcome,snapshots' && result.outcome === 'listed' + && Array.isArray(result.snapshots) && result.snapshots.length > 0; + globalThis.__rangoonQ3HeaderProbe = refused ? 'refused' : listed ? 'listed' : 'failed'; + }).catch(() => { globalThis.__rangoonQ3HeaderProbe = 'failed'; }); + })()"#; + const HEADER_POLL: &str = "globalThis.__rangoonQ3HeaderProbe"; + + #[derive(Debug, PartialEq, Eq)] + enum HeaderReply { + Pending, + Refused, + Listed, + } + fn header_reply(raw: &str) -> Result { + if raw.len() > 32 { + return Err(()); + } + match serde_json::from_str::(raw) + .map_err(|_| ())? + .as_str() + { + "pending" => Ok(HeaderReply::Pending), + "refused" => Ok(HeaderReply::Refused), + "listed" => Ok(HeaderReply::Listed), + _ => Err(()), + } + } + fn open_client(app: &AppHandle) -> Result { + let state = observation(app); + if state["close"]["state"] != "open" || state["failedClosed"] != false { + return Err(()); + } + let view = + serde_json::to_value(app.state::().request_view()).map_err(|_| ())?; + let id = view["clientId"].as_str().ok_or(())?; + if view["state"] != "open" + || view["storage"] != "managed_encrypted" + || id.len() != 64 + || !id + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(()); + } + Ok(id.to_owned()) + } + fn vault_counts() -> [u64; 3] { + [ + OPENS.load(Ordering::SeqCst), + READS.load(Ordering::SeqCst), + WRITES.load(Ordering::SeqCst), + ] + } + fn invoke_header_probe(app: &AppHandle, client: Option<&str>) -> Result { + let window = app.get_webview_window("main").ok_or(())?; + let script = HEADER_PROBE.replace( + "__CLIENT_JSON__", + &serde_json::to_string(&client).map_err(|_| ())?, + ); + window.eval(script).map_err(|_| ())?; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let (tx, rx) = std::sync::mpsc::sync_channel(1); + window + .eval_with_callback(HEADER_POLL, move |raw| { + let _ = tx.try_send(header_reply(&raw)); + }) + .map_err(|_| ())?; + let remaining = deadline.checked_duration_since(Instant::now()).ok_or(())?; + match rx.recv_timeout(remaining).map_err(|_| ())?? { + HeaderReply::Pending => std::thread::sleep(Duration::from_millis(30)), + result => { + window + .eval("delete globalThis.__rangoonQ3HeaderProbe") + .map_err(|_| ())?; + return Ok(result); + } + } + } + } + fn check_headers(app: &AppHandle, old: &str) -> Result<(), ()> { + let fresh = open_client(app)?; + if old == fresh { + return Err(()); + } + emit("header_probe_started", json!({"differentClient":true})); + for (name, header, expected) in [ + ("header_probe_missing", None, HeaderReply::Refused), + ("header_probe_stale", Some(old), HeaderReply::Refused), + ( + "header_probe_current", + Some(fresh.as_str()), + HeaderReply::Listed, + ), + ] { + let before = vault_counts(); + if invoke_header_probe(app, header)? != expected || open_client(app)? != fresh { + return Err(()); + } + let after = vault_counts(); + let valid = if expected == HeaderReply::Listed { + after[1] > before[1] && after[2] == before[2] + } else { + after == before + }; + if !valid { + return Err(()); + } + emit( + name, + json!({"matched":true,"vaultReadDelta":after[1]-before[1],"vaultWriteDelta":after[2]-before[2]}), + ); + } + Ok(()) + } + pub(crate) fn after_ready(app: &AppHandle, anchor: bool, presented: bool) { + let run = RUN + .get() + .unwrap_or_else(|| refuse("qualification run unavailable", 64)); + if let Some(window) = app.get_webview_window("main") { + window + .set_title(&format!("Rangoon Recovery QA {}", &run.nonce[..8])) + .unwrap_or_else(|_| refuse("qualification title unavailable", 70)); + } + emit( + "ready", + json!({"anchor":anchor,"windowPresented":presented,"state":observation(app)}), + ); + let watching = app.clone(); + std::thread::spawn(move || { + let mut previous = Value::Null; + while !EXITED.load(Ordering::SeqCst) { + let current = observation(&watching); + if current != previous { + emit("state", current.clone()); + previous = current; + } + std::thread::sleep(Duration::from_millis(100)); + } + }); + let controlling = app.clone(); + std::thread::spawn(move || { + let mut input = std::io::stdin().lock(); + let mut captured_client: Option = None; + let mut header_started = false; + let mut recovery_snapshot_taken = false; + loop { + let mut line = String::new(); + let read = (&mut input).take(65).read_line(&mut line); + match read { + Ok(0) => { + controlling.exit(4); + break; + } + Ok(_) if line == "observe\n" => emit("observed", observation(&controlling)), + Ok(_) + if line == "recovery-snapshot\n" + && (case_is("authoring") || case_is("relaunch")) + && !recovery_snapshot_taken => + { + recovery_snapshot_taken = true; + match controlling + .state::() + .qualification_recovery_snapshot() + { + Ok((backup_id, byte_length)) => emit( + "recovery_snapshot", + json!({"backupId":backup_id,"byteLength":byte_length}), + ), + Err(_) => { + emit("recovery_snapshot_failed", json!({})); + controlling.exit(4); + break; + } + } + } + Ok(_) + if line == "capture-client\n" + && case_is("authoring") + && !header_started => + { + header_started = true; + match open_client(&controlling) { + Ok(client) => { + captured_client = Some(client); + emit("header_client_captured", json!({"open":true})); + } + Err(()) => { + emit("header_probe_failed", json!({})); + controlling.exit(4); + break; + } + } + } + Ok(_) if line == "check-headers\n" && case_is("authoring") => { + let result = captured_client + .take() + .ok_or(()) + .and_then(|old| check_headers(&controlling, &old)); + if result.is_err() { + emit("header_probe_failed", json!({})); + controlling.exit(4); + break; + } + } + Ok(_) if line == "arm-read\n" && case_is("authoring") => { + let state = observation(&controlling); + if state["close"]["state"] != "open" + || state["clientPresent"] != true + || state["failedClosed"] != false + || READ_BARRIER + .arm(|| emit("read_barrier_armed", state)) + .is_err() + { + emit("control_refused", json!({})); + controlling.exit(4); + break; + } + } + Ok(_) if line == "release-read\n" && case_is("authoring") => { + let state = observation(&controlling); + if state["close"]["state"] != "closing" + || state["clientPresent"] != false + || state["requestState"] != "unavailable" + || state["failedClosed"] != false + || READ_BARRIER + .release(|| emit("read_barrier_released", state)) + .is_err() + { + emit("control_refused", json!({})); + controlling.exit(4); + break; + } + } + Ok(_) if line == "quit\n" => controlling.exit(0), + _ => { + emit("control_refused", json!({})); + controlling.exit(4); + break; + } + } + } + }); + } + pub(crate) fn exited(app: &AppHandle) { + EXITED.store(true, Ordering::SeqCst); + if let Some(original) = ORIGINAL.get() { + let run = RUN + .get() + .unwrap_or_else(|| refuse("qualification run unavailable", 64)); + if run.validate().is_err() || seeds::observe(&run.root()).as_ref() != Ok(original) { + refuse("disposable original changed during phase", 74); + } + emit( + "original_after", + serde_json::to_value(original) + .unwrap_or_else(|_| refuse("original observation unavailable", 70)), + ); + } + emit( + "exit", + json!({"clean":app.state::().clean_native_completion(),"failedClosed":app.state::().failure_latched(),"state":observation(app)}), + ); + } + #[cfg(test)] + mod header_tests { + use super::*; + #[test] + fn header_callback_accepts_only_finite_classifications() { + assert_eq!(header_reply("\"pending\""), Ok(HeaderReply::Pending)); + assert_eq!(header_reply("\"refused\""), Ok(HeaderReply::Refused)); + assert_eq!(header_reply("\"listed\""), Ok(HeaderReply::Listed)); + for raw in [ + "null", + "true", + "1", + "{}", + "[]", + "\"failed\"", + "\"Listed\"", + "\"refused\" {}", + "\"refused\\n\"", + "\"snapshot content must never be accepted\"", + ] { + assert_eq!(header_reply(raw), Err(())); + } + } + } +} diff --git a/apps/desktop/src/native_encrypted_seeds.rs b/apps/desktop/src/native_encrypted_seeds.rs new file mode 100644 index 0000000..7ab1152 --- /dev/null +++ b/apps/desktop/src/native_encrypted_seeds.rs @@ -0,0 +1,377 @@ +//! Fixed disposable Legacy fixtures for the native qualification executable. +//! These helpers never create a Managed database or access a credential store. +use crate::native_encrypted_case_plan::Seed; +use rangoon_store::{WorkflowRecoveryCounts, Workspace}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + path::Path, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(crate) struct Inventory { + sources: u32, + capabilities: u32, + revisions: u32, + reviews: u32, + recipes: u32, + applications: u32, + derivations: u32, + workflows: u32, + workflow_revisions: u32, +} +impl From<&WorkflowRecoveryCounts> for Inventory { + fn from(c: &WorkflowRecoveryCounts) -> Self { + Self { + sources: c.sources, + capabilities: c.capabilities, + revisions: c.revisions, + reviews: c.reviews, + recipes: c.recipes, + applications: c.applications, + derivations: c.derivations, + workflows: c.workflows, + workflow_revisions: c.workflow_revisions, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(crate) struct Original { + schema: u32, + inventory: Inventory, + archive_sha256: String, + identity: String, + database_sha256: String, + database_bytes: u64, +} + +/// Observe an existing original through the actual bounded read-only capture. +/// Physical hashing supplements logical parity; neither authenticates an author. +pub(crate) fn observe(anchor: &Path) -> Result { + let store = Workspace::new(anchor.join("source-workspace")); + let mut capture = store.capture_existing_snapshot().map_err(|_| ())?; + let path = anchor.join("source-workspace/workspace.sqlite3"); + let before = fs::symlink_metadata(&path).map_err(|_| ())?; + if !before.is_file() + || before.file_type().is_symlink() + || before.nlink() != 1 + || before.mode() & 0o777 != 0o600 + || before.len() > 64 * 1024 * 1024 + { + return Err(()); + } + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(&path) + .map_err(|_| ())?; + let same = |m: &fs::Metadata| { + m.dev() == before.dev() + && m.ino() == before.ino() + && m.uid() == before.uid() + && m.mode() == before.mode() + && m.nlink() == before.nlink() + && m.len() == before.len() + && m.mtime() == before.mtime() + && m.mtime_nsec() == before.mtime_nsec() + && m.ctime() == before.ctime() + && m.ctime_nsec() == before.ctime_nsec() + }; + if !same(&file.metadata().map_err(|_| ())?) { + return Err(()); + } + let mut hash = Sha256::new(); + let mut bytes = 0u64; + let mut buffer = [0u8; 8192]; + loop { + let count = file.read(&mut buffer).map_err(|_| ())?; + if count == 0 { + break; + } + bytes = bytes.checked_add(count as u64).ok_or(())?; + if bytes > 64 * 1024 * 1024 { + return Err(()); + } + hash.update(&buffer[..count]); + } + if bytes != before.len() + || !same(&file.metadata().map_err(|_| ())?) + || !same(&fs::symlink_metadata(&path).map_err(|_| ())?) + { + return Err(()); + } + store + .revalidate_existing_capture(&mut capture) + .map_err(|_| ())?; + Ok(Original { + schema: capture.schema_version().map_err(|_| ())?, + inventory: capture.inventory().map_err(|_| ())?.into(), + archive_sha256: capture.digest().map_err(|_| ())?.to_owned(), + identity: capture.identity_fingerprint().map_err(|_| ())?, + database_sha256: hash + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(), + database_bytes: bytes, + }) +} + +/// Called only for a plan's initial phase after the runner validates its empty +/// fixed root. Repeated or partial seeds are refused without repair or deletion. +pub(crate) fn seed(anchor: &Path, kind: Seed) -> Result { + let metadata = fs::symlink_metadata(anchor).map_err(|_| ())?; + if kind == Seed::None + || !metadata.is_dir() + || metadata.file_type().is_symlink() + || metadata.mode() & 0o777 != 0o700 + || fs::read_dir(anchor).map_err(|_| ())?.next().is_some() + { + return Err(()); + } + let source = anchor.join("source-workspace"); + fs::DirBuilder::new() + .mode(0o700) + .create(&source) + .map_err(|_| ())?; + match kind { + Seed::LegacyEmpty => { + // Independent schema-0 SQLite page, also used by adoption tests. + let mut bytes = vec![0; 4096]; + bytes[..16].copy_from_slice(b"SQLite format 3\0"); + bytes[16..18].copy_from_slice(&4096u16.to_be_bytes()); + bytes[18] = 1; + bytes[19] = 1; + bytes[21] = 64; + bytes[22] = 32; + bytes[23] = 32; + for (offset, value) in [ + (24, 1u32), + (28, 1), + (44, 4), + (56, 1), + (92, 1), + (96, 3040000), + ] { + bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + } + bytes[100] = 13; + bytes[105..107].copy_from_slice(&4096u16.to_be_bytes()); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(source.join("workspace.sqlite3")) + .map_err(|_| ())?; + file.write_all(&bytes) + .and_then(|_| file.sync_all()) + .map_err(|_| ())?; + } + Seed::LegacyRich => populate(&Workspace::new(source.clone()))?, + Seed::None => return Err(()), + } + for directory in [&source, anchor] { + File::open(directory) + .and_then(|file| file.sync_all()) + .map_err(|_| ())?; + } + observe(anchor) +} + +fn populate(store: &Workspace) -> Result<(), ()> { + let report = rangoon_import::analyze( + "AGENTS.md", + b"\xef\xbb\xbf# Rules\r\nKeep originals.\r\n# Tests\r\nCheck edits.\r\n", + ) + .map_err(|_| ())?; + store.save(&report).map_err(|_| ())?; + let capability = store + .create_capability(&report.source.id, &report.fragments[0].id, "Transfer skill") + .map_err(|_| ())? + .capability; + store + .review_capability(&capability.id, &capability.latest_revision_id) + .map_err(|_| ())?; + let revised = store + .revise_capability( + &capability.id, + &capability.latest_revision_id, + "Retained history", + "Reviewed historical content.\r\n", + ) + .map_err(|_| ())? + .capability; + store + .review_capability(&revised.id, &revised.latest_revision_id) + .map_err(|_| ())?; + let value: serde_json::Value = serde_json::from_str(include_str!( + "../../../fixtures/composition/decompose-v0.json" + )) + .map_err(|_| ())?; + let request = rangoon_compose::application::Request { + schema_version: rangoon_compose::application::REQUEST_SCHEMA.into(), + draft: serde_json::from_value(value["draft"].clone()).map_err(|_| ())?, + targets: vec![ + rangoon_compose::application::Target::New {}, + rangoon_compose::application::Target::New {}, + ], + }; + let preview = store.preview_composition(&request).map_err(|_| ())?; + store.apply_composition(&preview, true).map_err(|_| ())?; + use rangoon_workflow::records::{SaveIntent, prepare_revision, workflow_id_from_nonce}; + let id = workflow_id_from_nonce(&[97; 32]); + let first = prepare_revision(&id, None, SaveIntent::Draft, br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Transfer workflow","nodes":[],"controlEdges":[],"dataEdges":[]}"#, br#"{"positions":[]}"#).map_err(|_| ())?; + let plan = store.inspect_workflow_save(&first).map_err(|_| ())?; + store + .save_workflow(&first, &plan.expected_state_id) + .map_err(|_| ())?; + let next = prepare_revision(&id, Some(first.id()), SaveIntent::Draft, br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Retained workflow history","nodes":[],"controlEdges":[],"dataEdges":[]}"#, br#"{"positions":[]}"#).map_err(|_| ())?; + let plan = store.inspect_workflow_save(&next).map_err(|_| ())?; + store + .save_workflow(&next, &plan.expected_state_id) + .map_err(|_| ())?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + os::unix::fs::symlink, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, + }; + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Root(PathBuf, fs::Metadata); + impl Root { + fn new() -> Self { + let root = std::env::temp_dir().canonicalize().unwrap().join(format!( + "rangoon-e1c5c-seed-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )); + fs::DirBuilder::new().mode(0o700).create(&root).unwrap(); + let metadata = fs::symlink_metadata(&root).unwrap(); + Self(root, metadata) + } + } + impl Drop for Root { + fn drop(&mut self) { + if fs::symlink_metadata(&self.0).is_ok_and(|m| { + m.is_dir() + && !m.file_type().is_symlink() + && m.dev() == self.1.dev() + && m.ino() == self.1.ino() + }) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + } + #[test] + fn empty_original_is_real_existing_schema_zero_and_observation_preserves_bytes() { + let root = Root::new(); + let original = seed(&root.0, Seed::LegacyEmpty).unwrap(); + assert_eq!(original.schema, 0); + assert_eq!( + original.inventory, + (&WorkflowRecoveryCounts::default()).into() + ); + assert_eq!(original.database_bytes, 4096); + assert_eq!(observe(&root.0).unwrap(), original); + assert_eq!( + fs::read_dir(root.0.join("source-workspace")) + .unwrap() + .count(), + 1 + ); + } + #[test] + fn rich_original_retains_all_record_families_and_both_revision_histories() { + let root = Root::new(); + let original = seed(&root.0, Seed::LegacyRich).unwrap(); + assert_eq!(original.schema, 4); + assert_eq!( + original.inventory, + Inventory { + sources: 1, + capabilities: 3, + revisions: 4, + reviews: 2, + recipes: 1, + applications: 1, + derivations: 2, + workflows: 1, + workflow_revisions: 2 + } + ); + let bytes = fs::read(root.0.join("source-workspace/workspace.sqlite3")).unwrap(); + assert_eq!(observe(&root.0).unwrap(), original); + assert_eq!( + fs::read(root.0.join("source-workspace/workspace.sqlite3")).unwrap(), + bytes + ); + assert_eq!(original.archive_sha256.len(), 64); + assert_eq!(original.identity.len(), 64); + assert_eq!(original.database_sha256.len(), 64); + } + #[test] + fn repeated_or_partial_seed_refuses_without_overwriting_original() { + let root = Root::new(); + assert!(seed(&root.0, Seed::None).is_err()); + let original = seed(&root.0, Seed::LegacyRich).unwrap(); + assert!(seed(&root.0, Seed::LegacyEmpty).is_err()); + assert_eq!(observe(&root.0).unwrap(), original); + fs::write(root.0.join("unknown"), b"preserve me").unwrap(); + assert!(seed(&root.0, Seed::LegacyRich).is_err()); + assert_eq!(fs::read(root.0.join("unknown")).unwrap(), b"preserve me"); + } + #[test] + fn absent_corrupt_or_linked_original_is_never_created_or_repaired() { + let root = Root::new(); + assert!(observe(&root.0).is_err()); + assert_eq!(fs::read_dir(&root.0).unwrap().count(), 0); + let other = Root::new(); + let original = seed(&other.0, Seed::LegacyEmpty).unwrap(); + symlink( + other.0.join("source-workspace"), + root.0.join("source-workspace"), + ) + .unwrap(); + assert!(observe(&root.0).is_err()); + assert_eq!(observe(&other.0).unwrap(), original); + let bad = Root::new(); + fs::create_dir(bad.0.join("source-workspace")).unwrap(); + fs::write( + bad.0.join("source-workspace/workspace.sqlite3"), + b"invalid fixture", + ) + .unwrap(); + assert!(observe(&bad.0).is_err()); + assert_eq!( + fs::read(bad.0.join("source-workspace/workspace.sqlite3")).unwrap(), + b"invalid fixture" + ); + } + #[test] + fn legitimate_legacy_edit_changes_observation_instead_of_reseeding() { + let root = Root::new(); + let old = seed(&root.0, Seed::LegacyRich).unwrap(); + let store = Workspace::new(root.0.join("source-workspace")); + let report = + rangoon_import::analyze("SKILL.md", b"# Later original\nKeep this change.\n").unwrap(); + store.save_v1(&report).unwrap(); + let new = observe(&root.0).unwrap(); + assert_eq!(new.inventory.sources, old.inventory.sources + 1); + assert_ne!(new.database_sha256, old.database_sha256); + assert_ne!(new.archive_sha256, old.archive_sha256); + assert!(seed(&root.0, Seed::LegacyRich).is_err()); + assert_eq!(observe(&root.0).unwrap(), new); + } +} diff --git a/apps/desktop/src/native_exit_qualification.rs b/apps/desktop/src/native_exit_qualification.rs new file mode 100644 index 0000000..8e48bd4 --- /dev/null +++ b/apps/desktop/src/native_exit_qualification.rs @@ -0,0 +1,441 @@ +//! Explicit, no-webview native lifecycle qualification. Never a product entry. +use super::*; +use crate::{NativeCloud, NativeModel, SourceAccess, WorkspaceClose}; +use rangoon_openshell_client::{ + OpenShellReadClient, + synthetic_peer::{SyntheticPeer, SyntheticRpc, SyntheticScenario}, +}; +use serde_json::{Value, json}; +use std::{ + io::Write, + sync::{Condvar, OnceLock, mpsc}, + time::{Duration, Instant}, +}; +use tauri::{AppHandle, Manager}; + +const CASES: &[&str] = &[ + "idle-clean", + "active-cancel", + "duplicate-timeout-retry", + "cleanup-failed", + "anchor-unavailable", + "anchor-install-failed", +]; +static CASE: OnceLock = OnceLock::new(); +static EVENTS: Mutex = Mutex::new(0); +static WAIT: (Mutex<(usize, usize)>, Condvar) = (Mutex::new((0, 0)), Condvar::new()); + +fn emit(event: &'static str, fields: Value) { + let mut seq = EVENTS.lock().expect("event lock"); + *seq += 1; + let record = + json!({"seq": *seq, "case": CASE.get().expect("case"), "event": event, "fields": fields}); + let line = serde_json::to_vec(&record).expect("fixed event"); + assert!(line.len() < 2048 && *seq <= 128); + let mut out = std::io::stdout().lock(); + out.write_all(&line).expect("event output"); + out.write_all(b"\n").expect("event output"); + out.flush().expect("event output"); +} + +/// Observes real waiter invocations. It cannot choose readiness or reissue exit. +#[derive(Default)] +pub(crate) struct WaitProbe { + checks: usize, + drained: bool, +} +impl WaitProbe { + pub(crate) fn checked(&mut self, drained: bool) { + if self.checks == 0 { + let mut state = WAIT.0.lock().expect("wait lock"); + state.0 += 1; + assert_eq!(state.0, 1, "duplicate active waiter"); + emit("waiter_started", json!({"active": state.0})); + } + self.checks += 1; + self.drained = drained; + } +} +impl Drop for WaitProbe { + fn drop(&mut self) { + if self.checks == 0 { + return; + } + let mut state = WAIT.0.lock().expect("wait lock"); + state.0 -= 1; + state.1 += 1; + emit( + "waiter_finished", + json!({"checks": self.checks, "drained": self.drained, "active": state.0}), + ); + WAIT.1.notify_all(); + } +} + +pub(crate) fn ready(app: &AppHandle, anchor: bool) { + emit( + "ready", + json!({"anchor": anchor, "failedClosed": app.state::().failure_latched()}), + ); +} +pub(crate) fn exit_action( + app: &AppHandle, + code: Option, + action: crate::workspace_close::failure::ExitAction, +) { + use crate::workspace_close::failure::ExitAction::*; + let action = match action { + Pass => "pass", + Prevent => "prevent", + PreventAndStart => "start", + PreventAndWait => "wait", + }; + emit( + "exit_request", + json!({"code": code, "action": action, + "admissionClosed": app.state::().begin(Lane::Read).is_err(), + "clean": app.state::().clean_native_completion()}), + ); +} +pub(crate) fn exited() { + emit("exit", json!({})); +} + +fn valid_context(config: &Value, assets_empty: bool) -> bool { + let Some(app) = config.get("app") else { + return false; + }; + let Some(build) = config.get("build") else { + return false; + }; + let Some(security) = app.get("security") else { + return false; + }; + let Some(caps) = security.get("capabilities").and_then(Value::as_array) else { + return false; + }; + config["identifier"] == "ai.rangoon.native-exit-qualification" + && config["bundle"]["active"] == false + && app["withGlobalTauri"] == false + && app["windows"].as_array().is_some_and(Vec::is_empty) + && [ + "frontendDist", + "devUrl", + "beforeDevCommand", + "beforeBuildCommand", + "beforeBundleCommand", + ] + .iter() + .all(|k| build.get(k).is_none_or(Value::is_null)) + && config + .get("plugins") + .is_none_or(|v| v.as_object().is_some_and(|o| o.is_empty())) + && caps.len() == 1 + && caps[0]["identifier"] == "nx06-no-permissions" + && caps[0]["local"] == false + && caps[0].get("remote").is_none_or(Value::is_null) + && ["windows", "webviews", "permissions"].iter().all(|k| { + caps[0] + .get(k) + .is_none_or(|v| v.as_array().is_some_and(Vec::is_empty)) + }) + && assets_empty +} + +// Pure negative predicates run before constructing a native application. +fn check_context(context: &tauri::Context) { + let mut config = serde_json::to_value(context.config()).expect("configuration"); + // Tauri serializes empty selector arrays by omission; normalize only those + // empty defaults after reading the actual typed context. + if let Some(cap) = config + .pointer_mut("/app/security/capabilities/0") + .and_then(Value::as_object_mut) + { + for key in ["windows", "webviews", "permissions"] { + cap.entry(key).or_insert_with(|| json!([])); + } + } + assert!(valid_context( + &config, + context.assets().iter().next().is_none() + )); + for (pointer, replacement) in [ + ("/identifier", json!("ai.rangoon.studio.dev")), + ("/app/windows", json!([{"label":"main"}])), + ("/app/withGlobalTauri", json!(true)), + ("/app/security/capabilities", json!([])), + ("/app/security/capabilities", json!(["source-analysis"])), + ("/app/security/capabilities/0/local", json!(true)), + ( + "/app/security/capabilities/0/permissions", + json!(["core:default"]), + ), + ("/bundle/active", json!(true)), + ] { + let mut bad = config.clone(); + *bad.pointer_mut(pointer).expect("predicate field") = replacement; + assert!(!valid_context(&bad, true)); + } + assert!(!valid_context(&config, false)); + emit( + "context_validated", + json!({"emptyAssets": true, "effectiveGrants": 0, "negativeChecks": 9}), + ); +} + +pub(crate) fn run() { + std::panic::set_hook(Box::new(|_| { + eprintln!("nx06: test panic"); + })); + let args: Vec<_> = std::env::args().skip(1).collect(); + if args.len() != 1 || !CASES.contains(&args[0].as_str()) { + eprintln!("nx06: one exact case required"); + std::process::exit(64); + } + CASE.set(args[0].clone()).expect("one case"); + let context = tauri::generate_context!( + "native-exit-qualification/tauri.conf.json", + test = true, + assets = tauri::utils::assets::EmbeddedAssets::new( + tauri::utils::assets::phf::Map::new(), + &[], + tauri::utils::assets::phf::Map::new() + ) + ); + check_context(&context); + let (gate, flight) = crate::admission_state(); + let source = if args[0] == "anchor-unavailable" { + crate::source_state(&gate, Err(rangoon_store::StoreError::Unavailable)) + } else { + SourceAccess::close_protocol_fixture(gate.clone()) + }; + if args[0] == "anchor-install-failed" { + source + .set_failure_notifier(Arc::new(|| {})) + .expect("occupied fixture notifier"); + } + let cloud = NativeCloud::default(); + if args[0] == "cleanup-failed" { + cloud.poison_for_native_exit_qualification(); + } + let app = tauri::Builder::default() + .manage(gate.clone()) + .manage(NativeModel::default()) + .manage(cloud) + .manage(flight) + .manage(crate::cloud_custody::Custody::with_gate(gate.clone())) + .manage(Host::new(gate)) + .manage(WorkspaceClose::new(source.clone())) + .manage(source) + .build(context) + .expect("qualification app"); + let mut anchor = None; + let waiter = crate::workspace_close::failure::CallbackWaiter::default(); + app.run(move |app, event| { + crate::coordinate_native_event(app, &event, &mut anchor, &waiter); + if matches!(event, tauri::RunEvent::Ready) { + let handle = app.clone(); + std::thread::spawn(move || { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drive(handle))).is_err() + { + // Never let an assertion failure look like a successful ordinary exit. + std::process::exit(70); + } + }); + } + }); +} + +struct HeldRead { + returned: mpsc::SyncSender, + release: mpsc::Receiver<()>, +} +impl SyntheticReadClient for HeldRead { + fn run( + self: Box, + config: ClientConfig, + lease: BearerLease, + kind: ReadKind, + control: WatchControl, + ) -> Result { + assert_eq!(kind, ReadKind::RecentWatch); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("client runtime"); + let result = rt.block_on(async { + let mut client = OpenShellReadClient::connect(config, lease).await?; + let protected_check = client.check_protected_read().await?; + let observation = Observation::RecentWatch( + client + .watch_recent(&control, None, Duration::from_secs(30)) + .await?, + ); + Ok(ReadOutcome { + protected_check, + observation, + }) + }); + drop(rt); + let cancelled = result == Err(ClientError::Cancelled); + emit("client_returned", json!({"cancelled": cancelled})); + self.returned + .send(cancelled) + .expect("client result receiver"); + self.release + .recv_timeout(Duration::from_secs(20)) + .expect("callback release"); + result + } +} + +fn roundtrip(app: &AppHandle, event: &'static str) { + let (tx, rx) = mpsc::sync_channel(1); + let checking = app.clone(); + app.run_on_main_thread(move || { + assert!(checking.state::().begin(Lane::Read).is_err()); + assert!(!checking.state::().cancel_and_check_exit()); + assert!(!checking.state::().clean_native_completion()); + emit( + event, + json!({"admissionClosed": true, "callbackHeld": true}), + ); + tx.send(()).expect("roundtrip receiver"); + }) + .expect("native roundtrip"); + rx.recv_timeout(Duration::from_secs(5)) + .expect("native roundtrip returned"); +} + +fn drive(app: AppHandle) { + let case = CASE.get().expect("case"); + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("peer runtime"); + let host = app.state::().inner().clone(); + let gate = app.state::().inner().clone(); + if case != "active-cancel" && case != "duplicate-timeout-retry" { + // An inert local socket sentinel observes the no-start path without + // opening a client or depending on private transport-crate counters. + let sentinel = + std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).expect("sentinel"); + sentinel + .set_nonblocking(true) + .expect("nonblocking sentinel"); + assert_eq!( + host.begin_production("nx06-unavailable"), + HostStatus::Unavailable + ); + assert!(matches!(sentinel.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock)); + emit( + "production_unavailable", + json!({"connections": 0, "rpcs": 0, "probe": "inert_socket_sentinel"}), + ); + drop(sentinel); + emit("peer_stopped", json!({"connections": 0, "rpcs": 0})); + emit("request_exit", json!({"code": 37})); + app.exit(37); + return; + } + let peer = rt + .block_on(SyntheticPeer::start(SyntheticScenario::StalledWatch)) + .expect("synthetic peer"); + assert_eq!( + host.begin_production("nx06-unavailable"), + HostStatus::Unavailable + ); + assert!(peer.calls().expect("calls").is_empty()); + emit("production_unavailable", json!({"rpcs": 0})); + let workspace = WorkspaceRequest::Managed(Arc::new(gate.observe_open().expect("open witness"))); + let target = ProposedTarget::new( + peer.origin().to_owned(), + peer.selected_peer(), + "installation-1".into(), + "workspace-1".into(), + "sandbox-1".into(), + peer.root_der().to_vec(), + peer.leaf_der().to_vec(), + ) + .expect("peer target"); + let review = host + .prepare( + &workspace, + target, + ReadKind::RecentWatch, + Retention::SessionOnly, + ) + .expect("review"); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + let (tx, rx) = mpsc::sync_channel(1); + let (release, held) = mpsc::channel(); + let lease = BearerLease::new( + "test-token".into(), + Instant::now() + Duration::from_secs(30), + ) + .expect("test lease"); + assert_eq!( + host.begin_synthetic( + &review.id, + lease, + Box::new(HeldRead { + returned: tx, + release: held + }) + ), + HostStatus::Running + ); + rt.block_on(peer.wait_watch_started()) + .expect("watch signal"); + assert_eq!( + peer.calls().expect("calls"), + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::WatchSandbox + ] + ); + emit("watch_started", json!({"rpcs": 3})); + emit("request_exit", json!({"code": 37})); + app.exit(37); + assert!( + rx.recv_timeout(Duration::from_secs(5)) + .expect("real cancellation") + ); + roundtrip(&app, "held_roundtrip"); + if case == "duplicate-timeout-retry" { + for _ in 0..3 { + app.exit(37); + } + roundtrip(&app, "duplicates_roundtrip"); + let state = WAIT.0.lock().expect("wait lock"); + let (state, timeout) = WAIT + .1 + .wait_timeout_while(state, Duration::from_secs(15), |s| s.1 == 0) + .expect("waiter signal"); + assert!(!timeout.timed_out()); + assert_eq!(*state, (0, 1)); + drop(state); + roundtrip(&app, "timeout_roundtrip"); + } + assert!(host.completed_observation(&workspace, &review.id).is_none()); + // Shut down the synthetic server before release can permit native process exit. + rt.block_on(peer.shutdown()).expect("peer shutdown"); + emit("peer_stopped", json!({"rpcs": 3})); + emit("release_callback", json!({})); + release.send(()).expect("release held callback"); + if case == "duplicate-timeout-retry" { + let deadline = Instant::now() + Duration::from_secs(5); + while !host.cancel_and_check_exit() { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + } + emit("callback_drained", json!({})); + emit("retry_exit", json!({"code": 37})); + app.exit(37); + } +} diff --git a/apps/desktop/src/openshell_credential.rs b/apps/desktop/src/openshell_credential.rs new file mode 100644 index 0000000..c839998 --- /dev/null +++ b/apps/desktop/src/openshell_credential.rs @@ -0,0 +1,120 @@ +//! Native-owned selection metadata. This is not an OS credential provider. +use super::{ClientError, HostError, Review, review_id}; +use std::time::{Duration, Instant}; + +const MAX_SELECTION_LIFETIME: Duration = Duration::from_secs(120); + +/// An inspection copy is only a lookup candidate, never owning custody. +#[derive(Clone, PartialEq, Eq)] +pub(super) struct CredentialInspection { + pub(super) reference: String, + pub(super) review: Review, +} + +/// Retained only in this Host's Pending state, alongside generation admission. +/// No Clone, Debug, serialization, lookup service, or ambient secret access. +pub(super) struct CredentialSelection { + inspection: CredentialInspection, + pub(super) deadline: Instant, +} + +impl CredentialSelection { + pub(super) fn new(review: &Review) -> Result { + let deadline = Instant::now() + .checked_add(MAX_SELECTION_LIFETIME) + .ok_or(HostError::Unavailable)?; + Ok(Self { + inspection: CredentialInspection { + reference: review_id()?, + review: review.clone(), + }, + deadline, + }) + } + + pub(super) fn inspect(&self) -> CredentialInspection { + self.inspection.clone() + } + + pub(super) fn matches(&self, candidate: &CredentialInspection, review: &Review) -> bool { + &self.inspection == candidate && &candidate.review == review + } + + pub(super) fn check(&self) -> Result<(), ClientError> { + check_deadline(self.deadline) + } + + pub(super) fn claim(self) -> CredentialClaim { + CredentialClaim { selection: self } + } +} + +pub(super) fn check_deadline(deadline: Instant) -> Result<(), ClientError> { + if Instant::now() >= deadline { + Err(ClientError::CredentialLeaseExpired) + } else { + Ok(()) + } +} + +/// One-shot native claim. No command, renderer input or ambient source can +/// construct it; the existing Host transfers it after exact native consent. +pub(super) struct CredentialClaim { + selection: CredentialSelection, +} + +impl CredentialClaim { + pub(super) fn deadline(&self) -> Instant { + self.selection.deadline + } + + /// Consumes the exact one-shot claim. The source can shorten its deadline, + /// never renew it. The unmounted native path uses the same corrected client lease. + pub(super) fn seal( + self, + mut value: zeroize::Zeroizing, + source_expiry: Option, + ) -> Result { + let deadline = source_expiry.map_or(self.selection.deadline, |expiry| { + expiry.min(self.selection.deadline) + }); + check_deadline(deadline)?; + if value.is_empty() + || value.len() > 16 * 1024 + || !value.bytes().all(|b| (0x20..=0x7e).contains(&b)) + { + return Err(ClientError::Source); + } + // Transfer the owned allocation to the existing client's owning lease. + // This does not promise erasure of + // every transient allocation inside the client's String-taking API. + let lease = + rangoon_openshell_client::BearerLease::new(std::mem::take(&mut *value), deadline) + .map_err(|_| { + check_deadline(deadline) + .err() + .unwrap_or(ClientError::Source) + })?; + Ok(AcquiredCredential { lease, deadline }) + } +} + +pub(super) struct AcquiredCredential { + lease: rangoon_openshell_client::BearerLease, + deadline: Instant, +} + +impl AcquiredCredential { + pub(super) fn deadline(&self) -> Instant { + self.deadline + } + + pub(super) fn into_lease(self) -> rangoon_openshell_client::BearerLease { + self.lease + } +} + +#[cfg(test)] +pub(super) trait CredentialAcquirer: Send + 'static { + fn acquire(self: Box, claim: CredentialClaim) -> Result; +} diff --git a/apps/desktop/src/openshell_credential_tests.rs b/apps/desktop/src/openshell_credential_tests.rs new file mode 100644 index 0000000..809b126 --- /dev/null +++ b/apps/desktop/src/openshell_credential_tests.rs @@ -0,0 +1,803 @@ +use super::super::credential::{CredentialAcquirer, CredentialClaim, CredentialInspection}; +use super::*; +use std::{ + sync::mpsc, + time::{Duration, Instant}, +}; +use zeroize::Zeroizing; + +macro_rules! assert_not_impl { + ($owner:ty: $trait:path) => { + const _: fn() = || { + trait AmbiguousIfImpl { + fn marker() {} + } + impl AmbiguousIfImpl<()> for T {} + struct Invalid; + impl AmbiguousIfImpl for T {} + let _ = <$owner as AmbiguousIfImpl<_>>::marker; + }; + }; +} + +assert_not_impl!(super::super::credential::CredentialSelection: Clone); +assert_not_impl!(super::super::credential::CredentialSelection: std::fmt::Debug); +assert_not_impl!(super::super::credential::CredentialSelection: serde::Serialize); +assert_not_impl!(super::super::credential::CredentialClaim: Clone); +assert_not_impl!(super::super::credential::CredentialClaim: std::fmt::Debug); +assert_not_impl!(super::super::credential::CredentialClaim: serde::Serialize); +assert_not_impl!(super::super::credential::AcquiredCredential: Clone); +assert_not_impl!(super::super::credential::AcquiredCredential: std::fmt::Debug); +assert_not_impl!(super::super::credential::AcquiredCredential: serde::Serialize); +assert_not_impl!(rangoon_native_credential_input::SecretInput: serde::Serialize); + +struct SealingAcquirer { + value: &'static str, + source_expiry: Option, + called: Option>, +} + +impl CredentialAcquirer for SealingAcquirer { + fn acquire( + self: Box, + claim: CredentialClaim, + ) -> Result { + let deadline = claim.deadline(); + if let Some(called) = self.called { + let _ = called.send(deadline); + } + claim.seal(Zeroizing::new(self.value.to_owned()), self.source_expiry) + } +} + +struct ReportingAcquirer { + source_expiry: Instant, + acquired: mpsc::Sender, +} + +impl CredentialAcquirer for ReportingAcquirer { + fn acquire( + self: Box, + claim: CredentialClaim, + ) -> Result { + let acquired = claim.seal( + Zeroizing::new("test-token".to_owned()), + Some(self.source_expiry), + )?; + self.acquired.send(acquired.deadline()).unwrap(); + Ok(acquired) + } +} + +struct FailingAcquirer { + called: mpsc::Sender<()>, + error: ClientError, +} + +impl CredentialAcquirer for FailingAcquirer { + fn acquire( + self: Box, + _claim: CredentialClaim, + ) -> Result { + let _ = self.called.send(()); + Err(self.error) + } +} + +struct HeldAcquirer { + started: mpsc::Sender<()>, + release: mpsc::Receiver<()>, +} + +impl CredentialAcquirer for HeldAcquirer { + fn acquire( + self: Box, + claim: CredentialClaim, + ) -> Result { + self.started.send(()).unwrap(); + let _ = self.release.recv(); + claim.seal(Zeroizing::new("test-token".to_owned()), None) + } +} + +struct SealedHeldAcquirer { + source_expiry: Instant, + sealed: mpsc::Sender, + release: mpsc::Receiver<()>, +} + +impl CredentialAcquirer for SealedHeldAcquirer { + fn acquire( + self: Box, + claim: CredentialClaim, + ) -> Result { + let acquired = claim.seal( + Zeroizing::new("test-token".to_owned()), + Some(self.source_expiry), + )?; + self.sealed.send(acquired.deadline()).unwrap(); + let _ = self.release.recv(); + Ok(acquired) + } +} + +struct PanickingAcquirer { + started: mpsc::Sender<()>, + release: mpsc::Receiver<()>, +} + +impl CredentialAcquirer for PanickingAcquirer { + fn acquire( + self: Box, + _claim: CredentialClaim, + ) -> Result { + self.started.send(()).unwrap(); + let _ = self.release.recv(); + panic!("synthetic credential callback failure"); + } +} + +fn inspection(host: &Host, review: &Review) -> CredentialInspection { + host.credential_inspection(&review.id) + .expect("selection inspection must exist with pending review") +} + +fn confirm(host: &Host, review: &Review) -> CredentialInspection { + let inspection = inspection(host, review); + let before_confirm = { + let state = host.state.lock().unwrap(); + match state.pending.as_ref().unwrap() { + Pending::Awaiting { selection, .. } => selection.deadline, + Pending::Confirmed { .. } => unreachable!(), + } + }; + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + let after_confirm = { + let state = host.state.lock().unwrap(); + match state.pending.as_ref().unwrap() { + Pending::Confirmed { selection, .. } => selection.deadline, + Pending::Awaiting { .. } => unreachable!(), + } + }; + assert_eq!(after_confirm, before_confirm); + inspection +} + +fn no_run_client(kind: ReadKind) -> Box { + Box::new(SyntheticClient { + expected_kind: kind, + result: Err(ClientError::Source), + started: None, + release: None, + }) +} + +#[test] +fn inspection_is_context_only_and_cannot_acquire_before_consent() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let selected = inspection(&host, &review); + assert_eq!(selected.review, review); + assert_ne!(selected.reference, review.id); + assert_eq!( + host.begin_production(&review.id), + HostStatus::AwaitingConsent + ); + + let (called, received) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: Some(called), + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::AwaitingConsent + ); + assert!(received.recv_timeout(Duration::from_millis(50)).is_err()); + assert_eq!(host.inspect_review(), Some(review.clone())); + assert_eq!(host.stop(), HostStatus::Cancelled); + assert!(gate.request_drain().unwrap().is_quiescent().unwrap()); +} + +#[test] +fn denied_native_confirmation_never_acquires_from_prior_inspection() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let selected = inspection(&host, &review); + assert_eq!(host.confirm(&review.id, false), HostStatus::Cancelled); + let (called, received) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: Some(called), + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Unavailable + ); + assert!(received.recv_timeout(Duration::from_millis(50)).is_err()); + assert!(gate.request_drain().unwrap().is_quiescent().unwrap()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn acquisition_uses_exact_inspection_and_real_tls_client_path() { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: None, + })), + Box::::default(), + ), + HostStatus::Running + ); + assert_eq!(real_terminal_status(&host).await, HostStatus::Completed); + assert_eq!( + peer.calls().unwrap(), + vec![SyntheticRpc::Health, SyntheticRpc::GetSandboxPolicyStatus] + ); + assert!(host.completed_observation(&workspace, &review.id).is_some()); + assert_eq!(host.begin_production(&review.id), HostStatus::Unavailable); + assert_eq!(host.stop(), HostStatus::Cancelled); + peer.shutdown().await.unwrap(); +} + +#[test] +fn changed_inspection_context_refuses_without_consuming_valid_selection() { + type InspectionChange = Box; + let changes: Vec = vec![ + Box::new(|candidate| candidate.reference.push('x')), + Box::new(|candidate| candidate.review.id.push('x')), + Box::new(|candidate| candidate.review.origin.push('x')), + Box::new(|candidate| candidate.review.selected_peer.set_port(444)), + Box::new(|candidate| candidate.review.installation.push('x')), + Box::new(|candidate| candidate.review.workspace.push('x')), + Box::new(|candidate| candidate.review.sandbox.push('x')), + Box::new(|candidate| candidate.review.product_version = "v0.1.4-changed"), + Box::new(|candidate| candidate.review.root_sha256.push('x')), + Box::new(|candidate| candidate.review.peer_pin_sha256.push('x')), + Box::new(|candidate| candidate.review.kind = ReadKind::RecentLogs), + Box::new(|candidate| candidate.review.data_classes.push(DataClass::RedactedLog)), + ]; + + for change in changes { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let mut candidate = selected.clone(); + change(&mut candidate); + let (called, received) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &candidate, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: Some(called), + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Unavailable + ); + assert!(received.recv_timeout(Duration::from_millis(50)).is_err()); + assert!( + host.credential_inspection(&review.id) + .is_some_and(|current| current == selected) + ); + assert_eq!(host.stop(), HostStatus::Cancelled); + } +} + +#[test] +fn foreign_host_and_stale_generation_refuse_without_acquisition() { + let first_gate = Gate::new(); + let first = Host::new(first_gate.clone()); + let first_review = prepare(&first, &first_gate, ReadKind::ProtectedCheck); + let first_selection = confirm(&first, &first_review); + let second_gate = Gate::new(); + let second = Host::new(second_gate.clone()); + let second_review = prepare(&second, &second_gate, ReadKind::ProtectedCheck); + let _second_selection = confirm(&second, &second_review); + let (called, received) = mpsc::channel(); + assert_eq!( + second.begin_acquisition( + &first_selection, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: Some(called), + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Unavailable + ); + assert!(received.recv_timeout(Duration::from_millis(50)).is_err()); + assert!(second.credential_inspection(&second_review.id).is_some()); + let _drain = first_gate.request_drain().unwrap(); + let (called, received) = mpsc::channel(); + assert_eq!( + first.begin_acquisition( + &first_selection, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: Some(called), + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Unavailable + ); + assert!(received.recv_timeout(Duration::from_millis(50)).is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn success_and_failure_consume_same_inspection_once() { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + for succeeds in [true, false] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (_, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let acquirer: Box = if succeeds { + Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: None, + }) + } else { + let (called, received) = mpsc::channel(); + let acquirer = Box::new(FailingAcquirer { + called, + error: ClientError::PermissionDenied, + }); + drop(received); + acquirer + }; + assert_eq!( + host.begin_acquisition(&selected, Some(acquirer), Box::::default()), + HostStatus::Running + ); + assert_eq!( + real_terminal_status(&host).await, + if succeeds { + HostStatus::Completed + } else { + HostStatus::Error(ClientError::Source) + } + ); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: None, + called: None, + })), + Box::::default(), + ), + HostStatus::Unavailable + ); + } + assert_eq!( + peer.calls().unwrap(), + vec![SyntheticRpc::Health, SyntheticRpc::GetSandboxPolicyStatus] + ); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn absent_backend_maps_to_fixed_source_error_without_rpc() { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (_, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + assert_eq!( + host.begin_acquisition(&selected, None, Box::::default()), + HostStatus::Running + ); + assert_eq!( + real_terminal_status(&host).await, + HostStatus::Error(ClientError::Source) + ); + assert!(peer.calls().unwrap().is_empty()); + assert_eq!(ClientError::Source.code(), "source_error"); + peer.shutdown().await.unwrap(); +} + +async fn start_held_acquisition() -> (SyntheticPeer, Gate, Host, Review, mpsc::Sender<()>) { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (_, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let (started, entered) = mpsc::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(HeldAcquirer { + started, + release: held, + })), + Box::::default(), + ), + HostStatus::Running + ); + entered.recv_timeout(Duration::from_secs(1)).unwrap(); + (peer, gate, host, review, release) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn held_acquisition_stop_retains_admission_then_drops_late_secret_without_rpc() { + let (peer, gate, host, _review, release) = start_held_acquisition().await; + assert_eq!(host.stop(), HostStatus::Closing); + let drain = gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + release.send(()).unwrap(); + assert_eq!(real_terminal_status(&host).await, HostStatus::Cancelled); + assert!(drain.is_quiescent().unwrap()); + assert!(peer.calls().unwrap().is_empty()); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn held_acquisition_workspace_close_waits_for_actual_callback_return() { + let (peer, gate, host, _review, release) = start_held_acquisition().await; + let close = WorkspaceClose::new(SourceAccess::close_protocol_fixture(gate.clone())); + let closing = close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!(serde_json::to_value(closing).unwrap()["state"], "closing"); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(false) + ); + release.send(()).unwrap(); + assert_eq!(real_terminal_status(&host).await, HostStatus::Cancelled); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(true) + ); + assert!(peer.calls().unwrap().is_empty()); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sealed_credential_expiry_after_acquisition_blocks_client_without_early_fence() { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (_, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let source_expiry = Instant::now() + Duration::from_secs(1); + let (sealed, acquired_deadline) = mpsc::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(SealedHeldAcquirer { + source_expiry, + sealed, + release: held, + })), + Box::::default(), + ), + HostStatus::Running + ); + let deadline = acquired_deadline + .recv_timeout(Duration::from_secs(1)) + .unwrap(); + assert_eq!(deadline, source_expiry); + assert!( + host.state + .lock() + .unwrap() + .active + .as_ref() + .is_some_and(|active| { active.state.lock().unwrap().admission.is_some() }) + ); + tokio::time::sleep_until(tokio::time::Instant::from_std(deadline) + Duration::from_millis(20)) + .await; + assert_eq!(host.status(), HostStatus::Running); + assert!( + host.state + .lock() + .unwrap() + .active + .as_ref() + .is_some_and(|active| { active.state.lock().unwrap().admission.is_some() }) + ); + release.send(()).unwrap(); + assert_eq!( + real_terminal_status(&host).await, + HostStatus::Error(ClientError::CredentialLeaseExpired) + ); + assert!(gate.request_drain().unwrap().is_quiescent().unwrap()); + assert!(peer.calls().unwrap().is_empty()); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn dropped_host_handles_do_not_release_held_acquisition_admission() { + let (peer, gate, host, _review, release) = start_held_acquisition().await; + let clone = host.clone(); + drop(host); + drop(clone); + let drain = gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + release.send(()).unwrap(); + for _ in 0..100 { + if drain.is_quiescent().unwrap() { + assert!(peer.calls().unwrap().is_empty()); + peer.shutdown().await.unwrap(); + return; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("dropped host handles must not detach acquisition callback custody"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn held_acquisition_native_exit_coordinator_waits_for_callback_return() { + use crate::workspace_close::failure::{ExitAction, ExitCoordinator, route_exit_request}; + + let (peer, gate, host, _review, release) = start_held_acquisition().await; + let source = SourceAccess::close_protocol_fixture(gate.clone()); + let close = WorkspaceClose::new(source.clone()); + let exit = ExitCoordinator::new(); + assert_eq!( + route_exit_request(Some(71), Some((&close, &exit)), || { + assert!(gate.observe_open().is_err()); + host.cancel_and_check_exit() + }), + ExitAction::PreventAndWait + ); + assert!(!source.request_close().unwrap().is_quiescent().unwrap()); + release.send(()).unwrap(); + assert_eq!(real_terminal_status(&host).await, HostStatus::Cancelled); + assert!(source.request_close().unwrap().is_quiescent().unwrap()); + assert_eq!( + route_exit_request(Some(71), Some((&close, &exit)), || host + .cancel_and_check_exit()), + ExitAction::PreventAndStart + ); + close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(true) + ); + assert!(exit.send(0)); + assert_eq!( + route_exit_request(Some(0), Some((&close, &exit)), || host + .cancel_and_check_exit()), + ExitAction::Pass + ); + assert!(peer.calls().unwrap().is_empty()); + peer.shutdown().await.unwrap(); +} + +#[test] +fn expired_selection_calls_neither_acquirer_nor_client_and_cannot_renew() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + { + let mut state = host.state.lock().unwrap(); + let Some(Pending::Confirmed { selection, .. }) = state.pending.as_mut() else { + panic!("confirmed pending selection expected"); + }; + selection.deadline = Instant::now() - Duration::from_millis(1); + } + let (called, received) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(SealingAcquirer { + value: "test-token", + source_expiry: Some(Instant::now() + Duration::from_secs(30)), + called: Some(called), + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Error(ClientError::CredentialLeaseExpired) + ); + assert!(received.recv_timeout(Duration::from_millis(50)).is_err()); + assert_eq!(host.status(), HostStatus::Unavailable); +} + +#[test] +fn acquisition_expiry_only_shortens_claim_deadline() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let expected = { + let state = host.state.lock().unwrap(); + match state.pending.as_ref().unwrap() { + Pending::Confirmed { selection, .. } => selection.deadline, + Pending::Awaiting { .. } => unreachable!(), + } + }; + let (reported, received) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(ReportingAcquirer { + source_expiry: expected + Duration::from_secs(10), + acquired: reported, + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Running + ); + assert_eq!( + received.recv_timeout(Duration::from_secs(1)).unwrap(), + expected + ); + assert_eq!(finish_status(&host), HostStatus::Error(ClientError::Source)); +} + +fn confirmed_selection_for_seal() -> super::super::credential::CredentialSelection { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let _selected = confirm(&host, &review); + let mut state = host.state.lock().unwrap(); + let Some(Pending::Confirmed { selection, .. }) = state.pending.take() else { + panic!("confirmed pending selection expected"); + }; + selection +} + +#[test] +fn credential_claim_seal_enforces_exact_secret_byte_bound() { + assert!(matches!( + confirmed_selection_for_seal() + .claim() + .seal(Zeroizing::new(String::new()), None), + Err(ClientError::Source) + )); + assert!(matches!( + confirmed_selection_for_seal() + .claim() + .seal(Zeroizing::new("x".repeat(16 * 1024 + 1)), None), + Err(ClientError::Source) + )); + assert!( + confirmed_selection_for_seal() + .claim() + .seal(Zeroizing::new("x".repeat(16 * 1024)), None) + .is_ok() + ); + for value in [ + "non-ascii-ñ".to_owned(), + "line\nbreak".to_owned(), + "tab\tvalue".to_owned(), + "delete\u{7f}value".to_owned(), + ] { + assert!(matches!( + confirmed_selection_for_seal() + .claim() + .seal(Zeroizing::new(value), None), + Err(ClientError::Source) + )); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn expiry_after_real_client_result_rejects_late_observation() { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let (returned, result_received) = tokio::sync::oneshot::channel(); + let (reported, acquired_deadline) = mpsc::channel(); + let (release, held) = mpsc::channel(); + let source_expiry = Instant::now() + Duration::from_secs(1); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(ReportingAcquirer { + source_expiry, + acquired: reported, + })), + Box::new(RealReadClient { + returned: Some(returned), + release: Some(held), + }), + ), + HostStatus::Running + ); + assert!( + tokio::time::timeout(Duration::from_secs(5), result_received) + .await + .expect("real client result must arrive within harness bound") + .unwrap() + .is_ok() + ); + let deadline = acquired_deadline + .recv_timeout(Duration::from_secs(1)) + .unwrap(); + assert_eq!(deadline, source_expiry); + tokio::time::sleep_until(tokio::time::Instant::from_std(deadline) + Duration::from_millis(20)) + .await; + release.send(()).unwrap(); + assert_eq!( + real_terminal_status(&host).await, + HostStatus::Error(ClientError::CredentialLeaseExpired) + ); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + peer.shutdown().await.unwrap(); +} + +#[test] +fn sealed_lease_debug_is_fixed_redaction() { + let lease = BearerLease::new( + "c0-test-secret-must-not-project".to_owned(), + Instant::now() + Duration::from_secs(1), + ) + .unwrap(); + let debug = format!("{lease:?}"); + assert_eq!(debug, "BearerLease([redacted])"); + assert!(!debug.contains("c0-test-secret-must-not-project")); +} + +#[test] +fn panic_in_acquirer_keeps_drain_until_callback_unwinds() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let selected = confirm(&host, &review); + let (started, entered) = mpsc::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_acquisition( + &selected, + Some(Box::new(PanickingAcquirer { + started, + release: held, + })), + no_run_client(ReadKind::ProtectedCheck), + ), + HostStatus::Running + ); + entered.recv_timeout(Duration::from_secs(1)).unwrap(); + let drain = gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + release.send(()).unwrap(); + assert_eq!(finish_status(&host), HostStatus::Error(ClientError::Source)); + assert!(drain.is_quiescent().unwrap()); +} diff --git a/apps/desktop/src/openshell_host.rs b/apps/desktop/src/openshell_host.rs index 059dfb8..227401f 100644 --- a/apps/desktop/src/openshell_host.rs +++ b/apps/desktop/src/openshell_host.rs @@ -10,6 +10,14 @@ // call merely to satisfy dead-code linting. #![allow(dead_code)] +#[path = "openshell_credential.rs"] +mod credential; +use credential::{CredentialInspection, CredentialSelection}; +#[path = "openshell_native_input.rs"] +mod native_input; +#[path = "openshell_session_view.rs"] +mod session_view; + use crate::{AdmissionError, workspace_requests::WorkspaceRequest}; use rangoon_desktop::workspace_lifecycle::{Gate, GenerationWitness, Lane, Lease}; #[cfg(test)] @@ -226,16 +234,24 @@ impl ReadOutcome { } } +#[derive(Clone, Copy)] +enum CallbackStart { + Confirmed, + NativeReview, +} + enum Pending { Awaiting { review: Review, target: ProposedTarget, admission: Lease, + selection: CredentialSelection, }, Confirmed { review: Review, target: ProposedTarget, admission: Lease, + selection: CredentialSelection, }, } @@ -246,6 +262,12 @@ impl Pending { } } + fn selection(&self) -> &CredentialSelection { + match self { + Self::Awaiting { selection, .. } | Self::Confirmed { selection, .. } => selection, + } + } + fn is_current(&self) -> bool { match self { Self::Awaiting { admission, .. } | Self::Confirmed { admission, .. } => { @@ -253,14 +275,31 @@ impl Pending { } } } + + /// Readback reports the retained phase without consuming consent or custody. + /// Expired selections remain owned until Stop or the existing close path. + fn status(&self) -> HostStatus { + if !self.is_current() { + return HostStatus::Unavailable; + } + if let Err(error) = self.selection().check() { + return HostStatus::Error(error); + } + match self { + Self::Awaiting { .. } => HostStatus::AwaitingConsent, + Self::Confirmed { .. } => HostStatus::ReadyForNativeCredential, + } + } } struct Active { review_id: String, + kind: ReadKind, witness: GenerationWitness, control: WatchControl, state: Mutex, cancelled: AtomicBool, + parent_label: Option, } struct ActiveState { @@ -268,16 +307,15 @@ struct ActiveState { /// lets the workspace drain prove quiescence. admission: Option, result: Option>, + credential_deadline: Option, } /// Finalize callback custody after its stack has unwound. This guard is /// created before invoking the client, so client arguments (including the /// secret lease) are dropped before admission is released on a panic. /// It does not catch panics, change the panic hook, or handle process abort. -#[cfg(test)] struct CallbackCompletion(Arc); -#[cfg(test)] impl Drop for CallbackCompletion { fn drop(&mut self) { // finish is single-assignment. A normal result stays intact, while an @@ -287,17 +325,37 @@ impl Drop for CallbackCompletion { } impl Active { - fn new(review_id: String, admission: Lease, control: WatchControl) -> Self { + fn new(review_id: String, kind: ReadKind, admission: Lease, control: WatchControl) -> Self { Self { review_id, + kind, witness: admission.witness(), control, state: Mutex::new(ActiveState { admission: Some(admission), result: None, + credential_deadline: None, }), cancelled: AtomicBool::new(false), + parent_label: None, + } + } + + fn accept_credential(&self, deadline: std::time::Instant) -> Result<(), ClientError> { + if self.cancelled.load(Ordering::Acquire) || !self.witness.is_current().unwrap_or(false) { + return Err(ClientError::Cancelled); } + credential::check_deadline(deadline) + } + + fn bind_credential_deadline(&self, deadline: std::time::Instant) -> Result<(), ClientError> { + let mut state = self.state.lock().map_err(|_| ClientError::Source)?; + let bound = state + .credential_deadline + .map_or(deadline, |old| old.min(deadline)); + state.credential_deadline = Some(bound); + drop(state); + self.accept_credential(bound) } fn finish(&self, result: Result) { @@ -307,6 +365,11 @@ impl Active { if state.result.is_none() { state.result = Some(if self.cancelled.load(Ordering::Acquire) { Err(ClientError::Cancelled) + } else if state + .credential_deadline + .is_some_and(|deadline| credential::check_deadline(deadline).is_err()) + { + Err(ClientError::CredentialLeaseExpired) } else { result }); @@ -319,6 +382,7 @@ impl Active { return HostStatus::Unavailable; }; match state.result { + None if self.cancelled.load(Ordering::Acquire) => HostStatus::Closing, None => HostStatus::Running, Some(Ok(_)) => HostStatus::Completed, Some(Err(ClientError::Cancelled)) => HostStatus::Cancelled, @@ -394,6 +458,16 @@ impl Host { if !admission.is_current().unwrap_or(false) { return Err(HostError::Unavailable); } + self.retain_review(admission, target, kind, retention) + } + + fn retain_review( + &self, + admission: Lease, + target: ProposedTarget, + kind: ReadKind, + retention: Retention, + ) -> Result { let review = Review { id: review_id()?, origin: target.origin.clone(), @@ -409,13 +483,20 @@ impl Host { data_classes: data_classes(kind).to_vec(), }; let mut state = self.state.lock().map_err(|_| HostError::Unavailable)?; + // Close fences admission before taking this mutex to purge pending + // reviews. A preparation that lost that race must drop its lease here. + if !admission.is_current().unwrap_or(false) { + return Err(HostError::Unavailable); + } if state.pending.is_some() || state.active.is_some() { return Err(HostError::Busy); } + let selection = CredentialSelection::new(&review)?; state.pending = Some(Pending::Awaiting { review: review.clone(), target, admission, + selection, }); Ok(review) } @@ -429,6 +510,14 @@ impl Host { .map(|pending| pending.review().clone()) } + /// An inspection reference cannot acquire a secret or supply native consent. + fn credential_inspection(&self, review_id: &str) -> Option { + let state = self.state.lock().ok()?; + let pending = state.pending.as_ref()?; + (pending.review().id == review_id && pending.is_current()) + .then(|| pending.selection().inspect()) + } + /// Internal readback only; future UI needs its own reviewed IPC contract. /// Current Managed admission and the original review ID must both match. pub(crate) fn completed_observation( @@ -471,6 +560,7 @@ impl Host { review, target, admission, + selection, } = pending else { unreachable!("pending phase checked before ownership transfer"); @@ -478,10 +568,14 @@ impl Host { if !admission.is_current().unwrap_or(false) { return HostStatus::Unavailable; } + if let Err(error) = selection.check() { + return HostStatus::Error(error); + } state.pending = Some(Pending::Confirmed { review, target, admission, + selection, }); HostStatus::ReadyForNativeCredential } @@ -504,6 +598,27 @@ impl Host { } } + /// Unmounted native path. Only the explicit disposable qualification target + /// calls this until production mounting receives separate acceptance. + pub(crate) fn begin_native( + &self, + review_id: &str, + parent: tauri::Window, + ) -> HostStatus { + native_input::begin(self, review_id, parent) + } + + /// Called by the single existing native window hook. It cancels only the + /// flight bound to this exact initiating window, never another window's UI. + pub(crate) fn parent_closed(&self, label: &str) { + if let Ok(state) = self.state.lock() + && let Some(active) = &state.active + && active.parent_label.as_deref() == Some(label) + { + active.cancel(); + } + } + /// Stop is safe before, during, or after a synthetic callback. A running /// callback remains counted until it itself reports a result. pub(crate) fn stop(&self) -> HostStatus { @@ -574,6 +689,69 @@ impl Host { lease: BearerLease, client: Box, ) -> HostStatus { + self.begin_callback( + review_id, + None, + CallbackStart::Confirmed, + None, + move |config, kind, control, _, _| client.run(config, lease, kind, control), + ) + } + + /// C0 is test-only: the acquirer and peer contain synthetic data only. + #[cfg(test)] + fn begin_acquisition( + &self, + inspection: &CredentialInspection, + acquirer: Option>, + client: Box, + ) -> HostStatus { + self.begin_callback( + &inspection.review.id, + Some(inspection), + CallbackStart::Confirmed, + None, + move |config, kind, control, active, selection| { + let deadline = selection.deadline; + active.bind_credential_deadline(deadline)?; + let acquisition = acquirer + .ok_or(ClientError::Source)? + .acquire(selection.claim()); + active.accept_credential(deadline)?; + let acquired = acquisition.map_err(|error| match error { + ClientError::Cancelled | ClientError::CredentialLeaseExpired => error, + _ => ClientError::Source, + })?; + let deadline = acquired.deadline(); + active.bind_credential_deadline(deadline)?; + let result = client.run(config, acquired.into_lease(), kind, control); + // A callback can outlive transport success. Expiry or cancellation + // before actual return still rejects the retained observation. + active.accept_credential(deadline)?; + result + }, + ) + } + + fn begin_callback( + &self, + review_id: &str, + inspection: Option<&CredentialInspection>, + start: CallbackStart, + parent_label: Option, + run: F, + ) -> HostStatus + where + F: FnOnce( + ClientConfig, + ReadKind, + WatchControl, + &Arc, + CredentialSelection, + ) -> Result + + Send + + 'static, + { let Ok(mut state) = self.state.lock() else { return HostStatus::Unavailable; }; @@ -583,37 +761,55 @@ impl Host { if pending.review().id != review_id { return HostStatus::Unavailable; } - if !matches!(pending, Pending::Confirmed { .. }) { + if let Some(candidate) = inspection + && !pending.selection().matches(candidate, pending.review()) + { + return HostStatus::Unavailable; + } + if !matches!( + (start, pending), + (CallbackStart::Confirmed, Pending::Confirmed { .. }) + | (CallbackStart::NativeReview, Pending::Awaiting { .. }) + ) { return HostStatus::AwaitingConsent; } let pending = state.pending.take().expect("pending checked above"); - let Pending::Confirmed { + let (Pending::Awaiting { review, target, admission, - } = pending - else { - unreachable!("pending phase checked before ownership transfer"); - }; + selection, + } + | Pending::Confirmed { + review, + target, + admission, + selection, + }) = pending; if !admission.is_current().unwrap_or(false) { return HostStatus::Unavailable; } + if let Err(error) = selection.check() { + return HostStatus::Error(error); + } let control = WatchControl::default(); - let active = Arc::new(Active::new(review.id.clone(), admission, control.clone())); + let mut active = Active::new(review.id.clone(), review.kind, admission, control.clone()); + active.parent_label = parent_label; + let active = Arc::new(active); let callback = Arc::clone(&active); let kind = review.kind; let spawned = std::thread::Builder::new() - .name("rangoon-openshell-synthetic-read".into()) + .name("rangoon-openshell-observation".into()) .spawn(move || { let completion = CallbackCompletion(callback); - let result = client - .run(target.config, lease, kind, control) - .and_then(|outcome| { + let result = run(target.config, kind, control, &completion.0, selection).and_then( + |outcome| { outcome .matches_review(&review) .then_some(outcome) .ok_or(ClientError::Source) - }); + }, + ); completion.0.finish(result); }); if spawned.is_err() { @@ -623,15 +819,113 @@ impl Host { HostStatus::Running } - #[cfg(test)] - fn status(&self) -> HostStatus { + /// Snapshot one current Managed session. This is not an IPC delivery guard. + pub(crate) fn inspect_session( + &self, + workspace: &WorkspaceRequest, + ) -> session_view::SessionView { + self.inspect_session_inner( + workspace, + #[cfg(test)] + None, + ) + } + + fn inspect_session_inner( + &self, + workspace: &WorkspaceRequest, + #[cfg(test)] probe: Option<&session_view::SnapshotProbe>, + ) -> session_view::SessionView { + use session_view::SessionView; + if !matches!(workspace, WorkspaceRequest::Managed(_)) { + return SessionView::unavailable(); + } + let Ok(admission) = workspace.admit(&self.gate, Lane::Read) else { + return SessionView::unavailable(); + }; + #[cfg(test)] + if let Some(probe) = probe { + session_view::cross_probe(&probe.before_lock); + } + // Stop and close purge use Host -> Active. Neither lock spans transport, + // toolkit dispatch, await, or a user callback. Projection is bounded. + let Ok(state) = self.state.lock() else { + return SessionView::unavailable(); + }; + if let Some(active) = state.active.as_ref() { + let Ok(active_state) = active.state.lock() else { + return SessionView::unavailable(); + }; + let candidate = match &active_state.result { + None => SessionView::phase(HostStatus::Running, Some(active.kind)), + Some(Ok(outcome)) => SessionView::completed(active.kind, outcome), + Some(Err(ClientError::Cancelled)) => { + SessionView::phase(HostStatus::Cancelled, Some(active.kind)) + } + Some(Err(error)) => { + SessionView::phase(HostStatus::Error(*error), Some(active.kind)) + } + }; + #[cfg(test)] + if let Some(probe) = probe { + session_view::cross_probe(&probe.before_final); + } + if !active.witness.is_current().unwrap_or(false) + || !admission.is_current().unwrap_or(false) + { + return SessionView::unavailable(); + } + // Last witness check above defines this instantaneous snapshot; + // cancellation is checked while both captured states stay protected. + let view = if active.cancelled.load(Ordering::Acquire) { + let phase = if active_state.result.is_none() { + HostStatus::Closing + } else { + HostStatus::Cancelled + }; + SessionView::phase(phase, Some(active.kind)) + } else { + candidate + }; + #[cfg(test)] + if let Some(probe) = probe { + session_view::cross_probe(&probe.after_final); + } + return view; + } + #[cfg(test)] + if let Some(probe) = probe { + session_view::cross_probe(&probe.before_final); + } + if !admission.is_current().unwrap_or(false) { + return SessionView::unavailable(); + } + // Pending::status performs the last retained witness check, then checks + // the immutable selection deadline. Do not cache a phase before this + // boundary: a queued inspection may outlive native review consent. + let candidate = state + .pending + .as_ref() + .map_or_else(SessionView::unavailable, |pending| { + SessionView::phase(pending.status(), Some(pending.review().kind)) + }); + #[cfg(test)] + if let Some(probe) = probe { + session_view::cross_probe(&probe.after_final); + } + candidate + } + + pub(crate) fn status(&self) -> HostStatus { let Ok(state) = self.state.lock() else { return HostStatus::Unavailable; }; match state.active.as_ref() { Some(active) => active.status(), - None if state.pending.is_some() => HostStatus::AwaitingConsent, - None => HostStatus::Unavailable, + None => state + .pending + .as_ref() + .map_or(HostStatus::Unavailable, Pending::status), } } @@ -691,3 +985,11 @@ trait SyntheticReadClient: Send + 'static { #[cfg(test)] #[path = "openshell_host_tests.rs"] mod tests; + +#[cfg(all(test, feature = "native-exit-qualification"))] +#[path = "native_exit_qualification.rs"] +pub(crate) mod native_exit_qualification; + +#[cfg(all(test, feature = "native-credential-qualification"))] +#[path = "native_credential_qualification.rs"] +pub(crate) mod native_credential_qualification; diff --git a/apps/desktop/src/openshell_host_tests.rs b/apps/desktop/src/openshell_host_tests.rs index 73b2a7d..6ab8ce0 100644 --- a/apps/desktop/src/openshell_host_tests.rs +++ b/apps/desktop/src/openshell_host_tests.rs @@ -674,6 +674,268 @@ enum CancellationPath { NativeExit, } +struct HeldSuccessfulRead { + peer: SyntheticPeer, + gate: Gate, + host: Host, + workspace: WorkspaceRequest, + review: Review, + release: mpsc::Sender<()>, + transport_result: ReadOutcome, +} + +impl HeldSuccessfulRead { + async fn start() -> Self { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::RecentLogs); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + let (returned, result_received) = tokio::sync::oneshot::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_synthetic( + &review.id, + peer_lease("test-token"), + Box::new(RealReadClient { + returned: Some(returned), + release: Some(held), + }), + ), + HostStatus::Running + ); + // This is the real client's successful result, after its runtime has + // dropped but before the host callback can return through the barrier. + let transport_result = tokio::time::timeout(Duration::from_secs(5), result_received) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(transport_result.matches_review(&review)); + assert!(matches!( + transport_result.observation, + Observation::RecentLogs(_) + )); + assert_eq!( + peer.calls().unwrap(), + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::GetSandboxLogs, + ] + ); + assert_eq!(host.status(), HostStatus::Running); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + assert!(!host.cancellation_signalled()); + Self { + peer, + gate, + host, + workspace, + review, + release, + transport_result, + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn real_client_success_waits_for_callback_before_publication() { + let HeldSuccessfulRead { + peer, + gate, + host, + workspace, + review, + release, + transport_result, + } = HeldSuccessfulRead::start().await; + release.send(()).unwrap(); + assert_eq!(real_terminal_status(&host).await, HostStatus::Completed); + assert_eq!( + host.completed_observation(&workspace, &review.id), + Some(transport_result) + ); + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!(host.stop(), HostStatus::Cancelled); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + + // Stop permits a fresh review; it does not resurrect the consumed consent. + let (_, next) = real_review(&host, &gate, &peer, ReadKind::RecentLogs); + assert_ne!(next.id, review.id); + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!(host.inspect_review(), Some(next.clone())); + assert_eq!(host.confirm(&next.id, false), HostStatus::Cancelled); + assert!(gate.request_drain().unwrap().is_quiescent().unwrap()); + assert_eq!( + peer.calls().unwrap(), + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::GetSandboxLogs, + ] + ); + peer.shutdown().await.unwrap(); +} + +async fn real_success_cancellation(path: CancellationPath) { + let HeldSuccessfulRead { + peer, + gate, + host, + workspace, + review, + release, + transport_result: _, + } = HeldSuccessfulRead::start().await; + let source = SourceAccess::close_protocol_fixture(gate.clone()); + let close = WorkspaceClose::new(source.clone()); + use crate::workspace_close::failure::{ExitAction, ExitCoordinator, route_exit_request}; + let exit = ExitCoordinator::new(); + assert_eq!( + host.prepare( + &workspace, + peer_target(&peer, "workspace-1", peer.leaf_der()), + ReadKind::RecentLogs, + Retention::SessionOnly, + ), + Err(HostError::Busy) + ); + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!( + host.begin_synthetic( + &review.id, + peer_lease("test-token"), + Box::::default(), + ), + HostStatus::Unavailable + ); + + let drain = match path { + CancellationPath::Stop => { + assert_eq!(host.stop(), HostStatus::Closing); + // The test closes Gate solely to measure outstanding custody. + // Stop itself does not claim to close workspace admission. + Some(gate.request_drain().unwrap()) + } + CancellationPath::ExitHelper => { + assert!(!host.cancel_and_check_exit()); + Some(gate.request_drain().unwrap()) + } + CancellationPath::WorkspaceClose => { + let closing = close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!(serde_json::to_value(closing).unwrap()["state"], "closing"); + None + } + CancellationPath::NativeExit => { + assert_eq!( + route_exit_request(Some(71), Some((&close, &exit)), || { + assert!(gate.observe_open().is_err()); + host.cancel_and_check_exit() + }), + ExitAction::PreventAndWait + ); + assert!(!source.request_close().unwrap().is_quiescent().unwrap()); + None + } + }; + assert!(host.cancellation_signalled()); + assert_eq!(host.status(), HostStatus::Closing); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + if let Some(drain) = &drain { + assert!(!drain.is_quiescent().unwrap()); + } + if matches!(path, CancellationPath::WorkspaceClose) { + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(false) + ); + } + release.send(()).unwrap(); + assert_eq!(real_terminal_status(&host).await, HostStatus::Cancelled); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!( + host.begin_synthetic( + &review.id, + peer_lease("test-token"), + Box::::default(), + ), + HostStatus::Unavailable + ); + if let Some(drain) = &drain { + assert!(drain.is_quiescent().unwrap()); + } + match path { + CancellationPath::WorkspaceClose => assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(true) + ), + CancellationPath::NativeExit => { + assert!(source.request_close().unwrap().is_quiescent().unwrap()); + assert_eq!( + route_exit_request(Some(71), Some((&close, &exit)), || host + .cancel_and_check_exit()), + ExitAction::PreventAndStart + ); + close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(true) + ); + assert!(close.clean_native_completion()); + assert!(exit.send(0)); + assert_eq!( + route_exit_request(Some(0), Some((&close, &exit)), || host + .cancel_and_check_exit()), + ExitAction::Pass + ); + assert_eq!( + route_exit_request(Some(0), Some((&close, &exit)), || host + .cancel_and_check_exit()), + ExitAction::Prevent + ); + } + _ => assert!(host.cancel_and_check_exit()), + } + assert_eq!(host.status(), HostStatus::Unavailable); + assert!(gate.observe_open().is_err()); + assert_eq!( + peer.calls().unwrap(), + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::GetSandboxLogs, + ] + ); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn real_client_success_stop_discards_late_observation() { + real_success_cancellation(CancellationPath::Stop).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn real_client_success_workspace_close_discards_late_observation() { + real_success_cancellation(CancellationPath::WorkspaceClose).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn real_client_success_exit_helper_discards_late_observation() { + real_success_cancellation(CancellationPath::ExitHelper).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn real_client_success_native_exit_coordinator_discards_late_observation() { + real_success_cancellation(CancellationPath::NativeExit).await; +} + async fn real_watch_cancellation(path: CancellationPath) { let peer = SyntheticPeer::start(SyntheticScenario::StalledWatch) .await @@ -751,7 +1013,7 @@ async fn real_watch_cancellation(path: CancellationPath) { .unwrap(), Err(ClientError::Cancelled) ); - assert_eq!(host.status(), HostStatus::Running); + assert_eq!(host.status(), HostStatus::Closing); if let Some(drain) = &drain { assert!(!drain.is_quiescent().unwrap()); } @@ -1058,7 +1320,14 @@ async fn real_watch_expiry_retains_callback(path: ExpiredCallbackPath) { Some(gate.request_drain().unwrap()) } }; - assert_eq!(host.status(), HostStatus::Running); + assert_eq!( + host.status(), + if matches!(path, ExpiredCallbackPath::ReturnError) { + HostStatus::Running + } else { + HostStatus::Closing + } + ); if let Some(drain) = &drain { assert!(!drain.is_quiescent().unwrap()); } @@ -1204,6 +1473,92 @@ fn consent_is_one_shot_and_production_start_stays_closed() { assert_eq!(host.inspect_review(), Some(review)); } +#[test] +fn pending_status_tracks_confirmation_without_consuming_or_dispatching() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::RecentLogs); + assert_eq!(host.status(), HostStatus::AwaitingConsent); + assert_eq!( + host.confirm("foreign-review", true), + HostStatus::Unavailable + ); + assert_eq!(host.status(), HostStatus::AwaitingConsent); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + for _ in 0..3 { + assert_eq!(host.status(), HostStatus::ReadyForNativeCredential); + assert_eq!(host.inspect_review(), Some(review.clone())); + assert_eq!(host.begin_production(&review.id), HostStatus::Unavailable); + } + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!(host.stop(), HostStatus::Cancelled); + assert_eq!(host.status(), HostStatus::Unavailable); + assert_eq!(host.inspect_review(), None); +} + +#[test] +fn pending_status_reports_expiry_without_releasing_retained_custody() { + for confirmed in [false, true] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::RecentLogs); + if confirmed { + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + } + { + let mut state = host.state.lock().unwrap(); + let selection = match state.pending.as_mut().unwrap() { + Pending::Awaiting { selection, .. } | Pending::Confirmed { selection, .. } => { + selection + } + }; + selection.deadline = Instant::now() - Duration::from_secs(1); + } + for _ in 0..3 { + assert_eq!( + host.status(), + HostStatus::Error(ClientError::CredentialLeaseExpired) + ); + assert!(host.state.lock().unwrap().pending.is_some()); + assert!(host.state.lock().unwrap().active.is_none()); + } + let drain = gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + assert_eq!(host.status(), HostStatus::Unavailable); + assert_eq!(host.stop(), HostStatus::Cancelled); + assert!(drain.is_quiescent().unwrap()); + assert_eq!(host.status(), HostStatus::Unavailable); + } +} + +#[test] +fn pending_status_refuses_stale_generation_in_both_consent_phases() { + for confirmed in [false, true] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::PolicyStatus); + if confirmed { + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + } + let drain = gate.request_drain().unwrap(); + assert_eq!(host.status(), HostStatus::Unavailable); + assert_eq!(host.inspect_review(), None); + assert!(host.state.lock().unwrap().pending.is_some()); + assert!(!drain.is_quiescent().unwrap()); + assert_eq!(host.stop(), HostStatus::Cancelled); + assert!(drain.is_quiescent().unwrap()); + } +} + #[test] fn refusal_and_replayed_review_release_admission() { let gate = Gate::new(); @@ -1220,6 +1575,70 @@ fn refusal_and_replayed_review_release_admission() { assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); } +#[test] +fn preparation_publication_after_close_purge_releases_stale_admission() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let close = WorkspaceClose::new(SourceAccess::close_protocol_fixture(gate.clone())); + let workspace = WorkspaceRequest::Managed(Arc::new(gate.observe_open().unwrap())); + let admission = workspace.admit(&gate, Lane::Read).unwrap(); + assert!(admission.is_current().unwrap()); + + // Pause the real preparation flow at its admission/publication boundary. + // Close fences the same Gate and purges the same Host before publication. + let closing = close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!(serde_json::to_value(closing).unwrap()["state"], "closing"); + assert_eq!(host.inspect_review(), None); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(false) + ); + + let publication = host.retain_review( + admission, + target(), + ReadKind::RecentWatch, + Retention::SessionOnly, + ); + let retained = host.state.lock().unwrap().pending.is_some(); + let completed = close.progress_native(|drained| host.purge_for_workspace_close(drained)); + assert_eq!( + (publication.map(|_| ()), retained, completed), + (Err(HostError::Unavailable), false, Ok(true)) + ); + assert_eq!(host.inspect_review(), None); + assert!(gate.observe_open().is_err()); +} + +#[test] +fn published_pending_review_is_purged_before_native_close_completes() { + for confirmed in [false, true] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let close = WorkspaceClose::new(SourceAccess::close_protocol_fixture(gate.clone())); + let review = prepare(&host, &gate, ReadKind::RecentWatch); + if confirmed { + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + } + assert_eq!(host.inspect_review(), Some(review.clone())); + + let closing = close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!(serde_json::to_value(closing).unwrap()["state"], "closing"); + assert_eq!(host.inspect_review(), None); + assert!(host.state.lock().unwrap().pending.is_none()); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(true) + ); + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!(host.begin_production(&review.id), HostStatus::Unavailable); + assert!(gate.observe_open().is_err()); + } +} + #[test] fn workspace_drain_invalidates_pending_review_before_consent() { let gate = Gate::new(); @@ -1666,7 +2085,7 @@ fn workspace_close_coordinator_waits_for_active_callback_before_native_completio close.progress_native(|drained| host.purge_for_workspace_close(drained)), Ok(false) ); - assert_eq!(host.status(), HostStatus::Running); + assert_eq!(host.status(), HostStatus::Closing); release.send(()).unwrap(); assert_eq!(finish_status(&host), HostStatus::Cancelled); @@ -1677,3 +2096,359 @@ fn workspace_close_coordinator_waits_for_active_callback_before_native_completio assert_eq!(host.status(), HostStatus::Unavailable); assert!(gate.observe_open().is_err()); } + +#[test] +fn native_review_callback_holds_admission_and_binds_only_its_parent() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + let original_deadline = match host.state.lock().unwrap().pending.as_ref().unwrap() { + Pending::Awaiting { selection, .. } => selection.deadline, + Pending::Confirmed { .. } => unreachable!("new review must await native consent"), + }; + assert_eq!( + host.begin_callback( + &review.id, + None, + CallbackStart::Confirmed, + None, + |_, _, _, _, _| Err(ClientError::Source), + ), + HostStatus::AwaitingConsent + ); + assert_eq!(host.inspect_review(), Some(review.clone())); + assert_eq!( + host.begin_callback( + "wrong-review", + None, + CallbackStart::NativeReview, + Some("native-parent".into()), + |_, _, _, _, _| Err(ClientError::Source), + ), + HostStatus::Unavailable + ); + assert_eq!(host.inspect_review(), Some(review.clone())); + + let (entered, started) = mpsc::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_callback( + &review.id, + None, + CallbackStart::NativeReview, + Some("native-parent".into()), + move |_, _, _, active, selection| { + entered.send(selection.deadline).unwrap(); + let _ = held.recv(); + active.accept_credential(selection.deadline)?; + Err(ClientError::Cancelled) + }, + ), + HostStatus::Running + ); + assert_eq!( + started.recv_timeout(Duration::from_secs(1)).unwrap(), + original_deadline + ); + assert_eq!(host.confirm(&review.id, true), HostStatus::Unavailable); + assert_eq!( + host.begin_callback( + &review.id, + None, + CallbackStart::NativeReview, + Some("native-parent".into()), + |_, _, _, _, _| Err(ClientError::Source), + ), + HostStatus::Unavailable + ); + host.parent_closed("other-parent"); + assert!(!host.cancellation_signalled()); + assert_eq!(host.status(), HostStatus::Running); + host.parent_closed("native-parent"); + assert!(host.cancellation_signalled()); + assert_eq!(host.status(), HostStatus::Closing); + let drain = gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + + release.send(()).unwrap(); + assert_eq!(finish_status(&host), HostStatus::Cancelled); + assert!(drain.is_quiescent().unwrap()); + assert_eq!(host.stop(), HostStatus::Cancelled); +} + +#[path = "openshell_credential_tests.rs"] +mod credential_binding; + +#[test] +fn native_fixture_input_rejects_and_clears_every_non_fixture_value_before_client() { + use zeroize::Zeroizing; + for value in [ + "", + "credential-example", + " test-token", + "test-token ", + "test-token\n", + "TEST-TOKEN", + ] { + let mut held = Zeroizing::new(value.to_owned()); + assert_eq!( + super::native_input::validate_fixture_input(&mut held), + Err(ClientError::InvalidConfiguration) + ); + assert!( + held.is_empty(), + "rejected owned input must be cleared before returning" + ); + } + let mut accepted = Zeroizing::new("test-token".to_owned()); + assert_eq!( + super::native_input::validate_fixture_input(&mut accepted), + Ok(()) + ); + assert_eq!(accepted.as_str(), "test-token"); +} + +// This enters after native confirmation/input. It only exercises the shared +// post-input tail used by that callback; no test constructs a native widget. +fn begin_fixture_post_input_callback( + host: &Host, + review: &Review, + value: String, + read: F, +) -> HostStatus +where + F: FnOnce( + ClientConfig, + BearerLease, + ReadKind, + WatchControl, + ) -> Result + + Send + + 'static, +{ + host.begin_callback( + &review.id, + None, + CallbackStart::NativeReview, + Some("fixture-native-parent".into()), + move |config, kind, control, active, selection| { + super::native_input::finish_after_native_input( + active, + selection.claim(), + zeroize::Zeroizing::new(value), + None, + |lease| read(config, lease, kind, control), + ) + }, + ) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_fixture_post_input_tail_seals_and_reads_only_after_exact_marker() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let reader_started = Arc::new(AtomicUsize::new(0)); + let reader_callback = Arc::clone(&reader_started); + assert_eq!( + begin_fixture_post_input_callback( + &host, + &review, + "test-token".to_owned(), + move |config, lease, kind, control| { + reader_callback.fetch_add(1, Ordering::SeqCst); + super::native_input::read_once(config, lease, kind, control) + }, + ), + HostStatus::Running + ); + assert_eq!(real_terminal_status(&host).await, HostStatus::Completed); + assert_eq!(reader_started.load(Ordering::SeqCst), 1); + assert_eq!( + peer.calls().unwrap(), + vec![SyntheticRpc::Health, SyntheticRpc::GetSandboxPolicyStatus] + ); + assert!(host.completed_observation(&workspace, &review.id).is_some()); + assert_eq!( + begin_fixture_post_input_callback(&host, &review, "test-token".to_owned(), |_, _, _, _| { + Err(ClientError::Source) + }), + HostStatus::Unavailable + ); + let drain = gate.request_drain().unwrap(); + assert!(drain.is_quiescent().unwrap()); + assert!(host.cancel_and_check_exit()); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_fixture_post_input_tail_rejects_non_markers_before_reader() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + for value in [ + "".to_owned(), + "credential-example".to_owned(), + " test-token".to_owned(), + "test-token ".to_owned(), + "test-token\n".to_owned(), + "TEST-TOKEN".to_owned(), + "tést-token".to_owned(), + "x".repeat(16 * 1024 + 1), + ] { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let reader_started = Arc::new(AtomicUsize::new(0)); + let reader_callback = Arc::clone(&reader_started); + assert_eq!( + begin_fixture_post_input_callback( + &host, + &review, + value, + move |config, lease, kind, control| { + reader_callback.fetch_add(1, Ordering::SeqCst); + super::native_input::read_once(config, lease, kind, control) + }, + ), + HostStatus::Running + ); + assert_eq!( + real_terminal_status(&host).await, + HostStatus::Error(ClientError::InvalidConfiguration) + ); + assert_eq!(reader_started.load(Ordering::SeqCst), 0); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + assert!(peer.calls().unwrap().is_empty()); + assert_eq!( + begin_fixture_post_input_callback( + &host, + &review, + "test-token".to_owned(), + |_, _, _, _| { Err(ClientError::Source) } + ), + HostStatus::Unavailable + ); + let drain = gate.request_drain().unwrap(); + assert!(drain.is_quiescent().unwrap()); + assert!(host.cancel_and_check_exit()); + peer.shutdown().await.unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_fixture_post_input_tail_stop_before_tail_refuses_valid_marker() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let reader_started = Arc::new(AtomicUsize::new(0)); + let reader_callback = Arc::clone(&reader_started); + let (entered, started) = mpsc::channel(); + let (release, held) = mpsc::channel(); + assert_eq!( + host.begin_callback( + &review.id, + None, + CallbackStart::NativeReview, + Some("fixture-native-parent".into()), + move |config, kind, control, active, selection| { + entered.send(()).unwrap(); + let value = held.recv().map_err(|_| ClientError::Source)?; + super::native_input::finish_after_native_input( + active, + selection.claim(), + zeroize::Zeroizing::new(value), + None, + |lease| { + reader_callback.fetch_add(1, Ordering::SeqCst); + super::native_input::read_once(config, lease, kind, control) + }, + ) + }, + ), + HostStatus::Running + ); + started.recv_timeout(Duration::from_secs(1)).unwrap(); + assert_eq!(host.stop(), HostStatus::Closing); + let drain = gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + release.send("test-token".to_owned()).unwrap(); + assert_eq!(real_terminal_status(&host).await, HostStatus::Cancelled); + assert_eq!(reader_started.load(Ordering::SeqCst), 0); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + assert!(peer.calls().unwrap().is_empty()); + assert_eq!( + begin_fixture_post_input_callback(&host, &review, "test-token".to_owned(), |_, _, _, _| { + Err(ClientError::Source) + },), + HostStatus::Unavailable + ); + assert!(drain.is_quiescent().unwrap()); + assert!(host.cancel_and_check_exit()); + peer.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_fixture_post_input_tail_expired_received_selection_never_reads() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let (workspace, review) = real_review(&host, &gate, &peer, ReadKind::ProtectedCheck); + let reader_started = Arc::new(AtomicUsize::new(0)); + let reader_callback = Arc::clone(&reader_started); + assert_eq!( + host.begin_callback( + &review.id, + None, + CallbackStart::NativeReview, + Some("fixture-native-parent".into()), + move |config, kind, control, active, mut selection| { + selection.deadline = Instant::now() - Duration::from_secs(1); + super::native_input::finish_after_native_input( + active, + selection.claim(), + zeroize::Zeroizing::new("test-token".to_owned()), + None, + |lease| { + reader_callback.fetch_add(1, Ordering::SeqCst); + super::native_input::read_once(config, lease, kind, control) + }, + ) + }, + ), + HostStatus::Running + ); + assert_eq!( + real_terminal_status(&host).await, + HostStatus::Error(ClientError::CredentialLeaseExpired) + ); + assert_eq!(reader_started.load(Ordering::SeqCst), 0); + assert_eq!(host.completed_observation(&workspace, &review.id), None); + assert!(peer.calls().unwrap().is_empty()); + assert_eq!( + begin_fixture_post_input_callback(&host, &review, "test-token".to_owned(), |_, _, _, _| { + Err(ClientError::Source) + }), + HostStatus::Unavailable + ); + let drain = gate.request_drain().unwrap(); + assert!(drain.is_quiescent().unwrap()); + assert!(host.cancel_and_check_exit()); + peer.shutdown().await.unwrap(); +} diff --git a/apps/desktop/src/openshell_native_input.rs b/apps/desktop/src/openshell_native_input.rs new file mode 100644 index 0000000..dc4fd8b --- /dev/null +++ b/apps/desktop/src/openshell_native_input.rs @@ -0,0 +1,238 @@ +//! Shared, unmounted native review -> input -> finite read callback. +//! No renderer, secret store or provider discovery participates in this path. +use super::*; +use rangoon_native_credential_input::{InputError, InputGuard, ReadMethod, ReviewDisplay}; +use rangoon_openshell_client::OpenShellReadClient; +use std::time::{Duration, Instant}; +use tauri::{Runtime, Window}; +use zeroize::{Zeroize, Zeroizing}; + +struct Guard { + active: Arc, + deadline: Instant, + observer: Option, +} + +impl InputGuard for Guard { + fn check(&self) -> Result<(), InputError> { + self.active + .accept_credential(self.deadline) + .map_err(|error| match error { + ClientError::CredentialLeaseExpired => InputError::Expired, + ClientError::Cancelled => InputError::Cancelled, + _ => InputError::Unavailable, + }) + } + + fn review_queued(&self) { + notify_phase(self.observer.as_ref(), NativePhase::ReviewQueued); + } + + fn input_presented(&self) { + notify_phase(self.observer.as_ref(), NativePhase::InputPresented); + } +} + +// Qualification observers are diagnostics only. A failed observer must not +// unwind across an already queued native callback and release Host custody. +fn notify_phase(observer: Option<&Observer>, phase: NativePhase) { + if let Some(observer) = observer { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| observer(phase))); + } +} + +#[test] +fn diagnostic_observer_failure_does_not_unwind_callback_custody() { + let seen = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = Arc::clone(&seen); + let observer: Observer = Arc::new(move |phase| { + assert_eq!(phase.code(), "native_review_queued"); + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + panic!("synthetic diagnostic failure"); + }); + notify_phase(None, NativePhase::ReviewQueued); + notify_phase(Some(&observer), NativePhase::ReviewQueued); + assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1); +} + +fn map_error(error: InputError) -> ClientError { + match error { + InputError::Expired => ClientError::CredentialLeaseExpired, + InputError::Cancelled | InputError::ParentClosed => ClientError::Cancelled, + InputError::InvalidInput => ClientError::InvalidConfiguration, + InputError::Unavailable | InputError::Busy => ClientError::Source, + } +} + +#[derive(Clone, Copy)] +pub(super) enum NativePhase { + ReviewQueued, + ReviewAccepted, + InputQueued, + InputPresented, + InputAccepted, + ReadReturned, +} +impl NativePhase { + pub(super) fn code(self) -> &'static str { + match self { + Self::ReviewQueued => "native_review_queued", + Self::ReviewAccepted => "native_review_accepted", + Self::InputQueued => "native_input_queued", + Self::InputPresented => "native_input_presented", + Self::InputAccepted => "native_input_accepted", + Self::ReadReturned => "read_returned", + } + } +} +pub(super) type Observer = Arc; + +/// C1-M is limited to the disposable fixture marker. This guard applies to +/// the shared native callback, before a lease or client can be constructed. +/// Removing it for real credentials requires a separately qualified mounting +/// packet. It is not a token parser or an authorization decision. +pub(super) fn validate_fixture_input(value: &mut Zeroizing) -> Result<(), ClientError> { + if value.as_str() != "test-token" { + value.zeroize(); + Err(ClientError::InvalidConfiguration) + } else { + Ok(()) + } +} + +/// The native callback and source regressions share this post-input boundary. +/// Refusal drops the owned input without reaching credential sealing or the +/// reader. This seam does not supply native confirmation or create a claim. +pub(super) fn finish_after_native_input( + active: &Arc, + claim: credential::CredentialClaim, + mut value: Zeroizing, + observer: Option<&Observer>, + read: impl FnOnce(rangoon_openshell_client::BearerLease) -> Result, +) -> Result { + let deadline = claim.deadline(); + active.accept_credential(deadline)?; + notify_phase(observer, NativePhase::InputAccepted); + validate_fixture_input(&mut value)?; + let acquired = claim.seal(value, None)?; + active.bind_credential_deadline(acquired.deadline())?; + let result = read(acquired.into_lease()); + notify_phase(observer, NativePhase::ReadReturned); + active.accept_credential(deadline)?; + result +} + +pub(super) fn begin(host: &Host, review_id: &str, parent: Window) -> HostStatus { + begin_inner(host, review_id, parent, None) +} + +/// Qualification observes fixed phase boundaries only. It cannot supply +/// confirmation, credentials, results or a replacement custody implementation. +#[cfg(all(test, feature = "native-credential-qualification"))] +pub(super) fn begin_observed( + host: &Host, + review_id: &str, + parent: Window, + observer: Observer, +) -> HostStatus { + begin_inner(host, review_id, parent, Some(observer)) +} + +fn begin_inner( + host: &Host, + review_id: &str, + parent: Window, + observer: Option, +) -> HostStatus { + let Some(review) = host + .inspect_review() + .filter(|review| review.id == review_id) + else { + return HostStatus::Unavailable; + }; + let label = parent.label().to_owned(); + host.begin_callback( + review_id, + None, + CallbackStart::NativeReview, + Some(label), + move |config, kind, control, active, selection| { + let deadline = selection.deadline; + active.bind_credential_deadline(deadline)?; + // Clone only the exact existing flight Arc, never admission, selection + // or credential custody. Native UI checks this same Host generation. + let guard = Guard { + active: Arc::clone(active), + deadline, + observer: observer.clone(), + }; + let guard: Arc = Arc::new(guard); + let display = ReviewDisplay { + origin: review.origin.clone(), + selected_peer: review.selected_peer.to_string(), + installation: review.installation.clone(), + workspace: review.workspace.clone(), + sandbox: review.sandbox.clone(), + product_version: review.product_version.to_owned(), + root_sha256: review.root_sha256.clone(), + peer_sha256: review.peer_pin_sha256.clone(), + method: match kind { + ReadKind::ProtectedCheck => ReadMethod::ProtectedCheck, + ReadKind::PolicyStatus => ReadMethod::PolicyStatus, + ReadKind::RecentLogs => ReadMethod::RecentLogs, + ReadKind::RecentWatch => ReadMethod::RecentWatch, + }, + }; + let notify = |phase| notify_phase(observer.as_ref(), phase); + rangoon_native_credential_input::confirm(parent.clone(), display, Arc::clone(&guard)) + .map_err(map_error)?; + active.accept_credential(deadline)?; + notify(NativePhase::ReviewAccepted); + let claim = selection.claim(); // never consumed before real native confirmation + notify(NativePhase::InputQueued); + let value = + rangoon_native_credential_input::acquire(parent, guard).map_err(map_error)?; + finish_after_native_input( + active, + claim, + value.into_value(), + observer.as_ref(), + |lease| read_once(config, lease, kind, control), + ) + }, + ) +} + +pub(super) fn read_once( + config: ClientConfig, + lease: rangoon_openshell_client::BearerLease, + kind: ReadKind, + control: WatchControl, +) -> Result { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| ClientError::Source)?; + let result = runtime.block_on(async move { + let mut client = OpenShellReadClient::connect(config, lease).await?; + let protected_check = client.check_protected_read().await?; + let observation = match kind { + ReadKind::ProtectedCheck => Observation::ProtectedCheck(protected_check.clone()), + ReadKind::PolicyStatus => { + Observation::PolicyStatus(client.read_policy_status(0).await?) + } + ReadKind::RecentLogs => Observation::RecentLogs(client.read_recent_logs().await?), + ReadKind::RecentWatch => Observation::RecentWatch( + client + .watch_recent(&control, None, Duration::from_secs(30)) + .await?, + ), + }; + Ok(ReadOutcome { + protected_check, + observation, + }) + }); + drop(runtime); + result +} diff --git a/apps/desktop/src/openshell_session_view.rs b/apps/desktop/src/openshell_session_view.rs new file mode 100644 index 0000000..5496046 --- /dev/null +++ b/apps/desktop/src/openshell_session_view.rs @@ -0,0 +1,450 @@ +//! App-private, minimized display of one instantaneous native session. +//! No provider record, target, credential or inbound replacement is serializable. +use super::{HostStatus, Observation, PRODUCT_VERSION, ReadKind, ReadOutcome}; +use rangoon_openshell_client::{ + ClientError, Continuity, HealthStatus, Loss, PolicyLoadStatus, ProducerKind, WatchEventKind, +}; +use serde::Serialize; +use std::io::{self, Write}; + +const MAX_ENCODED_BYTES: usize = 8_192; +const MAX_REVISIONS: usize = 64; +const MAX_LOG_LINES: usize = 64; +const MAX_WATCH_EVENTS: usize = 128; +const MAX_LOSSES: usize = 12; + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct SessionView { + schema: &'static str, + provider: &'static str, + product_version: &'static str, + phase: Phase, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + read_kind: Option, + start_available: bool, + retention: &'static str, + provenance: Provenance, + #[serde(skip_serializing_if = "Option::is_none")] + observation: Option, +} + +#[derive(Clone, Copy, Serialize)] +#[serde(rename_all = "snake_case")] +enum Phase { + Unavailable, + AwaitingConsent, + ReadyForNativeCredential, + Running, + Closing, + Cancelled, + Completed, + Error, +} + +#[derive(Clone, Copy, Serialize)] +#[serde(rename_all = "snake_case")] +enum SelectedRead { + ProtectedCheck, + PolicyStatus, + RecentLogs, + RecentWatch, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Provenance { + authenticity: &'static str, + authority: &'static str, + execution: &'static str, + action_outcome: &'static str, + coverage: &'static str, + omissions: [&'static str; 5], +} + +#[derive(Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum Summary { + #[serde(rename_all = "camelCase")] + ProtectedCheck { + health: Health, + policy_load: LoadState, + }, + #[serde(rename_all = "camelCase")] + PolicyStatus { + active_version: u32, + queried_version: u32, + load_state: LoadState, + revision_count: usize, + }, + #[serde(rename_all = "camelCase")] + RecentLogs { + returned_line_count: u32, + provider_buffer_total: u32, + }, + #[serde(rename_all = "camelCase")] + RecentWatch { + event_count: usize, + kinds: EventCounts, + producers: ProducerCounts, + producer_absent_count: usize, + continuity: WindowContinuity, + loss_reasons: Vec, + }, +} + +#[derive(Serialize)] +#[serde(rename_all = "snake_case")] +enum Health { + Unspecified, + Healthy, + Degraded, + Unhealthy, + Unknown, +} + +#[derive(Serialize)] +#[serde(rename_all = "snake_case")] +enum LoadState { + Unspecified, + Pending, + Loaded, + Failed, + Superseded, + Unknown, +} + +#[derive(Default, Serialize)] +struct EventCounts { + status: usize, + log: usize, + platform: usize, + warning: usize, +} + +#[derive(Default, Serialize)] +struct ProducerCounts { + gateway: usize, + sandbox: usize, + kubernetes: usize, + docker: usize, + process: usize, + unknown: usize, +} + +#[derive(Serialize)] +#[serde(rename_all = "snake_case")] +enum WindowContinuity { + Bounded, + Gap, +} + +#[derive(Clone, Copy, Serialize)] +#[serde(rename_all = "snake_case")] +enum LossReason { + PolicyHashMissing, + PolicyHashInvalid, + PolicyBodyRedacted, + PolicyLoadErrorRedacted, + PolicyProvenanceRedacted, + LogTextRedacted, + LogFieldsRedacted, + PlatformTextRedacted, + ProducerInferredFromLegacyEmpty, + ProducerUnrecognized, + MissingNativeEventId, + StreamWarning, +} + +impl SessionView { + pub(super) fn unavailable() -> Self { + Self::phase(HostStatus::Unavailable, None) + } + + /// Non-completed phases never carry a summary. A bare Completed is invalid. + pub(super) fn phase(status: HostStatus, kind: Option) -> Self { + let (phase, error) = match status { + HostStatus::Unavailable | HostStatus::Completed => (Phase::Unavailable, None), + HostStatus::AwaitingConsent => (Phase::AwaitingConsent, None), + HostStatus::ReadyForNativeCredential => (Phase::ReadyForNativeCredential, None), + HostStatus::Running => (Phase::Running, None), + HostStatus::Closing => (Phase::Closing, None), + HostStatus::Cancelled => (Phase::Cancelled, None), + HostStatus::Error(error) => (Phase::Error, Some(error.code())), + }; + let read_kind = if matches!(phase, Phase::Unavailable) { + None + } else { + kind.map(SelectedRead::from) + }; + Self { + schema: "rangoon.openshell.session-view.v1", + provider: "openshell", + product_version: PRODUCT_VERSION, + phase, + error, + read_kind, + start_available: false, + retention: "session_only", + provenance: Provenance { + authenticity: "unqualified", + authority: "none", + execution: "unavailable", + action_outcome: "unknown", + coverage: "bounded_partial", + omissions: [ + "native_identifiers", + "source_timestamps", + "policy_hashes", + "provider_payloads", + "target_and_credential_references", + ], + }, + observation: None, + } + } + + pub(super) fn completed(kind: ReadKind, outcome: &ReadOutcome) -> Self { + match Summary::from_outcome(kind, outcome) { + Ok(summary) => { + let mut view = Self::phase(HostStatus::Running, Some(kind)); + view.phase = Phase::Completed; + view.observation = Some(summary); + // Bound even app-private schema growth before publishing a view. + if view.encode().is_err() { + return Self::phase(HostStatus::Error(ClientError::Bounds), Some(kind)); + } + view + } + Err(error) => Self::phase(HostStatus::Error(error), Some(kind)), + } + } + + /// Bounded in-memory encoding; failure returns no prefix or partial JSON. + pub(crate) fn encode(&self) -> Result, ClientError> { + let mut writer = BoundedJson(Vec::new()); + serde_json::to_writer(&mut writer, self).map_err(|_| ClientError::Bounds)?; + Ok(writer.0) + } +} + +impl Summary { + fn from_outcome(kind: ReadKind, outcome: &ReadOutcome) -> Result { + let check = &outcome.protected_check; + if check.reported_product_version != PRODUCT_VERSION + || !matches!(check.health, HealthStatus::Healthy | HealthStatus::Degraded) + { + return Err(ClientError::Source); + } + bounded_losses(&check.protected_read.losses)?; + let scope_matches = |installation: &str, workspace: &str, sandbox: &str| { + check.installation == installation + && check.workspace == workspace + && check.sandbox == sandbox + }; + match (&outcome.observation, kind) { + (Observation::ProtectedCheck(value), ReadKind::ProtectedCheck) if value == check => { + Ok(Self::ProtectedCheck { + health: Health::from(value.health), + policy_load: LoadState::from(value.protected_read.status), + }) + } + (Observation::PolicyStatus(value), ReadKind::PolicyStatus) + if scope_matches(&value.installation, &value.workspace, &value.sandbox) => + { + if value.revisions.len() > MAX_REVISIONS { + return Err(ClientError::Bounds); + } + bounded_losses(&value.queried.losses)?; + for revision in &value.revisions { + bounded_losses(&revision.losses)?; + } + Ok(Self::PolicyStatus { + active_version: value.active_version, + queried_version: value.queried.version, + load_state: LoadState::from(value.queried.status), + revision_count: value.revisions.len(), + }) + } + (Observation::RecentLogs(value), ReadKind::RecentLogs) + if scope_matches(&value.installation, &value.workspace, &value.sandbox) => + { + let count = value.line_count as usize; + if count > MAX_LOG_LINES + || value.source_times_millis.len() != count + || value.producers.len() != count + { + return Err(ClientError::Bounds); + } + bounded_losses(&value.losses)?; + Ok(Self::RecentLogs { + returned_line_count: value.line_count, + provider_buffer_total: value.buffer_total, + }) + } + (Observation::RecentWatch(value), ReadKind::RecentWatch) + if scope_matches(&value.installation, &value.workspace, &value.sandbox) => + { + if value.events.len() > MAX_WATCH_EVENTS { + return Err(ClientError::Bounds); + } + let mut kinds = EventCounts::default(); + let mut producers = ProducerCounts::default(); + let mut producer_absent_count = 0; + let mut seen_losses = [false; MAX_LOSSES]; + for event in &value.events { + bounded_losses(&event.losses)?; + match event.kind { + WatchEventKind::Status => kinds.status += 1, + WatchEventKind::Log => kinds.log += 1, + WatchEventKind::Platform => kinds.platform += 1, + WatchEventKind::Warning => kinds.warning += 1, + } + match event.producer { + Some(ProducerKind::Gateway) => producers.gateway += 1, + Some(ProducerKind::Sandbox) => producers.sandbox += 1, + Some(ProducerKind::Kubernetes) => producers.kubernetes += 1, + Some(ProducerKind::Docker) => producers.docker += 1, + Some(ProducerKind::Process) => producers.process += 1, + Some(ProducerKind::Unknown) => producers.unknown += 1, + None => producer_absent_count += 1, + } + for loss in &event.losses { + seen_losses[loss_index(*loss)] = true; + } + } + if kinds.warning != 0 && value.continuity != Continuity::Gap { + return Err(ClientError::Source); + } + let loss_reasons = LOSS_REASONS + .into_iter() + .enumerate() + .filter_map(|(index, reason)| seen_losses[index].then_some(reason)) + .collect(); + Ok(Self::RecentWatch { + event_count: value.events.len(), + kinds, + producers, + producer_absent_count, + continuity: match value.continuity { + Continuity::Bounded => WindowContinuity::Bounded, + Continuity::Gap => WindowContinuity::Gap, + }, + loss_reasons, + }) + } + _ => Err(ClientError::Source), + } + } +} + +fn bounded_losses(losses: &[Loss]) -> Result<(), ClientError> { + if losses.len() > MAX_LOSSES { + Err(ClientError::Bounds) + } else { + Ok(()) + } +} + +impl From for SelectedRead { + fn from(value: ReadKind) -> Self { + match value { + ReadKind::ProtectedCheck => Self::ProtectedCheck, + ReadKind::PolicyStatus => Self::PolicyStatus, + ReadKind::RecentLogs => Self::RecentLogs, + ReadKind::RecentWatch => Self::RecentWatch, + } + } +} +impl From for Health { + fn from(value: HealthStatus) -> Self { + match value { + HealthStatus::Unspecified => Self::Unspecified, + HealthStatus::Healthy => Self::Healthy, + HealthStatus::Degraded => Self::Degraded, + HealthStatus::Unhealthy => Self::Unhealthy, + HealthStatus::Unknown => Self::Unknown, + } + } +} +impl From for LoadState { + fn from(value: PolicyLoadStatus) -> Self { + match value { + PolicyLoadStatus::Unspecified => Self::Unspecified, + PolicyLoadStatus::Pending => Self::Pending, + PolicyLoadStatus::Loaded => Self::Loaded, + PolicyLoadStatus::Failed => Self::Failed, + PolicyLoadStatus::Superseded => Self::Superseded, + PolicyLoadStatus::Unknown => Self::Unknown, + } + } +} + +const LOSS_REASONS: [LossReason; MAX_LOSSES] = [ + LossReason::PolicyHashMissing, + LossReason::PolicyHashInvalid, + LossReason::PolicyBodyRedacted, + LossReason::PolicyLoadErrorRedacted, + LossReason::PolicyProvenanceRedacted, + LossReason::LogTextRedacted, + LossReason::LogFieldsRedacted, + LossReason::PlatformTextRedacted, + LossReason::ProducerInferredFromLegacyEmpty, + LossReason::ProducerUnrecognized, + LossReason::MissingNativeEventId, + LossReason::StreamWarning, +]; +fn loss_index(value: Loss) -> usize { + match value { + Loss::PolicyHashMissing => 0, + Loss::PolicyHashInvalid => 1, + Loss::PolicyBodyRedacted => 2, + Loss::PolicyLoadErrorRedacted => 3, + Loss::PolicyProvenanceRedacted => 4, + Loss::LogTextRedacted => 5, + Loss::LogFieldsRedacted => 6, + Loss::PlatformTextRedacted => 7, + Loss::ProducerInferredFromLegacyEmpty => 8, + Loss::ProducerUnrecognized => 9, + Loss::MissingNativeEventId => 10, + Loss::StreamWarning => 11, + } +} + +struct BoundedJson(Vec); +impl Write for BoundedJson { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if bytes.len() > MAX_ENCODED_BYTES.saturating_sub(self.0.len()) { + return Err(io::Error::other("session view exceeds encoded bound")); + } + self.0.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(test)] +#[derive(Default)] +pub(super) struct SnapshotProbe { + pub(super) before_lock: Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>, + pub(super) before_final: Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>, + pub(super) after_final: Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>, +} +#[cfg(test)] +pub(super) fn cross_probe( + boundary: &Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>, +) { + if let Some((entered, release)) = boundary { + let _ = entered.send(()); + // Sender drop also releases a test that unwinds; never wait forever. + let _ = release.recv_timeout(std::time::Duration::from_secs(10)); + } +} + +#[cfg(test)] +#[path = "openshell_session_view_tests.rs"] +mod tests; diff --git a/apps/desktop/src/openshell_session_view_tests.rs b/apps/desktop/src/openshell_session_view_tests.rs new file mode 100644 index 0000000..e096581 --- /dev/null +++ b/apps/desktop/src/openshell_session_view_tests.rs @@ -0,0 +1,956 @@ +use super::super::{ + Host, HostStatus, Observation, PRODUCT_VERSION, ProposedTarget, ReadKind, ReadOutcome, + Retention, SyntheticReadClient, +}; +use super::*; +use crate::{SourceAccess, workspace_close::WorkspaceClose, workspace_requests::WorkspaceRequest}; +use rangoon_desktop::workspace_lifecycle::Gate; +use rangoon_openshell_client::{ + Authenticity, BearerLease, ClientConfig, ClientError, ConnectionCheck, Continuity, + HealthStatus, LogWindow, OpenShellReadClient, PolicyLoadStatus, PolicyRead, PolicyRevision, + ProducerKind, WatchControl, WatchEvent, WatchEventKind, WatchWindow, +}; +use serde_json::{Value, json}; +use std::{ + io::Write, + net::{IpAddr, Ipv4Addr, SocketAddr}, + sync::{Arc, mpsc}, + time::{Duration, Instant}, +}; + +const WAIT: Duration = Duration::from_secs(3); + +fn target() -> ProposedTarget { + ProposedTarget::new( + "https://openshell.test".into(), + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 443), + "installation-canary".into(), + "workspace-canary".into(), + "sandbox-canary".into(), + b"root-canary".to_vec(), + b"leaf-canary".to_vec(), + ) + .unwrap() +} + +fn workspace(gate: &Gate) -> WorkspaceRequest { + WorkspaceRequest::Managed(Arc::new(gate.observe_open().unwrap())) +} + +fn prepare(host: &Host, gate: &Gate, kind: ReadKind) -> super::super::Review { + host.prepare(&workspace(gate), target(), kind, Retention::SessionOnly) + .unwrap() +} + +fn lease() -> BearerLease { + BearerLease::new( + "test-token".into(), + Instant::now() + Duration::from_secs(30), + ) + .unwrap() +} + +fn check() -> ConnectionCheck { + ConnectionCheck { + authenticity: Authenticity::Unqualified, + installation: "installation-canary".into(), + workspace: "workspace-canary".into(), + sandbox: "sandbox-canary".into(), + reported_product_version: PRODUCT_VERSION.into(), + health: HealthStatus::Healthy, + protected_read: PolicyRevision { + version: 7, + policy_hash: Some("hash-canary".into()), + status: PolicyLoadStatus::Loaded, + created_time_millis: Some(111), + loaded_time_millis: Some(222), + losses: vec![Loss::PolicyHashMissing], + }, + received_time_millis: 333, + } +} + +fn outcome(kind: ReadKind) -> ReadOutcome { + let protected_check = check(); + let observation = match kind { + ReadKind::ProtectedCheck => Observation::ProtectedCheck(protected_check.clone()), + ReadKind::PolicyStatus => Observation::PolicyStatus(PolicyRead { + authenticity: Authenticity::Unqualified, + installation: "installation-canary".into(), + workspace: "workspace-canary".into(), + sandbox: "sandbox-canary".into(), + active_version: 7, + queried: PolicyRevision { + version: 7, + policy_hash: Some("policy-hash-canary".into()), + status: PolicyLoadStatus::Loaded, + created_time_millis: Some(333), + loaded_time_millis: Some(444), + losses: vec![Loss::PolicyBodyRedacted], + }, + revisions: vec![PolicyRevision { + version: 7, + policy_hash: Some("revision-hash-canary".into()), + status: PolicyLoadStatus::Loaded, + created_time_millis: Some(555), + loaded_time_millis: Some(666), + losses: vec![Loss::PolicyHashInvalid], + }], + received_time_millis: 777, + }), + ReadKind::RecentLogs => Observation::RecentLogs(LogWindow { + authenticity: Authenticity::Unqualified, + installation: "installation-canary".into(), + workspace: "workspace-canary".into(), + sandbox: "sandbox-canary".into(), + line_count: 2, + buffer_total: 99, + native_sandbox_id: Some("native-id-canary".into()), + source_times_millis: vec![Some(1000), Some(2000)], + producers: vec![ProducerKind::Gateway, ProducerKind::Process], + received_time_millis: 3000, + losses: vec![Loss::LogTextRedacted], + }), + ReadKind::RecentWatch => Observation::RecentWatch(WatchWindow { + authenticity: Authenticity::Unqualified, + installation: "installation-canary".into(), + workspace: "workspace-canary".into(), + sandbox: "sandbox-canary".into(), + events: vec![ + WatchEvent { + kind: WatchEventKind::Status, + producer: Some(ProducerKind::Gateway), + cursor: Some("cursor-canary".into()), + native_sandbox_id: Some("native-id-canary".into()), + source_time_millis: Some(4000), + received_time_millis: 5000, + losses: vec![Loss::MissingNativeEventId], + }, + WatchEvent { + kind: WatchEventKind::Warning, + producer: None, + cursor: Some("cursor-canary-2".into()), + native_sandbox_id: None, + source_time_millis: None, + received_time_millis: 6000, + losses: vec![Loss::StreamWarning], + }, + ], + continuity: Continuity::Gap, + }), + }; + ReadOutcome { + protected_check, + observation, + } +} + +struct ResultClient { + kind: ReadKind, + result: Result, + entered: Option>, + release: Option>, + returning: Option>, +} + +impl SyntheticReadClient for ResultClient { + fn run( + mut self: Box, + _config: ClientConfig, + _lease: BearerLease, + kind: ReadKind, + _control: WatchControl, + ) -> Result { + assert_eq!(kind, self.kind); + if let Some(entered) = self.entered.take() { + entered.send(()).unwrap(); + } + if let Some(release) = self.release.take() { + release.recv_timeout(WAIT).unwrap(); + } + if let Some(returning) = self.returning.take() { + returning.send(()).unwrap(); + } + self.result + } +} + +fn start(host: &Host, review: &super::super::Review, result: Result) { + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + assert_eq!( + host.begin_synthetic( + &review.id, + lease(), + Box::new(ResultClient { + kind: review.kind, + result, + entered: None, + release: None, + returning: None, + }) + ), + HostStatus::Running + ); +} + +fn terminal(host: &Host) -> HostStatus { + let until = Instant::now() + WAIT; + loop { + let status = host.status(); + if !matches!(status, HostStatus::Running | HostStatus::Closing) { + return status; + } + assert!(Instant::now() < until, "callback did not terminate"); + std::thread::yield_now(); + } +} + +fn value(view: &SessionView) -> Value { + serde_json::from_slice(&view.encode().unwrap()).unwrap() +} + +fn unavailable(view: SessionView) { + assert_eq!( + value(&view), + json!({ + "schema":"rangoon.openshell.session-view.v1", "provider":"openshell", + "productVersion":"v0.1.4", "phase":"unavailable", "startAvailable":false, + "retention":"session_only", "provenance": { + "authenticity":"unqualified", "authority":"none", "execution":"unavailable", + "actionOutcome":"unknown", "coverage":"bounded_partial", "omissions":[ + "native_identifiers", "source_timestamps", "policy_hashes", "provider_payloads", + "target_and_credential_references" + ] + } + }) + ); +} + +#[test] +fn unavailable_refuses_no_current_legacy_refused_foreign_stale_draining_and_poisoned_custody() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + unavailable(host.inspect_session(&workspace(&gate))); + unavailable(host.inspect_session(&WorkspaceRequest::Legacy)); + unavailable(host.inspect_session(&WorkspaceRequest::Refused)); + let foreign = Gate::new(); + unavailable(host.inspect_session(&workspace(&foreign))); + let current = workspace(&gate); + let _drain = gate.request_drain().unwrap(); + unavailable(host.inspect_session(¤t)); + + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let poisoned = host.clone(); + std::thread::spawn(move || { + let _guard = poisoned.state.lock().unwrap(); + panic!("synthetic session-view poison"); + }) + .join() + .unwrap_err(); + unavailable(host.inspect_session(&workspace(&gate))); +} + +#[test] +fn pending_phases_preserve_kind_and_expiry_and_stale_win_over_expiry() { + for (confirmed, phase) in [ + (false, "awaiting_consent"), + (true, "ready_for_native_credential"), + ] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::PolicyStatus); + if confirmed { + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + } + let request = workspace(&gate); + let current = value(&host.inspect_session(&request)); + assert_eq!(current["phase"], phase); + assert_eq!(current["readKind"], "policy_status"); + assert!(current.get("observation").is_none()); + let mut state = host.state.lock().unwrap(); + match state.pending.as_mut().unwrap() { + super::super::Pending::Awaiting { selection, .. } + | super::super::Pending::Confirmed { selection, .. } => { + selection.deadline = Instant::now() - Duration::from_secs(1); + } + } + drop(state); + let expired = value(&host.inspect_session(&request)); + assert_eq!(expired["phase"], "error"); + assert_eq!(expired["error"], "credential_lease_expired"); + assert_eq!(expired["readKind"], "policy_status"); + let _drain = gate.request_drain().unwrap(); + unavailable(host.inspect_session(&request)); + } +} + +#[test] +fn pending_snapshot_rechecks_expiry_after_before_final_barrier_for_both_consent_phases() { + for confirmed in [false, true] { + let gate = Gate::new(); + let host = Arc::new(Host::new(gate.clone())); + let review = prepare(&host, &gate, ReadKind::RecentLogs); + if confirmed { + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + } + let deadline = Instant::now() + Duration::from_secs(2); + { + let mut state = host.state.lock().unwrap(); + match state.pending.as_mut().unwrap() { + super::super::Pending::Awaiting { selection, .. } + | super::super::Pending::Confirmed { selection, .. } => { + selection.deadline = deadline + } + } + } + let request = workspace(&gate); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let probe = SnapshotProbe { + before_final: Some((entered_tx, release_rx)), + ..Default::default() + }; + let reader = { + let host = Arc::clone(&host); + std::thread::spawn(move || host.inspect_session_inner(&request, Some(&probe))) + }; + entered_rx.recv_timeout(WAIT).unwrap(); + assert!(Instant::now() < deadline, "barrier must precede expiry"); + while Instant::now() < deadline { + std::thread::yield_now(); + } + release_tx.send(()).unwrap(); + let view = value(&reader.join().unwrap()); + assert_eq!(view["phase"], "error"); + assert_eq!(view["error"], "credential_lease_expired"); + assert_eq!(view["readKind"], "recent_logs"); + assert!(view.get("observation").is_none()); + } +} + +#[test] +fn active_phases_errors_and_completed_keep_retained_kind() { + let errors = [ + ClientError::InvalidConfiguration, + ClientError::CredentialLeaseExpired, + ClientError::Unreachable, + ClientError::Tls, + ClientError::Unauthenticated, + ClientError::PermissionDenied, + ClientError::Unsupported, + ClientError::Cancelled, + ClientError::Stale, + ClientError::DeadlineExceeded, + ClientError::InvalidCursor, + ClientError::Gap, + ClientError::Bounds, + ClientError::Source, + ]; + for kind in [ + ReadKind::ProtectedCheck, + ReadKind::PolicyStatus, + ReadKind::RecentLogs, + ReadKind::RecentWatch, + ] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, kind); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + assert_eq!( + host.begin_synthetic( + &review.id, + lease(), + Box::new(ResultClient { + kind, + result: Ok(outcome(kind)), + entered: Some(entered_tx), + release: Some(release_rx), + returning: None, + }) + ), + HostStatus::Running + ); + entered_rx.recv_timeout(WAIT).unwrap(); + let running = value(&host.inspect_session(&workspace(&gate))); + assert_eq!(running["phase"], "running"); + assert_eq!(running["readKind"], kind_name(kind)); + assert!(running.get("observation").is_none()); + assert_eq!(host.stop(), HostStatus::Closing); + let closing = value(&host.inspect_session(&workspace(&gate))); + assert_eq!(closing["phase"], "closing"); + assert_eq!(closing["readKind"], kind_name(kind)); + assert!(closing.get("observation").is_none()); + release_tx.send(()).unwrap(); + assert_eq!(terminal(&host), HostStatus::Cancelled); + let cancelled = value(&host.inspect_session(&workspace(&gate))); + assert_eq!(cancelled["phase"], "cancelled"); + assert_eq!(cancelled["readKind"], kind_name(kind)); + + for error in errors { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, kind); + start(&host, &review, Err(error)); + let terminal_status = terminal(&host); + let expected_status = if error == ClientError::Cancelled { + HostStatus::Cancelled + } else { + HostStatus::Error(error) + }; + assert_eq!(terminal_status, expected_status); + let view = value(&host.inspect_session(&workspace(&gate))); + let expected_phase = if error == ClientError::Cancelled { + "cancelled" + } else { + "error" + }; + assert_eq!(view["phase"], expected_phase); + if error == ClientError::Cancelled { + assert!(view.get("error").is_none()); + } else { + assert_eq!(view["error"], error.code()); + } + assert_eq!(view["readKind"], kind_name(kind)); + assert!(view.get("observation").is_none()); + } + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, kind); + start(&host, &review, Ok(outcome(kind))); + assert_eq!(terminal(&host), HostStatus::Completed); + let done = value(&host.inspect_session(&workspace(&gate))); + assert_eq!(done["phase"], "completed"); + assert_eq!(done["readKind"], kind_name(kind)); + assert!(done.get("observation").is_some()); + } +} + +fn kind_name(kind: ReadKind) -> &'static str { + match kind { + ReadKind::ProtectedCheck => "protected_check", + ReadKind::PolicyStatus => "policy_status", + ReadKind::RecentLogs => "recent_logs", + ReadKind::RecentWatch => "recent_watch", + } +} + +#[test] +fn completed_is_historical_after_expiry_but_stop_and_close_purge_before_next_delivery() { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + start(&host, &review, Ok(outcome(ReadKind::ProtectedCheck))); + assert_eq!(terminal(&host), HostStatus::Completed); + { + let state = host.state.lock().unwrap(); + state + .active + .as_ref() + .unwrap() + .state + .lock() + .unwrap() + .credential_deadline = Some(Instant::now() - Duration::from_secs(1)); + } + assert_eq!( + value(&host.inspect_session(&workspace(&gate)))["phase"], + "completed" + ); + assert_eq!(host.stop(), HostStatus::Cancelled); + unavailable(host.inspect_session(&workspace(&gate))); + + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, ReadKind::RecentLogs); + start(&host, &review, Ok(outcome(ReadKind::RecentLogs))); + assert_eq!(terminal(&host), HostStatus::Completed); + let closed_request = workspace(&gate); + let close = WorkspaceClose::new(SourceAccess::close_protocol_fixture(gate.clone())); + let closing = close.begin(|drained| host.purge_for_workspace_close(drained)); + assert_eq!(serde_json::to_value(closing).unwrap()["state"], "closing"); + assert_eq!( + close.progress_native(|drained| host.purge_for_workspace_close(drained)), + Ok(true) + ); + unavailable(host.inspect_session(&closed_request)); +} + +#[test] +fn encoded_schema_has_exact_allowlist_and_never_leaks_canaries() { + for kind in [ + ReadKind::ProtectedCheck, + ReadKind::PolicyStatus, + ReadKind::RecentLogs, + ReadKind::RecentWatch, + ] { + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let review = prepare(&host, &gate, kind); + let credential_reference = host.credential_inspection(&review.id).unwrap().reference; + start(&host, &review, Ok(outcome(kind))); + assert_eq!(terminal(&host), HostStatus::Completed); + let bytes = host.inspect_session(&workspace(&gate)).encode().unwrap(); + let view: Value = serde_json::from_slice(&bytes).unwrap(); + let observation = match kind { + ReadKind::ProtectedCheck => json!({ + "kind": "protected_check", "health": "healthy", "policyLoad": "loaded" + }), + ReadKind::PolicyStatus => json!({ + "kind": "policy_status", "activeVersion": 7, "queriedVersion": 7, + "loadState": "loaded", "revisionCount": 1 + }), + ReadKind::RecentLogs => json!({ + "kind": "recent_logs", "returnedLineCount": 2, "providerBufferTotal": 99 + }), + ReadKind::RecentWatch => json!({ + "kind": "recent_watch", "eventCount": 2, + "kinds": {"status": 1, "log": 0, "platform": 0, "warning": 1}, + "producers": { + "gateway": 1, "sandbox": 0, "kubernetes": 0, + "docker": 0, "process": 0, "unknown": 0 + }, + "producerAbsentCount": 1, "continuity": "gap", + "lossReasons": ["missing_native_event_id", "stream_warning"] + }), + }; + // Full equality fixes every nested key, scalar type and semantic value. + // It also prevents a timestamp from being substituted for an allowed count. + assert_eq!( + view, + json!({ + "schema": "rangoon.openshell.session-view.v1", "provider": "openshell", + "productVersion": "v0.1.4", "phase": "completed", "readKind": kind_name(kind), + "startAvailable": false, "retention": "session_only", + "provenance": { + "authenticity": "unqualified", "authority": "none", "execution": "unavailable", + "actionOutcome": "unknown", "coverage": "bounded_partial", "omissions": [ + "native_identifiers", "source_timestamps", "policy_hashes", "provider_payloads", + "target_and_credential_references" + ] + }, + "observation": observation + }) + ); + let raw = String::from_utf8(bytes).unwrap(); + let peer = review.selected_peer.to_string(); + for forbidden in [ + review.id.as_str(), + credential_reference.as_str(), + review.origin.as_str(), + peer.as_str(), + review.installation.as_str(), + review.workspace.as_str(), + review.sandbox.as_str(), + review.root_sha256.as_str(), + review.peer_pin_sha256.as_str(), + "root-canary", + "leaf-canary", + "hash-canary", + "policy-hash-canary", + "revision-hash-canary", + "native-id-canary", + "cursor-canary", + "cursor-canary-2", + "111", + "222", + "333", + "444", + "555", + "666", + "777", + "1000", + "2000", + "3000", + "4000", + "5000", + "6000", + "test-token", + ] { + assert!(!raw.contains(forbidden), "leaked forbidden fixture value"); + } + } +} + +#[test] +fn malformed_kind_mismatch_oversized_lists_and_writer_boundary_refuse_without_truncation() { + let mismatch = SessionView::completed(ReadKind::RecentLogs, &outcome(ReadKind::ProtectedCheck)); + assert_eq!(value(&mismatch)["error"], "source_error"); + let mut many = outcome(ReadKind::RecentWatch); + if let Observation::RecentWatch(window) = &mut many.observation { + window.events = vec![window.events[0].clone(); 129]; + } + let oversized = SessionView::completed(ReadKind::RecentWatch, &many); + assert_eq!(value(&oversized)["error"], "bounds"); + assert!(value(&oversized).get("observation").is_none()); + let mut losses = outcome(ReadKind::PolicyStatus); + losses.protected_check.protected_read.losses = vec![Loss::LogTextRedacted; 13]; + let bad_losses = SessionView::completed(ReadKind::PolicyStatus, &losses); + assert_eq!(value(&bad_losses)["error"], "bounds"); + let mut revisions = outcome(ReadKind::PolicyStatus); + if let Observation::PolicyStatus(policy) = &mut revisions.observation { + policy.revisions = vec![policy.queried.clone(); 65]; + } + assert_eq!( + value(&SessionView::completed(ReadKind::PolicyStatus, &revisions))["error"], + "bounds" + ); + let mut logs = outcome(ReadKind::RecentLogs); + if let Observation::RecentLogs(window) = &mut logs.observation { + window.line_count = 65; + window.source_times_millis = vec![None; 65]; + window.producers = vec![ProducerKind::Unknown; 65]; + } + assert_eq!( + value(&SessionView::completed(ReadKind::RecentLogs, &logs))["error"], + "bounds" + ); + let mut metadata = outcome(ReadKind::PolicyStatus); + if let Observation::PolicyStatus(policy) = &mut metadata.observation { + policy.workspace = "wrong-workspace".into(); + } + assert_eq!( + value(&SessionView::completed(ReadKind::PolicyStatus, &metadata))["error"], + "source_error" + ); + let mut writer = BoundedJson(vec![b'x'; MAX_ENCODED_BYTES - 1]); + assert!(writer.write(b"xx").is_err()); + assert_eq!(writer.0.len(), MAX_ENCODED_BYTES - 1); +} + +#[test] +fn probe_orders_snapshot_against_stop_and_generation_fence_without_contradictory_completion() { + let gate = Gate::new(); + let host = Arc::new(Host::new(gate.clone())); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + start(&host, &review, Ok(outcome(ReadKind::ProtectedCheck))); + assert_eq!(terminal(&host), HostStatus::Completed); + let request = workspace(&gate); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let probe = SnapshotProbe { + before_final: Some((entered_tx, release_rx)), + ..Default::default() + }; + let reader = { + let host = Arc::clone(&host); + std::thread::spawn(move || host.inspect_session_inner(&request, Some(&probe))) + }; + entered_rx.recv_timeout(WAIT).unwrap(); + // Host lock stays held at final witness; Stop waits. Release lets snapshot win historically. + let stopper = { + let host = Arc::clone(&host); + std::thread::spawn(move || host.stop()) + }; + release_tx.send(()).unwrap(); + let snap = reader.join().unwrap(); + assert_eq!(value(&snap)["phase"], "completed"); + assert_eq!(stopper.join().unwrap(), HostStatus::Cancelled); + unavailable(host.inspect_session(&workspace(&gate))); + + let gate = Gate::new(); + let host = Arc::new(Host::new(gate.clone())); + let review = prepare(&host, &gate, ReadKind::RecentLogs); + start(&host, &review, Ok(outcome(ReadKind::RecentLogs))); + assert_eq!(terminal(&host), HostStatus::Completed); + let request = workspace(&gate); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let probe = SnapshotProbe { + before_final: Some((entered_tx, release_rx)), + ..Default::default() + }; + let reader = { + let host = Arc::clone(&host); + std::thread::spawn(move || host.inspect_session_inner(&request, Some(&probe))) + }; + entered_rx.recv_timeout(WAIT).unwrap(); + let drain = gate.request_drain().unwrap(); + release_tx.send(()).unwrap(); + unavailable(reader.join().unwrap()); + assert!(host.purge_for_workspace_close(false)); + assert!(drain.is_quiescent().unwrap()); + assert!(host.purge_for_workspace_close(true)); +} + +#[test] +fn before_lock_stop_wins_and_dropped_inspection_reader_keeps_callback_custody() { + let gate = Gate::new(); + let host = Arc::new(Host::new(gate.clone())); + let review = prepare(&host, &gate, ReadKind::ProtectedCheck); + start(&host, &review, Ok(outcome(ReadKind::ProtectedCheck))); + assert_eq!(terminal(&host), HostStatus::Completed); + let request = workspace(&gate); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let probe = SnapshotProbe { + before_lock: Some((entered_tx, release_rx)), + ..Default::default() + }; + let reader = { + let host = Arc::clone(&host); + std::thread::spawn(move || host.inspect_session_inner(&request, Some(&probe))) + }; + entered_rx.recv_timeout(WAIT).unwrap(); + assert_eq!(host.stop(), HostStatus::Cancelled); + release_tx.send(()).unwrap(); + unavailable(reader.join().unwrap()); + + let gate = Gate::new(); + let host = Arc::new(Host::new(gate.clone())); + let review = prepare(&host, &gate, ReadKind::RecentWatch); + let (callback_entered_tx, callback_entered_rx) = mpsc::channel(); + let (callback_release_tx, callback_release_rx) = mpsc::channel(); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + assert_eq!( + host.begin_synthetic( + &review.id, + lease(), + Box::new(ResultClient { + kind: ReadKind::RecentWatch, + result: Ok(outcome(ReadKind::RecentWatch)), + entered: Some(callback_entered_tx), + release: Some(callback_release_rx), + returning: None + }) + ), + HostStatus::Running + ); + callback_entered_rx.recv_timeout(WAIT).unwrap(); + let request = workspace(&gate); + let (inspect_entered_tx, inspect_entered_rx) = mpsc::channel(); + let (inspect_release_tx, inspect_release_rx) = mpsc::channel(); + let probe = SnapshotProbe { + before_lock: Some((inspect_entered_tx, inspect_release_rx)), + ..Default::default() + }; + let (reply_tx, reply_rx) = mpsc::channel(); + let reader = { + let host = Arc::clone(&host); + std::thread::spawn(move || { + let snapshot = host.inspect_session_inner(&request, Some(&probe)); + assert!(reply_tx.send(snapshot).is_err(), "waiter must be gone"); + }) + }; + inspect_entered_rx.recv_timeout(WAIT).unwrap(); + drop(reply_rx); + inspect_release_tx.send(()).unwrap(); + reader.join().unwrap(); + assert_eq!(host.stop(), HostStatus::Closing); + callback_release_tx.send(()).unwrap(); + assert_eq!(terminal(&host), HostStatus::Cancelled); + assert!(gate.request_drain().unwrap().is_quiescent().unwrap()); +} + +#[test] +fn callback_finish_blocked_while_stop_waits_resolves_to_cancelled_without_observation() { + let gate = Gate::new(); + let host = Arc::new(Host::new(gate.clone())); + let review = prepare(&host, &gate, ReadKind::RecentLogs); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let (returning_tx, returning_rx) = mpsc::channel(); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + assert_eq!( + host.begin_synthetic( + &review.id, + lease(), + Box::new(ResultClient { + kind: ReadKind::RecentLogs, + result: Ok(outcome(ReadKind::RecentLogs)), + entered: Some(entered_tx), + release: Some(release_rx), + returning: Some(returning_tx) + }) + ), + HostStatus::Running + ); + entered_rx.recv_timeout(WAIT).unwrap(); + let active = host.state.lock().unwrap().active.as_ref().unwrap().clone(); + let active_guard = active.state.lock().unwrap(); + release_tx.send(()).unwrap(); + returning_rx.recv_timeout(WAIT).unwrap(); + let (stopped_tx, stopped_rx) = mpsc::channel(); + let stopper = { + let host = Arc::clone(&host); + std::thread::spawn(move || { + stopped_tx.send(host.stop()).unwrap(); + }) + }; + // Stop sets cancellation only after obtaining Host custody and before + // waiting for Active. This flag proves that ordering while both Stop and + // callback completion remain blocked by the held Active guard. + let until = Instant::now() + WAIT; + while !active.cancelled.load(std::sync::atomic::Ordering::Acquire) { + assert!( + Instant::now() < until, + "Stop did not reach Active cancellation" + ); + std::thread::yield_now(); + } + assert!(matches!( + stopped_rx.try_recv(), + Err(mpsc::TryRecvError::Empty) + )); + drop(active_guard); + assert!(matches!( + stopped_rx.recv_timeout(WAIT).unwrap(), + HostStatus::Closing | HostStatus::Cancelled + )); + stopper.join().unwrap(); + assert!(matches!( + terminal(&host), + HostStatus::Cancelled | HostStatus::Unavailable + )); + let view = value(&host.inspect_session(&workspace(&gate))); + assert!(matches!( + view["phase"].as_str(), + Some("cancelled") | Some("unavailable") + )); + assert!(view.get("observation").is_none()); +} + +struct RealClient; +impl SyntheticReadClient for RealClient { + fn run( + self: Box, + config: ClientConfig, + lease: BearerLease, + kind: ReadKind, + control: WatchControl, + ) -> Result { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let mut client = OpenShellReadClient::connect(config, lease).await?; + let protected_check = client.check_protected_read().await?; + let observation = match kind { + ReadKind::ProtectedCheck => { + Observation::ProtectedCheck(protected_check.clone()) + } + ReadKind::PolicyStatus => { + Observation::PolicyStatus(client.read_policy_status(0).await?) + } + ReadKind::RecentLogs => { + Observation::RecentLogs(client.read_recent_logs().await?) + } + ReadKind::RecentWatch => Observation::RecentWatch( + client + .watch_recent(&control, None, Duration::from_secs(30)) + .await?, + ), + }; + Ok(ReadOutcome { + protected_check, + observation, + }) + }) + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn real_tls_callbacks_have_exact_ledger_and_repeated_inspect_adds_no_rpc() { + use rangoon_openshell_client::synthetic_peer::{ + SyntheticPeer, SyntheticRpc, SyntheticScenario, + }; + for (kind, ledger) in [ + ( + ReadKind::ProtectedCheck, + vec![SyntheticRpc::Health, SyntheticRpc::GetSandboxPolicyStatus], + ), + ( + ReadKind::PolicyStatus, + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::ListSandboxPolicies, + ], + ), + ( + ReadKind::RecentLogs, + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::GetSandboxLogs, + ], + ), + ( + ReadKind::RecentWatch, + vec![ + SyntheticRpc::Health, + SyntheticRpc::GetSandboxPolicyStatus, + SyntheticRpc::WatchSandbox, + ], + ), + ] { + let peer = SyntheticPeer::start(SyntheticScenario::Healthy) + .await + .unwrap(); + let gate = Gate::new(); + let host = Host::new(gate.clone()); + let request = workspace(&gate); + let review = host + .prepare( + &request, + ProposedTarget::new( + peer.origin().into(), + peer.selected_peer(), + "installation-1".into(), + "workspace-1".into(), + "sandbox-1".into(), + peer.root_der().to_vec(), + peer.leaf_der().to_vec(), + ) + .unwrap(), + kind, + Retention::SessionOnly, + ) + .unwrap(); + assert_eq!( + host.confirm(&review.id, true), + HostStatus::ReadyForNativeCredential + ); + assert_eq!(host.begin_production(&review.id), HostStatus::Unavailable); + assert_eq!( + host.begin_synthetic(&review.id, lease(), Box::new(RealClient)), + HostStatus::Running + ); + let deadline = Instant::now() + WAIT; + while matches!(host.status(), HostStatus::Running | HostStatus::Closing) { + assert!(Instant::now() < deadline); + tokio::task::yield_now().await; + } + assert_eq!(host.status(), HostStatus::Completed); + assert_eq!(peer.calls().unwrap(), ledger); + for _ in 0..3 { + let view = value(&host.inspect_session(&request)); + assert_eq!(view["phase"], "completed"); + assert_eq!(view["readKind"], kind_name(kind)); + } + assert_eq!(peer.calls().unwrap(), ledger); + peer.shutdown().await.unwrap(); + } +} diff --git a/apps/desktop/src/source_collection.rs b/apps/desktop/src/source_collection.rs new file mode 100644 index 0000000..0c88a3c --- /dev/null +++ b/apps/desktop/src/source_collection.rs @@ -0,0 +1,157 @@ +//! Native-owned bulk selection. No renderer paths, writes, or analysis selection. +use crate::{AdmissionError, workspace_source_access::SourceAccess}; +use rangoon_host::{SourceCollectionResult, inspect_selected_sources}; +use tauri::{AppHandle, Manager}; +use tauri_plugin_dialog::DialogExt; + +#[tauri::command] +pub(crate) async fn select_and_inspect_sources( + workspace: crate::workspace_requests::WorkspaceRequest, + app: AppHandle, +) -> SourceCollectionResult { + let operation = match app + .state::() + .for_request(&workspace) + .begin_selection() + { + Ok(operation) => operation, + Err(AdmissionError::Busy) => { + return SourceCollectionResult::failed( + "source_collection_busy", + "Finish the current workspace operation first.", + ); + } + Err(AdmissionError::Unavailable) => { + return SourceCollectionResult::failed( + "source_collection_unavailable", + "Unlock or reopen the workspace before choosing files.", + ); + } + }; + tauri::async_runtime::spawn_blocking(move || { + let result = if !operation.is_current() { + SourceCollectionResult::stale() + } else if let Some(window) = app.get_webview_window("main") { + let selection = app + .dialog() + .file() + .set_parent(&window) + .set_title("Choose up to 32 agent Markdown files") + .add_filter("Markdown", &["md"]) + .blocking_pick_files(); + if !operation.is_current() { + SourceCollectionResult::stale() + } else { + match selection { + None => SourceCollectionResult::Cancelled, + Some(selection) => match selection + .into_iter() + .map(|file| file.into_path()) + .collect::, _>>() + { + Ok(paths) => inspect_selected_sources(&paths, || operation.is_current()), + Err(_) => SourceCollectionResult::failed( + "source_collection_unavailable", + "Choose regular Markdown files available on this computer.", + ), + }, + } + } + } else { + SourceCollectionResult::failed( + "source_collection_unavailable", + "The file workbench is unavailable.", + ) + }; + operation.complete_read_only(result) + }) + .await + .map(|completed| completed.deliver(SourceCollectionResult::stale)) + .unwrap_or_else(|_| { + SourceCollectionResult::failed( + "source_collection_failed", + "File inspection did not complete. Previous results remain available.", + ) + }) +} + +/// Fresh native folder selection; renderer supplies no path or row reference. +#[tauri::command] +pub(crate) async fn select_and_list_sources( + workspace: crate::workspace_requests::WorkspaceRequest, + app: AppHandle, +) -> rangoon_host::FolderCollectionResult { + use rangoon_host::FolderCollectionResult; + #[cfg(not(unix))] + { + let _ = (workspace, app); + FolderCollectionResult::failed( + "folder_inventory_unsupported", + "Folder discovery is unavailable on this platform. Choose individual files instead.", + ) + } + #[cfg(unix)] + { + let operation = match app + .state::() + .for_request(&workspace) + .begin_selection() + { + Ok(operation) => operation, + Err(AdmissionError::Busy) => { + return FolderCollectionResult::failed( + "folder_inventory_busy", + "Finish the current workspace operation first.", + ); + } + Err(AdmissionError::Unavailable) => { + return FolderCollectionResult::failed( + "folder_inventory_unavailable", + "Unlock or reopen the workspace before choosing a folder.", + ); + } + }; + tauri::async_runtime::spawn_blocking(move || { + let result = if !operation.is_current() { + FolderCollectionResult::stale() + } else if let Some(window) = app.get_webview_window("main") { + let selection = app + .dialog() + .file() + .set_parent(&window) + .set_title("Choose folder to list Markdown file metadata") + .blocking_pick_folder(); + if !operation.is_current() { + FolderCollectionResult::stale() + } else { + match selection { + None => FolderCollectionResult::Cancelled, + Some(file) => match file.into_path() { + Ok(path) => { + rangoon_host::list_selected_root(&path, || operation.is_current()) + } + Err(_) => FolderCollectionResult::failed( + "folder_inventory_unavailable", + "Choose a folder available on this computer.", + ), + }, + } + } + } else { + FolderCollectionResult::failed( + "folder_inventory_unavailable", + "The file workbench is unavailable.", + ) + }; + operation.complete_read_only(result) + }) + .await + .map(|completed| completed.deliver(FolderCollectionResult::stale)) + .unwrap_or_else(|_| { + FolderCollectionResult::failed( + "folder_inventory_failed", + "Folder listing did not finish. Previous results remain available.", + ) + }) + } +} diff --git a/apps/desktop/src/workspace_adoption.rs b/apps/desktop/src/workspace_adoption.rs new file mode 100644 index 0000000..312fe49 --- /dev/null +++ b/apps/desktop/src/workspace_adoption.rs @@ -0,0 +1,1421 @@ +//! Native Legacy-to-Managed conversion. No renderer trust or ordinary client issuance. +#[cfg(feature = "encrypted-workspace")] +use crate::workspace_close::{StartupBinding, StartupPermit, setup::Consent}; +#[cfg(feature = "encrypted-workspace")] +use crate::workspace_startup::{EmptyProvisioningProof, Inspection}; +use crate::workspace_startup::{StartupRoots, State as StartupState}; +#[cfg(feature = "encrypted-workspace")] +use rangoon_desktop::workspace_keys::{Error as KeyError, Store}; +use rangoon_desktop::{ + workspace_keys::WorkspaceId, + workspace_session::{Owner, Vault}, +}; +use rangoon_domain::byte_digest; +use rangoon_store::{ExistingWorkspaceCapture, Workspace, WorkspaceBackup}; +use std::{ + fs::{self, File, Metadata, OpenOptions}, + io::{Read, Write}, + path::{Path, PathBuf}, + sync::OnceLock, +}; +use zeroize::Zeroizing; + +#[path = "workspace_adoption_record.rs"] +mod records; +use records::{Inventory, Phase, Record}; +const DIRECTORY: &str = "workspace-adoption"; +const CONTROL: &str = "adoption.lock"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Error { + UnsupportedPlatform, + BackendUnavailable, + Unavailable, + RecoveryRequired, + Changed, + ConsentRequired, + SameProcess, + WriteUncertain, +} +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Status { + NoAttempt, + Interrupted, + SelectionRecorded, + LegacyDiverged, + RecoveryRequired, + Unavailable, + UnsupportedPlatform, +} + +/// Routing observations only. Destination identity still requires the live +/// existing Owner before any key lookup or ordinary unlock can be offered. +pub(super) enum Route { + NoAttempt, + RestartRequired, + VerifyRequired, + Selected(Selection), + Recovery(Recovery), + RecoveryRequired, + Unavailable, +} + +/// Retains the exact selected journal across native destination binding. +pub(super) struct Selection { + anchor: PathBuf, + journal: Journal, + destination: String, +} +impl Selection { + pub(super) fn destination(&self) -> &str { + &self.destination + } + pub(super) fn check(&self) -> Result<(), Error> { + self.journal.check(None) + } + #[cfg(feature = "encrypted-workspace")] + pub(super) fn original_matches(&self, permit: &StartupPermit<'_>) -> Result { + matches_original(&self.anchor, &self.journal, permit) + } +} + +pub(super) fn route(anchor: &Path) -> Route { + match fs::symlink_metadata(anchor.join(DIRECTORY)) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Route::NoAttempt, + Err(_) => return Route::Unavailable, + _ => (), + } + let Ok(journal) = Journal::open(anchor) else { + return Route::RecoveryRequired; + }; + let Some(last) = journal.records.last().map(|stored| &stored.record) else { + return Route::RecoveryRequired; + }; + match last.phase { + Phase::Copied => match process_identity() { + Ok(current) if last.creator_process == current => Route::RestartRequired, + Ok(_) => Route::VerifyRequired, + Err(_) => Route::Unavailable, + }, + Phase::Selected => match last.destination.clone() { + Some(destination) => Route::Selected(Selection { + anchor: anchor.to_owned(), + journal, + destination, + }), + None => Route::RecoveryRequired, + }, + Phase::Target | Phase::Reopened => { + let phase = last.phase; + Route::Recovery(Recovery { + anchor: anchor.to_owned(), + journal, + phase, + #[cfg(feature = "encrypted-workspace")] + inspection: None, + #[cfg(feature = "encrypted-workspace")] + native_binding: None, + }) + } + _ => Route::RecoveryRequired, + } +} + +#[cfg(feature = "encrypted-workspace")] +pub(super) fn original_matches(anchor: &Path, permit: &StartupPermit<'_>) -> Result { + permit.checkpoint().map_err(|_| Error::Unavailable)?; + let journal = Journal::open(anchor)?; + matches_original(anchor, &journal, permit) +} + +#[cfg(feature = "encrypted-workspace")] +fn matches_original( + anchor: &Path, + journal: &Journal, + permit: &StartupPermit<'_>, +) -> Result { + permit.checkpoint().map_err(|_| Error::Unavailable)?; + let record = &journal + .records + .last() + .ok_or(Error::RecoveryRequired)? + .record; + let mut capture = Workspace::new(StartupRoots::new(anchor.to_owned()).legacy()) + .capture_existing_snapshot() + .map_err(|_| Error::Changed)?; + matches(record, &capture)?; + revalidate(anchor, &mut capture)?; + journal.check(None)?; + permit.checkpoint().map_err(|_| Error::Unavailable)?; + Ok(true) +} + +fn process_identity() -> Result<&'static str, Error> { + static ID: OnceLock> = OnceLock::new(); + ID.get_or_init(|| { + WorkspaceId::generate() + .map(|id| id.as_hex()) + .map_err(|_| Error::Unavailable) + }) + .as_ref() + .map(String::as_str) + .map_err(|error| *error) +} +fn identity(left: &Metadata, right: &Metadata) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + left.dev() == right.dev() && left.ino() == right.ino() + } + #[cfg(not(unix))] + { + let _ = (left, right); + false + } +} +fn regular(metadata: &Metadata, limit: u64) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + metadata.is_file() + && !metadata.file_type().is_symlink() + && metadata.nlink() == 1 + && metadata.len() <= limit + } + #[cfg(not(unix))] + { + let _ = (metadata, limit); + false + } +} +fn options(write: bool) -> OpenOptions { + let mut options = OpenOptions::new(); + options.read(true).write(write); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + options +} +fn verify(file: &File, path: &Path, limit: u64) -> Result { + let held = file.metadata().map_err(|_| Error::Unavailable)?; + let current = fs::symlink_metadata(path).map_err(|_| Error::Changed)?; + if !regular(&held, limit) || !regular(¤t, limit) || !identity(&held, ¤t) { + return Err(Error::Changed); + } + Ok(held) +} +fn absent(path: &Path) -> Result<(), Error> { + match fs::symlink_metadata(path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + _ => Err(Error::RecoveryRequired), + } +} +fn read_error(error: std::io::Error) -> Error { + if error.kind() == std::io::ErrorKind::NotFound { + return Error::Changed; + } + #[cfg(unix)] + if error.raw_os_error() == Some(libc::ELOOP) { + return Error::Changed; + } + Error::Unavailable +} +fn directory(path: &Path) -> Result { + let metadata = fs::symlink_metadata(path).map_err(|_| Error::Unavailable)?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(Error::Changed); + } + Ok(metadata) +} +struct Ancestry(Vec<(PathBuf, Metadata)>); +impl Ancestry { + fn observe(path: &Path) -> Result { + if !cfg!(unix) { + return Err(Error::UnsupportedPlatform); + } + if !path.is_absolute() + || path.components().count() > 64 + || path.components().any(|c| { + matches!( + c, + std::path::Component::CurDir | std::path::Component::ParentDir + ) + }) + { + return Err(Error::Unavailable); + } + let mut proof = Vec::new(); + for path in path.ancestors().collect::>().into_iter().rev() { + proof.push((path.to_owned(), directory(path)?)); + } + let result = Self(proof); + result.check()?; + Ok(result) + } + fn check(&self) -> Result<(), Error> { + for (path, held) in &self.0 { + if !identity(held, &directory(path)?) { + return Err(Error::Changed); + } + } + Ok(()) + } +} +fn sync(path: &Path) -> Result<(), Error> { + if !cfg!(unix) { + return Err(Error::UnsupportedPlatform); + } + File::open(path) + .and_then(|file| file.sync_all()) + .map_err(|_| Error::WriteUncertain) +} +fn create_directory(path: &Path) -> Result<(), Error> { + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(path).map_err(|_| Error::WriteUncertain) +} + +#[cfg(test)] +type Probe = Box Result<(), Error>>; +#[cfg(test)] +std::thread_local! { + static PROBE: std::cell::RefCell> = std::cell::RefCell::new(None); +} +fn point(stage: &str, boundary: &str) -> Result<(), Error> { + #[cfg(all(test, feature = "native-encrypted-qualification", target_os = "macos"))] + crate::native_encrypted_qualification::adoption_checkpoint(stage, boundary) + .map_err(|()| Error::WriteUncertain)?; + #[cfg(test)] + { + PROBE.with(|probe| match probe.borrow_mut().as_mut() { + Some(probe) => probe(stage, boundary), + None => Ok(()), + }) + } + #[cfg(not(test))] + { + let _ = (stage, boundary); + Ok(()) + } +} + +struct Stored { + record: Record, + bytes: Vec, + metadata: Metadata, +} +struct Journal { + root: PathBuf, + ancestry: Ancestry, + control: File, + records: Vec, +} +impl Journal { + fn create(anchor: &Path) -> Result { + let ancestry = Ancestry::observe(anchor)?; + let root = anchor.join(DIRECTORY); + absent(&root)?; + point("journal", "before_root_create")?; + ancestry.check()?; + create_directory(&root)?; + point("journal", "after_root_create")?; + ancestry.check()?; + point("journal", "before_parent_sync")?; + sync(anchor)?; + point("journal", "after_parent_sync")?; + let root_proof = Ancestry::observe(&root)?; + point("journal", "before_lock_create")?; + root_proof.check()?; + let control = options(true) + .create_new(true) + .open(root.join(CONTROL)) + .map_err(|_| Error::WriteUncertain)?; + point("journal", "after_lock_create")?; + verify(&control, &root.join(CONTROL), 0)?; + control.try_lock().map_err(|_| Error::Unavailable)?; + point("journal", "before_lock_sync")?; + control.sync_all().map_err(|_| Error::WriteUncertain)?; + point("journal", "after_lock_sync")?; + point("journal", "before_root_sync")?; + sync(&root)?; + point("journal", "after_root_sync")?; + let result = Self { + root, + ancestry: root_proof, + control, + records: Vec::new(), + }; + result.check(None)?; + Ok(result) + } + fn open(anchor: &Path) -> Result { + let root = anchor.join(DIRECTORY); + let ancestry = Ancestry::observe(&root)?; + let control_path = root.join(CONTROL); + let metadata = fs::symlink_metadata(&control_path).map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + Error::RecoveryRequired + } else { + Error::Unavailable + } + })?; + if !regular(&metadata, 0) { + return Err(Error::Changed); + } + let control = options(false).open(&control_path).map_err(read_error)?; + verify(&control, &control_path, 0)?; + control.try_lock().map_err(|_| Error::Unavailable)?; + let mut result = Self { + root, + ancestry, + control, + records: Vec::new(), + }; + let names = result.names()?; + for phase in Phase::ALL { + if !names.iter().any(|name| name == phase.name()) { + break; + } + let (bytes, metadata) = result.read(phase)?; + let record = Record::decode(&bytes)?; + result.validate_next(&record)?; + result.records.push(Stored { + record, + bytes, + metadata, + }); + } + result.check(None)?; + Ok(result) + } + fn names(&self) -> Result, Error> { + let mut names = Vec::new(); + for entry in fs::read_dir(&self.root).map_err(|_| Error::Unavailable)? { + if names.len() == 6 { + return Err(Error::RecoveryRequired); + } + names.push(entry.map_err(|_| Error::Unavailable)?.file_name()); + } + Ok(names) + } + fn read(&self, phase: Phase) -> Result<(Vec, Metadata), Error> { + let path = self.root.join(phase.name()); + if !regular( + &fs::symlink_metadata(&path).map_err(read_error)?, + records::LIMIT as u64, + ) { + return Err(Error::Changed); + } + let mut file = options(false).open(&path).map_err(read_error)?; + let before = verify(&file, &path, records::LIMIT as u64)?; + let mut bytes = Vec::new(); + (&mut file) + .take(records::LIMIT as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| Error::Unavailable)?; + let after = verify(&file, &path, records::LIMIT as u64)?; + if !identity(&before, &after) + || before.len() != after.len() + || bytes.len() as u64 != after.len() + { + return Err(Error::Changed); + } + Ok((bytes, after)) + } + fn check(&self, staged: Option) -> Result<(), Error> { + self.ancestry.check()?; + verify(&self.control, &self.root.join(CONTROL), 0)?; + let names = self.names()?; + if names.len() != 1 + self.records.len() + usize::from(staged.is_some()) + || !names.iter().any(|n| n == CONTROL) + { + return Err(Error::Changed); + } + for saved in &self.records { + let (bytes, metadata) = self.read(saved.record.phase)?; + if bytes != saved.bytes || !identity(&metadata, &saved.metadata) { + return Err(Error::Changed); + } + } + if staged.is_some_and(|phase| !names.iter().any(|name| name == phase.name())) { + return Err(Error::Changed); + } + Ok(()) + } + fn validate_next(&self, next: &Record) -> Result<(), Error> { + if next.phase.index() != self.records.len() { + return Err(Error::RecoveryRequired); + } + if self.records.last().is_some_and(|previous| { + !next.same_binding(&previous.record) + || next.previous_digest.as_deref() != Some(byte_digest(&previous.bytes).as_str()) + }) { + return Err(Error::RecoveryRequired); + } + Ok(()) + } + fn append(&mut self, record: Record) -> Result<(), Error> { + self.validate_next(&record)?; + let bytes = record.encode()?; + let phase = record.phase; + let path = self.root.join(phase.name()); + point(phase.name(), "before_create")?; + self.check(None)?; + let mut file = options(true) + .create_new(true) + .open(&path) + .map_err(|_| Error::WriteUncertain)?; + let created = verify(&file, &path, records::LIMIT as u64)?; + point(phase.name(), "after_create")?; + point(phase.name(), "before_write")?; + self.check(Some(phase))?; + verify(&file, &path, records::LIMIT as u64)?; + file.write_all(&bytes).map_err(|_| Error::WriteUncertain)?; + point(phase.name(), "after_write")?; + point(phase.name(), "before_file_sync")?; + self.check(Some(phase))?; + verify(&file, &path, records::LIMIT as u64)?; + file.sync_all().map_err(|_| Error::WriteUncertain)?; + point(phase.name(), "after_file_sync")?; + point(phase.name(), "before_directory_sync")?; + self.check(Some(phase))?; + sync(&self.root)?; + point(phase.name(), "after_directory_sync")?; + point(phase.name(), "before_readback")?; + self.check(Some(phase))?; + let (readback, metadata) = self.read(phase)?; + if readback != bytes || !identity(&metadata, &created) { + return Err(Error::WriteUncertain); + } + point(phase.name(), "after_readback")?; + self.check(Some(phase))?; + let (final_bytes, metadata) = self.read(phase)?; + if final_bytes != bytes || !identity(&metadata, &created) { + return Err(Error::WriteUncertain); + } + self.records.push(Stored { + record, + bytes, + metadata, + }); + self.check(None) + } + fn next( + &self, + phase: Phase, + destination: Option, + verifier: Option, + ) -> Result { + let previous = self.records.last().ok_or(Error::RecoveryRequired)?; + let mut record = previous.record.clone(); + record.phase = phase; + record.previous_digest = Some(byte_digest(&previous.bytes)); + record.destination = destination; + record.verifier_process = verifier; + Ok(record) + } +} + +#[cfg(test)] +pub(super) fn inspect(anchor: &Path) -> Status { + if !cfg!(unix) { + return Status::UnsupportedPlatform; + } + if Ancestry::observe(anchor).is_err() { + return Status::Unavailable; + } + match fs::symlink_metadata(anchor.join(DIRECTORY)) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Status::NoAttempt, + Err(_) => return Status::Unavailable, + _ => (), + } + match Journal::open(anchor) { + Ok(journal) => match journal.records.last() { + Some(last) if last.record.phase == Phase::Selected => { + let captured = Workspace::new(StartupRoots::new(anchor.to_owned()).legacy()) + .capture_existing_snapshot(); + if captured + .as_ref() + .is_ok_and(|capture| matches(&last.record, capture).is_ok()) + { + Status::SelectionRecorded + } else { + Status::LegacyDiverged + } + } + _ => Status::Interrupted, + }, + Err(Error::Unavailable) => Status::Unavailable, + Err(_) => Status::RecoveryRequired, + } +} + +pub(super) struct CopyConsent { + token: String, +} +pub(super) struct VerifyConsent { + token: String, +} +pub(super) struct Conversion { + anchor: PathBuf, + capture: ExistingWorkspaceCapture, + intent: Record, + token: String, + #[cfg(feature = "encrypted-workspace")] + native_binding: Option, +} +pub(super) struct Verification { + anchor: PathBuf, + journal: Journal, + capture: ExistingWorkspaceCapture, + owner: Owner, + preview: String, + token: String, + #[cfg(feature = "encrypted-workspace")] + native_binding: Option, +} + +/// Metadata custody only until an explicit native recovery action. Source +/// capture, Owner inspection and every effect remain inside that action's Flight. +pub(super) struct Recovery { + anchor: PathBuf, + journal: Journal, + phase: Phase, + #[cfg(feature = "encrypted-workspace")] + inspection: Option, + #[cfg(feature = "encrypted-workspace")] + native_binding: Option, +} + +#[cfg(feature = "encrypted-workspace")] +enum RecoveryInspection { + Complete(Inspection), + Empty(EmptyProvisioningProof), +} + +#[cfg(feature = "encrypted-workspace")] +impl RecoveryInspection { + fn check(&self, roots: &StartupRoots) -> Result<(), Error> { + match self { + Self::Complete(inspection) => roots.revalidate(inspection).map(|_| ()), + Self::Empty(proof) => proof.check(), + } + .map_err(|_| Error::Changed) + } +} + +#[cfg(feature = "encrypted-workspace")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RecoveryStep { + Inspect, + InitializeEmpty, + Reconcile, + Unlock, + Restore, + RecordCopied, + CompleteSelection, +} + +#[cfg(feature = "encrypted-workspace")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RecoveryOutcome { + Cancelled, + Copied, + Selected, +} + +/// Existing-key custody only. Reject the wrong identity before even opening a +/// slot, and never delegate a key write while recovering an existing target. +#[cfg(feature = "encrypted-workspace")] +struct RecoveryVault<'a, V> { + expected: &'a str, + vault: &'a V, +} +#[cfg(feature = "encrypted-workspace")] +struct ExistingKeySlot(S); +#[cfg(feature = "encrypted-workspace")] +impl Vault for RecoveryVault<'_, V> { + type Slot = ExistingKeySlot; + fn open(&self, identity: &WorkspaceId) -> Result { + if identity.as_hex() != self.expected { + return Err(KeyError::Changed); + } + self.vault.open(identity).map(ExistingKeySlot) + } +} +#[cfg(feature = "encrypted-workspace")] +impl Store for ExistingKeySlot { + fn identity(&self) -> &WorkspaceId { + self.0.identity() + } + fn read(&self) -> Result>>, KeyError> { + self.0.read() + } + fn write(&self, _bytes: &[u8]) -> Result<(), KeyError> { + Err(KeyError::Unavailable) + } +} + +#[cfg(feature = "encrypted-workspace")] +impl Recovery { + pub(super) fn bind_native(mut self, permit: &StartupPermit<'_>) -> Result { + permit.checkpoint().map_err(|_| Error::Unavailable)?; + self.journal.check(None)?; + let roots = StartupRoots::new(self.anchor.clone()); + let inspection = roots.inspect(); + let inspection = if inspection.state() == StartupState::Mixed { + roots.revalidate(&inspection).map_err(|_| Error::Changed)?; + RecoveryInspection::Complete(inspection) + } else if self.phase == Phase::Target { + let destination = self + .journal + .records + .last() + .and_then(|record| record.record.destination.as_deref()) + .ok_or(Error::RecoveryRequired)?; + RecoveryInspection::Empty( + roots + .empty_provisioning_candidate(destination) + .map_err(|_| Error::RecoveryRequired)?, + ) + } else { + return Err(Error::RecoveryRequired); + }; + self.native_binding = Some(permit.binding().map_err(|_| Error::Unavailable)?); + self.inspection = Some(inspection); + Ok(self) + } + pub(super) fn revalidate_native(&mut self, permit: &StartupPermit<'_>) -> Result<(), Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + self.journal.check(None)?; + self.inspection + .as_ref() + .ok_or(Error::Unavailable)? + .check(&StartupRoots::new(self.anchor.clone()))?; + Ok(()) + } + fn checkpoint( + &self, + permit: &StartupPermit<'_>, + capture: &mut ExistingWorkspaceCapture, + ) -> Result<(), Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + self.journal.check(None)?; + revalidate(&self.anchor, capture)?; + matches( + &self + .journal + .records + .last() + .ok_or(Error::RecoveryRequired)? + .record, + capture, + )?; + permit.checkpoint().map_err(|_| Error::Unavailable) + } + fn ask( + &self, + permit: &StartupPermit<'_>, + capture: &mut ExistingWorkspaceCapture, + step: RecoveryStep, + destination: &str, + confirmation: &mut impl FnMut(RecoveryStep, &str) -> Consent, + ) -> Result { + self.checkpoint(permit, capture)?; + let consent = confirmation(step, destination); + self.checkpoint(permit, capture)?; + match consent { + Consent::Approved => Ok(true), + Consent::Cancelled => Ok(false), + Consent::Unavailable => Err(Error::Unavailable), + } + } + pub(super) fn recover_native( + mut self, + permit: &StartupPermit<'_>, + vault: &impl Vault, + mut confirmation: impl FnMut(RecoveryStep, &str) -> Consent, + ) -> Result { + use rangoon_desktop::workspace_session::{Error as OwnerError, RecoveryOperation}; + + self.revalidate_native(permit)?; + let last = self + .journal + .records + .last() + .ok_or(Error::RecoveryRequired)? + .record + .clone(); + if last.phase != self.phase || !matches!(last.phase, Phase::Target | Phase::Reopened) { + return Err(Error::RecoveryRequired); + } + if last.phase == Phase::Reopened && last.creator_process == process_identity()? { + return Err(Error::SameProcess); + } + let destination = last.destination.clone().ok_or(Error::RecoveryRequired)?; + WorkspaceId::parse(&destination).map_err(|_| Error::RecoveryRequired)?; + let scoped = RecoveryVault { + expected: &destination, + vault, + }; + let roots = StartupRoots::new(self.anchor.clone()); + let mut capture = Workspace::new(roots.legacy()) + .capture_existing_snapshot() + .map_err(|_| Error::Changed)?; + self.checkpoint(permit, &mut capture)?; + let inspection = self.inspection.take().ok_or(Error::Unavailable)?; + inspection.check(&roots)?; + let mut owner = + Owner::acquire_existing(roots.managed()).map_err(|_| Error::RecoveryRequired)?; + inspection.check(&roots)?; + let empty_provisioning = matches!(inspection, RecoveryInspection::Empty(_)); + // Intentional Owner writes may replace operation metadata. From here + // the Owner, full source capture and retained journal own revalidation. + self.checkpoint(permit, &mut capture)?; + + if last.phase == Phase::Reopened { + let preview = owner + .prepare_unlock() + .map_err(|_| Error::RecoveryRequired)?; + if preview.workspace_id != destination { + return Err(Error::Changed); + } + if !self.ask( + permit, + &mut capture, + RecoveryStep::CompleteSelection, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + owner + .confirm(&preview.id, &scoped) + .map_err(|_| Error::RecoveryRequired)?; + self.checkpoint(permit, &mut capture)?; + parity(&mut owner, &scoped, &capture)?; + self.checkpoint(permit, &mut capture)?; + let verifier = last.verifier_process.ok_or(Error::RecoveryRequired)?; + let selected = self + .journal + .next(Phase::Selected, Some(destination), Some(verifier))?; + self.journal.append(selected)?; + self.checkpoint(permit, &mut capture)?; + owner.lock(); + capture.cancel(); + return Ok(RecoveryOutcome::Selected); + } + + let preview = match owner.prepare_unlock() { + Ok(preview) => Some(preview), + Err(OwnerError::RecoveryRequired) => None, + Err(_) => return Err(Error::RecoveryRequired), + }; + if preview + .as_ref() + .is_some_and(|preview| preview.workspace_id != destination) + { + return Err(Error::Changed); + } + if !self.ask( + permit, + &mut capture, + RecoveryStep::Inspect, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + if let Some(preview) = preview { + owner + .confirm(&preview.id, &scoped) + .map_err(|_| Error::RecoveryRequired)?; + } else { + if empty_provisioning { + let recovery = owner + .inspect_empty_provisioning(&scoped) + .map_err(|_| Error::RecoveryRequired)?; + if recovery.workspace_id != destination { + return Err(Error::Changed); + } + if !self.ask( + permit, + &mut capture, + RecoveryStep::InitializeEmpty, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + owner + .finish_empty_provisioning(&recovery.id, &scoped) + .map_err(|_| Error::RecoveryRequired)?; + } else { + let recovery = owner + .inspect_recovery(&scoped) + .map_err(|_| Error::RecoveryRequired)?; + if recovery.workspace_id != destination + || !matches!( + recovery.operation, + RecoveryOperation::CreateEmpty | RecoveryOperation::Restore + ) + { + return Err(Error::RecoveryRequired); + } + if !self.ask( + permit, + &mut capture, + RecoveryStep::Reconcile, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + owner + .confirm_recovery(&recovery.id, &scoped) + .map_err(|_| Error::RecoveryRequired)?; + } + self.checkpoint(permit, &mut capture)?; + let preview = owner + .prepare_unlock() + .map_err(|_| Error::RecoveryRequired)?; + if preview.workspace_id != destination { + return Err(Error::Changed); + } + if !self.ask( + permit, + &mut capture, + RecoveryStep::Unlock, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + owner + .confirm(&preview.id, &scoped) + .map_err(|_| Error::RecoveryRequired)?; + } + self.checkpoint(permit, &mut capture)?; + if archive_matches(&mut owner, &scoped, &capture)? { + if !self.ask( + permit, + &mut capture, + RecoveryStep::RecordCopied, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + } else { + let backup = WorkspaceBackup::decode(capture.archive().map_err(|_| Error::Changed)?) + .map_err(|_| Error::Changed)?; + let plan = owner + .prepare_adoption_restore( + &scoped, + &backup, + capture.schema_version().map_err(|_| Error::Changed)?, + ) + .map_err(|_| Error::RecoveryRequired)?; + if !self.ask( + permit, + &mut capture, + RecoveryStep::Restore, + &destination, + &mut confirmation, + )? { + return Ok(RecoveryOutcome::Cancelled); + } + owner + .restore_adoption(&scoped, &backup, &plan) + .map_err(|_| Error::RecoveryRequired)?; + } + self.checkpoint(permit, &mut capture)?; + parity(&mut owner, &scoped, &capture)?; + self.checkpoint(permit, &mut capture)?; + let copied = self.journal.next(Phase::Copied, Some(destination), None)?; + self.journal.append(copied)?; + self.checkpoint(permit, &mut capture)?; + owner.lock(); + capture.cancel(); + Ok(RecoveryOutcome::Copied) + } +} +macro_rules! redacted { + ($kind:ty, $name:literal) => { + impl std::fmt::Debug for $kind { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str($name) + } + } + }; +} +redacted!(Conversion, "Conversion()"); +redacted!(Verification, "Verification()"); +redacted!(CopyConsent, "CopyConsent()"); +redacted!(VerifyConsent, "VerifyConsent()"); + +fn revalidate(anchor: &Path, capture: &mut ExistingWorkspaceCapture) -> Result<(), Error> { + Workspace::new(StartupRoots::new(anchor.to_owned()).legacy()) + .revalidate_existing_capture(capture) + .map_err(|_| Error::Changed) +} +fn matches(record: &Record, capture: &ExistingWorkspaceCapture) -> Result<(), Error> { + if capture.schema_version().map_err(|_| Error::Changed)? != record.source_schema + || capture.digest().map_err(|_| Error::Changed)? != record.source_archive + || capture.identity_fingerprint().map_err(|_| Error::Changed)? != record.source_identity + || Inventory::from(capture.inventory().map_err(|_| Error::Changed)?) != record.inventory + { + return Err(Error::Changed); + } + Ok(()) +} +fn parity( + owner: &mut Owner, + vault: &impl Vault, + capture: &ExistingWorkspaceCapture, +) -> Result<(), Error> { + if archive_matches(owner, vault, capture)? { + Ok(()) + } else { + Err(Error::Changed) + } +} +fn archive_matches( + owner: &mut Owner, + vault: &impl Vault, + capture: &ExistingWorkspaceCapture, +) -> Result { + let exported = Zeroizing::new( + owner + .export_workflow_backup(vault) + .map_err(|_| Error::RecoveryRequired)?, + ); + Ok(exported.as_slice() == capture.archive().map_err(|_| Error::Changed)?) +} + +impl Conversion { + #[cfg(feature = "encrypted-workspace")] + pub(super) fn revalidate_native(&mut self, permit: &StartupPermit<'_>) -> Result<(), Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + revalidate(&self.anchor, &mut self.capture)?; + matches(&self.intent, &self.capture) + } + #[cfg(test)] + pub(super) fn prepare(anchor: PathBuf) -> Result { + Self::prepare_checked(anchor, &mut || Ok(())) + } + #[cfg(feature = "encrypted-workspace")] + pub(super) fn prepare_native( + anchor: PathBuf, + permit: &StartupPermit<'_>, + ) -> Result { + let mut prepared = Self::prepare_checked(anchor, &mut || { + permit.checkpoint().map_err(|_| Error::Unavailable) + })?; + prepared.native_binding = Some(permit.binding().map_err(|_| Error::Unavailable)?); + Ok(prepared) + } + fn prepare_checked( + anchor: PathBuf, + checkpoint: &mut dyn FnMut() -> Result<(), Error>, + ) -> Result { + checkpoint()?; + if !cfg!(unix) { + return Err(Error::UnsupportedPlatform); + } + if !cfg!(feature = "encrypted-workspace") { + return Err(Error::BackendUnavailable); + } + absent(&anchor.join(DIRECTORY))?; + let roots = StartupRoots::new(anchor.clone()); + if roots.inspect().state() != StartupState::LegacyCandidate { + return Err(Error::RecoveryRequired); + } + let capture = roots + .capture_existing() + .map_err(|_| Error::Unavailable)? + .into_adoption_capture() + .map_err(|_| Error::Changed)?; + checkpoint()?; + let intent = Record { + schema_version: records::SCHEMA.into(), + phase: Phase::Intent, + attempt_id: WorkspaceId::generate() + .map_err(|_| Error::Unavailable)? + .as_hex(), + creator_process: process_identity()?.into(), + previous_digest: None, + source_identity: capture.identity_fingerprint().map_err(|_| Error::Changed)?, + source_archive: capture.digest().map_err(|_| Error::Changed)?.into(), + source_schema: capture.schema_version().map_err(|_| Error::Changed)?, + target_schema: capture.schema_version().map_err(|_| Error::Changed)?.max(1), + inventory: Inventory::from(capture.inventory().map_err(|_| Error::Changed)?), + destination: None, + verifier_process: None, + }; + let token = WorkspaceId::generate() + .map_err(|_| Error::Unavailable)? + .as_hex(); + Ok(Self { + anchor, + capture, + intent, + token, + #[cfg(feature = "encrypted-workspace")] + native_binding: None, + }) + } + #[cfg(test)] + fn synthetic_consent(&self) -> CopyConsent { + CopyConsent { + token: self.token.clone(), + } + } + /// The trusted host supplies the native-sheet callback. IPC cannot supply + /// this result, manufacture the permit, or retain a cancelled capture. + #[cfg(feature = "encrypted-workspace")] + pub(super) fn confirm_native( + mut self, + permit: &StartupPermit<'_>, + confirmation: impl FnOnce() -> Consent, + ) -> Result, Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + revalidate(&self.anchor, &mut self.capture)?; + matches(&self.intent, &self.capture)?; + permit.checkpoint().map_err(|_| Error::Unavailable)?; + let outcome = confirmation(); + permit.checkpoint().map_err(|_| Error::Unavailable)?; + match outcome { + Consent::Approved => { + revalidate(&self.anchor, &mut self.capture)?; + matches(&self.intent, &self.capture)?; + permit.checkpoint().map_err(|_| Error::Unavailable)?; + let consent = CopyConsent { + token: self.token.clone(), + }; + Ok(Some((self, consent))) + } + Consent::Cancelled => { + self.capture.cancel(); + Ok(None) + } + Consent::Unavailable => { + self.capture.cancel(); + Err(Error::Unavailable) + } + } + } + #[cfg(feature = "encrypted-workspace")] + pub(super) fn copy_native( + self, + consent: CopyConsent, + vault: &impl Vault, + permit: &StartupPermit<'_>, + ) -> Result<(), Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + self.copy_checked(consent, vault, &mut || { + permit.checkpoint().map_err(|_| Error::Unavailable) + }) + } + #[cfg(test)] + pub(super) fn copy(self, consent: CopyConsent, vault: &impl Vault) -> Result<(), Error> { + self.copy_checked(consent, vault, &mut || Ok(())) + } + fn copy_checked( + mut self, + consent: CopyConsent, + vault: &impl Vault, + checkpoint: &mut dyn FnMut() -> Result<(), Error>, + ) -> Result<(), Error> { + checkpoint()?; + if consent.token != self.token { + return Err(Error::ConsentRequired); + } + revalidate(&self.anchor, &mut self.capture)?; + matches(&self.intent, &self.capture)?; + let roots = StartupRoots::new(self.anchor.clone()); + if roots.inspect().state() != StartupState::LegacyCandidate { + return Err(Error::Changed); + } + checkpoint()?; + let mut journal = Journal::create(&self.anchor)?; + checkpoint()?; + journal.append(self.intent)?; + checkpoint()?; + revalidate(&self.anchor, &mut self.capture)?; + absent(&roots.managed())?; + journal.check(None)?; + point("destination", "before_create")?; + revalidate(&self.anchor, &mut self.capture)?; + journal.check(None)?; + absent(&roots.managed())?; + checkpoint()?; + create_directory(&roots.managed())?; + sync(&self.anchor)?; + checkpoint()?; + point("destination", "after_create")?; + let mut owner = Owner::acquire(roots.managed()).map_err(|_| Error::RecoveryRequired)?; + checkpoint()?; + let prepared = owner + .prepare_create_empty() + .map_err(|_| Error::RecoveryRequired)?; + let target = journal.next(Phase::Target, Some(prepared.workspace_id.clone()), None)?; + checkpoint()?; + journal.append(target)?; + checkpoint()?; + revalidate(&self.anchor, &mut self.capture)?; + journal.check(None)?; + point("destination", "before_confirm")?; + revalidate(&self.anchor, &mut self.capture)?; + journal.check(None)?; + checkpoint()?; + owner + .confirm(&prepared.id, vault) + .map_err(|_| Error::RecoveryRequired)?; + checkpoint()?; + point("destination", "after_confirm")?; + revalidate(&self.anchor, &mut self.capture)?; + journal.check(None)?; + let backup = WorkspaceBackup::decode(self.capture.archive().map_err(|_| Error::Changed)?) + .map_err(|_| Error::Changed)?; + checkpoint()?; + let plan = owner + .prepare_adoption_restore( + vault, + &backup, + self.capture.schema_version().map_err(|_| Error::Changed)?, + ) + .map_err(|_| Error::RecoveryRequired)?; + checkpoint()?; + point("destination", "before_restore")?; + revalidate(&self.anchor, &mut self.capture)?; + journal.check(None)?; + checkpoint()?; + owner + .restore_adoption(vault, &backup, &plan) + .map_err(|_| Error::RecoveryRequired)?; + checkpoint()?; + point("destination", "after_restore")?; + parity(&mut owner, vault, &self.capture)?; + checkpoint()?; + revalidate(&self.anchor, &mut self.capture)?; + let copied = journal.next(Phase::Copied, Some(prepared.workspace_id), None)?; + checkpoint()?; + journal.append(copied)?; + checkpoint()?; + owner.lock(); + self.capture.cancel(); + point("destination", "after_close")?; + Ok(()) + } +} + +impl Verification { + #[cfg(feature = "encrypted-workspace")] + pub(super) fn revalidate_native(&mut self, permit: &StartupPermit<'_>) -> Result<(), Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + revalidate(&self.anchor, &mut self.capture)?; + self.journal.check(None) + } + #[cfg(test)] + pub(super) fn prepare(anchor: PathBuf) -> Result { + Self::prepare_checked(anchor, &mut || Ok(())) + } + #[cfg(feature = "encrypted-workspace")] + pub(super) fn prepare_native( + anchor: PathBuf, + permit: &StartupPermit<'_>, + ) -> Result { + let mut prepared = Self::prepare_checked(anchor, &mut || { + permit.checkpoint().map_err(|_| Error::Unavailable) + })?; + prepared.native_binding = Some(permit.binding().map_err(|_| Error::Unavailable)?); + Ok(prepared) + } + fn prepare_checked( + anchor: PathBuf, + checkpoint: &mut dyn FnMut() -> Result<(), Error>, + ) -> Result { + checkpoint()?; + if !cfg!(unix) { + return Err(Error::UnsupportedPlatform); + } + if !cfg!(feature = "encrypted-workspace") { + return Err(Error::BackendUnavailable); + } + let journal = Journal::open(&anchor)?; + let last = &journal + .records + .last() + .ok_or(Error::RecoveryRequired)? + .record; + if last.phase != Phase::Copied { + return Err(Error::RecoveryRequired); + } + if last.creator_process == process_identity()? { + return Err(Error::SameProcess); + } + let roots = StartupRoots::new(anchor.clone()); + if roots.inspect().state() != StartupState::Mixed { + return Err(Error::RecoveryRequired); + } + let capture = Workspace::new(roots.legacy()) + .capture_existing_snapshot() + .map_err(|_| Error::Changed)?; + matches(last, &capture)?; + checkpoint()?; + let mut owner = + Owner::acquire_existing(roots.managed()).map_err(|_| Error::RecoveryRequired)?; + let preview = owner + .prepare_unlock() + .map_err(|_| Error::RecoveryRequired)?; + if last.destination.as_deref() != Some(preview.workspace_id.as_str()) { + return Err(Error::Changed); + } + checkpoint()?; + let token = WorkspaceId::generate() + .map_err(|_| Error::Unavailable)? + .as_hex(); + Ok(Self { + anchor, + journal, + capture, + owner, + preview: preview.id, + token, + #[cfg(feature = "encrypted-workspace")] + native_binding: None, + }) + } + #[cfg(test)] + fn synthetic_consent(&self) -> VerifyConsent { + VerifyConsent { + token: self.token.clone(), + } + } + #[cfg(feature = "encrypted-workspace")] + pub(super) fn confirm_native( + mut self, + permit: &StartupPermit<'_>, + confirmation: impl FnOnce() -> Consent, + ) -> Result, Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + revalidate(&self.anchor, &mut self.capture)?; + self.journal.check(None)?; + permit.checkpoint().map_err(|_| Error::Unavailable)?; + let outcome = confirmation(); + permit.checkpoint().map_err(|_| Error::Unavailable)?; + match outcome { + Consent::Approved => { + revalidate(&self.anchor, &mut self.capture)?; + self.journal.check(None)?; + permit.checkpoint().map_err(|_| Error::Unavailable)?; + let consent = VerifyConsent { + token: self.token.clone(), + }; + Ok(Some((self, consent))) + } + Consent::Cancelled => Ok(None), + Consent::Unavailable => Err(Error::Unavailable), + } + } + #[cfg(feature = "encrypted-workspace")] + pub(super) fn select_native( + self, + consent: VerifyConsent, + vault: &impl Vault, + permit: &StartupPermit<'_>, + ) -> Result<(), Error> { + permit + .check_binding(self.native_binding.as_ref().ok_or(Error::Unavailable)?) + .map_err(|_| Error::Unavailable)?; + self.select_checked(consent, vault, &mut || { + permit.checkpoint().map_err(|_| Error::Unavailable) + }) + } + #[cfg(test)] + pub(super) fn select(self, consent: VerifyConsent, vault: &impl Vault) -> Result<(), Error> { + self.select_checked(consent, vault, &mut || Ok(())) + } + fn select_checked( + mut self, + consent: VerifyConsent, + vault: &impl Vault, + checkpoint: &mut dyn FnMut() -> Result<(), Error>, + ) -> Result<(), Error> { + checkpoint()?; + if consent.token != self.token { + return Err(Error::ConsentRequired); + } + revalidate(&self.anchor, &mut self.capture)?; + self.journal.check(None)?; + checkpoint()?; + self.owner + .confirm(&self.preview, vault) + .map_err(|_| Error::RecoveryRequired)?; + checkpoint()?; + point("verification", "after_unlock")?; + parity(&mut self.owner, vault, &self.capture)?; + checkpoint()?; + revalidate(&self.anchor, &mut self.capture)?; + let destination = self + .journal + .records + .last() + .ok_or(Error::RecoveryRequired)? + .record + .destination + .clone(); + let verifier = Some(process_identity()?.into()); + let reopened = self + .journal + .next(Phase::Reopened, destination.clone(), verifier.clone())?; + checkpoint()?; + self.journal.append(reopened)?; + checkpoint()?; + point("verification", "before_selection")?; + revalidate(&self.anchor, &mut self.capture)?; + checkpoint()?; + parity(&mut self.owner, vault, &self.capture)?; + let selected = self.journal.next(Phase::Selected, destination, verifier)?; + checkpoint()?; + self.journal.append(selected)?; + checkpoint()?; + self.owner.lock(); + self.capture.cancel(); + Ok(()) + } +} +impl Drop for Verification { + fn drop(&mut self) { + self.owner.lock(); + self.capture.cancel(); + } +} + +#[cfg(test)] +#[path = "workspace_adoption_tests.rs"] +mod tests; diff --git a/apps/desktop/src/workspace_adoption_owner_tests.rs b/apps/desktop/src/workspace_adoption_owner_tests.rs new file mode 100644 index 0000000..479b1bf --- /dev/null +++ b/apps/desktop/src/workspace_adoption_owner_tests.rs @@ -0,0 +1,169 @@ +//! Synthetic Owner transfer and uncertain-write tests. No OS vault. +#[cfg(feature = "encrypted-workspace")] +use super::*; + +#[cfg(feature = "encrypted-workspace")] +mod fixture { + use super::*; + use std::{ + cell::{Cell, RefCell}, + collections::BTreeMap, + rc::Rc, + }; + #[derive(Clone, Default)] + pub(super) struct TestVault { + pub records: Rc>>>, + pub writes: Rc>, + } + pub(super) struct Slot { + identity: WorkspaceId, + vault: TestVault, + } + impl Vault for TestVault { + type Slot = Slot; + fn open(&self, identity: &WorkspaceId) -> Result { + Ok(Slot { + identity: identity.clone(), + vault: self.clone(), + }) + } + } + impl Store for Slot { + fn identity(&self) -> &WorkspaceId { + &self.identity + } + fn read(&self) -> Result>>, workspace_keys::Error> { + Ok(self + .vault + .records + .borrow() + .get(&self.identity.as_hex()) + .cloned() + .map(zeroize::Zeroizing::new)) + } + fn write(&self, bytes: &[u8]) -> Result<(), workspace_keys::Error> { + self.vault.writes.set(self.vault.writes.get() + 1); + self.vault + .records + .borrow_mut() + .insert(self.identity.as_hex(), bytes.to_vec()); + Ok(()) + } + } + pub(super) struct Root(pub PathBuf); + impl Root { + pub fn new() -> Self { + let path = std::env::temp_dir().canonicalize().unwrap().join(format!( + "rangoon-owner-adoption-{}", + WorkspaceId::generate().unwrap().as_hex() + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Root { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + pub(super) fn source(root: &Root) -> WorkspaceBackup { + let workspace = Workspace::new(root.0.join("source")); + workspace + .save(&rangoon_import::analyze("AGENTS.md", b"# Transfer\nExact original.\n").unwrap()) + .unwrap(); + WorkspaceBackup::decode(&workspace.export_workflow_backup().unwrap()).unwrap() + } + pub(super) fn empty(root: &Root, vault: &TestVault) -> (Owner, Preview) { + let path = root.0.join("managed"); + fs::create_dir(&path).unwrap(); + let mut owner = Owner::acquire(path).unwrap(); + let preview = owner.prepare_create_empty().unwrap(); + owner.confirm(&preview.id, vault).unwrap(); + (owner, preview) + } +} + +#[cfg(feature = "encrypted-workspace")] +use fixture::*; + +#[test] +#[cfg(feature = "encrypted-workspace")] +fn owner_strict_transfer_is_exact_and_reopens_with_existing_slot_only() { + let root = Root::new(); + let vault = TestVault::default(); + let backup = source(&root); + let (mut owner, preview) = empty(&root, &vault); + let plan = owner.prepare_adoption_restore(&vault, &backup, 1).unwrap(); + owner.restore_adoption(&vault, &backup, &plan).unwrap(); + let expected = owner.export_workflow_backup(&vault).unwrap(); + assert_eq!(owner.list(&vault).unwrap().len(), 1); + owner.lock(); + drop(owner); + let mut owner = Owner::acquire(root.0.join("managed")).unwrap(); + let unlock = owner.prepare_unlock().unwrap(); + assert_eq!(unlock.workspace_id, preview.workspace_id); + owner.confirm(&unlock.id, &vault).unwrap(); + assert!(owner.export_workflow_backup(&vault).unwrap() == expected); + assert_eq!(vault.writes.get(), 1); + assert!(owner.prepare_adoption_restore(&vault, &backup, 1).is_err()); +} + +#[test] +#[cfg(feature = "encrypted-workspace")] +fn owner_uncertain_transfer_locks_and_retains_real_restore_recovery() { + let root = Root::new(); + let vault = TestVault::default(); + let backup = source(&root); + let (mut owner, _) = empty(&root, &vault); + let plan = owner.prepare_adoption_restore(&vault, &backup, 1).unwrap(); + owner.inject_fault(Fault::AfterRestore); + assert!(matches!( + owner.restore_adoption(&vault, &backup, &plan), + Err(Error::WriteUncertain) + )); + assert!(!owner.is_unlocked()); + assert!(owner.requires_recovery()); + drop(owner); + let mut owner = Owner::acquire(root.0.join("managed")).unwrap(); + assert!(matches!( + owner.prepare_unlock(), + Err(Error::RecoveryRequired) + )); + assert_eq!(vault.writes.get(), 1); +} + +#[test] +#[cfg(feature = "encrypted-workspace")] +fn owner_transfer_intent_and_completion_failures_cannot_leave_an_unlocked_client() { + for fault in [Fault::BeforeIntentWrite, Fault::BeforeCompletionWrite] { + let root = Root::new(); + let vault = TestVault::default(); + let backup = source(&root); + let (mut owner, _) = empty(&root, &vault); + let plan = owner.prepare_adoption_restore(&vault, &backup, 1).unwrap(); + owner.inject_fault(fault); + assert!(owner.restore_adoption(&vault, &backup, &plan).is_err()); + assert!(!owner.is_unlocked()); + assert!(owner.requires_recovery()); + assert_eq!(vault.writes.get(), 1); + } +} + +#[test] +#[cfg(feature = "encrypted-workspace")] +fn missing_key_after_transfer_is_not_replaced() { + let root = Root::new(); + let vault = TestVault::default(); + let backup = source(&root); + let (mut owner, _) = empty(&root, &vault); + let plan = owner.prepare_adoption_restore(&vault, &backup, 1).unwrap(); + owner.restore_adoption(&vault, &backup, &plan).unwrap(); + owner.lock(); + drop(owner); + vault.records.borrow_mut().clear(); + let mut owner = Owner::acquire(root.0.join("managed")).unwrap(); + let preview = owner.prepare_unlock().unwrap(); + assert!(owner.confirm(&preview.id, &vault).is_err()); + assert!(!owner.is_unlocked()); + assert_eq!(vault.writes.get(), 1); +} diff --git a/apps/desktop/src/workspace_adoption_record.rs b/apps/desktop/src/workspace_adoption_record.rs new file mode 100644 index 0000000..9b397bb --- /dev/null +++ b/apps/desktop/src/workspace_adoption_record.rs @@ -0,0 +1,172 @@ +//! Bounded local conversion metadata. These records are not authorization. +use super::Error; +use rangoon_desktop::workspace_keys::WorkspaceId; +use rangoon_store::WorkflowRecoveryCounts; +use serde::{Deserialize, Serialize}; + +pub(super) const LIMIT: usize = 4096; +pub(super) const SCHEMA: &str = "rangoon.workspace-adoption.v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Phase { + Intent, + Target, + Copied, + Reopened, + Selected, +} +impl Phase { + pub(super) const ALL: [Self; 5] = [ + Self::Intent, + Self::Target, + Self::Copied, + Self::Reopened, + Self::Selected, + ]; + pub(super) fn index(self) -> usize { + Self::ALL + .iter() + .position(|p| *p == self) + .expect("closed phase") + } + pub(super) fn name(self) -> &'static str { + [ + "intent.json", + "target.json", + "copied.json", + "reopened.json", + "selected.json", + ][self.index()] + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Inventory { + sources: u32, + capabilities: u32, + revisions: u32, + reviews: u32, + recipes: u32, + applications: u32, + derivations: u32, + workflows: u32, + workflow_revisions: u32, +} +impl From<&WorkflowRecoveryCounts> for Inventory { + fn from(value: &WorkflowRecoveryCounts) -> Self { + Self { + sources: value.sources, + capabilities: value.capabilities, + revisions: value.revisions, + reviews: value.reviews, + recipes: value.recipes, + applications: value.applications, + derivations: value.derivations, + workflows: value.workflows, + workflow_revisions: value.workflow_revisions, + } + } +} + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Record { + pub(super) schema_version: String, + pub(super) phase: Phase, + pub(super) attempt_id: String, + pub(super) creator_process: String, + pub(super) previous_digest: Option, + pub(super) source_identity: String, + pub(super) source_archive: String, + pub(super) source_schema: u32, + pub(super) target_schema: u32, + pub(super) inventory: Inventory, + pub(super) destination: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) verifier_process: Option, +} +impl std::fmt::Debug for Record { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("AdoptionRecord()") + } +} +pub(super) fn hex(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +impl Record { + pub(super) fn encode(&self) -> Result, Error> { + let bytes = serde_json::to_vec(self).map_err(|_| Error::RecoveryRequired)?; + Self::decode(&bytes)?; + Ok(bytes) + } + pub(super) fn decode(bytes: &[u8]) -> Result { + if bytes.is_empty() || bytes.len() > LIMIT { + return Err(Error::RecoveryRequired); + } + // The typed pass rejects duplicates before any Value-based presence check. + let value: Self = serde_json::from_slice(bytes).map_err(|_| Error::RecoveryRequired)?; + let presence: serde_json::Value = + serde_json::from_slice(bytes).map_err(|_| Error::RecoveryRequired)?; + let object = presence.as_object().ok_or(Error::RecoveryRequired)?; + let base = [ + "schemaVersion", + "phase", + "attemptId", + "creatorProcess", + "previousDigest", + "sourceIdentity", + "sourceArchive", + "sourceSchema", + "targetSchema", + "inventory", + "destination", + ]; + let verified = matches!(value.phase, Phase::Reopened | Phase::Selected); + if object.len() != base.len() + usize::from(verified) + || base.iter().any(|key| !object.contains_key(*key)) + || object.contains_key("verifierProcess") != verified + || value.schema_version != SCHEMA + || WorkspaceId::parse(&value.attempt_id).is_err() + || WorkspaceId::parse(&value.creator_process).is_err() + || !hex(&value.source_identity) + || !hex(&value.source_archive) + || value.source_schema > 4 + || value.target_schema != value.source_schema.max(1) + || (value.phase == Phase::Intent + && (value.previous_digest.is_some() || value.destination.is_some())) + || (value.phase != Phase::Intent + && (!value.previous_digest.as_deref().is_some_and(hex) + || !value + .destination + .as_deref() + .is_some_and(|id| WorkspaceId::parse(id).is_ok()))) + || (verified + && !value.verifier_process.as_deref().is_some_and(|id| { + WorkspaceId::parse(id).is_ok() && id != value.creator_process + })) + { + return Err(Error::RecoveryRequired); + } + Ok(value) + } + pub(super) fn same_binding(&self, previous: &Self) -> bool { + self.attempt_id == previous.attempt_id + && self.creator_process == previous.creator_process + && self.source_identity == previous.source_identity + && self.source_archive == previous.source_archive + && self.source_schema == previous.source_schema + && self.target_schema == previous.target_schema + && self.inventory == previous.inventory + && (previous.phase == Phase::Intent || self.destination == previous.destination) + && (self.phase != Phase::Selected || self.verifier_process == previous.verifier_process) + } +} + +#[cfg(test)] +#[path = "workspace_adoption_record_tests.rs"] +mod tests; diff --git a/apps/desktop/src/workspace_adoption_record_tests.rs b/apps/desktop/src/workspace_adoption_record_tests.rs new file mode 100644 index 0000000..7807684 --- /dev/null +++ b/apps/desktop/src/workspace_adoption_record_tests.rs @@ -0,0 +1,304 @@ +use super::*; + +const ATTEMPT: &str = "1111111111111111111111111111111111111111111111111111111111111111"; +const CREATOR: &str = "2222222222222222222222222222222222222222222222222222222222222222"; +const DESTINATION: &str = "3333333333333333333333333333333333333333333333333333333333333333"; +const OTHER_DESTINATION: &str = "4444444444444444444444444444444444444444444444444444444444444444"; +const VERIFIER: &str = "5555555555555555555555555555555555555555555555555555555555555555"; +const OTHER_VERIFIER: &str = "6666666666666666666666666666666666666666666666666666666666666666"; +const PREVIOUS: &str = "7777777777777777777777777777777777777777777777777777777777777777"; +const SOURCE_IDENTITY: &str = "8888888888888888888888888888888888888888888888888888888888888888"; +const SOURCE_ARCHIVE: &str = "9999999999999999999999999999999999999999999999999999999999999999"; + +fn record_json(phase: &str, source_schema: u32) -> String { + let target_schema = source_schema.max(1); + let (previous_digest, destination) = if phase == "intent" { + ("null".to_owned(), "null".to_owned()) + } else { + (format!("\"{PREVIOUS}\""), format!("\"{DESTINATION}\"")) + }; + let verifier = match phase { + "reopened" | "selected" => format!(",\"verifierProcess\":\"{VERIFIER}\""), + _ => String::new(), + }; + format!( + r#"{{"schemaVersion":"rangoon.workspace-adoption.v1","phase":"{phase}","attemptId":"{ATTEMPT}","creatorProcess":"{CREATOR}","previousDigest":{previous_digest},"sourceIdentity":"{SOURCE_IDENTITY}","sourceArchive":"{SOURCE_ARCHIVE}","sourceSchema":{source_schema},"targetSchema":{target_schema},"inventory":{{"sources":3,"capabilities":4,"revisions":5,"reviews":6,"recipes":7,"applications":8,"derivations":9,"workflows":10,"workflowRevisions":11}},"destination":{destination}{verifier}}}"# + ) +} + +fn decoded(phase: &str, source_schema: u32) -> Record { + Record::decode(record_json(phase, source_schema).as_bytes()).expect("valid literal fixture") +} + +fn with_root_field(mut input: String, field: &str, value: &str) -> String { + assert_eq!(input.pop(), Some('}'), "fixture object closes"); + format!("{input},\"{field}\":{value}}}") +} + +fn refuses(bytes: &[u8], case: &str) { + assert!( + matches!(Record::decode(bytes), Err(Error::RecoveryRequired)), + "accepted {case}" + ); +} + +#[test] +fn codec_accepts_every_phase_and_supported_source_schema() { + let phases = [ + ("intent", Phase::Intent, false), + ("target", Phase::Target, false), + ("copied", Phase::Copied, false), + ("reopened", Phase::Reopened, true), + ("selected", Phase::Selected, true), + ]; + + for (name, phase, verified) in phases { + for source_schema in 0..=4 { + let record = decoded(name, source_schema); + assert_eq!(record.phase, phase, "{name} schema {source_schema}"); + assert_eq!(record.source_schema, source_schema); + assert_eq!(record.target_schema, source_schema.max(1)); + assert_eq!(record.previous_digest.is_none(), phase == Phase::Intent); + assert_eq!(record.destination.is_none(), phase == Phase::Intent); + assert_eq!(record.verifier_process.is_some(), verified); + + let encoded = record.encode().expect("encode validated fixture"); + assert_eq!( + Record::decode(&encoded).expect("decode encoded fixture"), + record, + "{name} schema {source_schema}" + ); + } + } +} + +#[test] +fn codec_refuses_malformed_extra_and_oversized_json() { + refuses(b"", "empty input"); + refuses(b"{", "malformed object"); + + let duplicate = record_json("intent", 0).replacen( + "\"phase\":\"intent\"", + "\"phase\":\"intent\",\"phase\":\"target\"", + 1, + ); + refuses(duplicate.as_bytes(), "duplicate field"); + + let unknown = with_root_field(record_json("intent", 0), "untrusted", "true"); + refuses(unknown.as_bytes(), "unknown field"); + + let mut extra = record_json("intent", 0).into_bytes(); + extra.extend_from_slice(b"{}"); + refuses(&extra, "extra JSON value"); + + let oversized = vec![b' '; LIMIT + 1]; + refuses(&oversized, "over-limit input"); +} + +#[test] +fn codec_refuses_missing_or_untyped_inventory_fields() { + let base = record_json("reopened", 4); + let required = [ + "schemaVersion", + "phase", + "attemptId", + "creatorProcess", + "previousDigest", + "sourceIdentity", + "sourceArchive", + "sourceSchema", + "targetSchema", + "inventory", + "destination", + "verifierProcess", + ]; + for field in required { + let mut value: serde_json::Value = serde_json::from_str(&base).expect("fixture JSON"); + value.as_object_mut().expect("fixture object").remove(field); + let bytes = serde_json::to_vec(&value).expect("fixture bytes"); + refuses(&bytes, &format!("missing {field}")); + } + + for field in [ + "sources", + "capabilities", + "revisions", + "reviews", + "recipes", + "applications", + "derivations", + "workflows", + "workflowRevisions", + ] { + let mut value: serde_json::Value = serde_json::from_str(&base).expect("fixture JSON"); + value + .get_mut("inventory") + .and_then(serde_json::Value::as_object_mut) + .expect("fixture inventory") + .remove(field); + let bytes = serde_json::to_vec(&value).expect("fixture bytes"); + refuses(&bytes, &format!("missing inventory {field}")); + } + + let overflow = base.replacen("\"sources\":3", "\"sources\":4294967296", 1); + refuses(overflow.as_bytes(), "u32 inventory overflow"); + + let inventory_unknown = base.replacen( + "\"workflowRevisions\":11}", + "\"workflowRevisions\":11,\"surplus\":12}", + 1, + ); + refuses(inventory_unknown.as_bytes(), "unknown inventory field"); +} + +#[test] +fn codec_refuses_noncanonical_identifiers_and_schema_mappings() { + let zero = "0".repeat(64); + let uppercase = "A".repeat(64); + + let zero_attempt = record_json("intent", 1).replacen(ATTEMPT, &zero, 1); + refuses(zero_attempt.as_bytes(), "zero attempt identifier"); + + let zero_creator = record_json("intent", 1).replacen(CREATOR, &zero, 1); + refuses(zero_creator.as_bytes(), "zero creator identifier"); + + let zero_destination = record_json("target", 1).replacen(DESTINATION, &zero, 1); + refuses(zero_destination.as_bytes(), "zero destination identifier"); + + let uppercase_identity = record_json("intent", 1).replacen(SOURCE_IDENTITY, &uppercase, 1); + refuses(uppercase_identity.as_bytes(), "uppercase source identity"); + + let short_archive = record_json("intent", 1).replacen(SOURCE_ARCHIVE, "abc", 1); + refuses(short_archive.as_bytes(), "short source archive"); + + let uppercase_previous = record_json("target", 1).replacen(PREVIOUS, &uppercase, 1); + refuses(uppercase_previous.as_bytes(), "uppercase previous digest"); + + let zero_verifier = record_json("reopened", 1).replacen(VERIFIER, &zero, 1); + refuses(zero_verifier.as_bytes(), "zero verifier identifier"); + + let unknown_phase = + record_json("intent", 1).replacen("\"phase\":\"intent\"", "\"phase\":\"unknown\"", 1); + refuses(unknown_phase.as_bytes(), "unknown phase"); + + let unsupported_source = record_json("target", 4) + .replacen("\"sourceSchema\":4", "\"sourceSchema\":5", 1) + .replacen("\"targetSchema\":4", "\"targetSchema\":5", 1); + refuses(unsupported_source.as_bytes(), "unsupported source schema"); + + let zero_target = + record_json("target", 0).replacen("\"targetSchema\":1", "\"targetSchema\":0", 1); + refuses(zero_target.as_bytes(), "schema zero target must be one"); + + let wrong_target = + record_json("target", 2).replacen("\"targetSchema\":2", "\"targetSchema\":1", 1); + refuses(wrong_target.as_bytes(), "source and target schema mismatch"); +} + +#[test] +fn codec_refuses_wrong_phase_fields_and_verifiers() { + let intent_previous = record_json("intent", 1).replacen( + "\"previousDigest\":null", + &format!("\"previousDigest\":\"{PREVIOUS}\""), + 1, + ); + refuses(intent_previous.as_bytes(), "intent previous digest"); + + let intent_destination = record_json("intent", 1).replacen( + "\"destination\":null", + &format!("\"destination\":\"{DESTINATION}\""), + 1, + ); + refuses(intent_destination.as_bytes(), "intent destination"); + + for phase in ["target", "copied", "reopened", "selected"] { + let no_previous = record_json(phase, 1).replacen( + &format!("\"previousDigest\":\"{PREVIOUS}\""), + "\"previousDigest\":null", + 1, + ); + refuses( + no_previous.as_bytes(), + &format!("{phase} missing previous digest"), + ); + + let no_destination = record_json(phase, 1).replacen( + &format!("\"destination\":\"{DESTINATION}\""), + "\"destination\":null", + 1, + ); + refuses( + no_destination.as_bytes(), + &format!("{phase} missing destination"), + ); + } + + for phase in ["intent", "target", "copied"] { + let first_phase_verifier = with_root_field( + record_json(phase, 1), + "verifierProcess", + &format!("\"{VERIFIER}\""), + ); + refuses( + first_phase_verifier.as_bytes(), + &format!("{phase} verifier present"), + ); + } + + for phase in ["reopened", "selected"] { + let no_verifier = + record_json(phase, 1).replacen(&format!(",\"verifierProcess\":\"{VERIFIER}\""), "", 1); + refuses(no_verifier.as_bytes(), &format!("{phase} verifier absent")); + + let creator_verifier = record_json(phase, 1).replacen(VERIFIER, CREATOR, 1); + refuses( + creator_verifier.as_bytes(), + &format!("{phase} verifier is creator"), + ); + } +} + +#[test] +fn same_binding_refuses_changed_common_destination_or_selected_verifier() { + let intent = decoded("intent", 3); + let target = decoded("target", 3); + assert!( + target.same_binding(&intent), + "intent permits first destination" + ); + + let changed_common = Record::decode( + record_json("target", 3) + .replacen(SOURCE_ARCHIVE, OTHER_VERIFIER, 1) + .as_bytes(), + ) + .expect("valid changed common fixture"); + assert!(!changed_common.same_binding(&intent)); + + let copied_other_destination = Record::decode( + record_json("copied", 3) + .replacen(DESTINATION, OTHER_DESTINATION, 1) + .as_bytes(), + ) + .expect("valid changed destination fixture"); + assert!(!copied_other_destination.same_binding(&target)); + + let reopened = decoded("reopened", 3); + let selected_other_verifier = Record::decode( + record_json("selected", 3) + .replacen(VERIFIER, OTHER_VERIFIER, 1) + .as_bytes(), + ) + .expect("valid changed verifier fixture"); + assert!(!selected_other_verifier.same_binding(&reopened)); +} + +#[test] +fn debug_is_fixed_redaction_for_synthetic_marker() { + let mut record = decoded("intent", 1); + record.source_archive = "synthetic-marker-must-not-log".to_owned(); + + let debug = format!("{record:?}"); + assert_eq!(debug, "AdoptionRecord()"); + assert!(!debug.contains("synthetic-marker-must-not-log")); +} diff --git a/apps/desktop/src/workspace_adoption_tests.rs b/apps/desktop/src/workspace_adoption_tests.rs new file mode 100644 index 0000000..b88e386 --- /dev/null +++ b/apps/desktop/src/workspace_adoption_tests.rs @@ -0,0 +1,2510 @@ +//! Disposable transfer, process-restart and crash-journal qualification. No OS vault. +use super::*; + +#[test] +fn unsupported_backend_does_not_create_an_attempt() { + if cfg!(feature = "encrypted-workspace") { + return; + } + let root = std::env::temp_dir().canonicalize().unwrap().join(format!( + "rangoon-adoption-absent-{}", + WorkspaceId::generate().unwrap().as_hex() + )); + assert!(matches!( + Conversion::prepare(root.clone()), + Err(Error::BackendUnavailable | Error::UnsupportedPlatform) + )); + assert!(!root.exists()); +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +mod fixture { + use super::*; + use rangoon_desktop::workspace_keys::{Error as KeyError, Store}; + use std::{ + process::{Child, Command, Stdio}, + time::{Duration, Instant}, + }; + pub(super) struct Root { + pub base: PathBuf, + pub anchor: PathBuf, + } + impl Root { + pub fn new(schema: u32, populated: bool) -> Self { + let base = std::env::temp_dir().canonicalize().unwrap().join(format!( + "rangoon-adoption-{}", + WorkspaceId::generate().unwrap().as_hex() + )); + fs::create_dir(&base).unwrap(); + fs::write(base.join("test-owner"), b"rangoon.e1c5b.disposable.v1").unwrap(); + let anchor = base.join("anchor"); + fs::create_dir(&anchor).unwrap(); + fs::create_dir(base.join("keys")).unwrap(); + let root = Self { base, anchor }; + root.source(schema, populated); + root + } + pub fn vault(&self) -> TestVault { + TestVault(self.base.join("keys")) + } + pub fn source(&self, schema: u32, populated: bool) { + let store = Workspace::new(self.anchor.join("source-workspace")); + if schema == 0 { + // Independent one-page empty SQLite fixture; the real existing-only + // reader must validate it before any adoption can proceed. + fs::create_dir(self.anchor.join("source-workspace")).unwrap(); + let mut bytes = vec![0; 4096]; + bytes[..16].copy_from_slice(b"SQLite format 3\0"); + bytes[16..18].copy_from_slice(&4096u16.to_be_bytes()); + bytes[18] = 1; + bytes[19] = 1; + bytes[21] = 64; + bytes[22] = 32; + bytes[23] = 32; + for (offset, value) in [ + (24, 1u32), + (28, 1), + (44, 4), + (56, 1), + (92, 1), + (96, 3040000), + ] { + bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + } + bytes[100] = 13; + bytes[105..107].copy_from_slice(&4096u16.to_be_bytes()); + fs::write( + self.anchor.join("source-workspace/workspace.sqlite3"), + bytes, + ) + .unwrap(); + } else { + let report = rangoon_import::analyze( + "AGENTS.md", + b"\xef\xbb\xbf# Rules\r\nKeep originals.\r\n# Tests\r\nCheck edits.\r\n", + ) + .unwrap(); + store.save(&report).unwrap(); + if schema >= 2 { + let cap = store + .create_capability( + &report.source.id, + &report.fragments[0].id, + "Transfer skill", + ) + .unwrap() + .capability; + store + .review_capability(&cap.id, &cap.latest_revision_id) + .unwrap(); + let revised = store + .revise_capability( + &cap.id, + &cap.latest_revision_id, + "Retained history", + "Reviewed historical content.\r\n", + ) + .unwrap() + .capability; + store + .review_capability(&revised.id, &revised.latest_revision_id) + .unwrap(); + } + if schema >= 3 { + let value: serde_json::Value = serde_json::from_str(include_str!( + "../../../fixtures/composition/decompose-v0.json" + )) + .unwrap(); + let request = rangoon_compose::application::Request { + schema_version: rangoon_compose::application::REQUEST_SCHEMA.into(), + draft: serde_json::from_value(value["draft"].clone()).unwrap(), + targets: vec![ + rangoon_compose::application::Target::New {}, + rangoon_compose::application::Target::New {}, + ], + }; + let preview = store.preview_composition(&request).unwrap(); + store.apply_composition(&preview, true).unwrap(); + } + if schema == 4 { + use rangoon_workflow::records::{ + SaveIntent, prepare_revision, workflow_id_from_nonce, + }; + let record=prepare_revision(&workflow_id_from_nonce(&[97;32]),None,SaveIntent::Draft,br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Transfer workflow","nodes":[],"controlEdges":[],"dataEdges":[]}"#,br#"{"positions":[]}"#).unwrap(); + let plan = store.inspect_workflow_save(&record).unwrap(); + store + .save_workflow(&record, &plan.expected_state_id) + .unwrap(); + let next = prepare_revision(&workflow_id_from_nonce(&[97;32]), Some(record.id()), SaveIntent::Draft, br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Retained workflow history","nodes":[],"controlEdges":[],"dataEdges":[]}"#, br#"{"positions":[]}"#).unwrap(); + let plan = store.inspect_workflow_save(&next).unwrap(); + store.save_workflow(&next, &plan.expected_state_id).unwrap(); + } + if !populated { + let data = store.workflow_data().unwrap(); + for workflow in data.workflows { + let plan = store + .inspect_workflow_deletion( + rangoon_store::WorkflowRecordKind::Workflow, + &workflow.id, + ) + .unwrap(); + store.delete_workflow_record(&plan).unwrap(); + } + let data = store.workflow_data().unwrap(); + for cap in data.capabilities { + let plan = store + .inspect_workflow_deletion( + rangoon_store::WorkflowRecordKind::Capability, + &cap.id, + ) + .unwrap(); + store.delete_workflow_record(&plan).unwrap(); + } + let data = store.workflow_data().unwrap(); + for source in data.sources { + let plan = store + .inspect_workflow_deletion( + rangoon_store::WorkflowRecordKind::Source, + &source.source_id, + ) + .unwrap(); + store.delete_workflow_record(&plan).unwrap(); + } + } + } + let capture = store.capture_existing_snapshot().unwrap(); + assert_eq!(capture.schema_version().unwrap(), schema); + } + pub fn copied(&self) { + let conversion = Conversion::prepare(self.anchor.clone()).unwrap(); + let consent = conversion.synthetic_consent(); + conversion.copy(consent, &self.vault()).unwrap(); + } + pub fn retain_expected_outputs(&self) { + let store = Workspace::new(self.anchor.join("source-workspace")); + if store + .capture_existing_snapshot() + .unwrap() + .schema_version() + .unwrap() + == 0 + { + fs::write(self.base.join("expected-outputs.json"), b"[]").unwrap(); + return; + } + let mut values = Vec::new(); + for source in store.list().unwrap() { + values.push(serde_json::to_value(store.open(&source.source_id).unwrap()).unwrap()); + } + for capability in store.list_capabilities_v1().unwrap() { + values.push( + serde_json::to_value(store.open_capability_v1(&capability.id, None).unwrap()) + .unwrap(), + ); + for profile in [ + rangoon_compile::Profile::AgentsMdV1, + rangoon_compile::Profile::ClaudeMdV1, + ] { + let compiled = store + .compile_capability(&capability.id, &capability.latest_revision_id, profile) + .unwrap(); + values.push(serde_json::to_value(&compiled).unwrap()); + if let Ok(bundle) = rangoon_compile::encode_bundle(&compiled.compilation) { + values.push(serde_json::json!({"bundle":bundle.bytes})); + } + } + } + fs::write( + self.base.join("expected-outputs.json"), + serde_json::to_vec(&values).unwrap(), + ) + .unwrap(); + } + pub fn spawn(&self, mode: &str, stage: Option<(&str, &str)>) -> Child { + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "workspace_adoption::tests::process_child", + "--ignored", + "--nocapture", + ]) + .env("RANGOON_E1C5B_TEST_ROOT", &self.base) + .env("RANGOON_E1C5B_TEST_MODE", mode) + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + if let Some((phase, boundary)) = stage { + command + .env("RANGOON_E1C5B_TEST_PHASE", phase) + .env("RANGOON_E1C5B_TEST_BOUNDARY", boundary); + } + command.spawn().unwrap() + } + } + impl Drop for Root { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.base); + } + } + #[derive(Clone)] + pub(super) struct TestVault(pub PathBuf); + pub(super) struct Slot { + id: WorkspaceId, + path: PathBuf, + } + impl Vault for TestVault { + type Slot = Slot; + fn open(&self, id: &WorkspaceId) -> Result { + point("vault", "before_open").map_err(|_| KeyError::Unavailable)?; + Ok(Slot { + id: id.clone(), + path: self.0.join(id.as_hex()), + }) + } + } + impl Store for Slot { + fn identity(&self) -> &WorkspaceId { + &self.id + } + fn read(&self) -> Result>>, KeyError> { + point("vault", "before_read").map_err(|_| KeyError::Unavailable)?; + match fs::read(&self.path) { + Ok(bytes) if bytes.len() <= 512 => Ok(Some(Zeroizing::new(bytes))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + _ => Err(KeyError::Unavailable), + } + } + fn write(&self, bytes: &[u8]) -> Result<(), KeyError> { + point("vault", "before_write").map_err(|_| KeyError::WriteUncertain)?; + let mut file = options(true) + .create_new(true) + .open(&self.path) + .map_err(|_| KeyError::WriteUncertain)?; + file.write_all(bytes) + .and_then(|_| file.sync_all()) + .map_err(|_| KeyError::WriteUncertain)?; + point("vault", "after_write").map_err(|_| KeyError::WriteUncertain) + } + } + pub(super) struct ChildGuard(pub Child); + impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + pub(super) fn kill_at(root: &Root, mode: &str, phase: &str, boundary: &str) { + let mut child = ChildGuard(root.spawn(mode, Some((phase, boundary)))); + let start = Instant::now(); + while !root.base.join("ready").exists() { + assert!( + child.0.try_wait().unwrap().is_none(), + "child exited before checkpoint" + ); + assert!( + start.elapsed() < Duration::from_secs(20), + "child checkpoint timeout" + ); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(child.0.try_wait().unwrap().is_none()); + child.0.kill().unwrap(); + assert!(!child.0.wait().unwrap().success()); + } + pub(super) fn intent() -> Record { + Record { + schema_version: records::SCHEMA.into(), + phase: Phase::Intent, + attempt_id: "1".repeat(64), + creator_process: "2".repeat(64), + previous_digest: None, + source_identity: "3".repeat(64), + source_archive: "4".repeat(64), + source_schema: 1, + target_schema: 1, + inventory: Inventory::from(&rangoon_store::WorkflowRecoveryCounts::default()), + destination: None, + verifier_process: None, + } + } + pub(super) fn append_phase(journal: &mut Journal, phase: Phase) { + let record = if phase == Phase::Intent { + intent() + } else { + journal + .next( + phase, + Some("5".repeat(64)), + if matches!(phase, Phase::Reopened | Phase::Selected) { + Some("6".repeat(64)) + } else { + None + }, + ) + .unwrap() + }; + journal.append(record).unwrap(); + } +} +#[cfg(all(unix, feature = "encrypted-workspace"))] +use crate::{ + workspace_close::{WorkspaceClose, setup::Consent}, + workspace_source_access::{ControlError, ControlKind, SourceAccess}, +}; +#[cfg(all(unix, feature = "encrypted-workspace"))] +use fixture::*; +#[cfg(all(unix, feature = "encrypted-workspace"))] +use rangoon_desktop::workspace_lifecycle::Gate; +#[cfg(all(unix, feature = "encrypted-workspace"))] +use serde_json::json; + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn control_identity(close: &WorkspaceClose) -> (String, String) { + let view = serde_json::to_value(close.inspect(|_| true)).unwrap(); + ( + view["attemptId"].as_str().unwrap().to_owned(), + view["epoch"].as_str().unwrap().to_owned(), + ) +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn acknowledgement(id: &str, epoch: &str) -> Vec { + serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-purge-ack.v1", + "attemptId": id, + "epoch": epoch, + })) + .unwrap() +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn startup_close(root: &Root) -> WorkspaceClose { + let access = SourceAccess::managed_deferred( + Gate::new(), + root.anchor.join("managed-workspace"), + root.vault(), + ); + let close = WorkspaceClose::new(access); + let started = serde_json::to_value(close.begin(|_| true)).unwrap(); + let id = started["attemptId"].as_str().unwrap().to_owned(); + let epoch = started["epoch"].as_str().unwrap().to_owned(); + let locked = + serde_json::to_value(close.acknowledge(&acknowledgement(&id, &epoch), |_| true)).unwrap(); + assert_eq!(locked["state"], "locked"); + close +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn acknowledge_startup_flight(close: &WorkspaceClose) { + let (id, epoch) = control_identity(close); + let view = + serde_json::to_value(close.acknowledge(&acknowledgement(&id, &epoch), |_| true)).unwrap(); + assert_eq!(view["state"], "closing"); +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn startup_action_request( + view: &serde_json::Value, + action: &str, +) -> crate::workspace_startup_host::ActionRequest { + crate::workspace_startup_host::ActionRequest::parse( + &serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-startup-action.v1", + "startupId": view["startupId"].as_str().unwrap(), + "attemptId": view["attemptId"].as_str().unwrap(), + "epoch": view["epoch"].as_str().unwrap(), + "action": action, + })) + .unwrap(), + ) + .unwrap() +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn assert_no_copy_effects(root: &Root) { + assert!(!root.anchor.join(DIRECTORY).exists()); + assert!(!root.anchor.join("managed-workspace").exists()); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 0); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn recovery_vault_scopes_existing_identity_and_never_delegates_write() { + use rangoon_desktop::{ + workspace_keys::{Error as KeyError, Store, WorkspaceId}, + workspace_session::Vault, + }; + use std::sync::{Arc, Mutex}; + + let root = Root::new(1, true); + let expected = WorkspaceId::generate().unwrap(); + let wrong = WorkspaceId::generate().unwrap(); + let counts = Arc::new(Mutex::new([0_usize; 2])); + PROBE.with(|probe| { + let counts = Arc::clone(&counts); + *probe.borrow_mut() = Some(Box::new(move |stage, boundary| { + let index = match (stage, boundary) { + ("vault", "before_open") => Some(0), + ("vault", "before_write") => Some(1), + _ => None, + }; + if let Some(index) = index { + counts.lock().unwrap()[index] += 1; + } + Ok(()) + })); + }); + let vault = root.vault(); + let scoped = RecoveryVault { + expected: &expected.as_hex(), + vault: &vault, + }; + + assert!(matches!(scoped.open(&wrong), Err(KeyError::Changed))); + assert_eq!(*counts.lock().unwrap(), [0, 0]); + let slot = scoped.open(&expected).unwrap(); + assert_eq!(*counts.lock().unwrap(), [1, 0]); + assert!(matches!( + slot.write(b"never write"), + Err(KeyError::Unavailable) + )); + assert_eq!(*counts.lock().unwrap(), [1, 0]); + PROBE.with(|probe| *probe.borrow_mut() = None); +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn interrupted_copy(root: &Root, boundary: &'static str) { + let conversion = Conversion::prepare(root.anchor.clone()).unwrap(); + let consent = conversion.synthetic_consent(); + PROBE.with(|probe| { + *probe.borrow_mut() = Some(Box::new(move |stage, current| { + if stage == "destination" && current == boundary { + return Err(Error::WriteUncertain); + } + Ok(()) + })); + }); + assert_eq!( + conversion.copy(consent, &root.vault()), + Err(Error::WriteUncertain) + ); + PROBE.with(|probe| *probe.borrow_mut() = None); + assert!(root.anchor.join(DIRECTORY).join("target.json").is_file()); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn killed_key_write_before_database_recovers_only_after_explicit_native_completion() { + let root = Root::new(4, true); + root.retain_expected_outputs(); + let source = Workspace::new(root.anchor.join("source-workspace")); + let mut capture = source.capture_existing_snapshot().unwrap(); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + + // The existing Store checkpoint follows a real synced envelope write and + // precedes its return to create_key. No record is forged or removed. + kill_at(&root, "copy", "vault", "after_write"); + let journal = Journal::open(&root.anchor).unwrap(); + let target = &journal.records.last().unwrap().record; + assert_eq!(target.phase, Phase::Target); + let destination = target.destination.as_ref().unwrap().clone(); + let attempt_id = target.attempt_id.clone(); + let database = root + .anchor + .join("managed-workspace/encrypted-workspaces") + .join(&destination) + .join("workspace.sqlite3"); + assert!(!database.exists()); + let binding_path = root + .anchor + .join("managed-workspace/encrypted-workspace.binding"); + let pending_path = root + .anchor + .join("managed-workspace/encrypted-workspace.operation.pending"); + let binding_before = fs::read(&binding_path).unwrap(); + let pending_before = fs::read(&pending_path).unwrap(); + let immutable_paths = [ + root.anchor.join(DIRECTORY).join("intent.json"), + root.anchor.join(DIRECTORY).join("target.json"), + ]; + let immutable: Vec<_> = immutable_paths + .iter() + .map(|path| fs::read(path).unwrap()) + .collect(); + drop(journal); + let key_path = root.vault().0.join(&destination); + let key = Zeroizing::new(fs::read(&key_path).unwrap()); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 1); + let run_child = |mode: &str| { + let mut child = ChildGuard(root.spawn(mode, None)); + let started = std::time::Instant::now(); + let status = loop { + if let Some(status) = child.0.try_wait().unwrap() { + break status; + } + if started.elapsed() >= std::time::Duration::from_secs(20) { + let _ = child.0.kill(); + let _ = child.0.wait(); + panic!("{mode} child timeout"); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + let mut diagnostics = String::new(); + if let Some(stderr) = child.0.stderr.take() { + stderr.take(8192).read_to_string(&mut diagnostics).unwrap(); + } + assert!(status.success(), "{mode} failed: {diagnostics}"); + }; + + // Cancelled native consent cannot repair the interrupted target or replace + // its existing key. Both paths are real fresh host processes. + for mode in [ + "recover-host-no-database-cancel-inspect", + "recover-host-no-database-cancel-initialize", + ] { + run_child(mode); + source.revalidate_existing_capture(&mut capture).unwrap(); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + for (path, previous) in immutable_paths.iter().zip(&immutable) { + assert_eq!(fs::read(path).unwrap(), *previous); + } + assert_eq!(fs::read(&binding_path).unwrap(), binding_before); + assert_eq!(fs::read(&pending_path).unwrap(), pending_before); + let current_key = Zeroizing::new(fs::read(&key_path).unwrap()); + assert!( + current_key.as_slice() == key.as_slice(), + "disposable key changed" + ); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 1); + assert!(!database.exists()); + assert!( + !root + .anchor + .join("managed-workspace/encrypted-workspace.operation.terminal") + .exists() + ); + for phase in [Phase::Copied, Phase::Reopened, Phase::Selected] { + assert!(!root.anchor.join(DIRECTORY).join(phase.name()).exists()); + } + } + + run_child("recover-host-no-database"); + source.revalidate_existing_capture(&mut capture).unwrap(); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + for (path, previous) in immutable_paths.iter().zip(&immutable) { + assert_eq!(fs::read(path).unwrap(), *previous); + } + let binding_after = fs::read(&binding_path).unwrap(); + assert_eq!(binding_after.len(), binding_before.len()); + assert_eq!(&binding_after[..29], &binding_before[..29]); + assert_eq!(binding_before[29], 0); + assert_eq!(binding_after[29], 1); + assert_eq!(&binding_after[30..], &binding_before[30..]); + // Initialize identity is checked at Unlock, before Restore starts its own attempt. + + let current_key = Zeroizing::new(fs::read(&key_path).unwrap()); + assert!( + current_key.as_slice() == key.as_slice(), + "disposable key changed" + ); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 1); + assert!(database.is_file()); + let journal = Journal::open(&root.anchor).unwrap(); + let copied = &journal.records.last().unwrap().record; + assert_eq!(copied.phase, Phase::Copied); + assert_eq!(copied.destination.as_deref(), Some(destination.as_str())); + assert_eq!(copied.attempt_id, attempt_id); + drop(journal); + + run_child("verify"); + assert!(root.anchor.join(DIRECTORY).join("reopened.json").is_file()); + assert!(root.anchor.join(DIRECTORY).join("selected.json").is_file()); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_restores_empty_target_after_interrupted_confirm() { + let root = Root::new(1, true); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + interrupted_copy(&root, "after_confirm"); + + let output = root + .spawn("recover-host-target-empty", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "empty target recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.anchor.join(DIRECTORY).join("copied.json").is_file()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_records_matching_target_after_interrupted_restore() { + let root = Root::new(1, true); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + interrupted_copy(&root, "after_restore"); + + let output = root + .spawn("recover-host-target-full", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "matching target recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.anchor.join(DIRECTORY).join("copied.json").is_file()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_reconciles_pending_terminal_before_recording_matching_target() { + let root = Root::new(1, true); + interrupted_copy(&root, "after_restore"); + let terminal = root + .anchor + .join("managed-workspace/encrypted-workspace.operation.terminal"); + assert!(terminal.is_file()); + fs::remove_file(&terminal).unwrap(); + + let output = root + .spawn("recover-host-target-pending", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "pending target recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(root.anchor.join(DIRECTORY).join("copied.json").is_file()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn third_process_host_recovery_completes_reopened_selection_without_rewriting_history() { + let root = Root::new(1, true); + root.copied(); + kill_at(&root, "verify", "verification", "before_selection"); + let reopened_path = root.anchor.join(DIRECTORY).join("reopened.json"); + let reopened = fs::read(&reopened_path).unwrap(); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + + let output = root + .spawn("recover-host-reopened", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "reopened selection recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fs::read(&reopened_path).unwrap(), reopened); + let reopened_record = Record::decode(&reopened).unwrap(); + let selected = + Record::decode(&fs::read(root.anchor.join(DIRECTORY).join("selected.json")).unwrap()) + .unwrap(); + assert_eq!(selected.verifier_process, reopened_record.verifier_process); + assert_eq!(inspect(&root.anchor), Status::SelectionRecorded); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_cancel_before_inspect_reoffers_rotated_token_without_vault_access() { + let root = Root::new(1, true); + interrupted_copy(&root, "after_confirm"); + + let output = root + .spawn("recover-host-cancel-inspect", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "inspect cancellation recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(root.anchor.join(DIRECTORY).join("target.json").is_file()); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_cancel_at_unlock_reoffers_rotated_token_and_retries() { + let root = Root::new(1, true); + interrupted_copy(&root, "after_restore"); + fs::remove_file( + root.anchor + .join("managed-workspace/encrypted-workspace.operation.terminal"), + ) + .unwrap(); + + let output = root + .spawn("recover-host-cancel-unlock", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "unlock cancellation recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(root.anchor.join(DIRECTORY).join("copied.json").is_file()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_record_copied_destination_drift_refuses_before_journal_append() { + let root = Root::new(1, true); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + interrupted_copy(&root, "after_restore"); + + let output = root + .spawn("recover-host-record-copied-drift", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "record-copied destination drift recovery failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.anchor.join(DIRECTORY).join("target.json").is_file()); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_missing_existing_key_refuses_without_regeneration() { + let root = Root::new(1, true); + interrupted_copy(&root, "after_restore"); + for entry in fs::read_dir(root.vault().0.clone()).unwrap() { + fs::remove_file(entry.unwrap().path()).unwrap(); + } + + let output = root + .spawn("recover-host-missing-key", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "missing recovery key refusal failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(root.anchor.join(DIRECTORY).join("target.json").is_file()); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 0); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_wrong_target_identity_refuses_before_vault_open() { + let root = Root::new(1, true); + interrupted_copy(&root, "after_restore"); + let target = root.anchor.join(DIRECTORY).join("target.json"); + let mut value: serde_json::Value = serde_json::from_slice(&fs::read(&target).unwrap()).unwrap(); + value["destination"] = serde_json::Value::String("e".repeat(64)); + fs::write(&target, serde_json::to_vec(&value).unwrap()).unwrap(); + + let output = root + .spawn("recover-host-wrong-target", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "wrong recovery target refusal failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_recovery_c1_revocation_during_confirmation_blocks_followup_effects() { + let root = Root::new(1, true); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + interrupted_copy(&root, "after_confirm"); + + let output = root + .spawn("recover-host-c1-revoked", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "recovery C1 revocation refusal failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.anchor.join(DIRECTORY).join("target.json").is_file()); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn preparation_cancel_bad_consent_and_drift_have_no_destination_or_key_effects() { + let root = Root::new(1, true); + let conversion = Conversion::prepare(root.anchor.clone()).unwrap(); + assert_eq!(format!("{conversion:?}"), "Conversion()"); + drop(conversion); + assert_eq!(inspect(&root.anchor), Status::NoAttempt); + assert!(!root.anchor.join("managed-workspace").exists()); + assert_eq!(fs::read_dir(&root.vault().0).unwrap().count(), 0); + let conversion = Conversion::prepare(root.anchor.clone()).unwrap(); + assert_eq!( + conversion.copy( + CopyConsent { + token: "f".repeat(64) + }, + &root.vault() + ), + Err(Error::ConsentRequired) + ); + assert_eq!(inspect(&root.anchor), Status::NoAttempt); + let conversion = Conversion::prepare(root.anchor.clone()).unwrap(); + let consent = conversion.synthetic_consent(); + Workspace::new(root.anchor.join("source-workspace")) + .save(&rangoon_import::analyze("SKILL.md", b"# Changed\n").unwrap()) + .unwrap(); + assert_eq!(conversion.copy(consent, &root.vault()), Err(Error::Changed)); + assert_eq!(inspect(&root.anchor), Status::NoAttempt); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn unacknowledged_startup_control_cannot_mint_native_permit_or_capture() { + let root = Root::new(1, true); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + + assert!(matches!( + flight.startup_permit(), + Err(ControlError::Unavailable) + )); + assert_no_copy_effects(&root); + drop(flight); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn every_schema_transfers_and_selects_only_after_real_process_restart() { + for (schema, populated) in (0..=4) + .map(|s| (s, false)) + .chain((1..=4).map(|s| (s, true))) + { + let root = Root::new(schema, populated); + root.retain_expected_outputs(); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + root.copied(); + assert_eq!(inspect(&root.anchor), Status::Interrupted); + assert!(matches!( + Verification::prepare(root.anchor.clone()), + Err(Error::SameProcess) + )); + let output = root.spawn("verify", None).wait_with_output().unwrap(); + assert!( + output.status.success(), + "verification child failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(inspect(&root.anchor), Status::SelectionRecorded); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 1); + assert!(Conversion::prepare(root.anchor.clone()).is_err()); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn journal_failures_at_all_phase_boundaries_preserve_prior_files_and_refuse_resume() { + let boundaries = [ + "before_create", + "after_create", + "before_write", + "after_write", + "before_file_sync", + "after_file_sync", + "before_directory_sync", + "after_directory_sync", + "before_readback", + "after_readback", + ]; + for phase in Phase::ALL { + for boundary in boundaries { + let root = Root::new(1, true); + let mut journal = Journal::create(&root.anchor).unwrap(); + for previous in Phase::ALL.into_iter().take(phase.index()) { + append_phase(&mut journal, previous); + } + let originals: Vec<_> = journal + .records + .iter() + .map(|r| (r.record.phase.name(), r.bytes.clone())) + .collect(); + let selected = phase.name().to_owned(); + let label = boundary.to_owned(); + PROBE.with(|p| { + *p.borrow_mut() = Some(Box::new(move |stage, point| { + if stage == selected && point == label { + Err(Error::WriteUncertain) + } else { + Ok(()) + } + })) + }); + let record = if phase == Phase::Intent { + intent() + } else { + journal + .next( + phase, + Some("5".repeat(64)), + if matches!(phase, Phase::Reopened | Phase::Selected) { + Some("6".repeat(64)) + } else { + None + }, + ) + .unwrap() + }; + assert!(journal.append(record).is_err()); + PROBE.with(|p| *p.borrow_mut() = None); + drop(journal); + for (name, bytes) in originals { + assert_eq!( + fs::read(root.anchor.join(DIRECTORY).join(name)).unwrap(), + bytes + ); + } + // The disk reader distinguishes complete surviving metadata from torn records; + // it never supplies an operational client or historical acknowledgment. + let observed = inspect(&root.anchor); + assert!( + matches!( + observed, + Status::Interrupted | Status::RecoveryRequired | Status::LegacyDiverged + ), + "journal phase {} boundary {boundary}: {observed:?}", + phase.name() + ); + } + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn journal_rejects_unknown_linked_replaced_and_conflicting_files() { + use std::os::unix::fs::symlink; + let root = Root::new(1, true); + let mut journal = Journal::create(&root.anchor).unwrap(); + append_phase(&mut journal, Phase::Intent); + drop(journal); + let path = root.anchor.join(DIRECTORY); + fs::write(path.join("unknown"), b"x").unwrap(); + assert_eq!(inspect(&root.anchor), Status::RecoveryRequired); + fs::remove_file(path.join("unknown")).unwrap(); + fs::hard_link(path.join("intent.json"), root.base.join("alias")).unwrap(); + assert_eq!(inspect(&root.anchor), Status::RecoveryRequired); + fs::remove_file(root.base.join("alias")).unwrap(); + fs::rename(path.join("intent.json"), root.base.join("original")).unwrap(); + symlink(root.base.join("original"), path.join("intent.json")).unwrap(); + assert_eq!(inspect(&root.anchor), Status::RecoveryRequired); + fs::remove_file(path.join("intent.json")).unwrap(); + let journal = Journal::open(&root.anchor).unwrap(); + assert!(matches!(journal.read(Phase::Intent), Err(Error::Changed))); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn initial_journal_faults_and_busy_owner_do_not_reuse_or_replace_attempts() { + for boundary in [ + "before_root_create", + "after_root_create", + "before_parent_sync", + "after_parent_sync", + "before_lock_create", + "after_lock_create", + "before_lock_sync", + "after_lock_sync", + "before_root_sync", + "after_root_sync", + ] { + let root = Root::new(1, true); + let label = boundary.to_owned(); + PROBE.with(|p| { + *p.borrow_mut() = Some(Box::new(move |stage, b| { + if stage == "journal" && b == label { + Err(Error::WriteUncertain) + } else { + Ok(()) + } + })) + }); + assert!(Journal::create(&root.anchor).is_err()); + PROBE.with(|p| *p.borrow_mut() = None); + assert!(matches!( + inspect(&root.anchor), + Status::NoAttempt | Status::Interrupted | Status::RecoveryRequired + )); + assert!(!root.anchor.join("managed-workspace").exists()); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 0); + } + let root = Root::new(1, true); + let journal = Journal::create(&root.anchor).unwrap(); + assert!(Journal::open(&root.anchor).is_err()); + assert!(Journal::create(&root.anchor).is_err()); + drop(journal); + assert_eq!(inspect(&root.anchor), Status::Interrupted); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn competing_source_commits_before_effects_and_during_copy_invalidate_attempt() { + for boundary in [ + "before_create", + "before_confirm", + "before_restore", + "after_restore", + ] { + let root = Root::new(2, true); + let source = root.anchor.join("source-workspace"); + let label = boundary.to_owned(); + PROBE.with(|p| { + *p.borrow_mut() = Some(Box::new(move |stage, b| { + if stage == "destination" && b == label { + Workspace::new(source.clone()) + .save( + &rangoon_import::analyze("SKILL.md", b"# Competing writer\n").unwrap(), + ) + .unwrap(); + } + Ok(()) + })) + }); + let conversion = Conversion::prepare(root.anchor.clone()).unwrap(); + let consent = conversion.synthetic_consent(); + assert!(conversion.copy(consent, &root.vault()).is_err()); + PROBE.with(|p| *p.borrow_mut() = None); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + let writes = fs::read_dir(root.vault().0).unwrap().count(); + assert_eq!( + writes, + usize::from(matches!(boundary, "before_restore" | "after_restore")) + ); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn killed_destination_provision_and_restore_boundaries_require_inspection() { + for (stage, boundary) in [ + ("destination", "before_create"), + ("destination", "after_create"), + ("vault", "before_write"), + ("vault", "after_write"), + ("destination", "after_confirm"), + ("destination", "before_restore"), + ("destination", "after_restore"), + ("destination", "after_close"), + ] { + let root = Root::new(3, true); + kill_at(&root, "copy", stage, boundary); + assert!(matches!( + inspect(&root.anchor), + Status::Interrupted | Status::RecoveryRequired + )); + assert!(Conversion::prepare(root.anchor.clone()).is_err()); + assert!(fs::read_dir(root.vault().0).unwrap().count() <= 1); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn source_commit_during_distinct_process_verification_prevents_selection() { + for boundary in ["after_unlock", "before_selection"] { + let root = Root::new(2, true); + root.copied(); + let output = root + .spawn("verify-drift", Some(("verification", boundary))) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "verification drift refusal failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn killed_copy_processes_leave_inspection_only_and_no_second_key() { + for phase in ["intent.json", "target.json", "copied.json"] { + for boundary in [ + "before_create", + "after_write", + "after_file_sync", + "after_directory_sync", + "after_readback", + ] { + let root = Root::new(1, true); + let before = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + kill_at(&root, "copy", phase, boundary); + assert!(matches!( + inspect(&root.anchor), + Status::Interrupted | Status::RecoveryRequired + )); + assert!(Conversion::prepare(root.anchor.clone()).is_err()); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + before + ); + assert!(fs::read_dir(root.vault().0).unwrap().count() <= 1); + } + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn killed_verification_and_selection_processes_report_only_surviving_metadata() { + for phase in ["reopened.json", "selected.json"] { + for boundary in [ + "before_create", + "after_write", + "after_file_sync", + "after_directory_sync", + "after_readback", + ] { + let root = Root::new(2, true); + root.copied(); + kill_at(&root, "verify", phase, boundary); + assert!(matches!( + inspect(&root.anchor), + Status::Interrupted | Status::RecoveryRequired | Status::SelectionRecorded + )); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 1); + } + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn missing_key_wrong_target_and_source_drift_prevent_selection() { + for mode in ["missing-key", "source-drift", "wrong-target"] { + let root = Root::new(1, true); + root.copied(); + match mode { + "missing-key" => { + for entry in fs::read_dir(root.vault().0).unwrap() { + fs::remove_file(entry.unwrap().path()).unwrap(); + } + } + "source-drift" => { + Workspace::new(root.anchor.join("source-workspace")) + .save(&rangoon_import::analyze("SKILL.md", b"# Later\n").unwrap()) + .unwrap(); + } + _ => { + let path = root.anchor.join(DIRECTORY).join("target.json"); + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + value["destination"] = serde_json::Value::String("e".repeat(64)); + fs::write(path, serde_json::to_vec(&value).unwrap()).unwrap(); + } + } + let output = root + .spawn("expect-refusal", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "refusal child failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn verifier_cancel_wrong_consent_and_busy_owner_never_advance_selection() { + let root = Root::new(2, true); + root.copied(); + for mode in ["verify-cancel", "verify-wrong-consent"] { + let output = root.spawn(mode, None).wait_with_output().unwrap(); + assert!( + output.status.success(), + "verifier refusal failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(inspect(&root.anchor), Status::Interrupted); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); + } + let owner = Owner::acquire(root.anchor.join("managed-workspace")).unwrap(); + assert!( + root.spawn("expect-refusal", None) + .wait_with_output() + .unwrap() + .status + .success() + ); + drop(owner); + assert!(!root.anchor.join(DIRECTORY).join("reopened.json").exists()); + assert!( + root.spawn("verify", None) + .wait_with_output() + .unwrap() + .status + .success() + ); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn replaced_removed_or_mixed_source_never_creates_destination_or_key() { + for mode in ["replace", "remove", "mixed"] { + let root = Root::new(1, true); + let conversion = Conversion::prepare(root.anchor.clone()).unwrap(); + let consent = conversion.synthetic_consent(); + let database = root.anchor.join("source-workspace/workspace.sqlite3"); + match mode { + "replace" => { + fs::rename(&database, root.base.join("retained-original")).unwrap(); + fs::copy(root.base.join("retained-original"), &database).unwrap(); + } + "remove" => fs::remove_file(database).unwrap(), + _ => fs::create_dir(root.anchor.join("managed-workspace")).unwrap(), + } + assert!(conversion.copy(consent, &root.vault()).is_err()); + assert!(!root.anchor.join(DIRECTORY).exists()); + assert_eq!(fs::read_dir(root.vault().0).unwrap().count(), 0); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn later_encrypted_authoring_is_valid_but_legacy_divergence_is_separate() { + let root = Root::new(1, true); + root.copied(); + assert!( + root.spawn("verify", None) + .wait_with_output() + .unwrap() + .status + .success() + ); + let mut owner = Owner::acquire(root.anchor.join("managed-workspace")).unwrap(); + let preview = owner.prepare_unlock().unwrap(); + owner.confirm(&preview.id, &root.vault()).unwrap(); + owner + .save( + &root.vault(), + &rangoon_import::analyze("SKILL.md", b"# Managed addition\n").unwrap(), + ) + .unwrap(); + owner.lock(); + drop(owner); + assert_eq!(inspect(&root.anchor), Status::SelectionRecorded); + Workspace::new(root.anchor.join("source-workspace")) + .save(&rangoon_import::analyze("SKILL.md", b"# Legacy diverged\n").unwrap()) + .unwrap(); + assert_eq!(inspect(&root.anchor), Status::LegacyDiverged); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_confirmation_cancel_or_unavailable_leaves_no_journal_destination_or_key() { + for outcome in [Consent::Cancelled, Consent::Unavailable] { + let root = Root::new(1, true); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &permit).unwrap(); + + match outcome { + Consent::Cancelled => assert!( + conversion + .confirm_native(&permit, || Consent::Cancelled) + .unwrap() + .is_none() + ), + Consent::Unavailable => assert!(matches!( + conversion.confirm_native(&permit, || Consent::Unavailable), + Err(Error::Unavailable) + )), + Consent::Approved => unreachable!(), + } + assert_no_copy_effects(&root); + drop(flight); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn stale_native_permit_refuses_before_prepare_without_io() { + let root = Root::new(1, true); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let (id, epoch) = control_identity(&close); + close.cancel_control(&id, &epoch, |_| true); + + assert!(matches!( + Conversion::prepare_native(root.anchor.clone(), &permit), + Err(Error::Unavailable) + )); + assert_no_copy_effects(&root); + drop(flight); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_confirmation_cancelled_during_callback_cannot_mint_copy_consent() { + let root = Root::new(1, true); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &permit).unwrap(); + let (id, epoch) = control_identity(&close); + let cancelling_close = close.clone(); + + assert!(matches!( + conversion.confirm_native(&permit, move || { + cancelling_close.cancel_control(&id, &epoch, |_| true); + Consent::Approved + }), + Err(Error::Unavailable) + )); + assert_no_copy_effects(&root); + drop(flight); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_confirmation_source_drift_after_callback_refuses_before_copy_effects() { + let root = Root::new(1, true); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &permit).unwrap(); + let source = root.anchor.join("source-workspace"); + + assert!(matches!( + conversion.confirm_native(&permit, move || { + Workspace::new(source) + .save(&rangoon_import::analyze("SKILL.md", b"# Changed after sheet\n").unwrap()) + .unwrap(); + Consent::Approved + }), + Err(Error::Changed) + )); + assert_no_copy_effects(&root); + drop(flight); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_conversion_rejects_new_startup_flight_after_original_cancelled() { + let root = Root::new(1, true); + let close = startup_close(&root); + let old_flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let old_permit = old_flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &old_permit).unwrap(); + let (conversion, consent) = conversion + .confirm_native(&old_permit, || Consent::Approved) + .unwrap() + .unwrap(); + let (old_id, old_epoch) = control_identity(&close); + let cancelled = + serde_json::to_value(close.cancel_control(&old_id, &old_epoch, |_| true)).unwrap(); + let next_id = cancelled["attemptId"].as_str().unwrap().to_owned(); + let next_epoch = cancelled["epoch"].as_str().unwrap().to_owned(); + drop(old_flight); + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(&next_id, &next_epoch), |_| true)) + .unwrap()["state"], + "locked" + ); + + let new_flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let new_permit = new_flight.startup_permit().unwrap(); + assert!(matches!( + conversion.copy_native(consent, &root.vault(), &new_permit), + Err(Error::Unavailable) + )); + assert_no_copy_effects(&root); + drop(new_flight); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_conversion_rejects_matching_serial_from_different_close_coordinator() { + let root = Root::new(1, true); + let first_close = startup_close(&root); + let first_flight = first_close + .start_control(ControlKind::Startup, |_| true) + .unwrap(); + acknowledge_startup_flight(&first_close); + let first_permit = first_flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &first_permit).unwrap(); + + let second_close = startup_close(&root); + let second_flight = second_close + .start_control(ControlKind::Startup, |_| true) + .unwrap(); + acknowledge_startup_flight(&second_close); + let second_permit = second_flight.startup_permit().unwrap(); + assert!(matches!( + conversion.confirm_native(&second_permit, || panic!("foreign permit reached callback")), + Err(Error::Unavailable) + )); + assert_no_copy_effects(&root); + drop(second_flight); + drop(first_flight); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_verification_replay_refuses_before_confirmation_or_selection() { + for mode in [ + "verify-native-replay-confirm", + "verify-native-replay-select", + ] { + let root = Root::new(2, true); + root.copied(); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + let output = root.spawn(mode, None).wait_with_output().unwrap(); + assert!( + output.status.success(), + "native verification replay refusal failed for {mode}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(!root.anchor.join(DIRECTORY).join("reopened.json").exists()); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn approved_native_copy_uses_real_permit_preserves_original_and_verifies_after_worker_drop() { + let root = Root::new(3, true); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &permit).unwrap(); + let (conversion, consent) = conversion + .confirm_native(&permit, || Consent::Approved) + .unwrap() + .unwrap(); + conversion + .copy_native(consent, &root.vault(), &permit) + .unwrap(); + + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); + drop(flight); + assert_eq!( + serde_json::to_value(close.inspect(|_| true)).unwrap()["state"], + "locked" + ); + drop(close); + + let output = root + .spawn("verify-native", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "native copy parity verification failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(inspect(&root.anchor), Status::SelectionRecorded); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn host_verification_cancel_then_approved_after_distinct_restart_keeps_source_and_key_custody() { + let root = Root::new(1, true); + root.copied(); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + + let output = root + .spawn("verify-host-cancel-approve", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "host verification cancel/approve flow failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert_eq!(inspect(&root.anchor), Status::SelectionRecorded); + assert!(root.anchor.join(DIRECTORY).join("reopened.json").is_file()); + assert!(root.anchor.join(DIRECTORY).join("selected.json").is_file()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn native_copy_cancellation_checkpoints_preserve_original_and_known_partial_state() { + for (boundary, expected_keys) in [("before_confirm", 0), ("after_restore", 1)] { + let root = Root::new(1, true); + let original = fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(); + let close = startup_close(&root); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let conversion = Conversion::prepare_native(root.anchor.clone(), &permit).unwrap(); + let (conversion, consent) = conversion + .confirm_native(&permit, || Consent::Approved) + .unwrap() + .unwrap(); + let (id, epoch) = control_identity(&close); + let cancelling_close = close.clone(); + let expected_boundary = boundary.to_owned(); + PROBE.with(|probe| { + *probe.borrow_mut() = Some(Box::new(move |stage, current_boundary| { + if stage == "destination" && current_boundary == expected_boundary { + cancelling_close.cancel_control(&id, &epoch, |_| true); + } + Ok(()) + })) + }); + + assert!(matches!( + conversion.copy_native(consent, &root.vault(), &permit), + Err(Error::Unavailable) + )); + PROBE.with(|probe| *probe.borrow_mut() = None); + assert_eq!( + fs::read(root.anchor.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.anchor.join(DIRECTORY).join("target.json").exists()); + assert!(!root.anchor.join(DIRECTORY).join("copied.json").exists()); + assert_eq!( + fs::read_dir(root.vault().0.clone()).unwrap().count(), + expected_keys + ); + drop(flight); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn verification_control_disappearance_refuses_without_recreation_or_selection() { + let root = Root::new(1, true); + root.copied(); + let output = root + .spawn("verify-control-disappears", None) + .wait_with_output() + .unwrap(); + assert!( + output.status.success(), + "existing-control disappearance refusal failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + !root + .anchor + .join("managed-workspace/encrypted-workspace.lock") + .exists() + ); + assert!(!root.anchor.join(DIRECTORY).join("reopened.json").exists()); + assert!(!root.anchor.join(DIRECTORY).join("selected.json").exists()); + assert_eq!(fs::read_dir(root.vault().0.clone()).unwrap().count(), 1); +} + +#[test] +#[ignore = "Disposable process child; only its exact parent fixtures supply context"] +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn process_child() { + let base = PathBuf::from(std::env::var_os("RANGOON_E1C5B_TEST_ROOT").expect("test root")); + let temp = std::env::temp_dir().canonicalize().unwrap(); + assert!(base.starts_with(&temp) && base == base.canonicalize().unwrap()); + assert!( + base.file_name() + .unwrap() + .to_str() + .unwrap() + .starts_with("rangoon-adoption-") + ); + assert_eq!( + fs::read(base.join("test-owner")).unwrap(), + b"rangoon.e1c5b.disposable.v1" + ); + let anchor = base.join("anchor"); + let vault = TestVault(base.join("keys")); + if let (Ok(stage), Ok(boundary)) = ( + std::env::var("RANGOON_E1C5B_TEST_PHASE"), + std::env::var("RANGOON_E1C5B_TEST_BOUNDARY"), + ) { + let marker = base.join("ready"); + PROBE.with(|p| { + *p.borrow_mut() = Some(Box::new(move |s, b| { + if s == stage && b == boundary { + if std::env::var("RANGOON_E1C5B_TEST_MODE").as_deref() == Ok("verify-drift") { + Workspace::new(marker.parent().unwrap().join("anchor/source-workspace")) + .save( + &rangoon_import::analyze( + "SKILL.md", + b"# Concurrent verification writer\n", + ) + .unwrap(), + ) + .unwrap(); + return Ok(()); + } + fs::write(&marker, b"ready").unwrap(); + loop { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + Ok(()) + })) + }); + } + match std::env::var("RANGOON_E1C5B_TEST_MODE").unwrap().as_str() { + "copy" => { + let conversion = Conversion::prepare(anchor).unwrap(); + let consent = conversion.synthetic_consent(); + conversion.copy(consent, &vault).unwrap(); + } + "verify" => { + let verification = Verification::prepare(anchor.clone()).unwrap(); + let consent = verification.synthetic_consent(); + verification.select(consent, &vault).unwrap(); + if base.join("expected-outputs.json").exists() { + let mut owner = Owner::acquire(anchor.join("managed-workspace")).unwrap(); + let preview = owner.prepare_unlock().unwrap(); + owner.confirm(&preview.id, &vault).unwrap(); + let mut values = Vec::new(); + for source in owner.list(&vault).unwrap() { + values.push( + serde_json::to_value(owner.open(&vault, &source.source_id).unwrap()) + .unwrap(), + ); + } + for capability in owner.list_capabilities(&vault).unwrap() { + values.push( + serde_json::to_value( + owner.open_capability(&vault, &capability.id, None).unwrap(), + ) + .unwrap(), + ); + for profile in [ + rangoon_compile::Profile::AgentsMdV1, + rangoon_compile::Profile::ClaudeMdV1, + ] { + let compiled = owner + .compile_capability( + &vault, + &capability.id, + &capability.latest_revision_id, + profile, + ) + .unwrap(); + values.push(serde_json::to_value(&compiled).unwrap()); + if let Ok(bundle) = rangoon_compile::encode_bundle(&compiled.compilation) { + values.push(serde_json::json!({"bundle":bundle.bytes})); + } + } + } + let expected: Vec = + serde_json::from_slice(&fs::read(base.join("expected-outputs.json")).unwrap()) + .unwrap(); + assert!( + values == expected, + "exact source/history/compiler/export parity required after restart" + ); + owner.lock(); + } + } + "verify-native" => { + let access = SourceAccess::managed_deferred( + Gate::new(), + anchor.join("managed-workspace"), + vault.clone(), + ); + let close = WorkspaceClose::new(access); + let started = serde_json::to_value(close.begin(|_| true)).unwrap(); + let id = started["attemptId"].as_str().unwrap().to_owned(); + let epoch = started["epoch"].as_str().unwrap().to_owned(); + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(&id, &epoch), |_| true)) + .unwrap()["state"], + "locked" + ); + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let permit = flight.startup_permit().unwrap(); + let verification = Verification::prepare_native(anchor, &permit).unwrap(); + let (verification, consent) = verification + .confirm_native(&permit, || Consent::Approved) + .unwrap() + .unwrap(); + verification + .select_native(consent, &vault, &permit) + .unwrap(); + drop(flight); + } + "verify-host-cancel-approve" => { + use std::sync::{Arc, Mutex}; + + let gate = Gate::new(); + let (access, close, host) = crate::workspace_native_bootstrap::startup_state( + &gate, + anchor.clone(), + vault.clone(), + ); + let initial = serde_json::to_value(close.begin(|_| true)).unwrap(); + assert_eq!(initial["state"], "closing"); + assert_eq!( + serde_json::to_value(close.acknowledge( + &acknowledgement( + initial["attemptId"].as_str().unwrap(), + initial["epoch"].as_str().unwrap(), + ), + |_| true + )) + .unwrap()["state"], + "locked" + ); + let first = serde_json::to_value(host.status( + |_| true, + |current| { + let view = serde_json::to_value(current.inspect(|_| true)).unwrap(); + assert_eq!(view["state"], "closing"); + let acknowledged = serde_json::to_value(current.acknowledge( + &acknowledgement( + view["attemptId"].as_str().unwrap(), + view["epoch"].as_str().unwrap(), + ), + |_| true, + )) + .unwrap(); + assert_eq!(acknowledged["state"], "closing"); + true + }, + )) + .unwrap(); + assert_eq!(first["state"], "verify_required"); + assert_eq!(first["retainedOriginal"], "present_unencrypted"); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + + let counts = Arc::new(Mutex::new([0_usize; 3])); + PROBE.with(|probe| { + let counts = Arc::clone(&counts); + *probe.borrow_mut() = Some(Box::new(move |stage, boundary| { + let index = match (stage, boundary) { + ("vault", "before_open") => Some(0), + ("vault", "before_read") => Some(1), + ("vault", "before_write") => Some(2), + _ => None, + }; + if let Some(index) = index { + counts.lock().unwrap()[index] += 1; + } + Ok(()) + })); + }); + + let cancelled = serde_json::to_value(host.action( + startup_action_request(&first, "verify"), + &vault, + |_| Consent::Cancelled, + )) + .unwrap(); + assert_eq!(cancelled["state"], "verify_required"); + assert_ne!(cancelled["startupId"], first["startupId"]); + assert!(!anchor.join(DIRECTORY).join("reopened.json").exists()); + assert!(!anchor.join(DIRECTORY).join("selected.json").exists()); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + + let stale = serde_json::to_value(host.action( + startup_action_request(&first, "verify"), + &vault, + |_| panic!("stale verify reached native confirmation"), + )) + .unwrap(); + assert_eq!(stale["state"], "verify_required"); + assert_eq!(stale["startupId"], cancelled["startupId"]); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + + let handoff = serde_json::to_value(host.action( + startup_action_request(&cancelled, "verify"), + &vault, + |_| Consent::Approved, + )) + .unwrap(); + assert_eq!(handoff["state"], "handoff"); + assert!(handoff["startupId"].is_null()); + assert!(handoff["attemptId"].is_null()); + assert!(handoff["epoch"].is_null()); + assert!(anchor.join(DIRECTORY).join("reopened.json").is_file()); + assert!(anchor.join(DIRECTORY).join("selected.json").is_file()); + let final_counts = *counts.lock().unwrap(); + assert!(final_counts[0] > 0); + assert!(final_counts[1] > 0); + assert_eq!(final_counts[2], 0); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + } + mode @ ("recover-host-target-empty" + | "recover-host-target-full" + | "recover-host-target-pending" + | "recover-host-no-database" + | "recover-host-no-database-cancel-inspect" + | "recover-host-no-database-cancel-initialize" + | "recover-host-reopened" + | "recover-host-cancel-inspect" + | "recover-host-cancel-unlock" + | "recover-host-record-copied-drift" + | "recover-host-missing-key" + | "recover-host-wrong-target" + | "recover-host-c1-revoked") => { + use std::sync::{Arc, Mutex}; + + let gate = Gate::new(); + let (access, close, host) = crate::workspace_native_bootstrap::startup_state( + &gate, + anchor.clone(), + vault.clone(), + ); + let c1_identity = Arc::new(Mutex::new(None)); + let initial = serde_json::to_value(close.begin(|_| true)).unwrap(); + assert_eq!(initial["state"], "closing"); + assert_eq!( + serde_json::to_value(close.acknowledge( + &acknowledgement( + initial["attemptId"].as_str().unwrap(), + initial["epoch"].as_str().unwrap(), + ), + |_| true, + )) + .unwrap()["state"], + "locked" + ); + let target_destination = Journal::open(&anchor) + .unwrap() + .records + .last() + .unwrap() + .record + .destination + .clone() + .unwrap(); + let pending_before_initialize = (mode == "recover-host-no-database").then(|| { + fs::read(anchor.join("managed-workspace/encrypted-workspace.operation.pending")) + .unwrap() + }); + let acknowledged = Arc::clone(&c1_identity); + let recovery = serde_json::to_value(host.status( + |_| true, + |current| { + let view = serde_json::to_value(current.inspect(|_| true)).unwrap(); + *acknowledged.lock().unwrap() = Some(( + view["attemptId"].as_str().unwrap().to_owned(), + view["epoch"].as_str().unwrap().to_owned(), + )); + let _ = current.acknowledge( + &acknowledgement( + view["attemptId"].as_str().unwrap(), + view["epoch"].as_str().unwrap(), + ), + |_| true, + ); + true + }, + )) + .unwrap(); + assert_eq!(recovery["state"], "recovery_required"); + assert_eq!(recovery["retainedOriginal"], "not_verified"); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + + let counts = Arc::new(Mutex::new([0_usize; 3])); + PROBE.with(|probe| { + let counts = Arc::clone(&counts); + *probe.borrow_mut() = Some(Box::new(move |stage, boundary| { + let index = match (stage, boundary) { + ("vault", "before_open") => Some(0), + ("vault", "before_read") => Some(1), + ("vault", "before_write") => Some(2), + _ => None, + }; + if let Some(index) = index { + counts.lock().unwrap()[index] += 1; + } + Ok(()) + })); + }); + if mode == "recover-host-no-database-cancel-inspect" { + let mut steps = Vec::new(); + let cancelled = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + Consent::Cancelled + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!(steps, vec![RecoveryStep::Inspect]); + assert_eq!(cancelled["state"], "recovery_required"); + assert_ne!(cancelled["startupId"], recovery["startupId"]); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + assert!( + !anchor + .join("managed-workspace/encrypted-workspaces") + .join(&target_destination) + .join("workspace.sqlite3") + .exists() + ); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-no-database-cancel-initialize" { + let mut steps = Vec::new(); + let cancelled = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + if step == RecoveryStep::InitializeEmpty { + Consent::Cancelled + } else { + Consent::Approved + } + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!( + steps, + vec![RecoveryStep::Inspect, RecoveryStep::InitializeEmpty] + ); + assert_eq!(cancelled["state"], "recovery_required"); + assert_ne!(cancelled["startupId"], recovery["startupId"]); + let counts = *counts.lock().unwrap(); + assert!(counts[0] > 0); + assert!(counts[1] > 0); + assert_eq!(counts[2], 0); + assert!( + !anchor + .join("managed-workspace/encrypted-workspaces") + .join(&target_destination) + .join("workspace.sqlite3") + .exists() + ); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-record-copied-drift" { + let binding = anchor.join("managed-workspace/encrypted-workspace.binding"); + let mut steps = Vec::new(); + let refused = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + if step == RecoveryStep::RecordCopied { + let mut bytes = fs::read(&binding).unwrap(); + bytes[0] ^= 1; + fs::write(&binding, bytes).unwrap(); + } + Consent::Approved + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!( + steps, + vec![RecoveryStep::Inspect, RecoveryStep::RecordCopied] + ); + assert_eq!(refused["state"], "unavailable"); + assert!(!anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(!anchor.join(DIRECTORY).join("selected.json").exists()); + assert_eq!(counts.lock().unwrap()[2], 0); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-missing-key" { + let mut steps = Vec::new(); + let refused = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + Consent::Approved + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!(steps, vec![RecoveryStep::Inspect]); + assert_eq!(refused["state"], "unavailable"); + let counts = *counts.lock().unwrap(); + assert!(counts[0] > 0); + assert!(counts[1] > 0); + assert_eq!(counts[2], 0); + assert!(!anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-wrong-target" { + let refused = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |_| panic!("wrong target reached recovery confirmation"), + )) + .unwrap(); + assert_eq!(refused["state"], "unavailable"); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + assert!(!anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-c1-revoked" { + let (id, epoch) = c1_identity.lock().unwrap().clone().unwrap(); + let cancelling_close = close.clone(); + let mut steps = Vec::new(); + let refused = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + assert_eq!(step, RecoveryStep::Inspect); + cancelling_close.cancel_control(&id, &epoch, |_| true); + Consent::Approved + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!(steps, vec![RecoveryStep::Inspect]); + assert_eq!(refused["state"], "unavailable"); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + assert!(!anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(!anchor.join(DIRECTORY).join("selected.json").exists()); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-cancel-inspect" { + let mut steps = Vec::new(); + let cancelled = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + Consent::Cancelled + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!(steps, vec![RecoveryStep::Inspect]); + assert_eq!(cancelled["state"], "recovery_required"); + assert_ne!(cancelled["startupId"], recovery["startupId"]); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + + let stale = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |_| panic!("stale recovery reached confirmation"), + )) + .unwrap(); + assert_eq!(stale["state"], "recovery_required"); + assert_eq!(stale["startupId"], cancelled["startupId"]); + assert_eq!(*counts.lock().unwrap(), [0, 0, 0]); + assert!(anchor.join(DIRECTORY).join("target.json").is_file()); + assert!(!anchor.join(DIRECTORY).join("copied.json").exists()); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + if mode == "recover-host-cancel-unlock" { + let mut steps = Vec::new(); + let cancelled = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + steps.push(step); + if step == RecoveryStep::Unlock { + Consent::Cancelled + } else { + Consent::Approved + } + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!( + steps, + vec![ + RecoveryStep::Inspect, + RecoveryStep::Reconcile, + RecoveryStep::Unlock, + ] + ); + assert_eq!(cancelled["state"], "recovery_required"); + assert_ne!(cancelled["startupId"], recovery["startupId"]); + assert!(!anchor.join(DIRECTORY).join("copied.json").exists()); + + let stale = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |_| panic!("stale recovery reached confirmation"), + )) + .unwrap(); + assert_eq!(stale["state"], "recovery_required"); + assert_eq!(stale["startupId"], cancelled["startupId"]); + + let mut retry_steps = Vec::new(); + let retried = serde_json::to_value(host.action( + startup_action_request(&cancelled, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, + .. + } => { + retry_steps.push(step); + Consent::Approved + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + assert_eq!( + retry_steps, + vec![RecoveryStep::Inspect, RecoveryStep::RecordCopied] + ); + assert_eq!(retried["state"], "restart_required"); + assert_eq!( + serde_json::to_value(host.status(|_| true, |_| true)).unwrap()["state"], + "restart_required" + ); + let counts = *counts.lock().unwrap(); + assert!(counts[0] > 0); + assert!(counts[1] > 0); + assert_eq!(counts[2], 0); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + return; + } + let mut steps = Vec::new(); + let recovered = serde_json::to_value(host.action( + startup_action_request(&recovery, "recover"), + &vault, + |confirmation| match confirmation { + crate::workspace_startup_host::StartupConfirmation::Recovery { + step, .. + } => { + steps.push(step); + if mode == "recover-host-no-database" && step == RecoveryStep::Unlock { + let pending = pending_before_initialize.as_ref().unwrap(); + assert!( + fs::read(anchor.join( + "managed-workspace/encrypted-workspace.operation.pending" + )) + .unwrap() + == *pending + ); + let terminal = + fs::read(anchor.join( + "managed-workspace/encrypted-workspace.operation.terminal", + )) + .unwrap(); + let prefix = b"rangoon.workspace-operation.v1\0"; + assert!(terminal.starts_with(prefix)); + assert_eq!(pending[prefix.len()], 0); + assert_eq!(terminal[prefix.len()], 1); + // Same operation, sequence, workspace and exact Owner attempt. + assert_eq!( + &terminal[prefix.len() + 1..prefix.len() + 138], + &pending[prefix.len() + 1..prefix.len() + 138] + ); + } + Consent::Approved + } + _ => Consent::Unavailable, + }, + )) + .unwrap(); + let (expected, terminal_state) = match mode { + "recover-host-target-empty" => ( + vec![RecoveryStep::Inspect, RecoveryStep::Restore], + "restart_required", + ), + "recover-host-target-full" => ( + vec![RecoveryStep::Inspect, RecoveryStep::RecordCopied], + "restart_required", + ), + "recover-host-target-pending" => ( + vec![ + RecoveryStep::Inspect, + RecoveryStep::Reconcile, + RecoveryStep::Unlock, + RecoveryStep::RecordCopied, + ], + "restart_required", + ), + "recover-host-no-database" => ( + vec![ + RecoveryStep::Inspect, + RecoveryStep::InitializeEmpty, + RecoveryStep::Unlock, + RecoveryStep::Restore, + ], + "restart_required", + ), + "recover-host-reopened" => (vec![RecoveryStep::CompleteSelection], "handoff"), + _ => unreachable!(), + }; + assert_eq!(recovered["state"], terminal_state); + assert_eq!(steps, expected); + if terminal_state == "restart_required" { + assert_eq!( + serde_json::to_value(host.status(|_| true, |_| true)).unwrap()["state"], + "restart_required" + ); + } else { + assert!(recovered["startupId"].is_null()); + assert!(recovered["attemptId"].is_null()); + assert!(recovered["epoch"].is_null()); + } + let counts = *counts.lock().unwrap(); + assert!(counts[0] > 0); + assert!(counts[1] > 0); + assert_eq!(counts[2], 0); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); + PROBE.with(|probe| *probe.borrow_mut() = None); + } + "verify-native-replay-confirm" => { + let access = SourceAccess::managed_deferred( + Gate::new(), + anchor.join("managed-workspace"), + vault.clone(), + ); + let close = WorkspaceClose::new(access); + let started = serde_json::to_value(close.begin(|_| true)).unwrap(); + let id = started["attemptId"].as_str().unwrap().to_owned(); + let epoch = started["epoch"].as_str().unwrap().to_owned(); + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(&id, &epoch), |_| true)) + .unwrap()["state"], + "locked" + ); + let old_flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let old_permit = old_flight.startup_permit().unwrap(); + let verification = Verification::prepare_native(anchor, &old_permit).unwrap(); + let (old_id, old_epoch) = control_identity(&close); + let cancelled = + serde_json::to_value(close.cancel_control(&old_id, &old_epoch, |_| true)).unwrap(); + let next_id = cancelled["attemptId"].as_str().unwrap().to_owned(); + let next_epoch = cancelled["epoch"].as_str().unwrap().to_owned(); + drop(old_flight); + assert_eq!( + serde_json::to_value( + close.acknowledge(&acknowledgement(&next_id, &next_epoch), |_| true) + ) + .unwrap()["state"], + "locked" + ); + let fresh_flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let fresh_permit = fresh_flight.startup_permit().unwrap(); + assert!(matches!( + verification + .confirm_native(&fresh_permit, || panic!("replayed verify reached callback")), + Err(Error::Unavailable) + )); + drop(fresh_flight); + } + "verify-native-replay-select" => { + let access = SourceAccess::managed_deferred( + Gate::new(), + anchor.join("managed-workspace"), + vault.clone(), + ); + let close = WorkspaceClose::new(access); + let started = serde_json::to_value(close.begin(|_| true)).unwrap(); + let id = started["attemptId"].as_str().unwrap().to_owned(); + let epoch = started["epoch"].as_str().unwrap().to_owned(); + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(&id, &epoch), |_| true)) + .unwrap()["state"], + "locked" + ); + let old_flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let old_permit = old_flight.startup_permit().unwrap(); + let verification = Verification::prepare_native(anchor, &old_permit).unwrap(); + let (verification, consent) = verification + .confirm_native(&old_permit, || Consent::Approved) + .unwrap() + .unwrap(); + let (old_id, old_epoch) = control_identity(&close); + let cancelled = + serde_json::to_value(close.cancel_control(&old_id, &old_epoch, |_| true)).unwrap(); + let next_id = cancelled["attemptId"].as_str().unwrap().to_owned(); + let next_epoch = cancelled["epoch"].as_str().unwrap().to_owned(); + drop(old_flight); + assert_eq!( + serde_json::to_value( + close.acknowledge(&acknowledgement(&next_id, &next_epoch), |_| true) + ) + .unwrap()["state"], + "locked" + ); + let fresh_flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + acknowledge_startup_flight(&close); + let fresh_permit = fresh_flight.startup_permit().unwrap(); + assert!(matches!( + verification.select_native(consent, &vault, &fresh_permit), + Err(Error::Unavailable) + )); + drop(fresh_flight); + } + "verify-drift" => { + let verification = Verification::prepare(anchor).unwrap(); + let consent = verification.synthetic_consent(); + assert!(verification.select(consent, &vault).is_err()); + } + "verify-control-disappears" => { + let control = anchor.join("managed-workspace/encrypted-workspace.lock"); + let mut checkpoints = 0; + assert!( + Verification::prepare_checked(anchor, &mut || { + checkpoints += 1; + if checkpoints == 2 { + fs::remove_file(&control).unwrap(); + } + Ok(()) + }) + .is_err() + ); + assert_eq!(checkpoints, 2); + assert!(!control.exists()); + assert_eq!(fs::read_dir(vault.0).unwrap().count(), 1); + } + "verify-cancel" => { + let verification = Verification::prepare(anchor).unwrap(); + drop(verification); + } + "verify-wrong-consent" => { + let verification = Verification::prepare(anchor).unwrap(); + assert!(matches!( + verification.select( + VerifyConsent { + token: "f".repeat(64) + }, + &vault + ), + Err(Error::ConsentRequired) + )); + } + "expect-refusal" => { + if let Ok(verification) = Verification::prepare(anchor) { + let consent = verification.synthetic_consent(); + assert!(verification.select(consent, &vault).is_err()); + } + } + _ => panic!("unsupported disposable test mode"), + } +} diff --git a/apps/desktop/src/workspace_close.rs b/apps/desktop/src/workspace_close.rs index 9f04722..e47c469 100644 --- a/apps/desktop/src/workspace_close.rs +++ b/apps/desktop/src/workspace_close.rs @@ -102,6 +102,35 @@ impl WorkspaceClose { state: Arc::new(Mutex::new(State::default())), } } + /// Bootstrap uses the existing close protocol before the first renderer is + /// present. It must leave a real Closing attempt for that renderer to purge + /// and acknowledge; this is never a shortcut to Locked or an open client. + pub(super) fn begin_initial(&self, cleanup: impl FnOnce(bool) -> bool) -> bool { + let fresh = self.state.lock().is_ok_and(|state| { + state.epoch == 0 + && !state.failed + && !state.exiting + && state.attempt.is_none() + && state.control.is_none() + }); + if !fresh { + return false; + } + let view = self.begin(cleanup); + matches!(view.state, Phase::Closing) + && view.attempt_id.is_some() + && view.epoch.is_some() + && view.diagnostic.is_none() + } + /// Startup failure is terminal for this application lifetime. Even a later + /// successful drain cannot turn it into a successful startup/clean exit. + pub(super) fn fail_startup(&self) { + match self.state.lock() { + Ok(mut state) => state.failed = true, + Err(error) => error.into_inner().failed = true, + } + self.source.fail_closed(); + } /// Serialize the irreversible exit fence with closed-control resume. The /// source owns the drain cycle; this adds no second drain or cleanup owner. pub(super) fn fence_admission_for_exit(&self) { @@ -472,6 +501,8 @@ pub(super) mod failure; #[allow(dead_code)] #[path = "workspace_close_control.rs"] mod control; +#[cfg(feature = "encrypted-workspace")] +pub(crate) use control::{Flight as StartupFlight, StartupBinding, StartupPermit}; #[path = "workspace_setup.rs"] pub(super) mod setup; @@ -489,7 +520,7 @@ fn next_identity( } (id, epoch.map(|n| n.to_string())) } -fn native_cleanup(app: &AppHandle, drained: bool) -> bool { +pub(super) fn native_cleanup(app: &AppHandle, drained: bool) -> bool { let local = app .state::() .purge_for_workspace_close(); @@ -502,7 +533,8 @@ fn native_cleanup(app: &AppHandle, drained: bool) -> bool { let openshell = app .state::() .purge_for_workspace_close(drained); - let mut healthy = local.healthy && cloud.healthy && credential.healthy && openshell; + let startup = crate::workspace_startup_host::cleanup_consistent(app, drained); + let mut healthy = local.healthy && cloud.healthy && credential.healthy && openshell && startup; for (label, keep_parent) in [ (crate::model_consent::REVIEW_WINDOW, local.keep_parent), (crate::cloud_model_consent::REVIEW_WINDOW, cloud.keep_parent), @@ -556,6 +588,9 @@ pub(super) fn window_event(window: &Window, event: &WindowEvent) { |drained| native_cleanup(app, drained), || failure::wake(app), ); + if main_window_destroyed(window.label(), event) { + crate::workspace_startup_host::retire_for_close(app); + } } #[tauri::command] pub(super) fn get_workspace_close_state( @@ -580,7 +615,9 @@ pub(super) fn begin_workspace_close( allowed(window.label())?; let state = app.state::(); Ok(if empty(request.body()) { + let retirement = crate::workspace_startup_host::retire_for_ordinary_close(&app); let view = state.begin(|drained| native_cleanup(&app, drained)); + drop(retirement); failure::wake(&app); view } else { diff --git a/apps/desktop/src/workspace_close_control.rs b/apps/desktop/src/workspace_close_control.rs index b206b8d..034980c 100644 --- a/apps/desktop/src/workspace_close_control.rs +++ b/apps/desktop/src/workspace_close_control.rs @@ -34,6 +34,72 @@ pub(crate) struct Flight { disarmed: bool, } +/// Borrowed custody for bounded native startup work. It cannot outlive the +/// Flight, be decoded from IPC, or resume the content registry. +#[cfg(feature = "encrypted-workspace")] +pub(crate) struct StartupPermit<'a> { + flight: &'a Flight, +} + +/// Retained native plan identity. Neither a request ID nor a standalone grant: +/// every use still requires the same live coordinator and exact control cycle. +#[cfg(feature = "encrypted-workspace")] +pub(crate) struct StartupBinding { + coordinator: std::sync::Weak>, + serial: u64, +} + +#[cfg(feature = "encrypted-workspace")] +impl StartupPermit<'_> { + pub(crate) fn binding(&self) -> Result { + self.checkpoint()?; + Ok(StartupBinding { + coordinator: Arc::downgrade(&self.flight.close.state), + serial: self.flight.serial, + }) + } + pub(crate) fn check_binding(&self, binding: &StartupBinding) -> Result<(), ControlError> { + if binding.serial != self.flight.serial + || !binding + .coordinator + .upgrade() + .is_some_and(|coordinator| Arc::ptr_eq(&coordinator, &self.flight.close.state)) + { + return Err(ControlError::Stale); + } + self.checkpoint() + } + pub(crate) fn checkpoint(&self) -> Result<(), ControlError> { + if self.flight.stage != Stage::New || !self.flight.current() { + return Err(ControlError::Stale); + } + let control = self.flight.control.as_ref().ok_or(ControlError::Stale)?; + control.startup_checkpoint()?; + // C0 cleanup allowed this control to be created. Source-bearing startup + // work also needs the fresh C1 renderer acknowledgment; caller-supplied + // identities and the old completed cycle cannot stand in for it. + let ready = self.flight.close.state.lock().is_ok_and(|state| { + !state.exiting + && !state.failed + && state.control.as_ref().is_some_and(|retained| { + retained.serial == self.flight.serial && retained.active + }) + && state.attempt.as_ref().is_some_and(|attempt| { + attempt.progress.lock().is_ok_and(|progress| { + progress.healthy + && progress.initial_done + && !progress.finishing + && progress.acknowledged + }) + }) + }); + if !ready { + return Err(ControlError::Unavailable); + } + control.startup_checkpoint() + } +} + fn attempt( ticket: CloseTicket, id: Option, @@ -58,6 +124,58 @@ fn random(bytes: &mut [u8]) -> Result<(), ()> { } impl WorkspaceClose { + /// Observation for the bounded native waiter only. A true value is not a + /// permit: the retained Flight still rechecks its exact serial and lease. + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn startup_acknowledged(&self) -> Result { + let state = self.state.lock().map_err(|_| ControlError::Unavailable)?; + if state.exiting + || state.failed + || self.source.failure_latched() + || !state.control.as_ref().is_some_and(|retained| { + retained.kind == ControlKind::Startup + && retained.stage == Stage::New + && retained.active + }) + { + return Err(ControlError::Unavailable); + } + let attempt = state.attempt.as_ref().ok_or(ControlError::Unavailable)?; + let progress = attempt + .progress + .lock() + .map_err(|_| ControlError::Unavailable)?; + if !progress.healthy || !progress.initial_done || progress.finishing { + return Err(ControlError::Unavailable); + } + Ok(progress.acknowledged) + } + + /// Native startup may begin only from the coordinator's actual completed + /// close. Returned identifiers match requests; they do not replace custody. + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn locked_startup_cycle(&self) -> Result<(String, String), ControlError> { + let state = self.state.lock().map_err(|_| ControlError::Unavailable)?; + if state.exiting + || state.control.is_some() + || self.source.failure_latched() + || !healthy_attempt(&state) + { + return Err(ControlError::Unavailable); + } + let attempt = state.attempt.as_ref().ok_or(ControlError::Unavailable)?; + let progress = attempt + .progress + .lock() + .map_err(|_| ControlError::Unavailable)?; + if !progress.native_done || !progress.acknowledged { + return Err(ControlError::Unavailable); + } + Ok(( + attempt.id.clone().ok_or(ControlError::Unavailable)?, + attempt.epoch.clone().ok_or(ControlError::Unavailable)?, + )) + } /// Call only after native consent policy and main-window identity are /// qualified. This private seam does not establish either by itself. #[cfg(test)] @@ -387,6 +505,49 @@ fn healthy_attempt(state: &State) -> bool { }) } impl Flight { + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn check_bound_identity(&mut self, expected: &str) -> Result<(), ControlError> { + if self.stage != Stage::New { + return Err(ControlError::Invalid); + } + self.apply(|control| control.check_bound_identity(expected)) + } + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn startup_cycle(&self) -> Result<(String, String), ControlError> { + if self.stage != Stage::New || !self.current() { + return Err(ControlError::Stale); + } + self.control + .as_ref() + .ok_or(ControlError::Stale)? + .startup_checkpoint()?; + let state = self + .close + .state + .lock() + .map_err(|_| ControlError::Unavailable)?; + let attempt = state.attempt.as_ref().ok_or(ControlError::Stale)?; + Ok(( + attempt.id.clone().ok_or(ControlError::Unavailable)?, + attempt.epoch.clone().ok_or(ControlError::Unavailable)?, + )) + } + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn startup_permit(&self) -> Result, ControlError> { + let permit = StartupPermit { flight: self }; + permit.checkpoint()?; + Ok(permit) + } + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn bind_locked_owner( + &mut self, + proof: crate::workspace_startup::BindingProof, + ) -> Result<(), ControlError> { + if self.stage != Stage::New { + return Err(ControlError::Invalid); + } + self.apply(|control| control.bind_locked_owner(proof)) + } fn current(&self) -> bool { self.close.state.lock().is_ok_and(|s| { !s.exiting diff --git a/apps/desktop/src/workspace_close_control_tests.rs b/apps/desktop/src/workspace_close_control_tests.rs index afda069..85bcde7 100644 --- a/apps/desktop/src/workspace_close_control_tests.rs +++ b/apps/desktop/src/workspace_close_control_tests.rs @@ -636,3 +636,162 @@ fn panicking_callback_cleanup_and_generic_lock_after_success_stay_closed() { Err(AdmissionError::Unavailable) )); } + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn startup_permit_keeps_real_closed_custody_without_content_or_vault_access() { + let root = TestRoot::new("startup-permit-custody"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let close = locked_close(access.clone()); + let opens = vault.0.lock().unwrap().opens; + + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + let (id, epoch) = control_attempt(&close); + assert!(matches!( + flight.startup_permit(), + Err(ControlError::Unavailable) + )); + assert!(matches!( + access.begin(Lane::Read), + Err(AdmissionError::Unavailable) + )); + assert_eq!(vault.0.lock().unwrap().opens, opens); + + assert_eq!( + view_json(close.acknowledge(&acknowledgement(&id, &epoch), |_| true))["state"], + "closing" + ); + let permit = flight.startup_permit().unwrap(); + assert!(permit.checkpoint().is_ok()); + assert_eq!(vault.0.lock().unwrap().opens, opens); + + drop(flight); + assert_eq!(view_json(close.inspect(|_| true))["state"], "locked"); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn ordinary_controls_cannot_mint_startup_permits_or_run_startup_as_setup() { + for (label, kind) in [ + ("create", ControlKind::CreateEmpty), + ("unlock", ControlKind::Unlock), + ("recovery", ControlKind::Recovery), + ] { + let root = TestRoot::new(&format!("startup-permit-{label}")); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let close = locked_close(access); + let flight = close.start_control(kind, |_| true).unwrap(); + let (id, epoch) = control_attempt(&close); + assert_eq!( + view_json(close.acknowledge(&acknowledgement(&id, &epoch), |_| true))["state"], + "closing" + ); + assert!(matches!( + flight.startup_permit(), + Err(ControlError::Invalid) + )); + drop(flight); + } + + let root = TestRoot::new("startup-resume-not-ordinary-control"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let close = locked_close(access); + let opens = vault.0.lock().unwrap().opens; + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + assert!(matches!(flight.resume(), Err(ControlError::Invalid))); + assert_eq!(vault.0.lock().unwrap().opens, opens); + + let root = TestRoot::new("startup-prepare-not-ordinary-control"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let close = locked_close(access); + let opens = vault.0.lock().unwrap().opens; + let mut flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + assert!(matches!(flight.prepare(), Err(ControlError::Invalid))); + assert_eq!(vault.0.lock().unwrap().opens, opens); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn retained_startup_requires_fresh_c1_ack_and_has_one_active_worker() { + let root = TestRoot::new("startup-retained-worker"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let close = locked_close(access); + + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + let (id, epoch) = control_attempt(&close); + flight.retain().unwrap(); + assert!(matches!( + close.take_control_ready(&id, &epoch, |_| true), + Err(ControlError::Unavailable) + )); + assert_eq!( + view_json(close.acknowledge(&acknowledgement(&id, &epoch), |_| true))["state"], + "closing" + ); + + let worker = close.take_control_ready(&id, &epoch, |_| true).unwrap(); + assert!(worker.startup_permit().unwrap().checkpoint().is_ok()); + assert!(matches!( + close.take_control_ready(&id, &epoch, |_| true), + Err(ControlError::Busy) + )); + assert_eq!( + view_json(close.cancel_control("wrong", &epoch, |_| true))["diagnostic"], + "invalid_workspace_close_request" + ); + + let cancelled = view_json(close.cancel_control(&id, &epoch, |_| true)); + let (new_id, new_epoch) = attempt(&cancelled); + assert_ne!( + (id.as_str(), epoch.as_str()), + (new_id.as_str(), new_epoch.as_str()) + ); + assert!(matches!(worker.startup_permit(), Err(ControlError::Stale))); + assert!(matches!( + close.take_control_ready(&id, &epoch, |_| true), + Err(ControlError::Stale) + )); + assert_eq!( + view_json(close.cancel_control(&id, &epoch, |_| true))["diagnostic"], + "invalid_workspace_close_request" + ); + drop(worker); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn cancelling_a_held_startup_permit_waits_for_actual_flight_drop() { + let root = TestRoot::new("startup-held-permit-cancel"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let close = locked_close(access.clone()); + let opens = vault.0.lock().unwrap().opens; + + let flight = close.start_control(ControlKind::Startup, |_| true).unwrap(); + let (old_id, old_epoch) = control_attempt(&close); + assert_eq!( + view_json(close.acknowledge(&acknowledgement(&old_id, &old_epoch), |_| true))["state"], + "closing" + ); + let permit = flight.startup_permit().unwrap(); + let cancelled = view_json(close.cancel_control(&old_id, &old_epoch, |_| true)); + let (new_id, new_epoch) = attempt(&cancelled); + assert!(matches!(permit.checkpoint(), Err(ControlError::Stale))); + assert!(matches!( + access.begin(Lane::Read), + Err(AdmissionError::Unavailable) + )); + assert_eq!(vault.0.lock().unwrap().opens, opens); + assert_eq!( + view_json(close.acknowledge(&acknowledgement(&new_id, &new_epoch), |_| true))["state"], + "closing" + ); + + drop(flight); + assert_eq!(view_json(close.inspect(|_| true))["state"], "locked"); +} diff --git a/apps/desktop/src/workspace_empty_provisioning_tests.rs b/apps/desktop/src/workspace_empty_provisioning_tests.rs new file mode 100644 index 0000000..46aa2c9 --- /dev/null +++ b/apps/desktop/src/workspace_empty_provisioning_tests.rs @@ -0,0 +1,802 @@ +//! Synthetic interrupted-empty provisioning tests. No OS vault or native UI. +use super::*; + +use std::{cell::RefCell, collections::BTreeMap, fs, path::PathBuf, rc::Rc}; + +struct TestRoot(PathBuf); + +impl TestRoot { + fn new(label: &str) -> Self { + let path = std::env::temp_dir().canonicalize().unwrap().join(format!( + "rangoon-empty-provisioning-{label}-{}", + WorkspaceId::generate().unwrap().as_hex(), + )); + fs::create_dir(&path).unwrap(); + Self(path.canonicalize().unwrap()) + } + + fn binding(&self) -> PathBuf { + self.0.join(BINDING) + } + + fn encrypted_root(&self) -> PathBuf { + self.0.join(PARENT) + } +} + +impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn provisioning_binding(workspace_id: &str) -> Vec { + Binding { + ready: false, + identity: WorkspaceId::parse(workspace_id).unwrap(), + } + .bytes() +} + +fn database_path(root: &TestRoot, workspace_id: &str) -> PathBuf { + root.encrypted_root().join(workspace_id).join(DATABASE) +} + +fn assert_error(actual: Result, expected: Error) { + match actual { + Ok(_) => panic!("expected {expected:?}"), + Err(error) => assert_eq!(error, expected), + } +} + +fn selected_source() -> rangoon_domain::AnalysisReport { + rangoon_import::analyze("AGENTS.md", b"# Test\nSynthetic source.\n").unwrap() +} + +#[derive(Default)] +struct VaultState { + records: BTreeMap>, + opens: usize, + reads: usize, + writes: usize, + uncertain_write_once: bool, + after_read_effect: Option, +} + +#[derive(Clone)] +struct ReadEffect { + trigger: usize, + path: PathBuf, + bytes: Vec, +} + +#[derive(Clone, Default)] +struct InterruptedVault(Rc>); + +struct InterruptedSlot { + identity: WorkspaceId, + vault: InterruptedVault, +} + +impl InterruptedVault { + fn arm_uncertain_write_once(&self) { + self.0.borrow_mut().uncertain_write_once = true; + } + + fn opens(&self) -> usize { + self.0.borrow().opens + } + + fn reads(&self) -> usize { + self.0.borrow().reads + } + + fn writes(&self) -> usize { + self.0.borrow().writes + } + + fn remove(&self, workspace_id: &str) { + self.0.borrow_mut().records.remove(workspace_id); + } + + fn corrupt(&self, workspace_id: &str) { + let mut state = self.0.borrow_mut(); + let record = state.records.get_mut(workspace_id).unwrap(); + *record.last_mut().unwrap() ^= 1; + } + + fn malformed(&self, workspace_id: &str) { + self.0 + .borrow_mut() + .records + .insert(workspace_id.into(), vec![0]); + } + + fn arm_after_reads(&self, reads: usize, path: PathBuf, bytes: &[u8]) { + let mut state = self.0.borrow_mut(); + state.after_read_effect = Some(ReadEffect { + trigger: state.reads + reads, + path, + bytes: bytes.to_vec(), + }); + } + + fn snapshot(&self, workspace_id: &str) -> zeroize::Zeroizing> { + zeroize::Zeroizing::new(self.0.borrow().records.get(workspace_id).unwrap().clone()) + } + + fn matches(&self, workspace_id: &str, expected: &zeroize::Zeroizing>) -> bool { + self.0 + .borrow() + .records + .get(workspace_id) + .is_some_and(|actual| actual.as_slice() == expected.as_slice()) + } +} + +impl Vault for InterruptedVault { + type Slot = InterruptedSlot; + + fn open(&self, identity: &WorkspaceId) -> Result { + let mut state = self.0.borrow_mut(); + state.opens += 1; + Ok(InterruptedSlot { + identity: identity.clone(), + vault: self.clone(), + }) + } +} + +impl Store for InterruptedSlot { + fn identity(&self) -> &WorkspaceId { + &self.identity + } + + fn read(&self) -> Result>>, workspace_keys::Error> { + let (record, effect) = { + let mut state = self.vault.0.borrow_mut(); + state.reads += 1; + let effect = if state + .after_read_effect + .as_ref() + .is_some_and(|effect| effect.trigger == state.reads) + { + state.after_read_effect.take() + } else { + None + }; + (state.records.get(&self.identity.as_hex()).cloned(), effect) + }; + if let Some(effect) = effect { + fs::write(effect.path, effect.bytes).map_err(|_| workspace_keys::Error::Unavailable)?; + } + Ok(record.map(zeroize::Zeroizing::new)) + } + + fn write(&self, envelope: &[u8]) -> Result<(), workspace_keys::Error> { + let mut state = self.vault.0.borrow_mut(); + state.writes += 1; + state + .records + .insert(self.identity.as_hex(), envelope.to_vec()); + if std::mem::take(&mut state.uncertain_write_once) { + return Err(workspace_keys::Error::WriteUncertain); + } + Ok(()) + } +} + +struct Interrupted { + root: TestRoot, + vault: InterruptedVault, + workspace_id: String, +} + +/// Persists the real key envelope, then reports an uncertain write. This leaves +/// Owner's genuine Pending/CreateEmpty operation and unready binding intact. +fn interrupted_empty(label: &str) -> Interrupted { + let root = TestRoot::new(label); + let vault = InterruptedVault::default(); + let mut owner = Owner::acquire(root.0.clone()).unwrap(); + let create = owner.prepare_create_empty().unwrap(); + vault.arm_uncertain_write_once(); + assert_error(owner.confirm(&create.id, &vault), Error::WriteUncertain); + assert_eq!( + fs::read(root.binding()).unwrap(), + provisioning_binding(&create.workspace_id) + ); + assert!(!database_path(&root, &create.workspace_id).exists()); + assert_eq!(vault.writes(), 1); + drop(owner); + Interrupted { + root, + vault, + workspace_id: create.workspace_id, + } +} + +#[test] +fn empty_provisioning_finishes_exact_interrupted_attempt_then_requires_unlock() { + let interrupted = interrupted_empty("finish"); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + + assert_eq!(preview.workspace_id, interrupted.workspace_id); + assert_ne!(preview.attempt_id, preview.workspace_id); + assert_eq!(preview.status, "uninitialized"); + assert_eq!(interrupted.vault.writes(), 1); + assert!(interrupted.vault.reads() > 0); + + owner + .finish_empty_provisioning(&preview.id, &interrupted.vault) + .unwrap(); + assert!(!owner.is_unlocked()); + assert_eq!(interrupted.vault.writes(), 1); + + let unlock = owner.prepare_unlock().unwrap(); + owner.confirm(&unlock.id, &interrupted.vault).unwrap(); + assert!(owner.list(&interrupted.vault).unwrap().is_empty()); +} + +#[test] +fn empty_provisioning_tokens_are_consumed_before_new_vault_access() { + let interrupted = interrupted_empty("tokens"); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + + assert_error( + owner.finish_empty_provisioning("wrong", &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + + owner + .finish_empty_provisioning(&preview.id, &interrupted.vault) + .unwrap(); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); +} + +#[test] +fn replacement_inspection_drops_old_plan_even_when_new_inspection_refuses() { + let interrupted = interrupted_empty("replacement"); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let first = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + interrupted.vault.remove(&interrupted.workspace_id); + assert!( + owner + .inspect_empty_provisioning(&interrupted.vault) + .is_err() + ); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + + assert_error( + owner.finish_empty_provisioning(&first.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + assert!(!database_path(&interrupted.root, &interrupted.workspace_id).exists()); +} + +#[test] +fn empty_provisioning_refuses_missing_or_malformed_existing_key() { + for case in ["missing", "malformed"] { + let interrupted = interrupted_empty(case); + match case { + "missing" => interrupted.vault.remove(&interrupted.workspace_id), + "malformed" => interrupted.vault.malformed(&interrupted.workspace_id), + _ => unreachable!(), + } + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let writes = interrupted.vault.writes(); + assert!( + owner + .inspect_empty_provisioning(&interrupted.vault) + .is_err() + ); + assert_eq!(interrupted.vault.writes(), writes); + assert!(!database_path(&interrupted.root, &interrupted.workspace_id).exists()); + } +} + +#[test] +fn changed_key_after_inspection_refuses_completion_without_initialization() { + let interrupted = interrupted_empty("changed-after-inspection"); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + interrupted.vault.corrupt(&interrupted.workspace_id); + let writes = interrupted.vault.writes(); + + // Without a database, a fresh inspection cannot authenticate a different + // well-formed envelope. Completion revalidates its retained inspection. + assert!( + owner + .finish_empty_provisioning(&preview.id, &interrupted.vault) + .is_err() + ); + assert_eq!(interrupted.vault.writes(), writes); + assert!(!database_path(&interrupted.root, &interrupted.workspace_id).exists()); + + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); +} + +#[test] +fn empty_provisioning_refuses_nonempty_or_non_create_empty_evidence_before_vault() { + for case in ["extra", "zero", "source", "ready"] { + let interrupted = if case == "source" { + let root = TestRoot::new("source-operation"); + let vault = InterruptedVault::default(); + let mut owner = Owner::acquire(root.0.clone()).unwrap(); + let create = owner.prepare_create(&selected_source()).unwrap(); + vault.arm_uncertain_write_once(); + assert_error(owner.confirm(&create.id, &vault), Error::WriteUncertain); + drop(owner); + Interrupted { + root, + vault, + workspace_id: create.workspace_id, + } + } else if case == "ready" { + let root = TestRoot::new("ready-operation"); + let vault = InterruptedVault::default(); + let mut owner = Owner::acquire(root.0.clone()).unwrap(); + let create = owner.prepare_create_empty().unwrap(); + owner.confirm(&create.id, &vault).unwrap(); + owner.lock(); + drop(owner); + Interrupted { + root, + vault, + workspace_id: create.workspace_id, + } + } else { + interrupted_empty(case) + }; + if case == "extra" { + fs::write( + interrupted + .root + .encrypted_root() + .join(&interrupted.workspace_id) + .join("unexpected"), + b"x", + ) + .unwrap(); + } + if case == "zero" { + fs::write( + database_path(&interrupted.root, &interrupted.workspace_id), + [], + ) + .unwrap(); + } + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let opens = interrupted.vault.opens(); + assert!( + owner + .inspect_empty_provisioning(&interrupted.vault) + .is_err() + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.writes(), 1); + } +} + +#[test] +fn post_initialization_faults_recover_with_existing_metadata_path_without_replay() { + for fault in [ + Fault::BeforeReconcileReadyWrite, + Fault::BeforeReconcileReadySync, + Fault::BeforeReconcileReadyReadback, + Fault::BeforeCompletionWrite, + Fault::BeforeCompletionSync, + Fault::BeforeCompletionReadback, + ] { + let interrupted = interrupted_empty("finish-fault"); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + owner.inject_fault(fault); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::WriteUncertain, + ); + assert!(!owner.is_unlocked()); + assert!(database_path(&interrupted.root, &interrupted.workspace_id).is_file()); + assert_eq!(interrupted.vault.writes(), 1); + drop(owner); + + let mut fresh = Owner::acquire(interrupted.root.0.clone()).unwrap(); + assert!( + fresh + .inspect_empty_provisioning(&interrupted.vault) + .is_err() + ); + let recovery = fresh.inspect_recovery(&interrupted.vault).unwrap(); + fresh + .confirm_recovery(&recovery.id, &interrupted.vault) + .unwrap(); + assert_eq!(interrupted.vault.writes(), 1); + } +} + +#[test] +fn empty_provisioning_refuses_damaged_or_foreign_metadata_before_vault_access() { + let prefix = b"rangoon.workspace-operation.v1\0"; + let phase = prefix.len(); + let sequence = phase + 2; + let workspace = sequence + 8; + let attempt = workspace + 64; + + for case in [ + "truncated-pending", + "unknown-operation", + "observed-pending", + "foreign-workspace", + "attempt-is-workspace", + "sequence-two", + "terminal-present", + "terminal-damaged", + "ready-binding", + "corrupt-binding", + ] { + let interrupted = interrupted_empty(case); + let pending = interrupted + .root + .0 + .join("encrypted-workspace.operation.pending"); + let terminal = interrupted + .root + .0 + .join("encrypted-workspace.operation.terminal"); + let binding = interrupted.root.binding(); + match case { + "truncated-pending" => fs::write(&pending, b"truncated").unwrap(), + "unknown-operation" => { + let mut bytes = fs::read(&pending).unwrap(); + bytes[phase + 1] = u8::MAX; + fs::write(&pending, bytes).unwrap(); + } + "observed-pending" => { + let mut bytes = fs::read(&pending).unwrap(); + bytes[phase] = 1; + fs::write(&pending, bytes).unwrap(); + } + "foreign-workspace" => { + let mut bytes = fs::read(&pending).unwrap(); + bytes[workspace] = if bytes[workspace] == b'a' { b'b' } else { b'a' }; + fs::write(&pending, bytes).unwrap(); + } + "attempt-is-workspace" => { + let mut bytes = fs::read(&pending).unwrap(); + let identity = bytes[workspace..workspace + 64].to_vec(); + bytes[attempt..attempt + 64].copy_from_slice(&identity); + fs::write(&pending, bytes).unwrap(); + } + "sequence-two" => { + let mut bytes = fs::read(&pending).unwrap(); + bytes[sequence + 7] = 2; + fs::write(&pending, bytes).unwrap(); + } + "terminal-present" => fs::write(&terminal, fs::read(&pending).unwrap()).unwrap(), + "terminal-damaged" => fs::write(&terminal, b"damaged").unwrap(), + "ready-binding" => { + let mut bytes = fs::read(&binding).unwrap(); + bytes[29] = 1; + fs::write(&binding, bytes).unwrap(); + } + "corrupt-binding" => { + let mut bytes = fs::read(&binding).unwrap(); + bytes[0] ^= 1; + fs::write(&binding, bytes).unwrap(); + } + _ => unreachable!(), + } + let expected_pending = fs::read(&pending).unwrap(); + let expected_binding = fs::read(&binding).unwrap(); + let expected_terminal = terminal.exists().then(|| fs::read(&terminal).unwrap()); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + + assert!( + owner + .inspect_empty_provisioning(&interrupted.vault) + .is_err() + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + assert_eq!(interrupted.vault.writes(), 1); + assert_eq!(fs::read(&pending).unwrap(), expected_pending); + assert_eq!(fs::read(&binding).unwrap(), expected_binding); + assert_eq!(terminal.exists(), expected_terminal.is_some()); + if let Some(expected) = expected_terminal { + assert_eq!(fs::read(terminal).unwrap(), expected); + } + } +} + +#[test] +fn empty_provisioning_lock_and_reacquisition_invalidate_retained_finish_tokens() { + let interrupted = interrupted_empty("lock-stale"); + let binding = fs::read(interrupted.root.binding()).unwrap(); + let pending = fs::read( + interrupted + .root + .0 + .join("encrypted-workspace.operation.pending"), + ) + .unwrap(); + let envelope = interrupted.vault.snapshot(&interrupted.workspace_id); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + owner.lock(); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + drop(owner); + + let mut fresh = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + assert_error( + fresh.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + assert_eq!(fs::read(interrupted.root.binding()).unwrap(), binding); + assert_eq!( + fs::read( + interrupted + .root + .0 + .join("encrypted-workspace.operation.pending"), + ) + .unwrap(), + pending + ); + assert!( + interrupted + .vault + .matches(&interrupted.workspace_id, &envelope) + ); + assert!(fresh.inspect_empty_provisioning(&interrupted.vault).is_ok()); + assert_eq!(interrupted.vault.writes(), 1); +} + +#[test] +fn empty_provisioning_finish_refuses_replaced_or_nonempty_destination_before_vault() { + for case in [ + "empty-database", + "partial-database", + "sidecar", + "extra", + "replaced-directory", + "replaced-control", + "replaced-binding", + ] { + let interrupted = interrupted_empty(case); + let pending = interrupted + .root + .0 + .join("encrypted-workspace.operation.pending"); + let pending_before = fs::read(&pending).unwrap(); + let envelope = interrupted.vault.snapshot(&interrupted.workspace_id); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + let destination = interrupted + .root + .encrypted_root() + .join(&interrupted.workspace_id); + let mut preserved = None; + match case { + "empty-database" => { + let path = database_path(&interrupted.root, &interrupted.workspace_id); + fs::write(&path, []).unwrap(); + preserved = Some(path); + } + "partial-database" => { + let path = database_path(&interrupted.root, &interrupted.workspace_id); + fs::write(&path, b"partial").unwrap(); + preserved = Some(path); + } + "sidecar" => { + let path = destination.join("workspace.sqlite3-wal"); + fs::write(&path, b"sidecar").unwrap(); + preserved = Some(path); + } + "extra" => { + let path = destination.join("unexpected"); + fs::write(&path, b"extra").unwrap(); + preserved = Some(path); + } + "replaced-directory" => { + fs::rename(&destination, interrupted.root.0.join("retained-directory")).unwrap(); + fs::create_dir(&destination).unwrap(); + } + "replaced-control" => { + let control = interrupted.root.0.join(CONTROL); + fs::rename(&control, interrupted.root.0.join("retained-control")).unwrap(); + fs::write(control, []).unwrap(); + } + "replaced-binding" => { + let binding = interrupted.root.binding(); + fs::rename(&binding, interrupted.root.0.join("retained-binding")).unwrap(); + fs::write(binding, b"replacement").unwrap(); + } + _ => unreachable!(), + } + let preserved_bytes = preserved.as_ref().map(|path| fs::read(path).unwrap()); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + + assert!( + owner + .finish_empty_provisioning(&preview.id, &interrupted.vault) + .is_err() + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + assert_eq!(interrupted.vault.writes(), 1); + assert_eq!(fs::read(&pending).unwrap(), pending_before); + assert!( + interrupted + .vault + .matches(&interrupted.workspace_id, &envelope) + ); + if let (Some(path), Some(expected)) = (preserved, preserved_bytes) { + assert_eq!(fs::read(path).unwrap(), expected); + } + } +} + +#[test] +fn post_initialization_sidecars_or_extras_refuse_before_ready_or_terminal() { + for name in [ + "unexpected", + "workspace.sqlite3-journal", + "workspace.sqlite3-wal", + "workspace.sqlite3-shm", + ] { + let interrupted = interrupted_empty(name); + let pending = interrupted + .root + .0 + .join("encrypted-workspace.operation.pending"); + let pending_before = fs::read(&pending).unwrap(); + let envelope = interrupted.vault.snapshot(&interrupted.workspace_id); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + let injected = interrupted + .root + .encrypted_root() + .join(&interrupted.workspace_id) + .join(name); + + // The first finish read revalidates before initialization. This hook + // runs on the second one, after the actual encrypted database exists. + interrupted + .vault + .arm_after_reads(2, injected.clone(), b"injected"); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::WriteUncertain, + ); + + assert_eq!( + fs::read(interrupted.root.binding()).unwrap(), + provisioning_binding(&interrupted.workspace_id) + ); + assert_eq!(fs::read(&pending).unwrap(), pending_before); + assert!( + !interrupted + .root + .0 + .join("encrypted-workspace.operation.terminal") + .exists() + ); + assert!(database_path(&interrupted.root, &interrupted.workspace_id).is_file()); + assert_eq!(fs::read(injected).unwrap(), b"injected"); + assert_eq!(interrupted.vault.writes(), 1); + assert!( + interrupted + .vault + .matches(&interrupted.workspace_id, &envelope) + ); + } +} +#[test] +fn changed_valid_pending_after_inspection_refuses_before_vault_and_preserves_bytes() { + let interrupted = interrupted_empty("pending-after-inspect"); + let mut owner = Owner::acquire(interrupted.root.0.clone()).unwrap(); + let preview = owner + .inspect_empty_provisioning(&interrupted.vault) + .unwrap(); + let envelope = interrupted.vault.snapshot(&interrupted.workspace_id); + let pending_path = interrupted + .root + .0 + .join("encrypted-workspace.operation.pending"); + let mut changed = fs::read(&pending_path).unwrap(); + let prefix = b"rangoon.workspace-operation.v1\0"; + assert!(changed.starts_with(prefix)); + let attempt_start = prefix.len() + 74; + let workspace_start = prefix.len() + 10; + // Change only one lowercase hexadecimal attempt byte. The alternate is + // distinct from both old attempt and workspace, retaining a valid record. + changed[attempt_start] = b"abc" + .iter() + .copied() + .find(|byte| *byte != changed[attempt_start] && *byte != changed[workspace_start]) + .unwrap(); + fs::write(&pending_path, &changed).unwrap(); + assert!(owner.read_operation().unwrap().is_some()); + let opens = interrupted.vault.opens(); + let reads = interrupted.vault.reads(); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); + assert_eq!(interrupted.vault.writes(), 1); + assert!( + interrupted + .vault + .matches(&interrupted.workspace_id, &envelope) + ); + assert!(fs::read(&pending_path).unwrap() == changed); + assert!(!database_path(&interrupted.root, &interrupted.workspace_id).exists()); + assert!( + !interrupted + .root + .0 + .join("encrypted-workspace.operation.terminal") + .exists() + ); + assert_error( + owner.finish_empty_provisioning(&preview.id, &interrupted.vault), + Error::Stale, + ); + assert_eq!(interrupted.vault.opens(), opens); + assert_eq!(interrupted.vault.reads(), reads); +} diff --git a/apps/desktop/src/workspace_failure.rs b/apps/desktop/src/workspace_failure.rs index bb7b5da..81ded2a 100644 --- a/apps/desktop/src/workspace_failure.rs +++ b/apps/desktop/src/workspace_failure.rs @@ -343,6 +343,11 @@ impl Host for NativeHost { let _ = sender.send(Progress::Stopped); return; }; + if app.state::().failure_latched() { + // The source failure already closed admission. Retire a ready + // startup plan without waiting on its retained Flight here. + crate::workspace_startup_host::retire_for_close(&app); + } let completed = app .state::() .progress_native(|drained| native_cleanup(&app, drained)); @@ -432,13 +437,18 @@ impl Anchor { route_exit_request( code, Some((&self.app.state::(), &self.exit)), - cancel_and_check, + || { + // route_exit_request closes admission before this cancellation. + crate::workspace_startup_host::retire_for_close(&self.app); + cancel_and_check() + }, ) } pub(crate) fn begin_exit_close(&self) { self.app .state::() .begin(|drained| native_cleanup(&self.app, drained)); + crate::workspace_startup_host::retire_for_close(&self.app); wake(&self.app); } } diff --git a/apps/desktop/src/workspace_managed_bootstrap_tests.rs b/apps/desktop/src/workspace_managed_bootstrap_tests.rs new file mode 100644 index 0000000..a1e7c78 --- /dev/null +++ b/apps/desktop/src/workspace_managed_bootstrap_tests.rs @@ -0,0 +1,627 @@ +use super::*; + +use crate::{ + capabilities::CapabilityResult, + workspace_close::{ + WorkspaceClose, + setup::{self, Cycle, Preparation}, + }, + workspace_requests::WorkspaceRequest, +}; +use rangoon_desktop::{ + workspace_keys::{Error as KeyError, Store, WorkspaceId}, + workspace_session::{Error as OwnerError, Vault}, +}; +use serde_json::json; +use std::{ + collections::BTreeMap, + fs, + sync::{Arc, Mutex}, +}; +use tauri::ipc::InvokeBody; +use zeroize::Zeroizing; + +#[derive(Default)] +struct CountingVaultState { + slots: BTreeMap>>, + opens: usize, + reads: usize, + writes: usize, +} + +#[derive(Clone, Default)] +struct CountingVault(Arc>); + +struct CountingSlot { + identity: WorkspaceId, + lookup: String, + state: Arc>, +} + +impl CountingVault { + fn counts(&self) -> (usize, usize, usize) { + let state = self.0.lock().unwrap(); + (state.opens, state.reads, state.writes) + } + + fn reset_counts(&self) { + let mut state = self.0.lock().unwrap(); + state.opens = 0; + state.reads = 0; + state.writes = 0; + } +} + +impl Vault for CountingVault { + type Slot = CountingSlot; + + fn open(&self, identity: &WorkspaceId) -> Result { + let mut state = self.0.lock().unwrap(); + state.opens += 1; + let lookup = identity.as_hex(); + state.slots.entry(lookup.clone()).or_insert(None); + Ok(CountingSlot { + identity: identity.clone(), + lookup, + state: Arc::clone(&self.0), + }) + } +} + +impl Store for CountingSlot { + fn identity(&self) -> &WorkspaceId { + &self.identity + } + + fn read(&self) -> Result>>, KeyError> { + let mut state = self.state.lock().unwrap(); + state.reads += 1; + Ok(state + .slots + .get(&self.lookup) + .cloned() + .flatten() + .map(Zeroizing::new)) + } + + fn write(&self, envelope: &[u8]) -> Result<(), KeyError> { + let mut state = self.state.lock().unwrap(); + state.writes += 1; + state + .slots + .insert(self.lookup.clone(), Some(envelope.to_vec())); + Ok(()) + } +} + +fn managed_locked(root: &TestRoot, vault: &CountingVault) -> SourceAccess { + SourceAccess::managed_locked(Gate::new(), root.0.clone(), vault.clone()).unwrap() +} + +#[test] +fn deferred_managed_refuses_prebind_content_without_latching_failure_or_touching_storage() { + let root = TestRoot::new("deferred-prebind"); + let roots = crate::workspace_startup::StartupRoots::new(root.0.clone()); + let vault = CountingVault::default(); + let access = SourceAccess::managed_deferred(Gate::new(), roots.managed(), vault.clone()); + assert!(access.encrypted_close_available()); + assert!(!roots.managed().exists()); + assert_unavailable(&access); + let called = std::cell::Cell::new(false); + let result = access.call_backend( + || true, + |_| { + called.set(true); + Ok(()) + }, + Error::Store(StoreError::Unavailable), + ); + assert!(result.is_err()); + assert!(!called.get()); + assert!(!access.failure_latched()); + assert!(!roots.managed().exists()); + assert_eq!(vault.counts(), (0, 0, 0)); +} + +#[test] +fn deferred_binding_uses_real_closed_custody_then_existing_native_confirmation() { + let root = TestRoot::new("deferred-confirm"); + let roots = crate::workspace_startup::StartupRoots::new(root.0.clone()); + let vault = CountingVault::default(); + let access = SourceAccess::managed_deferred(Gate::new(), roots.managed(), vault.clone()); + let close = WorkspaceClose::new(access.clone()); + let (id, epoch) = complete_c0(&close); + let mut flight = close + .start_control_for(&id, &epoch, ControlKind::CreateEmpty, synthetic_cleanup_ok) + .unwrap(); + let proof = roots.fresh_binding(roots.inspect()).unwrap(); + flight.bind_locked_owner(proof).unwrap(); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_unavailable(&access); + assert_eq!(fs::read_dir(roots.managed()).unwrap().count(), 1); + flight.retain().unwrap(); + let current = serde_json::to_value(close.inspect_control().0).unwrap(); + let (id, epoch) = identity(¤t); + close.acknowledge(&acknowledgement(&id, &epoch), synthetic_cleanup_ok); + assert_eq!(consume_c1(&close, &id, &epoch)["outcome"], "opened"); + assert_eq!(vault.counts().2, 1); + assert!(!client_id(&access).is_empty()); + assert!(!roots.legacy().exists()); + close_open_access(&access, &close); +} + +#[test] +fn deferred_bind_twice_marks_cycle_unhealthy_without_any_credential_use() { + let root = TestRoot::new("deferred-twice"); + let roots = crate::workspace_startup::StartupRoots::new(root.0.clone()); + let vault = CountingVault::default(); + let access = SourceAccess::managed_deferred(Gate::new(), roots.managed(), vault.clone()); + let close = WorkspaceClose::new(access.clone()); + let (id, epoch) = complete_c0(&close); + let mut flight = close + .start_control_for(&id, &epoch, ControlKind::CreateEmpty, synthetic_cleanup_ok) + .unwrap(); + flight + .bind_locked_owner(roots.fresh_binding(roots.inspect()).unwrap()) + .unwrap(); + assert!( + flight + .bind_locked_owner(roots.setup_residue_binding().unwrap()) + .is_err() + ); + drop(flight); + assert_eq!( + serde_json::to_value(close.inspect_control().0).unwrap()["state"], + "recovery_required" + ); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_unavailable(&access); +} + +#[test] +fn deferred_bind_rejects_foreign_native_root_before_owner_or_credential_access() { + let root = TestRoot::new("deferred-fixed"); + let foreign = TestRoot::new("deferred-foreign"); + let roots = crate::workspace_startup::StartupRoots::new(root.0.clone()); + let other = crate::workspace_startup::StartupRoots::new(foreign.0.clone()); + let vault = CountingVault::default(); + let access = SourceAccess::managed_deferred(Gate::new(), roots.managed(), vault.clone()); + let close = WorkspaceClose::new(access.clone()); + let (id, epoch) = complete_c0(&close); + let mut flight = close + .start_control_for(&id, &epoch, ControlKind::CreateEmpty, synthetic_cleanup_ok) + .unwrap(); + assert!( + flight + .bind_locked_owner(other.fresh_binding(other.inspect()).unwrap()) + .is_err() + ); + drop(flight); + assert!(!roots.managed().exists()); + assert_eq!(fs::read_dir(other.managed()).unwrap().count(), 0); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_unavailable(&access); +} + +#[test] +fn deferred_cancelled_setup_can_bind_exact_existing_control_after_restart() { + let root = TestRoot::new("deferred-cancel-restart"); + let roots = crate::workspace_startup::StartupRoots::new(root.0.clone()); + let vault = CountingVault::default(); + { + let access = SourceAccess::managed_deferred(Gate::new(), roots.managed(), vault.clone()); + let close = WorkspaceClose::new(access.clone()); + let (id, epoch) = complete_c0(&close); + let mut flight = close + .start_control_for(&id, &epoch, ControlKind::CreateEmpty, synthetic_cleanup_ok) + .unwrap(); + flight + .bind_locked_owner(roots.fresh_binding(roots.inspect()).unwrap()) + .unwrap(); + flight.retain().unwrap(); + let current = serde_json::to_value(close.inspect_control().0).unwrap(); + let (id, epoch) = identity(¤t); + close.acknowledge(&acknowledgement(&id, &epoch), synthetic_cleanup_ok); + let response = setup::confirm( + &close, + cycle(&id, &epoch), + synthetic_cleanup_ok, + |_| setup::Consent::Cancelled, + || true, + ); + assert_eq!( + serde_json::to_value(response).unwrap()["outcome"], + "cancelled" + ); + assert_unavailable(&access); + } + assert_eq!(vault.counts(), (0, 0, 0)); + let access = SourceAccess::managed_deferred(Gate::new(), roots.managed(), vault.clone()); + let close = WorkspaceClose::new(access.clone()); + let (id, epoch) = complete_c0(&close); + let mut flight = close + .start_control_for(&id, &epoch, ControlKind::CreateEmpty, synthetic_cleanup_ok) + .unwrap(); + flight + .bind_locked_owner(roots.setup_residue_binding().unwrap()) + .unwrap(); + drop(flight); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_eq!(fs::read_dir(roots.managed()).unwrap().count(), 1); + assert_unavailable(&access); +} + +fn synthetic_cleanup_ok(_: bool) -> bool { + // Synthetic cleanup double only. It is not native-window or OS-consent proof. + true +} + +fn protection_json(close: &WorkspaceClose) -> serde_json::Value { + serde_json::to_value(setup::ProtectionResponse::observe(close)).unwrap() +} + +fn identity(value: &serde_json::Value) -> (String, String) { + ( + value["attemptId"].as_str().unwrap().to_owned(), + value["epoch"].as_str().unwrap().to_owned(), + ) +} + +fn body(value: serde_json::Value) -> InvokeBody { + InvokeBody::Raw(serde_json::to_vec(&value).unwrap()) +} + +fn preparation(id: &str, epoch: &str, action: &str) -> Preparation { + Preparation::parse(&body(json!({ + "schemaVersion": "rangoon.workspace-control-prepare.v1", + "attemptId": id, + "epoch": epoch, + "action": action, + }))) + .unwrap() +} + +fn cycle(id: &str, epoch: &str) -> Cycle { + Cycle::parse(&body(json!({ + "schemaVersion": "rangoon.workspace-control-cycle.v1", + "attemptId": id, + "epoch": epoch, + }))) + .unwrap() +} + +fn acknowledgement(id: &str, epoch: &str) -> Vec { + serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-purge-ack.v1", + "attemptId": id, + "epoch": epoch, + })) + .unwrap() +} + +fn complete_c0(close: &WorkspaceClose) -> (String, String) { + let started = serde_json::to_value(close.begin(synthetic_cleanup_ok)).unwrap(); + assert_eq!(started["state"], "closing"); + let (id, epoch) = identity(&started); + let locked = serde_json::to_value( + close.acknowledge(&acknowledgement(&id, &epoch), synthetic_cleanup_ok), + ) + .unwrap(); + assert_eq!(locked["state"], "locked"); + (id, epoch) +} + +fn prepare_c1( + close: &WorkspaceClose, + c0_id: &str, + c0_epoch: &str, + action: &str, +) -> (String, String) { + let response = serde_json::to_value(setup::prepare( + close, + preparation(c0_id, c0_epoch, action), + synthetic_cleanup_ok, + )) + .unwrap(); + assert_eq!(response["outcome"], "prepared"); + let (id, epoch) = identity(&response["close"]); + let acknowledged = serde_json::to_value( + close.acknowledge(&acknowledgement(&id, &epoch), synthetic_cleanup_ok), + ) + .unwrap(); + assert_eq!(acknowledged["state"], "closing"); + (id, epoch) +} + +fn consume_c1(close: &WorkspaceClose, id: &str, epoch: &str) -> serde_json::Value { + serde_json::to_value(setup::confirm( + close, + cycle(id, epoch), + synthetic_cleanup_ok, + |_| setup::Consent::Approved, + || true, + )) + .unwrap() +} + +fn client_id(access: &SourceAccess) -> String { + serde_json::to_value(access.request_view()).unwrap()["clientId"] + .as_str() + .unwrap() + .to_owned() +} + +fn assert_unavailable(access: &SourceAccess) { + assert_eq!( + serde_json::to_value(access.request_view()).unwrap()["state"], + "unavailable" + ); + assert!(matches!( + access.request_context("main", Some(&"a".repeat(64))), + WorkspaceRequest::Refused + )); + assert!(matches!( + access.request_context("main", None), + WorkspaceRequest::Refused + )); +} + +fn close_open_access(access: &SourceAccess, close: &WorkspaceClose) { + complete_c0(close); + assert!(!access.0.backend.lock().unwrap().control_is_open()); +} + +#[test] +fn managed_locked_cold_absent_and_existing_roots_do_not_touch_vault_or_issue_requests() { + let root = TestRoot::new("managed-bootstrap-cold-absent"); + let vault = CountingVault::default(); + let access = managed_locked(&root, &vault); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_unavailable(&access); + assert_eq!( + workspace_code(tauri::async_runtime::block_on(access.list_snapshots())), + "workspace_unavailable" + ); + assert_eq!(vault.counts(), (0, 0, 0)); + + let close = WorkspaceClose::new(access); + let (c0_id, c0_epoch) = complete_c0(&close); + assert_eq!(protection_json(&close)["layout"], "absent"); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "create_empty"); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_eq!(consume_c1(&close, &c1_id, &c1_epoch)["outcome"], "opened"); + assert!(vault.counts().0 > 0); + drop(close); + + vault.reset_counts(); + let reopened = managed_locked(&root, &vault); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_unavailable(&reopened); + drop(reopened); +} + +#[test] +fn managed_locked_c0_c1_consumption_binds_real_requests_and_reopen_preserves_source() { + let root = TestRoot::new("managed-bootstrap-round-trip"); + let vault = CountingVault::default(); + let source = report( + "managed-bootstrap.md", + b"# Managed bootstrap\nsecret data\n", + ); + let source_id = source.source.id.clone(); + + let old_header = { + let access = managed_locked(&root, &vault); + assert_unavailable(&access); + let close = WorkspaceClose::new(access.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + assert_eq!(protection_json(&close)["layout"], "absent"); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "create_empty"); + let opened = consume_c1(&close, &c1_id, &c1_epoch); + assert_eq!(opened["outcome"], "opened"); + assert_eq!(opened["reload"], true); + + let header = client_id(&access); + assert!(matches!( + access.request_context("main", None), + WorkspaceRequest::Refused + )); + let request = access.request_context("main", Some(&header)); + assert!(matches!(request, WorkspaceRequest::Managed(_))); + let bound = access.for_request(&request); + select(&bound, &source); + assert!(matches!( + tauri::async_runtime::block_on(bound.save_analysis(source_id.clone())), + WorkspaceResult::Saved { .. } + )); + match tauri::async_runtime::block_on(bound.open_snapshot(source_id.clone())) { + SelectionResult::Analyzed { report } => assert_eq!(*report, source), + _ => panic!("expected header-bound encrypted source"), + } + assert!(matches!( + tauri::async_runtime::block_on(bound.list_capabilities()), + CapabilityResult::Listed { .. } + )); + assert!(vault.counts().1 > 0); + + let database = fs::read_dir(root.0.join("encrypted-workspaces")) + .unwrap() + .find_map(Result::ok) + .map(|entry| entry.path().join("workspace.sqlite3")) + .unwrap(); + let bytes = fs::read(database).unwrap(); + assert!(!bytes.starts_with(b"SQLite format 3\0")); + + close_open_access(&access, &close); + assert!(matches!( + access.request_context("main", Some(&header)), + WorkspaceRequest::Refused + )); + assert!(matches!( + tauri::async_runtime::block_on(bound.list_snapshots()), + WorkspaceResult::Failed { .. } + )); + drop(bound); + drop(request); + drop(close); + drop(access); + header + }; + + let reopened = managed_locked(&root, &vault); + let close = WorkspaceClose::new(reopened.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + assert_eq!(protection_json(&close)["layout"], "locked"); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "unlock"); + assert_eq!(consume_c1(&close, &c1_id, &c1_epoch)["outcome"], "opened"); + let header = client_id(&reopened); + assert_ne!(header, old_header); + assert!(matches!( + reopened.request_context("main", Some(&old_header)), + WorkspaceRequest::Refused + )); + assert!(matches!( + reopened.request_context("main", None), + WorkspaceRequest::Refused + )); + let request = reopened.request_context("main", Some(&header)); + let bound = reopened.for_request(&request); + match tauri::async_runtime::block_on(bound.open_snapshot(source_id)) { + SelectionResult::Analyzed { report } => assert_eq!(*report, source), + _ => panic!("expected source after same-vault unlock"), + } +} + +#[test] +fn managed_locked_missing_key_refuses_unlock_without_regeneration_or_client() { + let root = TestRoot::new("managed-bootstrap-missing-key"); + let vault = CountingVault::default(); + + { + let access = managed_locked(&root, &vault); + let close = WorkspaceClose::new(access.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "create_empty"); + assert_eq!(consume_c1(&close, &c1_id, &c1_epoch)["outcome"], "opened"); + close_open_access(&access, &close); + } + + let key = vault + .0 + .lock() + .unwrap() + .slots + .keys() + .next() + .cloned() + .unwrap(); + vault.0.lock().unwrap().slots.remove(&key); + vault.reset_counts(); + + let access = managed_locked(&root, &vault); + let close = WorkspaceClose::new(access.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + assert_eq!(protection_json(&close)["layout"], "locked"); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "unlock"); + let refused = consume_c1(&close, &c1_id, &c1_epoch); + assert_eq!(refused["outcome"], "closed"); + assert_unavailable(&access); + let (opens, reads, writes) = vault.counts(); + assert!(opens > 0 && reads > 0); + assert_eq!(writes, 0); + assert_eq!(vault.0.lock().unwrap().slots.get(&key), Some(&None)); +} + +#[test] +fn managed_locked_busy_orphan_and_torn_roots_remain_closed_without_key_regeneration() { + let busy_root = TestRoot::new("managed-bootstrap-busy"); + let held = rangoon_desktop::workspace_session::Owner::acquire(busy_root.0.clone()).unwrap(); + let vault = CountingVault::default(); + assert!(matches!( + SourceAccess::managed_locked(Gate::new(), busy_root.0.clone(), vault.clone()), + Err(OwnerError::Busy) + )); + assert_eq!(vault.counts(), (0, 0, 0)); + drop(held); + + for (label, seed) in [ + ("orphan", "encrypted-workspaces"), + ("torn", "encrypted-workspace.binding"), + ] { + let root = TestRoot::new(&format!("managed-bootstrap-{label}")); + let vault = CountingVault::default(); + if seed == "encrypted-workspaces" { + fs::create_dir(root.0.join(seed)).unwrap(); + } else { + fs::write(root.0.join(seed), b"torn binding").unwrap(); + } + let access = managed_locked(&root, &vault); + let close = WorkspaceClose::new(access.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + if label == "orphan" { + assert_eq!(protection_json(&close)["layout"], "recovery_required"); + } + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "create_empty"); + let result = consume_c1(&close, &c1_id, &c1_epoch); + assert_eq!(result["outcome"], "closed", "{label}"); + assert_unavailable(&access); + assert_eq!(vault.counts(), (0, 0, 0), "{label}"); + } +} + +#[test] +fn managed_locked_cancel_stale_dropped_and_failed_cleanup_never_publish_client() { + let root = TestRoot::new("managed-bootstrap-cancel"); + let vault = CountingVault::default(); + let access = managed_locked(&root, &vault); + let close = WorkspaceClose::new(access.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + let refused = serde_json::to_value(setup::prepare( + &close, + preparation(&"f".repeat(64), &c0_epoch, "create_empty"), + synthetic_cleanup_ok, + )) + .unwrap(); + assert_eq!(refused["outcome"], "refused"); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "create_empty"); + let cancelled = serde_json::to_value(setup::cancel( + &close, + cycle(&c1_id, &c1_epoch), + synthetic_cleanup_ok, + )) + .unwrap(); + assert_eq!(cancelled["outcome"], "cancelled"); + assert_unavailable(&access); + assert_eq!(vault.counts(), (0, 0, 0)); + + let root = TestRoot::new("managed-bootstrap-dropped-result"); + let vault = CountingVault::default(); + let access = managed_locked(&root, &vault); + let close = WorkspaceClose::new(access.clone()); + let (c0_id, c0_epoch) = complete_c0(&close); + let (c1_id, c1_epoch) = prepare_c1(&close, &c0_id, &c0_epoch, "create_empty"); + let dropped = serde_json::to_value(setup::confirm( + &close, + cycle(&c1_id, &c1_epoch), + synthetic_cleanup_ok, + |_| setup::Consent::Approved, + || false, + )) + .unwrap(); + assert_eq!(dropped["outcome"], "closed"); + assert_unavailable(&access); + + let root = TestRoot::new("managed-bootstrap-failed-cleanup"); + let vault = CountingVault::default(); + let access = managed_locked(&root, &vault); + let close = WorkspaceClose::new(access.clone()); + let closing = serde_json::to_value(close.begin(|_| false)).unwrap(); + let (id, epoch) = identity(&closing); + let failed = serde_json::to_value( + close.acknowledge(&acknowledgement(&id, &epoch), synthetic_cleanup_ok), + ) + .unwrap(); + assert_eq!(failed["state"], "recovery_required"); + assert_unavailable(&access); + assert_eq!(vault.counts(), (0, 0, 0)); +} diff --git a/apps/desktop/src/workspace_native_bootstrap.rs b/apps/desktop/src/workspace_native_bootstrap.rs new file mode 100644 index 0000000..f2010e2 --- /dev/null +++ b/apps/desktop/src/workspace_native_bootstrap.rs @@ -0,0 +1,190 @@ +//! Shared startup ordering. A window is not evidence of an unlocked workspace. +use crate::{Gate, SourceAccess, WorkspaceClose}; +use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder}; + +/// One deferred native startup factory. The ordinary and isolated entry points +/// must share it when startup adoption is mounted; no existing user path or key +/// is opened here, and no mutable Tauri state replacement is necessary. +#[cfg(feature = "encrypted-workspace")] +pub(super) fn startup_state( + gate: &Gate, + anchor: std::path::PathBuf, + vault: V, +) -> ( + SourceAccess, + WorkspaceClose, + crate::workspace_startup_host::Host, +) { + let roots = crate::workspace_startup::StartupRoots::new(anchor.clone()); + let source = SourceAccess::managed_deferred(gate.clone(), roots.managed(), vault); + let close = WorkspaceClose::new(source.clone()); + let host = crate::workspace_startup_host::Host::new(anchor, close.clone()); + (source, close, host) +} + +/// Shared installation for ordinary and disposable native entry points. State +/// registration is one-shot; a failure cannot replace an existing service. +#[cfg(feature = "encrypted-workspace")] +pub(super) fn install_startup_state< + V: rangoon_desktop::workspace_session::Vault + Send + 'static, +>( + app: &AppHandle, + anchor: std::path::PathBuf, + vault: V, +) -> Result<(), StartupFailure> { + let (source, close, host) = startup_state(app.state::().inner(), anchor, vault); + if !app.manage(source) || !app.manage(close) || !app.manage(host) { + return Err(StartupFailure::StateInstallation); + } + Ok(()) +} + +pub(super) fn install_workbench_state( + app: &AppHandle, + anchor: Result, +) -> Result<(), StartupFailure> { + #[cfg(feature = "encrypted-workspace")] + if let Ok(anchor) = anchor { + return install_startup_state(app, anchor, native_startup_vault(app)); + } + #[cfg(not(feature = "encrypted-workspace"))] + let _ = anchor; + + let source = SourceAccess::unavailable(app.state::().inner().clone()); + let close = WorkspaceClose::new(source.clone()); + if !app.manage(source) || !app.manage(close) { + return Err(StartupFailure::StateInstallation); + } + Ok(()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum StartupFailure { + StateInstallation, + MissingAnchor, + InitialClose, + WindowCreation, +} + +/// The caller retains the real lifetime anchor outside managed state. Only its +/// installation result enters this private ordering helper; no wire DTO can +/// supply it. Managed startup never opens a client or acknowledges renderer purge. +fn prepare_workbench( + gate: &Gate, + source: &SourceAccess, + close: &WorkspaceClose, + anchor_installed: bool, + cleanup: impl FnOnce(bool) -> bool, + present: impl FnOnce() -> Result<(), ()>, +) -> Result<(), StartupFailure> { + let result = if source.encrypted_close_available() && !anchor_installed { + Err(StartupFailure::MissingAnchor) + } else if source.encrypted_close_available() && !close.begin_initial(cleanup) { + Err(StartupFailure::InitialClose) + } else { + present().map_err(|()| StartupFailure::WindowCreation) + }; + if result.is_err() { + close.fail_startup(); + // Managed SourceAccess retains its real drain. Legacy has no encrypted + // close protocol, but a failed window must still fence its shared Gate. + // Dropping a Drain never reopens admission. + if !source.encrypted_close_available() { + let _ = gate.request_drain(); + } + } + result +} + +pub(super) fn present_workbench( + app: &AppHandle, + anchor_installed: bool, +) -> Result<(), StartupFailure> { + prepare_workbench( + app.state::().inner(), + app.state::().inner(), + app.state::().inner(), + anchor_installed, + |drained| { + #[cfg(all(test, feature = "native-encrypted-qualification"))] + if crate::native_encrypted_qualification::case_is("cleanup-failure") { + return false; + } + crate::workspace_close::native_cleanup(app, drained) + }, + || { + #[cfg(all(test, feature = "native-encrypted-qualification"))] + if crate::native_encrypted_qualification::case_is("window-failure") { + return Err(()); + } + create_main_window(app) + }, + ) +} + +fn create_main_window(app: &AppHandle) -> Result<(), ()> { + let work_area = app.primary_monitor().ok().flatten().map(|monitor| { + ( + monitor.work_area().size.width, + monitor.work_area().size.height, + monitor.scale_factor(), + ) + }); + let (width, height) = crate::initial_window_size(work_area); + WebviewWindowBuilder::new(app, "main", WebviewUrl::App("analyze.html".into())) + .title("Rangoon") + .inner_size(width, height) + .min_inner_size(320.0, 480.0) + .center() + .on_navigation(crate::bundled_navigation) + .build() + .map(|_| ()) + .map_err(|_| ()) +} + +#[cfg(test)] +#[path = "workspace_native_bootstrap_tests.rs"] +mod tests; + +/// Native-owned slot selector. Construction performs no credential-store access. +/// Credential access occurs only through a separately confirmed native action. +#[cfg(feature = "encrypted-workspace")] +pub(super) struct OsVault { + application_identifier: String, +} +#[cfg(feature = "encrypted-workspace")] +impl OsVault { + pub(super) fn new(application_identifier: String) -> Self { + Self { + application_identifier, + } + } +} +#[cfg(feature = "encrypted-workspace")] +impl rangoon_desktop::workspace_session::Vault for OsVault { + type Slot = rangoon_desktop::workspace_keys::OsSlot; + fn open( + &self, + identity: &rangoon_desktop::workspace_keys::WorkspaceId, + ) -> Result { + Self::Slot::open(&self.application_identifier, identity.clone()) + } +} + +/// Use one native selector policy for ordinary control and startup adoption. +/// The isolated target decorates that same adapter with its exact registered +/// test service; startup copy/recovery must not bypass that custody wrapper. +#[cfg(feature = "encrypted-workspace")] +pub(super) fn native_startup_vault( + app: &AppHandle, +) -> impl rangoon_desktop::workspace_session::Vault + Send + 'static + use<> { + #[cfg(all(test, feature = "native-encrypted-qualification", target_os = "macos"))] + { + let _ = app; + crate::native_encrypted_qualification::startup_vault() + } + #[cfg(not(all(test, feature = "native-encrypted-qualification", target_os = "macos")))] + { + OsVault::new(app.config().identifier.clone()) + } +} diff --git a/apps/desktop/src/workspace_native_bootstrap_tests.rs b/apps/desktop/src/workspace_native_bootstrap_tests.rs new file mode 100644 index 0000000..9ad3c9b --- /dev/null +++ b/apps/desktop/src/workspace_native_bootstrap_tests.rs @@ -0,0 +1,1289 @@ +use super::*; + +use crate::workspace_close::WorkspaceClose; +#[cfg(feature = "encrypted-workspace")] +use crate::workspace_requests::WorkspaceRequest; +use rangoon_desktop::workspace_lifecycle::Lane; +#[cfg(feature = "encrypted-workspace")] +use rangoon_desktop::{ + workspace_keys::{Error as KeyError, Store, WorkspaceId}, + workspace_session::{Owner, Vault}, +}; +#[cfg(feature = "encrypted-workspace")] +use rangoon_store::Workspace; +#[cfg(feature = "encrypted-workspace")] +use serde_json::json; +use std::{ + fs, + path::PathBuf, + sync::{Arc, Mutex}, + time::{SystemTime, UNIX_EPOCH}, +}; +#[cfg(feature = "encrypted-workspace")] +use std::{ + io::{Read, Write}, + process::{Child, Command, Stdio}, + sync::mpsc, + thread, + time::{Duration, Instant}, +}; +#[cfg(feature = "encrypted-workspace")] +use tauri::ipc::InvokeBody; +#[cfg(feature = "encrypted-workspace")] +use zeroize::Zeroizing; + +struct TestRoot(PathBuf); + +#[cfg(feature = "encrypted-workspace")] +struct ChildGuard(Child); + +#[cfg(feature = "encrypted-workspace")] +impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +impl TestRoot { + fn new(label: &str) -> Self { + let root = std::env::temp_dir().canonicalize().unwrap().join(format!( + "rangoon-native-bootstrap-{label}-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(), + )); + fs::create_dir(&root).unwrap(); + Self(root.canonicalize().unwrap()) + } +} + +impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +#[test] +fn unavailable_backend_still_closes_before_presenting_a_source_free_window() { + let gate = Gate::new(); + let source = SourceAccess::unavailable(gate.clone()); + let close = WorkspaceClose::new(source.clone()); + let calls = Arc::new(Mutex::new(Vec::new())); + let result = prepare_workbench( + &gate, + &source, + &close, + true, + { + let calls = Arc::clone(&calls); + move |_| { + calls.lock().unwrap().push("cleanup"); + true + } + }, + { + let calls = Arc::clone(&calls); + let source = source.clone(); + let gate = gate.clone(); + let close = close.clone(); + move || { + assert!(gate.begin(Lane::Read).is_err()); + assert!(serde_json::to_value(source.request_view()).unwrap()["clientId"].is_null()); + assert_eq!( + serde_json::to_value(close.inspect(|_| true)).unwrap()["state"], + "closing" + ); + calls.lock().unwrap().push("window"); + Ok(()) + } + }, + ); + assert_eq!(result, Ok(())); + assert_eq!(*calls.lock().unwrap(), vec!["cleanup", "window"]); + assert!(!source.failure_latched()); +} + +#[cfg(feature = "encrypted-workspace")] +fn view(close: &WorkspaceClose) -> serde_json::Value { + serde_json::to_value(close.inspect(|_| true)).unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn acknowledgement(view: &serde_json::Value) -> Vec { + serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-purge-ack.v1", + "attemptId": view["attemptId"].as_str().unwrap(), + "epoch": view["epoch"].as_str().unwrap(), + })) + .unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn action_request( + view: &serde_json::Value, + action: &str, +) -> crate::workspace_startup_host::ActionRequest { + crate::workspace_startup_host::ActionRequest::parse( + &serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-startup-action.v1", + "startupId": view["startupId"].as_str().unwrap(), + "attemptId": view["attemptId"].as_str().unwrap(), + "epoch": view["epoch"].as_str().unwrap(), + "action": action, + })) + .unwrap(), + ) + .unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn completed_c1(close: &WorkspaceClose) -> serde_json::Value { + let closing = view(close); + assert_eq!(closing["state"], "closing"); + serde_json::to_value(close.acknowledge(&acknowledgement(&closing), |_| true)).unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn closed_startup_cycle(close: &WorkspaceClose) { + let started = serde_json::to_value(close.begin(|_| true)).unwrap(); + assert_eq!(started["state"], "closing"); + assert_eq!(completed_c1(close)["state"], "locked"); +} + +#[cfg(feature = "encrypted-workspace")] +fn control_preparation( + view: &serde_json::Value, + action: &str, +) -> crate::workspace_close::setup::Preparation { + crate::workspace_close::setup::Preparation::parse(&InvokeBody::Raw( + serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-control-prepare.v1", + "attemptId": view["attemptId"].as_str().unwrap(), + "epoch": view["epoch"].as_str().unwrap(), + "action": action, + })) + .unwrap(), + )) + .unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn control_cycle(view: &serde_json::Value) -> crate::workspace_close::setup::Cycle { + crate::workspace_close::setup::Cycle::parse(&InvokeBody::Raw( + serde_json::to_vec(&json!({ + "schemaVersion": "rangoon.workspace-control-cycle.v1", + "attemptId": view["attemptId"].as_str().unwrap(), + "epoch": view["epoch"].as_str().unwrap(), + })) + .unwrap(), + )) + .unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn confirmed_native_setup_action(close: &WorkspaceClose, action: &str) { + let locked = view(close); + let prepared = serde_json::to_value(crate::workspace_close::setup::prepare( + close, + control_preparation(&locked, action), + |_| true, + )) + .unwrap(); + assert_eq!(prepared["outcome"], "prepared"); + let control = &prepared["close"]; + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(control), |_| true)).unwrap()["state"], + "closing" + ); + let opened = serde_json::to_value(crate::workspace_close::setup::confirm( + close, + control_cycle(control), + |_| true, + |_| crate::workspace_close::setup::Consent::Approved, + || true, + )) + .unwrap(); + assert_eq!(opened["outcome"], "opened"); + assert_eq!(opened["reload"], true); +} + +#[cfg(feature = "encrypted-workspace")] +fn confirmed_create_empty(close: &WorkspaceClose) { + confirmed_native_setup_action(close, "create_empty"); +} + +#[cfg(feature = "encrypted-workspace")] +fn confirmed_unlock(close: &WorkspaceClose) { + confirmed_native_setup_action(close, "unlock"); +} + +#[cfg(feature = "encrypted-workspace")] +fn ordinary_lock(close: &WorkspaceClose, host: &crate::workspace_startup_host::Host) { + let retired = host.retire_for_ordinary_close(); + assert!(retired.is_none()); + let closing = serde_json::to_value(close.begin(|_| true)).unwrap(); + assert_eq!(closing["state"], "closing"); + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(&closing), |_| true)).unwrap()["state"], + "locked" + ); +} + +#[cfg(feature = "encrypted-workspace")] +fn status_with_current_c1(host: &crate::workspace_startup_host::Host) -> serde_json::Value { + serde_json::to_value(host.status( + |_| true, + |current| { + let closing = view(current); + assert_eq!(closing["state"], "closing"); + let _ = current.acknowledge(&acknowledgement(&closing), |_| true); + true + }, + )) + .unwrap() +} + +#[test] +fn legacy_startup_presents_without_cleanup_or_admission_fence() { + let root = TestRoot::new("legacy-success"); + let gate = Gate::new(); + let source = SourceAccess::legacy(gate.clone(), Ok(root.0.clone())); + let close = WorkspaceClose::new(source.clone()); + let cleanup_calls = Arc::new(Mutex::new(0_usize)); + let present_calls = Arc::new(Mutex::new(0_usize)); + + assert_eq!( + prepare_workbench( + &gate, + &source, + &close, + false, + { + let cleanup_calls = Arc::clone(&cleanup_calls); + move |_| { + *cleanup_calls.lock().unwrap() += 1; + true + } + }, + { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + }, + ), + Ok(()) + ); + assert_eq!(*cleanup_calls.lock().unwrap(), 0); + assert_eq!(*present_calls.lock().unwrap(), 1); + assert!(gate.begin(Lane::Read).is_ok()); + assert!(!source.failure_latched()); +} + +#[test] +fn legacy_window_failure_fences_shared_gate_without_cleanup() { + let root = TestRoot::new("legacy-window-failure"); + let gate = Gate::new(); + let source = SourceAccess::legacy(gate.clone(), Ok(root.0.clone())); + let close = WorkspaceClose::new(source.clone()); + let cleanup_calls = Arc::new(Mutex::new(0_usize)); + + assert_eq!( + prepare_workbench( + &gate, + &source, + &close, + false, + { + let cleanup_calls = Arc::clone(&cleanup_calls); + move |_| { + *cleanup_calls.lock().unwrap() += 1; + true + } + }, + || Err(()), + ), + Err(StartupFailure::WindowCreation) + ); + assert_eq!(*cleanup_calls.lock().unwrap(), 0); + assert!(gate.begin(Lane::Read).is_err()); + assert!(!source.failure_latched()); +} + +#[cfg(feature = "encrypted-workspace")] +#[derive(Default)] +struct CountingVaultState { + slots: std::collections::BTreeMap>>, + opens: usize, + reads: usize, + writes: usize, +} + +#[cfg(feature = "encrypted-workspace")] +#[derive(Clone, Default)] +struct CountingVault(Arc>); + +#[cfg(feature = "encrypted-workspace")] +struct CountingSlot { + identity: WorkspaceId, + lookup: String, + state: Arc>, +} + +#[cfg(feature = "encrypted-workspace")] +impl CountingVault { + fn counts(&self) -> (usize, usize, usize) { + let state = self.0.lock().unwrap(); + (state.opens, state.reads, state.writes) + } +} + +#[cfg(feature = "encrypted-workspace")] +impl Vault for CountingVault { + type Slot = CountingSlot; + + fn open(&self, identity: &WorkspaceId) -> Result { + let mut state = self.0.lock().unwrap(); + state.opens += 1; + let lookup = identity.as_hex(); + state.slots.entry(lookup.clone()).or_insert(None); + Ok(CountingSlot { + identity: identity.clone(), + lookup, + state: Arc::clone(&self.0), + }) + } +} + +#[cfg(feature = "encrypted-workspace")] +impl Store for CountingSlot { + fn identity(&self) -> &WorkspaceId { + &self.identity + } + + fn read(&self) -> Result>>, KeyError> { + let mut state = self.state.lock().unwrap(); + state.reads += 1; + Ok(state + .slots + .get(&self.lookup) + .cloned() + .flatten() + .map(Zeroizing::new)) + } + + fn write(&self, envelope: &[u8]) -> Result<(), KeyError> { + let mut state = self.state.lock().unwrap(); + state.writes += 1; + state + .slots + .insert(self.lookup.clone(), Some(envelope.to_vec())); + Ok(()) + } +} + +#[cfg(feature = "encrypted-workspace")] +fn managed_locked(root: &TestRoot, gate: Gate, vault: &CountingVault) -> SourceAccess { + SourceAccess::managed_locked(gate, root.0.clone(), vault.clone()).unwrap() +} + +#[cfg(feature = "encrypted-workspace")] +fn assert_no_client(access: &SourceAccess) { + assert_eq!( + serde_json::to_value(access.request_view()).unwrap()["state"], + "unavailable" + ); + assert!(matches!( + access.request_context("main", Some(&"a".repeat(64))), + WorkspaceRequest::Refused + )); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn managed_startup_closes_before_present_and_exact_ack_locks_without_client() { + let root = TestRoot::new("managed-order"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let source = managed_locked(&root, gate.clone(), &vault); + let close = WorkspaceClose::new(source.clone()); + let events = Arc::new(Mutex::new(Vec::new())); + + assert_eq!( + prepare_workbench( + &gate, + &source, + &close, + true, + { + let events = Arc::clone(&events); + move |drained| { + events.lock().unwrap().push(format!("cleanup:{drained}")); + true + } + }, + { + let events = Arc::clone(&events); + move || { + events.lock().unwrap().push("present".into()); + Ok(()) + } + }, + ), + Ok(()) + ); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert_eq!( + &*events.lock().unwrap(), + &[String::from("cleanup:false"), String::from("present")] + ); + + let closing = view(&close); + assert_eq!(closing["state"], "closing"); + assert_no_client(&source); + let locked = + serde_json::to_value(close.acknowledge(&acknowledgement(&closing), |_| true)).unwrap(); + assert_eq!(locked["state"], "locked"); + assert_no_client(&source); + assert_eq!(vault.counts(), (0, 0, 0)); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn managed_missing_anchor_refuses_before_cleanup_or_window() { + let root = TestRoot::new("managed-anchor"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let source = managed_locked(&root, gate.clone(), &vault); + let close = WorkspaceClose::new(source.clone()); + let cleanup_calls = Arc::new(Mutex::new(0_usize)); + let present_calls = Arc::new(Mutex::new(0_usize)); + + assert_eq!( + prepare_workbench( + &gate, + &source, + &close, + false, + { + let cleanup_calls = Arc::clone(&cleanup_calls); + move |_| { + *cleanup_calls.lock().unwrap() += 1; + true + } + }, + { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + }, + ), + Err(StartupFailure::MissingAnchor) + ); + assert_eq!(*cleanup_calls.lock().unwrap(), 0); + assert_eq!(*present_calls.lock().unwrap(), 0); + assert!(source.failure_latched()); + assert_no_client(&source); + assert!(gate.begin(Lane::Read).is_err()); + assert_eq!(vault.counts(), (0, 0, 0)); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn managed_failed_cleanup_or_window_never_claims_clean_startup() { + for panic_cleanup in [false, true] { + let root = TestRoot::new(if panic_cleanup { + "managed-cleanup-panic" + } else { + "managed-cleanup-false" + }); + let gate = Gate::new(); + let vault = CountingVault::default(); + let source = managed_locked(&root, gate.clone(), &vault); + let close = WorkspaceClose::new(source.clone()); + let present_calls = Arc::new(Mutex::new(0_usize)); + + let result = if panic_cleanup { + prepare_workbench(&gate, &source, &close, true, |_| panic!("cleanup panic"), { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + }) + } else { + prepare_workbench(&gate, &source, &close, true, |_| false, { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + }) + }; + assert_eq!(result, Err(StartupFailure::InitialClose)); + assert_eq!(*present_calls.lock().unwrap(), 0); + assert!(source.failure_latched()); + assert!(!close.clean_native_completion()); + let _ = close.progress_native(|_| true); + assert!(!close.clean_native_completion()); + assert_no_client(&source); + assert!(gate.begin(Lane::Read).is_err()); + assert_eq!(vault.counts(), (0, 0, 0)); + } + + let root = TestRoot::new("managed-window-failure"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let source = managed_locked(&root, gate.clone(), &vault); + let close = WorkspaceClose::new(source.clone()); + let cleanup_calls = Arc::new(Mutex::new(0_usize)); + + assert_eq!( + prepare_workbench( + &gate, + &source, + &close, + true, + { + let cleanup_calls = Arc::clone(&cleanup_calls); + move |_| { + *cleanup_calls.lock().unwrap() += 1; + true + } + }, + || Err(()), + ), + Err(StartupFailure::WindowCreation) + ); + assert_eq!(*cleanup_calls.lock().unwrap(), 1); + assert!(source.failure_latched()); + assert!(!close.clean_native_completion()); + let _ = close.progress_native(|_| true); + assert!(!close.clean_native_completion()); + assert_no_client(&source); + assert!(gate.begin(Lane::Read).is_err()); + assert_eq!(vault.counts(), (0, 0, 0)); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn managed_duplicate_or_exit_latched_startup_refuses() { + let root = TestRoot::new("managed-duplicate"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let source = managed_locked(&root, gate.clone(), &vault); + let close = WorkspaceClose::new(source.clone()); + let present_calls = Arc::new(Mutex::new(0_usize)); + assert_eq!( + prepare_workbench(&gate, &source, &close, true, |_| true, { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + }), + Ok(()) + ); + assert_eq!( + prepare_workbench(&gate, &source, &close, true, |_| true, { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + }), + Err(StartupFailure::InitialClose) + ); + assert_eq!(*present_calls.lock().unwrap(), 1); + assert!(source.failure_latched()); + assert_no_client(&source); + assert!(gate.begin(Lane::Read).is_err()); + assert_eq!(vault.counts(), (0, 0, 0)); + + let root = TestRoot::new("managed-exit-latched"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let source = managed_locked(&root, gate.clone(), &vault); + let close = WorkspaceClose::new(source.clone()); + close.fence_admission_for_exit(); + let present_calls = Arc::new(Mutex::new(0_usize)); + assert_eq!( + prepare_workbench(&gate, &source, &close, true, |_| true, { + let present_calls = Arc::clone(&present_calls); + move || { + *present_calls.lock().unwrap() += 1; + Ok(()) + } + },), + Err(StartupFailure::InitialClose) + ); + assert_eq!(*present_calls.lock().unwrap(), 0); + assert!(source.failure_latched()); + assert_no_client(&source); + assert!(gate.begin(Lane::Read).is_err()); + assert_eq!(vault.counts(), (0, 0, 0)); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn deferred_factory_has_no_metadata_key_or_client_before_a_closed_cycle() { + let root = TestRoot::new("deferred-factory"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let managed = root.0.join("managed-workspace"); + + let (source, close, _host) = startup_state(&gate, root.0.clone(), vault.clone()); + + assert!(!managed.exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert_eq!(view(&close)["state"], "open"); + assert!(!close.clean_native_completion()); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn startup_status_requires_completed_c0_and_current_c1_without_side_effects() { + let root = TestRoot::new("startup-c0-c1"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let managed = root.0.join("managed-workspace"); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + let c0 = serde_json::to_value(close.begin(|_| true)).unwrap(); + assert_eq!(c0["state"], "closing"); + let refused = serde_json::to_value(host.status(|_| true, |_| true)).unwrap(); + assert_eq!(refused["state"], "unavailable"); + assert!(!managed.exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + + assert_eq!(completed_c1(&close)["state"], "locked"); + let fresh = status_with_current_c1(&host); + assert_eq!(fresh["state"], "fresh"); + assert_eq!(fresh["retainedOriginal"], "not_applicable"); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert_eq!(view(&close)["state"], "closing"); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn fresh_setup_binds_only_locked_owner_then_hands_off_without_key_or_client() { + let root = TestRoot::new("fresh-setup"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + let fresh = status_with_current_c1(&host); + assert_eq!(fresh["state"], "fresh"); + let handoff = + serde_json::to_value(host.action(action_request(&fresh, "setup"), &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap(); + + assert_eq!(handoff["state"], "handoff"); + assert!(handoff["startupId"].is_null()); + assert!(handoff["attemptId"].is_null()); + assert!(handoff["epoch"].is_null()); + assert_eq!(handoff["actions"], json!([])); + assert!( + root.0 + .join("managed-workspace/encrypted-workspace.lock") + .is_file() + ); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert_eq!(view(&close)["state"], "locked"); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn bound_existing_owner_rejects_wrong_selected_identity_before_vault_or_client_access() { + use crate::{workspace_source_access::ControlKind, workspace_startup::StartupRoots}; + + let root = TestRoot::new("selected-identity"); + let managed = root.0.join("managed-workspace"); + fs::create_dir(&managed).unwrap(); + let fixture_vault = CountingVault::default(); + let mut owner = Owner::acquire(managed).unwrap(); + let preview = owner.prepare_create_empty().unwrap(); + owner.confirm(&preview.id, &fixture_vault).unwrap(); + owner.lock(); + drop(owner); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, _host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + assert!(close.startup_acknowledged().is_err()); + let locked = view(&close); + let mut flight = close + .start_control_for( + locked["attemptId"].as_str().unwrap(), + locked["epoch"].as_str().unwrap(), + ControlKind::Startup, + |_| true, + ) + .unwrap(); + assert_eq!(close.startup_acknowledged(), Ok(false)); + assert_eq!(completed_c1(&close)["state"], "closing"); + assert_eq!(close.startup_acknowledged(), Ok(true)); + flight.startup_permit().unwrap(); + flight + .bind_locked_owner( + StartupRoots::new(root.0.clone()) + .existing_binding() + .unwrap(), + ) + .unwrap(); + assert!(flight.check_bound_identity(&"f".repeat(64)).is_err()); + assert!(flight.startup_permit().is_err()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert!( + close + .start_control_for( + locked["attemptId"].as_str().unwrap(), + locked["epoch"].as_str().unwrap(), + ControlKind::CreateEmpty, + |_| true, + ) + .is_err() + ); + close.fence_admission_for_exit(); + assert!(close.startup_acknowledged().is_err()); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn legacy_review_stale_copy_cancel_and_verified_adoption_keep_native_custody_across_locks() { + let root = TestRoot::new("legacy-router"); + let legacy = Workspace::new(root.0.join("source-workspace")); + legacy + .save(&rangoon_import::analyze("AGENTS.md", b"# Existing\nExact bytes\n").unwrap()) + .unwrap(); + let original = fs::read(root.0.join("source-workspace/workspace.sqlite3")).unwrap(); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + let legacy_found = status_with_current_c1(&host); + assert_eq!(legacy_found["state"], "legacy_found"); + assert_eq!(legacy_found["retainedOriginal"], "unassessed"); + let review = serde_json::to_value(host.action( + action_request(&legacy_found, "review_conversion"), + &vault, + |_| crate::workspace_close::setup::Consent::Approved, + )) + .unwrap(); + assert_eq!(review["state"], "conversion_review"); + assert_eq!(review["retainedOriginal"], "present_unencrypted"); + assert_ne!(review["startupId"], legacy_found["startupId"]); + + let stale = serde_json::to_value(host.action( + action_request(&legacy_found, "copy"), + &vault, + |_| crate::workspace_close::setup::Consent::Approved, + )) + .unwrap(); + assert_eq!(stale["state"], "conversion_review"); + assert!(!root.0.join("managed-workspace").exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + + let cancelled = + serde_json::to_value(host.action(action_request(&review, "cancel"), &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap(); + assert_eq!(cancelled["state"], "legacy_found"); + assert_ne!(cancelled["startupId"], review["startupId"]); + assert!(!root.0.join("managed-workspace").exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_eq!( + fs::read(root.0.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + + let reviewed_again = serde_json::to_value(host.action( + action_request(&cancelled, "review_conversion"), + &vault, + |_| crate::workspace_close::setup::Consent::Approved, + )) + .unwrap(); + let restarted = serde_json::to_value(host.action( + action_request(&reviewed_again, "copy"), + &vault, + |_| crate::workspace_close::setup::Consent::Approved, + )) + .unwrap(); + assert_eq!(restarted["state"], "restart_required"); + assert_eq!(restarted["retainedOriginal"], "present_unencrypted"); + assert_eq!( + fs::read(root.0.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); + assert!(root.0.join("managed-workspace").exists()); + assert!(vault.counts().0 > 0); + assert_no_client(&source); + assert_eq!(view(&close)["state"], "locked"); + + let (slots, writes) = { + let state = vault.0.lock().unwrap(); + let slots: std::collections::BTreeMap<_, _> = state + .slots + .iter() + .map(|(identity, envelope)| { + assert!(WorkspaceId::parse(identity).is_ok()); + let envelope = envelope.as_ref().expect("copy stores one fixture key"); + assert!(!envelope.is_empty()); + (identity.clone(), envelope.clone()) + }) + .collect(); + assert_eq!(slots.len(), 1); + (serde_json::to_vec(&slots).unwrap(), state.writes) + }; + assert!(slots.len() <= 4096); + drop(host); + drop(close); + drop(source); + let mut child = ChildGuard( + Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "workspace_native_bootstrap::tests::legacy_adoption_process_child", + "--ignored", + "--nocapture", + ]) + .env("RANGOON_E1C5E_TEST_ROOT", &root.0) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(), + ); + child.0.stdin.take().unwrap().write_all(&slots).unwrap(); + let started = Instant::now(); + let status = loop { + if let Some(status) = child.0.try_wait().unwrap() { + break status; + } + if started.elapsed() >= Duration::from_secs(20) { + let _ = child.0.kill(); + let _ = child.0.wait(); + panic!("legacy adoption child timeout"); + } + thread::sleep(Duration::from_millis(5)); + }; + let mut diagnostics = String::new(); + child + .0 + .stderr + .take() + .unwrap() + .take(8192) + .read_to_string(&mut diagnostics) + .unwrap(); + assert!( + status.success(), + "legacy adoption child failed: {diagnostics}" + ); + assert_eq!(vault.counts().2, writes); + assert_eq!( + fs::read(root.0.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn close_begin_cancels_ready_startup_then_retired_plan_keeps_real_drain_until_drop() { + let root = TestRoot::new("retired-plan"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + let fresh = status_with_current_c1(&host); + assert_eq!(fresh["state"], "fresh"); + let retired = host.retire_for_ordinary_close().unwrap(); + assert_eq!( + serde_json::to_value(close.begin(|_| true)).unwrap()["state"], + "closing" + ); + assert_eq!(view(&close)["state"], "closing"); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert_eq!( + serde_json::to_value(host.action(action_request(&fresh, "setup"), &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap()["state"], + "unavailable" + ); + drop(retired); + assert_eq!( + serde_json::to_value(close.inspect(|_| true)).unwrap()["state"], + "closing" + ); + assert_eq!(completed_c1(&close)["state"], "locked"); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn fenced_native_copy_cannot_create_destination_or_key_after_blocked_confirmation_returns() { + let root = TestRoot::new("blocked-native-copy"); + Workspace::new(root.0.join("source-workspace")) + .save(&rangoon_import::analyze("AGENTS.md", b"# Existing\nExact bytes\n").unwrap()) + .unwrap(); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + closed_startup_cycle(&close); + let legacy = status_with_current_c1(&host); + let review = serde_json::to_value(host.action( + action_request(&legacy, "review_conversion"), + &vault, + |_| crate::workspace_close::setup::Consent::Approved, + )) + .unwrap(); + assert_eq!(review["state"], "conversion_review"); + + let copy = action_request(&review, "copy"); + let duplicate = action_request(&review, "copy"); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let (returned_tx, returned_rx) = mpsc::channel(); + let worker_host = host.clone(); + let worker_vault = vault.clone(); + let worker = thread::spawn(move || { + let result = worker_host.action(copy, &worker_vault, move |_| { + entered_tx.send(()).unwrap(); + if release_rx.recv_timeout(Duration::from_secs(5)).is_ok() { + crate::workspace_close::setup::Consent::Approved + } else { + crate::workspace_close::setup::Consent::Unavailable + } + }); + returned_tx.send(result).unwrap(); + }); + entered_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + + close.fence_admission_for_exit(); + assert!(host.retire().is_none()); + assert_eq!( + serde_json::to_value(host.status(|_| true, |_| true)).unwrap()["state"], + "unavailable" + ); + assert_eq!( + serde_json::to_value(host.action(duplicate, &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap()["state"], + "unavailable" + ); + assert!(!close.clean_native_completion()); + assert!(!host.cleanup_consistent(true)); + assert!(matches!( + returned_rx.try_recv(), + Err(mpsc::TryRecvError::Empty) + )); + assert!(!root.0.join("managed-workspace").exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + + release_tx.send(()).unwrap(); + let result = returned_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + worker.join().unwrap(); + assert_eq!( + serde_json::to_value(result).unwrap()["state"], + "unavailable" + ); + assert!(!root.0.join("managed-workspace").exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn fatal_source_failure_retires_ready_startup_without_resumable_client() { + let root = TestRoot::new("fatal-ready-startup"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + assert_eq!(status_with_current_c1(&host)["state"], "fresh"); + source.fail_closed(); + let retired = host.retire().unwrap(); + assert!(source.failure_latched()); + assert!(!close.clean_native_completion()); + assert_no_client(&source); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_eq!( + serde_json::to_value(host.status(|_| true, |_| true)).unwrap()["state"], + "unavailable" + ); + + drop(retired); + assert!(source.failure_latched()); + assert_no_client(&source); + assert!(!close.clean_native_completion()); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn ordinary_lock_preserves_only_completed_handoff_across_confirmed_unlock_cycles() { + let root = TestRoot::new("ordinary-handoff"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + let fresh = status_with_current_c1(&host); + let handoff = + serde_json::to_value(host.action(action_request(&fresh, "setup"), &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap(); + assert_eq!(handoff["state"], "handoff"); + assert!(handoff["startupId"].is_null()); + assert!(handoff["attemptId"].is_null()); + assert!(handoff["epoch"].is_null()); + + confirmed_create_empty(&close); + assert!(serde_json::to_value(source.request_view()).unwrap()["clientId"].is_string()); + + for cycle in 0..2 { + ordinary_lock(&close, &host); + assert_no_client(&source); + let before_unlock = vault.counts(); + confirmed_unlock(&close); + assert_eq!(vault.counts().2, before_unlock.2); + assert!(serde_json::to_value(source.request_view()).unwrap()["clientId"].is_string()); + + let retained = serde_json::to_value(host.status( + |_| true, + |_| panic!("completed handoff must not create a startup cycle"), + )) + .unwrap(); + assert_eq!(retained["state"], "handoff", "cycle {cycle}"); + assert!(retained["startupId"].is_null()); + assert!(retained["attemptId"].is_null()); + assert!(retained["epoch"].is_null()); + assert_eq!(retained["actions"], json!([])); + } +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn ordinary_lock_retires_busy_copy_before_result_or_custody_can_revive() { + let root = TestRoot::new("ordinary-busy-copy"); + Workspace::new(root.0.join("source-workspace")) + .save(&rangoon_import::analyze("AGENTS.md", b"# Existing\nExact bytes\n").unwrap()) + .unwrap(); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + closed_startup_cycle(&close); + let legacy = status_with_current_c1(&host); + let review = serde_json::to_value(host.action( + action_request(&legacy, "review_conversion"), + &vault, + |_| crate::workspace_close::setup::Consent::Approved, + )) + .unwrap(); + assert_eq!(review["state"], "conversion_review"); + + let copy = action_request(&review, "copy"); + let stale = action_request(&review, "copy"); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let (returned_tx, returned_rx) = mpsc::channel(); + let worker_host = host.clone(); + let worker_vault = vault.clone(); + let worker = thread::spawn(move || { + let result = worker_host.action(copy, &worker_vault, move |_| { + entered_tx.send(()).unwrap(); + if release_rx.recv_timeout(Duration::from_secs(5)).is_ok() { + crate::workspace_close::setup::Consent::Approved + } else { + crate::workspace_close::setup::Consent::Unavailable + } + }); + returned_tx.send(result).unwrap(); + }); + entered_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + + assert!(host.retire_for_ordinary_close().is_none()); + let closing = serde_json::to_value(close.begin(|_| true)).unwrap(); + assert_eq!(closing["state"], "closing"); + assert_eq!( + serde_json::to_value(close.acknowledge(&acknowledgement(&closing), |_| true)).unwrap()["state"], + "closing" + ); + assert_eq!( + serde_json::to_value(host.action(stale, &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap()["state"], + "unavailable" + ); + assert!(!close.clean_native_completion()); + assert!(!host.cleanup_consistent(true)); + assert!(matches!( + returned_rx.try_recv(), + Err(mpsc::TryRecvError::Empty) + )); + assert!(!root.0.join("managed-workspace").exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + + release_tx.send(()).unwrap(); + let result = returned_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + worker.join().unwrap(); + assert_eq!( + serde_json::to_value(result).unwrap()["state"], + "unavailable" + ); + assert!(!root.0.join("managed-workspace").exists()); + assert_eq!(vault.counts(), (0, 0, 0)); + assert_no_client(&source); + assert!(host.cleanup_consistent(true)); +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn terminal_exit_overrides_handoff_and_repeated_ordinary_lock_cannot_revive_it() { + let root = TestRoot::new("terminal-handoff"); + let gate = Gate::new(); + let vault = CountingVault::default(); + let (source, close, host) = startup_state(&gate, root.0.clone(), vault.clone()); + + closed_startup_cycle(&close); + let fresh = status_with_current_c1(&host); + assert_eq!( + serde_json::to_value(host.action(action_request(&fresh, "setup"), &vault, |_| { + crate::workspace_close::setup::Consent::Approved + },)) + .unwrap()["state"], + "handoff" + ); + + close.fence_admission_for_exit(); + assert!(host.retire().is_none()); + for _ in 0..2 { + assert!(host.retire_for_ordinary_close().is_none()); + assert_eq!( + serde_json::to_value(host.status(|_| true, |_| true)).unwrap()["state"], + "unavailable" + ); + assert_no_client(&source); + } +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +#[ignore = "Disposable process child; only the Legacy fixture supplies its root and fake vault"] +fn legacy_adoption_process_child() { + let Some(root) = std::env::var_os("RANGOON_E1C5E_TEST_ROOT") else { + return; + }; + let root = PathBuf::from(root); + let temporary = std::env::temp_dir().canonicalize().unwrap(); + assert!(root.starts_with(&temporary)); + assert_eq!(root, root.canonicalize().unwrap()); + assert!( + root.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("rangoon-native-bootstrap-legacy-router-")) + ); + + let mut encoded_slots = Vec::new(); + std::io::stdin() + .take(4097) + .read_to_end(&mut encoded_slots) + .unwrap(); + assert!(encoded_slots.len() <= 4096); + let mut slots: std::collections::BTreeMap> = + serde_json::from_slice(&encoded_slots).unwrap(); + assert_eq!(slots.len(), 1); + let (identity, envelope) = slots.pop_first().unwrap(); + assert!(WorkspaceId::parse(&identity).is_ok()); + assert!(!envelope.is_empty()); + let vault = CountingVault::default(); + vault + .0 + .lock() + .unwrap() + .slots + .insert(identity, Some(envelope)); + + let original = fs::read(root.join("source-workspace/workspace.sqlite3")).unwrap(); + let gate = Gate::new(); + let (source, close, host) = startup_state(&gate, root.clone(), vault.clone()); + closed_startup_cycle(&close); + let verify = status_with_current_c1(&host); + assert_eq!(verify["state"], "verify_required"); + assert_eq!(verify["retainedOriginal"], "present_unencrypted"); + let handoff = + serde_json::to_value(host.action(action_request(&verify, "verify"), &vault, |_| { + crate::workspace_close::setup::Consent::Approved + })) + .unwrap(); + assert_eq!(handoff["state"], "handoff"); + assert_eq!(handoff["retainedOriginal"], "present_unencrypted"); + assert!(handoff["startupId"].is_null()); + assert!(handoff["attemptId"].is_null()); + assert!(handoff["epoch"].is_null()); + assert_no_client(&source); + let writes_after_verify = vault.counts().2; + + confirmed_unlock(&close); + let mut previous_client = serde_json::to_value(source.request_view()).unwrap()["clientId"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(vault.counts().2, writes_after_verify); + for cycle in 0..2 { + ordinary_lock(&close, &host); + assert_no_client(&source); + assert_eq!(vault.counts().2, writes_after_verify); + + confirmed_unlock(&close); + let client = serde_json::to_value(source.request_view()).unwrap()["clientId"] + .as_str() + .unwrap() + .to_owned(); + assert_ne!(client, previous_client, "cycle {cycle}"); + previous_client = client; + assert_eq!(vault.counts().2, writes_after_verify); + + let retained = serde_json::to_value(host.status( + |_| true, + |_| panic!("verified handoff must not create a startup cycle"), + )) + .unwrap(); + assert_eq!(retained["state"], "handoff", "cycle {cycle}"); + assert_eq!(retained["retainedOriginal"], "present_unencrypted"); + assert!(retained["startupId"].is_null()); + assert!(retained["attemptId"].is_null()); + assert!(retained["epoch"].is_null()); + assert_eq!(retained["actions"], json!([])); + } + assert_eq!( + fs::read(root.join("source-workspace/workspace.sqlite3")).unwrap(), + original + ); +} diff --git a/apps/desktop/src/workspace_recovery.rs b/apps/desktop/src/workspace_recovery.rs index 5e01c9c..f6aef5d 100644 --- a/apps/desktop/src/workspace_recovery.rs +++ b/apps/desktop/src/workspace_recovery.rs @@ -132,6 +132,25 @@ pub struct RecoveryPreview { pub outcome: &'static str, pub inventory: WorkflowWorkspaceData, } + +/// Native display facts about an unfinished empty initialization. There is no +/// database to authenticate and no inventory or content-access authority. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EmptyProvisioningPreview { + pub id: String, + pub workspace_id: String, + pub attempt_id: String, + pub status: &'static str, +} + +pub(super) struct RetainedEmpty { + token: String, + record: Checkpoint, + binding: Vec, + directories: Directories, + key: RetainedKey, +} pub(super) struct Retained { token: String, record: Checkpoint, @@ -380,7 +399,11 @@ impl Owner { /// Explicit trusted-host inspection only. The caller must obtain consent /// before vault access. No key creation, store mutation or unlock occurs. pub fn inspect_recovery(&mut self, vault: &impl Vault) -> Result { - if self.opened.is_some() || self.pending.is_some() || self.reconciliation.is_some() { + if self.opened.is_some() + || self.pending.is_some() + || self.reconciliation.is_some() + || self.empty_provisioning.is_some() + { return Err(Error::Busy); } self.check_control()?; @@ -524,4 +547,227 @@ impl Owner { other => other, } } + + /// Inspect only after native consent. Replacing an inspection always drops + /// its earlier key custody, including when the new inspection fails. + pub fn inspect_empty_provisioning( + &mut self, + vault: &impl Vault, + ) -> Result { + self.empty_provisioning = None; + if self.opened.is_some() || self.pending.is_some() || self.reconciliation.is_some() { + return Err(Error::Busy); + } + self.check_control()?; + let record = self.empty_provisioning_record()?; + let binding_bytes = self.read_binding()?; + let binding = Binding::decode(&binding_bytes)?; + let directories = self.directories(&binding)?; + self.check_empty_provisioning(&record, &binding_bytes, &directories)?; + let slot = self.slot(vault, &binding.identity)?; + let key = workspace_keys::read_key(&slot).map_err(Error::Key)?; + self.check_empty_provisioning(&record, &binding_bytes, &directories)?; + let token = WorkspaceId::generate() + .map_err(|_| Error::Unavailable)? + .as_hex(); + if token == record.record.workspace || token == record.record.attempt { + return Err(Error::Unavailable); + } + let preview = EmptyProvisioningPreview { + id: token.clone(), + workspace_id: record.record.workspace.clone(), + attempt_id: record.record.attempt.clone(), + status: "uninitialized", + }; + self.empty_provisioning = Some(RetainedEmpty { + token, + record, + binding: binding_bytes, + directories, + key, + }); + Ok(preview) + } + + fn empty_provisioning_record(&self) -> Result { + let checkpoint = self.read_operation()?.ok_or(Error::RecoveryRequired)?; + if checkpoint.damaged + || checkpoint.slots[1].is_some() + || checkpoint.record.phase != Phase::Pending + || checkpoint.record.operation != Operation::CreateEmpty + || checkpoint.record.sequence != 1 + { + return Err(Error::RecoveryRequired); + } + Ok(checkpoint) + } + + fn check_empty_provisioning( + &self, + record: &Checkpoint, + binding_bytes: &[u8], + directories: &Directories, + ) -> Result<(), Error> { + self.check_control()?; + let binding = Binding::decode(binding_bytes)?; + if binding.ready + || binding.identity.as_hex() != record.record.workspace + || self.empty_provisioning_record()? != *record + || self.read_binding()? != binding_bytes + { + return Err(Error::Stale); + } + self.unchanged_directories(&binding, directories)?; + exact_children(&self.root, &[CONTROL, BINDING, PARENT, FILES[0]])?; + exact_children(&self.root.join(PARENT), &[&binding.identity.as_hex()])?; + exact_children(&self.directory(&binding), &[])?; + self.unchanged_directories(&binding, directories)?; + self.check_control() + } + + /// Consume one native-confirmed InitializeEmpty plan. Never create a key, + /// repeat a completed initialization, restore content or unlock the client. + pub fn finish_empty_provisioning( + &mut self, + token: &str, + vault: &impl Vault, + ) -> Result<(), Error> { + if !self + .empty_provisioning + .as_ref() + .is_some_and(|plan| plan.token == token) + { + return Err(Error::Stale); + } + let retained = self.empty_provisioning.take().ok_or(Error::Stale)?; + let mut attempted = false; + let result = (|| { + self.check_empty_provisioning( + &retained.record, + &retained.binding, + &retained.directories, + )?; + let mut binding = Binding::decode(&retained.binding)?; + let slot = self.slot(vault, &binding.identity)?; + let workspace = + workspace_keys::verified_workspace(&slot, &retained.key, self.directory(&binding)) + .map_err(Error::Key)?; + self.check_empty_provisioning( + &retained.record, + &retained.binding, + &retained.directories, + )?; + attempted = true; + // This store entry point exclusively creates the missing file and + // refuses an existing destination, including partial/empty files. + workspace + .initialize_empty_encrypted() + .map_err(|_| Error::WriteUncertain)?; + let previous = self.database(&binding)?; + let inventory = workspace.workflow_data().map_err(|_| Error::StoreInvalid)?; + if !inventory.sources.is_empty() + || !inventory.capabilities.is_empty() + || !inventory.workflows.is_empty() + { + return Err(Error::StoreInvalid); + } + self.unchanged_database(&binding, &previous)?; + self.unchanged_directories(&binding, &retained.directories)?; + exact_children(&self.directory(&binding), &[DATABASE])?; + let _verified = + workspace_keys::verified_workspace(&slot, &retained.key, self.directory(&binding)) + .map_err(Error::Key)?; + self.check_control()?; + self.unchanged_database(&binding, &previous)?; + self.unchanged_directories(&binding, &retained.directories)?; + exact_children(&self.directory(&binding), &[DATABASE])?; + if self.read_binding()? != retained.binding + || self.read_operation()?.as_ref() != Some(&retained.record) + { + return Err(Error::Stale); + } + sync_directory(&self.directory(&binding))?; + self.finish_provisioning_binding( + &mut binding, + &retained.binding, + &retained.directories, + )?; + exact_children(&self.directory(&binding), &[DATABASE])?; + if self.read_operation()?.as_ref() != Some(&retained.record) { + return Err(Error::Stale); + } + let opened = Opened { + binding, + retained: retained.key, + workspace, + directories: retained.directories, + }; + self.observe_operation(&opened) + })(); + self.lock(); + self.recovery = result.is_err(); + match result { + Err(_) if attempted => Err(Error::WriteUncertain), + other => other, + } + } + + fn finish_provisioning_binding( + &self, + binding: &mut Binding, + expected: &[u8], + directories: &Directories, + ) -> Result<(), Error> { + self.check_control()?; + self.unchanged_directories(binding, directories)?; + let path = self.root.join(BINDING); + let mut file = options() + .read(true) + .write(true) + .open(&path) + .map_err(|_| Error::WriteUncertain)?; + verify_file(&file, &path)?; + if self.read_binding()? != expected { + return Err(Error::Stale); + } + exact_children(&self.directory(binding), &[DATABASE])?; + #[cfg(all(test, feature = "encrypted-workspace"))] + self.fail_at(Fault::BeforeReconcileReadyWrite)?; + binding.ready = true; + file.seek(SeekFrom::Start(0)) + .map_err(|_| Error::WriteUncertain)?; + file.write_all(&binding.bytes()) + .map_err(|_| Error::WriteUncertain)?; + #[cfg(all(test, feature = "encrypted-workspace"))] + self.fail_at(Fault::BeforeReconcileReadySync)?; + file.sync_all().map_err(|_| Error::WriteUncertain)?; + sync_directory(&self.root)?; + verify_file(&file, &path)?; + #[cfg(all(test, feature = "encrypted-workspace"))] + self.fail_at(Fault::BeforeReconcileReadyReadback)?; + if self.read_binding()? != binding.bytes() { + return Err(Error::WriteUncertain); + } + exact_children(&self.directory(binding), &[DATABASE])?; + self.unchanged_directories(binding, directories) + } +} + +fn exact_children(path: &Path, names: &[&str]) -> Result<(), Error> { + let mut actual = fs::read_dir(path) + .map_err(|_| Error::RecoveryRequired)? + .take(names.len() + 1) + .map(|entry| entry.map(|entry| entry.file_name())) + .collect::, _>>() + .map_err(|_| Error::RecoveryRequired)?; + let mut expected = names + .iter() + .map(|name| std::ffi::OsString::from(*name)) + .collect::>(); + actual.sort(); + expected.sort(); + if actual != expected { + return Err(Error::RecoveryRequired); + } + Ok(()) } diff --git a/apps/desktop/src/workspace_recovery_file_tests.rs b/apps/desktop/src/workspace_recovery_file_tests.rs new file mode 100644 index 0000000..13c754c --- /dev/null +++ b/apps/desktop/src/workspace_recovery_file_tests.rs @@ -0,0 +1,510 @@ +use super::*; +#[cfg(all(unix, feature = "encrypted-workspace"))] +use crate::encrypted_recovery as recovery; + +fn code(result: DataResult) -> &'static str { + match result { + DataResult::Failed { error } => error.code, + _ => panic!("expected failure"), + } +} +#[test] +fn unsupported_backend_refuses_before_every_picker_or_file_callback() { + let root = TestRoot::new("recovery-unsupported"); + let access = SourceAccess::legacy(Gate::new(), Ok(root.0.clone())); + assert_eq!( + code( + access + .begin_file() + .unwrap() + .create_recovery_key(|| panic!("no picker")) + .deliver() + ), + "encrypted_recovery_unavailable" + ); + assert_eq!( + code( + access + .begin_file() + .unwrap() + .export_encrypted_backup( + || panic!("no key"), + || panic!("no output"), + |_, _| panic!("no write"), + |_| panic!("no read") + ) + .deliver() + ), + "encrypted_recovery_unavailable" + ); + assert_eq!( + code( + access + .begin_file() + .unwrap() + .prepare_encrypted_restore( + || panic!("no backup"), + || panic!("no key"), + |_| panic!("no read") + ) + .deliver() + ), + "encrypted_recovery_unavailable" + ); + let result = + serde_json::to_value(tauri::async_runtime::block_on(access.workflow_data())).unwrap(); + assert_eq!(result["encryptedRecoverySupported"], false); +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +mod managed { + use super::*; + #[test] + #[cfg(all(target_os = "macos", feature = "native-encrypted-qualification"))] + fn qualification_reader_uses_existing_registered_request_not_host_fixture_bypass() { + let root = TestRoot::new("recovery-reader-binding"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let unbound = access.for_request(&crate::workspace_requests::WorkspaceRequest::Refused); + assert_eq!( + unbound.qualification_recovery_snapshot().unwrap_err().code, + "workspace_unavailable" + ); + let initial = access.0.gate.request_drain().unwrap(); + access.0.clients.resume(&access.0.gate, &initial).unwrap(); + let expected = snapshot(&access); + let backup = Backup::decode(&expected).unwrap(); + let (id, length) = unbound.qualification_recovery_snapshot().unwrap(); + assert_eq!(id, backup.id()); + assert_eq!(length, expected.len()); + access.0.clients.revoke().unwrap(); + let opens = vault.0.lock().unwrap().opens; + assert_eq!( + unbound.qualification_recovery_snapshot().unwrap_err().code, + "workspace_unavailable" + ); + assert_eq!(vault.0.lock().unwrap().opens, opens); + } + #[test] + fn source_capture_revoked_before_encode_creates_no_cipher_or_output() { + let root = TestRoot::new("recovery-capture-drain"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let key = root.0.join("key.rangoon-key"); + recovery::create_key(&key).unwrap(); + let output = root.0.join("copy.rangoon-encrypted"); + let gate = access.0.gate.clone(); + let holder = Arc::new(Mutex::new(None)); + let observed = Arc::clone(&holder); + RECOVERY_CAPTURE_CHECKPOINT.with(|slot| { + *slot.borrow_mut() = Some(Box::new(move || { + *observed.lock().unwrap() = Some(gate.request_drain().unwrap()); + })) + }); + let before = recovery::encode_calls(); + let result = access + .begin_file() + .unwrap() + .export_encrypted_backup( + || Ok(Some(key)), + || Ok(Some(output.clone())), + |_, _| panic!("revoked capture must not write"), + |_| panic!("revoked capture must not read"), + ) + .deliver(); + assert_eq!(code(result), "workspace_unavailable"); + assert_eq!(recovery::encode_calls(), before); + assert!(!output.exists()); + assert!( + holder + .lock() + .unwrap() + .as_ref() + .unwrap() + .is_quiescent() + .unwrap() + ); + } + #[test] + #[cfg(all(target_os = "macos", feature = "native-encrypted-qualification"))] + fn qualification_snapshot_refuses_capture_revoked_before_decode_or_emit() { + let root = TestRoot::new("recovery-snapshot-drain"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let initial = access.0.gate.request_drain().unwrap(); + access.0.clients.resume(&access.0.gate, &initial).unwrap(); + let gate = access.0.gate.clone(); + let holder = Arc::new(Mutex::new(None)); + let observed = Arc::clone(&holder); + RECOVERY_CHECKPOINT.with(|cell| { + *cell.borrow_mut() = Some(Box::new(move || { + *observed.lock().unwrap() = Some(gate.request_drain().unwrap()); + })) + }); + let error = access.qualification_recovery_snapshot().unwrap_err(); + assert_eq!(error.code, "workspace_unavailable"); + assert!( + holder + .lock() + .unwrap() + .as_ref() + .unwrap() + .is_quiescent() + .unwrap() + ); + assert!(!access.0.backup.retained_for_close_test()); + } + #[test] + fn source_drift_before_write_has_no_output_and_post_write_drift_is_uncertain() { + for after_write in [false, true] { + let root = TestRoot::new("recovery-source-drift"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let key = root.0.join("key.rangoon-key"); + recovery::create_key(&key).unwrap(); + let path = root.0.join("backup.rangoon-encrypted"); + let changed = access.clone(); + let mutate = move || { + changed + .0 + .backend + .lock() + .unwrap() + .save(&report("changed.md", b"# External drift\nChanged source\n")) + .unwrap_or_else(|_| panic!("synthetic mutation failed")); + }; + let mut mutate = Some(mutate); + if !after_write { + RECOVERY_CHECKPOINT + .with(|cell| *cell.borrow_mut() = Some(Box::new(mutate.take().unwrap()))); + } + let result = access + .begin_file() + .unwrap() + .export_encrypted_backup( + || Ok(Some(key)), + || Ok(Some(path.clone())), + |path, bytes| { + recovery::write_cipher(path, bytes)?; + if let Some(change) = mutate.take() { + change(); + } + Ok(()) + }, + recovery::read_cipher, + ) + .deliver(); + assert_eq!( + code(result), + if after_write { + "workspace_recovery_output_uncertain" + } else { + "workspace_recovery_source_changed" + } + ); + assert_eq!(path.exists(), after_write); + assert!(!access.0.backup.retained_for_close_test()); + assert!(!access.failure_latched()); + } + } + #[test] + fn partial_write_failure_is_uncertain_and_key_close_discloses_secret_file() { + let root = TestRoot::new("recovery-partial-write"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let key = root.0.join("key.rangoon-key"); + let completed = access + .begin_file() + .unwrap() + .create_recovery_key(|| Ok(Some(key.clone()))); + let drain = access.0.gate.request_drain().unwrap(); + assert!(!drain.is_quiescent().unwrap()); + let result = serde_json::to_value(completed.deliver()).unwrap(); + assert_eq!(result["error"]["code"], "workspace_recovery_key_created"); + assert!( + result["error"]["message"] + .as_str() + .unwrap() + .contains("secret recovery key file") + ); + assert!(key.exists()); + assert!(drain.is_quiescent().unwrap()); + access.0.gate.resume(&drain).unwrap(); + let path = root.0.join("partial.rangoon-encrypted"); + let result = access + .begin_file() + .unwrap() + .export_encrypted_backup( + || Ok(Some(key)), + || Ok(Some(path.clone())), + |path, bytes| { + std::fs::write(path, &bytes[..100]).unwrap(); + Err(PublicError { + code: "fixture_io", + message: "Synthetic partial write", + }) + }, + |_| panic!("failed write must not read"), + ) + .deliver(); + assert_eq!(code(result), "workspace_recovery_output_uncertain"); + assert_eq!(fs::metadata(path).unwrap().len(), 100); + assert!(!access.0.backup.retained_for_close_test()); + assert!(!access.failure_latched()); + } + #[test] + fn close_during_selected_output_read_refuses_before_decryption_and_drains() { + let root = TestRoot::new("recovery-reread-drain"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let key = root.0.join("key.rangoon-key"); + recovery::create_key(&key).unwrap(); + let path = root.0.join("copy.rangoon-encrypted"); + let gate = access.0.gate.clone(); + let mut drain = None; + let before = recovery::decode_calls(); + let completed = access.begin_file().unwrap().export_encrypted_backup( + || Ok(Some(key)), + || Ok(Some(path.clone())), + recovery::write_cipher, + |path| { + let bytes = recovery::read_cipher(path)?; + drain = Some(gate.request_drain().unwrap()); + Ok(bytes) + }, + ); + assert_eq!(recovery::decode_calls(), before); + let drain = drain.unwrap(); + assert!(!drain.is_quiescent().unwrap()); + assert_eq!( + code(completed.deliver()), + "workspace_recovery_output_uncertain" + ); + assert!(drain.is_quiescent().unwrap()); + assert!(path.exists()); + } + fn export(access: &SourceAccess, key: &Path, path: &Path) -> DataResult { + access + .begin_file() + .unwrap() + .export_encrypted_backup( + || Ok(Some(key.into())), + || Ok(Some(path.into())), + recovery::write_cipher, + recovery::read_cipher, + ) + .deliver() + } + fn prepare(access: &SourceAccess, key: &Path, path: &Path) -> DataResult { + access + .begin_file() + .unwrap() + .prepare_encrypted_restore( + || Ok(Some(path.into())), + || Ok(Some(key.into())), + recovery::read_cipher, + ) + .deliver() + } + fn snapshot(access: &SourceAccess) -> zeroize::Zeroizing> { + let operation = access.begin_file().unwrap(); + zeroize::Zeroizing::new( + operation + .0 + .call(|backend| backend.capture_recovery_snapshot()) + .unwrap_or_else(|_| panic!("synthetic snapshot failed")), + ) + } + #[test] + fn native_managed_backup_recovers_full_records_into_fresh_owner_and_survives_reopen() { + use rangoon_desktop::workspace_session::Owner; + let root = TestRoot::new("recovery-routed-source"); + let vault = ThreadVault::default(); + let (access, identity) = encrypted_access(&root, &vault); + let source = report( + "AGENTS.md", + b"# Rules\nSynthetic routed recovery\n# Tests\nKeep exact history\n", + ); + select(&access, &source); + assert!(matches!( + tauri::async_runtime::block_on(access.save_analysis(source.source.id.clone())), + WorkspaceResult::Saved { .. } + )); + // Add full capability/composition/workflow records via the existing native Owner. + let op = access.begin_file().unwrap(); + op.0.call(|backend| { + let first=backend.create_capability(&source.source.id,&source.fragments[0].id,"Recovery skill")?.capability; + let revised=backend.revise_capability(&first.id,&first.latest_revision_id,"Retained revision","Synthetic retained revision")?.capability; + backend.review_capability(&revised.id,&revised.latest_revision_id)?; + use rangoon_workflow::records::{SaveIntent,prepare_revision,workflow_id_from_nonce}; + let mut parent=None; + for title in ["Recovery workflow","Retained workflow"]{ + let def=serde_json::to_vec(&serde_json::json!({"schemaVersion":"rangoon.workflow-definition.v1","title":title,"nodes":[],"controlEdges":[],"dataEdges":[]})).unwrap(); + let revision=prepare_revision(&workflow_id_from_nonce(&[111;32]),parent.as_deref(),SaveIntent::Draft,&def,br#"{"positions":[]}"#).unwrap(); + let plan=backend.inspect_workflow_save(&revision)?; backend.save_workflow(&revision,&plan.expected_state_id)?;parent=Some(revision.id().to_owned()); + } + Ok(()) + }).unwrap_or_else(|_| panic!("synthetic authoring failed")); + drop(op); + let expected = snapshot(&access); + let db = root + .0 + .join("encrypted-workspaces") + .join(&identity) + .join("workspace.sqlite3"); + let source_cipher = fs::read(&db).unwrap(); + let key = root.0.join("independent.rangoon-key"); + assert!(matches!( + access + .begin_file() + .unwrap() + .create_recovery_key(|| Ok(Some(key.clone()))) + .deliver(), + DataResult::RecoveryKeyCreated + )); + let path = root.0.join("portable.rangoon-encrypted"); + let receipt = serde_json::to_value(export(&access, &key, &path)).unwrap(); + assert_eq!(receipt["outcome"], "encrypted_exported"); + assert_eq!(receipt["format"], recovery::FORMAT); + assert_eq!(receipt.as_object().unwrap().len(), 4); + assert_eq!(fs::read(&db).unwrap(), source_cipher); + // Original database key is gone; only independently selected recovery key remains. + drop(access); + vault.0.lock().unwrap().slots.clear(); + let target_root = TestRoot::new("recovery-fresh-target"); + let target_vault = ThreadVault::default(); + let (target, target_identity) = encrypted_access(&target_root, &target_vault); + assert_ne!(identity, target_identity); + let target_db = target_root + .0 + .join("encrypted-workspaces") + .join(&target_identity) + .join("workspace.sqlite3"); + let before = fs::read(&target_db).unwrap(); + let plan = match prepare(&target, &key, &path) { + DataResult::RestoreReady { plan } => plan, + _ => panic!("expected preview"), + }; + assert_eq!(fs::read(&target_db).unwrap(), before); + assert!(matches!( + tauri::async_runtime::block_on(target.restore_workspace_backup( + plan.backup_id().into(), + plan.expected_state_id().into() + )), + DataResult::Restored { .. } + )); + assert_eq!(*snapshot(&target), *expected); + assert_ne!(fs::read(&target_db).unwrap(), source_cipher); + assert_eq!( + code(tauri::async_runtime::block_on( + target.restore_workspace_backup( + plan.backup_id().into(), + plan.expected_state_id().into() + ) + )), + "backup_invalid" + ); + drop(target); + let mut owner = Owner::acquire(target_root.0.clone()).unwrap(); + let preview = owner.prepare_unlock().unwrap(); + owner.confirm(&preview.id, &target_vault).unwrap(); + assert_eq!( + owner.export_workflow_backup(&target_vault).unwrap(), + *expected + ); + } + + #[test] + fn bad_key_tamper_cancel_and_collision_leave_healthy_target_unchanged() { + let root = TestRoot::new("recovery-input-errors"); + let vault = ThreadVault::default(); + let (access, identity) = encrypted_access(&root, &vault); + let key = root.0.join("key.rangoon-key"); + recovery::create_key(&key).unwrap(); + let wrong = root.0.join("wrong.rangoon-key"); + recovery::create_key(&wrong).unwrap(); + let path = root.0.join("backup.rangoon-encrypted"); + assert!(matches!( + export(&access, &key, &path), + DataResult::EncryptedExported { .. } + )); + let db = root + .0 + .join("encrypted-workspaces") + .join(identity) + .join("workspace.sqlite3"); + let before = fs::read(&db).unwrap(); + assert_eq!( + code(prepare(&access, &wrong, &path)), + "workspace_recovery_invalid" + ); + assert!(!access.failure_latched()); + let cipher = fs::read(&path).unwrap(); + let mut altered = cipher.clone(); + altered[100] ^= 1; + fs::write(&path, altered).unwrap(); + assert_eq!( + code(prepare(&access, &key, &path)), + "workspace_recovery_invalid" + ); + assert!(!access.failure_latched()); + fs::write(&path, &cipher).unwrap(); + assert_eq!( + code(export(&access, &key, &path)), + "workspace_recovery_output_uncertain" + ); + assert_eq!(fs::read(&path).unwrap(), cipher); + assert!(matches!( + access + .begin_file() + .unwrap() + .prepare_encrypted_restore(|| Ok(None), || panic!("no key"), |_| panic!("no read")) + .deliver(), + DataResult::Cancelled + )); + assert!(matches!( + access + .begin_file() + .unwrap() + .export_encrypted_backup( + || Ok(None), + || panic!("no output"), + |_, _| panic!("no write"), + |_| panic!("no read") + ) + .deliver(), + DataResult::Cancelled + )); + assert_eq!(fs::read(db).unwrap(), before); + } + + #[test] + fn close_during_real_file_write_retains_lease_until_failure_and_never_reports_cancel() { + let root = TestRoot::new("recovery-drain"); + let vault = ThreadVault::default(); + let (access, _) = encrypted_access(&root, &vault); + let key = root.0.join("key.rangoon-key"); + recovery::create_key(&key).unwrap(); + let path = root.0.join("copy.rangoon-encrypted"); + let gate = access.0.gate.clone(); + let mut drain = None; + let completed = access.begin_file().unwrap().export_encrypted_backup( + || Ok(Some(key)), + || Ok(Some(path.clone())), + |path, bytes| { + recovery::write_cipher(path, bytes)?; + drain = Some(gate.request_drain().unwrap()); + Ok(()) + }, + recovery::read_cipher, + ); + assert!(path.exists()); + let drain = drain.unwrap(); + assert!(!drain.is_quiescent().unwrap()); + assert_eq!( + code(completed.deliver()), + "workspace_recovery_output_uncertain" + ); + assert!(drain.is_quiescent().unwrap()); + } +} diff --git a/apps/desktop/src/workspace_reopen.rs b/apps/desktop/src/workspace_reopen.rs index 0f06f14..46d7091 100644 --- a/apps/desktop/src/workspace_reopen.rs +++ b/apps/desktop/src/workspace_reopen.rs @@ -9,6 +9,8 @@ pub(crate) enum Kind { CreateEmpty, Unlock, Recovery, + #[cfg(feature = "encrypted-workspace")] + Startup, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ControlError { @@ -131,6 +133,51 @@ impl CloseTicket { } } impl Control { + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn check_bound_identity(&mut self, expected: &str) -> Result<(), ControlError> { + if self.kind != Kind::Startup || self.phase != Phase::New { + return Err(ControlError::Invalid); + } + let result = self.run(|backend| backend.control_check_identity(expected)); + if result.is_err() { + self.mark_cleanup_failed(); + self.fail(); + } + result + } + /// Startup work keeps the real closed-operation lease. Request identities + /// cannot replace this check or publish an ordinary content client. + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn startup_checkpoint(&self) -> Result<(), ControlError> { + if self.kind != Kind::Startup || self.phase != Phase::New { + return Err(ControlError::Invalid); + } + if !self.current() { + return Err(ControlError::Stale); + } + Ok(()) + } + /// Bind once under actual closed-operation custody. This proof is created + /// only by the native fixed-root inspector, never by IPC or a UI action. + #[cfg(feature = "encrypted-workspace")] + pub(crate) fn bind_locked_owner( + &mut self, + proof: crate::workspace_startup::BindingProof, + ) -> Result<(), ControlError> { + if self.phase != Phase::New || !self.current() || proof.check_before().is_err() { + self.mark_cleanup_failed(); + self.fail(); + return Err(ControlError::Invalid); + } + let root = proof.root(); + let result = self.run(|backend| backend.control_bind_owner(&root, proof.existing())); + if result.is_err() || proof.check_after().is_err() { + self.mark_cleanup_failed(); + self.fail(); + return Err(ControlError::Unavailable); + } + Ok(()) + } fn current(&self) -> bool { self.lease .as_ref() @@ -210,7 +257,7 @@ impl Control { } } pub(crate) fn prepare(&mut self) -> Result { - if self.phase != Phase::New || self.kind == Kind::Recovery { + if self.phase != Phase::New || !matches!(self.kind, Kind::CreateEmpty | Kind::Unlock) { self.fail(); return Err(ControlError::Invalid); } @@ -220,7 +267,7 @@ impl Control { Ok(value) } pub(crate) fn confirm(&mut self, id: &str) -> Result<(), ControlError> { - if self.phase != Phase::Prepared || self.kind == Kind::Recovery { + if self.phase != Phase::Prepared || !matches!(self.kind, Kind::CreateEmpty | Kind::Unlock) { self.fail(); return Err(ControlError::Invalid); } @@ -261,7 +308,10 @@ impl Control { }) } fn resume_inner(mut self, after_resume: impl FnOnce()) -> Result<(), ControlError> { - if self.kind == Kind::Recovery || self.phase != Phase::Confirmed || !self.current() { + if !matches!(self.kind, Kind::CreateEmpty | Kind::Unlock) + || self.phase != Phase::Confirmed + || !self.current() + { return Err(ControlError::Invalid); } let (mut slot, healthy) = self diff --git a/apps/desktop/src/workspace_session.rs b/apps/desktop/src/workspace_session.rs index 3350120..b6d1b9c 100644 --- a/apps/desktop/src/workspace_session.rs +++ b/apps/desktop/src/workspace_session.rs @@ -6,10 +6,10 @@ use rangoon_compose::application::Request as CompositionRequest; use rangoon_domain::AnalysisReport; use rangoon_domain::capability_v1::{CapabilityDetail, CapabilitySummary}; use rangoon_store::{ - CapabilityReceiptV1, CompositionPreview, CompositionReceipt, SaveReceipt, SnapshotMetadata, - WorkflowDeletionPlan, WorkflowDetail, WorkflowRecordKind, WorkflowRestorePlan, - WorkflowSavePlan, WorkflowSaveReceipt, WorkflowSummary, WorkflowWorkspaceData, Workspace, - WorkspaceBackup, WorkspaceCompilation, + CapabilityReceiptV1, CompositionPreview, CompositionReceipt, EmptyWorkflowRestorePlan, + SaveReceipt, SnapshotMetadata, WorkflowDeletionPlan, WorkflowDetail, WorkflowRecordKind, + WorkflowRestorePlan, WorkflowSavePlan, WorkflowSaveReceipt, WorkflowSummary, + WorkflowWorkspaceData, Workspace, WorkspaceBackup, WorkspaceCompilation, }; use rangoon_workflow::records::WorkflowRevision; use serde::Serialize; @@ -21,7 +21,7 @@ use std::{ #[path = "workspace_recovery.rs"] mod recovery; -pub use recovery::{Operation as RecoveryOperation, RecoveryPreview}; +pub use recovery::{EmptyProvisioningPreview, Operation as RecoveryOperation, RecoveryPreview}; #[path = "workspace_protection.rs"] mod protection; @@ -186,6 +186,7 @@ pub struct Owner { opened: Option, recovery: bool, reconciliation: Option, + empty_provisioning: Option, #[cfg(all(test, feature = "encrypted-workspace"))] fault: Option, } @@ -220,21 +221,37 @@ enum DataMutation { } impl Owner { - /// Explicit native acquisition; default builds do not touch the filesystem. + /// Explicit native acquisition. This opens no credential slot or database. pub fn acquire(host_root: PathBuf) -> Result { + Self::acquire_inner(host_root, true) + } + + /// Acquire only an existing control file. A disappeared control is never + /// repaired, even when the caller previously observed a valid workspace. + pub fn acquire_existing(host_root: PathBuf) -> Result { + Self::acquire_inner(host_root, false) + } + + fn acquire_inner(host_root: PathBuf, create_control: bool) -> Result { workspace_keys::ensure_backend().map_err(|_| Error::BackendUnavailable)?; let root_metadata = plain_directory(&host_root)?; let path = host_root.join(CONTROL); let mut options = options(); - options.read(true).write(true).create_new(true); - let control = match options.open(&path) { - Ok(file) => file, - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - regular(&fs::symlink_metadata(&path).map_err(|_| Error::Unavailable)?)?; - options.create_new(false); - options.open(&path).map_err(|_| Error::Unavailable)? + options.read(true).write(true); + let control = if !create_control { + regular(&fs::symlink_metadata(&path).map_err(|_| Error::Unavailable)?)?; + options.open(&path).map_err(|_| Error::Unavailable)? + } else { + options.create_new(true); + match options.open(&path) { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + regular(&fs::symlink_metadata(&path).map_err(|_| Error::Unavailable)?)?; + options.create_new(false); + options.open(&path).map_err(|_| Error::Unavailable)? + } + Err(_) => return Err(Error::Unavailable), } - Err(_) => return Err(Error::Unavailable), }; verify_file(&control, &path)?; if control.metadata().map_err(|_| Error::Unavailable)?.len() != 0 { @@ -255,6 +272,7 @@ impl Owner { opened: None, recovery: false, reconciliation: None, + empty_provisioning: None, #[cfg(all(test, feature = "encrypted-workspace"))] fault: None, }; @@ -283,7 +301,11 @@ impl Owner { if self.recovery { return Err(Error::RecoveryRequired); } - if self.opened.is_some() || self.pending.is_some() || self.reconciliation.is_some() { + if self.opened.is_some() + || self.pending.is_some() + || self.reconciliation.is_some() + || self.empty_provisioning.is_some() + { return Err(Error::Busy); } self.check_control() @@ -909,6 +931,41 @@ impl Owner { self.finish_data_mutation(result, previous, DataMutation::Restore) } + /// Trusted host-only preparation for a separately created empty destination. + pub fn prepare_adoption_restore( + &mut self, + vault: &impl Vault, + backup: &WorkspaceBackup, + source_schema: u32, + ) -> Result { + let previous = self.checked(vault)?; + let result = self + .opened + .as_ref() + .ok_or(Error::Locked)? + .workspace + .prepare_empty_workflow_restore(backup, source_schema); + self.finish_read(result, previous) + } + + /// Uses existing Restore durable intent/uncertainty handling; no new operation code. + pub fn restore_adoption( + &mut self, + vault: &impl Vault, + backup: &WorkspaceBackup, + prepared: &EmptyWorkflowRestorePlan, + ) -> Result { + let previous = self.checked(vault)?; + self.begin_mutation(RecoveryOperation::Restore)?; + let result = self + .opened + .as_ref() + .ok_or(Error::Locked)? + .workspace + .restore_empty_workflow_backup(backup, prepared); + self.finish_data_mutation(result, previous, DataMutation::Restore) + } + /// Returns an exact dependency-aware logical deletion plan, not authority. pub fn inspect_workflow_deletion( &mut self, @@ -1175,6 +1232,7 @@ impl Owner { self.advance_composition_generation(); self.pending = None; self.reconciliation = None; + self.empty_provisioning = None; self.opened = None; } fn advance_composition_generation(&mut self) { @@ -1333,3 +1391,15 @@ fn sync_directory(path: &Path) -> Result<(), Error> { #[cfg(test)] #[path = "workspace_session_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "workspace_adoption_owner_tests.rs"] +mod adoption_tests; + +#[cfg(all(test, feature = "encrypted-workspace"))] +#[path = "workspace_startup_owner_tests.rs"] +mod startup_owner_tests; + +#[cfg(all(test, feature = "encrypted-workspace"))] +#[path = "workspace_empty_provisioning_tests.rs"] +mod empty_provisioning_tests; diff --git a/apps/desktop/src/workspace_setup.rs b/apps/desktop/src/workspace_setup.rs index 2d0cc81..2581225 100644 --- a/apps/desktop/src/workspace_setup.rs +++ b/apps/desktop/src/workspace_setup.rs @@ -1,6 +1,6 @@ //! Main-window setup/unlock protocol. No plaintext conversion or factory mount. //! Every Flight, including its finalizer, stays inside a blocking worker. -use super::{View, WorkspaceClose, allowed, empty, failure::WorkerCleanup}; +use super::{Phase, View, WorkspaceClose, allowed, empty, failure::WorkerCleanup}; use crate::workspace_source_access::ControlKind; use rangoon_desktop::workspace_session::{Action as NativeAction, Layout, Preview}; use serde::{Deserialize, Serialize}; @@ -11,6 +11,30 @@ use tauri::{ }; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogResult}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Consent { + Approved, + Cancelled, + Unavailable, +} + +pub(crate) fn dialog_consent( + result: MessageDialogResult, + affirmative: &str, + alive: bool, +) -> Consent { + if !alive { + return Consent::Unavailable; + } + match result { + MessageDialogResult::Custom(label) if label == affirmative => Consent::Approved, + MessageDialogResult::Custom(label) if label == "Cancel" => Consent::Cancelled, + // An unclassified dismissal or unavailable callback is not proof that + // the user selected this dialog's explicit Cancel button. + _ => Consent::Unavailable, + } +} + #[derive(Clone, Copy, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub(crate) enum Action { @@ -124,6 +148,29 @@ impl Response { false, ) } + fn cancelled_after_cleanup(close: &WorkspaceClose, request: &Cycle) -> Option { + let state = close.state.lock().ok()?; + let view = close.snapshot_locked(&state, false, None); + if state.exiting + || state.control.is_some() + || !matches!(view.state, Phase::Locked) + || view.storage != "managed_encrypted" + || view.attempt_id.as_deref() != Some(request.attempt_id.as_str()) + || view.epoch.as_deref() != Some(request.epoch.as_str()) + || view.diagnostic.is_some() + { + return None; + } + Some(Self { + schema_version: "rangoon.workspace-control-state.v1", + close: view, + phase: "locked", + action: None, + outcome: "cancelled", + diagnostic: None, + reload: false, + }) + } } #[derive(Serialize)] @@ -280,7 +327,7 @@ pub(crate) fn confirm( close: &WorkspaceClose, request: Cycle, cleanup: impl FnOnce(bool) -> bool + Send + 'static, - consent: impl FnOnce(&Preview) -> bool, + consent: impl FnOnce(&Preview) -> Consent, consumed: impl FnOnce() -> bool, ) -> Response { let Ok(mut flight) = close.take_control_ready(&request.attempt_id, &request.epoch, cleanup) @@ -293,15 +340,25 @@ pub(crate) fn confirm( preview.kind, NativeAction::CreateEmpty | NativeAction::Unlock ) || preview.source_id.is_some() - || !consent(&preview) { return None; } - flight.confirm(&preview.id).ok()?; - consumed().then_some(()) + match consent(&preview) { + Consent::Cancelled => Some(false), + Consent::Unavailable => None, + Consent::Approved => { + flight.confirm(&preview.id).ok()?; + consumed().then_some(true) + } + } })); - if !matches!(result, Ok(Some(()))) { + if !matches!(result, Ok(Some(true))) { drop(flight); + if matches!(result, Ok(Some(false))) + && let Some(cancelled) = Response::cancelled_after_cleanup(close, &request) + { + return cancelled; + } return Response::result( close, "closed", @@ -337,12 +394,12 @@ pub(crate) fn cancel( } } -fn native_consent(app: &AppHandle, cleanup: &WorkerCleanup, preview: &Preview) -> bool { +fn native_consent(app: &AppHandle, cleanup: &WorkerCleanup, preview: &Preview) -> Consent { if !cleanup.alive() || preview.source_id.is_some() { - return false; + return Consent::Unavailable; } let Some(parent) = app.get_webview_window("main") else { - return false; + return Consent::Unavailable; }; let (title, question, affirmative) = match preview.kind { NativeAction::CreateEmpty => ( @@ -355,7 +412,7 @@ fn native_consent(app: &AppHandle, cleanup: &WorkerCleanup, preview: &Preview) - "Read the existing Rangoon workspace key from this user's operating-system credential store and unlock the encrypted workspace? This does not authorize external calls or execution.", "Unlock workspace", ), - _ => return false, + _ => return Consent::Unavailable, }; let result = app .dialog() @@ -367,7 +424,17 @@ fn native_consent(app: &AppHandle, cleanup: &WorkerCleanup, preview: &Preview) - "Cancel".into(), )) .blocking_show_with_result(); - cleanup.alive() && matches!(result, MessageDialogResult::Custom(label) if label == affirmative) + let consent = dialog_consent(result, affirmative, cleanup.alive()); + #[cfg(all(test, feature = "native-encrypted-qualification", target_os = "macos"))] + { + let purpose = match preview.kind { + NativeAction::CreateEmpty => "create_empty", + NativeAction::Unlock => "unlock", + _ => return Consent::Unavailable, + }; + crate::native_encrypted_qualification::consent_observed(purpose, consent); + } + consent } #[tauri::command] @@ -479,3 +546,51 @@ pub(crate) async fn cancel_workspace_control( .await .map_err(|_| ()) } + +#[cfg(test)] +mod native_dialog_tests { + use super::{Consent, MessageDialogResult, dialog_consent}; + + #[test] + fn only_live_exact_native_buttons_classify_consent() { + assert_eq!( + dialog_consent( + MessageDialogResult::Custom("Set up workspace".into()), + "Set up workspace", + true + ), + Consent::Approved + ); + assert_eq!( + dialog_consent( + MessageDialogResult::Custom("Cancel".into()), + "Set up workspace", + true + ), + Consent::Cancelled + ); + for result in [ + MessageDialogResult::Cancel, + MessageDialogResult::Yes, + MessageDialogResult::No, + MessageDialogResult::Ok, + MessageDialogResult::Custom("cancel".into()), + MessageDialogResult::Custom("Unlock workspace".into()), + ] { + assert_eq!( + dialog_consent(result, "Set up workspace", true), + Consent::Unavailable + ); + } + for label in ["Cancel", "Set up workspace"] { + assert_eq!( + dialog_consent( + MessageDialogResult::Custom(label.into()), + "Set up workspace", + false + ), + Consent::Unavailable + ); + } + } +} diff --git a/apps/desktop/src/workspace_setup_tests.rs b/apps/desktop/src/workspace_setup_tests.rs index 4a008e4..a22aa95 100644 --- a/apps/desktop/src/workspace_setup_tests.rs +++ b/apps/desktop/src/workspace_setup_tests.rs @@ -4,7 +4,7 @@ use super::*; #[cfg(feature = "encrypted-workspace")] use crate::workspace_close::{ WorkspaceClose, - setup::{Cycle, Preparation, Response, cancel, confirm, prepare}, + setup::{Consent, Cycle, Preparation, Response, cancel, confirm, prepare}, }; #[cfg(feature = "encrypted-workspace")] use rangoon_desktop::workspace_session::{Action as NativeAction, Owner}; @@ -212,7 +212,7 @@ fn setup_confirm_acknowledges_c1_then_holds_real_owner_until_consumed() { |_| true, |preview| { assert!(preview.source_id.is_none()); - true + Consent::Approved }, || confirmed_tx.send(()).is_ok() && consume_rx.recv().is_ok(), )) @@ -263,7 +263,7 @@ fn setup_refuses_unacknowledged_wrong_and_replayed_c1_without_losing_retained_co &close, cycle(&c1_id, &c1_epoch), |_| true, - |_| false, + |_| Consent::Unavailable, || true, )); assert_eq!(declined["outcome"], "closed"); @@ -299,7 +299,10 @@ fn setup_unlock_confirms_existing_workspace_and_publishes_fresh_client() { &close, cycle(&c1_id, &c1_epoch), |_| true, - |preview| preview.kind == NativeAction::Unlock && preview.source_id.is_none(), + |preview| { + assert!(preview.kind == NativeAction::Unlock && preview.source_id.is_none()); + Consent::Approved + }, || true, )); assert_eq!(opened["outcome"], "opened"); @@ -341,7 +344,7 @@ fn setup_failed_consent_prepare_or_consumption_never_publishes_a_client() { &close, cycle(&c1_id, &c1_epoch), |_| true, - |_| true, + |_| Consent::Approved, || false, )); assert_eq!(unconsumed["outcome"], "closed"); @@ -359,7 +362,7 @@ fn setup_failed_consent_prepare_or_consumption_never_publishes_a_client() { &close, cycle(&c1_id, &c1_epoch), |_| true, - |_| true, + |_| Consent::Approved, || panic!("dropped completion is closed"), )); assert_eq!(panicked_consumption["outcome"], "closed"); @@ -527,7 +530,7 @@ fn setup_cancelled_blocked_callback_stays_closed_and_late_result_cannot_resume() &worker_close, cycle(&callback_id, &callback_epoch), |_| true, - |_| true, + |_| Consent::Approved, || true, )) }); @@ -557,7 +560,7 @@ fn setup_registry_poison_after_owner_confirmation_fails_closed() { &close, cycle(&c1_id, &c1_epoch), |_| true, - |_| true, + |_| Consent::Approved, || { access.0.clients.poison_for_test(); true @@ -612,3 +615,140 @@ impl rangoon_desktop::workspace_session::Vault for BlockingVault { rangoon_desktop::workspace_session::Vault::open(&self.inner, identity) } } + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn setup_explicit_cancel_releases_custody_and_allows_fresh_setup_or_unlock() { + for action in ["create_empty", "unlock"] { + let root = TestRoot::new("setup-explicit-cancel"); + let vault = ThreadVault::default(); + if action == "unlock" { + let mut owner = Owner::acquire(root.0.clone()).unwrap(); + let preview = owner.prepare_create_empty().unwrap(); + owner.confirm(&preview.id, &vault).unwrap(); + owner.lock(); + } + let opens_before = vault.0.lock().unwrap().opens; + let access = locked_access(&root, &vault); + let (close, mut id, mut epoch) = locked_close(access.clone()); + for _ in 0..2 { + let (_, next_id, next_epoch) = prepared_action(&close, &id, &epoch, action); + assert_ne!(id, next_id); + assert_ne!(epoch, next_epoch); + acknowledge_current(&close, &next_id, &next_epoch); + let cleanup_ran = Arc::new(AtomicBool::new(false)); + let cleaned = cleanup_ran.clone(); + let cancelled = response_json(confirm( + &close, + cycle(&next_id, &next_epoch), + move |drained| { + cleaned.store(drained, Ordering::SeqCst); + drained + }, + |_| Consent::Cancelled, + || panic!("cancel must not consume a successful Owner confirmation"), + )); + assert!(cleanup_ran.load(Ordering::SeqCst)); + assert_eq!(cancelled["outcome"], "cancelled"); + assert_eq!(cancelled["phase"], "locked"); + assert_eq!(cancelled["diagnostic"], serde_json::Value::Null); + assert_eq!(cancelled["action"], serde_json::Value::Null); + assert_eq!(cancelled["reload"], false); + assert_eq!( + identity(&cancelled["close"]), + (next_id.clone(), next_epoch.clone()) + ); + assert_owner_closed(&access); + assert_eq!(request_json(&access)["state"], "unavailable"); + assert_eq!(vault.0.lock().unwrap().opens, opens_before); + let protection = serde_json::to_value( + crate::workspace_close::setup::ProtectionResponse::observe(&close), + ) + .unwrap(); + assert_eq!( + protection["layout"], + if action == "unlock" { + "locked" + } else { + "absent" + } + ); + id = next_id; + epoch = next_epoch; + } + } +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn setup_cancel_with_failed_or_panicked_cleanup_cannot_report_retryable_cancellation() { + for panic_cleanup in [false, true] { + let root = TestRoot::new("setup-cancel-cleanup-failure"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let (close, id, epoch) = locked_close(access.clone()); + let (_, id, epoch) = prepared_empty(&close, &id, &epoch); + acknowledge_current(&close, &id, &epoch); + let cancelled = response_json(confirm( + &close, + cycle(&id, &epoch), + move |_| { + assert!(!panic_cleanup, "synthetic cleanup failure"); + false + }, + |_| Consent::Cancelled, + || panic!("cancel never consumes confirmation"), + )); + assert_eq!(cancelled["outcome"], "closed"); + assert_eq!(cancelled["diagnostic"], "workspace_control_not_completed"); + assert_eq!(cancelled["phase"], "recovery_required"); + assert_eq!(cancelled["reload"], false); + assert_owner_closed(&access); + assert_eq!(request_json(&access)["state"], "unavailable"); + assert_eq!(vault.0.lock().unwrap().opens, 0); + } +} + +#[cfg(feature = "encrypted-workspace")] +#[test] +fn setup_late_cancel_after_concurrent_close_or_exit_cannot_offer_retry() { + for exit in [false, true] { + let root = TestRoot::new("setup-late-native-cancel"); + let vault = ThreadVault::default(); + let access = locked_access(&root, &vault); + let (close, id, epoch) = locked_close(access.clone()); + let (_, id, epoch) = prepared_empty(&close, &id, &epoch); + acknowledge_current(&close, &id, &epoch); + let (entered_tx, entered_rx) = mpsc::channel(); + let (return_tx, return_rx) = mpsc::channel(); + let worker_close = close.clone(); + let worker_id = id.clone(); + let worker_epoch = epoch.clone(); + let worker = thread::spawn(move || { + response_json(confirm( + &worker_close, + cycle(&worker_id, &worker_epoch), + |_| true, + |_| { + entered_tx.send(()).unwrap(); + return_rx.recv_timeout(WAIT).unwrap(); + Consent::Cancelled + }, + || panic!("late cancel never consumes confirmation"), + )) + }); + entered_rx.recv_timeout(WAIT).unwrap(); + if exit { + close.fence_admission_for_exit(); + } else { + cancel(&close, cycle(&id, &epoch), |_| true); + } + return_tx.send(()).unwrap(); + let late = worker.join().unwrap(); + assert_eq!(late["outcome"], "closed"); + assert_eq!(late["reload"], false); + assert_owner_closed(&access); + assert_eq!(request_json(&access)["state"], "unavailable"); + assert_eq!(vault.0.lock().unwrap().opens, 0); + } +} diff --git a/apps/desktop/src/workspace_source_access.rs b/apps/desktop/src/workspace_source_access.rs index 5cf26fd..0b24c45 100644 --- a/apps/desktop/src/workspace_source_access.rs +++ b/apps/desktop/src/workspace_source_access.rs @@ -1,5 +1,4 @@ -//! Private typed source, capability and workflow routing. Production construction remains legacy; -//! managed encrypted Owner construction is confined to synthetic tests. +//! Private typed source, capability and workflow routing through native custody. #[cfg(test)] use super::admit; use super::{ @@ -44,7 +43,7 @@ use std::{ #[derive(Clone, Copy)] enum Error { Store(StoreError), - #[cfg(all(test, feature = "encrypted-workspace"))] + #[cfg(feature = "encrypted-workspace")] Managed(rangoon_desktop::workspace_session::Error), Cleared, WriteUncertain, @@ -83,7 +82,7 @@ impl Error { "workspace_write_completed", "The local change completed before the workspace closed. Reopen and inspect saved content; closing did not undo the change.", ), - #[cfg(all(test, feature = "encrypted-workspace"))] + #[cfg(feature = "encrypted-workspace")] Self::Managed(error) => { use rangoon_desktop::workspace_session::Error as ManagedError; match error { @@ -103,7 +102,7 @@ impl Error { PublicError { code, message } } fn managed_failure(self) -> bool { - #[cfg(all(test, feature = "encrypted-workspace"))] + #[cfg(feature = "encrypted-workspace")] if matches!(self, Self::Managed(_)) { return true; } @@ -171,6 +170,21 @@ impl Error { } trait Backend: Send { + fn content_bound(&self) -> bool { + true + } + #[cfg(feature = "encrypted-workspace")] + fn control_check_identity(&mut self, _expected: &str) -> Result<(), ControlOwnerError> { + Err(ControlOwnerError::ConsentRequired) + } + #[cfg(feature = "encrypted-workspace")] + fn control_bind_owner( + &mut self, + _root: &Path, + _existing: bool, + ) -> Result<(), ControlOwnerError> { + Err(ControlOwnerError::BackendUnavailable) + } fn control_layout(&self) -> ControlLayout { ControlLayout::Unavailable } @@ -254,6 +268,12 @@ trait Backend: Send { revision: &str, profile: rangoon_compile::Profile, ) -> Result; + fn encrypted_recovery_supported(&self) -> bool { + false + } + fn capture_recovery_snapshot(&mut self) -> Result, Error> { + Err(Error::EncryptedRecoveryUnavailable) + } fn plaintext_backup_export_allowed(&self) -> bool; fn export_workflow_backup(&mut self) -> Result, Error>; fn prepare_workflow_restore(&mut self, backup: &Backup) -> Result; @@ -386,7 +406,7 @@ impl Backend for Legacy { .store()? .apply_composition(&prepared, acknowledged) .map_err(Error::Store), - #[cfg(all(test, feature = "encrypted-workspace"))] + #[cfg(feature = "encrypted-workspace")] CompositionHandle::Managed(_) => Err(Error::Store(StoreError::CompositionInvalid)), } } @@ -439,60 +459,126 @@ impl Backend for Legacy { } } -#[cfg(all(test, feature = "encrypted-workspace"))] +#[cfg(feature = "encrypted-workspace")] struct Managed { - owner: rangoon_desktop::workspace_session::Owner, + owner: Option, + fixed_root: Option, vault: V, } -#[cfg(all(test, feature = "encrypted-workspace"))] +#[cfg(feature = "encrypted-workspace")] impl Backend for Managed { + fn content_bound(&self) -> bool { + self.owner.is_some() + } + fn control_check_identity(&mut self, expected: &str) -> Result<(), ControlOwnerError> { + let owner = self.owner.as_mut().ok_or(ControlOwnerError::Locked)?; + let result = owner.prepare_unlock().and_then(|preview| { + if preview.workspace_id == expected { + Ok(()) + } else { + Err(ControlOwnerError::InvalidBinding) + } + }); + // Inspection never retains an unlock preparation or opens a key slot. + owner.lock(); + result + } + fn control_bind_owner(&mut self, root: &Path, existing: bool) -> Result<(), ControlOwnerError> { + if self.owner.is_some() || self.fixed_root.as_deref() != Some(root) { + return Err(ControlOwnerError::ConsentRequired); + } + let owner = if existing { + rangoon_desktop::workspace_session::Owner::acquire_existing(root.to_owned())? + } else { + rangoon_desktop::workspace_session::Owner::acquire(root.to_owned())? + }; + self.owner = Some(owner); + Ok(()) + } fn control_layout(&self) -> ControlLayout { - self.owner.inspect_layout() + self.owner + .as_ref() + .map_or(ControlLayout::Unavailable, |owner| owner.inspect_layout()) } fn control_prepare(&mut self, kind: reopen::Kind) -> Result { + let owner = self.owner.as_mut().ok_or(ControlOwnerError::Locked)?; match kind { - reopen::Kind::CreateEmpty => self.owner.prepare_create_empty(), - reopen::Kind::Unlock => self.owner.prepare_unlock(), - reopen::Kind::Recovery => Err(ControlOwnerError::ConsentRequired), + reopen::Kind::CreateEmpty => owner.prepare_create_empty(), + reopen::Kind::Unlock => owner.prepare_unlock(), + reopen::Kind::Recovery | reopen::Kind::Startup => { + Err(ControlOwnerError::ConsentRequired) + } } } fn control_confirm(&mut self, id: &str) -> Result<(), ControlOwnerError> { - self.owner.confirm(id, &self.vault) + self.owner + .as_mut() + .ok_or(ControlOwnerError::Locked)? + .confirm(id, &self.vault) } fn control_inspect(&mut self) -> Result { - self.owner.inspect_recovery(&self.vault) + self.owner + .as_mut() + .ok_or(ControlOwnerError::Locked)? + .inspect_recovery(&self.vault) } fn control_reconcile(&mut self, id: &str) -> Result<(), ControlOwnerError> { - self.owner.confirm_recovery(id, &self.vault) + self.owner + .as_mut() + .ok_or(ControlOwnerError::Locked)? + .confirm_recovery(id, &self.vault) } fn control_is_open(&self) -> bool { - self.owner.is_unlocked() && !self.owner.requires_recovery() + self.owner + .as_ref() + .is_some_and(|owner| owner.is_unlocked() && !owner.requires_recovery()) } - fn ordinary_closed_error(&self) -> Error { - Error::Managed(if self.owner.requires_recovery() { - ControlOwnerError::RecoveryRequired - } else { - ControlOwnerError::Locked - }) + Error::Managed( + if self + .owner + .as_ref() + .is_some_and(|owner| owner.requires_recovery()) + { + ControlOwnerError::RecoveryRequired + } else { + ControlOwnerError::Locked + }, + ) } - fn close_session(&mut self) -> bool { - let healthy_for_reopen = !self.owner.requires_recovery(); - self.owner.lock(); + let Some(owner) = self.owner.as_mut() else { + return true; + }; + let healthy_for_reopen = !owner.requires_recovery(); + owner.lock(); healthy_for_reopen } fn list(&mut self) -> Result, Error> { - self.owner.list(&self.vault).map_err(Error::Managed) + self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? + .list(&self.vault) + .map_err(Error::Managed) } fn open(&mut self, id: &str) -> Result { - self.owner.open(&self.vault, id).map_err(Error::Managed) + self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? + .open(&self.vault, id) + .map_err(Error::Managed) } fn save(&mut self, report: &AnalysisReport) -> Result { - self.owner.save(&self.vault, report).map_err(Error::Managed) + self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? + .save(&self.vault, report) + .map_err(Error::Managed) } fn list_capabilities(&mut self) -> Result, Error> { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .list_capabilities(&self.vault) .map_err(Error::Managed) } @@ -502,6 +588,8 @@ impl Backend for Managed revision: Option<&str>, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .open_capability(&self.vault, id, revision) .map_err(Error::Managed) } @@ -512,6 +600,8 @@ impl Backend for Managed title: &str, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .create_capability(&self.vault, source, fragment, title) .map_err(Error::Managed) } @@ -523,6 +613,8 @@ impl Backend for Managed content: &str, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .revise_capability(&self.vault, id, expected, title, content) .map_err(Error::Managed) } @@ -532,21 +624,29 @@ impl Backend for Managed expected: &str, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .review_capability(&self.vault, id, expected) .map_err(Error::Managed) } fn workflow_data(&mut self) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .workflow_data(&self.vault) .map_err(Error::Managed) } fn list_workflows(&mut self) -> Result, Error> { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .list_workflows(&self.vault) .map_err(Error::Managed) } fn open_workflow(&mut self, id: &str, revision: Option<&str>) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .open_workflow(&self.vault, id, revision) .map_err(Error::Managed) } @@ -555,6 +655,8 @@ impl Backend for Managed candidate: &WorkflowRevision, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .inspect_workflow_save(&self.vault, candidate) .map_err(Error::Managed) } @@ -564,6 +666,8 @@ impl Backend for Managed expected: &str, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .save_workflow(&self.vault, candidate, expected) .map_err(Error::Managed) } @@ -572,6 +676,8 @@ impl Backend for Managed request: &rangoon_compose::application::Request, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .prepare_composition_confirmation(&self.vault, request) .map(RoutedCompositionPreview::managed) .map_err(Error::Managed) @@ -584,6 +690,8 @@ impl Backend for Managed match handle { CompositionHandle::Managed(token) => self .owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .confirm_composition(&self.vault, &token, acknowledged) .map_err(Error::Managed), CompositionHandle::Legacy(_) => Err(Error::Store(StoreError::CompositionInvalid)), @@ -596,9 +704,21 @@ impl Backend for Managed profile: rangoon_compile::Profile, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .compile_capability(&self.vault, id, revision, profile) .map_err(Error::Managed) } + fn encrypted_recovery_supported(&self) -> bool { + crate::encrypted_recovery::supported() + } + fn capture_recovery_snapshot(&mut self) -> Result, Error> { + self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? + .export_workflow_backup(&self.vault) + .map_err(Error::Managed) + } fn plaintext_backup_export_allowed(&self) -> bool { false } @@ -607,6 +727,8 @@ impl Backend for Managed } fn prepare_workflow_restore(&mut self, backup: &Backup) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .prepare_workflow_restore(&self.vault, backup) .map_err(Error::Managed) } @@ -616,6 +738,8 @@ impl Backend for Managed plan: &RestorePlan, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .restore_workflow_backup(&self.vault, backup, plan) .map_err(Error::Managed) } @@ -625,6 +749,8 @@ impl Backend for Managed id: &str, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .inspect_workflow_deletion(&self.vault, kind, id) .map_err(Error::Managed) } @@ -633,6 +759,8 @@ impl Backend for Managed plan: &DeletionPlan, ) -> Result { self.owner + .as_mut() + .ok_or(Error::Managed(ControlOwnerError::Locked))? .delete_workflow_record(&self.vault, plan) .map_err(Error::Managed) } @@ -779,6 +907,7 @@ enum Caller { HostFixture, } impl SourceAccess { + #[cfg(test)] fn new(gate: Gate, backend: Box) -> Self { Self::with_mode(gate, backend, false) } @@ -839,21 +968,75 @@ impl SourceAccess { pub(super) fn request_view(&self) -> crate::workspace_requests::View { self.0.clients.view() } + #[cfg(test)] pub(super) fn legacy(gate: Gate, root: Result) -> Self { Self::new(gate, Box::new(Legacy(root))) } + /// Pathless refusal state for a missing encrypted backend or native anchor. + /// The error carrier cannot open storage. Managed request custody remains + /// enabled, so a Legacy request can never acquire content permissions. + pub(super) fn unavailable(gate: Gate) -> Self { + Self::with_mode(gate, Box::new(Legacy(Err(StoreError::Unavailable))), true) + } #[cfg(test)] pub(super) fn close_protocol_fixture(gate: Gate) -> Self { // Memory-only protocol fixtures; real keyed Owner closure is tested separately. Self::with_mode(gate, Box::new(Legacy(Err(StoreError::Unavailable))), true).host_fixture() } + /// Retained fixture constructor for earlier isolated Owner/exit regressions. + /// Ordinary startup uses deferred acquisition and the startup host instead. + #[cfg(all(test, feature = "encrypted-workspace"))] + pub(super) fn managed_locked( + gate: Gate, + root: PathBuf, + vault: V, + ) -> Result { + let owner = rangoon_desktop::workspace_session::Owner::acquire(root)?; + Ok(Self::with_mode( + gate, + Box::new(Managed { + owner: Some(owner), + fixed_root: None, + vault, + }), + true, + )) + } + /// Fixed encrypted mode with no Owner, filesystem access or credential lookup. + #[cfg(feature = "encrypted-workspace")] + pub(super) fn managed_deferred< + V: rangoon_desktop::workspace_session::Vault + Send + 'static, + >( + gate: Gate, + root: PathBuf, + vault: V, + ) -> Self { + Self::with_mode( + gate, + Box::new(Managed { + owner: None, + fixed_root: Some(root), + vault, + }), + true, + ) + } #[cfg(all(test, feature = "encrypted-workspace"))] fn managed( gate: Gate, owner: rangoon_desktop::workspace_session::Owner, vault: V, ) -> Self { - Self::with_mode(gate, Box::new(Managed { owner, vault }), true).host_fixture() + Self::with_mode( + gate, + Box::new(Managed { + owner: Some(owner), + fixed_root: None, + vault, + }), + true, + ) + .host_fixture() } #[cfg(test)] fn host_fixture(mut self) -> Self { @@ -947,6 +1130,12 @@ impl SourceAccess { watch.armed = false; return Err(Error::Store(StoreError::Unavailable)); } + if !backend.content_bound() { + // Unbound is a closed startup state, not an authenticated session or + // a corruption event. Do not invoke ordinary work or its watchdog. + watch.armed = false; + return Err(Error::Store(StoreError::Unavailable)); + } let result = action(backend.as_mut()); if watch.armed { watch.armed = !backend.ordinary_session_healthy(); @@ -1350,7 +1539,10 @@ impl SourceAccess { } }; match tauri::async_runtime::spawn_blocking(move || { - let result = ticket.call(|backend| backend.workflow_data()); + let result = ticket.call(|backend| { + let data = backend.workflow_data()?; + Ok((data, backend.encrypted_recovery_supported())) + }); WorkflowInventoryCompletion { ticket, result: Some(result), @@ -1601,8 +1793,205 @@ impl ModelInputCompletion { } /// Picker/file callbacks carry the same real lease as typed workspace access. +#[cfg(test)] +type RecoveryCheckpoint = Box; +#[cfg(test)] +std::thread_local! { + static RECOVERY_CHECKPOINT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static RECOVERY_CAPTURE_CHECKPOINT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} pub(super) struct FileOperation(CapabilityTicket); +#[cfg(all(feature = "native-encrypted-qualification", target_os = "macos"))] +impl SourceAccess { + /// Fixed synthetic qualification observation, never mounted as an IPC command. + pub(super) fn qualification_recovery_snapshot(&self) -> Result<(String, usize), PublicError> { + // Use the registered current native request, just like the workbench. + // An unbound host fixture must not mask missing production request custody. + let unavailable = || Error::Store(StoreError::Unavailable).public(); + let view = serde_json::to_value(self.request_view()).map_err(|_| unavailable())?; + let client = view["clientId"].as_str().ok_or_else(unavailable)?; + let request = self.request_context("main", Some(client)); + let bound = self.for_request(&request); + let operation = bound + .begin_file() + .map_err(|_| Error::Store(StoreError::Unavailable).public())?; + operation + .require_encrypted_recovery() + .map_err(Error::public)?; + let bytes = zeroize::Zeroizing::new( + operation + .0 + .call(|backend| backend.capture_recovery_snapshot()) + .map_err(Error::public)?, + ); + #[cfg(test)] + if let Some(probe) = RECOVERY_CHECKPOINT.with(|cell| cell.borrow_mut().take()) { + probe(); + } + operation.current().map_err(Error::public)?; + let backup = Backup::decode(&bytes).map_err(|error| Error::Store(error).public())?; + operation.current().map_err(Error::public)?; + Ok((backup.id().to_owned(), backup.byte_length())) + } +} impl FileOperation { + fn require_encrypted_recovery(&self) -> Result<(), Error> { + if self + .0 + .call(|backend| Ok(backend.encrypted_recovery_supported()))? + { + Ok(()) + } else { + Err(Error::EncryptedRecoveryUnavailable) + } + } + pub(super) fn create_recovery_key( + self, + pick: impl FnOnce() -> Result, PublicError>, + ) -> DataCompletion { + let result = (|| { + self.require_encrypted_recovery()?; + let Some(path) = self.pick(pick)? else { + return Ok(DataResult::Cancelled); + }; + self.current()?; + crate::encrypted_recovery::create_key(&path).map_err(Error::from_host)?; + Ok(DataResult::RecoveryKeyCreated) + })(); + DataCompletion { + ticket: self.0, + result: Some(result), + authoring: false, + write: false, + } + } + pub(super) fn export_encrypted_backup( + self, + pick_key: impl FnOnce() -> Result, PublicError>, + pick_output: impl FnOnce() -> Result, PublicError>, + write: impl FnOnce(&Path, &[u8]) -> Result<(), PublicError>, + read: impl FnOnce(&Path) -> Result, PublicError>, + ) -> DataCompletion { + let mut output_attempted = false; + let result = (|| { + use crate::encrypted_recovery as recovery; + self.require_encrypted_recovery()?; + let Some(key_path) = self.pick(pick_key)? else { + return Ok(DataResult::Cancelled); + }; + let key = recovery::read_key(&key_path).map_err(Error::from_host)?; + self.current()?; + let Some(output) = self.pick(pick_output)? else { + return Ok(DataResult::Cancelled); + }; + let original = zeroize::Zeroizing::new( + self.0.call(|backend| backend.capture_recovery_snapshot())?, + ); + #[cfg(test)] + if let Some(probe) = RECOVERY_CAPTURE_CHECKPOINT.with(|cell| cell.borrow_mut().take()) { + probe(); + } + self.current()?; + let backup = Backup::decode(&original)?; + self.current()?; + let ciphertext = recovery::encode(&backup, &key).map_err(Error::from_host)?; + #[cfg(test)] + if let Some(probe) = RECOVERY_CHECKPOINT.with(|cell| cell.borrow_mut().take()) { + probe(); + } + self.current()?; + let current = zeroize::Zeroizing::new( + self.0.call(|backend| backend.capture_recovery_snapshot())?, + ); + if *current != *original { + return Err(Error::Host( + "workspace_recovery_source_changed", + "The workspace changed while preparing backup. Create a fresh backup; no output was written.", + )); + } + drop(current); + self.current()?; + output_attempted = true; + write(&output, &ciphertext).map_err(Error::from_host)?; + self.current()?; + // Verify the selected file, through a new stage and SQLite connection. + let written = read(&output).map_err(Error::from_host)?; + self.current()?; + if written != ciphertext { + return Err(Error::from_host(recovery::invalid())); + } + self.current()?; + let checked = recovery::decode(&written, &key).map_err(Error::from_host)?; + if !checked.same_recovery_records(&backup)? { + return Err(Error::from_host(recovery::invalid())); + } + let current = zeroize::Zeroizing::new( + self.0.call(|backend| backend.capture_recovery_snapshot())?, + ); + if *current != *original { + return Err(Error::from_host(recovery::invalid())); + } + self.current()?; + Ok(DataResult::EncryptedExported { + format: recovery::FORMAT, + backup_id: checked.id().to_owned(), + byte_length: written.len(), + }) + })(); + let result = if output_attempted && result.is_err() { + Err(Error::Host( + "workspace_recovery_output_uncertain", + "Backup did not return a verified result. A file may remain; inspect your selected output and create a fresh backup with a new name.", + )) + } else { + result + }; + DataCompletion { + ticket: self.0, + result: Some(result), + authoring: false, + write: false, + } + } + pub(super) fn prepare_encrypted_restore( + self, + pick_backup: impl FnOnce() -> Result, PublicError>, + pick_key: impl FnOnce() -> Result, PublicError>, + read: impl FnOnce(&Path) -> Result, PublicError>, + ) -> DataCompletion { + let result = (|| { + use crate::encrypted_recovery as recovery; + self.require_encrypted_recovery()?; + let Some(path) = self.pick(pick_backup)? else { + return Ok(DataResult::Cancelled); + }; + let bytes = read(&path).map_err(Error::from_host)?; + self.current()?; + let Some(key_path) = self.pick(pick_key)? else { + return Ok(DataResult::Cancelled); + }; + let key = recovery::read_key(&key_path).map_err(Error::from_host)?; + self.current()?; + let backup = recovery::decode(&bytes, &key).map_err(Error::from_host)?; + self.current()?; + let plan = self + .0 + .call(|backend| backend.prepare_workflow_restore(&backup))?; + self.current()?; + self.0 + .access + .0 + .backup + .stage_routed(backup, plan.clone(), self.0.lease.witness())?; + Ok(DataResult::RestoreReady { plan }) + })(); + DataCompletion { + ticket: self.0, + result: Some(result), + authoring: true, + write: false, + } + } fn current(&self) -> Result<(), Error> { if self.0.current() { Ok(()) @@ -1871,12 +2260,20 @@ impl DataCompletion { { Error::WriteCompleted.data() } - Ok(DataResult::Exported { .. }) if !current => DataResult::Failed { + Ok(DataResult::RecoveryKeyCreated) if !current => DataResult::Failed { error: PublicError { - code: "workspace_export_completed", - message: "Export completed before the workspace closed. Closing did not undo the file; inspect your selected output.", + code: "workspace_recovery_key_created", + message: "The secret recovery key file was created before the workspace closed. Closing did not remove it; inspect your selected location before creating another key.", }, }, + Ok(DataResult::Exported { .. } | DataResult::EncryptedExported { .. }) if !current => { + DataResult::Failed { + error: PublicError { + code: "workspace_export_completed", + message: "Export completed before the workspace closed. Closing did not undo the file; inspect your selected output.", + }, + } + } Ok(_) if !current => Error::Store(StoreError::Unavailable).data(), Ok(result) => result, Err(error) => error.data(), @@ -2131,7 +2528,7 @@ impl Drop for WorkflowCompletion { } struct WorkflowInventoryCompletion { ticket: CapabilityTicket, - result: Option>, + result: Option>, } impl WorkflowInventoryCompletion { fn deliver(mut self) -> DataResult { @@ -2155,7 +2552,10 @@ impl WorkflowInventoryCompletion { self.ticket.access.purge_workflow_authoring(); } match result { - Ok(workspace) => DataResult::Loaded { workspace }, + Ok((workspace, encrypted_recovery_supported)) => DataResult::Loaded { + workspace, + encrypted_recovery_supported, + }, Err(error) => DataResult::Failed { error: error.public(), }, diff --git a/apps/desktop/src/workspace_source_access_tests.rs b/apps/desktop/src/workspace_source_access_tests.rs index 2b82391..0d57e9e 100644 --- a/apps/desktop/src/workspace_source_access_tests.rs +++ b/apps/desktop/src/workspace_source_access_tests.rs @@ -63,6 +63,28 @@ fn workspace_code(result: WorkspaceResult) -> &'static str { } } +#[test] +fn unavailable_native_backend_rejects_legacy_requests_without_latching_corruption() { + let access = SourceAccess::unavailable(Gate::new()); + assert!(access.encrypted_close_available()); + let view = serde_json::to_value(access.request_view()).unwrap(); + assert_eq!(view["storage"], "managed_encrypted"); + assert!(view["clientId"].is_null()); + assert!(matches!( + access.request_context("main", None), + crate::workspace_requests::WorkspaceRequest::Refused + )); + let legacy = access.for_request(&crate::workspace_requests::WorkspaceRequest::Legacy); + assert!(legacy.begin_selection().is_err()); + assert!(legacy.begin_model_inputs().is_err()); + assert!(matches!( + tauri::async_runtime::block_on(legacy.list_snapshots()), + WorkspaceResult::Failed { .. } + )); + assert!(!access.failure_latched()); + assert!(serde_json::to_value(access.request_view()).unwrap()["clientId"].is_null()); +} + fn selection_code(result: SelectionResult) -> &'static str { match result { SelectionResult::Failed { error } => error.code, @@ -492,6 +514,24 @@ fn read_only_picker_never_selects_source_and_discards_late_result() { assert!(access.0.session.snapshot(&source.source.id).is_none()); } +#[test] +fn folder_listing_uses_counted_read_only_selection_and_fences_stale_delivery() { + let (access, _, _) = probe(report("existing.md", b"# Existing\n")); + let operation = access.begin_selection().unwrap(); + assert!(matches!( + access.begin_selection(), + Err(AdmissionError::Busy) + )); + let result = rangoon_host::FolderCollectionResult::Cancelled; + let pending = operation.complete_read_only(result); + assert!(matches!(access.clear_analysis(), WorkspaceResult::Cleared)); + let delivered = pending.deliver(rangoon_host::FolderCollectionResult::stale); + assert_eq!( + serde_json::to_value(delivered).unwrap()["error"]["code"], + "folder_inventory_cleared" + ); +} + #[test] fn operations_inspection_stops_before_read_when_picker_clears() { let (access, _, _) = probe(report("operations.md", b"# Source\n")); @@ -709,11 +749,17 @@ fn closed_admission_maps_to_unavailable_not_busy() { } #[test] -fn source_binding_keeps_private_dispatch_and_test_only_managed_constructor() { +fn source_binding_keeps_private_dispatch_and_native_owned_startup_factory() { let main = include_str!("main.rs"); let source = include_str!("workspace_source_access.rs"); + let bootstrap = include_str!("workspace_native_bootstrap.rs"); assert!(main.contains("mod workspace_source_access;")); - assert!(main.contains("app.manage(source_state(app.state::().inner(), root));")); + assert!( + main.contains("workspace_native_bootstrap::install_workbench_state(app.handle(), anchor)") + ); + assert!(bootstrap.contains("SourceAccess::managed_deferred")); + assert!(bootstrap.contains("SourceAccess::unavailable")); + assert!(!bootstrap.contains("SourceAccess::new(")); for call in [ "sources.list_snapshots().await", "sources.save_analysis(source_id).await", @@ -726,7 +772,8 @@ fn source_binding_keeps_private_dispatch_and_test_only_managed_constructor() { assert!( source.contains("#[cfg(all(test, feature = \"encrypted-workspace\"))]\n fn managed") ); - assert!(!source.contains("pub(super) fn managed")); + assert!(!source.contains("pub(super) fn managed<")); + assert!(!main.contains("SourceAccess::managed_locked")); } #[cfg(feature = "encrypted-workspace")] @@ -978,3 +1025,10 @@ mod setup_commands; #[path = "workspace_protection_access_tests.rs"] mod protection_status; + +#[cfg(feature = "encrypted-workspace")] +#[path = "workspace_managed_bootstrap_tests.rs"] +mod managed_bootstrap_tests; + +#[path = "workspace_recovery_file_tests.rs"] +mod recovery_files; diff --git a/apps/desktop/src/workspace_startup.rs b/apps/desktop/src/workspace_startup.rs new file mode 100644 index 0000000..8ca1cff --- /dev/null +++ b/apps/desktop/src/workspace_startup.rs @@ -0,0 +1,668 @@ +//! Startup observations and retained Legacy capture. The native host owns +//! confirmation, lifecycle coordination and conversion; these observations grant no authority. +#[cfg(test)] +use rangoon_store::WorkflowRecoveryCounts; +use rangoon_store::{ExistingWorkspaceCapture, Workspace}; +use std::{ + fs, + path::{Path, PathBuf}, +}; + +const DATABASE: &str = "workspace.sqlite3"; +const CONTROL: &str = "encrypted-workspace.lock"; +const BINDING: &str = "encrypted-workspace.binding"; +const PARENT: &str = "encrypted-workspaces"; +const OPERATIONS: [&str; 2] = [ + "encrypted-workspace.operation.pending", + "encrypted-workspace.operation.terminal", +]; +const MAX_DATABASE: u64 = 64 * 1024 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum State { + FreshCandidate, + LegacyCandidate, + ManagedCandidate, + Mixed, + RecoveryRequired, + Unavailable, + UnsupportedPlatform, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Error { + RecoveryRequired, + Unavailable, + UnsupportedPlatform, + Changed, +} + +pub(super) struct StartupRoots { + anchor: PathBuf, +} +pub(super) struct Inspection { + state: State, + proof: Option, +} +pub(super) struct RetainedSource { + roots: StartupRoots, + inspection: Inspection, + capture: Option, +} + +/// Native-only proof for one fixed-root Owner binding. Neither the path nor the +/// creating/existing distinction can be supplied by a renderer request. +pub(super) struct BindingProof { + roots: StartupRoots, + proof: Proof, + kind: BindingKind, +} + +/// Presence-only evidence for one interrupted adoption target. This is not a +/// complete Managed binding and cannot be used to publish a content client. +#[cfg(feature = "encrypted-workspace")] +pub(super) struct EmptyProvisioningProof { + roots: StartupRoots, + proof: Proof, + destination: String, +} +enum BindingKind { + Complete, + Residue, + Fresh, +} + +macro_rules! redacted_debug { + ($kind:ty, $label:literal) => { + impl std::fmt::Debug for $kind { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str($label) + } + } + }; +} +redacted_debug!(StartupRoots, "StartupRoots()"); +redacted_debug!(Inspection, "Inspection()"); +redacted_debug!(RetainedSource, "RetainedSource()"); +redacted_debug!(BindingProof, "BindingProof()"); + +struct Node { + path: PathBuf, + metadata: Option, + directory: bool, +} +struct Proof { + nodes: Vec, +} + +fn same_file(left: &fs::Metadata, right: &fs::Metadata) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + left.dev() == right.dev() && left.ino() == right.ino() + } + #[cfg(not(unix))] + { + let _ = (left, right); + false + } +} + +fn regular(metadata: &fs::Metadata) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + metadata.is_file() && metadata.nlink() == 1 + } + #[cfg(not(unix))] + { + let _ = metadata; + false + } +} + +impl Proof { + fn observe(&mut self, path: &Path, directory: bool) -> Result, Error> { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => { + if metadata.file_type().is_symlink() + || if directory { + !metadata.is_dir() + } else { + !regular(&metadata) + } + { + return Err(Error::RecoveryRequired); + } + Some(metadata) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(_) => return Err(Error::Unavailable), + }; + self.nodes.push(Node { + path: path.to_owned(), + metadata: metadata.clone(), + directory, + }); + Ok(metadata) + } + fn check(&self) -> Result<(), Error> { + for node in &self.nodes { + match (&node.metadata, fs::symlink_metadata(&node.path)) { + (None, Err(error)) if error.kind() == std::io::ErrorKind::NotFound => (), + (Some(before), Ok(after)) + if !after.file_type().is_symlink() + && (if node.directory { + after.is_dir() + } else { + regular(&after) + }) + && same_file(before, &after) + && (node.directory || before.len() == after.len()) => {} + _ => return Err(Error::Changed), + } + } + Ok(()) + } +} + +fn names(path: &Path, limit: usize) -> Result, Error> { + let mut result = Vec::new(); + for entry in fs::read_dir(path).map_err(|_| Error::Unavailable)? { + if result.len() == limit { + return Err(Error::RecoveryRequired); + } + result.push(entry.map_err(|_| Error::Unavailable)?.file_name()); + } + result.sort(); + Ok(result) +} + +impl StartupRoots { + /// Only a native application-data anchor, never an IPC-selected root. + pub(super) fn new(anchor: PathBuf) -> Self { + Self { anchor } + } + pub(super) fn legacy(&self) -> PathBuf { + self.anchor.join("source-workspace") + } + pub(super) fn managed(&self) -> PathBuf { + self.anchor.join("managed-workspace") + } + pub(super) fn inspect(&self) -> Inspection { + match self.observe() { + Ok((state, proof)) => Inspection { + state, + proof: Some(proof), + }, + Err(error) => Inspection { + state: match error { + Error::UnsupportedPlatform => State::UnsupportedPlatform, + Error::Unavailable => State::Unavailable, + Error::RecoveryRequired | Error::Changed => State::RecoveryRequired, + }, + proof: None, + }, + } + } + fn observe(&self) -> Result<(State, Proof), Error> { + if !cfg!(unix) { + return Err(Error::UnsupportedPlatform); + } + if !self.anchor.is_absolute() + || self.anchor.components().count() > 64 + || self.anchor.components().any(|part| { + matches!( + part, + std::path::Component::CurDir | std::path::Component::ParentDir + ) + }) + { + return Err(Error::Unavailable); + } + let mut proof = Proof { nodes: Vec::new() }; + let ancestors: Vec<_> = self.anchor.ancestors().collect(); + for path in ancestors.into_iter().rev() { + proof.observe(path, true)?; + } + let legacy = self.legacy(); + let managed = self.managed(); + let has_legacy = proof.observe(&legacy, true)?.is_some(); + let has_managed = proof.observe(&managed, true)?.is_some(); + if has_legacy { + if names(&legacy, 4)? != [std::ffi::OsString::from(DATABASE)] { + return Err(Error::RecoveryRequired); + } + Self::database(&mut proof, &legacy)?; + } + if has_managed { + Self::managed_shape(&mut proof, &managed)?; + } + proof.check()?; + Ok(( + match (has_legacy, has_managed) { + (false, false) => State::FreshCandidate, + (true, false) => State::LegacyCandidate, + (false, true) => State::ManagedCandidate, + (true, true) => State::Mixed, + }, + proof, + )) + } + fn database(proof: &mut Proof, root: &Path) -> Result<(), Error> { + let metadata = proof + .observe(&root.join(DATABASE), false)? + .ok_or(Error::RecoveryRequired)?; + if metadata.len() == 0 || metadata.len() > MAX_DATABASE { + return Err(Error::RecoveryRequired); + } + Ok(()) + } + fn managed_shape(proof: &mut Proof, root: &Path) -> Result<(), Error> { + let entries = names(root, 5)?; + if ![CONTROL, BINDING, PARENT] + .iter() + .all(|name| entries.contains(&(*name).into())) + || entries.iter().any(|name| { + ![CONTROL, BINDING, PARENT, OPERATIONS[0], OPERATIONS[1]] + .iter() + .any(|allowed| name == allowed) + }) + { + return Err(Error::RecoveryRequired); + } + let control = proof + .observe(&root.join(CONTROL), false)? + .ok_or(Error::RecoveryRequired)?; + let binding = proof + .observe(&root.join(BINDING), false)? + .ok_or(Error::RecoveryRequired)?; + if control.len() != 0 || binding.len() == 0 || binding.len() > 4096 { + return Err(Error::RecoveryRequired); + } + for name in OPERATIONS { + if let Some(metadata) = proof.observe(&root.join(name), false)? + && (metadata.len() == 0 || metadata.len() > 4096) + { + return Err(Error::RecoveryRequired); + } + } + let parent = root.join(PARENT); + proof + .observe(&parent, true)? + .ok_or(Error::RecoveryRequired)?; + let identities = names(&parent, 1)?; + let identity = identities + .first() + .and_then(|name| name.to_str()) + .ok_or(Error::RecoveryRequired)?; + if identity.len() != 64 + || !identity + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(Error::RecoveryRequired); + } + let directory = parent.join(identity); + proof + .observe(&directory, true)? + .ok_or(Error::RecoveryRequired)?; + if names(&directory, 1)? != [std::ffi::OsString::from(DATABASE)] { + return Err(Error::RecoveryRequired); + } + // Presence only: Owner still validates binding/version, recovery, + // ownership and decrypted state before any client can be issued. + Self::database(proof, &directory) + } + pub(super) fn revalidate(&self, inspection: &Inspection) -> Result { + let proof = inspection.proof.as_ref().ok_or(Error::Changed)?; + proof.check()?; + let (state, _) = self.observe()?; + if state != inspection.state { + return Err(Error::Changed); + } + // Recheck original identities after the fresh path observation too. + proof.check()?; + Ok(state) + } + pub(super) fn capture_existing(&self) -> Result { + let inspection = self.inspect(); + match inspection.state { + State::LegacyCandidate => (), + State::UnsupportedPlatform => return Err(Error::UnsupportedPlatform), + State::Unavailable => return Err(Error::Unavailable), + _ => return Err(Error::RecoveryRequired), + } + self.revalidate(&inspection)?; + let capture = Workspace::new(self.legacy()) + .capture_existing_snapshot() + .map_err(|_| Error::Unavailable)?; + self.revalidate(&inspection)?; + Ok(RetainedSource { + roots: Self::new(self.anchor.clone()), + inspection, + capture: Some(capture), + }) + } +} + +impl Inspection { + pub(super) fn state(&self) -> State { + self.state + } +} + +impl RetainedSource { + /// Consumes the Legacy-only proof before a native-created target makes it Mixed. + pub(super) fn into_adoption_capture(mut self) -> Result { + self.revalidate()?; + self.capture.take().ok_or(Error::Changed) + } + #[cfg(test)] + fn capture(&self) -> Result<&ExistingWorkspaceCapture, Error> { + self.capture.as_ref().ok_or(Error::Changed) + } + #[cfg(test)] + pub(super) fn schema_version(&self) -> Result { + self.capture()?.schema_version().map_err(|_| Error::Changed) + } + #[cfg(test)] + pub(super) fn inventory(&self) -> Result<&WorkflowRecoveryCounts, Error> { + self.capture()?.inventory().map_err(|_| Error::Changed) + } + #[cfg(test)] + pub(super) fn digest(&self) -> Result<&str, Error> { + self.capture()?.digest().map_err(|_| Error::Changed) + } + #[cfg(test)] + pub(super) fn archive(&self) -> Result<&[u8], Error> { + self.capture()?.archive().map_err(|_| Error::Changed) + } + pub(super) fn cancel(&mut self) { + self.capture = None; + } + pub(super) fn revalidate(&mut self) -> Result<(), Error> { + let result = (|| { + self.roots.revalidate(&self.inspection)?; + Workspace::new(self.roots.legacy()) + .revalidate_existing_capture(self.capture.as_mut().ok_or(Error::Changed)?) + .map_err(|_| Error::Changed)?; + self.roots.revalidate(&self.inspection)?; + Ok(()) + })(); + if result.is_err() { + self.cancel(); + } + result + } +} + +impl StartupRoots { + fn binding_ancestry(&self) -> Result { + if !cfg!(unix) { + return Err(Error::UnsupportedPlatform); + } + if !self.anchor.is_absolute() + || self.anchor.components().count() > 64 + || self.anchor.components().any(|part| { + matches!( + part, + std::path::Component::CurDir | std::path::Component::ParentDir + ) + }) + { + return Err(Error::Unavailable); + } + let mut proof = Proof { nodes: Vec::new() }; + for path in self + .anchor + .ancestors() + .collect::>() + .into_iter() + .rev() + { + proof.observe(path, true)?.ok_or(Error::Changed)?; + } + Ok(proof) + } + + #[cfg(feature = "encrypted-workspace")] + pub(super) fn empty_provisioning_candidate( + &self, + destination: &str, + ) -> Result { + rangoon_desktop::workspace_keys::WorkspaceId::parse(destination) + .map_err(|_| Error::RecoveryRequired)?; + let mut proof = self.binding_ancestry()?; + let legacy = self.legacy(); + proof.observe(&legacy, true)?.ok_or(Error::Changed)?; + if names(&legacy, 1)? != [std::ffi::OsString::from(DATABASE)] { + return Err(Error::RecoveryRequired); + } + Self::database(&mut proof, &legacy)?; + let managed = self.managed(); + proof.observe(&managed, true)?.ok_or(Error::Changed)?; + let mut expected = [CONTROL, BINDING, PARENT, OPERATIONS[0]] + .into_iter() + .map(std::ffi::OsString::from) + .collect::>(); + expected.sort(); + if names(&managed, 4)? != expected { + return Err(Error::RecoveryRequired); + } + let control = proof + .observe(&managed.join(CONTROL), false)? + .ok_or(Error::Changed)?; + let binding = proof + .observe(&managed.join(BINDING), false)? + .ok_or(Error::Changed)?; + let pending = proof + .observe(&managed.join(OPERATIONS[0]), false)? + .ok_or(Error::Changed)?; + if control.len() != 0 + || binding.len() == 0 + || binding.len() > 4096 + || pending.len() == 0 + || pending.len() > 4096 + || proof + .observe(&managed.join(OPERATIONS[1]), false)? + .is_some() + { + return Err(Error::RecoveryRequired); + } + let parent = managed.join(PARENT); + proof.observe(&parent, true)?.ok_or(Error::Changed)?; + if names(&parent, 1)? != [std::ffi::OsString::from(destination)] { + return Err(Error::RecoveryRequired); + } + let directory = parent.join(destination); + proof.observe(&directory, true)?.ok_or(Error::Changed)?; + if !names(&directory, 1)?.is_empty() { + return Err(Error::RecoveryRequired); + } + for name in [ + DATABASE, + "workspace.sqlite3-wal", + "workspace.sqlite3-shm", + "workspace.sqlite3-journal", + ] { + if proof.observe(&directory.join(name), false)?.is_some() { + return Err(Error::RecoveryRequired); + } + } + proof.check()?; + Ok(EmptyProvisioningProof { + roots: Self::new(self.anchor.clone()), + proof, + destination: destination.to_owned(), + }) + } + + /// Inspect only the fixed destination. A retained original may legitimately + /// diverge after conversion; it cannot replace destination validation. + pub(super) fn existing_binding(&self) -> Result { + let mut proof = self.binding_ancestry()?; + proof + .observe(&self.managed(), true)? + .ok_or(Error::Changed)?; + Self::managed_shape(&mut proof, &self.managed())?; + let result = BindingProof { + roots: Self::new(self.anchor.clone()), + proof, + kind: BindingKind::Complete, + }; + result.check_before()?; + Ok(result) + } + + /// The sole resumable setup residue: one empty existing control, no data, + /// binding, attempt, original workspace or unknown entry. + pub(super) fn setup_residue_binding(&self) -> Result { + let mut proof = self.binding_ancestry()?; + if proof.observe(&self.legacy(), true)?.is_some() + || proof + .observe(&self.anchor.join("workspace-adoption"), true)? + .is_some() + { + return Err(Error::RecoveryRequired); + } + proof + .observe(&self.managed(), true)? + .ok_or(Error::Changed)?; + if names(&self.managed(), 2)? != [std::ffi::OsString::from(CONTROL)] { + return Err(Error::RecoveryRequired); + } + if proof + .observe(&self.managed().join(CONTROL), false)? + .ok_or(Error::Changed)? + .len() + != 0 + { + return Err(Error::RecoveryRequired); + } + let result = BindingProof { + roots: Self::new(self.anchor.clone()), + proof, + kind: BindingKind::Residue, + }; + result.check_before()?; + Ok(result) + } + + /// Called only for an explicit native setup action. Creates metadata, never + /// a key, database or a replacement for an observed existing destination. + pub(super) fn fresh_binding(&self, mut inspection: Inspection) -> Result { + if self.revalidate(&inspection)? != State::FreshCandidate { + return Err(Error::Changed); + } + let mut proof = inspection.proof.take().ok_or(Error::Changed)?; + if proof + .observe(&self.anchor.join("workspace-adoption"), true)? + .is_some() + { + return Err(Error::RecoveryRequired); + } + // Missing native app-data ancestry is created one component at a time. + // Update only the node just created; any concurrent appearance refuses. + for index in 0..proof.nodes.len() { + let node = &proof.nodes[index]; + if node.metadata.is_some() || !self.anchor.starts_with(&node.path) { + continue; + } + let path = node.path.clone(); + proof.check()?; + create_startup_directory(&path)?; + proof.nodes[index].metadata = + Some(fs::symlink_metadata(&path).map_err(|_| Error::Unavailable)?); + proof.check()?; + } + let managed = self.managed(); + proof.check()?; + create_startup_directory(&managed)?; + let node = proof + .nodes + .iter_mut() + .find(|node| node.path == managed) + .ok_or(Error::Changed)?; + if node.metadata.is_some() { + return Err(Error::Changed); + } + node.metadata = Some(fs::symlink_metadata(&managed).map_err(|_| Error::Unavailable)?); + let result = BindingProof { + roots: Self::new(self.anchor.clone()), + proof, + kind: BindingKind::Fresh, + }; + result.check_before()?; + Ok(result) + } +} + +#[cfg(feature = "encrypted-workspace")] +impl EmptyProvisioningProof { + pub(super) fn check(&self) -> Result<(), Error> { + self.proof.check()?; + let current = self.roots.empty_provisioning_candidate(&self.destination)?; + current.proof.check()?; + self.proof.check() + } +} + +fn create_startup_directory(path: &Path) -> Result<(), Error> { + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(path).map_err(|_| Error::Changed)?; + let parent = path.parent().ok_or(Error::Changed)?; + fs::File::open(parent) + .and_then(|file| file.sync_all()) + .map_err(|_| Error::Unavailable) +} + +impl BindingProof { + pub(super) fn root(&self) -> PathBuf { + self.roots.managed() + } + pub(super) fn existing(&self) -> bool { + !matches!(self.kind, BindingKind::Fresh) + } + pub(super) fn check_before(&self) -> Result<(), Error> { + self.check(false) + } + pub(super) fn check_after(&self) -> Result<(), Error> { + self.check(true) + } + fn check(&self, bound: bool) -> Result<(), Error> { + self.proof.check()?; + match self.kind { + BindingKind::Complete => { + let mut observed = Proof { nodes: Vec::new() }; + StartupRoots::managed_shape(&mut observed, &self.root())?; + observed.check()?; + } + BindingKind::Fresh if !bound => { + if !names(&self.root(), 1)?.is_empty() { + return Err(Error::Changed); + } + } + BindingKind::Residue | BindingKind::Fresh => { + if names(&self.root(), 2)? != [std::ffi::OsString::from(CONTROL)] { + return Err(Error::Changed); + } + let metadata = + fs::symlink_metadata(self.root().join(CONTROL)).map_err(|_| Error::Changed)?; + if !regular(&metadata) || metadata.file_type().is_symlink() || metadata.len() != 0 { + return Err(Error::Changed); + } + } + } + self.proof.check() + } +} + +#[cfg(test)] +#[path = "workspace_startup_tests.rs"] +mod tests; diff --git a/apps/desktop/src/workspace_startup_host.rs b/apps/desktop/src/workspace_startup_host.rs new file mode 100644 index 0000000..35023b1 --- /dev/null +++ b/apps/desktop/src/workspace_startup_host.rs @@ -0,0 +1,1618 @@ +//! Source-free local startup messages. Exact matching is request bookkeeping; +//! only native closed-control custody and confirmation can permit an operation. +#[cfg(any(test, feature = "encrypted-workspace"))] +use rangoon_desktop::workspace_keys::WorkspaceId; +use serde::{Deserialize, Serialize}; +use tauri::{AppHandle, WebviewWindow, ipc::Request}; + +#[cfg(feature = "encrypted-workspace")] +use crate::workspace_close::{ + failure::WorkerCleanup, + setup::{Consent, dialog_consent}, +}; +#[cfg(feature = "encrypted-workspace")] +use tauri::Manager; +#[cfg(feature = "encrypted-workspace")] +use tauri_plugin_dialog::{DialogExt, MessageDialogButtons}; + +/// Native-only confirmation purpose. It is not an IPC action or an execution +/// approval; adoption additionally checks its retained capture and real lease. +#[cfg(feature = "encrypted-workspace")] +#[derive(Clone, Copy)] +pub(crate) enum StartupConfirmation { + CopyExisting, + VerifyCopy, + Recovery { + step: crate::workspace_adoption::RecoveryStep, + workspace: [u8; 64], + }, +} + +#[cfg(feature = "encrypted-workspace")] +pub(crate) fn native_startup_consent( + app: &AppHandle, + cleanup: &WorkerCleanup, + purpose: StartupConfirmation, +) -> Consent { + if !cleanup.alive() { + return Consent::Unavailable; + } + let Some(parent) = app.get_webview_window("main") else { + return Consent::Unavailable; + }; + let (title, question, affirmative) = match purpose { + StartupConfirmation::CopyExisting => ( + "Copy existing workspace?", + "Copy the reviewed existing Rangoon workspace to its fixed encrypted workspace and save a new key in this user's operating-system credential store? The original copy is kept. It remains unencrypted. Rangoon must close and reopen before verifying the encrypted copy. This does not authorize external calls or execution.".to_owned(), + "Copy workspace", + ), + StartupConfirmation::VerifyCopy => ( + "Verify encrypted copy?", + "Read the existing key from this user's operating-system credential store and compare the encrypted copy with the retained original workspace? A matching copy may be selected for later use. The original copy is kept. It remains unencrypted. Verification does not unlock the workbench or authorize external calls or execution.".to_owned(), + "Verify copy", + ), + StartupConfirmation::Recovery { step, workspace } => { + use crate::workspace_adoption::RecoveryStep; + let Ok(identity) = std::str::from_utf8(&workspace) else { + return Consent::Unavailable; + }; + if WorkspaceId::parse(identity).is_err() { + return Consent::Unavailable; + } + let (title, explanation, affirmative) = match step { + RecoveryStep::Inspect => ("Inspect interrupted copy?", "Read its existing operating-system key and inspect this fixed destination? This does not restore records or select it for use.", "Inspect copy"), + RecoveryStep::InitializeEmpty => ("Finish empty encrypted setup?", "Create only the missing empty encrypted database using the exact existing key and inspected unfinished attempt? No key is created or replaced. A separate unlock and restore are required before the retained original can be copied.", "Initialize empty copy"), + RecoveryStep::Reconcile => ("Reconcile copy metadata?", "Read the existing key again and reconcile the exact inspected CreateEmpty or Restore operation metadata? This may repair its ready marker and operation record. It does not replay that operation or restore records.", "Reconcile metadata"), + RecoveryStep::Unlock => ("Unlock copy for recovery?", "Read the existing key and unlock this fixed destination for native recovery inspection only? This does not open the workbench.", "Inspect destination"), + RecoveryStep::Restore => ("Resume copy into empty destination?", "Restore the retained original into this exact proven-empty encrypted destination, check complete parity and record the copy? No existing records may be overwritten. Close and reopen Rangoon afterward to verify it.", "Resume copy"), + RecoveryStep::RecordCopied => ("Record matching encrypted copy?", "Record the already matching complete encrypted copy without repeating Restore? Close and reopen Rangoon afterward to verify it.", "Record copy"), + RecoveryStep::CompleteSelection => ("Complete verified-copy selection?", "Read the existing key, recheck complete parity and append only the missing selection record, preserving its earlier verifier identity? This does not unlock the workbench.", "Complete selection"), + }; + (title, format!("Workspace {identity}\n\n{explanation}\n\nThe original copy is kept. It remains unencrypted. Recovery cannot create a replacement key and does not authorize external calls or execution."), affirmative) + } + }; + let result = app + .dialog() + .message(question) + .title(title) + .parent(&parent) + .buttons(MessageDialogButtons::OkCancelCustom( + affirmative.into(), + "Cancel".into(), + )) + .blocking_show_with_result(); + let consent = dialog_consent(result, affirmative, cleanup.alive()); + #[cfg(all(test, feature = "native-encrypted-qualification", target_os = "macos"))] + { + use crate::workspace_adoption::RecoveryStep; + let purpose = match purpose { + StartupConfirmation::CopyExisting => "copy_existing", + StartupConfirmation::VerifyCopy => "verify_copy", + StartupConfirmation::Recovery { step, .. } => match step { + RecoveryStep::Inspect => "recovery_inspect", + RecoveryStep::InitializeEmpty => "recovery_initialize_empty", + RecoveryStep::Reconcile => "recovery_reconcile", + RecoveryStep::Unlock => "recovery_unlock", + RecoveryStep::Restore => "recovery_restore", + RecoveryStep::RecordCopied => "recovery_record_copied", + RecoveryStep::CompleteSelection => "recovery_complete_selection", + }, + }; + crate::native_encrypted_qualification::consent_observed(purpose, consent); + } + consent +} + +const VIEW_SCHEMA: &str = "rangoon.workspace-startup.v1"; +const ACTION_SCHEMA: &str = "rangoon.workspace-startup-action.v1"; +const MAX_REQUEST: usize = 512; +#[cfg(any(test, feature = "encrypted-workspace"))] +const MAX_RESPONSE: usize = 2048; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Error { + Invalid, + #[cfg(any(test, feature = "encrypted-workspace"))] + Unavailable, +} + +#[derive(Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +#[cfg_attr( + not(feature = "encrypted-workspace"), + allow( + dead_code, + reason = "Frozen DTO vocabulary; builds without the backend can emit only unavailable" + ) +)] +pub(super) enum Stage { + Fresh, + LegacyFound, + ConversionReview, + Copying, + RestartRequired, + VerifyRequired, + RecoveryRequired, + Handoff, + Unavailable, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Action { + Setup, + ReviewConversion, + Copy, + Cancel, + Verify, + Recover, + Quit, +} + +#[derive(Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +#[cfg_attr( + not(feature = "encrypted-workspace"), + allow( + dead_code, + reason = "Frozen DTO vocabulary; builds without the backend cannot assess original data" + ) +)] +pub(super) enum Original { + Unassessed, + PresentUnencrypted, + NotVerified, + NotApplicable, +} + +#[derive(Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +#[allow( + dead_code, + reason = "Frozen local DTO vocabulary; the synchronous host does not fabricate intermediate copy progress" +)] +pub(super) enum CopyPhase { + CreatingDestination, + CopyingRecords, + CheckingCopy, + RecordingSelection, +} + +#[derive(Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr( + not(feature = "encrypted-workspace"), + allow( + dead_code, + reason = "Frozen DTO vocabulary; builds without the backend can report only backend unavailability" + ) +)] +pub(super) enum Diagnostic { + #[serde(rename = "startup_unavailable")] + Unavailable, + #[serde(rename = "backend_unavailable")] + BackendUnavailable, + #[serde(rename = "startup_layout_invalid")] + LayoutInvalid, + #[serde(rename = "startup_changed")] + Changed, + #[serde(rename = "startup_busy")] + Busy, + #[serde(rename = "startup_key_missing")] + #[allow( + dead_code, + reason = "Reserved diagnostic; unavailable custody must not imply proven key loss" + )] + KeyMissing, + #[serde(rename = "startup_copy_interrupted")] + #[allow( + dead_code, + reason = "Reserved diagnostic; uncertain recovery must not imply a proven interruption" + )] + CopyInterrupted, + #[serde(rename = "startup_recovery_required")] + RecoveryRequired, + #[serde(rename = "startup_control_unavailable")] + ControlUnavailable, +} + +#[cfg(any(test, feature = "encrypted-workspace"))] +pub(super) struct Identity { + startup_id: String, + attempt_id: String, + epoch: String, +} +#[cfg(any(test, feature = "encrypted-workspace"))] +impl std::fmt::Debug for Identity { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("StartupIdentity()") + } +} + +fn identity(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} +fn epoch(value: &str) -> bool { + !value.starts_with('0') + && value.len() <= 20 + && value + .parse::() + .is_ok_and(|number| number > 0 && number.to_string() == value) +} +#[cfg(any(test, feature = "encrypted-workspace"))] +impl Identity { + /// The supplied cycle must come from the native close coordinator. This + /// token never replaces that coordinator's actual current lease checks. + pub(crate) fn new(attempt_id: &str, cycle_epoch: &str) -> Result { + if !identity(attempt_id) || !epoch(cycle_epoch) { + return Err(Error::Invalid); + } + Ok(Self { + startup_id: WorkspaceId::generate() + .map_err(|_| Error::Unavailable)? + .as_hex(), + attempt_id: attempt_id.to_owned(), + epoch: cycle_epoch.to_owned(), + }) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ActionRequest { + schema_version: String, + startup_id: String, + attempt_id: String, + epoch: String, + #[cfg_attr( + not(feature = "encrypted-workspace"), + allow( + dead_code, + reason = "The action is validated but no backend exists to dispatch it" + ) + )] + action: Action, +} +impl std::fmt::Debug for ActionRequest { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("StartupAction()") + } +} +impl ActionRequest { + pub(super) fn parse(raw: &[u8]) -> Result { + if raw.len() > MAX_REQUEST { + return Err(Error::Invalid); + } + let value: Self = serde_json::from_slice(raw).map_err(|_| Error::Invalid)?; + if value.schema_version != ACTION_SCHEMA + || !identity(&value.startup_id) + || !identity(&value.attempt_id) + || !epoch(&value.epoch) + { + return Err(Error::Invalid); + } + Ok(value) + } + #[cfg(any(test, feature = "encrypted-workspace"))] + pub(super) fn matches(&self, expected: &Identity) -> bool { + self.startup_id == expected.startup_id + && self.attempt_id == expected.attempt_id + && self.epoch == expected.epoch + } + #[cfg(any(test, feature = "encrypted-workspace"))] + pub(crate) fn action(&self) -> Action { + self.action + } +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct View { + schema_version: &'static str, + state: Stage, + startup_id: Option, + attempt_id: Option, + epoch: Option, + actions: Vec, + copy_phase: Option, + retained_original: Original, + diagnostic: Option, +} +#[cfg(any(test, feature = "encrypted-workspace"))] +impl Stage { + fn actions(self) -> &'static [Action] { + use Action::*; + match self { + Self::Fresh => &[Setup, Quit], + Self::LegacyFound => &[ReviewConversion, Quit], + Self::ConversionReview => &[Copy, Cancel, Quit], + Self::Copying | Self::RestartRequired | Self::Unavailable => &[Quit], + Self::VerifyRequired => &[Verify, Quit], + Self::RecoveryRequired => &[Recover, Quit], + Self::Handoff => &[], + } + } + fn permits_original(self, original: Original) -> bool { + use Original::*; + match self { + Self::Fresh => original == NotApplicable, + Self::LegacyFound => original == Unassessed, + Self::ConversionReview | Self::Copying | Self::RestartRequired => { + original == PresentUnencrypted + } + Self::VerifyRequired => matches!(original, PresentUnencrypted | NotVerified), + Self::RecoveryRequired => original == NotVerified, + Self::Handoff => matches!(original, NotApplicable | PresentUnencrypted | NotVerified), + Self::Unavailable => matches!(original, NotApplicable | NotVerified), + } + } +} +impl View { + #[cfg(feature = "encrypted-workspace")] + fn completed_handoff(&self) -> bool { + self.schema_version == VIEW_SCHEMA + && self.state == Stage::Handoff + && self.startup_id.is_none() + && self.attempt_id.is_none() + && self.epoch.is_none() + && self.actions.is_empty() + && self.copy_phase.is_none() + && Stage::Handoff.permits_original(self.retained_original) + && self.diagnostic.is_none() + } + + /// A completed native routing handoff has no outstanding startup action. + /// It must not invent a still-current close cycle after normal unlock. + #[cfg(any(test, feature = "encrypted-workspace"))] + pub(super) fn handoff(retained_original: Original) -> Result { + if !Stage::Handoff.permits_original(retained_original) { + return Err(Error::Invalid); + } + let result = Self { + schema_version: VIEW_SCHEMA, + state: Stage::Handoff, + startup_id: None, + attempt_id: None, + epoch: None, + actions: Vec::new(), + copy_phase: None, + retained_original, + diagnostic: None, + }; + result.encode()?; + Ok(result) + } + pub(super) fn unavailable(diagnostic: Diagnostic) -> Self { + Self { + schema_version: VIEW_SCHEMA, + state: Stage::Unavailable, + startup_id: None, + attempt_id: None, + epoch: None, + actions: Vec::new(), + copy_phase: None, + retained_original: Original::NotApplicable, + diagnostic: Some(diagnostic), + } + } + #[cfg(any(test, feature = "encrypted-workspace"))] + pub(super) fn for_cycle( + identity: &Identity, + state: Stage, + retained_original: Original, + actions: &[Action], + copy_phase: Option, + diagnostic: Option, + ) -> Result { + let permitted = state.actions(); + let mut previous = None; + for action in actions { + let index = permitted + .iter() + .position(|candidate| candidate == action) + .ok_or(Error::Invalid)?; + if previous.is_some_and(|prior| index <= prior) { + return Err(Error::Invalid); + } + previous = Some(index); + } + if actions.len() > 3 + || (state == Stage::Copying) != copy_phase.is_some() + || !state.permits_original(retained_original) + { + return Err(Error::Invalid); + } + let result = Self { + schema_version: VIEW_SCHEMA, + state, + startup_id: Some(identity.startup_id.clone()), + attempt_id: Some(identity.attempt_id.clone()), + epoch: Some(identity.epoch.clone()), + actions: actions.to_vec(), + copy_phase, + retained_original, + diagnostic, + }; + result.encode()?; + Ok(result) + } + #[cfg(any(test, feature = "encrypted-workspace"))] + pub(super) fn encode(&self) -> Result, Error> { + let bytes = serde_json::to_vec(self).map_err(|_| Error::Invalid)?; + if bytes.len() > MAX_RESPONSE { + return Err(Error::Invalid); + } + Ok(bytes) + } +} + +#[cfg(test)] +#[path = "workspace_startup_host_tests.rs"] +mod tests; + +/// The host retains real closed-control custody with each native preview. It +/// does not own a second content store or any ordinary client-publication path. +#[cfg(feature = "encrypted-workspace")] +mod runtime { + use super::*; + use crate::{ + workspace_adoption::{ + self as adoption, Conversion, Recovery, RecoveryOutcome, Verification, + }, + workspace_close::{StartupFlight, WorkspaceClose}, + workspace_source_access::ControlKind, + workspace_startup::{BindingProof, Inspection, StartupRoots, State as RootState}, + }; + use rangoon_desktop::workspace_session::Vault; + use std::{ + path::PathBuf, + sync::{Arc, Mutex}, + }; + + enum Payload { + Fresh(Inspection), + Residue(BindingProof), + Legacy(Inspection), + Conversion(Box), + Verification(Box), + Recovery(Box), + } + struct Plan { + payload: Option, + flight: Option, + identity: Identity, + stage: Stage, + original: Original, + } + impl Plan { + fn view(&self) -> Result { + View::for_cycle( + &self.identity, + self.stage, + self.original, + self.stage.actions(), + None, + None, + ) + } + } + impl Drop for Plan { + fn drop(&mut self) { + // Drop capture/locked verification Owner before actual drain custody. + drop(self.payload.take()); + drop(self.flight.take()); + } + } + #[derive(Default)] + struct State { + busy: Option, + plan: Option, + outcome: Option, + terminal: bool, + quit_requested: bool, + } + struct Inner { + anchor: PathBuf, + close: WorkspaceClose, + state: Mutex, + } + #[derive(Clone)] + pub(crate) struct Host(Arc); + /// Move this into a real blocking cleanup worker. Its contained Flight + /// keeps exit drain pending until capture and Owner cleanup actually return. + pub(crate) struct Retired(Option); + impl Drop for Retired { + fn drop(&mut self) { + drop(self.0.take()); + } + } + struct Work { + host: Host, + token: String, + plan: Option, + disarmed: bool, + } + + impl Work { + fn current(&self) -> bool { + self.host + .0 + .state + .lock() + .is_ok_and(|state| !state.terminal && state.busy.as_deref() == Some(&self.token)) + } + fn finish(mut self, view: View) -> View { + if let Some(plan) = self.plan.as_mut() { + drop(plan.payload.take()); + } + let accepted = self.host.0.state.lock().is_ok_and(|mut state| { + if state.busy.as_deref() != Some(&self.token) { + return false; + } + let accepted = !state.terminal; + if accepted { + // A read before completed C0 has no retained plan to + // consume. Keep that refusal retryable on this same fixed + // Host; never replace managed state to recover timing. + state.outcome = if view.state == Stage::Unavailable && view.startup_id.is_none() + { + None + } else { + Some(view.clone()) + }; + } + state.busy = None; + accepted + }); + // The host no longer claims retained content before Flight's + // finalizer can call native drained-cleanup inspection. + drop(self.plan.take()); + self.disarmed = true; + if accepted { + view + } else { + View::unavailable(Diagnostic::ControlUnavailable) + } + } + fn retain(mut self, stage: Stage, original: Original, rotate: bool) -> Result { + if !self.current() { + return Err(Error::Unavailable); + } + let mut plan = self.plan.take().ok_or(Error::Unavailable)?; + let flight = plan.flight.as_ref().ok_or(Error::Unavailable)?; + flight.startup_permit().map_err(|_| Error::Unavailable)?; + if rotate { + let (id, epoch) = flight.startup_cycle().map_err(|_| Error::Unavailable)?; + plan.identity = Identity::new(&id, &epoch)?; + } + plan.stage = stage; + plan.original = original; + let view = plan.view()?; + let mut state = self.host.0.state.lock().map_err(|_| Error::Unavailable)?; + if state.terminal || state.busy.as_deref() != Some(&self.token) || state.plan.is_some() + { + drop(state); + self.plan = Some(plan); + return Err(Error::Unavailable); + } + state.plan = Some(plan); + state.busy = None; + self.disarmed = true; + Ok(view) + } + fn unavailable(self, diagnostic: Diagnostic) -> View { + let view = self + .plan + .as_ref() + .and_then(|plan| { + let original = if plan.original == Original::NotApplicable { + Original::NotApplicable + } else { + Original::NotVerified + }; + View::for_cycle( + &plan.identity, + Stage::Unavailable, + original, + &[Action::Quit], + None, + Some(diagnostic), + ) + .ok() + }) + .unwrap_or_else(|| View::unavailable(diagnostic)); + self.finish(view) + } + } + impl Drop for Work { + fn drop(&mut self) { + if self.disarmed { + return; + } + if let Some(plan) = self.plan.as_mut() { + drop(plan.payload.take()); + } + match self.host.0.state.lock() { + Ok(mut state) => { + if state.busy.as_deref() == Some(&self.token) { + state.busy = None; + state.terminal = true; + } + } + Err(poisoned) => poisoned.into_inner().terminal = true, + } + drop(self.plan.take()); + } + } + impl Host { + /// Native application-data anchor only. Construction performs no I/O, + /// directory creation, credential lookup or content publication. + pub(crate) fn new(anchor: PathBuf, close: WorkspaceClose) -> Self { + Self(Arc::new(Inner { + anchor, + close, + state: Mutex::new(State::default()), + })) + } + fn claim(&self) -> Result { + let token = WorkspaceId::generate() + .map_err(|_| Error::Unavailable)? + .as_hex(); + let mut state = self.0.state.lock().map_err(|_| Error::Unavailable)?; + if state.terminal || state.busy.is_some() { + return Err(Error::Unavailable); + } + state.busy = Some(token.clone()); + Ok(Work { + host: self.clone(), + token, + plan: state.plan.take(), + disarmed: false, + }) + } + /// Called before terminal close/failure cancellation, not from ordinary + /// C0/C1 cleanup. Never drop the returned custody under this mutex. + pub(crate) fn retire(&self) -> Option { + let mut state = match self.0.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.terminal = true; + state.outcome = None; + state.plan.take().map(|plan| Retired(Some(plan))) + } + /// Ordinary Lock may keep only a completed, idle, non-effectful handoff. + /// Classification and retirement share the claim/finish mutex; an + /// active Work must see terminal retirement before it can publish. + pub(crate) fn retire_for_ordinary_close(&self) -> Option { + let (mut state, healthy) = match self.0.state.lock() { + Ok(state) => (state, true), + Err(error) => (error.into_inner(), false), + }; + if healthy + && !state.terminal + && state.busy.is_none() + && state.plan.is_none() + && state.outcome.as_ref().is_some_and(View::completed_handoff) + { + return None; + } + state.terminal = true; + state.outcome = None; + state.plan.take().map(|plan| Retired(Some(plan))) + } + pub(crate) fn cleanup_consistent(&self, drained: bool) -> bool { + self.0 + .state + .lock() + .is_ok_and(|state| !drained || (state.plan.is_none() && state.busy.is_none())) + } + pub(crate) fn quit_requested(&self) -> bool { + self.0.state.lock().is_ok_and(|state| state.quit_requested) + } + /// The waiter services a real renderer acknowledgment independently of + /// this worker. Its boolean alone permits nothing: the actual permit is + /// rechecked afterward. No host mutex spans the wait or native work. + pub(crate) fn status( + &self, + cleanup: impl FnOnce(bool) -> bool + Send + 'static, + wait_for_ack: impl FnOnce(&WorkspaceClose) -> bool, + ) -> View { + if let Ok(state) = self.0.state.lock() { + if state.terminal { + return View::unavailable(Diagnostic::ControlUnavailable); + } + if let Some(view) = &state.outcome { + return view.clone(); + } + } + let Ok(mut work) = self.claim() else { + return View::unavailable(Diagnostic::Busy); + }; + if let Some(plan) = work.plan.as_mut() { + let checked = (|| { + let permit = plan + .flight + .as_ref() + .ok_or(Error::Unavailable)? + .startup_permit() + .map_err(|_| Error::Unavailable)?; + match plan.payload.as_mut().ok_or(Error::Unavailable)? { + Payload::Fresh(proof) | Payload::Legacy(proof) => { + StartupRoots::new(self.0.anchor.clone()) + .revalidate(proof) + .map_err(|_| Error::Unavailable)?; + } + Payload::Residue(proof) => { + proof.check_before().map_err(|_| Error::Unavailable)?; + } + Payload::Conversion(value) => value + .revalidate_native(&permit) + .map_err(|_| Error::Unavailable)?, + Payload::Verification(value) => value + .revalidate_native(&permit) + .map_err(|_| Error::Unavailable)?, + Payload::Recovery(value) => value + .revalidate_native(&permit) + .map_err(|_| Error::Unavailable)?, + } + Ok::<_, Error>((plan.stage, plan.original)) + })(); + return match checked { + Ok((stage, original)) => work + .retain(stage, original, false) + .unwrap_or_else(|_| View::unavailable(Diagnostic::ControlUnavailable)), + Err(_) => work.unavailable(Diagnostic::Changed), + }; + } + let started = (|| { + let (id, epoch) = self + .0 + .close + .locked_startup_cycle() + .map_err(|_| Error::Unavailable)?; + let flight = self + .0 + .close + .start_control_for(&id, &epoch, ControlKind::Startup, cleanup) + .map_err(|_| Error::Unavailable)?; + let (id, epoch) = flight.startup_cycle().map_err(|_| Error::Unavailable)?; + let identity = Identity::new(&id, &epoch)?; + work.plan = Some(Plan { + payload: None, + flight: Some(flight), + identity, + stage: Stage::Unavailable, + original: Original::NotApplicable, + }); + if !wait_for_ack(&self.0.close) || !work.current() { + return Err(Error::Unavailable); + } + work.plan + .as_ref() + .and_then(|plan| plan.flight.as_ref()) + .ok_or(Error::Unavailable)? + .startup_permit() + .map_err(|_| Error::Unavailable)?; + Ok::<_, Error>(()) + })(); + if started.is_err() { + return work.unavailable(Diagnostic::ControlUnavailable); + } + self.classify(work) + } + fn classify(&self, mut work: Work) -> View { + let roots = StartupRoots::new(self.0.anchor.clone()); + let route = adoption::route(&self.0.anchor); + match route { + adoption::Route::Selected(selection) => { + work.plan.as_mut().unwrap().original = Original::NotVerified; + let matches = work + .plan + .as_ref() + .and_then(|plan| plan.flight.as_ref()) + .and_then(|flight| flight.startup_permit().ok()) + .is_some_and(|permit| selection.original_matches(&permit) == Ok(true)); + let original = if matches { + Original::PresentUnencrypted + } else { + Original::NotVerified + }; + return self.bind_existing(work, Some(selection), original); + } + adoption::Route::VerifyRequired => { + let prepared = (|| { + let permit = work + .plan + .as_ref() + .and_then(|plan| plan.flight.as_ref()) + .ok_or(Error::Unavailable)? + .startup_permit() + .map_err(|_| Error::Unavailable)?; + Verification::prepare_native(self.0.anchor.clone(), &permit) + .map_err(|_| Error::Unavailable) + })(); + return match prepared { + Ok(value) => { + work.plan.as_mut().unwrap().payload = + Some(Payload::Verification(Box::new(value))); + work.retain(Stage::VerifyRequired, Original::PresentUnencrypted, true) + .unwrap_or_else(|_| { + View::unavailable(Diagnostic::ControlUnavailable) + }) + } + Err(_) => work.unavailable(Diagnostic::RecoveryRequired), + }; + } + adoption::Route::RestartRequired => { + work.plan.as_mut().unwrap().original = Original::NotVerified; + let matches = work + .plan + .as_ref() + .and_then(|plan| plan.flight.as_ref()) + .and_then(|flight| flight.startup_permit().ok()) + .is_some_and(|permit| { + adoption::original_matches(&self.0.anchor, &permit) == Ok(true) + }); + if !matches { + return work.unavailable(Diagnostic::Changed); + } + let plan = work.plan.as_ref().unwrap(); + let view = View::for_cycle( + &plan.identity, + Stage::RestartRequired, + Original::PresentUnencrypted, + &[Action::Quit], + None, + None, + ); + return work.finish( + view.unwrap_or_else(|_| View::unavailable(Diagnostic::Unavailable)), + ); + } + adoption::Route::RecoveryRequired => { + work.plan.as_mut().unwrap().original = Original::NotVerified; + return work.unavailable(Diagnostic::RecoveryRequired); + } + adoption::Route::Recovery(recovery) => { + return self.offer_recovery(work, recovery); + } + adoption::Route::Unavailable => return work.unavailable(Diagnostic::Unavailable), + adoption::Route::NoAttempt => {} + } + let inspection = roots.inspect(); + let (payload, stage, original) = match inspection.state() { + RootState::FreshCandidate => ( + Payload::Fresh(inspection), + Stage::Fresh, + Original::NotApplicable, + ), + RootState::LegacyCandidate => ( + Payload::Legacy(inspection), + Stage::LegacyFound, + Original::Unassessed, + ), + RootState::ManagedCandidate => { + return self.bind_existing(work, None, Original::NotApplicable); + } + _ => match roots.setup_residue_binding() { + Ok(proof) => ( + Payload::Residue(proof), + Stage::Fresh, + Original::NotApplicable, + ), + Err(_) => return work.unavailable(Diagnostic::LayoutInvalid), + }, + }; + work.plan.as_mut().unwrap().payload = Some(payload); + work.retain(stage, original, true) + .unwrap_or_else(|_| View::unavailable(Diagnostic::ControlUnavailable)) + } + fn offer_recovery(&self, mut work: Work, recovery: Recovery) -> View { + work.plan.as_mut().unwrap().original = Original::NotVerified; + let prepared = (|| { + let permit = work + .plan + .as_ref() + .and_then(|plan| plan.flight.as_ref()) + .ok_or(Error::Unavailable)? + .startup_permit() + .map_err(|_| Error::Unavailable)?; + recovery + .bind_native(&permit) + .map_err(|_| Error::Unavailable) + })(); + match prepared { + Ok(recovery) => { + work.plan.as_mut().unwrap().payload = + Some(Payload::Recovery(Box::new(recovery))); + work.retain(Stage::RecoveryRequired, Original::NotVerified, true) + .unwrap_or_else(|_| View::unavailable(Diagnostic::ControlUnavailable)) + } + Err(_) => work.unavailable(Diagnostic::RecoveryRequired), + } + } + fn bind_existing( + &self, + mut work: Work, + selection: Option, + original: Original, + ) -> View { + let checked = (|| { + if !work.current() { + return Err(Error::Unavailable); + } + let roots = StartupRoots::new(self.0.anchor.clone()); + if let Some(selected) = &selection { + selected.check().map_err(|_| Error::Unavailable)?; + } + let proof = roots.existing_binding().map_err(|_| Error::Unavailable)?; + let flight = work + .plan + .as_mut() + .and_then(|plan| plan.flight.as_mut()) + .ok_or(Error::Unavailable)?; + flight.startup_permit().map_err(|_| Error::Unavailable)?; + flight + .bind_locked_owner(proof) + .map_err(|_| Error::Unavailable)?; + if let Some(selected) = &selection { + flight + .check_bound_identity(selected.destination()) + .map_err(|_| Error::Unavailable)?; + selected.check().map_err(|_| Error::Unavailable)?; + } + Ok::<_, Error>(()) + })(); + if checked.is_err() { + // A bound destination whose selected proof changed cannot be + // exposed through a later direct ordinary unlock request. + self.0.close.fail_startup(); + return work.unavailable(Diagnostic::RecoveryRequired); + } + drop(selection); + work.finish( + View::handoff(original) + .unwrap_or_else(|_| View::unavailable(Diagnostic::Unavailable)), + ) + } + pub(crate) fn action( + &self, + request: ActionRequest, + vault: &impl Vault, + mut confirm: impl FnMut(StartupConfirmation) -> Consent, + ) -> View { + // A completed Copy may retain only a restart/quit observation, no + // source preview or Flight. Match that exact outcome before Quit. + if let Ok(mut state) = self.0.state.lock() + && !state.terminal + && state.busy.is_none() + && let Some(view) = &state.outcome + { + let view = view.clone(); + let quit = request.action() == Action::Quit + && view.actions.contains(&Action::Quit) + && view.startup_id.as_deref() == Some(&request.startup_id) + && view.attempt_id.as_deref() == Some(&request.attempt_id) + && view.epoch.as_deref() == Some(&request.epoch); + if quit { + state.quit_requested = true; + state.terminal = true; + state.outcome = None; + return View::unavailable(Diagnostic::ControlUnavailable); + } + return view; + } + let Ok(mut work) = self.claim() else { + return View::unavailable(Diagnostic::Busy); + }; + let valid = work.plan.as_ref().is_some_and(|plan| { + request.matches(&plan.identity) && plan.stage.actions().contains(&request.action()) + }); + if !valid { + // A malformed/stale action cannot consume a valid retained plan. + if let Some(plan) = work.plan.as_ref() { + let (stage, original) = (plan.stage, plan.original); + return work + .retain(stage, original, false) + .unwrap_or_else(|_| View::unavailable(Diagnostic::ControlUnavailable)); + } + return work.unavailable(Diagnostic::ControlUnavailable); + } + if request.action() == Action::Quit { + if let Ok(mut state) = self.0.state.lock() { + state.quit_requested = true; + } + let _ = self.retire(); + return work.unavailable(Diagnostic::ControlUnavailable); + } + let result = (|| { + if !work.current() { + return Err(Error::Unavailable); + } + let plan = work.plan.as_mut().ok_or(Error::Unavailable)?; + let flight = plan.flight.as_mut().ok_or(Error::Unavailable)?; + let permit = flight.startup_permit().map_err(|_| Error::Unavailable)?; + let payload = plan.payload.take().ok_or(Error::Unavailable)?; + match (request.action(), payload) { + (Action::Setup, Payload::Fresh(inspection)) => { + let proof = StartupRoots::new(self.0.anchor.clone()) + .fresh_binding(inspection) + .map_err(|_| Error::Unavailable)?; + permit.checkpoint().map_err(|_| Error::Unavailable)?; + flight + .bind_locked_owner(proof) + .map_err(|_| Error::Unavailable)?; + Ok(None) + } + (Action::Setup, Payload::Residue(proof)) => { + permit.checkpoint().map_err(|_| Error::Unavailable)?; + flight + .bind_locked_owner(proof) + .map_err(|_| Error::Unavailable)?; + Ok(None) + } + (Action::ReviewConversion, Payload::Legacy(inspection)) => { + StartupRoots::new(self.0.anchor.clone()) + .revalidate(&inspection) + .map_err(|_| Error::Unavailable)?; + let conversion = Conversion::prepare_native(self.0.anchor.clone(), &permit) + .map_err(|_| Error::Unavailable)?; + plan.payload = Some(Payload::Conversion(Box::new(conversion))); + Ok(Some(( + Stage::ConversionReview, + Original::PresentUnencrypted, + ))) + } + (Action::Cancel, Payload::Conversion(value)) => { + drop(value); + Ok(Some((Stage::LegacyFound, Original::Unassessed))) + } + (Action::Copy, Payload::Conversion(value)) => { + match value + .confirm_native(&permit, || confirm(StartupConfirmation::CopyExisting)) + .map_err(|_| Error::Unavailable)? + { + Some((value, consent)) => { + value + .copy_native(consent, vault, &permit) + .map_err(|_| Error::Unavailable)?; + Ok(Some((Stage::RestartRequired, Original::PresentUnencrypted))) + } + None => Ok(Some((Stage::LegacyFound, Original::Unassessed))), + } + } + (Action::Verify, Payload::Verification(value)) => { + match value + .confirm_native(&permit, || confirm(StartupConfirmation::VerifyCopy)) + .map_err(|_| Error::Unavailable)? + { + Some((value, consent)) => { + value + .select_native(consent, vault, &permit) + .map_err(|_| Error::Unavailable)?; + Ok(None) + } + None => { + // Explicit Cancel retires the old one-shot + // preview, not the valid Copied journal. Rebuild + // native custody without reading a key; a later + // attempt still needs its own confirmation. + let verification = + Verification::prepare_native(self.0.anchor.clone(), &permit) + .map_err(|_| Error::Unavailable)?; + plan.payload = Some(Payload::Verification(Box::new(verification))); + Ok(Some((Stage::VerifyRequired, Original::PresentUnencrypted))) + } + } + } + (Action::Recover, Payload::Recovery(value)) => { + match value + .recover_native(&permit, vault, |step, destination| { + let Ok(workspace) = destination.as_bytes().try_into() else { + return Consent::Unavailable; + }; + confirm(StartupConfirmation::Recovery { step, workspace }) + }) + .map_err(|_| Error::Unavailable)? + { + RecoveryOutcome::Cancelled => { + Ok(Some((Stage::RecoveryRequired, Original::NotVerified))) + } + RecoveryOutcome::Copied => { + Ok(Some((Stage::RestartRequired, Original::PresentUnencrypted))) + } + RecoveryOutcome::Selected => Ok(None), + } + } + _ => Err(Error::Invalid), + } + })(); + match result { + Ok(Some((Stage::RecoveryRequired, _))) => match adoption::route(&self.0.anchor) { + adoption::Route::Recovery(recovery) => self.offer_recovery(work, recovery), + _ => work.unavailable(Diagnostic::RecoveryRequired), + }, + Ok(Some((Stage::LegacyFound, original))) => { + let proof = StartupRoots::new(self.0.anchor.clone()).inspect(); + if proof.state() != RootState::LegacyCandidate { + return work.unavailable(Diagnostic::Changed); + } + work.plan.as_mut().unwrap().payload = Some(Payload::Legacy(proof)); + work.retain(Stage::LegacyFound, original, true) + .unwrap_or_else(|_| View::unavailable(Diagnostic::ControlUnavailable)) + } + Ok(Some((Stage::RestartRequired, original))) => { + let plan = work.plan.as_ref().unwrap(); + let view = View::for_cycle( + &plan.identity, + Stage::RestartRequired, + original, + &[Action::Quit], + None, + None, + ) + .unwrap_or_else(|_| View::unavailable(Diagnostic::Unavailable)); + work.finish(view) + } + Ok(Some((stage, original))) => work + .retain(stage, original, true) + .unwrap_or_else(|_| View::unavailable(Diagnostic::ControlUnavailable)), + Ok(None) => { + if matches!(request.action(), Action::Verify | Action::Recover) { + match adoption::route(&self.0.anchor) { + adoption::Route::Selected(selected) => self.bind_existing( + work, + Some(selected), + Original::PresentUnencrypted, + ), + _ => work.unavailable(Diagnostic::RecoveryRequired), + } + } else if request.action() == Action::Setup { + work.finish( + View::handoff(Original::NotApplicable) + .unwrap_or_else(|_| View::unavailable(Diagnostic::Unavailable)), + ) + } else { + work.unavailable(Diagnostic::RecoveryRequired) + } + } + Err(_) => work.unavailable(Diagnostic::RecoveryRequired), + } + } + } + #[cfg(test)] + mod ordinary_close_state_tests { + use super::*; + + fn host_with_handoff(original: Original) -> Host { + let source = crate::SourceAccess::legacy(crate::Gate::new(), Ok(PathBuf::new())); + let host = Host::new(PathBuf::new(), WorkspaceClose::new(source)); + host.0.state.lock().unwrap().outcome = Some(View::handoff(original).unwrap()); + host + } + + #[test] + fn only_exact_completed_handoffs_survive_repeated_ordinary_close() { + for original in [ + Original::NotApplicable, + Original::PresentUnencrypted, + Original::NotVerified, + ] { + let host = host_with_handoff(original); + for _ in 0..3 { + assert!(host.retire_for_ordinary_close().is_none()); + let state = host.0.state.lock().unwrap(); + assert!(!state.terminal); + assert!(state.outcome.as_ref().unwrap().completed_handoff()); + } + } + } + + #[test] + fn partial_or_effectful_handoffs_are_terminally_retired() { + let mutations: [fn(&mut View); 9] = [ + |view| view.schema_version = "not-the-startup-contract", + |view| view.state = Stage::Fresh, + |view| view.startup_id = Some("a".repeat(64)), + |view| view.attempt_id = Some("b".repeat(64)), + |view| view.epoch = Some("1".to_owned()), + |view| view.actions.push(Action::Quit), + |view| view.copy_phase = Some(CopyPhase::CreatingDestination), + |view| view.retained_original = Original::Unassessed, + |view| view.diagnostic = Some(Diagnostic::Unavailable), + ]; + for mutate in mutations { + let host = host_with_handoff(Original::NotApplicable); + mutate(host.0.state.lock().unwrap().outcome.as_mut().unwrap()); + assert!(host.retire_for_ordinary_close().is_none()); + let state = host.0.state.lock().unwrap(); + assert!(state.terminal); + assert!(state.outcome.is_none()); + } + } + + #[test] + fn busy_work_cannot_publish_an_old_handoff_after_ordinary_close() { + let host = host_with_handoff(Original::NotApplicable); + let work = host.claim().unwrap(); + assert!(work.current()); + assert!(host.retire_for_ordinary_close().is_none()); + assert!(!work.current()); + assert!(!host.cleanup_consistent(true)); + let result = work.finish(View::handoff(Original::NotApplicable).unwrap()); + assert!(result.state == Stage::Unavailable); + assert!(host.cleanup_consistent(true)); + let state = host.0.state.lock().unwrap(); + assert!(state.terminal); + assert!(state.outcome.is_none()); + } + + #[test] + fn ordinary_close_fences_a_handoff_after_its_last_flight_check() { + struct UnusedVault; + impl Vault for UnusedVault { + type Slot = rangoon_desktop::workspace_keys::OsSlot; + + fn open( + &self, + _: &WorkspaceId, + ) -> Result { + panic!("this lifecycle regression must not access a vault") + } + } + + fn value(close: &WorkspaceClose) -> serde_json::Value { + serde_json::to_value(close.inspect(|_| true)).unwrap() + } + + fn acknowledge(close: &WorkspaceClose) -> serde_json::Value { + let view = value(close); + let bytes = serde_json::to_vec(&serde_json::json!({ + "schemaVersion": "rangoon.workspace-purge-ack.v1", + "attemptId": view["attemptId"], + "epoch": view["epoch"], + })) + .unwrap(); + serde_json::to_value(close.acknowledge(&bytes, |_| true)).unwrap() + } + + let gate = crate::Gate::new(); + let source = + crate::SourceAccess::managed_deferred(gate.clone(), PathBuf::new(), UnusedVault); + let close = WorkspaceClose::new(source.clone()); + let host = Host::new(PathBuf::new(), close.clone()); + close.begin(|_| true); + assert_eq!(acknowledge(&close)["state"], "locked"); + let (id, epoch) = close.locked_startup_cycle().unwrap(); + let flight = close + .start_control_for(&id, &epoch, ControlKind::Startup, |_| true) + .unwrap(); + assert_eq!(acknowledge(&close)["state"], "closing"); + let (id, epoch) = flight.startup_cycle().unwrap(); + let mut work = host.claim().unwrap(); + work.plan = Some(Plan { + payload: None, + flight: Some(flight), + identity: Identity::new(&id, &epoch).unwrap(), + stage: Stage::Fresh, + original: Original::NotApplicable, + }); + + let (checked, checked_rx) = std::sync::mpsc::channel(); + let (release, release_rx) = std::sync::mpsc::channel(); + let worker = std::thread::spawn(move || { + // Pause at the actual Work commit boundary after its last live + // Flight check, without a production test hook or fake lease. + work.plan + .as_ref() + .unwrap() + .flight + .as_ref() + .unwrap() + .startup_permit() + .unwrap(); + assert!(work.current()); + checked.send(()).unwrap(); + release_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap(); + work.finish(View::handoff(Original::NotApplicable).unwrap()) + }); + checked_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap(); + + let retired = host.retire_for_ordinary_close(); + assert!(retired.is_none()); + assert_eq!( + serde_json::to_value(close.begin(|_| true)).unwrap()["state"], + "closing" + ); + assert!(!host.cleanup_consistent(true)); + assert_eq!(value(&close)["state"], "closing"); + assert!( + gate.begin(rangoon_desktop::workspace_lifecycle::Lane::Read) + .is_err() + ); + assert!(serde_json::to_value(source.request_view()).unwrap()["clientId"].is_null()); + + // Complete between source cancellation and detached-custody drop: + // the old final-check/publication gap must not restore Handoff. + release.send(()).unwrap(); + assert!(worker.join().unwrap().state == Stage::Unavailable); + drop(retired); + assert!(host.cleanup_consistent(true)); + assert_eq!(value(&close)["state"], "closing"); + assert_eq!(acknowledge(&close)["state"], "locked"); + assert!( + gate.begin(rangoon_desktop::workspace_lifecycle::Lane::Read) + .is_err() + ); + assert!(serde_json::to_value(source.request_view()).unwrap()["clientId"].is_null()); + for _ in 0..2 { + assert!(host.retire_for_ordinary_close().is_none()); + let state = host.0.state.lock().unwrap(); + assert!(state.terminal); + assert!(state.busy.is_none()); + assert!(state.outcome.is_none()); + assert!(state.plan.is_none()); + } + } + + #[test] + fn ordinary_close_without_a_completed_outcome_remains_terminal() { + let host = host_with_handoff(Original::NotApplicable); + host.0.state.lock().unwrap().outcome = None; + assert!(host.retire_for_ordinary_close().is_none()); + assert!(host.0.state.lock().unwrap().terminal); + } + + #[test] + fn terminal_retirement_wins_a_race_with_idle_handoff_retention() { + let host = host_with_handoff(Original::NotApplicable); + let barrier = Arc::new(std::sync::Barrier::new(3)); + let ordinary_host = host.clone(); + let ordinary_barrier = Arc::clone(&barrier); + let ordinary = std::thread::spawn(move || { + ordinary_barrier.wait(); + assert!(ordinary_host.retire_for_ordinary_close().is_none()); + }); + let terminal_host = host.clone(); + let terminal_barrier = Arc::clone(&barrier); + let terminal = std::thread::spawn(move || { + terminal_barrier.wait(); + assert!(terminal_host.retire().is_none()); + }); + barrier.wait(); + ordinary.join().unwrap(); + terminal.join().unwrap(); + for _ in 0..2 { + assert!(host.retire_for_ordinary_close().is_none()); + let state = host.0.state.lock().unwrap(); + assert!(state.terminal); + assert!(state.outcome.is_none()); + } + } + + #[test] + fn poisoned_mutex_cannot_preserve_an_otherwise_completed_handoff() { + let host = host_with_handoff(Original::NotApplicable); + let worker_host = host.clone(); + assert!( + std::thread::spawn(move || { + let _guard = worker_host.0.state.lock().unwrap(); + panic!("poison the disposable host mutex"); + }) + .join() + .is_err() + ); + assert!(host.retire_for_ordinary_close().is_none()); + let state = match host.0.state.lock() { + Ok(_) => panic!("expected a poisoned host mutex"), + Err(error) => error.into_inner(), + }; + assert!(state.terminal); + assert!(state.outcome.is_none()); + } + } +} + +#[cfg(feature = "encrypted-workspace")] +pub(super) use runtime::Host; + +/// Terminal lifecycle hooks call this after closing source admission. Moving +/// retained custody to a real blocking task keeps the event loop responsive; +/// dropping its JoinHandle does not count as completion or release the Flight. +pub(crate) fn retire_for_close(app: &tauri::AppHandle) { + #[cfg(feature = "encrypted-workspace")] + if let Some(host) = app.try_state::() + && let Some(retired) = host.retire() + { + tauri::async_runtime::spawn_blocking(move || drop(retired)); + } + #[cfg(not(feature = "encrypted-workspace"))] + let _ = app; +} + +/// Cleanup custody only; an empty guard conveys no approval or permission. +/// Keep this named guard alive until ordinary close has fenced admission. +pub(crate) struct OrdinaryCloseRetirement { + #[cfg(feature = "encrypted-workspace")] + retained: Option, +} + +impl Drop for OrdinaryCloseRetirement { + fn drop(&mut self) { + #[cfg(feature = "encrypted-workspace")] + if let Some(retired) = self.retained.take() { + tauri::async_runtime::spawn_blocking(move || drop(retired)); + } + } +} + +/// Classify before cancellation can unblock Work and publish a late handoff. +/// The caller then closes admission before dropping this cleanup guard. No +/// Host mutex is held across source closure, callbacks or custody destruction. +pub(crate) fn retire_for_ordinary_close(app: &tauri::AppHandle) -> OrdinaryCloseRetirement { + #[cfg(not(feature = "encrypted-workspace"))] + let _ = app; + OrdinaryCloseRetirement { + #[cfg(feature = "encrypted-workspace")] + retained: app + .try_state::() + .and_then(|host| host.retire_for_ordinary_close()), + } +} + +pub(super) fn cleanup_consistent(app: &tauri::AppHandle, drained: bool) -> bool { + #[cfg(feature = "encrypted-workspace")] + { + app.try_state::() + .is_none_or(|host| host.cleanup_consistent(drained)) + } + #[cfg(not(feature = "encrypted-workspace"))] + { + let _ = (app, drained); + true + } +} + +#[cfg(feature = "encrypted-workspace")] +fn wait_for_startup_ack(close: &crate::WorkspaceClose, cleanup: &WorkerCleanup) -> bool { + let started = std::time::Instant::now(); + while cleanup.alive() && started.elapsed() < std::time::Duration::from_secs(30) { + match close.startup_acknowledged() { + Ok(true) => return true, + Ok(false) => std::thread::sleep(std::time::Duration::from_millis(25)), + Err(_) => return false, + } + } + false +} + +fn main_window(label: &str) -> Result<(), ()> { + (label == "main").then_some(()).ok_or(()) +} + +fn empty_object(body: &tauri::ipc::InvokeBody) -> Result<(), ()> { + matches!(body, tauri::ipc::InvokeBody::Json(value) + if value.as_object().is_some_and(|object| object.is_empty())) + .then_some(()) + .ok_or(()) +} + +fn request_quit( + label: &str, + body: &tauri::ipc::InvokeBody, + request_exit: impl FnOnce(), +) -> Result<(), ()> { + main_window(label)?; + empty_object(body)?; + request_exit(); + Ok(()) +} + +/// Failure cards may have no current plan identity. Request the same exit path +/// as native window close; this does not prove drain or force process exit. +#[tauri::command] +pub(crate) fn workspace_startup_quit( + app: AppHandle, + window: WebviewWindow, + request: Request<'_>, +) -> Result<(), ()> { + request_quit(window.label(), request.body(), || { + app.exit(crate::workspace_close::failure::CLEAN_EXIT_CODE); + }) +} + +/// Source-free commands have their own bounded native lifecycle path. They do +/// not accept a content client, workspace path, credential or replacement data. +#[tauri::command] +pub(crate) async fn workspace_startup_status( + app: AppHandle, + window: WebviewWindow, + request: Request<'_>, +) -> Result { + main_window(window.label())?; + empty_object(request.body())?; + #[cfg(feature = "encrypted-workspace")] + { + let Some(host) = app.try_state::().map(|state| state.inner().clone()) else { + return Ok(View::unavailable(Diagnostic::BackendUnavailable)); + }; + let Some(cleanup) = app + .try_state::() + .map(|state| state.inner().clone()) + .filter(WorkerCleanup::alive) + else { + return Ok(View::unavailable(Diagnostic::ControlUnavailable)); + }; + let finalizer = cleanup.clone(); + let view = tauri::async_runtime::spawn_blocking(move || { + host.status( + move |drained| finalizer.cleanup(drained), + |close| wait_for_startup_ack(close, &cleanup), + ) + }) + .await + .map_err(|_| ())?; + #[cfg(all(test, feature = "native-encrypted-qualification", target_os = "macos"))] + crate::native_encrypted_qualification::startup_observed(&app, &view); + Ok(view) + } + #[cfg(not(feature = "encrypted-workspace"))] + { + let _ = app; + Ok(View::unavailable(Diagnostic::BackendUnavailable)) + } +} + +#[tauri::command] +pub(crate) async fn workspace_startup_action( + app: AppHandle, + window: WebviewWindow, + request: Request<'_>, +) -> Result { + main_window(window.label())?; + let tauri::ipc::InvokeBody::Raw(raw) = request.body() else { + return Err(()); + }; + let action = ActionRequest::parse(raw).map_err(|_| ())?; + #[cfg(feature = "encrypted-workspace")] + { + let Some(host) = app.try_state::().map(|state| state.inner().clone()) else { + return Ok(View::unavailable(Diagnostic::BackendUnavailable)); + }; + let Some(cleanup) = app + .try_state::() + .map(|state| state.inner().clone()) + .filter(WorkerCleanup::alive) + else { + return Ok(View::unavailable(Diagnostic::ControlUnavailable)); + }; + tauri::async_runtime::spawn_blocking(move || { + let vault = crate::workspace_native_bootstrap::native_startup_vault(&app); + let view = host.action(action, &vault, |purpose| { + native_startup_consent(&app, &cleanup, purpose) + }); + #[cfg(all(test, feature = "native-encrypted-qualification", target_os = "macos"))] + crate::native_encrypted_qualification::startup_observed(&app, &view); + if host.quit_requested() { + // This requests the existing native exit coordinator. It does + // not bypass callback drain, cleanup or the exit-code proof. + app.exit(crate::workspace_close::failure::CLEAN_EXIT_CODE); + } + view + }) + .await + .map_err(|_| ()) + } + #[cfg(not(feature = "encrypted-workspace"))] + { + let _ = (app, action); + Ok(View::unavailable(Diagnostic::BackendUnavailable)) + } +} diff --git a/apps/desktop/src/workspace_startup_host_tests.rs b/apps/desktop/src/workspace_startup_host_tests.rs new file mode 100644 index 0000000..f3338ee --- /dev/null +++ b/apps/desktop/src/workspace_startup_host_tests.rs @@ -0,0 +1,459 @@ +use super::*; +use serde_json::{Value, json}; + +const ACTION_SCHEMA: &str = "rangoon.workspace-startup-action.v1"; +const VIEW_SCHEMA: &str = "rangoon.workspace-startup.v1"; + +#[test] +fn startup_commands_are_limited_to_the_exact_main_window_label() { + assert!(main_window("main").is_ok()); + for label in ["", "Main", "main/child", "model-review", "splash"] { + assert!(main_window(label).is_err()); + } +} + +#[test] +fn source_free_quit_requires_main_and_empty_json_before_requesting_exit() { + use std::cell::Cell; + use tauri::ipc::InvokeBody; + let exits = Cell::new(0); + for label in ["", "Main", "main/child", "model-review", "splash"] { + assert!( + request_quit(label, &InvokeBody::Json(json!({})), || exits + .set(exits.get() + 1)) + .is_err() + ); + } + for body in [ + InvokeBody::Raw(b"{}".to_vec()), + InvokeBody::Json(json!(null)), + InvokeBody::Json(json!([])), + InvokeBody::Json(json!({"action": "quit"})), + InvokeBody::Json(json!({"path": "not-accepted"})), + InvokeBody::Json(json!({"exitCode": 0})), + ] { + assert!(request_quit("main", &body, || exits.set(exits.get() + 1)).is_err()); + } + assert_eq!(exits.get(), 0); + request_quit("main", &InvokeBody::Json(json!({})), || { + exits.set(exits.get() + 1) + }) + .unwrap(); + assert_eq!(exits.get(), 1); +} + +fn attempt() -> String { + "a".repeat(64) +} + +fn action_body( + schema_version: &str, + startup_id: &str, + attempt_id: &str, + epoch: &str, + action: &str, +) -> Vec { + serde_json::to_vec(&json!({ + "schemaVersion": schema_version, + "startupId": startup_id, + "attemptId": attempt_id, + "epoch": epoch, + "action": action, + })) + .unwrap() +} + +fn identity() -> Identity { + Identity::new(&attempt(), "1").unwrap() +} + +fn request_for(identity: &Identity, action: &str) -> ActionRequest { + ActionRequest::parse(&action_body( + ACTION_SCHEMA, + &identity.startup_id, + &identity.attempt_id, + &identity.epoch, + action, + )) + .unwrap() +} + +#[test] +fn action_request_requires_the_exact_closed_schema_and_all_fields_in_any_order() { + let identity = identity(); + let reordered = format!( + r#"{{"action":"quit","epoch":"{}","attemptId":"{}","startupId":"{}","schemaVersion":"{}"}}"#, + identity.epoch, identity.attempt_id, identity.startup_id, ACTION_SCHEMA + ); + let request = ActionRequest::parse(reordered.as_bytes()).unwrap(); + assert!(request.matches(&identity)); + assert_eq!(request.action(), Action::Quit); + assert_eq!(format!("{request:?}"), "StartupAction()"); + + let valid = json!({ + "schemaVersion": ACTION_SCHEMA, + "startupId": &identity.startup_id, + "attemptId": &identity.attempt_id, + "epoch": &identity.epoch, + "action": "quit", + }); + for field in ["schemaVersion", "startupId", "attemptId", "epoch", "action"] { + let mut missing = valid.clone(); + missing.as_object_mut().unwrap().remove(field); + assert!(ActionRequest::parse(&serde_json::to_vec(&missing).unwrap()).is_err()); + } + for invalid in [ + json!({"schemaVersion": "other", "startupId": &identity.startup_id, "attemptId": &identity.attempt_id, "epoch": &identity.epoch, "action": "quit"}), + json!({"schemaVersion": ACTION_SCHEMA, "startupId": &identity.startup_id, "attemptId": &identity.attempt_id, "epoch": &identity.epoch, "action": "quit", "extra": true}), + ] { + assert!(ActionRequest::parse(&serde_json::to_vec(&invalid).unwrap()).is_err()); + } +} + +#[test] +fn action_request_rejects_duplicate_unknown_malformed_and_wrongly_typed_values() { + let identity = identity(); + for duplicate in [ + format!( + r#"{{"schemaVersion":"{ACTION_SCHEMA}","startupId":"{}","startupId":"{}","attemptId":"{}","epoch":"1","action":"quit"}}"#, + identity.startup_id, identity.startup_id, identity.attempt_id + ), + format!( + r#"{{"schemaVersion":"{ACTION_SCHEMA}","startupId":"{}","attemptId":"{}","epoch":"1","action":"quit","unexpected":true,"unexpected":false}}"#, + identity.startup_id, identity.attempt_id + ), + ] { + assert!(ActionRequest::parse(duplicate.as_bytes()).is_err()); + } + assert!(ActionRequest::parse(b"\xff").is_err()); + for value in [ + json!({"schemaVersion": ACTION_SCHEMA, "startupId": null, "attemptId": &identity.attempt_id, "epoch": "1", "action": "quit"}), + json!({"schemaVersion": ACTION_SCHEMA, "startupId": &identity.startup_id, "attemptId": [], "epoch": "1", "action": "quit"}), + json!({"schemaVersion": ACTION_SCHEMA, "startupId": &identity.startup_id, "attemptId": &identity.attempt_id, "epoch": 1, "action": "quit"}), + json!({"schemaVersion": ACTION_SCHEMA, "startupId": &identity.startup_id, "attemptId": &identity.attempt_id, "epoch": "1", "action": null}), + ] { + assert!(ActionRequest::parse(&serde_json::to_vec(&value).unwrap()).is_err()); + } +} + +#[test] +fn action_request_accepts_all_closed_actions_and_only_canonical_identity_fields() { + let startup_id = "b".repeat(64); + let attempt_id = attempt(); + for action in [ + "setup", + "review_conversion", + "copy", + "cancel", + "verify", + "recover", + "quit", + ] { + assert!( + ActionRequest::parse(&action_body( + ACTION_SCHEMA, + &startup_id, + &attempt_id, + "1", + action, + )) + .is_ok() + ); + } + for invalid in [ + "a".repeat(63), + "A".repeat(64), + format!("{}g", "a".repeat(63)), + ] { + assert!( + ActionRequest::parse(&action_body( + ACTION_SCHEMA, + &invalid, + &attempt_id, + "1", + "quit", + )) + .is_err() + ); + assert!( + ActionRequest::parse(&action_body( + ACTION_SCHEMA, + &startup_id, + &invalid, + "1", + "quit", + )) + .is_err() + ); + } + for invalid in ["0", "00", "01", "+1", "18446744073709551616"] { + assert!( + ActionRequest::parse(&action_body( + ACTION_SCHEMA, + &startup_id, + &attempt_id, + invalid, + "quit", + )) + .is_err() + ); + } + assert!( + ActionRequest::parse(&action_body( + ACTION_SCHEMA, + &startup_id, + &attempt_id, + &u64::MAX.to_string(), + "quit", + )) + .is_ok() + ); +} + +#[test] +fn action_request_accepts_exactly_512_raw_bytes_and_rejects_513() { + let identity = identity(); + let mut raw = action_body( + ACTION_SCHEMA, + &identity.startup_id, + &identity.attempt_id, + &identity.epoch, + "quit", + ); + assert!(raw.len() < 512); + raw.resize(512, b' '); + assert!(ActionRequest::parse(&raw).is_ok()); + raw.push(b' '); + assert!(ActionRequest::parse(&raw).is_err()); +} + +#[test] +fn identity_rotation_and_request_matching_compare_all_opaque_bookkeeping_fields() { + let first = identity(); + let second = Identity::new(&attempt(), "1").unwrap(); + assert_ne!(first.startup_id, second.startup_id); + assert_eq!(first.attempt_id, second.attempt_id); + assert_eq!(first.epoch, second.epoch); + assert_eq!(format!("{first:?}"), "StartupIdentity()"); + + assert!(request_for(&first, "quit").matches(&first)); + for request in [ + action_body( + ACTION_SCHEMA, + &second.startup_id, + &first.attempt_id, + &first.epoch, + "quit", + ), + action_body( + ACTION_SCHEMA, + &first.startup_id, + &"c".repeat(64), + &first.epoch, + "quit", + ), + action_body( + ACTION_SCHEMA, + &first.startup_id, + &first.attempt_id, + "2", + "quit", + ), + ] { + assert!(!ActionRequest::parse(&request).unwrap().matches(&first)); + } +} + +#[test] +fn views_allow_only_ordered_state_actions_originals_and_copying_phases() { + let identity = identity(); + let cases = [ + ( + Stage::Fresh, + Original::NotApplicable, + &[Action::Setup, Action::Quit][..], + None, + ), + ( + Stage::LegacyFound, + Original::Unassessed, + &[Action::ReviewConversion, Action::Quit][..], + None, + ), + ( + Stage::ConversionReview, + Original::PresentUnencrypted, + &[Action::Copy, Action::Cancel, Action::Quit][..], + None, + ), + ( + Stage::Copying, + Original::PresentUnencrypted, + &[Action::Quit][..], + Some(CopyPhase::CopyingRecords), + ), + ( + Stage::RestartRequired, + Original::PresentUnencrypted, + &[Action::Quit][..], + None, + ), + ( + Stage::VerifyRequired, + Original::NotVerified, + &[Action::Verify, Action::Quit][..], + None, + ), + ( + Stage::RecoveryRequired, + Original::NotVerified, + &[Action::Quit][..], + None, + ), + (Stage::Handoff, Original::NotApplicable, &[][..], None), + ( + Stage::Unavailable, + Original::NotApplicable, + &[Action::Quit][..], + None, + ), + ]; + for (stage, original, actions, phase) in cases { + let view = View::for_cycle(&identity, stage, original, actions, phase, None).unwrap(); + let value: Value = serde_json::from_slice(&view.encode().unwrap()).unwrap(); + assert_eq!(value["state"], serde_json::to_value(stage).unwrap()); + assert_eq!(value["actions"], serde_json::to_value(actions).unwrap()); + } + for (stage, original, actions, phase) in [ + ( + Stage::Fresh, + Original::NotApplicable, + &[Action::Quit, Action::Setup][..], + None, + ), + ( + Stage::Fresh, + Original::NotApplicable, + &[Action::Setup, Action::Setup][..], + None, + ), + ( + Stage::Fresh, + Original::NotApplicable, + &[Action::Copy][..], + None, + ), + ( + Stage::Fresh, + Original::Unassessed, + &[Action::Setup][..], + None, + ), + ( + Stage::Copying, + Original::PresentUnencrypted, + &[Action::Quit][..], + None, + ), + ( + Stage::Fresh, + Original::NotApplicable, + &[Action::Quit][..], + Some(CopyPhase::CheckingCopy), + ), + ] { + assert!(View::for_cycle(&identity, stage, original, actions, phase, None).is_err()); + } +} + +#[test] +fn unavailable_view_has_no_identity_or_actions_and_views_encode_only_closed_fields() { + let identity = identity(); + let unavailable = View::unavailable(Diagnostic::BackendUnavailable); + let unavailable_value: Value = serde_json::from_slice(&unavailable.encode().unwrap()).unwrap(); + assert_eq!(unavailable_value["schemaVersion"], VIEW_SCHEMA); + assert_eq!(unavailable_value["startupId"], Value::Null); + assert_eq!(unavailable_value["attemptId"], Value::Null); + assert_eq!(unavailable_value["epoch"], Value::Null); + assert_eq!(unavailable_value["actions"], json!([])); + + let view = View::for_cycle( + &identity, + Stage::Copying, + Original::PresentUnencrypted, + &[Action::Quit], + Some(CopyPhase::CheckingCopy), + Some(Diagnostic::Busy), + ) + .unwrap(); + let encoded = view.encode().unwrap(); + assert!(encoded.len() <= 2048); + let value: Value = serde_json::from_slice(&encoded).unwrap(); + let mut keys = value + .as_object() + .unwrap() + .keys() + .cloned() + .collect::>(); + keys.sort(); + assert_eq!( + keys, + [ + "actions", + "attemptId", + "copyPhase", + "diagnostic", + "epoch", + "retainedOriginal", + "schemaVersion", + "startupId", + "state", + ] + ); + for forbidden in ["root", "source", "key", "customPayload"] { + assert!(value.get(forbidden).is_none()); + } +} + +#[test] +fn terminal_handoff_has_no_cycle_or_effectful_fields() { + for original in [ + Original::NotApplicable, + Original::PresentUnencrypted, + Original::NotVerified, + ] { + let handoff = View::handoff(original).unwrap(); + let value: Value = serde_json::from_slice(&handoff.encode().unwrap()).unwrap(); + assert_eq!(value["state"], "handoff"); + assert_eq!(value["startupId"], Value::Null); + assert_eq!(value["attemptId"], Value::Null); + assert_eq!(value["epoch"], Value::Null); + assert_eq!(value["actions"], json!([])); + assert_eq!(value["copyPhase"], Value::Null); + assert_eq!( + value["retainedOriginal"], + serde_json::to_value(original).unwrap() + ); + assert_eq!(value["diagnostic"], Value::Null); + } + assert_eq!( + View::handoff(Original::Unassessed).err(), + Some(Error::Invalid) + ); +} + +#[test] +fn view_encoding_cap_rejects_test_mutated_output_without_claiming_valid_input_reachability() { + let identity = identity(); + let mut view = View::for_cycle( + &identity, + Stage::Fresh, + Original::NotApplicable, + &[Action::Setup], + None, + None, + ) + .unwrap(); + view.startup_id = Some("x".repeat(2049)); + assert_eq!(view.encode(), Err(Error::Invalid)); +} diff --git a/apps/desktop/src/workspace_startup_owner_tests.rs b/apps/desktop/src/workspace_startup_owner_tests.rs new file mode 100644 index 0000000..976f83c --- /dev/null +++ b/apps/desktop/src/workspace_startup_owner_tests.rs @@ -0,0 +1,232 @@ +//! Existing-only Owner acquisition tests. No vault or workspace data is used. +use super::*; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, + sync::atomic::{AtomicUsize, Ordering}, + time::{SystemTime, UNIX_EPOCH}, +}; + +static NEXT: AtomicUsize = AtomicUsize::new(0); + +struct TestRoot(PathBuf); + +impl TestRoot { + fn new(label: &str) -> Self { + #[cfg(unix)] + let parent = PathBuf::from("/tmp").canonicalize().unwrap(); + #[cfg(not(unix))] + let parent = std::env::temp_dir().canonicalize().unwrap(); + let root = parent.join(format!( + "rangoon-owner-{label}-{}-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir(&root).unwrap(); + Self(root.canonicalize().unwrap()) + } + + fn control(&self) -> PathBuf { + self.0.join("encrypted-workspace.lock") + } + + fn managed(&self) -> PathBuf { + self.0.join("managed") + } +} + +impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn assert_error(actual: Result, expected: Error) { + match actual { + Ok(_) => panic!("expected {expected:?}"), + Err(error) => assert_eq!(error, expected), + } +} + +fn assert_regular_root_bytes(root: &Path, expected: &[(&str, &[u8])]) { + let actual = fs::read_dir(root) + .unwrap() + .map(|entry| { + let entry = entry.unwrap(); + let name = entry.file_name().into_string().unwrap(); + let metadata = fs::symlink_metadata(entry.path()).unwrap(); + assert!(metadata.is_file(), "{name} must stay a regular file"); + (name, fs::read(entry.path()).unwrap()) + }) + .collect::>(); + let expected = expected + .iter() + .map(|(name, bytes)| ((*name).to_owned(), bytes.to_vec())) + .collect::>(); + assert_eq!(actual, expected); +} + +fn assert_control_only(root: &Path) { + assert_regular_root_bytes(root, &[("encrypted-workspace.lock", b"")]); + for absent in [ + "encrypted-workspace.binding", + "encrypted-workspaces", + "workspace.sqlite3", + "operation", + ] { + assert!(!root.join(absent).exists(), "{absent} must not be created"); + } +} + +#[test] +fn acquire_existing_missing_root_or_control_never_creates_a_path() { + let fixture = TestRoot::new("missing"); + let missing_root = fixture.managed(); + assert!(!missing_root.exists()); + assert_error( + Owner::acquire_existing(missing_root.clone()), + Error::Unavailable, + ); + assert!(!missing_root.exists()); + assert_regular_root_bytes(&fixture.0, &[]); + + fs::create_dir(&missing_root).unwrap(); + assert_error( + Owner::acquire_existing(missing_root.clone()), + Error::Unavailable, + ); + assert_regular_root_bytes(&missing_root, &[]); +} + +#[test] +fn acquire_existing_locks_only_an_existing_zero_byte_regular_control_and_drop_releases_it() { + let root = TestRoot::new("valid"); + fs::write(root.control(), b"").unwrap(); + assert_control_only(&root.0); + + let first = Owner::acquire_existing(root.0.clone()).unwrap(); + assert!(!first.is_unlocked()); + assert_control_only(&root.0); + assert_error(Owner::acquire_existing(root.0.clone()), Error::Busy); + assert_control_only(&root.0); + + drop(first); + let second = Owner::acquire_existing(root.0.clone()).unwrap(); + assert!(!second.is_unlocked()); + drop(second); + assert_control_only(&root.0); +} + +#[test] +fn acquire_existing_rejects_nonzero_control_without_changing_its_bytes() { + let root = TestRoot::new("nonzero"); + let bytes = b"preexisting nonempty control"; + fs::write(root.control(), bytes).unwrap(); + + assert_error( + Owner::acquire_existing(root.0.clone()), + Error::InvalidBinding, + ); + assert_regular_root_bytes(&root.0, &[("encrypted-workspace.lock", bytes)]); +} + +#[test] +fn acquire_existing_detects_replaced_root_before_any_workspace_setup() { + let fixture = TestRoot::new("replaced-root"); + let managed = fixture.managed(); + fs::create_dir(&managed).unwrap(); + fs::write(managed.join("encrypted-workspace.lock"), b"").unwrap(); + let mut owner = Owner::acquire_existing(managed.clone()).unwrap(); + + let retained = fixture.0.join("retained-root"); + fs::rename(&managed, &retained).unwrap(); + fs::create_dir(&managed).unwrap(); + fs::write(managed.join("encrypted-workspace.lock"), b"").unwrap(); + + assert_error(owner.prepare_create_empty(), Error::Unavailable); + assert_control_only(&managed); + assert_control_only(&retained); + drop(owner); +} + +#[test] +fn acquire_existing_detects_replaced_control_before_any_workspace_setup() { + let root = TestRoot::new("replaced-control"); + fs::write(root.control(), b"").unwrap(); + let mut owner = Owner::acquire_existing(root.0.clone()).unwrap(); + + let retained = root.0.join("retained-control"); + fs::rename(root.control(), &retained).unwrap(); + fs::write(root.control(), b"").unwrap(); + + assert_error(owner.prepare_create_empty(), Error::InvalidBinding); + assert_regular_root_bytes( + &root.0, + &[("encrypted-workspace.lock", b""), ("retained-control", b"")], + ); + assert!(!root.0.join("encrypted-workspace.binding").exists()); + assert!(!root.0.join("encrypted-workspaces").exists()); + drop(owner); +} + +#[cfg(unix)] +#[test] +fn acquire_existing_rejects_linked_directory_and_special_controls_without_repair() { + use std::os::unix::{ + fs::{FileTypeExt, symlink}, + net::UnixListener, + }; + + let root = TestRoot::new("symlink"); + let target = root.0.join("target"); + fs::write(&target, b"").unwrap(); + symlink(&target, root.control()).unwrap(); + assert_error( + Owner::acquire_existing(root.0.clone()), + Error::InvalidBinding, + ); + assert!( + fs::symlink_metadata(root.control()) + .unwrap() + .file_type() + .is_symlink() + ); + assert_eq!(fs::read(&target).unwrap(), b""); + + let root = TestRoot::new("hardlink"); + fs::write(root.control(), b"").unwrap(); + let alias = root.0.join("control-alias"); + fs::hard_link(root.control(), &alias).unwrap(); + assert_error( + Owner::acquire_existing(root.0.clone()), + Error::InvalidBinding, + ); + assert_eq!(fs::read(root.control()).unwrap(), b""); + assert_eq!(fs::read(alias).unwrap(), b""); + + let root = TestRoot::new("directory"); + fs::create_dir(root.control()).unwrap(); + assert_error( + Owner::acquire_existing(root.0.clone()), + Error::InvalidBinding, + ); + assert!(fs::symlink_metadata(root.control()).unwrap().is_dir()); + + let root = TestRoot::new("socket"); + let _listener = UnixListener::bind(root.control()).unwrap(); + assert_error( + Owner::acquire_existing(root.0.clone()), + Error::InvalidBinding, + ); + assert!( + fs::symlink_metadata(root.control()) + .unwrap() + .file_type() + .is_socket() + ); +} diff --git a/apps/desktop/src/workspace_startup_tests.rs b/apps/desktop/src/workspace_startup_tests.rs new file mode 100644 index 0000000..8865eac --- /dev/null +++ b/apps/desktop/src/workspace_startup_tests.rs @@ -0,0 +1,775 @@ +use super::*; + +use std::{ + fs, + path::{Path, PathBuf}, + sync::atomic::{AtomicUsize, Ordering}, + time::{SystemTime, UNIX_EPOCH}, +}; + +const DATABASE: &str = "workspace.sqlite3"; +const CONTROL: &str = "encrypted-workspace.lock"; +const BINDING: &str = "encrypted-workspace.binding"; +const PARENT: &str = "encrypted-workspaces"; + +static NEXT_ROOT: AtomicUsize = AtomicUsize::new(0); + +struct TestDir { + root: PathBuf, +} + +impl TestDir { + fn new(label: &str) -> Self { + let parent = std::env::temp_dir().canonicalize().unwrap(); + let root = parent.join(format!( + "rangoon-startup-{label}-{}-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(), + NEXT_ROOT.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir(&root).unwrap(); + Self { + root: root.canonicalize().unwrap(), + } + } + + fn join(&self, name: &str) -> PathBuf { + self.root.join(name) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } +} + +fn write(path: impl AsRef, bytes: &[u8]) { + fs::write(path, bytes).unwrap(); +} + +fn legacy(root: &Path, bytes: &[u8]) { + let directory = root.join("source-workspace"); + fs::create_dir(&directory).unwrap(); + write(directory.join(DATABASE), bytes); +} + +fn managed(root: &Path) { + let directory = root.join("managed-workspace"); + fs::create_dir(&directory).unwrap(); + write(directory.join(CONTROL), b""); + write(directory.join(BINDING), b"fake-binding"); + let parent = directory.join(PARENT); + fs::create_dir(&parent).unwrap(); + let workspace = parent.join("a".repeat(64)); + fs::create_dir(&workspace).unwrap(); + write(workspace.join(DATABASE), b"fake-database-metadata-only"); +} + +fn assert_state(root: &Path, expected: State) { + assert_eq!( + StartupRoots::new(root.to_owned()).inspect().state(), + expected + ); +} + +#[cfg(unix)] +#[test] +fn missing_and_empty_anchors_are_fresh_without_filesystem_mutation() { + let directory = TestDir::new("fresh"); + let missing = directory.join("missing-anchor"); + assert_state(&missing, State::FreshCandidate); + assert!(!missing.exists()); + assert!(fs::read_dir(&directory.root).unwrap().next().is_none()); + + assert_state(&directory.root, State::FreshCandidate); + assert!(fs::read_dir(&directory.root).unwrap().next().is_none()); +} + +#[cfg(unix)] +#[test] +fn legacy_candidate_uses_nonempty_database_metadata_only() { + let directory = TestDir::new("legacy"); + legacy(&directory.root, b"not-a-sqlite-database"); + + assert_state(&directory.root, State::LegacyCandidate); + assert_eq!( + fs::read(directory.join("source-workspace").join(DATABASE)).unwrap(), + b"not-a-sqlite-database" + ); +} + +#[cfg(unix)] +#[test] +fn managed_candidate_accepts_only_bounded_shape_presence() { + let directory = TestDir::new("managed"); + managed(&directory.root); + + assert_state(&directory.root, State::ManagedCandidate); + assert_eq!( + fs::read(directory.join("managed-workspace").join(BINDING)).unwrap(), + b"fake-binding" + ); +} + +#[cfg(unix)] +#[test] +fn both_known_layouts_are_mixed() { + let directory = TestDir::new("mixed"); + legacy(&directory.root, b"legacy-only-metadata"); + managed(&directory.root); + + assert_state(&directory.root, State::Mixed); +} + +#[cfg(unix)] +#[test] +fn partial_empty_sidecar_or_unknown_layouts_require_recovery() { + let empty_legacy = TestDir::new("empty-legacy"); + fs::create_dir(empty_legacy.join("source-workspace")).unwrap(); + assert_state(&empty_legacy.root, State::RecoveryRequired); + + let zero_database = TestDir::new("zero-database"); + legacy(&zero_database.root, b""); + assert_state(&zero_database.root, State::RecoveryRequired); + + let sidecar = TestDir::new("legacy-sidecar"); + legacy(&sidecar.root, b"metadata"); + write( + sidecar + .join("source-workspace") + .join("workspace.sqlite3-wal"), + b"sidecar", + ); + assert_state(&sidecar.root, State::RecoveryRequired); + + let orphan = TestDir::new("managed-orphan"); + let managed_root = orphan.join("managed-workspace"); + fs::create_dir(&managed_root).unwrap(); + write(managed_root.join(CONTROL), b""); + write(managed_root.join(BINDING), b"binding"); + fs::create_dir(managed_root.join(PARENT)).unwrap(); + assert_state(&orphan.root, State::RecoveryRequired); + + let unknown = TestDir::new("unknown-managed-entry"); + managed(&unknown.root); + write( + unknown.join("managed-workspace").join("unexpected"), + b"unknown", + ); + assert_state(&unknown.root, State::RecoveryRequired); +} + +#[cfg(unix)] +#[test] +fn candidate_inspection_creates_no_cipher_key_or_owner_artifacts() { + let directory = TestDir::new("inert-candidates"); + let missing = directory.join("missing"); + assert_state(&missing, State::FreshCandidate); + assert!(!missing.exists()); + + legacy(&directory.root, b"metadata"); + assert_state(&directory.root, State::LegacyCandidate); + assert!(!directory.join("cipher").exists()); + assert!(!directory.join("key").exists()); + assert!(!directory.join("owner").exists()); + + fs::remove_dir_all(directory.join("source-workspace")).unwrap(); + managed(&directory.root); + assert_state(&directory.root, State::ManagedCandidate); + assert!(!directory.join("cipher").exists()); + assert!(!directory.join("key").exists()); + assert!(!directory.join("owner").exists()); +} + +#[cfg(all(unix, target_family = "unix"))] +#[test] +fn symlink_and_hardlink_paths_require_recovery_without_touching_targets() { + use std::os::unix::fs::symlink; + + let root_link = TestDir::new("root-link"); + let root_target = root_link.join("target"); + fs::create_dir(&root_target).unwrap(); + write(root_target.join("sentinel"), b"root-target"); + let alias = root_link.join("alias"); + symlink(&root_target, &alias).unwrap(); + assert_state(&alias, State::RecoveryRequired); + assert_eq!( + fs::read(root_target.join("sentinel")).unwrap(), + b"root-target" + ); + + let ancestor_link = TestDir::new("ancestor-link"); + let physical = ancestor_link.join("physical"); + fs::create_dir(&physical).unwrap(); + let anchor = physical.join("anchor"); + fs::create_dir(&anchor).unwrap(); + write(physical.join("sentinel"), b"ancestor-target"); + let linked_parent = ancestor_link.join("linked-parent"); + symlink(&physical, &linked_parent).unwrap(); + assert_state(&linked_parent.join("anchor"), State::RecoveryRequired); + assert_eq!( + fs::read(physical.join("sentinel")).unwrap(), + b"ancestor-target" + ); + + let file_link = TestDir::new("database-link"); + let target = file_link.join("database-target"); + write(&target, b"database-target"); + fs::create_dir(file_link.join("source-workspace")).unwrap(); + symlink(&target, file_link.join("source-workspace").join(DATABASE)).unwrap(); + assert_state(&file_link.root, State::RecoveryRequired); + assert_eq!(fs::read(&target).unwrap(), b"database-target"); + + let hard_link = TestDir::new("database-hardlink"); + legacy(&hard_link.root, b"database-target"); + let database = hard_link.join("source-workspace").join(DATABASE); + let alias = hard_link.join("database-alias"); + fs::hard_link(&database, &alias).unwrap(); + assert_state(&hard_link.root, State::RecoveryRequired); + assert_eq!(fs::read(&alias).unwrap(), b"database-target"); +} + +#[cfg(unix)] +#[test] +fn stale_preview_rejects_root_replacement_and_new_layout() { + let replaced = TestDir::new("replaced-root"); + let anchor = replaced.join("anchor"); + fs::create_dir(&anchor).unwrap(); + legacy(&anchor, b"metadata"); + let roots = StartupRoots::new(anchor.clone()); + let inspection = roots.inspect(); + assert_eq!(inspection.state(), State::LegacyCandidate); + fs::remove_dir_all(&anchor).unwrap(); + fs::create_dir(&anchor).unwrap(); + legacy(&anchor, b"replacement-metadata"); + assert_eq!(roots.revalidate(&inspection), Err(Error::Changed)); + + let new_layout = TestDir::new("new-layout"); + let roots = StartupRoots::new(new_layout.root.clone()); + let inspection = roots.inspect(); + assert_eq!(inspection.state(), State::FreshCandidate); + managed(&new_layout.root); + assert_eq!(roots.revalidate(&inspection), Err(Error::Changed)); +} + +#[cfg(all(unix, target_family = "unix"))] +#[test] +fn held_control_lock_still_reports_shape_only_without_mutation() { + use std::fs::OpenOptions; + + let directory = TestDir::new("held-control-lock"); + managed(&directory.root); + let control = directory.join("managed-workspace").join(CONTROL); + let lock = OpenOptions::new() + .read(true) + .write(true) + .open(&control) + .unwrap(); + lock.lock().unwrap(); + assert_state(&directory.root, State::ManagedCandidate); + assert_eq!(fs::metadata(&control).unwrap().len(), 0); +} + +#[cfg(unix)] +#[test] +fn debug_output_is_fixed_and_redacts_paths() { + let directory = TestDir::new("debug"); + let roots = StartupRoots::new(directory.root.clone()); + let inspection = roots.inspect(); + + assert_eq!(format!("{roots:?}"), "StartupRoots()"); + assert_eq!(format!("{inspection:?}"), "Inspection()"); + assert!(!format!("{roots:?}").contains(directory.root.to_string_lossy().as_ref())); +} + +#[cfg(unix)] +fn saved_legacy(directory: &TestDir) -> Workspace { + let workspace = Workspace::new(directory.join("source-workspace")); + let report = rangoon_import::analyze( + "AGENTS.md", + b"# Private startup marker\nRetain the exact original source.\n", + ) + .unwrap(); + workspace.save(&report).unwrap(); + workspace +} + +#[cfg(unix)] +#[test] +fn retained_real_capture_revalidates_and_cancel_clears_all_accessors() { + let directory = TestDir::new("real-capture"); + saved_legacy(&directory); + let database = directory.join("source-workspace").join(DATABASE); + let before = fs::read(&database).unwrap(); + let roots = StartupRoots::new(directory.root.clone()); + assert_eq!(roots.inspect().state(), State::LegacyCandidate); + let mut retained = roots.capture_existing().unwrap(); + assert_eq!(retained.schema_version().unwrap(), 1); + assert_eq!(retained.inventory().unwrap().sources, 1); + assert!(!retained.digest().unwrap().is_empty()); + assert!( + retained + .archive() + .unwrap() + .starts_with(b"RANGOON-BACKUP-V2\n") + ); + assert_eq!(format!("{retained:?}"), "RetainedSource()"); + retained.revalidate().unwrap(); + assert_eq!(fs::read(&database).unwrap(), before); + assert_eq!( + fs::read_dir(directory.join("source-workspace")) + .unwrap() + .count(), + 1 + ); + + retained.cancel(); + assert_eq!(retained.schema_version(), Err(Error::Changed)); + assert_eq!(retained.inventory(), Err(Error::Changed)); + assert_eq!(retained.digest(), Err(Error::Changed)); + assert_eq!(retained.archive(), Err(Error::Changed)); + assert_eq!(retained.revalidate(), Err(Error::Changed)); +} + +#[cfg(unix)] +#[test] +fn retained_capture_refuses_domain_drift_and_new_managed_layout() { + let directory = TestDir::new("real-drift"); + let workspace = saved_legacy(&directory); + let roots = StartupRoots::new(directory.root.clone()); + let mut retained = roots.capture_existing().unwrap(); + workspace + .save(&rangoon_import::analyze("SKILL.md", b"# Another source\nNew content.\n").unwrap()) + .unwrap(); + assert_eq!(retained.revalidate(), Err(Error::Changed)); + assert_eq!(retained.archive(), Err(Error::Changed)); + + let mut retained = roots.capture_existing().unwrap(); + managed(&directory.root); + assert_eq!(retained.revalidate(), Err(Error::Changed)); + assert_eq!(retained.inventory(), Err(Error::Changed)); + assert_eq!(roots.inspect().state(), State::Mixed); +} + +#[cfg(unix)] +#[test] +fn adoption_handoff_checks_legacy_only_once_then_retains_existing_source_proof() { + let directory = TestDir::new("adoption-handoff"); + saved_legacy(&directory); + let roots = StartupRoots::new(directory.root.clone()); + let retained = roots.capture_existing().unwrap(); + let expected = retained.archive().unwrap().to_vec(); + let mut capture = retained.into_adoption_capture().unwrap(); + let fingerprint = capture.identity_fingerprint().unwrap(); + managed(&directory.root); + assert_eq!(roots.inspect().state(), State::Mixed); + let workspace = rangoon_store::Workspace::new(roots.legacy()); + workspace.revalidate_existing_capture(&mut capture).unwrap(); + assert_eq!(capture.archive().unwrap(), expected); + assert_eq!(capture.identity_fingerprint().unwrap(), fingerprint); + capture.cancel(); + assert!(capture.identity_fingerprint().is_err()); + assert!(roots.capture_existing().is_err()); +} + +#[cfg(unix)] +#[test] +fn capture_does_not_treat_metadata_candidate_as_valid_sqlite() { + let directory = TestDir::new("invalid-candidate"); + legacy(&directory.root, b"not-a-sqlite-database"); + let roots = StartupRoots::new(directory.root.clone()); + assert_eq!(roots.inspect().state(), State::LegacyCandidate); + assert!(matches!(roots.capture_existing(), Err(Error::Unavailable))); + assert_eq!( + fs::read(directory.join("source-workspace").join(DATABASE)).unwrap(), + b"not-a-sqlite-database" + ); + assert_eq!( + fs::read_dir(directory.join("source-workspace")) + .unwrap() + .count(), + 1 + ); +} + +#[cfg(unix)] +fn root_names(path: &Path) -> Vec { + let mut names = fs::read_dir(path) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect::>(); + names.sort(); + names +} + +#[cfg(unix)] +fn control_only(path: &Path) { + assert_eq!(root_names(path), [CONTROL]); + assert_eq!(fs::read(path.join(CONTROL)).unwrap(), b""); + for absent in [BINDING, PARENT, DATABASE, "workspace-adoption"] { + assert!(!path.join(absent).exists(), "{absent} must not exist"); + } +} + +#[cfg(unix)] +#[test] +fn fresh_binding_creates_only_fixed_metadata_for_missing_anchor_ancestry() { + let directory = TestDir::new("fresh-binding"); + let anchor = directory.join("missing-parent").join("anchor"); + write(directory.join("other-app-state"), b"unchanged"); + let roots = StartupRoots::new(anchor.clone()); + let inspection = roots.inspect(); + assert_eq!(inspection.state(), State::FreshCandidate); + assert!(!anchor.exists()); + + let proof = roots.fresh_binding(inspection).unwrap(); + assert_eq!(proof.root(), anchor.join("managed-workspace")); + assert!(!proof.existing()); + proof.check_before().unwrap(); + assert_eq!( + root_names(&directory.root), + ["missing-parent", "other-app-state"] + ); + assert_eq!( + fs::read(directory.join("other-app-state")).unwrap(), + b"unchanged" + ); + assert_eq!(root_names(&anchor), ["managed-workspace"]); + assert!(root_names(&proof.root()).is_empty()); + assert!(!anchor.join("source-workspace").exists()); + assert!(!anchor.join("workspace-adoption").exists()); + assert_eq!(proof.check_after(), Err(Error::Changed)); + + write(proof.root().join("unexpected"), b"unexpected"); + assert_eq!(proof.check_before(), Err(Error::Changed)); + assert_eq!(proof.check_after(), Err(Error::Changed)); + fs::remove_file(proof.root().join("unexpected")).unwrap(); + write(proof.root().join(CONTROL), b""); + proof.check_after().unwrap(); + control_only(&proof.root()); +} + +#[cfg(unix)] +#[test] +fn fresh_binding_refuses_stale_or_recovery_observations_before_creating_managed_root() { + let stale = TestDir::new("fresh-stale"); + let roots = StartupRoots::new(stale.root.clone()); + let inspection = roots.inspect(); + legacy(&stale.root, b"legacy metadata"); + assert!(matches!( + roots.fresh_binding(inspection), + Err(Error::Changed) + )); + assert!(!roots.managed().exists()); + assert_eq!(root_names(&stale.root), ["source-workspace"]); + + let unknown = TestDir::new("fresh-managed-unknown"); + fs::create_dir(unknown.join("managed-workspace")).unwrap(); + write( + unknown.join("managed-workspace").join("unrecognized"), + b"do not replace this", + ); + let roots = StartupRoots::new(unknown.root.clone()); + let inspection = roots.inspect(); + assert_eq!(inspection.state(), State::RecoveryRequired); + assert!(matches!( + roots.fresh_binding(inspection), + Err(Error::Changed) + )); + assert_eq!(root_names(&unknown.root), ["managed-workspace"]); + assert_eq!(root_names(&roots.managed()), ["unrecognized"]); + assert_eq!( + fs::read(roots.managed().join("unrecognized")).unwrap(), + b"do not replace this" + ); +} + +#[cfg(unix)] +#[test] +fn setup_residue_binding_accepts_only_one_zero_byte_regular_control() { + let valid = TestDir::new("residue-valid"); + fs::create_dir(valid.join("managed-workspace")).unwrap(); + write(valid.join("managed-workspace").join(CONTROL), b""); + let roots = StartupRoots::new(valid.root.clone()); + let proof = roots.setup_residue_binding().unwrap(); + assert_eq!(proof.root(), roots.managed()); + assert!(proof.existing()); + proof.check_before().unwrap(); + proof.check_after().unwrap(); + control_only(&roots.managed()); + + for label in ["binding", "unknown", "nonzero"] { + let directory = TestDir::new(label); + let managed = directory.join("managed-workspace"); + fs::create_dir(&managed).unwrap(); + write(managed.join(CONTROL), b""); + match label { + "binding" => write(managed.join(BINDING), b"binding"), + "unknown" => write(managed.join("unknown"), b"unknown"), + "nonzero" => write(managed.join(CONTROL), b"nonzero"), + _ => unreachable!(), + } + assert!(matches!( + StartupRoots::new(directory.root.clone()).setup_residue_binding(), + Err(Error::RecoveryRequired) + )); + assert_eq!( + root_names(&managed).len(), + if label == "unknown" || label == "binding" { + 2 + } else { + 1 + } + ); + } + + for label in ["legacy", "journal"] { + let directory = TestDir::new(label); + let managed = directory.join("managed-workspace"); + fs::create_dir(&managed).unwrap(); + write(managed.join(CONTROL), b""); + match label { + "legacy" => legacy(&directory.root, b"legacy metadata"), + "journal" => fs::create_dir(directory.join("workspace-adoption")).unwrap(), + _ => unreachable!(), + } + assert!(matches!( + StartupRoots::new(directory.root.clone()).setup_residue_binding(), + Err(Error::RecoveryRequired) + )); + control_only(&managed); + } +} + +#[cfg(unix)] +#[test] +fn existing_binding_retains_managed_identity_while_ignoring_original_divergence() { + let directory = TestDir::new("existing-proof"); + managed(&directory.root); + let roots = StartupRoots::new(directory.root.clone()); + let proof = roots.existing_binding().unwrap(); + assert_eq!(proof.root(), roots.managed()); + assert!(proof.existing()); + proof.check_before().unwrap(); + + legacy(&directory.root, b"later original divergence"); + proof.check_before().unwrap(); + proof.check_after().unwrap(); + assert_eq!( + fs::read(roots.legacy().join(DATABASE)).unwrap(), + b"later original divergence" + ); + assert!(!directory.join("workspace-adoption").exists()); +} + +#[cfg(unix)] +#[test] +fn existing_binding_rejects_replaced_managed_root_or_control_without_creation() { + let root = TestDir::new("existing-root-replaced"); + managed(&root.root); + let roots = StartupRoots::new(root.root.clone()); + let proof = roots.existing_binding().unwrap(); + let retained = root.join("retained-managed"); + fs::rename(roots.managed(), &retained).unwrap(); + managed(&root.root); + assert_eq!(proof.check_before(), Err(Error::Changed)); + assert!(!root.join("workspace-adoption").exists()); + + let control = TestDir::new("existing-control-replaced"); + managed(&control.root); + let roots = StartupRoots::new(control.root.clone()); + let proof = roots.existing_binding().unwrap(); + let retained = roots.managed().join("retained-control"); + fs::rename(roots.managed().join(CONTROL), &retained).unwrap(); + write(roots.managed().join(CONTROL), b""); + assert_eq!(proof.check_after(), Err(Error::Changed)); + assert_eq!(fs::read(&retained).unwrap(), b""); + assert_eq!(fs::read(roots.managed().join(CONTROL)).unwrap(), b""); + assert!(!control.join("workspace-adoption").exists()); +} + +#[cfg(all(unix, target_family = "unix"))] +#[test] +fn setup_residue_and_fresh_after_checks_reject_linked_controls() { + use std::os::unix::fs::symlink; + + let linked = TestDir::new("residue-symlink"); + let target = linked.join("target"); + write(&target, b""); + fs::create_dir(linked.join("managed-workspace")).unwrap(); + symlink(&target, linked.join("managed-workspace").join(CONTROL)).unwrap(); + assert!(matches!( + StartupRoots::new(linked.root.clone()).setup_residue_binding(), + Err(Error::RecoveryRequired) + )); + assert_eq!(fs::read(target).unwrap(), b""); + + let hard_link = TestDir::new("fresh-hardlink"); + let roots = StartupRoots::new(hard_link.root.clone()); + let proof = roots.fresh_binding(roots.inspect()).unwrap(); + let target = hard_link.join("control-target"); + write(&target, b""); + fs::hard_link(&target, proof.root().join(CONTROL)).unwrap(); + assert_eq!(proof.check_after(), Err(Error::Changed)); + assert_eq!(fs::read(&target).unwrap(), b""); +} + +#[cfg(not(unix))] +#[test] +fn inspection_reports_unsupported_platform() { + let directory = TestDir::new("unsupported"); + assert_state(&directory.root, State::UnsupportedPlatform); +} + +/// Presence fixtures are intentionally not valid Owner records. Only the +/// native Owner can interpret the operation and key after explicit consent. +#[cfg(all(unix, feature = "encrypted-workspace"))] +fn empty_provisioning_shape(root: &Path) -> String { + let identity = "a".repeat(64); + legacy(root, b"presence-only-original"); + let managed = root.join("managed-workspace"); + fs::create_dir(&managed).unwrap(); + write(managed.join(CONTROL), b""); + write(managed.join(BINDING), b"presence-only-binding"); + write(managed.join(OPERATIONS[0]), b"presence-only-pending"); + fs::create_dir(managed.join(PARENT)).unwrap(); + fs::create_dir(managed.join(PARENT).join(&identity)).unwrap(); + identity +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +#[test] +fn empty_provisioning_presence_never_substitutes_for_complete_managed_binding() { + let directory = TestDir::new("empty-presence"); + let identity = empty_provisioning_shape(&directory.root); + let roots = StartupRoots::new(directory.root.clone()); + let proof = roots.empty_provisioning_candidate(&identity).unwrap(); + proof.check().unwrap(); + assert_state(&directory.root, State::RecoveryRequired); + assert!(roots.existing_binding().is_err()); + assert!( + fs::read_dir(roots.managed().join(PARENT).join(identity)) + .unwrap() + .next() + .is_none() + ); +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +#[test] +fn empty_provisioning_presence_rejects_foreign_or_noncanonical_destination() { + let directory = TestDir::new("empty-presence-identity"); + empty_provisioning_shape(&directory.root); + let roots = StartupRoots::new(directory.root.clone()); + for destination in [ + "0".repeat(64), + "A".repeat(64), + "b".repeat(64), + "../escape".into(), + ] { + assert!(roots.empty_provisioning_candidate(&destination).is_err()); + } +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +#[test] +fn empty_provisioning_presence_rejects_partial_sidecar_terminal_and_extra_files() { + for case in [ + "zero", + "partial", + "wal", + "terminal", + "extra-root", + "extra-parent", + ] { + let directory = TestDir::new(case); + let identity = empty_provisioning_shape(&directory.root); + let roots = StartupRoots::new(directory.root.clone()); + let managed = roots.managed(); + let destination = managed.join(PARENT).join(&identity); + match case { + "zero" => write(destination.join(DATABASE), b""), + "partial" => write(destination.join(DATABASE), b"partial"), + "wal" => write(destination.join("workspace.sqlite3-wal"), b""), + "terminal" => write(managed.join(OPERATIONS[1]), b"existing-terminal"), + "extra-root" => write(managed.join("unexpected"), b"retained"), + "extra-parent" => fs::create_dir(managed.join(PARENT).join("b".repeat(64))).unwrap(), + _ => unreachable!(), + } + assert!( + roots.empty_provisioning_candidate(&identity).is_err(), + "{case}" + ); + } +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +#[test] +fn empty_provisioning_presence_revalidates_absence_and_directory_identities() { + for case in ["database", "directory", "parent", "binding"] { + let directory = TestDir::new(case); + let identity = empty_provisioning_shape(&directory.root); + let roots = StartupRoots::new(directory.root.clone()); + let proof = roots.empty_provisioning_candidate(&identity).unwrap(); + let managed = roots.managed(); + let destination = managed.join(PARENT).join(&identity); + match case { + "database" => write(destination.join(DATABASE), b""), + "directory" => { + fs::rename(&destination, directory.join("retained-directory")).unwrap(); + fs::create_dir(&destination).unwrap(); + } + "parent" => { + fs::rename(managed.join(PARENT), directory.join("retained-parent")).unwrap(); + fs::create_dir(managed.join(PARENT)).unwrap(); + fs::create_dir(&destination).unwrap(); + } + "binding" => { + let path = managed.join(BINDING); + let bytes = fs::read(&path).unwrap(); + fs::rename(&path, directory.join("retained-binding")).unwrap(); + write(path, &bytes); + } + _ => unreachable!(), + } + assert!(proof.check().is_err(), "{case}"); + } +} + +#[cfg(all(unix, feature = "encrypted-workspace"))] +#[test] +fn empty_provisioning_presence_rejects_linked_records_and_destination() { + use std::os::unix::fs::symlink; + for case in ["hardlink", "symlink", "directory"] { + let directory = TestDir::new(case); + let identity = empty_provisioning_shape(&directory.root); + let roots = StartupRoots::new(directory.root.clone()); + let managed = roots.managed(); + match case { + "hardlink" => { + fs::hard_link(managed.join(BINDING), directory.join("linked-binding")).unwrap() + } + "symlink" => { + let path = managed.join(BINDING); + let retained = directory.join("retained-binding"); + fs::rename(&path, &retained).unwrap(); + symlink(retained, path).unwrap(); + } + "directory" => { + let path = managed.join(PARENT).join(&identity); + let retained = directory.join("retained-directory"); + fs::rename(&path, &retained).unwrap(); + symlink(retained, path).unwrap(); + } + _ => unreachable!(), + } + assert!( + roots.empty_provisioning_candidate(&identity).is_err(), + "{case}" + ); + } +} diff --git a/apps/desktop/src/workspace_workflow_access_tests.rs b/apps/desktop/src/workspace_workflow_access_tests.rs index cbb5ee0..9b65090 100644 --- a/apps/desktop/src/workspace_workflow_access_tests.rs +++ b/apps/desktop/src/workspace_workflow_access_tests.rs @@ -122,7 +122,7 @@ fn legacy_workflow_routing_keeps_inventory_history_exact_bytes_and_source_clear_ let access = SourceAccess::legacy(Gate::new(), Ok(root.0.clone())); match tauri::async_runtime::block_on(access.workflow_data()) { - DataResult::Loaded { workspace } => { + DataResult::Loaded { workspace, .. } => { assert_eq!(workspace.sources.len(), 1); assert!(workspace.workflows.is_empty()); } @@ -437,7 +437,7 @@ fn workflow_clear_purge_and_cross_instance_handles_do_not_reopen_or_change_inven "workspace_changed" ); match tauri::async_runtime::block_on(access.workflow_data()) { - DataResult::Loaded { workspace } => assert!(workspace.workflows.is_empty()), + DataResult::Loaded { workspace, .. } => assert!(workspace.workflows.is_empty()), _ => panic!("expected unchanged inventory"), } let drain = gate.request_drain().unwrap(); diff --git a/crates/rangoon-cli/src/main.rs b/crates/rangoon-cli/src/main.rs index a008ea6..7ec8e3f 100644 --- a/crates/rangoon-cli/src/main.rs +++ b/crates/rangoon-cli/src/main.rs @@ -326,7 +326,9 @@ mod tests { .as_str() .unwrap() .as_bytes(); - hex.chunks_exact(2) + hex.as_chunks::<2>() + .0 + .iter() .map(|pair| { fn nibble(byte: u8) -> u8 { match byte { diff --git a/crates/rangoon-cli/tests/bundle.rs b/crates/rangoon-cli/tests/bundle.rs index 905a063..590d574 100644 --- a/crates/rangoon-cli/tests/bundle.rs +++ b/crates/rangoon-cli/tests/bundle.rs @@ -62,7 +62,9 @@ fn hex(input: &str) -> Vec { } input .as_bytes() - .chunks_exact(2) + .as_chunks::<2>() + .0 + .iter() .map(|pair| (nibble(pair[0]) << 4) | nibble(pair[1])) .collect() } diff --git a/crates/rangoon-compile/src/bundle_tests.rs b/crates/rangoon-compile/src/bundle_tests.rs index 0019694..c165df6 100644 --- a/crates/rangoon-compile/src/bundle_tests.rs +++ b/crates/rangoon-compile/src/bundle_tests.rs @@ -543,7 +543,9 @@ fn decode_hex(value: &str) -> Vec { assert_eq!(value.len() % 2, 0); value .as_bytes() - .chunks_exact(2) + .as_chunks::<2>() + .0 + .iter() .map(|pair| (hex_nibble(pair[0]) << 4) | hex_nibble(pair[1])) .collect() } diff --git a/crates/rangoon-compose/src/lib.rs b/crates/rangoon-compose/src/lib.rs index 9739008..a4efb88 100644 --- a/crates/rangoon-compose/src/lib.rs +++ b/crates/rangoon-compose/src/lib.rs @@ -832,17 +832,17 @@ fn coverage( let mut pieces = Vec::new(); for (oi, output) in draft.outputs.iter().enumerate() { for (pi, piece) in output.pieces.iter().enumerate() { - if let Piece::Copy { range } | Piece::Replace { range, .. } = piece { - if range.input_index == input_index as u32 { - endpoints.insert(range.start_byte); - endpoints.insert(range.end_byte); - pieces.push(( - range, - oi as u32, - pi as u32, - matches!(piece, Piece::Copy { .. }), - )); - } + if let Piece::Copy { range } | Piece::Replace { range, .. } = piece + && range.input_index == input_index as u32 + { + endpoints.insert(range.start_byte); + endpoints.insert(range.end_byte); + pieces.push(( + range, + oi as u32, + pi as u32, + matches!(piece, Piece::Copy { .. }), + )); } } } diff --git a/crates/rangoon-host/Cargo.toml b/crates/rangoon-host/Cargo.toml index 5ec38a0..dfc1969 100644 --- a/crates/rangoon-host/Cargo.toml +++ b/crates/rangoon-host/Cargo.toml @@ -15,6 +15,7 @@ serde.workspace = true [target.'cfg(unix)'.dependencies] libc = "=0.2.190" +rustix = { version = "=1.1.5", features = ["fs"] } [dev-dependencies] serde_json.workspace = true diff --git a/crates/rangoon-host/src/lib.rs b/crates/rangoon-host/src/lib.rs index c7f6c0a..c4cea08 100644 --- a/crates/rangoon-host/src/lib.rs +++ b/crates/rangoon-host/src/lib.rs @@ -1,7 +1,19 @@ -//! Bounded reads for a host-selected file. The caller owns the selection UI. -//! This is not a generic frontend path API or a directory confinement boundary. +//! Native-selected file reads and retained-root metadata inventory. +//! Single-file helpers do not retain parents; inventory owns directory handles. +//! Neither interface is a generic frontend path or file-mutation API. #![forbid(unsafe_code)] +mod source_inventory; +pub use source_inventory::{ + FileObservation, FolderCollectionResult, InventoryError, InventoryPage, PartialReason, + SelectedRootInventory, list_selected_root, +}; + +mod source_collection; +pub use source_collection::{ + MAX_COLLECTION_BYTES, MAX_COLLECTION_FILES, SourceCollectionItem, SourceCollectionResult, + inspect_selected_sources, +}; mod backup; pub use backup::{MAX_BACKUP_FILE_BYTES, read_selected_backup, write_selected_backup}; mod instructions; diff --git a/crates/rangoon-host/src/source_collection.rs b/crates/rangoon-host/src/source_collection.rs new file mode 100644 index 0000000..b0c7dbe --- /dev/null +++ b/crates/rangoon-host/src/source_collection.rs @@ -0,0 +1,266 @@ +//! Bounded read-only inspection of files explicitly selected by the native user. +//! This is neither directory discovery nor trusted filesystem custody for writes. +use super::{PublicError, SelectionResult, analyze_selected_path}; +use serde::Serialize; +use std::path::PathBuf; + +pub const MAX_COLLECTION_FILES: usize = 32; +pub const MAX_COLLECTION_BYTES: u64 = 4 * 1024 * 1024; +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceCollectionItem { + pub selection_index: u32, + pub display_name: String, + pub result: SelectionResult, +} +#[derive(Debug, Serialize)] +#[serde( + tag = "outcome", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +pub enum SourceCollectionResult { + Cancelled, + Inspected { + schema_version: &'static str, + selected_count: u32, + retained_bytes: u64, + items: Vec, + }, + Failed { + error: PublicError, + }, +} +impl SourceCollectionResult { + pub fn failed(code: &'static str, message: &'static str) -> Self { + Self::Failed { + error: PublicError { code, message }, + } + } + pub fn stale() -> Self { + Self::failed( + "source_collection_cleared", + "File inspection was cleared. Choose files again.", + ) + } +} +/// Call only with paths returned by a fresh native multi-file picker. No path is +/// serialized. Cancellation is checked before every file and before delivery. +pub fn inspect_selected_sources( + paths: &[PathBuf], + current: impl Fn() -> bool, +) -> SourceCollectionResult { + if paths.is_empty() || paths.len() > MAX_COLLECTION_FILES { + return SourceCollectionResult::failed( + "source_collection_limit", + "Choose between 1 and 32 Markdown files. No files were read.", + ); + } + let mut items = Vec::with_capacity(paths.len()); + let mut retained_bytes = 0u64; + let mut budget_exhausted = false; + for (index, path) in paths.iter().enumerate() { + if !current() { + return SourceCollectionResult::stale(); + } + let display_name = path + .file_name() + .and_then(|name| name.to_str()) + .filter(|name| name.len() <= 255 && !name.chars().any(char::is_control)) + .unwrap_or("Unsupported file") + .to_owned(); + let result = if budget_exhausted { + SelectionResult::failed( + "source_collection_budget", + "Not read: this selection reached its 4 MiB retained-content limit. Choose a smaller batch.", + ) + } else { + match analyze_selected_path(path) { + SelectionResult::Analyzed { report } => { + // Native single-file analysis already bounds each input at + // 256 KiB. At most one such report is discarded on overflow; + // after overflow no further selected paths are read. + let next = retained_bytes.checked_add(report.source.byte_length); + if next.is_none_or(|bytes| bytes > MAX_COLLECTION_BYTES) { + budget_exhausted = true; + SelectionResult::failed( + "source_collection_budget", + "Not retained: this file exceeds the batch's remaining 4 MiB content budget. Choose a smaller batch.", + ) + } else { + retained_bytes = next.unwrap(); + SelectionResult::Analyzed { report } + } + } + other => other, + } + }; + items.push(SourceCollectionItem { + selection_index: index as u32, + display_name, + result, + }); + } + if !current() { + return SourceCollectionResult::stale(); + } + SourceCollectionResult::Inspected { + schema_version: "rangoon.source-collection.v1", + selected_count: paths.len() as u32, + retained_bytes, + items, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + fs, + time::{SystemTime, UNIX_EPOCH}, + }; + struct Root(PathBuf); + impl Root { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "rangoon-source-collection-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&p).unwrap(); + Self(p) + } + fn file(&self, name: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(name); + fs::write(&path, bytes).unwrap(); + path + } + } + impl Drop for Root { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + #[test] + fn explicit_files_remain_unchanged_with_partial_refusals_and_no_paths_in_wire() { + let root = Root::new(); + let a = root.file("AGENTS.md", b"# Rules\r\nKeep originals.\r\n"); + let bad = root.file("binary.md", b"bad\0bytes"); + let paths = vec![a.clone(), bad]; + let result = inspect_selected_sources(&paths, || true); + let wire = serde_json::to_value(&result).unwrap(); + assert_eq!(wire["outcome"], "inspected"); + assert_eq!(wire["selectedCount"], 2); + assert_eq!(wire["items"][0]["result"]["outcome"], "analyzed"); + assert_eq!(wire["items"][1]["result"]["outcome"], "rejected"); + assert_eq!(fs::read(a).unwrap(), b"# Rules\r\nKeep originals.\r\n"); + assert!( + !serde_json::to_string(&result) + .unwrap() + .contains(root.0.to_str().unwrap()) + ); + } + #[test] + fn count_limits_and_cancellation_refuse_before_any_file_read() { + use std::cell::Cell; + let calls = Cell::new(0); + let paths = vec![PathBuf::from("must-not-be-read.md"); 33]; + assert!(matches!( + inspect_selected_sources(&paths, || { + calls.set(calls.get() + 1); + true + }), + SourceCollectionResult::Failed { .. } + )); + assert_eq!(calls.get(), 0); + assert!(matches!( + inspect_selected_sources(&[], || true), + SourceCollectionResult::Failed { .. } + )); + assert!(matches!( + inspect_selected_sources(&paths[..1], || false), + SourceCollectionResult::Failed { + error: PublicError { + code: "source_collection_cleared", + .. + } + } + )); + } + #[test] + fn budget_has_explicit_outcomes_and_stops_further_reads() { + let root = Root::new(); + // A compact source near the 256 KiB bound: 16 long lines. + let data = b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n".repeat(7900); + assert!(data.len() < 262144); + let file = root.file("large.md", &data); + let mut paths = vec![file; 17]; + paths.push(root.0.join("missing-after-budget.md")); + let SourceCollectionResult::Inspected { + items, + retained_bytes, + .. + } = inspect_selected_sources(&paths, || true) + else { + panic!("expected inspected"); + }; + assert!(retained_bytes <= MAX_COLLECTION_BYTES); + assert_eq!(items.len(), 18); + assert!(matches!( + items[17].result, + SelectionResult::Failed { + error: PublicError { + code: "source_collection_budget", + .. + } + } + )); + } + #[cfg(unix)] + #[test] + fn selected_link_is_refused_and_duplicate_names_retain_selection_indices() { + use std::os::unix::fs::symlink; + let root = Root::new(); + let a = root.file("AGENTS.md", b"# Scope\nBounded.\n"); + let link = root.0.join("link.md"); + symlink(&a, &link).unwrap(); + let SourceCollectionResult::Inspected { items, .. } = + inspect_selected_sources(&[a.clone(), a, link], || true) + else { + panic!("expected collection"); + }; + assert_eq!(items[0].selection_index, 0); + assert_eq!(items[1].selection_index, 1); + assert!(matches!(items[2].result, SelectionResult::Rejected { .. })); + } + #[test] + fn cancellation_between_files_drops_all_retained_content() { + use std::cell::Cell; + let root = Root::new(); + let file = root.file("AGENTS.md", b"# Synthetic private content\n"); + let checks = Cell::new(0); + let result = inspect_selected_sources(&[file, root.0.join("must-not-read.md")], || { + let n = checks.get() + 1; + checks.set(n); + n == 1 + }); + assert!(matches!( + &result, + SourceCollectionResult::Failed { + error: PublicError { + code: "source_collection_cleared", + .. + } + } + )); + assert_eq!(checks.get(), 2); + assert!( + !serde_json::to_string(&result) + .unwrap() + .contains("Synthetic private content") + ); + } +} diff --git a/crates/rangoon-host/src/source_inventory.rs b/crates/rangoon-host/src/source_inventory.rs new file mode 100644 index 0000000..03a4ab5 --- /dev/null +++ b/crates/rangoon-host/src/source_inventory.rs @@ -0,0 +1,915 @@ +//! Incremental metadata observations of a native-selected directory object. +//! No content read, hash, writes, renderer paths, transport or snapshot claim. +use serde::Serialize; +use std::path::Path; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum InventoryError { + UnsupportedPlatform, + InvalidRoot, + Unavailable, + Cancelled, + Closed, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PartialReason { + ReadError, + ChangedDirectory, + OtherDevice, + RepeatedDirectory, + RepeatedEntry, + DepthLimit, + EntryLimit, + RecordLimit, + UnsupportedName, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileObservation { + /// Session-local ordinal; not a persistent file or revision identity. + pub observation_id: u64, + pub relative_path: String, + pub byte_length: u64, + /// Observed filesystem time, at whole-second precision. Not freshness proof. + pub modified_at_ms: Option, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InventoryPage { + pub schema_version: &'static str, + pub entries: Vec, + pub visited_entries: u64, + pub emitted_records: u64, + pub excluded_entries: u64, + /// Traversal stopped/exhausted; inspect partial_reasons independently. + pub exhausted: bool, + pub partial_reasons: Vec, +} + +pub const MAX_FOLDER_COLLECTION_BYTES: usize = 2 * 1024 * 1024; +fn folder_window_bound(entries: &[FileObservation]) -> usize { + // Conservative JSON upper bound: fixed envelope + per-row keys/numbers, + // then exact string escaping. No original bytes are serialized. + 2048 + entries + .iter() + .map(|row| { + 256 + row + .relative_path + .chars() + .map(|c| match c { + '"' | '\\' => 2, + c if c.is_control() => 6, + c => c.len_utf8(), + }) + .sum::() + }) + .sum::() +} + +/// One bounded, metadata-only window. No directory capability survives delivery. +#[derive(Debug, Serialize)] +#[serde( + tag = "outcome", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +pub enum FolderCollectionResult { + Cancelled, + Listed { + schema_version: &'static str, + root_label: String, + entries: Vec, + visited_entries: u64, + emitted_records: u64, + excluded_entries: u64, + exhausted: bool, + partial_reasons: Vec, + }, + Failed { + error: crate::PublicError, + }, +} +impl FolderCollectionResult { + pub fn failed(code: &'static str, message: &'static str) -> Self { + Self::Failed { + error: crate::PublicError { code, message }, + } + } + pub fn stale() -> Self { + Self::failed( + "folder_inventory_cleared", + "Folder listing was cleared. Choose the folder again.", + ) + } +} +/// Native picker paths only. Metadata is bounded and never retained as source. +pub fn list_selected_root(path: &Path, current: impl Fn() -> bool) -> FolderCollectionResult { + let label = path + .file_name() + .and_then(|value| value.to_str()) + .filter(|name| name.len() <= 255 && !name.chars().any(char::is_control)) + .unwrap_or("Selected folder") + .to_owned(); + #[cfg(unix)] + let label = if unix::safe_component(&label) { + label + } else { + "Selected folder".to_owned() + }; + let mut inventory = match SelectedRootInventory::open_selected_root(path, ¤t) { + Ok(inventory) => inventory, + Err(InventoryError::Cancelled) => return FolderCollectionResult::stale(), + Err(InventoryError::UnsupportedPlatform) => { + return FolderCollectionResult::failed( + "folder_inventory_unsupported", + "Folder discovery is unavailable on this platform. Choose individual files instead.", + ); + } + Err(_) => { + return FolderCollectionResult::failed( + "folder_inventory_unavailable", + "The selected folder could not be listed. Choose an available folder without linked ancestors.", + ); + } + }; + let mut entries = Vec::new(); + loop { + match inventory.next_page(¤t) { + Ok(mut page) => { + entries.append(&mut page.entries); + if folder_window_bound(&entries) > MAX_FOLDER_COLLECTION_BYTES { + inventory.close(); + return FolderCollectionResult::failed( + "folder_inventory_budget", + "Folder metadata exceeds this view's 2 MiB limit. Choose a smaller folder.", + ); + } + if page.exhausted { + inventory.close(); + if !current() { + return FolderCollectionResult::stale(); + } + return FolderCollectionResult::Listed { + schema_version: "rangoon.folder-collection.v1", + root_label: label, + entries, + visited_entries: page.visited_entries, + emitted_records: page.emitted_records, + excluded_entries: page.excluded_entries, + exhausted: true, + partial_reasons: page.partial_reasons, + }; + } + } + Err(_) => { + inventory.close(); + return FolderCollectionResult::stale(); + } + } + } +} + +/// Construct only from a fresh native folder selection. Never expose this +/// constructor as a renderer path API. Lock/cancel must close this owner. +pub struct SelectedRootInventory { + #[cfg(unix)] + inner: unix::Inventory, +} +impl SelectedRootInventory { + pub fn open_selected_root( + path: &Path, + current: impl Fn() -> bool, + ) -> Result { + #[cfg(unix)] + { + unix::Inventory::open(path, current).map(|inner| Self { inner }) + } + #[cfg(not(unix))] + { + let _ = (path, current); + Err(InventoryError::UnsupportedPlatform) + } + } + pub fn next_page( + &mut self, + current: impl Fn() -> bool, + ) -> Result { + #[cfg(unix)] + { + self.inner.next_page(current, |_| {}) + } + #[cfg(not(unix))] + { + let _ = current; + Err(InventoryError::UnsupportedPlatform) + } + } + pub fn close(&mut self) { + #[cfg(unix)] + self.inner.close(); + } +} + +#[cfg(unix)] +mod unix { + use super::*; + use rustix::fs::{AtFlags, Dir, FileType, Mode, OFlags, Stat, fstat, open, openat, statat}; + use std::collections::HashSet; + use std::path::Component; + + const FLAGS: OFlags = OFlags::RDONLY + .union(OFlags::DIRECTORY) + .union(OFlags::NOFOLLOW) + .union(OFlags::NONBLOCK) + .union(OFlags::CLOEXEC); + #[derive(Clone, Copy)] + struct Limits { + depth: usize, + visited: u64, + records: u64, + page_records: usize, + page_work: usize, + } + impl Default for Limits { + fn default() -> Self { + Self { + depth: 16, + visited: 10_000, + records: 1000, + page_records: 50, + page_work: 512, + } + } + } + struct Frame { + dir: Dir, + relative: String, + depth: usize, + } + pub(super) struct Inventory { + frames: Vec, + directories: HashSet<(u64, u64)>, + files: HashSet, + device: u64, + visited: u64, + emitted: u64, + excluded: u64, + reasons: Vec, + closed: bool, + limits: Limits, + } + // Unix dev_t/ino_t widths differ across supported targets. + #[allow(clippy::unnecessary_cast)] + fn identity(stat: &Stat) -> (u64, u64) { + (stat.st_dev as u64, stat.st_ino as u64) + } + fn directory(stat: &Stat) -> bool { + FileType::from_raw_mode(stat.st_mode) == FileType::Directory + } + pub(super) fn safe_component(name: &str) -> bool { + !name.is_empty() && name.encode_utf16().count() <= 255 && name != "." && name != ".." && + !name.chars().any(|c| (!c.is_ascii() && !c.is_alphanumeric()) || c.is_control() || matches!(c, '\\' | ':' | '%' | '?' | '#' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}')) && + !name.ends_with(['.', ' ']) && + !matches!(name.split('.').next().unwrap_or("").to_ascii_lowercase().as_str(), "con" | "prn" | "aux" | "nul" | "com1" | "com2" | "com3" | "com4" | "com5" | "com6" | "com7" | "com8" | "com9" | "lpt1" | "lpt2" | "lpt3" | "lpt4" | "lpt5" | "lpt6" | "lpt7" | "lpt8" | "lpt9") + } + fn excluded(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + matches!( + lower.as_str(), + "node_modules" | "target" | "vendor" | "dist" | "build" + ) || name.starts_with('.') + && !matches!( + lower.as_str(), + ".claude" | ".cursor" | ".windsurf" | ".github" | ".codex" | ".agents" + ) + } + impl Inventory { + pub(super) fn open( + path: &Path, + current: impl Fn() -> bool, + ) -> Result { + if !current() { + return Err(InventoryError::Cancelled); + } + if !path.is_absolute() || path.components().count() > 65 { + return Err(InventoryError::InvalidRoot); + } + let mut fd = + open("/", FLAGS, Mode::empty()).map_err(|_| InventoryError::Unavailable)?; + let mut count = 0; + for component in path.components() { + if !current() { + return Err(InventoryError::Cancelled); + } + match component { + Component::RootDir => continue, + Component::Normal(name) => { + let before = statat(&fd, name, AtFlags::SYMLINK_NOFOLLOW) + .map_err(|_| InventoryError::Unavailable)?; + if !directory(&before) { + return Err(InventoryError::InvalidRoot); + } + let next = openat(&fd, name, FLAGS, Mode::empty()) + .map_err(|_| InventoryError::Unavailable)?; + let after = fstat(&next).map_err(|_| InventoryError::Unavailable)?; + if !directory(&after) || identity(&before) != identity(&after) { + return Err(InventoryError::Unavailable); + } + fd = next; + count += 1; + } + _ => return Err(InventoryError::InvalidRoot), + } + } + // Never allow an accidental whole-filesystem root selection. + if count == 0 { + return Err(InventoryError::InvalidRoot); + } + let stat = fstat(&fd).map_err(|_| InventoryError::Unavailable)?; + let dir = Dir::new(fd).map_err(|_| InventoryError::Unavailable)?; + if !current() { + return Err(InventoryError::Cancelled); + } + Ok(Self { + frames: vec![Frame { + dir, + relative: String::new(), + depth: 0, + }], + directories: HashSet::from([identity(&stat)]), + files: HashSet::new(), + device: identity(&stat).0, + visited: 0, + emitted: 0, + excluded: 0, + reasons: Vec::new(), + closed: false, + limits: Limits::default(), + }) + } + fn reason(&mut self, reason: PartialReason) { + if !self.reasons.contains(&reason) { + self.reasons.push(reason); + } + } + pub(super) fn close(&mut self) { + self.frames.clear(); + self.directories.clear(); + self.files.clear(); + self.closed = true; + } + pub(super) fn next_page( + &mut self, + current: impl Fn() -> bool, + mut before_directory_open: impl FnMut(&str), + ) -> Result { + if self.closed { + return Err(InventoryError::Closed); + } + let mut entries = Vec::new(); + let mut work = 0; + while !self.frames.is_empty() + && entries.len() < self.limits.page_records + && work < self.limits.page_work + { + if !current() { + self.close(); + return Err(InventoryError::Cancelled); + } + if self.visited >= self.limits.visited { + self.reason(PartialReason::EntryLimit); + self.frames.clear(); + break; + } + if self.emitted >= self.limits.records { + self.reason(PartialReason::RecordLimit); + self.frames.clear(); + break; + } + let frame = self.frames.last_mut().unwrap(); + let item = match frame.dir.next() { + None => { + self.frames.pop(); + continue; + } + Some(Err(_)) => { + self.frames.pop(); + self.reason(PartialReason::ReadError); + continue; + } + Some(Ok(item)) => item, + }; + work += 1; + self.visited += 1; + let name = match item.file_name().to_str() { + Ok("." | "..") => continue, + Ok(name) if safe_component(name) => name.to_owned(), + _ => { + self.reason(PartialReason::UnsupportedName); + continue; + } + }; + if excluded(&name) { + self.excluded += 1; + continue; + } + let relative = if frame.relative.is_empty() { + name.clone() + } else { + format!("{}/{name}", frame.relative) + }; + if relative.encode_utf16().count() > 1024 { + self.reason(PartialReason::UnsupportedName); + continue; + } + let fd = match frame.dir.fd() { + Ok(fd) => fd, + Err(_) => { + self.reason(PartialReason::ReadError); + continue; + } + }; + let stat = match statat(fd, name.as_str(), AtFlags::SYMLINK_NOFOLLOW) { + Ok(stat) => stat, + Err(_) => { + self.reason(PartialReason::ReadError); + continue; + } + }; + if identity(&stat).0 != self.device { + self.reason(PartialReason::OtherDevice); + continue; + } + match FileType::from_raw_mode(stat.st_mode) { + FileType::Directory => { + if frame.depth >= self.limits.depth { + self.reason(PartialReason::DepthLimit); + continue; + } + before_directory_open(&relative); + let child = match openat(fd, name.as_str(), FLAGS, Mode::empty()) { + Ok(child) => child, + Err(error) => { + self.reason( + if matches!( + error, + rustix::io::Errno::LOOP + | rustix::io::Errno::NOTDIR + | rustix::io::Errno::NOENT + ) { + PartialReason::ChangedDirectory + } else { + PartialReason::ReadError + }, + ); + continue; + } + }; + let opened = match fstat(&child) { + Ok(opened) => opened, + Err(_) => { + self.reason(PartialReason::ReadError); + continue; + } + }; + if !directory(&opened) || identity(&stat) != identity(&opened) { + self.reason(PartialReason::ChangedDirectory); + continue; + } + if !self.directories.insert(identity(&opened)) { + self.reason(PartialReason::RepeatedDirectory); + continue; + } + let depth = frame.depth + 1; + match Dir::new(child) { + Ok(dir) => self.frames.push(Frame { + dir, + relative, + depth, + }), + Err(_) => self.reason(PartialReason::ReadError), + } + } + FileType::RegularFile + if name.to_ascii_lowercase().ends_with(".md") && stat.st_size >= 0 => + { + if !self.files.insert(relative.clone()) { + self.reason(PartialReason::RepeatedEntry); + continue; + } + self.emitted += 1; + entries.push(FileObservation { + observation_id: self.emitted, + relative_path: relative, + byte_length: stat.st_size as u64, + modified_at_ms: u64::try_from(stat.st_mtime) + .ok() + .and_then(|seconds| seconds.checked_mul(1000)), + }); + } + _ => self.excluded += 1, + } + } + if !current() { + self.close(); + return Err(InventoryError::Cancelled); + } + Ok(InventoryPage { + schema_version: "rangoon.local-inventory.observation.v1", + entries, + visited_entries: self.visited, + emitted_records: self.emitted, + excluded_entries: self.excluded, + exhausted: self.frames.is_empty(), + partial_reasons: self.reasons.clone(), + }) + } + } + + #[cfg(test)] + mod tests { + use super::*; + use std::{ + fs, + os::unix::fs::{FileTypeExt, symlink}, + sync::atomic::{AtomicU64, Ordering}, + }; + static SERIAL: AtomicU64 = AtomicU64::new(0); + struct Root(std::path::PathBuf); + impl Root { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "rangoon-inventory-{}-{}", + std::process::id(), + SERIAL.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(fs::canonicalize(path).unwrap()) + } + fn file(&self, name: &str) { + let path = self.0.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"private content must not enter inventory").unwrap(); + } + fn inventory(&self) -> Inventory { + Inventory::open(&self.0, || true).unwrap() + } + } + impl Drop for Root { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + fn all(inventory: &mut Inventory) -> (Vec, InventoryPage) { + let mut rows = Vec::new(); + loop { + let mut page = inventory.next_page(|| true, |_| {}).unwrap(); + rows.append(&mut page.entries); + if page.exhausted { + return (rows, page); + } + } + } + #[test] + fn aggregate_metadata_json_budget_bounds_wide_unicode_paths() { + let rows = (0..1000) + .map(|index| FileObservation { + observation_id: index, + relative_path: "界".repeat(1000), + byte_length: u64::MAX, + modified_at_ms: Some(u64::MAX), + }) + .collect::>(); + assert!(folder_window_bound(&rows) > MAX_FOLDER_COLLECTION_BYTES); + let encoded = serde_json::to_vec(&rows).unwrap(); + assert!(encoded.len() < folder_window_bound(&rows)); + } + #[test] + fn collected_window_has_only_metadata_and_clears_on_late_cancellation() { + let root = Root::new(); + root.file("AGENTS.md"); + let successful_calls = std::cell::Cell::new(0); + let result = list_selected_root(&root.0, || { + successful_calls.set(successful_calls.get() + 1); + true + }); + let encoded = serde_json::to_value(result).unwrap(); + assert_eq!(encoded["outcome"], "listed"); + assert_eq!(encoded["entries"].as_array().unwrap().len(), 1); + assert!(!encoded.to_string().contains("private content")); + assert!(!encoded.to_string().contains(root.0.to_str().unwrap())); + let calls = std::cell::Cell::new(0); + let result = list_selected_root(&root.0, || { + calls.set(calls.get() + 1); + calls.get() < successful_calls.get() + }); + assert_eq!(serde_json::to_value(result).unwrap()["outcome"], "failed"); + } + #[test] + fn metadata_only_relative_markdown_and_explicit_policy() { + let root = Root::new(); + for name in [ + "AGENTS.md", + "project/CLAUDE.MD", + ".claude/SKILL.md", + ".cursor/rules/example.md", + ".ssh/secret.md", + ".git/history.md", + "node_modules/no.md", + "target/no.md", + "notes.txt", + ".env", + "vendor/no.md", + ] { + root.file(name); + } + let (rows, page) = all(&mut root.inventory()); + assert_eq!(rows.len(), 4); + assert!(page.partial_reasons.is_empty()); + assert!(page.excluded_entries >= 7); + for row in &rows { + assert!(!row.relative_path.starts_with('/')); + assert!(row.modified_at_ms.is_some()); + } + let encoded = serde_json::to_string(&rows).unwrap(); + assert!(!encoded.contains("private content")); + assert!(!encoded.contains(root.0.to_str().unwrap())); + assert!(!encoded.contains("sha256")); + } + #[test] + fn symlink_root_and_ancestor_are_refused() { + let root = Root::new(); + root.file("real/AGENTS.md"); + symlink(root.0.join("real"), root.0.join("alias")).unwrap(); + assert!(Inventory::open(&root.0.join("alias"), || true).is_err()); + fs::create_dir(root.0.join("real/sub")).unwrap(); + assert!(Inventory::open(&root.0.join("alias/sub"), || true).is_err()); + assert!(matches!( + Inventory::open(Path::new("/"), || true), + Err(InventoryError::InvalidRoot) + )); + assert!(Inventory::open(Path::new("relative"), || true).is_err()); + } + #[test] + fn child_symlinks_and_special_files_are_not_followed() { + let root = Root::new(); + let outside = Root::new(); + outside.file("SECRET.md"); + root.file("AGENTS.md"); + symlink(&outside.0, root.0.join("escape")).unwrap(); + symlink(outside.0.join("SECRET.md"), root.0.join("link.md")).unwrap(); + symlink(&root.0, root.0.join("loop")).unwrap(); + assert!( + std::process::Command::new("/usr/bin/mkfifo") + .arg(root.0.join("fifo.md")) + .status() + .unwrap() + .success() + ); + assert!( + fs::symlink_metadata(root.0.join("fifo.md")) + .unwrap() + .file_type() + .is_fifo() + ); + let socket = std::os::unix::net::UnixListener::bind(root.0.join("socket.md")).unwrap(); + assert!( + fs::symlink_metadata(root.0.join("socket.md")) + .unwrap() + .file_type() + .is_socket() + ); + let (rows, page) = all(&mut root.inventory()); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].relative_path, "AGENTS.md"); + assert!(page.excluded_entries >= 5); + drop(socket); + } + #[test] + fn directory_substitution_between_stat_and_open_cannot_escape() { + let root = Root::new(); + let outside = Root::new(); + root.file("child/AGENTS.md"); + outside.file("SECRET.md"); + let mut inventory = root.inventory(); + let page = inventory + .next_page( + || true, + |relative| { + if relative == "child" { + fs::rename(root.0.join("child"), root.0.join("retired")).unwrap(); + symlink(&outside.0, root.0.join("child")).unwrap(); + } + }, + ) + .unwrap(); + assert!( + page.partial_reasons + .contains(&PartialReason::ChangedDirectory) + ); + assert!( + !page + .entries + .iter() + .any(|row| row.relative_path.contains("SECRET")) + ); + let (rest, _) = all(&mut inventory); + assert!(!rest.iter().any(|row| row.relative_path.contains("SECRET"))); + } + #[test] + fn directory_replaced_by_fifo_is_refused_without_opening_content() { + let root = Root::new(); + root.file("child/AGENTS.md"); + let mut inventory = root.inventory(); + let page = inventory + .next_page( + || true, + |relative| { + if relative == "child" { + fs::rename(root.0.join("child"), root.0.join("retired")).unwrap(); + assert!( + std::process::Command::new("/usr/bin/mkfifo") + .arg(root.0.join("child")) + .status() + .unwrap() + .success() + ); + } + }, + ) + .unwrap(); + assert!( + page.partial_reasons + .contains(&PartialReason::ChangedDirectory) + ); + assert!( + !page + .entries + .iter() + .any(|row| row.relative_path == "child/AGENTS.md") + ); + } + #[test] + fn root_path_replacement_does_not_redirect_held_directory_object() { + let root = Root::new(); + let outside = Root::new(); + root.file("AGENTS.md"); + outside.file("SECRET.md"); + let mut inventory = root.inventory(); + let moved = root.0.with_extension("moved"); + fs::rename(&root.0, &moved).unwrap(); + symlink(&outside.0, &root.0).unwrap(); + let (rows, _) = all(&mut inventory); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].relative_path, "AGENTS.md"); + inventory.close(); + fs::remove_file(&root.0).unwrap(); + fs::rename(moved, &root.0).unwrap(); + } + #[test] + fn bounded_incremental_pages_and_session_ordinals() { + let root = Root::new(); + for n in 0..121 { + root.file(&format!("file-{n}.md")); + } + let mut inventory = root.inventory(); + let first = inventory.next_page(|| true, |_| {}).unwrap(); + assert_eq!(first.entries.len(), 50); + assert!(!first.exhausted); + let second = inventory.next_page(|| true, |_| {}).unwrap(); + assert_eq!(second.entries.len(), 50); + assert_eq!(second.entries[0].observation_id, 51); + let (rest, last) = all(&mut inventory); + assert_eq!(rest.len(), 21); + assert_eq!(last.emitted_records, 121); + assert!(last.partial_reasons.is_empty()); + } + #[test] + fn production_record_budget_stops_without_claiming_complete_coverage() { + let root = Root::new(); + for index in 0..1001 { + root.file(&format!("file-{index}.md")); + } + let (rows, page) = all(&mut root.inventory()); + assert_eq!(rows.len(), 1000); + assert_eq!(page.emitted_records, 1000); + assert!(page.exhausted); + assert!(page.partial_reasons.contains(&PartialReason::RecordLimit)); + } + #[test] + fn work_depth_and_total_limits_are_explicit() { + let root = Root::new(); + for n in 0..20 { + root.file(&format!("file-{n}.md")); + } + root.file("child/deeper/a.md"); + let mut inventory = root.inventory(); + inventory.limits.page_work = 2; + let page = inventory.next_page(|| true, |_| {}).unwrap(); + assert!(page.visited_entries <= 2); + assert!(!page.exhausted); + let mut inventory = root.inventory(); + inventory.limits.records = 3; + let (rows, page) = all(&mut inventory); + assert_eq!(rows.len(), 3); + assert!(page.partial_reasons.contains(&PartialReason::RecordLimit)); + let mut inventory = root.inventory(); + inventory.limits.visited = 3; + let (_, page) = all(&mut inventory); + assert!(page.partial_reasons.contains(&PartialReason::EntryLimit)); + let mut inventory = root.inventory(); + inventory.limits.depth = 0; + let (_, page) = all(&mut inventory); + assert!(page.partial_reasons.contains(&PartialReason::DepthLimit)); + } + #[test] + fn cancel_before_open_and_during_page_closes_owner_and_discards_page() { + let root = Root::new(); + root.file("a.md"); + assert!(matches!( + Inventory::open(&root.0, || false), + Err(InventoryError::Cancelled) + )); + let mut inventory = root.inventory(); + let calls = std::cell::Cell::new(0); + let result = inventory.next_page( + || { + calls.set(calls.get() + 1); + calls.get() < 3 + }, + |_| {}, + ); + assert!(matches!(result, Err(InventoryError::Cancelled))); + assert!(inventory.frames.is_empty()); + assert!(matches!( + inventory.next_page(|| true, |_| {}), + Err(InventoryError::Closed) + )); + } + #[test] + fn invalid_names_are_reported_not_normalized_or_lossily_decoded() { + let root = Root::new(); + for name in ["a%2f.md", "NUL.md", "bad\u{202e}.md", "line\n.md"] { + root.file(name); + } + // APFS refuses non-UTF-8 names at creation. Linux can exercise the + // actual directory-entry branch with a disposable byte-name file. + #[cfg(target_os = "linux")] + { + use std::os::unix::ffi::OsStringExt; + fs::write( + root.0 + .join(std::ffi::OsString::from_vec(vec![0xff, b'.', b'm', b'd'])), + b"hidden", + ) + .unwrap(); + } + root.file("café.md"); + let (rows, page) = all(&mut root.inventory()); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].relative_path, "café.md"); + assert!( + page.partial_reasons + .contains(&PartialReason::UnsupportedName) + ); + } + #[test] + fn device_and_repeated_directory_refusals_are_explicit() { + let root = Root::new(); + root.file("child/AGENTS.md"); + let mut inventory = root.inventory(); + inventory.device = inventory.device.wrapping_add(1); + let (rows, page) = all(&mut inventory); + assert!(rows.is_empty()); + assert!(page.partial_reasons.contains(&PartialReason::OtherDevice)); + let mut inventory = root.inventory(); + let child = open(root.0.join("child"), FLAGS, Mode::empty()).unwrap(); + inventory + .directories + .insert(identity(&fstat(&child).unwrap())); + let (rows, page) = all(&mut inventory); + assert!(rows.is_empty()); + assert!( + page.partial_reasons + .contains(&PartialReason::RepeatedDirectory) + ); + } + #[test] + fn close_is_terminal_and_exact_root_errors_do_not_echo_paths() { + let root = Root::new(); + let mut inventory = + SelectedRootInventory::open_selected_root(&root.0, || true).unwrap(); + inventory.close(); + assert!(matches!( + inventory.next_page(|| true), + Err(InventoryError::Closed) + )); + assert_eq!( + serde_json::to_string(&InventoryError::Unavailable).unwrap(), + "\"unavailable\"" + ); + } + } +} diff --git a/crates/rangoon-integrations/src/lnsat_evidence.rs b/crates/rangoon-integrations/src/lnsat_evidence.rs index a7bb337..00816d7 100644 --- a/crates/rangoon-integrations/src/lnsat_evidence.rs +++ b/crates/rangoon-integrations/src/lnsat_evidence.rs @@ -465,7 +465,7 @@ fn parse_authorization( native_state: required_string(object, "state")?.to_owned(), state_projection: state_projection( required_string(object, "state")?, - &["issued", "consumed", "expired", "revoked"], + &["active", "consumed", "cancelled", "expired", "revoked"], ), state_effective_at: required_string(object, "state_effective_at")?.to_owned(), active: required_bool(object, "active")?, @@ -533,7 +533,7 @@ fn parse_operation( state_projection: state_projection( state, &[ - "created", + "prepared", "dispatching", "outcome_unknown", "completed", @@ -583,36 +583,34 @@ fn validate_selected_ids( nested_attempt: Option<&LnsatAttemptEvidence>, standalone_attempt: Option<&LnsatAttemptEvidence>, ) -> Result<(), LnsatEvidenceError> { - if let (Some(selected), Some(value)) = (input.selected_authorization_id, authorization) { - if selected != value.authorization_id { - return Err(LnsatEvidenceError::IdMismatch); - } + if let (Some(selected), Some(value)) = (input.selected_authorization_id, authorization) + && selected != value.authorization_id + { + return Err(LnsatEvidenceError::IdMismatch); } - if let (Some(selected), Some(value)) = (input.selected_operation_id, operation) { - if selected != value.operation_id { - return Err(LnsatEvidenceError::IdMismatch); - } + if let (Some(selected), Some(value)) = (input.selected_operation_id, operation) + && selected != value.operation_id + { + return Err(LnsatEvidenceError::IdMismatch); } - if let (Some(selected), Some(value)) = (input.selected_authorization_id, operation) { - if selected != value.authorization_id { - return Err(LnsatEvidenceError::IdMismatch); - } + if let (Some(selected), Some(value)) = (input.selected_authorization_id, operation) + && selected != value.authorization_id + { + return Err(LnsatEvidenceError::IdMismatch); } - if let Some(value) = nested_attempt { - if input.selected_operation_id != Some(value.operation_id.as_str()) + if let Some(value) = nested_attempt + && (input.selected_operation_id != Some(value.operation_id.as_str()) || input .selected_operation_attempt_id - .is_some_and(|selected| selected != value.operation_attempt_id) - { - return Err(LnsatEvidenceError::IdMismatch); - } + .is_some_and(|selected| selected != value.operation_attempt_id)) + { + return Err(LnsatEvidenceError::IdMismatch); } - if let Some(value) = standalone_attempt { - if input.selected_operation_id != Some(value.operation_id.as_str()) - || input.selected_operation_attempt_id != Some(value.operation_attempt_id.as_str()) - { - return Err(LnsatEvidenceError::IdMismatch); - } + if let Some(value) = standalone_attempt + && (input.selected_operation_id != Some(value.operation_id.as_str()) + || input.selected_operation_attempt_id != Some(value.operation_attempt_id.as_str())) + { + return Err(LnsatEvidenceError::IdMismatch); } Ok(()) } @@ -626,20 +624,24 @@ fn validate_joins( ) -> Result<(), LnsatEvidenceError> { if let (Some(authorization), Some(selected_operation_id)) = (authorization, input.selected_operation_id) + && authorization.operation_id != selected_operation_id { - if authorization.operation_id != selected_operation_id { - return Err(LnsatEvidenceError::ReferenceMismatch); - } + return Err(LnsatEvidenceError::ReferenceMismatch); } - if operation.is_none() { - if let (Some(authorization), Some(attempt)) = (authorization, standalone_attempt) { - if authorization.project_ref != attempt.project_ref - || authorization.resource_ref != attempt.resource_ref - { - return Err(LnsatEvidenceError::ScopeMismatch); + if let Some(authorization) = authorization { + for attempt in [nested_attempt, standalone_attempt].into_iter().flatten() { + if authorization.adapter_ref != attempt.adapter_ref { + return Err(LnsatEvidenceError::ReferenceMismatch); } } } + if operation.is_none() + && let (Some(authorization), Some(attempt)) = (authorization, standalone_attempt) + && (authorization.project_ref != attempt.project_ref + || authorization.resource_ref != attempt.resource_ref) + { + return Err(LnsatEvidenceError::ScopeMismatch); + } if let (Some(authorization), Some(operation)) = (authorization, operation) { if authorization.authorization_id != operation.authorization_id { return Err(LnsatEvidenceError::ReferenceMismatch); @@ -667,10 +669,10 @@ fn validate_joins( } } } - if let (Some(nested), Some(standalone)) = (nested_attempt, standalone_attempt) { - if nested != standalone { - return Err(LnsatEvidenceError::AttemptMismatch); - } + if let (Some(nested), Some(standalone)) = (nested_attempt, standalone_attempt) + && nested != standalone + { + return Err(LnsatEvidenceError::AttemptMismatch); } Ok(()) } diff --git a/crates/rangoon-integrations/src/lnsat_request_record.rs b/crates/rangoon-integrations/src/lnsat_request_record.rs index 3d2c493..49a0d48 100644 --- a/crates/rangoon-integrations/src/lnsat_request_record.rs +++ b/crates/rangoon-integrations/src/lnsat_request_record.rs @@ -1460,7 +1460,7 @@ fn parse(b: &[u8]) -> Result { } Ok(v) } -impl Parser<'_> { +impl<'a> Parser<'a> { fn ws(&mut self) { while self .s @@ -1757,7 +1757,7 @@ fn time(v: &str) -> Result<(), RequestRecordError> { let max = match m { 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, 4 | 6 | 9 | 11 => 30, - 2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29, + 2 if y.is_multiple_of(4) && (!y.is_multiple_of(100) || y.is_multiple_of(400)) => 29, 2 => 28, _ => return Err(RequestRecordError::InvalidEnvelope), }; diff --git a/crates/rangoon-integrations/src/openshell_observation.rs b/crates/rangoon-integrations/src/openshell_observation.rs index 633ee57..ea47ff0 100644 --- a/crates/rangoon-integrations/src/openshell_observation.rs +++ b/crates/rangoon-integrations/src/openshell_observation.rs @@ -302,19 +302,18 @@ pub fn map_openshell_window( } let fingerprint = serde_json::to_string(&mapped) .map_err(|_| OpenShellObservationError::SerializationFailed)?; - if let Some(event_id) = mapped.event_id.as_deref() { - if let Some(previous) = + if let Some(event_id) = mapped.event_id.as_deref() + && let Some(previous) = event_fingerprints.insert(event_id.to_owned(), fingerprint.clone()) - { - diagnostics.push(MappedDiagnostic { - code: if previous == fingerprint { - "repeated_event_id" - } else { - "conflicting_event_id" - }, - event_id: Some(event_id.to_owned()), - }); - } + { + diagnostics.push(MappedDiagnostic { + code: if previous == fingerprint { + "repeated_event_id" + } else { + "conflicting_event_id" + }, + event_id: Some(event_id.to_owned()), + }); } items.push(mapped); } diff --git a/crates/rangoon-integrations/tests/lnsat_evidence.rs b/crates/rangoon-integrations/tests/lnsat_evidence.rs index 357299c..55d247d 100644 --- a/crates/rangoon-integrations/tests/lnsat_evidence.rs +++ b/crates/rangoon-integrations/tests/lnsat_evidence.rs @@ -282,7 +282,7 @@ fn replays_fixture_cases_without_provider_access() { ] ); match authorization.native_state.as_str() { - "issued" => assert_eq!( + "active" => assert_eq!( ( authorization.operation_id.as_str(), authorization.operation_audit_binding_id.as_str(), @@ -443,6 +443,155 @@ fn refuses_cross_envelope_conflicts_and_preserves_unsupported_native_state() { ); } +#[test] +fn recognizes_pinned_native_states_without_inferring_authority() { + let fixture = fixture(); + for state in ["active", "consumed", "cancelled", "expired", "revoked"] { + let mut authorization = template(&fixture, "authorization").clone(); + authorization["authorization"]["state"] = Value::String(state.into()); + authorization["authorization"]["active"] = Value::Bool(state == "active"); + let encoded = bytes(&authorization); + let output = decode_lnsat_evidence(input( + Some(&encoded), + None, + None, + Some("xau_one"), + None, + None, + )) + .expect("pinned authorization state remains observable"); + let observed = output.authorization.expect("authorization"); + assert_eq!(observed.native_state, state); + assert_eq!( + observed.state_projection, "reported_native_state", + "{state}" + ); + assert_eq!(output.rangoon_authority, "none"); + assert_eq!(output.approval, "not_inferred"); + assert_eq!(output.execution, "not_inferred"); + } + for state in [ + "prepared", + "dispatching", + "outcome_unknown", + "completed", + "failed", + ] { + let mut operation = template(&fixture, "operation").clone(); + operation["operation"]["state"] = Value::String(state.into()); + if state == "prepared" { + operation["operation"]["consumption_id"] = Value::Null; + } + let encoded = bytes(&operation); + let output = decode_lnsat_evidence(input( + None, + Some(&encoded), + None, + Some("xau_one"), + Some("opn_one"), + None, + )) + .expect("pinned operation state remains observable"); + let observed = output.operation.expect("operation"); + assert_eq!(observed.native_state, state); + assert_eq!( + observed.state_projection, "reported_native_state", + "{state}" + ); + assert_eq!(output.rangoon_authority, "none"); + assert_eq!(output.approval, "not_inferred"); + assert_eq!(output.execution, "not_inferred"); + } +} + +#[test] +fn authorization_and_operation_attempt_must_name_the_same_adapter() { + let fixture = fixture(); + let mut authorization = template(&fixture, "authorization").clone(); + authorization["authorization"]["operation_id"] = Value::String("opn_one".into()); + authorization["authorization"]["operation_audit_binding_id"] = + Value::String("audit:operation".into()); + let authorization = bytes(&authorization); + for (with_operation, with_nested, with_standalone) in [ + (false, false, true), + (true, false, true), + (true, true, false), + (true, true, true), + ] { + for matching_adapter in [true, false] { + let mut attempt = template(&fixture, "attempt").clone(); + if !matching_adapter { + attempt["attempt"]["adapter_ref"] = Value::String("adapter:other".into()); + } + let mut operation = template(&fixture, "operation").clone(); + if with_nested { + operation["operation"]["attempt"] = attempt["attempt"].clone(); + } + let operation = with_operation.then(|| bytes(&operation)); + let attempt = with_standalone.then(|| bytes(&attempt)); + let decoded = decode_lnsat_evidence(input( + Some(&authorization), + operation.as_deref(), + attempt.as_deref(), + Some("xau_one"), + Some("opn_one"), + Some("opa_one"), + )); + if matching_adapter { + let output = decoded.expect("matching adapter preserves the existing join"); + assert_eq!(output.attempt.expect("attempt").adapter_ref, "adapter:one"); + assert_eq!(output.rangoon_authority, "none"); + assert_eq!(output.execution, "not_inferred"); + } else { + let error = decoded.expect_err("contradictory adapter must refuse atomically"); + assert_eq!(error, LnsatEvidenceError::ReferenceMismatch); + assert_eq!(error.to_string(), "lnsat_evidence_reference_mismatch"); + assert!(!error.to_string().contains("adapter:other")); + } + } + } +} + +#[test] +fn non_native_state_labels_remain_explicitly_unsupported() { + let fixture = fixture(); + let mut operation = template(&fixture, "operation").clone(); + operation["operation"]["state"] = Value::String("created".into()); + let encoded = bytes(&operation); + let output = decode_lnsat_evidence(input( + None, + Some(&encoded), + None, + Some("xau_one"), + Some("opn_one"), + None, + )) + .expect("unrecognized state is retained without becoming supported"); + let observed = output.operation.expect("operation"); + assert_eq!(observed.native_state, "created"); + assert_eq!(observed.state_projection, "unsupported_native_state"); + assert_eq!(output.rangoon_authority, "none"); + assert_eq!(output.execution, "not_inferred"); + + let mut authorization = template(&fixture, "authorization").clone(); + authorization["authorization"]["state"] = Value::String("issued".into()); + let encoded = bytes(&authorization); + let output = decode_lnsat_evidence(input( + Some(&encoded), + None, + None, + Some("xau_one"), + None, + None, + )) + .expect("non-native authorization state is retained without becoming supported"); + let observed = output.authorization.expect("authorization"); + assert_eq!(observed.native_state, "issued"); + assert_eq!(observed.state_projection, "unsupported_native_state"); + assert_eq!(output.rangoon_authority, "none"); + assert_eq!(output.execution, "not_inferred"); +} + #[test] fn refuses_unmatched_authorization_operation_references_without_projection() { let fixture = fixture(); diff --git a/crates/rangoon-language/tests/d0a.rs b/crates/rangoon-language/tests/d0a.rs index 13e484e..5bf7c7e 100644 --- a/crates/rangoon-language/tests/d0a.rs +++ b/crates/rangoon-language/tests/d0a.rs @@ -322,7 +322,7 @@ fn sha256(bytes: &[u8]) -> String { fn decode_base64(input: &str) -> Vec { assert_eq!(input.len() % 4, 0); let mut output = Vec::with_capacity(input.len() / 4 * 3); - for chunk in input.as_bytes().chunks_exact(4) { + for chunk in input.as_bytes().as_chunks::<4>().0.iter() { let padding = chunk.iter().filter(|&&byte| byte == b'=').count(); assert!( padding <= 2 && (padding == 0 || chunk[4 - padding..].iter().all(|&byte| byte == b'=')) diff --git a/crates/rangoon-model-cloud/src/check_wire.rs b/crates/rangoon-model-cloud/src/check_wire.rs index 236ee33..30c9916 100644 --- a/crates/rangoon-model-cloud/src/check_wire.rs +++ b/crates/rangoon-model-cloud/src/check_wire.rs @@ -94,7 +94,7 @@ fn digits(bytes: &[u8]) -> Option { } fn leap_year(year: u16) -> bool { - year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) + year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) } #[cfg(test)] diff --git a/crates/rangoon-model-cloud/src/transport.rs b/crates/rangoon-model-cloud/src/transport.rs index 87b05a2..60f79d6 100644 --- a/crates/rangoon-model-cloud/src/transport.rs +++ b/crates/rangoon-model-cloud/src/transport.rs @@ -399,10 +399,10 @@ fn validate_headers(headers: &hyper::HeaderMap, cap: usize) -> Result<(), Diagno } } let mut encodings = headers.get_all(header::CONTENT_ENCODING).iter(); - if let Some(value) = encodings.next() { - if !value.as_bytes().eq_ignore_ascii_case(b"identity") || encodings.next().is_some() { - return Err(Diagnostic::ResponseInvalid); - } + if let Some(value) = encodings.next() + && (!value.as_bytes().eq_ignore_ascii_case(b"identity") || encodings.next().is_some()) + { + return Err(Diagnostic::ResponseInvalid); } if let Some(value) = headers.get(header::CONTENT_LENGTH) { let length: u64 = value diff --git a/crates/rangoon-model-cloud/src/wire.rs b/crates/rangoon-model-cloud/src/wire.rs index 9d08414..481d8e4 100644 --- a/crates/rangoon-model-cloud/src/wire.rs +++ b/crates/rangoon-model-cloud/src/wire.rs @@ -203,10 +203,10 @@ fn reasoning(item: &Map) -> Result<(), Diagnostic> { { return Err(Diagnostic::ResponseInvalid); } - if let Some(status) = item.get("status") { - if status.as_str() != Some("completed") { - return Err(Diagnostic::ResponseInvalid); - } + if let Some(status) = item.get("status") + && status.as_str() != Some("completed") + { + return Err(Diagnostic::ResponseInvalid); } Ok(()) } diff --git a/crates/rangoon-model-local/src/transport.rs b/crates/rangoon-model-local/src/transport.rs index 183732d..775dc36 100644 --- a/crates/rangoon-model-local/src/transport.rs +++ b/crates/rangoon-model-local/src/transport.rs @@ -317,10 +317,10 @@ fn validate_headers(headers: &hyper::HeaderMap, cap: usize) -> Result<(), Diagno } } let mut encodings = headers.get_all(header::CONTENT_ENCODING).iter(); - if let Some(value) = encodings.next() { - if !value.as_bytes().eq_ignore_ascii_case(b"identity") || encodings.next().is_some() { - return Err(Diagnostic::ResponseInvalid); - } + if let Some(value) = encodings.next() + && (!value.as_bytes().eq_ignore_ascii_case(b"identity") || encodings.next().is_some()) + { + return Err(Diagnostic::ResponseInvalid); } if let Some(value) = headers.get(header::CONTENT_LENGTH) { let length: u64 = value diff --git a/crates/rangoon-model-session/src/cloud.rs b/crates/rangoon-model-session/src/cloud.rs index a6c5fee..b8f8496 100644 --- a/crates/rangoon-model-session/src/cloud.rs +++ b/crates/rangoon-model-session/src/cloud.rs @@ -312,14 +312,13 @@ impl Operation { impl Drop for Operation { fn drop(&mut self) { self.cancellation.cancel(); - if let Ok(mut state) = self.session.lock() { - if state + if let Ok(mut state) = self.session.lock() + && state .active .as_ref() .is_some_and(|a| a.view.run_id == self.id) - { - state.active = None; - } + { + state.active = None; } } } diff --git a/crates/rangoon-model-session/src/lib.rs b/crates/rangoon-model-session/src/lib.rs index 0d04832..03ceacd 100644 --- a/crates/rangoon-model-session/src/lib.rs +++ b/crates/rangoon-model-session/src/lib.rs @@ -322,14 +322,13 @@ impl Operation { impl Drop for Operation { fn drop(&mut self) { self.cancellation.cancel(); - if let Ok(mut state) = self.session.lock() { - if state + if let Ok(mut state) = self.session.lock() + && state .active .as_ref() .is_some_and(|a| a.view.run_id == self.id) - { - state.active = None; - } + { + state.active = None; } } } diff --git a/crates/rangoon-openshell-client/src/lib.rs b/crates/rangoon-openshell-client/src/lib.rs index bf0ba8b..a4fd17a 100644 --- a/crates/rangoon-openshell-client/src/lib.rs +++ b/crates/rangoon-openshell-client/src/lib.rs @@ -40,7 +40,7 @@ use tonic::{ transport::{Channel, Endpoint}, }; use tower::Service; -use zeroize::Zeroizing; +use zeroize::{Zeroize, Zeroizing}; // These private, generated bindings reflect the pinned provider protocol and // are not project-authored API. Keep Clippy suppression scoped to this module. @@ -147,7 +147,7 @@ impl CertificatePin { return Err(ClientError::InvalidConfiguration); } let mut pin = [0_u8; 32]; - for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { + for (index, pair) in value.as_bytes().as_chunks::<2>().0.iter().enumerate() { pin[index] = hex_byte(pair).ok_or(ClientError::InvalidConfiguration)?; } Ok(Self(pin)) @@ -174,8 +174,8 @@ fn hex_byte(pair: &[u8]) -> Option { Some((digit(pair.first().copied()?)? << 4) | digit(pair.get(1).copied()?)?) } -/// Caller-selected, short-lived bearer credential. It cannot refresh itself, -/// is not `Debug`, and never appears in an error or projection. +/// Caller-selected, short-lived bearer credential. It cannot refresh itself; +/// Debug is redacted and no credential appears in an error or projection. pub struct BearerLease { value: Zeroizing, expires_at: Instant, @@ -183,13 +183,24 @@ pub struct BearerLease { impl BearerLease { pub fn new(value: String, expires_at: Instant) -> Result { + // Establish cleanup custody before validation, including error and + // unwind paths. No credential clone is needed for this transfer. + let mut value = Zeroizing::new(value); + Self::validate_owned_value(&mut value, expires_at)?; + Ok(Self { value, expires_at }) + } + + fn validate_owned_value( + value: &mut Zeroizing, + expires_at: Instant, + ) -> Result<(), ClientError> { if value.is_empty() || value.len() > 16 * 1024 || expires_at <= Instant::now() { + // Clear before returning the fixed error, even if a trusted caller + // retains the guard. Its Drop remains cleanup defense in depth. + value.zeroize(); return Err(ClientError::InvalidConfiguration); } - Ok(Self { - value: Zeroizing::new(value), - expires_at, - }) + Ok(()) } fn deadline(&self) -> LeaseDeadline { @@ -2134,6 +2145,55 @@ pub mod synthetic_peer { #[cfg(test)] mod tests { use super::*; + + #[test] + fn credential_constructor_rejected_values_clear_before_error_return() { + let future = Instant::now() + Duration::from_secs(30); + for (plain, expiry) in [ + (String::new(), future), + ("x".repeat(16 * 1024 + 1), future), + ("expired-dummy-credential".to_owned(), Instant::now()), + ] { + let mut owned = Zeroizing::new(plain); + assert_eq!( + BearerLease::validate_owned_value(&mut owned, expiry), + Err(ClientError::InvalidConfiguration) + ); + // Observe the live owned value, never deallocated or spare memory. + assert!(owned.is_empty()); + } + } + + #[test] + fn credential_constructor_preserves_rejection_boundaries() { + let future = Instant::now() + Duration::from_secs(30); + for (plain, expiry) in [ + (String::new(), future), + ("x".repeat(16 * 1024 + 1), future), + ("expired-dummy-credential".to_owned(), Instant::now()), + ] { + let error = BearerLease::new(plain, expiry).unwrap_err(); + assert_eq!(error, ClientError::InvalidConfiguration); + assert_eq!(error.code(), "invalid_configuration"); + } + } + + #[test] + fn credential_constructor_valid_value_keeps_bound_and_immutable_deadline() { + let expiry = Instant::now() + Duration::from_secs(30); + let mut owned = Zeroizing::new("x".repeat(16 * 1024)); + assert_eq!( + BearerLease::validate_owned_value(&mut owned, expiry), + Ok(()) + ); + assert_eq!(owned.len(), 16 * 1024); + assert!(owned.bytes().all(|byte| byte == b'x')); + let lease = BearerLease::new(std::mem::take(&mut *owned), expiry).unwrap(); + assert_eq!(lease.value.len(), 16 * 1024); + assert_eq!(lease.deadline().0, expiry); + assert_eq!(format!("{lease:?}"), "BearerLease([redacted])"); + } + fn pinned_config(origin: &str) -> Result { let certificate = vec![1, 2, 3, 4]; let pin = CertificatePin::from_certificate_der(&certificate)?; diff --git a/crates/rangoon-ops/src/approvals.rs b/crates/rangoon-ops/src/approvals.rs index 92519a3..1f02eca 100644 --- a/crates/rangoon-ops/src/approvals.rs +++ b/crates/rangoon-ops/src/approvals.rs @@ -351,20 +351,19 @@ impl Inspector<'_> { }) { flags[4] = true; } - if o.kind() == "approval_decision" { - if let Some(d) = v["delegationId"] + if o.kind() == "approval_decision" + && let Some(d) = v["delegationId"] .as_str() .and_then(|id| self.value(id, "delegation")) - { - references.push(self.reference( - budget, - &mut flags, - "delegation.delegateId", - None, - text(d, "delegateId"), - "actor", - )?); - } + { + references.push(self.reference( + budget, + &mut flags, + "delegation.delegateId", + None, + text(d, "delegateId"), + "actor", + )?); } Ok((flags, references)) } @@ -815,13 +814,12 @@ fn local_votes( _ => (), } } - if !blocked(&local) { - if let Some(required) = stage.row.required_reported_subject_count { - local[24] |= votes.approve_subjects < required as usize; - local[23] |= - stage.row.reported_human_required && votes.human_approve_subjects == 0; - stage.row.reported_votes = Some(votes); - } + if !blocked(&local) + && let Some(required) = stage.row.required_reported_subject_count + { + local[24] |= votes.approve_subjects < required as usize; + local[23] |= stage.row.reported_human_required && votes.human_approve_subjects == 0; + stage.row.reported_votes = Some(votes); } stage.local = local; stage.final_flags = local; diff --git a/crates/rangoon-ops/src/delegations.rs b/crates/rangoon-ops/src/delegations.rs index 581422f..9737bdd 100644 --- a/crates/rangoon-ops/src/delegations.rs +++ b/crates/rangoon-ops/src/delegations.rs @@ -442,10 +442,10 @@ pub fn inspect_delegations( break; }; union(&mut flags[i], &aggregate_delegations[current]); - if let Some(delegator) = &bindings[ordinal][0] { - if !seen_subjects.insert(delegator.clone()) { - flags[i][15] = true; - } + if let Some(delegator) = &bindings[ordinal][0] + && !seen_subjects.insert(delegator.clone()) + { + flags[i][15] = true; } let Some(parent) = optional_text(&obs[ordinal].value, "parentDelegationId") else { break; diff --git a/crates/rangoon-ops/src/lifecycle.rs b/crates/rangoon-ops/src/lifecycle.rs index 2a5a596..4b17132 100644 --- a/crates/rangoon-ops/src/lifecycle.rs +++ b/crates/rangoon-ops/src/lifecycle.rs @@ -782,48 +782,47 @@ fn event_refs( } _ => (), } - if matches!(kind, "authorization" | "attempt" | "suspension") { - if let Some(id) = item.predecessor() { - let expected_kind: &'static str = match kind { - "authorization" => "authorization", - "attempt" => "attempt", - "suspension" => "suspension", - _ => return Err(LifecycleError::SerializationFailed), - }; - refs.push(reference( - index, - tainted, - budget, - flags, - ReferenceRequest { - field: "previousObservationId", - list_index: None, - id, - expected: expected_kind, - }, - )?); - } + if matches!(kind, "authorization" | "attempt" | "suspension") + && let Some(id) = item.predecessor() + { + let expected_kind: &'static str = match kind { + "authorization" => "authorization", + "attempt" => "attempt", + "suspension" => "suspension", + _ => return Err(LifecycleError::SerializationFailed), + }; + refs.push(reference( + index, + tainted, + budget, + flags, + ReferenceRequest { + field: "previousObservationId", + list_index: None, + id, + expected: expected_kind, + }, + )?); } if matches!( kind, "authorization" | "attempt" | "suspension" | "coverage" - ) { - if let Some(ids) = item.value.get("evidenceIds").and_then(Value::as_array) { - for (i, id) in ids.iter().enumerate() { - if let Some(id) = id.as_str() { - refs.push(reference( - index, - tainted, - budget, - flags, - ReferenceRequest { - field: "evidenceIds", - list_index: Some(i), - id, - expected: "evidence", - }, - )?); - } + ) && let Some(ids) = item.value.get("evidenceIds").and_then(Value::as_array) + { + for (i, id) in ids.iter().enumerate() { + if let Some(id) = id.as_str() { + refs.push(reference( + index, + tainted, + budget, + flags, + ReferenceRequest { + field: "evidenceIds", + list_index: Some(i), + id, + expected: "evidence", + }, + )?); } } } @@ -832,17 +831,13 @@ fn event_refs( && link.expected_kind != "evidence" && link.expected_kind != "gateway_revision" && link.field != "previousObservationId" + && let Some(record) = index.get(&link.record_id) + && let Some(first) = observations.get(record.first) + && first.value.get("context").is_some() + && item.value.get("context").is_some() + && !flow_equal(&item.value, &first.value) { - if let Some(record) = index.get(&link.record_id) { - if let Some(first) = observations.get(record.first) { - if first.value.get("context").is_some() - && item.value.get("context").is_some() - && !flow_equal(&item.value, &first.value) - { - mark(flags, "context_mismatch"); - } - } - } + mark(flags, "context_mismatch"); } } Ok(refs) @@ -1109,10 +1104,9 @@ pub fn inspect_lifecycle(decoded: &DecodedWindow) -> Result>(); timeline.sort_by_key(|event| event.input_ordinal); - if timeline.iter().enumerate().any(|(ordinal, event)| { - event.input_ordinal != ordinal || !RECORD_KINDS.contains(&event.record_kind.as_str()) - }) { - return Err(OperatorViewError::InvalidView); + let mut record_counts = [0usize; RECORD_KINDS.len()]; + for (ordinal, event) in timeline.iter().enumerate() { + if event.input_ordinal != ordinal { + return Err(OperatorViewError::InvalidView); + } + let Some(kind_index) = RECORD_KINDS + .iter() + .position(|kind| *kind == event.record_kind.as_str()) + else { + return Err(OperatorViewError::InvalidView); + }; + record_counts[kind_index] += 1; + } + if RECORD_KINDS + .iter() + .zip(record_counts) + .any(|(kind, count)| decoded.inventory().record_counts().get(*kind).copied() != Some(count)) + { + return Err(OperatorViewError::StageMismatch); } let relationship_events = indexed_stage( diff --git a/crates/rangoon-ops/src/operator_view_tests.rs b/crates/rangoon-ops/src/operator_view_tests.rs index 27159de..3c13b88 100644 --- a/crates/rangoon-ops/src/operator_view_tests.rs +++ b/crates/rangoon-ops/src/operator_view_tests.rs @@ -511,6 +511,90 @@ fn decision_counts_remain_byte_identical_when_all_source_ids_change() { } } +#[test] +fn nondecision_record_kind_counts_must_match_even_with_equal_event_totals() { + let value = window(1_000, true); + let valid = inspect(&value); + let valid: Value = serde_json::from_slice(valid.canonical_bytes()).unwrap(); + assert_eq!(valid["sourceCounts"]["eventCount"], 2); + + for replacement in RECORD_KINDS.iter().copied().filter(|kind| { + !matches!( + *kind, + "actor" | "evaluation" | "approval_decision" | "authorization" | "attempt" + ) + }) { + let ( + decoded, + mut projection, + mut relationships, + mut delegations, + mut approvals, + mut lifecycle, + ) = inspection_parts(&value); + assert_eq!(projection.document.timeline[0].record_kind, "actor"); + projection.document.timeline[0].record_kind = replacement.to_owned(); + projection.canonical = serde_json::to_vec(&projection.document).unwrap(); + let projection_digest = projection.canonical_digest(); + relationships.document.structural_projection_digest = projection_digest.clone(); + relationships.canonical = serde_json::to_vec(&relationships.document).unwrap(); + delegations.document.structural_projection_digest = projection_digest.clone(); + delegations.canonical = serde_json::to_vec(&delegations.document).unwrap(); + approvals.document.structural_projection_digest = projection_digest.clone(); + approvals.document.relationship_digest = relationships.canonical_digest(); + approvals.document.delegation_digest = delegations.canonical_digest(); + approvals.canonical = serde_json::to_vec(&approvals.document).unwrap(); + lifecycle.document.structural_projection_digest = projection_digest; + lifecycle.document.relationship_digest = relationships.canonical_digest(); + lifecycle.document.delegation_digest = delegations.canonical_digest(); + lifecycle.document.approval_digest = approvals.canonical_digest(); + lifecycle.canonical = serde_json::to_vec(&lifecycle.document).unwrap(); + + assert_eq!( + projection.document.timeline.len(), + decoded.inventory().event_count() + ); + let result = build_operator_view( + &decoded, + &projection, + &relationships, + &delegations, + &approvals, + &lifecycle, + ); + assert_eq!( + result.unwrap_err(), + OperatorViewError::StageMismatch, + "non-decision kind {replacement} must not bypass per-kind counts" + ); + } +} + +#[test] +fn each_record_kind_inventory_count_mismatch_is_rejected() { + let value = window(1_000, true); + for kind in RECORD_KINDS { + let (mut decoded, projection, relationships, delegations, approvals, lifecycle) = + inspection_parts(&value); + let source_digest = decoded.canonical_digest().to_owned(); + *decoded.inventory.record_counts.get_mut(kind).unwrap() += 1; + assert_eq!(decoded.canonical_digest(), source_digest); + assert_eq!( + build_operator_view( + &decoded, + &projection, + &relationships, + &delegations, + &approvals, + &lifecycle, + ) + .unwrap_err(), + OperatorViewError::StageMismatch, + "inventory count for {kind} must match the observed timeline" + ); + } +} + #[test] fn reference_aggregate_ceiling_is_atomic_for_internal_malformed_stage_data() { let value = request_evaluation_window(1_000); diff --git a/crates/rangoon-ops/src/projection.rs b/crates/rangoon-ops/src/projection.rs index 816d199..b1f4c50 100644 --- a/crates/rangoon-ops/src/projection.rs +++ b/crates/rangoon-ops/src/projection.rs @@ -401,32 +401,29 @@ fn outside_scope(o: &Observation<'_>, snapshot: &Snapshot) -> bool { { return true; } - if let Some(c) = &o.event.correlation { - if c.workspace_id != scope.workspace_id + if let Some(c) = &o.event.correlation + && (c.workspace_id != scope.workspace_id || !scope.system_ids.contains(&c.system_id) || !scope.environment_ids.contains(&c.environment_id) - || !scope.engine_ids.contains(&c.engine_id) - { - return true; - } + || !scope.engine_ids.contains(&c.engine_id)) + { + return true; } - if let Some(context) = o.record.get("context") { - if context["workspaceId"].as_str() != Some(scope.workspace_id.as_str()) + if let Some(context) = o.record.get("context") + && (context["workspaceId"].as_str() != Some(scope.workspace_id.as_str()) || !contains(&scope.system_ids, &context["systemId"]) || !contains(&scope.environment_ids, &context["environmentId"]) || !contains(&scope.engine_ids, &context["engineId"]) - || !contains(policy_ids, &context["policyRevisionId"]) - { - return true; - } + || !contains(policy_ids, &context["policyRevisionId"])) + { + return true; } - if let Some(action) = o.record.get("scope") { - if !contains(&scope.system_ids, &action["systemId"]) + if let Some(action) = o.record.get("scope") + && (!contains(&scope.system_ids, &action["systemId"]) || !subset(&action["environmentIds"], &scope.environment_ids) - || !subset(&action["policyRevisionIds"], policy_ids) - { - return true; - } + || !subset(&action["policyRevisionIds"], policy_ids)) + { + return true; } false } @@ -455,10 +452,10 @@ fn correlation_mismatch(o: &Observation<'_>) -> bool { ("engineId", Some(c.engine_id.as_str())), ("policyRevisionId", c.policy_revision_id.as_deref()), ] { - if let Some(actual) = o.field(key) { - if Some(actual) != expected { - return true; - } + if let Some(actual) = o.field(key) + && Some(actual) != expected + { + return true; } } if let Some(context) = o.record.get("context") { @@ -506,12 +503,11 @@ fn correlation_mismatch(o: &Observation<'_>) -> bool { if o.record_kind() == "request" && c.request_id.as_deref() != Some(o.record_id()) { return true; } - if matches!(o.record_kind(), "attempt" | "metric") { - if let Some(id) = o.field("attemptId") { - if c.attempt_id.as_deref() != Some(id) { - return true; - } - } + if matches!(o.record_kind(), "attempt" | "metric") + && let Some(id) = o.field("attemptId") + && c.attempt_id.as_deref() != Some(id) + { + return true; } false } diff --git a/crates/rangoon-ops/src/relationship_tests.rs b/crates/rangoon-ops/src/relationship_tests.rs index bcf08ac..1dc4b97 100644 --- a/crates/rangoon-ops/src/relationship_tests.rs +++ b/crates/rangoon-ops/src/relationship_tests.rs @@ -92,6 +92,36 @@ fn document(value: &Value) -> Value { serde_json::to_value(related.document()).unwrap() } +fn inspection_documents(value: &Value) -> (Value, Value) { + let decoded = decode_window(&serde_json::to_vec(value).unwrap()).unwrap(); + let projection = project_window(&decoded).unwrap(); + let relationships = relate_window(&decoded).unwrap(); + let delegations = inspect_delegations(&decoded).unwrap(); + let approvals = inspect_approvals(&decoded).unwrap(); + let lifecycle = inspect_lifecycle(&decoded).unwrap(); + let view = build_operator_view( + &decoded, + &projection, + &relationships, + &delegations, + &approvals, + &lifecycle, + ) + .unwrap(); + ( + serde_json::to_value(relationships.document()).unwrap(), + serde_json::to_value(view.document()).unwrap(), + ) +} + +fn cross_producer_actor_event(record: Value) -> Value { + let mut observed = event(1, 510, record, Value::Null); + observed["producerId"] = json!(oid(12)); + observed["fenceId"] = json!(oid(22)); + observed["previousEventId"] = Value::Null; + observed +} + fn link_codes(document: &Value, record_id: &str) -> Vec { document["eventLinks"] .as_array() @@ -209,6 +239,133 @@ fn missing_wrong_kind_ambiguous_and_exact_repeat_references_remain_explicit() { assert_eq!(actor_reference["matchingEventOrdinals"], json!([0, 9])); } +#[test] +fn cross_producer_identical_actor_is_unique_unverified_and_minimized() { + let mut value = window(); + value["tail"] + .as_array_mut() + .unwrap() + .push(cross_producer_actor_event(actor())); + + let (relationships, view) = inspection_documents(&value); + let actor_reference = link(&relationships, &oid(108))["references"] + .as_array() + .unwrap() + .iter() + .find(|row| row["field"] == "actorId") + .unwrap(); + assert_eq!(actor_reference["status"], "unique_unverified"); + assert_eq!(actor_reference["matchingEventOrdinals"], json!([0, 9])); + assert_eq!(view["sourceCounts"]["eventCount"], 10); + assert_eq!(view["sourceCounts"]["producerCount"], 2); + assert_eq!(view["events"].as_array().unwrap().len(), 10); + assert_eq!( + view["events"][0], + json!({ + "inputOrdinal": 0, "producerOrdinal": 0, "fenceOrdinal": 0, + "sequence": 1, "recordKind": "actor", "reportedValue": null, + "structuralDiagnostics": [], "issueStages": [], "references": [] + }) + ); + assert_eq!( + view["events"][9], + json!({ + "inputOrdinal": 9, "producerOrdinal": 1, "fenceOrdinal": 0, + "sequence": 1, "recordKind": "actor", "reportedValue": null, + "structuralDiagnostics": [], "issueStages": [], "references": [] + }) + ); + for (field, expected) in [ + ("authority", "none"), + ("authenticity", "unverified"), + ("eligibility", "unknown"), + ("execution", "unavailable"), + ("outcome", "unknown"), + ("coverage", "unknown"), + ] { + assert_eq!(view[field], expected); + } + let rendered = serde_json::to_string(&view).unwrap(); + for source_only in [ + oid(100), + oid(501), + oid(510), + oid(11), + oid(12), + oid(21), + oid(22), + digest(5), + digest(8), + ] { + assert!( + !rendered.contains(&source_only), + "source identity leaked: {source_only}" + ); + } +} + +#[test] +fn cross_producer_changed_actor_is_ambiguous_and_conflicting() { + let mut value = window(); + let mut changed_actor = actor(); + changed_actor["canonicalSubjectId"] = json!(oid(201)); + value["tail"] + .as_array_mut() + .unwrap() + .push(cross_producer_actor_event(changed_actor)); + + let (relationships, view) = inspection_documents(&value); + let request = link(&relationships, &oid(108)); + let actor_reference = request["references"] + .as_array() + .unwrap() + .iter() + .find(|row| row["field"] == "actorId") + .unwrap(); + assert_eq!(actor_reference["status"], "ambiguous"); + assert_eq!(actor_reference["matchingEventOrdinals"], json!([0, 9])); + assert_eq!(request["assessment"], "ambiguous"); + assert_eq!(view["structuralState"], "conflict"); + for ordinal in [0, 9] { + assert_eq!( + view["events"][ordinal]["structuralDiagnostics"], + json!(["record_identity_conflict"]) + ); + assert_eq!( + view["events"][ordinal]["issueStages"], + json!(["structural", "delegations"]) + ); + } + for (field, expected) in [ + ("authority", "none"), + ("authenticity", "unverified"), + ("eligibility", "unknown"), + ("execution", "unavailable"), + ("outcome", "unknown"), + ("coverage", "unknown"), + ] { + assert_eq!(view[field], expected); + } + let rendered = serde_json::to_string(&view).unwrap(); + for source_only in [ + oid(100), + oid(201), + oid(501), + oid(510), + oid(11), + oid(12), + oid(21), + oid(22), + digest(5), + digest(8), + ] { + assert!( + !rendered.contains(&source_only), + "source identity leaked: {source_only}" + ); + } +} + #[test] fn branching_cycle_disconnected_and_lineage_fence_observations_never_pick_a_tip() { let mut branch = window(); diff --git a/crates/rangoon-ops/src/relationships.rs b/crates/rangoon-ops/src/relationships.rs index 2b7ae9e..03e1832 100644 --- a/crates/rangoon-ops/src/relationships.rs +++ b/crates/rangoon-ops/src/relationships.rs @@ -217,12 +217,11 @@ pub fn relate_window(decoded: &DecodedWindow) -> Result) -> fmt::Result { + f.write_str(match self { + Self::TooLarge => "Recovery input exceeds a supported limit.", + Self::Unsupported => "Recovery format is unsupported.", + Self::InvalidOrUnreadable => "Recovery data or identity is invalid or unreadable.", + Self::Unavailable => "Recovery operation is unavailable.", + }) + } +} +impl std::error::Error for Error {} + +/// Explicit caller-supplied X25519 identity, with no file/key discovery. +/// +/// ```compile_fail +/// fn serializable() {} +/// serializable::(); +/// ``` +pub struct RecoveryIdentity(age::x25519::Identity); + +impl RecoveryIdentity { + pub fn parse(secret: Zeroizing) -> Result { + if secret.len() > MAX_KEY_TEXT { + return Err(Error::InvalidOrUnreadable); + } + secret + .parse() + .map(Self) + .map_err(|_| Error::InvalidOrUnreadable) + } + pub fn recipient(&self) -> RecoveryRecipient { + RecoveryRecipient(self.0.to_public()) + } +} +impl fmt::Debug for RecoveryIdentity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RecoveryIdentity()") + } +} + +pub struct RecoveryRecipient(age::x25519::Recipient); +impl RecoveryRecipient { + pub fn parse(public: &str) -> Result { + if public.len() > MAX_KEY_TEXT { + return Err(Error::InvalidOrUnreadable); + } + public + .parse() + .map(Self) + .map_err(|_| Error::InvalidOrUnreadable) + } +} +impl fmt::Debug for RecoveryRecipient { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RecoveryRecipient") + } +} + +/// Fully decrypted envelope body; logical backup validity remains unassessed. +/// Caller copies and OS memory are outside this buffer's cleanup guarantee. +/// +/// ```compile_fail +/// fn serializable() {} +/// serializable::(); +/// ``` +pub struct RecoveredBackup(Zeroizing>); +impl RecoveredBackup { + pub fn as_bytes(&self) -> &[u8] { + &self.0[INNER_VERSION.len()..] + } +} +impl fmt::Debug for RecoveredBackup { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RecoveredBackup()") + } +} + +struct BoundedOutput(Vec); +impl Write for BoundedOutput { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if bytes.len() > MAX_CIPHERTEXT_BYTES.saturating_sub(self.0.len()) { + return Err(io::Error::other("Ciphertext limit.")); + } + self.0 + .try_reserve(bytes.len()) + .map_err(|_| io::Error::other("Allocation unavailable."))?; + self.0.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Wrap opaque backup bytes. This does not establish logical backup validity. +pub fn encrypt(backup: &[u8], recipient: &RecoveryRecipient) -> Result, Error> { + if backup.len() > MAX_BACKUP_BYTES { + return Err(Error::TooLarge); + } + let encryptor = + age::Encryptor::with_recipients(std::iter::once(&recipient.0 as &dyn age::Recipient)) + .map_err(|_| Error::Unavailable)?; + let mut writer = encryptor + .wrap_output(BoundedOutput(Vec::new())) + .map_err(|_| Error::Unavailable)?; + writer + .write_all(INNER_VERSION) + .map_err(|_| Error::Unavailable)?; + writer.write_all(backup).map_err(|_| Error::Unavailable)?; + let bytes = writer.finish().map_err(|_| Error::Unavailable)?.0; + guard_header(&bytes).map_err(|_| Error::Unavailable)?; + Ok(bytes) +} + +// Resource preflight only. Cryptographic header validation belongs to age. +fn guard_header(bytes: &[u8]) -> Result<(), Error> { + if bytes.len() > MAX_CIPHERTEXT_BYTES { + return Err(Error::TooLarge); + } + if !bytes.starts_with(OUTER_VERSION) { + return Err(Error::Unsupported); + } + let bounded = &bytes[..bytes.len().min(MAX_HEADER_BYTES)]; + let start = bounded + .windows(5) + .position(|part| part == b"\n--- ") + .ok_or(Error::InvalidOrUnreadable)? + + 1; + let end = start + + bounded[start..] + .iter() + .position(|byte| *byte == b'\n') + .ok_or(Error::InvalidOrUnreadable)? + + 1; + if bounded[..end] + .split(|byte| *byte == b'\n') + .filter(|line| line.starts_with(b"-> ")) + .count() + > MAX_STANZAS + { + return Err(Error::InvalidOrUnreadable); + } + Ok(()) +} + +/// Never exposes chunks before the complete authenticated EOF and inner version. +pub fn decrypt(ciphertext: &[u8], identity: &RecoveryIdentity) -> Result { + guard_header(ciphertext)?; + let decryptor = + age::Decryptor::new_buffered(ciphertext).map_err(|_| Error::InvalidOrUnreadable)?; + if decryptor.is_scrypt() { + return Err(Error::Unsupported); + } + let mut reader = decryptor + .decrypt(std::iter::once(&identity.0 as &dyn age::Identity)) + .map_err(|_| Error::InvalidOrUnreadable)?; + let limit = MAX_BACKUP_BYTES + INNER_VERSION.len(); + let mut body = Zeroizing::new(Vec::new()); + let mut chunk = Zeroizing::new([0u8; 8192]); + loop { + let count = reader + .read(&mut chunk[..]) + .map_err(|_| Error::InvalidOrUnreadable)?; + if count == 0 { + break; + } + if count > limit.saturating_sub(body.len()) { + return Err(Error::TooLarge); + } + body.try_reserve(count).map_err(|_| Error::Unavailable)?; + body.extend_from_slice(&chunk[..count]); + } + if !body.starts_with(INNER_VERSION) { + return Err(Error::Unsupported); + } + Ok(RecoveredBackup(body)) +} diff --git a/crates/rangoon-recovery/tests/envelope.rs b/crates/rangoon-recovery/tests/envelope.rs new file mode 100644 index 0000000..6782a4e --- /dev/null +++ b/crates/rangoon-recovery/tests/envelope.rs @@ -0,0 +1,280 @@ +use rangoon_recovery::{ + Error, MAX_BACKUP_BYTES, MAX_CIPHERTEXT_BYTES, MAX_HEADER_BYTES, RecoveryIdentity, + RecoveryRecipient, decrypt, encrypt, +}; +use serde::Deserialize; +use std::io::Write; +use zeroize::Zeroizing; + +#[derive(Deserialize)] +struct Fixture { + identity: String, + recipient: String, + #[serde(rename = "backupHex")] + backup_hex: String, + #[serde(rename = "ageCiphertextHex")] + ciphertext_hex: String, +} +fn fixture() -> Fixture { + serde_json::from_str(include_str!("fixtures/reference-age-v1.json")).unwrap() +} +fn identity() -> RecoveryIdentity { + RecoveryIdentity::parse(Zeroizing::new(fixture().identity)).unwrap() +} +fn recipient() -> RecoveryRecipient { + RecoveryRecipient::parse(&fixture().recipient).unwrap() +} +fn hex(value: &str) -> Vec { + let (pairs, remainder) = value.as_bytes().as_chunks::<2>(); + assert!(remainder.is_empty()); + pairs + .iter() + .map(|part| u8::from_str_radix(std::str::from_utf8(part).unwrap(), 16).unwrap()) + .collect() +} +// Independent library call lets tests create authenticated unsupported/oversized bodies. +fn raw_age_body(body: &[u8]) -> Vec { + let public: age::x25519::Recipient = fixture().recipient.parse().unwrap(); + let e = + age::Encryptor::with_recipients(std::iter::once(&public as &dyn age::Recipient)).unwrap(); + let mut writer = e.wrap_output(Vec::new()).unwrap(); + writer.write_all(body).unwrap(); + writer.finish().unwrap() +} + +#[test] +fn independent_go_reference_decrypts_exact_binary_backup() { + let f = fixture(); + let recovered = decrypt(&hex(&f.ciphertext_hex), &identity()).unwrap(); + assert_eq!(recovered.as_bytes(), hex(&f.backup_hex)); +} + +#[test] +fn round_trip_preserves_empty_binary_bom_crlf_and_unicode() { + for body in [ + b"".as_slice(), + b"\0\xff\x01", + b"\xef\xbb\xbf# Instructions\r\nKeep exact bytes.\r\n", + "# Review\nစမ်းသပ် ✓".as_bytes(), + ] { + let ciphertext = encrypt(body, &recipient()).unwrap(); + assert!(ciphertext.starts_with(b"age-encryption.org/v1\n")); + assert_eq!(decrypt(&ciphertext, &identity()).unwrap().as_bytes(), body); + } +} + +#[test] +fn supplied_public_recipient_matches_identity_derived_recipient() { + let body = b"Exact supplied public recipient"; + let encrypted = encrypt(body, &identity().recipient()).unwrap(); + assert_eq!(decrypt(&encrypted, &identity()).unwrap().as_bytes(), body); +} + +#[test] +fn fresh_randomness_changes_repeated_ciphertext() { + let first = encrypt(b"Repeated public canary", &recipient()).unwrap(); + let second = encrypt(b"Repeated public canary", &recipient()).unwrap(); + assert_ne!(first, second); + assert_eq!( + decrypt(&first, &identity()).unwrap().as_bytes(), + decrypt(&second, &identity()).unwrap().as_bytes() + ); +} + +#[test] +fn chunk_boundaries_require_final_authentication() { + for size in [65516, 65517, 65518, 65535, 65536, 65537, 131072] { + let body = vec![0x93; size]; + let ciphertext = encrypt(&body, &recipient()).unwrap(); + assert_eq!(decrypt(&ciphertext, &identity()).unwrap().as_bytes(), body); + assert!(decrypt(&ciphertext[..ciphertext.len() - 1], &identity()).is_err()); + let mut corrupt = ciphertext; + *corrupt.last_mut().unwrap() ^= 1; + assert!(decrypt(&corrupt, &identity()).is_err()); + } +} + +#[test] +fn maximum_backup_round_trips_and_one_extra_byte_is_refused() { + let mut body = vec![0x5a; MAX_BACKUP_BYTES]; + let ciphertext = encrypt(&body, &recipient()).unwrap(); + assert!(ciphertext.len() < MAX_CIPHERTEXT_BYTES); + assert_eq!(decrypt(&ciphertext, &identity()).unwrap().as_bytes(), body); + body.push(1); + assert_eq!(encrypt(&body, &recipient()).unwrap_err(), Error::TooLarge); +} + +#[test] +fn ciphertext_limit_refuses_before_version_or_decryption() { + assert_eq!( + decrypt(&vec![0; MAX_CIPHERTEXT_BYTES + 1], &identity()).unwrap_err(), + Error::TooLarge + ); +} + +#[test] +fn fully_authenticated_oversized_plaintext_is_not_returned() { + let mut body = b"RANGOON-RECOVERY-V1\n".to_vec(); + body.resize(body.len() + MAX_BACKUP_BYTES + 1, 0xa1); + let ciphertext = raw_age_body(&body); + assert!(ciphertext.len() < MAX_CIPHERTEXT_BYTES); + assert_eq!( + decrypt(&ciphertext, &identity()).unwrap_err(), + Error::TooLarge + ); +} + +#[test] +fn wrong_identity_never_returns_any_plaintext() { + use age::secrecy::ExposeSecret; + let wrong = age::x25519::Identity::generate().to_string(); + let wrong = RecoveryIdentity::parse(Zeroizing::new(wrong.expose_secret().to_owned())).unwrap(); + let ciphertext = encrypt(b"Do not release partial data", &recipient()).unwrap(); + assert_eq!( + decrypt(&ciphertext, &wrong).unwrap_err(), + Error::InvalidOrUnreadable + ); +} + +#[test] +fn every_single_byte_tamper_of_small_reference_is_refused() { + let bytes = hex(&fixture().ciphertext_hex); + for index in 0..bytes.len() { + let mut altered = bytes.clone(); + altered[index] ^= 1; + assert!(decrypt(&altered, &identity()).is_err(), "Tamper at {index}"); + } +} + +#[test] +fn every_reference_truncation_trailing_byte_and_concatenation_is_refused() { + let bytes = hex(&fixture().ciphertext_hex); + for size in 0..bytes.len() { + assert!( + decrypt(&bytes[..size], &identity()).is_err(), + "Truncation at {size}" + ); + } + for tail in [b"x".as_slice(), b"\n", bytes.as_slice()] { + let mut appended = bytes.clone(); + appended.extend_from_slice(tail); + assert!(decrypt(&appended, &identity()).is_err()); + } +} + +#[test] +fn unsupported_authenticated_inner_versions_are_not_backup_bytes() { + for body in [ + b"RANGOON-RECOVERY-V2\nSecret".as_slice(), + b"RANGOON-RECOVERY-V1\r\nSecret", + b"Unframed secret", + b"", + ] { + assert_eq!( + decrypt(&raw_age_body(body), &identity()).unwrap_err(), + Error::Unsupported + ); + } +} + +#[test] +fn outer_versions_armor_and_invalid_key_types_are_refused() { + for body in [ + b"age-encryption.org/v2\n".as_slice(), + b"-----BEGIN AGE ENCRYPTED FILE-----\n", + b"not an archive", + ] { + assert_eq!(decrypt(body, &identity()).unwrap_err(), Error::Unsupported); + } + for key in [ + "", + "age-plugin-../../canary", + "AGE-PLUGIN-FAKE-1", + "ssh-ed25519 AAAA", + &"a".repeat(129), + ] { + assert_eq!( + RecoveryIdentity::parse(Zeroizing::new(key.to_owned())).unwrap_err(), + Error::InvalidOrUnreadable + ); + assert_eq!( + RecoveryRecipient::parse(key).unwrap_err(), + Error::InvalidOrUnreadable + ); + } +} + +#[test] +fn passphrase_envelopes_are_unsupported_without_attempting_password_recovery() { + // Deliberately cheap fixture generation; this is never an accepted profile. + let mut passphrase = age::scrypt::Recipient::new(age::secrecy::SecretString::from( + "PUBLIC TEST PASSPHRASE".to_owned(), + )); + passphrase.set_work_factor(1); + let e = age::Encryptor::with_recipients(std::iter::once(&passphrase as &dyn age::Recipient)) + .unwrap(); + let mut writer = e.wrap_output(Vec::new()).unwrap(); + writer.write_all(b"RANGOON-RECOVERY-V1\nCanary").unwrap(); + let ciphertext = writer.finish().unwrap(); + assert_eq!( + decrypt(&ciphertext, &identity()).unwrap_err(), + Error::Unsupported + ); +} + +#[test] +fn resource_preflight_refuses_large_headers_and_many_stanzas() { + let mut header = b"age-encryption.org/v1\n".to_vec(); + header.extend_from_slice(&vec![b'x'; MAX_HEADER_BYTES]); + header.extend_from_slice(b"\n--- "); + header.extend_from_slice(&[b'A'; 43]); + header.push(b'\n'); + assert!(decrypt(&header, &identity()).is_err()); + let mut many = b"age-encryption.org/v1\n".to_vec(); + for _ in 0..9 { + many.extend_from_slice(b"-> X25519 AAAA\nAAAA\n"); + } + many.extend_from_slice(b"--- "); + many.extend_from_slice(&[b'A'; 43]); + many.push(b'\n'); + assert_eq!( + decrypt(&many, &identity()).unwrap_err(), + Error::InvalidOrUnreadable + ); +} + +#[test] +fn malformed_corpus_never_panics_or_returns_content() { + let mut seed = 0x72616e676f6f6eu64; + for size in 0..512 { + let mut bytes = Vec::with_capacity(size); + for _ in 0..size { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + bytes.push(seed as u8); + } + if size % 2 == 0 { + bytes.splice(0..0, b"age-encryption.org/v1\n".iter().copied()); + } + assert!(decrypt(&bytes, &identity()).is_err()); + } +} + +#[test] +fn errors_and_secret_owners_have_fixed_redacted_diagnostics() { + let f = fixture(); + let identity = identity(); + let recovered = decrypt(&hex(&f.ciphertext_hex), &identity).unwrap(); + assert_eq!(format!("{identity:?}"), "RecoveryIdentity()"); + assert_eq!(format!("{recovered:?}"), "RecoveredBackup()"); + for error in [ + Error::TooLarge, + Error::Unsupported, + Error::InvalidOrUnreadable, + Error::Unavailable, + ] { + assert!(!format!("{error:?}: {error}").contains(&f.identity)); + assert!(std::error::Error::source(&error).is_none()); + } +} diff --git a/crates/rangoon-recovery/tests/fixtures/reference-age-v1.json b/crates/rangoon-recovery/tests/fixtures/reference-age-v1.json new file mode 100644 index 0000000..fbe3055 --- /dev/null +++ b/crates/rangoon-recovery/tests/fixtures/reference-age-v1.json @@ -0,0 +1,9 @@ +{ + "notice": "PUBLIC SYNTHETIC TEST IDENTITY. Never use for real data.", + "reference": "FiloSottile/age v1.3.2, official darwin-amd64 release", + "referenceBinarySha256": "0c2fbcffab91d0af398162a8ed792e096916c8c47c3c400e303904431103f492", + "identity": "AGE-SECRET-KEY-15HS2FWZJUN5WNYTSQ9GU76WDM3JVV6X5KQJD0U2CZQ0RQRVU32KQTZR8FE", + "recipient": "age18hqzkzzawdc88px4u3axlkjal4uqkk8dzmqu32d5av5mzeh4apcskeqdhw", + "backupHex": "efbbbf23205265636f766572656420696e737472756374696f6e730d0a4b6565702070726f76656e616e63652e20e29c930a00ff", + "ageCiphertextHex": "6167652d656e6372797074696f6e2e6f72672f76310a2d3e205832353531392065554a33666f655447302f5139744f6f7a685a325873613648394a69534d57544176692f47726c6a5847770a54587a66454454694a554178576b54326f442b417456554b2f75624868585472394d50595171765a6732770a2d2d2d206c63634d396564526d547a476f4867484e75366f707530504962697856636956436d4776616f4968354d630a9e944063475f50e3c7d6153124b7185cb7d75f282dbc0ffc3c4b95a7933a4976faafdfd8c960763a48885b26e44d235b1f04959aa41b15e36f8d2c3593367f23caa5bb25678c2f59b30b09a31e1e7eedf7ec1e4826e63ad0e1d736c78acd580120467ffcdd19954a" +} diff --git a/crates/rangoon-store/src/composition_backup.rs b/crates/rangoon-store/src/composition_backup.rs index 15d42cb..1c8674f 100644 --- a/crates/rangoon-store/src/composition_backup.rs +++ b/crates/rangoon-store/src/composition_backup.rs @@ -268,6 +268,8 @@ pub(super) fn encode(records: &Records) -> Result, StoreError> { if !(1..=3).contains(&records.version) || !records.workflows.owners.is_empty() || !records.workflows.revisions.is_empty() + || !records.history.changes.is_empty() + || !records.history.events.is_empty() { return Err(StoreError::UnsupportedSchema); } @@ -430,12 +432,14 @@ pub(super) fn ensure_schema(db: &Connection, version: i64) -> Result<(), StoreEr verify_schema(db) } pub(super) fn canonical_database(records: &Records) -> Result { - if records.version == 4 { + if matches!(records.version, 4 | 5) { return workflow_backup::canonical_database(records); } if !(1..=3).contains(&records.version) || !records.workflows.owners.is_empty() || !records.workflows.revisions.is_empty() + || !records.history.changes.is_empty() + || !records.history.events.is_empty() { return Err(StoreError::UnsupportedSchema); } diff --git a/crates/rangoon-store/src/composition_records.rs b/crates/rangoon-store/src/composition_records.rs index c2d0331..00c8e27 100644 --- a/crates/rangoon-store/src/composition_records.rs +++ b/crates/rangoon-store/src/composition_records.rs @@ -90,6 +90,7 @@ pub(super) struct Records { pub recipes: BTreeMap, pub applications: BTreeMap, pub workflows: workflow_records::WorkflowRows, + pub history: instruction_history::HistoryRows, histories: BTreeMap>, } @@ -111,6 +112,7 @@ impl Records { recipes: BTreeMap::new(), applications: BTreeMap::new(), workflows: workflow_records::WorkflowRows::default(), + history: instruction_history::HistoryRows::default(), histories: BTreeMap::new(), } } @@ -136,6 +138,7 @@ impl Records { recipes: BTreeMap::new(), applications: BTreeMap::new(), workflows: workflow_records::WorkflowRows::default(), + history: instruction_history::HistoryRows::default(), histories: BTreeMap::new(), }; for metadata in list_metadata(db)? { @@ -149,13 +152,16 @@ impl Records { records.load_owners(db)?; records.load_revisions(db)?; } - if matches!(version, 3 | 4) { + if matches!(version, 3..=5) { records.load_compositions(db)?; } records.validate()?; - if version == 4 { + if version >= 4 { records.workflows = workflow_records::WorkflowRows::load(db, &records)?; } + if version == 5 { + records.history = instruction_history::HistoryRows::load(db, &records)?; + } Ok(records) } @@ -184,7 +190,7 @@ impl Records { }, ); } - if matches!(self.version, 3 | 4) { + if matches!(self.version, 3..=5) { check_count( db, "SELECT count(*) FROM derived_capabilities", @@ -786,6 +792,12 @@ impl Records { } pub fn state_id(&self) -> Result { + if self.version == 5 { + return self.history.state_id(self); + } + if !self.history.changes.is_empty() || !self.history.events.is_empty() { + return Err(StoreError::Corrupt); + } if self.version == 4 { return self.workflows.state_id_v4(self); } diff --git a/crates/rangoon-store/src/encryption.rs b/crates/rangoon-store/src/encryption.rs index ba7e584..912acae 100644 --- a/crates/rangoon-store/src/encryption.rs +++ b/crates/rangoon-store/src/encryption.rs @@ -96,7 +96,7 @@ mod keyed { let verify = || -> rusqlite::Result<()> { key(db, secret)?; if file_bytes != 0 { - if file_bytes % 4096 != 0 { + if !file_bytes.is_multiple_of(4096) { return Err(rusqlite::Error::InvalidQuery); } // Consume only row existence. Never retrieve page/error text. diff --git a/crates/rangoon-store/src/instruction_history.rs b/crates/rangoon-store/src/instruction_history.rs new file mode 100644 index 0000000..69d2ddc --- /dev/null +++ b/crates/rangoon-store/src/instruction_history.rs @@ -0,0 +1,890 @@ +//! Exact instruction restore points. Persistence is encrypted-only; no file writes. +use super::*; +use composition_records::Records; +use rangoon_compose::InputReference; +use rangoon_domain::{AnalysisReport, byte_digest, capability::valid_id}; +use std::collections::{BTreeMap, BTreeSet}; +use zeroize::Zeroize; + +pub const MAX_INSTRUCTION_CHANGES: usize = 128; +pub const MAX_INSTRUCTION_EVENTS: usize = 512; +pub const MAX_INSTRUCTION_BYTES: usize = 256 * 1024; +pub const MAX_INSTRUCTION_HISTORY_BYTES: usize = 16 * 1024 * 1024; +pub(super) const MAX_RECORD_BYTES: usize = 2 * MAX_INSTRUCTION_BYTES * 4 + 16 * 1024; +pub(super) const SCHEMAS: &[(&str, &str)] = &[ + ( + "instruction_changes", + "CREATE TABLE instruction_changes (change_id TEXT PRIMARY KEY NOT NULL, record_json BLOB NOT NULL)", + ), + ( + "instruction_events", + "CREATE TABLE instruction_events (event_id TEXT PRIMARY KEY NOT NULL, record_json BLOB NOT NULL)", + ), +]; + +/// Native-selected identities, never evidence that filesystem custody was acquired. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct InstructionTarget { + pub workspace_identity: String, + pub target_identity: String, + pub parent_identity: String, + pub file_name: String, + pub file_identity: Option, +} +impl InstructionTarget { + fn valid(&self) -> bool { + [ + &self.workspace_identity, + &self.target_identity, + &self.parent_identity, + ] + .iter() + .all(|id| valid_id(id, "")) + && self + .file_identity + .as_ref() + .is_none_or(|id| valid_id(id, "")) + && !self.file_name.is_empty() + && self.file_name.len() <= 255 + && !matches!(self.file_name.as_str(), "." | "..") + && !self + .file_name + .chars() + .any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '\u{2028}' | '\u{2029}')) + } + fn same_location(&self, other: &Self) -> bool { + self.workspace_identity == other.workspace_identity + && self.target_identity == other.target_identity + && self.parent_identity == other.parent_identity + && self.file_name == other.file_name + } +} + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ChangeWire { + schema_version: String, + target: InstructionTarget, + before: Option>, + after: Option>, + before_sha256: Option, + after_sha256: Option, + inputs: Vec, + composition_id: Option, + parent_change_id: Option, + created_at_ms: i64, +} +impl Drop for ChangeWire { + fn drop(&mut self) { + if let Some(bytes) = &mut self.before { + bytes.zeroize(); + } + if let Some(bytes) = &mut self.after { + bytes.zeroize(); + } + } +} + +/// A native-host value with private validated bytes. Never renderer JSON input. +#[derive(Clone, PartialEq, Eq)] +pub struct InstructionChange { + id: String, + wire: ChangeWire, +} +impl std::fmt::Debug for InstructionChange { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("InstructionChange()") + } +} +impl InstructionChange { + #[allow(clippy::too_many_arguments)] + pub fn prepare( + target: InstructionTarget, + before: Option<&[u8]>, + after: Option<&[u8]>, + inputs: Vec, + composition_id: Option, + parent_change_id: Option, + created_at_ms: i64, + ) -> Result { + // Check lengths before copying native-captured originals. + if before.is_some_and(|b| b.len() > MAX_INSTRUCTION_BYTES) + || after.is_some_and(|b| b.len() > MAX_INSTRUCTION_BYTES) + { + return Err(StoreError::InstructionHistoryInvalid); + } + let wire = ChangeWire { + schema_version: "rangoon.instruction-change.v1".into(), + target, + before: before.map(<[u8]>::to_vec), + after: after.map(<[u8]>::to_vec), + before_sha256: before.map(byte_digest), + after_sha256: after.map(byte_digest), + inputs, + composition_id, + parent_change_id, + created_at_ms, + }; + Self::from_wire(wire) + } + fn from_wire(wire: ChangeWire) -> Result { + if wire.schema_version != "rangoon.instruction-change.v1" + || !wire.target.valid() + || wire.before == wire.after + || wire.target.file_identity.is_some() != wire.before.is_some() + || wire + .before + .as_ref() + .is_some_and(|b| b.len() > MAX_INSTRUCTION_BYTES) + || wire + .after + .as_ref() + .is_some_and(|b| b.len() > MAX_INSTRUCTION_BYTES) + || wire.before.as_deref().map(byte_digest) != wire.before_sha256 + || wire.after.as_deref().map(byte_digest) != wire.after_sha256 + || wire.inputs.len() > 16 + || !valid_time(wire.created_at_ms) + || wire + .composition_id + .as_ref() + .is_some_and(|id| !valid_id(id, "composition:")) + || wire + .parent_change_id + .as_ref() + .is_some_and(|id| !valid_id(id, "instruction-change:")) + { + return Err(StoreError::InstructionHistoryInvalid); + } + let mut unique = BTreeSet::new(); + for input in &wire.inputs { + let (id, digest) = match input { + InputReference::Source { source_id, sha256 } if valid_id(source_id, "source:") => { + (source_id, sha256) + } + InputReference::Revision { + capability_id, + revision_id, + sha256, + } if valid_id(capability_id, "capability:") + && valid_id(revision_id, "revision:") => + { + (revision_id, sha256) + } + _ => return Err(StoreError::InstructionHistoryInvalid), + }; + if !valid_id(digest, "") || !unique.insert(id) { + return Err(StoreError::InstructionHistoryInvalid); + } + } + let bytes = zeroize::Zeroizing::new( + serde_json::to_vec(&wire).map_err(|_| StoreError::InstructionHistoryInvalid)?, + ); + if bytes.len() > MAX_RECORD_BYTES { + return Err(StoreError::InstructionHistoryInvalid); + } + Ok(Self { + id: format!("instruction-change:{}", byte_digest(&bytes)), + wire, + }) + } + pub fn id(&self) -> &str { + &self.id + } + pub fn target(&self) -> &InstructionTarget { + &self.wire.target + } + pub fn parent_change_id(&self) -> Option<&str> { + self.wire.parent_change_id.as_deref() + } + pub fn inputs(&self) -> &[InputReference] { + &self.wire.inputs + } + pub fn composition_id(&self) -> Option<&str> { + self.wire.composition_id.as_deref() + } + pub fn created_at_ms(&self) -> i64 { + self.wire.created_at_ms + } + /// Trusted host access to exact originals. No renderer command is registered. + pub fn before(&self) -> Option<&[u8]> { + self.wire.before.as_deref() + } + pub fn after(&self) -> Option<&[u8]> { + self.wire.after.as_deref() + } + pub fn before_sha256(&self) -> Option<&str> { + self.wire.before_sha256.as_deref() + } + pub fn after_sha256(&self) -> Option<&str> { + self.wire.after_sha256.as_deref() + } + /// Reuses the deterministic analyzer; unsupported/binary bytes remain archived. + /// Its fragments and categories are advisory, never restoration authority. + pub fn analyze_after(&self) -> Result { + analyze( + &self.wire.target.file_name, + self.after().ok_or(StoreError::InstructionHistoryInvalid)?, + ) + .map_err(|_| StoreError::InstructionHistoryInvalid) + } + pub(super) fn bytes(&self) -> Result>, StoreError> { + Ok(zeroize::Zeroizing::new( + serde_json::to_vec(&self.wire).map_err(|_| StoreError::Corrupt)?, + )) + } + pub(super) fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_RECORD_BYTES { + return Err(StoreError::InstructionHistoryInvalid); + } + let wire = + serde_json::from_slice(bytes).map_err(|_| StoreError::InstructionHistoryInvalid)?; + let value = Self::from_wire(wire)?; + if value.bytes()?.as_slice() != bytes { + return Err(StoreError::InstructionHistoryInvalid); + } + Ok(value) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InstructionPhase { + Attempted, + Verified, + Failed, + Unknown, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Observation { + file_identity: Option, + sha256: Option, + byte_length: Option, +} +impl Observation { + fn capture(file_identity: Option, bytes: Option<&[u8]>) -> Result { + if file_identity.is_some() != bytes.is_some() + || file_identity.as_ref().is_some_and(|id| !valid_id(id, "")) + || bytes.is_some_and(|b| b.len() > MAX_INSTRUCTION_BYTES) + { + return Err(StoreError::InstructionHistoryInvalid); + } + Ok(Self { + file_identity, + sha256: bytes.map(byte_digest), + byte_length: bytes.map(|b| b.len() as u32), + }) + } + fn valid(&self) -> bool { + match (&self.file_identity, &self.sha256, self.byte_length) { + (None, None, None) => true, + (Some(id), Some(sha), Some(len)) => { + valid_id(id, "") && valid_id(sha, "") && len as usize <= MAX_INSTRUCTION_BYTES + } + _ => false, + } + } +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EventWire { + schema_version: String, + change_id: String, + parent_event_id: Option, + phase: InstructionPhase, + observation: Option, + observed_at_ms: i64, +} +#[derive(Clone, PartialEq, Eq)] +pub struct InstructionEvent { + id: String, + wire: EventWire, +} +impl std::fmt::Debug for InstructionEvent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("InstructionEvent()") + } +} +impl InstructionEvent { + /// Trusted native caller supplies readback bytes. This value is not an + /// authorization receipt or proof that the caller acquired exclusive custody. + pub fn prepare( + change_id: String, + parent_event_id: Option, + phase: InstructionPhase, + observation: Option<(Option, Option<&[u8]>)>, + observed_at_ms: i64, + ) -> Result { + Self::from_wire(EventWire { + schema_version: "rangoon.instruction-event.v1".into(), + change_id, + parent_event_id, + phase, + observation: observation + .map(|(id, bytes)| Observation::capture(id, bytes)) + .transpose()?, + observed_at_ms, + }) + } + fn from_wire(wire: EventWire) -> Result { + if wire.schema_version != "rangoon.instruction-event.v1" + || !valid_id(&wire.change_id, "instruction-change:") + || wire + .parent_event_id + .as_ref() + .is_some_and(|id| !valid_id(id, "instruction-event:")) + || !valid_time(wire.observed_at_ms) + || wire.observation.as_ref().is_some_and(|o| !o.valid()) + || (wire.phase == InstructionPhase::Verified && wire.observation.is_none()) + || (wire.phase == InstructionPhase::Attempted && wire.observation.is_some()) + { + return Err(StoreError::InstructionHistoryInvalid); + } + let bytes = serde_json::to_vec(&wire).map_err(|_| StoreError::InstructionHistoryInvalid)?; + Ok(Self { + id: format!("instruction-event:{}", byte_digest(&bytes)), + wire, + }) + } + pub fn id(&self) -> &str { + &self.id + } + pub fn phase(&self) -> InstructionPhase { + self.wire.phase + } + pub fn change_id(&self) -> &str { + &self.wire.change_id + } + pub fn parent_event_id(&self) -> Option<&str> { + self.wire.parent_event_id.as_deref() + } + pub fn observed_at_ms(&self) -> i64 { + self.wire.observed_at_ms + } + pub(super) fn bytes(&self) -> Result, StoreError> { + serde_json::to_vec(&self.wire).map_err(|_| StoreError::Corrupt) + } + pub(super) fn decode(bytes: &[u8]) -> Result { + if bytes.len() > 2048 { + return Err(StoreError::InstructionHistoryInvalid); + } + let value = Self::from_wire( + serde_json::from_slice(bytes).map_err(|_| StoreError::InstructionHistoryInvalid)?, + )?; + if value.bytes()? != bytes { + return Err(StoreError::InstructionHistoryInvalid); + } + Ok(value) + } +} +fn valid_time(t: i64) -> bool { + (0..=8_640_000_000_000_000).contains(&t) +} + +#[derive(Clone, Debug, Default)] +pub(super) struct HistoryRows { + pub changes: BTreeMap, + pub events: BTreeMap, +} +impl HistoryRows { + pub fn load(db: &Connection, base: &Records) -> Result { + // Enforce the shared budget before copying or decoding any row. Per-table + // checks alone could exceed the combined bound during reconstruction. + let total: i64 = db.query_row("SELECT (SELECT coalesce(sum(length(record_json)),0) FROM instruction_changes) + (SELECT coalesce(sum(length(record_json)),0) FROM instruction_events)", [], |row| row.get(0))?; + if total < 0 || total as u64 > MAX_INSTRUCTION_HISTORY_BYTES as u64 { + return Err(StoreError::Full); + } + let mut result = Self::default(); + for (table, column, max_count, max_bytes) in [ + ( + "instruction_changes", + "change_id", + MAX_INSTRUCTION_CHANGES, + MAX_RECORD_BYTES, + ), + ( + "instruction_events", + "event_id", + MAX_INSTRUCTION_EVENTS, + 2048, + ), + ] { + let invalid: bool = db.query_row( + &format!( + "SELECT count(*) > ?1 OR coalesce(sum(length(record_json)),0) > ?2 FROM {table}" + ), + params![max_count as i64, MAX_INSTRUCTION_HISTORY_BYTES as i64], + |row| row.get(0), + )?; + let malformed: bool = db.query_row(&format!("SELECT EXISTS(SELECT 1 FROM {table} WHERE typeof({column}) != 'text' OR length(CAST({column} AS BLOB)) > 96 OR typeof(record_json) != 'blob' OR length(record_json) > ?1)"), [max_bytes as i64], |row| row.get(0))?; + if invalid || malformed { + return Err(StoreError::Corrupt); + } + let mut q = db.prepare(&format!( + "SELECT {column},record_json FROM {table} ORDER BY {column} LIMIT {}", + max_count + 1 + ))?; + let mut rows = q.query([])?; + while let Some(row) = rows.next()? { + let id: String = row.get(0)?; + let bytes: zeroize::Zeroizing> = zeroize::Zeroizing::new(row.get(1)?); + if table == "instruction_changes" { + let value = + InstructionChange::decode(&bytes).map_err(|_| StoreError::Corrupt)?; + if value.id != id || result.changes.insert(id, value).is_some() { + return Err(StoreError::Corrupt); + } + } else { + let value = + InstructionEvent::decode(&bytes).map_err(|_| StoreError::Corrupt)?; + if value.id != id || result.events.insert(id, value).is_some() { + return Err(StoreError::Corrupt); + } + } + } + } + result.validate(base)?; + Ok(result) + } + pub fn validate(&self, base: &Records) -> Result<(), StoreError> { + if self.changes.len() > MAX_INSTRUCTION_CHANGES + || self.events.len() > MAX_INSTRUCTION_EVENTS + { + return Err(StoreError::Full); + } + let mut total = 0usize; + let mut children = BTreeSet::new(); + for (id, change) in &self.changes { + if id != change.id() { + return Err(StoreError::Corrupt); + } + total = total + .checked_add(change.bytes()?.len()) + .ok_or(StoreError::Full)?; + if let Some(parent_id) = &change.wire.parent_change_id { + let parent = self + .changes + .get(parent_id) + .ok_or(StoreError::InstructionHistoryInvalid)?; + if !parent.wire.target.same_location(&change.wire.target) + || parent.after() != change.before() + || parent.wire.created_at_ms > change.wire.created_at_ms + { + return Err(StoreError::InstructionHistoryInvalid); + } + let mut seen = BTreeSet::new(); + let mut cursor = Some(id.as_str()); + while let Some(id) = cursor { + if !seen.insert(id) { + return Err(StoreError::InstructionHistoryInvalid); + } + cursor = self + .changes + .get(id) + .ok_or(StoreError::InstructionHistoryInvalid)? + .wire + .parent_change_id + .as_deref(); + } + } + for input in &change.wire.inputs { + let valid = match input { + InputReference::Source { source_id, sha256 } => base + .sources + .get(source_id) + .is_some_and(|s| &s.metadata.sha256 == sha256), + InputReference::Revision { + capability_id, + revision_id, + sha256, + } => base.revisions.get(revision_id).is_some_and(|r| { + &r.capability_id == capability_id && &r.revision.sha256 == sha256 + }), + }; + if !valid { + return Err(StoreError::RecordInUse); + } + } + if change + .wire + .composition_id + .as_ref() + .is_some_and(|id| !base.recipes.contains_key(id)) + { + return Err(StoreError::RecordInUse); + } + } + for (id, event) in &self.events { + if id != event.id() { + return Err(StoreError::Corrupt); + } + total = total + .checked_add(event.bytes()?.len()) + .ok_or(StoreError::Full)?; + let change = self + .changes + .get(&event.wire.change_id) + .ok_or(StoreError::InstructionHistoryInvalid)?; + if event.wire.observed_at_ms < change.wire.created_at_ms { + return Err(StoreError::InstructionHistoryInvalid); + } + match &event.wire.parent_event_id { + None => { + if event.wire.phase != InstructionPhase::Attempted + || !children.insert((event.wire.change_id.as_str(), None)) + { + return Err(StoreError::InstructionHistoryInvalid); + } + } + Some(parent_id) => { + let parent = self + .events + .get(parent_id) + .ok_or(StoreError::InstructionHistoryInvalid)?; + if parent.wire.change_id != event.wire.change_id + || parent.wire.observed_at_ms > event.wire.observed_at_ms + || parent.wire.phase != InstructionPhase::Attempted + || event.wire.phase == InstructionPhase::Attempted + || !children.insert((event.wire.change_id.as_str(), Some(parent_id))) + { + return Err(StoreError::InstructionHistoryInvalid); + } + } + } + if event.wire.phase == InstructionPhase::Verified { + let observation = event + .wire + .observation + .as_ref() + .ok_or(StoreError::InstructionHistoryInvalid)?; + if observation.sha256.as_deref() != change.after_sha256() + || observation.byte_length.map(|n| n as usize) + != change.after().map(<[u8]>::len) + { + return Err(StoreError::InstructionHistoryInvalid); + } + } + } + if total > MAX_INSTRUCTION_HISTORY_BYTES { + return Err(StoreError::Full); + } + Ok(()) + } + pub fn insert_all(&self, db: &Connection) -> Result<(), StoreError> { + for (id, change) in &self.changes { + db.execute( + "INSERT INTO instruction_changes VALUES (?1,?2)", + params![id, change.bytes()?.as_slice()], + )?; + } + for (id, event) in &self.events { + db.execute( + "INSERT INTO instruction_events VALUES (?1,?2)", + params![id, event.bytes()?], + )?; + } + Ok(()) + } + pub fn union(&self, other: &Self, base: &Records) -> Result { + let mut result = self.clone(); + for (id, value) in &other.changes { + if result.changes.get(id).is_some_and(|v| v != value) { + return Err(StoreError::InstructionHistoryInvalid); + } + result.changes.insert(id.clone(), value.clone()); + } + for (id, value) in &other.events { + if result.events.get(id).is_some_and(|v| v != value) { + return Err(StoreError::InstructionHistoryInvalid); + } + result.events.insert(id.clone(), value.clone()); + } + result.validate(base)?; + Ok(result) + } + pub fn state_id(&self, base: &Records) -> Result { + self.validate(base)?; + let bytes = serde_json::to_vec(&( + "rangoon.workspace-state.v3", + base.workflows.state_id_v4(base)?, + self.changes.keys().collect::>(), + self.events.keys().collect::>(), + )) + .map_err(|_| StoreError::Corrupt)?; + Ok(format!("workspace:{}", byte_digest(&bytes))) + } +} + +/// Exact-state deletion preview. Removing history is logical deletion, not erasure. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstructionHistoryDeletion { + id: String, + expected_state_id: String, + events: usize, +} +impl InstructionHistoryDeletion { + pub fn change_id(&self) -> &str { + &self.id + } + pub fn removed_event_count(&self) -> usize { + self.events + } + pub fn expected_state_id(&self) -> &str { + &self.expected_state_id + } +} + +impl Workspace { + fn require_history_key(&self) -> Result<(), StoreError> { + let key = self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + encryption::verify_backend(key) + } + /// Encrypted-only opt-in. Does not change any external instruction file. + pub fn save_instruction_change( + &self, + change: &InstructionChange, + expected_state_id: &str, + ) -> Result { + self.require_history_key()?; + let checked = InstructionChange::decode(&change.bytes()?)?; + let mut db = self + .connect_complete_read_only(false)? + .ok_or(StoreError::WorkspaceChanged)?; + let tx = db.transaction()?; + let current = workflow_mutations::read_records(&tx)?; + let result = prepare_change(¤t, &checked, expected_state_id)?; + tx.commit()?; + drop(db); + let mut db = self + .connect_complete(false)? + .ok_or(StoreError::WorkspaceChanged)?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let current = workflow_mutations::read_records(&tx)?; + let fresh = prepare_change(¤t, &checked, expected_state_id)?; + if fresh.state_id()? != result.state_id()? { + return Err(StoreError::WorkspaceChanged); + } + workflow_mutations::ensure_schema(&tx, 5)?; + tx.set_limit( + rusqlite::limits::Limit::SQLITE_LIMIT_LENGTH, + (rangoon_compose::MAX_DRAFT_BYTES + 4096) as i32, + )?; + #[cfg(test)] + composition_recovery_tests::fault_checkpoint(&tx, "after_instruction_history_schema")?; + if !current.history.changes.contains_key(checked.id()) { + tx.execute( + "INSERT INTO instruction_changes VALUES (?1,?2)", + params![checked.id(), checked.bytes()?.as_slice()], + )?; + } + #[cfg(test)] + composition_recovery_tests::fault_checkpoint(&tx, "after_instruction_history_change")?; + let actual = workflow_mutations::read_records(&tx)?; + if actual.state_id()? != fresh.state_id()? { + return Err(StoreError::Corrupt); + } + workflow_mutations::data(&tx, &actual)?; + tx.commit()?; + actual.state_id() + } + pub fn append_instruction_event( + &self, + event: &InstructionEvent, + expected_state_id: &str, + ) -> Result { + self.require_history_key()?; + let event = InstructionEvent::decode(&event.bytes()?)?; + let mut db = self + .connect_complete(false)? + .ok_or(StoreError::WorkspaceChanged)?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let current = workflow_mutations::read_records(&tx)?; + if current.version != 5 || current.state_id()? != expected_state_id { + return Err(StoreError::WorkspaceChanged); + } + let mut result = current.clone(); + if result + .history + .events + .insert(event.id().into(), event.clone()) + .is_some() + { + return Err(StoreError::InstructionHistoryInvalid); + } + result.history.validate(&result)?; + composition_backup::canonical_database(&result)?; + tx.execute( + "INSERT INTO instruction_events VALUES (?1,?2)", + params![event.id(), event.bytes()?], + )?; + #[cfg(test)] + composition_recovery_tests::fault_checkpoint(&tx, "after_instruction_history_event")?; + let actual = workflow_mutations::read_records(&tx)?; + if actual.state_id()? != result.state_id()? { + return Err(StoreError::Corrupt); + } + tx.commit()?; + actual.state_id() + } + pub fn instruction_changes(&self) -> Result, StoreError> { + self.require_history_key()?; + let Some(mut db) = self.connect_complete_read_only(false)? else { + return Ok(Vec::new()); + }; + let tx = db.transaction()?; + let records = workflow_mutations::read_records(&tx)?; + let values = records.history.changes.into_values().collect(); + tx.commit()?; + Ok(values) + } + pub fn instruction_events(&self, change_id: &str) -> Result, StoreError> { + self.require_history_key()?; + if !valid_id(change_id, "instruction-change:") { + return Err(StoreError::InstructionHistoryInvalid); + } + let mut db = self + .connect_complete_read_only(false)? + .ok_or(StoreError::NotFound)?; + let tx = db.transaction()?; + let records = workflow_mutations::read_records(&tx)?; + if !records.history.changes.contains_key(change_id) { + return Err(StoreError::NotFound); + } + let events = records + .history + .events + .into_values() + .filter(|e| e.change_id() == change_id) + .collect(); + tx.commit()?; + Ok(events) + } + pub fn inspect_instruction_restore( + &self, + id: &str, + target: &InstructionTarget, + current_bytes: Option<&[u8]>, + ) -> Result { + self.require_history_key()?; + if !valid_id(id, "instruction-change:") || !target.valid() { + return Err(StoreError::InstructionHistoryInvalid); + } + let mut db = self + .connect_complete_read_only(false)? + .ok_or(StoreError::NotFound)?; + let tx = db.transaction()?; + let records = workflow_mutations::read_records(&tx)?; + let change = records + .history + .changes + .get(id) + .ok_or(StoreError::NotFound)?; + let verified = records + .history + .events + .values() + .find(|e| e.wire.change_id == id && e.wire.phase == InstructionPhase::Verified) + .ok_or(StoreError::InstructionHistoryInvalid)?; + let observed = Observation::capture(target.file_identity.clone(), current_bytes)?; + if !target.same_location(change.target()) + || Some(&observed) != verified.wire.observation.as_ref() + || current_bytes != change.after() + { + return Err(StoreError::WorkspaceChanged); + } + // Eligibility only. Native custody, single-use preview and file replacement + // are deliberately not implemented by this read-only inspection. + let value = change.clone(); + tx.commit()?; + Ok(value) + } + pub fn prepare_instruction_history_deletion( + &self, + id: &str, + ) -> Result { + self.require_history_key()?; + let mut db = self + .connect_complete_read_only(false)? + .ok_or(StoreError::NotFound)?; + let tx = db.transaction()?; + let records = workflow_mutations::read_records(&tx)?; + let plan = deletion(&records, id)?; + tx.commit()?; + Ok(plan) + } + pub fn delete_instruction_history( + &self, + retained: &InstructionHistoryDeletion, + ) -> Result<(), StoreError> { + self.require_history_key()?; + let mut db = self + .connect_complete(false)? + .ok_or(StoreError::WorkspaceChanged)?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let records = workflow_mutations::read_records(&tx)?; + if &deletion(&records, &retained.id)? != retained { + return Err(StoreError::WorkspaceChanged); + } + for (id, event) in &records.history.events { + if event.wire.change_id == retained.id { + tx.execute("DELETE FROM instruction_events WHERE event_id=?1", [id])?; + } + } + tx.execute( + "DELETE FROM instruction_changes WHERE change_id=?1", + [&retained.id], + )?; + workflow_mutations::read_records(&tx)?; + tx.commit()?; + Ok(()) + } +} +fn deletion(records: &Records, id: &str) -> Result { + if !valid_id(id, "instruction-change:") { + return Err(StoreError::InstructionHistoryInvalid); + } + if !records.history.changes.contains_key(id) { + return Err(StoreError::NotFound); + } + if records + .history + .changes + .values() + .any(|c| c.wire.parent_change_id.as_deref() == Some(id)) + { + return Err(StoreError::RecordInUse); + } + Ok(InstructionHistoryDeletion { + id: id.into(), + expected_state_id: records.state_id()?, + events: records + .history + .events + .values() + .filter(|e| e.wire.change_id == id) + .count(), + }) +} +fn prepare_change( + current: &Records, + change: &InstructionChange, + expected: &str, +) -> Result { + if !valid_id(expected, "workspace:") || current.state_id()? != expected { + return Err(StoreError::WorkspaceChanged); + } + let mut result = current.clone(); + result.version = 5; + result + .history + .changes + .insert(change.id().into(), change.clone()); + result.history.validate(&result)?; + Records::load_complete(&composition_backup::canonical_database(&result)?) +} + +#[cfg(test)] +#[path = "instruction_history_tests.rs"] +mod tests; diff --git a/crates/rangoon-store/src/instruction_history_backup.rs b/crates/rangoon-store/src/instruction_history_backup.rs new file mode 100644 index 0000000..7fd166c --- /dev/null +++ b/crates/rangoon-store/src/instruction_history_backup.rs @@ -0,0 +1,277 @@ +//! Complete V4 logical recovery: V3 base plus exact instruction changes/journal. +//! Plaintext in-memory encoding is not an authenticated export format. +use super::*; +use composition_records::Records; +use instruction_history::{HistoryRows, InstructionChange, InstructionEvent}; +use rangoon_domain::{byte_digest, capability::valid_id}; + +const MAGIC: &[u8] = b"RANGOON-BACKUP-V4\n"; +const MAX_MANIFEST: usize = 128 * 1024; +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Descriptor { + id: String, + byte_length: u32, +} +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Manifest { + schema_version: String, + base_length: u32, + #[serde(deserialize_with = "changes")] + changes: Vec, + #[serde(deserialize_with = "events")] + events: Vec, +} +fn changes<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + composition_backup::bounded::<_, _, 128>(d) +} +fn events<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + composition_backup::bounded::<_, _, 512>(d) +} +impl Manifest { + fn bytes(&self) -> Result, StoreError> { + let bytes = serde_json::to_vec(self).map_err(|_| StoreError::BackupInvalid)?; + if bytes.len() > MAX_MANIFEST { + return Err(StoreError::Full); + } + Ok(bytes) + } + fn payload_length(&self) -> Result { + if self.schema_version != "rangoon.backup.v4" + || self.base_length == 0 + || self.base_length as usize > MAX_BACKUP_BYTES + { + return Err(StoreError::BackupInvalid); + } + let mut total = self.base_length as usize; + let mut history_total = 0usize; + for (records, prefix, count, bound) in [ + ( + &self.changes, + "instruction-change:", + 128, + instruction_history::MAX_RECORD_BYTES, + ), + (&self.events, "instruction-event:", 512, 2048), + ] { + if records.len() > count { + return Err(StoreError::BackupInvalid); + } + let mut previous: Option<&str> = None; + for item in records { + if !valid_id(&item.id, prefix) + || previous.is_some_and(|id| id >= item.id.as_str()) + || item.byte_length == 0 + || item.byte_length as usize > bound + { + return Err(StoreError::BackupInvalid); + } + history_total = history_total + .checked_add(item.byte_length as usize) + .ok_or(StoreError::Full)?; + if history_total > instruction_history::MAX_INSTRUCTION_HISTORY_BYTES { + return Err(StoreError::Full); + } + total = total + .checked_add(item.byte_length as usize) + .ok_or(StoreError::Full)?; + if total > MAX_BACKUP_BYTES { + return Err(StoreError::Full); + } + previous = Some(&item.id); + } + } + Ok(total) + } +} + +pub(super) fn canonical_database(base: &Records) -> Result { + if base.version != 5 { + return Err(StoreError::UnsupportedSchema); + } + base.history.validate(base)?; + let mut projected = base.clone(); + projected.version = 4; + projected.history = HistoryRows::default(); + let mut db = workflow_backup::canonical_database(&projected)?; + let tx = db.transaction()?; + for (_, sql) in instruction_history::SCHEMAS { + tx.execute_batch(sql)?; + } + tx.pragma_update(None, "user_version", 5)?; + base.history.insert_all(&tx)?; + let checked = Records::load_complete(&tx)?; + workflow_mutations::data(&tx, &checked)?; + tx.commit()?; + Ok(db) +} +pub(super) fn encode(base: &Records) -> Result, StoreError> { + canonical_database(base)?; + let mut projected = base.clone(); + projected.version = 4; + projected.history = HistoryRows::default(); + let base_bytes = zeroize::Zeroizing::new(workflow_backup::encode(&projected)?); + let changes = base + .history + .changes + .values() + .map(|c| { + Ok(Descriptor { + id: c.id().into(), + byte_length: c.bytes()?.len() as u32, + }) + }) + .collect::, StoreError>>()?; + let events = base + .history + .events + .values() + .map(|e| { + Ok(Descriptor { + id: e.id().into(), + byte_length: e.bytes()?.len() as u32, + }) + }) + .collect::, StoreError>>()?; + let manifest = Manifest { + schema_version: "rangoon.backup.v4".into(), + base_length: base_bytes.len() as u32, + changes, + events, + }; + let metadata = manifest.bytes()?; + let length = MAGIC + .len() + .checked_add(4) + .and_then(|n| n.checked_add(metadata.len())) + .and_then(|n| n.checked_add(manifest.payload_length().ok()?)) + .and_then(|n| n.checked_add(64)) + .filter(|n| *n <= MAX_BACKUP_BYTES) + .ok_or(StoreError::Full)?; + let mut bytes = Vec::with_capacity(length); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&(metadata.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&metadata); + bytes.extend_from_slice(&base_bytes); + for change in base.history.changes.values() { + bytes.extend_from_slice(&change.bytes()?); + } + for event in base.history.events.values() { + bytes.extend_from_slice(&event.bytes()?); + } + bytes.extend_from_slice(byte_digest(&bytes).as_bytes()); + if bytes.len() != length { + return Err(StoreError::Corrupt); + } + Ok(bytes) +} +pub(super) fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BACKUP_BYTES + || bytes.len() < MAGIC.len() + 4 + 64 + || !bytes.starts_with(MAGIC) + { + return Err(StoreError::BackupInvalid); + } + let end = bytes.len() - 64; + if byte_digest(&bytes[..end]).as_bytes() != &bytes[end..] { + return Err(StoreError::BackupInvalid); + } + let start = MAGIC.len() + 4; + let size = u32::from_be_bytes( + bytes[MAGIC.len()..start] + .try_into() + .map_err(|_| StoreError::BackupInvalid)?, + ) as usize; + let payload = start + .checked_add(size) + .filter(|n| *n <= end && size <= MAX_MANIFEST) + .ok_or(StoreError::BackupInvalid)?; + let manifest: Manifest = + serde_json::from_slice(&bytes[start..payload]).map_err(|_| StoreError::BackupInvalid)?; + if manifest.bytes()? != bytes[start..payload] + || payload.checked_add(manifest.payload_length()?) != Some(end) + { + return Err(StoreError::BackupInvalid); + } + let base_end = payload + .checked_add(manifest.base_length as usize) + .filter(|n| *n <= end) + .ok_or(StoreError::BackupInvalid)?; + // No recursive archive embedding or legacy base substitution. + if !bytes[payload..base_end].starts_with(b"RANGOON-BACKUP-V3\n") { + return Err(StoreError::BackupInvalid); + } + let mut records = WorkspaceBackup::decode(&bytes[payload..base_end])?.records; + if records.version != 4 { + return Err(StoreError::BackupInvalid); + } + let mut cursor = base_end; + for (items, change) in [(&manifest.changes, true), (&manifest.events, false)] { + for item in items { + let next = cursor + .checked_add(item.byte_length as usize) + .filter(|n| *n <= end) + .ok_or(StoreError::BackupInvalid)?; + let data = &bytes[cursor..next]; + cursor = next; + if change { + let value = + InstructionChange::decode(data).map_err(|_| StoreError::BackupInvalid)?; + if value.id() != item.id + || records + .history + .changes + .insert(item.id.clone(), value) + .is_some() + { + return Err(StoreError::BackupInvalid); + } + } else { + let value = + InstructionEvent::decode(data).map_err(|_| StoreError::BackupInvalid)?; + if value.id() != item.id + || records + .history + .events + .insert(item.id.clone(), value) + .is_some() + { + return Err(StoreError::BackupInvalid); + } + } + } + } + records.version = 5; + if cursor != end { + return Err(StoreError::BackupInvalid); + } + canonical_database(&records).map_err(|_| StoreError::BackupInvalid)?; + Ok(records) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn combined_history_descriptor_budget_rejects_before_payload_decode() { + let changes = (0..8) + .map(|i| Descriptor { + id: format!("instruction-change:{i:064x}"), + byte_length: (2 * 1024 * 1024) as u32, + }) + .collect(); + let events = vec![Descriptor { + id: format!("instruction-event:{:064x}", 0), + byte_length: 1, + }]; + let manifest = Manifest { + schema_version: "rangoon.backup.v4".into(), + base_length: 1, + changes, + events, + }; + assert_eq!(manifest.payload_length(), Err(StoreError::Full)); + // No base or change/event payload exists: refusal is descriptor-only. + } +} diff --git a/crates/rangoon-store/src/instruction_history_tests.rs b/crates/rangoon-store/src/instruction_history_tests.rs new file mode 100644 index 0000000..bd0e8dd --- /dev/null +++ b/crates/rangoon-store/src/instruction_history_tests.rs @@ -0,0 +1,1145 @@ +use super::*; +use crate::composition_records_tests::TestDir; +use rangoon_compose::{Draft, InputRange, Operation, OutputRecipe, Piece, ResolvedInput}; + +fn target(present: bool) -> InstructionTarget { + InstructionTarget { + workspace_identity: "a".repeat(64), + target_identity: "b".repeat(64), + parent_identity: "c".repeat(64), + file_name: "AGENTS.md".into(), + file_identity: present.then(|| "d".repeat(64)), + } +} +fn change(before: Option<&[u8]>, after: Option<&[u8]>) -> InstructionChange { + InstructionChange::prepare( + target(before.is_some()), + before, + after, + vec![], + None, + None, + 10, + ) + .unwrap() +} +#[test] +fn exact_bytes_absent_empty_binary_and_redacted_debug() { + let bytes = b"\xef\xbb\xbf# Plan\r\n\xc3\xa9\r\n\xff"; + let c = change(Some(bytes), Some(b"")); + assert_eq!(c.before(), Some(bytes.as_slice())); + assert_eq!(c.after(), Some(b"".as_slice())); + assert_eq!(c.before_sha256(), Some(byte_digest(bytes).as_str())); + assert_eq!(c.after_sha256(), Some(byte_digest(b"").as_str())); + let absent = change(None, Some(b"")); + assert_ne!(absent.id(), c.id()); + assert_ne!(change(Some(b""), None).id(), absent.id()); + assert_eq!(InstructionChange::decode(&c.bytes().unwrap()).unwrap(), c); + assert_eq!(format!("{c:?}"), "InstructionChange()"); + assert!(c.analyze_after().is_ok()); // empty supported Markdown remains exact + assert!(change(None, Some(bytes)).analyze_after().is_err()); +} +#[test] +fn changes_reject_noop_oversize_bad_identity_and_path() { + assert!(InstructionChange::prepare(target(false), None, None, vec![], None, None, 0).is_err()); + assert!( + InstructionChange::prepare(target(true), Some(b"x"), Some(b"x"), vec![], None, None, 0) + .is_err() + ); + assert!( + InstructionChange::prepare( + target(false), + None, + Some(&vec![0; MAX_INSTRUCTION_BYTES + 1]), + vec![], + None, + None, + 0 + ) + .is_err() + ); + assert!( + InstructionChange::prepare(target(true), None, Some(b"x"), vec![], None, None, 0).is_err() + ); + for name in ["../AGENTS.md", "a/b", "a\\b", "C:x", "", ".", "..", "x\0md"] { + let mut t = target(false); + t.file_name = name.into(); + assert!(InstructionChange::prepare(t, None, Some(b"x"), vec![], None, None, 0).is_err()); + } + let mut t = target(false); + t.parent_identity = "D".repeat(64); + assert!(InstructionChange::prepare(t, None, Some(b"x"), vec![], None, None, 0).is_err()); +} +#[test] +fn decoder_rejects_changed_digest_unknown_fields_version_and_noncanonical() { + let bytes = change(None, Some(b"secret")).bytes().unwrap(); + for field in ["schemaVersion", "afterSha256", "parentChangeId", "inputs"] { + let mut wire: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + wire[field] = "invalid".into(); + assert!(InstructionChange::decode(&serde_json::to_vec(&wire).unwrap()).is_err()); + } + let mut wire: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + wire["authority"] = "allow".into(); + assert!(InstructionChange::decode(&serde_json::to_vec(&wire).unwrap()).is_err()); + let mut extra = bytes.to_vec(); + extra.push(b' '); + assert!(InstructionChange::decode(&extra).is_err()); + assert!(InstructionChange::decode(&vec![b' '; MAX_RECORD_BYTES + 1]).is_err()); +} +#[test] +fn events_require_explicit_attempt_and_exact_readback() { + let c = change(None, Some(b"new")); + let mut records = Records::empty(); + records.version = 5; + records.history.changes.insert(c.id().into(), c.clone()); + let attempted = + InstructionEvent::prepare(c.id().into(), None, InstructionPhase::Attempted, None, 11) + .unwrap(); + let verified = InstructionEvent::prepare( + c.id().into(), + Some(attempted.id().into()), + InstructionPhase::Verified, + Some((Some("e".repeat(64)), Some(b"new"))), + 12, + ) + .unwrap(); + records + .history + .events + .insert(attempted.id().into(), attempted.clone()); + records + .history + .events + .insert(verified.id().into(), verified.clone()); + assert!(records.history.validate(&records).is_ok()); + let wrong = InstructionEvent::prepare( + c.id().into(), + Some(attempted.id().into()), + InstructionPhase::Verified, + Some((Some("e".repeat(64)), Some(b"wrong"))), + 12, + ) + .unwrap(); + records.history.events.remove(verified.id()); + records.history.events.insert(wrong.id().into(), wrong); + assert!(records.history.validate(&records).is_err()); + assert!( + InstructionEvent::prepare(c.id().into(), None, InstructionPhase::Verified, None, 12) + .is_err() + ); + assert!( + InstructionEvent::prepare( + c.id().into(), + None, + InstructionPhase::Attempted, + Some((None, None)), + 12 + ) + .is_err() + ); +} +#[test] +fn archive_parent_requires_exact_content_scope_and_retention() { + let first = change(None, Some(b"one")); + let mut records = Records::empty(); + records.version = 5; + records + .history + .changes + .insert(first.id().into(), first.clone()); + let child = InstructionChange::prepare( + target(true), + Some(b"one"), + Some(b"two"), + vec![], + None, + Some(first.id().into()), + 11, + ) + .unwrap(); + records + .history + .changes + .insert(child.id().into(), child.clone()); + assert!(records.history.validate(&records).is_ok()); + assert_eq!(deletion(&records, first.id()), Err(StoreError::RecordInUse)); + assert!(deletion(&records, child.id()).is_ok()); + let bad = InstructionChange::prepare( + target(true), + Some(b"other"), + Some(b"three"), + vec![], + None, + Some(first.id().into()), + 12, + ) + .unwrap(); + records.history.changes.insert(bad.id().into(), bad); + assert!(records.history.validate(&records).is_err()); +} +#[test] +fn parser_ranges_split_merge_and_reassembly_preserve_original_bytes() { + let text = "\u{feff}# First\r\nUse careful review.\r\n## Second\r\nKeep provenance.\r\n"; + let c = change(None, Some(text.as_bytes())); + let report = c.analyze_after().unwrap(); + assert_eq!(report.source.content.as_bytes(), text.as_bytes()); + assert!(report.fragments.len() >= 2); + let inputs = vec![ResolvedInput::Source { + source_id: report.source.id.clone(), + sha256: report.source.sha256.clone(), + content: text.into(), + }]; + let reference = InputReference::Source { + source_id: report.source.id.clone(), + sha256: report.source.sha256.clone(), + }; + let pieces: Vec<_> = report + .fragments + .iter() + .map(|f| Piece::Copy { + range: InputRange { + input_index: 0, + start_byte: f.span.start_byte, + end_byte: f.span.end_byte, + }, + }) + .collect(); + let mut draft = Draft { + schema_version: rangoon_compose::DRAFT_SCHEMA.into(), + operation: Operation::Decompose, + inputs: vec![reference], + outputs: vec![OutputRecipe { + title: "Reassembled".into(), + pieces, + }], + exclusions: vec![], + duplications: vec![], + conflicts: vec![], + }; + let preview = rangoon_compose::preview(&draft, &inputs).unwrap(); + assert_eq!(preview.outputs[0].content.as_bytes(), text.as_bytes()); + draft.operation = Operation::Split; + let cap = format!("capability:{}", "1".repeat(64)); + let rev = format!("revision:{}", "2".repeat(64)); + draft.inputs = vec![InputReference::Revision { + capability_id: cap.clone(), + revision_id: rev.clone(), + sha256: report.source.sha256.clone(), + }]; + let inputs = vec![ResolvedInput::Revision { + capability_id: cap, + revision_id: rev, + sha256: report.source.sha256.clone(), + content: text.into(), + }]; + draft.outputs = report + .fragments + .iter() + .enumerate() + .map(|(i, f)| OutputRecipe { + title: format!("Part {i}"), + pieces: vec![Piece::Copy { + range: InputRange { + input_index: 0, + start_byte: f.span.start_byte, + end_byte: f.span.end_byte, + }, + }], + }) + .collect(); + let split = rangoon_compose::preview(&draft, &inputs).unwrap(); + let joined: String = split.outputs.iter().map(|o| o.content.as_str()).collect(); + assert_eq!(joined, text); + let parts: Vec<_> = split + .outputs + .iter() + .enumerate() + .map(|(i, o)| analyze(&format!("part-{i}.md"), o.content.as_bytes()).unwrap()) + .collect(); + let merged = Draft { + schema_version: rangoon_compose::DRAFT_SCHEMA.into(), + operation: Operation::Merge, + inputs: parts + .iter() + .enumerate() + .map(|(i, p)| InputReference::Revision { + capability_id: format!("capability:{}", byte_digest(&[i as u8])), + revision_id: format!("revision:{}", byte_digest(&[i as u8])), + sha256: p.source.sha256.clone(), + }) + .collect(), + outputs: vec![OutputRecipe { + title: "Merged".into(), + pieces: parts + .iter() + .enumerate() + .map(|(i, p)| Piece::Copy { + range: InputRange { + input_index: i as u32, + start_byte: 0, + end_byte: p.source.byte_length, + }, + }) + .collect(), + }], + exclusions: vec![], + duplications: vec![], + conflicts: vec![], + }; + let resolved: Vec<_> = parts + .iter() + .enumerate() + .map(|(i, p)| ResolvedInput::Revision { + capability_id: format!("capability:{}", byte_digest(&[i as u8])), + revision_id: format!("revision:{}", byte_digest(&[i as u8])), + sha256: p.source.sha256.clone(), + content: p.source.content.clone(), + }) + .collect(); + assert_eq!( + rangoon_compose::preview(&merged, &resolved) + .unwrap() + .outputs[0] + .content, + text + ); + + let mut invalid = draft.clone(); + if let Piece::Copy { range } = &mut invalid.outputs[0].pieces[0] { + range.start_byte = 1; + } + assert!(rangoon_compose::preview(&invalid, &inputs).is_err()); +} +#[test] +fn plaintext_workspaces_refuse_all_history_access_without_creating_files() { + let root = TestDir::new(); + let store = root.store(); + let c = change(None, Some(b"new")); + assert_eq!( + store.save_instruction_change(&c, &format!("workspace:{}", "a".repeat(64))), + Err(StoreError::EncryptionUnavailable) + ); + assert!(matches!( + store.instruction_changes(), + Err(StoreError::EncryptionUnavailable) + )); + assert!(matches!( + store.snapshot_encrypted_recovery(), + Err(StoreError::EncryptionUnavailable) + )); + assert!(!root.0.exists()); +} +#[cfg(feature = "encrypted-sqlite")] +fn keyed(root: &TestDir, byte: u8) -> Workspace { + Workspace::encrypted(root.0.clone(), WorkspaceKey::from_bytes([byte; 32])).unwrap() +} +#[cfg(feature = "encrypted-sqlite")] +fn seed(root: &TestDir, byte: u8) -> Workspace { + let store = keyed(root, byte); + store.initialize_empty_encrypted().unwrap(); + store +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn encrypted_persistence_restore_eligibility_drift_and_reopen() { + let root = TestDir::new(); + let store = seed(&root, 0x31); + let c = change(Some(b"original\r\n"), Some(b"changed")); + let state = store.workflow_data().unwrap().state_id; + let archived = store.save_instruction_change(&c, &state).unwrap(); + assert_eq!( + store.save_instruction_change(&c, &state), + Err(StoreError::WorkspaceChanged) + ); + let attempted = + InstructionEvent::prepare(c.id().into(), None, InstructionPhase::Attempted, None, 11) + .unwrap(); + let pending = store + .append_instruction_event(&attempted, &archived) + .unwrap(); + assert!( + store + .inspect_instruction_restore(c.id(), &target(true), Some(b"changed")) + .is_err() + ); + let verified = InstructionEvent::prepare( + c.id().into(), + Some(attempted.id().into()), + InstructionPhase::Verified, + Some((Some("e".repeat(64)), Some(b"changed"))), + 12, + ) + .unwrap(); + let final_state = store.append_instruction_event(&verified, &pending).unwrap(); + let mut current = target(true); + current.file_identity = Some("e".repeat(64)); + assert_eq!( + store + .inspect_instruction_restore(c.id(), ¤t, Some(b"changed")) + .unwrap(), + c + ); + assert!(matches!( + store.inspect_instruction_restore(c.id(), ¤t, Some(b"drift")), + Err(StoreError::WorkspaceChanged) + )); + current.parent_identity = "f".repeat(64); + assert!(matches!( + store.inspect_instruction_restore(c.id(), ¤t, Some(b"changed")), + Err(StoreError::WorkspaceChanged) + )); + drop(store); + let reopened = keyed(&root, 0x31); + assert_eq!(reopened.workflow_data().unwrap().state_id, final_state); + assert_eq!(reopened.instruction_changes().unwrap(), vec![c]); + assert_eq!( + reopened.workflow_data().unwrap().records.instruction_events, + 2 + ); + let disk = fs::read(reopened.path()).unwrap(); + assert!(!disk.windows(8).any(|w| w == b"original")); + assert!(!disk.starts_with(b"SQLite format 3")); +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn protected_history_only_leaves_as_encrypted_complete_recovery_copy() { + let a = TestDir::new(); + let b = TestDir::new(); + let c = TestDir::new(); + let store = seed(&a, 0x32); + let change = change(None, Some(b"private instruction history")); + store + .save_instruction_change(&change, &store.workflow_data().unwrap().state_id) + .unwrap(); + assert_eq!( + store.export_workflow_backup(), + Err(StoreError::UnsupportedSchema) + ); + let captured = store.snapshot_encrypted_recovery().unwrap(); + let internal = workflow_backup::encode(&captured.records).unwrap(); + assert!(internal.starts_with(b"RANGOON-BACKUP-V4\n")); + assert!(matches!( + WorkspaceBackup::decode(&internal), + Err(StoreError::BackupInvalid) + )); + let recovery = keyed(&b, 0x33); + let ciphertext = recovery.create_encrypted_recovery_copy(&captured).unwrap(); + assert!(!ciphertext.windows(7).any(|w| w == b"private")); + let readback = recovery + .inspect_encrypted_recovery_copy(ciphertext.len() as u64) + .unwrap(); + assert!(captured.same_recovery_records(&readback).unwrap()); + let fresh = seed(&c, 0x34); + let plan = fresh.prepare_empty_workflow_restore(&readback, 5).unwrap(); + fresh + .restore_empty_workflow_backup(&readback, &plan) + .unwrap(); + drop(fresh); + let reopened = keyed(&c, 0x34); + assert_eq!(reopened.instruction_changes().unwrap(), vec![change]); + assert!( + captured + .same_recovery_records(&reopened.snapshot_encrypted_recovery().unwrap()) + .unwrap() + ); + assert!(matches!( + keyed(&b, 0x77).inspect_encrypted_recovery_copy(ciphertext.len() as u64), + Err(StoreError::EncryptedStoreInvalid) + )); + let before = fs::read(recovery.path()).unwrap(); + assert_eq!(before, ciphertext); + let mut altered = before.clone(); + altered[4200] ^= 1; + fs::write(recovery.path(), &altered).unwrap(); + assert!( + recovery + .inspect_encrypted_recovery_copy(altered.len() as u64) + .is_err() + ); + assert_eq!(fs::read(recovery.path()).unwrap(), altered); +} + +#[test] +fn unknown_and_failed_events_never_satisfy_restore_evidence_and_forks_refuse() { + let c = change(None, Some(b"new")); + let attempt = + InstructionEvent::prepare(c.id().into(), None, InstructionPhase::Attempted, None, 11) + .unwrap(); + let unknown = InstructionEvent::prepare( + c.id().into(), + Some(attempt.id().into()), + InstructionPhase::Unknown, + None, + 12, + ) + .unwrap(); + let mut records = Records::empty(); + records.version = 5; + records.history.changes.insert(c.id().into(), c.clone()); + records + .history + .events + .insert(attempt.id().into(), attempt.clone()); + records.history.events.insert(unknown.id().into(), unknown); + assert!(records.history.validate(&records).is_ok()); + assert!( + !records + .history + .events + .values() + .any(|e| e.phase() == InstructionPhase::Verified) + ); + let fail = InstructionEvent::prepare( + c.id().into(), + Some(attempt.id().into()), + InstructionPhase::Failed, + None, + 13, + ) + .unwrap(); + records.history.events.insert(fail.id().into(), fail); + assert!(records.history.validate(&records).is_err()); +} +#[test] +fn malformed_bytes_and_rechecksummed_internal_archives_do_not_panic_or_validate() { + let c = change(None, Some(b"synthetic")); + let bytes = c.bytes().unwrap(); + for end in 0..bytes.len() { + assert!(InstructionChange::decode(&bytes[..end]).is_err()); + } + let mut records = Records::empty(); + records.version = 5; + records.history.changes.insert(c.id().into(), c); + let archive = workflow_backup::encode(&records).unwrap(); + for index in (0..archive.len() - 64).step_by(71) { + let mut altered = archive.clone(); + altered[index] ^= 0x80; + let end = altered.len() - 64; + let digest = byte_digest(&altered[..end]); + altered[end..].copy_from_slice(digest.as_bytes()); + assert!( + instruction_history_backup::decode(&altered).is_err(), + "accepted altered byte {index}" + ); + } + let mut trailing = archive.clone(); + trailing.push(0); + assert!(instruction_history_backup::decode(&trailing).is_err()); + assert!(instruction_history_backup::decode(&vec![0; MAX_BACKUP_BYTES + 1]).is_err()); +} +#[test] +fn history_count_and_storage_budget_fail_without_eviction() { + let mut records = Records::empty(); + records.version = 5; + for i in 0..MAX_INSTRUCTION_CHANGES { + let c = InstructionChange::prepare( + target(false), + None, + Some(format!("change-{i}").as_bytes()), + vec![], + None, + None, + i as i64, + ) + .unwrap(); + records.history.changes.insert(c.id().into(), c); + } + assert!(records.history.validate(&records).is_ok()); + let extra = change(None, Some(b"extra")); + records.history.changes.insert(extra.id().into(), extra); + assert_eq!(records.history.validate(&records), Err(StoreError::Full)); + assert_eq!(records.history.changes.len(), MAX_INSTRUCTION_CHANGES + 1); + records.history.changes.clear(); + for i in 0..32 { + let mut data = vec![255; MAX_INSTRUCTION_BYTES]; + data[0] = i; + let c = change(None, Some(&data)); + records.history.changes.insert(c.id().into(), c); + } + assert_eq!(records.history.validate(&records), Err(StoreError::Full)); +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn nonempty_restore_merges_history_events_and_preserves_later_authoring() { + use rangoon_workflow::records::{SaveIntent, prepare_revision, workflow_id_from_nonce}; + let a = TestDir::new(); + let b = TestDir::new(); + let sa = seed(&a, 0x41); + let sb = seed(&b, 0x42); + let ca = change(None, Some(b"one")); + let cb = change(None, Some(b"two")); + sa.save_instruction_change(&ca, &sa.workflow_data().unwrap().state_id) + .unwrap(); + sb.save_instruction_change(&cb, &sb.workflow_data().unwrap().state_id) + .unwrap(); + let incoming = sa.snapshot_encrypted_recovery().unwrap(); + let plan = sb.prepare_workflow_restore(&incoming).unwrap(); + sb.restore_workflow_backup(&incoming, &plan).unwrap(); + assert_eq!(sb.instruction_changes().unwrap().len(), 2); + let report = analyze("SKILL.md", b"# Skill\nKeep exact history.\n").unwrap(); + sb.save_v1(&report).unwrap(); + let cap = sb + .create_capability_v1(&report.source.id, &report.fragments[0].id, "Saved") + .unwrap(); + let cap = sb + .revise_capability_v1( + &cap.capability.id, + &cap.capability.latest_revision_id, + "Revised", + "# Revised\nNew content.\n", + ) + .unwrap(); + sb.review_capability_v1(&cap.capability.id, &cap.capability.latest_revision_id) + .unwrap(); + assert!( + sb.compile_capability( + &cap.capability.id, + &cap.capability.latest_revision_id, + rangoon_compile::Profile::AgentsMdV1 + ) + .is_ok() + ); + let definition=br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Draft","nodes":[],"controlEdges":[],"dataEdges":[]}"#; + let workflow = prepare_revision( + &workflow_id_from_nonce(&[6; 32]), + None, + SaveIntent::Draft, + definition, + br#"{"positions":[]}"#, + ) + .unwrap(); + let save = sb.inspect_workflow_save(&workflow).unwrap(); + sb.save_workflow(&workflow, &save.expected_state_id) + .unwrap(); + assert_eq!(sb.instruction_changes().unwrap().len(), 2); + let db = sb.connect_complete_read_only(false).unwrap().unwrap(); + assert_eq!( + db.pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0)) + .unwrap(), + 5 + ); +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn lineage_dependency_deletion_and_explicit_archive_removal() { + let root = TestDir::new(); + let store = seed(&root, 0x44); + let report = analyze("AGENTS.md", b"# Original\nKeep lineage.\n").unwrap(); + store.save_v1(&report).unwrap(); + let c = InstructionChange::prepare( + target(false), + None, + Some(b"new"), + vec![InputReference::Source { + source_id: report.source.id.clone(), + sha256: report.source.sha256.clone(), + }], + None, + None, + 10, + ) + .unwrap(); + store + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .unwrap(); + assert!(matches!( + store.inspect_workflow_deletion(WorkflowRecordKind::Source, &report.source.id), + Err(StoreError::RecordInUse) + )); + let retained = store.prepare_instruction_history_deletion(c.id()).unwrap(); + assert_eq!(retained.change_id(), c.id()); + assert_eq!(retained.removed_event_count(), 0); + let other = change(None, Some(b"other")); + store + .save_instruction_change(&other, &store.workflow_data().unwrap().state_id) + .unwrap(); + assert_eq!( + store.delete_instruction_history(&retained), + Err(StoreError::WorkspaceChanged) + ); + let retained = store.prepare_instruction_history_deletion(c.id()).unwrap(); + store.delete_instruction_history(&retained).unwrap(); + assert_eq!(store.instruction_changes().unwrap(), vec![other]); + let plan = store + .inspect_workflow_deletion(WorkflowRecordKind::Source, &report.source.id) + .unwrap(); + store.delete_workflow_record(&plan).unwrap(); +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn wrong_key_does_not_mutate_workspace_or_expose_history() { + let root = TestDir::new(); + let store = seed(&root, 0x45); + let c = change(None, Some(b"private")); + store + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .unwrap(); + let before = fs::read(store.path()).unwrap(); + let wrong = keyed(&root, 0x46); + assert!(wrong.instruction_changes().is_err()); + assert!( + wrong + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .is_err() + ); + assert_eq!(fs::read(store.path()).unwrap(), before); +} + +#[test] +#[ignore = "launched only by the isolated history parent test"] +#[cfg(feature = "encrypted-sqlite")] +fn instruction_history_child() { + let root = TestDir(PathBuf::from( + std::env::var_os("RANGOON_RECOVERY_TEST_WORKSPACE").unwrap(), + )); + // Parent owns this directory and cleanup. TestDir's Drop is avoided in the + // child so a successful distinct-process read cannot delete parent evidence. + let root = std::mem::ManuallyDrop::new(root); + let store = keyed(&root, 0x5c); + let c = change(None, Some(b"child history")); + match std::env::var("RANGOON_RECOVERY_TEST_DELETE_ID") + .unwrap() + .as_str() + { + "reopen" => { + assert_eq!(store.instruction_changes().unwrap(), vec![c]); + assert_eq!(store.workflow_data().unwrap().records.instruction_events, 1); + } + "change" => { + store + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .unwrap(); + } + "event" => { + let attempted = InstructionEvent::prepare( + c.id().into(), + None, + InstructionPhase::Attempted, + None, + 11, + ) + .unwrap(); + store + .append_instruction_event(&attempted, &store.workflow_data().unwrap().state_id) + .unwrap(); + } + _ => panic!("unknown controlled history child case"), + } +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn process_restart_and_killed_transactions_retain_exact_prior_state() { + use crate::composition_recovery_tests::fault_child_for; + for phase in [ + "after_instruction_history_schema", + "after_instruction_history_change", + "after_instruction_history_event", + ] { + let root = TestDir::new(); + let store = seed(&root, 0x5c); + let c = change(None, Some(b"child history")); + let action = if phase.ends_with("event") { + store + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .unwrap(); + "event" + } else { + "change" + }; + let before = store.workflow_data().unwrap().state_id; + fault_child_for( + &root, + &root.0.join("unused"), + phase, + "crash", + action, + "instruction_history::tests::instruction_history_child", + ); + // Open the keyed writable connection for ordinary SQLite rollback-journal + // recovery after the owned child is killed. No target file was touched. + drop(store.connect_complete(false).unwrap().unwrap()); + assert_eq!(store.workflow_data().unwrap().state_id, before); + assert_eq!(store.workflow_data().unwrap().records.instruction_events, 0); + } + let root = TestDir::new(); + let store = seed(&root, 0x5c); + let c = change(None, Some(b"child history")); + store + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .unwrap(); + let attempted = + InstructionEvent::prepare(c.id().into(), None, InstructionPhase::Attempted, None, 11) + .unwrap(); + store + .append_instruction_event(&attempted, &store.workflow_data().unwrap().state_id) + .unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--ignored", + "--exact", + "instruction_history::tests::instruction_history_child", + ]) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("RANGOON_RECOVERY_TEST_WORKSPACE", &root.0) + .env("RANGOON_RECOVERY_TEST_DELETE_ID", "reopen") + .status() + .unwrap(); + assert!(status.success()); +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn maximum_binary_original_and_proposal_fit_after_schema_one_upgrade() { + let root = TestDir::new(); + let store = seed(&root, 0x49); + let before = vec![255; MAX_INSTRUCTION_BYTES]; + let mut after = before.clone(); + after[0] = 254; + let c = change(Some(&before), Some(&after)); + assert!(c.bytes().unwrap().len() <= MAX_RECORD_BYTES); + store + .save_instruction_change(&c, &store.workflow_data().unwrap().state_id) + .unwrap(); + assert_eq!(store.instruction_changes().unwrap(), vec![c]); +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn quota_refuses_before_mutation_and_explicit_delete_removes_only_selected_journal() { + let mut records = Records::empty(); + records.version = 5; + for i in 0..MAX_INSTRUCTION_CHANGES { + let c = change(None, Some(format!("bounded-{i}").as_bytes())); + records.history.changes.insert(c.id().into(), c); + } + let root = TestDir::new(); + let store = keyed(&root, 0x4a); + let backup = + WorkspaceBackup::decode_complete(&workflow_backup::encode(&records).unwrap()).unwrap(); + store.create_encrypted_recovery_copy(&backup).unwrap(); + let state = store.workflow_data().unwrap().state_id; + let before = fs::read(store.path()).unwrap(); + assert_eq!( + store.save_instruction_change(&change(None, Some(b"overflow")), &state), + Err(StoreError::Full) + ); + assert_eq!(fs::read(store.path()).unwrap(), before); + let selected = store.instruction_changes().unwrap()[0].clone(); + let attempt = InstructionEvent::prepare( + selected.id().into(), + None, + InstructionPhase::Attempted, + None, + 11, + ) + .unwrap(); + let state = store.append_instruction_event(&attempt, &state).unwrap(); + let unknown = InstructionEvent::prepare( + selected.id().into(), + Some(attempt.id().into()), + InstructionPhase::Unknown, + None, + 12, + ) + .unwrap(); + store.append_instruction_event(&unknown, &state).unwrap(); + assert_eq!(store.instruction_events(selected.id()).unwrap().len(), 2); + let delete = store + .prepare_instruction_history_deletion(selected.id()) + .unwrap(); + assert_eq!(delete.removed_event_count(), 2); + store.delete_instruction_history(&delete).unwrap(); + let data = store.workflow_data().unwrap(); + assert_eq!(data.records.instruction_changes, 127); + assert_eq!(data.records.instruction_events, 0); + assert!(matches!( + store.instruction_events(selected.id()), + Err(StoreError::NotFound) + )); +} + +#[test] +fn combined_database_budget_refuses_before_decoding_any_blob() { + let db = Connection::open_in_memory().unwrap(); + for (_, sql) in SCHEMAS { + db.execute_batch(sql).unwrap(); + } + for i in 0..8 { + db.execute( + "INSERT INTO instruction_changes VALUES (?1,zeroblob(?2))", + params![format!("instruction-change:{i:064x}"), 2 * 1024 * 1024], + ) + .unwrap(); + } + db.execute( + "INSERT INTO instruction_events VALUES (?1,zeroblob(1))", + [format!("instruction-event:{:064x}", 0)], + ) + .unwrap(); + // Blobs are deliberately undecodable. Full, rather than a decoding error, + // proves the shared-budget rejection happens before record reconstruction. + assert!(matches!( + HistoryRows::load(&db, &Records::empty()), + Err(StoreError::Full) + )); +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn nonempty_recovery_retains_applied_composition_recipe_and_exact_lineage() { + let source = TestDir::new(); + let target_root = TestDir::new(); + let source_store = seed(&source, 0x4b); + let report = analyze( + "AGENTS.md", + b"\xef\xbb\xbf# Rules\r\nKeep originals.\r\n# Tests\r\nCheck edits.\r\n", + ) + .unwrap(); + source_store.save_v1(&report).unwrap(); + let mut request = crate::composition_records_tests::fixture_request(); + request.draft.inputs = vec![InputReference::Source { + source_id: report.source.id.clone(), + sha256: report.source.sha256.clone(), + }]; + request.draft.outputs = report + .fragments + .iter() + .enumerate() + .map(|(i, fragment)| OutputRecipe { + title: format!("Archived part {i}"), + pieces: vec![Piece::Copy { + range: InputRange { + input_index: 0, + start_byte: fragment.span.start_byte, + end_byte: fragment.span.end_byte, + }, + }], + }) + .collect(); + let recipe_id = rangoon_compose::composition_id(&request.draft).unwrap(); + let preview = source_store.preview_composition(&request).unwrap(); + assert!(preview.preview.saveable); + source_store.apply_composition(&preview, true).unwrap(); + let change = InstructionChange::prepare( + target(false), + None, + Some(b"derived"), + request.draft.inputs.clone(), + Some(recipe_id.clone()), + None, + 10, + ) + .unwrap(); + source_store + .save_instruction_change(&change, &source_store.workflow_data().unwrap().state_id) + .unwrap(); + let incoming = source_store.snapshot_encrypted_recovery().unwrap(); + let destination = seed(&target_root, 0x4c); + let other = super::tests::change(None, Some(b"existing")); + destination + .save_instruction_change(&other, &destination.workflow_data().unwrap().state_id) + .unwrap(); + let plan = destination.prepare_workflow_restore(&incoming).unwrap(); + destination + .restore_workflow_backup(&incoming, &plan) + .unwrap(); + drop(destination); + let reopened = keyed(&target_root, 0x4c); + let snapshot = reopened.snapshot_encrypted_recovery().unwrap(); + assert!(snapshot.records.recipes.contains_key(&recipe_id)); + assert_eq!(snapshot.records.applications.len(), 1); + let recovered = reopened + .instruction_changes() + .unwrap() + .into_iter() + .find(|c| c.id() == change.id()) + .unwrap(); + assert_eq!(recovered, change); + assert_eq!(recovered.inputs(), request.draft.inputs); + let mut forged = incoming.records.clone(); + forged.recipes.get_mut(&recipe_id).unwrap().draft.outputs[0].title = "altered".into(); + assert!(composition_backup::canonical_database(&forged).is_err()); +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn incompatible_nonempty_recovery_refuses_missing_pinned_revision_without_mutation() { + let source = TestDir::new(); + let prior = TestDir::new(); + let source_store = seed(&source, 0x4d); + let report = analyze("AGENTS.md", b"# Scope\nInitial.\n").unwrap(); + source_store.save_v1(&report).unwrap(); + let root = source_store + .create_capability_v1(&report.source.id, &report.fragments[0].id, "Scoped") + .unwrap() + .capability; + let ancestor = source_store.snapshot_encrypted_recovery().unwrap(); + let destination = keyed(&prior, 0x4e); + destination + .create_encrypted_recovery_copy(&ancestor) + .unwrap(); + let revised = source_store + .revise_capability_v1( + &root.id, + &root.latest_revision_id, + "Scoped", + "# Scope\nChanged.\n", + ) + .unwrap() + .capability; + let change = InstructionChange::prepare( + target(false), + None, + Some(b"new"), + vec![InputReference::Revision { + capability_id: revised.id, + revision_id: revised.revision.id, + sha256: revised.revision.sha256, + }], + None, + None, + 10, + ) + .unwrap(); + source_store + .save_instruction_change(&change, &source_store.workflow_data().unwrap().state_id) + .unwrap(); + let incoming = source_store.snapshot_encrypted_recovery().unwrap(); + let before = fs::read(destination.path()).unwrap(); + let state = destination.workflow_data().unwrap().state_id; + assert!(matches!( + destination.prepare_workflow_restore(&incoming), + Err(StoreError::RecordInUse) + )); + assert_eq!(destination.workflow_data().unwrap().state_id, state); + assert_eq!(fs::read(destination.path()).unwrap(), before); + assert!(destination.instruction_changes().unwrap().is_empty()); +} + +#[test] +fn old_inventory_wire_is_exact_and_schema_five_negotiates_v3_even_empty() { + for version in 1..=4 { + let mut records = Records::empty(); + records.version = version; + let data = workflow_views::data(&records, 0, 0).unwrap(); + let expected = format!( + r#"{{"schemaVersion":"rangoon.workspace-data.v2","stateId":"{}","records":{{"sources":0,"capabilities":0,"revisions":0,"reviews":0,"recipes":0,"applications":0,"derivations":0,"workflows":0,"workflowRevisions":0}},"databaseBytes":0,"reusableBytes":0,"sources":[],"capabilities":[],"workflows":[]}}"#, + records.state_id().unwrap() + ); + assert_eq!(serde_json::to_string(&data).unwrap(), expected); + } + let mut records = Records::empty(); + records.version = 5; + let empty = workflow_views::data(&records, 0, 0).unwrap(); + assert_eq!(empty.schema_version, "rangoon.workspace-data.v3"); + let c = change(None, Some(b"new")); + records.history.changes.insert(c.id().into(), c); + let json = serde_json::to_value(workflow_views::data(&records, 0, 0).unwrap()).unwrap(); + assert_eq!(json["schemaVersion"], "rangoon.workspace-data.v3"); + assert_eq!(json["records"]["instructionChanges"], 1); +} +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn history_restore_plan_version_is_explicit_and_stale_preview_refuses() { + let a = TestDir::new(); + let b = TestDir::new(); + let sa = seed(&a, 0x60); + let sb = seed(&b, 0x61); + let old = sa.snapshot_encrypted_recovery().unwrap(); + assert_eq!( + serde_json::to_value(sb.prepare_workflow_restore(&old).unwrap()).unwrap()["schemaVersion"], + "rangoon.restore-plan.v2" + ); + let c = change(None, Some(b"new")); + sa.save_instruction_change(&c, &sa.workflow_data().unwrap().state_id) + .unwrap(); + let incoming = sa.snapshot_encrypted_recovery().unwrap(); + let retained = sb.prepare_workflow_restore(&incoming).unwrap(); + let json = serde_json::to_value(&retained).unwrap(); + assert_eq!(json["schemaVersion"], "rangoon.restore-plan.v3"); + assert_eq!(json["add"]["instructionChanges"], 1); + sb.save_instruction_change( + &change(None, Some(b"local")), + &sb.workflow_data().unwrap().state_id, + ) + .unwrap(); + let before = fs::read(sb.path()).unwrap(); + assert!(matches!( + sb.restore_workflow_backup(&incoming, &retained), + Err(StoreError::WorkspaceChanged) + )); + assert_eq!(fs::read(sb.path()).unwrap(), before); + assert_eq!( + serde_json::to_value(sb.prepare_workflow_restore(&old).unwrap()).unwrap()["schemaVersion"], + "rangoon.restore-plan.v3" + ); + let remove = sb + .prepare_instruction_history_deletion(sb.instruction_changes().unwrap()[0].id()) + .unwrap(); + sb.delete_instruction_history(&remove).unwrap(); + assert_eq!( + sb.workflow_data().unwrap().schema_version, + "rangoon.workspace-data.v3" + ); + assert_eq!( + serde_json::to_value(sb.prepare_workflow_restore(&old).unwrap()).unwrap()["schemaVersion"], + "rangoon.restore-plan.v3" + ); +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn generic_empty_history_recovery_preserves_schema_five_for_fresh_targets() { + let source = TestDir::new(); + let sa = seed(&source, 0x62); + let c = change(None, Some(b"temporary")); + sa.save_instruction_change(&c, &sa.workflow_data().unwrap().state_id) + .unwrap(); + let delete = sa.prepare_instruction_history_deletion(c.id()).unwrap(); + sa.delete_instruction_history(&delete).unwrap(); + let archive = sa.snapshot_encrypted_recovery().unwrap(); + assert_eq!(archive.records.version, 5); + for initialized in [false, true] { + let target_root = TestDir::new(); + let target = keyed(&target_root, 0x63); + if initialized { + target.initialize_empty_encrypted().unwrap(); + } + let preview = target.prepare_workflow_restore(&archive).unwrap(); + let json = serde_json::to_value(&preview).unwrap(); + assert_eq!(json["schemaVersion"], "rangoon.restore-plan.v3"); + assert_eq!(json["targetWorkspaceSchema"], 5); + let data = target.restore_workflow_backup(&archive, &preview).unwrap(); + assert_eq!(data.schema_version, "rangoon.workspace-data.v3"); + assert_eq!(data.records, WorkflowRecoveryCounts::default()); + drop(target); + let reopened = keyed(&target_root, 0x63); + assert_eq!( + reopened + .snapshot_encrypted_recovery() + .unwrap() + .records + .version, + 5 + ); + let report = analyze("AGENTS.md", b"# After recovery\nKeep version.\n").unwrap(); + reopened.save_v1(&report).unwrap(); + assert_eq!( + reopened.workflow_data().unwrap().schema_version, + "rangoon.workspace-data.v3" + ); + assert_eq!( + reopened + .snapshot_encrypted_recovery() + .unwrap() + .records + .version, + 5 + ); + assert_eq!( + reopened.export_workflow_backup(), + Err(StoreError::UnsupportedSchema) + ); + } +} diff --git a/crates/rangoon-store/src/lib.rs b/crates/rangoon-store/src/lib.rs index e8be816..cbd196d 100644 --- a/crates/rangoon-store/src/lib.rs +++ b/crates/rangoon-store/src/lib.rs @@ -17,7 +17,15 @@ mod composition_recovery; mod composition_recovery_tests; mod compositions; mod encryption; +mod instruction_history; +mod instruction_history_backup; pub use encryption::WorkspaceKey; +pub use instruction_history::{ + InstructionChange, InstructionEvent, InstructionHistoryDeletion, InstructionPhase, + InstructionTarget, MAX_INSTRUCTION_BYTES, MAX_INSTRUCTION_CHANGES, MAX_INSTRUCTION_EVENTS, + MAX_INSTRUCTION_HISTORY_BYTES, +}; +mod recovery_copy; mod workspace_data; #[cfg(test)] mod workspace_data_tests; @@ -37,9 +45,11 @@ pub use composition_recovery::{ CompositionDeletionPlan, CompositionRestorePlan, CompositionWorkspaceData, RecoveryCounts, }; pub use compositions::{CompositionPreview, CompositionReceipt}; -pub use workflow_backup::WorkspaceBackup; +pub use workflow_backup::{ExistingWorkspaceCapture, WorkspaceBackup}; pub use workflow_deletion::{WorkflowDeletionPlan, WorkflowRecordKind}; -pub use workflow_recovery::{WorkflowRecoveryCounts, WorkflowRestorePlan}; +pub use workflow_recovery::{ + EmptyWorkflowRestorePlan, WorkflowRecoveryCounts, WorkflowRestorePlan, +}; pub use workflow_saves::{WorkflowSavePlan, WorkflowSaveReceipt}; pub use workflow_views::{ WorkflowDetail, WorkflowReference, WorkflowReferenceStatus, WorkflowRevisionSummary, @@ -113,6 +123,7 @@ pub enum StoreError { CompositionDependencyMissing, CompilationInvalid, RecordInUse, + InstructionHistoryInvalid, WorkflowInvalid, WorkflowNotFound, WorkflowConflict, @@ -122,6 +133,10 @@ pub enum StoreError { impl StoreError { pub fn public(self) -> (&'static str, &'static str) { match self { + Self::InstructionHistoryInvalid => ( + "instruction_history_invalid", + "Instruction history is invalid or incomplete. No instruction file was changed.", + ), Self::EncryptionUnavailable => ( "encryption_unavailable", "The qualified encrypted storage backend is unavailable. No plaintext fallback was used.", @@ -349,7 +364,7 @@ impl Workspace { initialize_or_verify(&tx)?; } let version: i64 = tx.pragma_query_value(None, "user_version", |r| r.get(0))?; - if matches!(version, 3 | 4) && !allow_composition { + if matches!(version, 3..=5) && !allow_composition { return Err(StoreError::UnsupportedSchema); } if allow_composition { @@ -530,9 +545,12 @@ impl Workspace { } // Reject unsupported files before changing their persistent journal mode. let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?; + if version == 5 && self.key.is_none() { + return Err(StoreError::EncryptionUnavailable); + } if version != 0 { verify_schema_mode(&db, allow_workflows)?; - if matches!(version, 3 | 4) { + if matches!(version, 3..=5) { db.set_limit( Limit::SQLITE_LIMIT_LENGTH, (rangoon_compose::MAX_DRAFT_BYTES + 4096) as i32, @@ -685,13 +703,13 @@ fn verify_schema(db: &Connection) -> Result<(), StoreError> { } fn verify_schema_mode(db: &Connection, allow_workflows: bool) -> Result<(), StoreError> { let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?; - if !((1..=3).contains(&version) || allow_workflows && version == 4) { + if !((1..=3).contains(&version) || allow_workflows && matches!(version, 4 | 5)) { return Err(StoreError::UnsupportedSchema); } let app_id: i64 = db.pragma_query_value(None, "application_id", |r| r.get(0))?; - let mut query = db.prepare("SELECT type, name, sql FROM sqlite_schema WHERE name NOT IN ('sqlite_autoindex_snapshots_1','sqlite_autoindex_capabilities_1','sqlite_autoindex_revisions_1','sqlite_autoindex_reviews_1','sqlite_autoindex_compositions_1','sqlite_autoindex_composition_applications_1','sqlite_autoindex_derived_capabilities_1','sqlite_autoindex_derived_capabilities_2','sqlite_autoindex_revision_derivations_1','sqlite_autoindex_revision_derivations_2') AND NOT (?1 AND name IN ('sqlite_autoindex_workflows_1','sqlite_autoindex_workflow_revisions_1')) ORDER BY name")?; + let mut query = db.prepare("SELECT type, name, sql FROM sqlite_schema WHERE name NOT IN ('sqlite_autoindex_snapshots_1','sqlite_autoindex_capabilities_1','sqlite_autoindex_revisions_1','sqlite_autoindex_reviews_1','sqlite_autoindex_compositions_1','sqlite_autoindex_composition_applications_1','sqlite_autoindex_derived_capabilities_1','sqlite_autoindex_derived_capabilities_2','sqlite_autoindex_revision_derivations_1','sqlite_autoindex_revision_derivations_2') AND NOT (?1 AND name IN ('sqlite_autoindex_workflows_1','sqlite_autoindex_workflow_revisions_1','sqlite_autoindex_instruction_changes_1','sqlite_autoindex_instruction_events_1')) ORDER BY name")?; let schema: Vec<(String, String, String)> = query - .query_map([allow_workflows && version == 4], |r| { + .query_map([allow_workflows && matches!(version, 4 | 5)], |r| { Ok((r.get(0)?, r.get(1)?, r.get(2)?)) })? .collect::>()?; @@ -704,20 +722,27 @@ fn verify_schema_mode(db: &Connection, allow_workflows: bool) -> Result<(), Stor .map(|(name, sql)| ("table".into(), (*name).into(), (*sql).into())), ); } - if matches!(version, 3 | 4) { + if matches!(version, 3..=5) { expected.extend( composition_records::SCHEMAS .iter() .map(|(name, sql)| ("table".into(), (*name).into(), (*sql).into())), ); } - if version == 4 { + if version >= 4 { expected.extend( workflow_records::SCHEMAS .iter() .map(|(name, sql)| ("table".into(), (*name).into(), (*sql).into())), ); } + if version == 5 { + expected.extend( + instruction_history::SCHEMAS + .iter() + .map(|(name, sql)| ("table".into(), (*name).into(), (*sql).into())), + ); + } expected.sort_by(|a, b| a.1.cmp(&b.1)); if app_id != APPLICATION_ID || schema != expected { return Err(StoreError::UnsupportedSchema); diff --git a/crates/rangoon-store/src/recovery_copy.rs b/crates/rangoon-store/src/recovery_copy.rs new file mode 100644 index 0000000..7be2ae7 --- /dev/null +++ b/crates/rangoon-store/src/recovery_copy.rs @@ -0,0 +1,122 @@ +//! Pinned SQLCipher recovery images. The host owns private directory/key custody. +use super::*; +use std::io::Read; +use zeroize::Zeroizing; + +impl WorkspaceBackup { + /// Complete canonical record comparison for trusted recovery verification. + pub fn same_recovery_records(&self, other: &Self) -> Result { + let left = Zeroizing::new(workflow_backup::encode(&self.records)?); + let right = Zeroizing::new(workflow_backup::encode(&other.records)?); + Ok(*left == *right) + } +} + +impl Workspace { + /// Opaque, validated recovery snapshot for the trusted native host. Protected + /// instruction history is never returned as a plaintext portable byte buffer. + pub fn snapshot_encrypted_recovery(&self) -> Result { + let key = self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + encryption::verify_backend(key)?; + let mut db = self + .connect_complete_read_only(false)? + .ok_or(StoreError::NotFound)?; + let tx = db.transaction()?; + let bytes = Zeroizing::new(workflow_backup::encode(&workflow_mutations::read_records( + &tx, + )?)?); + let snapshot = WorkspaceBackup::decode_complete(&bytes)?; + tx.commit()?; + Ok(snapshot) + } + + /// Creates a new encrypted canonical copy, never modifies an existing file. + /// Logical records stay in host memory; the returned bytes are ciphertext. + pub fn create_encrypted_recovery_copy( + &self, + backup: &WorkspaceBackup, + ) -> Result, StoreError> { + self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + self.initialize_empty_encrypted()?; + let schema = + u32::try_from(backup.records.version).map_err(|_| StoreError::BackupInvalid)?; + let plan = self.prepare_empty_workflow_restore(backup, schema)?; + self.restore_empty_workflow_backup(backup, &plan)?; + let length = fs::symlink_metadata(self.path()) + .map_err(|_| StoreError::Unavailable)? + .len(); + let checked = self.inspect_encrypted_recovery_copy(length)?; + if !checked.same_recovery_records(backup)? { + return Err(StoreError::Corrupt); + } + // All SQLite handles have closed before reading the encrypted image. + let mut file = fs::File::open(self.path()).map_err(|_| StoreError::Unavailable)?; + let mut bytes = Vec::new(); + (&mut file) + .take(MAX_DATABASE_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| StoreError::Unavailable)?; + if bytes.len() as u64 != length + || file.metadata().map_err(|_| StoreError::Unavailable)?.len() != length + { + return Err(StoreError::WorkspaceChanged); + } + Ok(bytes) + } + + /// Existing-only, read-only inspection of a host-staged encrypted image. + /// Rejects trailing pages/bytes, sidecars, wrong keys and domain corruption. + pub fn inspect_encrypted_recovery_copy( + &self, + expected_file_bytes: u64, + ) -> Result { + self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + if expected_file_bytes == 0 || expected_file_bytes > MAX_DATABASE_BYTES { + return Err(StoreError::BackupInvalid); + } + let before = fs::symlink_metadata(self.path()).map_err(|_| StoreError::Unavailable)?; + if !before.is_file() || before.len() != expected_file_bytes { + return Err(StoreError::BackupInvalid); + } + self.require_absent_sidecars()?; + let mut database = self + .connect_complete_read_only(false)? + .ok_or(StoreError::BackupInvalid)?; + let transaction = database.transaction()?; + let pages: i64 = transaction.query_row("PRAGMA page_count", [], |row| row.get(0))?; + if u64::try_from(pages) + .ok() + .and_then(|pages| pages.checked_mul(4096)) + != Some(expected_file_bytes) + { + return Err(StoreError::BackupInvalid); + } + let archive = Zeroizing::new(workflow_backup::encode(&workflow_mutations::read_records( + &transaction, + )?)?); + let backup = WorkspaceBackup::decode_complete(&archive)?; + transaction.commit()?; + drop(database); + self.require_absent_sidecars()?; + let after = fs::symlink_metadata(self.path()).map_err(|_| StoreError::Unavailable)?; + if !after.is_file() || after.len() != expected_file_bytes { + return Err(StoreError::WorkspaceChanged); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if before.dev() != after.dev() + || before.ino() != after.ino() + || before.mtime() != after.mtime() + || before.mtime_nsec() != after.mtime_nsec() + { + return Err(StoreError::WorkspaceChanged); + } + } + Ok(backup) + } +} + +#[cfg(test)] +#[path = "recovery_copy_tests.rs"] +mod tests; diff --git a/crates/rangoon-store/src/recovery_copy_tests.rs b/crates/rangoon-store/src/recovery_copy_tests.rs new file mode 100644 index 0000000..47e0ba3 --- /dev/null +++ b/crates/rangoon-store/src/recovery_copy_tests.rs @@ -0,0 +1,171 @@ +use super::*; +use crate::composition_records_tests::TestDir; +#[cfg(feature = "encrypted-sqlite")] +use crate::composition_records_tests::{fixture_request, legacy, source}; + +#[test] +fn plaintext_store_cannot_create_or_inspect_recovery_copy() { + let root = TestDir::new(); + let backup = WorkspaceBackup::decode(&root.store().export_workflow_backup().unwrap()).unwrap(); + assert!(matches!( + root.store().create_encrypted_recovery_copy(&backup), + Err(StoreError::EncryptionUnavailable) + )); + assert!(matches!( + root.store().inspect_encrypted_recovery_copy(4096), + Err(StoreError::EncryptionUnavailable) + )); + assert!(!root.0.exists()); +} + +#[cfg(feature = "encrypted-sqlite")] +fn keyed(root: &TestDir, key: u8) -> Workspace { + Workspace::encrypted(root.0.clone(), WorkspaceKey::from_bytes([key; 32])).unwrap() +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn complete_records_recover_under_three_independent_keys_and_reopen() { + use rangoon_workflow::records::{SaveIntent, prepare_revision, workflow_id_from_nonce}; + let seed = TestDir::new(); + let saved = source(&seed); + let capability = legacy(&seed, &saved); + seed.store() + .review_capability(&capability.id, &capability.latest_revision_id) + .unwrap(); + let revised = seed + .store() + .revise_capability( + &capability.id, + &capability.latest_revision_id, + "Retained revision", + "Synthetic retained content", + ) + .unwrap() + .capability; + seed.store() + .review_capability(&revised.id, &revised.latest_revision_id) + .unwrap(); + let preview = seed + .store() + .preview_composition(&fixture_request()) + .unwrap(); + seed.store().apply_composition(&preview, true).unwrap(); + let mut parent = None; + for title in ["Recovery draft", "Retained workflow revision"] { + let definition = serde_json::to_vec(&serde_json::json!({"schemaVersion":"rangoon.workflow-definition.v1","title":title,"nodes":[],"controlEdges":[],"dataEdges":[]})).unwrap(); + let revision = prepare_revision( + &workflow_id_from_nonce(&[42; 32]), + parent.as_deref(), + SaveIntent::Draft, + &definition, + br#"{"positions":[]}"#, + ) + .unwrap(); + let plan = seed.store().inspect_workflow_save(&revision).unwrap(); + seed.store() + .save_workflow(&revision, &plan.expected_state_id) + .unwrap(); + parent = Some(revision.id().to_owned()); + } + let expected = seed.store().export_workflow_backup().unwrap(); + let backup = WorkspaceBackup::decode(&expected).unwrap(); + let source_root = TestDir::new(); + keyed(&source_root, 1) + .create_encrypted_recovery_copy(&backup) + .unwrap(); + let source_before = fs::read(source_root.0.join("workspace.sqlite3")).unwrap(); + let recovery_root = TestDir::new(); + let ciphertext = keyed(&recovery_root, 2) + .create_encrypted_recovery_copy(&backup) + .unwrap(); + assert!( + !ciphertext + .windows(16) + .any(|bytes| bytes == b"SQLite format 3\0") + ); + assert!( + !ciphertext + .windows(saved.source.content.len()) + .any(|b| b == saved.source.content.as_bytes()) + ); + let imported_root = TestDir::new(); + fs::create_dir(&imported_root.0).unwrap(); + fs::write(imported_root.0.join("workspace.sqlite3"), &ciphertext).unwrap(); + let recovered = keyed(&imported_root, 2) + .inspect_encrypted_recovery_copy(ciphertext.len() as u64) + .unwrap(); + let target_root = TestDir::new(); + let target = keyed(&target_root, 3); + target.initialize_empty_encrypted().unwrap(); + let plan = target.prepare_workflow_restore(&recovered).unwrap(); + target.restore_workflow_backup(&recovered, &plan).unwrap(); + drop(target); + assert_eq!( + keyed(&target_root, 3).export_workflow_backup().unwrap(), + expected + ); + assert_eq!( + fs::read(source_root.0.join("workspace.sqlite3")).unwrap(), + source_before + ); + assert!(keyed(&target_root, 2).workflow_data().is_err()); +} + +#[test] +#[cfg(feature = "encrypted-sqlite")] +fn wrong_key_tampering_trailing_bytes_pages_and_sidecars_are_rejected_read_only() { + let source_root = TestDir::new(); + source(&source_root); + let backup = + WorkspaceBackup::decode(&source_root.store().export_workflow_backup().unwrap()).unwrap(); + let stage = TestDir::new(); + let ciphertext = keyed(&stage, 2) + .create_encrypted_recovery_copy(&backup) + .unwrap(); + assert!( + keyed(&stage, 9) + .inspect_encrypted_recovery_copy(ciphertext.len() as u64) + .is_err() + ); + assert!( + keyed(&stage, 2) + .create_encrypted_recovery_copy(&backup) + .is_err() + ); + for mutation in 0..4 { + let mut altered = ciphertext.clone(); + match mutation { + 0 => altered[100] ^= 1, + 1 => altered.push(0), + 2 => altered.extend_from_slice(&[0; 4096]), + _ => { + altered[4096 + 100] ^= 1; + } + } + let root = TestDir::new(); + fs::create_dir(&root.0).unwrap(); + fs::write(root.0.join("workspace.sqlite3"), &altered).unwrap(); + assert!( + keyed(&root, 2) + .inspect_encrypted_recovery_copy(altered.len() as u64) + .is_err(), + "mutation {mutation}" + ); + assert_eq!(fs::read(root.0.join("workspace.sqlite3")).unwrap(), altered); + } + for suffix in ["-journal", "-wal", "-shm"] { + let sidecar = stage.0.join(format!("workspace.sqlite3{suffix}")); + fs::write(&sidecar, b"synthetic").unwrap(); + assert!( + keyed(&stage, 2) + .inspect_encrypted_recovery_copy(ciphertext.len() as u64) + .is_err() + ); + fs::remove_file(sidecar).unwrap(); + } + assert_eq!( + fs::read(stage.0.join("workspace.sqlite3")).unwrap(), + ciphertext + ); +} diff --git a/crates/rangoon-store/src/workflow_backup.rs b/crates/rangoon-store/src/workflow_backup.rs index 3de81a2..6bf4310 100644 --- a/crates/rangoon-store/src/workflow_backup.rs +++ b/crates/rangoon-store/src/workflow_backup.rs @@ -14,16 +14,293 @@ const SCHEMA: &str = "rangoon.backup.v3"; const MAX_MANIFEST: usize = 2 * 1024 * 1024; const MAX_RECORD: usize = 160 * 1024; -#[derive(Debug)] pub struct WorkspaceBackup { pub(super) records: Records, id: String, byte_length: usize, } +impl std::fmt::Debug for WorkspaceBackup { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("WorkspaceBackup()") + } +} + +/// A bounded, existing-only Legacy capture. This is not migration authority. +/// Paths, decoded records and plaintext bytes never enter diagnostics. +/// +/// ```compile_fail +/// fn serializable() {} +/// serializable::(); +/// ``` +pub struct ExistingWorkspaceCapture { + content: Option, + #[cfg(unix)] + source: ExistingSourceProof, +} + +struct CapturedContent { + archive: zeroize::Zeroizing>, + digest: String, + schema: u32, + inventory: WorkflowRecoveryCounts, +} + +impl std::fmt::Debug for ExistingWorkspaceCapture { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("ExistingWorkspaceCapture()") + } +} + +impl ExistingWorkspaceCapture { + fn content(&self) -> Result<&CapturedContent, StoreError> { + self.content.as_ref().ok_or(StoreError::WorkspaceChanged) + } + pub fn schema_version(&self) -> Result { + Ok(self.content()?.schema) + } + pub fn inventory(&self) -> Result<&WorkflowRecoveryCounts, StoreError> { + Ok(&self.content()?.inventory) + } + pub fn digest(&self) -> Result<&str, StoreError> { + Ok(&self.content()?.digest) + } + /// Restart-stable identity metadata, not authentication or content authority. + pub fn identity_fingerprint(&self) -> Result { + self.content()?; + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + self.source.check()?; + let mut bytes = b"rangoon.legacy-identity.v1\0".to_vec(); + bytes.push( + u8::try_from(self.source.ancestors.len()).map_err(|_| StoreError::Unavailable)?, + ); + for metadata in self + .source + .ancestors + .iter() + .rev() + .map(|(_, metadata)| metadata) + .chain(std::iter::once(&self.source.database)) + { + bytes.extend_from_slice(&metadata.dev().to_be_bytes()); + bytes.extend_from_slice(&metadata.ino().to_be_bytes()); + } + Ok(byte_digest(&bytes)) + } + #[cfg(not(unix))] + { + Err(StoreError::Unavailable) + } + } + /// Trusted Rust host access only. No renderer/export endpoint is registered. + pub fn archive(&self) -> Result<&[u8], StoreError> { + Ok(&self.content()?.archive) + } + pub fn cancel(&mut self) { + self.content = None; + } +} + +#[cfg(unix)] +struct ExistingSourceProof { + directory: PathBuf, + ancestors: Vec<(PathBuf, fs::Metadata)>, + database: fs::Metadata, +} + +#[cfg(unix)] +impl ExistingSourceProof { + fn observe(directory: &std::path::Path) -> Result { + use std::path::Component; + if !directory.is_absolute() + || directory.components().count() > 64 + || directory + .components() + .any(|part| matches!(part, Component::CurDir | Component::ParentDir)) + { + return Err(StoreError::Unavailable); + } + let mut ancestors = Vec::new(); + for path in directory.ancestors() { + let metadata = fs::symlink_metadata(path).map_err(|_| StoreError::Unavailable)?; + if linked(&metadata) || !metadata.is_dir() { + return Err(StoreError::Unavailable); + } + ancestors.push((path.to_owned(), metadata)); + } + let database = Self::database(directory)?; + let result = Self { + directory: directory.to_owned(), + ancestors, + database, + }; + result.check()?; + Ok(result) + } + fn same_identity(left: &fs::Metadata, right: &fs::Metadata) -> bool { + use std::os::unix::fs::MetadataExt; + left.dev() == right.dev() && left.ino() == right.ino() + } + fn database(directory: &std::path::Path) -> Result { + use std::os::unix::fs::MetadataExt; + // Refuse all sidecars before SQLite can inspect or recover them. A + // later appearance is a refusal too, never a repair/checkpoint path. + let mut count = 0; + for entry in fs::read_dir(directory).map_err(|_| StoreError::Unavailable)? { + let entry = entry.map_err(|_| StoreError::Unavailable)?; + count += 1; + if count > 1 || entry.file_name() != "workspace.sqlite3" { + return Err(StoreError::Unavailable); + } + } + let metadata = fs::symlink_metadata(directory.join("workspace.sqlite3")) + .map_err(|_| StoreError::Unavailable)?; + if linked(&metadata) || !metadata.is_file() || metadata.nlink() != 1 || metadata.len() == 0 + { + return Err(StoreError::Unavailable); + } + if metadata.len() > MAX_DATABASE_BYTES { + return Err(StoreError::Full); + } + Ok(metadata) + } + fn check(&self) -> Result<(), StoreError> { + for (path, held) in &self.ancestors { + let current = fs::symlink_metadata(path).map_err(|_| StoreError::WorkspaceChanged)?; + if linked(¤t) || !current.is_dir() || !Self::same_identity(held, ¤t) { + return Err(StoreError::WorkspaceChanged); + } + } + if !Self::same_identity(&self.database, &Self::database(&self.directory)?) { + return Err(StoreError::WorkspaceChanged); + } + Ok(()) + } + fn unchanged_during_capture(&self) -> Result<(), StoreError> { + use std::os::unix::fs::MetadataExt; + self.check()?; + let current = Self::database(&self.directory)?; + if self.database.len() != current.len() + || self.database.mtime() != current.mtime() + || self.database.mtime_nsec() != current.mtime_nsec() + || self.database.ctime() != current.ctime() + || self.database.ctime_nsec() != current.ctime_nsec() + { + return Err(StoreError::WorkspaceChanged); + } + Ok(()) + } +} + +#[cfg(test)] +std::thread_local! { + static CAPTURE_PROBE: std::cell::RefCell>> = std::cell::RefCell::new(None); +} + +impl Workspace { + /// Captures only an existing, initialized Legacy database. No create, + /// upgrade, journal recovery, vault access or temporary archive is allowed. + pub fn capture_existing_snapshot(&self) -> Result { + #[cfg(not(unix))] + { + Err(StoreError::Unavailable) + } + #[cfg(unix)] + { + if self.key.is_some() { + return Err(StoreError::Unavailable); + } + let source = ExistingSourceProof::observe(&self.directory)?; + let mut database = self + .connect_complete_read_only(true)? + .ok_or(StoreError::Unavailable)?; + source.check()?; + let transaction = database.transaction()?; + let schema: u32 = + transaction.pragma_query_value(None, "user_version", |row| row.get(0))?; + let records = workflow_mutations::read_records(&transaction)?; + let inventory = workflow_recovery::counts(&records); + let archive = zeroize::Zeroizing::new(encode(&records)?); + if archive.len() > MAX_BACKUP_BYTES { + return Err(StoreError::Full); + } + WorkspaceBackup::decode(&archive)?; + let digest = byte_digest(&archive); + #[cfg(test)] + CAPTURE_PROBE.with(|probe| { + if let Some(probe) = probe.borrow_mut().take() { + probe(); + } + }); + transaction.commit()?; + drop(database); + source.unchanged_during_capture()?; + Ok(ExistingWorkspaceCapture { + content: Some(CapturedContent { + archive, + digest, + schema, + inventory, + }), + source, + }) + } + } + + /// Full logical recapture, not an exclusive writer fence or cutover. + /// Every failure invalidates retained plaintext, including path mismatch. + pub fn revalidate_existing_capture( + &self, + retained: &mut ExistingWorkspaceCapture, + ) -> Result<(), StoreError> { + let result = (|| { + #[cfg(not(unix))] + { + let _ = retained; + Err(StoreError::Unavailable) + } + #[cfg(unix)] + { + retained.content()?; + if self.directory != retained.source.directory { + return Err(StoreError::WorkspaceChanged); + } + retained.source.check()?; + let fresh = self.capture_existing_snapshot()?; + let old = retained.content()?; + let new = fresh.content()?; + if old.schema != new.schema + || old.inventory != new.inventory + || old.digest != new.digest + || old.archive != new.archive + { + return Err(StoreError::WorkspaceChanged); + } + Ok(()) + } + })(); + if result.is_err() { + retained.cancel(); + } + result + } +} + impl WorkspaceBackup { pub fn decode(bytes: &[u8]) -> Result { - let records = if bytes.starts_with(MAGIC) { + // Protected history has no plaintext import/export surface. The complete + // codec is used only inside authenticated encrypted recovery custody. + if bytes.starts_with(b"RANGOON-BACKUP-V4\n") { + return Err(StoreError::BackupInvalid); + } + Self::decode_complete(bytes) + } + pub(super) fn decode_complete(bytes: &[u8]) -> Result { + let records = if bytes.starts_with(b"RANGOON-BACKUP-V4\n") { + instruction_history_backup::decode(bytes) + } else if bytes.starts_with(MAGIC) { decode(bytes).map_err(|error| match error { StoreError::Full => StoreError::Full, _ => StoreError::BackupInvalid, @@ -195,6 +472,12 @@ impl Manifest { /// Schema downgrade here is only the in-memory base reconstruction step; no /// destination database or original record version is changed. pub(super) fn canonical_database(base: &Records) -> Result { + if base.version == 5 { + return instruction_history_backup::canonical_database(base); + } + if !base.history.changes.is_empty() || !base.history.events.is_empty() { + return Err(StoreError::Corrupt); + } let workflows = &base.workflows; if !(1..=4).contains(&base.version) { return Err(StoreError::UnsupportedSchema); @@ -235,6 +518,12 @@ pub(super) fn canonical_database(base: &Records) -> Result Result, StoreError> { + if base.version == 5 { + return instruction_history_backup::encode(base); + } + if !base.history.changes.is_empty() || !base.history.events.is_empty() { + return Err(StoreError::Corrupt); + } let workflows = &base.workflows; if !(1..=4).contains(&base.version) { return Err(StoreError::UnsupportedSchema); @@ -373,7 +662,11 @@ impl Workspace { return encode(&Records::empty()); }; let tx = db.transaction()?; - let bytes = encode(&workflow_mutations::read_records(&tx)?)?; + let records = workflow_mutations::read_records(&tx)?; + if records.version == 5 { + return Err(StoreError::UnsupportedSchema); + } + let bytes = encode(&records)?; tx.commit()?; Ok(bytes) } @@ -382,3 +675,7 @@ impl Workspace { #[cfg(test)] #[path = "workflow_backup_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "workspace_capture_tests.rs"] +mod capture_tests; diff --git a/crates/rangoon-store/src/workflow_backup_tests.rs b/crates/rangoon-store/src/workflow_backup_tests.rs index 5b587d8..a569bb3 100644 --- a/crates/rangoon-store/src/workflow_backup_tests.rs +++ b/crates/rangoon-store/src/workflow_backup_tests.rs @@ -179,7 +179,7 @@ fn legacy_v1_v2_decode_and_old_export_bytes_are_unchanged() { ); assert!(v2.records.workflows.revisions.is_empty()); assert!(encode(&base, &fixture(&base)).is_err()); - for version in [0, 5, i64::MAX] { + for version in [0, 6, i64::MAX] { let mut unknown = base.clone(); unknown.version = version; assert_eq!( diff --git a/crates/rangoon-store/src/workflow_deletion.rs b/crates/rangoon-store/src/workflow_deletion.rs index a0fc1f5..c4d8d72 100644 --- a/crates/rangoon-store/src/workflow_deletion.rs +++ b/crates/rangoon-store/src/workflow_deletion.rs @@ -81,6 +81,7 @@ fn deletion_plan( )?; result.version = current.version; result.workflows = current.workflows.clone(); + result.history = current.history.clone(); (base_plan.title, base_plan.dependencies, result) } }; @@ -144,7 +145,7 @@ fn commit_deletion( } WorkflowRecordKind::Capability => { tx.execute("DELETE FROM reviews WHERE revision_id IN (SELECT revision_id FROM revisions WHERE capability_id=?1)", [&plan.id])?; - if matches!(current.version, 3 | 4) { + if matches!(current.version, 3..=5) { tx.execute("DELETE FROM revision_derivations WHERE revision_id IN (SELECT revision_id FROM revisions WHERE capability_id=?1)", [&plan.id])?; } tx.execute("DELETE FROM revisions WHERE capability_id=?1", [&plan.id])?; @@ -152,7 +153,7 @@ fn commit_deletion( "DELETE FROM capabilities WHERE capability_id=?1", [&plan.id], )?; - if matches!(current.version, 3 | 4) { + if matches!(current.version, 3..=5) { tx.execute( "DELETE FROM derived_capabilities WHERE capability_id=?1", [&plan.id], @@ -169,7 +170,7 @@ fn commit_deletion( tx.execute("DELETE FROM workflows WHERE workflow_id=?1", [&plan.id])?; } } - if matches!(current.version, 3 | 4) { + if matches!(current.version, 3..=5) { for id in current .applications .keys() diff --git a/crates/rangoon-store/src/workflow_mutations.rs b/crates/rangoon-store/src/workflow_mutations.rs index 9ca14d6..11eb6ef 100644 --- a/crates/rangoon-store/src/workflow_mutations.rs +++ b/crates/rangoon-store/src/workflow_mutations.rs @@ -16,18 +16,26 @@ pub(super) fn read_records(db: &Connection) -> Result { pub(super) fn ensure_schema(db: &Connection, target: i64) -> Result<(), StoreError> { let current: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?; - if !(1..=4).contains(&target) || !(0..=4).contains(¤t) || target < current { + if !(1..=5).contains(&target) || !(0..=5).contains(¤t) || target < current { return Err(StoreError::UnsupportedSchema); } - if current == 4 { + if current == target && current >= 4 { return verify_schema_mode(db, true); } - composition_backup::ensure_schema(db, target.min(3))?; - if target == 4 { - for (_, sql) in workflow_records::SCHEMAS { + if current < 4 { + composition_backup::ensure_schema(db, target.min(3))?; + if target >= 4 { + for (_, sql) in workflow_records::SCHEMAS { + db.execute_batch(sql)?; + } + db.pragma_update(None, "user_version", 4)?; + } + } + if current < 5 && target == 5 { + for (_, sql) in instruction_history::SCHEMAS { db.execute_batch(sql)?; } - db.pragma_update(None, "user_version", 4)?; + db.pragma_update(None, "user_version", 5)?; } verify_schema_mode(db, true) } @@ -99,6 +107,22 @@ pub(super) fn insert_additions( )?; } } + for (id, change) in &result.history.changes { + if !current.history.changes.contains_key(id) { + db.execute( + "INSERT INTO instruction_changes VALUES (?1,?2)", + params![id, change.bytes()?.as_slice()], + )?; + } + } + for (id, event) in &result.history.events { + if !current.history.events.contains_key(id) { + db.execute( + "INSERT INTO instruction_events VALUES (?1,?2)", + params![id, event.bytes()?], + )?; + } + } Ok(()) } diff --git a/crates/rangoon-store/src/workflow_recovery.rs b/crates/rangoon-store/src/workflow_recovery.rs index c89fcfe..6d9024f 100644 --- a/crates/rangoon-store/src/workflow_recovery.rs +++ b/crates/rangoon-store/src/workflow_recovery.rs @@ -15,6 +15,14 @@ pub struct WorkflowRecoveryCounts { pub derivations: u32, pub workflows: u32, pub workflow_revisions: u32, + #[serde(skip_serializing_if = "is_zero")] + pub instruction_changes: u32, + #[serde(skip_serializing_if = "is_zero")] + pub instruction_events: u32, +} + +fn is_zero(value: &u32) -> bool { + *value == 0 } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -28,6 +36,8 @@ pub struct WorkflowRestorePlan { kept_sources: u32, kept_capabilities: u32, kept_workflows: u32, + #[serde(skip_serializing_if = "Option::is_none")] + target_workspace_schema: Option, } impl WorkflowRestorePlan { @@ -39,6 +49,60 @@ impl WorkflowRestorePlan { } } +/// Host-retained plan for a separately created, empty encrypted destination. +/// +/// ```compile_fail +/// fn serializable() {} +/// serializable::(); +/// ``` +pub struct EmptyWorkflowRestorePlan { + base: WorkflowRestorePlan, + target_schema: i64, + source_schema: u32, + directory: PathBuf, +} +impl std::fmt::Debug for EmptyWorkflowRestorePlan { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("EmptyWorkflowRestorePlan()") + } +} + +fn empty_restore_plan( + current: &Records, + backup: &WorkspaceBackup, + source_schema: u32, +) -> Result<(WorkflowRestorePlan, Records), StoreError> { + if counts(current) != WorkflowRecoveryCounts::default() + || current.version != 1 + || source_schema > 5 + { + return Err(StoreError::WorkspaceChanged); + } + // Generic restore may trim unneeded composition records. An exact transfer + // into a proven empty target preserves every validated incoming record. + let (plan, _) = restore_plan(current, backup)?; + if source_schema == 0 && counts(&backup.records) != WorkflowRecoveryCounts::default() { + return Err(StoreError::BackupInvalid); + } + let mut result = backup.records.clone(); + // V2 decoding reconstructs schema 3. Only the retained Legacy capture knows + // the physical source schema; validate its representation without changing bytes. + result.version = i64::from(source_schema.max(1)); + let checked = Records::load_complete(&composition_backup::canonical_database(&result)?)?; + if workflow_backup::encode(&checked)? != workflow_backup::encode(&backup.records)? { + return Err(StoreError::Corrupt); + } + Ok((plan, checked)) +} + +fn empty_target_records(database: &Connection) -> Result { + let schema: i64 = database.pragma_query_value(None, "user_version", |row| row.get(0))?; + if schema != 1 { + return Err(StoreError::WorkspaceChanged); + } + Records::load_complete(database) +} + pub(super) fn counts(records: &Records) -> WorkflowRecoveryCounts { let base = composition_recovery::counts(records); WorkflowRecoveryCounts { @@ -51,6 +115,8 @@ pub(super) fn counts(records: &Records) -> WorkflowRecoveryCounts { derivations: base.derivations, workflows: records.workflows.owners.len() as u32, workflow_revisions: records.workflows.revisions.len() as u32, + instruction_changes: records.history.changes.len() as u32, + instruction_events: records.history.events.len() as u32, } } @@ -69,15 +135,18 @@ pub(super) fn difference( derivations: sub(larger.derivations, smaller.derivations)?, workflows: sub(larger.workflows, smaller.workflows)?, workflow_revisions: sub(larger.workflow_revisions, smaller.workflow_revisions)?, + instruction_changes: sub(larger.instruction_changes, smaller.instruction_changes)?, + instruction_events: sub(larger.instruction_events, smaller.instruction_events)?, }) } pub(super) fn base_projection(records: &Records) -> Records { let mut result = records.clone(); - if result.version == 4 { + if result.version >= 4 { result.version = 3; } result.workflows = WorkflowRows::default(); + result.history = instruction_history::HistoryRows::default(); result } @@ -85,19 +154,30 @@ pub(super) fn restore_plan( current: &Records, backup: &WorkspaceBackup, ) -> Result<(WorkflowRestorePlan, Records), StoreError> { - let mut result = - composition_recovery::union(&base_projection(current), &base_projection(&backup.records))?; - let (workflows, kept_workflows) = current - .workflows - .union(&backup.records.workflows, &result) - .map_err(|error| match error { - UnionError::Invalid => StoreError::BackupInvalid, - UnionError::Full => StoreError::WorkflowFull, - UnionError::DependencyMissing => StoreError::WorkflowDependencyMissing, - })?; - result.workflows = workflows; + // A fresh target must recover the complete archive, including composition + // records not currently referenced by an output. Nonempty targets retain + // their established additive merge semantics and conflict checks. + let (mut result, kept_workflows) = if counts(current) == WorkflowRecoveryCounts::default() { + (backup.records.clone(), 0) + } else { + let mut result = composition_recovery::union( + &base_projection(current), + &base_projection(&backup.records), + )?; + let (workflows, kept) = current + .workflows + .union(&backup.records.workflows, &result) + .map_err(|error| match error { + UnionError::Invalid => StoreError::BackupInvalid, + UnionError::Full => StoreError::WorkflowFull, + UnionError::DependencyMissing => StoreError::WorkflowDependencyMissing, + })?; + result.workflows = workflows; + result.history = current.history.union(&backup.records.history, &result)?; + (result, kept) + }; let add = difference(counts(&result), counts(current))?; - result.version = if add == WorkflowRecoveryCounts::default() { + result.version = if add == WorkflowRecoveryCounts::default() && backup.records.version != 5 { current.version } else { current.version.max(backup.records.version) @@ -106,7 +186,14 @@ pub(super) fn restore_plan( // This creates only an in-memory database, never the destination directory. let result = Records::load_complete(&composition_backup::canonical_database(&result)?)?; let plan = WorkflowRestorePlan { - schema_version: "rangoon.restore-plan.v2", + schema_version: if current.version == 5 + || backup.records.version == 5 + || result.version == 5 + { + "rangoon.restore-plan.v3" + } else { + "rangoon.restore-plan.v2" + }, backup_id: backup.id().into(), expected_state_id: current.state_id()?, byte_length: backup.byte_length(), @@ -118,6 +205,10 @@ pub(super) fn restore_plan( .ok_or(StoreError::Corrupt)?, add, kept_workflows, + target_workspace_schema: (current.version == 5 + || backup.records.version == 5 + || result.version == 5) + .then_some(result.version as u32), }; Ok((plan, result)) } @@ -147,7 +238,7 @@ fn commit_restore( ) -> Result { let current = workflow_mutations::read_records(tx)?; let (plan, result) = checked_restore(¤t, backup, retained)?; - if plan.add != WorkflowRecoveryCounts::default() { + if plan.add != WorkflowRecoveryCounts::default() || result.version != current.version { #[cfg(test)] composition_recovery_tests::fault_checkpoint(tx, "before_workflow_restore_migration")?; workflow_mutations::ensure_schema(tx, result.version)?; @@ -165,12 +256,93 @@ fn commit_restore( } impl Workspace { + /// Does not create a destination. This profile requires existing keyed schema 1. + pub fn prepare_empty_workflow_restore( + &self, + backup: &WorkspaceBackup, + source_schema: u32, + ) -> Result { + let key = self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + encryption::verify_backend(key)?; + let mut database = self + .connect_complete_read_only(true)? + .ok_or(StoreError::WorkspaceChanged)?; + let transaction = database.transaction()?; + let current = empty_target_records(&transaction)?; + let (base, result) = empty_restore_plan(¤t, backup, source_schema)?; + transaction.commit()?; + Ok(EmptyWorkflowRestorePlan { + base, + target_schema: result.version, + source_schema, + directory: self.directory.clone(), + }) + } + + /// Complete logical transfer only into the exact retained empty keyed target. + pub fn restore_empty_workflow_backup( + &self, + backup: &WorkspaceBackup, + retained: &EmptyWorkflowRestorePlan, + ) -> Result { + let key = self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + encryption::verify_backend(key)?; + if self.directory != retained.directory { + return Err(StoreError::WorkspaceChanged); + } + let mut database = self + .connect_complete_read_only(true)? + .ok_or(StoreError::WorkspaceChanged)?; + let transaction = database.transaction()?; + let current = empty_target_records(&transaction)?; + let (base, result) = empty_restore_plan(¤t, backup, retained.source_schema)?; + if base != retained.base || result.version != retained.target_schema { + return Err(StoreError::WorkspaceChanged); + } + transaction.commit()?; + drop(database); + let mut database = self + .connect_complete_with_empty(false, true)? + .ok_or(StoreError::WorkspaceChanged)?; + let transaction = database.transaction_with_behavior(TransactionBehavior::Immediate)?; + let current = empty_target_records(&transaction)?; + let (base, result) = empty_restore_plan(¤t, backup, retained.source_schema)?; + if base != retained.base || result.version != retained.target_schema { + return Err(StoreError::WorkspaceChanged); + } + #[cfg(test)] + composition_recovery_tests::fault_checkpoint( + &transaction, + "before_workflow_restore_migration", + )?; + workflow_mutations::ensure_schema(&transaction, result.version)?; + #[cfg(test)] + composition_recovery_tests::fault_checkpoint( + &transaction, + "after_workflow_restore_migration", + )?; + workflow_mutations::insert_additions(&transaction, ¤t, &result)?; + #[cfg(test)] + composition_recovery_tests::fault_checkpoint(&transaction, "after_workflow_restore_rows")?; + let actual = workflow_mutations::read_records(&transaction)?; + if actual.state_id()? != result.state_id()? + || workflow_backup::encode(&actual)? != workflow_backup::encode(&backup.records)? + { + return Err(StoreError::Corrupt); + } + let data = workflow_mutations::data(&transaction, &actual)?; + transaction.commit()?; + Ok(data) + } /// The host must retain the exact validated archive and issued plan. pub fn restore_workflow_backup( &self, backup: &WorkspaceBackup, retained: &WorkflowRestorePlan, ) -> Result { + if backup.records.version == 5 { + self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + } // Preflight is noncreating. No-op absence is linearized at this read. let (absent, current) = match self.connect_complete_read_only(true)? { None => (true, Records::empty()), @@ -181,8 +353,9 @@ impl Workspace { (false, records) } }; - let (plan, _) = checked_restore(¤t, backup, retained)?; - let additions = plan.add != WorkflowRecoveryCounts::default(); + let (plan, result) = checked_restore(¤t, backup, retained)?; + let additions = + plan.add != WorkflowRecoveryCounts::default() || result.version != current.version; if absent && !additions { return workflow_views::data(¤t, 0, 0); } @@ -210,6 +383,9 @@ impl Workspace { &self, backup: &WorkspaceBackup, ) -> Result { + if backup.records.version == 5 { + self.key.as_ref().ok_or(StoreError::EncryptionUnavailable)?; + } let Some(mut db) = self.connect_complete_read_only(true)? else { return Ok(restore_plan(&Records::empty(), backup)?.0); }; @@ -228,3 +404,7 @@ mod tests; #[cfg(test)] #[path = "workflow_restore_tests.rs"] mod restore_tests; + +#[cfg(test)] +#[path = "workspace_adoption_tests.rs"] +mod adoption_tests; diff --git a/crates/rangoon-store/src/workflow_saves.rs b/crates/rangoon-store/src/workflow_saves.rs index 6b7ab32..b5a890d 100644 --- a/crates/rangoon-store/src/workflow_saves.rs +++ b/crates/rangoon-store/src/workflow_saves.rs @@ -108,7 +108,7 @@ fn prepare( return Err(StoreError::Unavailable); } let mut result = current.clone(); - result.version = 4; + result.version = current.version.max(4); result .workflows .owners @@ -141,7 +141,7 @@ fn commit_save( if !plan.already_saved { #[cfg(test)] composition_recovery_tests::fault_checkpoint(tx, "before_workflow_save_migration")?; - workflow_mutations::ensure_schema(tx, 4)?; + workflow_mutations::ensure_schema(tx, result.version)?; #[cfg(test)] composition_recovery_tests::fault_checkpoint(tx, "after_workflow_save_migration")?; let saved = result diff --git a/crates/rangoon-store/src/workflow_views.rs b/crates/rangoon-store/src/workflow_views.rs index 9fd9312..262bdd3 100644 --- a/crates/rangoon-store/src/workflow_views.rs +++ b/crates/rangoon-store/src/workflow_views.rs @@ -195,7 +195,11 @@ pub(super) fn data( reusable_bytes: u64, ) -> Result { Ok(WorkflowWorkspaceData { - schema_version: "rangoon.workspace-data.v2", + schema_version: if records.version == 5 { + "rangoon.workspace-data.v3" + } else { + "rangoon.workspace-data.v2" + }, state_id: records.state_id()?, records: workflow_recovery::counts(records), database_bytes, diff --git a/crates/rangoon-store/src/workspace_adoption_tests.rs b/crates/rangoon-store/src/workspace_adoption_tests.rs new file mode 100644 index 0000000..17614cb --- /dev/null +++ b/crates/rangoon-store/src/workspace_adoption_tests.rs @@ -0,0 +1,386 @@ +//! Disposable strict encrypted-destination transfer tests. +use super::*; +use crate::composition_records_tests::TestDir; + +#[test] +#[cfg(unix)] +fn source_fingerprint_matches_root_to_file_identity_and_is_unavailable_after_cancel() { + use std::os::unix::fs::MetadataExt; + let source = TestDir::new(); + crate::composition_records_tests::source(&source); + let mut capture = source.store().capture_existing_snapshot().unwrap(); + let paths: Vec<_> = source.0.ancestors().collect(); + let mut expected = b"rangoon.legacy-identity.v1\0".to_vec(); + expected.push(u8::try_from(paths.len()).unwrap()); + let database = source.store().path(); + for path in paths + .into_iter() + .rev() + .chain(std::iter::once(database.as_path())) + { + let metadata = fs::symlink_metadata(path).unwrap(); + expected.extend_from_slice(&metadata.dev().to_be_bytes()); + expected.extend_from_slice(&metadata.ino().to_be_bytes()); + } + assert_eq!( + capture.identity_fingerprint().unwrap(), + rangoon_domain::byte_digest(&expected) + ); + capture.cancel(); + assert!(capture.identity_fingerprint().is_err()); +} + +#[test] +fn plaintext_target_cannot_prepare_strict_transfer_or_create_data() { + let target = TestDir::new(); + let source = TestDir::new(); + let archive = + WorkspaceBackup::decode(&source.store().export_workflow_backup().unwrap()).unwrap(); + assert!(matches!( + target.store().prepare_empty_workflow_restore(&archive, 0), + Err(StoreError::EncryptionUnavailable) + )); + assert!(!target.0.exists()); +} + +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn fixture(schema: u32, populated: bool) -> TestDir { + use crate::composition_records_tests::{fixture_request, legacy, source}; + let root = TestDir::new(); + if populated { + let saved = source(&root); + if schema >= 2 { + let capability = legacy(&root, &saved); + root.store() + .review_capability(&capability.id, &capability.latest_revision_id) + .unwrap(); + let revised = root + .store() + .revise_capability( + &capability.id, + &capability.latest_revision_id, + "Retained history", + "Reviewed historical content.\r\n", + ) + .unwrap() + .capability; + root.store() + .review_capability(&revised.id, &revised.latest_revision_id) + .unwrap(); + } + if schema >= 3 { + let preview = root + .store() + .preview_composition(&fixture_request()) + .unwrap(); + root.store().apply_composition(&preview, true).unwrap(); + } + if schema == 4 { + use rangoon_workflow::records::{SaveIntent, prepare_revision, workflow_id_from_nonce}; + let record = prepare_revision(&workflow_id_from_nonce(&[87; 32]), None, SaveIntent::Draft, br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Adoption draft","nodes":[],"controlEdges":[],"dataEdges":[]}"#, br#"{"positions":[]}"#).unwrap(); + let plan = root.store().inspect_workflow_save(&record).unwrap(); + root.store() + .save_workflow(&record, &plan.expected_state_id) + .unwrap(); + let next = prepare_revision(&workflow_id_from_nonce(&[87;32]), Some(record.id()), SaveIntent::Draft, br#"{"schemaVersion":"rangoon.workflow-definition.v1","title":"Retained workflow history","nodes":[],"controlEdges":[],"dataEdges":[]}"#, br#"{"positions":[]}"#).unwrap(); + let plan = root.store().inspect_workflow_save(&next).unwrap(); + root.store() + .save_workflow(&next, &plan.expected_state_id) + .unwrap(); + } + } else { + fs::create_dir(&root.0).unwrap(); + let database = root.db(); + database + .execute_batch("PRAGMA page_size=4096; VACUUM;") + .unwrap(); + if schema > 0 { + workflow_mutations::ensure_schema(&database, i64::from(schema)).unwrap(); + } + } + root +} + +#[cfg(feature = "encrypted-sqlite")] +fn encrypted(root: &TestDir) -> Workspace { + Workspace::encrypted(root.0.clone(), WorkspaceKey::from_bytes([89; 32])).unwrap() +} + +#[test] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn exact_transfer_preserves_all_empty_and_populated_schemas_and_records() { + for (schema, populated) in (0..=4) + .map(|s| (s, false)) + .chain((1..=4).map(|s| (s, true))) + { + let source = fixture(schema, populated); + let before = fs::read(source.store().path()).unwrap(); + let capture = source.store().capture_existing_snapshot().unwrap(); + let backup = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + let target = TestDir::new(); + let store = encrypted(&target); + store.initialize_empty_encrypted().unwrap(); + let plan = store + .prepare_empty_workflow_restore(&backup, schema) + .unwrap(); + assert_eq!(format!("{plan:?}"), "EmptyWorkflowRestorePlan()"); + store.restore_empty_workflow_backup(&backup, &plan).unwrap(); + assert_eq!( + store.export_workflow_backup().unwrap(), + capture.archive().unwrap() + ); + let database = store.connect_complete_read_only(true).unwrap().unwrap(); + let actual: u32 = database + .pragma_query_value(None, "user_version", |r| r.get(0)) + .unwrap(); + assert_eq!(actual, schema.max(1)); + drop(database); + assert_eq!( + encrypted(&target).export_workflow_backup().unwrap(), + capture.archive().unwrap() + ); + assert_eq!(fs::read(source.store().path()).unwrap(), before); + for capability in store.list_capabilities_v1().unwrap() { + assert_eq!( + serde_json::to_value(store.open_capability_v1(&capability.id, None).unwrap()) + .unwrap(), + serde_json::to_value( + source + .store() + .open_capability_v1(&capability.id, None) + .unwrap() + ) + .unwrap() + ); + for profile in [ + rangoon_compile::Profile::AgentsMdV1, + rangoon_compile::Profile::ClaudeMdV1, + ] { + let actual = store + .compile_capability(&capability.id, &capability.latest_revision_id, profile) + .unwrap(); + let expected = source + .store() + .compile_capability(&capability.id, &capability.latest_revision_id, profile) + .unwrap(); + assert_eq!( + serde_json::to_value(&actual).unwrap(), + serde_json::to_value(&expected).unwrap() + ); + assert_eq!( + rangoon_compile::encode_bundle(&actual.compilation), + rangoon_compile::encode_bundle(&expected.compilation) + ); + } + } + assert!( + !fs::read(store.path()) + .unwrap() + .starts_with(b"SQLite format 3") + ); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn strict_transfer_keeps_shared_application_with_missing_output() { + use crate::composition_records_tests::{ + fixture_request, resolved_source, retain_outputs, schema3, source, + }; + let origin = TestDir::new(); + let saved = source(&origin); + let database = origin.db(); + schema3(&database); + retain_outputs( + &database, + &fixture_request(), + &resolved_source(&saved), + &[], + &[0], + ); + drop(database); + let capture = origin.store().capture_existing_snapshot().unwrap(); + assert_eq!(capture.inventory().unwrap().recipes, 1); + assert_eq!(capture.inventory().unwrap().applications, 1); + assert_eq!(capture.inventory().unwrap().capabilities, 1); + let backup = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + let target = TestDir::new(); + let store = encrypted(&target); + store.initialize_empty_encrypted().unwrap(); + let plan = store.prepare_empty_workflow_restore(&backup, 3).unwrap(); + store.restore_empty_workflow_backup(&backup, &plan).unwrap(); + assert_eq!( + store.export_workflow_backup().unwrap(), + capture.archive().unwrap() + ); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn source_schema_must_represent_complete_archive_without_silent_downconversion() { + let origin = fixture(4, true); + let capture = origin.store().capture_existing_snapshot().unwrap(); + let backup = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + let target = TestDir::new(); + let store = encrypted(&target); + store.initialize_empty_encrypted().unwrap(); + let before = fs::read(store.path()).unwrap(); + for schema in [0, 1, 2, 3, 5, u32::MAX] { + assert!( + store + .prepare_empty_workflow_restore(&backup, schema) + .is_err() + ); + assert_eq!(fs::read(store.path()).unwrap(), before); + } +} + +#[test] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn strict_transaction_full_rolls_back_and_kills_refuse_uncertain_destination() { + for (phase, mode) in [ + ("before_workflow_restore_migration", "full"), + ("after_workflow_restore_migration", "full"), + ("before_workflow_restore_migration", "crash"), + ("after_workflow_restore_migration", "crash"), + ("after_workflow_restore_rows", "crash"), + ] { + let source = fixture(4, true); + let large = format!( + "# Large synthetic source\n{}", + format!("{}\n", "x".repeat(2000)).repeat(90) + ); + source + .store() + .save_v1(&analyze("SKILL.md", large.as_bytes()).unwrap()) + .unwrap(); + let capture = source.store().capture_existing_snapshot().unwrap(); + let target = TestDir::new(); + let store = encrypted(&target); + store.initialize_empty_encrypted().unwrap(); + let before = store.export_workflow_backup().unwrap(); + let input = target.0.join("synthetic-archive"); + fs::write(&input, capture.archive().unwrap()).unwrap(); + crate::composition_recovery_tests::fault_child_for( + &target, + &input, + phase, + mode, + "unused", + "workflow_recovery::adoption_tests::strict_transaction_child", + ); + if mode == "full" || phase == "before_workflow_restore_migration" { + assert_eq!(encrypted(&target).export_workflow_backup().unwrap(), before); + assert_eq!( + encrypted(&target).workflow_data().unwrap().records, + WorkflowRecoveryCounts::default() + ); + } else { + // A killed spilled transaction leaves an uncertain encrypted journal. + // Existing readers refuse it; this packet must not recover/repair it. + assert!(matches!( + encrypted(&target).export_workflow_backup(), + Err(StoreError::EncryptedStoreInvalid) + )); + assert!(encrypted(&target).workflow_data().is_err()); + let backup = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + assert!( + encrypted(&target) + .prepare_empty_workflow_restore(&backup, 4) + .is_err() + ); + } + } +} + +#[test] +#[ignore = "Disposable encrypted store child driven only by its parent"] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn strict_transaction_child() { + let root = PathBuf::from(std::env::var_os("RANGOON_RECOVERY_TEST_WORKSPACE").unwrap()); + assert!(root.starts_with(std::env::temp_dir().canonicalize().unwrap())); + assert!( + root.file_name() + .unwrap() + .to_str() + .unwrap() + .starts_with("rangoon-composition-records-") + ); + let store = Workspace::encrypted(root.clone(), WorkspaceKey::from_bytes([89; 32])).unwrap(); + let backup = + WorkspaceBackup::decode(&fs::read(root.join("synthetic-archive")).unwrap()).unwrap(); + let plan = store.prepare_empty_workflow_restore(&backup, 4).unwrap(); + let result = store.restore_empty_workflow_backup(&backup, &plan); + assert_eq!( + std::env::var("RANGOON_RECOVERY_TEST_MODE").as_deref(), + Ok("full") + ); + assert!( + matches!(result, Err(StoreError::Full)), + "actual SQLite-full result required" + ); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn strict_transfer_refuses_absent_nonempty_stale_foreign_and_changed_backup_targets() { + let source = fixture(2, true); + let capture = source.store().capture_existing_snapshot().unwrap(); + let backup = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + let absent = TestDir::new(); + assert!( + encrypted(&absent) + .prepare_empty_workflow_restore(&backup, 2) + .is_err() + ); + assert!(!absent.0.exists()); + let target = TestDir::new(); + let store = encrypted(&target); + store.initialize_empty_encrypted().unwrap(); + let plan = store.prepare_empty_workflow_restore(&backup, 2).unwrap(); + let foreign = TestDir::new(); + let other = encrypted(&foreign); + other.initialize_empty_encrypted().unwrap(); + assert!(other.restore_empty_workflow_backup(&backup, &plan).is_err()); + let empty = WorkspaceBackup::decode( + &Workspace::new(TestDir::new().0.clone()) + .export_workflow_backup() + .unwrap(), + ) + .unwrap(); + assert!(store.restore_empty_workflow_backup(&empty, &plan).is_err()); + store + .save(&analyze("AGENTS.md", b"# Target changed\n").unwrap()) + .unwrap(); + let before = store.export_workflow_backup().unwrap(); + assert!(store.prepare_empty_workflow_restore(&backup, 2).is_err()); + assert!(store.restore_empty_workflow_backup(&backup, &plan).is_err()); + assert_eq!(store.export_workflow_backup().unwrap(), before); +} + +#[test] +#[cfg(all(unix, feature = "encrypted-sqlite"))] +fn additive_noop_restore_keeps_schema_while_strict_transfer_preserves_empty_higher_schema() { + let source = fixture(4, false); + let backup = WorkspaceBackup::decode( + source + .store() + .capture_existing_snapshot() + .unwrap() + .archive() + .unwrap(), + ) + .unwrap(); + let target = TestDir::new(); + let store = encrypted(&target); + store.initialize_empty_encrypted().unwrap(); + let before = store.export_workflow_backup().unwrap(); + let plan = store.prepare_workflow_restore(&backup).unwrap(); + store.restore_workflow_backup(&backup, &plan).unwrap(); + assert_eq!(store.export_workflow_backup().unwrap(), before); + let strict = store.prepare_empty_workflow_restore(&backup, 4).unwrap(); + store + .restore_empty_workflow_backup(&backup, &strict) + .unwrap(); + assert_ne!(store.export_workflow_backup().unwrap(), before); +} diff --git a/crates/rangoon-store/src/workspace_capture_tests.rs b/crates/rangoon-store/src/workspace_capture_tests.rs new file mode 100644 index 0000000..7266307 --- /dev/null +++ b/crates/rangoon-store/src/workspace_capture_tests.rs @@ -0,0 +1,420 @@ +//! Disposable existing-only capture and drift tests. No normal workspace/key. +use super::*; +use crate::composition_records_tests::TestDir; +#[cfg(unix)] +use crate::composition_records_tests::{fixture_request, legacy, source}; + +#[cfg(unix)] +fn populated(version: u32) -> TestDir { + let directory = TestDir::new(); + let saved = source(&directory); + if version >= 2 { + let capability = legacy(&directory, &saved); + directory + .store() + .review_capability(&capability.id, &capability.latest_revision_id) + .unwrap(); + } + if version >= 3 { + let preview = directory + .store() + .preview_composition(&fixture_request()) + .unwrap(); + directory.store().apply_composition(&preview, true).unwrap(); + } + if version == 4 { + append_workflow(&directory, None); + } + directory +} + +#[cfg(unix)] +fn append_workflow( + directory: &TestDir, + parent: Option<&str>, +) -> rangoon_workflow::records::WorkflowRevision { + use rangoon_workflow::records::{SaveIntent, prepare_revision, workflow_id_from_nonce}; + let definition = serde_json::json!({"schemaVersion":"rangoon.workflow-definition.v1","title":if parent.is_some() {"Next draft"} else {"First draft"},"nodes":[],"controlEdges":[],"dataEdges":[]}); + let record = prepare_revision( + &workflow_id_from_nonce(&[91; 32]), + parent, + SaveIntent::Draft, + &serde_json::to_vec(&definition).unwrap(), + br#"{"positions":[]}"#, + ) + .unwrap(); + let plan = directory.store().inspect_workflow_save(&record).unwrap(); + directory + .store() + .save_workflow(&record, &plan.expected_state_id) + .unwrap(); + record +} + +#[test] +#[cfg(unix)] +fn complete_existing_capture_preserves_all_versions_and_inventory_without_writes() { + for version in 1..=4 { + let directory = populated(version); + let before = fs::read(directory.store().path()).unwrap(); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + assert_eq!(capture.schema_version().unwrap(), version); + let counts = capture.inventory().unwrap(); + assert_eq!(counts.sources, 1); + assert_eq!(counts.reviews, u32::from(version >= 2)); + assert_eq!( + counts.capabilities, + if version >= 3 { + 3 + } else { + u32::from(version >= 2) + } + ); + assert_eq!( + counts.revisions, + if version >= 3 { + 3 + } else { + u32::from(version >= 2) + } + ); + assert_eq!(counts.recipes, u32::from(version >= 3)); + assert_eq!(counts.applications, u32::from(version >= 3)); + assert_eq!(counts.derivations, if version >= 3 { 2 } else { 0 }); + assert_eq!(counts.workflows, u32::from(version == 4)); + assert_eq!(counts.workflow_revisions, u32::from(version == 4)); + assert!(capture.archive().unwrap().starts_with(if version == 4 { + b"RANGOON-BACKUP-V3\n" + } else { + b"RANGOON-BACKUP-V2\n" + })); + assert_eq!( + capture.digest().unwrap(), + byte_digest(capture.archive().unwrap()) + ); + let decoded = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + assert_eq!(workflow_recovery::counts(&decoded.records), *counts); + assert_eq!( + encode(&decoded.records).unwrap(), + capture.archive().unwrap() + ); + directory + .store() + .revalidate_existing_capture(&mut capture) + .unwrap(); + assert_eq!(fs::read(directory.store().path()).unwrap(), before); + assert_eq!(fs::read_dir(&directory.0).unwrap().count(), 1); + } +} + +#[test] +#[cfg(unix)] +fn missing_zero_byte_and_valid_initialized_empty_are_distinct() { + let directory = TestDir::new(); + assert!(directory.store().capture_existing_snapshot().is_err()); + assert!(!directory.0.exists()); + // Preserve the older export's intentionally empty behavior. + assert!(directory.store().export_workflow_backup().is_ok()); + fs::create_dir(&directory.0).unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + fs::write(directory.store().path(), []).unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + assert_eq!(fs::metadata(directory.store().path()).unwrap().len(), 0); + let database = directory.db(); + database + .execute_batch("PRAGMA page_size=4096; VACUUM;") + .unwrap(); + drop(database); + let before = fs::read(directory.store().path()).unwrap(); + let capture = directory.store().capture_existing_snapshot().unwrap(); + assert_eq!(capture.schema_version().unwrap(), 0); + assert_eq!( + capture.inventory().unwrap(), + &WorkflowRecoveryCounts::default() + ); + assert!( + capture + .archive() + .unwrap() + .starts_with(b"RANGOON-BACKUP-V2\n") + ); + assert_eq!(fs::read(directory.store().path()).unwrap(), before); +} + +#[test] +#[cfg(unix)] +fn same_size_same_modified_time_logical_change_invalidates_capture() { + let directory = populated(2); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + let counts = capture.inventory().unwrap().clone(); + let before = fs::metadata(directory.store().path()).unwrap(); + let digest = capture.digest().unwrap().to_owned(); + directory + .db() + .execute("UPDATE snapshots SET saved_at_ms=saved_at_ms+1", []) + .unwrap(); + fs::File::open(directory.store().path()) + .unwrap() + .set_modified(before.modified().unwrap()) + .unwrap(); + assert_eq!( + fs::metadata(directory.store().path()).unwrap().len(), + before.len() + ); + let changed = directory.store().capture_existing_snapshot().unwrap(); + assert_eq!(changed.inventory().unwrap(), &counts); + assert_ne!(changed.digest().unwrap(), digest); + assert_eq!( + directory.store().revalidate_existing_capture(&mut capture), + Err(StoreError::WorkspaceChanged) + ); + assert!(capture.archive().is_err()); + assert!(capture.inventory().is_err()); +} + +#[test] +#[cfg(unix)] +fn review_composition_and_workflow_history_drift_cannot_reuse_capture() { + let directory = TestDir::new(); + let saved = source(&directory); + let capability = legacy(&directory, &saved); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + directory + .store() + .review_capability(&capability.id, &capability.latest_revision_id) + .unwrap(); + assert!( + directory + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); + assert!(capture.archive().is_err()); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + let preview = directory + .store() + .preview_composition(&fixture_request()) + .unwrap(); + directory.store().apply_composition(&preview, true).unwrap(); + assert!( + directory + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); + let root = append_workflow(&directory, None); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + append_workflow(&directory, Some(root.id())); + assert!( + directory + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); + assert!(capture.schema_version().is_err()); +} + +#[test] +#[cfg(unix)] +fn replacement_disappearance_and_cancel_clear_retained_plaintext() { + let directory = populated(1); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + let original = fs::read(directory.store().path()).unwrap(); + fs::rename(directory.store().path(), directory.0.join("old.sqlite")).unwrap(); + fs::write(directory.store().path(), &original).unwrap(); + assert!( + directory + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); + assert!(capture.archive().is_err()); + fs::remove_file(directory.0.join("old.sqlite")).unwrap(); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + fs::remove_file(directory.store().path()).unwrap(); + assert!( + directory + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); + assert!(capture.archive().is_err()); + fs::write(directory.store().path(), &original).unwrap(); + let mut capture = directory.store().capture_existing_snapshot().unwrap(); + capture.cancel(); + assert!(capture.archive().is_err()); + assert!( + directory + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); +} + +#[test] +#[cfg(unix)] +fn another_root_cannot_revalidate_or_reuse_capture() { + let original = populated(1); + let other = populated(1); + let mut capture = original.store().capture_existing_snapshot().unwrap(); + assert!( + other + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); + assert!(capture.archive().is_err()); + assert!( + original + .store() + .revalidate_existing_capture(&mut capture) + .is_err() + ); +} + +#[test] +#[cfg(unix)] +fn mid_capture_source_substitution_or_removal_returns_no_snapshot() { + for remove in [false, true] { + let directory = populated(1); + let path = directory.store().path(); + CAPTURE_PROBE.with(|probe| { + *probe.borrow_mut() = Some(Box::new(move || { + let bytes = fs::read(&path).unwrap(); + fs::remove_file(&path).unwrap(); + if !remove { + fs::write(&path, bytes).unwrap(); + } + })) + }); + assert!(directory.store().capture_existing_snapshot().is_err()); + } +} + +#[test] +#[cfg(unix)] +fn sidecars_wal_busy_corrupt_and_over_capacity_are_refused_without_repair() { + for suffix in ["-journal", "-wal", "-shm"] { + let directory = populated(1); + let path = directory.0.join(format!("workspace.sqlite3{suffix}")); + fs::write(&path, b"untrusted sidecar").unwrap(); + let before = fs::read(directory.store().path()).unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + assert_eq!(fs::read(directory.store().path()).unwrap(), before); + assert_eq!(fs::read(path).unwrap(), b"untrusted sidecar"); + } + let directory = populated(1); + let database = directory.db(); + database.execute_batch("BEGIN EXCLUSIVE").unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + database.execute_batch("ROLLBACK").unwrap(); + database.pragma_update(None, "journal_mode", "WAL").unwrap(); + let before = fs::read(directory.store().path()).unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + assert_eq!(fs::read(directory.store().path()).unwrap(), before); + drop(database); + let directory = populated(1); + fs::write(directory.store().path(), b"not SQLite").unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + assert_eq!(fs::read(directory.store().path()).unwrap(), b"not SQLite"); + fs::OpenOptions::new() + .write(true) + .open(directory.store().path()) + .unwrap() + .set_len(MAX_DATABASE_BYTES + 1) + .unwrap(); + assert!(matches!( + directory.store().capture_existing_snapshot(), + Err(StoreError::Full) + )); +} + +#[test] +#[cfg(unix)] +fn links_and_denied_directory_do_not_become_empty_or_valid_capture() { + use std::os::unix::fs::{PermissionsExt, symlink}; + let directory = populated(1); + let alias = TestDir::new(); + symlink(&directory.0, &alias.0).unwrap(); + assert!(alias.store().capture_existing_snapshot().is_err()); + fs::remove_file(&alias.0).unwrap(); + let before = fs::read(directory.store().path()).unwrap(); + let outside = TestDir::new(); + fs::create_dir(&outside.0).unwrap(); + let linked = outside.0.join("linked.sqlite"); + fs::hard_link(directory.store().path(), &linked).unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + fs::remove_file(linked).unwrap(); + let permissions = fs::metadata(&directory.0).unwrap().permissions(); + fs::set_permissions(&directory.0, fs::Permissions::from_mode(0o000)).unwrap(); + let denied = directory.store().capture_existing_snapshot(); + fs::set_permissions(&directory.0, permissions).unwrap(); + // A root test runner does not establish an access-denial case. + use std::os::unix::fs::MetadataExt; + if fs::metadata(&directory.0).unwrap().uid() != 0 { + assert!(denied.is_err()); + } + assert_eq!(fs::read(directory.store().path()).unwrap(), before); +} + +#[test] +#[cfg(unix)] +fn capture_and_backup_debug_are_fixed_redactions() { + let directory = TestDir::new(); + let report = analyze("AGENTS.md", b"# E1C5A_PRIVATE_MARKER\nNever print me.\n").unwrap(); + directory.store().save(&report).unwrap(); + let capture = directory.store().capture_existing_snapshot().unwrap(); + let backup = WorkspaceBackup::decode(capture.archive().unwrap()).unwrap(); + assert_eq!( + format!("{capture:?}"), + "ExistingWorkspaceCapture()" + ); + assert_eq!(format!("{backup:?}"), "WorkspaceBackup()"); + assert!(!format!("{capture:?}{backup:?}").contains("E1C5A_PRIVATE_MARKER")); +} + +#[test] +#[cfg(unix)] +fn unsupported_schema_and_excess_records_do_not_produce_partial_capture() { + let directory = populated(1); + directory + .db() + .pragma_update(None, "user_version", 99) + .unwrap(); + let before = fs::read(directory.store().path()).unwrap(); + assert!(matches!( + directory.store().capture_existing_snapshot(), + Err(StoreError::UnsupportedSchema) + )); + assert_eq!(fs::read(directory.store().path()).unwrap(), before); + let directory = populated(1); + let database = directory.db(); + for index in 0..MAX_SNAPSHOTS { + let report = analyze("AGENTS.md", format!("# Synthetic {index}\n").as_bytes()).unwrap(); + database + .execute( + "INSERT INTO snapshots VALUES (?1,?2,?3,?4,1)", + params![ + report.source.id, + report.source.display_name, + report.source.sha256, + report.source.content.as_bytes() + ], + ) + .unwrap(); + } + drop(database); + let before = fs::read(directory.store().path()).unwrap(); + assert!(directory.store().capture_existing_snapshot().is_err()); + assert_eq!(fs::read(directory.store().path()).unwrap(), before); + assert_eq!(fs::read_dir(&directory.0).unwrap().count(), 1); +} + +#[test] +#[cfg(not(unix))] +fn existing_capture_refuses_without_supported_file_identity() { + assert!(matches!( + TestDir::new().store().capture_existing_snapshot(), + Err(StoreError::Unavailable) + )); +} diff --git a/docs/application-architecture.md b/docs/application-architecture.md index 02e5dfa..5f971d3 100644 --- a/docs/application-architecture.md +++ b/docs/application-architecture.md @@ -4,6 +4,28 @@ Authority: [intent.md](intent.md), October 5 engine architecture and October 7 p Owner: Jeff. Architecture, trust boundaries, schema, integration and release decisions remain with the primary controller. Validation/publication state belongs in [development.md](development.md). +## Internal operations-first boundary — October 22, 2026 + +The [accepted internal-first direction](intent.md#internal-operations-first-direction--october-22-2026) prioritizes Hypler's own supervised workloads over speculative integration breadth or a funding narrative. It extends the existing operations/fleet and deployment designs below; it does not replace the local capability workbench or create a second control plane. + +Jeff's Customer Zero clarification preserves the general product: the same public contracts must work for another operator's projects, workers and providers through private configuration. The [source reconciliation](customer-zero-gap-analysis.md) distinguishes current content/model/inspection components from missing durable task service, runtime execution, MCP, worker and accounting functions. Its proposed distributed source-review pilot refines the next value milestone; the prior finite-read connector work remains independently useful without becoming a mandatory runtime or authorization dependency. A durable task must outlive its initiating Codex/desktop client, while actual scheduling and process isolation remain with a qualified runtime. + +| Layer | Responsibility and boundary | +| --- | --- | +| Rangoon workbench and application services | Existing capability authoring/provenance/compilation, plus planned fleet supervision, typed task coordination, model-routing preferences, budget accounting and operator evidence. The same services should serve UI, eventual CLI and authenticated hosted APIs; the renderer owns no authority or database access. | +| Runtime, scheduler and monitoring adapters | Translate an explicitly supported operation to an established runtime's native interface. That runtime owns process placement, isolation and lifecycle; monitoring sources own their observations. A Rangoon placement recommendation is not a scheduler allocation, and a task acknowledgement is not a completed effect. | +| Independent authority integrations | LNSAT and alternative qualified engines retain their own authorization, approval, credential and evidence semantics. An unavailable required control blocks the affected operation, while unrelated local work remains available. OpenShell and LNSAT need not depend on each other. | +| Independent VUSL consumer | Future adoption of a pinned usable VUSL core preserves native identity, provenance, explicit uncertainty and translation loss. Rangoon does not maintain a competing VUSL specification or infer authority from semantic compatibility. | +| Managed application interfaces | IZIOS, Sugarberry and other portfolio systems may later expose versioned, allowlisted health/readback and narrowly scoped operational functions. These are candidates, not connected systems. No generic shell, shared application database or inferred production permission is introduced. | + +The proposed orchestration core is an application-service responsibility within the modular architecture, not a mandate for a new daemon or microservice. Reuse the [shared management-state and deployment design](#deployment-tiers-and-distribution) and existing [fleet console](operations-control-plane.md#fleet-management-console-direction). A later server may own durable jobs, leases, outbox, scoped enrollment and task checkpoints; external runtimes still own actual scheduling. Do not build a competing scheduler or copy a desktop SQLite file across hosts. Neither LNSAT's nor VUSL's database becomes Rangoon's shared state. + +Model routing and cost control need explicit resource/privacy requirements and provider-specific capabilities. Keep estimated, reserved, observed and finalized usage distinct; missing usage is unknown, not free. Concurrent admission, retries, reservation settlement, cancellation and late provider charges need a reviewed accounting contract before a hard budget limit is claimed. Local CPU/GPU time, memory, energy estimates and external API charges have different measurement bases. No model or tool can expand its own budget or authority. + +Proxmox, Nomad and other established infrastructure products are integration candidates, not a required combined stack or current compatibility claim. Select a product/version, supported OS/backend, license and exact operation only when a pilot needs it. The supplied hardware list is not an authenticated inventory; older GPU acceleration and usable capacity require measurement. Keep production hosting outside the experimental worker pool and establish network, identity and resource isolation before enrollment. No inventory scan, provider installation, runtime activation or production access is authorized by this architecture. + +The user interface stays layered: searchable inventory/table first, compact task/status bar, then a selected-system inspector; topology remains an alternate view. Show source, freshness, unsupported operations and unknown outcomes at the point of action. Fleet, Tasks, Deployments and Evidence reuse the existing Operations group; budgets appear with their task/project scope rather than as decorative totals. The next delivery sequence is in the [canonical plan](plan.md#internal-operations-first-delivery--october-22-2026). + ## Purpose and first useful outcome Rangoon should turn scattered agent instructions into understandable, reusable capabilities, then make the change from an idea to a deployed or executed action inspectable. Its first useful promise is: **know what an agent is configured to do, where those instructions came from, and what a proposed change will preserve or lose.** That is valuable without a running LNSAT engine, a model account or a cloud subscription. @@ -210,6 +232,88 @@ Multiple LNSAT instances are separate registered authority endpoints unless LNSA Do not confuse Rangoon's shared management storage with LNSAT's authority store. Independent LNSAT nodes keep independent native stores. A future one-service LNSAT cluster might need shared transactional authority state or a qualified consensus design, but that choice belongs to LNSAT and cannot be achieved by pointing today's single-node SQLite daemons at one file. Its design must cover serializable one-time consumption, session/approval/policy/revocation propagation, key custody, leader/fence behavior, crash and partition recovery, exact receipt identity and non-retry of unknown effects. Rangoon records the proven topology and compatibility; it cannot supply these engine invariants from its own database. +### Remote setup and agent-file management — October 26, 2026 + +Jeff's [accepted remote-management direction](intent.md#remote-setup-management-direction--october-26-2026) extends the existing fleet/deployment design to the everyday file workbench. This is a required product capability with staged implementation, not a statement that remote management works today. Preserve useful local operation and the Customer Zero decision to reuse qualified external runtimes rather than build another scheduler. + +**Ownership and topology.** Rangoon owns inventory, source/revision inspection, reviewed configuration and artifact plans, routing and evidence display. A target's runtime owns process execution; a target management adapter owns its admitted filesystem/management operations and readback. An optional authority engine owns its own authorization/evidence semantics. Use Rangoon-to-Rangoon connections for shared agent files: one controlling installation connects to other explicitly enrolled Rangoon installations. Each sharing installation owns a restricted host service over the same application/repository contracts as local use. A later headless Rangoon installation may expose that same service without a GUI; it is a deployment mode of Rangoon, not a second bridge product. Third-party APIs remain separate optional system adapters, not the default access path to Rangoon-shared files. The sharing service is not a generic remote-access agent, engine or scheduler. A future always-on Rangoon service may own durable coordination when desktop disconnect must not stop supervision; reuse the existing service/repository ports and shared-state design. Neither the peer-sharing host service nor always-on coordinator exists in current source. + +**Peer sharing model.** The owner of installation B enables Share files, selects registered folders/workspaces and the exact metadata/content operations permitted, reviews installation A's authenticated identity and acting user/service identity, and grants bounded access. Installation A then adds B under Systems and browses only B's granted roots. Sharing is off by default; pairing alone grants no file scope. B enforces every request using its own registered-root resolution, current grant, principal, session and lifecycle state. Renderer selections or A's local administrator status cannot broaden B's scope. Expose a narrowly authenticated application API, never raw Tauri commands, arbitrary paths, a database/key endpoint or general remote shell. Client-side hiding is not enforcement. + +Separate peer-machine authentication from user/service authorization; require both identities and a grant bound to the selected host/root/operation. The sharing installation validates the acting principal under its own trust policy; a caller-supplied username, role or actor label is not authentication. Each installation keeps its own encrypted workspace and local keys. Share file records through the service rather than sharing database files or copying database keys to peers. Reading selected source bytes is a distinct grant from listing names/metadata; edit, restore and execution require separately qualified grants and native operations. No permission is transitive: A's access to B grants nothing on C, and B cannot delegate C's access by claiming a relationship. Product forwarding of another host's content needs separate explicit transfer consent; a compromised authorized reader can still copy plaintext already disclosed to it. + +Grant expiry/revocation, host sharing disabled, workspace lock and changed peer/root identity close new admissions and fence late results. Default sharing does not reuse a locked GUI's prior unlocked state. An unattended/headless mode needs its own accepted service identity, credential/key custody, permitted content scope and recovery/lifecycle policy; do not silently keep reads alive through desktop lock. Already-disclosed content cannot be recalled by revocation, and cached copies remain subject to the receiving installation's explicit encrypted retention/deletion policy. Peer identifiers, display names and network addresses remain distinct; copied backups or duplicate installation identity need conflict detection/re-enrollment rather than inherited trust. These are proposed source requirements, not implemented sharing behavior. + +**Installation and enrollment.** Peer metadata and content require an authenticated encrypted transport with verified peer identity; refuse plaintext, silent downgrade and certificate/key verification bypass. Initial onboarding is explicit and operator-initiated for one host: review the exact endpoint and authenticated host identity, adapter/product/version and allowed roots/operations, then complete a separately qualified enrollment flow. Do not auto-accept an address, discovered name, changed host key/certificate or reverse-DNS identity. Duplicate enrollment with a different host identity needs review; an endpoint/name can change without becoming a new target or inheriting another target's history. A later pairing design needs short-lived single-use material, per-device identity and scoped credential custody, rotation/revocation and no secrets in renderer/logs/URLs. This direction chooses no credential backend or new wire protocol. No ambient SSH agent, key files, environment tokens, proxy configuration, provider profile or network scanning. Optional existing SSH transport must be explicitly selected/pinned and constrained to the reviewed helper/protocol; it never opens a general shell or turns shell output into a trustworthy filesystem API. It is not the first implemented transport by default. + +**Allowed data and operations.** Reuse the R9 adapter/version/capability descriptor design and the future BF-2 selected-root application port. These operation names describe use cases, not a released API/schema: + +| Operation | Scope and result | Required refusal/limitation | +| --- | --- | --- | +| List registered roots and file metadata | Host-scoped opaque root IDs, cursor-paged allowed relative names, supported file type, size and observed timestamps; optional digest only when actually computed | No arbitrary path, parent escape, symlink/reparse escape, home/network scan, secrets outside selected roots or unbounded directory expansion. Metadata transfer also needs scope/consent. | +| Inspect one source | Explicit selected host/root/file reference, bounded original bytes, native analysis provenance and exact digest | No provider upload, remote command execution, hidden bulk download or save. Preserve BF-1 per-file limits until a reviewed contract changes them. Validate again at the remote read boundary; a stale metadata token is not file custody. | +| Inspect revision/history | Exact host/registered-root/target binding, ordered recorded changes and events, source spans/inputs, before/after hashes, originating and receiving timestamps | No filename-based ancestry or cross-host conflation. Remote self-report is labeled; authenticated transport alone does not prove truthful or complete history. | +| Prepare/apply/restore | Later target-specific retained plan, expected prior digest/revision, encrypted restore point, explicit scoped authorization, durable job/outcome and effective readback | Unavailable until remote target custody, concurrency/replay/revocation, encrypted recovery and unknown-outcome reconciliation qualify. UI approval and provider allow alone never authorize the write. | +| Inspect runtime/configuration | Only each adapter's qualified read subset; configured, installed and effective state remain separate | A reachable host is not a managed runtime. Task execution, restart, upgrade, deployment and secret/key management remain separately qualified capabilities. | + +A bridge must independently enforce its root/operation scope using the host OS's verified boundary; it cannot trust renderer-supplied absolute paths or imported instructions. Deny traversal, ambiguous encodings, unsupported file kinds, oversized reports, archive expansion and stale/changed root identity. Listing returns bounded metadata rather than retaining every original in the renderer. Cancellation stops admission of subsequent reads and drains admitted work; disconnect/session-generation fencing prevents late results repopulating a locked or reconnected view. No arbitrary plugin code or provider-returned HTML executes in the desktop. + +**Privacy, storage and revision provenance.** Source content may move from the chosen host into Rangoon memory only for explicit inspection; saving it needs a separate explicit encrypted-workspace action. Connection approval must show destination, selected roots, operation, metadata/content sent and returned, retention and egress. A granted metadata scope is not consent for source text, mutation or a model call. Cache only permitted records in encrypted application storage with scoped identity, expiry/retention/deletion and recovery; the persistent inventory/cache schema is not implemented. Do not use the 128 archived snapshots as a fleet index or silently raise their bound. Reuse existing encrypted history through a host/root/target binding and repository port; any schema extension needs migration and complete backup/restore tests. Never network-share or synchronize a live SQLite file. Engine stores and keys remain independent. Encryption cannot protect data from a fully compromised unlocked host; minimize exposure and rely on separately qualified runtime/OS confinement. + +Keep remote observed time, Rangoon received time, local saved time and successful check time distinct. Filesystem mtime is observed metadata, not proof of freshness, authenticity or parentage. Preserve clock-skew/unavailable-time markers, content hashes, the source's native revision and local record identity separately. A transport epoch/freshness label cannot conceal producer resets or history gaps. Cache/offline observations show their timestamp and stale/unknown status; reconnect does not erase gaps or convert an earlier requested write into confirmed state. + +**Security and error boundary.** Separate transport/session state (`unconfigured`, `disconnected`, `connecting`, `connected`, `identity_changed`, `revoked`, `error`) from each operation's supported/unsupported/unassessed coverage, synchronization freshness and task outcomes. A connected host may have no file or write permission. Use structured bounded codes and safe human messages for identity mismatch, scope denial, unsupported version/operation, unavailable root, stale reference, conflict, timeout/cancellation, capacity and uncertain outcome. No diagnostic includes credentials or original content by default. Failed checks do not weaken peer identity or silently fall back to another host/transport. Writes remain pinned to one exact target/attempt; a lost response pauses for reconciliation, not automatic retry. Local work continues during remote failures. + +**Staging and source evidence.** Current BF-1 `select_and_inspect_sources` in `apps/desktop/src/source_collection.rs` accepts only a native local picker; `crates/rangoon-host/src/source_collection.rs` is a local bounded reader, not remote transport. Existing saved-source reads are local workspace operations. The I1 integration crate provides offline metadata/evidence inspection, not a remote file API. OpenShell finite-read Host/client work is product-specific and does not authorize generic file management; neither it nor a logo supplies a running bridge. Existing AR-1/AR-2 history is encrypted store source, not mounted target-write or remote history UI. + +| Stage | Useful deliverable | Gate and relationship to existing work | +| --- | --- | --- | +| RM-0 direction (this record) | Reconcile remote agent-file management with fleet inventory, history and SDK architecture | Documentation only; no source, connection or installation. Local native qualification stays on its release path. | +| RM-1 offline remote inventory contract | Typed installation/principal/grant/root/file identity, paged metadata, separate reported metadata consent, freshness/provenance and honest states with hostile fixtures | RM-1 source implemented below; unmounted offline contract only. Reuse the BF-2 application-port design and R9 descriptor vocabulary; no public protocol or remote backend. | +| RM-2 two read-only lab installations | One controlling Rangoon installation and one sharing Rangoon installation, authenticated enrollment and explicitly consented bounded inventory/content read | Freeze peer transport, machine plus actor identity, grants/credential custody and root-confined host-service implementation first. Use one disposable lab endpoint; prove actual OS/transport scope and cancellation/refusal. No auto-connect, normal source or remote writes. | +| RM-3 reviewed remote file changes | Draft/diff, exact encrypted restore point, target-pinned apply/restore and recorded reconciliation | Reuse AR-3 retained previews/custody and existing S3 staged deployment semantics. Prove crash/partition, drift, replay, lease/fence, partial batch, wrong-host and unknown-response behavior before any real instruction file. | +| RM-4 durable multi-host operations | Multi-host inventory, scoped task supervision and controlled rollout views | Reuse the Customer Zero runtime-adapter direction plus S1–S3 service/shared-state plans only when the workload needs durable background coordination. No parallel scheduler or mandatory cluster for one remote host. | + +**RM-1 internal offline contract — October 27, 2026.** Jeff's request to implement the direction accepts the [seven-path source packet](intent.md#rm-1-offline-inventory-implementation--october-27-2026). Root owns the new `preview/remote-inventory-model.mjs`, `tests/remote-inventory-model.test.mjs`, `tests/fixtures/remote-inventory.v1.json` plus this architecture, intent, continue and development records. It is an unmounted, in-memory metadata reader; no filesystem, native command, service, credential, transport, cache or UI connection is mounted. The internal `rangoon.remote-inventory.offline.v1` name is neither a public wire protocol nor a VUSL replacement. It reuses R9's adapter/product/version/operation vocabulary and the BF-2 root/reference direction without claiming runtime interoperability. + +The model accepts bounded JSON text for one reported scope: pinned adapter ID/product/version and operation list; exact installation ID/enrollment epoch, principal, grant and root; session and snapshot IDs; separate grant operation scope, metadata consent identity/operation and grant/consent deadlines. These fields are unverified producer assertions. Their structural agreement never authenticates a host/user, validates a real grant, proves consent, or grants access. `inventory.metadata` is the only implemented operation, even if another operation appears in reported capabilities. Source-content inspection remains a separate unimplemented operation/consent boundary. A successful scope replacement clears prior records; invalid replacement preserves the previous scope. + +`beginPage` returns an instance-bound request with local generation/serial and exact scope/snapshot/cursor. `acceptPage` consumes only that exact request object, requires matching report adapter pin, access scope/deadlines, identity and expected cursor, and atomically validates every row before adding any. A rejected current response consumes that attempt but preserves accepted pages; a new attempt uses a new serial. Stale/foreign request objects cannot consume a pending current request. Cursor replay/self-loops and changes in reported snapshot coverage fail. Installation/session/snapshot replacement fences prior callbacks; copied installation identities cannot be detected or authenticated by this offline reader and remain an enrollment-layer requirement. + +Limits: 128 KiB UTF-8 per descriptor/page, maximum JSON depth 16, 50 entries/page, 1000 records and 64 accepted pages per working view, including empty pages. Duplicate JSON keys (including escaped aliases), unknown fields at each object, role/trust assertions, source-text payload fields, duplicate file IDs/paths, invalid numbers and nonconforming digests are rejected. A cap is a bounded desktop inspection window, not a fleet-storage limit. Backend indexing/paging remains separate; do not raise encrypted source-archive caps or hold a million originals in the renderer. + +File rows carry an opaque file ID, relative Markdown path, byte length, optional observed mtime, optional lowercase SHA-256 and optional native revision ID. None establishes ancestry, integrity against a malicious producer or a restorable original. Paths use `/`, end in `.md` case-insensitively, have at most 1024 UTF-16 units and 255 units/segment, and reject empty/dot/parent segments, absolute/drive/UNC forms, backslashes, percent/colon/query/fragment syntax, controls/format characters/unpaired surrogates, trailing dot/space, reserved device names and `.git`/`.ssh`/`.aws`/`node_modules` segments. `.claude`/`.cursor` and Unicode names remain possible. Preserve exact case and Unicode sequence; do not normalize names into filesystem identity. This grammar validates report data only; native resolution must separately enforce actual roots, symlinks/reparse points, file kinds and platform alias behavior. No path reaches a filesystem API here. + +Producer-observed, locally received and file-modified times remain separate. Page freshness is `unknown`, `clock_skew`, `stale` or `recent_report` (never live/verified); receiver age expires after five minutes independently of producer time, and any producer time ahead of its receipt or current local time is flagged. A backwards/invalid local clock clears scope; reported grant/consent expiry clears retained metadata at admission, result acceptance or state inspection. There is no timer or background task in this model, and these reported deadlines are not authorization leases. `reportedCoverage` is complete/partial/unknown, stable within the snapshot. `window` independently records not_started/partial/capacity/complete: reaching a terminal cursor completes pagination only, even when reported coverage is partial or unknown. Host completeness, missing events and truthful observations still require independent evidence. + +Lock, disconnect, revocation, identity change and cancellation clear scope, records, pages, cursors and pending work; late results cannot revive the view. Dispose is terminal. The only mode is `offline_unverified`; no connection/authentication/approval/execution outcome is synthesized. Public state is copied defensively. Fixed structured diagnostics do not echo report/source content. No persistence or native content API is added. + +Validators: `node --test tests/remote-inventory-model.test.mjs`, `npm run build:check`, `node scripts/validate-review.mjs`, the intent artifact validator, exact owned-delta whitespace/hash preservation, finite working-window measurement and fresh independent read-only review. The [development receipt](development.md#rm-1-offline-inventory-contract--october-27-2026) records actual results. Fixture validation does not prove peer authentication, OS confinement, consent presentation, encrypted caching or remote revision/restore behavior. + +**BF-2a retained-root source — October 27, 2026.** The host crate now implements unmounted Unix metadata traversal in `source_inventory.rs`, using the already locked/cached `rustix =1.1.5` safe filesystem API. `rangoon-host` retains `#![forbid(unsafe_code)]`. This direct dependency edge and fs feature are new; no package version/checksum changes or downloads occur. The pinned crate has the existing Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT license expression; dependency checksum/lock evidence is in the development receipt, not a security certification. + +A caller must supply a fresh native-selected absolute root, never renderer paths. The backend walks from `/` with retained directory descriptors, `statat(SYMLINK_NOFOLLOW)`, `openat(DIRECTORY|NOFOLLOW|NONBLOCK|CLOEXEC)` and pre/post device/inode checks. It refuses root `/`, relative/parent paths, symlink ancestors/final roots and excessive root-component depth. Root ownership means the opened directory object: renaming its pathname and replacing that pathname with a symlink does not redirect the existing owner. There is no canonicalization, `/proc` reopening or path-string containment test in production. This is an unmounted host API, not enforcement that a frontend request came from a picker. + +Enumeration stays relative to owned directory handles. Only directories are opened; regular/special files receive no-follow metadata inspection only. Child identity is checked after opening; cross-device/repeated directories and detected replacements are refused and reported. Same-device mount aliases and a compromised kernel/privileged host are not isolated by this API; tests use no real mounts. Metadata may change immediately and directory iteration is not an atomic snapshot. Previously returned pages remain copies held by callers; a later native admission/renderer owner must purge/fence those copies on lock or revocation. + +Pages return at most 50 rows after at most 512 visited entries; a session stops at 10,000 visited entries or 1000 emitted rows, with depth at most 16 below the chosen root. Directory handles are bounded by traversal depth and identity/path sets by the session budgets. Exact relative Markdown names, byte lengths, whole-second filesystem mtime in milliseconds and session-local observation ordinals are returned. Ordinals are neither durable file references nor revision ancestry. There is no file content, hash, native absolute path, device/inode, key or original in serialized rows. Reading a selected row later still needs retained native content custody; a display path must never become an arbitrary read endpoint. + +The initial discovery policy excludes dot entries other than `.claude`, `.cursor`, `.windsurf`, `.github`, `.codex`, `.agents`, plus `node_modules`, `target`, `vendor`, `dist` and `build`. It rejects invalid UTF-8 names, unsafe separators/control/format/reserved names, overlong segments/paths and non-ASCII characters outside the initial alphanumeric subset. Unicode sequences are never normalized; this backend is deliberately narrower than RM-1's offline path grammar, and unsupported names produce an explicit partial reason. Other file types, symlinks and special files are excluded without reading them. Future configurable ignore rules need a reviewed policy contract, not ambient shell/git execution. + +`exhausted` means traversal stopped, not complete coverage: cumulative partial reasons separately retain read/replacement/device/loop/name/depth/entry/record problems. Work-limited short/empty pages remain resumable. Duplicate relative observations are refused. Cancellation before/through/after a page drops traversal handles and discards the whole current page; explicit close is terminal. The current callback can stop subsequent work, but cannot promise interruption of a blocked kernel call or a hard elapsed-time limit, especially on a selected network filesystem. + +BF-2a changes no Tauri command, picker, IPC capability, renderer screen, database, source archive, engine or network service. Unix source now has pinned Rust 1.99.1 disposable macOS x86_64 test evidence through BF-2b; Windows explicitly returns `unsupported_platform` without fallback. BF-2a originally closed with required Rust 1.99.1 unavailable; its 1.98.0 diagnostics used `--ignore-rust-version` and never satisfied that gate. BF-2b installs the exact official 1.99.1 x86_64 Apple toolchain and passes formatting, 705 portable workspace tests and warnings-denied Clippy over unchanged source with the pinned validator; the [qualification receipt](development.md#bf-2b-pinned-toolchain-qualification--october-27-2026) owns current results. Linux/Windows source/GUI and OS custody qualification remain open. Fixed `/usr/bin/mkfifo` is a macOS test-fixture prerequisite, not production behavior; APFS cannot create the non-UTF-8 filename fixture, which is Linux-only. See [BF-2a evidence](development.md#bf-2a-retained-root-inventory-backend--october-27-2026). + +**BF-2c native folder metadata workbench — October 27, 2026.** `select_and_list_sources` now opens a fresh native folder picker through existing SourceAccess exclusive admission, then runs BF-2a traversal in a blocking worker. The renderer passes no path, limits or observation reference. Workspace generation is checked before selection/opening, through every page and at final delivery. Root handles are explicitly closed before constructing the success or budget-failure result; read-only completion retains callback counting and discards stale results. The command never changes native source-analysis selection or writes a source/database. Windows reports unsupported before displaying a folder picker. + +`rangoon.folder-collection.v1` returns one transient window: root display label, at most 1000 relative Markdown metadata rows, cumulative visited/excluded counts, traversal-exhausted flag and bounded partial reasons. No absolute root, source ID, hash, content, native handle, device/inode, cursor or durable revision reference is serialized. Each observation ordinal is session-local; the renderer replaces it with its own selection serial/row key. A conservative JSON upper bound rejects windows over 2 MiB before IPC, while the renderer independently checks actual UTF-8 JSON size and exact fields/types/path grammar/counters/ordinals. Record/entry-limit reasons must agree with their counters. Oversized or malformed replacements preserve the previous accepted window. Native mtime is nullable whole-second observed filesystem time, not authenticity, freshness or ancestry. + +Agent files now merges folder-origin metadata rows with saved/explicitly selected records in its existing library/inspector hierarchy. New folder observations appear first; one folder window replaces only prior folder rows. Search includes relative paths; paging renders 50 rows without native calls. Metadata gets a separate count and filter, not an actionable unchecked or checked verdict. Folder rows cannot be bulk-marked/checked or opened through saved-source commands. Their inspector offers **Choose files to inspect**, which opens the existing explicit native multi-file picker; no filename/digest match silently links those newly chosen contents to a folder observation. Clear folder removes only these memory records. Saved refresh and individual-file selection retain folder context. Cancel/failure preserves prior state; Lock/dispose purge metadata and fence late callbacks. Ordinary unlocked navigation retains workspace context; it does not keep root capabilities alive. + +This mounts metadata discovery only. Native folder-picker GUI, current-artifact encrypted lifecycle and Linux/Windows qualification remain open. The [BF-2c receipt](development.md#bf-2c-native-folder-metadata-workbench--october-27-2026) records source tests, synthetic browser evidence and the canonical disposable-test-root correction, without changing production storage/encryption or no-follow behavior. No persistent index/tag store, remote service, copy/apply/restore, hash-backed external revision chain or authority grant is added. + +**Next gates:** qualify this exact native picker/Lock flow using a fresh isolated disposable artifact before personal folders, then add retained, target-bound native row-inspection custody. A relative display path or observation ordinal must never become a generic read endpoint. After those gates, qualify two disposable installations with authenticated transport, machine plus actor identity, grants, explicit sharing and encrypted retention. Reviewed copy/apply/restore and durable multi-host rollout remain RM-3/RM-4; metadata discovery qualifies none of those effects. + ### Deployment management as a control-plane workflow Separate three deployment objects: a Rangoon service version, a compiled capability/artifact revision sent to a target harness, and an authority-engine configuration revision. One successful deployment does not establish the other two. A proposed managed target has an enrolled identity, owner, environment, adapter/product/version pin, allowed operation subset, current observed/effective revision, health and rollback capability. An imported or qualified discovery result creates only an unverified review candidate, not registered inventory or deployment permission. Active discovery requires explicit consent, an allowlisted destination and scope, bounded rate and egress, recorded provenance and a separately qualified adapter; authenticated enrollment and operator review precede managed status. @@ -278,26 +382,31 @@ Research-worthy proof should measure semantic preservation across target formats ## Native encryption adoption boundary -[E1](encrypted-workspace.md) separates the optional keyed store and identity-bound native Owner from production mounting. The SourceAccess dispatcher and Gate now cover the ordinary native command families; all 45 ordinary commands use native-issued generation admission. Native close drains counted callbacks before key release, and the renderer has a global purge/acknowledgment path. Source-free protection controls expose explicit setup/unlock orchestration without reading content while closed. These are source and fixture-qualified prerequisites, not an encrypted desktop release. Production still constructs Legacy plaintext storage; Managed construction remains test-only. A disposable Managed factory, actual OS dialog/reload/failure paths, durable recovery and three-OS GUI/vault qualification remain before adoption. An encrypted database will not retroactively encrypt explicit plaintext exports. Gate quiescence, content review, model advice, provider decisions and execution authority remain different facts. The [development ledger](development.md) owns dated validation and adoption status. +Ordinary desktop source enables `encrypted-workspace` by default. `workspace_native_bootstrap::install_workbench_state` installs deferred Managed services under the native OS app-local anchor; absent backend/anchor stays unavailable. `workspace_startup` separates `managed-workspace` from the older `source-workspace` location and requires explicit setup, unlock or verified Legacy copy. It does not automatically fall back to plaintext or migrate existing files. The portable store feature remains optional for other callers, and Legacy source remains for explicit compatibility/regression paths. +SourceAccess and Gate bind ordinary operations to native-issued generation admission. Close drains actual callback custody before Owner/key release and requires the matching renderer purge acknowledgment before a completed UI Lock claim. Source-free setup/protection controls use the same lifecycle boundary. Native mounting is implemented; dated disposable macOS receipts are narrower than qualification of the current artifact, normal profile or all desktop platforms. Windows startup and encrypted key-file recovery are currently unsupported; Linux GUI/custody and package qualification remain open. [E1 contract](encrypted-workspace.md), [E1d-2 recovery](encrypted-workspace.md#e1d-2-native-sqlcipher-recovery-copy--october-25-2026) and the [development ledger](development.md) own the precise mechanics and evidence. ### Retained-state audit for lock adoption -| Surface and source | Implemented custody | Remaining adoption proof | +| Surface and source | Implemented custody | Remaining qualification | | --- | --- | --- | -| Native source, composition, workflow, data-control and compilation services | Shared dispatcher, generation admission and retained callback custody cover their ordinary commands; close drains before Owner/key release | Exercise actual Managed factory, picker/write failure, restart and OS-specific callbacks with disposable data | -| Native local/cloud model and credential services | Consent, cancellation and callback custody join the same close protocol; late results are fenced | Qualify real OS prompts, transport cancellation and uncertain write/outcome recovery without assuming cancellation undoes an effect | -| Renderer controllers and DOM | Global lock purge invalidates retained content and request generations before acknowledgment; source-free controls are separate | Qualify actual packaged GUI, reload and failure-driven close on macOS, Windows and Linux, including focus and accessibility | -| Explicit file exports and backups | Exported files are separate artifacts, outside database key custody | Disclose plaintext outputs; qualify encrypted archives and retention separately before claiming protected backup coverage | - -Native callback quiescence must precede final Owner key/handle release. Cancel alone cannot prove that a blocking OS prompt closed, a provider stopped or a filesystem write did not commit. Renderer/native purge removes retained application references and visible content; it cannot establish secure erasure of allocator, browser/parser, SQLite or OS copies. Source/fixture routing coverage does not prove the real Managed factory, platform vault or interrupted-operation recovery. Rangoon content review, provider authorization, cleanup readiness and execution outcomes keep separate provenance and authority. +| Source, composition, workflow, data-control and compilation services | Managed dispatcher, generation admission and retained callbacks; close drains before Owner/key release | Current-artifact picker/write failure, restart, recovery and platform-specific callback proof | +| Local/cloud model and credential services | Explicit consent, cancellation and callback custody; late results fenced | Applicable real OS prompt and transport behavior; cancellation must not imply that an effect was undone | +| Renderer controllers and DOM | Global lock purge invalidates retained content/generations; source-free controls remain separate | Current rendered interaction, packaged GUI, focus/accessibility and OS-specific lifecycle checks | +| Encrypted recovery | Canonical SQLCipher image, separately selected key, verified output reread, retained exact restore plan; selected disposable macOS evidence | Current artifact, normal-data adoption, Windows implementation and Linux/Windows qualification | +| Readable instruction exports and original files | Explicit selected output/input; outside workspace/recovery key custody | Honest disclosure and target-specific handling; no claim that database encryption protects delivered content | +Cancel is not callback quiescence, successful rollback or secure memory erasure. Application purge removes retained references and visible content; it does not prove erasure from allocator, browser/parser, SQLite or OS copies. Content review, provider authorization, cleanup readiness and execution outcomes keep separate provenance and authority. ### Installation and management adoption direction -The [encrypted setup and management contract](encrypted-workspace.md#installation-first-run-setup-and-management-surfaces) adds the accepted October 8 outcome to E1 without duplicating its behavior here. Install binaries separately from first interactive, per-user encrypted provisioning. Simple, Advanced and eventual CLI share typed managed services, exact custody/state checks and domain receipts; presentation does not grant privileges. A standalone CLI host must contend for the same cooperating-owner lease rather than access SQLite directly or revoke a desktop Owner. Broker transport is a separate future security contract. +Install binaries separately from first interactive per-user provisioning. Simple, Advanced and eventual CLI surfaces must share typed native services, exact custody/state checks and domain receipts; presentation never grants privileges. Empty encrypted setup, explicit Legacy copy/recovery, source-free unlock and encrypted recovery backup/restore are implemented source. October 25 macOS disposable evidence demonstrates recovery after original test-key removal into an independently keyed fresh workspace and a separate-process reopen. That receipt does not qualify later source changes or normal-profile adoption. + +The existing CLI has no workspace persistence commands. A future CLI must acquire the same cooperating-owner lease rather than access SQLite directly or revoke a desktop Owner. Rotation, broader retention tools and remote brokers remain separate work. The Managed host refuses plaintext whole-workspace export; older plaintext import is explicit, and ordinary instruction exports remain readable. The recovery key file is itself unencrypted and must be protected separately from the ciphertext. Neither recovery nor encryption authenticates authorship, establishes freshness against rollback or grants engine authority. + +## Saved-revision navigation boundary -Owner preserves creation from a retained selected source and adds distinct empty encrypted provisioning under [E1b-2b8](encrypted-workspace.md#e1b-2b8-empty-encrypted-provisioning), without a fabricated source or new domain schema. Ordinary command routing, callback/renderer purge and source-free consent controls have source/fixture evidence. A qualified Managed factory, durable interrupted-setup recovery, real three-OS vault/GUI and packaged backend proof still precede default adoption. Current mounted desktop database/backups remain plaintext and existing CLI has no workspace persistence commands. Advanced rotation/migration/encrypted archives remain staged, explicitly unavailable features until qualified. +CW-1 adds one read-only Skills-to-Compile handoff. The renderer passes exact capability/revision selectors to the existing native `open_capability` command, validates the returned detail and binds completion to the unchanged selection, navigation epoch and workspace lifecycle. A historical revision is never silently upgraded to current head. A dirty draft for the selected skill blocks both current and historical handoff; other drafts remain retained. Native reads own record validation, while eligibility hints only govern navigation. Successful handoff clears a stale compilation context only after an exact fresh read. First use also attempts the bounded native library under the same guard; failed summaries remain visible but do not block an independently validated exact revision. Controller-owned route entry preserves that selection without an automatic duplicate read; explicit Refresh retries the library. It does not compile, save, review, export or grant authority. [Experience and qualification status](product-experience.md#cw-1-saved-revision-continuation--october-29-2026). ## Authority-module reference surface diff --git a/docs/continue.md b/docs/continue.md index 06cc838..59f08ea 100644 --- a/docs/continue.md +++ b/docs/continue.md @@ -1,5 +1,286 @@ # Continue Rangoon application work +## Current: full application source publication — October 29, 2026 +Jeff authorized all current application work for GitHub main only. The publication candidate reconciles the complete authored app snapshot onto public main `01423598`, preserves PR51/53/54, and includes encrypted startup/recovery, instruction history, native lifecycle seams, Agent files/Markdown review, and Skills → Compile continuity. Original application and website dirt remain outside the publication worktree. The [accepted publication intent](intent.md#full-application-source-publication--october-29-2026) and [receipt](development.md#full-application-source-publication--october-29-2026) supersede the earlier source packets' publication holds for this snapshot only. + +Use the current source and dated evidence together. Synthetic browser and source tests do not qualify installed native tasks or ordinary user data. Next: correct the isolated BF-2c qualification permission/fixture lists, build a fresh disposable artifact, and prove folder selection, metadata/Lock purge and the complete local workflow before personal files. Retained row-inspection custody follows. Remote sharing, live authority/execution, source Apply/Restore and Windows/Linux GUI qualification remain open. + +Historical entries below retain their original scope and outcomes. `` paths identify private developer receipts; they are not public download links or independently reproducible artifacts. Public validators and GitHub checks provide the reproducible source evidence. Publication does not change separate website, LNSAT or VUSL work, and does not distribute a desktop release. + + +## Current: CW-1 saved-revision compile handoff — October 29, 2026 + +Skills now opens an exact saved revision in Compile through an existing native read, preserving historical pins and other drafts. Dirty current edits for that skill block both current and historical handoff; conflicts, busy state, navigation and Lock retain their guards. No compile/export/save/review/run is automatic. README, architecture and reviewer guidance now distinguish implemented Managed-default startup/encrypted recovery from dated disposable macOS proof, unsupported Windows paths, unqualified current artifacts and readable instruction exports. + +[Intent](intent.md#cw-1-saved-revision-compile-handoff-and-current-storage-status--october-29-2026), [experience](product-experience.md#cw-1-saved-revision-continuation--october-29-2026) and [receipt](development.md#cw-1-saved-revision-compile-handoff--october-29-2026) own this fifteen-path packet. Exact preimages, command logs, baseline and final review status: `/rangoon-continuity-20261029`. Preserve all pre-existing dirty work; no commit/push/merge/deploy/release is part of this slice. + +Finish required synthetic browser interaction and 320/768/1440 dark/light checks when CUA can start; current failure is the configured symlinked writable root, before any page opens. Do not count source fixtures as rendered proof. Next native slice: add `allow-select-and-list-sources` to both isolated qualification permission lists, add manifest-bound disposable folder metadata/Lock-purge evidence, then build a fresh isolated artifact. The existing artifact/seal does not qualify the new picker. Keep normal files/keys/vault, live providers, LNSAT/VUSL changes and publication closed. Retained native row-inspection custody follows; do not use renderer paths to reopen files. + +## Current: BF-2c native folder metadata workbench — October 27, 2026 + +Jeff says proceed after toolchain qualification. Choose folder is now wired through a new scoped native picker command and existing SourceAccess counted read-only admission. It returns a bounded metadata-only window into the Agent files library: relative paths, size, observed modified time, filter/page/partial details and Clear folder. Clicking a folder row makes no native read; Choose files to inspect uses the existing explicit picker. Native roots close before delivery; no display path, session ordinal or metadata approval grants content access. [Experience](product-experience.md#bf-2c-folder-metadata-browsing--october-27-2026), [architecture](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026), [intent](intent.md#bf-2c-native-folder-metadata-workbench--october-27-2026) and [receipt](development.md#bf-2c-native-folder-metadata-workbench--october-27-2026) own scope/evidence. Exact 23-path preimages, failures, logs and final seal: `/rangoon-folder-ui-20261027`. + +Read the final seal, then qualify the current native picker/Lock flow in a fresh isolated disposable artifact before normal folders. Retained native row-inspection custody is next; do not substitute a renderer path API. Windows folder discovery remains explicitly unsupported; Linux/Windows GUI remains unqualified. Real remote transport, persistent index/tags, version-linked copy/apply/restore and rollout remain future work. Use the pinned Rust 1.99.1 checker, preserve all unrelated dirty work and the historical diagnostic evidence. No normal files/keys/vault, real native GUI, providers/remote/engines, foreign edits, dependency fetch or publication occurred. No commit/push/merge/deploy/release. + +## Current: BF-2b pinned toolchain qualification — October 27, 2026 + +Jeff asks to resolve BF-2a's Rust version blocker. Rustup installed official `1.99.1-x86_64-apple-darwin` with rustfmt/Clippy. Actual rustc/rustdoc commit is `58cf8f9c35b355199727627d07ae34a4e2846d67`, Cargo is 1.99.1, rustfmt 1.10.0-stable and Clippy 0.1.99. Pinned source qualification passes: formatting, 705 workspace tests (eight ignored), warnings-denied workspace Clippy and all 13 focused inventory tests. The source checker verifies those actual tool identities and pins subprocess paths; negative fixture strings in its unit-test log are not compiler evidence. The [intent](intent.md#bf-2b-pinned-toolchain-qualification--october-27-2026), [receipt](development.md#bf-2b-pinned-toolchain-qualification--october-27-2026) and `/rangoon-toolchain-qualification-20261027/review-seal.json` own final qualification status. Preserve all five BF-2a source/manifest/lock hashes; only four documentation paths change. + +Use `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` for portable source checks, or its `--toolchain-bin ` argument for the exact installed path. Bare Homebrew `cargo` still selects 1.98 and is not the accepted validator. Do not use an MSRV override. The installed compiler targets x86_64 on an arm64 Mac under emulation; this is not native-arm, Linux, Windows or GUI qualification. BF-2c now mounts folder metadata selection/admission; disposable GUI qualification and retained row custody remain next. No normal data/keys/vault, GUI, provider/remote/engine operation, dependency upgrade or publication. + +## Current: BF-2a retained-root inventory backend — October 27, 2026 + +Jeff says proceed with secure native folder inventory. Host source now implements actual incremental Unix metadata discovery over owned directory handles, without source-content reads, hashes, writes or path-string reopening. Fixed limits, ignored/unsafe-name rules, partial reasons, cancellation/closure and disposable race fixtures are in the [architecture](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026), [intent](intent.md#bf-2a-retained-root-inventory-backend--october-27-2026) and [receipt](development.md#bf-2a-retained-root-inventory-backend--october-27-2026). Nine owned paths/preimages/logs/review: `/rangoon-root-inventory-20261027`. The dependency promotion uses only already locked/cached rustix 1.1.5; both lockfiles add only that direct host edge. + +At BF-2a closeout Rust 1.99.1 was unavailable; its 1.98.0 `--ignore-rust-version` evidence remains diagnostic. BF-2b now installs the pin and separately qualifies unchanged source. Read the BF-2b final seal before mounting native folder selection, generation/admission ownership, row inspection custody and Agent files UI. No new native command or remote service exists; Windows is explicitly unsupported, Linux unqualified. Preserve existing encrypted routing, local file review and all unrelated dirty work. No normal data/keys/vault, GUI/provider/remote operation, dependency download, engine/VUSL edit or publication. RM-1 remains offline and copy/restore/rollouts remain unimplemented. + +## Current: RM-1 offline inventory contract — October 27, 2026 + +Jeff asks to implement scale, network files, versioning and cross-system copies. The first shared contract is now source: strict, bounded, unmounted offline metadata inventory, identity/session/snapshot binding, cursor paging, stable reported coverage, independent freshness clocks, expiry/lifecycle purge and hostile fixtures. [Architecture mechanics](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026), [intent](intent.md#rm-1-offline-inventory-implementation--october-27-2026) and [receipt](development.md#rm-1-offline-inventory-contract--october-27-2026) distinguish this from operational remote sharing. Seven owned paths and exact source evidence: `/rangoon-remote-inventory-20261027`. Read the final seal for independent disposition. + +BF-2a supplies the unmounted Unix root-inventory source and BF-2b passes pinned-source qualification; BF-2c now mounts metadata selection/admission; qualify its disposable GUI and retained row inspection before qualifying two disposable Rangoon installations with authenticated machine plus actor identity and explicit sharing. Do not mount this fixture model as a connected system or use its scope/deadlines as actual authorization. Source inspection, encrypted remote cache, copy/update/restore and rollout remain unimplemented. Existing local workflows stay available. Preserve all prior source and unrelated dirt; no normal files/keys/vault, filesystem scan, native/provider/network/remote operation, dependency fetch, engine/VUSL edit or publication occurred in RM-1. + +## Current: WF-1 intuitive in-file Find — October 27, 2026 + +Jeff requests a more intuitive workspace. Agent files now adds secondary Find in file with literal/case search, result counts, wrapping navigation, safe syntax-preserving highlights, folded-result reveal and scoped keyboard controls. Same-file refresh retains ephemeral state; file/route changes and Lock clear it. No source edit, search history, native request or provider call is introduced. [Experience](product-experience.md#wf-1-in-file-find--october-27-2026), [intent](intent.md#wf-1-intuitive-in-file-review-search--october-27-2026) and [development receipt](development.md#wf-1-in-file-find--october-27-2026) own the contract and evidence. Exact ten-path preimages/review/seal: `/rangoon-find-20261027`. + +Read the final review seal before resuming. Preserve the previous saved-source handoff, encrypted routing and all unrelated dirty work. Next useful functional slice: accepted selected-root discovery/inventory packet, with explicit roots and bounded paging, before filesystem-wide search or persistent categorization. Native disposable picker/workflow qualification remains separate and required before personal files. Remote transport, source Apply/Restore, providers, LNSAT/VUSL edits, dependencies and publication remain closed. No commit/push/merge/deploy/release in WF-1. + + +## Current: saved-file source-workbench handoff — October 27, 2026 + +FH-1 closes a functional dead end: selected saved Agent file → Open saved source → Import source sections → existing section-to-Skills form. Existing native `open_snapshot` receives only saved source ID; returned ID and handoff digest/byte count must match before UI selection changes. Pending/duplicate/temporary/mismatch/error states are explicit; failure retains inspection/previous analysis. Lock/deletion/late callback and user navigation are fenced. [Experience](product-experience.md#fh-1-saved-file-source-workbench-handoff--october-27-2026), [intent](intent.md#fh-1-saved-file-source-workbench-handoff--october-27-2026) and [receipt](development.md#fh-1-saved-file-source-workbench-handoff--october-27-2026) own truth. Exact thirteen-path baseline/evidence/seal: `/rangoon-source-handoff-20261027`. + +Read the passing final seal before claiming closure. Source/renderer behavior uses the existing native reference-based read/selection command; it adds no native opcode, schema, crypto, persistence, provider or execution authority. Synthetic five-section fixture reaches the prefilled skill form but performs no native skill save/review. Fresh current-artifact native GUI remains needed before normal personal data. Next functional slice should address bounded literal in-file search; follow existing BF-2/BF-3/BF-4 gates for folder discovery, encrypted organization and reviewed batch changes/undo. Remote/runtime/Terraform support remains proposed separately. Preserve unrelated work; no normal data/keys/vault, native/provider/remote operations, foreign edits, dependency fetch or publication. + +## Current: compact reference-aligned workbench — October 27, 2026 + +VR-1 responds to the harsh/bulky UI: softer charcoal/white surfaces, restrained dividers, sans chrome, compact shared task headings and a combined Agent files toolbar. File rows show compact dates with full timestamps/UTC retained in the inspector/title; limits/Import stay reachable. Markdown outline starts secondary/closed; source/folds/line jumps remain. [Visual contract](visual-system.md#compact-reference-aligned-workbench--october-27-2026), [experience](product-experience.md#vr-1-compact-reference-aligned-workbench--october-27-2026) and [receipt](development.md#vr-1-compact-reference-aligned-workbench--october-27-2026) own scope/results. Exact eleven-path evidence/preimages/seal: `/rangoon-refinement-20261027`. + +Read the final passing seal before claiming closure. UI-only: no new engine, parser, native/storage, remote, Terraform or authority capability. Next refine remaining Workflows/management routes against these same original structural references and actual supported workflows. Current changed renderer still needs fresh native artifact/GUI qualification before normal personal files. Preserve unrelated dirt and independent LNSAT/VUSL repositories. No normal data/keys/vault, providers, dependency install/fetch or publication. + +## Current: IDE-style Markdown review — October 27, 2026 + +MR-1 follows Jeff's request for agent/Markdown files to work like IDE review: central source pane, ATX outline/hierarchy, foldable sections/fenced code/YAML metadata, escaped lexical hints, original line numbers and advisory finding jumps. Import shares hints while native spans stay authoritative. Matching rerenders preserve local folds/scroll/focus; lock clears the source. [Experience mechanics and Terraform proposal](product-experience.md#mr-1-ide-style-markdown-review--october-27-2026) and [development receipt](development.md#mr-1-ide-style-markdown-review--october-27-2026) define truth. Exact thirteen-path preimages/results/seal: `/rangoon-markdown-ide-20261027`. + +Read the passing final seal before claiming closure. This is read-only lexical review, not full language validation, semantic review, source editing or a replacement for native parsing. Terraform is proposed read-only plan inspection first; no install/provider/plan/apply, credential, remote/infrastructure action or support claim is opened. Continue the focused local editing/composition workflow; qualify any actual target loader and fresh native artifact before using normal personal files. Remote peer service, full LSP/editor, Terraform adapter and source-history Apply/Restore remain separately scoped. No publication or foreign edits. + +## Current: Skills editing and revision context — October 27, 2026 + +CU-2 continues the intuitive editing overhaul on Skills: explicit saved/draft/history/pending/conflict state, visible native revision dates and position, collapsed technical provenance/source creation, per-record disclosure retention, and exact local-only draft discard with confirmation. The [experience contract](product-experience.md#cu-2-skills-editing-and-revision-context--october-27-2026) and [development receipt](development.md#cu-2-skills-editing-and-revision-context--october-27-2026) own scope/results. Evidence/preimages and final seal: `/rangoon-skills-ux-20261027`. Root alone owns the twelve-path packet; unrelated recovered work remains untouched. + +Read the final seal before claiming closure. Apply the same focused library/working selection/inspector pattern to Workflows next, preserving native validation, draft retention and unavailable states. A new native artifact/smoke is still needed before counting this changed renderer as a qualified personal-data journey. Remote peer implementation, target execution, providers and source-history Apply/Restore remain separate work. No normal data/keys/vault, native/provider operations, LNSAT/VUSL edits, dependency install/fetch or publication in CU-2. No commit/push/merge/deploy/release. + +## Current: contextual composition UI — October 26, 2026 + +Jeff authorizes continuing the intuitive edit/combine overhaul. CU-1 changes the existing composition renderer/CSS and tests, not controller/core/native/storage semantics: native-analyzed section shortcuts, in-place selection, visible source/destination inspector, primary Assign and closed More operations, exact-range-bound advanced fields and clear Return/Cancel. Destination, disclosure and live fields survive ordinary route changes; lock purges them and ignores late results. The [experience contract](product-experience.md#cu-1-contextual-editing-and-combination--october-26-2026) and [development receipt](development.md#cu-1-contextual-composition-ui--october-26-2026) own acceptance/results. Exact eight-path preimages/evidence: `/rangoon-composition-ux-20261026`. + +Read the final packet seal for current source/UI review disposition, then apply the same task-focused pattern to Skills/Workflows. Native disposable workflow/picker qualification remains necessary before normal personal files. Do not count synthetic renderer preview refusal, source tests or screenshots as native save/recovery proof. Actual OS media, screen reader/touch and three-OS GUI remain open. Peer installations and host sharing remain proposed. RM-1 now has an unmounted offline metadata reader; no transport/credentials/remote backend is mounted. Preserve concurrent LNSAT integration work and all other dirt. No normal data/keys/vault, native/provider/target operations, foreign edits, dependency install/fetch or publication. + +## Current: remote setup direction — October 26, 2026 + +Jeff requires remote setups alongside bulk agent-file viewing, timestamps and revisions. The [canonical remote architecture](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) reconciles existing fleet, deployment, adapter and encrypted-history work. RM-0 is documentation-only. Jeff clarifies the primary file-access path is Rangoon-to-Rangoon: a sharing installation explicitly grants another authenticated installation and acting user/service access to selected roots/operations. The same restricted host service may later run in headless Rangoon; no separate bridge product or mandatory LNSAT. Start with one host's read-only file inventory/inspection; remote writes depend on AR-3 and target-bound encrypted recovery. Preserve local qualification priority and Customer Zero's external-runtime boundary. + +RM-1 now has the accepted seven-path unmounted offline metadata implementation; its exact ownership, validators, privacy/failure tests and remaining native/transport decisions are in the architecture section and `/rangoon-remote-inventory-20261027`. BF-2a supplies the unmounted Unix backend and BF-2b passes pinned-source qualification; native picker qualification and retained row inspection still precede the proposed RM-2 peer transport. No transport/backend/bridge implementation or remote contact is authorized by RM-0. Do not duplicate the fleet registry, invent filename revision lineage, expose a raw shell/database, share SQLite across hosts, use ambient credentials, or edit LNSAT/VUSL. BF-1 remains local; its fresh source/UI reviews and 534-test receipt are complete, while disposable native picker and OS-mode qualification remain open. All prior dirt stays preserved; no publication. Direction evidence/preimages: `/rangoon-remote-direction-20261026`; peer clarification: `/rangoon-peer-direction-20261026`. + +## Current: bulk agent-file UI overhaul — October 26, 2026 + +Jeff prioritizes practical bulk agent-file viewing, performance and advisory issue/outdated-method tags. BF-1 source adds the Agent files workbench, explicit bounded native multi-file read-only inspection and saved-source checks without replacing native analysis. The [experience/next-stage contract](product-experience.md#bf-1-agent-file-workbench--october-26-2026) owns layout and BF-2 through BF-5 proposals; the [development receipt](development.md#bf-1-bulk-agent-file-workbench--october-26-2026) owns exact validation/review and limits. Preimages/ownership/logs: `/rangoon-bulk-files-20261026`. Dates distinguish native saved records from session-only selected/checked wall-clock observations. No filesystem mtime or linked revision timeline is claimed. Next: selected-root inventory plus target-bound history read models reusing encrypted AR storage; do not infer ancestry from filenames. + +Current slice has no folder crawl, persistent tags, batch save/fix, executor, model call or obsolete-version assertion. Selected files are temporary; saved inventory uses existing encrypted routing and schema. Preserve completed AR-1/AR-2 history work; AR-3 native Apply/Restore remains required before external instruction replacement. Existing unrelated dirt and publication gates stay intact. + +Fresh source/UI review is complete. Next run disposable native multi-picker rehearsal before normal personal files, then prepare BF-2 selected-root discovery and metadata paging. No normal data/keys/vault, provider/target operation, LNSAT/VUSL edit, dependency fetch, publication or release. Do not confuse synthetic browser transport, unit tests or compile checks with actual OS GUI qualification. + +## Current: encrypted instruction history — October 25, 2026 + +Jeff authorizes AR-1/AR-2 encrypted instruction-history persistence and retention of parse/decompose/split/merge/reassembly lineage. Root owns the store-only source delta, schema/recovery/security and integration. Reuse the [archive contract](target-loader-qualification.md#instruction-change-archive-and-restore--october-25-2026); do not invent another parser or authority profile. Exact ownership/preimages and validation logs: `/rangoon-instruction-history-20261025`. The [development receipt](development.md#ar-1ar-2-encrypted-instruction-history--october-25-2026) records checks and remaining work. + +New history APIs require an existing keyed workspace and explicitly opt it into schema 5. Private V4 recovery encoding includes every change/journal event; the public plaintext exporter refuses schema 5, and public plaintext import rejects V4. Native/renderer history mounting remains closed until it uses opaque encrypted recovery and qualified target custody. Existing V1–V4 behavior and logical backup formats must stay intact. Source tests do not establish native adoption or Windows/Linux qualification. + +AR-1/AR-2 source validation and fresh independent review pass. Next: AR-3 native retained previews, custody and crash reconciliation before external instruction-file replacement. Connect the opaque encrypted recovery path and new v3 inventory/restore contracts before mounting history; preserve unknown outcomes and add qualified reconciliation without repeating an uncertain write. No normal data/keys/vault, target/provider process, LNSAT/VUSL edits, dependency fetch, publication or release. Current tree contains substantial unrelated recovered work; use exact packet preimages and preserve it. + +## Current: target-readback prerequisite and secure instruction history — October 25, 2026 + +Jeff requests the next target-handoff/readback phase, followed by secured backup/undo for external instruction changes. TLQ-1 adds only an unmounted macOS synthetic isolation self-test and bounded supervisor. The [target record](target-loader-qualification.md#tlq-1-isolation-prerequisite--october-25-2026) owns scope; the [receipt](development.md#tlq-1-target-isolation-prerequisite--october-25-2026) owns exact tests, failed canaries, review and remaining gates. Installed Codex identity changed to `0.164.0-alpha.11.1`; no target process was launched. + +The [instruction archive requirement](target-loader-qualification.md#instruction-change-archive-and-restore--october-25-2026) is accepted product direction, not implemented rollback. Exact hashes alone are insufficient: original bytes and metadata need authenticated encrypted custody, a durable change journal, explicit restore preview and qualified target custody/drift handling. Existing workspace backup and new-file bundle export do not yet restore external originals. Implement archive persistence/recovery and native restore before any target installer can replace files; keep proposed AR-1 through AR-4 separate from TLQ-1. + +TLQ-1 now passes 19 focused tests and seven selected macOS synthetic canaries with the exact hash-pinned Apple loader support. Both earlier pre-main failures remain separate evidence; there is still no target-loading result. Next: implement the proposed instruction-archive domain/encrypted persistence packet and prepare separately accepted target-specific schema/startup capture. No Codex/Claude invocation, real config/credentials/provider, normal data/keys, foreign edits or publication is opened. Do not add a fake loaded/verified badge or mount Apply/Restore controls before their native contracts work. Previous management and encrypted-recovery evidence stays separate; preserve all unrelated dirt. + + +## Current: management audit and activity-report optimization — October 25, 2026 + +Jeff requested evaluating management systems and optimizing them. The [usability checkpoint](product-experience.md#management-usability-checkpoint--october-25-2026) distinguishes useful local controls from unfinished live fleet, approval, deployment and SDK workflows. The [development receipt](development.md#management-audit-and-activity-report-optimization--october-25-2026) owns exact changes, validation, review and limitations. + +The activity-report renderer now accepts valid prefix-only producer inventories, pages record/timeline lists at 50, provides Clear filters and Show selected record, resets stale filters on successful replacement/purge, preserves failed/cancelled inspection and skips unchanged local renders. Keyboard focus and reference-route announcements are corrected. No native, storage, protocol, provider or execution behavior changes. E1d-2's prior native recovery evidence remains separate. + +Next safe priority remains the bounded personal package/install/recovery rehearsal, followed by one qualified target handoff and effective configuration readback. A live management surface needs a separately accepted source/session contract; do not grow a custom scheduler or display fake activity. Current work remains uncommitted and unpublished; preserve unrelated dirt and include a substantive reviewed README update before any future publication. + + +## Current: native encrypted recovery — October 25, 2026 + +Native encrypted backup/restore is implemented using existing SQLCipher. The age experiment is retained as standalone historical source outside active builds. The [E1d-2 receipt](development.md#e1d-2-native-encrypted-recovery--october-25-2026) owns exact paths, commands, review and narrow native evidence. + +Five disposable macOS phases demonstrate selected-file backup, original test-key removal, complete-history recovery into a different encrypted workspace, distinct-process reopen and exact test-slot cleanup. The source, recovered target and restarted target have the same complete canonical archive identity and length. Recovery keys remain outside the renderer; original source ciphertext stays unchanged; Managed plaintext backup export still refuses. + +Native testing found and corrected the qualification observer's missing request binding and the renderer's recovery-command allowlist. Rejected runs remain separate evidence; they are not qualification passes. Jeff's requested disclaimers now explain the unencrypted recovery key file, key-loss consequences and limits against compromised hosts, readable originals/exports and unauthenticated history. + +Next safe work: prepare a bounded personal-use package/install and recovery-rehearsal packet. Keep normal data/key custody explicit. Windows/Linux custody and GUI, signing/distribution, broader compatibility and public release remain separate. No providers, LNSAT/VUSL edits or publication were opened. Do not restore the retired crypto experiment or broaden protocol/scheduler scope. Before any future push/merge, include the required substantive README update. + + +## E1d-1 experimental recovery codec — October 25, 2026 + +Historical E1d-1 checkpoint, superseded for active native recovery by E1d-2 above. Jeff's continuation opened the [bounded source experiment](intent.md#e1d-1-experimental-codec-continuation--october-25-2026). New `rangoon-recovery` implements an unmounted, bounded age-v1 envelope, explicit X25519 key wrappers, full authentication before borrowed plaintext and fixed/redacted diagnostics. Logical archive validation still belongs to the existing store; no native backup/restore or recovery-key UI is enabled. Age 0.12.1 was rejected after a current crypto-bigint dependency advisory; selected age 0.11.5 remains beta/testing-only, with unmaintained compile-time and future-compiler compatibility warnings that block native/production promotion. The 128-bit file key is not an AES-256 or post-quantum claim. Focused tests pass 17 cases and two privacy compile-fail doctests; a pinned independent Go reference passes one Go-to-Rust fixture and four Rust-to-Go cases. Full workspace tests pass 656 cases, formatting and focused/full-workspace Clippy with `-D warnings` pass, and fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh) source review passes with no actionable P1/P2/P3. The separate Cargo future-compiler dependency warning remains. Fresh independent documentation/evidence review also passes with no residual findings; [the development receipt](development.md#e1d-1-experimental-encrypted-recovery-codec--october-25-2026) and `/rangoon-e1d1-assessment-20261025` own final outcomes. All 167 old lock package identities/checksums remain; necessary feature-addition edges are recorded. No native/store/UI/desktop-lock, normal data/key, engine/provider, foreign-repository or publication change. + + +## Next phase: portable recovery — October 25, 2026 + +Historical E1d-0 planning checkpoint, superseded by the implemented E1d-2 path above. Jeff requested addressing the security gaps and setting the next phase. E1d-0 completed a docs-only source assessment and independently reviewed next-phase proposal, owned by the [E1d behavior contract](encrypted-workspace.md#e1d-portable-encrypted-recovery--october-25-2026) and [dated receipt](development.md#e1d-0-recovery-and-intrusion-phase--october-25-2026). Managed plaintext backup export already refuses before picker/archive access; instruction exports remain deliberately readable after explicit selection. The subsequent E1d-1 entry above records experimental source and limits; resolve its production dependency gate before native backup/restore custody and an isolated restore rehearsal. No codec, library fetch, recovery-key UI or live hostile-worker test was delivered by E1d-0. A one-runtime target-load/enforcement proof follows recovery; L7 audit logging is not proof of denial. Normal data/keys, engines, foreign repos and publication remain closed; the later E1d-1 validation acquisition does not reopen those actions. Independent review and validator results are recorded in `/rangoon-recovery-phase-20261025`. + + +## Technical details disclosure — October 24, 2026 + +Jeff requested cleaner everyday views with internal identifiers in Advanced or Technical details. The [bounded UI receipt](development.md#progressive-technical-details--october-24-2026) owns Compile/Workspace disclosures, the shared component/styles and focused tests. Names, status, warnings and actions remain visible; exact identifiers remain unchanged and inspectable. Collapsing metadata is not credential protection. Stored secrets stay outside the main workbench; existing credential-entry contracts remain separate. Duplicate names retain collision-safe record discriminators and exact deletion targets; same-view refresh retains open details and summary focus. Completion checks pass 35 focused and 488 full tests, twelve responsive and four expanded synthetic captures, plus mounted refresh/preview/Cancel checks. Fresh independent OpenAI `gpt_ui_review` (`gpt-5.6-terra`, xhigh) review passes with no actionable P1/P2/P3; exact source, validation and final capture evidence is in `/rangoon-technical-details-20261024`. Intrusion research and proposed adversarial gaps are in `/rangoon-agent-intrusion-review-20261024/research.md`; no hostile-worker harness, content broker, publication or engine/security implementation is included. + + +## Product copy and project audit — October 24, 2026 + +Jeff requested a full source/interface/claims audit, then professional user-facing copy. The audit covers the active application, independent VUSL core and distinct parallel LNSAT worktrees; evidence is `/rangoon-project-audit-20261024/audit.md`. Local authoring/composition/export and bounded encrypted macOS smoke remain real progress; actual target loading, VUSL consumer adoption, connected engine workflows, encrypted portable recovery and plugin SDK remain separate unfinished work. The copy slice changes labels/descriptions only, with exact ownership and validation in the [development receipt](development.md#workbench-copy-refinement--october-24-2026). Copy checks pass 38 focused and 483 full tests; twelve synthetic responsive captures and fresh independent OpenAI `gpt_ui_review` (`gpt-5.6-terra`, xhigh) review pass. Exact evidence is `/rangoon-production-copy-20261024`. Preserve all recovered/unrelated source. No publication or foreign changes are included; the prior native smoke remains bounded evidence and is not rerun by this copy change. + + +## Current native smoke — October 24, 2026 + +Jeff explicitly authorized the [UIC-1 disposable native smoke](development.md#uic-1-disposable-native-smoke--october-24-2026). Use only the unchanged harness, new nonce/artifact and eight named existing phases. Production source remains frozen; exact test-only Keychain/data access is permitted, normal keys/data and providers are not. All eight native phases now have successful parent/child receipts, including actual authoring/export/additive Restore, Lock/read-drain/Unlock/header probes, distinct-process persistence, malformed-bundle refusal and missing-test-key recovery/cleanup. Two reviewed test-fixture Restore grants were necessary; the runner/case plan and ordinary product behavior stayed unchanged. Final evidence and independent reviews belong to the native smoke seal. Next prepare an ordinary personal build/profile for noncritical copies; encrypted portable backup, existing-data migration and broader release/platform qualification remain open. No whole-product/release qualification follows. + +## Current local-workbench repair — October 24, 2026 + +Recovery is sealed PASS. Current bounded source repair is [UIC-1 personal workspace controls](development.md#uic-1-personal-workspace-controls--october-24-2026): truthful setup/Quit, storage-specific Data actions and safe recovery guidance. Current user continuation supplies authority for these ordinary local UI repairs; historical proposed packets remain history. Source checks pass: 47 focused and 483 complete renderer tests; the ordinary macOS desktop build also passes offline. Source review passes; final rendered review and exact evidence belong to the UIC-1 seal. Next run the unchanged disposable native harness against a fresh artifact before normal personal use. Historical native receipts do not qualify the new renderer. Actual forced-colors/reduced-motion media and Windows/Linux native qualification remain open. No normal data/key/vault or provider/publication gate is opened. + +## Personal-use continuation — October 24, 2026 + +Jeff explicitly resumed completion for his own use. Active durable application checkout: ``, branch `codex/personal-workbench-20261024`, base HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Start with git branch/HEAD/concise status; read AGENTS.md, intent.md, this entry, then the current development receipt. The older `app-review` checkout remains dirty and untouched. The former temporary audit directory lost Git metadata and source files; do not use it as a build or authoritative checkout. + +All 714 source identities recorded after the October 22 focused-UI packet were recovered by exact SHA-256 from the committed base, remaining files and exact saved preimages. [Recovery receipt](development.md#personal-use-source-recovery--october-24-2026) owns validators and independent review; absent final passing seal leaves recovery open. No runtime semantics were changed by restoration. + +Next qualify and repair the encrypted local source → skill → compose → compile/export → lock/reopen workflow using disposable data/keys. Personal usefulness governs priority; no commercial-uniqueness experiment is required first. Keep the existing useful local features and optional providers. Normal data/keys/vault, real credentials/providers, paid calls, production/infrastructure, foreign-repository edits, publication and release remain closed. Do not add a scheduler, broad new protocol or platform expansion before the local workflow works. Later records below retain their dated history. + +## Current direction and next work — October 22, 2026 + +Latest accepted focus: the [capability-workbench direction](product-experience.md#focused-workbench-direction--october-22-2026) now foregrounds source import, skills, composition/export and evidence. The first UI-only pass regroups the twelve existing routes and labels samples; it adds no disclosure behavior or integration. The [Rangoon/Hypler site brief](focused-workbench-site-brief.md) supplies corresponding copy without publishing either site. Prepare the isolated OpenHands adapter/test next; defer further platform expansion until it proves useful. Exact implementation/validation belongs to the [focused UI receipt](development.md#focused-workbench-navigation-and-site-brief--october-22-2026). + +Jeff directs [internal operations-first delivery](intent.md#internal-operations-first-direction--october-22-2026): make Rangoon useful for Hypler's own supervised workloads and software portfolio before expanding speculative integrations or funding scope. Reuse existing capability work, fleet inventory, deployment and shared-state contracts; keep LNSAT, OpenShell and VUSL independent. The [canonical plan](plan.md#internal-operations-first-delivery--october-22-2026) owns staging, and the [reconciliation receipt](development.md#internal-operations-first-architecture-reconciliation--october-22-2026) owns this five-document packet's evidence. No infrastructure, production target, normal data/key, provider, foreign-repository or publication action is opened. + +Latest clarification: build the general product, with Jeff/Hypler as Customer Zero. The supplied plan is proposed input, not blanket source/operational acceptance. The [Customer Zero gap assessment](customer-zero-gap-analysis.md) and [audit receipt](development.md#customer-zero-product-reconciliation--october-22-2026) reconcile implemented source with the requested persistent engineering-job workflow. They govern the revised next milestone; do not hardcode Hypler hosts or make OpenShell/LNSAT/VUSL completion prerequisites for an otherwise qualified constrained job. + +The [current-artifact C1-M matrix](development.md#c1-m-current-artifact-native-matrix--october-22-2026) completed all six disposable macOS synthetic cases with runner exit 0, exact controller handoffs, closed source/artifact freeze and fresh independent bounded functional PASS. Evidence: `/rangoon-c1-native-matrix-20261022-v17`. Raw whole-product qualification remains false. Earlier v14–v16 remain failed; v13 remains historical. Do not rerun completed cases without a relevant change or unresolved concern, and do not count this as mounted/live-provider or three-OS support. + +Next prepare the proposed isolated OpenHands adapter test from the [direct comparison](openhands-comparison.md), then freeze its exact source/ownership, runtime, identity, confinement and validation contract. Custom agent-execution and scheduling implementation stays on hold pending the comparison/test outcome; preserve the workbench. The prior Customer Zero documentation audit is sealed. Bind immutable execution identities and fail-closed task isolation, including negative runtime probes. CZ-2 qualifies one CLI-only deterministic project-review job that survives client disconnect and preserves scoped results/recovery; CZ-3 replays it through MCP to complete the supplied demonstration before heterogeneous workers or paid model runs. Do not restart the completed native matrix without a relevant change. OpenShell mounting stays a separately gated connector lane. Production Start, real providers/credentials, OS vault, normal data/keys, new service/runtime/plugin implementation, LNSAT/VUSL edits, dependency fetches and publication remain closed. Hardware roles and infrastructure adoption require measured inventory and separate selection; existing production services stay outside the experiment. + +## Earlier checkpoint context + +The following entries retain their dated state. The current direction and latest development receipts above govern continuation. + +Current accepted continuation: [C1-M native qualification after C2a](development.md#c1-m-native-qualification-after-c2a--october-21-2026), with a new 711-file baseline in `/rangoon-c1-post-c2a-20261021`. Source/artifact preflight precedes any native launch; the original six disposable cases and all consent/attribution/deadline rules remain unchanged. C2a is source-complete, while v14 remains failed and v13 historical. No new implementation or provider, normal-data/key, vault, foreign edit or publication gate is opened. + +Post-C2a preflight passed independent review, but native v15 and v16 remain failed with zero of six qualified cases. V16's first child completed its synthetic read and exited 0; the parent rejected missing timely controller return attribution and exited 1. Preserve both failed evidence directories and their closed 711-file/artifact freezes. No qualification app remains running. Resume only the original six-case C1-M matrix with fresh identities and timely controller handoffs; do not reuse the failed case as a pass or weaken deadlines. Exact evidence and limits belong to the linked receipt above. + +Current accepted [C2a bounded native session inspection](development.md#openshell-c2a-bounded-session-inspection--october-21-2026) is implemented in its exact six-path source/tests scope. Eleven new grouped cases, all 85 Host cases, complete default/no-default desktop suites (724 plus one nested child / 405), format, strict Clippy, normal builds and feature isolation pass. Its receipt and exact final independent review/evidence seal belong to `/rangoon-c2a-session-view-20261021`; a missing passing final seal leaves that gate open. All 705 outside-owned existing identities stay exact. Next work is the separately scoped mounted finite-read workflow and platform qualification, with R9 retaining SDK/UI/CLI contract plans. C1 v14 remains failed, no native pass is promoted, and no provider, credential, UI/IPC, persistence or publication gate is opened. + +Current C1-M source/artifact preflight passes with fresh independent review; the subsequent v14 native matrix failed its first case, with child exit 70 and zero qualified cases. Its failed capture/freeze is preserved and no C1-M app remains in the post-run inventory. The [current-source qualification receipt](development.md#current-source-c1-m-qualification-continuation--october-21-2026) owns exact source comparison, validators and artifact/review evidence in `/rangoon-c1-current-artifact-20261021`; native evidence is `/rangoon-c1-native-matrix-20261021-v14`. Old v13 remains bound to its separate historical artifact. Jeff accepted C2a source/tests during that attempt; its separate source implementation and validation are recorded above after the failed native freeze closed. Real credentials/providers, normal data/keys, vault, foreign edits and publication stay closed. No new GUI/native pass is claimed. + +Current bounded source correction enforces [operator record-kind count consistency](development.md#operator-record-kind-count-consistency--october-21-2026) under the existing O2 contract: all nineteen per-kind timeline totals must match the decoded inventory before a safe view is returned. Red/green reproduction and two regressions cover per-kind inventory contradictions and equal-total non-decision substitutions. Complete portable workspace tests pass 637 cases, including all 151 operations tests; eight ignored cases remain unqualified. Formatting, strict operations Clippy and 28 existing renderer/parity checks pass. Exact four-path ownership and the final independent review/hash disposition belong to that receipt and its evidence directory. No new schema, renderer behavior, native operation or provider integration is opened. C2a was pending when this correction closed; Jeff subsequently accepted its exact six-path source/tests packet, as recorded above. + +Current independent work records [Windows/Linux native-input design](development.md#openshell-platform-input-design--october-21-2026). The [platform plan](openshell-observation-connector.md#windowslinux-input-design--research-october-21-2026) identifies GTK destruction without response, Windows dialog-message integration and credential truncation as explicit qualification cases. Linux GTK 3 is a candidate; Windows GUI-thread/parent lifetime remains unresolved. This documentation packet opens no backend, dependency fetch or native run. Windows/Linux input remains unavailable. The C2a proposal body stayed byte-for-byte unchanged during that design packet; Jeff subsequently accepted its separate source/tests scope. + +Current bounded work fixes [pending-state readback](development.md#openshell-pending-state-readback-correction--october-21-2026) in the existing OpenShell Host. Confirmed reviews must not poll as awaiting consent; expiry and fenced generations must remain honest while custody stays retained until Stop/close. Exact five-path scope and evidence live in that receipt. Three new regressions, all 74 Host cases, complete default/no-default desktop suites (713/394 top-level tests plus the default child helper), format and strict Clippy pass; ignored OS fixtures remain unqualified. Fresh independent source and proposed C2a design reviews pass; the final exact-hash disposition is retained with the evidence. The following v13 native evidence remains tied to its original frozen artifact; this source correction does not constitute a new native run or mounted connection. + +C1-M remains the accepted [23-path source/test packet](openshell-observation-connector.md#c1-m-native-reviewinput-and-actual-macos-qualification--proposed-source-packet). The [guarded native matrix receipt](development.md#guarded-native-matrix-accepted--october-21-2026) now records six passing bounded macOS synthetic native cases, fresh independent OpenAI `gpt_ui_review` (configured Terra xhigh) PASS and controller acceptance. Evidence: `/rangoon-c1-native-matrix-20261021-v13`. One frozen artifact, all 709 source identities, fifteen completed CUA calls, six exact controller handoffs and clean child exits were verified. Accept-read made exactly three selected RPCs; Cancel, queued/open Stop, expiry and programmatic owned-parent close made none. The raw parent result stays separate from the narrower independent acceptance; this does not qualify a mounted product or real provider. + +Jeff reported no interaction during discarded v9. The [investigation](development.md#controller-attribution-investigation-and-correction--october-21-2026) found no internal auto-confirm or runner UI-injection path; its AppKit actor and exit-70 cause remain unknown. Other chats were not read. Historical failed/unqualified runs remain preserved. The guarded runner refuses unexplained phase advancement, uses full case/nonce context and action intent/return records, and requires a fresh start and terminal challenge for each child. Its sixty-second post-exit controller-return allowance does not extend the native 120-second credential deadline. Offline Python passes 45 tests; independent source review passes. Prior Rust format, eight focused checks, strict Clippy and no-run build remain valid for unchanged Rust bytes. All 703 outside-owned identities remain exact; index empty, HEAD unchanged. Exact source correction/evidence: `/rangoon-c1-attribution-20261021`, including `return-grace`. + +Accepted source deliverable: [C2a bounded session inspection](openshell-observation-connector.md#c2a-session-inspection-source--proposed-next-packet), reusing Host/Gate without commands, renderer or provider activation. Jeff accepted its reviewed exact six-path scope, privacy allowlist and validators; the current C2a receipt above owns its completed source and validation, while commands and renderer mounting remain separate. Continue the separately scoped Windows/Linux native input qualification and mounted one-read workflow stages in the [connector plan](openshell-observation-connector.md#remaining-delivery-stages-and-full-support-target). Preserve existing source, consent, callback drain and provider boundaries. Production Connect/Start, real providers/credentials, OS vault, normal data/keys, renderer mounting, LNSAT/VUSL edits, dependency fetches and publication remain closed. C1-M macOS evidence does not complete those stages or full cross-runtime support. + +SDK direction remains [R9](provider-interoperability.md#adapter-sdk-and-independent-foundations--october-20-2026): reuse VUSL semantics through a separately qualified consumer adoption, implement Rangoon manifest/host/conformance tooling, and retain provider-native capabilities and authority. Current clients/inspectors are reusable; public adapter SDK/plugin runtime is not built. First developer implementation remains the offline descriptor/reference-worker conformance packet, without a provider install or activation. + +Current UI-only foundation polish follows Jeff's VUSL/LNSAT identity and usability request. The [development receipt](development.md#foundation-identity-and-sdk-context--october-20-2026) owns its exact fifteen paths and validation. Reuse canonical local logos, distinguish shared language from optional authority engine, retain diagnostic command/state behavior and keep VUSL outside the authority catalog. SDK wording refines R9 only; no SDK/runtime or VUSL adoption is implemented. Focused 20 tests and full npm build:check with 468 tests pass. Both routes render at measured 320/768/1440 CSS widths in light/dark with loaded marks and no overflow; keyboard disclosure/focus checks pass. Forced-colors runtime remains unexercised, source handling is reviewed separately. Fresh independent OpenAI gpt_ui_review (configured Terra xhigh) review passes with no actionable P1/P2/P3. The reviewer verified all fifteen hashes, preservation, supplied validators and final screenshots without rerunning tests. This is UI/source review, not native, provider, SDK, OS or release qualification. No publication or foreign edit. + +Current accepted O1/O2 test continuation covers distinct-producer exact repeats and changed same-ID records through the actual Rust inspectors and minimized operator view. [The cross-producer receipt](development.md#cross-producer-repeated-record-conformance--october-20-2026) owns the exact three paths, semantics, named gates and independent review. V1 exposed an over-narrow changed-record test oracle: O2 correctly propagates both structural and delegation conflict stages. Root reconciled the accepted delegation contract and corrected only that expectation. Both focused cases, all 149 rangoon-ops tests, formatting, strict Clippy and 28 existing renderer/model/parity/view tests pass; V2 independent review found one P3 privacy assertion gap on the changed-record case; the added assertion now passes both focused cases, all 149 ops tests, formatting and strict Clippy; fresh independent OpenAI gpt_reviewer (configured Terra xhigh) review passes with no open P1/P2/P3; documentation/whitespace and all 691 outside-owned identities pass. The renderer checks use unchanged fixtures, not the new Rust cases or a GUI. No production or UI change is included. Jeff separately accepted C1-M source/tests; begin that packet with its own baseline after this O1 continuation closes. No native prompt, credential/provider, foreign edit or publication is performed by this packet. + +Current usability/native-input design ties the next engineering packet to the real user task: configure locally, review access, native input, one finite read, local inspection and explicit refresh. [Product experience](product-experience.md#connected-system-usability--october-20-2026) owns the proposed practical flow and scoped-session friction. [C1-M](openshell-observation-connector.md#c1-m-native-reviewinput-and-actual-macos-qualification--proposed-source-packet) proposes 23 exact source/test/document paths and six actual disposable macOS cases, with a small separately reviewed native boundary and unchanged app unsafe bans. Actual native review must retain callback admission across queued/open UI; C0's metadata-only pending state is not that proof. Windows/Linux and the three-OS shipping requirement remain explicit. The earlier proposal itself accepted no source or native execution; Jeff’s later C1-M source/test acceptance above opens only its exact bounded source/disposable-test scope. [The design receipt](development.md#connection-usability-and-native-input-plan--october-20-2026) owns evidence; proportional documentation/whitespace checks and all 690 outside-owned identities pass. Proposal review’s subprocess/address ambiguities are corrected; fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) final architecture/UX/evidence/status review passes with no open P1/P2/P3. That design was subsequently accepted for C1-M source/tests as recorded above; source and native qualification remain distinct from acceptance. + +Current bounded client correction closes the owned rejected-String cleanup gap identified by C0 under the existing accepted lease privacy/deadline contract. It is a separate four-path correction, not a new credential source or C0 scope expansion. [The constructor-cleanup receipt](development.md#openshell-bearer-constructor-rejection-cleanup--october-20-2026) owns exact source, safe buffer tests, validation and fresh independent review. The correction now passes fourteen pinned locked/offline Rust gates: three focused constructor tests, 35 client conformance tests, 632 core, 703 default desktop and 384 no-default desktop tests, format/strict Clippy/builds and normal feature isolation. All 690 outside-owned files, lockfiles, compiler pin and C0 source/tests remain exact. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) final source/evidence/status review passed with no P1/P2/P3; source/build evidence does not qualify real native input or connected support. Production Start, native input, real credentials/providers, OS vault and publication remain closed. + +Current OpenShell C0 source/tests are accepted: Jeff answered “Accept C0 source/tests.” The [accepted packet](openshell-observation-connector.md#first-source-packet-d2b-2b-c0-credential-selection-binding) opens seven named paths for exact selection/reference binding and acquisition custody within existing Host, using dummy credentials and synthetic TLS peers only. C0 source now passes all ten final pinned locked/offline Rust gates: 18 focused credential tests, 64 Host tests, 703 default and 384 no-default desktop tests, formatting, both strict Clippy modes, both normal builds and normal dependency-feature exclusion. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) final source/evidence/status review passed with no P1/P2/P3; all 687 outside-owned files, lockfiles and compiler pin remain exact. [The C0 receipt](development.md#openshell-c0-credential-selection-and-acquisition-custody--october-20-2026) owns exact commands, retained failed diagnostics and limits. Production Start, native prompts, OS vault, real credentials/providers, renderer mounting, database changes, foreign edits and publication stay closed. The separate constructor-cleanup receipt above owns the follow-on source correction; actual native acquisition and platform qualification remain required before real-secret mounting. UIC-1 acceptance remains pending; full cross-runtime support is unfinished. + +Current OpenShell mounting design now identifies the missing native-owned credential-selection/acquisition step and keeps session reads separate from later encrypted observation Save. The [proposed D2b-2b-C0 packet](openshell-observation-connector.md#first-source-packet-d2b-2b-c0-credential-selection-binding) names seven future paths, reuses existing Host pending/active and callback custody, and limits its tests to memory acquisition doubles composed with the real client against synthetic TLS peers. Production Start, native prompts, OS-secret access, renderer mounting and provider contact remain closed. Its proposed absolute selection/lease deadline does not renew at confirmation or acquisition. The [three-document design receipt](development.md#openshell-native-mounting-design--october-20-2026) owns research, validation and review; documentation/reference and whitespace checks pass, all 689 outside-owned files remain exact, and fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) proposal review passes with no P1/P2/P3. This earlier proposal was subsequently accepted as the C0 source/tests packet recorded above. Its design review alone did not create connected support. Durable observation schema/recovery, qualified ingress and the complete per-action operator record remain separate unfinished deliverables. UIC-1 acceptance is still pending; the closed native nonce must not be reused. + +Current OpenShell successful-read cancellation composition adds five real-client tests under the accepted synthetic bridge, with no production change. The [receipt](development.md#openshell-successful-read-cancellation-composition--october-20-2026) records actual successful protected/log RPCs before callback return, a positive publication control, primary-path Stop/close/exit cancellation, held drain, suppressed late observation, consumed consent and unchanged RPC ledgers. All seven pinned Rust gates pass: new five, all 46 host tests, 685 default and 366 no-default desktop tests, formatting and both Clippy modes. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source/evidence review passed with no P1/P2/P3; document/whitespace and 688-path preservation checks pass. Four exact test/document paths are owned; production host/client, lockfiles, compiler pin and unrelated work remain preserved. Cancelled is host-session handling after an actual read, not a provider denial or proof of no external effect. No real provider, credential, native GUI, foreign edit or publication. UIC-1 acceptance remains pending. Further connected support requires the separately proposed native-only credential/observation mounting and authenticated-ingress qualification; these tests do not create per-action decisions or a complete cross-runtime operator record. + +Preceding OpenShell host correction closes a reproduced prepare/close race within the accepted D2b-2a custody contract. The [bounded receipt](development.md#openshell-prepareclose-custody-correction--october-20-2026) records the failing pre-fix stale-pending/drain tuple, mutex-protected generation recheck and two deterministic regressions for both publication orders. All nine pinned locked/offline Rust gates pass: 41 focused host tests, 680 default and 361 no-default desktop tests, formatting, both Clippy/build modes and 32 existing synthetic-client tests. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source/evidence review passed with no actionable P1/P2/P3. Only two host source/test paths and three canonical records are owned; no renderer, client, Gate, store, dependency or foreign repository changed. Production Start remains unavailable. Old 46-case native evidence stays old-artifact evidence. UIC-1 acceptance remains pending. The subsequent successful-result/callback-cancellation tests are now recorded above; neither packet is an action execution or live operator workflow. Connected LNSAT/OpenShell support still needs separately qualified ingress, credential and runtime paths. + +Target-readback feasibility now separates native prompt content, resolved configuration and managed requirements. The [study refinement](target-loader-qualification.md#complementary-native-readbacks-and-the-next-gate--october-20-2026) identifies app-server configuration reads as candidates, not current integrations. No packaged standalone schema was found within the bounded installed-bundle JSON/TypeScript search; compiled strings and mutable docs do not establish the pinned wire contract. Before any reader implementation or target run, resolve exact-version schema and independently enforced startup isolation, then retain separate-process drift and capture gaps. Schema generation itself executes the target and is not accepted here. The [three-document receipt](development.md#target-readback-feasibility--october-20-2026) records passing documentation/whitespace/preservation checks and fresh independent read-only review with no P1/P2/P3; implementation/runtime qualification remains proposed. UIC-1 acceptance is still pending, the 46-case encrypted native nonce stays closed, and no target/provider/foreign-repository/publication action is opened. + +Current Rust alignment: Jeff [requested one toolchain](intent.md#unified-rust-toolchain--october-20-2026) matching VUSL's inspected `1.99.1` floor. Both workspaces, the root pin, seven-component validator, CI and active setup instructions now agree. The exact thirty-eight-path packet preserves lockfiles, dependencies and runtime/crypto behavior; only compiler-required equivalent condition/iterator/helper changes accompany the validator. Final frozen-source gates pass: core 629 tests plus format/Clippy/build; desktop default 678 and no-default 359 plus format/Clippy/build; preview 463 and validator regressions 7. Documentation (573 text files), CI static coherence, preservation (654 outside-owned paths and both lockfiles exact) and fresh independent review all pass with no actionable P1/P2/P3; the [receipt](development.md#unified-rust-toolchain--october-20-2026) owns exact evidence. All changes remain uncommitted and unpublished on `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; pre-existing unrelated work remains intact. The old native nonce is exactly cleaned; the native continuation below owns the new 1.99.1 artifact and remaining qualification. No VUSL dependency/adoption, target launch, provider call, foreign-repository change or publication. + +Current native follow-through after Rust alignment: all 46 parent cases now pass on the unchanged selected E1c-5e artifact, including final exact cleanup. The [accepted native receipt](development.md#e1c-5e-rust-1991-native-follow-through--october-20-2026) and its final matrix checkpoint own evidence. Nonce `4f2d3497f32b886e8dc5bca51bf2155e` binds source `f086d06312cb464ffbd4829706f5a1049265f263c6fd43bd98c01f007bba550c`, executable `7d0b526d4783f10cb10e56bc03d7c81e5690dd2fb5f0d2715058f4c90dfd8442` and plan `ba72790c56048b2fe5cb4de72b5c565d6b1f739033bcec72ce45e8bf1f56425b`, on macOS 26.0 x86_64. This covers actual authoring/revisions/composition/compile/draft-workflow save/reopen, held-read Lock/drain/independent Unlock/header probes, deliberate instruction export/refused unavailable archive, key-loss refusal, empty/populated conversion, cancellation, distinct-process parity verification, three adoption crash boundaries and interrupted real-key provisioning recovery. Final selection recovery preserves the earlier Reopened record and adds only Selected after fresh parity consent; provisioning recovery uses the exact existing key through separate inspection, empty initialization, recovery unlock and strict Restore. Both reopen the complete nine-category populated inventory only after ordinary Unlock. All 46 exact claimed children stopped; cleanup attempted only the eight registered test accounts and independently confirmed each absent. No test keys remain registered as present; encrypted test bytes and explicit plaintext fixture/export evidence remain retained. The nonce is closed and all one-shot permits consumed: do not resume it or combine other artifacts into its result. Actual captured dark/native states have no new UI findings, but three prior P2s remain: setup-Cancel continuity, unavailable backup advertising and missing-key recovery guidance. Light/compact/keyboard/assistive, Windows/Linux/arm64, package/release, target-load and connected-engine qualification remain open. Evidence: `/rangoon-e1c5e-native-rust199-retry-20261020`, especially `batch3/results.json`, `current-parent-results.json`, `native-current.json`, `key-custody-checkpoint.json` and hashed captures. Source, harness, limits and all 690 outside-owned inputs remain exact; only these two status documents changed during qualification. Final independent evidence/documentation review and proportional checks pass. Next take the bounded UI corrections and single-target loading proof under their own recorded scope. LNSAT/OpenShell stay independent and optional; full operator evidence across connected runtimes is not established by this storage matrix. Normal user data/keys, providers, foreign edits and publication remain closed. + +Prepared next source packet: [UIC-1 truthful workspace controls](development.md#uic-1-truthful-workspace-controls--proposed-next-source-packet) closes the three actual UI P2s with five named renderer/CSS paths, five named tests and the two status records. It reuses the qualified native Quit command, keeps generic recovery guidance honest and makes encrypted Data export availability match Rust while preserving selected additive Restore and valid Legacy behavior. This is proposed scope, not new source acceptance; no renderer or native source changed during preparation. Fresh independent proposal review passes with no P1/P2/P3; owner source/tests acceptance is pending. Existing E1c-5e nonce is closed and cannot be reused. The single-target load/readback milestone remains next after these bounded corrections; broad connected-engine support is still unfinished. + +Latest product priority, October 20: Jeff identified real target loading/effective configuration as the next distinctive milestone. The [target-load study](target-loader-qualification.md#target-load-milestone--october-20-2026) now separates exported, placed, target-input-observed, effective-configuration-assessed and enforcement-assessed evidence. GitHub confirms PR #51 and its exact-commit seven-job source CI; this is not VUSL integration or qualification of the mixed local source. Codex metadata/binary hashes remain at the October 16 pin. Version-matched immutable upstream source exposes auth/thread startup and only `prompt.input` output, so isolated startup and sufficient readback still need review before any target launch. Complete accepted encrypted-workspace qualification, then prioritize this single-target proof over more disconnected decoder/catalog breadth. UI refinement and the full independent-engine/operator-record objective remain intact. No target run, dependency, new adapter, VUSL/LNSAT edit or publication is authorized by this documentation priority; source/runtime qualification remains a separate proposed packet. The [receipt](development.md#target-load-milestone-and-public-evidence-recheck--october-20-2026) owns current evidence. + +Current E1c-5e: Jeff [accepted the ordinary-Lock handoff correction](intent.md#e1c-5e-ordinary-lock-handoff-acceptance--october-20-2026). Source now separates ordinary Lock from terminal retirement: classify Host atomically before source cancellation, retain only an exact completed idle non-effectful Handoff, and hold detached cleanup custody across synchronous closure before drop outside the mutex. Pending/busy/ambiguous and terminal states still retire and drain. Focused checks pass 7 Host and 18 bootstrap tests, including real-process Legacy verification. Fresh V2 production and V3 source/test reviews pass; final V4 moves only the inline test module and passes all ten pinned locked/offline gates (678 default, 359 no-default). Existing 69 renderer and 38 parent checks pass; all 683 outside-owned authored paths remain exact. Fresh independent V4 source/evidence review passes with no actionable P1/P2/P3. The corrected actual native Lock → drain → confirmed Unlock → reloaded Skills workbench/header phase now passes its strict parent oracle on fresh nonce `46ccc0e368c1b415b1808ce1264592c9` (47 events, required headers verified, clean exit). Historical opening remains unresolved: CUA guarded that action and the next full AX observation showed unexpected Merge; attribution is unconfirmed and Jeff was asked about exclusive control. No child is running; exact registered-slot cleanup now passed with slot_absent and parent exit 0 before the separately requested Rust alignment. That nonce is closed; remaining historical/full-matrix checks need a new immutable artifact after toolchain changes. A prior same-artifact run timed out at the unchanged 20-minute limit and was exactly cleaned; it is not qualifying evidence. Continue only the new immutable artifact and keep the full 46-phase matrix on that one source/executable/plan; old E1c-5d binaries cannot supply its missing phases. Windows/Linux remain release gates. No normal data/keys, providers, LNSAT/VUSL edits, dependency fetches or publication. Evidence and exact seven-path ownership: `/rangoon-e1c5e-source-20261020`; [development receipt](development.md#e1c-5e-ordinary-lock-and-startup-handoff-correction--october-20-2026). + +Next product focus, directed by Jeff: after the current storage/lifecycle qualification, review actual task usability, logic and ease of use across import, organize, compose, save and reopen. Preserve the original shell/workspace/inspector vision and security boundaries. Jeff explicitly requested cleaner fonts, dark/light matched sliders and dropdowns, responsive scaling and menus, a subtle left-to-right button highlight, soft border glow/light effects, color blending and graphic alignment. Root direction is a coherent agent operations studio with a shared explorer/task/inspector and consistent object, state and action patterns. Library/Build/Systems grouping is a design proposal over existing routes; Activity/Review require real qualified record sources and cannot imply live telemetry or approval routing. First proposed style ownership is only `preview/app.css` and `preview/visual-system.css`, using existing local fonts, theme tokens, readable type, unchanged hit targets, disabled/focus contrast, short interaction-only effects, reduced-motion/forced-color fallbacks and no dependency or controller/native changes. Browser 320/768/1440 light/dark plus actual native controls and task-state review are required before completion. A separate bounded behavior proposal owns `preview/composition-view.mjs` and `tests/composition-view.test.mjs` to align range-action availability and selection labels; existing model guards remain. No UI source is changed while the current native artifact is frozen; record exact accepted implementation scope before beginning either packet. + +Current E1c-5d source: [existing-key completion](development.md#e1c-5d-existing-key-empty-provisioning-completion--october-20-2026) now implements exact pending-CreateEmpty inspection and native InitializeEmpty, then separate Unlock/Restore. All ten final V8 source gates pass (668 default and 359 no-default tests); file-vault process regressions preserve original data and exact key with zero replacement writes. Fresh final V5 source/evidence re-review passes with no actionable findings. The bounded harness extension is source-qualified; native qualification found the ordinary-Lock handoff defect described below. Review its correction packet before building the next artifact and completing the disposable macOS journey. No GUI/OS-key/full-matrix pass follows from source tests. The independently reviewed extension now preserves those forty cases and adds six (46 phases/14 roots); 38 Python and 11 Rust plan checks pass. Review found and corrected a parser-capacity mismatch and its old overflow fixture; final V8 source checks pass and fresh V3 source/evidence review passes with no actionable findings. Native qualification uses a new artifact. Earlier V6 results do not qualify the subsequently corrected bytes. Jeff's [E1c-5d acceptance](intent.md#e1c-5d-source-and-disposable-macos-acceptance--october-19-2026) covers this work; normal data/keys, providers, LNSAT/VUSL edits, dependency fetches and publication remain closed. + +Current native E1c-5d qualification: all six new recovery phases pass their parent oracles on the final artifact, including existing-key InitializeEmpty/Restore, complete parity, distinct-process Verify and later Unlock. Cold cancellation/relaunch, busy-owner refusal and exact cleanup also pass. The full 46-phase UI journey remains incomplete. Original authoring navigation is unattributed; an identical-binary reproduction saved its workflow on the correct native route, then exposed ordinary Lock terminal-retiring startup state: native Unlock opens a client, but reloaded startup becomes unavailable. Read the [bounded correction proposal](encrypted-workspace.md#e1c-5e-ordinary-lock-and-startup-handoff--proposed-correction) and [native diagnostic receipt](development.md#e1c-5d-disposable-native-qualification-in-progress) before any implementation. E1c-5e now has separate source/test acceptance as recorded above. Both diagnostic runs stopped cleanly and exact disposable key cleanup passed; normal data/keys remain untouched. Evidence: `/rangoon-e1c5d-source-20261019/automation-investigation.json` and `native-fresh-progress-v2.json`. That diagnostic used frozen V8 source; the separately accepted E1c-5e now changes its three named native files and requires new artifact-bound evidence. Never infer human interference from a CUA guard, retry an ambiguous mutation blindly, or count incomplete native cases as qualification. + +Current language direction: [accepted RUSL retirement](intent.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026) is public through [PR #51](https://github.com/hypler-dev/rangoon/pull/51), main `9bd9be17d17fd8f778ec88f8e9b9f41df5c01dc4`. Old parser/fixtures remain inert experimental history until usable pinned VUSL core adoption, updated affected tests and independent cutover review. No reader/converter/alias/dual-profile or compatibility program without evidence. VUSL development stays upstream; native OpenShell/LNSAT connectors and provider-free local workflows remain independent. This documentation reconciliation does not publish active native/connector source. + +Current recovery preparation: [the durable-interruption receipt](development.md#e1c-5c-durable-interruption-and-recovery-qualification-preparation--october-19-2026) adds three fixed interrupted-copy/verification chains to the same qualification target (40 phases/13 roots). Pre-code review, 9 Rust/28 Python checks and all ten named native source gates pass. V1 review found two parent-oracle P2s; corrections pass expanded Python checks and V2 re-review closes both P2s; its P3 regression gap is corrected and final V3 independent source/evidence review passes with no residual actionable findings. Do not count synthetic source tests as native GUI/OS-key evidence. Continue unresolved Owner reconciliation and post-selection/layout cases before qualifying the complete journey on one artifact. No normal data/keys, provider/engine changes or publication. + +Latest fixed-case preparation: [the current receipt](development.md#e1c-5c-fixed-conversion-and-restart-qualification-cases--october-19-2026) records the shared 25-phase/10-root plan, synthetic empty/populated Legacy seeds, original-preservation checks, real consent-result observations and stronger parent workflow oracles. Focused native/Python tests, the complete named native source matrix and fresh independent V3 re-review pass. Continue fixed interrupted-copy/reconciliation and post-selection cases, then qualify the full native journey on one new artifact. No native GUI/OS-vault case or product-wide qualification follows from the preparation tests. OpenSSF practices accompany feature work; full assessment belongs in V1 finalization and does not displace mechanics. + +Current E1c-5c implementation: the [native/renderer mounting receipt](development.md#e1c-5c-encrypted-default-native-and-renderer-mounting--october-19-2026) records the shared deferred factory, encrypted default feature, C0/C1 purge service, delayed content controllers and fresh Managed-open/client handoff. The exact native test/build/lint matrix, portable/store gates, synthetic browser checks and fresh independent source/UI reviews pass. Explicit no-default-feature builds stay unavailable rather than opening Legacy. This is not completed native GUI/OS-vault qualification or a published default switch. Continue the accepted disposable macOS fresh/cancel/restart, Legacy copy, distinct-process verification and conditional recovery cases on the new artifact; then qualify Windows/Linux before release. Preserve the full independent-engine/operator-record objective. Normal user data/keys, providers, engine edits and publication remain closed. Earlier entries below are historical checkpoints; their unmounted/Legacy descriptions do not override the latest receipt. + +Native qualification now has one bounded real Cancel/exit observation on the new artifact: usable setup returns after Cancel, zero vault access/client, clean child exit, control-only residue. No provisioning/restart/conversion/recovery claim follows. Prepare the remaining fixed harness cases before qualifying the complete E1c-5c matrix on one selected executable. The disposable run nonce and immutable receipts are recorded under `/rangoon-e1c5c-mount-20261019`; no test child remains running and no test key was created. + +Historical E1c-5c design/acceptance checkpoint: [the native startup/recovery design](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate) passed independent design review after E1c-5b. The [design receipt](development.md#e1c-5c-startup-and-recovery-design--october-19-2026) owns that earlier acceptance/review state. Jeff accepted source and disposable macOS tests on October 19. Immutable custody, native copy/verify consent, conditional recovery and source mounting have since advanced through the latest receipt above; the next work is integrated disposable native qualification, not another pre-mount component. Preserve the E1c-5b seal and unrelated active work. Normal user data/keys, providers, engine edits and publication remain closed. + +E1c-5c component checkpoint: the [deferred-binding and startup-message receipt](development.md#e1c-5c-deferred-binding-and-startup-message-foundation--october-19-2026) records reviewed existing-only Owner acquisition, deferred Managed binding, pure local DTOs and unmounted renderer components. Named source regressions pass. Real startup routing, consent/recovery workers, renderer handoff and integrated disposable native tests remain unfinished; ordinary desktop still uses Legacy plaintext. + +E1c-5c native adoption custody checkpoint: the [native custody receipt](development.md#e1c-5c-native-adoption-custody--october-19-2026) tracks current closed-cycle/native-confirmation integration and tests. Plans bind to the exact native coordinator/control cycle, require fresh C1 purge acknowledgment, and cannot reuse old consent after cancellation. This is an unmounted component; native routing, conditional recovery, renderer handoff, encrypted-default activation and disposable GUI qualification remain required. Ordinary desktop remains Legacy plaintext. + +Operator-view follow-up: the accepted O2 path now rejects per-kind inventories that contradict its events, including same-total substitutions. The [correction receipt](development.md#o2-record-count-consistency-correction--october-19-2026) owns exact evidence and review. This is a renderer consistency fix, not provider ingestion or E1c-5c acceptance. + +Latest native checkpoint: [selected-artifact E1c-4 completion checks](development.md#e1c-4-selected-artifact-native-completion-checks--october-19-2026) records the resumed Q2/Q4/Q5/Q6/Q8 observations, exact cleanup and same executable as prior Q1/Q3/Q7. All test children stopped and both disposable slots are absent. Fresh independent evidence review completed with no P1/P2; its stale-status P3 is corrected. Do not infer full inventory, other-OS or release qualification from bounded UI observations. Earlier pending/free-window paragraphs below are historical. Ordinary desktop still uses Legacy plaintext. + +Next adoption design: [E1c-5](encrypted-workspace.md#e1c-5-ordinary-startup-and-legacy-adoption--proposed) covers first launch, existing Legacy data, verified conversion and restart. Overall design passed independent review. The accepted [E1c-5a source packet](encrypted-workspace.md#e1c-5a-startup-inspection-and-existing-source-capture--proposed-source-packet) implements unmounted metadata-only startup candidates, existing-only source capture, identity/drift checks and redacted diagnostics; [development](development.md#e1c-5a-implementation--october-19-2026) owns exact checks and independent review. Ordinary startup remains Legacy plaintext. Jeff accepted the exact [E1c-5b conversion/selection source and disposable tests](encrypted-workspace.md#e1c-5b-verified-conversion-and-durable-selection--proposed-source-packet) on October 19. It implements unmounted fresh-destination transfer, explicit empty-schema handling, the capture-to-Mixed custody transition, bounded cross-root journal, full equivalence and distinct-process verification. The [implementation receipt](development.md#e1c-5b-implementation--october-19-2026) owns current source validation and independent review. Normal data/keys, OS vault, UI/default switching, providers and publication remain closed. E1c-5c routing/recovery and platform qualification remain later. Keep capability-aware backup UX and encrypted portable recovery distinct. VUSL specification development belongs only upstream; Rangoon retains a future consumer-integration path. Preserve the separate reference branch and unrelated active source. + +Queued VUSL consumer follow-up, separate from E1c-5a: the upstream chat reports an independently reviewed candidate `docs/d0a-origin-reference-test-cases.md` and `conformance/d0a-origin-reference-case-plan.v1.json`, with plan SHA-256 `407d8afa835539765bb5809349a85b22816452fd00d0281103c5f9aa43ef907a`, 398 deterministic recipes (69 expected accepts, 329 refusals). These are specification expectations, not parser results. A later proposed Rangoon proof packet must verify the upstream commit/input identities and current Rust/reference entry points before running the exact candidate. No parser/harness change or production repin is accepted; do not repin to uncommitted upstream prose or develop the VUSL specification here. + +The later upstream planning handoff reports Jeff selected a VUSL-owned standalone core library consumed by Rangoon, with SDK/CLI/language bindings deferred and LNSAT independent. Its `docs/implementation-plan.md` “Safe D0a parser extraction” review snapshot is reported as `88307121b3b8326fa2dac3e1dd281f8399ab0cbb5f5e860c824e0e0473cfdf42`; it is uncommitted planning material, not a dependency pin. No parser moved. A separately opened Rangoon E0/E1 packet must inventory immutable current source/test/oracle identities, drift, workspace/toolchain/lock/dependency/license coupling and unchanged replay evidence before any extraction. Later VUSL E2/E3 owns standalone intake/parity; Rangoon E4/E5 owns actual consumer pin/cutover/rollback. Preserve one production grammar, the independent Python oracle, original manifest/case IDs/wire identifiers/digest domain and applicable diagnostic parity without inventing normative precedence. This queues owner coordination only; it does not expand E1c-5b or authorize parser tests, source changes or repinning here. + +D3a correction checkpoint: [pinned-evidence correctness correction](development.md#d3a-pinned-evidence-correctness-correction--october-19-2026) rejects contradictory authorization/attempt adapter joins and fixes native state labels against the unchanged `f669181a` pin. This is the accepted offline profile, not the proposed newer request-record decoder or a live connection. The development receipt owns validation/review state. The later E1c-5a source acceptance does not authorize ordinary encrypted adoption. + +Latest read-only LNSAT recheck: the [October 19 request-record candidate](lnsat-evidence-connector.md#october-19-request-record-candidate-compatibility-check) adds a separate source-shaped operator read with evaluation, replay/conflict and linked evidence. D3a remains on its existing pin; no decoder, connection or authority changed. The canonical development receipt owns exact local candidate identity, ten named function comparisons and remaining privacy/effect gaps. E1c-5a source was later accepted on October 19; this audit does not authorize its default switch or migration. + +Repository coordination checkpoint: user requested owner-repository rules. Reviewed docs-only branches are pushed in [Rangoon #52](https://github.com/hypler-dev/rangoon/pull/52), [VUSL #1](https://github.com/hypler-dev/vusl/pull/1) and [LNSAT #103](https://github.com/hypler-dev/LNSAT/pull/103); none was merged by this chat. They add owning-repository updates, verified remotes, isolated writer worktrees and version-pinned handoffs. Active LNSAT and native Rangoon source were untouched. Q3 header-probe design is recorded in the encrypted-workspace specification; header-probe source passed independent review. Actual required-mode native header and in-flight checks now pass on one recorded disposable executable; exact key cleanup and process exit are verified. Fresh independent native-evidence review passed. The [Q3 header receipt](development.md#e1c-4-q3-native-header-qualification--october-18-2026) owns evidence. Q1/Q7 now also pass on the identical executable. A later authoring attempt was stopped after a CUA user-change warning; Jeff confirmed using the window. It is not Q2 proof; its disposable key was cleaned and every child stopped. That historical wait and remaining-case list is superseded by the October 19 receipt above; it remains no authority for normal-startup cutover. + +October 18 plaintext-resolution checkpoint: accepted [E1c-4a](encrypted-workspace.md#e1c-4a-native-cancellation-and-storage-disclosure-correction--proposed) fixes native Cancel recovery and validated storage disclosure. Source checks and independent source review pass. Fresh disposable native run passes repeated setup cancellation/retry, full authoring with clean exit, observed restart recovery with exact compilation parity, missing-key refusal without replacement/fallback, and explicit instruction export with exact-byte verification. Basic Lock/purge/Unlock Cancel passes; **Q3 in-flight/late-result and explicit missing/stale-header checks now pass together on a new recorded executable; independent evidence review passed**. Q6/Q7 also pass fresh runs with the same source digest but a distinct rebuilt executable. Independent review caught the initial binary conflation; complete qualification still requires the full matrix on one selected artifact. The [current receipt](development.md#e1c-4a-native-cancellation-and-storage-disclosure--october-18-2026) owns hashes, exact bounds, cleanup, validators and final evidence-review state. All disposable keys/processes are closed; normal data/keys remain untouched. The [Q3 receipt](development.md#e1c-4-q3-in-flight-read-qualification--october-18-2026) owns the separate artifact and manual UI bounds. Next finish the remaining final-artifact matrix and review before normal-startup cutover or verified Legacy migration. Data backup controls also need a bounded capability-aware UX follow-up; Managed backup is refused, not implemented. Ordinary desktop remains Legacy plaintext. VUSL specifications now live independently at https://github.com/hypler-dev/vusl, pinned initial commit `b55e01955e9c59cd6ab652afe9a54c43589b09b8`, with the approved logo in its README. Rangoon reference-only commit `5cae421` is pushed on `codex/vusl-spec-reference` in https://github.com/hypler-dev/rangoon/pull/51, not merged. Preserve its compatibility pointers and exact wire identifiers when reconciling this dirty app worktree; do not recreate duplicate normative specifications. The earlier RUSL docs remain on main as `d23b2b7` until that reference PR merges. Native work remains uncommitted and unpublished. + +NX-06 accepted source and disposable macOS matrix now pass. Shared real native event coordinator, empty test context, six cases plus two repeats, default/encrypted regressions, client tests and compiler/normal-artifact isolation are verified. Tested artifact is x86_64 on an arm64 macOS 26.0 host; no arm64-binary or Windows/Linux claim. [NX-06 receipt](development.md#nx-06-disposable-macos-native-lifecycle-qualification--october-18-2026) owns evidence and remaining gates. Fresh source/evidence and final receipt reviews passed with no actionable P1/P2/P3. Work remains uncommitted; previous O2 work preserved. Earlier pending-acceptance entries below are historical. Production credentials/providers, encrypted mounting, LNSAT edits, publication and release remain closed. + +E1c-3 unmounted source integration and independent source review now pass under Jeff's instruction to resolve plaintext issues. The [reviewed startup contract](encrypted-workspace.md#e1c-3-encrypted-startup-integration-proposal--october-18-2026) supplies the production-shaped, unmounted encrypted constructor and real request-bound tests. Reuse existing Owner, Gate and close-cycle controls, then qualify the integrated disposable native application. The [source receipt](development.md#encrypted-startup-source-integration--october-18-2026) owns validation/review state. Normal startup, real vault/provider access and publication remain unchanged. + +## Historical continuation receipts + +The entries below preserve earlier checkpoints and their then-current restrictions. They do not override the current NX-06 result above; pending NX-06 acceptance/implementation statements are superseded. + +October 18 publication verified: PR #50 merged the reviewed `c132ea6` head to main `cb0e87849bef09e123567ac13debbb916df46ab4`; all 14 exact-head hosted checks passed. Windows checkout conversion was corrected without relaxing protobuf hashes. The app branch starts this continuation clean. The next [NX-06 exact proposal](openshell-observation-connector.md#nx-06-disposable-native-event-qualification--proposed-exact-packet) combines test-only source and disposable macOS native-event qualification, with six parent-observed cases and no ordinary workspace, keychain or provider. Fresh independent read-only proposal review passed after correcting explicit test-context isolation, the pinned empty-assets constructor and the unavailable-anchor fixture. Compiler probes and document/scope checks pass. Owner acceptance of the concrete source-plus-macOS-run packet is the next step; no native harness is accepted, implemented or run. The complete operator record remains the goal; this closes a native-lifecycle prerequisite only, not action-decision or cross-runtime evidence coverage. + +October 18 offline parity continuation: while NX-06 acceptance is pending, the bounded [O2 decision-state parity receipt](development.md#o2-decision-state-cross-language-parity--october-18-2026) covers a fixed synthetic decision window through the existing Rust inspectors and renderer. This is test-only regression work under the existing O2 contract, with no source/contract or provider change. Validation and fresh independent review passed: 145 Rust unit tests plus two cross-language parity tests, 25 operations Node tests, Clippy, formatting, document and scope checks. Conflict/unknown states stay visible and all six truth labels stay fixed. The new tests/fixtures and receipt remain uncommitted; they cannot close native qualification, O3 or action/effect evidence gaps. Latest language direction: [RUSL retirement](intent.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026) is accepted. RUSL has no active implementation roadmap. Preserve its inert experimental parser, exact wire values, fixtures and tests until a usable pinned VUSL core and updated affected consumer tests permit a separately reviewed cutover. No RUSL reader/converter/alias/dual-profile or backward-compatibility work is needed without evidence. VUSL specification/core work belongs only upstream; native OpenShell/LNSAT adapters and local capability workflows remain independent. The [current receipt](development.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026) owns validation/publication state. Earlier D0a/RUSL continuation entries are historical checkpoints, not current instructions. Historical October 18 naming checkpoint, superseded by the retirement direction above: **VUSL** replaced RUSL in product/specification prose at that checkpoint. Read the [guide](vusl.md), [conformance rules](vusl-conformance.md), [accepted editorial scope](intent.md#vusl-documentation-naming--october-18-2026) and [receipt](development.md#vusl-naming-and-mechanics--october-18-2026). The implementation still accepts exact `rangoon.rusl.*` identifiers; source, fixture bytes and historical evidence are unchanged. VUSL specifications are extracted to their own repository; Rangoon retains compatibility pointers and pinned offline vectors. The private strategic assessment is not repository content. The extraction receipt owns commit/publication state. This documentation packet stays separate from ongoing encrypted-workspace qualification in the application worktree. Historical entries below preserve their original dated names and states. @@ -8,6 +289,7 @@ Historical October 18 naming checkpoint, superseded by the retirement direction October 18 RUSL documentation publication: Jeff accepted public protocol documentation and commit/push. The [entry point](rusl.md), [conformance guide](rusl-conformance.md) and reconciled architecture/profile distinguish the public draft from experimental offline D1 and separate D2a/D3a projections. [Intent](intent.md#rusl-documentation-publication--october-18-2026) owns the exact documentation scope; the [receipt](development.md#rusl-public-draft-documentation--october-18-2026) owns validation/publication state. This packet is isolated from accepted E1c-4 and existing uncommitted encryption/native work; it does not replace the next encrypted-workspace qualification task or expand any engine/runtime permission. Resume that work from its original worktree and current accepted packet after publication. Historical checkpoints below describe earlier source states. + October 18 research/publication checkpoint: Jeff requested transcript-backed harness research and a separate [LNSAT handoff](lnsat-harness-research-handoff.md), then explicitly authorized commit/push/merge to main with refreshed README and documentation. Read the [research assessment](harness-research-20261018.md), [ordered completion track](plan.md#harness-value-and-portability-completion-track), [publication acceptance](intent.md#research-and-source-publication-acceptance--october-18-2026), and [current receipt](development.md#research-and-source-publication--october-18-2026). That receipt owns actual publication results; this paragraph grants no additional action. Existing local/encryption/native qualification remains first; HV-01 offline evaluation records are the next new product capability proposal. NX-06 preparation is preserved, but its native harness is not launched or accepted by this source publication. Production Start, real providers/credentials, LNSAT edits, activation, deployment and executable release remain closed. Historical continuation entries below retain their dated scope; the current source-publication authorization supersedes their publication prohibitions only for the reviewed accumulated application packet. October 18 native exit/admission correction: Jeff accepted the [source packet](intent.md#native-exitadmission-source-acceptance--october-18-2026). The shared native router now fences ordinary and closed-control admission before cancellation; its bounded waiter retains actual callback custody and leaves the fence closed on duplicate requests, spawn failure, timeout and retry. Default/encrypted desktop tests, Clippy, build, formatting and document/diff checks pass; fresh independent final review returned PASS with no actionable findings. The [source receipt](development.md#native-exitadmission-source-correction--october-18-2026) owns exact tests, scoped paths and remaining evidence. This supersedes pending-source-acceptance statements below only for this correction. Next prepare the separate disposable native event-harness packet. Production Start, real credentials/providers, native event harness, LNSAT edits and publication remain closed. @@ -334,7 +616,7 @@ node scripts/validate-review.mjs git diff --check ``` -For core Rust source changes, install Rust 1.85.0 with rustfmt and Clippy first, then use the validator that pins and prints Cargo, rustc and Clippy versions. A bare `rustup run` can still select Homebrew subcommands from PATH: +For core Rust source changes, provision Rust 1.99.1 with rustfmt and Clippy first, then use the validator that pins and prints Cargo, rustc and Clippy versions. A bare `rustup run` can still select Homebrew subcommands from PATH: ```sh node scripts/check-source-rust.mjs diff --git a/docs/customer-zero-gap-analysis.md b/docs/customer-zero-gap-analysis.md new file mode 100644 index 0000000..26b0218 --- /dev/null +++ b/docs/customer-zero-gap-analysis.md @@ -0,0 +1,106 @@ +# Customer Zero: source reconciliation and proposed delivery + +Status: assessment and proposed implementation direction, not source or operational acceptance. +Owner: Jeff. Authority: the [accepted product intent](intent.md) and October 22 clarification that Rangoon remains a general product with Jeff as its first tester. [Development](development.md#customer-zero-product-reconciliation--october-22-2026) owns evidence, review and current execution state. This assessment refines the [delivery plan](plan.md#internal-operations-first-delivery--october-22-2026); it does not create a second status ledger. + +The product remains a local-first Agent Operations and Engineering Workbench. Hypler supplies the first representative workloads, not public defaults or product-specific branches. Preserve Apache-2.0, macOS/Windows/Linux release scope, useful local authoring without providers, and independent LNSAT/VUSL products. The supplied Customer Zero plan is a proposal for review; its full feature list is not implementation authority. + +## Source baseline and classification + +Inspected application worktree: `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, including its retained uncommitted implementation. This is the application checkout, not the separate marketing site. The source audit reads the workspace manifests, content/workflow/store/CLI contracts, model/session APIs, operations/integration inspectors, desktop startup, OpenShell Host and command registration. It is not a fresh full security scan, test-suite execution or public-main parity check. + +**Implemented** means the behavior is present in inspected source. **Source-tested** refers to existing exact-source validation receipts, not a production guarantee. **Partial** means a useful component exists but the requested workflow is absent. **Proposed** means design only. **Unavailable** means no callable qualified operation is established. Prior test and native qualification limits remain in the development ledger. + +| Capability | Current source evidence | Customer Zero gap | +| --- | --- | --- | +| Markdown import and provenance | Implemented/source-tested: bounded analysis, immutable bytes, fragments and digests in [domain](../crates/rangoon-domain/src/lib.rs) and [import](../crates/rangoon-import/src/lib.rs). | Reuse as task input provenance; a digest is not permission to execute repository content. | +| Capability revisions, composition and compilation | Implemented/source-tested: [store](../crates/rangoon-store/src/lib.rs), [pure composition](../crates/rangoon-compose/src/lib.rs) and [compiler](../crates/rangoon-compile/src/lib.rs). | Reuse immutable source/recipe/artifact identity; target loading and effective configuration remain separately qualified. | +| Workflow authoring | Implemented/source-tested definitions, topology and revisions in [workflow](../crates/rangoon-workflow/src/lib.rs) and [records](../crates/rangoon-workflow/src/records.rs). Execution explicitly reports unavailable. | A workflow definition is not a running task, attempt, queue or worker lease. | +| Desktop and encrypted content storage | Implemented/source-tested and partially native-qualified. [Ordinary startup](../apps/desktop/src/workspace_native_bootstrap.rs) installs deferred Managed services when the encrypted feature is enabled; absent backend fails closed. | Complete OS/backend/setup/recovery/release qualification remains open. A new headless service needs its own key custody, storage schema and recovery contract. | +| Local/cloud model assistance | Implemented bounded advisory components: [packing](../crates/rangoon-model-assistance/src/lib.rs), [local client](../crates/rangoon-model-local/src/lib.rs), [cloud client](../crates/rangoon-model-cloud/src/lib.rs) and [memory-only sessions](../crates/rangoon-model-session/src/lib.rs). | No durable coding-agent runtime, fleet routing or reconciled usage/budget ledger follows from an advisory model session. | +| Operations inspection | Implemented/source-tested [offline records/projections](../crates/rangoon-ops/src/lib.rs) and [selected-file desktop inspection](../apps/desktop/src/operations.rs). | No qualified live collector, durable cross-runtime task history or outcome verification service. | +| OpenShell | Partial: pinned native read client, Host custody and minimized session view exist. Six current-artifact disposable macOS fixture cases passed bounded independent review. | No target-selection command or mounted finite-read screen; real-provider use and Windows/Linux input qualification remain open. Observation is not a coding-agent executor. | +| LNSAT | Partial: [offline evidence decoder](../crates/rangoon-integrations/src/lnsat_evidence.rs); the separate [engine port](../crates/rangoon-engine/src/lib.rs) still returns unavailable. | No qualified connected action authorization/receipt/reconciliation workflow in Rangoon. Do not move LNSAT implementation into this repository. | +| VUSL | Independent experimental core exists upstream; no dependency in the inspected Rangoon manifests. Rangoon's old parser is inert historical source. | A pinned consumer adoption remains separate. Neither VUSL nor a replacement language is a prerequisite for the first constrained task. | +| CLI and MCP | Existing [CLI](../crates/rangoon-cli/src/main.rs) supports analysis, instruction-bundle inspection and inert engine diagnostics. | No Rangoon task API, MCP server, task/worker CLI or persistent agent-session supervisor. | +| Durable task/worker service | Proposed in [application architecture](application-architecture.md#desktop-self-hosted-and-enterprise-evolution); not implemented by the inspected workspaces. | Logical task/attempt records, enrollment, runtime identity mapping, recovery and service lifetime independent of the desktop/agent client. | +| Fleet, budgets and SDK | Existing fleet/coverage and [R9 adapter](provider-interoperability.md#adapter-sdk-and-independent-foundations--october-20-2026) designs; no executable public SDK or fleet-budget controller. | Real inventory, limited runtime adapters, accounting and conformance tooling, followed by qualification of a second adapter. | + +There is documentation debt: the header of [workspace_source_access.rs](../apps/desktop/src/workspace_source_access.rs) still describes Legacy-only production construction, contrary to the inspected ordinary startup path. Record it for a bounded source-comment correction; do not use that stale comment to conclude encryption is test-only or claim all encrypted desktop behavior is qualified. + +## Required architecture changes + +### 1. Add a durable service mode over reusable application contracts + +Rangoon's desktop is currently the native application host. A task that must survive Codex closing needs an independently supervised Rangoon service or qualified external runtime, not an MCP request or desktop window holding its only state. Extend the modular architecture with reusable application use cases and thin UI/CLI/MCP adapters; retain one logical task authority. A service process restart may require reconciliation: durability is not a promise that every task continues uninterrupted. + +Start with one controller and one isolated worker. Keep a separately versioned operational store and bounded artifact references; do not put unbounded logs/jobs into the content workspace's existing 64 MiB limit or network-share its SQLite file. The operational store's encryption, service-owned key custody, migrations, quotas, retention, backup and recovery need explicit tests. A headless process cannot silently inherit a desktop unlock or vault permission. Multi-controller shared metadata and high availability remain later measured needs; the first pilot does not require PostgreSQL, a new cluster or a hypervisor. + +### 2. Separate a task from its attempts, runtime jobs and effects + +Define versioned task identity and pinned input/scope/resource requirements, then distinct attempt identities, runtime-native job references, ownership/fences, deadlines, progress, artifacts and reconciliation. Reuse existing authored workflow/capability revisions as inputs and existing evidence concepts as projections; do not mutate either into a job queue. + +Submission must be idempotent for an identical caller-scoped key and payload; conflicting reuse is refused. Distinguish queued, assigned, starting, running, awaiting approval, cancellation requested, completed, failed, outcome unknown and reconciliation required. Define exact legal transitions before implementation. A cancelled request is not proof that a process stopped; lease expiry is not proof that an earlier attempt cannot still have effects. Do not promise distributed exactly-once execution. Unknown consequential outcomes cannot be retried or moved to another worker automatically. + +### 3. Integrate one execution runtime before building scheduling infrastructure + +Rangoon can own task priority, eligible worker/resource/privacy constraints and placement preference. One selected runtime owns physical dispatch, native process lifecycle and its own allocation/lease mechanics. Preserve that ownership through an adapter; do not create two competing schedulers or treat a native job identifier as authenticated evidence without qualification. + +Evaluate Dagu against the exact pilot and a minimal OS-supervised runner. Dagu already documents [server queues/coordinator and distributed workers](https://docs.dagu.sh/overview/deployment-models) and a built-in [MCP surface](https://docs.dagu.sh/mcp/). Its generic run/edit tools must not become Rangoon's unrestricted agent API. Check cancellation, crash recovery, worker identity, isolation, result durability, API versioning, resource use and data handling. Do not assume a scheduler is a sandbox. Its [GPL-3.0-or-later and embedding terms](https://docs.dagu.sh/embedding/licensing) require distribution review; do not embed its Go API into an Apache-2.0 deliverable by default. Product selection and license suitability remain open, not legal conclusions or installation authority. + +Proxmox, OpenHands, LiteLLM and observability products remain optional candidates when a measured requirement justifies them. Avoid adopting an entire stack to run the first task. + +### 4. Implement two distinct agent integration directions + +**Agent to Rangoon:** a restricted MCP adapter calls the same durable application service as UI/CLI. Proposed operations are worker inspection, submission of an allowlisted task type, bounded status/results/artifact retrieval and cancellation/approval requests. Submission returns a task reference; a long MCP connection does not own execution. Caller identity, target/project scope, quotas, output limits and idempotency are required. No arbitrary command, path, credential, plugin install or self-expanded permission field belongs in the initial task API. + +Pin the actual MCP protocol/SDK/transport and advertised capabilities before implementation. Record the authenticated requester separately from a claimed agent name, worker identity and runtime/model identity; an approval request is not an approval or execution grant. Native task records introduce a new operational concern, not a way to authenticate imported O1/O2 observations. Reuse their provenance concepts only through a separately reviewed mapping. + +**Rangoon to an agent:** a provider-specific runner starts and supervises an explicitly selected coding-agent mode in an isolated workspace. Prefer a batch interface for the first bounded job; interactive sessions are later. Official [Codex CLI automation](https://learn.chatgpt.com/docs/developer-commands#codex-exec) documents JSONL batch output. The [Codex App Server](https://learn.chatgpt.com/docs/app-server) offers richer JSON-RPC session/event integration but is experimental and not supported for production workloads. The old [Codex MCP-server command was removed](https://learn.chatgpt.com/docs/mcp-server); Codex can still consume an external Rangoon MCP server. Do not confuse these directions. + +Claude documents [programmatic CLI/SDK operation](https://code.claude.com/docs/en/headless), with provider-specific events, controls and errors. Pin and test each runner separately. [Anthropic's credential rules](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use) distinguish end-user sign-in to its unmodified binary from a third-party product routing subscription credentials. Keep provider sign-in under the user's supported authentication flow; never copy session tokens between workers or promise unlimited subscription concurrency. Service-mediated API funding and user-operated subscription sessions require separate applicability checks. No paid run is needed to qualify task durability. + +### 5. Treat source review as code execution inside an isolation boundary + +An IZIOS engineering review is read-only with respect to production, but tests, build hooks and validators execute repository-controlled code. Pin a revision and file manifest, transfer an explicitly approved source snapshot without home directories, production credentials or incidental configuration, and create a disposable workspace. At admission, record an immutable validator-profile revision and digest, exact argv without shell evaluation, executable/toolchain identities, sandbox-policy revision, dependency lockfile and isolated cache-snapshot identities, and CPU/memory/disk/time/output limits. The worker verifies the same identities before starting; a changed or unavailable identity refuses execution rather than silently selecting the latest profile, binary, cache or policy. Dependencies/caches are read-only or materialized into an attempt-isolated copy; shared mutable caches cannot redefine an admitted execution. Failed prerequisites are reported as skipped/unavailable, never passed. + +Make isolation a fail-closed dispatch invariant, not a best-effort setting. Execute repository code under a dedicated unprivileged identity or qualified equivalent sandbox, separate from the service/worker supervisor. Do not inherit supervisor credentials, host home directories, incidental environment variables, file descriptors, credential stores, host/control-plane sockets, container-runtime sockets, cloud metadata access or unapproved mounts. Supply only the profile's explicit non-secret environment and scoped input/output handles. The supervisor's enrollment identity and control channel remain outside the task process. Default-deny task network access; any necessary exception names the exact destination, purpose, protocol and scope in the admitted profile and requires explicit approval. Missing platform enforcement or an unverifiable exception blocks dispatch. An ordinary process running as the operator, or a scheduler without those controls, does not satisfy this contract. + +Bound snapshot/archive size and file counts; refuse traversal, unsafe links, unexpected submodules or substituted inputs. Artifact retrieval uses scoped immutable references, never a caller-supplied host path. A process exit or scanner report is captured evidence, not proof that a production system was safe or unchanged. + +Source copies, caches, artifacts, subprocess logs and an external scheduler's files are separate confidentiality surfaces from the encrypted content database. Specify permitted storage volumes, encryption, retention and cleanup. Enforce task isolation before running code; imported instructions and model results cannot alter it. CZ-2 must run negative probes from inside the actual task process: attempts to read synthetic supervisor secrets, host files and inherited handles, reach control/container sockets or cloud metadata, escape source/output mounts, and exfiltrate synthetic source/artifacts through unapproved egress must be denied. Verify resource caps and termination of descendants, not just the initial process. Use canaries and disposable targets; never test against real secrets or production systems. Record actual observed denials and bounded retained evidence per OS/runtime; a configuration file alone is not proof. Redact and bound result text, treat it as untrusted UI input, and preserve original evidence references without publishing secrets. Production applications and database/payment/purchase/deployment operations remain outside this pilot. + +### 6. Add accounting before claiming autonomous cost control + +Create model/provider capability metadata and a task/attempt usage ledger that distinguishes provider-reported counts, gateway measurements, estimates, reservations and finalized charges. Use explicit units/currency/rate revisions; subscription quota is not API per-token billing. Local resource measurements and energy estimates have different evidence. Unknown usage stays unknown. Dispatch admission, concurrent reservations, retries, cancellation and late settlement require tests before claiming a hard spending cap. Provider-side checkpoints may limit overshoot only where actually supported. + +First run deterministic tests and scanners with no model call. Add one authorized model review afterward, then a second provider. Do not use paid inference to exercise scheduler concurrency or train a model to replace deterministic permission checks. + +### 7. Present an operational workflow in the existing shell + +Use Tasks as the primary Operations entry, with Workers and Usage as related views and a right inspector for the selected task. Keep Import/Skills/Workflows/Compile accessible. Show scope, source revision, attempt, worker/runtime, current phase, last observation, resource limits, cost basis and artifacts. Label unknown, stale, cancellation requested and unverified evidence explicitly. Topology is an alternate view of the same bounded records. Simple/Advanced changes detail, not permissions. Hostnames, inventories and Hypler-specific policies belong in private profiles, not public defaults. + +## Revised first acceptance workflow + +The proposed first value milestone is the supplied IZIOS source-review job, generalized as a project review task. CZ-2 first qualifies its durable service/runtime path through a CLI, without MCP or a model. CZ-3 then replays that qualified job through Codex and Rangoon MCP, completing the supplied Customer Zero demonstration. These are intermediate and full acceptance gates, not competing definitions of completion. OpenShell finite-read mounting may proceed in its own accepted lane when useful, but is not a prerequisite for deterministic engineering-task execution. Neither LNSAT nor VUSL completion should block an otherwise qualified constrained pilot; unavailable mandatory controls still block affected actions. + +1. A user selects a pinned, authorized source snapshot and immutable validator/execution profile. The CLI submits the bounded task for CZ-2; Codex submits it through Rangoon MCP for CZ-3. Both use the same application contract and durable task identity scheme. +2. Rangoon durably records scope, idempotency key, budget/resource admission and input identities before acknowledging submission. The selected runtime receives a distinct attempt with an exact eligible worker binding. +3. The worker revalidates the admitted source and execution identities, establishes the required isolation, then runs only the approved validators and captures bounded structured results/artifact digests. Identity drift or failed isolation refuses the attempt before repository code starts. Model review is optional, separately consented and separately accounted in a later slice. +4. The initiating CLI client disconnects in CZ-2, and Codex disconnects in CZ-3. Another authorized client retrieves the same task, attempt and results. A controller/worker restart test reconciles native state rather than fabricating completion or resubmitting blindly. +5. The operator receives findings, test outcomes, measured resource/usage data, skipped checks, evidence references and remaining unknowns. Native completion, provider claims, local review and verified external effects remain distinct facts. + +Before accepting CZ-2, test duplicate/conflicting submissions; wrong scope/worker/revision; mutation of the admitted validator profile, argv, executable/toolchain, sandbox policy or dependency/cache snapshot between submission, dispatch and launch; disabled or missing runtime; denied required authority; worker/controller death; network partition; expired lease and late completion; cancellation before and during execution; disk/output exhaustion; hostile result text; missing/partial artifacts; and uncertain outcomes without automatic rerun. Prove the isolation denials above while the task code runs. Closing the initiating CLI must not lose the task. CZ-3 must repeat the complete submission/disconnect/retrieval path through MCP, including its identity, scope, malformed-request and result-boundary checks, before the full demonstration is complete. Production access and ambient secrets must remain absent. Every test names its actual OS/runtime and observed consequence; source fixtures do not establish the complete path. + +## Staging and decisions before source acceptance + +| Stage | Deliverable and gate | +| --- | --- | +| CZ-0: this assessment | Reconcile Customer Zero with existing architecture, inspect source, validate documentation and obtain fresh independent review. No runtime installation or new feature implementation. | +| CZ-1: durable task contract and runtime decision | Freeze task/attempt/state/error/storage contracts, immutable execution-profile identities and fail-closed isolation requirements above. Compare one pinned external runtime with a minimal supervised runner against the pilot. Specify exact source ownership, negative runtime probes, validators and operational exclusions before implementation. Do not add a second scheduler by convenience. | +| CZ-2: CLI-only deterministic job acceptance | Implement the accepted service/runtime/storage/CLI slice and prove one isolated job, persistence, CLI disconnect, restart reconciliation and cancellation. Prove actual sandbox/resource denials and refusal of post-admission execution-profile/input drift on the pilot OS. This is intermediate acceptance, without MCP, paid model, production target or public release. | +| CZ-3: full MCP demonstration and Customer Zero UI | Mount the same application contracts for Codex submission and task/results UI. Replay the qualified project-review job through MCP, including client disconnect/reconnect and full source-to-artifact history, to complete the supplied first demonstration. No separate MCP-only state machine. | +| CZ-4: heterogeneous workers and agent runners | Add a second OS worker, then bounded Codex/Claude or other independently qualified runners and measured accounting. Qualify SDK contracts using two reference adapters; preserve unsupported capabilities explicitly. | +| CZ-5: sustained use and release | Faulted synthetic concurrency, limited authorized provider runs and a 24-hour soak; production interfaces only under separate authorization. Preserve three-OS product, encrypted recovery, signed/distribution and standards-readiness gates. | + +Owner decisions still required: pilot controller/worker and runtime/backend; exact source/validator profile and transfer scope; operational store/key custody and artifact retention; initial identity/transport; whether provider funding is allowed; and acceptance of the exact first source packet. Hardware counts and GPU suitability remain unverified until inventoried and benchmarked. All new service, MCP, dispatch, worker, budget, plugin, live-provider, infrastructure, foreign-repository and publication work remains proposed. Existing useful local functionality is retained. diff --git a/docs/desktop-spike.md b/docs/desktop-spike.md index 7013536..4be9c83 100644 --- a/docs/desktop-spike.md +++ b/docs/desktop-spike.md @@ -4,14 +4,16 @@ Authority: [intent.md](intent.md). Experience acceptance: [product-experience.md ## Run from source -The portable analyzer/host workspace retains Rust 1.85. The native shell is a separate workspace, uses Rust 1.98, and pins released Tauri 2.12.1, tauri-build 2.7.1 and dialog plugin 2.8.1. It reuses the static Rangoon frontend without adding a JavaScript build tool or duplicating the Rust parser. +The portable analyzer/host workspace and separate native shell now share Rust 1.99.1, pinned by the root `rust-toolchain.toml` and both Cargo manifests. This raises the former 1.85/1.98 compiler floors to align with VUSL, without adding a VUSL dependency. The shell still pins Tauri 2.12.1, tauri-build 2.7.1 and dialog plugin 2.8.1. It reuses the static Rangoon frontend without adding a JavaScript build tool or duplicating the Rust parser. Install the relevant [Tauri native build prerequisites](https://v2.tauri.app/start/prerequisites/) for your OS: Xcode command-line tools on macOS, Microsoft C++ build tools and WebView2 on Windows, or the documented WebKitGTK 4.1 development libraries on Linux. Installing prerequisites is a developer action, not something imported instructions trigger. ```sh -cargo run --manifest-path apps/desktop/Cargo.toml --locked +cargo +1.99.1 run --manifest-path apps/desktop/Cargo.toml --locked ``` +Run `node scripts/check-source-rust.mjs --desktop` for pinned source validation, or `--check-config` for version coherence only. The validator never installs tools; use `--toolchain-bin /absolute/path/to/bin` for an already provisioned isolated toolchain. Source checks remain separate from native GUI and packaged-release qualification. + Choose `fixtures/contracts/AGENTS.md` from the native picker for the first test. The browser-only preview cannot invoke the native analyzer; its analysis page explains that state. No Node server or localhost HTTP API is started by the desktop app. Installer bundling is disabled. Current save/restart/open evidence: [native workspace reopen](screenshots/native-workspace-reopen.png). The branded [launch preview](../preview/splash.html) uses the same composition as the native startup overlay; it is labelled as a preview and does not simulate loading. diff --git a/docs/development.md b/docs/development.md index a6a54ca..2cf57e4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,7 +1,1432 @@ # Development status +## Full application source publication — October 29, 2026 + +Authority and scope: Jeff requested publication of all current Rangoon application work and explicitly selected GitHub main only. The [accepted intent](intent.md#full-application-source-publication--october-29-2026) opens source publication while keeping executable release, hosted deployment, live providers, normal data/vault use and foreign repositories closed. The preserved source worktree was based on `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; a separate publication worktree reconciles its authored changes onto public main `01423598cc212a5ad7f3bbefd213573f37efd55d`. Newer public RUSL-retirement and LNSAT request-record/inspection work is retained. + +Delivered source: encrypted-by-default startup with explicit setup/unlock, existing-workspace adoption and encrypted recovery-copy/restore; schema-5 instruction history with source lineage; native exit/admission, credential-custody and bounded session inspection seams; bounded explicit file/folder metadata selection; IDE-style Markdown review/find; retained skill drafts and exact saved-revision compilation handoff; refined local Operations inspection; pinned Rust 1.99.1 validation and updated documentation. The provider-independent local workbench remains the active product boundary. The old age-envelope experiment is retained as an unmounted standalone crate, excluded from active workspaces; it is not the SQLCipher recovery implementation and is not promoted into a supported backup format. + +Reconciliation and public hygiene: preserve the original dirty worktree; publish no ignored build output, application database, credential or raw native receipt. The machine-cutover symlink for `cloud-credential-entry.json` is not copied: its content matches the regular public capability file. A candidate-specific authored-file inventory verifies regular files and content digests rather than treating the original source inventory as proof. Newly published documentation replaces private absolute machine paths with neutral placeholders and removes empty duplicate retirement headings. The limited changed-text credential-pattern review found only two deliberate private-key header markers in synthetic source-review tests, with no key body/end marker; it is not a comprehensive secret certification. + +Experience evidence: the real renderer is exercised through the existing loopback-only synthetic QA bridge in a fresh headless Chrome profile, with reduced motion and external requests blocked. Source and synthetic-browser evidence remain distinct from the dated disposable macOS native receipts. Earlier CUA startup failed at its symlinked writable-root check; the existing Playwright/Chrome installation provides rendered evidence without changing Codex settings or installing a dependency. Initial QA-script failures were incorrect expectations about lifecycle readbacks, generic public error copy, the navigation selector and Lock confirmation; production behavior was not changed to satisfy those expectations. + +Validation on the reconciled candidate: + +- `npm run build:check`: PASS, 627 JavaScript tests plus syntax/visual-contract/vision checks. +- Pinned Rust source checker: PASS, workspace formatting, 740 tests (eight ignored) and warnings-denied all-target Clippy. +- Pinned checker with `--desktop`: PASS, formatting, 738 native-host source tests (four ignored), warnings-denied Clippy and development build without installers. This runs disposable source tests, not native GUI qualification. +- Standalone historical `rangoon-recovery`: PASS, pinned/locked/offline formatting, 19 tests including doctests, and warnings-denied Clippy using its previously populated isolated dependency cache. The default cache initially lacked `age`; no dependency was fetched. Cargo still reports the known future-compatibility warning for `proc-macro-error2`; retaining this excluded experiment does not promote that dependency or recovery format into the product. +- `python3 -m unittest discover -s tests -p '*_test.py'`: PASS, 104 native-qualification harness unit tests; no GUI/vault/provider operation. +- Synthetic browser checks: PASS, 12 cases in Chrome 156.0.8078.76, covering Skills and Compile at 320/768/1440 in dark/light, exact current/historical revision and keyboard focus, dirty-discard confirmation, failed read/retry, failed library with valid exact pin, navigation invalidation and Lock purge. No page errors or attempted external requests were recorded. Fresh independent rendered review passed. +- `node scripts/validate-review.mjs`: PASS, eight reference-image hashes, the historical brief, local Markdown targets and 637 authored text files. Intent metadata validation and `git diff --check` pass. Candidate inventory contains 236 changed/new regular files, no symlinks or deletions; all 247 original snapshot paths retain their starting bytes and the source index remains empty. All ignored tests remain outside the passing counts. + +Fresh independent native/source and UI reviews pass. Documentation review identified private absolute receipt paths, duplicate empty retirement headings and stale current-scope emphasis; those were corrected, and final documentation re-review passes with no remaining P1/P2/P3 findings. The public pull request and exact-head CI record the publication commit and merge state. Historical packet evidence remains dated; a source publication is not a current native artifact qualification. + +Security and standards impact: existing SQLCipher storage and OS custody remain native-owned; renderer selectors do not choose database paths, furnish replacement originals or grant execution authority. Recovery key files and intentionally readable source/export files retain their confidentiality disclosures. No new dependency is introduced during reconciliation. Pinned manifests/locks, source CI, synthetic adversarial tests and independent review support the existing ISO/OpenSSF development evidence track without asserting certification, runtime enforcement, supply-chain level or release readiness. Full platform custody/GUI, package signing/provenance and target-loader readback remain separate gates. + +Review ownership: root Codex controller, OpenAI, owns source reconciliation/integration and publication. Native `gpt_docs` handled bounded documentation reconciliation; independent `gpt_reviewer` and `gpt_ui_review` roles inspect the resulting native/source, documentation and rendered/UI evidence. Configured reviewer role pin is `gpt-5.6-terra`; actual serving identifiers are not exposed. No GLM transfer is used in this publication. Exact changed paths belong to the Git diff; private raw command logs and hashes remain developer evidence, not public artifacts. + +Next safe slice: qualify the new native folder-picker permission and fixture flow in a fresh isolated disposable artifact, then prove the complete local editing/compilation/recovery workflow before normal data. Windows encrypted startup/recovery is unsupported in current source; Linux GUI/custody, general target-loader compatibility, remote transport and live engine operations remain unqualified or unimplemented as documented. + + +## CW-1 saved-revision compile handoff — October 29, 2026 + +Authority: Jeff asks to keep working through the October 29 whole-app audit. The [bounded intent](intent.md#cw-1-saved-revision-compile-handoff-and-current-storage-status--october-29-2026) accepts exact saved-revision navigation and storage-document reconciliation. Repository `app-personal`, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; root owns implementation and integration. Exact fifteen paths, preimages, baseline, command logs and final review disposition: `/rangoon-continuity-20261029/owned-paths.json` and adjacent evidence. No prior unrelated source is included in this packet. The synthetic QA server was stopped after its browser startup was blocked; no test server is left running by this slice. + +Owned paths: `preview/skill-compile-handoff.mjs`, `preview/skills-view.mjs`, `preview/compilation-model.mjs`, `preview/analyze.mjs`, `tests/skill-compile-handoff.test.mjs`, `tests/skills-view.test.mjs`, `tests/compilation-model.test.mjs`, `scripts/qa-skills-interaction.mjs`, `README.md`, `docs/application-architecture.md`, `docs/reviewer-guide.md`, `docs/intent.md`, `docs/continue.md`, `docs/development.md`, `docs/product-experience.md`. + +Experience: Open in Compile continues from a saved skill without finding it again. Historical selection stays exact. A dirty current draft for that skill blocks either view, with return-to-current guidance; unrelated drafts remain intact. Pending/conflict/unavailable states explain the refusal. Failure stays in Skills, and successful navigation focuses the selected revision/profile area. Existing layout, controls and styling are reused. + +Technical/security impact: a new pure renderer helper supplies exact capability/revision selectors to the existing native read; the compilation controller validates returned identity before replacing stale context. Route/selection/lifecycle guards fence late results and duplicate requests. On first use, the same guarded handoff loads the bounded native library before opening the pinned revision; route entry then reuses that validated selection instead of reopening it. No authoritative saveability, native storage, crypto, IPC permission, dependency or provider behavior changes. There is no automatic compile/export/save/review/run. Source text remains in the same existing native-to-renderer boundary; the synthetic QA fixture records only fixed command/selectors. Existing ISO/OpenSSF development evidence requirements remain; no certification or runtime-security claim is added. + +Documentation: obsolete production-Legacy/plaintext-default language is replaced with current Managed-default source behavior, implemented explicit Legacy copy and encrypted recovery, dated October 25 disposable macOS evidence and remaining current-artifact/platform gates. Windows startup/custody/recovery is unsupported, not merely untested. Original instruction files, explicit readable exports and the separate unencrypted recovery key file retain their disclosures. Dated implementation receipts are preserved. + +Validation: focused handoff/view/controller checks pass 36/36; `npm run build:check` passes all 627 tests plus syntax/visual-contract/vision checks. `node scripts/validate-review.mjs` passes eight reference-image hashes, the historical brief hash, local Markdown targets and whitespace for 635 authored text files. The intent validator passes. Exact preservation compares 756 baseline paths against 758 current paths: only the fifteen owned paths differ, including two new files; HEAD is unchanged and the index is empty. No Rust source changed; prior native/Rust receipts are historical evidence, not rerun CW-1 checks. Fresh independent source/docs and UI source reviews pass after the corrections below. Producer: root Codex controller, OpenAI; serving model identity unavailable. Reviewers: native `gpt_reviewer` and `gpt_ui_review`, OpenAI, configured role pin `gpt-5.6-terra` at xhigh; serving model identity is not exposed. No GLM provider transfer was used. Source acceptance does not waive the blocked rendered gate. Actual browser checks are blocked: CUA failed during runtime startup because the configured writable root traverses ``, a symlink. No page was opened or rendered, and no native app/data/key was accessed. This gate remains pending; source tests cannot replace it. The first source review identified ambiguous dirty-draft handling in historical view; the guard and regression tests now refuse it for the selected skill while preserving unrelated drafts. Independent UI source review then found that idle-list route refresh reopened the just-selected revision. A guarded initial list and controller-owned route load remove that redundant read; the real controller/handoff regression asserts one initial list plus one exact revision read, failure preservation/retry and late-result refusal during either phase. A further availability review made the summary-list read best-effort: failed summaries remain visibly failed while an independently validated exact pin can open. If the pin also fails, the prior selection/stale gate and failed list state are retained. Explicit Refresh retries the library; route entry does not. This is source integration evidence, not browser hash/focus proof. An earlier `await` in a non-async click callback failed syntax validation; the handler was corrected to a guarded promise chain before the passing builds. + +Next: finish rendered checks, then a separate native qualification correction for BF-2c. Its disposable permission config and exact verifier omit the new folder-picker command; the runner also needs a manifest-bound synthetic folder and metadata/Lock evidence. No native permission or harness source is changed here. No normal data/keys/vault, providers, remote/engine operation, LNSAT/VUSL edits, dependency fetch, commit/push/merge/deploy/release occurred. + +## BF-2c native folder metadata workbench — October 27, 2026 + +Authority: Jeff says proceed after BF-2b toolchain qualification. [Intent](intent.md#bf-2c-native-folder-metadata-workbench--october-27-2026), [experience](product-experience.md#bf-2c-folder-metadata-browsing--october-27-2026) and [architecture](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) define this metadata-only native/UI mount. Repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Root sole writer; independent source/UI reviewers read-only. Exact 23 owned paths, startup, preimages, delta, failed attempts, command logs, browser evidence and review seal: `/rangoon-folder-ui-20261027/owned-paths.json` and adjacent artifacts. + +Owned paths are the two host inventory/export files; desktop source collection/main/admission tests/build/capability/generated command permission; renderer workspace guard, Agent files controller/view/app binding/refinement styles; three focused JS test files; synthetic QA server; five canonical intent/experience/architecture/continue/development records; and the separately recorded disposable recovery-fixture correction. The ownership manifest is the exact authoritative list. No manifest/dependency/lockfile, production storage/encryption, engine or foreign-project change. + +Experience: Choose folder adds first-position folder metadata to the existing paged library, with relative-path search, a separate Metadata only count/filter, observed size/mtime, compact partial details and Clear folder. Saved and selected content review remain available. Folder clicks/filter/page/clear make no native content read; explicit Choose files to inspect reaches the existing Markdown review via the native multi-file picker. Folder rows carry no content/hash/source identity or revision lineage and cannot be bulk-checked. Unknown filesystem mtime stays unknown; local listing time is not trusted audit time. + +Technical/security impact: one new local-main-window permission/command, `select_and_list_sources`, accepts only the existing workspace request context, opens a fresh folder picker and uses the same exclusive counted read-only source lane. BF-2a owns relative handle traversal; worker checks generation through the bounded loop and closes all root handles before returning. A conservative 2 MiB JSON budget rejects oversized windows before IPC; renderer independently checks actual UTF-8 response size, strict fields/path/name/counter/ordinal/partial-reason invariants. Native ordinals become fresh renderer-local keys, not persistent references. Lock/dispose clear data and reject late results. This is metadata disclosure after explicit native selection, not a grant to inspect contents, execute, save or contact providers. No cache/schema/key changes or new dependencies; existing ISO/OpenSSF/SLSA controls remain, with no certification claim. + +Validation: 66 focused JS tests and full `npm run build:check` pass 615 tests plus syntax/visual/vision checks. Pinned Rust 1.99.1 host tests pass 31 unit and five integration tests. Default desktop source tests pass 172 library tests plus one isolated subprocess test, 543 main tests and 22 doc tests (one library and three main tests ignored). No-default desktop tests pass 43 library, 342 main and 22 doc tests (one main ignored). Both default/no-default warnings-denied desktop all-target Clippy pass; default native build and touched formatting pass. Native command registration, generated permission and managed renderer-client header coverage are included. These are source/runtime test fixtures, not a launched native GUI, a signed package or three-OS qualification. + +A default desktop test first failed at `encrypted_recovery_tests.rs:103` with `StoreError::Unavailable` during synthetic source save. The same test failed in isolation under macOS's `/var` TMPDIR and passed unchanged with an isolated canonical `/private` TMPDIR. This identified a symlinked temporary-fixture path conflicting with existing no-follow storage behavior. Scope added only that test file before mutation: its fresh TestRoot now canonicalizes its own created directory, matching other native fixtures. Full original-environment desktop tests then pass. Production storage/encryption/no-follow code is unchanged; original failure and the controlled experiment remain in `desktop.log`, `recovery-isolated.log`, `temp-path-diagnostic.json` and `recovery-canonical-temp.log`. + +Synthetic browser evidence: final 1440/768/320 dark/light JPEGs have those exact widths by image metadata and 900px height; DOM metrics show no horizontal overflow and approximately 44px controls. Initial blank/clipped captures were rejected; explicit device-pixel clip coordinates at DPR 1.72 produce complete final frames. Only `final-*.jpg` and `final-layouts.json` support visual acceptance. Real browser actions prove metadata-only selection, path filtering, 50-row paging, partial details, quiet Cancel, Clear preserving saved records, separate explicit source inspection preserving folder context, and Lock refusing a held late response. No actual OS media settings, screen reader/touch or native folder-dialog activity was tested. + +Fresh source review corrected native aggregate-response bounds and complete root-label/path parity; fresh UI review corrected metadata being counted as actionable Unchecked and rejected invalid screenshots. Final dispositions/hashes are in the seal. Remaining: actual isolated native picker/Lock qualification and retained row-inspection custody before personal folders; Windows folder discovery unsupported; Linux/Windows GUI, persistent organization/history, remote transport and copy/apply/restore remain separate gates. No normal data/keys/vault, real native GUI, provider/remote/infrastructure/engine operation, foreign edits, dependency download, commit/push/merge/deploy/release. + +## BF-2b pinned toolchain qualification — October 27, 2026 + +Authority: Jeff asks to resolve the required-toolchain blocker. [BF-2b intent](intent.md#bf-2b-pinned-toolchain-qualification--october-27-2026) accepts compiler installation and validation while preserving BF-2a source, version pins and dependency locks. Repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Root owns installation/integration and four paths: `docs/intent.md`, `docs/application-architecture.md`, `docs/continue.md`, `docs/development.md`. Evidence/preimages, installation log, actual compiler identities, command receipts, preservation and fresh review: `/rangoon-toolchain-qualification-20261027`. + +The [official Rust release announcement](https://blog.rust-lang.org/2026/10/15/Rust-1.99.1/) confirms the exact existing pin. Installed through existing `/usr/local/bin/rustup`: `toolchain install 1.99.1-x86_64-apple-darwin --profile minimal --component rustfmt --component clippy --no-self-update`, with explicit official Rust distribution/update endpoints. No default/override command or project dependency update is run; rustup currently reports no configured global default. The install initially logged a timeout reading rustc's version; subsequent real probes and the pinned identity validator succeeded. This is x86_64 tooling under emulation on an arm64 Mac, matching the prior compiler target; it does not establish native-arm or three-OS behavior. + +Actual identity evidence is `pinned-core.log`: rustc/rustdoc 1.99.1, compiler commit `58cf8f9c35b355199727627d07ae34a4e2846d67`, Cargo 1.99.1, rustfmt 1.10.0-stable and Clippy 0.1.99 at that compiler commit. `tests/check-source-rust.test.mjs` passes eight negative/positive validator tests; its forged/nightly fixture output is not an installed-tool claim. The existing checker pins absolute cargo/rustc/rustdoc/format/Clippy subprocess paths, refuses wrappers and verifies exact identities. `CARGO_NET_OFFLINE=true` and the existing task build directory keep project dependency resolution offline; no `--ignore-rust-version` is used in BF-2b. Bare Homebrew cargo remains 1.98; use the checked runner rather than assuming PATH selects the project toolchain. + +Security/standards impact: a trusted official build tool is installed in local rustup custody. No application dependency version/checksum, native source, credential, data/encryption boundary or operation permission changes. Existing package/SBOM/provenance and ISO/OpenSSF release requirements remain. Source validation is neither a desktop package nor native enrollment, encrypted-workspace GUI or runtime authorization proof. The prior diagnostic-only receipt remains historical; this packet supplies new actual pinned evidence instead of relabeling it. + +Results: `CARGO_NET_OFFLINE=true CARGO_TARGET_DIR=/rangoon-audit-20261015/target node scripts/check-source-rust.mjs --toolchain-bin ` exits 0. Actual pinned checks pass workspace formatting, 705 tests with eight ignored across 60 suites, and workspace/all-targets Clippy with `-D warnings`. The separately pinned `cargo test -p rangoon-host --locked --offline source_inventory` passes all 13 inventory tests; desktop metadata resolves locked/offline. Eight validator tests, reference/whitespace review and intent/link checks pass. BF-2a's unchanged JavaScript 606-test receipt is reused, not rerun or counted as a new result. All five BF-2a native manifest/source/lock hashes remain identical. The original blocked seal and diagnostic logs remain intact; this new packet supersedes the toolchain block with actual pinned evidence. Fresh independent read-only review binds the final four-document delta, unchanged source and exact evidence in the final seal. Next: native folder-picker admission/lifecycle and opaque row-inspection mounting. No normal user data/keys/vault, native GUI, provider/remote/infrastructure/engine operation, LNSAT/VUSL edit, dependency upgrade, commit/push/merge/deploy/release. + +## BF-2a retained-root inventory backend — October 27, 2026 + +Authority: Jeff says proceed after RM-1 with native folder inventory. [BF-2a intent](intent.md#bf-2a-retained-root-inventory-backend--october-27-2026) and [canonical mechanics](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) own this host-only implementation. Repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Root sole writer; independent reviewer read-only. Exact startup, preimages, dependency/command evidence, failures, final hashes and review disposition: `/rangoon-root-inventory-20261027`. + +Owned nine paths: `crates/rangoon-host/Cargo.toml`, `crates/rangoon-host/src/lib.rs`, `crates/rangoon-host/src/source_inventory.rs`, `Cargo.lock`, `apps/desktop/Cargo.lock`, `docs/intent.md`, `docs/application-architecture.md`, `docs/continue.md`, `docs/development.md`. No renderer/IPC/native command/storage change. Experience: no visible folder button yet; the future Agent files library gains a real bounded metadata source instead of scanning or retaining every original in the renderer. + +Technical: a Unix root is opened component by component without following symlinks; root/child directory handles stay owned and pre/post identities match. Metadata-only stat observes regular Markdown files, without opening any file content, FIFO, socket or device. Names are exact relative display data; no absolute paths or device/inode identifiers are serialized. Cumulative partial reasons are distinct from traversal exhaustion and count budgets. Root rename/replacement cannot redirect a held owner. No atomic filesystem snapshot, durable file reference, authorization, remote sharing or revision ancestry is claimed. A later host mount must manage request admission, callback drain, retained content and previously delivered page purge. Windows returns unsupported; same-device privileged mount aliases and blocked-kernel-I/O isolation remain outside this implementation. + +Dependency/security/standards impact: promote only already present rustix 1.1.5 with fs feature in the target-Unix host manifest; preserve forbid-unsafe in our crate. Both lockfiles have only the host-to-rustix direct edge, with no version/package/checksum changes. Cached package SHA-256 matches `891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d`. No dependency fetch/install or new organizational security claim. Existing native admission, encrypted workspace, ISO/OpenSSF/SLSA and release requirements remain. Synthetic test names/metadata stay in disposable folders; fixed `/usr/bin/mkfifo` and a local Unix socket are test-only fixtures. APFS refuses creation of invalid UTF-8 filenames; that real-filesystem fixture is Linux-only. Other-device/loop branch tests modify internal test state; they do not qualify real mount confinement. + +Validation status: required `cargo test -p rangoon-host --locked --offline source_inventory` refuses the repo's Rust 1.99.1 requirement because installed Homebrew cargo/rustc are 1.98.0. A rustup inventory query attempted automatic pin synchronization but filesystem permissions stopped it before a temporary file/download; no retry/install or toolchain changes occurred. All later Rust commands explicitly use `--ignore-rust-version` for diagnostics only. They cannot satisfy the required pinned gate or release qualification. Exact logs retain initial sandbox Unix-socket/invalid-name fixture failures, the unavailable Apple rustix mkfifoat test compile, the Clippy portability-cast warning and final corrected diagnostics. A narrow unnecessary-cast allowance documents platform-dependent dev_t/ino_t widths; no general warnings exemption is added. Final available-compiler diagnostics pass 13 inventory tests within 29 host unit tests plus five integration tests (34 total); the full portable workspace passes 705 tests with 8 ignored. Warnings-denied host Clippy and touched formatting pass on the available tools. JavaScript build/visual/vision checks pass all 606 tests. Desktop metadata resolves locked/offline; that is not a desktop build or OS qualification. Reference/whitespace review and intent validation pass. All Rust test counts are diagnostics under the explicit version override, never a Rust 1.99.1 gate pass. Final exact hashes, independent review and required-toolchain blockage are in the seal. + +Next: required pinned-toolchain validation, then native folder selection/admission, opaque row inspection and full lock/cancel/drain mounting. No normal data/keys/vault, native GUI, provider/network/remote/engine operation, VUSL edit, database change, dependency download, commit/push/merge/deploy/release. + +## RM-1 offline inventory contract — October 27, 2026 + +Authority: Jeff requests implementation of the remote files/version/copy direction; [RM-1 intent](intent.md#rm-1-offline-inventory-implementation--october-27-2026) accepts this first seven-path shared metadata contract. Repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; existing dirty work and empty index preserved. Startup, preimages, ownership, exact delta, tests, performance and independent seal: `/rangoon-remote-inventory-20261027`. + +Owned paths: `preview/remote-inventory-model.mjs`, `tests/remote-inventory-model.test.mjs`, `tests/fixtures/remote-inventory.v1.json`, `docs/application-architecture.md`, `docs/intent.md`, `docs/continue.md`, `docs/development.md`. Root sole writer; reviewer read-only. The [canonical mechanics](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) freeze identity, operation, path, page/cursor, time, provenance, refusal and lifecycle semantics. This is an internal offline consumer profile, not a new independent language or exported service API. + +Experience: no UI change or new Connect button. The eventual file library can consume exact scoped pages without mixing host identities, confusing a terminal page with full coverage, or turning stale metadata into permission. Technical: JSON-only strict validation; atomic page acceptance; instance/generation-bound request custody; 50-row pages, 1000-record/64-page working window; exact relative Markdown names/digests/revision reports; lifecycle/clock/expiry purge. No remote source bytes or filesystem operations exist here. External revision IDs remain producer reports, not local revision ancestry or effective configuration proof. + +Security/standards impact: handles synthetic names/metadata only in memory, with no credentials/content/storage/network/dependency/build-privilege change. Scoped metadata and consent/deadline agreement are structural checks only, never identity verification or authorization. Explicit authenticated enrollment, OS root confinement, encrypted retained cache, real consent and target readback remain future owners/gates. ISO/OpenSSF/SLSA readiness records remain authoritative; no certification or runtime security qualification is claimed. The 1000-row cap limits a working view, not future server-side fleet capacity. + +Validation: `node --test tests/remote-inventory-model.test.mjs` passes 23 tests with table-driven hostile cases. `npm run build:check` passes syntax/visual/vision and all 606 JavaScript tests. `node scripts/validate-review.mjs` passes eight image hashes, historical brief, local links and 631 authored text files; intent artifact validation passes. Exact whitespace/links/hash preservation and independent disposition are recorded in the final seal. A finite Node sample accepted 1000 metadata rows across 20 pages (221,804 input bytes) in 55.16ms and copied its state in 5.07ms; these single-run pure-model numbers prove no network/native or million-request throughput. An added UTF-8 boundary test first used a fixture below the byte cap; its precondition failed, the fixture was corrected to exceed 128 KiB and the final suite passes. The failed log remains evidence, not a source defect. Early independent review identified infinite-empty-page risk, path grammar ambiguity, completeness conflation and strict-schema needs; the source now caps accepted pages, freezes path rules, separates coverage/window/freshness and rejects duplicate/unknown JSON fields. Native/UI/OS/network qualification is deliberately unrun for this unmounted model. Source-only completion does not mean remote files, version replication, apply/restore or deployment work. + +Next: retained native root inventory, then disposable authenticated read-only peer sharing; reviewed transfers depend on target-bound encrypted originals and reconciliation. Normal data/keys/vault, native app/provider/network/remote operation, LNSAT/VUSL edit, dependency install/fetch, commit/push/merge/deploy/release remain closed. No publication in this packet. + +## WF-1 in-file Find — October 27, 2026 + +Authority: Jeff requests continued work toward an intuitive workspace; [WF-1 intent](intent.md#wf-1-intuitive-in-file-review-search--october-27-2026) and [experience](product-experience.md#wf-1-in-file-find--october-27-2026) define this bounded local feature. Repository ``, branch `codex/personal-workbench-20261024`, startup HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, empty index and 221 existing dirty entries. Root is sole writer. Exact preimages, ownership, logs, browser checks, six screenshots, hash preservation and review seal: `/rangoon-find-20261027`. Compare packet preimages, not HEAD, to exclude previously recovered work. + +Owned paths: `preview/markdown-find.mjs`, `preview/markdown-review.mjs`, `preview/analyze.mjs`, `preview/workbench-refinement.css`, `tests/markdown-find.test.mjs`, `tests/markdown-review.test.mjs`, `docs/intent.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. + +Technical: the pure Find model reuses the bounded Markdown presentation parser. Literal searches map lowercase matches back to whole original code points and return at most 1000 UI-only offsets. DOM binding wraps text nodes with marks via document APIs, preserving syntax spans and original text without HTML interpretation. Typing repaints marks/status only. Navigation opens enclosing details and scrolls the source pane without moving input focus. The application captures same-file Find state before redraw and disposes listeners, query and marks on replacement, route exit or workspace purge. This is renderer presentation, not byte authentication, composition, saveability or authorization. No native/Rust/storage/schema/crypto/authority behavior changes. + +Validation: `node --test tests/markdown-find.test.mjs tests/markdown-review.test.mjs tests/agent-files-view.test.mjs` passes 39 tests after the reviewer-requested focus correction. `npm run build:check` runs syntax, visual-system, vision and full JavaScript checks; passes all 583 tests plus syntax, visual-system and vision checks. Synthetic real-browser checks cover query/case/wrap, folded code reveal, multitoken highlights with original line text unchanged, same-file filtering, literal HTML inertness, scoped shortcut, Escape, different-file reset, route cleanup and Lock removal. Six dark/light 320/768/1440 screenshots show no document overflow and approximately 44px Find controls. These synthetic browser checks do not prove native saves, OS screen readers, touch, actual media settings or three-OS GUI qualification. + +Finite Node sample: 229,988 bytes/10,000 lines, model construction 20.0ms, absent search 26.4ms, final-line match 13.1ms, capped 1000-match search 1.64ms, 1000 navigation moves 0.85ms. These single-run model timings exclude DOM/native costs and are not an SLA. Full exact data is in `benchmark.json`. + +Fresh independent source/UI review and final hash binding are recorded in the seal. Source review found a P2 focus gap for Find/Close on matching redraw; explicit capture/restoration and a binding regression correct it. Final dispositions and exact hashes are in `review-seal.json`. Preserve unrelated dirt and empty index. No normal data/keys/vault, native app, provider/remote/infrastructure, engine edits, install/fetch, commit, push, merge, deploy or release. + +## FH-1 saved-file source-workbench handoff — October 27, 2026 + +Authority: Jeff requests continued work on missing functionality. [FH-1 intent](intent.md#fh-1-saved-file-source-workbench-handoff--october-27-2026) and [experience](product-experience.md#fh-1-saved-file-source-workbench-handoff--october-27-2026) accept this bounded local application/controller slice. Startup repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, empty index and219 existing dirty entries. Exact preimages, baseline hashes, delta, command/browser evidence and seal: `/rangoon-source-handoff-20261027`. Root is sole writer; reviewers read only. Prior visual/Markdown/controller work is preserved rather than attributed to this packet. + +Experience: saved files gain Open saved source beside source review, with a pending state, prerequisite guidance for temporary selections and meaningful busy/mismatch/removed/retry diagnostics. Success opens the correct Import source and its sections, then the existing section-to-Skills action opens/focuses a correctly prefilled form. Failure preserves file inspection and previous analysis. The action is local, explicit and reference-based; there is no automatic skill creation, local review, import/save batch or source mutation. Helper wording distinguishes temporary selected results from saved records without claiming identical content cannot already be archived elsewhere. + +Technical: the Agent files controller calls a bounded application callback with saved ID/digest/byte count, never source text/path. The callback uses existing analysis `openSnapshot`; only `{sourceId}` reaches native `open_snapshot`. Native `apps/desktop/src/main.rs` delegates to existing `SourceAccess.open_snapshot`, which resolves the ID through the existing exclusive request lane and backend with selection retained. Those Rust files are read-only and unchanged. The renderer now checks exact returned source ID for every saved open, plus expected digest/bytes for this handoff, before changing its analysis selection. That guard supports honest context; native remains responsible for source resolution, bytes, admission, storage and later mutation validation. + +The controllers refuse duplicates/pending work and use workspace/request epochs to reject late results. A pending saved-open marker records exact-source deletion, retains callback drain and refuses that result rather than making it the selected source. Observer-triggered purge before callback dispatch prevents acquisition. A route epoch blocks automatic Import navigation if the user leaves, including a leave-and-return round trip. Only known callback outcomes map to bounded messages; unexpected values, prototype-like keys and noncontract success values fail closed. Native/provider diagnostics and source payloads are not copied into arbitrary error text. + +Exact thirteen changed paths: `preview/agent-files-model.mjs`, `preview/agent-files-view.mjs`, `preview/analysis-model.mjs`, `preview/analyze.mjs`, `preview/workbench-refinement.css`, `tests/agent-files-model.test.mjs`, `tests/agent-files-view.test.mjs`, `tests/analysis.test.mjs`, `scripts/qa-agent-files.mjs`, `docs/intent.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. Existing parser, storage, composition, compiler/export, native commands/capabilities and other repositories are unchanged. + +Validation: focused `node --test tests/analysis.test.mjs tests/agent-files-model.test.mjs tests/agent-files-view.test.mjs` passes52 cases. Full `npm run build:check` passes syntax/visual/vision checks and573 JavaScript tests. Regression coverage includes exact ID-only IPC, metadata mismatch preservation, invalid reference/expected metadata, duplicate/pending/temporary/unavailable callbacks, failed/unknown outcomes, observer purge, lock/late open and deletion during open. An old retry fixture intentionally used a different returned source ID; it was corrected to request that distinct synthetic ID, while new negative tests assert mismatches stay refused. A new deletion-race test initially failed and drove the pending-source deletion marker; the failure is not counted as passing evidence. Intent/link/whitespace, exact preimage diff/hashes and unrelated-file preservation have their own receipts. + +Actual synthetic browser: a saved AGENTS.md opens its exact synthetic source with five native-shaped sections and focuses the Import title. Selecting Local checks and Create skill from section opens Skills, expands the source form, prefills Local checks and focuses title; no skill-write command is exercised. Existing native skill/compose/compile semantics are not requalified by this fixture. A held open disables its button and makes exactly one open call. Failed/mismatched reads stay in Agent files with the same inspection and enabled retry; temporary selection is disabled with accurate guidance. Hold→leave for Skills→release stays in Skills; hold→leave→return Agent files→release stays in Agent files and restores its available action, with no stale Import focus. Hold→Lock→release leaves the locked shell, with no source/file/action DOM revival. Six320/768/1440 dark/light views fit without page overflow and the new action measures44px. Screenshot/metrics/interaction receipts are under the packet evidence directory. Browser proof is synthetic renderer only; native current-artifact GUI, OS media, screen reader and touch remain unrun. + +Independent source review requested the explicit held-navigation regression; actual renderer checks cover both leave and leave-return paths. Final source/UI verdicts and exact hashes belong to `review-seal.json`; absent a passing seal closure stays open. Root/OpenAI Codex produces/integrates; fresh native OpenAI `gpt_reviewer` and `gpt_ui_review` are configured `gpt-5.6-terra` xhigh; runtime returned model IDs are not exposed. No GLM/Spark contacted. + +Security/standards impact: explicit local read/selection over existing saved IDs, with no renderer originals, arbitrary filesystem paths, new network/provider, credentials, plaintext storage, dependency or execution permission. Saved/temporary identity, digest and byte count remain exact; no fuzzy match establishes identity. Rust custody/encryption/admission/transaction boundaries remain unchanged, and a provider/classifier/UI decision gains no authority. No standards certification, production readiness, native qualification or broad coverage claim follows from these tests. Normal user data/keys/vault, native app operation, LNSAT/VUSL, infrastructure and publication remain untouched. Index empty; no commit/push/merge/deploy/release. Next local functional gap: bounded in-file search, then existing encrypted organization and reviewed batch-change/undo gates, with fresh native workflow qualification before normal personal files. + +## VR-1 compact reference-aligned workbench — October 27, 2026 + +Authority: Jeff asks to soften/compress the harsh/bulky UI and revisit the original reference screens. [Intent](intent.md#vr-1-compact-reference-aligned-workbench--october-27-2026), [visual contract](visual-system.md#compact-reference-aligned-workbench--october-27-2026) and [experience](product-experience.md#vr-1-compact-reference-aligned-workbench--october-27-2026) define the bounded UI-only work. Repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; exact startup/preimages/unrelated-file hashes are under `/rangoon-refinement-20261027`. Preserve all prior MR-1/CU-2/recovered dirty work and the empty index. + +Experience: compared the original Decompose image and structural Skills reference with the populated source-review fixture. Root integrated read-only design direction: calm sans navigation/task headers, softer dark/light panels and dividers, quieter continuous source, source-first density, no new decorative graphics or motion. Agent files has one compact header with actions/limits and one filter/count/advisory toolbar. Review-library rows omit repeated type labels but retain selected/saved groups, filename/date and finding state; type filters and inspector format remain. Full time/UTC/epoch remains in record activity/details and date titles. Markdown outline starts closed while original source/section/code groups remain open and navigable. + +Technical outcome: presentation and markup only. New `preview/workbench-refinement.css` is mounted before the canonical final shell stylesheet, preserving the existing vision gate and responsive shell ownership. Scoped route specificity refines shared header density; standalone startup/credentials/sample pages retain their own CSS. The only projection default change is initial outline disclosure. No model/controller/native parser/range/storage/crypto/provider/authority behavior changes. Existing source identity, advisories, errors, refusal messages and local state remain intact. Compactness removes framing/padding/redundancy while preserving approximately44px actual control targets and12px source text. + +Exact eleven changed paths: `preview/workbench-refinement.css` (new), `preview/analyze.html`, `preview/agent-files-view.mjs`, `preview/markdown-review.mjs`, `tests/agent-files-view.test.mjs`, `tests/markdown-review.test.mjs`, `docs/intent.md`, `docs/visual-system.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. New regressions cover header limits/Import reachability and unduplicated toolbar, compact date exact-time retention, and closed outline with all original source lines/navigation retained. Do not count this slice as new engine functionality. + +Measured before/after at populated1440CSS dark view: source panel top411.9→199.8px; code top751.4→339.7px; header153.6→65.0px; file row112.5→64.6px; source width622.6→651.9px. Original source/font size remains readable. `before-metrics.json` and `after-metrics.json` record exact geometry. All six320/768/1440 dark/light views have no horizontal page overflow and measured review/header/filter controls round to at least44px. Actual keyboard source-outline jump opens enclosing groups and focuses line6; search preserves a folded code group and input focus. Limits opens in flow at320px, fits the page and retains enabled Import. Shared Skills1440/768 light, Decompose1440 light and Import320 light spot checks fit; final Skills heading computes28px and padding15×18px. Import still displays its seven source lines. Explicit Lock removes source/highlight/review DOM. These are synthetic renderer observations, not native GUI/media/SR/touch qualification. + +Validation: focused `node --test tests/agent-files-view.test.mjs tests/markdown-review.test.mjs` passes28 cases. Full `npm run build:check` passes syntax/visual/vision checks and566 JavaScript cases in the sealed final run. Initial full check refused the new stylesheet as the last link; corrected mount order rather than changing the guard. The disposable fixture caches its HTML at startup, so final browser evidence was captured only after restart with the actual final links; the initial incomplete-style capture is not acceptance evidence. Shared-hero specificity was verified on a fresh Skills page. Independent UI review also rejected an unsettled tablet screenshot with a blank right region; it was recaptured after viewport/AX settling in a separate screenshot call. The final768CSS Skills image fills the content width, with body/shell/main759.3px after scrollbar and no overflow. Final logs, link/intent/packet-whitespace checks, exact preimage diff/hash preservation and reviewer disposition belong to `review-seal.json`; absent a passing seal closure remains open. + +Security/standards: no new data store, network, provider, credentials, dependency, animation framework or build privilege. Existing text escaping, source bounds and native authority remain unchanged. New tokens/selectors apply only to the workbench shell; reduced-motion/forced-color rules and visible keyboard focus remain. No claim of ISO/OpenSSF certification, production readiness or whole-app accessibility qualification follows. Normal data/keys/vault, native app operation, LNSAT/VUSL, remote/infrastructure and publication remain untouched. + +Root/OpenAI Codex produces/integrates; read-only design uses configured OpenAI `gpt_ui_design` (`gpt-5.6-terra` high); fresh independent source/UI examination uses configured OpenAI `gpt_ui_review` (`gpt-5.6-terra` xhigh). Returned runtime model IDs are not exposed. No GLM/Spark contacted. Final exact-hash review and remaining issues are recorded in the seal. No commit/push/merge/deploy/release. Next continue task-specific Workflows/management UI refinement, preserving the local native qualification gate before normal personal files. + +## MR-1 IDE-style Markdown review — October 27, 2026 + +Authority: Jeff requests agent/Markdown parsing and review like a code IDE with highlighting and grouped code. [MR-1 intent](intent.md#mr-1-ide-style-markdown-review--october-27-2026) and [experience mechanics](product-experience.md#mr-1-ide-style-markdown-review--october-27-2026) govern the bounded renderer slice. Startup repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, empty index and 214 existing dirty entries. Exact source baseline/preimages/diff/hashes, logs, browser evidence and final seal: `/rangoon-markdown-ide-20261027`. Root is sole writer; independent reviewers are read-only. Prior CU-2 and other recovered changes are preserved, not reattributed to this packet. + +Experience: Agent files adds a source workspace between a compact library and metadata/findings inspector. ATX heading outline, nested section folds, YAML frontmatter and backtick/tilde code groups, line numbers, language labels and lexical colors make instruction sets navigable. Outline/finding jumps open enclosing groups and focus the original display line. Matching rerenders retain fold/outline/scroll/focus; another file starts with its own structure. Import uses the same safe highlights with unchanged native fragment selection and source ranges. Original content is read-only and no tool code, Markdown HTML, image/link, shell or URL is activated. + +Technical: new pure `markdown-review.mjs` builds a bounded presentation projection, separate from Rust source analysis and native contracts. It handles heading hierarchy, fences/metadata, Unicode/BOM/CRLF, unclosed block notes, unknown-language plain text and explicit limit fallback. Maximum display source is 256 KiB/10,000 lines/16,384 UTF-16 code units per line/256 groups; the native parser's existing limits remain separate. Lines exceeding 2,048 code units or 512 hint tokens show complete escaped plain text with a visible syntax-limit notice. Review refusal is whole-view and explicit, never silent truncation or an authoritative parse diagnosis. Import uses its own explicit unavailable notice at those bounds. No persistent projection/content cache, native command, dependency, provider, storage/schema or authority change was introduced. + +Exact changed paths: new `preview/markdown-review.mjs`, `preview/markdown-review.css`, `tests/markdown-review.test.mjs`; existing `preview/agent-files-view.mjs`, `preview/agent-files.css`, `preview/analyze.mjs`, `preview/analyze.css`, `tests/agent-files-view.test.mjs`, `scripts/qa-agent-files.mjs`, `docs/intent.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. The QA helper supplies synthetic instructions with metadata, nested headings, fenced shell, checklist and inert link text. No normal files are read. + +Validation: focused `node --test tests/markdown-review.test.mjs tests/agent-files-view.test.mjs tests/agent-files-model.test.mjs` covers 42 cases; final `npm run build:check` owns syntax/visual/vision checks plus the complete JavaScript suite, with its exact count/result in `build-final.log` and the final seal. Tests cover escaped active content/labels, nonexecuting links, hierarchy/code-fence/frontmatter rules, malformed/unclosed input, numeric line jumps, all bounds, whole-view refusal, code and Markdown token caps below the line-length limit, native activeSpan rendering, matching focus/fold/scroll restoration and existing lifecycle/draft behavior. Intent/link/packet-whitespace and exact unrelated-file preservation are separate recorded checks. No Rust/native semantic change requires a new native compile claim. + +Measured finite Node benchmark: a 247,976-byte/10,000-line/200-heading sample parsed in approximately 24 ms and rendered to an HTML string in 46 ms on this development host. Adversarial 16,000-character bracket/quote lines used bounded plain highlighting fallback. `benchmark-final.json` records exact figures. These are sample string-processing results, not browser-layout timing, throughput SLA, load qualification or million-request capacity. + +Actual synthetic browser: 320/768/1440 CSS pixels in both themes, no horizontal page overflow and measured visible review controls rounding to at least 44px. Heading inside fenced shell stays out of the outline; frontmatter/code/nested sections are grouped. Keyboard folding emits no source command, outline navigation opens enclosing folds/focuses the correct line, search rerender retains folded code and search focus, a different file resets folds, advisory finding jumps to exact line 2, and the existing Back to files control remains. Import's native selected section still highlights lines 3–5 with shared syntax colors. Lock removes review/source/highlight DOM and visible instruction content. Existing model tests cover late reads; no new async projection exists. Six screenshots/metrics and `browser-interactions.json` record evidence. Native picker/current-artifact GUI, actual OS media emulation, screen reader and touch are not qualified by this run. + +Independent source review found a P2 silent fallback notice gap; fixed in both source review and Import with behavioral regressions. It also requested separate ≤2,048-character code/Markdown tests for >512 tokens; added both. Fresh final source/UI dispositions and exact hash checks belong to `review-seal.json`; absent a passing seal closure stays open. Root/OpenAI Codex produces/integrates. Reviewer roles are native OpenAI `gpt_reviewer`/`gpt_ui_review`, configured `gpt-5.6-terra` xhigh; returned runtime model IDs are not exposed. No GLM/Spark contacted. + +Security/standards impact: untrusted source remains escaped inert local text; all styles/class names/line targets are bounded local presentation values. No key/vault access, secret logging, new persistent data, telemetry, external dependency or execution privilege. Original files and export confidentiality retain existing boundaries; source review grants no trust, approval, authorization or target compatibility. Existing ISO/OpenSSF engineering requirements still apply; tests/agent review do not confer certification or production security. Normal user data, native app operation, providers, remote/infrastructure and LNSAT/VUSL remain untouched. Jeff's Terraform question is recorded as a proposed optional plan-inspection adapter with primary references and sensitive-plan handling, not implementation or execution authority. No commit/push/merge/deploy/release; index empty, unrelated dirt preserved. + +## CU-2 Skills editing and revision context — October 27, 2026 + +Authority: Jeff's keep-working request continues CU-1's intuitive edit/combine direction. [CU-2 intent](intent.md#cu-2-skills-editing-and-revision-context--october-27-2026) and [experience mechanics](product-experience.md#cu-2-skills-editing-and-revision-context--october-27-2026) define this bounded slice. Startup: repository ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, empty index and 207 pre-existing dirty entries. Exact preimages, source hashes, final delta and review seal: `/rangoon-skills-ux-20261027`. Preserve the dirty baseline; a diff against HEAD also contains unrelated work. + +Experience: Skills retains library/editor/inspector, compact heading, clear saved/draft/history/conflict status, saved/reviewed native timestamps and revision position. Source creation and technical provenance are disclosed on demand. Typed title/content update status/action chrome without replacing the input. Current drafts survive history and other-skill browsing. Discard has explicit inline confirmation and focus return; editing invalidates the armed context. Per-capability Advanced/original/saved disclosure state and per-source creation disclosure state survive ordinary navigation, then clear on lock. + +Technical: the controller's local discard verifies exact capability/base revision/title/content, rejects pending/historical/stale/wrong-skill context, resets only the current local draft and never invokes IPC. Conflict discard preserves `needsReload`; native create/save/review/open validation and persistence are unchanged. The pure view supplies UI hints only. The new loopback QA fixture runs the actual renderer/controllers with two synthetic skill records and a two-revision history; mutations explicitly fail, so it cannot establish native persistence or approval. Its trace stores command names only, not instruction payloads. + +Exact changed paths: `preview/skills-model.mjs`, `preview/skills-view.mjs`, `preview/analyze.mjs`, `preview/analyze.css`, `tests/skills-model.test.mjs`, `tests/skills-view.test.mjs`, `tests/term-help.test.mjs`, new `scripts/qa-skills-interaction.mjs`, `docs/intent.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. The glossary validator was adjusted after full validation exposed its outdated assumption that Skills had only one disclosure; it still verifies exactly one closed glossary and no creation action within that help panel. + +Validation: `node --test tests/skills-model.test.mjs tests/skills-view.test.mjs tests/term-help.test.mjs` covers 34 focused cases; `npm run build:check` covers syntax, visual/vision rules and 551 JavaScript tests. Initial sandboxed full execution had a loopback EPERM plus the outdated glossary assumption; neither is counted as passing. The corrected full check runs with loopback permission. Final command logs, intent/document/link checks, packet-only whitespace checks, exact source hashes and unrelated-file preservation are recorded in the final seal. No Rust/native/storage implementation changed; the prior native receipts remain their own artifact-bound evidence. + +Actual browser QA: 320, 768 and 1440 CSS pixels in both themes, no horizontal overflow, measured library/action/provenance targets round to at least 44px. Keyboard title/content editing updates status without focus replacement; Tab reaches enabled Save. History is read-only and Return restores the current draft. Switching preserves another skill's draft. Discard Cancel returns focus and keeps text; editing disarms; Confirm resets only selected text without a content-mutation command. Filters preserve hidden selection/editor/focus; Advanced disclosure stays with its skill. Synthetic conflict disables save/review, discard retains conflict, explicit reload reopens the gate. Failed library reload retains the editor. Pending open makes fields read-only/actions disabled; lock purges content/confirmation and a late result cannot revive the editor. Source A creation closed state survives list rerender; source B has independent default/open state; return to A retains closed. Explicit Create opens the source form and focuses title. `browser-interactions.json`, six screenshots and `browser-metrics.json` record observations. These are synthetic renderer results; no native save/review, OS media emulation, screen reader or touch qualification is claimed. + +Security/standards impact: source content and unsaved edits remain within the existing renderer lifetime; no new persistence, telemetry, external calls, credentials, crypto/schema, build privilege or dependencies. Exact identity matching controls local destructive UI reset, while native authority and transaction checks remain unchanged. Maps and confirmation references clear at lock. ISO/OpenSSF readiness remains the existing engineering track; these checks establish no certification, badge or production security guarantee. Normal data, keys/vault, providers, native GUI, infrastructure and LNSAT/VUSL remain untouched. + +Root/OpenAI Codex produces and integrates. Read-only design uses `gpt_ui_design`; fresh independent source/UI review uses `gpt_reviewer` / `gpt_ui_review`, configured OpenAI `gpt-5.6-terra` (high design, xhigh review). Runtime returned model identities are not exposed; role configuration is the provenance claim. No GLM/Spark contacted. Final reviewer findings/resolutions, exact hashes and disposition belong to `review-seal.json`; absent a passing seal, closure remains open. Unrelated dirt is preserved, index remains empty, and no commit/push/merge/deploy/release occurs. Next bounded experience slice: Workflows, followed by fresh artifact-bound native local workflow qualification before normal personal data. + +## UIC-1 disposable native smoke — October 24, 2026 + +Authority: Jeff explicitly requested native smoke tests for the encrypted workspace and full local workflow before using real data. Root owns this ledger and `docs/continue.md`, isolated build/evidence outputs, operation of the unchanged qualification runner, and the two explicitly reviewed test-fixture permission paths below. Ordinary product behavior stays frozen at the sealed UIC-1 source/UI result. Evidence: `/rangoon-uic1-native-20261024`. + +Run only the existing `cold-cancel`, `cold-relaunch`, `authoring` with required header/read-drain probes, `relaunch`, `export`, `lose-key`, `missing-key` and `cleanup` phases under a fresh nonce and immutable artifact. This permits only the harness-generated disposable workspace and exact isolated test Keychain slots, including intentional loss of that test key and exact cleanup; it does not permit selecting normal user data or keys. Verify setup/Cancel, source-to-skill composition/compilation/export, actual Lock/drain/Unlock, persistence across distinct processes, Data export/restore boundaries and closed missing-key guidance/Quit. Record missing coverage honestly. No provider/model/engine operation, foreign edits, dependency fetch, publication or release. + +Preflight requires source/artifact identity, unchanged harness and 38 synthetic parent-oracle tests, pinned offline Rust build and fresh independent read-only review before launch. Runtime evidence must pair actual native UI observations with case-specific receipts; a clean exit alone does not prove the authoring journey. Source/UI changes during qualification invalidate the freeze and require a fresh artifact/run. Existing ISO/OpenSSF custody, consent, output confidentiality and lifecycle requirements remain. The generated ordinary exports may intentionally be readable outside the encrypted workspace and must be explicitly selected/disclosed. + +Preflight stopped before launch: independent review found the isolated qualification target omitted the two existing Restore permissions and the synthetic backup filename used an extension excluded by the native picker. User's current full-workflow test request authorizes this necessary bounded test-fixture correction: Root adds only `apps/desktop/native-encrypted-qualification/tauri.conf.json` and its exact `PERMISSIONS` guard in `apps/desktop/src/native_encrypted_qualification.rs` to ownership, adding existing `allow-prepare-workspace-restore` and `allow-restore-workspace-backup`. Production capabilities/commands, restore semantics, data/crypto and case plan remain unchanged. Preserve the zero-launch initial artifact as invalid for this workflow; rebuild a new nonce/artifact and obtain fresh review before launch. Rename the exact synthetic archive to the supported `.rangoon-backup` extension. Existing 38 parent tests and native context negative checks are retained; actual Restore interaction is the behavioral regression test, not a duplicated static allowlist assertion. + +The fresh artifact completed all eight named phases with parent and child exit 0, eight distinct PIDs and actual chronological claim/receipt order. All 715 recorded source identities and the wrapped executable remained exact through runtime closure, before these final ledger updates. Native evidence is bound to nonce `633dd84492d64f5e43ca0a703c6fd452`, executable SHA-256 recorded in `artifact.json`, and the unchanged case-plan digest. The initial blocked zero-launch nonce is preserved separately and is not a passing run. + +Actual native experience: both cold cases showed fresh startup, native CreateEmpty Cancel, canonical encrypted setup/Details/secondary Quit, and clean button-driven exit with zero vault reads/writes and no content client. Authoring approved only the isolated test-key setup, imported the fixed 144-byte Markdown with a native picker, saved the source, created two skills, revised and locally reviewed one, merged two pinned revisions with inspected native preview and explicit acknowledgement, and committed the composition. Compilation correctly blocked unreviewed export; after local review and inventory refresh it generated a static candidate and wrote an explicitly selected plaintext instruction bundle. Managed Data hid unsupported archive Export, displayed the selected-input confidentiality warning and completed an explicitly selected additive synthetic Restore. Inventory was two sources, four skills, five revisions, two local reviews, and two recipes/applications/derivations. No agent/tool execution occurred. + +The authoring case held a real inventory read before OS key retrieval, then actual Lock confirmation purged the renderer and closed admission. Release occurred only after native Closing with no content client and unavailable request admission; the read drained and native state became Locked. Explicit native Unlock restored the inventory. Required header probes refused absent/stale clients without vault access and allowed the new client read. A distinct-process relaunch required fresh Unlock and retained the complete inventory/reviews/provenance. A separate process recomputed the identical candidate identity and read back the exported bundle as internal-consistency-only evidence with authority none; a one-byte-mutated copy was refused with `bundle_invalid`, while the UI labeled the prior inspection as previous evidence. + +Storage/recovery observations: the 77,824-byte isolated database had mode `0600`, no plaintext SQLite header and no visible synthetic source markers. These observations complement actual encrypted backend reads/writes; they are not cryptographic certification. Intentional removal of the exact nonce-derived test key led to recovery-required UI after explicit Unlock, with preservation/original-account/store guidance, no content client, zero replacement-key writes and no reset action. The encrypted database size and SHA-256 were unchanged through key loss and refused unlock. Actual recovery Quit exited cleanly. Final exact-slot cleanup confirmed absence, all eight child receipts completed and no qualification app remained in the CUA inventory. + +Validation: 38 parent-oracle tests, pinned offline qualification build, formatting, source/artifact freeze, exact four-path diff and documentation/whitespace checks pass. Fresh independent preflight review found and resolved the missing test-only Restore grants and wrong synthetic filename extension before any launch; it also required explicit eight-case chronology because cleanup alone is not proof of the preceding cases. Final independent runtime and actual-native UI review, final document hashes, preservation proof and closed-gate disposition belong to `/rangoon-uic1-native-20261024/review-seal.json`; an absent passing seal leaves closure open. Root/OpenAI Codex owns operations and integration; reviewers use the verified OpenAI `gpt_reviewer`/`gpt_ui_review` roles pinned to `gpt-5.6-terra` xhigh. No GLM/Spark was contacted. + +Acceptance is this bounded fresh macOS native local-authoring smoke, not all 46 historical cases, plaintext-to-encrypted migration, ordinary installer/profile adoption, Windows/Linux, full accessibility/media, live providers or whole-product security/release qualification. Original imported files and explicitly selected instruction exports remain readable outside the encrypted database; encrypted portable workspace-backup export remains unfinished. Before normal personal use, prepare the ordinary personal app/profile and verify it with noncritical copies, keeping originals independently recoverable. Normal user data/keys, LNSAT/VUSL, external providers, production, publication and release remain untouched. No commit, push, merge or deploy occurred. + +## UIC-1 personal workspace controls — October 24, 2026 + +Authority: Jeff resumed finishing Rangoon for his own use. This current request authorizes ordinary reversible repairs to the existing local-workbench experience; it does not accept every historical proposal or open provider, normal-data/key or release gates. Reuse the three observed findings and the bounded UIC-1 specification below. Recovery is sealed PASS in `/rangoon-personal-recovery-20261024/review-seal.json`; current implementation evidence belongs to `/rangoon-uic1-20261024`. + +Experience: preserve encrypted setup and Quit after Cancel, show only supported Data controls for the observed storage mode, and provide preservation-oriented recovery guidance. Root owns `preview/analyze.mjs`, `preview/workspace-lock-view.mjs`, `preview/workbench-shell.css`, the lock-view tests, new `tests/workspace-close-quit.test.mjs`, this ledger and `docs/continue.md`. A bounded worker owns only `preview/workspace-view.mjs`, `preview/workspace.css`, `tests/workspace-model.test.mjs` and `tests/workspace-view-purge.test.mjs`. The existing startup-view test is included only if needed for canonical-copy comparison. No other production source is owned. + +Technical/security: native Rust, IPC permissions, database/crypto/key handling, lifecycle authority, manifests, dependencies and engine/language behavior stay unchanged. Presentation uses only existing validated finite state; it never grants authority. Reuse the existing empty-body native Quit command and preserve startup-unavailable Quit. Pending, rejection, Lock/purge and fenced-document races must fail closed. No hidden external calls or private-source transfer. Existing ISO/OpenSSF development requirements apply; this correction establishes no certification or release readiness. + +Validation: focused tests for the five named UIC-1 test files, full renderer build check, reference/whitespace/ownership checks, rendered 320/768/1440 light/dark states with keyboard, reduced motion and forced colors, and fresh independent read-only review. Prior native results remain bound to their old artifacts. Any fresh disposable native run requires a new artifact and the unchanged existing harness; no new native qualification is inferred from browser tests. No normal data/keys/vault, provider/model, foreign-repository, install/fetch, publication, deployment or release action is opened. + +Scope correction before editing the build validator: `npm run build:check` failed with `Required control missing: workspace-export` because `scripts/validate-vision.mjs` required an Export control in the unavailable state. Root adds only that validator to ownership, replacing the obsolete universal-control assertion with mode-specific unavailable/managed/Legacy checks. The test must preserve disabled unknown-state actions and supported Restore rather than reintroduce unsupported export. No runtime/native authority scope changes. The initial failed check remains in the evidence. + +Source validation completed: five focused test files pass 47 tests; the complete renderer build check passes 483 tests, syntax, visual assets and vision checks. The initial obsolete-vision failure is retained separately. The final strengthened vision validator also passes. The pinned Rust 1.99.1 locked/offline ordinary macOS desktop build passes with the existing multiple-target manifest warning; no native application was launched. Recovery's portable Rust 637-pass/eight-ignored, format and strict-Clippy evidence is reused for unchanged Rust bytes, not reported as a new run. + +Rendered validation uses the actual workbench with a synthetic loopback fixture only: fresh setup, closed recovery and managed Data at 320/768/1440 logical pixels in both themes. DOM geometry shows no horizontal overflow; corrected complete captures are exactly the logical width by 900 pixels. Earlier captures were cropped by browser screenshot scaling and remain discarded evidence; only `*-complete.png` establishes the full matrix. Keyboard checks observed setup/secondary Quit focus, rejected Quit returning focus and fixed failure feedback, Space expansion of Details and Data refresh focus. Native Legacy behavior is not claimed: Legacy mode is covered by source/binding tests, while the existing full-page legacy fixture remained unavailable at startup. Reduced-motion and forced-colors rules receive static review; actual OS/media emulation is not covered. + +Root/OpenAI Codex integrated the changes. Bounded OpenAI `gpt_worker` (`gpt-5.6-terra`, high) produced only the four Data view/CSS/test files. Fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh) returned PASS with no actionable findings; final rendered `gpt_ui_review` disposition, exact source/artifact hashes, documentation checks and preservation proof belong to the final seal in the UIC-1 evidence directory. A missing final passing seal leaves source closure open. No GLM or Spark lane was needed or contacted. + +Next: qualify the corrected renderer in the previously specified disposable macOS native cases using a fresh immutable artifact and the unchanged harness. The prior 46-case matrix is historical and does not qualify this new renderer. Complete setup/Cancel, authoring, Lock/reopen, supported export/restore boundaries and missing-key/Quit before using normal personal data. Portable encrypted archive export, actual accessibility media qualification, Windows/Linux native qualification and connected providers remain unfinished. No source commit, push, merge, deploy or release occurred; restored historical work remains uncommitted and unrelated website/older-checkout changes remain preserved. + +## Personal-use source recovery — October 24, 2026 + +Authority: Jeff explicitly resumed Rangoon completion for himself. Root owns recovery/integration and the four canonical documents `docs/intent.md`, `docs/plan.md`, `docs/continue.md` and this ledger. This packet reconstructs previously recorded source without semantic changes; it does not add a runtime, integration, storage migration or activation. Evidence: `/rangoon-personal-recovery-20261024`. + +Startup found website branch `website-local` at `3cce5c8e4511b4f74192db012e981929df8e4fcc`, with substantial unrelated editorial work. Application `app-review` is on `codex/approval-duty-inspection` at `8140689303737a6bd163f5190a7cf6910596915b`, with 193 status entries and 580 authored file identities. Neither checkout was used as a destination or overwritten. The later `/rangoon-audit-20261015` lost Git metadata and 390 files from the recorded source inventory; this packet does not attribute the cause. Previous paths/qualification receipts remain historical evidence, not a usable checkout. + +Root created an isolated worktree from the locally available committed base `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, then moved it to durable `` on `codex/personal-workbench-20261024`. No fetch/install was needed. The October 22 focused-UI before-inventory plus final reviewed hashes define 714 exact source identities. Of these, 556 matched the fresh committed base, 133 were recovered from hash-matching remnants and 25 missing files from exact hash-matching saved preimages. All 714 identities pass recomputation. The older checkout's 580 authored identities and HEAD remain unchanged. No missing file was guessed or rewritten. Recovery locations and all expected/restored digests are recorded separately from the four new direction-document edits. + +Experience track: resume the existing source/skills/composition/export workbench for personal use; no UI changed during recovery. Technical/security track: restore encryption/startup/native/test sources exactly, preserve key custody/admission/recovery and provider boundaries, then run named validation. Initial discovery also found the custom Rust 1.99.1 toolchain outside rustup; use the existing pinned toolchain path and offline mode, without silently substituting an older installed compiler. Existing ISO/OpenSSF requirements remain; recovery is not security or native-release qualification. + +Named checks: all recovered-file hashes and original-checkout preservation, complete renderer build check, documentation/reference plus intent/plan artifact validation, pinned Rust configuration/tool identity and portable source tests/format/Clippy where local cached dependencies permit. No dependency fetch, normal vault/data/key, provider/model, LNSAT/VUSL or production operation is permitted by validation. Fresh independent read-only review checks exact reconstruction, four-document intent changes and final evidence. Final results/hashes/limitations belong to the recovery directory's review seal; a missing passing seal leaves the packet open. No commit/push/merge/deploy/release was performed. The next implementation slice must address an observed defect in the isolated encrypted local workflow, not add theoretical surface area. + +Validation completed: the renderer build check passed all 469 tests. Portable Rust 1.99.1 locked/offline workspace tests passed 637 tests with eight ignored, followed by formatting and strict all-target Clippy. The ordinary desktop formatting check and locked/offline macOS development build also passed; the application was not launched. Documentation/reference, intent/plan, Rust configuration and exact-path whitespace checks passed. Fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh; installed role pin checked) reviewed reconstruction and direction with no actionable findings; the final evidence review is bound to the recovery seal. These are source/build results, not GUI, vault, migration, three-OS or release qualification. + +## Focused workbench navigation and site brief — October 22, 2026 + +Authority: Jeff accepted focusing Rangoon on the differentiated capability workbench and OpenHands integration proof, requested UI simplification and a plan suitable for updating Rangoon/Hypler sites. Root owns exactly `preview/workbench-navigation.mjs`, `preview/workbench-shell.css`, `tests/workbench-navigation.test.mjs`, `docs/product-experience.md`, `docs/plan.md`, this ledger, `docs/continue.md` and new `docs/focused-workbench-site-brief.md`. Baseline/preimages, isolated patch, validator and rendered-review evidence belong to `/rangoon-focused-ui-20261022`. This is UI-only navigation/positioning, not technical adapter progress or site publication. + +Experience: Workbench → Compose & export → Review now precedes Advanced and Samples & prototypes. Labels distinguish imported source, authored workflow definitions, system coverage and evidence inspection. All twelve existing route IDs/destinations, one current item, brand destination, theme control, native workspace guard and compact drawer/focus behavior remain. The bounded OpenAI `gpt_ui_design` review recommended metadata-first changes, avoiding nested disclosure regressions; Root retained that limitation. Advanced/samples remain visible wide and use separators; later disclosure and populated-workflow refinements remain planned. No claim is made that this finishes the whole UI redesign. + +Technical/security: no IPC, native authority, storage, credential, provider, event collection or execution behavior changed. Reused native/core workflows remain intact. The new navigation regression checks every exact destination plus primary/secondary placement and absence of fake connection/run controls. ISO/OpenSSF readiness and existing encryption/release limits remain unchanged. OpenHands is under evaluation, with no Connect/Run action mounted. LNSAT/VUSL stay independent; no foreign repository/site edits. Site copy distinguishes implemented workbench components from planned effective-target verification. + +Validation: run focused navigation tests, the required renderer build/vision/visual/test checks, documentation/reference and plan validators, exact whitespace/ownership preservation, and rendered 320/768/1440 dark/light review with focus/compact navigation checks. The first static-preview launch was denied loopback access by the sandbox; the fixture-permitted loopback-only rerun starts without weakening its CSP. The initial build check also caught changed sample-label capitalization in two existing assertions; retaining the original names after a Sample prefix resolves it without weakening assertions. The fixture-permitted complete build check passes all 469 renderer tests plus syntax/vision/asset validators. Six browser readbacks confirm actual 320/768/1440 CSS widths in both themes, with no document horizontal overflow; an initial device-pixel scaling mismatch is preserved separately and not counted. Compact Enter/Escape returns focus to the summary, and compile/evidence links reach their existing unavailable-in-browser screens. Browser bitmap capture clips portions of the viewport, so retained images are partial visual evidence, not full native/populated-layout qualification. No motion was added; existing reduced-motion handling remains. Native/core suites are not rerun for this UI-only change. Fresh independent OpenAI `gpt_ui_review` must review exact source/diff, evidence and scope; final hashes/results/disposition belong to the evidence-directory seal. Missing passing seal leaves this packet open. Producer Root/OpenAI; installed design/review role pins are recorded in evidence. No dependency installation, real provider/model credential use, normal data/keys, native operation, custom executor/scheduler, commit/push/merge/deploy/release or external publication is opened. + +## OpenHands execution reuse comparison — October 22, 2026 + +Authority: Jeff requested a practical source-level Rangoon/OpenHands comparison, architectural faults/advantages and a hold on custom execution/scheduling pending the assessment. Root owns exactly new `docs/openhands-comparison.md`, `docs/plan.md`, this ledger and `docs/continue.md`. Baseline/preimages, pinned public sources and release metadata, isolated patch, hashes, validators and independent review belong to `/rangoon-openhands-comparison-20261022`. This is design/review only; a later isolated integration test is proposed, not run or implicitly authorized for credentials/providers. + +The comparison preserves Rangoon's pure transformations, transactional content authority, provenance and independent evidence inspection. SDK/Agent Server is the recommended first execution reuse candidate; the separate Automation service already owns scheduling/dispatch but remains beta and is evaluated separately. Public SDK v1.58.0 (`38b6cdcc825df69ffdfe9c50e6635705612575ba`) and Automation 1.25.0 (`850c66835a8176f30c6b0eaf75ca8b656191dad2`) source/release identities are pinned. Root inspected key contracts; bounded read-only OpenAI `gpt_reader` supplied additional exact-source evidence. No downloaded code or upstream tests ran. Provider support, native enforcement, interoperability and performance are not qualified by this comparison. + +Architectural/security impact: preserve one native execution owner, distinct local admission/native confirmation/external authority/effects, immutable execution identities, confined task processes and confidential external event/artifact storage. The exact native confirmation request has no expected action identity; accepting it invokes run. Direct tool execution bypasses loop confirmation. Thus the proposed adapter cannot claim atomic exact-action approval from native confirmation alone. Local Automation directories do not establish sandboxing; cancellation acknowledgement is not proof all processes stopped. These are scoped integration/architecture gaps, not a complete vulnerability audit. Existing ISO/OpenSSF, encryption and release requirements remain unchanged. + +Run documentation/reference, plan artifact and exact-scope whitespace/preservation validators; fresh independent OpenAI `gpt_reviewer` reviews final files and primary-source claims. Final named results and hashes belong to a passing review seal in the evidence directory; absent seal leaves this packet open. Runtime suites are not rerun for docs-only work. Existing dirty work stays exact outside the four owned paths. No source implementation, dependency installation, provider/model/credential use, normal-data/key/vault access, foreign repository edit, infrastructure operation, commit/push/merge/deploy or release is opened. Next prepare a bounded Codex-controlled synthetic task test, then separately authorize its implementation and any runtime operation. + +## Customer Zero product reconciliation — October 22, 2026 + +Authority: Jeff clarified that Rangoon remains a product he wants built out, with himself as its first tester, and requested analysis of the supplied proposed Customer Zero plan. This authorizes source-based architecture/gap assessment and documentation, not that proposal's full implementation or operational scope. Root owns exactly new `docs/customer-zero-gap-analysis.md` plus `docs/intent.md`, `docs/application-architecture.md`, `docs/plan.md`, this ledger and `docs/continue.md`. Baseline, preimages, isolated patch, source evidence, validators and independent review belong to `/rangoon-customer-zero-audit-20261022`. All runtime source and unrelated work remain preserved. + +The assessment inventories content/provenance/revisions, composition/compile/export, workflow definitions, encrypted native startup, advisory models, operations inspection, independent engine boundaries, CLI and SDK gaps. Two bounded read-only OpenAI `gpt_reader` agents (`gpt-5.6-luna`, medium; installed role pin checked) supplied exact core/store/CLI and model/operations evidence. An earlier native-seam reader exposed a stale Legacy-only source comment; Root verified that ordinary startup actually installs deferred Managed services under the encrypted feature. The assessment records the comment debt without changing source or promoting native qualification. Root retains architecture, privacy, storage and authority judgment. + +The revised first value milestone is a generalized pinned-source engineering-review job that survives its initiating client, rather than a mandatory OpenShell read. Proposed additions are reusable durable application services, task/attempt records, one qualified runtime/worker path, restricted MCP tools and reconciled accounting. Existing authoring and evidence contracts remain inputs/projections, not a second queue or scheduler. Jeff's infrastructure is private pilot configuration; public product, Apache-2.0, provider independence, three-OS shipping and independent VUSL/LNSAT ownership remain unchanged. No new source implementation began. + +Primary documentation was checked for Codex CLI/App Server/MCP direction, Claude automation/credential rules and Dagu worker/MCP/licensing boundaries. Codex App Server remains an experimental integration candidate, while its former MCP-server command was removed; Codex still consumes external MCP tools. Dagu already offers distributed execution and MCP, so evaluate reuse before duplicating it, with explicit GPL/embedding review. These are documented capabilities and constraints, not installed or tested integrations. Account entitlement, provider funding, source-transfer permissions, runtime/backend selection and actual isolation remain undecided. No credentials, paid services, model processes, workers or infrastructure were used. + +Fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh; installed role pin checked) found three proposed-design gaps: insufficiently explicit worker isolation, a CLI/MCP acceptance sequencing mismatch, and unpinned execution-profile identities. The corrected proposal requires fail-closed unprivileged task isolation, no inherited supervisor secrets/handles/mounts/control sockets or metadata access, default-deny task egress with explicitly approved scoped exceptions, and actual negative probes. Admission and launch bind the immutable validator profile, exact argv, toolchain, sandbox policy and dependency/cache identities; mutation is refused. CZ-2 is explicitly intermediate CLI-only acceptance; CZ-3 completes the original MCP demonstration. These are design corrections, not claims of vulnerabilities in a running task service. Preserve the initial review/patch receipts; the revised patch and final review must bind the corrected bytes. + +Experience/security impact: task-first UI/CLI/MCP share future application services; status, cancellation requests, costs, observations and actual effects remain distinct. Tests/scanners execute untrusted repository code, even in a production-read-only review, so the pilot needs measured isolation, egress, resource, source/artifact confidentiality and recovery controls. ISO/OpenSSF and encrypted storage requirements still apply. Run documentation/reference checks, intent/plan artifact validation, exact scope/whitespace and fresh independent architecture/source-evidence review; do not rerun unchanged runtime suites or relabel old receipts as fresh. Final named results, hashes and a passing independent review seal in the evidence directory close this assessment packet; a missing seal leaves it open. Provider/production/key/vault operation, new feature implementation, dependency fetches, foreign edits and publication remain closed. + +## Internal operations-first architecture reconciliation — October 22, 2026 + +Authority: Jeff's [internal operations-first direction](intent.md#internal-operations-first-direction--october-22-2026). Root owns this documentation-only reconciliation in exactly `docs/intent.md`, `docs/application-architecture.md`, `docs/plan.md`, this ledger and `docs/continue.md`. Baseline, five preimages, isolated patch, validation and review evidence belong to `/rangoon-internal-ops-direction-20261022`. Existing source and unrelated work remain preserved. The accepted outcome changes priority toward Hypler's own supervised workloads, not the availability or authority of any runtime. + +The architecture reuses existing optional-provider ports, fleet inventory, deployment jobs, shared management-state proposals and operations projections. It does not introduce another scheduler, semantic contract, database or UI shell. The plan progresses from native qualification and one finite lab read to one supervised development task, measured costs, a second adapter and separately authorized portfolio operations. Placement preferences remain distinct from native scheduling; budget estimates/reservations/observations/final charges remain distinct. Proxmox/Nomad and proposed hardware roles remain candidates pending inventory, measurements and product/version/operation review. Commercialization remains possible without controlling the next milestone. + +A bounded OpenAI `gpt_reader` (`gpt-5.6-luna`, medium; installed role pin checked) identified the existing contracts and missing task/budget implementation; Root made the product/architecture decisions and wrote the records. Read-only local repository checks observed LNSAT `6741676496241a3cddf146d7dc28aa6c1a09860b` with one dirty entry and VUSL `78b5ae41c8c720badd1f2301e1eabd0d07a83d5e` clean. Their committed READMEs were inspected for product boundaries only, not their full working source or runtime behavior. LNSAT remains pre-release and VUSL's experimental core is not yet a Rangoon dependency; no new cross-product qualification follows. Public GitHub pages were consulted, but the VUSL public page/raw README could not be retrieved, so no public-main parity is claimed. No foreign file was changed. + +Experience/security impact: preserve task-first navigation, inventory/table plus inspector, exact per-adapter controls, freshness and unknown states. Existing encryption, credential custody, consent, redaction and execution-time authority gates remain controlling requirements. Internal use does not waive ISO/OpenSSF readiness, platform/release checks, production isolation or independent review. Named documentation/artifact/ownership checks and fresh independent read-only architecture/claim review are required for this packet. Source implementation, provider operation, normal data/keys, OS vault, production access, infrastructure changes, dependency fetches, foreign edits, publication and release remain closed. + +The initial generic artifact checks exposed an inherited intent-header metadata failure and a new non-enum plan Status value. The latter is restored to `proposed`; accepted priority remains in the linked intent rather than implying every future stage is accepted. The intent now has valid current header metadata, with the earlier acceptance block explicitly retained as history. Exact initial failures, final named validator outcomes, five-path hashes/preservation and fresh independent review belong to the evidence directory above. Completion requires its final passing review seal; a missing seal leaves this documentation packet open. Runtime suites are not rerun for this documentation-only change. + +## C1-M current-artifact native matrix — October 22, 2026 + +Authority: the previously accepted C1-M source and six disposable macOS cases. Evidence is `/rangoon-c1-native-matrix-20261022-v17`; the separate source/artifact preflight is `/rangoon-c1-preflight-20261022`. No runtime source, native implementation, deadline or attribution oracle changed. The locked/offline custom-target no-run build was refreshed; the exact unchanged C2a source/Host/desktop checks and helper/pin/runner checks were explicitly reused from the linked preflight receipts, not counted as fresh suite runs. The fresh preflight `gpt_reviewer` (`gpt-5.6-terra`, xhigh/OpenAI; installed pin checked) returned PASS without P1/P2/P3. + +The full six-case parent runner exited 0, all six children exited cleanly, and every case completed its fresh start challenge, exact nonce/PID/context/artifact-bound action correlation and terminal handoff. Accept-read made exactly one Health, PolicyStatus and Logs RPC against the synthetic local TLS peer; Cancel, queued Stop, open-input Stop, expiry and programmatic owned-parent close each made zero RPCs. Expiry completed after 120.7119 seconds under the original 120-second deadline. Ten completed CUA action calls observed the exact review contexts and native controls; four cases observed masked secure input. Parent-close is the programmatic owned-parent case, not a CUA close action or whole-application Quit test. Fixed dummy input and generated test TLS material were used; no credential contents or raw UI dumps were retained in the evidence sidecar. + +The closure verifies all 711 authored source identities, the original and wrapped executable SHA-256 `cd95a27662d850b4897c83f86c6f0e9042a86750bbbab92ee926817afe181c6a`, wrapper plist digest, contiguous native/controller records and six distinct nonces/PIDs. All children were reaped and the post-run CUA qualification-app inventory was empty before documentation changed. Fresh independent OpenAI `gpt_ui_review` (`gpt-5.6-terra`, xhigh; installed pin checked) returned PASS without P1/P2/P3 for these exact six functional fixture cases; Root accepts that bounded evidence. The independent review and controller disposition are in `independent-review.json`. Raw `results.json` intentionally retains `qualificationComplete: false`. + +This is current-artifact disposable macOS functional evidence, not rendered visual quality, complete keyboard/assistive-technology coverage, a mounted product task, real provider/credential/vault operation, Windows/Linux qualification, production security, release or V1 completion. Previous failed v14–v16 runs and their closed freezes remain preserved and are not counted. The next task remains a separately reviewed command/controller/inspector mounting packet over existing native custody and C2a summaries; no provider, execution or publication gate is opened by this result. + +## C1-M native qualification after C2a — October 21, 2026 + +Authority: Jeff's accepted [C1-M source and six disposable macOS cases](openshell-observation-connector.md#c1-m-native-reviewinput-and-actual-macos-qualification--proposed-source-packet), following the independently reviewed C2a readback source. This continuation owns only validation/artifact selection and two documentation paths: this ledger and `docs/continue.md`. Baseline and evidence: `/rangoon-c1-post-c2a-20261021`. No runtime source, native UI implementation, runner, dependency, normal workspace, key, provider or foreign repository is changed. Prior v14 remains failed with zero of six qualified cases; v13 remains historical, not qualification of the new source. + +Current C2a complete desktop suites, Host cases, strict Clippy, formatting, normal builds and feature isolation are reusable only after exact six-path/source and outside-owned identity checks against their final review seal. The preceding helper/native runner/pin and portable workspace receipts are reusable only for exact unchanged source; report reuse explicitly, not fresh test counts. Refresh opt-in qualification-feature compilation/Clippy, focused native/context checks and the exact locked/offline custom executable. Before GUI, require fresh independent source/artifact preflight with all 711 frozen authored file identities, selected original/wrapped executable and context identity. Native execution remains the original six closed cases with exact fresh action/start/return/terminal handoffs, generated test TLS and fixed dummy input, then separate independent actual UI/evidence review. Missing evidence leaves the gate open. + +Experience/security impact: verify actual native review, masked input, finite selected read, Cancel, queued/open Stop, immutable expiry and owned-parent close after the latest source change. No mounted product, credential vault, other OS backend, persistent observation, real target support or release is claimed. Root/OpenAI owns this protected qualification; fresh native GPT review is required. GLM/Spark are skipped for protected native/artifact fit, with no external payload. ISO/OpenSSF readiness remains separate. No normal data/keys, real credentials/providers, vault, LNSAT/VUSL edits, dependency fetch, publication, deploy or release is opened. + +Source/artifact preflight passed with fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) review; its immutable evidence is `review-seal.json` under the baseline directory above. The subsequent v15 and v16 native attempts remain failed with zero of six qualified cases. In `/rangoon-c1-native-matrix-20261021-v15`, the first child exited 70 without a native result. In `/rangoon-c1-native-matrix-20261021-v16`, actual native review and masked input were observed, and the first child recorded a completed observation with exactly one Health, PolicyStatus and Logs RPC to the synthetic peer, then exited cleanly with code 0. However, the controller did not complete the input-submit return correlation within its post-exit allowance; the parent refused attribution and exited 1. This result cannot qualify the case or substitute for a complete matrix. Do not weaken the native deadline or attribution oracle to count it as a pass. + +Both failed-run freeze closures preserve all 711 source identities and the exact original/wrapped executable. V16 also preserves the wrapper plist digest; its post-run CUA inventory contains no qualification app. `freeze-closure-failed.json` in each evidence directory records closure. No runtime source or runner changed during either run. C1-M remains open; historical v13 qualifies only its older artifact. Current security conclusions are limited to reviewed design and bounded source/synthetic evidence, not a completed security assessment, certification or production release. + +## OpenShell C2a bounded session inspection — October 21, 2026 + +Authority: Jeff explicitly accepted the reviewed [C2a six-path source/tests packet](openshell-observation-connector.md#c2a-session-inspection-source--proposed-next-packet). Root owns native lifecycle, privacy, integration and validation. Exact changed paths are `apps/desktop/src/openshell_host.rs`, new `apps/desktop/src/openshell_session_view.rs` and `apps/desktop/src/openshell_session_view_tests.rs`, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. Baseline, preimages, exact patches/hashes, command receipts and review belong to `/rangoon-c2a-session-view-20261021`. All 705 outside-owned existing file identities remain exact, including manifests, locks and the Rust pin; the two new source/test paths bring the authored inventory from 709 to 711. The index remains empty and HEAD is unchanged. + +Implemented source: `Host::inspect_session` admits only a current Managed request and captures phase plus its matching minimized result under Host-to-Active lock order. Active custody retains the immutable selected read kind. Final generation/cancellation checks suppress stale results coherently; a callback still draining reports Closing. Pending witness and original expiry are checked at the final phase boundary. Stop that wins afterward does not rewrite the already captured historical instant, while the next inspection reflects cancellation or unavailable custody. No lock spans provider I/O, toolkit dispatch, await or a user callback. The typed app-private session-view v1 declares unqualified provenance, no authority, unavailable execution, unknown action outcome, bounded/partial coverage and fixed omissions. Its encoder refuses output above 8,192 bytes without returning a partial prefix. Completed summaries expose only the accepted protected-check states, numeric policy versions/count, distinct returned-log/provider-total counts, or bounded watch kind/producer counts, continuity and deduplicated closed loss reasons. Absent and Unknown producers remain distinct. No native target, credential reference, identity, hash, raw timestamp or provider payload is serialized. + +Final pinned locked/offline validation passes: eleven new grouped session-view tests; all 85 Host/credential/session-view tests; complete default desktop suite with 724 top-level passing tests including 22 privacy doctests, plus one separately invoked child helper (four ignored); complete no-default suite with 405 passing tests including 22 privacy doctests (one ignored); desktop formatting, all-target warnings-denied Clippy and normal builds in both modes. Normal/build feature graphs exclude synthetic peer support, qualification features and Tauri unstable. The existing Cargo duplicate-source custom-target manifest warning remains recorded; no Rust warning was suppressed. Documentation/reference/whitespace and exact preservation checks pass. Portable core and renderer suites were not rerun because this packet changes neither surface; earlier receipts remain their evidence, not additional passes here. No ignored OS fixture is qualified by these counts. + +Tests cover all four selected read kinds and existing fixed errors, pending/active phases, expiry/stale precedence, poisoned or foreign custody, actual existing workspace-close purge, historical completed expiry, exact full nested JSON and every retained fixture target/reference/hash/time/token canary, malformed/bounded projection refusal, snapshot/Stop ordering, generation fencing, dropped inspection waiter and callback completion while Stop waits. Real OpenShell client callbacks use disposable synthetic TLS peers and exact allowlisted RPC ledgers; three repeated inspections per completed read add no RPC. Production Start remains unavailable. Earlier wrong package/compiler/import/assertion attempts and the sandbox-denied loopback run are retained, corrected and superseded by the fixture-permitted complete run; no assertion or peer case was waived. A later validator wrapper refused an existing evidence filename before running its focused command; unique reviewed receipt names preserve both histories. + +Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source/privacy/test review has no open P1/P2/P3. It identified and verified correction of two P2 gaps: pending expiry could change after an early phase capture, and initial privacy tests did not fix every nested output field and retained canary. Root also strengthened the Stop acquisition and dropped-waiter ordering proofs. Final six-path hashes, preservation, validators and independent evidence disposition belong to the same directory; a missing passing final review seal leaves that final gate open. Producer is Root/OpenAI; native OpenAI `gpt_worker` (configured Terra high) wrote only the new test file before Root integration. GLM/Spark were skipped for protected native/privacy fit, with no external payload or contact error. + +Experience/security impact: this prepares a safe readback contract for the later finite-read screen; it mounts no UI or CLI command and is not a public SDK or VUSL profile. Inspection obtains no credential and performs no network call. Existing production Start, consent, cancellation and callback custody remain authoritative. No new persistent storage, dependency, permission, credential source or execution authority is added. ISO/OpenSSF organizational and release evidence remain separate. C1 v14 remains failed with zero of six qualified native cases, and v13 remains bound to its historical artifact; C2a changes no such receipt into a pass. Windows/Linux native input and actual mounted target qualification remain unfinished. Normal data/keys, vault, real credentials/providers, LNSAT/VUSL edits, dependency fetch, publication and release remain closed. All edits are uncommitted. The next separately scoped work remains native/platform qualification and the mounted finite-read workflow; R9 owns the later adapter SDK, conformance kit and shared UI/CLI operation-contract direction. + +## Current-source C1-M qualification continuation — October 21, 2026 + +Current-source preflight passes: five helper tests, 713 default desktop tests plus one nested helper (four ignored), 394 no-default tests (one ignored), both desktop Clippy/build modes, helper and portable strict Clippy, formatting, eight pin tests, 45 runner tests and documentation/whitespace. The current 637-test portable workspace result is reused by exact runtime/test/fixture/manifest/lock identity, not counted as a fresh run. Normal dependency graphs exclude qualification/synthetic support. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) preflight review passes with no P1/P2/P3 and binds the frozen 709-file source, two documentation hashes and original/wrapped artifact SHA-256 `a3ad125282ed65e97f6b58f5a92b4a7aa289e2419306afff4b8d71efe7726cef`. This is source/artifact preflight only. + +The subsequent fresh v14 native matrix failed its first case and qualifies zero of six cases. Evidence: `/rangoon-c1-native-matrix-20261021-v14`. The controller observed the exact new native review and successfully selected Continue; the masked input was presented, but no input-fill or input-submit was issued before the child ended with code 70 after 124.046 seconds. The parent reports no timeout, cleanup failure or attribution-failure flag; stderr was present, and the exit-70 cause remains unresolved. There is no successful native result/exit receipt or completed controller handoff. The late attempted review-action return did not become a successful journal record. The parent is terminal and the post-run native inventory has no C1-M entry. All 709 frozen source identities and original/wrapped artifacts remained exact through termination. Preserve the failed capture and `freeze-closure-failed.json`; no deadline, oracle or missing return is waived. Earlier v13 remains its separate historical pass. Jeff's C2a acceptance arrived during this attempt and opens only its separately accepted source/tests packet; it does not turn this native run into a pass. + +Authority: Jeff's accepted [C1-M source and six disposable macOS cases](openshell-observation-connector.md#c1-m-native-reviewinput-and-actual-macos-qualification--proposed-source-packet), applied after the independently reviewed pending-state and operator-count corrections. This reuses the exact existing native flow, runner and six-case plan; it changes no runtime source or source scope. Root owns validation, artifact selection and these two documentation paths: this ledger and `docs/continue.md`. Baseline, exact since-v13 comparison, status, command logs and review belong to `/rangoon-c1-current-artifact-20261021`. Compared with v13, only four Rust source/test paths and three documents differ. Native input/FFI, credential acquisition, transport, runner, case plan, manifests and locks remain byte-identical. Earlier v13 remains historical artifact evidence, not automatic qualification of this source. + +Revalidate source and build the exact opt-in qualification executable before any new GUI launch. Reuse the current 637-test portable workspace receipt only after exact source-identity comparison; do not count it as another run. Check complete default/no-default desktop tests, helper tests/Clippy, strict portable/desktop Clippy, formatting, normal builds/feature isolation, the eight pin-validator and 45 runner regressions, documentation/whitespace and exact outside-owned preservation. Keep compiler output, test counts, original failed attempts and selected artifact hashes. A fresh independent read-only preflight assessment must bind the reviewed source and artifact. A built target or passing source suite is not a native pass. Any later six-case run needs a fresh full source freeze, disposable application identity/case nonce, exact intent/return/start/terminal handoffs, actual UI evidence and independent native review under the existing C1-M rules. Do not resume the old v13 processes or reuse their source/artifact/nonce receipts. + +Experience/security impact: verify the actual native review → masked dummy input → finite selected read after recent source fixes, retaining Stop, expiry and parent-close drain. No visual change or new capability is claimed. Test-only synthetic TLS and the fixed dummy marker remain the only permitted runtime inputs; no normal data/key, vault, real credential/provider, renderer mounting, persistence, execution, dependency fetch or foreign repository operation is opened. ISO/OpenSSF readiness remains separate from certification. Root is the OpenAI producer/controller; fresh native GPT review is required, while GLM/Spark are skipped for protected native/artifact fit with no external payload/contact. Final dated validators and independent dispositions live in the evidence directory; missing passing evidence leaves each gate open. C2a was pending during preflight and was subsequently accepted for its separate source/tests packet, as recorded above. Windows/Linux input, mounted connection and the full cross-runtime operator-record goal remain unfinished. No commit, push, merge, deploy or release is authorized by this qualification continuation. + +## Operator record-kind count consistency — October 21, 2026 + +Authority: the existing accepted O2 [exact operator-view contract](operations-local-window.md#exact-operator-viewv1-allowlist) and Jeff's continuing request to resume and address issues. This is an isolated consistency correction, not a new feature, schema, integration or source profile. Root owns semantics, implementation, tests and integration across exactly four paths: `crates/rangoon-ops/src/operator_view.rs`, `crates/rangoon-ops/src/operator_view_tests.rs`, this ledger and `docs/continue.md`. Baseline, preimages and evidence: `/rangoon-operator-kind-count-20261021`. The pending C2a source proposal and all native/renderer/provider/storage/dependency paths stay outside scope. + +The builder currently binds all inspectors to one source and validates decision buckets against four inventory counts, but does not compare all nineteen timeline record-kind totals to the decoded inventory. An internally inconsistent non-decision projection can therefore produce a DTO the renderer correctly rejects. This is a consistency guard for private stage data, not evidence that external callers can forge internal inspectors or obtain authority. The correction must reject a per-kind mismatch atomically using the existing fixed error, including equal aggregate event totals, while retaining valid output bytes and all authority/privacy labels. A real-pipeline control and internally corrupted, canonically rebound stage regressions must show the old failure before the guard is added. A reader's separate diagnostic-count concern was withdrawn: stage aggregates include richer snapshot/topology occurrences and cannot be inferred from per-event boolean issue markers; those semantics remain unchanged. + +Named validation: focused red/green regression, complete `rangoon-ops` and portable workspace suites, pinned Rust 1.99.1 formatting and all-target warnings-denied crate Clippy, existing operations renderer/model/parity checks, documentation/whitespace, exact outside-owned preservation and fresh independent read-only source/evidence review. The focused red run executes one test and fails because the old builder returned success; the guard then passes that regression. A second regression checks each of the nineteen inventory kinds independently, while the first covers fourteen non-decision substitutions without changing the event total. All real inspectors run before internal corruption is injected; stage canonical/digest linkage is rebound where appropriate, so refusal is not merely a mixed-source digest failure. Two initial test-only compiler mistakes are retained and corrected without exposing private fields or changing production ownership. + +The complete locked/offline workspace suite passes 637 top-level harness tests, including all 151 operations tests (149 unit and two unchanged golden-view integrations); eight ignored cases remain unqualified. The first sandboxed workspace run failed an unchanged Unix-socket fixture with `Operation not permitted`; the fixture-permitted rerun passes, with no assertion or unrelated source change. Rust 1.99.1 workspace formatting, all-target warnings-denied operations Clippy and all 28 existing renderer/model/parity checks pass. Documentation/whitespace and exact preservation of all 705 outside-owned identities are required for the final seal. The unchanged goldens establish byte-identical valid payloads; the JavaScript checks use existing fixtures and do not claim a native GUI run or connected engine. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) reviews the exact source, tests and evidence; final hashes, preservation, validator records and disposition belong to the evidence directory. A missing passing final seal leaves that review open. + +Security/standards impact: enforce existing renderer-safe count consistency without adding input fields, collection, storage, transport, identity, permissions, dependency/build privilege or authority. ISO/OpenSSF readiness remains separate from certification. Producer is Root/OpenAI; an OpenAI `gpt_reader` (configured Luna medium) supplied the bounded source inventory and withdrew its unsupported diagnostic-count concern. GLM/Spark are skipped for this exact protected contract correction; no external payload/contact. No native GUI, real credential/provider, vault, normal data/key operation, LNSAT/VUSL edit, dependency fetch, commit/push/merge/deploy or release is opened. Existing mixed dirt is preserved and the full integration goal remains unfinished. + +## OpenShell platform input design — October 21, 2026 + +Authority: the continuing support objective and existing three-OS native-input stage in [the connector plan](openshell-observation-connector.md#windowslinux-input-design--research-october-21-2026). This was design/review only, independent of the then-pending C2a session-inspection source packet. Root owns protected platform/credential architecture and exactly three documentation paths: `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. The C2a proposal body is frozen by SHA-256 and must remain unchanged. Baseline, preimages, research and validation belong to `/rangoon-native-platform-design-20261021`. No source, manifest, lock, renderer, normal data, key or foreign repository is owned. + +Primary Microsoft/GTK documentation and exact cached Tauri 2.12.1 source expose concrete design hazards: GTK dialog destruction need not emit response; Windows modeless keyboard handling cannot assume Tauri's privately installed accelerator hook; widget text limits can clip oversized input or be bypassed by programmatic text. The connector plan now requires independent destroy/drain handling and bounded readback that cannot accept a clipped credential prefix. Linux's candidate reuses Tauri's GTK 3 family with asynchronous main-thread UI. A dedicated Windows GUI thread is only a candidate pending trusted-parent lifetime, dispatcher, keyboard, DPI/accessibility and teardown proof; no backend is selected by inference alone. The pinned `windows` 0.62.2 and `gtk`/`gtk-sys` 0.18.2 binding sources are absent from this host's cache. No dependency fetch or target compilation occurred. Windows/Linux input remains unavailable. + +Named validation for this documentation packet: authored-text/reference/local-link check, whitespace, C2a body-hash equality, exact preservation of every outside-owned identity with empty index and unchanged HEAD, plus fresh independent read-only architecture/evidence review. Documentation checks pass 587 authored text files, eight reference-image hashes, the historical brief and local links; whitespace passes. All 706 outside-owned identities remain exact. C2a's complete heading range is identical to its preimage and the original body hash is reproduced. The initial preservation checker included the heading in a body-only hash; the corrected extraction retains that failure and changes no source, expected hash or acceptance assertion. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) design review found two P2 omissions: the worker-to-GTK completion bridge and exact Windows sentinel-buffer capacity. The revised proposal requires worker-only waiting with main-thread widgets/cleanup, and at least 16,386 wide-buffer slots including NUL with sentinel/full/unterminated refusal. Final validator results, hashes, preservation and independent disposition are retained in the evidence directory; a missing passing final seal leaves review open. Prior 713/394 desktop test counts belong to the preceding unchanged-source correction, not new platform tests. Security/standards impact: specify cancellation, input integrity and secret custody before adding a backend; no new collection, transfer, storage, permission, dependency/build privilege or execution authority. ISO/OpenSSF readiness remains separate from certification. GLM/Spark are skipped for protected native architecture; no external GLM payload/contact. No GUI, provider, credentials/vault, normal data/keys, LNSAT/VUSL edit, dependency fetch, commit/push/merge/deploy or release is opened. The full integration goal remains unfinished. C2a was pending at this design closeout; Jeff subsequently accepted its separate source/tests packet, as recorded in the current-source receipt above. + +## OpenShell pending-state readback correction — October 21, 2026 + +Authority: Jeff's continuing support objective and request to resume and address issues, applied to the existing accepted C0/C1 Host state contract in [the connector specification](openshell-observation-connector.md#states-and-failure-handling). This is an isolated correction to existing source, not acceptance of a new connection profile, IPC contract or source packet. Root owns protected native state logic, tests and integration; fresh independent read-only review is required. Exact five paths: `apps/desktop/src/openshell_host.rs`, `apps/desktop/src/openshell_host_tests.rs`, `docs/openshell-observation-connector.md`, `docs/continue.md` and this ledger. Baseline/preimages, ownership and named command receipts are in `/rangoon-openshell-status-20261021`. + +The previous Host poll collapsed both awaiting and confirmed pending reviews into `AwaitingConsent` and ignored pending expiry/generation when reporting status. Pending readback now checks the existing generation and immutable selection deadline, then reports the actual retained phase. Repeated reads cannot consume consent, construct a client, renew expiry or release pending admission. An expired review remains owned until Stop or the existing close path; a fenced generation takes precedence and reports unavailable. The existing active callback path and production Start refusal are unchanged. Three deterministic regressions cover correct confirmation/readback, expiry in both pending phases with retained custody, and workspace drain in both phases with explicit cleanup. No sleep or real credential is used. + +Validation passes: three new focused pending-state cases; all 74 existing-plus-new Host/credential cases; complete default desktop tests (713 top-level tests including privacy doctests, plus one separately invoked child helper; four ignored cases remain unqualified); complete no-default desktop tests (394 including privacy doctests; one ignored case remains unqualified); pinned Rust 1.99.1 formatting and all-target warnings-denied Clippy in both modes. The initial format check retained one assertion-wrapping failure; the corrected final format passes, and both complete suites ran on the formatted source. No assertion was waived. Documentation/reference/whitespace and exact outside-owned checks pass. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source and C2a design reviews pass with no open P1/P2/P3. The design review found two real P2 omissions: active read-kind retention and snapshot/Stop winner ordering. The proposal now requires immutable active kind, coherent Host-to-Active capture, explicit snapshot timing and deterministic race barriers. Neither change implements or accepts C2a. The review also raised then withdrew an expiry-priority test finding after confirming the existing expired-then-drained assertion in both phase cases; no duplicate test or assertion waiver was added. Exact final hashes, preservation, command records and the final review disposition belong to the same evidence directory; absence of a passing final seal keeps that acceptance open. No UI changed, so no new rendered or native-GUI qualification is claimed. Earlier v13 six-case acceptance remains bound to its original frozen source and executable; it is not silently promoted to a new artifact after this source correction. Security/standards impact: accurate local state reporting over existing custody; no new secret/output field, credential read, provider call, permission, dependency, schema or authority. ISO/OpenSSF organizational and release evidence remain separate. Normal data/keys, vault, real providers, LNSAT/VUSL edits, dependency fetches, Git publication, deploy and release remain closed. Producer is the OpenAI controller; a native OpenAI `gpt_reader` (configured Luna medium) supplied the bounded next-gap inventory and a fresh OpenAI `gpt_reviewer` (configured Terra xhigh) reviews source and evidence. GLM/Spark were skipped for protected native-state fit; no external payload transfer or provider contact occurred. At this correction closeout, the [C2a readback proposal](openshell-observation-connector.md#c2a-session-inspection-source--proposed-next-packet) named six future paths and validators and was neither implemented nor accepted. Jeff subsequently accepted that source/tests scope, as recorded in the current-source receipt above. No new architecture authority or competing SDK/language contract is introduced. + + +## Foundation identity and SDK context — October 20, 2026 + +Authority: Jeff's [foundation identity and developer context requirement](product-experience.md#foundation-identity-and-adapter-developer-context--october-20-2026). This is UI-only plus reconciliation of the existing R9 SDK direction. It does not count as backend, VUSL consumer, SDK runtime or connected-engine implementation. Root owns product direction, canonical records, integration and validation. Native OpenAI gpt_ui_design (configured Terra high) supplied a read-only inventory; gpt_worker (configured Terra high) supplied an isolated draft. Root applies it only after closing C1's failed qualification candidate and takes a new baseline. A fresh independent UI/source/evidence review is required. + +Exact fifteen owned paths: preview/assets/foundations/vusl-logo.png and provenance.json; preview/foundation-marks.mjs, foundations.css, authority-view.mjs, engine-view.mjs, engine.css, analyze.html; tests/foundation-marks.test.mjs, authority-view.test.mjs and engine.test.mjs; docs/provider-interoperability.md, product-experience.md, this ledger and continue.md. Existing unrelated dirty HTML and source are retained. The baseline, preimages and exact ownership are in `/rangoon-foundations-ui-20261020`. No authority catalog, state model, command/capability, native source, dependency, database or foreign repository is owned. + +Experience outcome: compact distinct product identities, readable local logos, one-line role/status and expandable mechanics on Authority Engines and LNSAT diagnostics; LNSAT references retain their existing routes. VUSL is Shared language with Integration planned; LNSAT is optional Authority engine with Adapter unavailable. Existing local diagnostic command, button availability and provider/native provenance remain exact. SDK direction reuses R9, language-neutral bounded contracts and an explicitly pinned VUSL consumer cutover with affected tests; it adds no runtime or competing semantic contract. Fresh independent OpenAI gpt_reviewer (configured Terra xhigh) reviewed the SDK wording: two P2 omissions were corrected to require updated/passing consumer tests and two real qualified reference adapters with fixture/conformance evidence. The revised draft review passes. + +Named validation: focused foundation/authority/engine tests, new module syntax, full npm build:check, documentation/whitespace and exact outside-owned preservation; rendered 320/768/1440 light/dark, keyboard/disclosure/focus, reduced-motion and forced-color checks; fresh independent UI review. Focused tests pass 20/20. The full npm build:check passes syntax, visual/vision rules and all 468 tests. Its first sandboxed run passed 467 tests and failed the existing local server test with listen EPERM; the authorized loopback-only rerun passes all 468, with both logs retained. Document validation passes 587 authored text files, the eight existing reference-image hashes, historical brief and local links; the new brand asset is separately hash-tested. Browser review checks both changed routes at actual CSS widths 320, 768 and 1440 in dark and light themes, with loaded logos, correct role/state, disabled browser diagnostic and no horizontal overflow. IAB viewport overrides required device-pixel-ratio calibration; retain the measured CSS widths rather than claiming requested physical dimensions. Early unsynchronized screenshot captures showed stale paint; settled route/theme/column captures supersede them in layout-checks-settled.json, with a fresh collapsed desktop capture after the keyboard-expanded case. Enter toggles both native disclosures, Tab moves between them, focus outlines remain visible and new card animations compute to none. Forced-colors handling is source-reviewed only; runtime emulation is not exposed by this browser surface and no forced-color GUI pass is claimed. Fresh independent OpenAI gpt_ui_review (configured Terra xhigh) review passes with no actionable P1/P2/P3. The reviewer verified all fifteen hashes, preservation, supplied validators and final screenshots without rerunning tests. This is UI/source review, not native, provider, SDK, OS or release qualification. Security/standards impact: static local identity assets and escaped app-owned copy only; no new script framework, transport, credential, secret, permission, storage/output, authority or external call. Provenance keeps brand rights separate from source licensing. ISO/OpenSSF readiness remains distinct from certification. C1 native startup and zero-of-six qualification remain unresolved and are not changed or validated by this packet. All edits remain uncommitted/unpublished; GLM/Spark are skipped, with no external payload/contact error. No engine operation, normal data/key action, VUSL/LNSAT edit, dependency fetch or release is opened. + +## OpenShell C1-M native review and input — October 20, 2026 + +### Controller-attribution investigation and correction — October 21, 2026 + +#### Guarded native matrix accepted — October 21, 2026 + +The accepted C1-M six-case macOS synthetic native matrix now passes on one frozen executable, SHA-256 `c80d4539e5c21c759b378d922a634db69ce3d506ad0b85c230c7ed2516b73815`. Evidence: `/rangoon-c1-native-matrix-20261021-v13`. The runner exited 0 after all six exact start/action/return/terminal sequences. Accept-read made exactly one Health, PolicyStatus and Logs RPC and retained one unqualified observation; cancel-review, stop-queued, stop-open, expire-open and parent-close each made zero RPCs and returned no observation. All six children exited cleanly without stderr. Parent close used the explicitly labeled programmatic owned-parent command; no AX-close or whole-product Quit claim is made. + +The controller observed five fresh native review contexts and four actual masked input fields through fifteen completed CUA calls with no tool errors. Every action was journaled before dispatch and its return recorded separately; the native callbacks and synthetic peer ledger determine outcomes. Stop assertions bind both entry and return to the original immutable deadline. The expiry case reached `credential_lease_expired` without a submitted Cancel or Stop. Parent elapsed times include callback hold/drain and controller acknowledgment, so they are not credential lifetime or performance measurements. Original/copied executable and plist hashes, all 709 frozen source identities, all event sequences and all six handoffs were rechecked before closing the freeze. No owned native process remained. Raw `results.json` correctly keeps `qualificationComplete: false`; the separate `independent-review.json` records the narrower reviewed acceptance without rewriting raw results. + +Fresh independent OpenAI `gpt_ui_review` (configured Terra xhigh) returned PASS with no P1/P2/P3 after reviewing the actual UI extracts, callbacks, timing guards, artifact identities, six native event streams and controller journals. Root accepts only the bounded macOS synthetic native evidence. This is not proof of exclusive human identity, real credentials, OS vault behavior, Windows/Linux, mounted product UX, live provider support, persistence, formal accessibility, production readiness or release. The historical v9 actor and exit-70 cause remain unknown; v7–v12 retain their existing limits/failures. The separate source-review seal for the sixty-second post-exit transport correction is `/rangoon-c1-attribution-20261021/return-grace/review-seal.json`, with 45 offline runner tests passing. No native credential deadline changed. No new dependency, permission, normal data/key operation, LNSAT/VUSL edit, publication or release occurred. Next engineering work remains the separately scoped platform and mounted finite-read stages below; this matrix does not activate production Connect. + + +Follow-up native attempts remain failed and immutable. V10 stopped at the start challenge without launching a child. V11 and V12 each produced the expected synthetic read result (one Health, PolicyStatus and Logs RPC, no authority, clean exit 0), but neither completed controller correlation. V11 combined the terminal click with an AX read after process exit; the tool returned “App quit” and automatic approval review refused recording that combined operation as successful. No success return was written. V12 separated the terminal click, which returned successfully, but the controller's post-exit return still arrived after the ten-second correlation window. The failed parent records are retained in their `/rangoon-c1-native-matrix-20261021-v10`, `-v11` and `-v12` directories; they do not qualify native UI. + +The bounded runner correction allows sixty seconds for an already-declared operation's return after child exit. It changes no live credential deadline, action admission, source/artifact checks, failure outcome or next-case challenge. Two deterministic clock regressions cover a delayed return after eleven seconds with new-action refusal and an unanswered return expiring at sixty seconds. The offline runner suite passes 45 tests. Rust/native source and artifact remain unchanged. Fresh independent source review passed, and the later v13 matrix is recorded above; no earlier failure is reinterpreted as passing. + +Authority remains Jeff's accepted C1-M source/tests packet. Jeff answered that neither he nor another chat interacted with the discarded v9 window and requested an automation investigation. The initial source-only investigation ended before attempts v10–v13; it launched no native UI. The exact current-controller call metadata shows zero CUA calls during v9: the last prior CUA call returned at 06:17:37.663 UTC, while v9 launched at 07:11:40.503936 UTC. This excludes an outstanding recorded call in this controller; it does not establish the behavior of an external automation service or another actor. Other chats were not read. The native source only emits ReviewAccepted after its actual AppKit completion returns confirmation; programmatic dismissal returns cancellation. InputPresented then follows automatically from credential-sheet presentation. The Python runner contains no UI/input injection. The acceptance actor and the reason for exit 70 after 21.327 seconds remain unknown. V9 remains discarded; no manual interference or application auto-confirm root cause is asserted. + +The reviewed design correction stays inside six accepted paths: `scripts/qualify-native-credential.py`, `tests/qualify_native_credential_test.py`, `apps/desktop/src/native_credential_qualification.rs`, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. Root owns protected implementation/integration and validation. Native OpenAI gpt_reader (configured Luna medium) and a separate native controller-class read-only agent traced disjoint source/runner evidence. Two earlier Terra worker/reviewer contacts failed with “Selected model is at capacity. Please try a different model.” Native read-only lanes supplied the diagnosis; no GLM/Spark or external payload transfer was used. Fresh independent native OpenAI gpt_reviewer (configured Terra xhigh) reviewed the correction and returned PASS, as recorded in the source seal. Producer does not approve its own source or native qualification. + +The revised private v2 harness uses a fresh pre-launch challenge, exact case/nonce/PID/artifact binding, full visible context in parent title/review installation/ready record, and one locked payload-free controller journal. Each UI intent is flushed before its operation; its return is a separate controller assertion. Unexpected native progress, a mismatched identity, stale/duplicate control, failed action or declared interference refuses the test and stops only its owned disposable child. Existing native callbacks, consent, deadline, one-shot claim and client stay authoritative. An already-declared UI operation may return after child exit; new actions after a result are refused. After clean exit and source/artifact/raw-oracle checks, a fresh terminal challenge must be acknowledged before another child starts. Programmatic parent close is labeled explicitly. Parent/controller completion never sets qualificationComplete true. Each new run requires separate fresh independent UI/evidence review; v13 has the bounded sidecar acceptance recorded above. Historical v1 receipts are preserved, not reinterpreted by the v2 reader. These are internal test records, not VUSL semantics or a public SDK. + +Evidence and baseline/preimages: `/rangoon-c1-attribution-20261021`. The first Python run retained one old test failure because the newly required controller gate correctly refused before its intended post-capture check; the test now supplies that prerequisite without changing the tamper oracle. Current offline Python suite passes 43 tests, including all six positive event/controller flows, live capture-thread refusal and a successful actual start/capture/relay/terminal path using an inert native-process double. No process double is native UI evidence. Review found three P2 failure-lifetime gaps: output overflow, launch/attach cleanup failure and event-receipt I/O failure. Each now requests immediate termination of only its owned child, retains bounded cleanup failure and has injected regressions; raw I/O error details are excluded from receipts. The P3 missing integrated successful parent path is covered without claiming native UI. Rust format, eight focused native/context/drain/timing checks, qualification-feature all-target warnings-denied Clippy and the custom locked/offline no-run build pass. Fresh independent OpenAI gpt_reviewer (configured Terra xhigh) rechecked the corrections and current source with no open P1/P2/P3. Python compilation, repository documentation/reference checks and six-path whitespace checks pass; all 703 outside-owned identities remain exact. Final hashes and the review seal are retained with the evidence. Production code, helper FFI, Host, store, lockfiles, compiler pin and dependencies are outside this correction. Prior complete desktop/core/renderer receipts remain prior evidence, not fresh reruns here. + +Security/experience impact is restricted to fixture-test attribution, bounded nonsecret diagnostics and truthful status. Controller intent is not human consent, proof of exclusive desktop control or provider authorization. No credentials/input contents, raw AX state, screenshot bytes, arbitrary stderr or provider text enter the new journal. The visible full nonce is a disposable correlation value, not a credential. ISO/OpenSSF and three-OS/distribution qualification remain separate unfinished gates. Native GUI, normal data/keys, OS vault, real credentials/providers, LNSAT/VUSL changes, dependency fetch/install and publication remain closed during diagnosis. All 703 outside-owned identities, both lockfiles and compiler pin remain exact; the index is empty and HEAD is unchanged. The first whitespace wrapper incorrectly treated git no-index difference exit 1 as a whitespace failure; its empty output and the repository checker showed no whitespace issue. The corrected wrapper accepts only exit 0/1 with empty check output. No commit, push, merge, deploy or release occurred. + +### Native outcome review and timing-oracle correction — October 21, 2026 + +V7 (`/rangoon-c1-native-matrix-20261021-v7`) completed all six parent oracles on frozen artifact `2c2a0fd3187071d11a642e4d6d548104fdd9d8bd84578acee72d23ebd0b3ac51`: accept-read (9 events), cancel-review (4), stop-queued (9), stop-open (13), expire-open (7) and parent-close (8). The original and copied executable, fixed plist, frozen source and every event sequence were independently rechecked before closing that freeze. The successful read uses only the three selected RPCs; all other cases report no observation/RPC and all six exit cleanly without stderr. Root observed the real native review followed by the masked field and used only fixed dummy input/local TLS. This establishes observed synthetic macOS outcomes; it is not full UI, three-OS, provider or production qualification. + +Fresh independent OpenAI gpt_ui_review (configured Terra xhigh) found two P2 qualification gaps: UI interaction attribution/exclusivity is not independently established by the runner's PID/nonce/event chain, and the Stop-open oracle does not prove Stop happened before the immutable deadline. Its 130.895-second total is not proof of that ordering. V8 expired before controller Stop and is retained as failure. V9 recorded review acceptance/input presentation without any Root CUA input, then exited 70; the review agent confirmed no GUI actions. V9 is discarded. Jeff subsequently reported no interaction and requested an automation investigation; the controller-attribution receipt above owns that follow-up. No manual actor is assumed, and native UI remains stopped during diagnosis. The v7 raw parent PASS remains preserved without promotion to independently qualified UI. Root's native freeze closure is `/rangoon-c1-callback-20261021/native-freeze-closure.json`. + +The accepted C1-M qualification target already owns `apps/desktop/src/native_credential_qualification.rs`. The current source continuation therefore expands to that fifth owned path (704 outside-owned identities); its original preimage is preserved. Independent source review confirmed the bounded correction: capture the exact Pending selection deadline before moving the same selection into the native callback, require at least ten seconds remaining immediately before either Stop/drain control, and reject a late or unavailable deadline. The guard also requires Stop/drain to return strictly before that same deadline, so a scheduler stall between the precheck and Stop cannot produce a qualifying result. Private boundary regressions accept the exact ten-second start margin, reject insufficient/expired start time, and reject completion exactly at or after expiry. No new native case/event schema, Host behavior, credential source, provider, dependency or permission is added. The final oracle-v2 source checks pass: format, seven focused native/context/drain/timing tests, qualification-feature all-target warnings-denied Clippy and the custom locked/offline no-run build. V1 receipts remain separate; the final post-return bracket is covered by V2. Fresh independent OpenAI gpt_reviewer (configured Terra xhigh) final source/evidence review passes with no open P1/P2/P3 after the packet metadata was aligned to both guards. The initially stale packet-description P3 and its correction are retained in the review evidence. Native/UI qualification remains rejected; `qualification-assessment.json` beside the v7 raw results and `native-review-assessment.json` in the source evidence record that decision without changing the raw parent results. This changes only the qualification target; the post-input production and Host test files retain their earlier reviewed/tested bytes. UI attribution evidence and a clean current-artifact native rerun remain separate gates. The next tooling proposal is a parent-side, payload-free action journal and explicit handoff between child cases: bind each expected UI action to the current case/nonce and visible test context, refuse unexplained native transitions, record completion or interference, and launch no next child until the controller acknowledges the previous terminal result. This is a test-evidence proposal, not a new approval/authorization contract or an implemented guarantee of human absence. Review its exact source/test ownership before implementation. User clarification and a current-artifact native rerun remain required. + +The earlier post-input checkpoint passed its named source gates within the same accepted C1-M packet. Exact four owned paths: `apps/desktop/src/openshell_native_input.rs`, `apps/desktop/src/openshell_host_tests.rs`, this record and `docs/continue.md`. Baseline/preimages and fresh command evidence live in `/rangoon-c1-callback-20261021`. Root owns the protected native integration; a bounded OpenAI gpt_worker (configured Terra high) owns only the Host test file. The shared private tail retains the active cancellation/deadline fence, diagnostic phase, exact disposable-marker validation, one-shot credential sealing, original deadline binding, finite reader and final acceptance check. Native callback and source regressions use that same tail. No native widget/confirmation double, secret constructor, public credential API or alternative Host lifecycle is added. The initial focused command used the wrong test-name filter and ran zero tests; it is retained as non-evidence. The corrected v2 filter executed all four post-input tests successfully. Fresh independent review then identified a production-only type-resolution defect: the new reader signature used a parent import available only under `cfg(test)`. Root changed it to the explicit `rangoon_openshell_client::BearerLease` identity before the final default/no-default builds and regression suites. That review finding and the pre-correction focused pass are preserved separately. The final qualified-type candidate passes the four focused source cases, all ten desktop gates, qualification-feature all-target strict Clippy and custom no-run build. Fresh independent OpenAI gpt_reviewer (configured Terra xhigh) source/evidence review passed with no open P1/P2/P3 for that four-path post-input checkpoint; native UI qualification was excluded. + +Final source evidence: `post-input-focused-final.json/log` executes four nonzero cases through actual Host admission and the shared post-input tail: valid marker reaches the real credential seal and shared TLS reader with the exact protected-check RPC ledger; eight invalid values return fixed InvalidConfiguration before the reader; Stop while the callback is held before the tail rejects subsequently released valid input; and the received selection deadline is deterministically expired inside the test callback before the tail. Negative cases retain no observation, execute no reader/RPC, refuse replay and finish callback drain. These are source-level post-input tests, not actual native confirmation or widget interaction. The earlier direct-validator regression separately checks clearing of rejected input. + +The final default suite passes 710 tests (172 library, 516 binary, 22 documentation), with four ignored tests still unqualified; the no-default suite passes 391 (43 library, 326 binary, 22 documentation), with one ignored. Do not include the default suite's nested one-test child receipt in those totals. `enqueue-desktop.json` records all ten passing locked/offline format/helper/test/Clippy/build/normal-feature gates. Helper tests pass 5/5; both normal builds pass and the normal dependency graph excludes qualification, synthetic-peer support and Tauri unstable. `post-input-feature-clippy.json/log` and `post-input-qualification-build.json/log` pass. The existing shared-main-source Cargo manifest warning remains visible. Portable-core, Python runner and renderer source are unchanged; their earlier receipts are not presented as fresh runs. + +The source continuation changes the native artifact: the earlier passing v6 queued diagnostic remains evidence only for its frozen source/executable. It does not qualify the present candidate, visible review/input or the full six-case matrix. The full user workflow and goal remain unfinished. No new dependency, authority, renderer, store, provider, LNSAT/VUSL or normal data/key behavior is in scope. Security/readiness impact is limited to stronger source proof at the existing input/credential/transport boundary; toolkit-copy limits and all native/three-OS/distribution requirements remain unchanged. No compliance or production-readiness claim follows. + +Current source-correction checkpoint remains within Jeff's accepted C1-M 23-path packet. Exact eight owned paths: `apps/desktop/src/native_credential_qualification.rs`, `scripts/qualify-native-credential.py`, `tests/qualify_native_credential_test.py`, `apps/desktop/native-input/src/lib.rs`, `apps/desktop/native-input/src/macos.rs`, `apps/desktop/src/openshell_native_input.rs`, `docs/development.md` and `docs/continue.md`. Baseline, preimages, incremental reviews and command receipts live in `/rangoon-c1-startup-20261020`; all 701 outside-owned files remain exact, the index is empty and HEAD remains c132ea62bc57b29375ee8c5a3a38ca005462ca40. No normal Gate/Host, command, permission, configuration, credential source, store, provider or foreign repository changes are included. + +The typed guard inspects the actual generated Tauri context. Pinned tauri-utils omits empty capability windows/webviews arrays when serializing; the old JSON-presence assertion therefore rejects its own inert context. The shared constructor is exercised by the positive test and eighteen capability/surface mutations plus nonempty assets. No constraint was weakened. The first focused CLI command named a nonexistent binary and executed no tests; its corrected command executed both context tests. At the Stop/drain checkpoint, an actual Host callback regression adds the third focused test: independent Exclusive admission succeeds while the Read callback is held, Stop returns Closing, an explicit memory drain remains non-quiescent until callback return, then state is Cancelled/quiescent with zero synthetic RPCs. Stop itself does not close unrelated lanes. The native harness retains that same drain through release and final completion, replacing its incorrect cross-lane admission oracle. + +The runner reuses E1c4's disposable app-wrapper approach: fixed test-only Info.plist, fresh private directories and exclusively created files containing unchanged Cargo artifact bytes. Both source and copied hashes, metadata and exact regular non-symlink paths are checked before/after each child and at final completion. It is not an installer, signing or product-package path. Native OpenAI gpt_worker (configured Terra high) added bounded inert wrapper tests; Root owns integration, privacy, the runner and the additional fixed-I/O-failure regression. Twenty runner tests pass, including valid controls, source/copy/plist/symlink tamper, refusal before capture and revalidation after capture. Python compilation passes. + +| Evidence stage | Verified outcome | +| --- | --- | +| Normal desktop preflight | All ten locked/offline gates passed: 705 default and 386 no-default tests, five helper tests, formatting, strict Clippy, both normal builds and feature isolation. This is the earlier checkpoint. The subsequent helper enqueue/observer correction also passes a fresh complete ten-gate rerun: 706 default and 387 no-default tests, helper tests, strict Clippy, builds, format and normal feature isolation, recorded in enqueue-desktop.json. | +| Latest qualification source | Four focused Rust tests, strict qualification-feature Clippy, formatting and custom no-run build pass. This includes the two actual-context tests, real Host callback regression and diagnostic-observer panic regression. | +| Wrapper/source checks | Twenty runner tests, Python compilation, 587-text/eight-image documentation and exact preservation pass. Eight pin-validator regressions remain passed on their unchanged source. | +| Independent source reviews | Fresh independent OpenAI gpt_reviewer (configured Terra xhigh) passes typed-context and wrapper source/evidence reviews with no new P1/P2/P3; Stop/drain and enqueue/observer corrections have fresh source PASS; fresh independent OpenAI gpt_reviewer (configured Terra xhigh) final v6 evidence/status review passes with no new actionable P1/P2/P3; the enqueue P2 is closed for accepted-queue evidence only. Earlier callback-to-no-seal/client negative-test P3 remains open. Reviews do not qualify OS/UI/provider support. | +| Native v2 | Child exits 101 before ready; exact panic unavailable because raw stderr was not retained. Do not infer absence of a window. | +| Native v3 | New source reaches ready/review queued. CUA inventory omits raw executable; exact-path getApp returns Invalid app. No UI input is sent. Child expires after 126.87 seconds, exits 70 and records no terminal result. | +| Native v4 | Byte-identical disposable app child reaches ready/review queued. Native UI-control service times out; no UI interaction is evidenced. Child expires after 123.26 seconds and exits 70. Root verifies no qualification child remains. | +| Diagnostic v5 | stop-queued receives Stop then exits 70 at the incorrect independent-lane oracle. This failed subset is not a pass. | +| Diagnostic v6 | PASS: exact frozen source/artifact, actual accepted native queue under held main loop, Stop/retained non-quiescent custody, release, Cancelled, zero Health/policy/log RPCs, no observation and clean exit. Nine strict events; qualificationComplete remains false because this is one diagnostic subset. | + +Retain `/rangoon-c1-native-matrix-20261020-v2`, `-v3`, `-v4` and `/rangoon-c1-native-queued-20261020-v5`; no failure is overwritten. Fresh v6 evidence is `/rangoon-c1-native-queued-20261020-v6`, artifact SHA-256 640ed07727732ee603471140664d9e767e6b8711846d7973d755d44755609c71. Root revalidates both original/copied artifact, exact source manifest and all event/result rules before closing the freeze and editing status documents. No complete native matrix has passed. Fresh independent review identified P2: the old NativePhase::ReviewQueued was emitted before helper.confirm actually enqueued native work. The accepted C1 correction now adds a payload-free InputGuard observation after successful run_on_main_thread, removes the earlier request marker and routes it through the existing Guard observer. Early guard/dispatch failure returns before notification. It reports accepted queue work, never visible review UI, consent or authority. Observer panic is contained so a diagnostic failure cannot unwind the owning callback after enqueue or across the existing presented notification; a focused regression exercises that observer path. Fresh independent source review passes with no new P1/P2/P3. All ten full desktop gates pass, and focused qualification tests pass 4/4 with qualification-feature strict Clippy/custom no-run. The real queued-Stop diagnostic passes; fresh independent OpenAI gpt_reviewer (configured Terra xhigh) final source/evidence/status review passes with no new actionable P1/P2/P3. Direct native queue-refusal and actual visible review/input remain unqualified. Keep requested, queued, presented and completed states distinct. This remains accepted C1 work, not public SDK implementation. + +Root owns protected diagnosis, integration and validation; the native Luna-medium reader supplied exact pinned-library evidence. GLM/Spark were skipped with no external transfer/contact error. No new dependency, storage/output, authority or standards-certification claim is introduced. ISO/OpenSSF readiness is separate from certification. Full native qualification, direct queue-refusal/visible-review evidence, callback negative proof, Windows/Linux entry qualification and production mounting remain unfinished. No real provider/credential, OS vault, normal user data/key, LNSAT/VUSL edit, install/fetch, commit/push/merge/deploy or release occurred. + +Source validation passes; actual native GUI qualification remains pending. No three-OS or release pass is claimed. Add the small native companion crate, retain the trusted parent only on the main thread, keep native widgets there without unsafe Send/Sync, and retain the existing Host's single admission across actual review/input/read callbacks until real completion and clear acknowledgement. Use the immutable original selection deadline, exact review and guarded one-shot claim. Normal Start and command/capability registration remain closed. The custom target alone may exercise dummy inputs with generated local TLS peers; six actual macOS cases and artifact-bound independent evidence must pass before counting native qualification. Windows/Linux native entry and qualification remain unfinished. + +Diagnostics follow Jeff's latest human/LLM usability direction: stable fixed code, failed phase, concise human explanation and safe next action, with selected-system/source identity kept distinct from arbitrary provider payloads. Do not erase provider-native meanings or conflate cancellation, credential expiry, provider denial, transport failure and uncertain outcomes. This packet may expose fixed internal native-input diagnostics; it does not establish a universal public diagnostic protocol, UI mounting or complete cross-provider harmonization. Jeff clarified that VUSL provides the shared language and remains independent, like LNSAT. Rangoon must reuse qualified VUSL semantics, not establish a competing format here. Neither current internal C1 errors nor test events claim VUSL consumer adoption. A parallel read-only design lane inventories VUSL/LNSAT logos and proposes a separate bounded polish packet; it makes no UI edits while C1 source/qualification is frozen. + +Named validation: focused helper/C0/Host regression tests; core and desktop default/no-default format/tests/strict Clippy/builds; eight third-manifest pin-validator regressions; normal feature-exclusion and dependency identity checks; Python qualification-runner regressions; six actual disposable macOS cases on one frozen artifact plus fresh independent UI/evidence review; documentation/whitespace and exact outside-owned preservation. Record failures and corrections before claiming a final pass. Early source checks pass: five helper input/diagnostic tests, eight pin-validator regressions, the normal desktop check, and 65 Host/C0 tests including actual dummy TLS reads. These are interim checks, not final frozen-source gates or native GUI evidence. V1 Host compilation found an overbroad worker test-oracle replacement referencing a nonexistent parameter; Root restored the uncancelled standalone expiry expectation to Running, preserving Closing only after actual cancellation. V2 compilation exposed and corrected one Root cfg delimiter. The first custom-target build exposed two source-assumption errors: SyntheticScenario is a closed enum (use Healthy), and Tauri 2.12.1 exposes the required plain WindowBuilder only through its unstable feature. Root confines that existing-version feature to native-credential-qualification; no new package/version, fetch or normal dependency feature is added. The test-only public plain-window constructor preserves the accepted no-webview/no-IPC context; final normal feature isolation must explicitly exclude tauri/unstable. This is a bounded feature-edge reconciliation within the accepted manifest/qualification paths, not production UI acceptance. Failed logs remain in the source evidence directory. Actual native cases remain pending. The first full default desktop run failed one unchanged recovery journal test at selected.json/before_file_sync with Unavailable. Its exact isolated rerun and the final full default suite now pass. No unowned database path or oracle changed; the transient failure remains recorded without an established root cause. A later sandboxed rerun failed a different unchanged special-file fixture with Operation not permitted. The retained phase-sandbox-v1 log records that environment restriction; the accepted disposable-fixture rerun with the required execution permission passes the full suite. No database source or expectation was modified. Initial runner review found exact-pin, generation-bound command and evidence-label gaps. Its correction pins Rust 1.99.1 literally, routes closed case/nonce-bound commands, rejects stale-generation commands, labels subsets as incomplete diagnostics, and retains fixed failure/cleanup facts. Fresh runner review passes with no P1/P2/P3. Root added shared-callback fixed-fixture input validation, clearing every other value before lease/client construction, with a live-buffer regression. Real-secret mounting remains unavailable. + +The frozen source passes all fourteen pinned locked/offline Rust gates: four portable workspace gates and ten desktop gates. Portable tests execute 634 cases with eight ignored. Default desktop executes 172 library, 511 binary and 22 documentation cases (705 total; four ignored); no-default executes 43 library, 321 binary and 22 documentation cases (386 total; one ignored). Counts exclude nested child output and overlapping focused checks. Desktop gates include five helper tests, helper strict Clippy, format, both test/strict-Clippy/build modes and normal-feature inspection. Normal/build edges exclude synthetic-peer-test-support, the credential qualification feature and Tauri unstable. Eight pin-validator and fourteen Python runner regressions pass; Python compilation passes. Source review finds no P1/P2. One P3 remains explicit: the exact-marker/live-buffer unit test does not exercise a non-marker through the whole native callback to prove zero lease/client/RPC; the guard's correct call order is independently inspected, and no negative native case is claimed. Existing six-case acceptance is not widened to hide that gap. Before GUI launch, Root found a further stop-open evidence-oracle bug: its generic phase lookup required a single phase and ordered a hold before a review that had already completed. V3 now checks exact per-case phase and control order, with valid and malformed stop-case regressions. V3 review then found a P1 proof gap: queued input was not proof that the native field was open. Root added a payload-free InputPresented notification after actual beginSheet and field setup, outside the native TLS borrow. V4 requires this phase before Stop/parent-close controls, exact open-case phase prefixes and refusal of late accepted-input/read records. Thirteen runner tests now pass, including queued-only, malformed order and late-result negatives. Fresh V4 reviews and the final custom no-run build remain required before GUI launch. The final custom target no-run build also passes. Fresh V4 review then identified a P2 test-proof error: two negative cases retained stop-open identities, hiding the intended phase refusals. V5 corrects every case identity, adds a valid control before each mutation, deep-copies records and asserts the specific phase/parent-order errors. Both fresh reviews clear source preflight with only the explicit P3 residual. The first full runner invocation then refused toolchain preflight before building or opening any window: Node eval arguments accidentally matched the imported validator’s CLI entrypoint. V6 adds a separate eval identity argument without weakening that CLI guard, plus a real-Node import regression. All fourteen Python tests, Python compilation and the actual seven-tool Rust 1.99.1 identity preflight pass; fresh V6 review remains required before another native attempt. + +Evidence: final-core.json, core-counts.json, final-desktop.json, retained V1 failures, journal-isolated-v1.json, native-review-hashes-v2.json and runner-review-hashes-v2.json in the source evidence directory. OpenAI gpt_reviewer (configured Terra xhigh) independently reviewed source/FFI/lifecycle and a separate fresh reviewer reviewed the Python runner. Review alone is not native qualification. The first GUI inventory was blocked by automatic approval review because final source/evidence review was not yet closed; no GUI or native test was launched by that request. Finish the gate before retrying. + +C1-M qualification candidate is now closed as an incomplete native attempt, not a pass. V6 runner review clears preflight with no P1/P2; all fourteen Python tests, actual seven-tool identity preflight and the existing Rust source gates pass. The fresh full-matrix attempt in `/rangoon-c1-native-matrix-20261020-v2` builds the exact custom target, then its first accept-read child exits 101 before any ready or phase record. It reports no timeout, overflow or cleanup failure; zero of six cases complete. No native window interaction, provider read, secret entry, OS vault or normal data/key action is evidenced. The cause is unresolved; source stability does not replace native proof. Preserve artifact `05737debd421a8c0450305f5cba7364c24fb3181b7c7a61b630dbb0afcd2cf61`, nonce and fixed failure receipt as failed evidence. A bounded startup diagnosis and fresh artifact-bound full matrix remain next native engineering work. Ending this candidate freeze permits Jeff's separately requested UI-only foundation polish; those changes do not qualify C1 and any later full-worktree qualification must use a new source manifest. + +Security/experience impact: optional native-only secret input is sensitive. No renderer secret, vault/ambient lookup, automatic retry, lifetime renewal, clipboard scan or helper subprocess. Clear the owned Rust value and native field, but do not claim complete erasure of toolkit/transport copies or workstation-compromise resistance. New local dependency edges may reuse only approved exact locked identities; no package/version change or dependency fetch. ISO/OpenSSF readiness remains separate from certification. Production Connect/Start, real credentials/providers, OS vault, renderer mounting, normal data/keys, LNSAT/VUSL edits, commit/push/merge/deploy/release remain closed. GLM/Spark are skipped for protected native/credential integration; no external GLM transfer or contact error. + +## Cross-producer repeated-record conformance — October 20, 2026 + +Authority: the existing accepted [operations control-plane continuation](intent.md#operations-control-plane-continuation--october-7-2026), O1 relationship/idempotence and O2 allowlisted-view contracts, and the continuing support goal's changed/repeated-record requirements. This is a bounded test continuation of existing behavior, not C1-M/native-input acceptance, a new protocol or a new authority decision. The existing exact-repeat regression clones one event; the missing case uses distinct event, producer and fence identities for identical record bytes, with a changed-record control. Root owns semantics, integration, these records and validation; a bounded native OpenAI `gpt_worker` (configured Terra high) owns only `crates/rangoon-ops/src/relationship_tests.rs`. Exact packet paths are that test file, this ledger and `docs/continue.md`. No production implementation, fixture, schema, renderer, adapter, credential, store or dependency change is owned. + +Required evidence: decode a bounded synthetic window with two real observed envelopes, pass it through actual structural/relationship/delegation/approval/lifecycle inspectors and the allowlisted O2 builder. Identical records with distinct producer/fence/event identities must keep both matching ordinals and source counts, remain unique-unverified only, preserve fixed no-authority/unknown outcome and expose no raw source identity through O2. Changed same-ID record bytes must instead remain ambiguous/conflicting with both ordinals, without selecting a trusted origin or granting authority. These are synthetic reported-producer cases, not proof of a real LNSAT/OpenShell relation, authenticated ingress or provider support. + +Named validation: nonzero focused cross-producer tests, complete rangoon-ops tests, formatting and all-target warnings-denied Clippy; relevant existing renderer/operations parity checks; exact three-path documentation/whitespace and 691 outside-owned/source/lock/toolchain identity checks; fresh independent read-only test/contract/evidence review. Baseline and three preimages: `/rangoon-ops-cross-producer-20261020`. The first focused run executed both tests: identical-record control passed; changed-record assertion expected only a structural issue stage, while actual O2 correctly also reported delegations. Root traced the unchanged accepted delegation contract: conflicting actor subject tuples taint actor/delegation assessments, and O2 propagates that stage. The V2 test now expects both structural and delegations; no production expectation was weakened. Failed V1 logs are retained. Final pinned Rust gates pass: both focused cases, 149 complete rangoon-ops tests (147 unit and two integration), formatting and all-target warnings-denied Clippy. The 28 existing renderer/model/parity/view tests also pass; those unchanged fixtures do not execute the two new Rust cases in JavaScript or qualify a GUI. V2 independent review found one P3 test gap: the changed-record case lacked the rendered raw-identity assertion already present on the exact-repeat control. Root added the same privacy assertion, including the changed subject ID. The final rerun passes both focused cases, all 149 ops tests, formatting and strict Clippy; fresh independent OpenAI gpt_reviewer (configured Terra xhigh) review passes with no open P1/P2/P3; documentation/whitespace and all 691 outside-owned identities pass. Jeff separately accepted C1-M source/tests while this packet was in flight; that native packet will use its own baseline after this conformance packet closes. This O1 continuation opens no provider, native UI, normal data/keys, credentials/vault, LNSAT/VUSL edit, dependency fetch, publication or release. + +Security/experience impact: retain reported evidence and privacy boundaries across repeated or conflicting inputs without changing the UI, state machine, encryption or trust semantics. No new data collection, storage, external transfer, dependency/build privilege or authority. ISO/OpenSSF requirements remain separate from certification. Full connected operator records, native input/session mounting and all three-OS qualification remain unfinished. GLM/Spark are skipped for this exact native conformance packet; no external payload or contact failure. Unrelated dirty work is preserved; all changes remain uncommitted and unpublished. + +## Connection usability and native input plan — October 20, 2026 + +Authority: the continuing support objective and Jeff's explicit request to explain practical user impact and prioritize ease of use/dynamics. This is design/review only. It does not widen accepted C0 or client-cleanup source scope. Root owns native credential architecture, integration/UX direction and these four records: `docs/product-experience.md`, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. Product experience owns the user-flow proposal, the connector specification owns the proposed C1-M source/qualification contract, and this receipt owns status. No new intent or competing implementation authority is created. + +Exact current audit: C0 binding/acquisition and the constructor cleanup have passing source evidence, but normal Start remains unavailable, acquisition/runner remain test-only, no minimized IPC result exists, and no native input or production read is mounted. Existing keyring packages store credentials rather than providing the required input UI; both app entry crates forbid unsafe code. Tauri's macOS parent is returned as an autoreleased pointer, so a masked field alone does not solve lifetime, main-thread and cancellation. Native review itself also needs retained admission: the current metadata-only Pending may be dropped on Stop and cannot stand in for an actual queued/open sheet callback. C1-M must cover that entire flight without a second session/drain authority. These findings change the next source scope; they are not production vulnerabilities or completed native capability. + +The [user-flow proposal](product-experience.md#connected-system-usability--october-20-2026) makes local work, optional connection reads and consequential approvals understandable as separate tasks. Configure a draft locally, review access, enter credentials natively, read once, inspect locally, and explicitly refresh. Graph/table selection and filtering never cause another provider call. Stop remains Stopping until actual return; old credential expiry does not invalidate an already accepted observation. The one-attempt/120-second contract creates repeat-auth friction; a separately accepted scoped reading-session design is needed before continuous Live/reconnect/credential reuse. No unseen background work is invented to make the interface feel dynamic. + +The [C1-M proposal](openshell-observation-connector.md#c1-m-native-reviewinput-and-actual-macos-qualification--proposed-source-packet) names 23 future source/test/document paths, a small desktop-only native boundary, existing exact package versions, new manifest pin checks and six actual disposable macOS cases. It preserves app-wide unsafe bans and confines any justified native FFI to independently reviewed companion-crate functions. Windows/Linux remain explicit backend/qualification work before the initial three-OS profile ships; missing support returns Unavailable, never a guessed equivalent. Renderer mounting, real provider/credential use, vault access and production Start stay closed. This is a proposal for real native UI/source proof, not another mock-only input manager or an accepted implementation packet. + +Evidence: `/rangoon-openshell-c1-native-plan-20261020` owns the 694-file baseline, four preimages, exact incremental diff/hashes and validation/review records. Two native OpenAI `gpt_reader` agents (configured Luna medium) supplied disjoint source/host and dependency/platform inventories; native OpenAI `gpt_ui_design` (configured Terra high) supplied user-flow critique. Root reconciled three design suggestions against source: Stop is not complete before callback return; completed observations can survive credential expiry; current bounded watch already has a reported gap projection. Cached pinned source and official Apple/Microsoft/GTK documentation were inspected read-only. No API example, dependency command, provider or native prompt was run. Proposed source ownership is not acceptance. + +Security/standards/experience impact: design preserves provider independence, local-first consent, non-authoritative observations and distinct authorization/execution outcomes. It exposes a new FFI/input/privacy review need rather than hiding it in the app or webview; no current dependency, privilege, storage/output or build policy changes. ISO/OpenSSF alignment remains an evidence target, not certification. Named proportional gates are documentation/reference/hash, exact four-path whitespace, all 690 outside-owned files and production/C0/client/lock/toolchain identity, plus fresh independent read-only architecture/UX/evidence review. Documentation/reference/hash and four-path whitespace checks pass; all 690 outside-owned files and named source/config identities remain exact. Independent proposal review identified a P2 ambiguity between forbidden input-helper subprocesses and required qualification children, plus P3 ambiguous native-address wording. The proposal now explicitly permits only its exact runtime test child and ordinary named build subprocesses, forbids input-helper/scripting subprocesses, and distinguishes native memory addresses from the configured target origin. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) final architecture/UX/evidence/status review passes with no open P1/P2/P3 after those corrections. The reviewer inspected exact hashes and evidence without rerunning tests; this does not accept source, native execution or release. All existing source, 122 dirty entries and unrelated work are preserved; no source implementation, native GUI, normal data/keys, credentials/vault/provider contact, foreign-repository edit, dependency fetch, publication or release occurs here. GLM/Spark are skipped for this protected credential/native boundary; no contact failure or external GLM payload transfer. + +## OpenShell bearer-constructor rejection cleanup — October 20, 2026 + +Authority: the existing accepted [credential-lifetime and private-lease correction](intent.md#openshell-credential-lifetime-correction-acceptance--october-18-2026), the continuing support direction, and the rejection-cleanup prerequisite identified by C0. This is Root's bounded correctness/privacy correction to the existing constructor contract, not a new credential source, public API, native feature or expansion of C0's seven-path ownership. The earlier C0 exclusion of client edits remains honored: this separate correction owns only `crates/rangoon-openshell-client/src/lib.rs` with its internal tests, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. Root owns protected implementation and validation; an OpenAI `gpt_reader` (configured Luna medium) supplies exact source/library evidence, and a fresh independent reviewer must assess the final source and evidence. No new intent or competing acceptance record is created. + +Pre-correction source validated an owned plain String before placing it in `Zeroizing`; rejected nonempty oversized or expired input therefore left its owned allocation outside that guard. No production credential-entry route or observed real-secret disclosure is established. The constructor now wraps the consumed String before every check, then calls one private borrowed validator that explicitly clears invalid input before returning the same fixed InvalidConfiguration error. The guard also retains Drop cleanup. The public String-taking signature, nonempty/16 KiB/future-deadline rules, immutable expiry, redacted Debug, cancellation priority and provider/TLS/scope remain intact. No dependency, manifest, lockfile, host/callback, UI, database, OS vault or authority change is included. + +Three focused tests exercise the actual borrowed validator's still-live rejected buffer, the public constructor's fixed errors, and the valid 16 KiB/deadline/redaction control. They do not read freed/spare memory, use unsafe code or an allocator hook, or establish erasure of every process copy. Existing pinned zeroize 1.9.0 supplies the clearing primitive; no dependency was fetched or installed. Source inspection and these assertions are complementary: an empty observed buffer alone is not an independent byte-level erasure proof. Executable validation passes all fourteen named Rust gates on the frozen source. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source-only review passed with no P1/P2/P3. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) final source/evidence/status review passed with no actionable P1/P2/P3. The reviewer checked exact source hashes, executable evidence and scope preservation without rerunning tests; review grants no OS, provider, native-secret or release qualification. + +| Gate | Result | +| --- | --- | +| Focused constructor regressions | PASS: three executed tests; the filter is nonzero. | +| Complete client synthetic conformance | PASS: 35 tests using dummy credentials and disposable local TLS peers. | +| Portable workspace | PASS: 632 tests, formatting, all-target warnings-denied Clippy and normal build. Eight ignored tests remain outside this executable result. | +| Default desktop | PASS: 172 library + 509 binary + 22 documentation = 703; four ignored entries remain unqualified by this run. | +| No-default desktop | PASS: 43 library + 319 binary + 22 documentation = 384; one ignored entry remains unqualified by this run. | +| Desktop format, Clippy and builds | PASS: formatting, both all-target warnings-denied Clippy modes and both normal builds. No qualification target or GUI launched. | +| Normal feature graph | PASS: no `synthetic-peer-test-support` in normal/build feature edges. This is source/build isolation evidence, not package qualification. | +| Documentation and preservation | PASS: 575 authored text files, eight image hashes, historical brief and local Markdown targets; exact four-path whitespace; all 690 outside-owned files, both lockfiles, compiler pin and four C0 source/test files unchanged. | + +Evidence: `/rangoon-openshell-lease-cleanup-20261020` contains the 694-file baseline, four preimages, exact incremental diff, source hashes, tool identities, command arrays, timestamps, exit codes and logs. `focused-validation.json`, `full-validation.json`, `test-totals.json`, `validation-final.json`, `document-validation.json` and `preservation-final.json` own the results. All commands use the isolated Rust/Cargo 1.99.1 toolchain, matching rustdoc/format/Clippy and locked offline dependencies. Totals use the final result per Cargo target so nested one-test subprocess output is not counted twice; focused and full suites overlap. The pre-existing shared-main-source Cargo manifest warning remains recorded, without suppression. No Graphify index exists. Root produced and validated the correction; the native OpenAI Luna-medium reader supplied exact source/library evidence and the fresh Terra-xhigh reviewer supplies independent judgment. GLM/Spark were not used for this protected credential correction; no contact failure or external payload transfer occurred. + +Security/experience track: the rejected-input cleanup gap is closed at this owned-buffer boundary without changing user controls, connectivity, storage, dependency privileges or telemetry. ISO/OpenSSF requirements remain separate from certification. This does not establish allocator/page/swap clearing, crash-dump resistance, erasure of prior caller/transport copies or safe real-native secret acquisition. C0 still uses synthetic values only. Exact native acquisition/platform qualification, encrypted observation storage, trusted ingress and complete cross-runtime operator scenarios remain unfinished. Prior native receipts do not qualify this changed client source. Normal data/keys, real credentials/providers, target operation, OS vault, LNSAT/VUSL edits, dependency fetch, publication and release remain closed. All four-path changes remain uncommitted on `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; unrelated dirty work is preserved. README publication requirements remain applicable to a separately authorized future push; no publication occurs here. + +## OpenShell C0 credential selection and acquisition custody — October 20, 2026 + +Authority: Jeff explicitly answered “Accept C0 source/tests” to the reviewed [D2b-2b-C0 packet](openshell-observation-connector.md#first-source-packet-d2b-2b-c0-credential-selection-binding). This supersedes only that packet's pending source gate. Root owns protected credential/lifecycle implementation, integration, canonical records and validation. A bounded native OpenAI `gpt_worker` (configured Terra high) owns the new credential tests and their existing host-test wiring only; fresh independent read-only review remains required. Exact seven-path ownership: `apps/desktop/src/openshell_host.rs`, new `apps/desktop/src/openshell_credential.rs`, new `apps/desktop/src/openshell_credential_tests.rs`, `apps/desktop/src/openshell_host_tests.rs`, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. No other production file, command, capability, client crate, Gate, store, manifest, dependency or lockfile is owned. + +The existing Host now allocates one random inspection reference with the exact target/review in Pending and an absolute monotonic deadline of at most 120 seconds from allocation. Its owning selection is non-cloneable, non-debuggable and non-serializable. The inspection copy is not custody or native consent. Confirm moves the same selection; matching acquisition consumes it during the existing Confirmed-to-Active transition. Changed/foreign references cannot consume another valid review. There is no registry, second session manager, ambient lookup or secret source in normal builds. Production Start remains unavailable. + +C0 acquisition and sealing are test-only. A memory acquirer runs inside the same admitted callback as the existing finite client. It consumes the one-shot claim and may only shorten its deadline. The Host checks cancellation/current generation/deadline before acquisition, after acquisition, after client return and under final result acceptance. Source failure is fixed; explicit cancellation wins, while expiry remains `CredentialLeaseExpired`. Callback admission survives a dropped waiter, late acquisition, panic or unsuccessful drain until actual callback completion; a non-cooperative acquisition cannot be declared stopped optimistically. Cancellation racing an already-started acquisition does not prove no acquisition occurred. Accepted session observations do not become authorization or effect evidence. + +Security/privacy limit: only dummy values are permitted. The zeroizing input transfers into the unchanged client's String-taking constructor; rejection inside that API does not establish erasure of every transient allocation. A later real native credential packet must own and correct that constructor boundary, test error/expiry cleanup and qualify exact OS acquisition before mounting. No normal secret input, OS vault or provider access is implemented or authorized here. This is explicit source-only custody evidence, not encryption certification, production secret handling or connected support. No new dependency/build privilege, storage/output, telemetry or authority is introduced; ISO/OpenSSF requirements remain distinct from achieved conformance. + +Named gates: nonzero focused credential and full host tests; pinned Rust 1.99.1 locked/offline default/no-default desktop tests, format, warnings-denied Clippy and normal builds; negative owner-trait and output privacy assertions; actual synthetic TLS-client composition; normal dependency-feature exclusion of test support; document/reference/whitespace checks and outside-owned/lockfile identity; fresh independent source/evidence review. Existing provider-free source/compose/compile/export code stays byte-identical. Old native GUI/Keychain receipts do not qualify new source. Final V3 executable validation passes all ten named Rust gates. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) reviewed the final V3 source/evidence and this exact status closure: PASS, no actionable P1/P2/P3. The reviewer verified final hashes, executable evidence and preservation without rerunning tests; review grants no provider, OS or release qualification. Evidence baseline, five existing preimages, exact command arrays, tool identities, logs and source snapshots: `/rangoon-openshell-c0-20261020`. + +| Gate | Final result | +| --- | --- | +| Focused credential acquisition | PASS: 18 executed tests; nine compile-time negative Clone/Debug/Serialize checks cover actual owning types. A zero-match library filter is not counted. | +| Full Host scope | PASS: 64 executed tests, including existing transport/custody cases. | +| Default desktop suite | PASS: 172 library + 509 binary + 22 documentation = 703; four ignored entries remain unqualified. The nested one-test subprocess result is not counted twice. | +| No-default desktop suite | PASS: 43 library + 319 binary + 22 documentation = 384; one ignored entry remains unqualified. | +| Formatting and strict all-target Clippy | PASS: formatting and both default/no-default warnings-denied Clippy modes. | +| Normal builds | PASS: default and no-default builds; no qualification executable or GUI was launched. | +| Normal dependency feature graph | PASS: no `synthetic-peer-test-support` in normal/build feature edges. This and the cfg/source/build review are exclusion evidence, not runtime or package qualification. | + +Document/reference checks pass for 575 authored text files, eight image hashes, the historical brief and local Markdown targets; exact seven-path whitespace checks pass. All 687 outside-owned baseline files, both lockfiles, the compiler pin and unchanged core source/compose/compile/export implementation remain exact. Four C0 code/test hashes match the final executable V3 source. `validation-final.json` and `preservation-final.json` retain the checks. No Graphify index exists, so indexed-update policy is inapplicable. + +The final frozen-source commands are in `focused-validation.json` and `full-validation.json`; each records actual exit, time, log and command, under pinned Rust/Cargo 1.99.1 with locked offline dependencies and matching rustdoc/format/Clippy identities. Focused counts overlap full counts and are not a product feature count. All real-client tests use disposable synthetic local TLS peers and dummy values. Valid no-acquisition contexts, 12 mutable inspection-field changes, closed retention/protocol choices, native denial, failed/absent backend, consumed reference replay, held acquisition under Stop/close/source-exit, dropped Host handles, panic, expiry before acquisition/after sealing/after actual transport success, byte bounds and immutable confirmation/acquisition deadlines are exercised. Dropped Host-handle evidence is callback custody, not a mounted IPC-waiter claim. + +Retained diagnostics: V1 compiled 17 C0 tests and passed 16, but its pure-expiry fixture called `request_drain` first and thereby retired the generation; the real guard correctly returned Cancelled. V2 removes that injected cancellation from the pure-expiry scenario, keeps actual admission while held and checks expiry before requesting drain after callback return. Separate cancellation cases still exercise real held drain. V2 full test modes passed but strict Clippy rejected a complex test closure-vector type. V3 adds a named equivalent test type alias, with no suppression or production change, then reruns all ten final gates successfully. Historical failed/intermediate logs remain diagnostics, not final qualification. The pre-existing Cargo manifest warning about shared main-source targets remains recorded; ordinary builds do not select the explicitly gated qualification targets. + +Experience track: no renderer, shell, graphics, control, availability or user-data change. Native prompt/UI mounting, encrypted observation Save, qualified ingress and real denied/approved/changed/repeated/uncertain operator scenarios remain unfinished separate stages. UIC-1 source acceptance is still pending. All work stays local, uncommitted and unpublished on `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. GLM/Spark are not used and private source is not sent externally. Normal user data/keys, real providers/credentials, target operation, LNSAT/VUSL edits, dependency installation/fetch, native GUI, publication and release remain closed. + +## OpenShell native mounting design — October 20, 2026 + +Authority: the continuing independent-engine support goal and the existing [D2b-2b native credential/observation mounting gate](openshell-observation-connector.md#d2b-2b-mounting-sequence--proposed-october-20-2026). This is documentation and review of proposed source scope, not acceptance of credential implementation. The accepted D2b-2a host and synthetic bridge remain the implementation base. They do not authorize native provider credentials or production Start. The existing [intent record](intent.md#d2b-2a-synthetic-peer-native-host-acceptance--october-17-2026) retains acceptance authority; this ledger records evidence and the connector specification owns behavior. Root owns architecture, protected credential/lifecycle judgment, documentation, validation and final integration. + +Exact current ownership: `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. No production source, test, dependency, renderer, command, storage schema, toolchain or foreign repository change belongs to this design packet. The separately proposed C0 source packet names seven future paths; those are not current implementation ownership or acceptance. Preimages, the 692-file authored baseline and research evidence are retained in `/rangoon-openshell-mounting-design-20261020`. + +Three bounded native read-only lanes inspected credential APIs, storage lifecycle and task UX. Findings change the next implementation choice: the existing workspace-key vault is scoped to database-key envelopes, not provider-secret selection; the cloud credential webview path cannot satisfy this connector's native-only entry rule; durable observations require a typed schema/version plus inventory, deletion, retention, capture and strict restore integration. A session-only connection can therefore precede Save without silently storing provider data in existing capability/workflow tables. Root corrected proposed UX language that overstated authentication, cancellation or advanced-inspector disclosure: provider-reported permission denial is not verified identity, a stopped local callback does not prove no RPC/effect, and saved records remain distinct from session results. + +Primary platform documentation identifies possible native entry controls, not a qualified implementation. AppKit documents masked input and alert accessory views; Microsoft forbids combining generic credential return with secure-desktop prompting and requires clearing/freeing its returned buffer; GTK documents masked entry and password-purpose guidance. The specification links the primary pages. Apple browser extraction returned a JavaScript shell and rejected Markdown content, so public same-origin Markdown GETs were retained instead. No API example, OS prompt, credential or gateway was operated. Exact platform bindings, dependencies and three-OS lifecycle qualification remain unresolved; native masking alone is not memory-erasure or workstation-compromise resistance evidence. + +The proposed first source slice, **D2b-2b-C0**, adds native-owned selection/reference binding and acquisition custody inside existing Host pending/active state. It reuses generation admission, one-shot native confirmation, cancellation, callback drain and the client's immutable lease deadline. Memory acquisition doubles must compose with the existing real TLS-client path against synthetic peers. No parallel session/registry service, native prompt, OS vault, renderer mounting, production Start or provider is included. The proposed single absolute selection/lease deadline is at most 120 seconds from allocation; acceptance is still required and tests must not renew it at confirmation or acquisition. The seven-path ownership table and exact healthy/refusal/replay/expiry/drain/privacy validators are in the specification. C0 acceptance would not accept subsequent native OS input, durable observation storage or authenticated operator ingress. + +Experience track: retain catalog, central finite-read task and inspector, simple/advanced layering, persistent Stop, focus recovery and honest unavailable/unsaved/locked states. No shell redesign or new art is needed. Technical track: this packet resolves scope and sequencing only; it does not add a working connection or complete the denied, provider-policy allow versus approval, changed, repeated and uncertain-action matrix. Those scenarios still need qualified native source semantics and independently pinned OpenShell and LNSAT products. Neither engine depends on the other, and local workbench release does not depend on broad integration coverage. Saving unqualified encrypted observations never creates authenticated operator history or grants authority. + +Security/standards impact: no new data collection, secret access, persistence, authority, build privilege, dependency or telemetry. This design preserves explicit external-call consent, exact target/context identity, no ambient credential lookup, no plaintext fallback and fail-closed drain. ISO/OpenSSF targets remain development requirements, not certification or measured conformance claims. Public documentation GETs are the only external research in this packet. Native OpenAI `gpt_reader` (configured Luna medium) supplied two exact inventories; `gpt_ui_design` (configured Terra high) supplied a read-only UX proposal. Root integrates their evidence. GLM/Spark were not contacted and no private source was sent to an external provider. An independent native OpenAI explorer confirmed that C0 can attach a non-cloneable selection to Pending and acquire inside the existing Confirmed-to-Active callback. That check identified the required pre/post-acquisition cancellation/generation/deadline guards and fixed existing-error mapping; the proposal now records both. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) reviewed the frozen V2 three-document patch and supplied source/evidence: PASS, no actionable P1/P2/P3. The reviewer verified all three document hashes and the 689-path preservation receipt, without rerunning validators. This is proposal review, not source acceptance or support qualification. + +Validation passes: `node scripts/validate-review.mjs` checks 573 authored text files, eight image hashes, the historical brief and local Markdown targets; the exact three-path `git diff --check` reports no errors. All 689 outside-owned files, both lockfiles, the production source and compiler pin match the 692-file baseline. Exact commands and results are in `validation-v2.json` and `preservation-v2.json`; the frozen patch/hashes and independent review remain retained with the final status-only delta. Owner acceptance of C0 source/tests is still pending. No Rust or GUI rerun is necessary for documentation-only changes; previous source and closed 46-case native receipts remain bound to their original artifacts. All changes remain local, uncommitted and unpublished on `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Normal user data/keys, real providers/credentials, target launch, LNSAT/VUSL edits, dependency installation/fetch, publication and release remain closed. UIC-1 source acceptance remains pending and is not supplied by this design review. + +## OpenShell successful-read cancellation composition — October 20, 2026 + +Authority: the accepted [D2b-2a synthetic validation bridge](intent.md#d2b-2a-synthetic-validation-bridge-acceptance--october-18-2026) already requires callback custody, cancellation, replay refusal and no invented success after a failed or uncertain attempt. The current support continuation closes its composed successful-result boundary, rather than adding a provider or action protocol. Root owns protected lifecycle judgment, tests and validation. Exact ownership: `apps/desktop/src/openshell_host_tests.rs`, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. No production source, test-support API, native GUI harness, dependency, store, UI, credential path or foreign repository change is included. If a production defect appears, record it and reconcile exact correction scope before any fix. + +Existing source tests cover real transport cancellation of a stalled watch and real expiry held before callback return. Late successful callbacks were suppressed only with a canned host-test result; that is not a composed real-client success test. Use the existing real-client adapter's returned-result signal and callback-release barrier with a healthy loopback TLS peer. Require the actual successful protected-check and selected RecentLogs result, the exact allowed RPC ledger, and no host observation while the callback is still held. A positive control releases the callback and observes the same minimized result. Separate Stop, workspace close, exit-helper and native exit-coordinator source cases cancel after that actual result but before callback return; each must retain custody until release, suppress the late observation and refuse old consent/replay. This tests local observation custody, not an uncertain external action, provider cancellation, execution receipt or authority. + +Named validation: nonzero focused successful-result tests, full host tests, pinned Rust 1.99.1 locked/offline default and no-default desktop tests, formatting and warnings-denied Clippy in both configurations; document/reference and exact-path whitespace checks; outside-owned, lockfile and production-host preservation; fresh independent read-only review. Reuse existing synthetic peer/client support with dummy leases and bounded timeouts; no real provider or credential. Normal data/keys, target/engine operations, dependencies, publication and release remain closed. The earlier 46-case native artifact remains closed; no new GUI qualification follows. Baseline and four owned preimages: `/rangoon-openshell-success-cancel-20261020`. All seven named Rust gates pass. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source/evidence review passed with no actionable P1/P2/P3. + +### Composed successful-result evidence + +Five new tests use the unchanged `RealReadClient` callback barrier and actual healthy synthetic TLS responses. Every case receives and validates the successful protected-check plus selected RecentLogs `ReadOutcome` before triggering teardown. The exact RPC ledger is `Health`, `GetSandboxPolicyStatus`, `GetSandboxLogs`; it stays unchanged after rejected replay and teardown. The host remains Running with no completed observation while the callback is held. The control releases that callback, observes the exact returned result, then Stops and verifies fresh review requires a new ID while old consent stays unavailable. + +Four separate tests then cover Stop, workspace close, exit helper and the native exit source coordinator after transport success. Each verifies the selected path itself set cancellation before callback release, without invoking another canceller that could mask a failure. Callback admission keeps actual drain or close incomplete until return; release yields Cancelled with no retained observation or replay. The Stop/helper cases request a test-only Gate drain to measure custody; they do not claim those standalone APIs fence workspace admission. Native exit uses the existing source coordinator with its real first-close fence and bounded consent/callback state, not an actual Tauri event loop. The real successful read still occurred and remains in the synthetic RPC ledger: Cancelled describes host-session acceptance, not a provider denial, undo, revocation or evidence that an external effect never occurred. Each peer explicitly shuts down and joins. + +| Gate | Result | +| --- | --- | +| Focused `openshell_host::tests::real_client_success_` | PASS: five tests executed; zero library matches do not count. | +| Full `openshell_host::tests::` | PASS: 46 tests. | +| Default desktop tests, locked/offline | PASS: 172 library + 491 binary + 22 documentation = 685; four ignored entries remain unqualified. Nested child output is not counted twice. | +| No-default desktop tests, locked/offline | PASS: 43 library + 301 binary + 22 documentation = 366; one ignored entry remains unqualified. | +| Desktop formatting | PASS. | +| Warnings-denied all-target desktop Clippy | PASS in default and no-default-feature configurations. | + +The seven exact command arrays, pinned tool identities, times, exits and retained logs are in `final-validation.json` and `final-*.log` in the evidence directory. All use Rust/Cargo 1.99.1, verified compiler/rustdoc/format/Clippy subprocesses and locked offline dependencies; loopback permission covers only disposable synthetic test peers in this validation scope. No production source changed, so the prior packet's source build evidence remains separate rather than being reported as a new build here. Focused/full counts overlap and are not a product feature count. Ignored OS-vault/native cases remain unqualified. + +Experience/security track: no UI, command, availability, authority, storage/schema, secret handling, dependency, build policy or telemetry change. These tests extend evidence for existing observation custody; they do not implement live connections, structured action decisions, approval chains, verified cross-engine relations or a complete operator record. Production Start remains unavailable. ISO/OpenSSF assessment and native GUI/three-OS/release qualification remain distinct. Root OpenAI Codex owns test production and executable validation; native OpenAI `gpt_reader` (configured Luna medium) supplied exact existing-seam evidence and a fresh OpenAI `gpt_reviewer` (configured Terra xhigh) independently reviewed the exact four-path patch, hashes and supplied validation evidence without rerunning tests. GLM/Spark were not contacted; no private source was transferred externally. Documentation/reference checks pass for 573 authored text files, eight image hashes, the historical brief and local Markdown paths; exact-path whitespace checks pass. All 688 outside-owned baseline files, production host source, both lockfiles and the compiler pin remain exact. All changes remain local, uncommitted and unpublished on `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; normal data/keys, real providers/credentials, LNSAT/VUSL and the closed native nonce remain untouched. + +## OpenShell prepare/close custody correction — October 20, 2026 + +Authority: the accepted [D2b-2a native host contract](intent.md#d2b-2a-synthetic-peer-native-host-acceptance--october-17-2026), its accepted synthetic bridge and the continuing independent-engine support goal. This is a bounded correction to the already accepted generation/cancellation invariant, not new connector functionality or production Start acceptance. The tests-only composed-lease continuation does not own this production correction; this receipt reconciles its exact scope back to the accepted host implementation. Root owns protected lifecycle judgment, implementation, validation and final integration. A native OpenAI explorer independently traced the candidate interleaving; fresh independent read-only review of the final patch remains required. + +Exact owned paths: `apps/desktop/src/openshell_host.rs`, `apps/desktop/src/openshell_host_tests.rs`, `docs/openshell-observation-connector.md`, this ledger and `docs/continue.md`. No client, Gate, close coordinator, store, renderer, command, permission, dependency or lockfile change is included. The unchanged production Start remains unavailable; tests use synthetic custody only. Do not expand this packet if another production owner becomes necessary. + +The pre-correction host checks admission before acquiring its state mutex. Close can fence the generation and purge visible pending state while preparation is paused before that mutex, after which preparation can retain a stale lease. The normal close poll waits for quiescence before final cleanup, so that hidden pending lease can prevent drain. Existing tests close after preparation returns and do not exercise this publication boundary. This is a pre-activation lifecycle liveness gap, not evidence of provider contact, unauthorized execution or current user-data compromise. + +Plan: extract the existing private pending-publication step without changing behavior; add a deterministic regression that retains real admission across the actual close/purge boundary and then invokes that same production publication step. Preserve a failing pre-fix result. Recheck generation under the host-state mutex before retaining the pending review, so a raced preparation drops its lease rather than retaining it after purge. Also cover healthy preparation and the complementary ordering where publication precedes close. This adds no public API, callback hook or alternate test implementation. + +Named validation: the focused regression and full host tests with a nonzero executed count; pinned Rust 1.99.1 locked/offline default and no-default desktop tests, format, warnings-denied Clippy and builds; existing synthetic-peer client conformance; document/reference and exact-path whitespace checks; outside-owned and lockfile identity preservation; fresh independent source/evidence review. No native GUI process is launched. The earlier 46-case result remains bound to its closed, unchanged artifact and does not qualify this new source. Normal user data/keys, real credentials/providers, foreign edits, dependency installation/fetch, publication and release remain closed. Evidence baseline and five preimages: `/rangoon-openshell-prepare-close-20261020`. Implementation and all nine named Rust gates now pass. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) source/evidence review passed with no actionable P1/P2/P3. + + +### Correction and validation evidence + +Production preparation now delegates only its existing private publication continuation to `retain_review`. Under the same Host mutex used by purge, it checks the original admission again before retaining pending state. If close fenced and purged first, the stale continuation returns `Unavailable` and drops its lease. If publication won first, close obtains the mutex afterward and purges the retained lease. The early check remains as a fast refusal; no current-generation reset, alternate Gate, timer, test callback hook or public API was added. + +The deterministic regression uses actual Managed request admission, the real `WorkspaceClose` with its existing memory-only SourceAccess fixture and the real Host purge/publication functions. With only the behavior-preserving extraction, one executed test failed with `(Ok(()), true, Ok(false))`: stale publication succeeded, pending custody survived and actual native close could not finish. After the mutex-protected check, the same test passes with `(Err(Unavailable), false, Ok(true))`. A second regression covers the complementary publication-first ordering for both Awaiting and Confirmed reviews; close purges each, old confirmation refuses and production Start remains unavailable. No sleeps, probabilistic scheduling, fake close implementation, provider or credential is needed for these two regressions. The initial weaker assertion failure is retained separately, alongside the stronger final pre-fix failure. + +| Gate | Result | +| --- | --- | +| Exact pre-fix regression | Expected failure: one test executed, exit 101, stale-pending/drain tuple observed. | +| Exact post-fix regression | PASS: one test executed, exit 0. | +| Full focused `openshell_host::tests::` | PASS: 41 tests; the separate library's zero matching tests is not counted. | +| Desktop default tests, locked/offline | PASS: 172 library, 486 binary and 22 documentation tests = 680; four ignored entries remain unqualified. Nested child output is not counted again. | +| Desktop no-default-feature tests, locked/offline | PASS: 43 library, 296 binary and 22 documentation tests = 361; one ignored entry remains unqualified. | +| Desktop formatting | PASS. | +| Desktop warnings-denied all-target Clippy | PASS in default and no-default-feature configurations. | +| Desktop executable build | PASS in default and no-default-feature configurations; no GUI launch or installer. | +| Existing opt-in synthetic-peer client suite | PASS: 32 tests; no client source changed. | + +All Rust commands use verified Rust/Cargo 1.99.1 with pinned rustc/rustdoc/rustfmt/Clippy subprocesses, `CARGO_NET_OFFLINE=true`, no incremental compilation and unchanged dependencies. The source runner records exact argument arrays, times, exits and logs in `red-validation.json`, `green-validation.json` and `final-validation.json` under the evidence directory. Full host/client suites used the accepted disposable loopback TLS peers and dummy leases with local-listen permission; no real gateway or provider credential was used. The inherited multi-target manifest warning was retained, not suppressed. No test or ordinary Cargo invocation launched either custom native GUI harness. + +Experience track: no UI, state label or availability changed. Technical/security track: close cannot hide a newly retained stale pending lease after its purge pass; current exact identity, consent and provider-independent behavior remain. No crypto, schema, storage, secret serialization, dependency, build privilege or telemetry change. This supplies bounded lifecycle evidence, not ISO/OpenSSF conformance or native GUI/three-OS/release qualification. Production Start stays closed. Final document/reference and exact-path whitespace checks pass (573 authored text files and eight image hashes); all 687 outside-owned baseline paths, both lockfiles and the root compiler pin remain exact. This repository has no Graphify index, so no generated graph update applies. Focused and full test counts overlap and are not feature counts. Root OpenAI Codex produced and validated the correction; the fresh read-only reviewer checked the five-file incremental patch, hashes and supplied logs without rerunning them. GLM/Spark were not used; no private source was transferred externally. All changes remain uncommitted and unpublished on `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; inherited unrelated work remains intact. The old 46-case storage/native result remains attached to its original artifact, not these new source bytes. UI correction acceptance and target-load runtime qualification remain separate. Complete connected operator support, structured per-action decision sources and trusted cross-runtime relations remain unfinished; none follows from this mutex correction. + +## Unified Rust toolchain — October 20, 2026 + +Authority: Jeff's explicit [unification instruction](intent.md#unified-rust-toolchain--october-20-2026). Rangoon's portable and desktop workspaces now share Rust `1.99.1`, matching the inspected VUSL compiler floor. One root `rust-toolchain.toml`, both Cargo manifests, the source validator, CI and current setup/architecture instructions agree. This is compiler alignment, not VUSL consumer integration. Dated receipts retain their original compiler identities. + +Root OpenAI Codex owns build/CI/MSRV decisions, protected source corrections, documentation, integration and validation. A disjoint OpenAI `gpt_worker` (configured Terra high) produced the two validator files; another produced only the five named operations-condition files. An OpenAI `gpt_reader` (configured Luna medium) independently checked active setup/version references. Fresh whole-packet read-only review passed with OpenAI `gpt_reviewer` (configured Terra xhigh), with no actionable P1/P2/P3 findings. The earlier checker-specific P2/P3 findings are corrected and independently closed. GLM was not contacted; native lanes were adequate and no private source was transferred externally. + +The validator checks all seven installed component identities: rustc, rustdoc, Cargo, rustfmt, cargo-fmt, cargo-clippy and clippy-driver. It pins child executables/PATH, rejects compiler-wrapper overrides, disables configured wrappers only in child processes and sets `RUSTUP_AUTO_INSTALL=0`. `--check-config` is static; `--toolchain-bin` accepts an already provisioned absolute tool directory. CI retains its seven-job matrix, pinned actions and read-only token permission, checks shared version coherence before explicit provisioning, then uses the same validator for core and desktop. No hosted run was triggered. + +Exact thirty-eight-path ownership, preimages and the 690-file baseline are in `/rangoon-rust-alignment-20261020`; [intent](intent.md#unified-rust-toolchain--october-20-2026) owns the file list. Compiler-required source changes are limited to equivalent conditional let chains, unsigned leap-year divisibility, constant-size chunk iteration and the new name for one test-only atomic helper. Existing guards, diagnostic order, mutex custody, cancellation, pin validation, fixture bytes and expectations remain intact. No lint suppression was added. The retired language parser's production source stays unchanged. Both lockfiles and dependency versions remain exact. Preservation confirms 690 original authored files plus only the two accepted additions (`rust-toolchain.toml` and the validator test), 36 modified owned paths, no missing/unexpected path and all 654 outside-owned paths byte-identical. The 692-file source freeze is `source-freeze-v3.json`; only owned documentation changes follow that freeze. Final hashes/diff and the review receipt are retained in the packet directory. + +Read-only VUSL inspection initially observed `1697a71a35b0508c0dc28bf434d58df9c33c8967`. Its independently active chat advanced HEAD to `7f377c4b119b8fae6474e2bb95f2fc66d2fd7608` during validation; the tracked compiler pin and MSRV still match `1.99.1`. No VUSL or LNSAT file was edited by this packet. The existing isolated `/vusl-native-tools/rust/bin` supplies rustc/cargo 1.99.1, Clippy 0.1.99 and rustfmt 1.10.0; compiler commit `58cf8f9c35b355199727627d07ae34a4e2846d67`, host `x86_64-apple-darwin`. Initial ambient rustup inventories printed stable/1.99.1 channel-sync notices; no installation completed. That inventory path was stopped. Final compiler commands use exact installed paths and offline Cargo; no dependency or tool installation occurred. Network behavior of the earlier inventory notices was not instrumented. + +Final source gates pass on the frozen source. All Rust commands use `CARGO_NET_OFFLINE=true CARGO_INCREMENTAL=0`, the explicit tool directory and the validator's pinned child environment. Counts use the final top-level Cargo suite results, excluding duplicate nested child-process output: + +| Gate | Result | Evidence under the packet directory | +| --- | --- | --- | +| Shared pin, syntax and validator regressions | PASS; 7 Node tests | `validator-final.log` | +| Core validator: format, workspace tests, all-target warnings-denied Clippy | PASS; 629 tests, 8 intentionally ignored helpers | `core-final-v4.log` | +| Core `cargo build --workspace --locked` in the same pinned environment | PASS | `core-final-v4.log` | +| Desktop validator: format, default tests, all-target warnings-denied Clippy and build without installers | PASS; 678 tests, 4 intentionally ignored helpers | `desktop-final-v2.log` | +| Desktop no-default tests, all-target warnings-denied Clippy and build in the same pinned environment | PASS; 359 tests, 1 intentionally ignored helper | `desktop-final-v2.log` | +| Preview syntax, assets, vision and behavior | PASS; 463 Node tests | `preview-check-v2.log` | +| Documentation, CI static coherence, preservation and fresh independent review | PASS; 573 authored text files, all 654 outside-owned paths and both lockfiles exact; no actionable P1/P2/P3 | `docs-final.log`, `ci-static-final.json`, `preservation-final.json`, `independent-review-v3.md` | + +Earlier failed Clippy/formatting/preview-listener runs and the source-overlapping desktop run remain diagnostic receipts, not final qualification. In one rerun the controller used edition-2021 formatting on three edition-2024 fixture files; the exact edition-2024 formatter corrected it before final checks. Compiler diagnostics were fixed without suppressions or changes to fixture expectations. Preview's first run could not bind its disposable loopback listener inside the sandbox; its permitted synthetic-listener rerun passed all 463 tests. Existing Cargo duplicate-target metadata warnings remain visible; strict Rust/Clippy gates pass. Exact commands, component identities and test counts are retained in `validation-final.json` and the named logs. + +Experience track: no layout, animation, route, control, unavailable state or artwork change. Technical/security track: this updates build inputs and compiler validation without changing authority, provider consent, persistence schema or cryptographic behavior. CI keeps pinned actions and least privilege. The ISO/OpenSSF readiness track still requires independent OS/artifact, dependency inventory and release evidence; a compiler pin or local source pass establishes no certification, supply-chain level or product readiness. + +Before source-pin changes, the stopped accepted E1c-5e nonce `46ccc0e368c1b415b1808ce1264592c9` completed exact cleanup with five events, registered-slot absence, parent exit 0 and no failure. Its log remains `/rangoon-e1c5e-source-20261020/native-repeat-cleanup-v4.log`. No normal key/data was accessed. Historical opening and the full 46-phase native journey remain incomplete; old native artifacts cannot qualify the new compiler. Windows/Linux/new native GUI qualification and VUSL adoption remain separate gates. No real target/model/provider operation, normal user data/key access, foreign-repository write, commit, push, merge, deployment or release occurred. + +## E1c-5e Rust 1.99.1 native follow-through — October 20, 2026 + +Authority remains Jeff's [accepted E1c-5e disposable macOS packet](intent.md#e1c-5e-ordinary-lock-handoff-acceptance--october-20-2026), following the completed Rust alignment above. This is validation and two canonical status documents only; no source, harness, policy, dependency, permission or UI implementation changes. Root OpenAI Codex owns native process/UI control, exact disposable custody and evidence; native GPT read-only lanes inspect commands, source/artifact identities and captured UI. GLM is not contacted. The prior goal turn made concrete progress by completing the shared compiler prerequisite; this follow-through resumes the accepted storage/lifecycle qualification rather than adding another disconnected feature. + +The new evidence directory is `/rangoon-e1c5e-native-rust199-20261020`. Its baseline contains all 692 authored regular files; only `docs/development.md` and `docs/continue.md` may change. All source, configuration, assets and test inputs were byte-identical before native preparation. The accepted ten locked/offline native source gates pass with explicit installed Rust 1.99.1, including the custom encrypted target build, format, both all-target/default and no-default tests, both documentation suites, both warnings-denied Clippy variants and both all-target builds. The 38 Python parent-oracle tests pass; the unchanged renderer/lifecycle source is also covered by the preceding complete 463-test Node pass. `native-source-gates.json`, `native-source-gates.log` and `parent-tests.log` retain commands/results. Existing custom-target unused-test/import and duplicate-target metadata warnings remain visible; this does not call the custom target lint-clean. + +Accepted NX-06 native event qualification also reran against the new compiler with sanitized inherited environment and synthetic loopback peers: all six distinct cases and two active/timeout repeats pass, with the expected 0/4/37 exit codes and actual child callback/exit observations. Three invalid-argument cases refuse. Evidence is `nx06/` and `nx06.log`; no production Start, provider credentials or remote engine was used. These bounded results do not qualify connected providers or a released desktop. + +The encrypted parent created new nonce `dfe72a24d4db26ce274efbaf9c649ebf`, source `f086d06312cb464ffbd4829706f5a1049265f263c6fd43bd98c01f007bba550c`, executable `66efdaf5f944e6b5f89eea0d12aabb6281af6633cfed52405420ad48453e5e00`, unchanged 46-phase plan `ba72790c56048b2fe5cb4de72b5c565d6b1f739033bcec72ce45e8bf1f56425b`, macOS 26.0, Mach-O x86_64. The copied disposable bundle, original executable and wrapper/directory identities are bound by the parent manifest. The root toolchain pin and all authored inputs are additionally frozen in `before.json`/`prelaunch.json`; the unchanged parent source digest does not independently include the newly added toolchain file. Its existing offline build used only the explicit installed tool directory first on PATH, with no configured compiler wrapper. No tool or dependency installation occurred. This artifact has zero completed encrypted native phases at this checkpoint; old nonces/compilers cannot supply its missing evidence. + +The first `cold-cancel` launch used the restricted shell sandbox and terminated with SIGABRT (-6) after context validation, before Ready or any observed vault event. Its exact crash report identifies macOS RegisterApplication/AppKit registration; stderr was empty. CUA app selection then timed out and supplied no successful binding or action evidence. The cause remains bounded to that observed launch until a permitted desktop rerun distinguishes the environment. The parent failed honestly with “missing native Ready”; no GUI qualification credit follows. Exact cleanup of nonce `dfe72a24d4db26ce274efbaf9c649ebf` passed with an empty slot registry. Never reuse its one-shot permit. See `launch-diagnostic.json`, `cold-cancel.log` and `failed-run-cleanup.log`. + +A new parent-created run supplied the accepted desktop-permission rerun: nonce `a973d4064a2dcd1172cdcc14cb504c3a`, unchanged source/plan, executable `7d0b526d4783f10cb10e56bc03d7c81e5690dd2fb5f0d2715058f4c90dfd8442`. The first prelaunch guard correctly refused to equate this with the prior executable. Both files have the same size and identical code/data bytes; all 1,792 changed bytes are seven-character temporary object suffixes in 256 debug-symbol object-path strings. This is evidence about these two local debug files, not a reproducible-build or functional-equivalence claim. Fresh independent artifact review passed with no actionable P1/P2/P3 before launch. Treat the complete new executable hash as distinct. `rebuild-artifact-delta.json`, `rebuild-symbol-string-analysis.json`, `independent-native-permissions-artifact-review.md` and `native-current.json` preserve the distinction. Native-permission launches reached actual Ready; CUA binding followed parent-observed Ready and a confirmed live exact child. + +The selected run completed the following bounded observations. Parent-oracle success and UI qualification remain distinct: + +| Phase | Actual result | Qualification limit | +| --- | --- | --- | +| Cold setup cancellation | Parent exit 0, 14 events; actual native Cancel; zero vault opens/reads/writes, no content client and clean exit | Dark 1440×900 captures show safe return; a setup-action continuity issue remains below | +| Fresh-process cold relaunch | Parent exit 0, 13 events; first-launch setup remains available; native Cancel again leaves zero vault activity | Not an encrypted-data unlock or content-relaunch test | +| Concurrent busy owner | Parent accepts expected child exit 4, 9 events; actual second process refuses before any vault access or content client | Run while the authoring child remained live; no second-window UI action was used | +| Authoring | Failed: parent exit 64, child SIGKILL (-9), 49 events; `RuntimeError: case exceeded 20-minute native UI limit` | No full authoring/lifecycle/header or GUI pass; partial UI observations cannot override the deadline failure | +| Exact slot cleanup | Parent exit 0, 5 events; exact nonce/account delete and independent `slot_absent` readback | Only this disposable slot; normal user keys/data remain untouched | + +The actual native authoring UI used the existing synthetic `fixtures/contracts/AGENTS.md` through the OS picker: 144 bytes, source digest `453acea7707fd5d102d47c0539950f5d93cd997561e704db516548761ab4b42d`. Save and reopen preserved the visible original, including `café`. Two capabilities were created from exact review/evidence spans (bytes 28–87 and 87–144); the first received a second immutable revision and local review. Both local reviews retained authority `none`. A Rust-calculated merge preview copied both pinned inputs into a 152-byte output, then saved the composition with an unreviewed result. The reviewed 93-byte revision compiled under the AGENTS.md text profile to digest `34bf139a4ac209d80bd7c5cb3e44419505b996b5d36860eeeccd552f4aa238ed`. The actual native Workflows route saved and reopened “Encrypted authoring fixture” as a read-only draft with one input node and four explicit structural issues; this proves draft persistence observations, not a valid or executable workflow. Five screenshot/AX pairs under `ui/authoring-01` through `authoring-05` retain these states. No example/playground route supplies native persistence evidence. + +The real Reload action reached the armed read barrier before its OS read. Actual UI Lock confirmation removed the content client and closed request admission while the read remained held. Parent release returned the read, then native state reached Locked with no client, requests unavailable and clean closure (events 42–49). The unchanged twenty-minute phase deadline expired immediately afterward, before confirmed Unlock, header probes, historical opening or the planned clean exit. CUA observation timed out after the child had been terminated; no missing app was rebound or silently relaunched. Two stale-index action errors during earlier rerenders were followed by fresh AX inspection; neither was retried blindly and both completed states were verified. The timeout is a failed qualification attempt, not proof of a product unlock defect or user interference. + +After stopping all exact claimed children, bounded read-only storage inspection found the disposable database at 94,208 bytes, mode 0600, without the plaintext SQLite header. This narrow observation is not cryptographic assurance, complete residue analysis or a release pass; no test key was retrieved and no post-stop decrypted content inspection occurred. Cleanup removed the only registered test key and confirmed its absence. Encrypted test bytes/evidence remain retained. Tauri reported shared test-identifier app-data/cache paths under `~/Library/Application Support/si.rangoon.encrypted-qualification` and `~/Library/Caches/si.rangoon.encrypted-qualification`; do not claim all effects stayed inside the nonce directory or that general memory/cache zeroization was qualified. + +Fresh OpenAI `gpt_ui_review` (configured Terra xhigh) review of the three actual cold-Cancel captures found one P2: the return screen changes “Set up encrypted workspace” to generic “Set up workspace,” changes the Details label and removes the explicit Quit action required by the fresh/control-only setup contract. Safe backend cancellation still passed. Preserve this open finding; a separate bounded UI correction and fresh capture checks are needed, rather than editing the frozen artifact or rewriting the requirement. The same read-only reviewer then inspected all five actual authoring screenshot/AX pairs: no additional actionable P1/P2/P3; the grouped navigation, central task and right inspector remain coherent, with exact provenance, local-review/authority separation and read-only workflow history visible. The supplied dark captures showed a restrained hierarchy and no horizontal crop; other themes, widths, keyboard/assistive behavior and a full task usability pass remain unqualified. No Locked screenshot, Unlock or request-header qualification was supplied. Final source/evidence review is recorded separately when complete. + +`native-follow-through-result.json` retains per-case results, selected identities, observed content digests, the bounded database-header check and limitations. Both current and earlier failed nonces are closed with exact cleanup; no child is running. The source freeze and new root toolchain pin were checked before every phase, with all 690 outside-owned inputs unchanged. A final read-only pin comparison still finds Rust 1.99.1 in both Rangoon and VUSL. This follow-through changes only the two named status documents and local test evidence; no new source, README publication packet or foreign-repository change is included. + +The selected nonce is now closed. A new attempt must use a fresh parent-created run and one immutable selected source/executable/plan; do not reuse one-shot permits or aggregate other artifact hashes. Follow the plan's prerequisite graph: `busy-owner` requires `authoring` to remain live and must run before that parent exits; the JSON case listing is not a sequential schedule. Pre-plan the actual UI sequence within the unchanged deadline. Do not lengthen limits or substitute synthetic IPC/consent to turn a failed run green. Header probes require captured current client, real held-read Lock/drain, Locked observation, independently confirmed Unlock and a distinct current client. Historical revision opening and the remaining 46-phase journey still need actual evidence. Final independent source/evidence/UI review remains required. Test screenshots and observations are evidence only for their recorded states; source tests or a clean exit never establish full qualification. + +Experience/security/standards impact: no design or authority change; this verifies actual encrypted startup, lifecycle and disposable OS custody before later usability work. Normal user data/keys, ordinary workspaces, model/provider calls, LNSAT/VUSL edits and publication/merge/deploy/release remain closed. Test keys may exist only after actual native consent in the fixed run namespace; exact registered-slot cleanup is mandatory before closure. Real target loading, connected-engine operation, Windows/Linux/arm64 and package/release qualification remain separate. No encrypted phase or full-matrix pass is claimed before its actual receipts. + + +### E1c-5e native authoring, restart, export and key-loss checkpoint + +The continuing accepted E1c-5e validation packet now has a successful authoring journey on a new parent-created nonce, without source, harness, permission, plan or deadline changes. Root OpenAI Codex owns actual process/UI/custody operations and these two status documents. OpenAI `gpt_reader` (configured Luna medium) mapped exact case/consent prerequisites; fresh OpenAI `gpt_reviewer` and `gpt_ui_review` (configured Terra xhigh) independently checked preparation and captured states. GLM was not contacted and no private source was transferred externally. The evidence directory is `/rangoon-e1c5e-native-rust199-retry-20261020`; it freezes all 692 authored regular files and permits only `docs/development.md` and `docs/continue.md` changes. All 690 other inputs, both locks and the root compiler pin remain exact. Previously passed ten native source gates, 38 Python parent tests, 463 renderer tests and NX-06 results apply to this unchanged source; they were not rerun merely to replace actual native evidence. + +First retry nonce `c12a64d067a9270c693a6001b58e5280` passed cold cancellation/relaunch and concurrent busy-owner refusal but did not complete authoring. Several actual Go-to-Folder actions reset its displayed path; no product defect or outside user activity is inferred. Keypad Enter eventually resolved the exact synthetic path, after which actual picker Cancel released the callback held by an already-requested Quit. Native cleanup drained and child exit 0 was observed; parent correctly failed with `RuntimeError: required header probe did not run` (parent exit 64). Exact registered-slot cleanup passed with `slot_absent`. Its phases never contribute to the selected run's pass count. A local operator-plan omission and later nonce-bound preflight-record gap were independently found, corrected and re-reviewed before the next launch. No acceptance rule or source guard was relaxed. A compact observation helper timed out; direct CUA observations of the same live child remained available, so no child was restarted on that observation timeout. + +Selected nonce `4f2d3497f32b886e8dc5bca51bf2155e` binds source `f086d06312cb464ffbd4829706f5a1049265f263c6fd43bd98c01f007bba550c`, executable `7d0b526d4783f10cb10e56bc03d7c81e5690dd2fb5f0d2715058f4c90dfd8442`, plan `ba72790c56048b2fe5cb4de72b5c565d6b1f739033bcec72ce45e8bf1f56425b`, macOS 26.0 and x86_64. Fresh artifact review passed before any phase; `artifact-resolved.json`, `manifest-resolved.json` and `prelaunch-resolved.json` retain exact identities, all-input hashes and the initial zero slot/permit/claim/receipt state. Native launches used the accepted desktop permissions and sanitized environment. Every CUA binding followed actual Ready and a live exact PID. Busy-owner ran while authoring remained live and stopped before original-owner UI control resumed. Per-phase input checks are retained in `case-input-checks.jsonl`. + +| Selected-run phase | Parent result | Bounded evidence | +| --- | --- | --- | +| `authoring` | PASS; child/parent 0, 61 events, required headers verified | Actual OS setup, selected source, immutable revision/review, merge, compile, draft-workflow save/open; held-read Lock/drain, independent Unlock, reloaded Skills, historical opening and exact request probes | +| `busy-owner` | PASS; expected child 4, parent 0, 9 events | Concurrent second process refuses before vault access or content admission | +| `relaunch` | PASS; child/parent 0, 17 events | Existing-key Unlock in a new process, exact original source/digest and saved workflow revision readback | +| `export` | PASS; child/parent 0, 19 events | Unavailable encrypted recovery export refused before native picker/file; deliberate synthetic plaintext instruction export and native external reinspection separately observed | +| `lose-key` | PASS; child/parent 0, 5 events | Delete only the exact registered test slot and independently observe absence | +| `missing-key` | PASS; child/parent 0, 13 events | Actual native Unlock consent, vault read, zero replacement writes, no client and source-free recovery-required screen | +| `cold-cancel`, `cold-relaunch` | PASS; child/parent 0, 13 events each | Actual native cancellation, zero vault activity and setup still available after process restart; UI continuity finding remains open | +| `anchor-failure`, `cleanup-failure`, `window-failure` | PASS; expected child 4, parent 0, 6 events each | Actual bounded pre-admission failures; no content client or vault access | + +The authoring UI used the existing 144-byte synthetic AGENTS.md fixture, digest `453acea7707fd5d102d47c0539950f5d93cd997561e704db516548761ab4b42d`. Original Unicode and exact spans survived Save, Open, Lock/Unlock and fresh-process Open. The 59-byte historical revision reopened read-only, with Save/review disabled and current revision still separately identified. The new 93-byte revision compiled to digest `34bf139a4ac209d80bd7c5cb3e44419505b996b5d36860eeeccd552f4aa238ed`; a 152-byte merge retained both pinned inputs and unreviewed/non-authoritative output. The native workflow remained an explicitly incomplete one-input draft with four structural issues, not an executable or valid workflow. Its saved revision reopened read-only in the same and a later process. The closed source state removed task navigation/content; independent Unlock reloaded the actual Skills workbench. Header probes observed a distinct current client: missing/stale requests each caused zero vault reads/writes; the current request caused one read and no write. All probes used the accepted real WebView/native request path, not a substitute grant or restored client. + +Selected database evidence after key loss: 94,208 bytes, mode 0600, digest `2831f221022bc5444cdd4c1d8842af2c24f4279f48455533d1389b5f3d32e042`; no plaintext SQLite header or known synthetic revision bytes were visible. A normal SQLite connection opened only with `mode=ro` refused its schema with `file is not a database`, and the database hash remained unchanged. These are bounded at-rest observations combined with actual encrypted-app reads; they are not cryptographic certification, rollback resistance, complete metadata/residue analysis or OS-release qualification. No key was retrieved for this probe. + +The separately selected plaintext instruction file is retained only under the evidence directory's `exports/`, outside managed workspace layout: 1,259 bytes, digest `f139de74e1c848cb7a5527c7a28c7d1e762344ccb160b67343d6c14478a2bb8f`. The actual native UI reported that Rangoon’s external-bundle inspection passed internal-consistency checks, with the selected file and 93-byte artifact digests matching the separately hashed bytes. Its screenshot/AX capture is the UI evidence; the source-free lifecycle receipt does not carry an inspection payload, and no second independent reader implementation was run. Origin authentication, complete lineage, target adherence and execution authority remain unproven. A generic JSON inspection was inapplicable to this framed format; it supplied no validation. The recorded native UI inspection and separate exact file/content digest checks own that bounded evidence. Workspace-wide archive export instead returned `encrypted_recovery_unavailable` before any destination picker or archive creation. Do not confuse this deliberate instruction export with a plaintext database fallback. + +Fresh read-only UI review passed the supplied actual dark 1440×900 Lock, historical, merge, compile, saved-workflow, restart and instruction-export states, with three open P2s: (1) setup-Cancel changes canonical labels and removes Quit; (2) the managed Data page and its confirmation still advertise unavailable unencrypted backup; (3) missing-key recovery exposes no visible next action beyond collapsed technical details. The backend refusals and source-free recovery state held; these findings concern truthful availability and recovery guidance, not evidence of an authority or encryption bypass. Expanded recovery details, light/compact/assistive states and other OSs were not reviewed. Preserve the findings for a separate bounded UI correction; do not edit the frozen artifact or claim the entire UI passed. + +This checkpoint has 11 successful parent phases, not a completed 46-phase matrix. Thirty-five phases remain, including interrupted setup/relaunch, empty/populated Legacy conversion, cancellation, distinct-process verification, crash/recovery/selection chains and final exact global cleanup. `current-parent-results.json`, `database-checkpoint.json`, `export-result.json` and `key-custody-checkpoint.json` retain results. All exact claimed children are stopped. The only registered test key was removed by `lose-key`, confirmed absent, and was not regenerated by missing-key Unlock. The selected nonce remains in progress; its one-shot global `cleanup` case has not been consumed. Continue only unrun cases against the same selected source/executable/plan and exact roots; never reuse a completed phase or count another nonce's results as this run. Test-identifier app-data/cache effects retain the previously disclosed shared paths. Normal user data/keys, models/providers, external engines, LNSAT/VUSL edits, dependency fetches, commit/push/merge/deploy/release remain untouched. Source and artifact inventories are evidence for the existing security/standards track, not ISO/OpenSSF certification or production readiness. + +### E1c-5e conversion, cancellation and recovery checkpoint + +The same accepted validation packet and unchanged selected nonce now have 34 successful parent cases, adding 23 to the earlier eleven-case checkpoint. This continuation changes only `docs/development.md` and `docs/continue.md`; source, harness, case plan, artifact and deadline remain frozen. Root OpenAI Codex owns native UI/process operations, custody, integration and the two records. OpenAI `gpt_reader` (configured Luna medium) mapped exact prerequisites and consent purposes; fresh OpenAI `gpt_ui_review` and `gpt_reviewer` (configured Terra xhigh) independently review actual captures and receipts. GLM was not contacted; no private source was transferred externally. The evidence directory's `batch2/preimage/docs/` retains this continuation's exact document preimages. + +| Additional phases | Parent result | Actual bounded evidence | +| --- | --- | --- | +| `interrupted-setup`, `interrupted-relaunch` | PASS; intentional child -9 at real-key provisioning barrier, then clean child 0 | Real CreateEmpty confirmation and one successful key write precede parent termination. Relaunch shows source-free Workspace unavailable with Quit and expanded details, zero vault activity and no content client. This is not a successful resume or normal Unlock. | +| `legacy-empty-copy`, `legacy-empty-verify`, `legacy-empty-relaunch` | PASS; child/parent 0, respectively 18/14/18 events | Actual native Copy, later distinct-process Verify, then separately confirmed normal Unlock; all nine inventory counts remain zero and original is retained. | +| `legacy-rich-copy`, `legacy-rich-verify-cancel`, `legacy-rich-verify`, `legacy-rich-relaunch` | PASS; child/parent 0, respectively 18/12/15/18 events | Complete populated copy; Cancel preserves Verify required with no vault access; fresh Verify does not unlock; separate normal Unlock opens the complete saved inventory. | +| `legacy-review-cancel`, `legacy-review-relaunch` | PASS; child/parent 0, 12/11 events | Actual Cancel review returns to the unassessed original state; restart requires fresh review. No native copy consent, destination or key is created. | +| `legacy-copy-cancel`, `legacy-copy-relaunch` | PASS; child/parent 0, 13/11 events | Native Copy Cancel and later restart preserve original-only routing and require fresh review/copy confirmation; zero key activity. | +| `recovery-empty-crash`, `recovery-empty-cancel`, `recovery-empty-resume`, `recovery-empty-verify`, `recovery-empty-relaunch` | PASS; intentional crash child -9, other children 0; 13/12/18/15/18 events | Parent kills exactly at `destination/after_confirm`. Inspect Cancel causes no vault access. Separately confirmed inspection and Restore use the existing key and exact proven-empty target, refuse overwrite, record parity, require restart verification and independent normal Unlock. | +| `recovery-parity-crash`, `recovery-parity-cancel`, `recovery-parity-resume`, `recovery-parity-verify`, `recovery-parity-relaunch` | PASS; intentional crash child -9, other children 0; 15/14/16/15/18 events | Parent kills at `destination/after_restore`. Inspection reads the existing key; Record copy Cancel leaves recovery closed. Later inspection and Record copy recognize complete matching records without repeating Restore, then require fresh-process Verify and normal Unlock. No replacement key is written. | + +All 23 parent receipts have null `parentFailure`, verified phase exit and the same selected source/executable/plan identities. Expected crash deaths and admission refusals are positive cases only for their exact parent oracles; they are not ordinary application success. The parent receipts retain `nativeCaseVerdict: unassessed; inspect UI evidence and case-specific assertions`; do not relabel that machine field as a whole-UI verdict. Actual CUA captures and fresh UI review supply separate evidence for the observed controls. Each binding followed actual Ready and exact live PID checks. Expected CUA timeouts or App quit after parent-controlled crash were resolved from that same parent receipt, without relaunching the missing app or reusing a permit. + +The actual populated relaunch and both completed recovery chains show one source, three capabilities, four immutable capability revisions, two local reviews, one recipe, one application, two derivations, one workflow and two workflow revisions. Empty conversion shows zero across all nine categories. Parent original-before/after snapshots preserve logical archive digest, database identity, bytes and full inventory where both observations are available. Retained originals remain plaintext; conversion neither deletes nor encrypts those original files. Recovery inspection is not restoration or destination selection. Complete-copy recording is not another Restore. Copy verification is not ordinary Unlock, local content review, external authorization or execution. + +`batch2/results.json` records the 23 new results and exact artifact identities; `current-parent-results.json` records all 34. `batch2/ui-capture-hashes.json` binds 27 actual screenshot/AX pairs. Fresh read-only UI review found no additional P1/P2/P3 in those states; the earlier three P2s remain open. Captures cover dark 1440 desktop and the actual native sheets only, not light/compact/other-OS/keyboard/assistive qualification. Parent lifecycle/content evidence and UI review remain distinct. Fresh independent read-only receipt, documentation and preservation review passed with no residual P1/P2/P3. Its earlier stale eleven-case snapshot finding was corrected before final recheck: the current ledger now exactly matches all 34 receipts. `node scripts/validate-review.mjs` passed eight reference images, the historical brief, local Markdown targets and 573 authored text files; the two-document `git diff --check` and final frozen-input check passed. `batch2/process-checkpoint.json` independently matches every exact claim to its receipt and confirms all 34 PIDs stopped. Root retains the incomplete-matrix judgment; green receipts and reviews grant no publication or release authority. + +All 34 exact claimed children are stopped. Six slots are registered in this disposable nonce: authoring was intentionally removed and absence proven earlier; five later slots belong to `interrupted-setup`, `legacy-empty`, `legacy-rich`, `recovery-empty` and `recovery-parity` and remain retained for continuation. Successful scoped key-write events and registry identities support this custody record; no independent vault enumeration or key retrieval occurred at this checkpoint. The one-shot global cleanup case has not been consumed and the nonce remains in progress. Twelve phases remain: five selection-recovery phases, six interrupted-rich-provisioning phases and final cleanup. Continue with `recovery-selection-copy`, preserving the same source/executable/plan and exact prerequisite graph. Do not regenerate keys, reuse permits, modify harness limits or aggregate another nonce's results. + +Security/standards impact is additional disposable native evidence for existing encryption, consent, data parity and crash-recovery boundaries; no new runtime behavior, dependency or authority is introduced. Frozen-source checks preserve all 690 outside-owned authored inputs, both lockfiles and the root Rust pin. Test-identifier app-data/cache paths retain the previously disclosed shared locations. Normal user data/keys, providers, target runtime, LNSAT/VUSL edits, dependency fetches and publication/merge/deploy/release remain untouched. Full 46-case qualification, three UI corrections, Windows/Linux/arm64 and package/release gates remain open. + +### E1c-5e final forty-six-case native checkpoint + +The accepted disposable macOS validation packet has now completed all 46 parent cases on one unchanged source/executable/plan tuple. The final twelve cases continue the earlier 34-case checkpoint; no production source, renderer, harness, permission, dependency, case plan or deadline changed. Root OpenAI Codex owns actual native/process/custody operations and the same two status documents. OpenAI `gpt_reviewer` (configured Terra xhigh) independently rechecked the immutable artifact and unused final permits before continuation; OpenAI `gpt_ui_review` (configured Terra xhigh) independently reviewed the sixteen new actual screenshot/AX pairs. OpenAI `gpt_reader` (configured Luna medium) checked the remaining operator-record implementation boundaries. No GLM contact or external transfer of private source occurred. + +| Final cases | Parent result | Bounded actual evidence | +| --- | --- | --- | +| `recovery-selection-copy`, `recovery-selection-crash`, `recovery-selection-cancel`, `recovery-selection-resume`, `recovery-selection-relaunch` | PASS; child 0/-9/0/0/0, 18/11/12/15/17 events; every parent 0 | Actual Copy, later Verify and parent kill exactly at `verification/before_selection`. Recovery Cancel causes no key access. Fresh Complete selection consent reads the existing key, checks complete parity and appends only Selected. Normal Unlock in a later process opens all saved record categories. | +| `legacy-rich-provisioning-crash`, `legacy-rich-provisioning-inspect-cancel`, `legacy-rich-provisioning-initialize-cancel`, `legacy-rich-provisioning-resume`, `legacy-rich-provisioning-verify`, `legacy-rich-provisioning-relaunch` | PASS; child -9/0/0/0/0/0, 13/13/14/22/15/17 events; every parent 0 | Parent kills only after the approved real disposable key write. Inspect Cancel leaves vault untouched; Initialize Cancel follows a separately approved existing-key inspection and preserves the unfinished attempt. Four fresh confirmations inspect, initialize only the missing empty encrypted database, unlock for native recovery inspection and strictly restore into that proven-empty target. No key is created or replaced by recovery. Separate-process Verify and later normal Unlock preserve the full inventory. | +| `cleanup` | PASS; child/parent 0, 26 events | Eight exact registered account/service delete attempts, eight separate absence checks, eight `slot_absent` observations and one `cleanup_complete`; no cleanup failure. Normal user accounts and unrelated keys are outside the fixed nonce/service registry. | + +Every one of the 46 receipts has null `parentFailure`, verified phase exit and the exact selected source `f086d06312cb464ffbd4829706f5a1049265f263c6fd43bd98c01f007bba550c`, executable `7d0b526d4783f10cb10e56bc03d7c81e5690dd2fb5f0d2715058f4c90dfd8442` and plan `ba72790c56048b2fe5cb4de72b5c565d6b1f739033bcec72ce45e8bf1f56425b`. No other nonce or older artifact contributes to this count. Required authoring request-header probes remain verified in that same artifact's receipt. Expected crash deaths/admission failures count only for their named refusal or interruption oracles. Parent `nativeCaseVerdict` remains explicitly unassessed; neither that field nor the aggregate count is a whole-UI or release verdict. + +Selection recovery's before/after storage observations retain the exact `reopened.json` bytes, digest, inode and identity while adding `selected.json`; Copied, Target and Intent observations remain unchanged. It does not fabricate or overwrite the previous verifier. The interrupted-provisioning Cancel observations retain Target/Intent and pending Owner metadata without creating a database. Completed existing-key recovery does not write a key or overwrite existing records. Actual selected/provisioning relaunch inventory matches one source, three capabilities, four capability revisions, two reviews, one recipe, one application, two derivations, one workflow and two workflow revisions. Retained originals remain unencrypted and preserved; parity and local content review do not establish authorization, target adherence or external effect. + +`batch3/results.json` records twelve new outcomes; `current-parent-results.json` records all 46. `batch3/process-checkpoint.json` matches every exact claim to its receipt and verifies all 46 PIDs stopped. `key-custody-checkpoint.json` now records eight registered roots and all eight exact absence observations; no disposable test key remains present according to the accepted cleanup checks. Registry/evidence files, encrypted test databases, retained synthetic plaintext originals and explicitly selected plaintext instruction output remain on disk. Cleanup is not secure erasure, residue cleanup or memory-zeroization evidence. Shared test-identifier app-data/cache paths remain disclosed as before. The global cleanup permit is consumed and this nonce is closed; never resume a completed phase, regenerate its keys or reuse its permits. + +Fresh read-only UI review found no new P1/P2/P3 in the supplied selection/provisioning captures. Distinct native consent scopes, no workbench during recovery inspection, separate normal Unlock, source-free Cancel states and full record inventory were visible. All three earlier P2s remain open for a bounded correction: setup-Cancel heading/Details/Quit continuity, the managed Data surface advertising unavailable plaintext backup, and missing-key recovery lacking a visible next step. Existing backend refusal and missing-key closure remained intact. These captures cover dark 1440 desktop and the actual native system sheets; light/compact/other-OS/keyboard/assistive and complete usability review remain unqualified. Fresh final independent read-only receipt/documentation review passed with no P1/P2/P3, including all 46 exact artifact-bound receipts, final twelve outcomes, retained Reopened proof, cancelled provisioning storage equality, eight exact slot-absence checks and stopped-process evidence. `node scripts/validate-review.mjs` passed eight reference image hashes, the historical brief, local Markdown targets and 573 authored text files; two-document `git diff --check` and final frozen-input checks passed. Final preservation records 692 authored paths, all 690 outside-owned inputs, both lockfiles and the root pin exact. The literal review/validation receipt metadata is appended by Root after that independent review; its result does not grant release or publication authority. + +Security/standards impact: completed scoped native evidence for the existing encryption/lifecycle/consent/recovery mechanics; no new behavior or authority. The root Rust pin, both lockfiles and 690 outside-owned authored inputs remain frozen. Previously passing Rust 1.99.1 source gates apply to those same unchanged bytes; no source suite was rerun merely to replace actual GUI evidence. Normal user data/keys, provider calls, target execution, LNSAT/VUSL edits, dependency fetches and commit/push/merge/deploy/release remain untouched. This completes the defined parent matrix on macOS 26.0 x86_64, not production readiness, certification, all-platform support or the full project goal. + +The next product milestone remains a single qualified target-load/readback journey, after resolving the bounded truthful-UI findings under a recorded correction scope. Existing O1/O2 operator inspection is local and unverified; OpenShell's D2b client remains unmounted and synthetic-peer-qualified, and LNSAT's D3a decoder remains offline. Approval identity, changed-action invalidation, replay refusal, authenticated ingress/correlation and independently observed effects across connected runtimes are still outstanding. Do not replace those gaps with more disconnected catalogs or present this storage qualification as completed engine support. No LNSAT-owned OpenShell middleware or engine dependency is introduced. Existing canonical integration records, rather than this validation receipt, own future connected behavior and activation gates. + +### UIC-1 truthful workspace controls — proposed next source packet + +Status: proposed, not source acceptance. The completed E1c-5e validation packet owns no new renderer implementation. This bounded correction follows the accepted experience/security contract and the three actual P2 findings, without adding key recovery, portable encryption, a native command, provider behavior or an authority surface. One Root controller owns native-boundary judgment, renderer integration, documentation and validation; one bounded UI worker may own only the declared view/CSS/view-test files. A fresh independent reviewer must check the final source and actual affected states. GLM/external private-source transfer is not accepted for this packet. + +Exact proposed production ownership: Root owns `preview/analyze.mjs`; the UI worker owns `preview/workspace-lock-view.mjs`, `preview/workbench-shell.css`, `preview/workspace-view.mjs` and `preview/workspace.css`. Exact test ownership: the worker owns `tests/workspace-lock-view.test.mjs`, `tests/workspace-model.test.mjs`, `tests/workspace-view-purge.test.mjs` and `tests/desktop-startup-view.test.mjs`; Root owns new `tests/workspace-close-quit.test.mjs`. Root owns only this ledger and `docs/continue.md` for the proposal and subsequent receipt. No native Rust, IPC permission, database, crypto, key, manifest, lockfile, language or engine path is included. Stop and revise the packet before any other production path is required. + +1. For the already validated fresh protected state (`status=protection`, `layout=absent`, `canProtect=true`), preserve canonical encrypted-setup heading, description, Details and secondary Quit after CreateEmpty Cancel. Setup remains the primary action. Reuse only the existing `workspace_startup_quit` command with an empty body; native main-window validation and the existing exit coordinator remain authoritative. No `window.close`, new IPC, direct process exit, client restoration or optimistic success. Pending Quit disables competing setup actions and duplicate Quit. A rejected invocation may return only to the current safe closed state; a fenced/disposed document must never be revived. The existing raw startup-unavailable Quit flow remains intact. +2. For Data, pass only the finite already observed native storage mode to presentation. Managed encrypted mode removes unavailable archive Export controls, export confirmation, plaintext-backup advertising and deletion advice to export that unavailable backup. Explain that encrypted portable export is unavailable. Existing explicitly selected additive Restore remains available: native `prepare_restore` and the managed Owner already implement it, independently of the refused archive-export path. Restore disclosure must still explain that the explicitly selected input backup can be unencrypted; hiding the unavailable export must not hide this real input confidentiality boundary. Legacy mode retains its existing explicit plaintext-export warning and picker behavior; browser, unknown and unavailable modes never gain enabled native actions. Mode is a UI hint, never authorization; Rust still refuses forged/direct unsupported export requests. Changing mode, Lock, purge or stale dialogs cannot revive an export action or expose retained content. +3. Closed recovery exposes a visible preservation/next-step message and qualified Quit, with no reset, replacement key, new attempt or recovery action. The current recovery enum is broader than missing-key failure, so generic recovery must not assert that a key is missing or promise that restoring credential access will repair corruption. Explain: keep workspace files intact; if operating-system account or credential-store access changed, restore access to the original account/store and reopen; if the original key is unavailable, Rangoon cannot replace it. Keep the workspace closed and distinguish guidance from an implemented recovery function. No source, path, key identity or raw diagnostic is added to the renderer. + +Use existing theme/focus/motion tokens, one primary action, readable closed-card hierarchy and 44px action targets. Validate 320/768/1440 logical widths in light/dark, keyboard focus, reduced motion and forced colors. Do not broaden visual redesign or change graph/workflow behavior while closing these findings. + +Named source validators: focused `node --test` for the five named test files, `npm run build:check`, `node scripts/validate-review.mjs` and exact-path `git diff --check`. Meaningful tests must exercise the actual quit dispatch/pending/rejection/fence path, canonical Cancel/fresh markup, broad recovery reason handling, mode-specific export/restore behavior, retained valid Legacy behavior, forged/direct native refusal through existing source tests, and purge/stale-dialog races. Do not rely solely on string snapshots or pretend these browser tests qualify the native exit path. + +Proposed disposable native verification uses a new immutable artifact and nonce, the unchanged accepted harness and only existing phases: `cold-cancel`, `cold-relaunch`, `authoring` (including required real Lock/drain/Unlock/header probes), `relaunch`, `export`, `lose-key`, `missing-key` and final `cleanup`. Capture the actual restored fresh card and visible Quit, managed Data without export/picker, missing-key guidance and real Quit through the existing exit coordinator. Preserve Legacy source/browser behavior tests; do not claim a native Legacy-content route or legacy GUI qualification absent its own actual evidence. Old 46-case evidence remains bound to its old artifact; do not relabel the new renderer artifact as having that full-matrix result. New native failure or a required harness/native change returns to Root for separate scope review. Normal user data/keys, model/provider/engine calls, target launch, foreign repository edits, dependency fetches and publication/release stay closed. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) proposal review passed with no P1/P2/P3 after checking native Quit gating, the broad recovery reason, supported Restore and exact file/test/native-case scope. This review is not owner acceptance; the source/tests acceptance request is pending. No implementation has begun. + +## Target-readback feasibility — October 20, 2026 + +Authority: the accepted product-value continuation and the existing [target-load study](target-loader-qualification.md#target-load-milestone--october-20-2026). This bounded research refines that study, not a source or runtime packet. Exact ownership is `docs/target-loader-qualification.md`, `docs/development.md` and `docs/continue.md`. Root OpenAI Codex owns research integration, privacy and claims; an independent OpenAI explorer supplied bounded non-secret installed-asset evidence. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) read-only review passed with no actionable P1/P2/P3; proportional validation passed as recorded below. No GLM contact or external private-source transfer occurred. + +Official OpenAI documentation distinguishes resolved configuration (`config/read`), reported managed requirements (`configRequirements/read`) and the separate prompt-input observation. Current docs are mutable, not the installed artifact's protocol schema. No standalone app-server schema was found among JSON/TypeScript assets in the pinned Codex bundle; the manifest/executable hashes still match the existing study, and compiled method/type strings are only discovery clues. This does not establish method support, schema completeness or binary/source correspondence. No normal configuration, authentication or session file was read. + +The [new study section](target-loader-qualification.md#complementary-native-readbacks-and-the-next-gate--october-20-2026) records complementary observation limits, the exact-version schema gate, independent startup containment and attribution across separate processes. Current docs describe version-specific schema generation, but it executes the target and remains outside this research. App-server's documented startup host and prompt debugging's source-observed thread startup prevent assuming read-method requests or no model turn mean side-effect-free startup. Schema generation, target launch and concrete isolation remain separately proposed. No isolation mechanism is selected or qualified. Separate config/prompt results cannot become an atomic effective-state claim through matching IDs, timestamps or file hashes. + +Experience track: preserve distinct exported, placed, target-input-observed, configuration-assessed and enforcement-assessed labels; no controls or readiness badges changed. Technical/security track: add concrete mismatch, absent/null requirements, cross-process drift, startup-side-effect and incomplete-capture acceptance cases to the existing study. No implementation, authority, crypto/schema storage, dependency or telemetry change. ISO/OpenSSF work remains separate evidence; target configuration, UI review and protocol compatibility never grant engine authorization. LNSAT/OpenShell remain independent optional products, and connected operator support remains unfinished. + +Evidence directory: `/rangoon-target-readback-feasibility-20261020`, containing the 692-path input baseline, three owned preimages, installed-asset and official-documentation read receipts. Named checks are `node scripts/validate-review.mjs`, exact-path `git diff --check`, incremental three-file diff review and identity preservation outside the owned paths, including both lockfiles and the root compiler pin. Validation passed: `node scripts/validate-review.mjs` checked 573 authored text files, eight reference-image hashes, the historical brief and local Markdown paths; exact-path `git diff --check` passed. All 689 outside-owned baseline paths, both lockfiles and the root compiler pin remain byte-identical. The fresh reviewer checked the incremental three-document patch, hashes, primary-source read receipts and preservation evidence; no runtime checks were claimed. This packet has not launched a target, generated schemas, used credentials, called a model/provider, edited VUSL/LNSAT, installed/fetched dependencies, committed, pushed, merged, deployed or released. Existing mixed-tree changes and the pending UIC-1 acceptance remain untouched. + +## Target-load milestone and public evidence recheck — October 20, 2026 + +Authority: Jeff's target-loading assessment and the accepted [product-value continuation](intent.md#product-value-priority-continuation--october-7-2026). This is a three-document research/priority packet; it does not accept target runtime qualification. Root OpenAI Codex owns direction, cross-repository judgment, claims and validation. Native OpenAI `gpt_reader` (configured Luna medium) independently inspected public version-matched source snapshots. Fresh independent read-only review passed as recorded below. GLM was not contacted; no private source was sent externally. + +GitHub GET evidence confirms PR #51 merged at `9bd9be17d17fd8f778ec88f8e9b9f41df5c01dc4` and Source checks run `39381341599` succeeded on that commit, with all seven jobs successful. Three desktop jobs ran source tests/lint and built native executables without installers; this does not qualify GUI, target loading or the mixed local worktree. Rangoon's active branch/HEAD remains `codex/ops-local-window` / `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Existing inert language source is retained; no VUSL dependency or consumer integration was added. + +Read-only metadata and executable hashing reconfirm Codex `0.163.0-alpha.10.2` and the exact October 16 bytes without launching it. The official matching tag resolves to `4ebc485ca321243727539187169425fcf972f2c4`; unsigned/version-matched source is not binary provenance. Its CLI/core prompt-debug path initializes authentication, extensions and thread infrastructure and returns only `prompt.input`. The independent reader confirms that supplied source does not prove full effective configuration, absent external I/O, hook behavior or installed-binary correspondence. These findings change the next safe action from a presumed offline invocation to explicit exact-version isolation/capture review. One attempted historical upstream path, `core/src/project_doc.rs`, returned 404 and supplies no evidence; no replacement loader was inferred. + +Experience track: the [canonical study](target-loader-qualification.md#target-load-milestone--october-20-2026) defines separate proof labels, a one-source/revision/profile/target journey, ten acceptance-case groups and per-case attribution. It keeps content inclusion distinct from adherence/enforcement. Technical/security track: no implementation, dependency, raw user-data capture, target process, model/provider call, credential use, LNSAT/VUSL edit or authority change. Only public GitHub/documentation GETs and explicit non-secret installed-artifact reads occurred. ISO/OpenSSF evidence and actual runtime/OS/release qualification remain distinct. + +Exact owned paths: `docs/target-loader-qualification.md`, `docs/continue.md`, `docs/development.md`. Baseline hashes of 690 authored files, preimages, public read receipts and immutable source snapshots are retained under `/rangoon-target-load-study-20261020`. `node scripts/validate-review.mjs` passed 571 authored text files, eight reference image hashes, the historical brief identity and local Markdown targets; packet whitespace passed. Preservation found only the three owned documents changed, no added/missing authored file and all 687 outside-owned paths exact; all three frozen E1c-5e native source hashes remain exact. Fresh independent review found no P1/P2 and one P3 stale validation-status sentence; the correction passed final independent recheck, closing P3 with no residual actionable finding. E1c-5e's native source and immutable test artifact stay unchanged; its historical full-matrix and window-control gates remain open. No commit, push, merge, deploy or release occurred. + +## E1c-5e ordinary Lock and startup handoff correction — October 20, 2026 + +Authority: Jeff explicitly accepted the [reviewed E1c-5e source and disposable-test packet](intent.md#e1c-5e-ordinary-lock-handoff-acceptance--october-20-2026). Root OpenAI Codex owns protected native production changes, integration and validation. A disjoint OpenAI `gpt_worker` (configured Terra high) owns only `apps/desktop/src/workspace_native_bootstrap_tests.rs`; fresh OpenAI `gpt_reviewer` (configured Terra xhigh) reviews source and evidence. GLM was not contacted. The accepted source files are `apps/desktop/src/workspace_close.rs`, `apps/desktop/src/workspace_startup_host.rs` and the named native-bootstrap tests, plus the four canonical records. Baseline, exact owned paths and preimages are frozen under `/rangoon-e1c5e-source-20261020` (690 authored files). All unrelated work remains separate. + +Source correction is complete and source-qualified. Ordinary Lock now selects a distinct Host operation that atomically classifies `terminal`, `busy`, `plan` and `outcome` under the existing claim/finish mutex. Only a healthy nonterminal Host with no Work, no Plan and an exact completed no-cycle/no-action Handoff is retained. All other states terminal-retire, clear outcome and detach custody under the same mutex; actual drop stays on the existing blocking cleanup path. Mutex poison refuses retention. No terminal flag reset, new Host, Owner recreation, restored confirmation or client publication is introduced. Window destruction and failure/exit keep unconditional terminal retirement. Final source tests and independent source/evidence review pass. Bounded native results and the remaining historical/full-matrix qualification are recorded below. + +Fresh independent V1 production review found a P1 ordering race: calling source close before Host classification could let Work pass its last Flight check, finish after cancellation and appear as an already completed Handoff. Root corrected the sequence to classify under the Host mutex first, hold detached cleanup custody in a named guard across synchronous source close, then dispatch its drop outside the mutex. OpenAI `gpt-6-astra` at high reasoning supplied read-only concurrency design review and passed that guard/order before application. The original failed review and immutable V1 source are retained. A dedicated actual-Flight/Work barrier targets the final-check/publication gap; it grants no synthetic lease or production test hook. The validation history below records the subsequent focused checks and final source gates. + +Focused V3 checks pass seven Host-state/race tests and 18 bootstrap tests, with one ignored process helper explicitly invoked by its Legacy parent. The Legacy fixture uses a real second test process and bounded synthetic-vault stdin transfer; replacing objects in one process correctly remained `restart_required` and was not counted as verification. Fresh V2 production and V3 seven-path source/test reviews pass with no residual actionable P1/P2/P3. The first final-check regression incorrectly expected Locked before the new renderer purge acknowledgment; its corrected sequence proves Closing until that exact acknowledgment. V3 full default/no-default tests and docs pass (678 and 359), together with 69 renderer and 38 parent checks; the ten-gate run then stopped at warnings-denied Clippy because the new inline test module preceded production items. Root moved that module to the runtime module's end without suppressing the lint or changing production behavior. The final V4 rerun passes all ten pinned locked/offline native gates with all three source hashes unchanged: custom qualification-target no-run, formatting, default/no-default all-target tests, docs, warnings-denied Clippy and builds. Default counts are 172 library + 484 binary + 22 docs = 678 passes; no-default counts are 43 library + 294 binary + 22 docs = 359 passes. Nested helper output is not double-counted. The custom qualification target retains its existing duplicate-target/shared-harness unused-test warnings; normal all-target Clippy passes without suppressing warnings. The earlier partial V3 gates remain historical, not final evidence. + +Final E1c-5e source evidence is frozen under `/rangoon-e1c5e-source-20261020`: `source-v4-hashes.json`, `native-validation-v4.json`, the retained focused and failed V1/V3 logs, surface receipts and review snapshots. V3-to-V4 source token comparison proves only the inline test-module placement moved. All 690 authored regular paths remain present, no authored path was added, and all 683 outside-owned paths remain byte-identical. Exact owned paths are `apps/desktop/src/workspace_close.rs`, `apps/desktop/src/workspace_startup_host.rs`, `apps/desktop/src/workspace_native_bootstrap_tests.rs`, `docs/intent.md`, `docs/encrypted-workspace.md`, `docs/continue.md` and `docs/development.md`. Fresh independent V4 source/evidence review passes with no actionable P1/P2/P3 after checking all seven hashes, exact commands/counts and preservation. The bounded native results and unfinished historical/full-46 gates are recorded below; source-test success alone does not establish native qualification. + +### E1c-5e artifact-bound native follow-through + +A new immutable macOS qualification artifact binds source `e3f2fe3d01ca5fbcbd13da5298088c7b8476d995946aae3ae52c38c31ddbfb6c`, executable `ce7867423d822ec611630662b649eaa0a8c5b96d784c860c0079798e0232a191`, and unchanged private plan `ba72790c56048b2fe5cb4de72b5c565d6b1f739033bcec72ce45e8bf1f56425b`. It is an x86_64 Mach-O test executable on macOS 26.0, not native arm64, Windows/Linux or an installed release package. + +The first run (`fdc715c1a89d2fc28e753802986d5bef`) saved actual synthetic source, reviewed revisions, a composed skill and two workflow revisions with typed data/control connections. Held-read Lock drained to Locked; approved Unlock returned to the workbench and its saved workflow library. The fixed 20-minute parent deadline then killed the child before the required header probe and clean exit. Its receipt correctly reports incomplete/failed qualification; these observations are diagnostic evidence only. Exact run-scoped cleanup removed its registered test slot and independently confirmed absence. The timeout and all prior failed receipts remain preserved; no deadline or assertion was relaxed. + +A fresh run (`46ccc0e368c1b415b1808ce1264592c9`) uses identical source/executable/plan bytes. The authoring phase passes its strict parent oracle with 47 native events, exit 0, `phaseExitVerified=true`, `headerProbeVerified=true` and no parent failure. It creates the encrypted workspace through actual native confirmation, saves a real 73-byte selected-file source and two skill revisions, then holds a real vault read across Lock. Closing removes the content client before callback release; actual return permits Locked. A separately approved Unlock returns an exact completed Handoff and the reloaded native Skills workbench, with its saved two-revision library. Missing and stale request headers refuse with zero vault reads/writes; the current header performs one real read with zero writes. Native clean exit is recorded. This is bounded real macOS lifecycle/header evidence, not complete product qualification. + +A later historical-revision click received a CUA user-change guard, and a fresh full accessibility observation showed Merge rather than the requested historical Skills view. Attribution is unconfirmed; neither the guard nor route change proves user interference or a production authorization defect. The child was stopped cleanly before further UI actions. Jeff was asked whether he or another chat was using the disposable window. Historical opening remains unqualified. Before the separately requested Rust alignment, accepted exact cleanup ran against this stopped nonce: exit 0, parentFailure null, slot_absent and cleanup_complete. No test key or native process remains. Do not infer a historical-opening or full 46-phase pass from the authoring phase; later source/toolchain changes require a new immutable artifact. Attribution of the earlier route change remains unresolved. + +Evidence: `/rangoon-e1c5e-source-20261020/native-progress-v4.json`, the two actual run receipts, `native-authoring-v4.log`, `native-authoring-repeat-v4.log`, `native-timeout-cleanup-v4.log`, `native-repeat-cleanup-v4.log`, and full AX/PNG pairs in `native-ui-v4` and `native-repeat-ui-v4`. The source freeze is unchanged; actual native evidence and the seven-path documentation delta require fresh independent review. No source gates were rerun because code did not change. Normal data/keys, provider/LNSAT/VUSL access and publication remain untouched. + +The earlier E1c-5d UI-evidence-only run stopped after explicit Inspect cancellation when E1c-5e was accepted. Its controlled crash and cancellation parent oracles pass; exact registered test-key cleanup passes. Full AX/PNG captures for the interrupted-copy and Inspect-consent screens are retained under `/rangoon-e1c5d-source-20261019/ui-recovery-review`; InitializeEmpty UI review is still pending. No manual action is substituted for an automated oracle. + +Jeff’s next product direction is a task-based usability review after the current storage/lifecycle qualification, followed by a cohesive visual system for agent management and telemetry. His visual brief includes typography cleanup, theme-matched sliders/scrollbars and menus/dropdowns, responsive scale, left-to-right button sheen, soft border glow/light effects, restrained color blending and aligned graphics. The existing eight-reference shell/workspace/inspector hierarchy remains; no live telemetry or connected-system claim follows. An independent OpenAI `gpt_ui_design` (configured Terra high) reviewed actual disposable native dark 1440×900 AX/PNG captures, while Root retained native control. It found no P1 in captured states and identified a premature “Local save available” empty-state label, enabled-looking no-selection composition controls and orange disabled-primary styling. This is bounded usability evidence; other themes, sizes, keyboard, native menus/resizers, physical 4K and other operating systems remain unqualified. + +A disjoint OpenAI `gpt_reader` (configured Luna medium) traced the range affordance: the view safely returns before any controller call when selection is absent, and the model separately validates input bounds and UTF-8 byte boundaries. The current view can leave its selected-range label stale after selection collapse. This is a UI coherence problem, not evidence of Rust authorization failure. Proposed repair ownership is `preview/composition-view.mjs` and `tests/composition-view.test.mjs`; preserve all model/native guards. Proposed first style ownership is only `preview/app.css` and `preview/visual-system.css`, with local fonts, shared state/theme tokens, accessible type/hit targets, short interaction-only effects and reduced-motion/forced-color equivalents. Root rejects tiny essential metadata and automatic post-Lock renderer-state restoration; any future Resume action must fetch fresh references only after confirmed unlock. These are reviewable follow-up packets, not a claim of implemented style, navigation, telemetry or behavior changes. No UI source changed during native qualification. + +Experience/security/standards impact: this fixes the ordinary Lock → native Unlock → renderer reload workflow without changing screen layout, native consent, request headers, storage/crypto/schema, key format, dependencies or external authority. Unlocked content still requires the existing independent native confirmation and current client generation. Existing metadata/original-file/export confidentiality limits remain unchanged. This is lifecycle correctness and candidate recovery/change-test evidence for the existing ISO/OpenSSF track, not certification or release qualification. Normal data/keys, providers, LNSAT/VUSL edits, dependency fetches, commit/push/merge/deploy/release remain closed. Windows/Linux native qualification remains required before release. + +## E1c-5d existing-key empty provisioning completion — October 20, 2026 + +Authority: Jeff's [accepted E1c-5d source and disposable macOS packet](intent.md#e1c-5d-source-and-disposable-macos-acceptance--october-19-2026). Root OpenAI Codex owns protected recovery/startup/consent integration, validation and documentation. A disjoint OpenAI `gpt_worker` (configured Terra high) supplied bounded Owner/process tests; fresh OpenAI `gpt_reviewer` (configured Terra xhigh) independently reviews immutable source and evidence. GLM was not contacted and private source was not transferred externally. This receipt supersedes the earlier diagnostic's missing-capability status for source only; GUI/OS-key and complete same-artifact macOS qualification remain unfinished. No commit or publication follows. + +Owner now separately inspects an intact pending CreateEmpty with unready binding, exact directories, no terminal record and physically absent database/sidecars. It retains the exact operation/binding/proof and existing key in private zeroizing custody. Wrong, stale, repeated, replaced or locked plans refuse before further vault access. Explicit native InitializeEmpty consumes the one-shot plan, revalidates the key and all proofs, initializes only the absent encrypted database using the existing pinned constructor, verifies authenticated empty inventory and exact resulting child set, and durably finishes the same original attempt. No key creation/write, arbitrary path, renderer token, replacement original or content client is added. A valid database left after interrupted completion uses existing authenticated metadata recovery instead of initialization replay. + +Startup mounts this distinct metadata-only candidate only for the exact existing-copy Target journal path; it does not weaken complete Managed shape or impersonate authenticated inventory for absent data. Consent order is Inspect, InitializeEmpty, separate Unlock, then Restore; cancellation consumes custody and leaves storage unchanged. Restored full parity precedes Copied. Distinct-process Verify and later ordinary Unlock remain required. A well-formed slot value before the first inspection has no independently authenticated earlier baseline when no database exists; this path does not claim protection from a compromised OS account. + +Source validation on immutable V5 passes all ten named locked/offline native gates: custom qualification-target no-run, scoped formatting, default/no-default all-target tests, documentation tests, warnings-denied Clippy and all-target builds. Default counts: 172 library + 472 binary + 22 docs = 666 passes (one library and two binary ignored). No-default: 43 library + 292 binary + 22 docs = 357 passes (one binary ignored). Nested child output is already included in library counts. The custom target retains existing shared-harness unused-test/import and duplicate-target manifest warnings; it is not described as lint-clean. Store regressions pass 166 default and 188 encrypted tests; portable CLI passes 16. Renderer/startup/lifecycle checks pass 69; existing qualification parent tests pass 28. Document/image/anchor and whitespace checks pass at the recorded source checkpoint. + +The real disposable file-vault child is killed after its synced envelope write and before database creation. Separate children cover Inspect cancellation, InitializeEmpty cancellation, existing-key completion, Restore, distinct-process verification and ordinary unlock. Twelve Owner tests cover malformed/missing/changed keys, damaged/foreign records, exact valid Pending drift after inspection, stale/rotated/locked plans, directory/control/binding/DB/sidecar drift and reused ready/terminal fault points. Five new presence-proof tests and the 39-test adoption family pass. Synthetic file-vault/process proof is not macOS OS-vault or GUI proof. Fresh independent V5 source/evidence re-review passes with no remaining actionable P1/P2/P3; the frozen 17-path hash manifest and all ten source-gate receipts were checked. + +Review-driven corrections: V1 identified missing exact post-initialization extra/sidecar checks; the implementation now repeats the closed child-set check around key callbacks, binding readiness and terminal observation, with injected extra/journal/WAL/SHM regressions. V2 required full exact-current library evidence and a post-inspection valid Pending mutation test; both are supplied in V5. Initial fixture failures came from reopening an exclusively held journal, assuming Pending survives a later real Restore unchanged, and changing a key before any authenticated baseline existed; fixtures now check the correct lifecycle boundaries. A sandbox-only Unix-listener refusal passes with scoped local-socket permission. A final test-only byte-slice Clippy finding is fixed and all ten gates rerun on the final frozen source. No validator or production boundary was weakened. + +Exact source/test paths: `apps/desktop/src/workspace_session.rs`, `workspace_recovery.rs`, `workspace_adoption.rs`, `workspace_startup.rs`, `workspace_startup_host.rs`, new `workspace_empty_provisioning_tests.rs`, `workspace_adoption_tests.rs`, `workspace_startup_tests.rs`, and the closed consent-purpose allowlist in `native_encrypted_qualification.rs`. Canonical records are `docs/intent.md`, `docs/encrypted-workspace.md`, `docs/continue.md` and this ledger. The accepted finite qualification-harness extension passed independent pre-code review and is implemented in the five named harness files; its preparation evidence follows below. The historical V5 source receipt above predates that extension. Evidence and original preimages: `/rangoon-e1c5d-source-20261019`, including `review-v5`, its hash manifest, `native-validation-v5.json`, focused/store/renderer receipts and retained earlier failed diagnostics. + +Experience/security/standards impact: a distinct native confirmation explains creating the missing empty database with the existing key and later unlock/restore; no UI layout or authoring semantics change. Source/key-free metadata remains readable and Legacy originals remain plaintext. No encryption/schema/archive format, dependency, provider authority or credential source changes. This is candidate confidentiality/recovery/change-test evidence for the existing ISO/OpenSSF plan, not certification or production readiness. Normal data/keys, providers, LNSAT/VUSL edits, dependency fetches, commit/push/merge/deploy/release remain closed. Windows/Linux qualification is still required before release. + +### E1c-5d finite native harness preparation + +The [accepted E1c-5d finite chain](encrypted-workspace.md#finite-interrupted-provisioning-qualification-chain) preserves all original 40 case objects and their order, adds one populated Legacy interrupted-provisioning root and six phases, and remains within the unchanged private version and bounds (46 phases, 14 roots, 11,210 JSON bytes). Independent OpenAI `gpt_reviewer` (configured Terra xhigh) pre-code design review passes. Root owns the existing key-write barrier, parent oracle, negative tests and integration; an OpenAI `gpt_worker` (configured Terra high) supplied only the private Rust plan and JSON. That worker's follow-on Python task failed twice before execution with “Selected model is at capacity”; Root completed those tests locally. GLM was not contacted or supplied source. + +The actual CountingSlot wrapper is reused after successful isolated OsSlot.write and before CreateEmpty returns. It adds only source-free custody counters for the new crash case. Wait is bounded to 120 seconds and timeout returns WriteUncertain; it never resumes initialization. Parent SIGKILL is restricted to its own child at the exact frozen case/checkpoint. Opaque stopped-child observations now distinguish absent ciphertext, fixed Owner metadata identities/lengths/hashes and exact child-name sets for this new root only. Cancellation must preserve the complete snapshot; Resume alone can initialize the absent database and advance legitimate operation metadata. Original database, directory/control identities and adoption-record prefix remain exact. No key body, metadata semantic parser, SQL read, new Owner observer, dependency or production fault API is added. + +Focused Python parent checks pass 38 tests; Rust private-plan checks pass 10. New regressions cover wrong/duplicate/missing/timed-out/mixed checkpoints, consent/custody order and strict counters, wrong slot, premature client/completion, original/directory/control/binding/Pending drift, invalid absent-to-present transition, real disposable zero/linked/extra/sidecar layouts and drift during observation, and stale prior crash/artifact receipts. An initial Rust test used unsupported LowerHex formatting for the installed SHA-256 array; explicit byte formatting fixes it. The first Python preservation test sorted JSON object fields despite the original struct serialization order; exact preimage equality confirmed unchanged old cases and the corrected byte ordering passes. Earlier failed logs remain retained. Final V6 locked/offline native validation passes all ten gates with source unchanged: default 172 library + 473 binary + 22 docs = 667 passes, and no-default 43 library + 293 binary + 22 docs = 358 passes. Independent harness review then found a P2 capacity mismatch: the worker had reduced Rust parser caps to the current 14-root/46-phase profile. Root restored the original 32-root/64-case caps and added a valid-at-capacity/excess refusal regression. V2 review and the full gate then caught the old overflow fixture still using 47 cases; restoring its original 33-root/65-case thresholds passes all 11 focused plan tests. The corrected V8 full matrix passes all ten gates with source unchanged: 172 library + 474 binary + 22 docs = 668 default passes; 43 library + 294 binary + 22 docs = 359 no-default passes. Renderer/lifecycle 69 and Python parent 38 tests pass. Fresh independent V3 source/evidence review passes with no residual actionable P1/P2/P3 and verifies the V8 receipts and frozen hashes. The earlier V6 pass remains historical, not proof for subsequently changed source. The first generated disposable artifact was never launched, created no test key, and is stale after the source correction; native qualification will use a new pinned artifact. No GUI/OS-key/full-matrix result is claimed. Original 40 case objects/order and 13 roots are exact; all 673 outside-owned preimage paths remain byte-identical. Evidence: `/rangoon-e1c5d-source-20261019`, including `harness-plan-v1.md`, `harness-review-v1`, focused logs and frozen source hashes. + +### E1c-5d disposable native qualification in progress + +The first launched final-source run was excluded after Jeff confirmed manual interaction during the Inspect-cancellation phase. Native receipts recorded four approvals that the harness did not send. The strict parent rejected the wrong consent sequence, the child exited cleanly, and exact run-scoped cleanup confirmed its only registered test slot absent. This is not an unexplained authorization or a passing cancellation case; no unlike run or manual activity is aggregated into qualification. The earlier generated pre-correction artifact was never launched and created no key. + +A fresh isolated run on the final source/artifact/plan passes all six new interrupted-provisioning parent oracles: controlled post-key-write crash, both cancellations, separately confirmed InitializeEmpty/Unlock/Restore with complete parity, distinct-process Verify, and later ordinary Unlock. The restored source, capability revision history and workflow history were opened in the actual native renderer. Cancellation snapshots remain exactly unchanged; completion uses the existing OS key with zero replacement writes. Cold cancellation, its relaunch, busy-owner refusal and exact cleanup also pass their parent oracles, for ten parent-verified phases. These checks do not establish the complete manual UI journey or the full 46-phase matrix. + +The same run's authoring case was stopped after unexpected synthetic-preview navigation during the Save check. Attribution is unconfirmed: Jeff said the window should be free and requested automation investigation. Do not classify this incident as user interference. The strict parent rejected the incomplete required header probe despite a clean native exit. Two historical AX evidence files contain default accessibility diffs rather than complete snapshots, so they cannot establish the Save target or route at the interruption. + +A separate disposable reproduction used the identical source, executable and plan. With full AX snapshots and fresh targets, native workflow inspection reported zero structural issues and unresolved references; acknowledgment and Save produced a saved revision while remaining on `tauri://localhost/analyze.html#workflows`. No scoped Save handler, refresh callback or harness control navigates to the synthetic preview. The original jump remains unexplained. CUA also issued its user-change guard while an unchanged native setup sheet remained visible, and reported an invalid element after a title edit had already succeeded. These are automation limitations, not proof of human activity; inspect current state before retrying an action. No automation guard was disabled. + +The reproduction then exposed a separate native lifecycle defect: an actual held read, Lock/discard, Closing without a client, released callback and clean Locked state all completed; after a new approved Unlock, native observation reported Open with a client, but startup and renderer reported unavailable. Ordinary `begin_workspace_close` currently calls terminal startup retirement; `Host::retire` clears the completed handoff and latches terminal state, so the renderer reload after unlock cannot obtain its startup handoff. The bounded [ordinary-lock correction proposal](encrypted-workspace.md#e1c-5e-ordinary-lock-and-startup-handoff--proposed-correction) preserves terminal exit/failure and incomplete-plan cancellation; it is not source acceptance. No application source was changed during diagnosis. + +Both diagnostic children exited cleanly. Their exact registered disposable Keychain slots were removed and absence confirmed by the accepted cleanup cases. Source remains frozen at V8; full macOS qualification and fresh actual UI/evidence review remain unfinished. Normal data/keys, providers, LNSAT/VUSL edits, dependency fetches and publication remain untouched. + +Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) confirmed the lifecycle P1 and missing regression. A separate read-only reviewer passed the diagnostic documentation and found a P1 in the initial correction proposal: atomic Host-state classification and a Lock-versus-active-Work race test were not explicit. Root corrected the proposal before any implementation; final V2 pre-code review passes and closes that finding. The proposal remains unaccepted source scope. Root OpenAI Codex produced diagnosis, native evidence and documentation; GLM was not contacted. Final proportional checks preserve all 13 V8 source hashes and 673 outside-owned paths, and pass six scoped local links and whitespace. No broader source tests were repeated because application source did not change. + +Evidence: `/rangoon-e1c5d-source-20261019/native-fresh-progress-v2.json` and `automation-investigation.json` pin source `20803756a13b8c571a33ce01f9b298932d479fb03acab80893b2e0f9ae4dd212`, executable `2cec95ef6e0aba6ef3cf36b8630ba930be5abb8f56a994abc17bfca904a7f467` and private plan `ba72790c56048b2fe5cb4de72b5c565d6b1f739033bcec72ce45e8bf1f56425b`. Full diagnostic AX/PNG pairs are under `ui-evidence/automation-*`; immutable native receipts and cleanup logs remain separate for each nonce. `native-manual-interference.json` retains only the earlier user-confirmed excluded run. A post-SIGKILL/post-Quit accessibility timeout is not exit evidence; process handles and actual parent receipts own termination proof. ## RUSL retirement and VUSL consumer sequencing — October 19, 2026 +### Active retirement reconciliation — October 19, 2026 + +Authority: [accepted retirement direction](intent.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026). Public documentation is merged through [PR #51](https://github.com/hypler-dev/rangoon/pull/51) at `9bd9be17d17fd8f778ec88f8e9b9f41df5c01dc4`; the pushed head was `190d03551014cd088fcca7039d33b5ef1727e1dc`. All 14 exact-head CI checks and fresh independent read-only review passed; fetched main's complete tree matched the reviewed head. No executable release or private E1c-5c publication followed. + +This active-worktree reconciliation imports eight reviewed reference/archive/provenance pages and targets existing README, intent, plan, continuation, connector/control-plane language and this ledger without replacing native engineering receipts. Root OpenAI Codex owns integration; native OpenAI `gpt_reader` (configured Luna medium) supplied an exact read-only map. RUSL is retired, old source remains inert and unchanged, and VUSL adoption requires a usable pinned upstream core, updated affected consumer tests, refusal/authority review and independent cutover review before source removal. Historical pins, identifiers and fixtures do not create a reader/converter/alias/dual-profile or backward-compatibility promise. + +Experience/security/standards impact: documentation only; unchanged UI, source, data handling, custody, schema/crypto, dependencies and authority. Native providers remain optional and independent. No new standard or compatibility claim. This reconciliation remains uncommitted/unpublished and preserves unrelated active work. Named checks are exact authored/source preservation, three fixture hashes, unchanged parser/reference tests, document/image/anchor/whitespace validation and fresh independent read-only review. Reconciliation validation passes: unchanged Rust parser 8 tests, independent Python reference 14 tests, three fixture hashes, document/image/anchor checks (570 authored text files), whitespace, and 672 outside-owned preimage paths. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) passes the exact frozen 17-path snapshot with no actionable P1/P2/P3. These preservation results apply before the separately accepted E1c-5d implementation begins; they do not assert later recovery source is unchanged. The reconciliation script initially stopped at a mismatched development heading; resuming only the remaining edits passed the complete preservation check. This was script routing, not a product failure. Evidence: `/rangoon-active-retirement-reconcile-20261019`. GLM is not contacted; native lanes are adequate and no private source is transferred externally. + +## E1c-5c interrupted provisioning diagnostic — October 19, 2026 + +Authority: accepted E1c-5c disposable qualification and the [interrupted provisioning diagnostic](encrypted-workspace.md#interrupted-provisioning-diagnostic). Root OpenAI Codex owns the one `workspace_adoption_tests.rs` regression and canonical documentation. The real synthetic copy child is killed after its existing key envelope is synced but before `Owner::create_key` returns; Target, Pending CreateEmpty and unready binding survive while the database is absent. Two distinct recovery processes preserve the exact original, envelope, pending/binding/journal bytes and refuse content/vault access. Key comparison stays in zeroizing test memory and prints no key or fingerprint. + +The actual startup result is unavailable with Quit only, before Inspect, because managed-shape inspection requires a database. The initial regression expected later recovery/Inspect and failed; tracing the real startup corrected that expectation. This passing negative regression proves an unfinished recovery capability, not successful recovery. The separate proposed [E1c-5d repair](encrypted-workspace.md#e1c-5d-interrupted-empty-provisioning-completion--proposed-source-gate) adds explicit typed inspection and InitializeEmpty using the existing key, followed by separate Unlock/Restore; Jeff subsequently accepted its source and disposable macOS tests; it remains unimplemented at this diagnostic checkpoint. + +Focused corrected regression and all ten frozen locked/offline native gates pass: qualification-target no-run, formatting, default/no-default all-target tests, docs, warnings-denied Clippy and all-target builds. Default totals are 160 library + 467 binary + 22 doc tests (649 passes); no-default totals are 43 library + 292 binary + 22 docs (357 passes). The separately printed one-test child is included in the library suite. Qualification-target compilation retains unused test/import warnings; warnings-denied applies to ordinary/default and no-default Clippy only. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) passes diagnostic source and proposed design, including the early startup refusal and separate provisioning-candidate proof, with no P1/P2/P3. Evidence: `/rangoon-e1c5c-pending-recovery-20261019`; all ten command receipts report source unchanged. + +Experience/security impact: no production behavior changed; the limitation is now reproducible. No GUI/OS-key case, normal data/key, new recovery operation, dependency, schema/crypto, provider, LNSAT/VUSL edit, commit, push, deployment or release is opened. The previous 40-phase native qualification plan and all unrelated work remain intact. OpenSSF/ISO readiness claims do not follow from source tests. GLM was not contacted. + +## E1c-5c durable interruption and recovery qualification preparation — October 19, 2026 + +Authority: Jeff's accepted E1c-5c source and disposable macOS packet; [the fixed durable-interruption contract](encrypted-workspace.md#fixed-durable-interruption-cases) refines only its shared qualification executable and runner. Independent OpenAI `gpt_reviewer` (configured Terra xhigh) pre-code review passes after clarifying that completed empty-target confirmation and unresolved Owner operations are different recovery branches. Root owns the narrow adoption checkpoint hook, native observer, parent oracles and documentation. A disjoint OpenAI `gpt_worker` (configured Terra high) owns the private plan/parser. The complete named native source matrix passes. Fresh V1 independent source review found two P2 oracle gaps; both are corrected. V2 re-review closes both P2s and identified one P3 missing negative regression for a completed startup outcome before a crash; that regression is added and fresh V3 independent source/evidence re-review passes with no residual actionable P1/P2/P3. No native GUI, OS-key or full-matrix execution has occurred in this preparation slice. + +The plan now has 40 phases across 13 roots, adding real interruption after completed empty-target confirmation, completed full restore and durable Reopened verification. Each chain includes native cancellation, distinct-process recovery and a subsequent confirmed unlock. Qualification-only callbacks use the existing adoption checkpoints, emit finite source-free observations and wait at most 120 seconds for the parent to terminate its own child. Timeout returns uncertain-write failure; no conversion resumes, journal or terminal Owner receipt is forged, or production fault API is added. The unresolved CreateEmpty/Restore path remains separate next work. + +The parent distinguishes provisioning from adoption interruption and checks exact checkpoint, actual consent order, custody bounds and no content client. Descriptor-relative, no-follow opaque file observations retain original bytes, journal prefix, directory/file identities and ciphertext without parsing journal semantics, SQL or encrypted contents. Cancellation cannot change records/ciphertext; full-parity recovery must append Copied without another restore; Reopened recovery must retain its original verification record and append Selected. A killed child supplies no original-after or clean-exit event: its native original-before observation is compared with stopped-child bytes, and the next real child must perform the existing full native capture against the baseline. Parent observations remain separate from native events. + +Initial source checks: 9 Rust profile tests pass with the correct separate desktop manifest; 28 Python tests pass, including all three synthetic chains, wrong/missing/duplicate/timed-out checkpoints, missing consent, key-access bounds, rewritten journals, changed ciphertext, prior-receipt rejection, links/hardlinks/modes/limits and mutation after an earlier snapshot read. The worker's first Cargo invocation used the root workspace and failed before any test with “package ID specification rangoon-desktop did not match any packages”; Root corrected it to `--manifest-path apps/desktop/Cargo.toml`. This was command routing, not a source/test failure. All ten locked/offline native gates pass with the frozen V1 snapshot unchanged before and after every command: custom-target no-run build, formatting, default/no-default all-target tests, doc tests, warnings-denied Clippy and all-target builds. Default results are 160 library + 466 binary + 22 doc tests (648 passes, one library/two binary ignored); no-default results are 43 library + 292 binary + 22 doc tests (357 passes, one binary ignored). The separately printed one-test child is included in the library suite. The custom target retains 403 unused-test/import warnings; only ordinary/default and no-default Clippy are described as warnings-denied. Repository review validation passes eight image hashes, the historical brief, local Markdown targets and 565 authored text files; whitespace passes. No dependency fetch/install or native GUI run occurred. + +V1 independent review found P2: crash observations/key-write events could precede approved consent, and CompleteSelection could include premature Handoff while also emitting a later valid one. The parent now refuses pre-approval custody, orders its real successful slot write after Copy consent and before the exact barrier, rejects completed startup outcomes before a crash, and requires every CompleteSelection Handoff after its approval. Negative tests exercise those false-positive traces. Existing-key reads after approved Inspect and before Restore/RecordCopied confirmation remain legitimate: the real core needs them to decide which recovery action to offer. All four Rust/profile paths remain byte-identical to the passing V1 native matrix; only parent/tests and evidence documentation changed after that run. The expanded Python suite passes; V2 review closes both P2s. Its P3 test gap is corrected with six negative completed-outcome-before-crash traces; fresh V3 review passes and closes the P3 with no residual actionable findings. + +Experience track: unchanged UI hierarchy and control meaning. Technical/security track: bounded disposable recovery evidence; no new dependency, crypto, schema, export format, provider or runtime permission. Existing plaintext originals/instruction exports retain their disclosed limits. OpenSSF practices accompany this work; full Passing assessment remains V1 finalization. Evidence: `/rangoon-e1c5c-recovery-cases-20261019` (684-path preimage, frozen draft, review snapshots and validator receipts). Normal data/keys, LNSAT/VUSL changes, dependency fetches, publication, deployment and release remain closed. GLM not contacted; native GPT lanes were adequate and no external source transfer occurred. + +## E1c-5c fixed conversion and restart qualification cases — October 19, 2026 + +Authority remains Jeff's accepted E1c-5c source and disposable macOS packet. The [fixed-case preparation contract](encrypted-workspace.md#fixed-disposable-case-preparation) refines its existing custom executable and runner; it does not replace the shared native factory or complete the full native matrix. Root owns protected native integration, synthetic Legacy seeds, consent observations, parent runner/oracles and documentation. A disjoint OpenAI `gpt_worker` (configured Terra high) owns the pure case-plan parser and JSON. Pre-code independent OpenAI `gpt_reviewer` (configured Terra xhigh) passed. The named native source matrix and fresh V3 independent source/documentation re-review pass with no residual actionable P1/P2/P3 after the artifact-pin correction below. No native application or OS-vault case was run in this preparation slice. + +The private embedded/read JSON plan now defines 25 fixed phases across 10 isolated roots. It retains the existing cases and adds control-only Cancel/relaunch; empty and populated Legacy copy, distinct-process verification and current unlock; verification Cancel; source-review Cancel; native-copy Cancel; and their restart phases. Run manifest v2 binds the exact plan SHA-256, source tree and executable; previous manifests are refused rather than adopted. Completed prerequisites must carry successful parent verification and the same artifact/source/plan identity. The parent refuses process-identity reuse, changed source/executable during a phase and duplicate JSON fields. + +Initial-only fixtures use existing public storage APIs and the independent schema-0 SQLite page. The populated schema-4 fixture contains one source, three capabilities, four capability revisions, two reviews, one composition recipe/application with two derivations, and one workflow with two revisions. Existing-only capture and physical database hashing retain the exact original schema, inventory, complete archive digest, identity, bytes and physical hash across each phase. Reopen never reseeds or repairs an original. Native sheets add only finite purpose/outcome observations after their real result; observers are compiled into the explicit test target only. Parent workflow checks reject a clean exit lacking required ordered states, actual confirmation, unchanged original, proper key-write/read bounds or client-publication boundaries. + +Focused checks pass: 13 native parser/seed tests and 15 Python parent-oracle tests, including malformed profiles, escaped/duplicate fields, invalid chains, linked/corrupt originals, retained record histories, real version-aware Legacy edits, missing/wrong consent, premature clients, unexpected key writes and absent/changed preservation evidence. Tests exposed and corrected two preparation defects: serde's internally tagged unit variants ignored extra prerequisite fields, so empty struct variants now reject them; a synthetic edit used the older schema-specific save API, so the test now calls the existing version-aware `save_v1`. No storage API/schema or product behavior was weakened to make those checks pass. + +All ten locked/offline native gates pass with the V2 snapshot unchanged around every command: `cargo fmt --all -- --check`; default and explicit no-default-feature all-target tests, doc tests, warnings-denied Clippy and all-target builds; and the explicit custom-target no-run build. Default results are 160 library + 465 binary + 22 doc tests, totaling 647 passes with one library/two binary tests ignored. No-default results are 43 library + 291 binary + 22 doc tests, totaling 356 passes with one binary test ignored. The separately printed one-test child result is already part of the library suite, not an extra pass. The custom target retains 403 unused-test/import warnings and is not described as lint-clean; both ordinary/no-default Clippy gates pass. No dependencies were installed or fetched. + +Fresh V2 review identified P2: the parent source digest omitted root `fixtures/`, including the composition JSON now embedded by the seed. The parent now hashes that directory and its new regression proves an embedded fixture edit changes the source pin and a fixture symlink refuses. All seven native/profile paths remain byte-identical to the passing native validation snapshot; the final parent-only correction passes the expanded 15-test Python suite. Fresh V3 re-review verifies all 13 frozen paths, closes P2 and passes with no residual actionable findings. The repository review validator passes eight reference-image hashes, the historical brief, local Markdown targets and 565 authored text files; scoped whitespace passes. Portable/store/frontend sources are unchanged from their prior mounted-source validation; those suites were not rerun for test-only native harness changes. + +Evidence: `/rangoon-e1c5c-matrix-20261019`, including the 680-path preimage, fixed profile draft, pre-code review, focused/Python logs, `native-validation.json` and immutable source-review snapshots. The only post-review documentation edits record the actual PASS verdict. Experience track: no UI layout or control-meaning change. Technical/security track: stronger disposable workflow evidence and original-preservation checks only; normal data/keys, provider calls, LNSAT/VUSL edits and new dependencies remain excluded. GLM was not contacted; native GPT lanes were adequate and no external source transfer occurred. Jeff's OpenSSF timing clarification is recorded in [the existing adoption plan](plan.md#openssf-best-practices-adoption-plan): practices accompany feature development, with the full assessment during V1.0 finalization. No badge administration replaces feature mechanics. + +Exact changed paths: `apps/desktop/src/main.rs`, `apps/desktop/src/native_encrypted_qualification.rs`, `apps/desktop/src/native_encrypted_case_plan.rs`, `apps/desktop/src/native_encrypted_seeds.rs`, `apps/desktop/native-encrypted-qualification/cases.v1.json`, `apps/desktop/src/workspace_startup_host.rs`, `apps/desktop/src/workspace_setup.rs`, `scripts/qualify-native-encrypted.py`, `tests/qualify_native_encrypted_test.py`, `docs/encrypted-workspace.md`, `docs/plan.md`, `docs/continue.md` and this `docs/development.md` receipt. Prior native/encryption/engine/operator dirt remains outside this incremental packet. + +Remaining E1c-5c work is explicit: post-selection destination edits and Legacy divergence; missing/invalid/partial layouts; real copy/verification interruption and conditional recovery, including unresolved CreateEmpty/Restore; cleanup; and the complete same-artifact macOS journey, followed by Windows/Linux qualification. These source tests are not GUI/OS-vault, release or full-matrix evidence. No commit, push, merge, deployment, release, normal-data conversion or key operation occurred. + +## E1c-5c encrypted-default native and renderer mounting — October 19, 2026 + +Authority: Jeff's accepted [E1c-5c source and disposable macOS packet](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate), including its [renderer mounting order](encrypted-workspace.md#renderer-mounting-and-returning-document-order). This completes the source mounting step; it does not complete disposable native qualification, normal-data conversion, the three-OS release or the operator/engine integration objective. The earlier unmounted/Legacy statements below describe their historical checkpoints. Branch is `codex/ops-local-window`, base HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; this packet remains uncommitted and unpublished. + +The ordinary desktop now selects the existing `encrypted-workspace` feature by default and installs the same deferred Managed factory as the disposable native target. Construction neither acquires an Owner nor accesses a vault. The immutable Managed registry, SourceAccess, close coordinator and startup Host share custody; no live service replacement occurs. An unavailable native anchor or explicit no-default-feature build installs a pathless unavailable Managed boundary instead of opening Legacy data. Existing Legacy originals and intentionally readable exports are not rewritten or relabeled as encrypted. + +The real renderer services C0 before its first startup request and independently purges/acknowledges C1 while native work waits. Lifecycle observation/acknowledgment is serialized separately from the pending status/action. Exact terminal Handoff stops and drains that pump; only a freshly validated ordinary Managed `open` state and native client permit constructing content controllers. An initially Open returning document still requires native Handoff. Legacy after Handoff refuses before client/content calls. Browser preview does not call startup IPC. Pagehide/BFCache fences and purges late work; a cancelable beforeunload prompt does not destroy the document if the user stays. Startup commands are registered only for the local main window. Unavailable cards have a separate empty-object Quit request to the existing exit coordinator, without forged plan identities or claims of completed shutdown. + +Root OpenAI Codex owns protected native/default/permission integration, fixture compatibility, validation and documentation. Disjoint native OpenAI `gpt_worker` lanes (configured Terra high) produced the startup-session module/tests and renderer mounting. Fresh native OpenAI `gpt_reviewer` and `gpt_ui_review` lanes (configured Terra xhigh) review separate immutable snapshots. UI review found the Legacy-after-Handoff gate and missing unavailable-card Quit; both are corrected and independently rechecked. Root browser testing also found the theme-shell selector intercepting all startup actions; it now selects only the theme button. A QA-only missing Handoff transition was corrected before final evidence. GLM was not contacted; no source was transferred to another provider. + +Evidence and original preimages: `/rangoon-e1c5c-mount-20261019`. Final native review uses `native-review-v4.patch`, its 16-path hashes and source snapshot; final UI review uses `ui-review-v3.patch`, its nine-path hashes and source snapshot. The native validator checks those source hashes around every command. An earlier run detected an in-flight QA/formatting change and was not counted as final immutable validation. Initial sandbox loopback refusals were rerun with scoped approval; a portable Clippy attempt selected the wrong installed driver, then passed with both Rust 1.85 compiler and driver pinned. No dependency installation, fetch, clean of shared targets or validation weakening occurred. + +Verified checks: encrypted-default all-target tests pass 160 library and 452 binary tests, with one library/two binary tests intentionally ignored; its isolated one-test child output is not an additional suite. Default documentation tests pass 22. Explicit no-default-feature all-target tests pass 43 library and 278 binary tests, with one binary test ignored, plus 22 documentation tests. `npm run build:check` passes syntax, visual/vision checks and all 456 behavior tests. Actual `analyze.html` browser QA passes source-free startup, duplicate action, Setup handoff, returning Open, Handoff-to-Legacy refusal, unavailable Quit/retry, pagehide, cancelable unload and no native IPC in preview; 320/768/1440, dark/light, focus and reduced-motion checks pass, with four local screenshots. Six ordinary-protection browser fixtures pass lock, held close, setup/unlock and Legacy/malformed refusal. These browser cases use synthetic native responses and establish no native GUI, OS-vault or real encrypted persistence qualification. Pinned Rust 1.85 workspace tests/Clippy and encrypted-store tests/Clippy pass; encrypted-store tests report 172 library, 10 capture, four adoption and two documentation cases, with nine library cases intentionally ignored. + +Final native matrix passes all nine source-guarded commands: all-target tests and documentation tests in both modes, all-target Clippy `-D warnings` in both modes, all-target builds in both modes, and explicit `native-encrypted-qualification` compilation. Every result records `source_unchanged: true`; `native-build-validation.json` preserves exact commands. Native `cargo fmt --all -- --check` and the document/reference validator pass. Default/disabled-backend Clippy is warnings-denied; the separately enabled custom executable compiles with 394 unused-test/import warnings from its shared harness, plus the existing duplicate-target Cargo manifest warning. That executable is not claimed lint-clean or native-qualified. Harness warning hygiene remains distinct work; no broad warning suppression or automatic `cargo fix` was applied. Native V4 and UI V3 independent reviews pass with no residual P1/P2/P3. + +Preservation closure: 677 original authored paths were checked against preimages. Exactly 25 owned paths changed and 652 remain byte-identical; three owned new paths bring the authored inventory to 680, with no missing path. `preservation.json` and the final hash seal own exact identities. Inherited encryption, NX-06, operations and connector changes outside this packet remain untouched. No staging, commit, push, merge, deploy or release occurred. + +First disposable macOS observation: the new nonce-scoped test artifact (`sourceSha256` `fc692774176963844a00d21520c570b852a5fe2a3b73b9a34814310a45a06dc0`, wrapped executable SHA-256 `8de25ddc4320d4b8e0385f8144816e619a5d05c6c15dd478a2e6a344c4247aeb`) displayed the real startup card, handed off to ordinary protection, opened its native setup sheet and returned to usable setup after explicit Cancel. The actual child exited 0 through native window close; the parent verified its exit receipt. Every recorded state/startup observation had zero vault opens/reads/writes and no client. Only the fixed Managed directory and its control file remain; no database or key was created. The post-close accessibility read timed out, so it is not used as exit evidence; the terminal process handle and clean native receipt are authoritative. `native-cold-cancel-receipt.json` and `native-cold-cancel-ui-evidence.json` retain the bounded evidence. This is one cancellation/exit observation, not successful provisioning, Cancel-after-restart, populated/empty Legacy conversion, recovery, other-OS or release qualification. The complete E1c-5c matrix still needs its additional fixed harness cases and one fully qualified selected artifact; do not aggregate unlike binaries into a blanket pass. + +Changed native paths: `apps/desktop/Cargo.toml`; `apps/desktop/build.rs`; `apps/desktop/capabilities/source-analysis.json`; `apps/desktop/native-encrypted-qualification/tauri.conf.json`; `apps/desktop/src/main.rs`; `apps/desktop/src/native_encrypted_qualification.rs`; `apps/desktop/src/workspace_adoption.rs`; `apps/desktop/src/workspace_adoption_tests.rs`; `apps/desktop/src/workspace_native_bootstrap.rs`; `apps/desktop/src/workspace_native_bootstrap_tests.rs`; `apps/desktop/src/workspace_source_access.rs`; `apps/desktop/src/workspace_source_access_tests.rs`; `apps/desktop/src/workspace_startup.rs`; `apps/desktop/src/workspace_startup_host.rs`; `apps/desktop/src/workspace_startup_host_tests.rs`; `scripts/qualify-native-encrypted.py`. The private verification return is unit; test-only inspection helpers are gated, and only reserved DTO vocabulary has narrowly explained dead-code annotations. No database/crypto/archive format or operation code changes. + +Changed renderer/test/documentation paths: `preview/analyze.html`; `preview/analyze.mjs`; `preview/desktop-startup-session.mjs` (new); `preview/workspace-lock-model.mjs` (existing decoder export only); `preview/desktop-startup-view.mjs`; `scripts/qa-desktop-startup.mjs` (new); `scripts/qa-workspace-lock.mjs`; `tests/desktop-startup-session.test.mjs` (new); `tests/desktop-startup-view.test.mjs`; `docs/encrypted-workspace.md`; `docs/continue.md`; this receipt. Existing ordinary-protection fixtures return only a cached source-free Handoff; the new startup fixture tests the actual C0/C1 service. No Graphify index exists in this app worktree. The separate default-cwd website is not this application and remains untouched. + +Security/standards impact: source-free lifecycle messages and exact main-window Quit requests add no source/key payload, provider transport, credential fallback or dependency. The same native vault selector now covers ordinary startup and the nonce-scoped disposable target; test copy/recovery cannot bypass its recorded custody wrapper. Native admission, real worker drain, OS confirmation, current identity and failure latch remain authoritative. This is candidate confidentiality/change-test evidence for the existing ISO/OpenSSF readiness plan, not a badge, certification, erasure proof or production-readiness claim. Next work remains the accepted disposable macOS first-launch/cancel/restart, Legacy copy and distinct-process verification/recovery matrix against this mounted artifact, followed by Windows/Linux qualification. Normal user data/keys, provider contact, LNSAT/VUSL edits, execution, publication and release remain closed. A substantive README update is required in any later publication packet. + +## E1c-5c conditional conversion recovery — October 19, 2026 + +Authority: Jeff's accepted [E1c-5c source and disposable macOS packet](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate). This completes the unmounted Target/Reopened recovery component, not the encrypted-default cutover or native GUI qualification. Root OpenAI Codex owns native integration and documentation; a disjoint OpenAI `gpt_worker` lane (configured Terra high) owns only `workspace_adoption_tests.rs`. Fresh OpenAI `gpt_reviewer` (configured Terra xhigh) passes the exact source/test snapshot with no remaining P1/P2/P3. GLM was not contacted; no source was transferred externally. + +Valid retained Target/Reopened journals now offer native recovery under the actual Startup Flight and fresh C1 acknowledgment. A private existing-key-only vault rejects a destination mismatch before opening a slot and refuses every key write. Recovery rechecks fixed-root layout before and after noncreating Owner acquisition, then retains Owner custody and checks the complete original capture, journal and native permit around callbacks and effects. Clean targets use native inspection consent; pending CreateEmpty/Restore operations require separately confirmed inspection, metadata reconciliation and a new unlock. Exact archive parity permits a separately confirmed Copied observation; a differing target must satisfy the existing strict empty-target restore contract before native Restore consent. Full Owner-backed parity is checked again after callbacks and immediately before Copied. No new Owner operation, crypto format, database schema or key-generation path is added. + +Target recovery always ends RestartRequired on the same fixed Host. Reopened recovery preserves its historical verifier identity and appends only Selected after fresh native key/parity consent. Both leave ordinary client publication to the existing protection flow. Explicit Cancel drops old previews and offers a newly bound recovery token when retained evidence still validates. Cancellation after confirmed reconciliation preserves that metadata write; it does not claim rollback. Unknown callbacks, missing keys, changed evidence and revoked cycles remain closed. + +Evidence, preimages and immutable review snapshots: `/rangoon-e1c5c-recovery-20261019`. Native commands use `/usr/local/bin/cargo`, `RUSTC=/usr/local/bin/rustc`, `RUSTDOC=/usr/local/bin/rustdoc`, `--manifest-path apps/desktop/Cargo.toml --locked --offline`. + +| Named validator | Result and limits | +| --- | --- | +| Native `cargo test` | PASS: 43 library, 303 binary and 22 documentation tests; one credential-QA binary test ignored | +| Native `cargo test --features encrypted-workspace` | PASS: 160 library, 449 binary and 22 documentation tests; one library and two binary helpers/credential-QA tests ignored. The isolated library child result is duplicate output, not another counted test | +| Focused `workspace_adoption::tests` | PASS: 38 tests, one child-process helper ignored; the ten `host_recovery_` cases also pass separately | +| Native default all-target Clippy and encrypted-feature test-target Clippy, `-D warnings` | PASS; the existing duplicate-main-target Cargo manifest warning remains | +| Encrypted-feature all-target Clippy, `-D warnings` | FAIL: the unchanged ordinary binary still leaves `startup_state` and `managed_deferred` unused. No warning suppression hides the remaining mounting work | +| Three startup/protection renderer suites | PASS: 33 tests; no DTO or renderer implementation changed | +| Exact-path Rustfmt, scoped whitespace and `node scripts/validate-review.mjs` | PASS: three changed Rust files; 556 authored text files, eight image hashes, the historical brief and local Markdown targets | + +Recovery regressions exercise empty/full/pending targets, real distinct-process Reopened completion, original preservation, scoped vault writes, cancellation before inspection, cancellation at Unlock after confirmed metadata reconciliation, stale-token refusal and fresh retry. Negative cases prove missing-key refusal without regeneration, wrong destination refusal before vault access, C1 revocation inside native confirmation before subsequent key/restore/journal effects, and destination drift during RecordCopied without a Copied append. These use disposable files and synthetic vaults only. Independent review's two P3 evidence gaps are closed by the post-reconciliation cancellation and real C1-revocation cases. Fresh independent matrix/receipt review also passes for this scoped component with no P1/P2/P3; it does not qualify native mounting or a release. The six-path delta preserves all 671 other authored preimage paths byte-for-byte. + +Exact changed paths: `apps/desktop/src/workspace_adoption.rs`, `apps/desktop/src/workspace_startup_host.rs`, `apps/desktop/src/workspace_adoption_tests.rs`, `docs/encrypted-workspace.md`, `docs/continue.md` and this receipt. Experience track: existing source-free states and action meanings remain stable; distinct native sheets explain each recovery step and the retained unencrypted original. Security/standards track: exact identities, noncreating acquisition, existing-key custody, explicit consent, complete parity and durable outcome distinctions supply candidate design/regression evidence, not certification or an OpenSSF badge. Dependencies, build privileges, provider behavior and engine contracts remain unchanged. + +Still required: mount the shared ordinary/disposable startup factory, service real C0/C1 renderer purges independently of waiting startup IPC, delay all content controllers until startup handoff plus ordinary protection, enable the encrypted default and qualify the integrated disposable macOS artifact. Ordinary desktop remains Legacy plaintext; Windows/Linux backend/native/GUI/install qualification remains a release requirement. The earlier journal fault-test intermittency is not diagnosed by a passing rerun. Unrelated mixed-tree work is preserved. No normal data/keys, real Keychain operation, provider, LNSAT/VUSL edit, commit, push, merge, deploy or release occurred. + +## E1c-5c native startup router and lifecycle custody — October 19, 2026 + +Authority: Jeff's accepted [E1c-5c source and disposable macOS packet](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate). This is ongoing implementation of that complete outcome, not a replacement constructor-only milestone. Root Codex owns protected native integration and canonical documentation. Disjoint OpenAI `gpt_worker` lanes (configured Terra high) own native bootstrap regressions and the bounded renderer wire correction. Fresh OpenAI `gpt_reviewer` (configured Terra xhigh) reviews the exact source delta; final validation and review results are recorded below. GLM is skipped; no source is transferred to another provider. + +The new native Host retains the actual Startup Flight and structural inspection, full Legacy capture or verification Owner. It requires completed C0 and fresh current C1 acknowledgment, exact plan/cycle matching and revalidation around native consent and storage effects. Fresh setup binds only a locked fixed-root Owner; normal CreateEmpty confirmation still owns key/database creation. Managed/Selected routes use noncreating acquisition and compare the exact live Owner identity before any key lookup. Selected journal custody remains held across binding; a mismatch latches failure rather than exposing a direct unlock bypass. Conversion cancellation retires its capture and rotates the plan token. Copy preserves original bytes and requires a real restart before verification; verification does not become normal unlock. + +Ready custody transfers out of the host mutex into a real blocking cleanup task on native close, exit or fatal source failure. Running work remains owned until its callback and cleanup return. Admission closes before terminal cancellation, and a dropped IPC waiter or JoinHandle is not drain proof. Registered main-window startup commands use empty-JSON status and at most 512 Raw UTF-8 action bytes; the content bridge rejects both. The native status worker has a bounded 30-second fresh-C1 wait and still checks the real Flight permit afterward. Terminal handoff nulls all request identities and carries no action, phase, diagnostic or content client. The unmounted renderer model now emits the native Raw body rather than an incompatible object wrapper. + +Evidence, exact preimages, final source snapshot and command logs: `/rangoon-e1c5c-startup-router-20261019`. Native commands use `/usr/local/bin/cargo`, `RUSTC=/usr/local/bin/rustc`, `RUSTDOC=/usr/local/bin/rustdoc`, `--manifest-path apps/desktop/Cargo.toml --locked --offline`. Final validation results: + +| Named validator | Result and limits | +| --- | --- | +| Native `cargo test` | PASS: 43 library, 303 binary and 22 documentation tests; one credential-QA binary test ignored | +| Native `cargo test --features encrypted-workspace` | PASS: 160 library, 438 binary and 22 documentation tests; one library and two binary helpers/credential-QA tests ignored. The isolated library child result is a duplicate, not another counted test | +| Native `cargo clippy --all-targets -- -D warnings` | PASS in the current default build | +| Native `cargo clippy --features encrypted-workspace --tests -- -D warnings` | PASS | +| Native `cargo clippy --features encrypted-workspace --all-targets -- -D warnings` | FAIL: `startup_state` and `managed_deferred` remain unused in the ordinary binary because mounting is unfinished. No warning is suppressed to hide this incomplete integration | +| Focused startup/protection/purge/request renderer suites | PASS: 65 tests across the ten named files in `renderer-focused.log` | +| `npm run build:check` | PASS: syntax, visual/vision contracts and all 445 Node tests; no rendered or native GUI qualification is inferred | +| Exact-path Rustfmt and `node scripts/validate-review.mjs` | PASS: 12 changed Rust files; 556 authored text files, eight image hashes, the historical brief and local Markdown targets. Scoped whitespace also passes | + +The router regressions include a real callback held across exit fencing, stale consent refusal before destination/key effects, retained Flight drain, current acknowledgment observation and wrong selected identity. Fresh independent review found two P2 defects: early no-cycle refusal was incorrectly cached forever, and explicit Verify Cancel was incorrectly reported as recovery. The same fixed Host now permits a new status read after actual C0 completion; native failure latches and plan-bound failures are not reset. Verify Cancel drops the old preview, revalidates a fresh one under the current permit and rotates its token without key access or selection. A real disposable child process proves Cancel, stale-token refusal and fresh Approved verification through null-ID handoff; key writes remain zero and no content client is published. Unavailable native callbacks remain distinct from explicit Cancel. Fresh independent source and final evidence/receipt reviews pass with no residual P1/P2/P3; this verdict covers this component only. No test exercises a normal OS vault, live provider or normal workspace. The initial oversized-enum/condition Clippy findings were corrected by boxing the two large payloads and simplifying the condition, not by weakening linting. The existing Cargo duplicate-main-target manifest warning remains. + +Exact owned native paths under `apps/desktop/src/`: `main.rs`, `workspace_adoption.rs`, `workspace_adoption_tests.rs`, `workspace_close.rs`, `workspace_close_control.rs`, `workspace_failure.rs`, `workspace_native_bootstrap.rs`, `workspace_native_bootstrap_tests.rs`, `workspace_reopen.rs`, `workspace_source_access.rs`, `workspace_startup_host.rs` and `workspace_startup_host_tests.rs`. Renderer paths: `preview/desktop-startup-model.mjs`, `preview/workspace-lock-model.mjs`, `tests/desktop-startup-model.test.mjs` and `tests/workspace-requests.test.mjs`. Documentation paths: `docs/encrypted-workspace.md`, `docs/continue.md` and this receipt. The 19-path delta preserves all 658 other authored preimage paths byte-for-byte. + +Experience track: no rendered layout change; this supplies truthful source-free startup state and native control plumbing. Security/standards track: retained plaintext snapshots stay native, exact identity/consent boundaries remain enforced, key lookup is gated, and real worker ownership replaces cancellation assumptions. There is no dependency upgrade, crypto/archive/schema change, provider behavior or new build privilege; permitted elevated tests use disposable local sockets and synthetic TLS peers only. This is candidate secure-design/regression evidence, not OpenSSF badge attainment. + +Unfinished within E1c-5c: Target/Reopened conditional recovery, normal/disposable use of the same deferred startup factory, independent renderer C0/C1 purge orchestration, delayed source-controller construction, fresh ordinary-protection handoff, encrypted-default selection and integrated disposable macOS qualification. The shared factory and router Host remain unmounted; ordinary desktop still uses Legacy plaintext. Windows/Linux backend/native/GUI/install qualification remains required before the three-OS release. The earlier journal fault-test intermittency remains an unresolved qualification concern unless its cause is established. Preserve all unrelated mixed-tree work. No normal data/keys, real Keychain operation, provider/LNSAT/VUSL change, commit, push, merge, deploy or release is performed here. + +## E1c-5c native adoption custody — October 19, 2026 + +Authority: Jeff's accepted [E1c-5c source and disposable macOS packet](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate). This receipt covers one implementation component; it does not establish completed startup, conversion recovery, encrypted-default activation or native GUI qualification. Root Codex owns protected native integration and canonical documentation. Two disjoint OpenAI `gpt_worker` lanes (configured Terra high) own adoption and close-supervisor tests. Fresh OpenAI `gpt_reviewer` (configured Terra xhigh) reviews the exact delta. GLM is skipped because native lanes are adequate; no source is transferred to an external provider. + +The Startup control retains the actual closed-operation lease without preparing, confirming or resuming an ordinary content client. Its borrowed permit requires the current healthy coordinator, actual lease and fresh C1 renderer acknowledgment before source capture or native adoption work. Conversion and verification plans retain an opaque weak coordinator identity plus exact control serial; a later valid cycle or another coordinator cannot revive earlier native consent. Native confirmation revalidates the retained source and current permit before and after the callback. Unclassified dismissal is unavailable, not explicit Cancel. Copy and verification use bounded cancellation checkpoints, retain real worker/Owner custody, preserve the original and retain interrupted journal evidence. An already entered bounded storage operation can finish after cancellation; neither cancellation nor a failed callback proves rollback or no effects. Verification now acquires only the existing destination control and never recreates a vanished control. Static copy/verify native-sheet definitions live in the startup host and reuse the exact-button classifier; no startup command is mounted yet. + +Independent review identified a pre-publication P1 in the initial delta: old approved plans could be passed to a different currently valid permit. The coordinator/serial binding corrects that defect. Separate verification confirmation/selection replay tests close the reviewer's P3 gap. Fresh independent source/spec review returns PASS with no residual P1/P2/P3 for this component; it does not approve the unfinished native startup phase. Earlier failed or superseded runs remain in the evidence directory. + +| Named validation | Result and scope | +| --- | --- | +| Native default `cargo test --manifest-path apps/desktop/Cargo.toml --locked --offline` | PASS: 43 library, 301 binary and 22 documentation tests; one binary helper is ignored | +| Native encrypted command above plus `--features encrypted-workspace` | PASS: 160 library, 427 binary and 22 documentation tests; one library and two binary helpers are ignored. An isolated child reports one of the same library tests separately; do not count it twice | +| Focused encrypted `workspace_adoption::tests` | PASS: 26 tests, one explicitly invoked process helper ignored by the parent. Includes real distinct-process native-permit verification, conversion/verification replay, cross-coordinator refusal, post-callback source drift, cancellation and missing-control refusal | +| Focused encrypted `supervisor_controls` | PASS: 18 tests, including refusal before fresh C1 ACK, exclusive retained worker and actual callback drain; these are included in the full binary result | +| `cargo clippy --manifest-path apps/desktop/Cargo.toml --locked --offline --all-targets -- -D warnings` | PASS for current default configuration | +| Encrypted Clippy with `--tests -- -D warnings` | PASS for the encrypted test targets | +| Encrypted Clippy with `--all-targets -- -D warnings` | NOT PASSING: existing unmounted `SourceAccess::managed_deferred` is unused in the ordinary non-test binary. Finish the accepted real startup factory; no lint suppression was added to conceal this gate | +| Scoped Rust formatting, whitespace and canonical links | PASS; final path hashes and preservation checks accompany this receipt | + +All commands use local Rust/Rustdoc/Cargo 1.98 and locked/offline dependencies. Sandbox runs initially failed on a disposable AF_UNIX socket and synthetic TLS peer startup; exact affected checks and the final full matrix pass outside that restriction, with no live provider or real credential use. The existing Cargo duplicate-main-target manifest warning remains. One preliminary parallel crash-journal assertion failed before it reported the actual observed status; a diagnostic-only change now records phase, boundary and status without widening the assertion. Its isolated test, final adoption suite and final full matrix pass. The initial intermittent failure's cause is not proven and remains a reliability concern for integrated qualification, not a hidden passing run. + +Exact owned source paths: `apps/desktop/src/main.rs`, `workspace_adoption.rs`, `workspace_adoption_tests.rs`, `workspace_close.rs`, `workspace_close_control.rs`, `workspace_close_control_tests.rs`, `workspace_reopen.rs`, `workspace_setup.rs`, `workspace_source_access.rs` and `workspace_startup_host.rs` (all latter names under `apps/desktop/src/`). Canonical documentation changes are `docs/encrypted-workspace.md`, `docs/continue.md` and this receipt. Prior mixed-tree work is preserved; the packet delta is measured against its preimage rather than the dirty branch's entire diff. + +Experience track: no rendered UI changes; the future native sheets explicitly describe OS-key use, retained unencrypted originals and separate restart verification. Technical/security track: native custody and consent freshness for full Legacy snapshots held in trusted memory and encrypted-destination operations; no dependency, crypto format, Owner operation code, provider behavior or build privilege change. This is candidate evidence for OpenSSF secure design, meaningful regression tests and warning discipline, not a completed badge assessment. The test privilege exception permits disposable local Unix sockets and synthetic TLS peers only; it does not permit live provider contact or real credentials. + +Evidence: `/rangoon-e1c5c-native-adoption-20261019`. Exact source snapshots, test commands/results, review and preservation receipts are retained there. Normal user data/keys, real OS-vault operation, provider/LNSAT/VUSL changes, commit, push, merge, deploy and release remain untouched. The ordinary factory still uses Legacy plaintext. The accepted next work remains the complete native startup/recovery host, terminal cancellation, shared ordinary/disposable factory, fresh renderer handoff, encrypted-default source selection and isolated macOS qualification, followed by Windows/Linux qualification before release. + +## O2 record-count consistency correction — October 19, 2026 + +Authority: the accepted [O2 local-window contract](operations-local-window.md), with an exact renderer-consistency correction. This does not accept E1c-5c, O3 ingress, provider mounting or a new data/authority contract. Root OpenAI Codex owns preview/operations-model.mjs, tests/operations-model.test.mjs and docs/{operations-local-window,continue,development}.md. Native OpenAI gpt_reader (configured Luna medium) mapped numeric and inventory contracts; it made no edits or test runs. A fresh independent read-only native OpenAI gpt_reviewer (configured Terra xhigh) returned PASS with no actionable P1/P2/P3, including a final hash-bound contract-wording check. GLM is skipped; no private source was sent externally. + +A direct malformed-response probe reproduced the defect: a two-event Rust golden containing one actor and one evidence record was accepted after its counts were changed to zero actors and two evidence records. The aggregate total remained correct. Current Rust projection emits the correct inventory; this was a missing renderer consistency fence, not evidence that a native parser, provider or execution engine supplied false records. The renderer previously verified the four decision-group denominators and reported-value buckets, leaving other record-kind counts unchecked. It now counts every validated event by the existing nineteen kinds and rejects any per-kind mismatch before publishing the view. This is bounded display validation, not relationship reduction, authenticity, approval or execution authority. + +Three new regressions failed before the correction. They cover all nineteen mismatched per-kind counters, a same-total kind substitution with a prior valid selection, and a valid empty view followed by invented inventory. The existing response rejection remains atomic: a failed replacement keeps the prior valid view, selection and explicit previous-window label. No DTO key, schema, native reader, Rust projection, fixture, graph behavior, DOM/style or persistence route changed. Experience track: operators cannot see contradictory category inventories accepted as a valid replacement. Technical/security track: fixed error behavior, bounded linear validation, existing privacy omissions and exact truth labels remain unchanged. No dependency, credential, cryptography, network behavior or standards/readiness claim was added. + +Evidence/preimages: /rangoon-o2-record-counts-20261019/. The focused Node model/view/golden-parity command passed all 28 tests. /usr/local/bin/cargo test -p rangoon-ops --test operator_view_parity --locked --offline passed both current Rust-to-renderer golden fixtures. npm run build:check passed syntax, asset/vision checks and all 430 Node tests on the permitted rerun. Its initial sandbox attempt failed only the existing preview-server test with listen EPERM on 127.0.0.1; the successful retry used the same assertions and a disposable loopback listener. The initial red-run summary helper expected TAP while Node emitted its default spec format; the preserved raw log contains the three expected failing regressions, and the final focused validator explicitly selects TAP. No assertion or fixture was weakened. node scripts/validate-review.mjs passed 548 authored text files, eight reference-image hashes, the historical brief and local Markdown targets; git diff --check passed. The exact five-file proof leaves 664 other authored files byte-identical. independent-review.json binds the reviewed hashes; final-seal.json records only the review-result/validation receipt update afterward. No rendered/native or other-OS qualification is claimed. + +The E1c-5c proposal and acceptance request remain separate. Existing E1c-5a/5b native/store source, fixtures and unrelated mixed-tree work are preserved. No normal data/key, OS vault, provider, LNSAT/VUSL edit, encrypted-default activation, commit, push, merge, deployment or release occurred. + +## OpenSSF Best Practices adoption planning — October 19, 2026 + +Authority: Jeff linked the OpenSSF Best Practices Badge program and requested that Rangoon plan adherence. This docs-only continuation refines the existing [security and standards readiness track](plan.md#openssf-best-practices-adoption-plan); it does not create a competing assessment register or change the accepted five-path VUSL E0/E1 packet in its separate worktree. Root OpenAI Codex owns only this receipt and the targeted docs/plan.md delta. Official program and Passing/all-level criteria pages were checked on October 19. Passing is the first development target, with later Silver/Gold assessment; the OSPS Baseline assessment remains distinct and its existing revision is unchanged. + +The plan assigns owners and proof for public/contribution/interface documentation, version/change/release discipline, monitored reporting, reproducible builds and meaningful tests, security/crypto/credential handling, and static/dynamic analysis. A later bounded readiness packet must inventory every criterion, preserve requirement strength and allowed applicability, and attach dated evidence and gaps. A source document or agent review cannot establish monitored response history, qualified human security ownership or actual hosted enforcement. No badge, percentage, certification or complete conformance is claimed. + +Validation passes: scoped whitespace, new anchor/link checks and all 24 sample criterion IDs against the official Passing list. Fresh independent OpenAI `gpt_reviewer` (configured gpt-5.6-terra, xhigh) passes with no residual P1/P2/P3 after a P2 correction explicitly separated the sample backlog from the one later canonical register and retained per-criterion requirement strength. Evidence: `/rangoon-openssf-plan-20261019`. GLM was not contacted. Experience track: no UI change. Security/standards track: clearer adoption backlog and accountability only; no runtime/data/authority/dependency/build privilege changes. Existing native/encryption source and all E0/E1 files remain untouched. No accounts, external messages, badge application, hosted setting, scanner/CI installation, provider, key/data operation, VUSL/LNSAT edit, commit, push, merge, deploy or release is authorized or performed here. + +## E1c-5c deferred-binding and startup-message foundation — October 19, 2026 + +Authority: Jeff accepted “E1c-5c source/tests”; [accepted intent](intent.md#e1c-5c-source-and-disposable-macos-acceptance--october-19-2026) and [startup/recovery contract](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate) own scope. This is an intermediate implementation, not completed encrypted-default startup or native qualification. Root OpenAI Codex owns protected native integration and documentation. Native OpenAI `gpt_worker` (configured Terra high) supplied disjoint tests and renderer components. Fresh OpenAI `gpt_reviewer` (configured Terra xhigh) reviewed the native foundation and pure message contract; a separate fresh reviewer reviewed the renderer components. Both pass with no open P1/P2/P3. GLM was not contacted; no private source was transferred externally. + +Native source adds existing-only Owner acquisition, an immutable deferred Managed backend/registry, and opaque fixed-root binding proofs consumed through the actual closed-control Flight. Unbound requests refuse without content access or a false corruption latch. Existing-only acquisition cannot create a missing control; fresh/residue binding checks exact managed-root contents and identities without accessing a key. The app-data anchor still permits unrelated application metadata. The new `workspace_startup_host` module contains only bounded source-free request/view types; no running host, startup action, native copy/verify consent or ordinary factory is mounted. Renderer model/view/CSS components match that closed grammar, retained-original warnings, disposal fences and accessible controls; no rendered/native UI claim follows from component tests. + +Exact source paths: apps/desktop/src/{workspace_session,workspace_source_access,workspace_reopen,workspace_close_control,workspace_startup,workspace_managed_bootstrap_tests,workspace_startup_tests,workspace_startup_owner_tests,workspace_startup_host,workspace_startup_host_tests,main}.rs; preview/{desktop-startup-model.mjs,desktop-startup-view.mjs,desktop-startup.css}; tests/{desktop-startup-model,desktop-startup-view}.test.mjs. Intent/contract/continuation documents record acceptance separately from inherited work. + +Validation: focused Owner/startup-proof/Managed-binding/message suites pass 6/20/10/8 tests. `cargo test --manifest-path apps/desktop/Cargo.toml --locked --offline` with recorded Rust 1.98 passes 43 library, 301 binary and 22 documentation tests, with one binary ignored. Adding `--features encrypted-workspace` passes 160 library, 412 binary and 22 documentation tests, with one library and two binary ignored; an isolated child reruns one library case and is not another unique test. `npm run build:check` passes syntax/assets/vision checks and 443 Node tests, including 13 new component tests. Formatting/whitespace and fresh review pass; the reviewer separately confirmed one formatter-only delta to an existing test assertion. Earlier sandbox/socket-fixture failures remain in the evidence. Expected unused deferred-constructor warnings remain until factory integration; no full-packet warnings-denied, Clippy or platform-build claim is made. + +Evidence: `/rangoon-e1c5c-implementation-20261019` contains preimages, exact commands/logs, result ledger and hash-bound reviews. These are scratch evidence, not runtime dependencies. Experience track: compact source-free startup components await integration. Security/standards track: existing-only metadata handling and native custody changed; no schema, archive/journal format, dependency, cryptography or provider contract changed. This neither authenticates storage against a malicious same-user host nor removes Legacy plaintext or establishes ISO/OpenSSF compliance. Ordinary desktop still uses Legacy plaintext. Next finish the shared ordinary/qualification factory, real consent/recovery workers, terminal cancellation, renderer close-cycle handoff and disposable macOS matrix. Windows/Linux qualification remains required before release. No normal data/key access, OS vault, provider, LNSAT/VUSL edit, default switch, commit, push, merge, deploy or release occurred in this component. + +## E1c-5c startup and recovery design — October 19, 2026 + +Authority: the accepted encryption-completion outcome, completed E1c-5b source and the continuing independent-engine/operator-record goal. This is design and read-only compatibility review, not E1c-5c source/default/migration/native-operation acceptance. The [canonical design gate](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate) owns candidate behavior. Root OpenAI Codex owns protected architecture and exactly five documentation paths: docs/{encrypted-workspace,plan,continue,development,lnsat-evidence-connector}.md. Native OpenAI gpt_reader (configured Luna medium) mapped current startup/close/consent seams; gpt_ui_design (configured Terra high) supplied bounded source-free UI-state advice. A fresh read-only native OpenAI gpt_reviewer (configured Terra xhigh) challenged selected-target trust, deferred binding, watchdog behavior, source revalidation, v1 verifier meaning and setup residue. The revised proposal includes its required checks. A separate fresh native OpenAI gpt_reviewer (configured Terra xhigh) reviewed the final five-document snapshot and supplied evidence: PASS, no actionable P1/P2/P3. GLM was skipped; no private source was transferred externally. + +Baseline remains /rangoon-audit-20261015, codex/ops-local-window, c132ea62bc57b29375ee8c5a3a38ca005462ca40. Preimages of all 669 authored files and the five owned documents are under /rangoon-e1c5c-design-20261019/. The E1c-5b implementation/evidence seal and all source/test/manifest/lock/frontend files remain unchanged. Previous goal turn is progress: it completed accepted unmounted conversion source, subprocess/fault evidence and independent review; the full operator-record objective is not complete. + +The audit found that ordinary main.rs still selects Legacy; managed_locked immediately acquires an Owner; SourceAccess fixes encrypted mode/registry behind one shared Inner; native setup supports only CreateEmpty/Unlock; and 5b consent constructors remain synthetic. Current lock layout cannot describe conversion. Owner::acquire also tries create_new for its control, so the proposal adds an existing-only acquisition seam for previously observed destinations; it must not repair a disappeared control file. The candidate therefore keeps one immutable Managed mode and deferred native Owner binding, introduces a separate source-free startup controller, preserves existing native client/closed-cycle checks, and explicitly plans worker/exit retention. It also freezes a recovery decision matrix before code: valid Target/Copied/Reopened phases require current real Owner/source/consent proof, while malformed or identity-unknown attempts cannot reset. Native key-read inspection, Owner reconciliation, transfer and ordinary unlock remain distinct operations. The architecture review confirmed that v1 retains the original Reopened verifier, not a selection-writer identity; current third-process recovery must independently recheck source/destination/consent and differ from creator. No v1 field is relabeled and no new journal/profile is proposed. + +Experience track: one coherent setup/review/restart/unlock/recovery flow, short controls and persistent retained-plaintext disclosure within the existing shell. No UI was changed or rendered; source review and a design-agent table are not usability/native/a11y qualification. The default-encrypted/copy-or-Quit behavior is proposed explicitly rather than silently changing Legacy compatibility. Technical/security track: no mutable backend-mode switch, renderer path/key/saveability authority, client-before-unlock, prior-consent reuse, automatic retry, new cryptography/dependency or certification claim. Three-OS and distribution gates remain open. + +Goal-path recheck: clean LNSAT request-bound Git-result worktree remains at 605742b3. A later clean guarded-fake-dispatch worktree is at 96e4a0910dcbb091c1846db742fa79daa6fb36ff, following 25d2afd4. Its private guarded dispatch is cfg(test), has no real runtime/effect, and fake success supplies no completion/receipt. The [connector follow-up](lnsat-evidence-connector.md#october-19-guarded-fake-dispatch-follow-up) records limits; no LNSAT test or operation ran here. D3a remains pinned to f669181a. After native encrypted adoption, D2b-2b/3, a separately designed D3b read path and O3 qualified ingress remain necessary for OR-01–OR-12. No OpenShell/LNSAT dependency or universal-support claim was introduced. No public competitors were re-audited in this packet. + +Proportional validation passes: node scripts/validate-review.mjs checks 548 authored text files, eight reference-image hashes, the historical brief and local Markdown links; git diff --check passes. Exact five-document scope proof leaves all 664 other authored files byte-identical, including the full E1c-5b source/test seal. No new file was added. Final independent design/evidence review passed; independent-review.json binds the reviewed hashes, and final-seal.json records only this review-result receipt update afterward. Source validators and disposable macOS/native-vault cases are proposed only, not run or accepted here. No source, normal data/key, OS vault, native UI, provider, LNSAT/VUSL edit, default switch, commit, push, merge, deployment or release occurred. Existing mixed-tree work is preserved. + + +## E1c-5b implementation — October 19, 2026 + +Authority: Jeff's explicit [E1c-5b source/disposable-test acceptance](intent.md#e1c-5b-source-acceptance--october-19-2026). The [accepted packet](encrypted-workspace.md#e1c-5b-verified-conversion-and-durable-selection--proposed-source-packet) owns behavior and exact ownership. Root OpenAI Codex owns protected store/native implementation, tests and integration. A disjoint native OpenAI `gpt_worker` (configured Terra high) supplied only the literal journal codec tests. Fresh native OpenAI `gpt_reviewer` (configured Terra xhigh), independent of the producers, reviews source and evidence. GLM was skipped; no private source was transferred externally. Baseline app worktree `/rangoon-audit-20261015`, branch `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Existing native/O2/D3a work and the separate VUSL reference branch remain preserved. + +Delivered source is unmounted: the private coordinator consumes an exact retained Legacy capture, requires a one-shot typed confirmation, creates a fresh Managed Owner, transfers into a proven empty encrypted target and checks complete archive equality. Strict restore uses the existing transaction/row writer and durable Owner `CreateEmpty`/`Restore` operations. Observed schema 0 maps to target schema 1; schemas 1–4 retain their physical schema, including empty sources. A bounded five-phase journal binds source identity/content, inventory, attempt, destination and process identities. Selection requires a distinct process, a fresh verification confirmation and exact source/destination equivalence again. It issues no client and grants no execution authority. Ordinary startup still selects Legacy plaintext. + +Implementation findings: V2 decoding reconstructs schema 3, so the strict plan separately binds the observed source schema and validates representability without changing archive bytes. Generic union resolves heads and can trim records no longer required by its result; strict transfer preserves the complete validated input, including a shared composition application whose other output is absent. Entirely orphaned recipes/applications remain invalid. Independent review found the identity-field order and missing/vanished journal-file classifications needed correction. Root-to-source-directory device/inode ordering now has an independently constructed byte test. Missing control/phase records and linked files refuse as interrupted/recovery state rather than being treated as successful selection. Genuine inaccessible/busy I/O stays unavailable. A complete surviving Selected record reports only SelectionRecorded, never proof of a previous caller's acknowledgment. Later legitimate Managed authoring remains valid; retained Legacy divergence reports LegacyDiverged separately. + +Focused evidence covers nine schema/population pairs; exact archives, physical schemas, source bytes, histories, reviews, composition relationships, two compiler profiles and instruction-bundle parity after actual process restart; no-create/no-overwrite/stale-plan refusals; one-key-only reopen and key-loss refusal; source commits before/during copy and during verification; dropped/wrong consent and busy ownership; seven strict journal codec tests; 50 phase-boundary injected failures and ten initial directory/control-boundary failures. Disposable coordinator kills cover 15 copy-phase boundaries, ten verification/selection boundaries and eight provision/key/restore/close boundaries. Three additional store subprocess kills bracket migration/row writes, and two cases force actual SQLite disk-full errors. SQLite-full transactions roll back to the empty destination. A kill before mutation remains empty; spilled killed transactions leave an uncertain encrypted journal and existing readers return EncryptedStoreInvalid. No repair or permissive reopen is used. Parent fixtures wait/reap children and delete only their exact synthetic namespaces; the final named-child process check found zero remaining children. + +Evidence directory: `/rangoon-e1c5b-implementation-20261019/`. `scope.json`, `owned.txt`, incremental `diff/`, matrix JSON and raw logs retain exact boundaries and identities. Production changes are `apps/desktop/src/{main,workspace_startup,workspace_session,workspace_adoption,workspace_adoption_record}.rs` and `crates/rangoon-store/src/{lib,workflow_backup,workflow_recovery}.rs`. Test changes are `apps/desktop/src/{workspace_startup_tests,workspace_adoption_tests,workspace_adoption_record_tests,workspace_adoption_owner_tests}.rs` and `crates/rangoon-store/src/workspace_adoption_tests.rs`. Documentation changes are `docs/{intent,encrypted-workspace,plan,continue,development}.md`. Twelve prior files changed and six were added; all 651 other captured authored files remain byte-identical. Manifests, lockfiles, normal entry calls, IPC registration, provider/engine code and frontend source are unchanged by this packet. No Graphify index exists in this worktree. + +The final multi-revision fixtures passed fresh full encrypted store/native tests and warnings-denied Clippy with exit 0. `store-encrypted-test-final.log`, `store-encrypted-clippy-final.log`, `native-encrypted-test-final.log` and `native-encrypted-clippy-final.log` bind those post-edit results. `native-default-test-final.log` and `native-default-clippy-final.log` retain the final default checks; `validation.json` preserves the initial matrices and explicit successful overrides rather than hiding the earlier lint failure. The table reports these final results. + +| Named validation | Result and bound | +| --- | --- | +| Homebrew Rust/Cargo 1.98.0 `cargo test -p rangoon-store --locked --offline`, default and `--features encrypted-sqlite` | PASS: default 162 unit tests, two integration tests and two privacy doctests; encrypted 172 unit tests, 14 integration tests and two privacy doctests. Eight/nine ignored helper cases remain explicit; parent-driven children are exercised by their parents, not counted twice | +| Same package `cargo build` and `cargo clippy --all-targets -- -D warnings`, both modes | PASS; no dependency or lockfile change | +| `cargo test --manifest-path apps/desktop/Cargo.toml --locked --offline`, default and `--features encrypted-workspace` | PASS: default 43 library + 287 binary tests; encrypted 154 library + 393 binary tests; both include 22 privacy doctests. One/two ignored binary helpers and the encrypted library helper are not additional qualification | +| Same native manifest `cargo build --bin rangoon-desktop` and all-target warnings-denied Clippy, both modes | PASS; the initial default Clippy found four new style warnings, corrected without lowering lint severity; `native-default-clippy-final.log` supersedes that failed run | +| `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` | PASS: pinned Rust/Cargo/Clippy 1.85.0 formatting, workspace tests and warnings-denied all-target Clippy. This remains the portable default-feature source gate | +| `cargo fmt --all -- --check` and native-manifest formatting check | PASS | +| Eight named renderer suites: startup lock/purge, workspace requests, authoring/view/services purge, save disclosure, lock model and lock view | PASS: 50 tests; frontend source unchanged | +| `node scripts/validate-review.mjs`, `git diff --check`, exact scope preservation | PASS: 548 authored text files, eight reference-image hashes, the historical brief hash, local Markdown targets and whitespace; 651 outside-owned preimages unchanged | + +Native synthetic-peer regressions and the pinned source gate ran with separately permitted sandbox access for existing localhost/symlink fixtures. No public endpoint was contacted. A sandboxed named-child `ps` check returned EPERM; its permitted read-only retry passed. This is environment permission evidence, not a product or test-assertion bypass. Intermediate new test-fixture errors (unsupported schema-0 ordinary list, an invalid fully orphaned recipe, a too-long synthetic line, and an incorrect pre-write crash expectation) were corrected to the existing contracts. The final tests preserve strict bounds and honest refusal behavior. + +Experience track: this supplies the conversion/restart foundation for a coherent native review and recovery flow; no UI, graph, artwork or interaction changed. Technical/security/standards track: bounded plaintext stays in host processing, synthetic test keys remain only in disposable fixture storage, and journal metadata (fingerprints/counts/local IDs) remains visible outside encryption. Retained Legacy plaintext is not deleted. There is no anti-rollback, malicious same-user defense, complete memory/swap erasure, old-Legacy-writer fence, new cryptography/dependency or certification claim. ISO/OpenSSF readiness still requires its separate organizational/package evidence. Real native consent, OS vault, ordinary startup/exit/purge and three-OS qualification remain E1c-5c; encrypted portable recovery remains E1d. Windows/Linux GUI and real-user migration are not qualified by this source packet. + +Fresh independent source and final receipt/hash review both passed with no remaining P1/P2/P3. The reviewer checked all 18 owned hashes, the post-fixture exit-0 logs, explicit initial-failure overrides and the stated source-only limits. `independent-review.json` and `reviewed-scope.json` retain that review snapshot; the final seal changes only this review-result sentence and rechecks scope/document validation. No normal data/key operation, OS vault, native UI operation, provider, LNSAT/VUSL edit, default switch, commit, push, merge, deployment or release occurred. The accepted source slice does not complete the broader encryption-adoption or independent-engine operator-record goals. + +## E1c-5b conversion packet design — October 19, 2026 + +Authority: accepted encryption completion and the E1c-5a handoff to a reviewed E1c-5b proposal. This is design/review only, not source acceptance. Root OpenAI Codex owns the four changed documents `docs/{encrypted-workspace,plan,continue,development}.md` and protected native/store decisions. A read-only OpenAI `gpt_reader` (configured Luna medium) mapped existing transfer/recovery functions; its initial schema-0 inference was corrected against `workflow_mutations::read_records`, `Records::empty` and the existing E1c-5a empty-capture test. Fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) design review returned PASS, with no actionable P1/P2/P3. GLM is skipped; no external private-source transfer is needed. Baseline remains app worktree `/rangoon-audit-20261015`, branch `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Preimages/evidence: `/rangoon-e1c5b-design-20261019/`. + +The [canonical proposal](encrypted-workspace.md#e1c-5b-verified-conversion-and-durable-selection--proposed-source-packet) reuses Owner creation/restoration and its durable operation records, adds only the missing cross-root attempt/selection mechanics, preserves generic additive restore, names exact prospective production/test ownership and requires the full transfer/restart proof. Two inspected edge cases drive the design: a no-additions restore retains destination schema, so empty schemas 2–4 need an explicit strict empty-target path; and creating Managed changes the layout to Mixed, so the accepted Legacy-only retained wrapper must be consumed into separately verified source/destination custody rather than weakened with a generic exception. A selected destination may later change through legitimate authoring; its migration digest is historical evidence, not a permanent content freeze. + +Experience track: conversion should show one reviewable source/target preview, real native confirmation and actionable interrupted/recovery states without presenting another empty workbench. Technical/security track: bounded plaintext only in host memory, native-owned paths and identity, exact empty-schema normalization, full record/archive parity, one-shot consent, finite durable phases and conservative uncertainty. A complete surviving selection record cannot prove a prior process received acknowledgment; the proposal separates SelectionRecorded from live validation and from interrupted/torn records. Proposed content-free journal metadata still exposes fingerprints/counts and is neither encryption nor authenticated audit/anti-rollback. No new dependency, crypto primitive, provider authority or standards-certification claim. Real native consent, OS vault and normal startup remain E1c-5c gates. No source change/test execution, normal data/key access, migration, default switch, provider call, LNSAT/VUSL edit, commit, push, merge, deployment or release belongs to this design packet. + +Validation: `node scripts/validate-review.mjs` passed 542 authored text files, eight reference-image hashes and the historical brief hash; `git diff --check` passed. Exact preimage audit found only the four owned documents changed and 659 other authored files unchanged, including all E1c-5a source/test hashes. Independent design review checked schema preservation, Mixed-state custody, consent/restart/uncertainty semantics, later legitimate authoring and exact ownership/test feasibility: PASS. The queued VUSL extraction handoff remains reported uncommitted upstream planning, not consumer execution, source movement or a dependency pin. Source validators are named in the proposal but intentionally unrun for docs-only work. Explicit E1c-5b source and disposable-test acceptance remains pending; this review is not that acceptance. + +## E1c-5a implementation — October 19, 2026 + +Authority: Jeff's explicit [E1c-5a source acceptance](intent.md#e1c-5a-source-acceptance--october-19-2026). The [accepted packet](encrypted-workspace.md#e1c-5a-startup-inspection-and-existing-source-capture--proposed-source-packet) owns behavior and exact paths. Root OpenAI Codex owns protected native/store integration. A native OpenAI `gpt_reader` (configured Luna medium) supplied focused source evidence; a native OpenAI `gpt_worker` (configured Terra high) authored the disjoint metadata-only startup tests, then root added the real store/capture lifecycle cases. A fresh read-only OpenAI `gpt_reviewer` (configured Terra xhigh) reviews final source. GLM is skipped; no external private-source transfer is needed. Baseline remains `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; preimages are `/rangoon-e1c5a-implementation-20261019/`. Existing native/O2/D3a and separate VUSL reference work are preserved. + +Implementation is complete at the unmounted source boundary. Experience track: later setup/conversion can distinguish missing, existing, mixed and invalid data before exposing an empty workspace. Technical track: fixed native roots have bounded metadata-only candidate inspection, retained Unix device/inode ancestry proofs and conservative refusal states. Existing-only Legacy capture uses the existing read-only connection and complete record reader in one transaction, retains version-aware canonical archive bytes/schema/inventory in host memory, and validates the archive through the existing decoder. Revalidation compares the full recaptured logical state; every failure or cancellation clears retained bytes. Source/sidecar comparisons and a private test-only capture hook cover refusal without repair. `WorkspaceBackup` and the new retained types have fixed redacted diagnostics; the public opaque store type has a compile-fail non-serialization check. No IPC or normal-entry call is registered. + +Exact changed paths: `apps/desktop/src/{workspace_startup.rs,workspace_startup_tests.rs}` (new), private module registration only in `apps/desktop/src/main.rs`; `crates/rangoon-store/src/{workflow_backup.rs,workspace_capture_tests.rs}` (the latter new), necessary re-export only in `crates/rangoon-store/src/lib.rs`; and `docs/{intent,encrypted-workspace,plan,continue,development}.md`. The preimage comparison verifies eight existing owned files changed, three owned source/test files added and 652 other captured authored files unchanged. Existing unrelated dirty source, generated/ignored state and the separate reference branch are preserved. Final source hashes are recorded in `source-hashes.json` beside the validation logs; final whole-packet hashes and scope proof are sealed after the receipt review. + +Source validation uses Homebrew Cargo/Rust 1.98.0 with explicit compiler/rustdoc paths and locked/offline dependencies. Results: + +| Check | Observed result | +| --- | --- | +| Store default full suite | 160 unit tests, two integration tests and one compile-fail documentation test passed; eight existing unit tests remain ignored | +| Store `encrypted-sqlite` full suite | 164 unit tests, 14 integration tests and one compile-fail documentation test passed; the same eight existing unit tests remain ignored | +| New capture and startup cases | 11 store cases in both backend modes and 13 native startup cases passed, including schema 0–4, valid empty versus absent/invalid data, drift, refusal, redaction and cancellation | +| Desktop default final suite | 43 library, 278 binary and 22 documentation tests passed; one existing binary helper remains ignored | +| Desktop `encrypted-workspace` final suite | 150 parent library tests plus one isolated child, 370 binary and 22 documentation tests passed; one existing library and one binary helper remain ignored | +| Default/encrypted desktop builds and store/desktop all-target Clippy | Both builds and all four warnings-denied Clippy configurations passed; the existing Cargo manifest warning about the shared main-file targets remains | +| Store/desktop formatting | Both checks passed | +| Portable Rust 1.85 gate | `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` passed workspace formatting, tests and warnings-denied Clippy with its pinned toolchain | +| Existing renderer regressions | 50 tests passed across startup/lock/request/purge/disclosure suites; no renderer source changed | +| Documents and whitespace | `node scripts/validate-review.mjs` passed 542 authored text files, eight reference-image hashes and the historical brief hash; `git diff --check` passed | + +The first portable run hit the existing `rangoon-host` symlink fixture's sandbox denial (`Operation not permitted`); the permitted disposable-fixture rerun passed. The first desktop Clippy run found an unnecessary unit expression and a collapsible conditional in the new module; both were corrected and the final desktop test/build/Clippy matrix passed. Synthetic-peer desktop tests used permitted local loopback only. No native GUI or OS vault was operated for this packet. The fresh independent source reviewer returned PASS with no actionable P1/P2/P3. A separate read-only OpenAI `gpt_reader` (configured Luna medium) verified this receipt, command logs, acceptance and exact scope hashes: PASS, no factual discrepancy. Its initial evidence pass used the website checkout; that incomplete pass was superseded by readback from this exact app worktree. Neither reviewer ran validators or changed files. Exact commands and per-command exit receipts are `store-validation.json`, `desktop-validation.json`, `desktop-final-validation.json` and the named logs in `/rangoon-e1c5a-implementation-20261019/`. + +Security/standards impact: bounded local plaintext capture in host memory, with explicit identity checks and output redaction. No new dependency, build privilege, crypto primitive, archive/schema version, persistent record, approval/execution authority or certification claim. Archive buffers use existing zeroizing containers; decoded records and SQLite/process memory do not have a complete-zeroization guarantee. Classification/capture prove neither a Legacy writer fence nor resistance to a malicious same-user path swap and restore. Unix identity behavior is source-tested on this macOS host; Windows returns unsupported at this seam, and Windows/Linux native behavior is not qualified. The earlier E1c-4 executable receipt remains historical evidence for its own exact artifact, not a GUI qualification of this changed source. Ordinary startup remains Legacy plaintext. E1c-5b still needs source custody, destination equivalence and recoverable selection; E1c-5c owns ordinary routing/recovery and platform qualification. Normal data/keys, OS credential operation, migration/default switching, providers, LNSAT/VUSL changes, commit, push, merge, deployment and release were not performed. + +## D3a pinned-evidence correctness correction — October 19, 2026 + +Authority: the existing accepted [D3a offline decoder](lnsat-evidence-connector.md#d3a-exact-offline-source-packet--accepted-for-internal-offline-source), with an exact bug-fix objective and no new provider/profile scope. Root OpenAI Codex owns `crates/rangoon-integrations/{src,tests}/lnsat_evidence.rs`, `fixtures/lnsat-evidence/phase8-public-main-f669181a.json` and `docs/{development,continue}.md`. A fresh native OpenAI `gpt_reviewer` (configured Terra xhigh) found two P2 correctness defects while inspecting accepted code: contradictory authorization/operation-attempt adapter references were accepted, and valid pinned native states were mislabeled unsupported. A different fresh read-only OpenAI `gpt_reviewer` (configured Terra xhigh) found no actionable code, test or fixture defect in the final correction. At the time of this correction, E1c-5a remained proposed; its later source acceptance and implementation are recorded above. This D3a correction did not implement or accept it. GLM is skipped; no external private-source transfer is needed. + +Pinned source remains `f669181a1eaf574b1891a5c3fcc838870097e176`. Exact native lineage copies authorization adapter into the operation, then its dispatch context and persisted operation attempt. The decoder now requires exact adapter equality for either nested or standalone attempt when authorization is supplied; mismatch returns the existing fixed `lnsat_evidence_reference_mismatch` without partial projection or echoed adapter. There is no guessed normalization or cross-engine join. Authorization native states are `active`, `consumed`, `cancelled`, `expired`, `revoked`; operation states are `prepared`, `dispatching`, `outcome_unknown`, `completed`, `failed`. The previous `issued`/`created` native labels were unsupported by that pin. They remain observable as unsupported states rather than being rejected or rewritten; source-native text is preserved. The synthetic authorization template and its one expected native-state value now use `active`; its conceptual issued-without-operation scenario and all 24 existing cases remain. + +Three new tests cover eight matching/mismatched adapter arrangements across authorization+standalone, operation+standalone, nested-only and nested+standalone joins; every recognized authorization/operation state; and the two erroneous old labels remaining explicitly unsupported. Existing unknown-state, redaction, malformed/limit, selected-ID, scope and nested/separate-conflict cases remain. All successful state/join controls retain `rangoon_authority: none` and uninferred execution; recognizing a native state never grants permission. Before the implementation, all 11 existing tests passed and the three new regressions failed. An interim run then caught the old fixture expectation `issued`; it was corrected to the source-native `active`, not suppressed. + +Experience track: future consumers receive faithful native state labels and no contradictory adapter join. O2 native lock/purge and renderer late-result fencing were read during this audit; their source is unchanged and no new UI/native qualification is claimed. Technical/security track: pure bounded parsing only; fixed errors, original version/pin, privacy omissions and provider-free core behavior remain. No new schema, dependency, storage, credentials, authority or standards claim. + +Evidence and exact preimages: `/rangoon-d3a-recheck-20261019/`, including immutable source slices in `pinned-source-proof.json`. Final focused tests passed 14/14, including the unchanged 24-case fixture replay. `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` passed the pinned Rust/Cargo/Clippy 1.85.0 workspace formatting, tests and warnings-denied all-target Clippy gates; eight pre-existing ignored helper/QA results remain unqualified. `npm run build:check` passed syntax/vision/behavior checks and all 427 Node tests. Package all-target Clippy `-D warnings` and formatting passed with verified Homebrew 1.98.0; document validation passed 539 authored files/reference hashes and `git diff --check` passed. Initial broad runs failed on existing sandbox-only symlink-fixture and loopback-server EPERM; separately permitted retries passed without test/assertion changes for those environment failures. The intermediate decoder fixture assertion was updated from `issued` to native `active` before final successful runs. `validation.json` and final raw logs retain commands/results. Exact preservation proof found only the five owned files changed and 655 other captured files unchanged. Fresh independent source/test/fixture review passed. The reviewer required final receipt-bound diff/hash evidence; root finalized this receipt, regenerated the exact incremental diffs and scope hashes, and rechecked documentation/whitespace and all five current file digests. This evidence seal does not grant publication or broaden profile support. Normal data/keys, native UI, providers, LNSAT/VUSL edits, migration/default switch and publication remain untouched. No commit, push, merge, deployment or release. + +## LNSAT request-record compatibility audit — October 19, 2026 + +Authority: Jeff's request to cross-check actively developed local LNSAT source and finish separate-engine operator visibility. This is Rangoon documentation/research only while E1c-5a source acceptance is pending. Root OpenAI Codex owns cross-repository judgment and `docs/{lnsat-evidence-connector,continue,development}.md`; native OpenAI `gpt_reader` (configured Luna medium) supplied focused read-only source evidence. Fresh independent read-only OpenAI `gpt_reviewer` (configured Terra xhigh) review passed after the correction below. GLM was skipped; no private source was sent externally. + +Clean inspected LNSAT candidate: `/lnsat-request-bound-git-result-20261018`, branch `codex/request-bound-git-result-20261018`, commit `605742b39e09bde9c37c6d767e21917e705b3757`. This is not the clean canonical checkout's older `6741676` branch, a verified public-main pin, released artifact or observed runtime. Exact Git-object snapshots of six source/contract files and `comparison.json` are under `/rangoon-lnsat-request-audit-20261019/`. All ten named D3a serializer/read-wrapper/denial functions match the old `f669181a` pin byte for byte; the unchanged parser remains pinned there. No inference about all routing, authentication, store dependencies or live compatibility follows. + +The new [compatibility section](lnsat-evidence-connector.md#october-19-request-record-candidate-compatibility-check) records the different `lnsat.action_request_record.v1` GET surface, caller/read-side effects, redaction needs, bounded degraded behavior and separate evidence families. It improves the candidate evidence path for denied/approval-required, changed/repeated and uncertain requests without claiming those functions are supported by Rangoon. Root verified the HTTP serializer directly, corrected the distinction between requester reference exposure and omitted approver identity, and retained the gap between generic result digests and independent detailed Git-effect evidence. The new private request-bound Git-result seam is source/test-only; no public result submission or actual dispatch was inferred. + +Experience track: future operator view must separate loaded/degraded record status from action outcome and show missing actor/effect detail. No UI changed. Technical/security track: no source, wire/profile pin, dependency, schema, credentials, storage, external transfer or authority change. The exact next integration candidate and proposed fixture coverage are recorded without duplicating VUSL specifications or changing either engine. ISO/OpenSSF and released-runtime qualification remain separate evidence tracks. + +Validation: `/usr/local/bin/cargo test -p rangoon-integrations --test lnsat_evidence --locked --offline` passed all 11 existing tests, including the pinned 24-case synthetic fixture; this does not test the proposed new profile. `node scripts/validate-review.mjs` passed 539 authored files and reference hashes; `git diff --check` passed. Exact preimage proof found only the three owned docs changed and all 657 other captured authored files unchanged. Fresh independent review identified ambiguous overflow wording: the 65th row is an internal rejection trigger, not a serialized sentinel. The contract now states at most 64 serialized rows per family and whole-record degradation on projection overflow/lineage failure. Final independent re-review PASS, no remaining actionable P1/P2/P3. No LNSAT test, daemon, CLI, normal data/key, provider, source edit, commit, push, merge, deployment or release was performed. Existing Rangoon source and both repository branches were preserved. + +## E1c-5a source packet preparation — October 19, 2026 + +Authority: accepted encryption completion direction, with E1c-5 source/default switching and migration still unaccepted. The [exact source proposal](encrypted-workspace.md#e1c-5a-startup-inspection-and-existing-source-capture--proposed-source-packet) owns the next implementation contract. Root OpenAI Codex owns this documentation-only preparation; a native OpenAI `gpt_reader` (configured Luna medium) supplied focused read-only store evidence. Fresh independent design review passed after the correction below. GLM is skipped; no external private-source transfer is needed. + +Current source confirms ordinary `source_state` still selects Legacy; `export_workflow_backup` maps a missing connection to an empty archive; its complete-record transaction is reusable but supplies no file-identity custody or later-write fence. `Owner::acquire` may create a lock and is not a non-mutating classifier. `workspace_session::same_file` is a real device/inode comparison on Unix but returns true on non-Unix, so the new contract forbids treating it as cross-platform identity proof. The proposed classifier emits candidates only and delegates eventual Managed validation to existing Owner. The proposed existing-only capture keeps complete version-aware archive/record logic in the store and distinguishes missing/corrupt/replaced sources from valid empty SQLite. Recheck equality is explicitly not a writer lock or completed cutover. + +Experience track: future first-launch and conversion controls can distinguish data presence, conflict and recovery without silently showing a blank workspace. No UI or startup behavior changes here. Technical track: exact production/test ownership, finite failures, retained snapshot limits, OS identity limitations, required malformed/concurrent cases and named source validators are now reviewable before implementation. Security/standards impact is plaintext host-memory capture and local filesystem identity; no new dependency, protocol, authority grant or certification claim. Existing provider-free workflows and independent LNSAT/VUSL ownership are unchanged. + +Evidence/preimages: `/rangoon-e1c5a-packet-20261019/`. `node scripts/validate-review.mjs` passed 539 authored files and reference hashes; `git diff --check` passed. Preimage comparison found only the four owned docs changed, with 656 other authored files unchanged. The fresh OpenAI `gpt_reviewer` (configured Terra xhigh) found one P2: existing public `WorkspaceBackup` derived `Debug` could expose nested source content, contrary to the proposed capture privacy rule. The packet now explicitly requires a manual fixed-redaction implementation preserving the trait, a private retained wrapper and direct synthetic-marker/format regression tests. Final independent re-review PASS, no remaining actionable P1/P2/P3. This accepts the review evidence, not the proposed source scope. Source tests are named but unrun because no source changed. No source, normal data/key access, UI operation, provider, LNSAT/VUSL edit, migration, default switch, commit, push, merge, deployment or release occurred. Existing dirty source is preserved. + +## E1c-4 selected-artifact native completion checks — October 19, 2026 + +Authority: accepted E1c-4/E1c-4a disposable macOS cases and Jeff's explicit response that the test window is free. Root OpenAI Codex performed native UI actions and exact test-namespace cleanup. Source remains unchanged at the selected digest below; the ordinary desktop is still Legacy plaintext. This receipt supersedes the pending remaining-case statements in the older Q3 entry without rewriting its historical evidence. E1c-5 remains proposed design, not accepted startup cutover or migration. + +Evidence: `/rangoon-e1c4-final-20261019/manual-observations.md`, `check_receipts.py`, `receipt-check.json`; raw run `/private/var/folders/v2/k6_v09bj1bg4q9szfz8573800000gn/T/rangoon-e1c4-915651f01042f6b373e0c0ddc62164bb`. Source SHA-256 `f1ceed94f05263d5d0f34866e77186d5a84a3f4f4b085595669cbbd53f90cd6d`, executable SHA-256 `0d2b4ba3574e9f16f92b9c137edd6e9ebd89af122ee450eac178f47ad2a051f6`, x86_64 Mach-O on arm64 macOS 26.0. These exactly match prior Q1/Q7 run `b77099f00196e51a44815a42e2470f5b` and required-mode Q3 run `0d0fd3c9abd0d0419e495473cfd05a59`. No arm64-binary, Windows/Linux or installer qualification follows. + +| Case | Observed native evidence | Bound | +| --- | --- | --- | +| Q2 authoring | PID 21816 confirmed setup, selected synthetic Markdown through native picker, saved/reopened source, created two skills, revised/reviewed one, merged both pinned revisions, reviewed/compiled the result and saved/reopened a workflow draft; clean exit | Workflow deliberately has one input and four reported structural issues. Draft persistence is exercised; valid graph execution is not | +| Q4 restart | Distinct PID 24343 started locked, confirmed unlock and reopened the same source, skill history/reviews, composition lineage and workflow. Displayed workflow JSON matched; composed content, native 314-byte digest and candidate ID matched before/after restart; clean exit | Manual UI plus native digest parity, not an independent complete decrypted-database inventory oracle | +| Q5 key loss | Exact disposable slot deleted after clean export exit. PID 25652 confirmed unlock and displayed recovery-only UI; no client, requests unavailable, one vault read, zero writes; clean exit. Database hash unchanged | Native protection layout remained locked; no claim of a persistent recovery marker or captured key-failure IPC diagnostic | +| Q6 busy/interrupted | PID 24266 refused ownership with exit 4 and zero vault opens. Separate root PID 25822 was killed only at recorded successful real-key-write barrier. PID 26095 relaunched recovery-required with zero vault access and no create/unlock controls; clean exit | Interruption is provisioning, not arbitrary post-commit crash or disk-full coverage | +| Q8 output boundary | Managed backup returned `encrypted_recovery_unavailable` before native picker. Explicit instruction export used native plaintext Save dialog; 1,623-byte file hash matched native receipt | Plaintext instruction bundle remains an intentional external output, not encrypted recovery | + +Restart source digest: `d05c876aab361e81c48356b20d792b671c667313cc6a40b0485d010b31318130`. Composition: `composition:9fa12ef27df3fe8778121edaea692fd04c11f6e17450a1921a838933bc706726`. Compiled content digest: `0af437dff32fa8c18597d3713ada0bea14506556673437157b45af7ba472e346`; candidate `candidate:e3a6fbeb33ef48aae0d52c16bf1d993f711170540c35467f38f1cddabe5a0b32`. Authority remained none; compilation initially refused export until a separate local review and fresh compile. The original Review revision remained unreviewed and read-only; only current revision had its local review. + +Cleanup PID 26204 verified both registered test slots absent; all referenced children stopped. Independent raw-file checks found no plaintext SQLite header or known synthetic source markers in the 94,208-byte database. Before/after key-loss database digest is `734c728e2e220abd1fdc551f1cf149bf0669540cb7bd32db0b348db650767037`. Bounded post-exit residue checks covered five authoring files, three interrupted-setup files, two dedicated app-cache files and zero dedicated app-data files, with no marker matches or skipped files. Raw phase receipts also contain no checked source markers. No surviving WAL/journal/SHM was present in these roots. Original selected input and explicit exported bundle remain readable in the previous disposable evidence directory. This is not process-memory, OS swap/snapshot/crash-report, secure-erasure or universal leak proof. + +Failed evidence stays retained: sandbox run `f06f710ccfec0e3fd8a1f783f5f354bb` aborted before Ready and was cleaned; run `871ff97891183c85ea184e8f483237c4` exceeded the fixed 20-minute parent limit and was cleaned. Neither counts as Q2/Q4 success. The final fresh run completed without changing harness limits or source. Native AX and screenshots are in the tool transcript; this final run has no standalone screenshot files. Raw runner verdicts remain unassessed; the manual observation record and independent review determine the bounded qualification claim. + +Validation: `python3 /rangoon-e1c4-final-20261019/check_receipts.py` PASS: nine new phase receipts plus five prior same-artifact receipts, exact current source digest, stopped child PIDs, expected refusal/interrupt states, unchanged key-loss database and exact export hash. `node scripts/validate-review.mjs` passed 539 authored files and reference hashes; `git diff --check` passed. Preimage comparison confirms only the four owned documentation files changed during this continuation, with all 656 other captured files unchanged. Fresh independent read-only OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) review found no P1/P2; its sole P3 was the pending-review wording, now corrected. The reviewer checked all 12 raw evidence copies against their originals and confirmed the stated qualification limits. GLM was skipped; no external source transfer was needed. Existing source checks are unchanged, not rerun or promoted into additional native claims. + +Follow-ups: capability-aware Data controls should explain unavailable Managed backup before offering an export confirmation; encrypted portable recovery remains E1d. Ordinary startup and verified Legacy migration remain E1c-5 proposed work. Normal data/keys, LNSAT, VUSL specifications, providers, default routing, publication and release were untouched. No commit or push. + +## E1c-5 startup and Legacy adoption design — October 18, 2026 + +Authority: accepted encryption completion direction; this is design-only preparation while E1c-4 native UI qualification waits for exclusive access. The [proposed contract](encrypted-workspace.md#e1c-5-ordinary-startup-and-legacy-adoption--proposed) owns behavior and stages. Source/default-switch, actual migration, ordinary data/key operation and publication remain unaccepted here. Root OpenAI Codex owns the four documentation paths: this ledger, `docs/encrypted-workspace.md`, `docs/plan.md` and `docs/continue.md`. An independent native source reader supplies exact snapshot/restore evidence; a fresh read-only reviewer checks the proposal. GLM is skipped; no external private-source transfer is needed. + +Baseline: `codex/ops-local-window` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, preserving active native/encryption/O2 changes. Preimages and all tracked/untracked authored-file hashes are in `/rangoon-e1c5-design-20261018/preimage.json`. Current ordinary startup still chooses Legacy. This packet adds no source and cannot be cited as encrypted adoption, provider support or completion of the cross-runtime operator record. VUSL specification work stays upstream; LNSAT remains independent and unchanged. + +Experience track: one coherent first-launch, existing-data conversion and restart outcome with short normal controls and advanced recovery detail. Technical/security track: explicit complete snapshot and inventory, no silent empty replacement, separate destination, preserved domain identities, real process reopen, durable selection, old-writer limitations and retained plaintext disclosure. Existing SQLCipher/Owner/Gate/consent/recovery seams are reused. Encrypted portable archives retain their existing E1d identity. No new dependency, crypto algorithm, standards/certification claim or data transfer. + +Validation: `node scripts/validate-review.mjs` passed 539 authored files, eight reference-image hashes and the historical brief hash; `git diff --check` passed. Exact preimage verification showed only the four owned documents changed and all 656 other captured files unchanged. Fresh independent native OpenAI GPT-5.6 Terra xhigh review found one P2: the initial proposal incorrectly described every Legacy export as V3. The corrected contract distinguishes schema 1–3 V2 output from schema 4 V3, validates the appropriate inventory and retains V1/V2/V3 decode compatibility. Final re-review PASS, no remaining P1/P2/P3. No source, normal database/key operation, provider contact, LNSAT edit, VUSL implementation/specification change, commit, push, merge, deployment or release belongs to this design packet. Jeff subsequently freed the test window; separate accepted E1c-4 native qualification resumes with its own receipts. + + +## E1c-4 Q3 native header qualification — October 18, 2026 + +Authority: accepted [E1c-4 Q3](encrypted-workspace.md#q3-native-request-header-qualification-note). Root owns the existing five-file qualification scope. A native OpenAI `gpt_reader` traced the production header extraction; a fresh native `gpt_reviewer` (configured GPT-5.6 Terra xhigh) reviewed the source before operation. The test target adds only fixed `capture-client` and `check-headers` controls and bounded main-WebView evaluations of the unchanged `list_snapshots` IPC command. Missing and revoked identities require exact redacted refusal without vault access; a fresh identity requires a nonempty real list and a vault read. Neither identities nor source metadata are emitted. The explicit parent `--require-headers` mode rejects absent or incomplete probe evidence; ordinary Q2 authoring is not mislabeled Q3. + +Source checks passed: three Q3 Rust tests; 24 fixed-script classification/argument cases; one positive and 29 negative parent cases; 20 renderer regressions. Default and encrypted native suites/builds/warnings-denied Clippy pass with synthetic loopback access. The initial sandboxed default run could not bind loopback and failed 19 synthetic-peer cases; direct bind returned `PermissionError 1`, and the authorized rerun passed. Custom-target Clippy caught test-module placement; corrected target passes `-D clippy::all` with 331 unused-helper/import warnings, not warnings-denied. Ordinary encrypted executable contains none of the four checked qualification marker/control strings. Fresh independent OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) source review passed with no remaining P1/P2/P3 after requiring explicit parent mode and correcting stale continuation text. + +Actual native Q3 run `0d0fd3c9abd0d0419e495473cfd05a59` passed required-header mode and the in-flight/purge journey on the same executable. Source SHA-256 is `f1ceed94f05263d5d0f34866e77186d5a84a3f4f4b085595669cbbd53f90cd6d`; executable SHA-256 is `0d2b4ba3574e9f16f92b9c137edd6e9ebd89af122ee450eac178f47ad2a051f6`, x86_64 Mach-O on macOS 26.0. PID 91300 used the actual native setup confirmation and file picker, saved one synthetic Markdown source, captured the current client privately, and held a real saved-source read before OS-slot access. Confirmed Lock fenced admission and purged visible content before barrier release. The real read then completed; native state reached Locked without a client, and manual accessibility evidence showed no restored source. A fresh native-confirmed unlock generated a different client. Missing and revoked-header requests each returned the expected refusal with zero vault reads/writes; fresh-header control returned a nonempty list with one vault read and zero writes. Subsequent UI open restored the exact synthetic marker. Parent required-header evidence and phase exit passed with exit 0. Raw receipt retains its unassessed full-UI verdict; the separate manual evaluation defines the narrower observed journey. + +Exact cleanup PID 92066 exited 0 and verified the registered disposable Keychain slot absent. Both processes are stopped. Raw receipts, artifact identity, manual AX/screenshot evidence and `native-evaluation.json` are retained under `/rangoon-q3-headers-20261018/`. Fresh independent native OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) evidence review passed with no P1/P2/P3; it checked hashes, ordered header/barrier outcomes, manual purge limits, exact cleanup and same-artifact Q1/Q7 receipts. This closes the observed missing/stale-header gap for `list_snapshots` and repeats the in-flight subset; it is not exhaustive IPC coverage or the complete E1c-4 matrix on one executable. Earlier Q1/Q2/Q4–Q8 receipts remain bound to other executables. A final-artifact matrix is still required before normal-startup cutover. + +Final-artifact replay has started in separate run `b77099f00196e51a44815a42e2470f5b`; both source and executable hashes exactly match the Q3 artifact above. Q1 PID 92620 repeated native Setup Cancel twice, returned to usable setup each time, remained without a client and made zero vault accesses; exit 0. Q7 anchor/cleanup/window fault phases returned expected exit 4 before a usable window/client and with zero vault access. All four children stopped. `final-matrix-progress.json` and copied raw receipts record their PIDs and exact bounds. A later authoring attempt (PID 93212) confirmed setup and saved the synthetic source, but CUA timed out during draft creation, then observed unexpected Merge navigation and explicitly reported a user change. Jeff subsequently confirmed that he was using the test window. The run stopped cleanly with exit 0; it is not Q2 qualification. Busy-owner PID 93301 had already refused with exit 4 and zero vault opens. Cleanup PID 95887 deleted the exact disposable slot and verified absence; all processes are stopped. Q2/Q4/Q5, interrupted provisioning Q6, and Q8 remain pending. The cleaned run must not be reused for those cases; initialize a fresh isolated run and verify the same selected executable hash. This interruption is UI-evidence contamination, not a diagnosed storage or application failure. Final independent receipt review passed with no P1/P2/P3, including the interrupted authoring, second-owner refusal, exact cleanup, stopped-process and no-Q2 claims. + +Experience/security impact: qualification only. No product source, production permissions, storage format, cryptography, dependencies, provider or engine semantics changed. Test callbacks expose finite classifications, not identities/source metadata. GLM/private-source transfer was unnecessary and unused. Normal startup remains Legacy plaintext. No normal data/key change, LNSAT edit, commit, push, merge, deploy or release occurred. Existing unrelated native/O2 work is preserved. + +## E1c-4 Q3 in-flight read qualification — October 18, 2026 + +Authority: accepted E1c-4 Q3 and its [bounded implementation note](encrypted-workspace.md#q3-deterministic-in-flight-read-implementation-note). This continues the existing disposable native qualification, not a new production capability. Root owns the target, parent runner and three specification/status records. A native OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) independently reviewed the proposed seam; a separate native reviewer performs source and evidence review. GLM and external private-source transfer remain unused for protected native work. + +The one-shot test barrier now delays the next actual OS-slot revalidation before the read, only after an explicit authoring-phase control and open native state. The unchanged real UI/IPC request retains its Gate lease/backend custody. Release requires Closing with no client; a monotonic 120-second limit and invalid-order refusal prevent indefinite or reusable controls. The wrapper resumes the actual read and reports only source-free state, never keys or fabricated content. The parent rejects incomplete, failed, duplicate or misordered barrier events and requires post-completion Locked evidence. It still labels UI journeys unassessed: accessibility/screenshots are separate manual observations. Missing/stale-header injection and full Q3 qualification remain open. + +Owned paths are `apps/desktop/src/native_encrypted_qualification.rs`, `scripts/qualify-native-encrypted.py`, and `docs/{encrypted-workspace,development,continue}.md`. Preimages, incremental patch and validation evidence are retained under `/rangoon-q3-inflight-20261018/`. No renderer/store/default/provider/LNSAT path changed. The design review initially questioned the slot-read seam; tracing `Owner::checked` to `verified_workspace` confirmed that ordinary operations revalidate the real slot, and the reviewer retracted that finding. Its valid concern about an automated UI oracle was resolved by explicitly separating deterministic native barrier evidence from manual UI inspection. + +Named checks passed: two barrier unit tests for ordering, one-shot use, timeout and poison; one positive and 20 negative parent-evidence cases; 35 renderer lifecycle/request/disclosure regressions; default/encrypted desktop tests, builds and all-target warnings-denied Clippy; formatting and document/whitespace checks. The intentional synthetic mutex-poison panic is caught by its passing test. Custom-target Clippy passes `-D clippy::all` while emitting 330 unused-helper/import warnings from the shared no-libtest target; it is not warnings-denied. The ordinary encrypted executable contains no qualification or read-barrier symbols. Fresh independent native source review passed with no actionable P1/P2/P3 findings. Actual native in-flight subset passed. Fresh independent native OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) evidence review also passed with no P1/P2/P3 findings; it checked artifact hashes, event order, manual UI bounds, exact cleanup and both terminated processes. + +Actual disposable run `62f1fe9447bc72c34ca70ea1f5ecdc05` used source digest `44f3c56e238f90a67358074ae7b5b39f2d87c8c90c3c573cd2e18cbfc0e0ee57` and x86_64 executable `8dbb4628c0f97753756fdb7732eea327e42e9bf59909a95355168320e2995257` on macOS 26.0. PID 70056 saved the synthetic source, held its actual open request before OS-slot read, entered Closing with no client, then released the read (key present) and reached Locked. Manual accessibility/screenshot evidence shows content purged before release and absent after late completion; fresh native unlock allowed the saved source to reopen. Parent exit was 0 with no parent failure. Exact cleanup PID 72766 exited 0 and verified the isolated slot absent; both processes stopped. `native-evaluation.json` records the ordered events and manual evidence limits. This is Q3 in-flight/late-result subset evidence, not full Q2 or full Q3; missing/stale headers and the complete matrix on one selected executable remain open. Encrypted disposable artifacts remain local evidence; no ordinary data was removed. + +Experience/security impact: qualification only; no new user controls, privileges, cryptography, schema, dependencies, source transfer or authority. Ordinary startup remains Legacy plaintext. Complete final-artifact native coverage, normal encrypted startup, verified migration and encrypted recovery remain unfinished. Existing NX-06/O2/E1c-3/E1c-4a work is preserved. No commit, push, merge, deploy or release occurred. + +## E1c-4a native cancellation and storage disclosure — October 18, 2026 + +Authority: Jeff explicitly answered “Accept E1c-4a correction.” The [accepted bounded correction](encrypted-workspace.md#e1c-4a-native-cancellation-and-storage-disclosure-correction--proposed) owns scope; this receipt owns execution evidence. Source correction, named validation and independent source review passed. The fresh native results below close the correction-specific journey; complete E1c-4 qualification remains open. Root owns native consent, renderer integration and validation. Native OpenAI `gpt_worker` owns only the two renderer test paths; fresh native OpenAI `gpt_reviewer` performs read-only independent review. No GLM or other external private-source transfer is used. + +The native result now distinguishes an exact live Cancel button from affirmative consent and unavailable/unclassified callbacks. It drops retained Flight custody before reporting cancellation and requires the same C1 to be healthy, locked, without a retained control and not exiting. Failed cleanup, panic, stale controls and lost delivery cannot become a retryable cancellation. Renderer cancellation requires exact C1, fresh authoritative control/protection reads and a fresh purge; it grants no client, reload or ordinary operation. Source-save wording derives from validated controller storage state, preserving Legacy plaintext disclosure and readable-file/export boundaries. + +Owned runtime paths are `apps/desktop/src/workspace_setup.rs`, `preview/workspace-lock-model.mjs` and `preview/analyze.mjs`; focused tests are `apps/desktop/src/workspace_setup_tests.rs`, two mechanical typed-consent callsites in `apps/desktop/src/workspace_managed_bootstrap_tests.rs`, `tests/workspace-lock-model.test.mjs` and new `tests/workspace-save-disclosure.test.mjs`. Supporting records are `docs/{intent,encrypted-workspace,continue,development}.md`. Existing dirty NX-06/E1c-3/O2/E1c-4 work is preserved. Evidence and preimages are under `/rangoon-e1c4a-20261018/`. + +The fresh pre-correction authoring runner `e6aacbbf79d8bceb1828fc3411ecb92e` was stopped cleanly before setup when acceptance arrived: PID 10382, exit 0, absent layout, no client and zero vault opens/reads/writes. It is not authoring evidence. Earlier native receipts remain historical; the changed source requires a fresh artifact and actual cancellation rerun. Named source validation passed: formatting; locked/offline default desktop tests (43 library, 265 binary, 22 documentation), encrypted tests (150 parent library plus one isolated child, 357 binary, 22 documentation); both builds and both all-target warnings-denied Clippy configurations; 35 renderer request/lock/purge/disclosure tests; renderer syntax; document validation (539 authored files/eight image hashes); and whitespace checks. Parent suites retain the two existing ignored OS-custody/child helpers. Fresh independent OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) returned source PASS with no actionable P1/P2/P3. Independent native-evidence and receipt review also returned PASS with no actionable P1/P2/P3; the additional Q6/Q7 follow-up review returned PASS after correcting the binary-identity claim described below, with no remaining actionable P1/P2/P3. + +Fresh native run `94bdf81349853dc7bbe8521aa3c96d5f` used source digest `d32e410f48333ba3011a66fc51511b83132e4bfebf866054d147b66e62db45c5` and executable digest `abe867f7d8389de8023355b9e0b3cb2046091be07a6369cda73e1aa9f616aa89`. The executable remains x86_64 Mach-O on an arm64 macOS 26.0 host; no arm64-binary, Windows/Linux or installed-package qualification follows. `native-evaluation.json`, raw identity-bound phase receipts, accessibility captures, `compile-restart-parity.json` and `export-byte-verification.json` are retained under the evidence directory above. Raw phase receipts preserve their default unassessed UI verdict: the evaluation records the observed journey separately instead of equating exit 0 with functionality. + +| Case | Fresh actual-native evidence | +| --- | --- | +| Q1 cancellation | PID 44231: two native Setup cancellations restore healthy setup/retry; distinct epochs 1/2/3, no client/database and zero vault opens/reads/writes. Clean exit 0. | +| Q2 authoring | PID 45545: native setup, file selection, source save/open, reviewed skill revisions, companion skill, two-input composition commit, AGENTS.md compilation and workflow draft save/open all completed through the real UI/IPC. Clean exit 0; no parent deadline failure. | +| Q3 lock | Same authoring process: confirmed Lock purges the workbench; native Unlock Cancel returns to Locked without client/reload or additional vault access. **Partial:** in-flight work, stale/absent headers and late-result native assertions remain unrun. | +| Q4 restart | Distinct PID 50465 starts locked and requires native unlock. Observed source, reviewed content/history, composition and workflow recover. Compiled 100-byte content hash and candidate identity exactly match the pre-restart values. Clean exit 0. This is observed content/history recovery, not an exhaustive database identity comparison; workflow accessibility labels abbreviate revision IDs. | +| Q5 missing key | The exact disposable slot was removed; PID 55947 then refused native unlock with recovery UI, one read, zero replacement writes and no client. All five database-root file hashes remained unchanged. Clean exit 0. | +| Q6/Q7 | Fresh run `8d71c78876bb6f7f6b76c77208871e2a` repeats busy/interrupted provisioning and all three startup failures on the same source digest but a distinct rebuilt executable. All required refusal/recovery observations passed; exact details follow. | +| Q8 export | PID 52125: encrypted backup refused with `encrypted_recovery_unavailable` before the destination picker. Explicit native instruction export produced the exact expected 100-byte artifact inside its framed, readable bundle. Clean exit 0. | + +Additional Q6/Q7 evidence is bound by `failure-regression-evaluation.json` and its raw phase receipts. Its executable digest is `9aa02dcacda291d9dbe93ecac05434793de93bf2c9af005c4672de3499e492a0`, different from the earlier authoring executable despite the unchanged source digest. Independent review caught and corrected the initial same-binary statement. These runs must not be combined into a complete single-artifact qualification; the final matrix must bind every required case to one selected executable. A held empty Owner (PID 59859; not a Q2 authoring claim) caused the second process to refuse before Ready/vault access. Native setup PID 60049 confirmed the real OS sheet, wrote its exact disposable key, and reached the provisioning barrier before parent termination (`-9`). Distinct PID 60727 displayed recovery-required with no setup/unlock action, no client and zero vault opens/reads/writes, then exited cleanly. Anchor, cleanup and window fault cases each terminated with fixed failed-closed exit 4, no usable window/client and zero vault activity. This remains interrupted provisioning evidence, not post-authoring-commit or disk-full recovery. The final cleanup removed only the registered interrupted-provisioning slot and confirmed absence; all eight native children are stopped. Screenshot `q6-recovery.png` supplies actual UI evidence because this run's accessibility tree exposed only the native window shell. + +The exported bundle file hash is `9d20359ba539060c812e2f9a8f0eab9cdf1902df7a8a715461bd1fdfb6281839`; its content hash is `adab3faa6a76e58d1761900252faa0418f756b548d79799e4506ba9fdc02711f`. Independent framing/length/trailer verification passed. An initial diagnostic attempted JSON parsing of the whole framed file and failed; it was corrected against the existing bundle format, not counted as a product failure. This deliberately readable export is not an encrypted backup. + +Exact test-key cleanup and absence verification completed after missing-key testing; no native test process or test key remains live. The five inspected database-root files contain neither the known synthetic marker nor a plaintext SQLite header. This narrow check excludes OS caches, snapshots and swap, and proves no secure erasure. Qualification webview directories in `~/Library/Application Support/si.rangoon.encrypted-qualification` and `~/Library/Caches/si.rangoon.encrypted-qualification`, plus evidence and the explicit export, remain identified. Normal data and key namespaces were untouched. + +Follow-up UX gap: Data still presents backup/restore controls and explanations before the Managed backend refuses backup. A future bounded capability-aware UI correction should show the unavailable state before asking for a destination; it must preserve the native refusal and must not invent encrypted recovery support. This is outside E1c-4a's source-save disclosure correction. The next qualification work is the remaining Q3 native race/admission cases, followed by the complete required matrix on one final executable. A bounded read-only native GPT reader confirmed that the existing target accepts only `observe`/`quit`, with no deterministic in-flight barrier or stale-header/result oracle. The next harness design must preserve the actual renderer/IPC path, hold an ordinary request at an observable test-only boundary, initiate the real Lock flow, reject stale/absent identities before backend work, release the late completion, and prove the renderer remains purged until fresh native-confirmed unlock. Direct Owner calls or fabricated controller state cannot close Q3. New test controls must remain absent from the ordinary executable; no renderer or production-hook expansion has been implemented or implicitly accepted. Default switching, verified Legacy migration and encrypted recovery remain separate work. + +Experience and security impact: removes false recovery after user cancellation and a misleading plaintext disclosure in Managed mode without weakening consent, custody, cleanup or backend validation. No new dependency, schema, cryptography, privilege, authority grant or certification claim. Normal startup remains Legacy; no migration, normal data/key operation, provider/LNSAT edit, commit, push, deployment or release occurs in this correction. + +## E1c-4 native target and disposable evidence — October 18, 2026 + +**Historical artifact-bound checkpoint.** E1c-4a above supersedes cancellation, authoring, restart, key-loss and export status. References to “current” in this historical receipt refer only to its recorded source/binary digests. Retain its failures and Q6/Q7 evidence without applying them to newer artifacts. + +Authority: Jeff's accepted [E1c-4 source and eight disposable macOS cases](encrypted-workspace.md#e1c-4-integrated-native-encrypted-workspace-qualification--proposed). The packet is **in progress**, not full encrypted-desktop qualification. Root owns protected source, native UI interaction, integration and validation. Native OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) supplies independent read-only review; the native reader supplies exact UI/source mapping. No GLM/private-source transfer was used for this protected work. The existing NX-06/E1c-3/O2 changes remain intact and uncommitted on `codex/ops-local-window`, HEAD `c132ea6`. + +Implemented the explicitly selected `native-encrypted-qualification` target, isolated Tauri configuration, lazy native OS-vault adapter and bounded parent runner. They reuse the shared production Builder, renderer, IPC handlers and lifecycle; ordinary startup still selects Legacy. The test context embeds the workbench with the same CSP and 34 explicit local permissions, excluding provider/model/cloud credentials, restore and deletion. Roots are nonce-derived, private, identity-checked temporary directories. Credentials use only the fixed qualification service plus run nonce and native-generated workspace identity. Exact test-slot cleanup records selectors and confirms absence without printing secret bytes. The unchanged test executable receives a disposable `.app` wrapper for native accessibility addressing; this is not a signed installer or product distribution. + +The runner binds source/config/assets, binary bytes, architecture, OS and wrapper metadata; rejects replaced roots/artifacts, ambiguous phases and Python optimization; limits time/output; validates actual process exits; and never equates a successful phase exit with a passed UI journey. Independent review corrected excessive initial permissions, missing exit propagation and counter/terminal-observation gaps before qualification. A real busy-owner run then exposed Tauri's deferred setup error behavior: returning `Err` from setup aborted through the OS callback instead of reaching the outer build error branch. The target now emits refusal and exits 4 before Ready; production setup behavior is unchanged. Raw failed evidence remains retained. + +Evidence directory: `/rangoon-encrypted-target-20261018/`. Current source digest `05be17dd4e93368939761bc062ce425574f2a81e7fb87e4a9a45cac365db3572`; executable digest `59b789cb882b92888c8a2e10ba16f8b1e1b38a5e741e38a821f6ade8160d3855`. Artifact is x86_64 Mach-O on arm64 macOS 26.0. The final run is `ad4c39196579f6f49eea71dafea7ffc4`; `current-native-evaluation.json` points to its raw identity-bound receipts. This does not establish native arm64, Windows/Linux or packaged support. + +| Case | Actual evidence and remaining result | +| --- | --- | +| Q1 cold start/cancel | Actual native sheet Cancel in run `ad4dd90efd3358c28e6d423ca0929700`, PID 94210: Locked/absent, zero slot opens/reads/writes, no client/database; only the lock file exists. UI incorrectly shows recovery required and loses setup retry. **Failed usability; not qualified.** Screenshots and raw receipt retained. An earlier user-interacted run is excluded from cancellation evidence; Jeff confirmed he clicked its controls. | +| Q2 setup/authoring | PID 97948 confirmed real OS setup, selected synthetic Markdown through the native picker, saved/reopened source, created/revised/reviewed a skill, committed a two-input composition, compiled AGENTS.md, and saved/reopened a workflow draft through real IPC. Each resulting UI state is recorded. The 20-minute parent deadline expired before clean quit, so **partial route evidence only**, not a passed Q2 phase or restart baseline. All five disposable authoring files lacked the known synthetic marker and plaintext SQLite header; this narrow residue check excludes OS caches/snapshots/swap and is not an erasure proof. | +| Q3 lock/stale results | Lock confirmation was displayed but not completed before the parent deadline. In-flight, stale/absent-header and late-completion native assertions remain unrun; source tests cannot substitute. | +| Q4 relaunch/content parity | Unrun. The timed-out authoring receipt correctly prevents sequencing a purported clean-restart test. | +| Q5 missing key | Unrun as a native unlock-failure case. Exact cleanup of a disposable key is not Q5 evidence. | +| Q6 busy/interrupted setup | Passed the bounded accepted cases on the current artifact: second Owner PID 5172 refused with exit 4, no Ready and zero vault opens. Separate setup PID 5379 received real native consent, wrote one exact test key, reached the native provisioning barrier and was terminated by its parent. Distinct PID 5647 reopened that exact root, showed recovery required and stayed without client or vault access; exit 0. No automatic retry/setup/key regeneration occurred. This does not qualify interruption after authoring commits or disk-full recovery. | +| Q7 startup failure | Anchor, cleanup and window-failure cases passed on the current artifact: no window/client, zero slot opens/reads/writes, failed-closed exit 4. | +| Q8 export boundary | Unrun through native pickers. Existing source refusal tests remain separate evidence. | + +Cleanup completed for every slot created during these runs: the user-interacted historical slot, timed-out authoring slot and interrupted-provisioning slot each have exact selector/absence receipts. No ordinary key/data namespace was selected. Test webview storage is separately identified at `~/Library/Application Support/si.rangoon.encrypted-qualification` and `~/Library/Caches/si.rangoon.encrypted-qualification`; those OS-owned directories and local evidence remain. Do not claim all writes occurred under the database root or that temporary evidence was securely erased. + +Final named source checks passed: formatting; locked/offline default desktop tests (43 library, 264 binary, 22 documentation); encrypted tests (150 parent library plus one isolated child, 353 binary, 22 documentation); both builds; both ordinary all-target warnings-denied Clippy configurations; and the 29 renderer request/lock/purge tests. The OS credential QA and isolated-child helper remain ignored in their parent suites. The explicit custom target passes Clippy lints with `-D clippy::all`, but emits 329 unused-test-helper/import warnings because it shares `main.rs` with a custom `harness=false` entry; that target is not claimed warnings-denied. Seventeen parent exit-oracle checks and seven private-record/path predicates passed. Combined test-feature refusal exits 64 before Builder. The earlier NX-06 six-case/two-repeat regression passed against the changed shared startup; later corrections are confined to the separate encrypted target. Document validation passed 538 authored files/eight image hashes; `git diff --check` passed. Exact scope verification preserves 650 of 656 baseline files: only the six owned existing paths and three named new target/config/runner paths changed in this slice. Graphify is absent. Fresh independent native OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) reviewed final source, bound raw receipts, native recovery screenshot, validation/scope ledgers and this status record, returning PASS with no actionable P1/P2/P3. That review qualifies the recorded partial evidence, not the unfinished E1c-4 packet or proposed E1c-4a source. + +Historical finding: two product corrections were proposed in [E1c-4a](encrypted-workspace.md#e1c-4a-native-cancellation-and-storage-disclosure-correction--proposed): distinguish explicit native Cancel from recovery failure, and derive source-save encryption wording from validated storage state. The current encrypted native UI still says source storage is unencrypted. Neither finding is disguised by changing renderer behavior inside E1c-4's excluded source scope. Complete those corrections and the remaining native cases before normal-startup cutover; migration and encrypted recovery archives remain separately scoped. + +Experience and standards impact: this packet tests actual consent, scoped OS custody, retained-data boundaries and fail-closed recovery using synthetic content. It introduces no dependency, crypto/schema change, provider call or authority grant. It supports the existing evidence discipline, not ISO/OpenSSF certification or production-readiness claims. No normal workspace conversion, default change, LNSAT edit, real provider/credential use, commit, push, merge, deploy or release occurred in this native slice. The separate RUSL documentation publication remains on public main `d23b2b7` and must be preserved when reconciling this worktree later. + +## E1c-4 integrated native qualification execution — October 18, 2026 + +Historical shared-startup checkpoint. The native-target receipt above supersedes its then-unbuilt/unrun status; the source regressions below remain valid within their stated scope. + +Authority: Jeff explicitly answered “Accept E1c-4” to the independently reviewed [source and eight disposable macOS cases](encrypted-workspace.md#e1c-4-integrated-native-encrypted-workspace-qualification--proposed). This accepts isolated Keychain creation/read, process restart, intentional loss of exact run-created test keys and exact cleanup. Normal workspaces/keys, default switching, migration, providers, LNSAT and publication remain excluded. Root owns protected native integration and validation; a disjoint native worker may write only the new bootstrap tests. Fresh independent final source/native-evidence review is required. + +Start: `codex/ops-local-window`, HEAD `c132ea6`, with existing NX-06/E1c-3/O2 work preserved. Preimages for 654 authored files, starting diff and status are under `/rangoon-encrypted-native-20261018/`. RUSL documentation was separately published as `d23b2b7`; this dirty implementation worktree has not incorporated that documentation-only commit. Preserve both lanes when preparing a later publication. + +The shared startup portion is implemented and source-validated; the complete E1c-4 packet remains in progress. Native setup now registers state without a webview. Ready installs the existing externally retained lifecycle anchor, then shared preparation requires a real initial Closing cycle before presenting a Managed workbench. Missing anchor, invalid/failed cleanup and failed window creation latch failure and keep admission closed; later successful cleanup cannot become a clean startup result. Legacy still uses its original factory and preserves ordinary admission on successful startup. No renderer acknowledgment, unlocked client or consent is fabricated. + +Root owns `apps/desktop/src/{main,workspace_close,workspace_native_bootstrap}.rs` and these status records. Native OpenAI `gpt_worker` (configured GPT-5.6 Terra high) owns only new `apps/desktop/src/workspace_native_bootstrap_tests.rs`. Its six focused encrypted tests include two Legacy regressions and use the real locked constructor with a counting in-memory vault. They cover initial ordering, exact purge acknowledgment, zero pre-consent vault access/client issuance, anchor refusal, cleanup false/panic, window failure, later cleanup, duplicate startup and exit-latched refusal. These are source fixtures, not actual renderer or OS-vault evidence. The initial Clippy run caught enum variant naming; root renamed the private variants, then reran the complete matrix. + +Named validation on the final source: Rust 1.98 formatting passed; locked/offline default desktop tests passed 43 library, 264 binary and 22 documentation tests; encrypted tests passed 150 parent library, one isolated child, 353 binary and 22 documentation tests. The existing OS credential QA and child helper remain explicitly ignored in their parent suites. Default/encrypted builds and both all-target warnings-denied Clippy checks passed. Final renderer checks (`node --test tests/workspace-requests.test.mjs tests/workspace-lock-model.test.mjs tests/workspace-lock-view.test.mjs tests/startup-lock-purge.test.mjs`) passed 29 tests. Earlier renderer output predated the final private-enum/test refinement; independent review requested a fresh receipt and this final run supersedes it. The accepted NX-06 native runner passed all six cases plus two repeats and invalid-argument refusal against the changed source. Its artifact is x86_64 Mach-O on arm64 macOS 26.0, not native arm64 or Windows/Linux evidence. Full before/after snapshots bind all 656 authored files, including the new untracked modules, to that unchanged native run. Logs, commands, incremental source patch and hashes are under `/rangoon-encrypted-native-20261018/`. + +Fresh native OpenAI `gpt_reviewer` (configured GPT-5.6 Terra xhigh) reviewed the exact incremental source, tests, raw evidence and this receipt and returned PASS with no actionable P1/P2/P3. Its stale-renderer-evidence finding was resolved by the final 29-test rerun; the reviewed partial startup slice does not complete E1c-4. GLM and external private-source transfer are skipped for protected startup work. The existing Cargo warning about sharing `main.rs` across explicit product/test targets remains; no Rust or Clippy warning remains in the named checks. Document validation and whitespace/scope checks are recorded with the final review. The 648 baseline authored files outside this partial slice remain unchanged, preserving NX-06/E1c-3/O2 work. Graphify is absent. + +Experience and standards impact: window creation moves after lifecycle ownership without changing artwork, renderer controls, product capabilities or defaults. No new dependency, schema, key format, data output, network grant or execution authority is introduced. Named tests and review support the existing source-validation requirements; they do not establish ISO/OpenSSF certification, encrypted desktop adoption or released OS support. + +No E1c-4 native case or real vault mutation has run yet. The isolated encrypted target, private OS-vault adapter, bounded parent runner and eight actual renderer/IPC/consent/Keychain/relaunch cases remain to be built and qualified within this already accepted packet. The NX-06 regression has no workbench webview or real OS vault and cannot substitute for those cases. Ordinary application startup continues to select Legacy plaintext. Normal data/keys, migration, providers, LNSAT, publication, deployment and release remain untouched; this partial source work is uncommitted. RUSL's separate `d23b2b7` documentation publication has now passed all seven hosted CI jobs and remains distinct from this unfinished encryption work. + + +## Encrypted native adoption packet — October 18, 2026 + +Authority: accepted encryption completion program and latest plaintext-resolution request; the concrete [E1c-4 native source/run packet](encrypted-workspace.md#e1c-4-integrated-native-encrypted-workspace-qualification--proposed) remains proposed. Root reconciled the source-qualified E1c-3 seam with actual native Builder/Ready ordering, renderer Closing/Locked initialization, existing C0/C1 native consent, OS-slot primitives and Managed backup refusal. Current branch is `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Baseline hashes for 654 tracked/untracked authored paths and the carried-forward diff are retained at `/rangoon-encrypted-native-plan-20261018/`. + +The concrete gap is ownership ordering: current main creates its webview in setup before Ready installs the native lifecycle anchor. The next packet moves shared main-window creation after anchor installation and the real first Managed close cycle. `WorkspaceClose::begin` creates that cycle; no alternate initial-Locked protocol or fabricated cleanup proof is needed. Existing source tests cannot prove native renderer purge, OS consent, real key custody or process relaunch. The proposal includes the real Keychain namespace, exact disposable-slot cleanup and missing-key cases; pinned keyring-core 1.0.0 already exposes exact-entry deletion, but Rangoon's product OsSlot intentionally has no general delete API. Qualification-only cleanup must remain isolated. No source or native capability changed in this planning step. + +Root owns only `docs/{intent,encrypted-workspace,continue,development}.md`. Experience: specifies a working native setup/lock/unlock flow using the existing UI, without another mockup or new controls. Security/standards: preserves explicit consent, exact identities, provider independence, no plaintext fallback, bounded test privileges and honest recovery/export disclosures. No compliance/certification claim. A native OpenAI explorer supplied a bounded read-only source assessment. Fresh independent OpenAI `gpt_reviewer` (configured GPT-5.6-Terra xhigh) found one P2: the original Q6 post-mutation interruption oracle depended on an inaccessible library-test fault hook outside owned scope. Root re-scoped Q6 to a real disposable provisioning key write held at the existing public Store boundary, followed by parent-observed process termination and a new-process recovery-required check before vault access. This does not claim native post-authoring-commit or disk-full evidence. Final re-review returned PASS with no actionable P1/P2/P3. `node scripts/validate-review.mjs` passed eight image hashes, historical brief/local targets and 534 authored text files; `git diff --check` passed; all 650 baseline identities outside the four owned documents are preserved. Source/native suites were not rerun for this documentation-only packet. Owner acceptance of E1c-4 source and disposable native/Keychain cases is still pending. No GLM/private-source transfer, app/vault/database operation, LNSAT change, commit, push, merge, deploy or release occurred. Prior NX-06, O2 and E1c-3 source/dirt remain preserved. + + +## Encrypted startup source integration — October 18, 2026 + +Authority: Jeff's [plaintext-resolution continuation](intent.md#encrypted-startup-source-continuation--october-18-2026), implementing the independently reviewed E1c-3 packet. Root owns protected source, scope, integration and validation; native OpenAI `gpt_worker` (configured GPT-5.6-Terra high) owns only `apps/desktop/src/workspace_managed_bootstrap_tests.rs`. Native OpenAI `gpt_reviewer` (configured GPT-5.6-Terra xhigh) supplies independent pre-code and final source/evidence review. Source implementation, named validation and fresh independent source/evidence/receipt review passed with no remaining P1/P2/P3. + +The existing Managed backend, its error mapping and retained composition handles now compile under the optional encryption feature without test cfg. A separate parent-private `managed_locked` constructor acquires one Owner, retains the normal Refused caller and empty request registry, and performs no key lookup, database open or fallback. The original HostFixture constructor remains test-only. New fixtures use the production-shaped constructor, real SQLCipher storage and header-bound requests with synthetic cleanup/consent and an in-memory counting vault. They compose the existing initial close and C0/C1 protocol instead of assigning cleanup state or minting a test client. + +Exact source ownership is `apps/desktop/src/{workspace_source_access,composition,workspace_source_access_tests,workspace_managed_bootstrap_tests}.rs`; supporting docs are `docs/{intent,encrypted-workspace,continue,development}.md`. Evidence is retained at `/rangoon-encrypted-bootstrap-20261018/`. The initial cold-admission expected diagnostic and a missing test serialization unwrap were fixture errors caught before a passing targeted run. Missing-key/layout, absent-header and single-coordinator proof were required during review; no production authority bypass was found in this review. + +Validation: Rust/Cargo 1.98.0 locked/offline default desktop suite passed 43 library, 262 binary and 22 privacy doc tests (one ignored); encrypted suite passed 150 library, one isolated child-process library case, 347 binary and 22 privacy doc tests (two ignored across parent suites). Five new bootstrap tests pass, including a missing-key read with zero replacement writes, actual absent/locked/recovery observations, one reused close coordinator, fresh identity after reacquisition and rejection of old/absent headers. Default/encrypted builds, all-target warnings-denied Clippy, manifest formatting, document checks (534 authored text files) and diff whitespace pass. The original focused compile failure is retained in `bootstrap-tests.log`; `bootstrap-reuse-tests.log` records the corrected five-test run, with the later stale-header assertion included in the full encrypted suite. The source-only fixture initially used a direct close ticket after open; root replaced it with the original WorkspaceClose C0 path and verified actual Owner closure, avoiding a weaker substitute for lifecycle coverage. + +The accepted NX-06 matrix was rebuilt and rerun against these source hashes: all six cases plus two repeats passed, with expected process codes 0/4/37 and invalid-argument exit 64. The actual executable remains x86_64 Mach-O on an arm64 macOS host. Records under `native-final/` bind the run to its input source; this is native lifecycle regression evidence using the existing memory-only harness, not actual native encrypted Owner/vault qualification. Final independent OpenAI Terra-xhigh source review found no remaining P1/P2/P3. No GLM/Spark or external private-source transfer was used; native GPT lanes were adequate. + +Experience and security boundary: ordinary desktop startup remains Legacy plaintext; this is an unmounted integration seam, not encrypted desktop activation. No UI, normal database, OS-vault, provider, credential, LNSAT, schema, dependency or default changes. Reacquiring a disposable Owner in one process does not prove process restart, OS key custody, native consent, renderer purge or Windows/Linux behavior. Existing plaintext exports/archives retain their disclosures; encrypted recovery remains unavailable rather than falling back. No compliance level, commit, push, merge, deployment or release follows from this work. Prior NX-06 and O2 work stays preserved. + + +## Encrypted startup integration audit — October 18, 2026 + +**Historical pre-code audit:** the source continuation above supersedes this audit's pending implementation/acceptance state. + +Authority: accepted encryption completion program, with the next [E1c-3 source packet proposed](encrypted-workspace.md#e1c-3-encrypted-startup-integration-proposal--october-18-2026). NX-06 is complete within its accepted scope; this audit does not expand its six-case authorization. Current branch is `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Startup hashes and carried-forward diff are retained at `/rangoon-encrypted-bootstrap-20261018/`. + +Root inspected the actual production Builder, SourceAccess/backend cfgs, Owner acquisition, native close/registry state and renderer initialization. A native OpenAI `gpt_reader` independently traced the minimum cfg dependencies and startup behavior without edits. Normal startup remains Legacy at `main.rs::source_state`; the Managed Backend and composition handle require test cfg. The current managed fixture constructor forces `HostFixture`. A newly locked Owner cannot simply be mounted: no-attempt close state says Open while the request Registry is unavailable, so renderer bootstrap fails closed. Existing source qualification remains useful, but does not close this integration seam. No new runtime test was executed by this audit. + +The proposed packet retains one Owner/Gate and normal request identities, composes a real initial close cycle rather than inventing a Locked state, and leaves ordinary startup unchanged until a disposable native application qualification. It names four exact source paths, existing typed controls, finite refusal behavior, real SQLCipher/fake-vault tests and the subsequent OS-custody/migration gates. This advances the local storage prerequisite for independent engine integration; it does not substitute storage tests for action authorization or cross-engine provenance evidence. + +Experience impact: no UI change; the planned initial Closing/Locked sequence reuses current protection controls. Security/standards impact: no new privilege or data handling now; the proposal preserves exact native consent, key isolation, no plaintext fallback and separate OS/distribution qualification. No ISO/OpenSSF maturity or compliance claim. Root owns this docs-only reconciliation. Fresh independent review and document/preservation checks are pending. No source edit, native run, vault/provider operation, LNSAT edit, commit, push, merge, deployment or release is authorized or performed by this audit. Existing NX-06/O2 dirt remains untouched. + + +## NX-06 disposable macOS native lifecycle qualification — October 18, 2026 + +Authority: [accepted NX-06 intent](intent.md#nx-06-disposable-native-event-qualification-proposal--october-18-2026) and [exact packet](openshell-observation-connector.md#nx-06-disposable-native-event-qualification--proposed-exact-packet). Jeff explicitly accepted the test-only source and six disposable macOS cases. Implementation, named native matrix and final independent receipt review passed. The complete cross-runtime operator-record goal remains incomplete. + +**Delivered.** Production and qualification now share one Ready/ExitRequested/Exit coordinator. An explicit, non-default Cargo test executable uses the real Wry/Cocoa event loop, a dedicated empty context, no webviews/plugins/invoke handlers, memory-only unavailable source fixtures and synthetic loopback peers. The parent verifies ordered bounded JSON evidence and actual process status; it cannot select a normal product executable. Invalid/missing/extra arguments exit `64` before context/app/listener construction. Python optimized mode is refused. Source hashes, dirty status, diff hashes, toolchain, executable format/hash and pre/post source-stability checks bind each qualifying matrix to its inputs. + +| Case | Observed native result | +| --- | --- | +| `idle-clean` | Ordinary `37` prevented; actual native cleanup; reissued/observed `0` | +| `active-cancel` | Real watch starts; admission fenced; client returns `Cancelled`; callback remains held through main-thread roundtrip; release, drain and cleanup; `0` | +| `duplicate-timeout-retry` | Four ordinary exits while callback held; one waiter; all 200 probes expire without cleanup; native roundtrip still held; explicit release/retry; `0` | +| `cleanup-failed` | Test-only NativeCloud mutex poison reaches unchanged native cleanup/terminal logic; observed `4` | +| `anchor-unavailable` | Non-encrypted unavailable source; no anchor; production Start unavailable; ordinary `37` passes through without cleanup claim | +| `anchor-install-failed` | Occupied notifier makes actual install fail closed; production Start unavailable; no anchor; ordinary `37` passes through | + +All six cases and repeats of `active-cancel` and `duplicate-timeout-retry` passed in final source-bound run `native-final-2`. Qualifying runner always requires all eight; no subset-success option remains. No-start cases assert zero accepts on an inert socket sentinel and invoke only the source-reviewed unavailable production path. This is not machine-wide network monitoring. Active cases independently check the actual TLS peer's three-RPC ledger. No client instrumentation or provider-client change was made. + +**Environment and evidence.** macOS 26.0 on an arm64 host; the tested executable is **x86_64 Mach-O**, built with Homebrew Rust 1.98.0 (`x86_64-apple-darwin`). This does not qualify an arm64 executable, Windows or Linux. Evidence directory: `/rangoon-nx06-run-20261018/`; `native-final-2/{source-before-build,metadata,results}.json` and per-case raw records own the final runtime result. `compiler-cfg-proof.json` and `verbose-build.stderr` prove the exact clean compiler invocation has `--cfg test` for the custom target and not the normal binary. `normal-isolation-proof.json` binds the normal executable hash and absent test/peer symbols; ordinary test-selection JSON excludes the custom target even with its feature enabled. + +**Validation.** Locked/offline default desktop: 43 library + 262 binary + 22 doc tests passed, one ignored. Encrypted feature: 150 parent library + one subprocess library + 342 binary + 22 doc tests passed, two ignored across parent suites. All 32 existing synthetic OpenShell client tests passed. Default and encrypted all-target Clippy with `-D warnings`, formatting, default/encrypted normal builds and normal build with the qualification feature passed. Normal dependency tree excludes `rcgen`; normal artifact symbols exclude qualification, poison and synthetic-peer entry points. Three invalid argument shapes return `64` without app evidence. Nine context checks reject altered identifier/windows/global injection/capabilities/bundling/nonempty assets; eight corrupted parent-evidence cases are rejected. Documentation/image/link and diff checks passed before receipt finalization and are rerun afterward. No Graphify index exists. + +**Failed attempts and corrections.** Initial sandboxed desktop tests failed 19 loopback cases with `Unreachable`; explicitly approved unrestricted local-fixture runs passed. Initial custom compilation attempted a private client-test socket accessor; replaced without changing that crate. First native attempt refused inherited product config *before Builder*: pinned Tauri codegen resolves by directory, not the alternate filename. The corrected config lives in `apps/desktop/native-exit-qualification/tauri.conf.json`; its existing icon reference is explicit because codegen otherwise looked for a nonexistent local icon. Empty capability selectors omitted by Tauri serialization are checked as empty defaults. Failed builds/runs remain retained; no failed case was counted as passing. Custom no-libtest compilation emits 81 unused-import and 577 dead-code warnings from product/test helpers it does not invoke, plus Cargo's duplicate-source-target warning. These were captured, not blanket-suppressed; normal warnings-denied Clippy still passes. + +**Review and ownership.** Root produced/integrated the lifecycle and harness changes. Fresh read-only OpenAI `gpt_reviewer` (GPT-5.6-Terra, xhigh) reviewed source and raw native evidence; initial findings about subset success, connection assertions, dirty-source binding and optimized Python were resolved. Source/evidence review returned no actionable P1/P2/P3. Final metadata/receipt follow-up also returned PASS with no actionable P1/P2/P3 after historical status entries were explicitly marked superseded. GLM/Spark skipped; no private-source external transfer. Owned source paths: `apps/desktop/Cargo.toml`, `apps/desktop/src/{main,cloud_models,openshell_host,native_exit_qualification}.rs`, `apps/desktop/native-exit-qualification/tauri.conf.json`, `scripts/qualify-native-exit.py`; supporting paths: `docs/{intent,continue,development,openshell-observation-connector}.md`. The host's added declaration is test-gated and preserves private synthetic APIs. Pre-existing O2 tests/fixtures and prior receipts are preserved. + +**Experience, security and remaining work.** No renderer/UI behavior or artwork changed. This is actual native event-loop evidence, not encrypted Owner/key release, renderer purge/window destruction, credential-sheet, provider authenticity, action authorization, observed-effect or installed-package evidence. Test context grants no effective permissions and starts no normal workspace/keychain/provider path. No dependency, lockfile, schema, policy, LNSAT or CI change. No ISO/OpenSSF certification/readiness level follows from these tests. D2b production credential/UI/save and encrypted factory adoption, actual provider qualification and O3 provenance/ingestion remain separate gates. No commit, push, merge, deploy or release occurred; the required substantive README update belongs to any later publication packet. + + +## O2 decision-state cross-language parity — October 18, 2026 + +Authority: accepted [operations intent](intent.md#operations-control-plane-continuation--october-7-2026) and unchanged [O2 local-window contract](operations-local-window.md). This bounded test-only continuation validates the existing Rust-to-renderer boundary while the separate NX-06 native-harness acceptance is pending. It does not accept that harness or add a provider adapter. Starting application HEAD is `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, branch `codex/ops-local-window`; four carried-forward NX-06 proposal documents are preserved. Baseline hashes and their preexisting diff are retained under `/rangoon-operator-parity-20261018/`. + +The existing Rust parity golden contains only actor/evidence records. Rust unit tests cover the decision states separately, and renderer unit tests use manually authored views. The new regression joins those existing contracts using one fixed synthetic O1 input and its actual Rust-generated safe-view golden. It covers three evaluation values, three approval decisions, five authorization states and eight attempt states, including unknown outcomes and reported reconciliation. The assertions must independently check exact group denominators, fixed truth labels, source omission and retained missing/conflict diagnostics; producing a golden from current code alone is not sufficient evidence. No fixture represents authenticated provider evidence, a valid approval chain, verified effect or a cross-engine join. + +Exact ownership: a native OpenAI `gpt_worker` (configured GPT-5.6-Terra high) owns `fixtures/operations/synthetic-decision-window-v1.json`, `crates/rangoon-ops/tests/operator_view_parity.rs` and `tests/operations-parity.test.mjs`; root owns `fixtures/operations/synthetic-decision-view-v1.json` and `docs/{continue,development}.md`, integration, validation and final judgment. A native OpenAI `gpt_reader` (configured GPT-5.6-Luna medium) supplied read-only API/test inventory. No production Rust/renderer/native source, schema, dependency, storage or authority semantics are changed. The source-specific decision/effect and O3 provenance gaps in [the operator-record checkpoint](operations-control-plane.md#operator-record-evidence-checkpoint--october-18-2026) remain open. + +Validation before edits: `cargo test -p rangoon-ops --locked --offline` passed 145 unit tests and one existing parity test. A temporary stdin/stdout projector compiled against the existing crate outside Git; it performs only pure offline decode/inspection/projection. Root generated the new canonical view through the existing public Rust pipeline and independently checked the 24-event count, the 3/3/5/8 group denominators, all nineteen reported-value buckets, six fixed truth labels, missing relationships and omitted synthetic private marker. The source deliberately contains incomplete and conflicting references; its diagnostic totals are structural 79, relationships 29, delegations 4, approvals 18 and lifecycle 32. The original two-record parity tests remain present alongside the new coverage; no prior fixture or test was removed. The populated renderer regression also rejects a same-total mutation that relabels an unknown attempt as completed. + +Final targeted checks passed: locked/offline `rangoon-ops` tests on Rust 1.85.0 (145 unit plus two parity tests); `cargo clippy -p rangoon-ops --all-targets --locked --offline -- -D warnings` and `cargo fmt -p rangoon-ops --check` using the available 1.98 toolchain; all three operations Node test files (25 tests); `node scripts/validate-review.mjs` (eight image hashes, historical brief/local links, 531 authored text files); and `git diff --check`. The golden generated with the existing Rust 1.98 artifact also matches under the 1.85 test run. Logs and exact commands are retained in the packet evidence directory. Fresh independent read-only OpenAI `gpt_reviewer` (configured GPT-5.6-Terra xhigh) found that a generic diagnostic assertion did not independently guarantee conflict retention. Root added exact Rust/Node assertions for `structuralState = conflict`, `event_identity_conflict`, and the rendered conflict warning; the focused Rust parity tests, all-target Clippy, formatting and all 25 operations Node tests passed again. Final re-review returned PASS with no actionable P1/P2/P3. Scope preservation passed: all 644 tracked files outside this six-path packet retain startup hashes, including the carried-forward NX-06 intent/spec changes; only the two named synthetic fixtures are new files. Root accepts this test-only regression evidence under the existing O2 contract. It does not accept or complete NX-06, O3, connected support or verified action/effect coverage. Experience impact is regression coverage of existing reported-state presentation, not new layout or rendered/native qualification. Security/standards impact is synthetic evidence and exact trust-label/privacy regression coverage; no new processing privilege or compliance claim. No GLM/Spark/private-source transfer, real provider/credential, LNSAT edit, native app/harness run, commit, push, merge, deployment or release is included. + +## NX-06 exact native qualification packet — October 18, 2026 + +**Historical proposal checkpoint, superseded:** the later [accepted implementation and native qualification receipt](#nx-06-disposable-macos-native-lifecycle-qualification--october-18-2026) owns current NX-06 status. Pending-acceptance and not-implemented statements in this section describe its earlier proposal state only. + +Authority: continued independent-engine support under the accepted application intent; the actual native harness remains explicitly excluded from earlier source/publication acceptance. This is a four-document proposal, not implementation or a completed qualification. Start: clean application branch `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, verified merged main `cb0e87849bef09e123567ac13debbb916df46ab4`. The previous goal turn made authoritative progress through PR #50; the end-to-end support objective remains incomplete. + +Root traced actual Ready/ExitRequested/Exit handling, native anchor installation, managed-state requirements and the memory-only close fixture. A bounded native OpenAI `gpt_reader` (configured GPT-5.6-Luna medium) confirmed the exact seam inventory. The proposal reuses one shared event path and real native cleanup, keeps Cocoa on the process main thread, includes an exact argument guard before app construction, and uses a parent process to verify exit codes and ordered evidence. It distinguishes an unavailable anchor, failed notifier installation and unhealthy native cleanup rather than conflating them. A no-webview test app cannot qualify review-window/renderer purge or real encrypted Owner/key custody. Clean locked/offline verbose Cargo probes now verify the custom target receives explicit `--cfg test` without libtest, while ordinary test selection omits it even with the qualification feature. The logs and assertions are retained in `cargo-probe-{explicit,ordinary}.log` and `cargo-probe-results.json` under the packet evidence directory. This is compiler/selection evidence, not a functioning Rangoon event harness. + +Independent design review initially questioned whether `harness = false` removes `cfg(test)`; actual compiler evidence disproved that finding and the reviewer withdrew it. A separate actionable finding required explicit alternate Tauri context selection and validation. Root also checked pinned Tauri's capability resolution: an empty capability list inherits discovered capabilities. The revised proposal requires an explicit permission-free inline selector, alternate config, empty assets, macro test mode and pre-Builder/parent context checks. The reviewer also caught a proposed use of `EmbeddedAssets::default()` that the pinned runtime type does not implement. The corrected exact constructor uses empty PHF maps and an empty CSP hash slice; a standalone metadata-only Rust probe against the cached pinned Tauri artifact passes (`empty-assets-probe-result.json`), without linking or running an app. This checks the constructor type only, not full generated-context or native-event behavior. Review also corrected the unavailable-anchor fixture: that case uses existing `source_state` with an unavailable error and no path; the encrypted lifecycle fixture remains limited to anchor-eligible cases. Neither fixture opens storage or owns key material. No Tauri dependency, feature activation or production configuration is changed by this documentation revision. + +Experience track: no UI change or connected badge; future native behavior must preserve unavailable states. Technical/security track: no source, dependencies, workflow privileges, storage, credentials, provider traffic, engine semantics or LNSAT change. The proposed test source permits only memory lifecycle state, dummy loopback peer data and bounded source-free evidence; it preserves independent engine boundaries. ISO/OpenSSF impact is qualified test isolation and traceable evidence, not organizational or platform certification. Root owns design and final judgment; no GLM/Spark or external source transfer is used. + +Exact changed paths: `docs/{openshell-observation-connector,intent,continue,development}.md`. Baseline tracked-file hashes are retained under `/rangoon-nx06-packet-20261018/`. Named validation passed: `node scripts/validate-review.mjs` (eight image hashes, historical brief hash, local Markdown targets and 531 authored text files), `git diff --check`, both proposal fragment targets, clean Cargo target-selection/cfg probes and the empty-assets metadata probe. All 644 tracked files outside the four-document scope retain their baseline hashes. Fresh independent read-only OpenAI `gpt_reviewer` (configured GPT-5.6-Terra xhigh) re-reviewed corrected scope, pinned source and probe evidence and returned PASS with no actionable P1/P2/P3. Review acceptance is limited to the proposal; owner acceptance for harness source and native runs is still pending. Root retains final integration/qualification judgment. No full source suite was rerun for this docs-only packet. No source edit, app launch, real credential/provider, native harness, commit, push, merge, deployment or release is part of this proposal turn. +### Reference publication checkpoint — October 19, 2026 + Authority: Jeff's [accepted retirement and public-update direction](intent.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026). RUSL is retired as an active technical contract; its source/history is retained while VUSL develops independently. No backward-compatibility program, new reader, converter, alias or dual-profile implementation is added. Old code must not be removed until a usable pinned VUSL core is adopted and affected Rangoon tests are updated and independently reviewed. The existing upstream manifest records historical spec/fixture provenance, not an adopted runtime core. Exact old identifiers, digest domains, fixture paths, accepted-case IDs and dated evidence remain unchanged. This documentation publication starts at the existing VUSL-reference PR head `5cae42176e5682cfa94a540c74c25e1335814db9` in a separate checkout, `codex/rusl-retirement-publication-20261019`. It includes that PR's bounded reference extraction and this retirement clarification. The dirty application checkout and older reference checkout are preserved, including unfinished native encryption work; none of those uncommitted changes is copied here. Root owns integration/README/publication; OpenAI `gpt_docs` (configured Luna medium) owns seven reference/audit pages; fresh independent OpenAI `gpt_reviewer` (configured Terra xhigh) reviews the complete main-to-publication diff. GLM is not contacted; no external private-source transfer is needed. @@ -34,6 +1459,7 @@ Validation: Rust 1.98.0 (x86_64-apple-darwin), Python 3.11.6 and Node 24.21.0 we Independent review: PASS, no unresolved P1/P2/P3 findings. The reviewer identified a missing direct README fixture link; both canonical and negative links were added and rechecked. The reviewer independently reran the documentation validator and whitespace check. Publication scope is only the eight reviewed documentation files, with a substantive README update. This receipt records pre-publication validation; the containing commit and remote `main` history establish publication. No source change, native launch, provider call, LNSAT edit, deployment or executable release belongs to this packet. + ## Research and source publication — October 18, 2026 Authority: Jeff requested transcript extraction, primary-source verification, Rangoon comparison, missing-work planning and a separate LNSAT handoff, then explicitly authorized commit/push/merge to main with updated README/docs. [Intent](intent.md#research-and-source-publication-acceptance--october-18-2026) records the source-only publication boundary; [plan](plan.md#harness-value-and-portability-completion-track) owns the reconciled order. This supersedes older no-publication status for this reviewed packet only. Deployment, executable release, native NX-06 harness operation, production Start, encrypted activation, real credentials/providers and LNSAT changes remain excluded. @@ -3936,6 +5362,368 @@ Independent review: an OpenAI GPT-5.6-Terra xhigh security reviewer found an obs Acceptance remains bounded to source and synthetic UI evidence. Production host still mounts Legacy plaintext and portable backups remain plaintext; Managed construction is test-only. A qualified encrypted factory, native sheet/actual vault GUI, durable recovery/failure wake across process exits, explicit Legacy import, encrypted archives and isolated macOS/Windows/Linux GUI evidence remain open. No normal database/vault, provider, paid call, credential, execution, default activation, migration, installer, push, merge, deploy or release occurred in this packet. + +## Workbench copy refinement — October 24, 2026 + +Jeff requested direct, professional product copy following the source/interface audit. This bounded presentation change updates Activity reports navigation, Workspace data headings and descriptions, and Compile & export selection, output-format and result labels. Existing route IDs, native commands, machine-readable fields, state predicates, review/freshness gates, plaintext disclosures and unsupported operations remain unchanged. The revised labels describe current operations; they do not establish production readiness or connected-provider support. + +Eight implementation/test/validator files are owned: `preview/workbench-navigation.mjs`, `preview/workspace-view.mjs`, `preview/compilation-view.mjs`, `tests/workbench-navigation.test.mjs`, `tests/compilation-view.test.mjs`, `tests/workspace-model.test.mjs`, `tests/vendor-marks.test.mjs`, and `scripts/validate-vision.mjs`. Existing copy expectations were updated without relaxing behavior or privacy assertions. Focused checks pass 38 tests. The complete renderer/build checks pass 483 tests, including the loopback preview-server test, syntax, vision and asset validation. The first sandboxed full run could not bind loopback; the unchanged test passed with explicit loopback access. Existing wording assertions were corrected before the passing run. + +Evidence is retained under `/rangoon-production-copy-20261024`. Synthetic static views use the actual renderers and styles; they are copy/layout evidence only, not interactive native workflow qualification. Final responsive review covers Compile and Workspace in light/dark at measured 320/768/1440 logical widths: all twelve static screenshots are readable with no horizontal overflow. The first desktop QA fixture incorrectly hid navigation; its fixture state was corrected and all final captures were replaced before review. Fresh independent OpenAI `gpt_ui_review` (configured `gpt-5.6-terra`, xhigh) verified all ten owned hashes, copy-only renderer changes, screenshots, retained guards and supplied validation; PASS with no P1/P2/P3 findings. Earlier Lock discoverability, exact-revision handoff and broader native workflow/layout findings remain open. The companion read-only project/claims audit is `/rangoon-project-audit-20261024/audit.md`; it records current local workbench functions, missing target-loading/VUSL/engine/SDK workflows, parallel LNSAT source snapshots and prioritized remaining work. No foreign repository, normal data/key, provider, credential, publication or release operation is included. + + +## Progressive technical details — October 24, 2026 + +Jeff requested that internal identifiers and metadata move into Advanced or detailed views. This UI-only slice adds a shared, native HTML disclosure to Compile and Workspace. Main views retain names, selected format, human-readable status, plaintext warnings, action blockers and confirmation controls. Generated-text digests, exact selected skill/revision IDs, candidate/export identities, inspection provenance and Workspace record identifiers are closed initially but remain inspectable. Existing data attributes, opaque IDs, command routing, native save/export/restore/delete gates and lifecycle purge behavior remain unchanged. No framework, provider connection, encryption change or credential-reveal flow is introduced. + +The shared disclosure renders only renderer-owned, escaped markup. It is a presentation mechanism, not a security boundary: collapsed identifiers remain in the DOM. Stored credential values are not metadata and must not be added to the main workbench or a disclosure; existing explicitly authorized credential-entry windows retain their own separate contracts. The [product experience rule](product-experience.md#technical-details-and-everyday-views--october-24-2026) records the distinction and rollout boundary. Other authoring/integration inspectors remain unchanged in this first slice. + +Owned paths: `preview/technical-details.mjs`, `preview/compilation-view.mjs`, `preview/workspace-view.mjs`, `preview/workbench-shell.css`, `tests/compilation-view.test.mjs`, `tests/workspace-model.test.mjs`, `tests/workspace-view-purge.test.mjs`, `docs/product-experience.md`, `docs/continue.md`, and this ledger. The first independent UI review found ambiguous duplicate-name deletion targets, lost disclosure/focus state on refresh, and incomplete expanded screenshot framing. Corrections add collision-safe visible record discriminators and distinct action labels, exact deletion target details, retained disclosure/focus state, and current-scroll screenshot framing. Regression tests cover colliding shortened identifiers and refresh followed by purge. The existing exact native action contracts remain unchanged. + +October 25 completion validation: 35 focused tests and all 488 `npm run build:check` tests pass, including syntax, asset and vision checks. Twelve actual-renderer synthetic views at 320, 768 and 1440 CSS pixels in both themes have no horizontal overflow and closed initial metadata. Four expanded captures verify Enter/Space, visible keyboard focus and wrapping; a mounted synthetic Workspace binding verifies open/focus preservation after refresh, an exact duplicate-name deletion preview, and Cancel returning focus without mutation. Disclosures compute to no animation and zero transition; reduced-motion and forced-colors rules are source-reviewed, not an emulated OS accessibility qualification. Earlier misleading `.png`/full-page framing is retained only as superseded diagnostic evidence. Final evidence and fresh independent review belong to `/rangoon-technical-details-20261024`; fresh independent OpenAI `gpt_ui_review` (`gpt-5.6-terra`, xhigh) review passes with no actionable P1/P2/P3. The reviewer verified all ten after-hashes, exact packet scope, source/tests, logs and final responsive/expanded captures. Review is source/synthetic UI evidence, not native qualification or security certification. These fixtures contain disposable synthetic data and no native bridge. No native GUI rerun or product-wide usability/security qualification follows. + +Security and standards impact: no new dependency, external call, credential access, storage/output format, permission or execution authority. Native commands still own validation and transactions. Collapsed metadata is still readable in the DOM and is not secret protection. ISO/OpenSSF consideration here is preservation of exact identities, visible destructive scope, privacy boundaries and independently reviewed validation, not certification. Normal data/keys, credentials, foreign edits, publication and release remain untouched. All changes remain uncommitted. + +Intrusion research is separately recorded at `/rangoon-agent-intrusion-review-20261024/research.md`. It compares primary NVIDIA OpenShell/NemoClaw, OpenHands, agentgateway and Langfuse evidence, distinguishes credential brokering from confidential instruction delivery, and records proposed adversarial cases. Priority gaps are recipient/resource-scoped egress, stale approvals, aggregate abuse, authority translation, hostile evidence, active-work revocation, control-plane compromise and rollback recovery. They are test hypotheses, not confirmed vulnerabilities or implemented protections. No qualified hostile-worker harness or content broker is delivered by this UI packet. Original instruction files and exported bundles can remain plaintext; a compromised authorized consumer can copy delivered content. Reuse a separately qualified runtime for any later isolated synthetic-worker milestone; no engine installation, live connection or new security service is included here. + +## E1d-0 recovery and intrusion phase — October 25, 2026 + +Authority: Jeff requested addressing unfinished security work and identifying the next phase. This packet is docs-only source assessment, reconciliation and a reviewable implementation sequence, under the existing encryption-completion intent. Exact ownership: `docs/encrypted-workspace.md`, `docs/plan.md`, `docs/continue.md`, and this ledger. Root owns architecture/security judgment and all edits; fresh independent read-only review is required. Preserve the existing dirty application at branch `codex/personal-workbench-20261024`, base HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; the 164 preexisting status entries and empty index are not this packet's changes. + +Current source evidence: `workspace_source_access.rs::export_backup` checks `plaintext_backup_export_allowed` before picker/archive export; Managed returns false. `workflow_backup.rs::WorkspaceBackup` supplies existing bounded logical archive validation and redacted debug handling. `instruction_bundles.rs::export_compiled` checks the expected candidate identity before writing; its explicit instruction export remains plaintext. The prior eight-case macOS native smoke and 488 renderer tests are earlier bounded evidence, not tests of an encrypted archive or live runtime. No source test is repeated or rebranded as proof of a missing codec. + +The E1d section now stages a standard-container candidate around existing logical backups, an independent portable recovery identity, complete authentication before parsing/mutation, resource/diagnostic limits, exact source ownership, two-way interoperability, native lifecycle/write verification and a fresh encrypted restore rehearsal. Age v1 and Rust age 0.12.1 were checked against primary format/library documentation; the library advertises pre-1.0 beta status and is not cached here. The candidate is not an accepted production dependency, fetched crate or new cipher. Dependency/license/advisory/feature/resource/interoperability assessment and explicit acquisition scope remain open before source implementation. Sender authentication and rollback detection are not provided by recipient encryption alone. + +The following runtime milestone requires actual instruction-load/effective-policy evidence and independently observed denials. NVIDIA's current v0.1.5 primary guidance explicitly distinguishes network admission from L7 audit/enforce. The next runtime packet must prove restrictive request-level enforcement and supported transport/resource scope; no healthy connection, log or provider decision becomes authorization. The full proposed intrusion cases remain staged; no live hostile worker, external provider or engine was run. + +Experience track: keep simple Back up/Restore/last verified result, with format/identity diagnostics in Advanced. Controls remain unavailable until real native qualification; no UI behavior or graphic is changed here. Technical track: specification/priority/gap reconciliation only. Security/standards impact: explicit confidentiality, key separation, bounded parsing and dependency review requirements; no new credential access, transport, execution authority, cryptography, schema, dependency or data mutation. ISO/OpenSSF practices are considered without certification or badge claims. Exact preimages, packet diff, checks and independent review belong to `/rangoon-recovery-phase-20261025`; document/reference validation passes (eight image hashes, historical brief, local targets and 594 authored text files), scoped whitespace checks pass, and fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh) review passes with no actionable P1/P2/P3. Targeted source-order assertions confirm Managed refusal precedes picker/archive access and expected candidate checking precedes instruction encoding/writing; these are source assertions, not runtime tests. All seven previously reviewed UI source/test hashes remain exact. No Rust, renderer or cryptographic tests were run for this four-document packet. No normal data/keys, dependency fetch, provider/engine operation, LNSAT/VUSL edit, commit/push/deploy or release. + +## E1d-1 experimental encrypted recovery codec — October 25, 2026 + +Authority: Jeff said “proceed then” after the reviewed E1d sequence. Exact eleven-path packet: root `Cargo.toml`/`Cargo.lock`, new `crates/rangoon-recovery/Cargo.toml`, `src/lib.rs`, `tests/envelope.rs` and `tests/fixtures/reference-age-v1.json` beneath that crate, and `docs/intent.md`, `docs/encrypted-workspace.md`, `docs/plan.md`, `docs/continue.md`, plus this ledger. Root is the sole producer and owns dependency/cryptography integration. The preimage/hash baseline covers 716 authored files with 164 preexisting dirty status entries and empty index at `c132ea62bc57b29375ee8c5a3a38ca005462ca40` on `codex/personal-workbench-20261024`. No mixed-tree diff is treated as this packet. + +Assessment found that exact age 0.12.1, even without optional features, resolved crypto-bigint 0.5.5 via P-256/HPKE. RustSec snapshot `21d909e4c8bd4e14c7aea58bf980c881a0053ab1` includes RUSTSEC-2026-0387, with patched range >=0.7.6. That candidate never entered Rangoon. This does not prove exploitability through X25519 or an existing Rangoon vulnerability. The selected experiment pins published age 0.11.5, default features disabled; cached source checksum and VCS identity are retained. Public tag verification was unavailable, so no verified-tag claim follows. The graph avoids crypto-bigint but is not called clean: basic-toml and proc-macro-error2 remain unmaintained compile-time dependencies, and Cargo reports a proc-macro-error2 future-compiler incompatibility notice. The library itself remains beta/testing-only. These are blockers for later native/production promotion, not waived by this experiment. The age file key is 128 bits; database AES-256 behavior remains unchanged. Source/library licenses include permissive choices, but distribution notices and full artifact supply-chain qualification remain later gates. + +The already-required Rust 1.99.1 was absent from the host (global Rust is 1.98). Official rustup provisioned only a temporary minimal 1.99.1 x86_64 toolchain/formatter/Clippy and isolated public package cache under `/rangoon-e1d1-assessment-20261025`. Global toolchains were not changed. The existing identity validator confirms rustc/rustdoc/formatter/Clippy compiler commit `58cf8f9c35b355199727627d07ae34a4e2846d67` and Cargo 1.99.1. Build/test children use a minimal credential-free environment with exact compiler paths and offline dependencies. The independent Go age v1.3.2 reference was taken from the official release, checked against its release-API asset SHA-256, and only age/age-keygen were extracted. No independent signature verification, provider connection or app installation is claimed. All key generation/data used only disposable public test fixtures; the committed identity must never protect real data. + +Experience track: no UI changed; encrypted backup controls remain unavailable. Technical track: the experimental source wraps opaque backup bytes in standard binary age v1 with an encrypted inner version. It caps body/ciphertext/header/stanza resources, accepts explicit X25519 wrappers only, keeps decrypted chunks private through authenticated EOF, rejects unsupported/tampered/truncated/trailing inputs, returns a private zeroizing owner and fixed redacted errors, and provides no file/process/network/vault/authority API. Existing logical backup validation and native consent/transaction/lifecycle ownership are unchanged. Full-memory erasure, sender authentication, rollback detection, logical archive validity and production recovery are not established by this codec. + +Pre-code independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh) review passes for the synthetic unmounted packet only. Focused source tests pass 17 cases plus two nonserialization compile-fail doctests, including 68 MiB maximum success, one-byte oversize refusal and authenticated oversized plaintext refusal. The deterministic malformed corpus is not coverage-guided fuzzing. Two-way interoperability passes a Go-to-Rust fixture and four Rust-to-Go cases spanning empty/binary and chunk boundaries. Scoped Clippy with `-D warnings` and pinned formatting pass; Cargo's separate transitive future-compiler warning remains explicit. The first Clippy run caught a test-helper chunk-iterator lint, corrected without a lint suppression. The lock proof preserves all 167 old package identities/checksums/dependency edges, adds 92 packages, and records necessary futures/zeroize feature-edge additions and explicit version qualifiers. The initial stricter byte-identity assertion correctly failed on those edge/qualifier changes; no old package version/checksum was replaced. All 709 outside-owned preexisting files remain exact at this checkpoint. + +Final locked/offline workspace tests pass all 656 cases across 62 successful result groups; full workspace Clippy with `-D warnings` and pinned formatting pass. The transitive future-compiler warning remains explicit and is not silenced. Fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh) source/security review passes with no actionable P1/P2/P3 and verifies all six source hashes. Document/reference validation passes eight image hashes, historical brief, local Markdown targets and 597 authored text files; scoped whitespace checks pass. Fresh independent OpenAI `gpt_reviewer` (`gpt-5.6-terra`, xhigh) documentation/evidence review passes with no residual findings after correcting the continuation step and intent metadata date. All six reviewed source hashes remain unchanged. Own temporary Cargo build output is removed after validation; exact source, pinned compiler/cache, reference tools, logs and metadata remain for replay. Exact commands/logs, independent reference provenance, dependency/RustSec snapshots, before/after hashes, packet diffs, lock semantics and preservation proof belong to `/rangoon-e1d1-assessment-20261025`. Security/OpenSSF impact is explicit dependency assessment, limits, secret handling, reproducible evidence and no-authority boundaries, not certification. No desktop/native/store/UI/CI source, desktop lockfile, normal data/keys, live provider/engine, LNSAT/VUSL or publication was changed. No new backup UI or production capability is claimed. The next gate is dependency promotion/compatibility resolution, followed by a separately reviewed native custody/selected-file/restore-rehearsal packet. + +## E1d-2 native encrypted recovery — October 25, 2026 + +Authority: Jeff requested resolving dependency promotion, connecting native backup/restore and proving recovery into a fresh encrypted workspace. His subsequent request requires appropriate in-app disclaimers. Status: source, focused/full validation and selected disposable macOS native evidence are complete; fresh independent source, UI and native-evidence reviews pass. This is not normal-profile adoption, Windows/Linux qualification or a release. + +The application repository remains ``, branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. The 720-file pre-packet source baseline and unrelated dirty work are preserved. The initial 27-path packet grew through recorded necessary corrections to the 37 exact paths below; `/rangoon-e1d2-native-recovery-20261025/contract.md`, `owned-paths.json` and `preimage/` retain scope, preimages and each reason before edits. No index, commit, push, merge, deployment or release is part of this work. + +### Dependency and storage mechanics + +The beta age candidate was not promoted. Rangoon reuses its existing SQLCipher 4.14.0/rusqlite 0.40.2 backend and encryption profile; there is no new runtime cipher, KDF, helper process or crypto dependency. The active root lockfile is byte-identical to the verified pre-experiment lockfile: 167 packages. An initial lockfile regeneration selected newer cached transitive versions; that candidate was discarded and locked metadata validates the restored exact graph. The old codec's source/tests are unchanged and retained in the excluded standalone `crates/rangoon-recovery` workspace with its own lockfile and retired README. No compatibility reader, alias or converter is mounted. + +`rangoon.recovery.sqlcipher.v1` stores a canonical encrypted workspace image, bounded at 64 MiB. The host selects an independently generated 32-byte recovery key through a strict owner-only key file. It captures the source through trusted Owner routing, reconstructs all records in a private 0700 encrypted staging directory, closes/reopens read-only, checks the pinned cipher profile/per-page HMAC, canonical schema/domain, exact page/file length and absence of sidecars. It exclusively writes/syncs the chosen ciphertext, rereads that actual output into a new stage and compares complete canonical records before reporting success. No plaintext recovery staging file is created. Existing readable instruction exports and original files retain their distinct contracts. + +Three native commands accept only existing workspace request identity: `create_workspace_recovery_key`, `export_encrypted_workspace_backup`, `prepare_encrypted_workspace_restore`. Their permissions and the renderer's private current-request bridge are exact. The loaded inventory's `encryptedRecoverySupported` flag is advisory and computed by the actual backend; native support checks still refuse before RNG, picker or file operations. Legacy and no-backend paths cannot activate encrypted recovery. Keys, filesystem paths and replacement originals never enter renderer payloads. Lock/close retains the real lease until callbacks, keys and private-stage cleanup drain; post-write uncertainty never becomes a false cancellation or retry. + +Restore reuses the retained native Backup/RestorePlan and exact generation/state-bound one-shot confirmation. Bad input does not falsely corrupt or lock a healthy destination. The ordinary restore path now preserves every canonical record into a truly empty target, including otherwise unreferenced composition records; nonempty additive union/conflict semantics remain unchanged. No restored review record grants approval or execution authority. + +### Experience and disclosures + +Primary actions are Back up workspace and Restore backup. The native-backed dialog can create a separate key or select an existing one. Older plaintext backup import remains explicit under More recovery options. Error/stale/Cancel handling retains honest outcomes; no secret entry field, automatic retry, fake progress, new framework or artwork is introduced. + +The dialog says the recovery key file itself is unencrypted, must be protected like a password and stored separately, and is required to restore the backup. Anyone holding both files can read it. Collapsed Encryption limits distinguishes encryption at rest from an unlocked or compromised host, original files and readable instruction exports; integrity does not establish authorship, trust, approval or execution authority. Windows/Linux native recovery qualification remains pending. No certification, compliance, rollback prevention, sender authentication, complete memory erasure or production-readiness claim follows. + +Source/UI review corrected stale-modal error and false-cancellation copy and added request-bridge coverage. Six synthetic 320/768/1440 CSS-pixel dark/light checks measure no horizontal overflow; controls remain enabled and adequately sized. The viewport backend required calibration to actual CSS width and produced some clipped screenshots, so those images alone do not prove visual fidelity. Narrow-dialog DOM bounds and Tab → Use recovery key → Tab → Create recovery key → Escape/focus-return pass. Fresh native AX and screenshot evidence separately demonstrates the actual dialogs and restored inventory. No new motion was added; existing reduced-motion CSS remains intact. + +### Native recovery proof + +Five final native phases use disposable data and isolated Keychain services on macOS 26.0, x86_64 artifacts: + +1. Source authoring nonce `514233366e735745a6d08389edd84ccd`: set up an encrypted workspace, explicitly import synthetic complete history, create/select a recovery key in a separate folder and write a 94,208-byte encrypted backup through real native dialogs. The application reports a verified reread. +2. Exact source cleanup removes the original test database key and verifies its absence. The encrypted source file remains byte-identical. Local permit/claim ordering confirms cleanup completed before target launch; this is local test evidence, not a trusted distributed timestamp. +3. Target authoring nonce `393f14b34d5928814854e057920e9786`: set up a different encrypted workspace/key, cancel the first picker, then select the encrypted backup and recovery key. Exact target ciphertext remains unchanged through cancellation and the validated preview. Confirm Restore additions and inspect all restored records. +4. Relaunch target in another process, unlock with its own existing test key and reread the complete canonical archive. No key is regenerated and no recovery file is needed for this ordinary reopen. +5. Exact target cleanup removes its registered test Keychain slot and verifies absence. The owner-only disposable recovery-key file and its private directory were removed at final cleanup; ordinary data/keys are never selected. + +All three canonical observations equal `backup:55a104db7ccf5db59078bde3701fd030d7084cb5a4ec2fe038fbbd9661f15357`, 6,623 logical bytes. The archive retains one source, three skills, four skill revisions, two reviews, one recipe, one application, two derivations and one workflow with two revisions. Source/target workspace IDs and ciphertext differ. Source preservation, no pre-confirmation mutation and distinct-process target reopen are separately observed. + +The final native source snapshot is `593482137b0416eb3797f164c94a3005ca3951cf615aef9d574f90ce299ee61b`. Source and target were separately built debug artifacts with recorded executable hashes `799bd96af9b4001fba257d04263800a520a3736eb3e21837a9ca1ff805574d7a` and `f65b7f34636a2695176399e5b4144b8c62c322c31d1170690a20708fb1ff196e`; target/relaunch reuse the same exact target binary. This does not establish bit-reproducible builds. The result manifest, exact five receipt paths/hashes, file observations, AX and captures are in `native-recovery-results.json`, `native-key-loss-ordering.json` and the evidence folder. + +Two earlier runs are rejected as recovery proof. `3e75dfdf` found that the test observer used an unbound source handle; it now binds the already-issued current native request without issuing or bypassing authority. `95af271f` found missing renderer bridge entries for the new commands; the three entries and a controller-through-bridge regression now exist. Both runs' exact test slots were cleaned before source changes. Their receipts remain separate and are not added to the five passing phases. + +### Named validation + +All Rust commands use the isolated, already-provisioned exact Rust/Cargo 1.99.1 toolchain with no auto-install, credential config or external provider calls. Public cache artifacts were checked against locked checksums. The temporary target cache was moved to the harness's required ignored desktop target path; a private compatibility symlink kept generated absolute Tauri build paths valid. A stale generated-permission-path failure was a validation-cache issue, not an application pass. Product-package clean/rebuild followed the request-bridge correction before the final native artifacts were captured. + +| Validator | Result | +| --- | --- | +| `cargo test --workspace --locked --offline` | 638 passed, 8 ignored; active portable workspace | +| `cargo clippy --workspace --all-targets --locked --offline -- -D warnings` | Pass | +| `cargo test -p rangoon-store --features encrypted-sqlite --locked --offline` | 175 unit + 10 empty-store + 4 encryption + 2 doc tests passed, 9 ignored | +| Final `cargo test -p rangoon-store --features encrypted-sqlite recovery_copy --locked --offline` | 3 focused cases passed; ordinary fresh restore preserves all canonical bytes | +| `cargo clippy -p rangoon-store --features encrypted-sqlite --all-targets --locked --offline -- -D warnings` | Pass | +| `cargo test --manifest-path apps/desktop/Cargo.toml --locked --offline` | 172 library + 542 binary + 22 doc tests passed, 4 ignored; a library subprocess regression also passes its child invocation | +| `cargo test --manifest-path apps/desktop/Cargo.toml --no-default-features --locked --offline` | 43 library + 341 binary + 22 doc tests passed, 1 ignored | +| `cargo test --manifest-path apps/desktop/Cargo.toml --bin rangoon-desktop --features native-encrypted-qualification recovery --locked --offline` | 37 focused cases passed, including real request binding, replacement, drift and drain | +| Desktop default and no-default `clippy --all-targets --locked --offline -- -D warnings` | Pass | +| Desktop default `cargo build --locked --offline` | Pass; no launch of the ordinary user profile | +| Portable and desktop `cargo fmt --all -- --check` | Pass | +| Explicit standalone historical codec `cargo test --manifest-path crates/rangoon-recovery/Cargo.toml --locked --offline` | 17 tests + 2 privacy doc tests passed; excluded from product builds | +| `python3 -m unittest discover -s tests -p qualify_native_encrypted_test.py` | 40 parent-oracle tests passed | +| `npm run build:check` | Syntax, visual/vision contracts and 496 renderer tests passed | +| Five isolated native macOS phases | Pass for the selected synthetic recovery journey only | + +Wrong key, malformed/tampered cipher, trailing bytes/pages, sidecars, key/cipher replacement before open and after read, key permissions/links, output collision, partial write, pre/post-write source drift, callback cancellation, close/drain, stale restore and replay refusals have focused source coverage. Only picker cancellation and the positive backup/fresh-restore/restart journey have new GUI evidence here; do not promote every source-negative case into an OS GUI claim. Initial sandbox EPERM failures for loopback/special-file fixtures were rerun in the authorized disposable test lane. Unchanged Tauri multi-target and the explicit qualification target's existing unused-helper warnings are not hidden; strict ordinary default/no-default Clippy passes. + +### Ownership, review and remaining gates + +Root/Sol owns protected dependency, store/native, request binding, integration, validation and final judgment. The UI writer is OpenAI `gpt_worker`, configured `gpt-5.6-terra` high. Fresh independent source, UI and final native-evidence reviewers are OpenAI `gpt_reviewer` / `gpt_ui_review`, configured `gpt-5.6-terra` xhigh; role TOMLs were verified, while the subagent API does not independently expose a runtime model identifier. Read-only reviewers approve no external action. All material source/UI findings were corrected and rereviewed; final evidence review reports no actionable P1/P2/P3. No GLM invocation or application model/provider connection was used; native GPT agents performed development and read-only review. + +Security/standards impact: synthetic content, local encrypted images and secret test recovery keys only; existing SQLCipher and local trust boundaries are reused. Exact refusal, consent, key separation, least-privilege file custody and retained evidence support the existing ISO/OpenSSF readiness track, but establish no certification, badge, maturity/score or SLSA level. Other-OS custody/GUI, inherited ACL and shared/network/removable-filesystem behavior, artifact-bound dependency inventory/SBOM, signing, install/update/rollback and organizational controls remain their own gates. The selected local key-file proof establishes the recorded POSIX mode/link/identity checks, not universal filesystem access control. Backups lack sender authentication and rollback prevention. File unlink does not establish secure erasure. The selected profile is pinned; future SQLite/SQLCipher compatibility requires qualified tests and explicit readers, not silent downconversion. + +Exact owned paths: + +- `Cargo.toml` +- `Cargo.lock` +- `crates/rangoon-recovery/Cargo.toml` +- `crates/rangoon-recovery/Cargo.lock` +- `crates/rangoon-recovery/README.md` +- `crates/rangoon-store/src/lib.rs` +- `crates/rangoon-store/src/recovery_copy.rs` +- `crates/rangoon-store/src/recovery_copy_tests.rs` +- `apps/desktop/src/main.rs` +- `apps/desktop/src/encrypted_recovery.rs` +- `apps/desktop/src/encrypted_recovery_tests.rs` +- `apps/desktop/src/workspace_source_access.rs` +- `apps/desktop/src/workspace_recovery_file_tests.rs` +- `apps/desktop/src/data_controls.rs` +- `apps/desktop/build.rs` +- `apps/desktop/capabilities/source-analysis.json` +- `apps/desktop/src/native_encrypted_qualification.rs` +- `preview/workspace-model.mjs` +- `preview/workspace-view.mjs` +- `tests/workspace-encrypted-recovery.test.mjs` +- `tests/workspace-model.test.mjs` +- `tests/workspace-view-purge.test.mjs` +- `docs/intent.md` +- `docs/encrypted-workspace.md` +- `docs/plan.md` +- `docs/continue.md` +- `docs/development.md` +- `apps/desktop/src/workspace_workflow_access_tests.rs` +- `apps/desktop/src/workspace_source_access_tests.rs` +- `crates/rangoon-store/src/workflow_recovery.rs` +- `crates/rangoon-store/src/encryption.rs` +- `scripts/validate-vision.mjs` +- `scripts/qualify-native-encrypted.py` +- `tests/qualify_native_encrypted_test.py` +- `apps/desktop/native-encrypted-qualification/tauri.conf.json` +- `preview/workspace-lock-model.mjs` +- `tests/workspace-requests.test.mjs` + +Preservation, final cleanup, document checks and reviewer receipts live under `/rangoon-e1d2-native-recovery-20261025`. No changes outside the exact packet are allowed. No normal data/keys, real provider or engine execution, LNSAT/VUSL edits, application paid-service calls, CI dispatch, publication, merge, deployment or release occurred. Synthetic loopback test peers are not live-provider qualification. Next safe packet: reviewed personal-use packaging/install and an explicit recovery rehearsal, then separately qualify other OSs and one external runtime. + + +## Management audit and activity-report optimization — October 25, 2026 + +Authority: Jeff requests assessing management systems and optimizing them. The [accepted continuation](intent.md#management-audit-and-optimization--october-25-2026) and [experience checkpoint](product-experience.md#management-usability-checkpoint--october-25-2026) define this bounded slice. Actual checkout ``, branch `codex/personal-workbench-20261024`, unchanged HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Broad prior dirt is not this packet. Exact preimages, ownership and validation are in `/rangoon-management-audit-20261025`. + +### Findings and repairs + +- P2 contract mismatch: native `operator_view.rs` counts producers across snapshot prefixes and tail but assigns display ordinals from tail events. The renderer incorrectly required equal producer counts. It now permits the observed tail producer count to be below the bounded inventory total. Dense ordinals, exact schemas, all event/decision counts and fixed no-authority states remain enforced. Prefix-only and prefix-extra producer cases pass; undercounts and more than 32 producers still reject. +- P2 usability: replacement success retained old filters and could make a populated new report appear empty. Success now resets filters/page. Cancel/rejection retain prior report, selection and filters; Clear and lock purge erase retained inspection and reset local filters/page. +- P3 rendering: a maximum 1,024-event report built 2,048 duplicated record buttons. Both lists now display 50 events per page, at most 100 combined controls in timeline mode, without changing the input bound or total counts. All 1,024 ordinals remain reachable in 21 pages. The full selected event stays inspectable and has explicit off-page/filter context with a reveal action. +- P3 redundant updates: identical or invalid filter/mode/page/selection operations do not publish another render or invoke native work. +- Browser and independent review identified focus loss on new paging/recovery controls. Explicit focus custody now restores the page status, event-number field or finite selection initiator as appropriate. The System coverage route replaces the previous route's stale announcement. Activity reports now matches navigation and observed counters use singular/plural grammar. + +### Ownership and security impact + +Ten changed paths: `preview/operations-model.mjs`, `preview/operations-view.mjs`, `preview/operations.css`, `preview/analyze.mjs`, `tests/operations-model.test.mjs`, `tests/operations-view.test.mjs`, `docs/intent.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. Root is the sole producer/writer. No new dependencies, native commands, data store, credentials, network calls, collection, execution or authority path. The renderer only presents the existing minimized native report. Paging is not dropping input records or downconverting provider semantics. No ISO/OpenSSF certification or complete standards assessment follows from this UI repair. + +### Validation and limits + +- `npm run build:check`: syntax, visual and vision contracts plus 504 renderer tests pass. Focused operations model/view/parity suite passes 36 tests. The first full run failed on sandbox loopback `listen EPERM`; an explicitly permitted disposable-loopback rerun passed. The failed log remains distinct. +- Actual workbench with a disposable synthetic bridge: maximum report load, paging, reveal, exact-number filter, keyboard Clear/Next/Previous, cancellation, rejection, prefix-only replacement, topology switching and retained decision disclosure verified. Local filter/page/view controls caused no additional synthetic report read. This is real renderer wiring over synthetic data, not native picker/provider qualification. Workspace disabled recovery capability and reference-only coverage copy were inspected without normal data, keys or native actions. +- Six calibrated 320/768/1440 × 900 CSS-pixel layouts in dark/light have no document horizontal overflow. New controls compute to a 44px minimum height (fractional backend rectangles approximately 43.995px). Keyboard theme switching was used after one pointer-driven 1440 theme capture did not change state; that earlier duplicate light case is not counted as dark-theme evidence. +- Existing reduced-motion and forced-colors source rules remain; no new motion exists. OS preference emulation, screen readers, physical 4K, native GUI and other-platform management workflows were not qualified here. Browser screenshots at oversized viewport overrides may clip; DOM layout metrics do not establish complete visual fidelity. +- Node v24.21.0 HTML-generation benchmark, 200 timed samples after warmup, one synthetic maximum report: before 2,048 buttons / 396,925 bytes / 1.260ms median / 2.032ms p95; after 100 / 24,648 / 0.086ms median / 0.191ms p95. This measures string generation only, not browser interaction latency, memory, native throughput or distributed capacity. Exact data is `render-benchmark.json`. +- No Rust source changed and no native build/test was rerun: prior encrypted recovery receipts remain separately scoped evidence. No Graphify graph exists in the active checkout; exact-symbol navigation was used. + +Independent initial audit: OpenAI `gpt_reviewer`; fresh change review: OpenAI `gpt_ui_review`. Both role TOMLs configure `gpt-5.6-terra`, xhigh; the runtime does not expose a separate returned-model identity. Review identified the focus defect above, which was corrected and browser-tested; final independent review returned PASS with no actionable P1/P2/P3 findings, and verified the focus correction, 36 focused tests and ten-path preservation. Exact evidence and preservation seal are recorded in the local packet. Root owns final integration judgment. No GLM or application model/provider invocation. + +No ordinary data/key/vault access, native application launch, real provider/engine contact, foreign repository change, dependency fetch, commit, push, merge, deploy or release. README is unchanged because this is not a publication packet; its substantive-update gate remains required before publication. Unrelated dirt stays preserved. Next: bounded personal install/recovery rehearsal, then one qualified target-load/readback workflow before live fleet management. + + +## TLQ-1 target-isolation prerequisite — October 25, 2026 + +Authority: Jeff requests starting the next phase after management optimization, then adds backup/undo and secured archive/restore with hashing. The [accepted continuation](intent.md#target-readback-prerequisite-continuation--october-25-2026), [isolation contract](target-loader-qualification.md#tlq-1-isolation-prerequisite--october-25-2026) and [archive direction](target-loader-qualification.md#instruction-change-archive-and-restore--october-25-2026) define this bounded source/tooling packet. Archive source stages remain proposed; no archive, installer, store-schema or UI implementation follows from TLQ-1. + +Checkout ``, branch `codex/personal-workbench-20261024`, unchanged HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. Seven owned paths: new `scripts/qualify-target-isolation.py`, `tests/qualify_target_isolation_test.py`, `tests/fixtures/target-isolation-probe.c`, and existing `docs/intent.md`, `docs/target-loader-qualification.md`, `docs/continue.md`, `docs/development.md`. Root is the sole writer and retains protected isolation, contract and integration judgment. Exact preimages, patch, pins and logs: `/rangoon-target-qualification-20261025`. All other recovered/management/recovery work stays outside this packet. + +### Candidate and startup findings + +Metadata/byte-only recheck identifies installed Codex `0.164.0-alpha.11.1`, package SHA-256 `2d850da28de4e799ff848e93a769087440b515c85083c40b984560b79a84d140`, executable 260,394,448 bytes / SHA-256 `a04752e4d46a4d89e53e6f61c59c5349a638c8ce172ffbf391fd482b4d902a4e`. No target help/version or process was invoked. Matching official tag resolves to `6905ecede7816e91373e9eabda3f6b0368fc747b`; fetched CLI, arg0, core prompt-debug and app-server files are individually hashed in `upstream.json`. Version correspondence is not proof of installed-binary/source equivalence. + +Pinned arg0 performs Codex-home dotenv loading and helper-directory/path preparation before dispatch. Prompt debugging loads config/authentication and starts thread infrastructure. Schema generation remains a candidate, not an authorized or qualified command. Official documentation describes app-server stdio and a separate outbound Code Mode host; it does not supply this binary's complete artifact-bound protocol/startup proof. An initial public source fetch failed Python's default certificate chain; retry used the existing macOS CA bundle with full TLS verification and no credential/proxy inheritance. No verification was disabled. + +### Supervisor and validation record + +The closed `--self-test` tool uses a fixed existing Xcode compiler/SDK and deprecated OS `sandbox-exec` only for synthetic development probes. It accepts no target/command/path option and forwards a minimal environment without HOME/CODEX_HOME or inherited credentials. The supervisor bounds combined output and wall time, distinguishes failures and retains actual process/pipe cleanup. Named canaries test permitted synthetic read/write and denied sibling read/write, TCP, Unix socket and child executable access; fixed probe startup markers prevent launcher crashes from masquerading as expected denials. Generated files are removed by exact name only. + +Initial unit runs exposed a repeated termination/exit race and a cleanup failure path. The corrected supervisor stops once, checks/reaps exited leaders and handles termination denial without claiming success. Fresh independent OpenAI `gpt_reviewer` then found a P2: selector/controller setup occurred after child spawn but before the cleanup guard. Root moved selector creation before spawn, wrapped all later setup in the guard, nested finalizers, and added pre-spawn selector failure plus post-spawn pipe OSError/KeyboardInterrupt cleanup regressions. Focused Python suite now passes 18 tests; the independent reviewer reran all 18 and returned source PASS for synthetic self-test only. + +The first actual macOS canary invocation returned failure: all seven cases exited with signal 6 before the fixed marker, so zero cases passed. Generated blocked input stayed unchanged, but permitted output did not exist; this was not containment proof. `selftest-first.json` and exit 3 remain explicit failed evidence. Read-only inspection of Apple's local `system.sb` showed `file-map-executable` is distinct from read permission. A minimal exact-probe/system-library executable-mapping allowance and regression were added for a separately reviewed rerun; no scratch mapping, user read, network or Mach allowance was added. The explicit map-only rerun also failed all seven cases before startup; `selftest-map-exec.json` remains failed evidence. Apple's local `dyld-support.sb` explicitly names rules required to bootstrap a process, including cryptex paths and restricted loader syscalls/fcntls. The next candidate imports only that exact reviewed OS file with a fixed SHA-256 pin and pre/post identity checks. Unknown policy bytes fail before build/run; no broad system/bsd policy, network, Mach lookup or user-data allowance follows. A new test covers this refusal. Final rerun/review disposition is retained separately in this packet; an absent passing seal leaves containment unqualified. + +### Final bounded result + +- `PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p qualify_target_isolation_test.py -v`: 19/19 pass. Source compilation with Python `compile()` passes without generating bytecode. Initial failed unit logs remain separate, as do the independently identified startup-cleanup finding and its passing regressions. +- `PYTHONDONTWRITEBYTECODE=1 python3 scripts/qualify-target-isolation.py --self-test`: final exit 0, seven of seven selected macOS cases pass in `selftest-dyld.json`. Permitted read/write exit 0; denied sibling read/write, TCP, Unix socket and executable access exit 42. All emit the 17-byte fixed marker, have empty stderr and completed drain. Protected fixture is byte-identical; permitted output is valid; pinned dyld profile unchanged. Generated named files and private directories were removed by the runner. Prior two exit-3, seven-crash runs remain failed and count zero passes. +- Selected host reports macOS 26.0; the final receipt records probe/source, compiler, sandbox, generated policy and OS support-profile SHA-256 identities. This does not establish reproducible build provenance, a supply-chain level, supported target artifact or other-OS behavior. +- A fresh independent source re-review passes with no actionable P1/P2/P3 after the startup-cleanup correction, exact mapping assertion and private OS-profile pin. Final seven-path diff, evidence/claims review and preservation seal are recorded in the local packet. + +### Security impact, scope and remaining work + +Data is generated synthetic canaries and public tool/source identity only. No new application runtime, dependency, cryptographic algorithm, authenticated archive format, provider call or persistent data schema. `sandbox-exec` is deprecated and is not selected as shipping product isolation. Finite checks do not establish full network-attempt capture, ordinary credential/Keychain protection, every alias, process/session escape, resource confinement or actual target startup safety. Passing source tests cannot be promoted into target loading, effective configuration, model adherence, authority, ISO/OpenSSF certification, release or cross-platform support. + +Jeff's secure archive requirement is reconciled with the real implementation: SQLCipher-backed workspace recovery exists separately; bundle exports refuse overwrite. A future instruction-change journal must archive exact original/proposed states and metadata inside authenticated encrypted storage before an external effect, integrate versioned backup/restore and explicit capacity/deletion semantics, refuse stale or unsupported replacement, and preserve uncertain crash outcomes. Hashes do not replace keyed authentication, source authorization or independent freshness protection; atomic rename plus a hash check is not a concurrency-safe compare-and-swap. Proposed AR-1 through AR-4 and acceptance cases are specified, not run. + +Fresh independent reviewer role: OpenAI `gpt_reviewer`, TOML-configured `gpt-5.6-terra`, xhigh; runtime model ID is not exposed. Root owns final integration judgment. No GLM or application model call. Source syntax/whitespace/ownership checks and final bounded evidence seal remain in the local packet. No UI or app Rust source changed; renderer/Rust/native matrices were not rerun for this standalone Python/C tooling slice. No Graphify graph exists in this checkout. + +No installed target launch, schema generation, authentication, real credentials/providers, normal data/key/vault reads, foreign edits, dependency install, commit, push, merge, deploy or release. README publication gate remains required before future publication. Next safe source work follows the explicit isolation/startup gate and secure archive sequence; do not use a model call or weakened policy as a substitute for target readback. + + +## AR-1/AR-2 encrypted instruction history — October 25, 2026 + +Authority: Jeff's explicit request to proceed with encrypted instruction-history persistence while retaining parsing and merge/split/reassembly. Canonical behavior: [instruction archive contract](target-loader-qualification.md#instruction-change-archive-and-restore--october-25-2026); scope: [accepted continuation](intent.md#ar-1ar-2-instruction-history-continuation--october-25-2026). Root is sole writer and owns protected store/schema/recovery judgment. This is store-only source, not native mounting or target-file modification. Existing unrelated recovered work remains intact. Initial branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; index empty. + +Implementation: immutable exact-byte changes, explicit absent/present/empty state, SHA-256 identities, selected-target metadata and exact source/revision/composition lineage; append-only attempted and terminal outcome events; encrypted-only opt-in schema 5, complete validation/capacity/state identities; drift-safe read-only restore eligibility; referenced-history/lineage deletion refusal and explicit logical history deletion. No filesystem Apply/Restore or execution authority is provided. Verified events are validated host-supplied observations, not cryptographic authorization receipts or proof of target custody. Unknown outcomes stay unknown and cannot be automatically replayed. + +Protected history uses a private bounded V4 in-memory recovery representation, opaque trusted-Rust snapshots and the existing authenticated SQLCipher recovery-copy path. Public plaintext backup export rejects schema 5; public plaintext import rejects V4. V1–V3 bytes/goldens remain unchanged. Complete recovery preserves history during fresh and nonempty restores and later authoring; history participates in state and dependency checks. No normal startup migration or UI mounting occurs. + +Parsing reuses the existing deterministic analyzer and exact byte spans. Existing composition performs source decomposition, saved-revision split and multi-revision merge with explicit recipes. Literal tests cover BOM/CRLF-preserving reassembly; no new semantic parser, auto-merge, model invocation or claim of general intelligent understanding is introduced. Unsupported/binary originals are still protected without requiring parse success. Fuzzy/classifier suggestions remain advisory and never replace exact identity or grant authority. + +Security/standards impact: new local sensitive originals/metadata stay inside the existing keyed SQLCipher workspace; no new crypto/dependency/build privilege, network, credential or telemetry surface. Owned plaintext buffers are zeroized where practical; parser/SQLite/caller copies and compromised/unlocked hosts remain outside that guarantee. Capacity is 256 KiB per side, 128 changes, 512 events, 16 MiB serialized history and the existing 64 MiB database ceiling, with no silent eviction. At-rest authentication does not prove authorship/freshness or prevent valid old-database replay. Independent rollback anchoring, native single-use preview/custody, three-OS filesystem qualification and UI lifecycle remain open. Existing OpenSSF/ISO readiness applies to integrity, least privilege, malformed-input handling, reproducible evidence and dependency custody; this receipt claims no certification, badge, maturity level or release readiness. + +Exact packet preimages, owned paths, failed attempts and validation logs: `/rangoon-instruction-history-20261025`. First focused test incorrectly used Merge with one source, then Split with a source reference; both correctly failed the established closed composition contract. Tests were corrected to use Decompose for source ranges and saved-revision-shaped inputs for Split/Merge. A later authoring test caught use of an unvalidated candidate's history index during allocation checking; canonical readback now supplies the fully validated records. These failures remain separate from final evidence. Design review identified the plaintext-export hazard before publication; public export/import now refuses protected history rather than serializing or silently omitting it. + +Cross-product review: root adopted a bounded read-only GPT reader's evidence from LNSAT canonical `6741676496241a3cddf146d7dc28aa6c1a09860b`, newer local object `605742b39e09bde9c37c6d767e21917e705b3757` (prunable worktree, source read from object store), and VUSL `78b5ae41c8c720badd1f2301e1eabd0d07a83d5e`. No sibling changed. The archive specification now records independent digest namespaces, local readback versus engine authorization/receipt semantics, unknown/no-retry behavior, and contextual lineage links versus stronger derivation proof. No source boundary redesign was indicated; this is not live/public-main compatibility qualification. Existing composition invariants prohibit orphan/unapplied recipes. A review-requested fixture exposed that invariant and was replaced with an actual applied composition; incompatible incoming pinned revision recovery now has an explicit no-mutation test rather than weakening the model. Shared 16 MiB history capacity is preflighted across both tables and V4 descriptors before decoding/allocation; maximum binary originals/proposals, explicit journal deletion and count-cap refusal have focused tests. + +Final frozen-source validation (existing Rust 1.99.1, offline and locked, no dependency fetch): + +- `python3 /rangoon-instruction-history-20261025/run-cargo.py test --offline --locked --workspace`: PASS; 651 logged test passes, including controlled subprocess results, eight harness-only ignored cases. The first sandboxed attempt failed at an unchanged host test's `UnixListener::bind` with `Operation not permitted`; the reviewed local-socket rerun passes. No network/provider target was contacted. +- `.../run-cargo.py test --offline --locked -p rangoon-store --features encrypted-sqlite`: PASS; 200 unit tests, 10 empty-encrypted integration tests, four encryption integration tests and two documentation tests. Ten harness-only tests are ignored by the ordinary runner; the new isolated history child is explicitly invoked and passes separately. The 25 new dedicated history tests (plus the separately invoked child) cover exact bytes/bounds, canonical malformed-input refusal, parser decomposition/revision split/merge/reassembly, encrypted reopen and three-key recovery, public plaintext-surface refusal, drift/unknown/fork refusal, shared capacity preflight, actual cap refusal before mutation, explicit event deletion, source/recipe/revision linkage, compatibility/stale previews, process restart and three killed-transaction checkpoints. +- `.../run-cargo.py clippy --offline --locked -p rangoon-store --all-targets --features encrypted-sqlite -- -D warnings`: PASS, no warnings. +- `.../run-cargo.py fmt --all -- --check`: PASS. +- `.../run-cargo.py check --manifest-path apps/desktop/Cargo.toml --offline --locked --no-default-features --tests`: PASS. +- `.../run-cargo.py check --manifest-path apps/desktop/Cargo.toml --offline --locked --no-default-features --features encrypted-workspace --tests`: PASS. Both desktop checks retain the pre-existing manifest warning that `main.rs` is shared by the binary and custom qualification-test targets. These are compile checks, not a GUI launch or new native qualification. + +History-aware inventory uses `rangoon.workspace-data.v3`, and restore previews use `rangoon.restore-plan.v3` whenever an input/result schema is 5, including empty history; literal V1–V4 v2 JSON remains unchanged. Tests also refuse a stale v3 retained restore preview without disk mutation. Earlier green evidence before the version and empty-schema corrections remains separately named `before-wire-version-*` and `before-empty-schema-*`; final checks are `*-verified.log`. The final recovery regression preserves schema 5 even after all history is deleted and when the selected destination is absent or initialized empty; the v3 retained plan exposes `targetWorkspaceSchema` and schema-only recovery remains transactional. Full Rust source hashes are frozen in `validation-source.json` and unchanged through final checks. + +Fresh independent review: PASS, no actionable P1/P2/P3, from the fresh read-only reviewer over the exact 18-path delta and final evidence. Review verified all 14 frozen Rust hashes, four final validator exits, compile checks, strict owned-path whitespace, current receipt counts and closed native/provider/publication scope. Review findings resolved: plaintext export/import isolation, shared-budget preflight, exact applied-recipe lineage fixtures without weakening orphan-record invariants, explicit v3 wire negotiation, and empty-schema-5 transactional recovery. Design/navigation and final source review use the configured OpenAI `gpt_reviewer` pin `gpt-5.6-terra`, xhigh. Bounded sibling source extraction uses configured OpenAI `gpt_reader` pin `gpt-5.6-luna`, medium. Root Codex controller is sole producer/integrator; its runtime model identifier is not exposed in this session. Configured worker pins were read from their role TOMLs; invocation responses do not expose an independent returned model ID. No GLM or workbench model/provider call was used. + +Exact changed paths (18; all other pre-existing dirt preserved): + +- `crates/rangoon-store/src/instruction_history.rs` +- `crates/rangoon-store/src/instruction_history_backup.rs` +- `crates/rangoon-store/src/instruction_history_tests.rs` +- `crates/rangoon-store/src/lib.rs` +- `crates/rangoon-store/src/composition_records.rs` +- `crates/rangoon-store/src/composition_backup.rs` +- `crates/rangoon-store/src/workflow_backup.rs` +- `crates/rangoon-store/src/workflow_backup_tests.rs` +- `crates/rangoon-store/src/workflow_recovery.rs` +- `crates/rangoon-store/src/workflow_mutations.rs` +- `crates/rangoon-store/src/workflow_deletion.rs` +- `crates/rangoon-store/src/workflow_saves.rs` +- `crates/rangoon-store/src/workflow_views.rs` +- `crates/rangoon-store/src/recovery_copy.rs` +- `docs/intent.md` +- `docs/target-loader-qualification.md` +- `docs/continue.md` +- `docs/development.md` + +Final scope: store-only AR-1/AR-2 source is implemented and source-tested. Native/renderer mounting, authoritative target selection/custody, Apply/Restore, explicit reconciliation after unknown, History UI, independent freshness/rollback anchoring and three-OS qualification remain open. Next packet is AR-3 native retained previews and encrypted recovery routing, with source acceptance and disposable rehearsals before normal target files. Commit/push/merge/deploy/release: none. HEAD stays `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; index stays empty. No normal data/keys/vault, target runtime, provider, LNSAT/VUSL edit or dependency fetch occurred. No renderer/native UI source changed, so no new rendered or native GUI result is claimed. + + +## BF-1 bulk agent-file workbench — October 26, 2026 + +Authority: Jeff requests a major UI overhaul for practical bulk agent-file management and advisory issue/outdated-method tags. Root owns native contracts/lifecycle/privacy, controller/integration and validation. A disjoint UI worker produced only the new view, scoped stylesheet and view tests; root integrated/refined focus, responsive behavior and authoritative boundaries. [Intent](intent.md#bf-1-bulk-agent-file-workbench--october-26-2026) and [experience contract](product-experience.md#bf-1-agent-file-workbench--october-26-2026) own scope. Initial branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; unrelated recovered work preserved. Exact owned paths/preimages/evidence: `/rangoon-bulk-files-20261026`. + +Technical delivery: scoped native `select_and_inspect_sources` accepts no renderer paths/content/options; fresh OS multi-picker selection uses existing per-file bounded validation, exclusive Gate admission, request identity, callback ownership/drain and read-only completion. At most 32 selected Markdown files and 4 MiB retained originals, with explicit per-item refusal and bounded overflow behavior. It does not replace native source-analysis selection. Renderer saved inspection reuses `read_composition_source`; startup metadata is reused instead of reloading it. Local rules are versioned advisory matches only. No storage/crypto/domain/protocol dependency or executor changes occur. Existing encrypted persistence, instruction history, composition/compiler/export and Skills editing stay separate. + +Experience delivery: Agent files navigation/page, compact source rows with local multi-selection, search/type/finding facets, 50-row paging and bounded scrolling, selected/saved occurrence context, single inspector, local findings, original text and closed technical details. Cancellation/total unread replacement keeps previous inspection; partial refusals stay visible. Filter-hidden/off-page context, selected-row versus marked-row distinction, 44px controls, caret/focus/list-scroll preservation and stacked-layout inspector/Back-to-files behavior are part of the same slice. The original 320px fixture placed the first row at 1,339px; compact/progressive controls bring the populated row region to about 916px in the final populated fixture (the earlier compact iteration measured about 881px) without document overflow. Larger screenshot captures can clip in this browser backend; geometry metrics and smaller captures are separate evidence, not complete wide visual proof. + +Follow-up metadata: native saved timestamps are visible alongside session-only selected/checked times, localized to seconds with UTC and exact epoch-ms date titles. Check observation uses a bounded injectable renderer wall clock, not trusted audit time; lock clears it. Refresh retains checks only for the same native source identity/digest/length. Filesystem modification dates are explicitly not collected. Details include line/fragment counts, analyzer version and source digest. Revision history is explicitly not linked: snapshots are not ordered revisions. The experience record specifies the next exact-target encrypted history mount using existing AR change/parent/input/outcome records; no new history store, filename-inferred chain or native write was introduced. + +Security/standards impact: new explicit user-selected local content read, no ambient crawl, network/provider/model call, filesystem write or credential/vault discovery. Native response includes original source text only for the explicitly selected batch; names are basenames, never renderer-addressable paths. Original files are unchanged. Temporary selected data and saved inspection are purged/fenced on lock; memory zeroization is not claimed. Advisory private-key/script markers may be examples and never execute or copy matched secrets into finding summaries. Missing version evidence yields Compatibility not assessed. The new Tauri ACL entry covers only the new scoped picker; no general file/dialog/shell/network permission is granted. No dependency/framework changes. Existing ISO/OpenSSF readiness applies to least privilege, bounded input, versioned diagnostics, lifecycle tests and evidence; no certification/badge/release readiness follows. + +Final source validation uses the existing pinned Rust 1.99.1 toolchain and populated offline dependency cache through `/rangoon-bulk-files-20261026/run-cargo.py`; no installation or dependency fetch: + +- `npm run build:check`: PASS, 534 JavaScript tests plus the repository syntax/visual/vision checks (`build-final-sealed.log`). Existing synthetic loopback tests require the reviewed sandbox exception; an earlier sandbox-only EPERM attempt is not passed evidence. +- `node --test tests/agent-files-model.test.mjs tests/agent-files-view.test.mjs`: PASS, 30 focused tests (`timestamp-focused.log`). They include separate date provenance, invalid clocks, no invented revision/mtime, escaped and accessible exact UTC values, startup failure propagation without duplicate reads, late-result purge, partial/all-unread/cancel behavior and paging. +- `.../run-cargo.py test --offline --locked --workspace`: PASS, 655 top-level test passes, eight existing ignored tests (`rust-workspace.log`). A separately spawned one-test child also passes and is not double-counted. This includes all five new collection tests and preserves existing domain/compose/compile/store suites. +- `.../run-cargo.py test --manifest-path apps/desktop/Cargo.toml --offline --locked --no-default-features --features encrypted-workspace --bin rangoon-desktop --lib`: PASS, native library 172 tests/one existing ignored, binary 542 tests/three existing ignored (`native-unit.log`). A one-test child process is separate evidence, not an additional top-level count. This command does not run the native GUI qualification harness. +- `.../run-cargo.py check --manifest-path apps/desktop/Cargo.toml --offline --locked --no-default-features --features encrypted-workspace --tests`: PASS (`native-check.log`). Existing warning: `main.rs` is shared by binary/custom qualification targets; no new compile error. +- `.../run-cargo.py clippy --offline --locked -p rangoon-host --all-targets -- -D warnings`: PASS (`host-clippy-final.log`). +- `.../run-cargo.py fmt --all -- --check`: PASS (`fmt-final.log`). Exact owned delta whitespace check and frozen-source hashes belong to the final seal. + +Actual browser QA uses `node scripts/qa-agent-files.mjs`, bound to loopback with an explicitly synthetic transport and no Tauri/native/user data. The real renderer handles 128 saved metadata rows plus three chosen files with 50 rows per page. Search, facets, marks and paging remain local; query caret and page-status keyboard focus survive rerenders. A held first read proves the mixed 50-mark selection truthfully checks only 47 saved records, focuses Cancel, and stops at zero completed after one callback drains. Picker cancel and failed reload preserve all 131 prior records. A failed startup inventory now displays the native public error without duplicating the startup read. Confirmed Lock removes all file rows/dates; empty and native-unavailable states remain honest. Stacked selection focuses/reveals the inspector and Back to files returns to the library. Exact observations: `browser-interactions-final.json`. + +Final geometry (`browser-metrics-final.json`): actual CSS viewports 320×900, 768×900 and 1440×900, each light/dark; document scroll width equals client width in all six cases. Controls measure about 44 CSS pixels (43.995 due device-scale rounding), list height about 432px, exactly 50 rendered rows. Visible row dates measure about 14px high, outside the screen-reader-only label. Wide captures can be backend-clipped, so `agent-files-final-wide.jpg` proves only its returned visible region; geometry evidence is separate. Forced-color/reduced-motion branches are source-checked, not qualified under an emulated OS setting. Screen-reader/real touch and native three-OS GUI remain future qualification. Independent review identified the initial intent wording as stronger than this evidence; the intent now explicitly separates source-level media-rule checks from pending actual OS-mode qualification. No accessibility or shipping gate is waived. + +Pure render measurement (`performance.json`, Node v24.21.0): 160 metadata records, 50 rendered rows and a 256 KiB inspector, 100 warmed iterations: median about 4.87ms, p95 about 5.73ms. This measures HTML generation only, not DOM paint, file read latency, live provider load or million-request throughput. No broad performance claim follows. + +Independent review covers the exact owned delta from preimages, not unrelated changes against HEAD. Source and UI reviewers use configured OpenAI `gpt_reviewer`/`gpt_ui_review` pins `gpt-5.6-terra`, xhigh; initial design/worker use configured `gpt_ui_design`/`gpt_worker` pins `gpt-5.6-terra`, high. Root Codex owns native/protected implementation and integration. Role TOMLs were checked; returned invocation model IDs are not exposed, so these are configured pins. No GLM or workbench model/provider call occurred. Final verdicts are recorded in `review-seal.json`. Resolved review/QA findings include stale navigation fixtures, all-unread replacement data loss, deterministic focus return, pending-check keyboard focus, explicit saved-only check count, row dates accidentally nested in a screen-reader-only label, and startup-error propagation. This does not qualify normal data use. + +Exact changed paths (21; two additional allowed paths stayed unchanged): + +- `preview/agent-files-model.mjs` +- `preview/agent-files-view.mjs` +- `preview/agent-files.css` +- `tests/agent-files-model.test.mjs` +- `tests/agent-files-view.test.mjs` +- `preview/analyze.mjs` +- `preview/analyze.html` +- `preview/workbench-navigation.mjs` +- `preview/workspace-lock-model.mjs` +- `tests/workbench-navigation.test.mjs` +- `apps/desktop/src/source_collection.rs` +- `apps/desktop/src/main.rs` +- `apps/desktop/build.rs` +- `apps/desktop/capabilities/source-analysis.json` +- `crates/rangoon-host/src/source_collection.rs` +- `crates/rangoon-host/src/lib.rs` +- `docs/intent.md` +- `docs/product-experience.md` +- `docs/continue.md` +- `docs/development.md` +- `scripts/qa-agent-files.mjs` + +All pre-existing non-generated source outside ownership remains byte-identical. Desktop compilation regenerated four ignored Tauri schemas under `apps/desktop/gen/schemas`; these are excluded generated artifacts, not authored/staged source. The pre-existing mixed working tree remains dirty. Index remains empty; HEAD remains `c132ea62bc57b29375ee8c5a3a38ca005462ca40`. No commit, push, merge, deploy or release. + +Next stage: qualify explicit multi-file native intake using disposable files, then selected-root inventory with retained root identity and target-bound encrypted revision/history read models. Persistent tags, authoritative target Apply/Restore, outdated-method catalog, folder discovery and runtime orchestration remain incomplete. No normal data/keys/vault, provider, foreign repository edit or dependency fetch occurred. + + + +## Remote setup management direction — October 26, 2026 + +Authority: Jeff requires remote setup management after BF-1 and timestamp/revision work. RM-0 accepts a bounded six-document architecture/experience reconciliation, not a remote service or source/operational packet. Producer: root Codex, architecture/integration/privacy owner; runtime model ID is not exposed. The [accepted intent](intent.md#remote-setup-management-direction--october-26-2026), [canonical architecture](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) and common fleet console own scope. Startup: `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, 200 dirty status entries, empty index. Exact preimages/source baseline: `/rangoon-remote-direction-20261026`. + +Reconciliation: existing architecture already defines enrolled targets, scoped adapters, deployment readback, shared management state and independent engines. BF-1 is local-only; I1 is offline evidence metadata; OpenShell's product-specific finite-read source is not a remote filesystem bridge; encrypted AR history is not mounted remote history/target Apply/Restore. This packet introduces no alternate registry, protocol, database, executor or source implementation. It specifies host/root-scoped bulk file metadata and explicit content inspection; distinct native/received/saved/check times and lineage; eventual encrypted target-bound changes/recovery; honest freshness/support/session errors; no shell/network scan/ambient credentials and no mandatory LNSAT/GUI on hosts. Proposed RM-1 is an exact six-path unmounted fixture model/test packet; later RM-2 separately qualifies one enrolled disposable host, while remote mutation reuses AR-3/S3. + +Experience: one shared Systems/fleet inventory, host detail with Files, History, Tasks and Configuration/Access, existing compact table/inspector, explicit local/remote context, offline cache/unknown states, per-host outcomes and progressive technical details. No new page, connection control, fake fleet data or live UI has been added. Remote adapters and authenticated transport are not implemented; actor/target scopes, custody, per-operation compatibility, content/cache consent and retention remain exact implementation decisions. + +Security/standards impact: documentation only, no new data handling, dependency, permission, socket, credential or persistence. The plan applies least privilege, explicit enrollment/peer identity, root confinement, bounded/untrusted input, encrypted history/caches, revocation, traceable provenance and uncertain-write reconciliation. OSPS/ISO/OpenSSF build requirements remain scoped engineering targets, not certification. Transport, key custody, actual remote OS confinement and privacy treatment need source and disposable operational proofs before support. Local encrypted and three-OS release gates remain; no infrastructure prerequisite is added to local release. + +Changed paths: `docs/intent.md`, `docs/application-architecture.md`, `docs/operations-control-plane.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. Preserve all other dirty source and BF-1 changes. Named validation: `node scripts/validate-review.mjs`, `python3 /scripts/validate_artifact.py docs/intent.md`, local Markdown target/anchor verification, exact preimage-delta whitespace and out-of-ownership source identities. Functional/Rust/native/rendered/remote tests are intentionally not rerun for this docs-only packet; prior receipts are historical source evidence, not new remote proof. Final command results, frozen hashes and fresh independent review disposition belong to the packet seal. + +Final RM-0 checks: PASS `node scripts/validate-review.mjs` (619 authored text files, eight reference image hashes, historical brief and local Markdown targets); PASS intent artifact validator; PASS nine added local link/anchor checks and exact owned-delta whitespace. Fresh independent read-only architecture review: PASS, no remaining P1/P2/P3 after correcting wording that could imply an implemented fleet registry/R9 adapter. Reviewer: native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra`, xhigh; returned model ID is not exposed. No GLM call. Six owned hashes and exact diff are frozen in the packet evidence; `review-seal.json` records final disposition. + +Concurrent out-of-packet changes appeared in `README.md`, `crates/rangoon-integrations/src/lib.rs` and `docs/lnsat-evidence-connector.md`. They were not edited or reverted by RM-0; preservation proof records these exceptions rather than claiming the whole mixed tree remained byte-identical. No unexpected new path or staged file is attributed to this documentation slice. + +Remote workflow/first OS and transport remain open choices. Default proposed first value is remote agent-file inventory/revision review, not autonomous fleet execution. No real host contact, enrollment, credential/vault/key access, normal data, provider, infrastructure change, dependency fetch/install, LNSAT/VUSL/other repository edit, commit/push/merge/deploy/release. + ## Offline LNSAT request-record decoder — October 26, 2026 Authority: Jeff directly accepted the reviewed decoder, bounded synthetic tests and independent GPT review. Canonical source evidence is `/private/tmp/rangoon-request-record-source-20261026`; the accepted preparation remains `/private/tmp/rangoon-request-record-decoder-preparation-20261025-VMBBo0`, using spec_03, OUTPUT_CONTRACT_02, NATIVE_FIELDS, NATIVE_RULES and matrix03. Repository branch/base is `codex/personal-workbench-20261024` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; substantial earlier uncommitted work is preserved. This packet owns only new decoder/test files, the exact module declaration, and additive README/connector/ledger text. No publication or runtime authority follows. @@ -3951,33 +5739,39 @@ Earlier syntax/type errors, test borrow failure,33/36 first behavioral result an Producer: primary Codex integration plus native OpenAI gpt_worker roles configured gpt-5.6-terra/high for disjoint implementation/test drafts. Reviewer: fresh native OpenAI gpt_reviewer configured gpt-5.6-terra/xhigh, backend runtime model ID unexposed. Independent source/test review is PASS; the final document readback is recorded separately. No GLM/external-provider source transfer, commit, push, PR, merge, install, target Git/runtime, host/VM/native/archive operation, deploy or release occurred. Next work remains separately scoped; no automatic promotion to connected operation. +## Rangoon peer-installation file access clarification — October 26, 2026 -Final source/test qualification: independent native OpenAI GPT reviewer PASS with no actionable P1/P2/P3 on source1365148451d70c35afc01491078e0b8b5c9ab2c7eb506082d933ac921d720b40 and testea65867f1c8e562bb9894d8a90348df720519b12445e5e58c722dd3170b0bc8c. Review's P2 exposed incomplete S31 byte-oracle coverage; the corrected independent serializer now compares full host/summary bytes for all variants and a full graph, nested field/value/order mutations, and all13 fixed errors. The initial reference-oracle count/evidence-shape error is preserved. Final tests10 passes36/36, strict Clippy04 and owned-format02 pass. The unchanged45 package regressions reuse tests04; there are81 unique tests, not accumulated repeated counts. Document-only final readback is separate; source/test/review evidence does not open L01–L06 or runtime. No current packet publication occurred. +Authority: Jeff clarifies that other installations of Rangoon provide remote file access. This narrows RM-0's product topology, not its source/operational scope. Root owns the same six documents: `docs/intent.md`, `docs/application-architecture.md`, `docs/operations-control-plane.md`, `docs/product-experience.md`, `docs/continue.md` and this receipt. Start: branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, 203 dirty entries, empty index. Exact preimages/baseline: `/rangoon-peer-direction-20261026`. The [canonical remote section](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) owns the corrected mechanics; prior RM-0 receipt retains its dated broader alternative. -## Request-record decoder publication — October 26, 2026 +Primary topology is controlling Rangoon installation → restricted service in sharing Rangoon installation → host-selected roots and permitted operations. Headless is a future mode of that same host service, not an independent bridge product. Optional third-party system adapters remain separate. Sharing defaults off; owner-selected roots plus per-peer and actor grants, distinct list/content/write scopes, expiry/revoke, lock/admission fencing and no transitive trust apply on the sharing host. Authentication alone or a controlling user's local-admin status grants no file access. No raw Tauri IPC, shell, database or keys are exposed. Peer history remains host/target scoped; independent encrypted stores and keys stay local. Revocation cannot recall plaintext already disclosed, and unattended access needs separate service/custody qualification. -Jeff separately authorized committing and pushing only the reviewed decoder slice, opening a PR and hosted source CI; merge, live reads, reconciliation, local installs and product/target runtime remain closed. Publication is isolated from the dirty worktree on public main `9bd9be17d17fd8f778ec88f8e9b9f41df5c01dc4`. Only the two decoder files, one module declaration and their README/connector/development additions are selected; the publication compatibility delta is recorded below. No D3a, dependency, toolchain or workflow change is included. Earlier Rust 1.99.1 fixture evidence is dated and conditional; public main still selects Rust 1.85.0 for core CI and 1.98.0 for desktop. Hosted exact-candidate results remain pending. No previous green source result establishes this candidate or runtime compatibility. Private publication receipts: `/private/tmp/rangoon-decoder-publication-20261026`. +Experience has explicit Share files controls on the host and Add Rangoon system/access review on the controller. Files, History, Tasks and Configuration remain planned host detail views; no live-looking page, socket, pairing, grant persistence, host-service backend or remote file operation is implemented. RM-1 now includes installation/principal/grant identity in its offline contract proposal; RM-2 must qualify two disposable Rangoon installations before a support claim. Same local-release, encrypted recovery, optional-engine and no-executor boundaries hold. + +Security/standards impact is clarified least-privilege ownership and peer/actor distinction in documentation only. No data/keys/vault, credential, dependency, UI/source behavior or privilege changed. Named validation: documentation/reference validator, intent artifact validator, added link/anchor and exact-delta whitespace checks, frozen owned hashes and preserved/unrelated-change proof; fresh independent read-only architecture review. Functional/native/remote/GUI tests are not rerun for wording/design-only changes and no such qualification is claimed. Producer: root Codex; model ID not exposed. Documentation/reference validation passes 621 authored text files, eight image hashes and the historical brief; the intent validator, three added link/anchor checks and exact-delta whitespace also pass. Independent reviewer: native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra`, xhigh; returned model ID not exposed. No GLM call. Final current-hash/review disposition and concurrent-path exceptions belong to this packet's `review-seal.json`. + +Remote sharing remains unimplemented. No host contact, normal data/key access, infrastructure/provider operation, external repository edit, install/fetch, commit/push/merge/deploy/release. Existing concurrent work remains untouched. + +Final source/test qualification: independent native OpenAI GPT reviewer PASS with no actionable P1/P2/P3 on source1365148451d70c35afc01491078e0b8b5c9ab2c7eb506082d933ac921d720b40 and testea65867f1c8e562bb9894d8a90348df720519b12445e5e58c722dd3170b0bc8c. Review's P2 exposed incomplete S31 byte-oracle coverage; the corrected independent serializer now compares full host/summary bytes for all variants and a full graph, nested field/value/order mutations, and all13 fixed errors. The initial reference-oracle count/evidence-shape error is preserved. Final tests10 passes36/36, strict Clippy04 and owned-format02 pass. The unchanged45 package regressions reuse tests04; there are81 unique tests, not accumulated repeated counts. Document-only final readback is separate; source/test/review evidence does not open L01–L06 or runtime. No current packet publication occurred. -Publication integration found the reviewed decoder used unsigned `is_multiple_of` (stable since Rust 1.87) although public core CI selects Rust 1.85. Only the leap-year expression was replaced with equivalent remainder comparisons against the same fixed nonzero divisors 4, 100 and 400. The original reviewed source remains preserved in its private packet and dirty checkout. Test bytes and wire/output behavior are unchanged; the corrected publication source requires separate Rust 1.85 validation and independent delta review before publication. No CI pin, workflow, dependency or D3a changes are included. -Current publication validation: the existing Rust 1.85.0 tuple passed all 78 package tests (19 library, 11 unchanged public-base D3a, 36 new decoder and 12 OpenShell), zero failures/ignored, through locked offline Cargo. The earlier 81-test source receipt includes three unrelated dirty-worktree D3a tests and is not the public-base regression count. Strict package all-target Clippy02 passes with warnings denied. Clippy01 correctly rejected one needless explicit implementation lifetime; replacing `impl<'a> Parser<'a>` with `impl Parser<'_>` is the second compatibility-only line change. No lint exemption was added. Workspace Rustfmt01 and document/reference checks (469 authored files, eight image hashes and historical brief) pass; the final exact-source format/readback and independent integration review are recorded separately. Existing source reviews are reused for the unchanged decoder/test behavior; historical receipts and failed attempts remain preserved. +## CU-1 contextual composition UI — October 26, 2026 -Publication integration qualification: final Rust 1.85 package tests02 passed 78/78; strict all-target package Clippy02, final workspace Rustfmt02, scoped whitespace and document/reference validation passed (469 authored text files). Fresh independent native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra/xhigh`, reviewed the six-path integration and exact two-line compatibility delta: PASS with no actionable P1/P2/P3. Backend runtime model ID is unexposed. No source/test/dependency/workflow bytes changed after those checks. Hosted source CI and publication outcome remain separately pending; no merge or runtime authority follows. +Authority: Jeff requests continuing the UI overhaul for intuitive modification and combination. This is an eight-path renderer/UI source packet under [accepted CU-1 intent](intent.md#cu-1-contextual-composition-interaction--october-26-2026). Root owns implementation/integration and native-boundary judgment; a read-only UI design agent recommended the selection-to-recipe rail. No code-writing subagent was used. Startup: branch `codex/personal-workbench-20261024`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, 203 dirty entries, empty index. Exact preimages, diff, validation logs and seal: `/rangoon-composition-ux-20261026`. -## Offline request-record inspection boundary — October 26, 2026 +Experience delivery: analyzed-section shortcuts or exact read-only text selection, a source/destination inspector, primary Assign and closed More operations. Existing placements are explicitly reassigned; Duplicate keeps both. Reason/replace/exclude/conflict remain deliberate. The action rail is above original text, initial source height is about 252px at 900px viewport height, locked-input heading describes actual saved inputs and coverage uses plain Source coverage. Starting a draft focuses/reveals input selection; quick selection preserves its invoking section focus. Global local notices stay in the active view. The [experience record](product-experience.md#cu-1-contextual-editing-and-combination--october-26-2026) owns detailed behavior and next-module direction. -Authority: Jeff directly accepted implementation of the reviewed offline inspection contract, synthetic tests, docs and independent GPT review, preserving D3a and excluding live reads, reconciliation, installs and real runtime. Canonical private source evidence is `/private/tmp/rangoon-offline-request-record-inspection-source-20261026`; the frozen reviewed preparation remains `/private/tmp/rangoon-offline-request-record-inspection-contract-20261026`. Preparation-only labels are dated history, superseded only for this exact pure source/test slice. Publication, native/UI adoption and later operational gates remain closed. The new isolated branch starts from then-verified public main `0e78b1d7dcb45f6e01a36b5c1559d839afbfdbaf`, preserving the prior publication branch and unrelated dirty checkout. +Technical delivery: same controller, exact source/revision references, native UTF-8/CRLF byte mapping, Undo/Redo, preview/ack/save and Rust validation. Quick/manual/same-source-return selection updates contextual DOM without replacing the editor. Destination/disclosure and live fields persist across normal route disposal, which now captures the live form before detach. Range-bound advanced drafts reject cross-range reuse and spoofed programmatic disabled-button dispatch; Return/Cancel recovers without data loss. Local reason validation focuses the field and restores the original textarea span before retry. Successful recipe changes clear selection; pending native preview disables actions; lock clears state/DOM/cache and fences late results. The inspector uses a UTF-8 boundary scan and a maximum 160-code-point excerpt without full-span decode, and byte-to-textarea offset mapping avoids per-code-point encoder allocations. Existing proportional controller mapping/cloning costs remain; these helpers are UI presentation and cannot authenticate content or decide native saveability. -Experience track: one offline inspection, summary-only fixed labels/counts, explicit Discard and honest pending/closed states. No rendered view, accessibility, keyboard, responsive or native UI qualification is supplied. Technical track: the pure host lifecycle/projection module implements the 28 reviewed source/synthetic/structural obligations using the existing pinned decoder without changing D3a or O1/O2. Current-candidate validation and source review are recorded below; earlier decoder CI is not evidence for this new module. +Security/standards impact: no new IPC, API, permission, key/credential, persistence, network, provider/model, plugin or dependency. Existing originals are displayed locally and remain escaped/read-only; selected excerpts stay local memory and are bounded, not logged. Exact range identity and unfinished-field binding reduce wrong-target user edits; no fuzzy authorization. Lock/cache lifecycle remains mandatory; memory zeroization is not claimed. ISO/OpenSSF build targets apply to bounded untrusted input, least privilege, deterministic regressions and evidence, not certification or native release. Remote peer sharing remains planned. The synthetic QA fixture never imports Tauri, contacts a provider or supplies a successful native preview/save. -Security/standards impact: sensitive input, full selection, native correlation fields, decoder host output and digest remain host-owned. Only a strictly closed summary or fixed error may reach a cooperating presenter; summary is not anonymous or accepted for storage. No persistence, diagnostics/model transmission, plaintext fallback, key/vault access, dependency, build privilege, workflow or authority change is included. Logical owned release and purge acknowledgment do not establish zeroization, native callback drain, authenticated ingress, hostile-process containment or supply-chain provenance. Applicable existing ISO/OpenSSF/OSPS/SLSA readiness work is bounded input/privacy/ownership documentation, positive/negative synthetic obligations, pinned source, named validation, fresh review and explicit gaps. No badge, score, certification, maturity/level or organizational compliance is claimed. Jeff owns separately accepting later source/native/UI/operational work and release-wide evidence; the controller owns current packet integration and the independent GPT owns review judgment only. +Named checks: focused `node --test tests/composition-view.test.mjs tests/composition-model.test.mjs` passes 47 tests; full `npm run build:check` passes 544 JavaScript tests plus syntax/visual/vision checks in the current run. Final freeze rerun and documentation/reference, intent, exact added-link/whitespace, owned/unrelated-source checks belong to the seal. No Rust/native tests rerun because no controller/contract/Rust/native/storage changes occur; prior source/native receipts remain separate. Source and UI reviews are fresh and read-only; final current-byte verdicts belong to `review-seal.json`. -Current validation scope selects the existing Rust 1.85 toolchain explicitly through rustup, locked/offline package tests and strict package all-target Clippy, workspace Rustfmt and document/reference checks. No installation/download or dependency-cache copying/import is permitted. Conditional trusted controller fixtures cannot prove installed runtime, physical clocks/deadlines/custody/durability/cleanup, three-OS GUI support, actual LNSAT consequence, Phase 11 or full functional readiness. All six later acquisition/renderer/workspace/native/connected adoption groups remain NOT_RUN. +Actual browser QA uses `node scripts/qa-composition-interaction.mjs` with the real renderer/controller and explicitly synthetic transport. Decompose selects the 144-byte golden source's 28–87 byte Review section, retains Output 3, validates missing reason, refuses applying A's replacement to B, returns to A, replaces and undoes. The ordinary Decompose → Skills → Decompose route restores reason/replacement/output/disclosure/range. Keyboard selection extends the current exact span while retaining source focus. Held preview disables actions; a synthetic refusal leaves Save disabled and Preview required. Merge chooses two distinct synthetic pinned revisions, starts one output, switches to input 2 and inspects its exact 0–25 byte range/destination. Confirmed Lock during a held merge preview removes composition/source fields and fixture original from application DOM; releasing the late response does not revive the page. These are renderer/controller outcomes, not native save/recovery evidence. `browser-interactions.json` records observations. -Current source: `lnsat_request_inspection` owns move-only input/completion custody and a non-Clone host with serialized mutable commands. A private original-instance/view/owner binding and terminal generation fence prevent late or foreign work from publishing. A borrowed presentation lease excludes mutation of that host while used. Discard clears the retained projection immediately but retains exact owner accounting until input/context/result release; final state also requires the current opaque purge-ticket acknowledgment. Repeated pending Discard cannot allocate a replacement purge after observing final release, and Close cannot reopen. The first API is pure; acknowledgment is a cooperating caller's report, not authenticated IPC or physical erasure. Caller copies and native/renderer caches are outside this source proof. +Final geometry in `browser-metrics-final.json`: CSS 320×900, 768×900 and 1440×900 in dark/light, all six document widths equal client widths; visible controls approximately 44px (43.995px device rounding); source remains read-only, three quick section controls, advanced operations closed by default. The primary action is around 683px from document top at 1440×900, versus below the initial viewport in the earlier iteration. Narrow views stack and require vertical scrolling; this is not a claim all controls fit one screen. `composition-final-light.jpg` is the final rail-above-text capture; earlier wide image is superseded. Large captures may be backend-clipped, so geometry evidence is separate. Actual OS reduced-motion/forced-colors, screen reader/touch and native GUI remain unrun. The managed synthetic harness can abort same-tab reload/navigation during its close lifecycle; fresh documents were used, and no reload qualification is claimed. -Final source-candidate checks: existing Rust 1.85.0, locked/offline `tests-02`, passed 110 distinct Rust tests (32 library = 19 inherited plus 13 new, 11 D3a, 19 new inspection integration, 36 underlying decoder and 12 OpenShell), zero failures/ignored, plus one borrow compile-fail doctest. The new inspection evidence is 32 tests plus one compile-fail check; 28 contract obligations are mapped across these and named preservation checks, not 28 physical executions. Strict all-target package Clippy02 and workspace Rustfmt-check01 passed. Test repetitions across earlier candidates are not additional unique tests. Twelve separately reviewed mocked controller-helper guards passed under optimized isolated Python; they are metadata/process-port models, not physical process-containment proof. The first full source candidate and changed-oracle unit/integration successors also passed, but final qualification uses current exact candidate04. No local or target dependency install/download or cache copying/import occurred; existing cache was used in place. Tools and linked platform inputs remain conditional controller inputs, not authenticated loaded-code or supply-chain proof. +Pure helper timing is recorded in `excerpt-performance.json`: 4 MiB synthetic source, 20 warmed iterations, at most 160 code points plus ellipsis. It excludes existing controller clone/selection mapping, HTML generation and DOM paint; no overall large-file, live-system or million-request throughput claim follows. The 4 MiB, astral-boundary, malformed-byte, no-rerender, range-switch refusal, field-loss, cache/purge and retry cases have dedicated regressions. Review corrections also moved the primary rail above the original, restored the actual selected textarea span after validation, and made reassignment semantics explicit. -Independent native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra/xhigh`, passed the corrected exact source/test chain with no open actionable P1/P2/P3. It closed two P2 oracle gaps (six unavailable failure labels and nested escaped duplicates) and a P3 post-close admission gap. Strict Clippy01 had failed two private enum-name warnings; the private type rename preserves serialized variant names and behavior, adds no allowance and passed exact delta review. Primary Codex integrated and strengthened initial native GPT worker source/tests; worker configured `gpt-5.6-terra/high`. Backend runtime model IDs are unexposed. All available draft, rejected helper and review snapshots, failed Clippy01 and the explicitly retracted helper-review observation remain in the private packet. Initial weak combined test names were rejected before any execution; they are not coverage evidence. Initial setup/ref/tool-dispatch and preparatory formatting/metadata failures are recorded separately. Document/reference, scope/preservation and final independent actual-evidence records belong to the same canonical private source packet; no hosted CI or publication is claimed. +Exact changed paths: `preview/composition-view.mjs`, `preview/composition.css`, `tests/composition-view.test.mjs`, `scripts/qa-composition-interaction.mjs`, `docs/intent.md`, `docs/product-experience.md`, `docs/continue.md`, `docs/development.md`. Preserve all existing/concurrent dirt; exact exceptions are recorded in preservation evidence. Producer/root Codex runtime model ID is not exposed. Read-only design role `gpt_ui_design` and fresh source/UI roles `gpt_reviewer`/`gpt_ui_review` use configured OpenAI `gpt-5.6-terra` high/xhigh pins; returned model IDs are not exposed. No GLM call. -The accepted preparation remains byte-frozen. Existing decoder, D3a and O1/O2 source/tests/profile, dependencies, lockfiles, workflow and toolchain files are protected; all other checkouts and unrelated work remain untouched. Real collection/selector entry, renderer/IPC and purge authentication, workspace lock/close mounting, native failure/allocator cleanup, connected reads and the six adoption groups remain unqualified and unrun. No source CI, synthetic marker, checksum or reported acknowledgment grants LNSAT authority, installation/runtime compatibility, zeroization, support, release or full functional readiness. This source/docs packet is uncommitted and grants no push, PR, merge or later operational authority. +Unfinished: whole-application redesign, native personal-file/picker qualification, actual media/assistive/touch modes, peer enrollment/service/grants, target-bound History UI and native Apply/Restore remain open. Next apply the same coherent pattern to Skills/Workflows and finish disposable native workflow validation before normal data. No normal data/keys/vault, native app/target/provider, external repository edit, dependency install/fetch, commit/push/merge/deploy/release. diff --git a/docs/encrypted-workspace.md b/docs/encrypted-workspace.md index 7a08db7..4e8b4e4 100644 --- a/docs/encrypted-workspace.md +++ b/docs/encrypted-workspace.md @@ -2,6 +2,665 @@ Authority: the accepted local-first V1 objective and Jeff's October 7 request to address database encryption in [intent.md](intent.md). This specification refines storage confidentiality without changing domain identities, authority semantics or the accepted three-desktop release target. Current evidence and acceptance belong only in [development.md](development.md). +Current source checkpoint: E1d-2 below adds native encrypted recovery to the accepted E1c-5c native/renderer path. The latter is now mounted with the existing encrypted feature selected by default and no Legacy fallback in an explicit no-backend build. [The mounting receipt](development.md#e1c-5c-encrypted-default-native-and-renderer-mounting--october-19-2026) owns exact source, tests, independent review and remaining native/platform qualification. Earlier proposed/unmounted descriptions below preserve their design baseline; they do not establish current release or normal-data migration status. + + +## E1d-2 native SQLCipher recovery copy — October 25, 2026 + +Status: implemented source and selected disposable macOS native recovery evidence recorded under Jeff's explicit request. The [development receipt](development.md#e1d-2-native-encrypted-recovery--october-25-2026) owns validators and independent-review status. Dependency promotion is resolved by reusing the existing pinned SQLCipher backend. The unpublished age experiment is now standalone historical source outside active builds. No compatibility reader/converter is promised for it. No new cipher, KDF, helper process or runtime crypto dependency is introduced. + +Recovery profile `rangoon.recovery.sqlcipher.v1` is a raw SQLCipher 4.14.0 encrypted workspace image with the existing 4096-byte/full-header/HMAC profile, Rangoon application ID and supported canonical schema. A separate random 32-byte raw recovery key is stored only after explicit native selection in an owner-only, single-link regular key file: `RANGOON-RECOVERY-KEY-V1` plus LF, 64 lowercase hex characters and LF. File custody checks enforce POSIX owner/mode and link/identity rules; inherited ACLs, shared/network filesystems and other storage media need separate qualification before broad adoption. The selected native proof uses a private local folder. The key file is itself unencrypted: protect it like a password and keep it separately from backups. Anyone holding both files can read the backup; losing the recovery key makes that backup unusable. It is neither a database/provider key export nor a renderer payload. Unknown profiles fail closed; future compatibility needs an explicit qualified reader, not guessed settings. + +The trusted host captures an exact complete logical source backup through Owner. A fresh 0700 OS-temp staging directory holds only an encrypted canonical workspace rebuilt with the existing strict empty Restore and a separate recovery key. Retain directory identity/ownership and reject replacement; cleanup only known files. Reopen read-only, verify the existing SQLCipher per-page HMAC/profile/schema/domain checks, exact physical file length equal to page_count × 4096, no sidecars and complete canonical logical archive equality. Counts alone are insufficient. Private staging is not a host-root/same-user-malware confinement guarantee. No plaintext staging file or new logical-backup parser is used. + +Native encrypted export rechecks source freshness, exclusively creates a selected `.rangoon-encrypted` file, syncs, rereads that selected ciphertext through another fresh private stage and compares its full logical content before reporting verified success. Source bytes stay unchanged. Wrong keys, malformed images, trailing bytes/pages, sidecars, collisions, source changes, cleanup failure and cancellation/close after a possible write cannot produce a false success. An output/key file may remain after uncertainty; never overwrite it or silently retry. Selected inputs are copied as bounded ciphertext, never opened writable. + +Three new workspace-scoped native commands create a recovery key, export an encrypted backup and prepare encrypted Restore. They accept no renderer key/path/content. Existing retained Backup/RestorePlan, generation, expected state and one-shot confirmation still own destination commit. The ordinary restore path preserves every canonical record into a truly empty destination; nonempty destinations retain their existing additive merge and conflict rules. The current registered workspace request header routes all three commands through the existing bridge and Gate. Bad recovery input is a host input failure, not evidence the current destination database is corrupt. Key-loss recovery uses a fresh encrypted destination with a different database key; no key replacement or reset decrypts the original. + +Loaded inventory adds advisory `encryptedRecoverySupported` from the actual native backend. Legacy is false; Managed is true only when the encryption/private-key-file implementation is available. Absence or malformed metadata disables modern controls. Native commands recheck support before RNG, pickers or filesystem access. Windows remains unavailable until owner-only key custody is implemented/qualified; Unix source and selected macOS qualification do not assert a Linux GUI pass. + +The simple UI offers Back up workspace and Restore backup. Backup explains the separate secret key file, offers Use recovery key or Create recovery key, and retains the dialog after key creation/cancellation. More recovery options contains explicit older plaintext backup import with its warning. Crypto failure never falls back to that path. No secrets enter the workbench, Advanced details, tooltips or logs. Progress reflects actual asynchronous work. Original instruction files and deliberately readable instruction exports remain outside recovery-image confidentiality. + +The simple and advanced disclosures distinguish encryption at rest from an unlocked or compromised host, original files and readable instruction exports. Ciphertext integrity establishes neither authorship nor local review, approval or execution authority. No sender authentication, rollback prevention, complete memory erasure, certification or three-OS release claim follows. + +Exact source ownership, API/DTOs, lifecycle, negative cases and validators are frozen in the evidence contract `/rangoon-e1d2-native-recovery-20261025/contract.md`; the development receipt owns results. Root owns store/native paths and reviewers remain read-only. Required proof spans full-history equality, wrong-key/tamper/trailing/sidecar and keyfile custody refusal, cancellation/drain, source preservation, selected-output reread, fresh destination/different key and independent macOS UI/custody evidence. No normal data/key, provider, engine, foreign repository, publication or release gate opens. + + +## E1d portable encrypted recovery — October 25, 2026 + +Historical E1d-0/E1d-1 baseline: the offline experiment is preserved, but it is not an active native backup contract. E1d-2 above owns current SQLCipher recovery; no age reader, converter or dual-profile promise is mounted. The development ledger owns dated evidence. Earlier descriptions of the desktop default below retain their historical context; the October 24 native receipt records the newer bounded encrypted macOS journey, not ordinary-profile migration or three-OS release qualification. + + +### E1d-1 experimental codec profile — October 25, 2026 + +The following dated source packet refines the E1d-0 candidate below for a synthetic, unmounted experiment only. Jeff's current continuation and [intent record](intent.md#e1d-1-experimental-codec-continuation--october-25-2026) define its exact ownership and validation acquisition scope. Age 0.12.1 is rejected for this experiment after its resolved P-256/HPKE path introduced crypto-bigint 0.5.5 under RUSTSEC-2026-0387; this is a dependency finding, not a proven exploit through the proposed X25519 API. The source pin is `age = "=0.11.5"` with `default-features = false`, plus existing `zeroize = "=1.9.0"`. It avoids that dependency path, but retains beta/testing-only status and unmaintained compile-time dependencies. Native/production promotion remains blocked. Age's 128-bit file key is not an AES-256 or post-quantum claim. + +Freeze a private in-memory profile: standard binary age v1 outside; encrypted `RANGOON-RECOVERY-V1` plus LF followed by opaque existing backup bytes inside. `RecoveryIdentity::parse(Zeroizing)` accepts only an explicitly supplied bounded X25519 identity and has redacted Debug, no Serialize or Clone. `RecoveryIdentity::recipient()` returns a public `RecoveryRecipient`; its parser accepts only bounded X25519 public text. `encrypt(&[u8], &RecoveryRecipient)` returns ciphertext; `decrypt(&[u8], &RecoveryIdentity)` returns `RecoveredBackup`, a private zeroizing owner exposing only a borrowed backup slice and redacted Debug. No library key type, public streaming reader, secret reveal, filesystem, process, network, vault or discovery API is exported. Logical archive validation is not performed by this codec; the existing store validator remains required later. + +Limits are 68 MiB backup plaintext, 69 MiB ciphertext, 4,096 bytes of header and eight stanza starts before library parsing. Encryption uses one supplied recipient. Decryption uses only the supplied identity; unknown stanzas may be ignored by the format library inside those limits without executing handlers. Successful decryption does not prove that no other recipient exists. Retain all authenticated chunks privately until the final chunk and EOF pass, then check the encrypted inner-version prefix before returning a borrowed body. Unknown versions, wrong identity, tamper, truncation, trailing/concatenated data and size-limit violations never expose partial plaintext. Public errors are fixed `TooLarge`, `Unsupported`, `InvalidOrUnreadable` and `Unavailable`, without raw library messages or source chains. Caller copies and OS/allocator memory are not guaranteed erased. + +Use Rust 1.99.1 in a temporary isolated toolchain/cache and credential-free child environment; builds/tests run offline after bounded acquisition. Two-way interoperability uses the independent Go age v1.3.2 reference with disposable data. The committed fixture contains an intentionally public test identity that must never protect real data. Reference release HTTPS/SHA-256 provenance is recorded; no independent signature-verification claim is made. The acceptance matrix below still applies. API/source qualification does not enable native recovery or change existing plaintext instruction export. + + +### Current source and priority + +`workspace_source_access.rs::export_backup` refuses Managed plaintext backup before picker/archive access. `rangoon-store::WorkspaceBackup` already validates the logical V1/V2/V3 inventory; V3 includes source, skill/revision/review, composition and workflow history. `instruction_bundles.rs::export_compiled` checks the expected candidate before writing an explicitly selected plaintext instruction bundle. Preserve these distinct behaviors. E1d adds portable encrypted recovery of saved workspace content; it does not change target instruction formats, encrypt original imported files, or protect plaintext after an authorized consumer reads it. + +Deliver encrypted recovery before using irreplaceable data. Then qualify one isolated external runtime and its actual loaded instructions/controls. A content broker, new scheduler, more catalog integrations and a distributed key service are not prerequisites for this local recovery milestone. + +### E1d-0 design baseline and retained limits + +Use an existing specified encryption container rather than design a cipher or KDF. The E1d-0 candidate was the [age v1 format](https://age-encryption.org/v1), wrapping the existing bounded logical backup bytes with an encrypted, versioned Rangoon recovery prefix. Keep the existing backup parser, identities, limits and additive Restore semantics. The format specification and implementation version are different pins. The Rust [age 0.12.1 library documentation](https://docs.rs/age/0.12.1/age/) claims interoperable age files but explicitly calls pre-1.0 releases beta; this is an unresolved dependency-assessment gate, not a production endorsement. No package had been fetched or added at E1d-0. The later E1d-1 assessment and experimental pin above supersede that snapshot; production dependency acceptance still requires exact source/license/advisory, feature/resource and interoperability assessment. + +The proposed first profile uses one explicitly supplied X25519 recovery identity/recipient and fresh library-generated encryption randomness. It does not accept SSH identities, plugin handlers, identities discovered on disk, ambient keys or arbitrary recipient collections. Passphrase recovery is deferred until native secret entry and minimum/maximum KDF resource costs have their own measured contract. Future profiles need explicit version negotiation; unsupported profiles fail closed, never silently downgrade. No post-quantum, future-proof, FIPS or certification claim follows from this candidate. + +The recovery identity must be independent of the OS-bound workspace database key and provider credentials. A portable backup is not recoverable on another machine merely because the original Keychain slot exists. The first codec takes explicit caller-owned synthetic identity material in tests; it does not touch Keychain, generate a production recovery kit or reveal a secret to the renderer. Later native custody must support deliberate separate recovery-key storage and a restore rehearsal. The user-facing loss statement is explicit: losing both a usable workspace and its recovery identity makes these backups unrecoverable; no replacement key can decrypt them. + +Keep plaintext backup content bounded by the current 68 MiB archive ceiling. The codec proposal caps the encrypted input/output at 69 MiB; dependency review must establish that valid maximum payloads fit and attacker-controlled headers cannot cause unbounded allocation or work. Do not introduce compression, recursive archives or arbitrary path extraction. Decryption is not a streaming import: authenticate the complete container, final chunk and EOF before exposing plaintext to the existing backup parser or preparing any mutation. Reject truncation, trailing/concatenated data, oversized input and unsupported profile/version; do not return partial authenticated chunks to a restore caller. Confirm these properties against the selected library API before freezing the source packet. + +All plaintext buffers remain in bounded trusted-host memory; do not write a plaintext staging file or return backup contents to the renderer. Minimize copies and use the existing zeroizing-buffer pattern, without claiming secure erasure of every runtime/OS copy. Do not log recovery identities, backup bodies, native paths or raw crypto-library error strings. Use bounded typed outcomes such as unavailable, unsupported, invalid-or-unreadable, cancelled and failed; inability to distinguish a wrong identity from corruption is not a reason to expose internals. + +Encrypted-container integrity is not sender authentication or permission to restore. Anyone with the public recipient can construct a new valid encrypted archive. Restoring an older valid archive is also possible. The existing archive validator, native preview, exact destination-state check and explicit confirmation remain required; preserve existing heads and additive history. Never infer an authenticated author, local review, engine approval, execution permission or freshness from successful decryption. Signing and independent rollback detection remain separate, unimplemented capabilities. + +### Small implementation sequence and exact ownership + +| Slice | Exact ownership and delivered proof | Closed scope | +| --- | --- | --- | +| E1d-0 — completed design | Root owns only this E1d section, `docs/plan.md`, `docs/continue.md` and `docs/development.md`. Verify current source guards, reconcile priority, record the candidate and gates, validate documents and obtain fresh independent review. | No Rust, dependency/lockfile, UI, keys, engine operation or publication changes. | +| E1d-1 — experimental source | Root owns the reviewed dependency/risk decision, workspace `Cargo.toml`/`Cargo.lock`, new `crates/rangoon-recovery/Cargo.toml`, `src/lib.rs`, `tests/envelope.rs` and `tests/fixtures/reference-age-v1.json` below that crate, plus this specification, intent, plan, continue and development records. The frozen API above delivers only a bounded in-memory codec with synthetic identities and independent interoperability evidence. | No native mounting, filesystem API, database mutation, key-store access, key discovery, subprocess/plugins, network, CLI secret arguments, provider contact or new UI claim. Public acquisition and temporary pinned-toolchain provisioning are confined to the accepted validation scope; native/production promotion stays blocked. | +| E1d-2 — later native recovery | Freeze a separate exact file packet around the existing Owner/Gate, retained previews and selected-file writer. Capture a consistent saved snapshot, encrypt before writing, retain custody through callback drain, exclusively create a selected ciphertext file, then independently reopen/decrypt/validate it before reporting a verified backup. Restore authenticates/validates before a native preview and existing additive commit. | No normal data/keys or default UI activation until isolated native qualification; no plaintext fallback, overwritten originals, key regeneration or automatic migration. | +| E1d-3 — later usable recovery journey | Simple view: Back up workspace, Restore workspace, and last verified backup. Advanced details: format/version, snapshot identity, ciphertext size and qualification limits; never secrets. Use explicit native recovery-key entry/custody, cancellation, lock/restart handling and a recovery rehearsal onto a fresh encrypted destination with a different database key. | No enabled recovery promise before the actual path is qualified. macOS evidence is not Windows/Linux qualification, secure erasure or whole-product release. | + +### Named acceptance and failure cases + +E1d-1 must prove round-trip exact bytes for empty, small, Unicode and maximum-bound payloads; different ciphertext for repeated encryption; wrong identity; header/payload/final-tag tamper; truncation at structural boundaries; concatenation/trailing data; unsupported version/profile; malformed and oversized input; bounded memory/work; and no partial plaintext return. Verify interoperability in both directions with a pinned independent implementation/vector source. Do not count a local encrypt/decrypt round trip as independent cryptographic validation. Source tests must prove secret-bearing types are non-serializable/redacted as appropriate and default diagnostics never contain identity or plaintext canaries. + +E1d-2/3 add wrong-key/tampered archive with zero destination mutation; stale preview/changed destination; cancellation and lock during capture/encryption/picker/restore; disk-full or interrupted ciphertext write; collision/symlink refusal and honest incomplete-output status; full logical source/skill/composition/workflow identity preservation; distinct-process reopen; and restore using the saved recovery identity after intentional loss of a disposable source-workspace key. Keep a positive control beside each denial. Tests use isolated synthetic data/keys and exact cleanup only. Never delete an original or report verified backup from a successful write alone. + +The proposed codec validators are pinned `cargo fmt --all -- --check`, `cargo test --locked --offline -p rangoon-recovery`, and `cargo clippy --locked --offline -p rangoon-recovery --all-targets -- -D warnings`, plus named cross-implementation vectors, documentation checks and fresh independent review. E1d-1 now runs the focused commands against its experimental source; exact outcomes belong to the dated development receipt. These checks do not satisfy native or production promotion gates. Native integration later requires the affected locked/offline core/desktop matrices and actual selected-platform GUI/custody evidence. Keep ISO/OpenSSF dependency, privacy and evidence requirements distinct from a badge, certification or security guarantee. + +### Next external-runtime gate after recovery + +Choose one pinned runtime for one disposable task; OpenHands and OpenShell remain candidates with different responsibilities. Freeze its installation/credentials/operation scope separately. Verify the actual target loaded the admitted instruction revision, then assess effective controls and outcomes. For OpenShell, the [v0.1.5 security guidance](https://docs.nvidia.com/openshell/latest/security/best-practices#enforcement-mode-audit-vs-enforce) documents an L7 `audit` default that logs violations while forwarding requests. Network admission is separate. Require effective policy evidence, appropriate inspected protocol, restrictive rules and `enforcement: enforce` before claiming request-level denial; unsupported body/recipient checks remain explicit limitations. + +Use positive and negative controls with independent target nonreceipt: unrelated file/credential/control-socket access, wrong repository/tenant on an allowed host, stale/replayed admission, unsupported authority translation, aggregate abuse, hostile evidence, revocation of queued/active work and restart/rollback. Test REST methods/paths, GraphQL body operations and WebSocket handshake/messages separately where applicable, and repeat after policy change/restart. Model advice, a provider allow record, protocol compatibility and UI approval never substitute for authorization or runtime enforcement. No live hostile-worker test or connected coverage is established by the current source/fixture evidence. LNSAT and VUSL remain independent optional projects and are not edited or required by E1d. + + +## E1c-5 ordinary startup and Legacy adoption — proposed + +Status: design proposal under the accepted encryption completion outcome, not source/default-switch or migration acceptance. E1c-4 must finish its full native matrix on one selected executable before ordinary startup is changed. This packet reuses the existing SQLCipher store, Owner, Gate, native consent, durable recovery and close protocol; it does not introduce another encryption architecture. E1d remains the separate encrypted portable-archive/recovery track. The [development receipt](development.md#e1c-5-startup-and-legacy-adoption-design--october-18-2026) owns review evidence. + +### Outcome and existing seams + +On first launch, a new user explicitly creates an encrypted workspace. An existing user sees the existing data and a reviewable conversion path; the app must not silently substitute a new empty encrypted workspace. A returning encrypted user confirms unlock and receives the same records and identities. Interrupted or ambiguous adoption stays closed with actionable recovery. Source authoring, skills, composition, workflows, compilation and exports remain usable without any provider. + +Current `main.rs::source_state` selects Legacy at `app_local_data_dir()/source-workspace`, regardless of the encryption feature. `Workspace::new` is the plaintext constructor; `workspace.sqlite3` is its database name. `SourceAccess::managed_locked`, `workspace_native_bootstrap::present_workbench` and `OsVault` already supply the unmounted encrypted startup/consent seams. `Owner::acquire` owns a different control lock and validates Managed layout; it is not a Legacy migration detector or a lock understood by every old binary. `workspace_source_access.rs::export_backup` already refuses Managed plaintext backup before the picker. Reuse these boundaries rather than adding renderer database selection or a second connection path. + +### Reusable transfer and unresolved ownership gaps + +Source inspection identifies a preferred transfer base: `workflow_backup.rs::export_workflow_backup` captures validated domain records in one read-only SQLite transaction and returns bounded in-memory archive bytes: schemas 1–3 emit V2, while schema 4 emits V3. `WorkspaceBackup::decode` accepts V1/V2/V3 and rebuilds an in-memory canonical database for validation. Conversion must validate the version appropriate to the captured schema and compare its complete logical inventory, never require a V3 prefix for older valid workspaces. The full schema-4/V3 inventory includes sources, capability histories/reviews, composition recipes/applications/derivations and workflow histories; current schema 1–4 round-trip tests cover logical identity preservation. It is not a physical file image or an encrypted archive. Original imported/exported files, filesystem permissions, journals, Owner/key metadata, durable operation receipts and renderer sessions are outside that logical inventory and need explicit treatment in the adoption record and UX. + +Reuse `Owner::prepare_workflow_restore` and `restore_workflow_backup` as the destination mutation seam only against a proven fresh, separately created Managed workspace. Existing restore is an additive union with destination-state checks and durable Restore reconciliation; it does not prove exact source-to-destination equivalence, freeze the source, or commit startup selection. Require a complete destination comparison afterward. Existing limits remain hard refusals, including the 64 MiB logical store, 68 MiB archive and record-count/revision limits; do not expand limits silently to make migration pass. Transfer byte buffers must remain host-owned and bounded, never renderer payloads or plaintext disk archives. + +A missing source connection currently exports an empty logical archive. Migration must separately prove the recognized Legacy database exists, is a regular unchanged file and was captured successfully; it must never interpret disappearance or substitution as an intentionally empty source. A valid empty Legacy database is a separate explicit case. No current export plan carries a source-side expected-state token. The new native snapshot custody must bind file identity and captured domain state through preview/confirmation and detect source drift before selection. Managed Restore intent/reconciliation is useful destination evidence but does not bind the Legacy source or supply a durable cutover journal. These are explicit missing mechanisms, not claims that existing backup/restore already performs migration. + +### Native startup classification + +Inspect only the fixed application-owned storage locations. Do not scan arbitrary directories, use renderer-supplied roots, open vault slots during classification or infer encryption from a file extension. Classification is native, bounded and version-aware; unexpected files, linked/replaced roots, malformed control records and unsupported versions are not an empty workspace. Any discovery result used later must be revalidated under operation custody; a stale preview never authorizes mutation. + +| Observed storage | User surface | Required routing | +| --- | --- | --- | +| Proven fresh layout | Set up encrypted workspace | Existing native create confirmation, Owner and initial close protocol; no key before confirmation | +| Recognized Managed layout only | Unlock workspace | Existing native unlock; no plaintext fallback or replacement key on failure | +| Recognized Legacy layout only | Existing unencrypted workspace; review conversion | Preserve existing data. Conversion is explicit; if deferred, any retained Legacy access is clearly labeled and must not be described as encrypted | +| Legacy plus Managed destination, no completed adoption record | Continue conversion review or recover interrupted conversion | Do not select either based on newest timestamp, filename or successful open alone | +| Valid completed adoption record and matching destination | Unlock converted workspace | Revalidate destination identity and supported state; keep retained Legacy copy distinct and disclose that it remains plaintext | +| Busy, unknown, partial, corrupt or conflicting layout | Fixed failure/recovery guidance | No source-bearing workbench, arbitrary-path picker, blank replacement, key regeneration or automatic repair | + +A source-free, bounded adoption record may describe source identity, destination workspace identity, format version and durable phase. It must reuse compatible existing recovery primitives where possible and have its exact schema/failure semantics reviewed before implementation. File contents and unkeyed hashes are untrusted routing evidence, not proof of user approval, authenticity or rollback resistance. Validate all identities against native-owned locations, Owner binding and the decrypted destination before any ordinary client is issued. Unsupported or inconsistent adoption metadata cannot fall back to a new workspace. Preserve the existing application/key-service identifier; a product-name change is not an OS credential migration. + +### Conversion and restart contract + +1. Close ordinary admission and drain actual callbacks before preparing conversion. Capture the source identity and a transactionally consistent view using a reviewed SQLite mechanism; copying only the main database while journals or another writer exist is forbidden. No new plaintext temporary archive is written. Preview exact record counts, schema/limits, destination identity, disk-space estimate and retained-plaintext implications from that captured view. +2. Require native confirmation bound to that source snapshot, destination and plan. Cancel leaves source data untouched and creates no reusable conversion authorization. Source replacement, a changed snapshot or expired plan requires a fresh preview/confirmation. Refuse an unsupported source schema or a dataset that cannot be represented completely; never truncate to fit current caps. +3. Create a separate encrypted destination through existing Owner/key custody. Transfer complete validated domain state and preserve record IDs, revisions, provenance, reviews, composition inputs/results, workflow definitions and relationships. Do not use additive restore as proof that an exact migration succeeded. The version-aware in-memory archive transfer is the preferred existing mechanism; its complete migration inventory oracle and source-custody contract must be frozen before source acceptance; no generic SQL or arbitrary database handle enters the renderer. +4. Verify destination structural/cipher integrity and a deterministic comparison of every migrated domain record and relationship, including compile/export parity for retained definitions. Close the destination, restart a distinct OS process, reacquire the exact Owner and confirm unlock using the retained OS key. Re-read and compare again before selection can be committed. Key lookup failure never regenerates a key. +5. Commit the durable selection only after successful verification. Test every record-write/sync/rename/readback failure boundary and recovery classification. Unknown completion remains a recovery state. Never report success from a UI click, directory existence, content checksum alone or an unobserved background callback. +6. Preserve the original Legacy copy by default. Report that it, its old backups and imported/exported files remain plaintext; encrypting the destination cannot erase those copies. Automatic deletion, secure-erasure claims, key rotation and portable encrypted recovery are excluded. Cleanup needs its own explicit retention/destructive-action scope. + +Concurrent/old-version access is a required design decision, not a solved property. A new advisory Owner lock cannot stop an old application that ignores it. A source snapshot preserves a point-in-time dataset; it does not prove no later Legacy writes occurred. Recheck source state before selection and detect later divergence on supported startup; refuse automatic merge or rollback. Before shipping writable cutover, either qualify an exclusive Legacy-writer protocol across the supported upgrade path or explicitly require old processes closed and document the residual inability to prevent an unsupported old binary from reopening retained plaintext. A malicious same-user process or replay of all valid local files remains outside any guarantee supplied by these unkeyed markers. + +### User controls and completion gates + +Keep normal controls concise: Set up, Unlock, Review conversion, Cancel, Continue recovery. Advanced details show storage mode, selected identity, last verified conversion phase, retained Legacy copy and backup availability. Do not show an enabled encrypted-backup/restore promise while E1d is unavailable. Explicit target instruction exports remain plaintext with their existing disclosure. An unsupported backend or unavailable OS vault must show a fixed actionable error, not silently choose Legacy. + +| Stage | Exact responsibility and deliverable | Required evidence | +| --- | --- | --- | +| E1c-5a startup classification and source capture | Sol owns native storage classification and source-snapshot design in `apps/desktop/src/workspace_startup.rs`, its focused tests and the minimal private module registration in `main.rs`. Jeff accepted this exact unmounted source/test scope on October 19. A read-only reviewer validates the state matrix; the development ledger owns results | Fresh/Legacy/Managed/mixed/unknown/linked/replaced/busy cases; no vault/data mutation during classification; stale-preview refusal; proof of a stable complete source snapshot before conversion work | +| E1c-5b conversion and interrupted adoption | Sol owns store/Owner transaction and durable selection changes; exact source files and record schema require a separate reviewed packet after the inventory/snapshot decision. A disjoint native worker may own synthetic fixtures only | Complete domain inventory and identities; concurrent writers; unsupported schema; over-capacity/disk-full; source replacement; cancellation; key loss; process kill around every phase; independent destination reopen and parity; no plaintext temporary output | +| E1c-5c ordinary startup and recovery UI | Sol owns normal startup routing; bounded UI worker owns capability-aware setup/conversion/data controls after the native contract freezes. Exact path list follows that contract | Completed E1c-4 matrix on one artifact; first-run and upgraded native tasks on macOS/Windows/Linux; no blank replacement; real restart and recovery; keyboard/focus/reduced-motion checks; packaging/backend/OS-vault evidence before release | + +The deliverable is the full first-launch/existing-data/restart experience, not merely a classifier or passing fixture. Staging permits review without claiming partial work is adoption. Required source validators include the scoped store/desktop tests, default and encrypted builds, warnings-denied Clippy, formatting, relevant renderer tests, document/vision checks and fresh independent review. Exact commands and artifacts belong in each accepted source packet. No normal database/key access, runtime mounting, provider connection, LNSAT change, VUSL specification work, migration, publication or release is authorized by this proposal. + +## E1c-5a startup inspection and existing-source capture — proposed source packet + +Status: accepted for the exact unmounted source and disposable tests. Jeff answered “Accepted” on October 19, 2026; [intent](intent.md#e1c-5a-source-acceptance--october-19-2026) records the scope. The heading retains its existing anchor. The completed [selected-artifact native checks](development.md#e1c-4-selected-artifact-native-completion-checks--october-19-2026) remove the earlier native-test wait; their recorded limits remain. This packet implements the first stage of E1c-5, not ordinary startup, conversion or the finished encrypted product. It makes an existing workspace distinguishable from absent, invalid or replaced data before a later adoption operation can select it. + +### Fixed paths and observation, not selection + +A private native `StartupRoots` derives both roots from the OS application-data anchor: existing `source-workspace` and proposed sibling `managed-workspace`. Keep the current application identifier. Neither root nor any replacement original comes from IPC. Tests inject only disposable anchors; no production caller mounts this module yet. The parent application-data directory is shared with other app state and must not be treated as an otherwise-empty Managed Owner root. + +Inspection observes only those two exact roots and bounded immediate entries. It must not create a directory/lock, open SQLite or a credential slot, generate a key, acquire `Owner`, or follow symbolic links/reparse points. `Owner::acquire` can create its lock file, so it cannot be used as a supposedly non-mutating classifier. Existing Owner binding/layout validation remains the later authority for Managed setup/unlock; do not copy its private decoder into a second implementation. + +Return finite observations: `FreshCandidate`, `LegacyCandidate`, `ManagedCandidate`, `Mixed`, `RecoveryRequired`, `Unavailable`, or `UnsupportedPlatform`. Candidate means presence and structural observations only. No candidate proves schema compatibility, decryptability, free ownership, consent or saveability. Mixed roots remain closed until a later validated adoption record exists. This packet accepts no adoption-record format. An empty existing Legacy directory, zero-byte database, partial Managed directory, orphan journal, unknown entries or unsupported metadata must never become `FreshCandidate`. A genuinely absent root differs from an inaccessible or replaced root. Valid empty SQLite content is recognized only by the capture validator below. + +Revalidate retained root/file identity at every later use. Use real OS file identity, including directory ancestry and final file identity, with bounded metadata and no-follow checks; do not equate timestamps/size with identity. Existing `workspace_session::same_file` returns true on non-Unix systems and therefore cannot serve as a cross-platform proof. If the chosen safe platform API cannot establish identity, return `UnsupportedPlatform`; compile success does not qualify Windows support. Do not add unsafe code or dependencies in this packet. Path observations remain fallible and do not defeat a malicious same-user process that can replace and restore every path between checks. + +### Existing-source capture and revalidation + +Add a separate store entry for **existing** Legacy capture. Preserve current `export_workflow_backup` behavior for its callers. Reuse its complete record reader, version-aware encoding and `WorkspaceBackup::decode`; no second archive format, parser or renderer backup path. The new method must return an error when the source directory/database is missing, disappears or is substituted. A zero-byte file is not an initialized empty workspace. A valid empty SQLite database is accepted only when the existing schema/page-size/empty-state checks pass. + +Capture all domain records within one SQLite read transaction. Read schema and inventory from that same transaction. Preserve schema 1–3/V2 and schema 4/V3 behavior; permit schema 0 only for the existing validated canonical empty-database case and test it separately. Do not upgrade the source schema, run checkpoints, repair journals, change journal mode or write a temporary archive. Keep the current DELETE-journal restriction and limits; busy/hot-journal/WAL/unsupported files refuse rather than being opened through an alternate permissive route. Read-only SQLite flags are not a general claim that SQLite can never touch auxiliary files; disposable tests must compare source and sidecar state and reject any unqualified mutation path. + +Return a host-owned retained snapshot containing bounded canonical archive bytes, their digest, observed schema, complete inventory counts and file/root identity evidence. The new retained snapshot must be a private non-serializable wrapper with no content-bearing derived `Debug`. Reusing `WorkspaceBackup::decode` also requires replacing the existing public `WorkspaceBackup` derived `Debug` in the already-owned `workflow_backup.rs` with a manual redacted implementation that preserves the `Debug` trait but emits only a fixed type/redaction label, never nested records, source text or archive bytes. Internal `Records` remain private and must not escape through another diagnostic path. Public diagnostic values are finite and source-free. Reuse existing byte hashing and zeroizing containers where applicable; do not claim complete SQLite/process-memory zeroization. Drop/cancel invalidates the retained object. No renderer command, approval token, persistent record or authority grant is created. + +A revalidation method checks the same native roots/identities, captures another consistent view and compares the full canonical archive plus schema/inventory. Any difference, failure, disappearance or unsupported condition invalidates the retained snapshot. Do not accept equal counts, equal timestamps or an unchanged main-file hash as a substitute for complete logical equality. Test same-size edits and relationship/review changes. Bound memory explicitly: each archive stays within the existing 68 MiB limit; no unbounded history, polling or concurrent capture queue. At most one retained snapshot and one bounded comparison capture belong to an operation. + +This proves a consistent captured dataset and observed equality at recheck. It does **not** reserve Legacy writers through cutover, prevent an old process from writing afterward, authenticate local files, establish anti-rollback or authorize migration. E1c-5b must add the reviewed source-custody/selection protocol and destination equivalence before ordinary routing changes. Never describe this retained capture as a completed migration or exclusive source lock. + +### Ownership, validators and handoff + +Root owns protected storage/native integration and these exact production paths: `apps/desktop/src/workspace_startup.rs` (new, private), private module registration only in `apps/desktop/src/main.rs`, `crates/rangoon-store/src/workflow_backup.rs`, and only necessary type re-exports in `crates/rangoon-store/src/lib.rs`. Test ownership is `apps/desktop/src/workspace_startup_tests.rs` and `crates/rangoon-store/src/workspace_capture_tests.rs` (both new). Preserve all existing dirty startup/lifecycle/O2 source. Documentation ownership is this specification plus `docs/{intent,plan,continue,development}.md`; acceptance is recorded only after an explicit owner response. No new schema, dependency, feature/default, command or normal-entry call is authorized. + +Required cases: absent roots; initialized empty Legacy; schemas 1–4; missing/zero-byte/corrupt/unsupported Legacy; Managed candidate; mixed/partial/unknown entries; linked/reparse/hard-linked/replaced files and ancestors; access denied; over-limit records; busy/hot-journal/WAL refusal; source removal during capture; same-inode/same-size logical change; review/revision/composition/workflow relationship drift; stable unchanged recapture; cancel/drop; no credential access; direct `Debug` formatting of decoded backups and every new retained/error type must omit a unique synthetic source marker and match the fixed redacted shape; no content-bearing diagnostics; no source/sidecar mutation; ordinary startup remains Legacy; unmounted module has no registered IPC. Schema/OS cases unsupported on the test host remain explicitly unqualified, never silently skipped as a pass. Existing valid authoring/export/restore behavior must retain its regression tests. + +Named source checks after acceptance: + +```sh +export PATH="/usr/local/bin:$PATH" +export RUSTC=/usr/local/bin/rustc +export RUSTDOC=/usr/local/bin/rustdoc +cargo --version +rustc --version +cargo test -p rangoon-store --locked --offline +cargo test -p rangoon-store --features encrypted-sqlite --locked --offline +cargo test --manifest-path apps/desktop/Cargo.toml --locked --offline +cargo test --manifest-path apps/desktop/Cargo.toml --features encrypted-workspace --locked --offline +cargo build --manifest-path apps/desktop/Cargo.toml --locked --offline +cargo build --manifest-path apps/desktop/Cargo.toml --features encrypted-workspace --locked --offline +cargo clippy -p rangoon-store --all-targets --locked --offline -- -D warnings +cargo clippy -p rangoon-store --features encrypted-sqlite --all-targets --locked --offline -- -D warnings +cargo clippy --manifest-path apps/desktop/Cargo.toml --all-targets --locked --offline -- -D warnings +cargo clippy --manifest-path apps/desktop/Cargo.toml --features encrypted-workspace --all-targets --locked --offline -- -D warnings +cargo fmt -p rangoon-store --check +cargo fmt --manifest-path apps/desktop/Cargo.toml --check +node scripts/validate-review.mjs +git diff --check +``` + +The earlier native/source evidence used the verified Homebrew Cargo/Rust 1.98.0 pair on this macOS host, not a rustup alias; that remains a historical tool identity. Current validation uses the unified Rust 1.99.1 pin and an explicitly selected provisioned toolchain. Also run `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` for the pinned Rust 1.99.1 portable default gate after store edits; preserve any unrelated baseline failure explicitly rather than claiming it passes. Record toolchain availability and actual commands/results; no success claim for unrun checks. Desktop synthetic-peer regressions may require separately permitted loopback access, never real providers. Require fresh independent read-only pre-code design and final source review, exact outside-scope hashes and no source/default/UI mutation while this packet is only proposed. The next handoff is a reviewed E1c-5b conversion/cutover packet using this capture, followed by E1c-5c native startup/recovery UX and three-OS qualification. Do not replace the full adoption outcome with passing capture tests. + +Normal data/keys, OS credential access, live providers, LNSAT edits, VUSL specification development, actual migration, startup activation, publication and release remain closed. Security impact is bounded plaintext capture in host memory with explicit privacy and identity limits, not a new authorization mechanism or standards certification. + +## E1c-5b verified conversion and durable selection — proposed source packet + +Status: accepted for the exact unmounted source and disposable tests. Jeff answered “Accept E1c-5b source/tests” on October 19, 2026; [intent](intent.md#e1c-5b-source-acceptance--october-19-2026) records the scope. The heading retains its existing anchor. The [development receipt](development.md#e1c-5b-implementation--october-19-2026) owns source evidence and independent review. E1c-5c remains the ordinary startup, real consent/recovery UI and platform qualification gate. No normal workspace conversion, OS credential access, default switch or provider action follows from this acceptance. + +### Reuse and exact missing behavior + +Keep the existing SQLCipher backend, OS-key abstraction, Owner, complete record reader, V1/V2/V3 decoder, restore union, Gate and native close protocol. `Owner::prepare_create_empty`/`confirm` supply fresh identity and encrypted creation; `prepare_workflow_restore`/`restore_workflow_backup` already bind a complete state and use durable `CreateEmpty`/`Restore` operation checkpoints. Owner checkpoints remain the authority for that destination's uncertain mutations. They do not describe which Legacy capture was copied or which root a future application startup should select. + +Existing additive restore deliberately retains the destination schema when no additions exist (`workflow_recovery.rs::restore_plan`). A fresh encrypted workspace is schema 1. An empty schema 2, 3 or 4 source therefore cannot be assumed to have an identical post-restore archive. Schema 0 is different: the existing verified-empty reader maps it to canonical `Records::empty()` version 1, and E1c-5a already tests successful schema-0 capture. V2 archive decoding reconstructs schema 3 and does not retain the original physical schema. The strict host plan must therefore receive the observed schema from the retained source capture, validate that the complete decoded records are representable in that schema, and bind it separately from the archive bytes. Generic union resolves retained heads and can trim composition records no longer needed by its result; an exact empty-target transfer must preserve every validated incoming record. Completely orphaned recipes or applications remain invalid under the existing record contract. Preserve ordinary restore behavior. Add a narrow empty-destination restore plan/method that reuses the existing union validation, schema initializer, row writer and transaction checks while also preserving the captured canonical schema when there are no rows to add. Require target schema 1 for observed source schema 0, and the same target schema for source schemas 1–4. No second archive format or duplicate parser is needed. + +The intended result is one complete, reviewable conversion attempt: capture; explicit native confirmation; create a separate empty encrypted destination; transfer; prove exact logical equivalence; close; reopen in a distinct process using the same synthetic test key custody; verify again; durably record selection. Ordinary application routing is not mounted in this packet. Source-only evidence must not be described as actual installed-user migration or real OS-vault qualification. + +### Native custody and confirmation + +Use only the existing application-data anchor and its fixed `source-workspace` and `managed-workspace` siblings. No renderer-selected database path, replacement original, raw key, archive bytes, arbitrary closure or caller-supplied verification boolean enters the coordinator. A private `Conversion` owns one capture and one comparison buffer; it is non-cloneable, non-serializable and has fixed redacted diagnostics. Source-derived schema/counts and finite states may form a later source-free preview; raw source and digests do not become log messages. + +Preparation inspects a Legacy-only layout and requires the Managed root and adoption directory absent. It captures complete source state through E1c-5a and retains native generation, a fresh attempt ID and the fixed fresh-target expectation. Preparation/cancellation writes no destination, adoption file or key. The eventual native confirmation must bind that retained capture, inventory, fixed fresh target, operation and retained-plaintext disclosure. The renderer can request that confirmation, never assert consent. The production consent adapter is not implemented or mounted by this source packet; tests use an explicitly synthetic host confirmation seam, compiled only for tests, rather than treating a renderer value as human consent. + +After confirmation, consume the in-memory attempt once, revalidate the source and target absence, then acquire the conversion lock and perform the bounded effects below. Cancellation before consumption drops retained plaintext. After effects begin, cancellation/exit stops later stages and closes the Owner; it does not report that a committed restore was undone or remove an uncertain key/destination. A failed or interrupted attempt requires inspection, fresh confirmation for any further mutation, and existing Owner recovery where applicable. Never regenerate a missing key or silently resume a write from a journal record. + +Creating the destination makes the layout Mixed, so blindly calling E1c-5a's Legacy-only `RetainedSource::revalidate` afterward is incorrect. Consume its capture into the coordinator only after the final Legacy-only check. Thereafter retain full Legacy ancestry/file identity and full logical recapture checks, while separately verifying the exact native-created destination through Owner. Do not add a general `allowMixed` flag or weaken ordinary startup classification. A bounded source-identity fingerprint must come from the existing capture's retained OS proof, not a fresh arbitrary path or a renderer field; the store may expose that source-free inspection value without exposing its private records or paths. + +E1c-5b is unmounted. Its disposable fixtures have no ordinary clients; tests may inject a competing writer to prove refusal. Before E1c-5c mounts it, the real native bootstrap must issue no ordinary client before classification/conversion resolves, close admission and drain any actual callback on cancellation/exit, and retain all native/renderer cleanup obligations. A dummy quiescence boolean is not proof of that integration. + +### Cross-root journal and selection contract + +Proposed fixed layout: `workspace-adoption/` under the existing application-data anchor, separate from both data roots and from Owner's private files. It contains at most six immediate entries: empty `adoption.lock` plus `intent.json`, `target.json`, `copied.json`, `reopened.json` and `selected.json`. Each JSON file is at most 4096 bytes, regular, single-link and application-write-once; it is not an authenticated append-only audit. Unknown entries, missing predecessor, a partial record, unsupported version, invalid binding or linked/replaced file/ancestor are recovery conditions. This packet is Unix-only where the accepted identity/fsync proof is available; other platforms return unsupported, never a pretend no-op sync or identity match. + +Use one strict typed record family, `rangoon.workspace-adoption.v1`, with exact phase-specific fields: + +| Field | Meaning and validation | +| --- | --- | +| `schemaVersion`, `phase` | Exact supported identifier and phase matching the fixed filename | +| `attemptId`, `creatorProcess` | Native-generated 64 lowercase hex identifiers; no caller-supplied identity or PID-based authorization | +| `previousDigest` | Null only for intent; otherwise the existing SHA-256 helper over the exact preceding stored record bytes | +| `sourceIdentity`, `sourceArchive` | 64 lowercase hex fingerprints of retained OS identity proof and canonical complete archive; neither is authentication or consent | +| `sourceSchema`, `targetSchema` | Source 0–4; target 1 for source 0, otherwise equal to source; refuse all other mappings | +| `inventory` | Exactly the nine bounded existing `WorkflowRecoveryCounts` fields; validate against a complete live capture rather than trusting metadata | +| `destination` | Null for intent; exact Owner-generated workspace identity for target and all later phases | +| `verifierProcess` | Present only for reopened/selected; native process-instance identity different from creator and consistent across those two records | + +Reject unknown/duplicate fields, extra JSON values, over-limit input, noncanonical identifiers, wrong phase/field presence, count overflow, differing common bindings or a broken predecessor chain. For restart-stable Unix `sourceIdentity`, hash `rangoon.legacy-identity.v1\0`, then one byte containing the retained ancestor count (at most 64), then root-to-source-directory device/inode pairs and the final database device/inode pair, each unsigned 64-bit big-endian. Use only the already observed no-follow proof; revalidate it before use. This private inspection encoding uses the existing hash helper and bounded local metadata; it introduces no JSON canonicalization standard, cryptographic signature, approval token or authority mechanism. The journal exposes content digests, counts and local identities outside encryption; disclose that metadata and its correlation risk. It contains no raw source, record body, key or arbitrary filesystem path. + +Create directories with restrictive existing platform permissions. Open fixed files with existing no-follow/nonblocking patterns, check held/path identities and single links, acquire the actual control-file lock, and recheck ancestry before every effect. Each phase uses `create_new`, bounded write, file sync, parent-directory sync, exact readback and identity recheck before advancement. Never truncate/overwrite an earlier phase or reuse a journal from another attempt. This design has no rename step; inject failures at every actual create/write/file-sync/directory-sync/readback boundary. Any uncertain durability closes the attempt. A lock only coordinates cooperating processes; it is not a Legacy SQLite writer lock or protection from a compromised same-user account. + +| Phase | Required operation and refusal behavior | +| --- | --- | +| Intent | After one-shot native confirmation and final source/absence recheck, create the adoption directory/lock and bind the complete source plus fresh target expectation. An existing adoption directory is inspection/recovery, never automatic overwrite | +| Target | Create only the previously absent Managed root, acquire its Owner, prepare empty setup, and persist the exact returned workspace identity before confirming creation/key access. Revalidate the source before confirmation. Owner owns CreateEmpty checkpoint/recovery; a partial Managed root cannot be mistaken for a new blank workspace | +| Copied | Prove destination complete inventory is empty, decode the retained source archive, and use the strict empty-destination restore plan under Owner's existing durable Restore operation. Compare full decrypted export bytes, canonical schema and complete inventory with the captured source, including explicit schema-0 normalization. Revalidate Legacy identity and full archive again. Counts or digest alone are insufficient. Persist only after these checks, then close/lock Owner and drop retained plaintext | +| Reopened | In a distinct OS process, reacquire the exact fixed roots/attempt/destination, obtain a fresh confirmation for unlock/verification, read the existing test key without creation, validate Owner recovery/integrity, recapture the same Legacy source and compare the complete decrypted destination export again. Same-process reopening or a supplied `verified` field cannot satisfy this gate. Persist the verified phase only after successful comparisons | +| Selected | Revalidate source and exact destination again under retained custody and the current native confirmation; append/sync/read back the final selection. This is a local routing observation, not execution authority. No ordinary client is issued by this packet | + +A missing/torn final selection or incomplete predecessor chain is Interrupted/RecoveryRequired, not successful migration, automatic Legacy fallback or permission to repeat Create/Restore. Inspection is read-only. A complete final record surviving a crash can report only SelectionRecorded; its bytes cannot prove the previous process received successful sync/readback acknowledgment. Real startup still requires fresh native unlock and live Owner/identity validation before any client, and must not relabel an uncertain caller outcome as observed success. Fault tests classify the actual surviving files rather than pretending a record reconstructs the precise crash point or a lost acknowledgment. A future recovery action must obtain fresh native consent and reconcile Owner's real state before advancing an exact attempt; automatic retry, journal deletion, destination deletion and key cleanup are excluded from this first source packet. Disposable test cleanup owns only its exact fixture namespace after children exit. + +After selection, legitimate encrypted authoring changes the destination content. Future startup must validate destination identity, supported binding, key, decrypted structure and current Owner operation state; it must not require every later destination to equal the original migration digest. That digest is historical transfer evidence. Recheck any retained Legacy copy separately: divergence, disappearance or substitution is an explicit inspection/recovery state, never an instruction to overwrite or silently merge the encrypted records. E1c-5c must define the corresponding user choices before mounting routing. Source capture/recheck still cannot prevent an old binary that ignores Rangoon custody from writing just after verification; supported cutover requires old processes closed and discloses that residual limitation. + +### Exact proposed ownership and evidence + +Root retains all protected store/native decisions and writes. Proposed production ownership is new `apps/desktop/src/{workspace_adoption.rs,workspace_adoption_record.rs}`, private module registration only in `apps/desktop/src/main.rs`, the narrow capture/proof handoff in `apps/desktop/src/workspace_startup.rs` and `crates/rangoon-store/src/workflow_backup.rs`, strict empty-target plan/transaction reuse in `crates/rangoon-store/src/workflow_recovery.rs`, necessary re-exports in `crates/rangoon-store/src/lib.rs`, and typed Owner forwarding in `apps/desktop/src/workspace_session.rs`. No raw handle or generic database service is added. The record submodule is private to the coordinator; it does not become another integration contract. + +Test ownership is new `apps/desktop/src/{workspace_adoption_tests.rs,workspace_adoption_record_tests.rs,workspace_adoption_owner_tests.rs}`, the existing `apps/desktop/src/workspace_startup_tests.rs` for the exact capture handoff, and new `crates/rangoon-store/src/workspace_adoption_tests.rs`. Root owns key/DB/coordinator tests; a disjoint bounded native worker may own literal journal fixtures only after source acceptance. Documentation ownership is `docs/{intent,encrypted-workspace,plan,continue,development}.md`. Existing shared-file native/O2/D3a work remains untouched outside these incremental responsibilities. No dependencies/lockfiles, ordinary handlers, frontend, engine/provider, VUSL, schema/archive versions or default settings change. Existing Owner operation codes and the generic additive restore contract remain unchanged. + +Required future evidence: + +1. Complete nonempty and canonical-empty sources for every observed schema 0–4; fresh encrypted destination; preserved physical canonical schema and exact archive bytes, IDs, history, reviews, relationships and compilation/export parity after restore and actual distinct-process reopen. Include empty schemas 2–4 so no-additions behavior cannot hide schema drift. Prove existing additive no-op restore still leaves its callers unchanged. +2. Source replacement/removal, same-size edits, review/relationship drift and competing-writer commits before confirmation, during transfer, before reopen and before selection. Every discrepancy invalidates the attempt. Document the residual interval after the final check rather than claiming a writer fence. +3. Existing/partial/mixed destination, wrong Owner identity, nonempty destination, busy lock, linked/reparse/hardlinked paths, unsupported platform/backend/schema, over-capacity records/database/archive, unavailable space and real SQLite-full/fault failures. No overwrite, truncation, repair, permissive connection or fallback. +4. Every journal/parser boundary and every actual create/write/sync/readback fault; wrong phase/predecessor/common fields, substitution, unknown names, oversized/duplicate/extra JSON and stale/repeated consent. Cancel/drop closes retained data; no content-bearing `Debug`, `Serialize`, error or log path. Bound retained memory to the existing limits. +5. Disposable subprocess kills around Intent, destination provision, CreateEmpty ready, Restore commit/observation, Copied close, distinct-process verification and Selected write/sync/readback. Reacquire the same fixture only for explicit read-only recovery inspection; prove no silent operational selection, retry, duplicate key or false acknowledgment claim. Preserve SelectionRecorded versus Interrupted/RecoveryRequired distinctions from actual surviving records. Known dummy keys/test Vault remain in the disposable test boundary; no OS Keychain, Credential Manager or Secret Service operation. +6. Subsequent legitimate destination mutation is not misclassified as failed migration; retained-Legacy divergence remains distinct. Ordinary startup, absent-provider local workflows, encrypted export refusal, existing authoring/restore/recovery regressions and current E1c-5a behavior remain unchanged. + +After acceptance, run the [same named default/encrypted store and desktop tests, builds, warnings-denied Clippy, formatting, pinned portable Rust 1.99.1 gate and document checks](#e1c-5a-startup-inspection-and-existing-source-capture--proposed-source-packet). The new tests use selectors `workflow_recovery::adoption_tests`, `workspace_session::adoption_tests`, `workspace_adoption::tests` and `workspace_adoption::records::tests`, with explicit ignored subprocess children driven only by their parent cases. Run both backend modes and preserve existing renderer regressions. Journal fault labels cover before/after create, write, file sync, directory sync and readback for each named phase; the receipt records the actual tested matrix rather than counting a generic fault hook as proof. No source tests were run as part of drafting this packet. Require fresh independent design review, explicit source/disposable-test acceptance, then fresh independent source/evidence review. E1c-5c must separately qualify actual native consent, OS vault, startup/exit/purge and three-OS tasks before adoption. No publication or release gate opens here. + +## E1c-5c native startup and recovery — design gate + +Status: accepted source and disposable macOS tests. Jeff explicitly answered “Accept E1c-5c source/tests” on October 19. This opens only the exact source/default behavior and isolated macOS cases below; validation and native qualification remain incomplete until their evidence passes. E1c-5a/5b source and E1c-4 disposable macOS evidence remain limited to their own artifacts. The [current development receipt](development.md#e1c-5c-startup-and-recovery-design--october-19-2026) owns review and acceptance state. The outcome remains the complete first-launch, existing-data and returning-user flow, followed by the accepted three-OS qualification; a source-free card alone is not completion. + +### Fixed routing instead of replacing live services + +At the E1c-5c design baseline, `SourceAccess` held an immutable encrypted flag, registry, Gate and backend behind one `Arc`. `main.rs` always installed Legacy, while `managed_locked` immediately acquired an Owner. The existing setup controller supports only CreateEmpty/Unlock and rejects source-bearing previews; it cannot stand in for conversion consent. A runtime swap of SourceAccess, its registry or its mode would leave retained callers and close state referring to different owners. The mounted path therefore uses deferred binding rather than Tauri state replacement or a renderer-supplied database path. + +The proposed encrypted path constructs one deferred Managed SourceAccess at the native-owned fixed root. Construction performs no filesystem creation, Owner acquisition or vault access. Its encrypted flag and client registry remain Managed for the process lifetime. The private backend initially has no Owner; all content operations refuse. A native startup host inspects only the existing fixed roots and adoption journal, retains exact observations, and binds one locked Owner only after the corresponding closed-cycle route is revalidated. Binding does not issue a client, confirm unlock or bypass purge. Reuse the existing native setup/Owner confirmation and client-publication checks afterward; do not create a second publication path. + +A private Control::bind_locked_owner transition is required; the existing control API cannot already do this. It requires the actual current native ClosedLease, healthy completed cleanup, quiescent real drain, released prior operation custody, an empty Owner slot/client registry, the fixed native root and a retained structural route proof. The incoming Owner remains locked. Caller-supplied cycle/epoch values are only request matching, not that lease. Failure/drop locks Owner, purges retained native state and leaves the cycle unhealthy; no second bind, root change or failure reset follows. Existing SourceAccess clones, failure notifier and WorkspaceClose refer to the same instance throughout. Preserve request-generation fencing and actual renderer purge acknowledgment. The native exit coordinator retains real adoption work until it returns; dropping an IPC waiter, closing a window or timing out a parent is not callback drain. + +Native adoption plans must retain an opaque binding to the actual close coordinator and its exact control serial. A currently valid permit from another coordinator or a later cycle cannot revive a cancelled conversion or verification preview, consent token, copy or selection. Source-bearing startup work also requires the fresh C1 renderer-purge acknowledgment; the completed C0 cycle is insufficient. Neither binding nor acknowledgment grants a content client or execution authority. Cancellation invalidates later checkpoints while an already entered bounded storage step may finish; the real worker retains custody until its Owner and captured data are dropped. Do not report cancellation as rollback or proof that no write occurred. + +Existing-destination acquisition must be noncreating. Owner::acquire currently tries create_new on the control file, so shape inspection alone cannot guarantee this across disappearance. Add a narrow Owner::acquire_existing entry that shares the same directory/control/lock validation but opens the existing control only, with no create or repair. Use it for Managed-only, Selected, valid-Target recovery and control-only residue; retain acquire for the explicitly requested fresh creation path. Missing or substituted control fails before vault access. Preserve existing acquire callers and all durable operation codes. + +Structural route proof is deliberately incomplete. For a selected journal, the required order is: validate the entire journal/fixed-root structure; bind the locked Owner under that closed custody; call Owner::prepare_unlock; compare its exact workspace_id to Selected.destination; obtain fresh native unlock consent; confirm the key/decrypted state; then use the existing resume/registry-publication path. Missing/replaced/wrong Managed roots never fall back to Legacy Copy or Fresh. E1c-5b inspect() alone only checks the journal and retained Legacy capture, so SelectionRecorded is insufficient even to trust a destination identity. + +Pre-bind content requests must refuse before the ordinary backend watchdog. They cannot call ordinary_session_healthy and latch a false corruption failure because no Owner exists yet; nor may that predicate be changed to claim an unbound backend is healthy. Keep startup operations on their exact native closed-control lease, and allow ordinary backend work only after binding, native confirmation and resume. The source-free UI needs no content service. Test hostile/missing/stale requests during bootstrap to prove both no client access and no accidental permanent failure latch. + +Fresh setup may create only its fixed Managed directory/control metadata after the explicit Set up request and a final fresh-layout check. It then binds a locked empty Owner and uses the existing CreateEmpty native confirmation before any key write or database creation. A cancelled setup must also work after process restart: recognize only the precisely bounded control-only residue, with no Legacy/adoption journal, binding, database, encrypted-workspaces child or unknown name, and validate Owner Empty under retained native custody without a vault lookup. This is not a rule that arbitrary partial Managed layouts are fresh. Every other partial, linked, substituted or ambiguous layout stays recovery-only. + +The proposed encrypted product route offers conversion or Quit for existing Legacy data; it does not open a plaintext workbench or create an empty replacement. Cancel before effects returns to the source-free choice. This is a deliberate proposed change from the currently shipped-source Legacy factory and requires owner acceptance. Default activation is proposed by making the existing desktop encrypted-workspace feature default, without changing dependency versions or crypto/storage formats. Explicit no-default-feature builds must show an unavailable backend for this route rather than fall back to Legacy. Do not perform normal user-data/key operation to validate that source change. Default source activation, disposable native qualification and publication are separate evidence claims; three-OS release remains gated even if one macOS artifact passes. + +### Startup and user-visible behavior + +Keep the existing workbench shell and compact visual system. Add a distinct local startup controller; do not overload workspaceLock.layout, turn a rendered button into consent, or instantiate source-bearing controllers before native routing and the ordinary protection controller allow them. The draft local DTO is rangoon.workspace-startup.v1; it is a Rangoon UI contract, not a VUSL profile. Native returns a finite state, current cycle/epoch, an exact bounded action allowlist and safe diagnostic/phase labels. No source text, arbitrary paths, database handles, vault identity, raw records or key bytes enter it. Counts may appear only from a successfully retained local conversion capture, not metadata-only classification. Unknown versions/fields, contradictory action/state combinations, malformed IDs and stale requests refuse; the native host independently checks every action again. + +Draft inert example, not an accepted public protocol or a passing fixture: + +```json +{ + "schemaVersion": "rangoon.workspace-startup.v1", + "state": "legacy_found", + "startupId": "1111111111111111111111111111111111111111111111111111111111111111", + "attemptId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": "1", + "actions": ["review_conversion", "quit"], + "copyPhase": null, + "retainedOriginal": "unassessed", + "diagnostic": null +} +``` + +The draft request uses schemaVersion rangoon.workspace-startup-action.v1, startupId, attemptId, epoch and one declared action only. Reuse the existing canonical nonzero u64 decimal epoch and 64-lowercase-hex attempt identity rules. startupId is a separate native opaque plan token, rotated when preparation, cancellation, stage or retained proof changes; it is not consent. Bind it to the actual close lease and current capture/route. Request bodies use the existing 512-byte raw-JSON bound; response DTOs are bounded to 2,048 bytes with at most three actions. Reject duplicate/unknown keys and unsupported/null identity combinations before any effect. A no-current-cycle failure response has null identities and no mutating action; native window close still uses the actual exit coordinator. Conversion capture counts remain in the native confirmation/retained host preview, not this initial DTO. Native status, not JavaScript text or an action array, owns the state transition. retainedOriginal is unassessed for metadata-only discovery, present_unencrypted only after a successful complete plaintext capture, not_verified after missing/drift/unavailability, and not_applicable when no original was involved. + +The local native command boundary accepts an empty JSON object for `workspace_startup_status` and a bounded Raw UTF-8 JSON body for `workspace_startup_action`; the action body is not a JSON `request` wrapper. Both commands are restricted to the exact main window. The ordinary content bridge rejects these lifecycle commands. A missing startup host or unavailable encrypted backend returns a source-free unavailable state, without opening Legacy data or attempting a key lookup through that command. + +A status read before completed C0 may be retried on the same fixed Host once the native cycle is eligible. Do not cache that no-plan timing refusal forever or replace managed state to recover it. This does not reset a native failure latch, repair invalid storage or revive a plan-bound unavailable result. Explicit Verify Cancel retires its old preview; if the current permit, source, existing Owner and Copied journal revalidate, offer a fresh Verify preview with a new startup token and no key access or selection effect. An unavailable or unclassified native callback is not explicit Cancel and stays closed. + +Native status work retains the actual Startup Flight while waiting at most 30 seconds for fresh C1 acknowledgment. A mounted renderer must service the actual close observation independently, complete its source purge and acknowledge that exact cycle; waiting for the status response before sending the acknowledgment would deadlock the flow. The waiter's observation alone is not authority: the Flight rechecks its own current serial, actual lease and acknowledged healthy cycle afterward. Timeout, terminal failure, changed cycle or application-lifetime loss refuses. No host mutex spans the wait, filesystem/key work, native confirmation or Flight cleanup. Source-bearing controllers remain unconstructed until the startup handoff and ordinary protection flow allow them. + +A completed source-free handoff has null `startupId`, `attemptId` and `epoch`, an empty action list, no phase and no diagnostic. It reports only the validated retained-original category. It does not publish a content client or replace normal CreateEmpty/Unlock confirmation. Terminal native close, exit and fatal-source hooks fence admission before retiring startup custody. Ready plans move to a real blocking cleanup task; running workers retain their capture, Owner and Flight until they return. Native cleanup cannot claim a proven drain while the host still owns a ready plan or active worker. Ordinary C0/C1 cleanup must not retire a healthy plan awaiting its own acknowledgment or consent. + +| Native observation/stage | Simple surface and allowed action | Required behavior | +| --- | --- | --- | +| Proven fresh or validated control-only setup residue | Set up encrypted workspace; Details; Quit | Existing native CreateEmpty confirmation. Cancel leaves no key/database and permits the same setup after restart | +| Managed only, with no conversion journal | Unlock workspace; Details; Quit | Bind the locked fixed Owner, validate native state, then existing native unlock. Layout presence alone is not healthy storage | +| Legacy metadata candidate only, no attempt | Existing workspace found; Review; Quit | Metadata is not database validity or encryption proof. Review must retain a complete valid plaintext source capture before offering conversion or the unencrypted-original label. No plaintext workbench/destination | +| Retained conversion review | Copy to encrypted workspace; Cancel review; Details | Native sheet names copy, OS credential use and retained plaintext original. Cancel/drop retires the capture and one-shot action; no destination/key effect | +| Copy in progress | Copying / Checking copy, as actually observed | Static native phase labels only; no invented percentage, ETA, completion or undo. Exit closes admission and waits for actual worker/Owner cleanup | +| Copied by this process | Copy saved. Close and reopen Rangoon to verify; Close Rangoon; Details | No self-relaunch or session-open shortcut. Real process exit and later distinct-process verification remain required | +| Valid Copied journal in another process | Verify encrypted copy; Details; Quit | Fresh native confirmation, exact retained Legacy/Owner identity and full decrypted parity through E1c-5b | +| Valid Selected journal and current destination | Unlock converted workspace; Details; Quit | SelectionRecorded is only routing metadata. Validate the exact live Owner/key/decrypted state before the existing client-publication path | +| Selected with retained original diverged/missing/unavailable | Original copy could not be verified; Review encrypted workspace; Details; Quit | Distinguish the warning from destination health. A separately confirmed current Owner unlock may open the encrypted records without rewriting, merging or trusting the old copy; historical migration digest does not freeze later legitimate authoring | +| Valid incomplete attempt | Review interrupted conversion; Details; Quit | Only the explicitly qualified recovery actions below; no generic retry/create/overwrite | +| Busy, unsupported backend/platform, malformed/unknown/linked layout, lost key or mismatched identity | Workspace unavailable / Recovery required; Details; Quit | Fixed truthful reason, retained original disclosure and bounded diagnostic export if later accepted. No picker, key replacement, permissive connection, hidden fallback or deletion | + +Verification and normal unlock remain separate native actions in this first proposal: verification locks/drops its Owner; startup then binds the same identity locked and uses existing Unlock confirmation. Do not silently reuse a verification token as an unlock grant. A later combined action would need its own bound handoff, publication proof and UX acceptance. Simple cards use one heading, a short explanation and one primary action. Advanced details show actual storage mode, native phase, retained-original status, fixed recovery guidance and unavailable encrypted portable backup. Source-free means no source bodies, filenames or paths; safe bounded native counts are not a source payload. Imported files and explicitly exported instruction bundles may still be plaintext. + +Display “The original copy is kept. It remains unencrypted.” at conversion confirmation and while a later complete capture still verifies that original. If the retained copy diverges, disappears or becomes inaccessible, say “The original copy could not be verified” instead; do not claim current presence or plaintext from metadata alone. Do not claim deletion, secure erase, key rotation or encrypted portable recovery. E1d remains separate. No cartoon artwork, artificial animation or simulated readiness is needed for this flow. Retain keyboard focus, native-sheet Cancel focus restoration, live-region state announcements, 44px targets and the shared light/dark/forced-color/reduced-motion tokens. Validate 320, 768 and 1440 logical-pixel views; hero artwork is not the completion criterion. + +### Recovery proof that must freeze before source acceptance + +Never overwrite an earlier journal phase, invent a successful callback or infer no prior effects from a missing response. Cross-root journal recovery and Owner mutation recovery are different layers. Native may first inspect a valid exact target under a fresh OS-key-read confirmation; any Owner reconciliation or new restore needs its own exact retained preview and explicit native mutation confirmation. Existing Owner operation codes and transaction semantics remain unchanged. A key-loss, unknown identity or invalid record is not permission to create another key/workspace. + +The following recovery matrix preserves v1 record semantics. Independent architecture review confirmed that verifierProcess identifies the distinct process retained in Reopened and must be copied unchanged into Selected; it does not identify or authenticate a later selection writer. Reopened recovery may use a third process after fresh native consent and complete revalidation, with current process != creator checked separately. Do not replace the stored verifier identity with the recovery process, rewrite Reopened, or claim v1 records who wrote selection. No v2/profile or new persistence format is needed. Jeff's later E1c-5c source/tests acceptance covers this frozen continuation; acceptance does not establish its implementation or qualification. + +| Retained native proof | Candidate permitted recovery | Always refused | +| --- | --- | --- | +| Valid Target, same exact destination, Owner reconciliation proves Ready/empty, fresh complete Legacy recapture matching every retained identity/schema/archive/inventory field | After fresh native mutation consent, use strict empty-target Restore under a new existing Owner Restore operation; compare full parity before appending Copied | Automatic replay, creating a key, generic union overwrite, treating an unresolved Owner operation as empty | +| Valid Target, same exact destination, Owner Ready and complete decrypted archive equals a fresh complete Legacy recapture matching every retained identity/schema/archive/inventory field | After fresh native recovery confirmation, append only the missing Copied observation; do not repeat Restore | Counts/digest alone, changed source, nonempty differing destination, made-up prior acknowledgment | +| Valid Copied | Existing E1c-5b distinct-process verification under fresh native consent | Same-process verification, supplied verified flag, opening a client before selection | +| Valid Reopened with no Selected | Fresh native confirmation, current process distinct from creator, complete source/Owner/key/parity recheck; append only Selected while preserving the original Reopened verifier identity | Rewriting Reopened, using prior confirmation, claiming that metadata proves who wrote selection, silently changing verifier semantics | +| Intent-only, missing/torn Target, unsupported journal, mismatched/unknown destination or irreconcilable Owner | Closed diagnosis and preservation; original remains available outside the new encrypted workbench | Guessing an identity, selecting the newest/openable directory, deletion/reset/quarantine, repeated CreateEmpty, orphan-key cleanup or a new attempt in the same target | +| Selected, later destination mutation and/or Legacy divergence | Existing live Owner recovery/unlock, with the retained-original warning kept separate | Comparing every future destination to the migration digest, rolling back/merging records, treating journal hashes as authenticity or execution authority | + +Before either Target continuation, revalidate the current full Legacy capture against matches(), exact target identity/schema and the real reconciled Owner state immediately before each effect and again before appending Copied. A Target record precedes original CreateEmpty confirmation; it never proves that a destination/key/database exists. No key access precedes the corresponding fresh native inspection/operation consent. The Ready/empty path needs strict emptiness; the parity-only path may append observation but cannot repeat Restore. Any changed source or nonempty differing target stays closed. + +This does not promise recovery from lost keys, malicious same-user tampering, filesystem rollback or arbitrary invalid metadata. Those remain explicit limits, not blank setup. Recovery must retain the sole unresolved evidence and disclose any blocked action. Original source bytes are never modified by these actions. Do not introduce an unbounded recovery directory, another archive format or an automatic journal-reset loop to make a test pass. + +### Native recovery coordinator mechanics + +Only valid Target or Reopened journals can offer Recover. Retain the complete journal and fixed-root inspection under the current Startup binding. Before acquiring the existing Owner, revalidate that inspection; recheck it after acquisition, then transfer destination custody to the Owner's existing control/directory checks. Do not keep a stale metadata-only layout proof across intentional Owner metadata writes. Capture the complete existing Legacy source, compare every retained source identity/schema/archive/inventory field, and revalidate it and the journal around each callback and effect. No renderer-supplied original, destination or verified flag is accepted. + +Target recovery uses a private existing-key-only vault wrapper. It rejects a workspace identity different from the exact Target destination before calling the underlying vault, and its slot refuses key writes. This also covers pending Owner operations: `prepare_unlock` cannot expose their identity because it rejects unresolved operation records, while `inspect_recovery` already reads the key. The wrapper keeps identity matching before that read without copying Owner's binding parser or changing its API. It does not authenticate the local journal or widen consent. + +A clean terminal Owner uses its exact Unlock preview and fresh native inspection consent. An unresolved Owner operation instead needs inspection consent before `inspect_recovery`, an exact matching destination and permitted CreateEmpty/Restore operation, fresh native metadata-reconciliation consent before `confirm_recovery`, then a separate new Unlock preview and native confirmation. Every step stays in the same real worker/Flight and existing-key scope. Missing keys, unsupported operations, unknown callbacks or changed evidence stay closed; no CreateEmpty confirmation or new key is invoked by recovery. + +After authenticated inspection, exact complete archive parity permits a separately confirmed Copied observation without Restore. Otherwise only a successfully retained strict empty-target restore plan permits fresh native Restore consent, the existing Restore operation and a complete parity recheck. Revalidate source and journal immediately before recording Copied. Target recovery finishes RestartRequired and never reclassifies itself into verification on the same immutable Host; v1 creatorProcess retains its original attempt meaning, not a new recovery-writer identity. + +Reopened recovery retains the original verifierProcess, requires the current process to differ from creatorProcess, and performs a fresh native key/parity/selection confirmation. It appends only Selected. Explicit Cancel drops all old previews and returns a freshly bound metadata recovery choice when its journal/layout still validate. Cancellation after an already confirmed reconciliation does not roll back that write. Unavailable callbacks and uncertain writes do not become Cancel or permission to retry. Native prompts identify the fixed nonsecret destination and each distinct operation; no key, path, source body or raw recovery inventory enters the renderer DTO. + +### Renderer mounting and returning-document order + +The mounted startup path needs a source-free lifecycle pump separate from the ordinary protection controller. Before its first startup status call, it observes the actual native close state and completes C0: a Closing cycle requires a successful fresh renderer purge and acknowledgment of that exact cycle; Locked requires a fresh local purge without inventing another acknowledgment. Keep the pump running while startup status waits for C1, and perform another fresh purge before acknowledging that distinct native cycle. Serialize lifecycle reads/acknowledgments, but do not serialize the waiting startup status or action ahead of the acknowledgment it needs. A malformed response, cycle mismatch, failed purge, transport failure or terminal document event stays closed. The pump does not create cycles, call content services or stand in for native consent. + +An existing confirmed ordinary setup/unlock may reload the document while the native Host retains its terminal Handoff and the workspace is Open. Open alone never qualifies startup. In that returning-document case, require the exact source-free all-null Handoff from the same native startup command, then construct a fresh ordinary protection controller and require its normal native control/client checks. Any other startup result while initially Open stays closed; no synthetic C0/C1 acknowledgment, inferred Handoff, cached renderer permission or automatic retry loop is permitted. + +Only startup Handoff followed by an unblocked ordinary protection controller permits constructing the content controllers and their fresh bridge. Browser-only preview has no native startup IPC and retains its existing fixture path. Startup purge must work when no content controller exists and must not dispose the source-free startup controller or pump that is awaiting its native response. Pagehide and persisted-page restoration fence generations, stop the pump/timers and purge retained renderer state; late responses cannot acknowledge a cycle, rebuild content or reopen the document. Mounting these components remains implementation work, not evidence supplied by this design. + +Mounted-native handoff additionally requires the ordinary controller's freshly validated Managed `open` state and native client. Its historical Browser/Legacy modes remain available to their own non-mounted contexts but cannot satisfy this encrypted startup gate. A Legacy/native-state mismatch after Handoff disposes the partial ordinary controller, purges the renderer and shows unavailable before constructing or calling content services. Test Handoff followed by Legacy as a negative case; do not weaken the shared decoder or treat an unblocked boolean alone as storage qualification. + +Source-free failure cards must retain a usable Quit action even when no current startup identity exists. The bounded local `workspace_startup_quit` command accepts only an empty JSON object from the exact main window and requests the existing native exit coordinator. It does not manufacture a startup action identity, replace a lease, access a path/vault, or report that exit/drain completed. This is the UI equivalent of closing the native window; actual admission fencing, retained callback cleanup and exit outcome remain owned by the existing coordinator. Failed or duplicate requests cannot activate content or alternate shutdown. Root owns this exact host command, main registration, ordinary/disposable permissions and native boundary tests; the UI writer owns its fixed unavailable-card control and duplicate-request/failure regressions. No general application-management permission is added. + +Mounting implementation ownership, October 19: Root owns native selection, the default feature, shared ordinary/disposable factories and fail-closed unavailable state in `apps/desktop/{Cargo.toml,build.rs}`, `apps/desktop/src/{main,workspace_native_bootstrap,workspace_source_access,native_encrypted_qualification}.rs`, their bootstrap/source-access regressions, `apps/desktop/capabilities/source-analysis.json`, the isolated qualification capability configuration and `scripts/qualify-native-encrypted.py`. Adding the two already frozen startup commands to the app permission manifest is necessary to mount that accepted main-window-only contract; it does not add arbitrary paths, credentials or execution. Root also owns canonical documentation, validation and integration. A disjoint renderer-session writer owns new `preview/desktop-startup-session.mjs`, new `tests/desktop-startup-session.test.mjs` and only an export of the existing strict close-state decoder from `preview/workspace-lock-model.mjs`. A disjoint UI writer owns `preview/analyze.{mjs,html}` and new `scripts/qa-desktop-startup.mjs`. The session owns only startup commands and serialized close observation/purge acknowledgment; native startup status must remain concurrent with the acknowledgment it needs. Its Handoff callback is not a content grant: the caller must construct and qualify a fresh ordinary protection controller before any content controller. Existing QA fixtures may need the same source-free startup envelope; Root owns those bounded fixture updates. No dependency, crypto/schema/operation-code, provider, normal-data/key, engine or publication scope is added. + +### Proposed ownership, implementation order and validators + +Root owns native/store/privacy/default decisions and all protected integration. Proposed native source ownership: apps/desktop/Cargo.toml for the existing default feature only; apps/desktop/src/main.rs; workspace_native_bootstrap.rs; workspace_startup.rs; workspace_adoption.rs; workspace_source_access.rs; workspace_reopen.rs; workspace_close.rs; workspace_close_control.rs; workspace_failure.rs; workspace_setup.rs; workspace_session.rs for the noncreating acquisition entry only; and new workspace_startup_host.rs. The normal and disposable target must call the same native startup factory; a separate test-only router cannot qualify ordinary startup. No store schema/archive or Owner operation-code change is proposed. If implementation needs one, return to this design gate. + +A disjoint UI writer may own preview/{desktop-startup-model.mjs,desktop-startup-view.mjs,desktop-startup.css} (new), preview/{workspace-lock-model.mjs,workspace-lock-view.mjs,analyze.mjs,analyze.html} after the native DTO is frozen. Reuse shared tokens through the dedicated stylesheet; do not change unrelated global layout, artwork or content-controller semantics. Exact native test ownership is apps/desktop/src/{workspace_source_access_tests,workspace_managed_bootstrap_tests,workspace_startup_tests,workspace_adoption_tests,workspace_native_bootstrap_tests,workspace_close_tests,workspace_close_control_tests,workspace_failure_tests,workspace_setup_tests}.rs and new workspace_startup_host_tests.rs and workspace_startup_owner_tests.rs (the latter registered inside workspace_session for strict noncreating acquisition), plus the existing in-module workspace_reopen tests. Renderer tests are new tests/desktop-startup-{model,view}.test.mjs and the existing tests/{startup-lock-purge,workspace-requests,workspace-authoring-purge,workspace-view-purge,workspace-save-disclosure,workspace-lock-model,workspace-services-purge,workspace-lock-view}.test.mjs. Root owns extensions to apps/desktop/src/native_encrypted_qualification.rs, apps/desktop/native-encrypted-qualification/tauri.conf.json and scripts/qualify-native-encrypted.py; retain its existing custom target rather than adding a second event loop. Canonical documentation ownership is this file, docs/{intent,plan,continue,development}.md and a substantive README update only in the later publication packet. No dependency upgrades, provider/LNSAT/VUSL changes, ambient credentials, normal-data migration, deployment or release. + +Sequence: freeze the native custody/recovery contract and review it; obtain owner acceptance of exact source plus disposable cases; implement deferred Managed binding and real worker/exit custody; add source-free native/renderer controls; run the complete source matrix; then qualify one disposable macOS artifact through first setup, Cancel/restart residue, populated/empty Legacy conversion, distinct-process verification, current unlock, legitimate post-conversion authoring, Legacy divergence, key loss, busy/partial/invalid layouts, interrupted copy/recovery and actual close/purge/exit. Use the isolated test root and exact test-only OS credential service, with no normal key/data operation. No automatic self-restart is accepted. Test fixture cleanup occurs only after every created child exits and removes only its registered fixture data/key. + +Required source checks: native cargo fmt; cargo test/build/clippy --all-targets -D warnings in encrypted-default and explicit --no-default-features modes, locked/offline; existing store default/encrypted and pinned Rust 1.99.1 workspace gates; named startup/close/adoption/Owner/exit suites; existing 50 renderer regressions plus new startup model/view tests; build:check, document/image/link checks and exact outside-owned hashes. Test stale/foreign/repeated cycle actions, missing headers, actual dropped waiters, late callbacks, native Cancel, no vault-before-consent, linked/corrupt/oversized inputs, no plaintext fallback and all conditional recovery branches. Test the actual native factory with no providers, not only a model. Native proof must bind the selected source/executable/toolchains/features and actual UI/key receipts. Require fresh independent source/evidence and UI/a11y review. Windows/Linux backend, credential-store, GUI, installation and packaging qualification remain explicit separate tasks before the three-OS release; no macOS/source evidence closes them. + +### Fixed disposable case preparation + +The remaining E1c-5c native matrix must prove workflows, not merely clean process exits. Extend the existing custom executable and its parent runner; do not add a second startup, conversion or recovery implementation. A private versioned JSON case plan under `apps/desktop/native-encrypted-qualification/` is embedded by Rust and read by Python. It contains only fixed case/root names, finite prerequisite and seed kinds, and closed expectation labels. Reject duplicate/unknown fields, malformed names, missing/cyclic prerequisites, root changes across a chain, excessive input and unsupported versions. Pin its SHA-256 in the run manifest and artifact. Old manifests are refused, not upgraded. The plan is test configuration, not an IPC, VUSL or provider contract. + +The first preparation slice retains every existing case and adds control-only Cancel/relaunch, empty Legacy copy/verification/relaunch, populated Legacy copy/verification-Cancel/verification/relaunch, source-review Cancel/relaunch, and native-copy Cancel/relaunch. Only initial phases may seed their new, identity-validated empty disposable root. Empty Legacy uses the existing independently constructed schema-0 SQLite fixture; populated Legacy uses the public source/capability/revision/review/composition/workflow APIs and a fixed synthetic source, retaining workflow history. Reopen phases never reseed. Before and after a phase, capture the existing original with the real existing-only reader and compare exact physical bytes, complete archive digest/schema/inventory and identity. Do not use a permissive backup export as an existence check, expose original bytes in receipts, or repair a seed after a failed phase. + +Native receipts may add finite consent-purpose/outcome events after the real native sheet returns; they cannot authorize or substitute for that sheet. Case-specific parent oracles require the observed startup state sequence, actual approved/cancelled result where applicable, vault-write/read bounds, client absence before handoff, and preservation of the original. Verification must occur in a different real child process from copy; a successful exit or counts alone is insufficient. Keep UI interaction evidence separate from parent assertions. Normal and disposable builds retain the same native factory and storage services. No new IPC, store API, dependency, crypto or archive format is needed for this preparation slice. + +Subsequent fixed preparation must still cover legitimate destination edits and Legacy divergence after selection; missing originals and invalid/partial layouts; real interruptions after empty-target creation, full restore and Reopened metadata; unresolved CreateEmpty/Restore reconciliation; nonempty differing destination refusal; and cleanup of registered isolated keys only after all children stop. Deterministic interruption must follow the real durable effect, not a forged journal or mocked successful restore. Freeze and independently review any required narrow test-only Owner observer before adding it; the first preparation slice does not widen `workspace_session.rs` ownership or claim these recovery cases passed. Qualify the complete matrix on one new source/executable artifact after all required cases are available. The earlier one-case Cancel receipt remains component evidence from its own artifact. + +Root owns `apps/desktop/src/main.rs` for test-only module registration, `apps/desktop/src/native_encrypted_qualification.rs`, new `apps/desktop/src/native_encrypted_seeds.rs`, the finite observation additions in `workspace_startup_host.rs` and `workspace_setup.rs`, `scripts/qualify-native-encrypted.py`, new `tests/qualify_native_encrypted_test.py`, and this document plus `docs/continue.md`/`docs/development.md`. A bounded worker may own only new `apps/desktop/src/native_encrypted_case_plan.rs` and `apps/desktop/native-encrypted-qualification/cases.v1.json`, including pure parser tests; Root performs integration. Require independent pre-code review, Rust/Python agreement and rejection tests, actual seed capture/preservation tests without OS keys, focused startup/consent tests, locked/offline native default/no-default tests and warnings-denied Clippy, plus a fresh source/evidence review. No native matrix verdict follows from parser tests. Existing accepted disposable macOS authority applies; normal data/keys, providers, LNSAT/VUSL edits, dependency fetches, publication and release remain closed. + +### Fixed durable-interruption cases + +Within accepted E1c-5c, extend the same private plan to 40 phases across 13 roots. Three populated-Legacy chains interrupt the real shared adoption path after completed empty-target confirmation, after completed full restore, and after durable Reopened verification metadata but before selection. Existing adoption checkpoints map only these finite case expectations to the explicit macOS qualification target. The callback emits a source-free checkpoint and custody counters, then waits at most 120 seconds for the parent to terminate its exact child. A timeout returns a fixed uncertain-write error and cannot resume conversion. No journal, Owner receipt, key or successful result is fabricated. No Owner-library observer, production fault API, IPC or recovery algorithm is added. + +The parent accepts SIGKILL only at the expected checkpoint, once, with the real preceding confirmation and key-write/read observations. Provisioning and adoption interruption receipts have separate flags and checkpoint identities. After a killed child stops, the parent hashes only fixed original/database and journal paths under the validated run/root and registered workspace ID. It does not parse journal semantics, SQL or encrypted contents. Use no-follow opens, exact ownership/mode/link checks, bounds and stable directory/file identities. Record parent observations separately from native events. Native original-before capture plus unchanged original bytes after termination are bounded interruption evidence; the next real recovery child must independently capture/revalidate the complete original against its original native baseline. A killed process cannot supply an original-after or clean-exit event. + +Each interrupted chain includes a real native Cancel followed by a different-process recovery. Empty-target recovery requires Inspect then Restore; it adds Copied only after the existing core validates full parity. Full-parity recovery requires Inspect then RecordCopied; it must retain ciphertext bytes and earlier journal bytes, proving the completed restore was not repeated. Reopened recovery requires CompleteSelection; it appends Selected while retaining the prior Reopened record, including its verifier identity, and ciphertext. Cancellation preserves all journal/database bytes; Inspect and CompleteSelection cancellation must not touch the vault. RecordCopied cancellation may read the existing key after approved Inspect but never write a key. Successful recovery uses existing-key reads, never creates another key and never publishes a content client. Subsequent distinct-process verification and ordinary native-confirmed unlock remain separate phases. Ordered startup, exact consent sequences and opaque before/after comparisons are required; a clean exit alone cannot pass. + +The completed-confirm checkpoint is after successful `Owner::confirm`, not inside its unresolved operation. Existing `host_recovery_restores_empty_target_after_interrupted_confirm` proves Inspect → Restore for that completed-empty branch. Pending CreateEmpty/Restore has the separate Inspect → Reconcile → Unlock path and remains outside these three new interruption chains. A test must reject that unexpected path here rather than silently reinterpret a checkpoint. + +| Closed expectation | Exact native consent sequence | Custody oracle | +| --- | --- | --- | +| `crash_empty_target`, `crash_matching_target` | `copy_existing: approved`, before the exact adoption barrier | Exactly one successful slot write; 1–64 opens/reads, one write at the barrier; no client or subsequent completion | +| `crash_reopened` | `verify_copy: approved`, before the exact adoption barrier | 1–64 existing-key opens/reads; zero writes; no client or subsequent completion | +| `recovery_inspect_cancel` | `recovery_inspect: cancelled` | Zero opens/reads/writes; recovery remains offered | +| `recovery_record_cancel` | `recovery_inspect: approved`, `recovery_record_copied: cancelled` | 1–64 existing-key opens/reads; zero writes; recovery remains offered | +| `recovery_selection_cancel` | `recovery_complete_selection: cancelled` | Zero opens/reads/writes; recovery remains offered | +| `recovery_restore` | `recovery_inspect: approved`, `recovery_restore: approved` | 1–64 existing-key opens/reads; zero writes; RestartRequired; no client | +| `recovery_record_copied` | `recovery_inspect: approved`, `recovery_record_copied: approved` | 1–64 existing-key opens/reads; zero writes; RestartRequired; no client | +| `recovery_complete_selection` | `recovery_complete_selection: approved` | 1–64 existing-key opens/reads; zero writes; Handoff without content client | + +All custody observations use nonnegative integer counters (booleans refuse), at most 64 opens/reads and one write; all new crash/recovery phases require client absence. Approved operations must occur after the observed offered stage; cancellation must show a fresh offered recovery stage after its final native result. No extra consent purpose/outcome or slot-write event is accepted. + +Root owns only the finite checkpoint integration in `apps/desktop/src/workspace_adoption.rs`, `apps/desktop/src/native_encrypted_qualification.rs`, `scripts/qualify-native-encrypted.py`, `tests/qualify_native_encrypted_test.py` and `docs/{encrypted-workspace,continue,development}.md`. A bounded worker owns only the private case-plan Rust/JSON and its pure expectation/checkpoint tests. Require fresh pre-code and final independent read-only review, strict-profile agreement, positive and malformed/cancel/replay/wrong-checkpoint/rewritten-journal/changed-ciphertext parent tests, focused adoption tests, and the locked/offline native default/no-default test/build/Clippy gates. No GUI, OS-key or full-matrix result is claimed by these source checks. Unresolved Owner CreateEmpty/Restore reconciliation and remaining post-selection/layout cases stay explicit next work; adding their narrower durable-effect observer requires its own frozen ownership/review before code. Normal data/keys, providers, LNSAT/VUSL, dependencies and publication remain closed. + +### Interrupted provisioning diagnostic + +Accepted E1c-5c qualification includes interruption after a real key write. Before widening recovery behavior, reproduce the analogous existing-copy boundary with the existing disposable process fixture: terminate its copy child at the public synthetic Store's `vault/after_write` checkpoint, after its exact key envelope file is synced and before returning to `Owner::create_key`. The real adoption Target and Owner pending CreateEmpty must already be durable; the database must still be absent. Do not forge metadata or remove a terminal record to simulate this case. + +The distinct recovery child must show the current fixed `unavailable` outcome immediately, offer only Quit and retain no content client or vault access even on repeated status. Startup managed-shape inspection requires a database before binding native recovery, so this boundary never offers Inspect today. Even if it were routed further, current Owner recovery also requires an existing database before reading the key. Both gates need the separately proposed typed completion path. Preserve the exact original, envelope, Pending, binding and journal bytes across this diagnostic; keys are compared in zeroizing test memory without printing key bodies or fingerprints. A second real process must retain the same unavailable state rather than create a new key. This is a failing product capability recorded by a passing negative regression, not successful recovery or native OS-vault qualification. + +Root owns only `apps/desktop/src/workspace_adoption_tests.rs` for the one killed-copy regression and finite child mode, and `docs/{encrypted-workspace,continue,development}.md` for its result and the proposed repair below. Use the existing synthetic file vault and child fixture; no production/library code, new target, dependency, real vault, provider or normal data. Require independent pre-code review, focused killed-copy regression, existing adoption tests, locked/offline native default/no-default all-target tests/Clippy/builds, scoped formatting/doc/whitespace checks and fresh independent source/evidence review. Preserve the previous 40-phase native plan until a reviewed functional correction is accepted. + +## E1c-5d interrupted empty provisioning completion — proposed source gate + +Status: accepted source and isolated disposable macOS tests. Jeff explicitly answered “Accept E1c-5d source/tests”; the [accepted intent](intent.md#e1c-5d-source-and-disposable-macos-acceptance--october-19-2026) owns this separate acceptance. The heading retains its proposed-source anchor for stable links. E1c-5c's earlier acceptance alone did not open this change to Owner recovery semantics. The [development ledger](development.md) owns diagnostic evidence and any later owner acceptance. The functional outcome is explicit completion of an interrupted **CreateEmpty** using its exact existing key, followed by separate unlock and normal empty-target restore. No automatic retry or key regeneration is allowed. + +Source component: [October 20 implementation receipt](development.md#e1c-5d-existing-key-empty-provisioning-completion--october-20-2026) records implemented Owner/startup/consent behavior, passing final source gates and independent source re-review. All six new recovery phases pass their native parent oracles; full disposable qualification remains unfinished, including the separately diagnosed ordinary-Lock handoff correction below. Acceptance or synthetic process proof alone is not GUI/OS-key qualification. + +### Eligibility and typed inspection + +Keep current `inspect_recovery`/`confirm_recovery` semantics for databases that already exist: their inspection returns real authenticated inventory and confirmation reconciles metadata only. Add separate typed `inspect_empty_provisioning` and `finish_empty_provisioning` operations; an absent database has no authenticated inventory and must never be represented as a successful empty query. The new preview contains only opaque one-shot ID, workspace ID, attempt ID and the finite fact that an uninitialized empty-provisioning attempt is eligible. It carries no source, key material, fake state ID or execution authority. + +Startup currently rejects the no-database layout before offering Inspect. Add a distinct target-scoped metadata-only provisioning-candidate presence proof for the valid adoption Target path; do not weaken ordinary `managed_shape` or treat a candidate as usable Managed storage. Preserve exact fixed Target identity, bounded allowed files/directories, absent database/sidecars and original capture/native lifecycle binding. Owner alone validates binding/operation semantics. Only after the candidate is safely retained may native Inspect consent invoke the new Owner inspection. This proposal mounts only the existing-copy continuation; fresh-setup recovery and arbitrary malformed layouts remain separately qualified work, not implied support. + +Native inspection is eligible only under exclusive Owner custody when all these facts survive exact revalidation: intact Pending CreateEmpty for the binding's identity/attempt, no terminal slot at all, provisioning binding `ready=false`, fixed parent/workspace directory identities, and an otherwise empty destination with no database or SQLite sidecar. Reject CreateSource, all other operations, damaged/foreign/contradictory records, partial/linked/nonregular files, any existing destination contents and unsupported backend. Inspect occurs only after native Inspect consent. It may read and validate the existing OS key envelope through the existing-identity `RecoveryVault`, but cannot create/replace a key or initialize a database. Missing or malformed envelopes, and changes after the retained inspection, remain closed. With no database to authenticate, a well-formed slot value has no independently authenticated earlier-value baseline; this path does not claim otherwise. Format/identity validation of a key without a database is not a claim of authenticating absent data or resisting a compromised OS account. + +Retain the exact operation/binding/directory proof and existing key privately in zeroizing custody with a one-shot token. A renderer gets no token, key or replacement original. Lock, close, exit, failed inspection, replacement inspection and dropped operation must invalidate the plan and release key custody. Repeated/wrong/stale tokens refuse before a new vault read; do not reuse public display fields as the retained plan. Preserve existing ordinary recovery custody and lifecycle gates. + +### Explicit completion and later recovery + +A new native `InitializeEmpty` confirmation must state that it will create the missing empty encrypted database using the existing key, keep the original and require later unlock/restore. Do not call this metadata-only Reconcile, select the workspace, unlock the workbench or authorize any provider/action. Cancel consumes/releases the retained plan, leaves all bytes and the existing key unchanged and offers a fresh recovery choice. + +On approved completion, consume the exact retained plan before any effect and revalidate the operation, binding, directory/absence proof and existing key. Never invoke `create_key` or delegate a slot write; the RecoveryVault continues to reject writes. Use the existing pinned encrypted store constructor and initialization path, exact fixed destination and bounded inventory validation. Revalidate complete original capture/native permit around host actions. After a real empty encrypted inventory exists, durably finish the same CreateEmpty attempt's ready binding and terminal observation using current bounded record/sync/readback rules. Do not rewrite adoption Target, invent a new attempt, treat initialization as restored content, or copy source data during this operation. Success returns locked with no content client; only native-confirmed Unlock then explicit Restore may populate the destination. Full parity precedes Copied; distinct-process Verify and later ordinary Unlock remain separate. + +Failure before a write leaves the attempt unchanged; any attempted write with uncertain outcome remains recovery-required without retry. An interrupted finish that leaves a valid empty database must flow through existing authenticated-inventory inspection and metadata reconciliation, never repeat initialization. An absent database may be inspected again through this explicit path; a corrupt/zero-length/partial database refuses instead of overwriting or deleting it. No cleanup, key deletion, rollback of original data or broad repair utility is included. Local metadata remains unauthenticated; preserve current threat-model limits and no security/compliance claims. + +### Proposed exact ownership, checks and acceptance + +Root owns protected `apps/desktop/src/{workspace_session,workspace_recovery,workspace_adoption,workspace_startup,workspace_startup_host}.rs`, new `apps/desktop/src/workspace_empty_provisioning_tests.rs` registered under the existing Owner test module, and exact recovery regressions in `workspace_adoption_tests.rs` and presence-proof regressions in `workspace_startup_tests.rs`. Root integrates the existing `native_encrypted_qualification.rs`, private case-plan Rust/JSON and parent/Python tests only for this bounded pending-CreateEmpty chain and distinct consent purpose. Canonical documentation is `docs/{intent,encrypted-workspace,continue,development}.md`. No store schema/crypto/archive/public provider contract, dependency, engine port, provider, LNSAT/VUSL, normal data/key operation, publication or release belongs here. No general Owner fault API is accepted by this proposal. + +Acceptance tests must cover: (1) real isolated process interruption after envelope write with no database; (2) cancelled Inspect/InitializeEmpty, rotated/stale/repeated actions and zero unintended vault access; (3) exact same workspace/attempt/key with zero slot writes and original byte/archive/identity preservation; (4) complete native Inspect → InitializeEmpty → Unlock → Restore, Copied, distinct-process Verify and current Unlock with full records/revisions; (5) missing/changed/malformed key, wrong identity, foreign/damaged records and non-CreateEmpty rejection; (6) no destination overwrite, linked/extra/zero-length/partial files, stale directory/binding/operation proof and backend absence; (7) lost waiters, Lock/exit/C1 revocation and retained-key drain; (8) failure before/after initialization, ready sync and terminal write/readback, actual process restart and no initialization replay; (9) existing normal creation, metadata-only recovery, composition/compilation/export and 40-phase harness contracts unchanged; (10) all complete native artifact-bound disposable cases and Windows/Linux qualification before release. Any required new durable-effect observer needs its own frozen narrow definition; do not fake crash states by deleting records. + +Run scoped Rust formatting; locked/offline native default/no-default all-target tests, docs, builds and warnings-denied Clippy; existing encrypted/default store and portable workspace gates because library recovery semantics change; renderer/native startup consent, lifecycle/purge tests; Python case-plan/parent tests; review/document/image/whitespace and outside-owned preimage checks. Require fresh independent design, source/evidence and actual native UI review. The recorded E1c-5d acceptance explicitly authorizes this source and isolated disposable macOS tests; implementation and qualification still require the checks above. Normal data/keys, providers/engine changes, dependency fetches and publication stay closed. + +### Finite interrupted-provisioning qualification chain + +The accepted harness extension preserves all original 40 case objects and their order, adds the `legacy-rich-provisioning` root and six phases before cleanup, and retains the private case-plan version and 16 KiB/32-root/64-case bounds. The resulting plan has 46 phases and 14 roots. Its independently reviewed pre-code snapshot is `/rangoon-e1c5d-source-20261019/harness-plan-v1.md`. This extends the existing qualification-only CountingSlot barrier; it introduces no Owner fault API or production effect observer. + +| Phase | Native confirmation and required outcome | +| --- | --- | +| Crash | Populated Legacy Copy approved; exactly one successful isolated OS slot write, then parent SIGKILL at the existing provisioning barrier before CreateEmpty returns; no database, client, completed startup or native Exit | +| Inspect cancellation | Inspect cancelled; zero vault opens/reads/writes; exact original, pending/binding/control/Target and absent-database proof preserved | +| Initialization cancellation | Inspect approved, InitializeEmpty cancelled; existing-key reads only, zero writes, identical stopped-child storage proof and fresh recovery choice | +| Resume | Inspect → InitializeEmpty → Unlock → Restore separately approved; absent database becomes encrypted restored content, original and adoption prefix remain exact, full parity precedes Copied; no key writes or client | +| Verification | Distinct process and explicit Verify; existing-key read, complete source-to-destination parity, durable Reopened and selection, no content client | +| Relaunch | Another process and current Unlock; client only after native confirmation, no key write or storage change | + +The existing key-write wrapper records its fixed run-scoped selector before invoking OsSlot.write. The new crash case adds only nonsecret custody counters to the existing barrier observation. Both provisioning barrier cases wait at most 120 seconds; timeout reports uncertainty instead of continuing setup. Successful OS write followed by real process-restart read is OS behavior evidence, not a power-loss durability guarantee. + +The parent observes only fixed, bounded, no-follow stopped-child paths. For the new root it retains opaque Owner metadata file identities, lengths and hashes, exact child-name sets, fixed directory identities, original database digest and adoption-record prefix. No key/envelope body, SQL or metadata semantic parser is added. The first three phases require no database or sidecars. Cancellation preserves the full snapshot; Resume alone permits absent-to-present initialization and legitimate binding/Pending/terminal updates. Real Restore starts its own operation, so the original CreateEmpty Pending is checked by the source fixture before Restore rather than falsely required to survive Restore unchanged. Verify/Relaunch remain read-only. + +All 46 phases must qualify against one final source/artifact/plan identity with case-specific receipts and independent UI/evidence review. Synthetic parent traces and earlier runs of unlike binaries cannot establish that verdict. Normal data/keys, providers, dependency fetches, publication and release remain closed. + +## E1c-5e ordinary lock and startup handoff — proposed correction + +Status: accepted source and isolated disposable macOS tests by Jeff’s explicit “Accept E1c-5e source/tests”; [accepted intent](intent.md#e1c-5e-ordinary-lock-handoff-acceptance--october-20-2026) owns acceptance. The heading retains its proposed-correction anchor for stable links. The E1c-5d disposable native reproduction found ordinary Lock calling terminal startup retirement. Native Unlock succeeds, then its renderer reload receives unavailable startup state. [The development receipt](development.md#e1c-5d-disposable-native-qualification-in-progress) owns observations and artifact identities. This proposal does not explain the earlier synthetic-preview jump, which remains unattributed. + +Root owns the protected native correction in exactly `apps/desktop/src/workspace_close.rs`, `apps/desktop/src/workspace_startup_host.rs` and `apps/desktop/src/workspace_native_bootstrap_tests.rs`, plus `docs/intent.md`, this contract, `docs/continue.md` and `docs/development.md`. Preserve all unrelated work and the frozen E1c-5d preimage. No renderer, harness, schema, dependency or cryptographic change is proposed. + +Separate ordinary Lock retirement from terminal exit/failure. Make one atomic decision under the existing Host mutex over `terminal`, `busy`, `plan` and `outcome`. Preserve only an already completed private non-effectful Handoff when the Host is not terminal, has no busy Work and has no retained Plan. Every other state follows terminal retirement: retain an existing terminal latch, clear the outcome and detach any Plan under that same mutex, then drop detached custody outside the mutex in the existing real blocking cleanup path. A busy Work must observe retirement before publishing any result and retain its Flight until actual cleanup completes. Do not precheck and retire in separate critical sections. + +Ordinary Lock must classify the Host before source-close cancellation can unblock an active Work. Hold any detached custody in a named cleanup-only guard while synchronously beginning source closure, then dispatch its drop outside the Host mutex. This ordering prevents a Work that has passed its final Flight check from publishing a late Handoff between cancellation and classification. A previously completed idle Handoff linearizes before Lock; a busy Work becomes terminal before cancellation. Neither the guard nor an empty guard is approval, a retained action or permission. Pending Plan custody already owns a Flight on a closed source cycle; an unwind cannot reopen admission. Exit and failure continue to use unconditional retirement. + +The preserved Handoff carries no action, startup/close identity or permission. It must not recreate an Owner, publish a client, bypass current native protection checks or restore an old action/confirmation; a later ordinary Unlock still requires its independent native confirmation and current lifecycle checks. Incomplete, active, stale, failed or ambiguous startup work must still lose its plans and drain retained custody. Real exit, window destruction, failure and concurrent terminal retirement remain irreversible for that Host. Do not reset a terminal flag or replace managed state to make reload succeed. Reuse the existing handoff DTO and current native lifecycle; new public contracts are unnecessary. + +Acceptance requires real Host/WorkspaceClose tests for repeated ordinary Lock/unlock after fresh setup and verified Legacy adoption, plus negative coverage for incomplete plans, stale actions, active workers, terminal exit/failure and concurrent retirement. Add a deterministic barrier where ordinary Lock races active Work: it must terminal-retire that state, reject late publication and keep real custody/Flight drain pending until cleanup, without reviving an action, confirmation, Owner or client. Include terminal exit racing an otherwise retainable Handoff; the terminal latch must win permanently. Prove that refusal performs no extra key write and malformed/wrong-window requests cannot change lifecycle state. Existing source and renderer tests must remain intact. Any uncertainty about safe handoff retention returns to design review before implementation. + +Run focused regressions, the ten pinned locked/offline native gates, existing 38 Python parent and 69 renderer/lifecycle checks, documentation/whitespace and outside-owned preservation checks. Obtain fresh independent pre-code and final source/evidence review. Then build a new artifact and repeat the actual native held-read → Lock → purge/drain → confirmed Unlock → workbench/historical opening and missing/stale/current-header checks. Full 46-phase qualification must eventually use one corrected source/executable/plan; old and new artifacts cannot be aggregated into a full pass. Windows/Linux remain separate release gates. + +Accepted scope covers source, disposable nonce-scoped macOS testing and exact cleanup. Normal data/keys, existing user workspaces, provider contact, LNSAT/VUSL edits, dependency fetches, publication, merge, deploy and release remain closed. A diagnostic UI failure is not evidence of plaintext fallback, lost encryption or unauthorized provider execution. + +## E1c-4 integrated native encrypted workspace qualification — proposed + +Status: accepted source and eight disposable macOS qualification cases. Jeff explicitly answered “Accept E1c-4” to the reviewed scope, including isolated Keychain setup, process restart, intentional test-key loss and exact cleanup. The heading retains its existing anchor; this acceptance supersedes the earlier proposed status only for the named packet. Authority remains the accepted encryption completion program in [intent.md](intent.md#encryption-completion-continuation--october-14-2026). E1c-3 supplies the source-qualified constructor; this packet joins the existing components into an actual disposable application. It does not replace the encryption, request, recovery or close protocols. [Development](development.md#encrypted-native-adoption-packet--october-18-2026) owns review evidence and acceptance state. + +### Outcome and current plaintext exposure + +The next useful result is a native workbench that creates an encrypted workspace after explicit confirmation, saves and reopens real synthetic authoring records, locks, quits, and unlocks the same records in a new OS process. A successful constructor test or simulated renderer does not meet this outcome. + +| Surface | Current source behavior | Completion requirement | +| --- | --- | --- | +| Ordinary desktop startup | `source_state` always chooses Legacy, including an encryption-feature build | Qualify the real encrypted startup path before selecting it for new workspaces | +| Managed persistence | SQLCipher-backed Owner and typed source, capability, workflow and composition routes exist; normal startup does not mount them | Exercise the same request-bound routes through native IPC, actual renderer and real OS custody | +| Existing Legacy workspace | Existing SQLite data remains plaintext | Separate explicit migration preview, stable source snapshot, verified separate encrypted destination and recoverable cutover; retain the original until separately authorized cleanup | +| Portable workspace backup | Legacy exports plaintext; Managed native export refuses before picker/serialization | Keep unavailable for Managed until an independently qualified encrypted archive/recovery format exists | +| Instruction bundles and original imported files | Deliberately readable files outside the workspace database | Keep explicit output selection and plaintext disclosure; database encryption must not relabel or silently rewrite these files | +| Metadata, logs and process memory | Nonsecret recovery identities remain readable; unlocked authoring uses memory | Verify source/key absence in app-owned metadata/logs and residual files; do not claim protection from an unlocked compromised OS account, crash dumps or OS snapshots | + +### Shared startup sequence + +Refactor the existing native Builder/state/handler registration and main-window creation into private shared helpers used by the ordinary entry and the isolated qualification entry. Production still supplies its current Legacy factory; only the explicit qualification target supplies `SourceAccess::managed_locked` and the OS-vault adapter. Preserve all existing handlers and lifecycle ownership; do not create a parallel application implementation or replace SourceAccess after consent. + +The shared sequence is: + +1. Setup registers the single Gate, SourceAccess, WorkspaceClose and existing native model/custody/OpenShell states. It does not create the main webview yet. +2. On Ready, install the existing externally owned lifecycle anchor. For Managed startup, anchor failure latches failure and refuses the workbench. There must be no usable main webview before this ownership exists. +3. For Managed startup, begin the real initial close cycle using `WorkspaceClose::begin` and the actual native cleanup function. `begin` creates the first attempt; no new initial-Locked state is necessary. Do not call an exit-specific operation to establish startup, fabricate cleanup flags, or issue a client. +4. Create the shared main webview only after a valid initial Closing cycle exists. The existing renderer initializes, purges and acknowledges that exact cycle; native drain then permits Locked. Existing C0/C1 protection controls and the parented OS consent sheet perform create/unlock. Success consumes native completion, reloads the document and issues a fresh request identity. +5. Legacy startup preserves current authoring behavior. Failed window creation, invalid initial cycle or anchor failure must produce a fixed failed outcome and keep admission closed; the exit coordinator must not translate a startup failure into a successful clean-start receipt. Retain the anchor until the actual Exit callback. + +Do not add renderer paths, automatic key reads, credentials, a user-facing security bypass, new wire states or a new crypto format. An OS-vault adapter opens only the slot for the native Owner's identity and the fixed application identifier. Constructing it must not read/create a slot; those operations occur only inside the existing native-confirmed Owner operation. + +### Qualification target and isolation + +Add a separate explicitly selected custom Cargo test target, `native-encrypted-qualification`, with `harness = false`, `test = false`, and required encryption/qualification features. Normal builds and ordinary tests must not run or include its entry, fault controls or key-deletion helpers. Resolve simultaneous NX-06/encrypted-qualification feature selection explicitly: ambiguous target arguments refuse before Builder construction. Do not silently change NX-06's six accepted cases or its permission-free context. + +Use its own configuration directory and exact identifier `si.rangoon.encrypted-qualification`; Tauri code generation resolves configuration by directory, so a sibling filename is insufficient isolation. Embed the existing workbench assets, the same CSP/navigation policy and an explicit local-main-window capability allowlist for lifecycle and the named local authoring operations. Do not inherit `source-analysis` wholesale: it also grants cloud credential and model transport commands. No remote capabilities, dev URL, external asset host, cloud/model credential windows or provider calls are permitted. Dialogs must use the existing native plugin and consent code; fixtures must not replace the positive-path OS confirmation with `true`. + +The runner creates an exclusive disposable run directory under the OS temporary directory and records its canonical identity. Each case root is a fixed child derived from a validated native run nonce and finite case name, never a renderer/user path. Reject preexisting roots on initial creation and reject linked/replaced roots on every launch. Q4/Q5 may reopen only the exact case directory recorded by this runner, with validated directory identity and expected phase; a new run cannot adopt an old directory. Pass only the bounded run identity/case to the test executable; production gains no CLI or environment path override. No normal app-local data directory is opened or migrated. The qualification app's OS-owned webview/cache directory must be separately identified and reported; do not claim the test writes only its database directory. + +Real-vault cases use service `si.rangoon.encrypted-qualification..encrypted-workspace-key.v1` and account `workspace-`. Neither string is a secret. The run nonce is lowercase fixed-length hexadecimal and the full identifier satisfies the existing 128-byte limit. The application knows this namespace before any slot access; it never falls back to the production application identifier or a cloud credential service. Count slot opens/reads/writes without logging key/envelope bytes or key fingerprints. Do not transfer, serialize, print, persist or pass keys in process arguments/environment. A real process restart reads the same exact slot after fresh native consent; an in-memory fake vault is not restart proof. + +Cleanup and the intentional missing-key case may delete only exact slots created by this run. Maintain a source-free registry of native-created workspace identities, validate each against the run namespace and refuse arbitrary selectors. Use the pinned native keyring backend's exact-entry deletion and confirm absence. Keep this facility inside the qualification target; do not add a general product key-delete API or shell-wide Keychain cleanup. Record each created/deleted slot and any leftover, without secret values. Cleanup failure stops the run and reports an exact leftover; it does not authorize deleting other entries. Loss of this disposable key intentionally makes that disposable database unrecoverable. Never apply the key-loss test to any ordinary workspace. + +### Native cases and evidence + +| Case | Required real behavior and oracle | +| --- | --- | +| Q1 cold start and cancel | Locked Owner starts without vault reads/writes or ordinary request admission; real renderer completes Closing to Locked; cancel the native setup sheet and verify no key/database/client was created | +| Q2 setup and authoring | Confirm native empty setup; use synthetic source through the real picker; save/open source, create/revise/review a capability, compose saved inputs, compile, and save/open a workflow through real IPC; compare identities/content and verify database is not a plaintext SQLite file | +| Q3 lock and stale results | Retain synthetic content and an ordinary request in flight; Lock fences admission before drain, renderer purges retained data, stale/absent headers and late completions cannot repopulate content; only fresh confirmed unlock restores usable requests | +| Q4 quit and process relaunch | Quit actual app, observe process termination and released Owner; launch a distinct PID using the same run/case root and OS slot, confirm native unlock, and compare Q2 records, revisions, relationships and compilation byte-for-byte | +| Q5 missing disposable key | After a clean exit, delete only Q2's exact registered test slot; relaunch and confirm unlock; require a closed fixed key-failure state, zero replacement writes and unchanged database bytes; no Legacy fallback or empty setup | +| Q6 busy and interrupted setup | A second process cannot acquire the first process's root. In a separate fresh root, a qualification-only Store wrapper delegates the real OS-slot write, then reports a fixed barrier and holds before returning to `create_key`; Owner has already durably recorded Pending and the provisioning binding. Parent terminates that exact child PID at the barrier. Relaunch must expose recovery-required state without another vault read/write, ordinary create/unlock, automatic replay or a second store. This proves interrupted provisioning after a key write, not interruption after an authoring database commit or arbitrary OS failure | +| Q7 startup/lifecycle failure | Inject anchor-install, initial-cleanup and main-window-creation failures in the qualification target only; no ordinary admission, success receipt or silent Legacy fallback; bounded termination and fixed failed diagnostics | +| Q8 plaintext-output refusal | Managed backup export refuses before picker/archive bytes; successful instructed plaintext instruction export requires its own real output selection and disclosure and does not become a recovery archive | + +Q6 uses the existing public Vault/Store boundary only; it does not expose private `Owner::inject_fault` or add production recovery hooks. The barrier contains no key/envelope bytes, and the parent uses a bounded timeout and its own child handle. Other post-commit authoring interruption and disk-full cases remain separately unqualified native evidence; existing source tests are not promoted to those claims. + +Positive native cases must exercise the actual app renderer, native command dispatch and OS dialogs. Browser mock fixtures, direct Owner calls, scripted synthetic consent and same-process reacquisition may supplement but cannot replace Q1–Q4. Any unsupported automation leaves a case explicitly unrun, never passed from source tests. Keep native screenshots and parent-observed source-free event/exit receipts. Store only synthetic content in this run. Inspect database, journals/WAL/SHM, app-owned temporary files, recovery metadata and logs for the known synthetic content marker; distinguish an intentionally selected plaintext instruction export from a storage leak. Absence of that marker is bounded residue evidence, not a general zeroization or secure-erasure proof. + +### Exact ownership and validators + +Root owns protected startup integration in `apps/desktop/src/{main,workspace_close,workspace_failure}.rs`, private native OS adapter `apps/desktop/src/workspace_native_bootstrap.rs`, `apps/desktop/Cargo.toml`, and integration of the new explicit target `apps/desktop/src/native_encrypted_qualification.rs`. The target may reuse shared Builder, handler and main-window helpers but never export test faults into production. Root owns the isolated config `apps/desktop/native-encrypted-qualification/tauri.conf.json` and parent runner `scripts/qualify-native-encrypted.py`. A bounded native worker may own only new `apps/desktop/src/workspace_native_bootstrap_tests.rs`; root integrates it. Existing `apps/desktop/src/workspace_managed_bootstrap_tests.rs` may receive only bootstrap-regression assertions. Documentation ownership is `docs/{intent,encrypted-workspace,continue,development}.md`. Read all existing changes before edits; preserve NX-06/O2/E1c-3 work. + +No dependency/lockfile, store schema, cryptographic primitive, production config/capability, renderer source, provider, LNSAT, migration or default-backend change belongs to this packet. If native qualification reveals a renderer or storage defect, record the exact failing case and propose a bounded correction; do not fake the result or silently enlarge ownership. The ordinary main-window timing changes are real product behavior and need Legacy regression checks even though its backend stays Legacy. + +Run Rust 1.99.1 desktop formatting; locked/offline default and encrypted tests/builds; both all-target warnings-denied Clippy variants; existing renderer lifecycle/request/control tests; `node scripts/validate-review.mjs`; `git diff --check`; exact outside-owned preimage checks. Verify ordinary target selection/default isolation and combined qualification-feature argument rejection before launching either test app. Rerun all accepted NX-06 native cases against the exact changed source because shared startup/lifecycle code changes. Bind each encrypted qualification receipt to source/config/assets hashes, executable hash/architecture, OS version and distinct process IDs. Parent runner enforces bounded output/timeouts, verifies actual exit codes and rejects Python optimization/assertion bypass. Require fresh independent pre-code and final source/native-evidence review. No x86_64-on-arm64 run claims native arm64, Windows/Linux or packaged support. + +Acceptance of this proposal opens only this source and these disposable macOS/Keychain cases, including exact test-slot cleanup/key-loss and native UI interaction. It does not open normal user data/vaults, default switching, migration, providers, LNSAT edits, credentials, network operations, publication, deployment, signing or release. + +### Q3 deterministic in-flight read implementation note + +This refines the already accepted Q3 qualification outcome within the existing target and runner ownership. It does not accept renderer, store, production capability or default changes. The first native subcase will hold the next real ordinary encrypted read at the existing qualification-only `CountingSlot::read` boundary before OS-slot access. `Owner::open/list` revalidates the slot through `checked` and `verified_workspace`, so the actual dispatched request retains its Gate lease and backend custody while held. No content, key or replacement result enters the barrier. + +The parent may arm this one-shot barrier only in the disposable authoring phase after native state is open. Finite `arm-read`/`release-read` controls accept no script, path, payload or identity. Invalid ordering refuses. The barrier has a bounded monotonic timeout and fails closed without delegating a read on timeout. Release is permitted only after the real Lock flow has fenced admission and native observation is Closing without a client. It resumes the original OS-slot read and unchanged request/delivery path, never synthesizes success, unlock or purge acknowledgment. Ordinary builds contain none of these controls. + +Use actual UI to open a saved synthetic source, initiate Lock and confirm discard while its request is held. Record the pending read, Closing state, absent client, UI purge, release and eventual Locked state. The barrier and native event sequence are deterministic; actual purge and non-repopulation are separately inspected through native accessibility/screenshots. The parent keeps its UI verdict unassessed, and this manual subcase cannot be reported as an automated renderer oracle or complete Q3 qualification. Confirm that no stale source reappears after completion; only a fresh native-confirmed unlock permits a subsequent ordinary read. Parent receipts must reject armed-but-unconsumed, timed-out, duplicate or incomplete barrier sequences, and must not equate clean exit with a passed UI journey. + +This subcase alone does not prove explicit missing/stale request-header injection or every delayed transport response. Those Q3 requirements remain open until a separate exact oracle exercises the real dispatch boundary. Scope is `apps/desktop/src/native_encrypted_qualification.rs`, `scripts/qualify-native-encrypted.py` and the existing three specification/status records. Root implements; independent read-only review checks the barrier, cleanup/deadlock behavior and raw evidence. Run focused barrier/parent negative tests, existing default/encrypted suites/builds/Clippy, renderer lifecycle checks, ordinary-target isolation, documentation and scope checks. The completed qualification must eventually replay all required native cases against one selected executable; source-digest equality cannot replace binary identity. + +### Q3 native request-header qualification note + +This completes the explicit missing/stale-header portion of accepted Q3 using only the existing qualification target and runner. Root owns the same five files as the preceding in-flight note. A read-only native GPT reader traced the exact production command/header path; fresh independent review must assess the implemented probe before any disposable run. + +Two finite parent controls are allowed in the authoring case: `capture-client` privately retains the current native request identity while Open; `check-headers` requires a distinct Open identity after an actual confirmed Lock/unlock cycle. Neither accepts a script, path, identity or payload. The test target evaluates a fixed script through the real main WebView, invoking the existing `list_snapshots` command without a header, with the revoked identity, and finally with the fresh identity. The production handler and `WorkspaceRequest` extraction remain unchanged. The callback channel returns only finite pending/refused/listed/failed classification; it never emits request identities or snapshot metadata. Evaluation and polling are bounded; duplicate controls, malformed callback data, timeout, unexpected responses or changed lifecycle state fail qualification. + +Each negative probe must return the exact `workspace_unavailable` failure shape without list/content fields, with unchanged native vault-read/write counters. The fresh positive control must return a nonempty saved-source list and perform a real vault read. A renderer-reported classification is transport-level test evidence, not a production trust boundary. This probe does not replace the separately observed purge/late-completion journey or claim exhaustive command coverage. For this subcase, launch the parent as `run NONCE authoring --require-headers`. Its required mode rejects zero or incomplete header events even after clean exit. The receipt records `requiredHeaderProbe` and `headerProbeVerified` separately from the still-unassessed complete native UI verdict. General authoring mode remains available for Q2-only work and does not establish Q3 coverage. Header evidence requires capture, native Locked observation, a new Open generation, all three ordered outcomes and clean actual exit; clean exit alone is insufficient. No fixture credentials, normal data/keys, production permissions, default switch, provider, LNSAT or release changes belong to this qualification. + +### Product completion immediately afterward + +Do not mistake this qualification target for the finished encrypted product. Next deliverable is the reviewed normal-startup cutover with a visible Legacy-data state and no new plaintext store. Existing users need an explicit migration into a separate destination; freeze source writers, preserve a stable SQLite snapshot, transfer the complete version-aware inventory, verify every source/revision/review/composition/workflow identity and relationship, then record recoverable cutover. Interruption and disk-full cases retain the original and never silently select an empty destination. Original plaintext files/backups remain disclosed until the user separately chooses cleanup; SSD/snapshot erasure is not promised. This migration is not implemented or authorized by E1c-4. An encrypted portable recovery archive is a separate usability prerequisite for recoverable key loss, with its own format and key/recovery design; until qualified, the application must say recovery is unavailable. Qualify each supported OS/backend and package independently before release. + +## E1c-4a native cancellation and storage disclosure correction — proposed + +Status: accepted by Jeff’s explicit “Accept E1c-4a correction” response on October 18, 2026; implementation and validation are in progress. This is a bounded correction to defects observed during the accepted E1c-4 native cases, not a default-backend cutover. The [native evidence receipt](development.md#e1c-4-native-target-and-disposable-evidence--october-18-2026) owns the findings. E1c-4 explicitly excludes renderer and setup-response changes, so its acceptance does not cover this additional source packet. + +**Observed defects.** Cancelling the actual setup sheet leaves the native Owner locked, protection layout absent, no database/client and zero vault access, but the renderer displays “Workspace recovery required” with no setup retry. `workspace_setup::confirm` currently folds declined consent into `closed/workspace_control_not_completed`; `beginProtection` accepts only `opened` and treats every other result as recovery. The source-save disclosure also always says “unencrypted” when the qualified native route is using Managed encrypted storage. + +**Required correction.** Preserve the existing control schema and exact close-cycle identities. Distinguish explicit native user cancellation from unavailable parent/callback, invalid preview, panic, failed preparation, failed cleanup, failed consumption and response loss. Use an internal typed native consent result; only the actual Cancel result while the worker and preview remain valid may select the existing `cancelled` outcome. Release retained control through the current Flight cleanup before reporting cancellation. Native cancellation must remain closed and must not invoke Owner confirmation, publish a client, read/write the vault or request a reload. If cleanup or state validation fails, keep the existing failure path. + +The renderer may restore setup/unlock only after validating the returned cancellation against its exact current C1 cycle and re-reading the authoritative native control/protection state. Reuse the existing fresh purge, closed-state polling and protection-entry functions; do not infer storage health from the button click. Malformed, stale, wrong-cycle, wrong-storage, opened/reload-shaped cancellation, late callbacks and delivery-unknown results remain blocked. Setup cancellation should return to the native `absent` protection layout; unlock cancellation to `locked`. An actual recovery-required native result must stay recovery-required. + +Source-save wording must use the existing validated workspace state. Managed open state may describe encrypted workspace storage; Legacy must keep its plaintext disclosure; browser/unavailable/unknown states must not claim encryption. Source files and instruction exports remain readable external files. Do not infer encryption from a Cargo feature, URL, test fixture or renderer preference. + +**Exact ownership.** Root owns protected native consent integration in `apps/desktop/src/workspace_setup.rs`, its focused regressions in `apps/desktop/src/workspace_setup_tests.rs`, renderer coordination in `preview/workspace-lock-model.mjs`, and the save disclosure in `preview/analyze.mjs`. The two existing direct confirmation fixtures in `apps/desktop/src/workspace_managed_bootstrap_tests.rs` receive only mechanical typed-consent updates. A disjoint native worker owns only `tests/workspace-lock-model.test.mjs` and `tests/workspace-save-disclosure.test.mjs`; root integrates. Documentation ownership remains `docs/{intent,encrypted-workspace,continue,development}.md`. No schema, database, crypto, dependency, permissions, export behavior, normal backend selection, migration, provider, LNSAT or publication change is included. + +**Acceptance and validators.** Add native tests for explicit decline versus unavailable/panicked consent, failed cleanup, concurrent close/exit and late completion; assert zero Owner confirmation/client/vault effect for cancellation. Add renderer tests for setup/unlock cancellation, exact C1/fresh-state checks, repeated cancellation/retry, malformed/stale/cross-cycle results, disposal and delivery loss. Keep the existing 29 lifecycle/request/control tests. Verify Legacy, Managed, browser and unavailable save disclosures. Run formatting, locked/offline default/encrypted desktop tests/builds, both all-target warnings-denied Clippy checks, `node scripts/validate-review.mjs`, `git diff --check` and exact scope checks. Obtain fresh independent read-only review before the native rerun and on final evidence. Repeat Q1 with a fresh source-bound target: actual setup sheet Cancel, usable setup retry, no database/client/vault access; then complete Q2–Q5/Q8 under the original E1c-4 scope. Q3 in-flight/stale-response qualification still needs actual evidence and cannot be inferred from a normal Lock click. + +## E1c-3 encrypted startup integration proposal — October 18, 2026 + +Status: **unmounted source implementation and independent source review passed**; the current source receipt owns remaining qualification. Authority is the [current source continuation](intent.md#encrypted-startup-source-continuation--october-18-2026) under the existing encryption completion program. The heading retains its proposal anchor for existing links. The [source receipt](development.md#encrypted-startup-source-integration--october-18-2026) owns current validation; the preceding audit remains historical evidence. No second encryption mechanism, database schema, authorization engine or replacement lifecycle is proposed. + +### Observed integration gap + +The normal desktop `source_state` still selects Legacy, including builds with `encrypted-workspace`. At the audit baseline, the actual `Managed` backend, managed errors and composition handles compiled only for tests. Its fixture constructor calls `host_fixture()`, bypassing the normal request-generation path. The implemented source packet lifts backend/handle compilation to the optional feature and adds a separate locked constructor; the old fixture constructor remains test-only. Simply promoting that fixture would have been incorrect. + +There is also a cold-start mismatch: a newly acquired locked Owner paired with `WorkspaceClose::new` has no close attempt, so the close snapshot reports `open`; its new managed request Registry has no client and reports `unavailable`. The renderer's open bootstrap requires that client and fails closed. Existing setup tests initialize or manually close their fixtures; NX-06 uses a memory-only close fixture. Neither proves a real locked encrypted application startup. This is an unmounted integration defect, not evidence that the current Legacy application or encryption algorithm is broken. + +### Required startup and recovery behavior + +1. Construct one Owner-backed backend under the existing optional encryption feature, with the same shared Gate, sessions and Registry. The production-shaped constructor must keep `Caller::Request(Refused)` and an empty Registry; `HostFixture` and fault injection remain test-only. A locked backend must exist before setup/unlock consent so the existing closed-cycle controls can operate. Never construct a second Owner after consent or replace SourceAccess during an active session. +2. Acquire only a trusted native root. Do not add a renderer path, environment-variable override, CLI path or ambient credential lookup. Owner acquisition can create its cooperating lock file, so it is a mutation of a specifically selected disposable/native-owned root, not a read-only inspection. It must not read a key, open an encrypted database, prepare provisioning or create a client. Acquire/feature/busy failures remain typed failures; never fall back to Legacy. +3. Establish the first real close cycle before exposing an encrypted workbench as usable. Reuse `WorkspaceClose::begin`, existing native cleanup, callback drain and renderer purge/acknowledgment. Present `closing` until those proofs exist, then `locked`; do not assign `Locked`, `native_done`, `released` or acknowledgment booleans directly to skip cleanup. The ordinary registry remains unavailable until successful setup/unlock consumes native completion. No new wire state or synthetic client is required to solve this mismatch. +4. Preserve the existing source-free layout and C0/C1 setup/unlock path, native consent, retained callback ownership, durable uncertainty evidence and fresh document reload. Missing keys, malformed layouts, busy roots, incomplete cleanup and lost delivery remain closed. Successful reopen must obtain a fresh request identity; old and absent headers must remain refused. Recovery-required layout must not offer setup or ordinary unlock. +5. Keep the ordinary Builder on Legacy in this source packet. Do not change `source-workspace`, auto-import plaintext, add a user-facing mode toggle or mount OS-vault access. Production mounting needs a separately reviewed trusted-root selection and native-host installation order before the first main webview can issue IPC. A source constructor alone is not encrypted desktop adoption. + +### Exact proposed source scope and ownership + +Root owns protected implementation and integration. Existing source paths are `apps/desktop/src/workspace_source_access.rs` (feature-only backend/errors and a separate production-shaped constructor), `apps/desktop/src/composition.rs` (matching feature-only managed handle/preview arms), and `apps/desktop/src/workspace_source_access_tests.rs` (retain the test-only fixture constructor and update its exact isolation assertions). Add `apps/desktop/src/workspace_managed_bootstrap_tests.rs` as a cfg-test child of the existing source-access tests, reusing their disposable root and fake vault. Do not promote the existing test constructor or its `HostFixture` caller. + +Freeze the host-private signature as `SourceAccess::managed_locked(gate: Gate, root: PathBuf, vault: V) -> Result`, with parent-module visibility only. It calls `Owner::acquire` exactly once and builds the existing backend through `with_mode(..., true)` without `host_fixture()`. It accepts no already-open Owner, does not inspect a key or issue a client, and propagates acquisition errors. This constructor alone does not claim a completed Locked lifecycle. The paired test/caller sequence is constructor, `WorkspaceClose::new(access.clone())`, real `begin`/cleanup/drain, renderer purge acknowledgment, then protection/layout and C0/C1 control. The future native caller must establish that sequence before exposing the workbench; this source packet does not supply that caller. Test cleanup/consent doubles are named as synthetic and include false/error outcomes; they are not native window or OS-consent proof. Compose existing lifecycle methods without changing their semantics or wire DTOs. If it cannot establish the required initial cycle without changing `workspace_close.rs`, `workspace_requests.rs`, native host/window order or the renderer, stop and amend this proposal with exact behavior and review rather than silently extending ownership. Those files are audit inputs, not owned source paths in this packet. No OS-vault implementation or native bootstrap caller is introduced here. The unused production-shaped constructor may have one localized documented dead-code allowance until the separately qualified caller mounts it; blanket warning suppression is forbidden. + +Supporting documentation ownership is `docs/{intent,encrypted-workspace,continue,development}.md`. No dependency, lockfile, schema, permission, CI, provider, LNSAT or production default changes. Preserve all NX-06 and O2 work. Native GPT read-only evidence and fresh independent review are permitted; no private-source transfer to an external model provider is included. + +### Acceptance and named validators + +Use the production-shaped constructor in every new positive test, never `.host_fixture()`. Prove: absent and existing encrypted roots start without a vault open/read/write or keyed database read; no ordinary request is admitted before consent; actual first close cycle and acknowledgment expose the correct layout; explicit empty setup creates a real SQLCipher database; explicit unlock reopens existing content; source save/read and at least one capability/composition/workflow route use the real header-bound request identity; close invalidates that identity and releases Owner custody; reacquisition with the same fake vault preserves saved identities; missing key does not regenerate; busy/orphan/torn metadata refuse safely; cancellation, stale C0/C1, dropped result and failed cleanup never publish an open client. Reacquisition within one test process is not process-restart qualification. Assert actual operation/custody counters and decrypted domain records, not success labels alone. + +Run pinned Rust 1.99.1 `cargo fmt --manifest-path apps/desktop/Cargo.toml --check`; default and `--features encrypted-workspace` forms of desktop `cargo test --locked --offline`, `cargo clippy --all-targets --locked --offline -- -D warnings`, and `cargo build --locked --offline`. Preserve privacy doc tests and default-feature isolation. Run `node scripts/validate-review.mjs`, `git diff --check`, exact changed-path/preimage checks, and a fresh independent source/evidence review. If startup/source changes affect NX-06 compilation or its shared coordinator, rerun the accepted full native matrix with the new source hash; do not reuse an older runtime receipt for changed code. + +### Completion path beyond this packet + +This seam is a prerequisite, not the product endpoint. Follow it with one integrated disposable macOS application qualification: real shared Builder/Ready ordering, actual encrypted Owner, existing renderer, OS-native consent, local authoring, lock/quit/relaunch/unlock, and explicit uncertain-write/recovery behavior. Fake-vault evidence and real isolated OS-slot evidence must be separate. An OS-slot run needs its own explicit disposable identity, cleanup and key-loss plan; normal user data and credentials remain excluded. Then qualify equivalent Windows/Linux behavior and explicit Legacy migration before changing defaults or releasing installers. Encrypted recovery archives remain encrypted-or-unavailable. Provider credentials, OpenShell reads, LNSAT evidence and O3 ingestion follow their independent contracts; encryption never creates engine authority. + ## E1c provisioning recovery and outcome reconciliation This continues the [accepted encryption program](intent.md#provisioning-recovery-continuation--october-15-2026). The baseline investigation below is historical; the E1c-1 subsection freezes the implemented source protocol, with validation and qualification limits in the canonical ledger. Reuse the existing empty/source initializer, Owner/key custody, exact confirmation tokens, binding, typed routing and close/drain/purge. No new cipher or database schema is needed to investigate this boundary. @@ -39,7 +698,7 @@ Root retains architecture, private Owner/host integration, filesystem and key/pr Acceptance must include source and empty setup, the four existing provisioning faults, process/Owner restart, malformed and mismatched evidence, failures before/after record persistence and final completion, read-only reconciliation and clean restart success. Add exact vault-open/write and key-generation counters; refused cases must not touch the vault or change database/key bytes. All mutating families require their own interruption matrix before activation; fixing provisioning alone does not solve later capability/workflow/composition/restore/deletion uncertainty. -Use disposable roots and fake vaults. Run pinned Rust 1.98 native format, default/encrypted all-target tests, both warnings-denied Clippy variants, privacy doctests and encrypted build; portable checks only if portable source changes. Run authored-reference/whitespace checks and exact outside-owned identity proof. Require fresh independent pre-code protocol and final source/evidence reviews. Process-kill, disk-full, real OS-vault/GUI and all-three-OS durability remain distinct qualification. Production stays Legacy and Managed stays test-only until the complete adoption gates pass. +Use disposable roots and fake vaults. Run pinned Rust 1.99.1 native format, default/encrypted all-target tests, both warnings-denied Clippy variants, privacy doctests and encrypted build; portable checks only if portable source changes. Run authored-reference/whitespace checks and exact outside-owned identity proof. Require fresh independent pre-code protocol and final source/evidence reviews. Process-kill, disk-full, real OS-vault/GUI and all-three-OS durability remain distinct qualification. Production stays Legacy and Managed stays test-only until the complete adoption gates pass. ### Durable operation protocol E1c-1 @@ -63,7 +722,7 @@ Add opaque non-Clone/non-Debug/non-serializable `ClosedLease`, with only `is_cur The host supervisor must retain the active drain, serialize final resume against cancellation, and install a new close cycle on renewed drain. An old close ticket/memo cannot complete a new cycle. It must refuse a completed Locked claim throughout any key-acquiring control or retained recovery inspection, discard stale callback results, close Owner/key after actual drain, and retain renderer purge/ack requirements. After a successful explicit create/unlock, drop actual closed-control custody before `Gate::resume`; a racing renewed drain makes the old resume Stale. Resume advances generation again; no old witness, control or prepared plan becomes current. Recovery reconciliation alone never resumes. No renderer-provided token can construct these native capabilities. These are integration obligations, not guarantees supplied by this unmounted primitive. -Acceptance: ordinary lanes remain blocked; exact wrong/stale/Open token errors; single closed control; callback/retained Arc owners outlive a dropped waiter; renewal invalidates current status but preserves actual drain; renewed drain cannot begin another control or resume until prior callback drops; dropping a drain/lease never opens; successful clean resume advances generation; old drains/witnesses remain stale; cross-Gate substitution, repeated renewal, poison and counter exhaustion stay closed. No filesystem, OS prompt, database/key/provider or UI operation is needed. Add privacy compile-fail doctests and run pinned Rust 1.98 native default/encrypted all-target tests, both warnings-denied Clippy variants, privacy doctests, formatting and encrypted build; reference/artifact/whitespace and outside-owned identity proof. Source-only review does not qualify native setup/unlock, real callback integration, OS custody or encryption mounting. +Acceptance: ordinary lanes remain blocked; exact wrong/stale/Open token errors; single closed control; callback/retained Arc owners outlive a dropped waiter; renewal invalidates current status but preserves actual drain; renewed drain cannot begin another control or resume until prior callback drops; dropping a drain/lease never opens; successful clean resume advances generation; old drains/witnesses remain stale; cross-Gate substitution, repeated renewal, poison and counter exhaustion stay closed. No filesystem, OS prompt, database/key/provider or UI operation is needed. Add privacy compile-fail doctests and run pinned Rust 1.99.1 native default/encrypted all-target tests, both warnings-denied Clippy variants, privacy doctests, formatting and encrypted build; reference/artifact/whitespace and outside-owned identity proof. Source-only review does not qualify native setup/unlock, real callback integration, OS custody or encryption mounting. ## Typed close-cycle control transitions E1c-2b @@ -279,7 +938,7 @@ Late data mutation success uses existing DataResult::Failed with redacted worksp Acceptance: Legacy compatibility, managed encrypted restore/deletion, exact Unicode/provenance, readonly compile/export bytes, bounded file callbacks, managed recovery export refusal without picker/store, cancellation zero reads/writes, dropped waiter/retained completion drain, closure during picker/read/compile prevents write, closure during write returns completed redacted, stale restore/deletion confirmations across drain/resume never reach backend, mismatch retains correct plan, replay never writes, panic uncertain, no raw resolver in production wrappers, no parent helper test changes. Use disposable files/fake Vault only. -Validators: pinned 1.98 locked offline desktop default/encrypted all-target tests, both warnings-denied Clippy, fmt, privacy doc tests, encrypted build; source-binding fixtures; outside-owned identity preservation; fresh final independent source/fixture/claims review. No dependency, schema/crypto, production vault/data/default, migration, providers, credentials, execution, publication, OS/GUI or readiness claim. +Validators: pinned 1.99.1 locked offline desktop default/encrypted all-target tests, both warnings-denied Clippy, fmt, privacy doc tests, encrypted build; source-binding fixtures; outside-owned identity preservation; fresh final independent source/fixture/claims review. No dependency, schema/crypto, production vault/data/default, migration, providers, credentials, execution, publication, OS/GUI or readiness claim. ## Typed model-input host routing @@ -297,7 +956,7 @@ October 14 exact sixteen-path startup/preimages: /tmp/rangoon-model-input-routin Acceptance: local/cloud synthetic reader and exact saved source/historical capability content; identical pack/body to existing Workspace wrappers; missing/empty/oversized/malformed selected input mapping; changed exact content/hash/head freshness; no fallback on Owner locked/malformed/missing storage; current Gate/selection checks; dropped waiter and held completion keep drain nonquiescent; no data in late results; no raw Workspace resolver in native production model paths; no new provider requests/consent bypass. -Validators: portable pinned Rust1.85 workspace/targeted model-session tests and warnings-denied Clippy; pinned desktop1.98 default/encrypted all-target tests+Clippy, fmt, privacy tests, encrypted build; exact incremental/identity proof; fresh independent contract+final source/fixture/claims review. Actual transports/OS custody/GUI/adoption still open. +Validators: portable pinned Rust1.99.1 workspace/targeted model-session tests and warnings-denied Clippy; pinned desktop1.99.1 default/encrypted all-target tests+Clippy, fmt, privacy tests, encrypted build; exact incremental/identity proof; fresh independent contract+final source/fixture/claims review. Actual transports/OS custody/GUI/adoption still open. ## Credential and prompt admission @@ -345,7 +1004,7 @@ Root owns new apps/desktop/src/workspace_source_access.rs and the relevant typed Acceptance must prove Builder and every named endpoint use the same dispatcher; no direct store resolver remains in those endpoints; wrong identity/generation/locked state is refused before action; actual callback custody survives waiter drop; late picker/open/save results cannot revive selected content; clear does not misreport a disk commit; and failures preserve existing data and public errors. Use channel/barrier-controlled cases, including drain during a blocked callback, selected-Session overflow/poison, failed scheduling, panic release and reopened-session stale confirmations. Existing private lifecycle tests separately prove Gate overflow/poison; native error-mapping fixtures prove those closed errors cannot become Busy or successful admission. This is layered source evidence, not a new end-to-end Gate fault-injection claim. The Gate implementation/test seams are outside this packet. No sleep-based race proof or automatic operation retry. -Named gates: pinned desktop Rust 1.98 format, default/encrypted all-target tests and warnings-denied Clippy; privacy compile-fail tests; command-map/source fixtures; artifact/intent/whitespace and outside-owned hash preservation; fresh independent contract and final source review. GUI/custody qualification is separate. No schema/dependency/crypto change, native default, real vault/database, migration, provider/runtime installation, execution, publication or certification follows from either this contract or the later source-family seam. Finish the other families, explicit consent and durable recovery before claiming encrypted application storage. +Named gates: pinned desktop Rust 1.99.1 format, default/encrypted all-target tests and warnings-denied Clippy; privacy compile-fail tests; command-map/source fixtures; artifact/intent/whitespace and outside-owned hash preservation; fresh independent contract and final source review. GUI/custody qualification is separate. No schema/dependency/crypto change, native default, real vault/database, migration, provider/runtime installation, execution, publication or certification follows from either this contract or the later source-family seam. Finish the other families, explicit consent and durable recovery before claiming encrypted application storage. ## E1b-2b8 empty encrypted provisioning @@ -357,7 +1016,7 @@ The Owner adds `prepare_create_empty()` and a distinct `CreateEmpty` preview, wi Controller owns protected store/Owner source, the parent fixture declarations, README and canonical records. A bounded native worker owns only new synthetic `empty_encrypted.rs` and `workspace_empty_tests.rs` fixtures. Acceptance covers zero records and no fake source; exact schema/read-only reopen; first real save and later capability/workflow/composition compatibility; no plaintext header/content markers; wrong-key refusal; unkeyed rejection before filesystem access; all existing base/sidecar refusals without byte changes; repeated creation refusal; matching-token consumption; explicit lock/reacquisition/unlock of empty inventory; legacy directory preservation; provisioning/ready fault retention. Bounded malformed/token cases are deterministic property fixtures, not coverage-guided fuzzing. -Named validators: pinned portable Rust 1.85 default gate and cipher tests/Clippy; pinned desktop Rust 1.98 format, both all-target test/Clippy variants, privacy doc tests and encrypted development build; artifact/intent/whitespace checks and outside-owned byte identity proof. Fresh independent pre-code and final reviews are required. All fixtures use disposable paths and fake vaults. No new dependency, crypto profile, key exposure, telemetry/network/provider call, native default, real user vault/data, migration, publication or certification claim is part of this prerequisite. ISO/OpenSSF impact is bounded source qualification and explicit fail-closed provisioning; native platform, process-kill/disk-full and release evidence remain open. +Named validators: pinned portable Rust 1.99.1 default gate and cipher tests/Clippy; pinned desktop Rust 1.99.1 format, both all-target test/Clippy variants, privacy doc tests and encrypted development build; artifact/intent/whitespace checks and outside-owned byte identity proof. Fresh independent pre-code and final reviews are required. All fixtures use disposable paths and fake vaults. No new dependency, crypto profile, key exposure, telemetry/network/provider call, native default, real user vault/data, migration, publication or certification claim is part of this prerequisite. ISO/OpenSSF impact is bounded source qualification and explicit fail-closed provisioning; native platform, process-kill/disk-full and release evidence remain open. ## E1b-2b7 retained composition confirmations @@ -369,7 +1028,7 @@ A full opaque identifier match is checked first without parsing, normalizing or Native ownership is bounded to one composition record, replacing rather than accumulating content. Lock drops that record before dropping the opened store/key. This is reference cleanup, not secure memory erasure. Inspection copies held by callers, renderer state, model callbacks, other prepared-operation families and full production command routing remain outside this packet. Existing trusted-host typed methods remain available for later coordinated adoption; they are not renderer confirmation endpoints. No plaintext fallback, schema/crypto format change, dependency, provider call, migration, default activation or production data/vault access is added. -Root owns `workspace_session.rs`, the single parent fixture declaration, README and canonical documentation. An independent native worker may own only the new synthetic confirmation fixture module. Acceptance requires exact-byte success, mutable display-copy isolation, unknown/malformed plus false acknowledgement leaving the valid record usable, matching acknowledgement refusal with consumption, one-shot consumption, preparation failure before and after custody, replacement, explicit/automatic lock, unlock and reacquisition invalidation, state drift, pre-call custody refusal, post-attempt uncertainty and permanent generation exhaustion with key release. Refused stale/declined cases assert unchanged store bytes and no vault calls. Named checks: pinned Rust 1.98 desktop formatting, default/encrypted all-target tests, both warnings-denied Clippy variants, privacy doc tests, encrypted development build, artifact/intent/whitespace validation and outside-owned file identity proof. Fresh independent pre-code and final review are required. These source checks do not establish native consent, complete purge, Windows replacement-race detection or three-OS qualification. +Root owns `workspace_session.rs`, the single parent fixture declaration, README and canonical documentation. An independent native worker may own only the new synthetic confirmation fixture module. Acceptance requires exact-byte success, mutable display-copy isolation, unknown/malformed plus false acknowledgement leaving the valid record usable, matching acknowledgement refusal with consumption, one-shot consumption, preparation failure before and after custody, replacement, explicit/automatic lock, unlock and reacquisition invalidation, state drift, pre-call custody refusal, post-attempt uncertainty and permanent generation exhaustion with key release. Refused stale/declined cases assert unchanged store bytes and no vault calls. Named checks: pinned Rust 1.99.1 desktop formatting, default/encrypted all-target tests, both warnings-denied Clippy variants, privacy doc tests, encrypted development build, artifact/intent/whitespace validation and outside-owned file identity proof. Fresh independent pre-code and final review are required. These source checks do not establish native consent, complete purge, Windows replacement-race detection or three-OS qualification. ## Current boundary and delivery sequence @@ -508,8 +1167,8 @@ Root owns protected storage design and implementation: `crates/rangoon-store/Car Named validation: -- Default pinned portable gate: `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` (Rust/Cargo/Clippy 1.85). -- Pinned Rust 1.85 encrypted gate: `cargo test --locked --offline -p rangoon-store --features encrypted-sqlite`; `cargo clippy --locked --offline -p rangoon-store --all-targets --features encrypted-sqlite -- -D warnings`, with pinned compiler/subcommands on PATH, and workspace formatting. +- Default pinned portable gate: `CARGO_NET_OFFLINE=true node scripts/check-source-rust.mjs` (Rust/Cargo 1.99.1 and Clippy 0.1.99). +- Pinned Rust 1.99.1 encrypted gate: `cargo test --locked --offline -p rangoon-store --features encrypted-sqlite`; `cargo clippy --locked --offline -p rangoon-store --all-targets --features encrypted-sqlite -- -D warnings`, with pinned compiler/subcommands on PATH, and workspace formatting. - Synthetic checks: encrypted save/reopen exact BOM/CRLF/Unicode bytes and identities; file header/content markers absent; native SQLite/no-key/wrong-key and modified allocated pages (including outside selected content) refuse content with no diagnostic-row text leakage; constructor on unsupported builds fails before disk access; plaintext-to-encrypted opening rejected without modifying source; encrypted-to-plaintext refusal; missing reads do not create state; explicit keyed-mode tests cover all five connection wrappers, restore mutation, clone and reopen; current store source/composition/workflow/recovery tests also pass under the cipher-enabled backend, without relabeling their plaintext constructors as encrypted-mode coverage; no provider/runtime/keyring calls in tests. Encryption tests use disposable directories and caller-authored dummy keys only. - Artifact/intent/whitespace checks and startup file identity comparison outside the exact packet. No frontend/native build or rendered acceptance is inferred from portable backend tests. @@ -569,7 +1228,7 @@ A returned store handle owns a separate key copy and may be cloned by existing A Controller owns protected design/source/integration: new `apps/desktop/src/lib.rs`, new `apps/desktop/src/workspace_keys.rs`, `apps/desktop/Cargo.toml` (optional feature and the already-published Apache license field only), `apps/desktop/Cargo.lock` (existing rangoon-store zeroize dependency entry only if required), this contract, `README.md`, `docs/intent.md`, `docs/plan.md`, `docs/continue.md`, and `docs/development.md`. One native worker owns only new `apps/desktop/src/workspace_keys_tests.rs`, using literal envelopes/fake stores and a private test seam `Entropy::fill(&self, &mut [u8]) -> Result<(), Error>` plus `create_with_entropy` and `generate_identity_with_entropy`. The worker does not implement or alter protected code. No default feature, native main/command/window, renderer/assets, portable store/schema, model/ops/integration/compiler/source, provider or parent-site changes belong to this packet. All prior mixed work and licensing publication evidence stay intact. Public-main licensing metadata reconciliation is required before any later publication; this packet does not publish. -Require independent pre-code contract review and fresh final source/test/claim review. Named validators: pinned Cargo/rustc/rustfmt/Clippy 1.98 desktop formatting, default and optional-feature library tests, all-target desktop default and optional-feature tests and warnings-denied Clippy; desktop development build with the optional feature; portable default gate only if shared source changes or a failure requires it. Use Cargo offline and existing dependencies. Validate artifacts/intent/whitespace and compare all startup file hashes outside these exact paths. All tests use synthetic records/fake stores and disposable directories, with no actual Keychain/Credential Manager/Secret Service access. Real vault/native GUI and Windows/Linux cipher/backend qualification remain separate evidence. +Require independent pre-code contract review and fresh final source/test/claim review. Named validators: pinned Rust 1.99.1 toolchain (Cargo, rustc, rustfmt and Clippy) desktop formatting, default and optional-feature library tests, all-target desktop default and optional-feature tests and warnings-denied Clippy; desktop development build with the optional feature; portable default gate only if shared source changes or a failure requires it. Use Cargo offline and existing dependencies. Validate artifacts/intent/whitespace and compare all startup file hashes outside these exact paths. All tests use synthetic records/fake stores and disposable directories, with no actual Keychain/Credential Manager/Secret Service access. Real vault/native GUI and Windows/Linux cipher/backend qualification remain separate evidence. Test contracts: strict identity/envelope parsing including header/version/length/trailing/id substitution; independent entropy and partial failures; default-backend rejection with zero fake-vault/entropy calls; retained/store identity mismatch returns changed before any fake read/write and creates no filesystem state; partial/failing identity generation returns entropy_unavailable with no ID or vault access; creation and exact readback; existing/corrupt slot refusal without writes; failed read/write/missing/different readback uncertainty; missing/invalid/cross-identity/revised/same-revision changed-key refusal; key-only calls create no directory; optional-feature synthetic encrypted save/reopen preserves exact source identity and bytes; drift from an earlier retained reference (wrong/missing/changed vault record) never yields a fresh keyed handle; an initially read well-formed wrong key remains unverified until actual database authentication and must fail that store read; native namespace/identifier validation without opening a real store; privacy of closed errors and absence of key serialization/debug surfaces. No erasure, OS-vault protection, atomic provisioning, lock UI, migration or release claim follows from these tests. @@ -638,7 +1297,7 @@ Managed list/open/save require unlocked state and retained ready bytes. Before e Controller owns new apps/desktop/src/workspace_session.rs, apps/desktop/src/lib.rs, workspace_keys.rs (only pub(crate) visibility for backend probe), apps/desktop/Cargo.toml (move existing rangoon-import from dev to ordinary dependencies and directly pin the already-locked Unix libc =0.2.190 for O_NOFOLLOW/O_NONBLOCK flags; no package/version upgrade), README.md, docs/encrypted-workspace.md, intent.md, plan.md, continue.md and development.md. Independent native Terra-high worker owns only new apps/desktop/src/workspace_session_tests.rs. Desktop Cargo.lock may change only to add the existing libc dependency to the desktop package entry; no package or version changes. No portable store/schema/default feature/main/IPC/renderer/model/ops/provider/release/parent-site edit. Preserve all inherited WIP, key primitive semantics and E1b-1 fixtures. -Require independent pre-code contract review and fresh source/tests/claim review. Named pinned Rust 1.98 offline desktop formatting, default/feature all-target tests, privacy doc tests and warnings-denied Clippy; optional development build; artifact/intent/whitespace and startup out-of-packet hashes. Shared portable source stays unchanged, so no repeated portable gate unless necessary. Tests use fake identity vaults and disposable canonical roots only; no actual OS store, normal database, credentials, provider, network, installation, publish or execution. +Require independent pre-code contract review and fresh source/tests/claim review. Named pinned Rust 1.99.1 offline desktop formatting, default/feature all-target tests, privacy doc tests and warnings-denied Clippy; optional development build; artifact/intent/whitespace and startup out-of-packet hashes. Shared portable source stays unchanged, so no repeated portable gate unless necessary. Tests use fake identity vaults and disposable canonical roots only; no actual OS store, normal database, credentials, provider, network, installation, publish or execution. For deterministic independent fault fixtures, controller exposes only a private test seam: cfg(all(test, feature="encrypted-workspace")) enum Fault { BeforeProvisionWrite, BeforeReadyWrite, BeforeReadySync, BeforeReadyReadback, AfterSave } and Owner::inject_fault(&mut self, Fault). Each simulates failure immediately before the named filesystem boundary (AfterSave after actual source save, before post-write validation); no production fault API, process-global flag, environment control or escaping callback exists. Fault does not delete/repair data or forge a successful durable write. @@ -678,7 +1337,7 @@ The native Builder creates exactly one Gate; source operation helpers and ModelF Controller owns protected new apps/desktop/src/workspace_lifecycle.rs, lib.rs, main.rs, model_flight.rs, capabilities.rs, data_controls.rs, workflows.rs, composition.rs, compilation.rs, instruction_bundles.rs, models.rs and cloud_models.rs; README.md; docs/encrypted-workspace.md, application-architecture.md, intent.md, plan.md, continue.md and development.md. A separate native Terra-high worker owns only new workspace_lifecycle_tests.rs and native_admission_tests.rs. The latter tests the shared native factory/read dispatcher; it does not invoke a Tauri window. The models.rs/cloud_models.rs ownership is confined to existing short Exclusive admission error routing; provider, credential, consent, transport and freshness semantics remain unchanged. No dependencies/locks, key/session primitives, shared store/schema, renderer/assets, provider/credential/transport behavior, permissions, CI, defaults, parent site or publication changes. Preserve inherited WIP. Original eight-screen experience remains unchanged; user-facing lock/cleanup surfaces are pending. Exact authority/evidence stays in the canonical ledger. -Require independent pre-code contract review and fresh source/fixture/claim review. Validators: pinned Rust 1.98 offline native fmt, default/encrypted all-target tests and warnings-denied Clippy; privacy doc tests; optional development build; artifact/intent/whitespace; startup hashes outside owned paths. No GUI qualification follows because no UI changes. Gate fixtures prove reader capacity/coexistence; Exclusive/Model mutual admission per lane; retained callback Arc custody after waiter drop; closed admission and old-lease invalidation at drain; quiescence only after all lane owners drop; no automatic reopen after Drain drop; wrong-gate/reused tokens and active-lane resume refusal; overflow fail-closed before mutation; poison closure; channel/barrier-coordinated cross-thread drain/admission behavior without sleeps; RAII unwind release; no key/source/store or execution content. Native integration fixtures must execute the same shared Gate/ModelFlight factory used by Builder and the same counted read dispatcher used by all six read routes. The dispatcher acquires Read before scheduling and holds the lease inside the actual native spawn_blocking callback, including when its waiter is dropped. Fixtures must prove closed/capacity admission before scheduling with observable zero action invocations on refusal, panic release, callback custody after waiter drop, all-lane drain waiting and shared factory/model admission. Use an exact channel/barrier handshake without sleeps: callback sends started and blocks on release; fixture waits for started, drops the returned JoinHandle, drains and asserts nonquiescent, releases the callback, receives returned-value Drop completion after worker lease RAII, then asserts quiescent. This proves waiter cancellation while the actual callback still owns Read, rather than an already-finished callback. Independent source review must trace Builder and every read endpoint to those tested helpers. These synthetic integration fixtures do not invoke Tauri windows or real endpoint IPC and do not establish GUI qualification. This refined evidence boundary was frozen and independently re-reviewed after final review identified the original unfulfilled Builder/endpoint integration-fixture requirement; source tracing alone is not its replacement. Tests use synthetic state only, no vault/database/provider/network/credential calls. +Require independent pre-code contract review and fresh source/fixture/claim review. Validators: pinned Rust 1.99.1 offline native fmt, default/encrypted all-target tests and warnings-denied Clippy; privacy doc tests; optional development build; artifact/intent/whitespace; startup hashes outside owned paths. No GUI qualification follows because no UI changes. Gate fixtures prove reader capacity/coexistence; Exclusive/Model mutual admission per lane; retained callback Arc custody after waiter drop; closed admission and old-lease invalidation at drain; quiescence only after all lane owners drop; no automatic reopen after Drain drop; wrong-gate/reused tokens and active-lane resume refusal; overflow fail-closed before mutation; poison closure; channel/barrier-coordinated cross-thread drain/admission behavior without sleeps; RAII unwind release; no key/source/store or execution content. Native integration fixtures must execute the same shared Gate/ModelFlight factory used by Builder and the same counted read dispatcher used by all six read routes. The dispatcher acquires Read before scheduling and holds the lease inside the actual native spawn_blocking callback, including when its waiter is dropped. Fixtures must prove closed/capacity admission before scheduling with observable zero action invocations on refusal, panic release, callback custody after waiter drop, all-lane drain waiting and shared factory/model admission. Use an exact channel/barrier handshake without sleeps: callback sends started and blocks on release; fixture waits for started, drops the returned JoinHandle, drains and asserts nonquiescent, releases the callback, receives returned-value Drop completion after worker lease RAII, then asserts quiescent. This proves waiter cancellation while the actual callback still owns Read, rather than an already-finished callback. Independent source review must trace Builder and every read endpoint to those tested helpers. These synthetic integration fixtures do not invoke Tauri windows or real endpoint IPC and do not establish GUI qualification. This refined evidence boundary was frozen and independently re-reviewed after final review identified the original unfulfilled Builder/endpoint integration-fixture requirement; source tracing alone is not its replacement. Tests use synthetic state only, no vault/database/provider/network/credential calls. ## E1b-2b2 typed managed inspections @@ -733,7 +1392,7 @@ Controller owns protected apps/desktop/src/workspace_session.rs, only the new ch Independent pre-code contract review and fresh source/fixture/claim review are required. Synthetic keyed-store/fake-vault fixtures prove create/revise/review exact literal content, IDs, provenance, review flags/timestamps and historical head behavior; create/revise/review idempotence; source-only and workflow-bearing complete-state preservation; no lost workflow records; lock/reunlock durability; all-three locked/recovery pre-call refusal without vault access; key drift before all three mutations returning Key(Changed) with unchanged database/control/binding and zero key writes; malformed, missing, wrong-owner and stale-head store refusal returning WriteUncertain, auto-lock and recovery fencing with unchanged refused state; successful store commit followed by the test-only finisher fault produces no receipt and a closed recovery state without retry. After dropping the faulted Owner, fixture-controlled explicit reopening may inspect the committed content, proving uncertainty rather than rollback; this is synthetic evidence, not a recovery UI. Compare owned results with trusted fixture store inspections, plus independent literal assertions, not timestamps from a second mutation invocation. Keep legacy plaintext fixture bytes unchanged and add no files or vault writes during managed capability operations beyond the existing transaction's transient journal behavior. -Retain bounded reproducible mutation/property testing: use a fixed seed and at least 36 valid Unicode input mutations spanning all three operations and malformed selector/title/content classes; every refusal asserts the exact post-attempt error and recovery fence, unchanged refused database bytes and no key writes/retry. Explicit fixture drop/reacquire/unlock between independent cases is permitted and must not be confused with production automatic recovery. No new fuzzing dependency or provider/vault/user-data access. Named validation remains pinned Rust 1.98 offline native formatting, default/encrypted all-target tests, warnings-denied Clippy, privacy doc tests and optional development build; artifact/intent/whitespace plus startup identity comparison outside exact ownership. Source-only acceptance does not qualify GUI, OS vaults, production encryption, rollback protection, installers or release. Canonical receipts belong only in development.md. +Retain bounded reproducible mutation/property testing: use a fixed seed and at least 36 valid Unicode input mutations spanning all three operations and malformed selector/title/content classes; every refusal asserts the exact post-attempt error and recovery fence, unchanged refused database bytes and no key writes/retry. Explicit fixture drop/reacquire/unlock between independent cases is permitted and must not be confused with production automatic recovery. No new fuzzing dependency or provider/vault/user-data access. Named validation remains pinned Rust 1.99.1 offline native formatting, default/encrypted all-target tests, warnings-denied Clippy, privacy doc tests and optional development build; artifact/intent/whitespace plus startup identity comparison outside exact ownership. Source-only acceptance does not qualify GUI, OS vaults, production encryption, rollback protection, installers or release. Canonical receipts belong only in development.md. ## E1b-2b4 typed managed workflow authoring @@ -819,7 +1478,7 @@ Primary Sol owns protected apps/desktop/src/workspace_session.rs, one child decl Synthetic acceptance: source-only and workflow-bearing keyed stores; unchanged bytes for export/preparation/inspection; exact plaintext archive disclosure and decode/reopen parity; additive restore preserves unrelated sources and workflow references; no-op semantics; dependency-blocked deletion and successful unreferenced deletion; actual post-commit fault for both mutations followed by explicit fixture Owner drop/reacquire/unlock; all five services locked/recovery/key-drift pre-call refuse with vault/write counts; stale/mismatched plan/archive refusals preserve bytes and conservatively recover; finite seeded malformed deletion selectors and bounded backup decoder mutations, with explicit tuple coverage and exact diagnostics. Fuzzy/property checks supplement exact security validation; no approximate IDs or authorization. Existing service bodies and old fixtures remain intact. Use fake vaults and disposable synthetic roots only; raw trusted fixture handles may exist only for setup/verification and cannot prove production custody. -Named final gates: pinned Rust 1.98 offline native fmt, default/encrypted-workspace all-target tests, both warnings-denied Clippy variants, both privacy doc-test variants and encrypted development build; docs/reference/intent/whitespace; startup file identities outside ten owned paths. Store source unchanged, so no redundant store gate unless review requires a scoped correction. Fresh review receives exact before/delta/evidence, not the broad mixed tree. Publication must independently isolate reviewed database source atop freshly fetched main, include substantive README/install-direction docs, revalidate that exact checkout and obtain fresh publication review before commit/push/PR. Do not copy unrelated approval/model/I1/UI backlog or infer main merge, default activation, installer, user-vault use, migration or release from a GitHub upload. +Named final gates: pinned Rust 1.99.1 offline native fmt, default/encrypted-workspace all-target tests, both warnings-denied Clippy variants, both privacy doc-test variants and encrypted development build; docs/reference/intent/whitespace; startup file identities outside ten owned paths. Store source unchanged, so no redundant store gate unless review requires a scoped correction. Fresh review receives exact before/delta/evidence, not the broad mixed tree. Publication must independently isolate reviewed database source atop freshly fetched main, include substantive README/install-direction docs, revalidate that exact checkout and obtain fresh publication review before commit/push/PR. Do not copy unrelated approval/model/I1/UI backlog or infer main merge, default activation, installer, user-vault use, migration or release from a GitHub upload. ## Native explicit-close coordination diff --git a/docs/export-handoff.md b/docs/export-handoff.md index 0f4a97f..75697de 100644 --- a/docs/export-handoff.md +++ b/docs/export-handoff.md @@ -29,7 +29,7 @@ Unknown bundle subcommands, extra arguments and missing subcommands return usage Use the existing independently framed `fixtures/compilation/instruction-bundle-v1.json` golden corpus as literal input. Tests compare both profile outputs with expected instruction bytes and fixed inspection identities, not with a value reconstructed by the implementation under test. Cover BOM/CRLF/Unicode, no added final newline, exact maximum artifact bytes, deterministic output, malformed/truncated/trailing/checksum-invalid/oversized input with zero stdout, non-echoed errors and argument rejection without stdin reads. Pin inspect stderr empty and artifact stderr exactly the fixed notice. Add both a bare short header and a minimum-sized truncated frame with an over-limit declared component, a zero-plus-oversized declaration, an exact `MAX_BUNDLE_BYTES + 1` reader-consumption assertion, argument rejection with stdin kept open, and injected stderr write/flush failures that produce zero artifact output and exit-3 failures. Inject stdout write/flush failures for both command modes and assert exit-3 failures; partial output after an I/O failure is possible and never success. Existing core verifier tests retain semantic/canonical tamper coverage. The CLI must not loosen that verifier. -Run pinned Rust 1.85 package tests and warnings-denied all-target Clippy plus workspace format, `node scripts/validate-review.mjs`, intent validation and packet whitespace checks. Existing CLI tests cover source/engine regressions. No UI change occurs, so no new synthetic layout or GUI acceptance follows. Three-OS CI can run the portable tests later; a local macOS run is not Windows/Linux runtime evidence. Review independently before source acceptance; publication remains closed. +Run pinned Rust 1.99.1 package tests and warnings-denied all-target Clippy plus workspace format, `node scripts/validate-review.mjs`, intent validation and packet whitespace checks. Existing CLI tests cover source/engine regressions. No UI change occurs, so no new synthetic layout or GUI acceptance follows. Three-OS CI can run the portable tests later; a local macOS run is not Windows/Linux runtime evidence. Review independently before source acceptance; publication remains closed. ## Two-target qualification still required diff --git a/docs/focused-workbench-site-brief.md b/docs/focused-workbench-site-brief.md new file mode 100644 index 0000000..13ca011 --- /dev/null +++ b/docs/focused-workbench-site-brief.md @@ -0,0 +1,50 @@ +# Rangoon and Hypler: focused product messaging + +Status: owner-requested positioning and site-update brief, October 22, 2026. Copy only; no sites published by this packet. + +## Product direction + +Rangoon is a local-first capability workbench: import existing agent instructions, organize reusable skills, compose versioned inputs, prepare inspectable exports and review available evidence. Its next proof is what an external executor actually loaded and ran. Reuse qualified execution/automation products rather than building another complete agent platform. Jeff is Customer Zero for the general product; Hypler infrastructure remains private configuration. + +## Rangoon site copy + +Suggested headline: **Make agent capabilities reviewable.** + +Suggested subheading: **Bring instructions into one workbench. Organize reusable skills, compose versioned capabilities, and keep source-to-output history visible.** + +Primary actions: **Explore the workbench** and **View development on GitHub**. The first action should point to an explicitly labeled preview or documented build, not imply an available production installer. + +Three product pillars: + +- **Author and compose:** review source sections, edit reusable skills, combine selected revisions and inspect the resulting instructions. +- **Trace changes:** retain source provenance, revision history and source-to-output mappings. +- **Inspect evidence:** review supported local/imported evidence with explicit source and coverage. External execution and effective-configuration verification are being qualified separately. + +Short development note: **Rangoon is in active development. Local workbench components are implemented; connected execution and cross-system verification are being qualified individually.** + +Integration card wording: **OpenHands — execution adapter under evaluation.** SDK/Agent Server is the first reuse candidate; Automation is a separate beta scheduling candidate. No supported integration badge until its named test passes. Optional future integrations may consume existing observability/authorization services; do not list research candidates as working connectors. + +## Hypler portfolio copy + +**Rangoon is Hypler's local-first capability workbench for organizing agent instructions, composing reusable skills and inspecting their provenance and evidence. Its development focuses on interoperability with existing execution systems, beginning with an isolated OpenHands adapter evaluation.** + +Keep the three projects distinct: + +- **Rangoon:** capability authoring, composition, review and operator visibility. +- **LNSAT:** independently developed authorization and evidence engine. +- **VUSL:** independently developed semantic interoperability project. + +These descriptions state product roles, not released integration or certification claims. Use each project's own logo and repository reference. Rangoon's useful local authoring does not require either other project. + +## Site sections to adjust + +Lead with the workbench and its source → skill → composition → export journey. Feature screenshots should show populated real local workflows when qualified, or carry a clear sample label. Put engine catalogs, infrastructure/fleet management, scheduling, budgets, broad plugin coverage and experimental 3D views into a roadmap or technical detail section. Preserve the existing abstract art direction without spending this milestone on new artwork. + +Do not claim universal portability, verified target loading, production-grade encrypted release, enforcement of every tool action, lower token cost, superior security, scale benchmarks or working OpenHands/LNSAT/VUSL connections without corresponding evidence. Native confirmation, Rangoon review and engine authorization remain distinct. + +## Delivery sequence + +1. Current slice: focused navigation labels/grouping and this synchronized messaging brief. No new executor or connection behavior. +2. Next engineering slice: freeze and accept the isolated Agent Server adapter/test scope; qualify input/configuration readback, confined execution, stable identity, recovery and honest evidence. +3. Next UI slice: expose only qualified adapter operations through a target/run/inspector flow; compare usability with OpenHands alone. Retain a replaceable adapter and one execution owner. +4. Expand only after representative use demonstrates reduced operator work or better detection/recovery/evidence, with actual costs recorded. No savings or market-superiority claim follows from the initial UI pass. diff --git a/docs/instruction-bundle.md b/docs/instruction-bundle.md index bd09ce3..a535e46 100644 --- a/docs/instruction-bundle.md +++ b/docs/instruction-bundle.md @@ -27,7 +27,7 @@ The manifest embeds only existing revision/provenance references and an unauthen ## Pure API and verification -Add a `bundle` module to `rangoon-compile`, retaining its Rust 1.85 and no-I/O boundary. Use existing dependencies only. +Add a `bundle` module to `rangoon-compile`, retaining its Rust 1.99.1 and no-I/O boundary. Use existing dependencies only. - `encode_bundle(&CompilationReport) -> Result` accepts only a fully consistent candidate report. The returned structure contains exact `bytes` and an `inspection`. Reject unreviewed/blocked reports and mutated public report fields. Encoding must pass the same verifier and require its reconstructed compilation report to equal the supplied report; do not trust caller-controlled candidate IDs or manifest fields. - `inspect_bundle(&[u8]) -> Result` validates an untrusted file in memory. It does not mutate storage, consult the environment, load includes, install files, invoke a provider or grant authority. diff --git a/docs/intent.md b/docs/intent.md index d0e90ba..93d1e75 100644 --- a/docs/intent.md +++ b/docs/intent.md @@ -1,6 +1,24 @@ # Intent: Rangoon application development and evidence +Status: accepted +Authority: Jeff's dated explicit directions and the source-publication scope below; native operation and release retain their separate gates +Owner: Jeff +Accepted by: Jeff; October 29 full application source publication to GitHub main only +Last updated: 2026-10-29 +## Full application source publication — October 29, 2026 + +Status: accepted. Authority: Jeff requested “push and deploy,” clarified “Update GitHub main only,” then expanded the scope to “we should push all of it.” This accepts publication of the complete authored Rangoon application snapshot, not only CW-1. It supersedes earlier packet-level publication holds for this snapshot; their implementation, native-operation and release limits remain historical and current evidence where applicable. + +Root owns reconciliation, validation, README/status updates, commit, branch push, pull request and merge to `hypler-dev/rangoon` main after passing required checks. Preserve the original dirty application worktree and separate website worktree. Reconcile onto public baseline `01423598cc212a5ad7f3bbefd213573f37efd55d`, retaining the independent VUSL direction and both public LNSAT request-record decoder and offline inspection modules. Publish authored source/tests/docs and synthetic fixtures only. Exclude build outputs, machine-local symlink substitutions, app data, credentials and private raw evidence. + +The candidate includes encrypted default startup and recovery, instruction-history persistence, native lifecycle/credential seams, bounded Agent files/folder metadata, Markdown review/find, composition and saved-skill compilation continuity, current toolchain pins, and documentation. It does not mount live providers, remote transport, a scheduler or agent execution. The retired recovery experiment remains explicitly separate from active Cargo workspaces and product recovery. + +Acceptance: pinned portable and desktop source validators; standalone retired-experiment checks where its cached dependencies are available; Python harness-unit checks; JavaScript/vision checks; synthetic rendered handoff, failure, navigation and Lock checks across 320/768/1440 dark/light layouts; document/intent/whitespace and authored-file inventory checks; fresh independent native, UI and documentation review. Before merge, verify the exact PR head, required CI, reviews/threads, protection and current base. No force push or protection bypass. The [publication receipt](development.md#full-application-source-publication--october-29-2026) owns results and remaining qualification gaps. + +No website/infrastructure deployment, executable packaging/release, normal data/key/vault access, live provider/engine operation, or LNSAT/VUSL repository change is authorized by this publication. The next development slice remains isolated native folder-picker/Lock and full local-workflow qualification, not a broader live-system rollout. + + ## RUSL retirement and VUSL consumer sequencing — October 19, 2026 Status: accepted. Authority: Jeff explicitly instructed “Retire RUSL as an active technical contract,” preserve its development history, and avoid maintaining a reader, converter, alias or dual-profile system without evidence of need. He separately required the old Rangoon code to remain until the independently developed VUSL core is usable and affected tests are updated; keeping inert experimental source is not a backward-compatibility promise. This latest direction supersedes earlier active RUSL/D0a roadmaps and standing old/new-reader or migration requirements. Historical acceptances, identifiers, fixtures, pins and receipts remain evidence of earlier work. @@ -21,6 +39,226 @@ The [VUSL guide](vusl.md) and [conformance guide](vusl-conformance.md) are compa Root owns integration, this intent, continuation and development receipts. A native documentation worker owns README and the affected guides/architecture/integration references. Named validation: local document/anchor checks, diff whitespace, exact source/fixture preservation, Rust D1 tests and independent Python reference replay; fresh independent read-only review is required. No schema, source, UI, dependency, engine or credential change is included. The later explicit repository-extraction request above supersedes the earlier naming-only publication restriction for the new specification repository. Rangoon merge and runtime release remain separate gates. Existing encrypted-workspace work remains isolated and preserves its accepted scope. + +## CW-1 saved-revision compile handoff and current storage status — October 29, 2026 + +Authority: Jeff asks to keep working through the reviewed October 29 audit. This bounded follow-up implements the first Skills-to-Compile continuity action and reconciles obsolete storage guidance; the audit's broader stages remain proposals. Root owns exactly the fifteen paths in `/rangoon-continuity-20261029/owned-paths.json`, preserved preimages, integration and validation. Fresh independent source and UI review is required. + +A selected saved skill revision can open Compile directly through the existing native `open_capability` read. Bind capability and revision IDs explicitly, including historical selection; never substitute current head, compile automatically, export, save, review or run. A dirty current draft for the selected skill blocks the handoff from either current or historical view; guide the user back to current to save or discard it. Pending requests, conflicts, missing native access and unavailable selections also refuse with explanatory copy. Preserve all drafts, including unrelated skill drafts. Revalidate the native detail and current source selection; navigation, selection changes, Lock and late callbacks cannot redirect or repopulate the destination. A fresh exact selection may clear stale compilation context only after native identity validation; invalidation during the read still wins. If Compile has no loaded library, fetch its bounded native summaries under the same request guard before the exact revision read. A failed summary list remains visible but does not replace the exact revision read or its validation. Route entry reuses that result without an automatic second revision read; explicit Refresh retries the library. Focus the selected revision/profile area after successful navigation. Keep existing native authorization and storage contracts unchanged. + +Update README, architecture and reviewer guidance to distinguish encrypted-by-default source startup, implemented encrypted recovery with dated disposable macOS evidence, unsupported Windows custody/startup/recovery, remaining artifact/OS qualification and intentionally readable instruction exports. Preserve historical evidence and avoid claiming production readiness. Record the BF-2c isolated qualification permission/fixture gap as the next native test correction; no normal app or existing artifact is launched in this slice. + +Validate current/historical exact revision selection, dirty/conflict/busy/unavailable gates, wrong/missing native identity, changed selection/draft/route, duplicate clicks, host rejection, stale compilation context and Lock/late-result purge. Run focused and full JS/vision/visual checks, actual synthetic browser interaction and 320/768/1440 light/dark layout checks, documentation/intent/link checks, exact owned/unowned preservation and fresh independent review. No new dependency, native/storage/crypto/permission change, normal files/keys/vault, provider/remote/engine activity, foreign repository edit or commit/push/merge/deploy/release. + +## BF-2c native folder metadata workbench — October 27, 2026 + +Authority: Jeff says proceed after the pinned toolchain gate cleared. Root owns the exact 23 paths in `/rangoon-folder-ui-20261027/owned-paths.json`, preimages and integration; fresh independent source/UI review required. This accepts native folder selection and bounded metadata display, not an arbitrary row-content reader. Reuse BF-2a traversal, BF-2b pinned tooling, existing SourceAccess exclusive selection admission and counted read-only delivery. + +A new `select_and_list_sources` command opens an explicit native folder picker and lists metadata only in a blocking worker. No renderer path, source ID, original or limit controls are accepted. Iterate bounded BF-2a pages, check workspace generation throughout and at delivery, close handles before returning at most 1000 rows/10,000 visited entries and a conservative 2 MiB JSON metadata bound. Oversized windows fail atomically before IPC; renderer independently checks actual UTF-8 size. Preserve cumulative partial reasons and policy exclusions; cancellation/lock returns no current-page data and stale results cannot repopulate the view. Windows returns explicit unsupported before choosing/scanning. No fabricated progress or claim of hard I/O cancellation. + +Agent files gains Choose folder, exact relative names, observed size/mtime, session-local listed time, filtering, existing 50-row pages, a clear-folder action and metadata inspector. Folder rows have no source ID/hash/content/findings/revision lineage; selecting them makes no native read. Source inspection uses a separate explicit Choose files action and native picker; never turn a display path or session ordinal into read permission. One folder window replaces prior folder observations only; failures/cancellation preserve prior results, saved/selected records and current source review. Folder records/tags are memory-only; Lock purges them and late results. Retained row-inspection custody remains the next separate native contract. + +Validate actual disposable host collection, native counted admission/stale delivery, strict renderer DTO/caps/paths/time/counters, duplicate and malformed pages, quiet cancellation, failure preservation, source handoff unchanged, lock/late-result purge, file filters/paging/clear, content-read command refusal for folder rows, escaped source-like labels and six 320/768/1440 dark/light browser views. Use Rust 1.99.1 locked/offline host+desktop relevant tests/Clippy/build, JS source/vision/reference checks, intent/links/whitespace/hash preservation and fresh independent source/UI review. All GUI browser fixtures are synthetic; no normal folders, user data/keys/vault, real native GUI, provider/network/remote/infrastructure/engine operation, LNSAT/VUSL edit, dependency install/fetch, commit/push/merge/deploy/release. Native folder-picker GUI/three-OS qualification remains separate. + +BF-2c bounded validation correction: default desktop tests exposed an existing recovery fixture rooted at macOS's symlinked `/var` temporary path. The exact existing test fails in isolation and passes unchanged with an isolated canonical `/private` TMPDIR. Add only `apps/desktop/src/encrypted_recovery_tests.rs` as the 23rd owned path, preserving its preimage before edit. Canonicalize the freshly created disposable TestRoot directory, matching other native test fixtures. No production storage, encryption or no-follow behavior changes. Re-run the original test under the original environment and full native checks; retain all failed and diagnostic logs. Screenshot evidence must show the complete requested CSS viewport; clipped/blank attempts are rejected, not counted. + +## BF-2b pinned toolchain qualification — October 27, 2026 + +Authority: Jeff asks to resolve BF-2a's unavailable Rust 1.99.1 qualification gate. Root owns installation/validation and four documentation paths: `docs/intent.md`, `docs/application-architecture.md`, `docs/continue.md`, `docs/development.md`. Preserve frozen BF-2a source, version pins, lockfiles and all unrelated dirt. Evidence/preimages: `/rangoon-toolchain-qualification-20261027`. + +Verify the official Rust 1.99.1 release; use installed rustup to install the exact x86_64-apple-darwin toolchain with minimal profile, rustfmt and Clippy from official Rust distribution endpoints. Do not change default toolchains or upgrade project dependencies. Validate compiler/subprocess identities through existing `scripts/check-source-rust.mjs` and exact native source hashes; use locked/offline project builds without an MSRV override. Run required portable fmt/tests/Clippy, focused/host inventory tests, desktop lock metadata, relevant renderer/reference/intent/link checks and fresh independent read-only review. Record failures honestly. Fixes to source/config beyond these four docs require a separately recorded bounded correction before mutation. + +This installation resolves build tooling only. Normal data/keys/vault, native GUI, provider/remote/infrastructure/engine operation, LNSAT/VUSL edits, package release, commit/push/merge/deploy remain closed. Successful source validation is not native UI/Windows/Linux qualification or completion of folder-picker mounting. + +## BF-2a retained-root inventory backend — October 27, 2026 + +Authority: Jeff says proceed after the RM-1 shared metadata contract and next native-root step. Accept this nine-path Unix host-only source/test packet: `crates/rangoon-host/Cargo.toml`, `crates/rangoon-host/src/lib.rs`, new `crates/rangoon-host/src/source_inventory.rs`, `Cargo.lock`, `apps/desktop/Cargo.lock`, `docs/intent.md`, `docs/application-architecture.md`, `docs/continue.md`, `docs/development.md`. Root owns integration, dependency and filesystem boundaries; fresh independent read-only review required. Exact preimages/evidence: `/rangoon-root-inventory-20261027`. + +Implement actual metadata-only discovery over retained Unix directory handles, with absolute native-selected root component walk, no-follow directories, relative no-follow metadata, opened-child identity/device checks, loop/depth/work/record limits and incremental pages. No source-file content/hash, plaintext cache, writes, renderer paths, native IPC/UI/service or remote connection. Root custody binds the opened directory object, not future resolution of its pathname. Results are observations, not an atomic snapshot or revision ancestry. Unsupported platforms fail explicitly. Cancellation closes handles and rejects the current page; a later mounted coordinator must purge previously delivered metadata and fence callbacks. No hard wall-clock/interruptible-kernel-I/O guarantee. + +Promote only already locked/cached `rustix =1.1.5` safe fs API to the Unix host dependency; preserve crate forbid-unsafe. Lockfiles may add that exact direct edge, not upgrade packages. Offline builds only, no dependency installation/fetch. Validate symlink roots/ancestors/children, deterministic replacement race, root rename custody, special files, ignored/invalid names, bounds, cancellation/closure, partial failures and metadata-only serialization using disposable temporary directories. Run focused/host/full portable Rust tests, warnings-denied host Clippy, touched formatting, desktop lock consistency, JS build/vision/review, intent/links/whitespace/exact preservation and fresh read-only review. Normal data/keys/vault, native GUI/provider/network/remote/engine/VUSL operation, storage/schema changes and publication remain closed. No commit/push/merge/deploy/release. + +## RM-1 offline inventory implementation — October 27, 2026 + +Authority: Jeff's request to finish and implement the remote files, versions and cross-system transfer direction accepts the first bounded RM-1 source packet described in the remote architecture. Root owns seven paths: `preview/remote-inventory-model.mjs`, `tests/remote-inventory-model.test.mjs`, `tests/fixtures/remote-inventory.v1.json`, `docs/application-architecture.md`, `docs/intent.md`, `docs/continue.md`, `docs/development.md`. Exact preimages and review evidence: `/rangoon-remote-inventory-20261027`. Preserve all unrelated work. + +Implement the internal unmounted offline metadata contract first. Bind each page/request to installation identity and epoch, acting principal, grant, registered root, session and snapshot; pin adapter/product/version, required metadata scope, separate consent/grant expiry and generation-fenced cursor chain. Bound page and working window, validate relative compatible file names, exact digest/revision identities and separate producer-observed/local-received timestamps. Preserve native provenance as unverified producer reports; refuse unknown fields, duplicates, cursor replay, wrong scope, incompatible versions, payload content and unsupported operations atomically. Lifecycle invalidation clears records and fences late results. Stale/future/skewed times remain visible and never prove live freshness or authorization. + +Acceptance: focused positive/hostile fixtures, paging/restart/expiry/clock/capacity/atomicity/cancellation/purge tests, finite scale check, full source/visual/vision suite, review validator, intent/links/exact-delta preservation and fresh independent read-only review. No UI mounting or claims of network connectivity/authentication, no filesystem scan/content read, Tauri/native/service/credentials/provider operation, persistence/schema/key changes, engine/VUSL edit, dependency install/fetch, commit/push/merge/deploy/release. Native retained-root custody and transport/enrollment remain next separate implementation gates, not implemented by fixture validation. + +## WF-1 intuitive in-file review search — October 27, 2026 + +Authority: Jeff requests continued work toward a more intuitive workspace. This accepts the next local functional gap recorded after FH-1: a compact Find in file experience in the open Agent files Markdown review. Root owns the ten-path implementation/integration; fresh independent source/UI review is required. Exact ownership/preimages: `/rangoon-find-20261027`. + +Use literal local search over the current bounded source, with query, match-case, visible count/limit state and previous/next wrap navigation. Open/reveal matches inside folded groups without moving focus away from the query/control or scrolling the whole page. Highlight exact display offsets through safe text-node wrapping without interpreting query/source HTML or changing original text/syntax token boundaries. No regex execution, source edit, provider, native/filesystem call, telemetry or persistent storage. Search positions are UI UTF-16 offsets, not authoritative native byte ranges, diagnostics, approval or composition semantics. Unicode lowercase matching must map back to whole original code-point boundaries; no normalization/locale/fuzzy identity claim. + +Keep the default workspace compact: explicit Find in file opens the inline toolbar; scoped Cmd/Ctrl+F or F3 may open it from the Markdown review only. Enter/Shift+Enter and F3/Shift+F3 navigate; Escape/Close clears query/highlights and returns to the find trigger. Filename filtering stays distinct. Cap query at256 UTF-16 code units, single line/no NUL; retain at most1000 matches and state any cap honestly. Reuse source display bounds; unavailable source/query/no-match are distinct. Typing must not rebuild the full file/workspace or lose caret. Matching rerenders preserve ephemeral find/fold/scroll/focus; changing files/routes or Lock disposes query/matches/highlights and must not revive them on late native callbacks. No cross-file search or search history is implied. + +Acceptance: literal escaping, case options, Unicode/CRLF/code-point positions, cap/invalid/empty/no-match states, deterministic next/previous wrap; actual folded/multitoken highlighting and source text unchanged; scoped keyboard/focus/scroll, filter rerender, other file, route, lock and current saved-source handoff preserved. Actual synthetic320/768/1440 dark/light, approximately44px controls, focused/full source/visual/vision tests, finite search benchmark, intent/links/exact-delta/hash preservation and fresh independent review. Normal data/keys/vault, native app/provider/remote/infrastructure, Rust/storage/crypto/authority, dependencies, LNSAT/VUSL and publication stay closed. Native current-artifact GUI/OS/SR/touch qualification remains separate. No commit/push/merge/deploy/release. + +## FH-1 saved-file source-workbench handoff — October 27, 2026 + +Authority: Jeff requests continued development of missing functionality after visual refinement. This accepts a bounded thirteen-path local application/controller handoff: Agent files can explicitly open its selected saved source in Import & Analyze, then use existing native sections and Create skill from section. Root owns implementation/integration; fresh independent source/UI review is required. Exact ownership/preimages: `/rangoon-source-handoff-20261027`. + +Keep the existing native `open_snapshot` command and source-reference boundary. Send only the saved source ID to native; validate returned source identity and, for this handoff, expected saved digest/byte count before replacing the source-analysis selection. This renderer check supports honest context and does not authenticate native bytes or grant authority. Never substitute renderer-held originals. Add visible pending/error state with exact local selection custody, duplicate/pending refusal and lifecycle fencing. Stay in Agent files on failure; preserve prior inspection and previous analysis. Navigate/focus source workbench only on successful exact open while still in the originating route. User navigation, lock, delete, cancellation/late callbacks must not force a stale route or resurrect content. Existing skill drafts/create-title maps, composition/storage/compile behavior remain intact. + +Selected unsaved files must show a clear save/import prerequisite and cannot use this saved-reference action. Do not silently save/import a batch or re-read arbitrary paths. Browser/native-unavailable state stays honest. The inspected saved record remains available for retry; native open/rejection is authoritative. UI source reference/digest guards remain exact; no fuzzy checks for identity. + +Acceptance: exact single saved-reference call, no source payload/path; success reaches the selected source's actual native sections and existing Skills creation handoff; duplicate/pending/unsaved/stale/mismatch/error/lock/late/navigation cases retain safe state and focus; compact readable controls with320/768/1440 dark/light browser evidence. Run focused source/agent model+view tests, full build/syntax/visual/vision checks, exact ownership/hash/whitespace/link/intent checks and fresh independent review. Synthetic fixtures never count as native persistence or execution proof. No Rust/native command/schema/crypto/storage, provider/remote/runtime, normal data/keys/vault, dependency install/fetch, LNSAT/VUSL or infrastructure change. No commit/push/merge/deploy/release; native current-artifact GUI qualification remains separate. + +## VR-1 compact reference-aligned workbench — October 27, 2026 + +Authority: Jeff says the interface is harsh/bulky and asks to compress it and revisit the original UI. Current request accepts this bounded eleven-path UI-only refinement. Exact ownership/preimages: `/rangoon-refinement-20261027`. Root owns markup/styles/integration; read-only design direction and fresh independent source/UI reviews apply. Original Decompose and Skills screenshots remain structural references: calm surfaces, restrained boundaries, compact navigation, content-first library/workspace/inspector. Do not restore mascot-heavy marketing or invented fleet data. + +Scope: local final workbench stylesheet, stylesheet mount, Agent files header/toolbar/row-density markup, compact row date presentation (full timestamps/UTC remain in inspector/title), and secondary initial Markdown outline disclosure. Soften workbench surfaces/borders/typography; remove stacked chrome/redundant row labels; favor source width and continuous code surface. Keep source bytes, line markers/outline/folds, findings, dates, metadata, errors, available actions and full keyboard focus accessible. Limits/disclosures remain present and labeled; no unsupported state is hidden to imply readiness. All actual controls retain approximately44px hit targets; reduce padding/visual framing and redundant stacked content rather than overlapping hit areas. Scope styles to the native workbench, not standalone setup/credentials/sample apps. + +Acceptance: actual synthetic before/after1440CSS source position/row density evidence; source starts earlier and more file rows fit; code stays readable; original task hierarchy and soft light/dark palettes;320/768/1440 dark/light no page overflow; keyboard outline/fold/finding navigation, selection/filter retention and lock purge unchanged; focused/full source/visual/vision tests and fresh read-only review. Existing reduced-motion/forced-color and unrun OS/SR/touch/native gates remain distinct. No model/controller/native/storage/crypto/authority/provider/dependency changes, normal data/keys/vault, engine/remote/infrastructure operation, foreign edits or publication. No commit/push/merge/deploy/release. + +## MR-1 IDE-style Markdown review — October 27, 2026 + +Authority: Jeff requests agent/Markdown files parsed and reviewed like a code IDE with highlighting and grouped code. Current request accepts this bounded thirteen-path renderer/source-review slice; exact ownership/preimages are in `/rangoon-markdown-ide-20261027`. Root owns implementation/integration and source/security decisions; fresh independent source/UI review is required. + +Additional user steering during this packet: Jeff asks “how can we support terraform and how does that help us?” This authorizes research/advice and a clearly proposed informational note in the already-owned experience/continuation/development documents. It does not accept a Terraform adapter implementation, architecture contract, dependency, configuration change, credential use, plan execution or Apply. Keep that proposal distinct from delivered Markdown features and from future implementation acceptance. + +Provide a local, bounded lexical review projection: line-numbered Markdown, heading outline/hierarchy, foldable heading and fenced-code groups, language labels, lightweight syntax colors, frontmatter grouping and line jumps from findings. Agent files gets a central source-review work area; Import source uses shared safe line highlighting without replacing native section selection. This is a read-only review aid, not a full CommonMark/language compiler, semantic validity check, saved artifact, native range parser or trust/approval signal. Preserve original source and native IDs/ranges, local findings, composition/storage/lock behavior. Escape all untrusted text, never render Markdown HTML, load link/image URLs, run embedded code or use a provider. No new dependencies or network/native calls. Unrecognized languages remain plain code with their exact label visible; malformed/unclosed blocks get honest lexical notes. Bound bytes/lines/groups/tokens with explicit unavailable fallback rather than silent truncation. + +Acceptance: headings inside fenced code/frontmatter stay inert; nested/empty/Unicode/CRLF/BOM/long/malformed sources remain stable and escaped; fold/jump is keyboard-operable, opens enclosing groups and targets the right original line; local matching rerenders preserve folds/scroll/focus, different files do not inherit folds, Lock clears source/UI state and late reads remain fenced. Native section/range contracts remain unchanged. Run focused view/tokenizer/binding tests, full source build/visual/vision tests, bounded parsing/render benchmark, exact ownership/hash/link/intent checks and actual synthetic 320/768/1440 light/dark interactions. Native GUI/media/SR/touch qualification stays separate if unrun. No normal data/keys/vault, provider/remote/native app operation, engine/LNSAT/VUSL edit, dependency install/fetch or commit/push/merge/deploy/release. + +## CU-2 Skills editing and revision context — October 27, 2026 + +Authority: Jeff says keep working after CU-1, continuing the accepted intuitive modification/combination direction in Skills. This accepts the bounded twelve-path UI/local-controller slice recorded in `/rangoon-skills-ux-20261027`: clear saved/draft/historical/conflict status, native revision timestamps and lineage context, collapsed source creation and advanced provenance, and explicit identity-bound confirmation to discard only current unsaved fields. Root owns implementation/integration; a read-only design role supplies direction and fresh independent source/UI review is required. + +Keep the existing native capability save/review/open contracts, dirty-draft maps, source references, conflict/reload and workspace lifecycle. Local discard performs no IPC or persistence and preserves all other skill drafts; conflict discard does not lift the reload gate. Confirmation binds exact skill/base revision/title/content and invalidates on edits or selection change. No delete/restore, native schema, provider/engine, remote sharing, runtime, new framework/dependency, authority or publication action. UI action hints do not replace native validation. + +Validator-driven scope adjustment: include `tests/term-help.test.mjs` to preserve the one closed glossary panel invariant while permitting the separate source-creation disclosure. This changes no glossary behavior or production scope. + +Acceptance: saved versus editing versus history/conflict state is visible and consistent during ordinary rerender and in-place input; historical records stay read-only with current draft retained; native-created/reviewed timestamps are distinct from edit state and exact UTC remains inspectable; technical IDs/hashes are collapsed; creation stays secondary and source-specific; discard requires explicit confirm, refuses stale/pending/historical/wrong-skill context, and keeps conflict and other drafts intact. Preserve focus/caret, current-skill disclosures and filtered-hidden context; lock clears confirmations/disclosures/drafts and ignores late results. Run focused model/view tests, full build/vision/visual checks, documentation/intent/link and exact-delta/hash preservation, actual synthetic browser 320/768/1440 dark/light and relevant interaction/failure tests. OS media/SR/touch and native save/recovery qualification remain separate if unrun. No normal data/keys/vault, native app/target/provider/remote contact, foreign edits, install/fetch, commit/push/merge/deploy/release. + +## CU-1 contextual composition interaction — October 26, 2026 + +Authority: Jeff requests continuing the UI overhaul so modification and combination feel intuitive and organic. This accepts a bounded renderer-only slice on the existing composition routes: section quick-selection, compact selection-to-output actions, progressively disclosed advanced operations, selected-source/destination inspector and retained local interaction context. Root owns implementation/integration; an independent design agent supplies read-only direction and fresh reviewers inspect final source/rendered behavior. Exact eight-path ownership/preimages: `/rangoon-composition-ux-20261026`. + +Reuse existing composition controller, exact UTF-8/CRLF range mapping, undo/redo, native preview/save gates, form-draft preservation and lock purge. No source mutation, new saveability computation, new storage/API/engine/provider, remote controls, runtime or framework/dependency. Source text remains read-only; these edits change only an in-memory recipe. Native saveability, retained preview and transaction stay authoritative. Remote sharing remains planned and receives no active-looking connection controls. + +Acceptance: clear no-selection versus selected/pending states; exact section range selection with escaped heading/provenance; no whole-view rerender on source selection; one primary Add action with output context; deliberate duplicate/replace/exclude/conflict in closed advanced controls; visible local validation notices; preserve output choice, advanced disclosure, selection/caret and unfinished text across ordinary rerenders; clear/fence on lock/dispose; undo and preview invalidation remain unchanged. Run focused view/controller tests, full build/vision/visual tests, exact ownership/whitespace/hash checks and actual synthetic browser interaction/layout checks at 320/768/1440 light/dark. Motion/color OS modes, real assistive technology/touch/native GUI remain separately pending unless actually exercised. Fresh independent source/UI review required. No normal data/keys/vault, target/provider operation, foreign edit, dependency install/fetch, commit/push/merge/deploy/release. + +## Remote setup management direction — October 26, 2026 + +Authority: Jeff requires the ability to manage remote setups, continuing the bulk agent-file, timestamp and revision workflow. This accepts product direction and a bounded six-document reconciliation; remote service/transport, enrollment, credentials, connections and writes remain separately scoped implementation/qualification. Reuse the existing fleet/deployment and R9 adapter-design vocabulary, plus encrypted-history source, not a second management product. The [remote-management section](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) is canonical for staging, source gaps and the first implementation packet. The [fleet console](operations-control-plane.md#fleet-management-console-direction) owns the common UI hierarchy. + +Default first milestone is one explicitly enrolled lab host's read-only agent-file inventory and selected content inspection; a different owner-selected priority can revise the sequence. Local work remains available offline. Jeff clarifies that remote file access should use other Rangoon installations: each sharing installation exposes an explicitly enabled, restricted host service to authorized Rangoon peers. A headless installation may later expose the same service without a GUI. LNSAT is optional; an unrelated bridge product or third-party API is not the default file-sharing path. No generic remote shell, raw database access, ambient credential/config discovery, home/network crawl or implied approval from successful connectivity. + +Root owns architecture/security/privacy and the six named documents. Acceptance: reconcile existing contracts and source; distinguish delivered local behavior from planned remote capabilities; specify host/target identity, bounded root scope, metadata/content transfer consent, cache/time/revision provenance, connection failure and uncertain-write behavior, per-operation support, stages and an exact first offline implementation packet with validators; fresh independent read-only review. Documentation/link/intent and exact-delta checks apply; no new UI/native/source or live-host claim. No normal data/keys/vault, credential use, host enrollment or remote contact, install, provider, infrastructure mutation, foreign edit, commit/push/merge/deploy/release is opened. Evidence/preimages: `/rangoon-remote-direction-20261026`; peer-installation clarification: `/rangoon-peer-direction-20261026`. + +## BF-1 bulk agent-file workbench — October 26, 2026 + +Authority: Jeff requests a major UI overhaul for practical bulk viewing/orchestration of agent files and automatic issue/outdated-method tags. This accepts a bounded first source/UI slice: an Agent files route using the current shared shell, native multi-file read-only selection and existing saved-source reads. Root owns source contracts, native privacy/lifecycle, controller/integration and validation. A disjoint UI worker may own only the pure view, scoped CSS and its test file. Fresh independent source/rendered review is required. Exact ownership and preimages: `/rangoon-bulk-files-20261026`. + +Normal view: compact task header, source-type facets, searchable paged file table with local multi-selection, selected-file inspector and clearly advisory findings. Advanced IDs/digests/rule evidence remain collapsed. Existing Skills, composition, encrypted storage, compiler/export and instruction history stay intact. No fake project paths, agents, live telemetry, executor or readiness state is introduced. Only explicit user actions initiate file selection or checking saved sources. Native selection accepts at most 32 explicit Markdown files; retained content is bounded at 4 MiB with visible per-item refused/unassessed outcomes, never silent truncation. Reuse native one-file validation and Gate/request/owner/drain handling. No renderer filesystem path or replacement original is accepted. Selected unsaved files stay in memory; this packet does not silently archive them or create a new persistence domain. + +Advisory checks use a small versioned local rule pack with exact source/line evidence and no execution or model/network call. Match diagnostics, empty content and explicit risky instruction markers; do not label arbitrary old files or unfamiliar methods obsolete. Actual outdated-method findings require pinned primary evidence plus relevant target-version context; where absent show compatibility not assessed and plan the catalog separately. Rule findings never become trust, local review, approval, authority or automatic fixes. Existing Markdown parsing/composition remains authoritative for its own closed scope. + +Acceptance: real native bounded selected-file/saved-source pathways, cancellation/stale/lock refusal and late-result purge; no analysis-session replacement during read-only collection inspection; original files unchanged; no silent data loss on cancel/failure; paging/search/local selection without native calls; escaped malformed/duplicate names and partial failures; bounded DOM/response/memory and measured renderer benchmark; actual 320/768/1440 dark/light layout and keyboard checks, source checks of reduced-motion/forced-color rules, focused/full JS and affected offline Rust/native compile tests, vision/build checks and fresh review. No new framework or dependency. Normal data/keys/vault, engine/provider operation, foreign edits, install/fetch, publication and release remain closed. Native GUI qualification uses disposable synthetic files only and remains distinct from compile/renderer evidence. + +Qualification boundary clarified after independent review: actual OS reduced-motion/forced-color, screen-reader, touch and native-picker checks remain required before claiming those modes or personal-data qualification. This source/UI slice records their pending status and does not waive them for desktop shipping. The earlier acceptance wording overstated the available OS-mode evidence; it is corrected here rather than marking an unrun check passed. + +This starts the overhaul; folder discovery, persistent collections/tags, version-aware compatibility catalogs, governed batch mutation and runtime task dispatch remain later scoped packets. Do not raise storage limits, bypass encrypted-history prerequisites or build another agent scheduler to make a bulk UI appear operational. + +Jeff's follow-up requires dates/timestamps and revision context. This slice adds distinct native saved and session selected/checked observations with explicit time provenance; it does not invent filesystem dates or filename-based revision lineage. Target-bound encrypted history mounting remains the next staged extension under AR-3, as specified in the experience record. + +## AR-1/AR-2 instruction history continuation — October 25, 2026 + +Jeff explicitly requests encrypted instruction-history persistence and preservation of parsing, merge, split and reassembly with intelligent detection. This authorizes the bounded store/domain continuation below; it does not open native target-file replacement or provider operations. Root owns source, schema, recovery and integration. The existing [archive contract](target-loader-qualification.md#instruction-change-archive-and-restore--october-25-2026) remains canonical. + +Implement exact immutable changes and an append-only outcome journal in opt-in schema 5 of the existing SQLCipher workspace. Complete record validation, state identities, capacity checks, dependency-aware deletion and a new complete backup version must cover the new domain before it can be saved. Preserve old archive decoding and existing schema behavior. New history save APIs refuse unencrypted workspaces. No history is automatically created or migrated during normal startup; native and renderer mounting remain later work. + +Reuse the existing deterministic Markdown analyzer and composition contracts for byte-range provenance, explicit copy/authored/replacement pieces, exclusions and conflicts. Analysis is advisory and exact original bytes remain independent of parsing success. No fuzzy match, classifier, inferred category or model output may authenticate a restore point, resolve an exact saved reference, authorize a target write or silently claim lossless reassembly. The focused tests must demonstrate exact reassembly and explicit split/merge recipes, malformed/unknown refusals, encrypted persistence/reopen, complete backup/restore, wrong-key/tamper refusal, capacity and stale-state behavior. Fresh independent read-only review is required. Exact paths and preimages are retained in `/rangoon-instruction-history-20261025`. + +No target runtime/file modification, normal data/keys, vault access, live provider, foreign repository, dependency install, publication or release is authorized. Persistent source and test implementation is not native UI or three-OS qualification. + +## Target-readback prerequisite continuation — October 25, 2026 + +Jeff requests starting the next phase after management optimization. This opens TLQ-1: exact installed-target identity/source research and a bounded, unmounted macOS isolation self-test harness using synthetic files and a local probe executable only. Root owns protected process/isolation judgment and source; fresh independent read-only review covers the exact seven-path packet and evidence. The [target qualification record](target-loader-qualification.md#tlq-1-isolation-prerequisite--october-25-2026) owns its behavior, acceptance and remaining runtime gates. + +Jeff's subsequent instruction-file backup/undo and secure archive/restore request adds an accepted product requirement to the same target-handoff direction. The [archive contract](target-loader-qualification.md#instruction-change-archive-and-restore--october-25-2026) requires exact byte hashes plus authenticated encrypted custody, drift-safe previews and crash recovery before target-file modification. It is not implemented by TLQ-1 or the existing workspace backup; its staged source packets remain proposed. + +No installed Codex/Claude process, schema generation, app-server, thread, model or tool call is opened by this slice. Do not repurpose HOME/CODEX_HOME, inherit credentials/configuration, read normal instructions or launch a real provider. Application/native/storage/compiler/profile behavior stays unchanged. Disposable canaries may create/read/write only their generated synthetic files and attempt denied local network/socket/child operations under the candidate OS policy. Missing containment fails closed without fallback. Normal data/keys, foreign repositories and publication remain closed. + + +## Management audit and optimization — October 25, 2026 + +Jeff requests assessing existing management systems and optimizing them. This bounded continuation audits workspace, activity-report and optional-system surfaces, then repairs the existing activity-report renderer/controller. Root owns contract interpretation, source and integration; fresh independent read-only review checks the exact delta and evidence. No new native, storage, protocol, execution or provider capability is opened. + +The canonical development receipt records current capability versus unfinished management workflows. Acceptance: preserve native report semantics and no-authority states; accept prefix-only producer counts without inventing tail events; cap duplicated event controls at 50 records per page; retain selection with explicit off-page/filter context; provide reset/reveal controls; clear stale filters after successful replacement or purge; preserve prior inspection on cancel/failure; avoid unchanged local rerenders. Current request supplies bounded source authority. Exact ownership and preimages are in `/rangoon-management-audit-20261025`. Normal data/keys, native launches, real providers, foreign edits and publication remain closed. + + +## E1d-2 native recovery continuation — October 25, 2026 + +Jeff explicitly requested: resolve dependency promotion, connect native backup/restore and prove recovery onto a fresh encrypted workspace. This opens the bounded [SQLCipher recovery-copy packet](encrypted-workspace.md#e1d-2-native-sqlcipher-recovery-copy--october-25-2026), source/UI integration, tests and isolated disposable macOS native qualification. Root owns store/native/security/integration and the request-bridge correction; a disjoint UI writer owns only the five named model/view/test files. The final 37-path packet includes the reviewed qualification observations, current-request bridge, format/vision assertions and focused regressions needed to complete the native path. Existing unrelated dirt is preserved. The evidence packet's exact ownership is `/rangoon-e1d2-native-recovery-20261025/owned-paths.json`. + +Do not promote the beta age experiment. Reuse existing pinned SQLCipher for a canonical encrypted workspace copy and separate native-selected recovery key file. The replacement is now usable on the selected disposable macOS path; the experiment is retained as standalone historical source outside the active workspace. No custom cipher/KDF, new crypto helper process or new runtime crypto dependency. Native file callbacks use the existing Gate/Owner/retained preview lifecycle. New native commands accept only workspace identity, never renderer keys/paths/original bytes. Source operations remain read-only and destination Restore stays explicitly previewed, additive and single-use. + + +The selected macOS journey created a native recovery key, wrote and independently reread a 94,208-byte encrypted backup, removed the original disposable database key, restored into a different encrypted workspace, and reopened it in another process with the same complete canonical archive identity. It retained one source, three skills, four skill revisions, two reviews, one recipe/application, two derivations and one workflow with two revisions. Five recorded native phases and their narrow limits belong to the development receipt. Jeff's additional disclaimer request is implemented in the backup dialog and collapsed recovery limits. Ordinary data access, other-platform and release gates remain closed. + +Qualification may create/read/remove only uniquely scoped test Keychain slots and disposable data/key/backup files. Normal user data/keys, provider/engine operation, LNSAT/VUSL edits and publication remain closed. A selected macOS result does not establish Windows/Linux recovery, release readiness, source authentication, rollback prevention or complete memory erasure. The specification and development ledger own exact validators, remaining gaps and independent reviews. + + +## E1d-1 experimental codec continuation — October 25, 2026 + +Jeff's “proceed then” after the reviewed E1d sequence opens dependency assessment and the bounded offline codec experiment. Exact ownership is workspace `Cargo.toml`/`Cargo.lock`, new `crates/rangoon-recovery/Cargo.toml`, `src/lib.rs`, `tests/envelope.rs` and `tests/fixtures/reference-age-v1.json` beneath that crate, plus this record, `docs/encrypted-workspace.md`, `docs/plan.md`, `docs/continue.md` and `docs/development.md`. Root owns protected dependency/cryptography judgment and implementation. Public registry/source/advisory/reference acquisition and an isolated temporary instance of the already-pinned Rust 1.99.1 are limited to this validation need; no global toolchain change or provider installation follows. Fresh independent pre-code review accepts only a synthetic unmounted prototype, not production recovery. + +The initial age 0.12.1 candidate is not selected: its resolved P-256 dependency path includes crypto-bigint 0.5.5 affected by RustSec RUSTSEC-2026-0387. Do not claim that dependency finding proves an exploit through X25519. The experiment pins age 0.11.5 with default features disabled, using explicit X25519 identities only. Its beta/testing status, 128-bit file key and unmaintained compile-time dependencies remain explicit; native/production promotion is blocked. No custom crypto, ambient key discovery, CLI secrets, key-store access, network/process/filesystem API, database mutation, renderer/native mounting, normal data/keys, foreign edits, publication or release is opened. The [frozen API and limits](encrypted-workspace.md#e1d-1-experimental-codec-profile--october-25-2026) and development receipt own implementation and evidence. + + +## Personal completion continuation — October 24, 2026 + +Accepted by Jeff: “screw it lets finish it” and “i want to finish it for me.” Resume Rangoon for personal utility. Commercial uniqueness, funding and competitor superiority are not acceptance gates for this continuation. Keep the existing local capability workbench and independent optional integrations. The discussion of shelving does not retire source or authorize deletion. + +First restore the latest recorded application source into a durable isolated branch, preserving both existing copies and unrelated website work. Then qualify the encrypted local source → skill → composition → compilation/export → reopen workflow on an isolated personal-use target. Personal macOS evaluation does not establish a released three-OS product or waive security, recovery or release gates. Supported external execution remains a later bounded adapter milestone; no custom scheduler, new universal protocol or broad feature expansion is required to finish the local workflow. + +This opens source recovery, focused implementation, offline/disposable validation and canonical planning updates necessary for that personal completion. Existing explicit restrictions on normal data/keys, credential/provider access, paid calls, infrastructure/production operation, LNSAT/VUSL edits, publication and release remain. The current recovery packet changes no runtime semantics: all recovered files must match their recorded identities before source work resumes. The development ledger owns exact recovery and validation evidence; the plan owns subsequent scope. + +## Internal operations-first direction — October 22, 2026 + +Owner: Jeff. Accepted direction: develop Rangoon first to supervise Hypler's own computing infrastructure, agent work and software portfolio. Commercialization and funding remain possible outcomes, but do not determine the next engineering milestone. Reuse the existing capability workbench, independent provider ports, operations records, fleet inventory and deployment-management designs. The [internal operations sequence](plan.md#internal-operations-first-delivery--october-22-2026) refines delivery order; [application architecture](application-architecture.md#internal-operations-first-boundary--october-22-2026) owns responsibility boundaries and the development ledger owns evidence. + +Customer Zero clarification: Jeff explicitly says he still wants the product built out and will be its first tester. Rangoon remains a general-purpose, open-source, cross-platform product; Hypler is the first user, not a required deployment or hardcoded product dependency. The supplied Customer Zero plan remains proposed strategic/implementation input. Jeff's current request authorizes [source reconciliation and gap analysis](customer-zero-gap-analysis.md), not automatic implementation of its full service, MCP, worker, model, budget or production scope. Complete and independently review that assessment before freezing the first new source packet. A distributed project-review job is the proposed first value milestone; unrelated connector completion is not a prerequisite for it. + +The intended outcome is an operator who can identify a registered system, inspect its actual state and coverage, supervise a bounded task, understand its measured resource/model costs, and reconcile its result. Existing runtimes retain process/VM/container scheduling and isolation. Rangoon coordinates typed application tasks; it does not become a hypervisor, container runtime, distributed-consensus implementation or unrestricted remote shell. LNSAT remains an independent optional authorization/evidence engine, OpenShell a separate optional runtime integration, and VUSL an independent semantic specification/core. No integration becomes a prerequisite for local content work. + +First prove a single isolated development target and a finite read before expanding the fleet or granting actions. Consequential operations later require a qualified enforcement path, exact target/action binding, applicable approval, execution-time checks and outcome reconciliation. Human approval, model advice, compatible protocols and a healthy target are never substitutes for that path. Existing production systems, credentials, keys, data and infrastructure remain outside this direction packet; later production adoption requires its own explicit operational authorization. + +Acceptance for this direction packet is a reconciled architecture and staged, measurable pilot plan, preserving the local release path and current source. Implementation of new task dispatch, hosted storage, budget enforcement, plugins, provider connections or infrastructure deployment requires its own reviewed source/operational scope. Hardware counts, GPU suitability and proposed machine roles are unverified planning input until inventoried and benchmarked. Risks include scope expansion, duplicate runtime responsibilities, stale observations, uncertain effects, incomplete cost accounting and accidental production access. Named documentation checks and fresh independent review are required; this direction does not establish product security, standards compliance or release readiness. + +## Unified Rust toolchain — October 20, 2026 + +Status: accepted direction and bounded implementation. Authority: Jeff explicitly requested unifying Rangoon's Rust version with newer VUSL. Read-only inspection of VUSL at `1697a71a35b0508c0dc28bf434d58df9c33c8967` confirms its workspace MSRV and toolchain are `1.99.1`. Rangoon adopts that exact compiler floor for the portable workspace and separate desktop workspace, with one root toolchain pin and coherent CI/validator/setup instructions. This deliberately supersedes the old current 1.85/1.98 split; dated validation receipts retain their original toolchain identities. + +Root owns manifests, build/CI policy, documentation, validation and final judgment. One bounded worker owns only the hardened source-check script and its tests. Exact packet paths: `Cargo.toml`, `apps/desktop/Cargo.toml`, `rust-toolchain.toml`, `scripts/check-source-rust.mjs`, `tests/check-source-rust.test.mjs`, `.github/workflows/source-checks.yml`, `README.md`, `docs/desktop-spike.md`, this record, `docs/continue.md`, `docs/development.md`, `docs/workflow-records.md`, `docs/workflow-definitions.md`, `docs/instruction-bundle.md`, `docs/export-handoff.md`, `docs/model-cloud-custody.md`, `docs/plan.md`, `docs/encrypted-workspace.md` and `crates/rangoon-compose/src/lib.rs`, `crates/rangoon-integrations/src/{lnsat_evidence,openshell_observation}.rs` and `crates/rangoon-ops/src/{approvals,delegations,lifecycle,projection,relationships}.rs` (equivalent conditional cleanups required by the new Clippy floor), plus `apps/desktop/src/cloud_models_tests.rs` (the deprecated atomic helper name only), `crates/rangoon-cli/src/main.rs`, `crates/rangoon-cli/tests/bundle.rs` and `crates/rangoon-language/tests/d0a.rs` (three equivalent test-fixture chunk iterators only), plus `crates/rangoon-model-local/src/transport.rs` and `crates/rangoon-model-cloud/src/{check_wire,transport,wire}.rs` (equivalent response guards and unsigned leap-year divisibility checks required by Clippy), plus `crates/rangoon-compile/src/bundle_tests.rs`, `crates/rangoon-model-session/src/{cloud,lib}.rs` and `crates/rangoon-openshell-client/src/lib.rs` (one fixture iterator, two lease-drop guards and one exact certificate-pin decoder iterator required by Clippy). Preserve both lockfiles and dependencies, runtime/domain/crypto behavior, historical parser source and unrelated changes. Use the already available isolated compiler; no local tool/dependency installation or fetch is accepted here. The existing CI provisioning steps may be updated to explicitly provision the pinned toolchain on future authorized runs; the validator itself never installs, and no hosted run is triggered here. The validator must pin subprocess identities, refuse wrapper/config drift and never auto-install a missing toolchain. + +Acceptance requires static pin coherence, meaningful validator regressions, locked/offline core and desktop format/test/Clippy/build evidence on 1.99.1, document/preview checks and fresh independent read-only review. Missing validation remains explicit rather than inherited from earlier CI. This is not VUSL consumer adoption, target-loader qualification, native GUI/OS/release qualification, provider activation or permission to edit VUSL/LNSAT. The prior disposable native nonce was exactly cleaned before source-pin changes; its unfinished cases require a new artifact. Commit, push, merge, deploy and release remain closed. The [development receipt](development.md#unified-rust-toolchain--october-20-2026) owns progress and exact evidence. + +## E1c-5e ordinary Lock handoff acceptance — October 20, 2026 + +Jeff explicitly answered “Accept E1c-5e source/tests” to the reviewed [ordinary-Lock/startup handoff correction](encrypted-workspace.md#e1c-5e-ordinary-lock-and-startup-handoff--proposed-correction). This accepts its three named native files, race and lifecycle regressions, canonical records and isolated disposable macOS rerun. Root owns protected lifecycle decisions, production integration and validation; a disjoint worker may own the named native-bootstrap test file only. One atomic Host-state decision may preserve only an exact completed idle non-effectful Handoff; all pending, busy, ambiguous and terminal states retain cancellation/drain or terminal refusal. No Host reset, replaced managed state or restored confirmation/client is permitted. Fresh independent source/evidence review and exact named gates remain required. Normal data/keys, provider contact, LNSAT/VUSL edits, dependency fetches, publication, merge, deployment and release remain closed. Acceptance is not native qualification. + +The reviewed correction classifies Host state before source cancellation, retains any detached cleanup custody through synchronous source closure, and drops it outside the Host mutex. This closes the final-check/publication race without changing the accepted packet's files, authority or lifecycle contracts. The development receipt preserves the failed first source review and subsequent correction; green tests do not replace native qualification. + +## E1c-5d source and disposable macOS acceptance — October 19, 2026 + +Jeff explicitly answered “Accept E1c-5d source/tests” to the reviewed [interrupted empty provisioning completion packet](encrypted-workspace.md#e1c-5d-interrupted-empty-provisioning-completion--proposed-source-gate). This accepts its exact protected Owner/native source, tests, bounded qualification-harness extensions and isolated disposable macOS qualification. Root owns recovery semantics, startup/consent/lifecycle integration and canonical records; disjoint workers may own bounded tests only. The operation completes an eligible pending CreateEmpty using the exact existing key, then requires separate Unlock and Restore; no key regeneration, overwrite or automatic retry is permitted. Fresh independent source/evidence and native UI review, exact source/store/renderer gates and artifact-bound disposable cases remain required. Normal data/keys, provider contact, LNSAT/VUSL changes, dependency fetches, publication and release remain closed. Windows/Linux qualification remains required before release; acceptance is not a passing test or implemented capability. + +## RUSL retirement and VUSL consumer sequencing — October 19, 2026 + +Status: accepted. Authority: Jeff explicitly retired RUSL as an active technical contract, preserved its development history, and rejected a maintained reader, converter, alias or dual-profile system without evidence of need. The old Rangoon parser remains inert experimental source until a usable independently developed VUSL core and updated affected consumer tests support a reviewed cutover. Retention is not a backward-compatibility promise. This supersedes active RUSL/D0a roadmap and old/new-reader or migration requirements in earlier records; their original acceptances, identifiers, fixtures and receipts remain historical evidence. + +VUSL owns its separate specification and core. Rangoon owns future consumer adoption: pin a usable upstream core/artifact, review mapping loss, refusal and authority boundaries, update and pass affected consumer tests, and independently review the cutover before removing old source. No current VUSL runtime dependency or public support is established by the historical spec/fixture manifest. Existing native OpenShell/LNSAT adapters remain independent optional integrations, and local capability workflows acquire no language or provider prerequisite. No RUSL source deletion, reader/converter/alias, dependency or VUSL/LNSAT edit is authorized here. + +The reviewed documentation direction is public through [PR #51](https://github.com/hypler-dev/rangoon/pull/51), merged at `9bd9be17d17fd8f778ec88f8e9b9f41df5c01dc4`. This active-worktree reconciliation preserves all native E1c-5c and independent connector work. The [development receipt](development.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026) owns exact files, validation and local state; public documentation does not publish the private engineering changes. Existing E1c-5c acceptance is unchanged. The separately accepted E1c-5d packet above owns its source and disposable-test scope. + +The following initial metadata and continuations preserve their dated acceptance history. They do not override newer directions or open a currently closed gate. + Status: accepted Authority: This record, based on Jeff's October 4, 2026 request in chat `01a10a12-fb75-7a42-bd2c-1ee9a0478d8d` Owner: Jeff @@ -38,7 +276,31 @@ Model assistance continuation, October 6, 2026: Jeff requested a function connec Optional curator continuation, October 16, 2026: Jeff selected an advanced model paired with human approval as an optional review aid for ambiguous consequential actions. A small local model may triage first; an advanced local or remote model may inspect a specifically selected, minimized case only through its qualified consent/privacy path. Models may propose risk tags, missing context and explanations. The human sees and approves the exact action and evidence where policy requires human approval; model output is never a human signature, delegated approver, grant or execution result. LNSAT remains model-independent and owns deterministic policy, scoped authorization and execution-time consumption. Missing or uncertain model output cannot silently weaken required review. This direction authorizes contract and fixture planning, not LNSAT modification, model download/training, external transfer, live approval routing or execution in the current packet. Future model-delegated authority remains a separate undecided design gate; model accuracy alone does not accept it. Jeff also requested decision analytics linking model advice, human review, deterministic policy, authorization, attempt and outcome without collapsing their distinct provenance. The [operations control-plane](operations-control-plane.md#telemetry-and-privacy) carries that planned evidence boundary. -Last updated: 2026-10-18 +Last updated: 2026-10-19 + +## E1c-5c source and disposable macOS acceptance — October 19, 2026 + +Jeff explicitly answered “Accept E1c-5c source/tests” to the reviewed [native startup and recovery packet](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate). This accepts its exact encrypted-default startup source, existing-workspace copy/recovery controls, named source validators and isolated disposable macOS Keychain/data tests. Root owns protected native/store/privacy integration; a disjoint UI writer may implement the frozen source-free contract. Fresh independent source/evidence and UI review remain required. This does not authorize normal user data/key operation, provider contact, LNSAT/VUSL changes, publication or release. Windows/Linux native/backend/GUI/install qualification remains required before the three-OS release. The development ledger owns actual implementation and qualification evidence; acceptance is not a passing test or completed cutover. + +## E1c-5b source acceptance — October 19, 2026 + +Jeff explicitly answered “Accept E1c-5b source/tests” to the reviewed [conversion and durable-selection packet](encrypted-workspace.md#e1c-5b-verified-conversion-and-durable-selection--proposed-source-packet). This accepts its exact unmounted native/store source, strict empty-target restore, bounded journal and disposable synthetic-key/process tests. Root owns protected implementation and integration; fresh independent source and evidence review remain required. Normal data/keys, OS vault, ordinary UI/default switching, providers, LNSAT/VUSL changes, publication and release remain closed. The development ledger owns execution evidence; E1c-5c remains separate native adoption. + +## E1c-5a source acceptance — October 19, 2026 + +Jeff answered “Accepted” to the reviewed [E1c-5a startup inspection and existing-source capture packet](encrypted-workspace.md#e1c-5a-startup-inspection-and-existing-source-capture--proposed-source-packet). This authorizes its exact unmounted native/store source and disposable tests, including bounded existing-only capture/revalidation and redacted backup diagnostics. The existing encrypted Owner, archive formats, source identities and limits remain authoritative. Normal data/keys, OS credential operation, actual migration, default switching, live providers, LNSAT/VUSL changes, publication and release remain closed. Root owns protected integration; fresh independent read-only source review and the packet's named validators are required. The development ledger owns implementation evidence. + +## Encrypted native cancellation correction acceptance — October 18, 2026 + +Jeff explicitly answered “Accept E1c-4a correction.” This accepts the [bounded native cancellation and storage-disclosure correction](encrypted-workspace.md#e1c-4a-native-cancellation-and-storage-disclosure-correction--proposed), its focused Rust/renderer regressions, independent review and fresh disposable native rerun. Native authority, exact control identities, explicit consent and fail-closed cleanup remain unchanged. Mechanical test-call updates to the two existing bootstrap confirmation fixtures accompany the typed consent result; they add no runtime behavior. No default switch, migration, normal data/key operation, provider/LNSAT change, publication or release is authorized. The development receipt owns execution evidence. + +## Integrated encrypted native qualification proposal — October 18, 2026 + +Continue toward the accepted plaintext-resolution outcome. The [E1c-4 packet](encrypted-workspace.md#e1c-4-integrated-native-encrypted-workspace-qualification--proposed) is accepted for source and its eight disposable macOS cases: shared native startup ordering, real renderer/Owner/OS consent, disposable macOS Keychain custody, actual process relaunch, bounded key-loss/cleanup and failure cases. It names exact source ownership and validators and preserves the separate accepted NX-06 matrix. Jeff explicitly answered “Accept E1c-4,” authorizing this reviewed source and the eight disposable macOS cases, including isolated Keychain setup, process restart, intentional test-key loss and exact cleanup. This supersedes the earlier proposal-only status. Normal data/keys, default switching, migration, providers, LNSAT and publication remain untouched. Ordinary startup remains Legacy until qualification and a separate reviewed cutover; existing data is not converted or deleted. The [development receipt](development.md#encrypted-native-adoption-packet--october-18-2026) owns review evidence. Do not add another constructor-only packet in place of this integrated outcome. + +## Encrypted startup source continuation — October 18, 2026 + +Jeff instructed “we need to resolve the plaintext issues” after the NX-06 result and the encrypted-startup audit. Continue the accepted encryption completion program with the independently reviewed [E1c-3 unmounted source packet](encrypted-workspace.md#e1c-3-encrypted-startup-integration-proposal--october-18-2026). Root owns the production-shaped locked constructor, feature-only backend/composition routing, integration, documentation and validation. A disjoint native GPT worker owns only the new bootstrap test file. This continuation implements that exact seam and its real SQLCipher/fake-vault request-bound tests; it does not authorize normal workspace conversion, OS-vault use, production mounting/defaults, provider operation, LNSAT edits or publication. Existing NX-06/O2 work is preserved. Fresh final source/evidence review follows the completed pre-code contract review. Actual encrypted desktop activation, Legacy migration and three-OS/package qualification remain separate gates. ## RUSL documentation publication — October 18, 2026 @@ -56,6 +318,10 @@ Jeff then explicitly requested committing, pushing and merging the accumulated R This supersedes older no-publication restrictions for the reviewed source packet only. Native NX-06 event-harness launch, real engine/credential access, encrypted production mounting, migration, deploy, executable package distribution and release remain closed. A source merge is not an installed-product completion claim. [Development](development.md#research-and-source-publication--october-18-2026) owns the final evidence and publication state. +## NX-06 disposable native event qualification proposal — October 18, 2026 + +Status: accepted for implementation and six disposable macOS cases. Jeff explicitly accepted NX-06 on October 18, 2026. The continuing support goal requires native event evidence beyond the accepted exit/admission source tests. The [exact NX-06 packet](openshell-observation-connector.md#nx-06-disposable-native-event-qualification--proposed-exact-packet) defines six cases, shared callback reuse, test-only fault/isolation boundaries, exact ownership, parent-observed exit codes and named validators. Acceptance covers bounded harness source and disposable macOS runs together, using only memory lifecycle fixtures and synthetic loopback peers. It does not open production Start, normal data/keychain use, encrypted factory mounting, real provider/credential access, LNSAT changes, restart execution, CI changes, publication, deployment or release. This acceptance supersedes the earlier native-harness exclusion only for this exact NX-06 packet. The earlier source/publication packet remains accepted and completed independently. The bounded NX-06 source and macOS qualification results are recorded in the [development receipt](development.md#nx-06-disposable-macos-native-lifecycle-qualification--october-18-2026); they do not complete the broader integration goal. + ## D2b-2a synthetic-peer native host acceptance — October 17, 2026 Jeff accepted the reviewed [D2b-2a source packet](openshell-observation-connector.md#d2b-2-native-host-consent-and-observation-custody--proposed-packet). Scope is exact native target and one-shot consent custody, workspace-generation and lifecycle handling, and dummy-lease synthetic-peer tests. Production Start, native provider credential acquisition, user gateway contact, renderer UI, encrypted observation save, LNSAT edits, merge, deployment and release remain closed. Root owns protected native integration, lifecycle, credential/network judgment and validation; one bounded implementer owns only the new host module and focused tests. D2b-2b and D2b-3 require separate acceptance and qualification. @@ -96,6 +362,8 @@ Jeff requested a provider-neutral, versioned Rangoon semantic language and a cur ## D1 pure offline parser authorization — October 16, 2026 +Historical scope: the accepted October 19 retirement decision above supersedes further RUSL/profile development or compatibility requirements. Preserve this original acceptance as history; it is not current VUSL behavior. + Jeff explicitly answered “Yes, begin D1 offline parser” after a question that limited work to a pure Rangoon parser and conformance tests, with no provider connection, LNSAT edit, credentials, execution, merge or release. This supersedes the preceding design-only restriction for **one experimental, unmounted D1 source packet**. Root owns `Cargo.toml`, `Cargo.lock`, this intent, the D0a specification, plan, continuation and development ledger. One bounded Rust worker owns only new `crates/rangoon-language/**`; the reviewed JSON vectors remain candidate inputs. The packet accepts no provider adapter, host mapping, database or filesystem access, network/process behavior, action/context commitment, approval, authority, native payload reference or actual execution. The candidate D0a profile is an implementation target for offline tests, not yet an accepted public wire/SDK contract or qualified provider support. Profile/schema identity, complete O1/I1 host fixtures, independent cross-language conformance and source/OS qualification remain separate gates before mounting or advertising interoperability. A fresh independent read-only source review and named Rust/workspace checks are required. ## Internal D0a profile and D2a offline adapter — October 17, 2026 diff --git a/docs/lnsat-evidence-connector.md b/docs/lnsat-evidence-connector.md index 18237ea..c0e9080 100644 --- a/docs/lnsat-evidence-connector.md +++ b/docs/lnsat-evidence-connector.md @@ -4,7 +4,7 @@ Status: proposed Intent: [VUSL design request](intent.md#universal-systems-language-design-request--october-16-2026) Owner: Jeff -Last updated: 2026-10-18 +Last updated: 2026-10-19 This is proposed D3: an **optional, read-only LNSAT evidence connector** for an exact operator-selected object. It refines the [accepted A1 boundary](engine-integration.md), [provider-neutral inspection contract](provider-interoperability.md), and [operator-record target](operations-control-plane.md#cross-runtime-operator-record-acceptance-target). It replaces none of them. Rangoon's local import, source provenance, revision, composition, compilation, export, and inspection must work with no LNSAT installation or connection. LNSAT alone owns authorization, approval, consumption, execution admission, receipts, and reconciliation. @@ -37,6 +37,36 @@ The inspected source routes `GET /v1/operations/{operation_id}`, `GET /v1/operat Critically, `POST /v1/operations/{operation_id}/reconcile` is a `MutationPreflight` request requiring `RequestAction`; its handler calls runtime reconciliation. Although LNSAT describes the route as inspection-only and never retry, it is **not** a GET evidence read. D3 excludes it. The `reconcile_operation` name in A1 remains unavailable, and no Rangoon button or background poll may invoke this POST under the read-only profile. A later explicit mutation packet would need its own authority, side-effect, idempotency, timeout and failure proof. +### October 19 request-record candidate compatibility check + +Read-only local inspection selected clean worktree `codex/request-bound-git-result-20261018` at `605742b39e09bde9c37c6d767e21917e705b3757`. The canonical LNSAT checkout remains on a different historical branch; this candidate is not a verified public-main, release or installed-runtime pin. No fetch, daemon, CLI, database or provider was operated. The [Rangoon audit receipt](development.md#lnsat-request-record-compatibility-audit--october-19-2026) owns comparison artifacts and validation. D3a remains pinned to `f669181a`; this research does not expand its accepted decoder or D3b transport scope. + +The candidate's six existing authorization/operation/attempt serializer functions, three exact read wrappers and runtime-composition denial formatter are byte-identical to D3a's research pin. This is ten named function comparisons, not complete transitive, routing, authentication or runtime compatibility. The new request-record schema is different and must not be fed into the existing decoder as if it were `lnsat.gateway.runtime_composition.v1_0`. + +| Candidate source surface | Actual supplied evidence | Rangoon integration consequence | +| --- | --- | --- | +| `GET /v1/action-requests/{request_id}/operator-record`, JSON `schema: "lnsat.action_request_record.v1"` | Exact request root, evaluation state, first replay/conflict observations and bounded linked evidence | Strong candidate for a separate request-record decoder/profile; not an added field or silent upgrade to D3a. GET/HEAD are supported by the inspected source, but a future evidence adapter should select the bounded GET response explicitly | +| Request/evaluation | Request/project/resource/packet commitments and `requester_ref`; recorded/failed/unknown evaluation, policy reference/reason/time | Request commitments have distinct digest domains from execution authorizations. Preserve the distinction. The source exposes a requester identity reference, so any future Rangoon projection must explicitly minimize/redact it; do not claim all actor references are absent | +| Replay/conflict observations | At most the first exact replay and first changed-packet conflict; submitted digest and observation time | Display reported repeated/changed submission evidence, not a retry count, attempted execution count or new evaluation. A conflict does not reveal the full changed packet or authorize resubmission | +| Linked evidence, `lnsat.action_request_linked_evidence.v1` | Separate policy, approvals, approval decisions, authorization attempts, authorizations, operations, consumptions, operation attempts, receipts, reconciliations and state histories | Preserve arrays, IDs, lineage, native state and uncertainty. Native approval decisions and a gate-satisfied bit are reported facts; they do not become Rangoon approvals or permission to execute. Approver identities/sessions and complete delegated approval-chain context are not supplied here | +| Private request-bound Git-result persistence | Generic linked receipt/result digest and reconciliation/state records can be projected when lineage validates | The read surface does not expose Git commit/tree IDs, changed paths, patch hash, adapter/protocol identity or detailed observer provenance. A receipt alone cannot identify that Git protocol or prove a real Git effect. The proof constructor and dispatch support in this candidate remain test-only; no production observer or public result-submission route follows | + +The native `approval_decisions.reason` string is also observable. A bounded engine allowlist is not proof that free-form reasons are secret-free; the future Rangoon profile must explicitly minimize that field and requester references instead of copying the full native record into logs, telemetry or UI diagnostics. + +The HTTP success body directly serializes the record; it has `schema`, not D3a's `contract` wrapper. The native `status: "complete"` means a complete bounded projection for that record, even when evaluation is unknown or an operation is unfinished. Rangoon must label record availability separately from request, approval, attempt and outcome states. `status: "degraded"` drops linked details and reports unknown evaluation; do not retain old favorable evidence under that response. The inspected response cap is 65,536 serialized bytes, with at most 64 serialized rows per linked family. Internal detection of a 65th row rejects the projection; it does not emit a wire sentinel. Projection overflow or invalid lineage degrades the whole record, without partial linked history. Other transport/authentication failures retain their separate generic refusal behavior. These are candidate engine limits, not a replacement for Rangoon's own bounded-input validation. + +The exact read requires active local session-token and session-proof verification, `ReadEvidence`, and either active Owner status or the original requester identity. `ReadEvidence` alone does not permit every Operator/Auditor to read every request. Missing and cross-identity records are indistinguishable after authentication; the generic HTTP 403 uses `gateway.action_request_record.denied`. A client must not interpret that as policy denial, object absence or proof of no action. Success includes `security_activity_touched`; authenticated read-side bookkeeping remains distinct from action/configuration mutation. This does not grant Rangoon a same-origin browser session, external-client identity, login/cleanup flow or credentials. + +**Recommended next integration target, still proposed:** prepare one independently reviewed offline request-record profile against a deliberately selected immutable LNSAT artifact. This pure offline profile can be developed independently; live integration still requires qualified encrypted custody. Retain D3a for its older exact-object purpose. Required future fixtures cover recorded policy allow/deny/approval-required, failed versus unknown evaluation, first replay/conflict, multiple linked approvals/attempts, generic 403, degraded/overflow data, omitted approver identity, unknown effect, receipt without independent effect proof, and foreign-engine matching IDs with no inferred join. Add malformed/duplicate/unknown-field and exact request/scope/lineage mismatch cases. A new profile must define its exact privacy projection and O1/O2 mapping before source acceptance; no VUSL schema is developed here. Live connection, request submission, approval/authorization mutation, execution and POST reconciliation remain separate closed gates. + +### October 19 guarded fake-dispatch follow-up + +A later read-only local worktree check found clean `codex/guarded-fake-dispatch-20261018` at `96e4a0910dcbb091c1846db742fa79daa6fb36ff`, following source commit `25d2afd4`. The prior request-bound Git-result candidate remains clean at `605742b39e09bde9c37c6d767e21917e705b3757`. These are different local candidate identities, not a public-main/release/install pin. No fetch, LNSAT test, daemon, CLI, database or provider operation was performed. D3a stays on f669181a; no Rangoon decoder or compatibility pin changes here. + +The candidate's `docs/architecture/request-execution-admission.md` describes a private fresh immediate-transaction guard immediately before fake handoff. It binds the reservation to the original in-memory store instance and rechecks the exact request/session/approval/authorization/nonce/digest/expiry lineage. Only cfg(test) exposes its fake dispatcher. Callback error/panic consumes the handoff and attempts source-protocol outcome_unknown persistence; fake success leaves dispatching and creates no receipt, reconciliation or completed effect. The documentation records fourteen grouped source tests, which this Rangoon audit did not run. Its build sequence still requires separately approved real disposable runtime proof. This is meaningful source progress in the independent engine, not production action-loop, real consequence or live Rangoon support. + +Rangoon must preserve that distinction in the future operator record: reservation and dispatching are not execution; source-protocol unknown has no proved consequence; matching IDs/digests are not a cross-runtime bridge. Complete denied, approved, changed, repeated and uncertain request views still need qualified native ingress and the explicit OR-01–OR-12 evidence matrix. Do not add LNSAT enforcement or a fake dispatch capability to the OpenShell connector. The [current goal-path receipt](development.md#e1c-5c-startup-and-recovery-design--october-19-2026) owns this follow-up and remaining sequence. + ### User job and scope An operator selects one explicit LNSAT installation/profile, environment, and exact operation ID. Rangoon may later show the engine's native authorization, attempt, receipt, and already-recorded reconciliation readback with native IDs, contract/version, source time, read time, redaction, and coverage. It must preserve distinctions among request/evaluation, human approval, issued authorization, consumed authorization, attempted effect, reported receipt, and independently verified consequence. A valid grant is not a completed effect; no receipt or a failed read does not prove non-execution. LNSAT evidence never becomes Rangoon's own approval or a permission for Rangoon to execute. @@ -53,7 +83,7 @@ OpenShell is a separate connector. LNSAT readback works without OpenShell; an Op | `read_exact_operation` | Request one exact operation, then its referenced exact authorization and optional attempt, only when the selected source allows each read. | GET only. Bind every returned object to the selected installation, environment, operation and exact reference. Never broaden to enumeration or follow arbitrary response URLs. | | `read_exact_evidence` | Future exact approval/audit object read where LNSAT offers an authorized stable route. | Separate permission and reviewed native schema; do not infer full approval chain from operation fields. Unsupported until pinned. | -Reuse I1's provider identity/version/compatibility and evidence-provenance concepts, A1's closed unavailable operation boundary, and O1/O2's existing local observation records and presentation. D3 needs an LNSAT-native decoder/mapper and conformance fixtures, not a second generic integration envelope or independent authority engine. The proposed D0a VUSL profile admits only unverified policy/runtime observations; it has **no authorization, approval, receipt, or authenticated-ingress variant**. Do not force these LNSAT objects into D0a or set `authenticity=verified` on a D0a document. Keep qualified native evidence in the selected host custody until a later separately reviewed VUSL authority/evidence profile and trusted ingress exist. +Reuse I1's provider identity/version/compatibility and evidence-provenance concepts, A1's closed unavailable operation boundary, and O1/O2's existing local observation records and presentation. D3 needs an LNSAT-native decoder/mapper and conformance fixtures, not a second generic integration envelope or independent authority engine. The retained historical D0a research admitted only unverified policy/runtime observations; it has **no authorization, approval, receipt, or authenticated-ingress variant**. RUSL is retired as an active contract. Do not force these LNSAT objects into D0a or set `authenticity=verified` on an old document. Keep qualified native evidence in selected host custody until its separately reviewed provider-native projection, retention and trusted-ingress gates are met. No RUSL/VUSL profile or core is a prerequisite for this independent connector; VUSL specification work stays upstream. For each native fact retain its source-qualified installation/environment/engine ID, product and wire contract, native object ID, object kind, referenced IDs, source timestamp and read timestamp, version/revision if actually supplied, payload digest or explicit omission, transport/authentication status, and adapter/profile version. Preserve native bytes only under an accepted encrypted-custody, redaction, retention, deletion and size policy with explicit consent. If native fields are omitted, transformed or unavailable, record that loss; never fill authority-critical fields from Rangoon UI state or another provider. A bounded canonical projection can add explanatory labels, not rewrite LNSAT decisions. @@ -102,11 +132,3 @@ One coherent caller-owned record is checked against independently selected reque Host output removes `requester_ref` and approval-decision `reason` after validation. It retains sensitive native identifiers, references, digests and times only in caller-owned host memory, with a fixed omission ledger. It is not anonymous, renderer-safe or accepted for plaintext persistence. Summary bytes contain only fixed labels and bounded counts; errors and Debug/Display are payload-free. No secret/session/header/path/URL/callback input, logger, network, database, clock sampling, storage or reconciliation interface is introduced. Offline decode claims no authentication or permission. A later native GET requires the engine's paired current session/proof and ReadEvidence plus active Owner or original-requester scope. Evidence reading never grants reconciliation-write authority. No POST, login, session cleanup, local capability, role upgrade, production observer/coordinator or actual Git consequence is opened. L01–L06 connected checks, credential custody, consent/encrypted retention/purge, transport, target OS/runtime and independent effect/reconciliation qualification remain separate and unrun. No O1/O2 wire conversion or UI is mounted; Rangoon remains usable without LNSAT and every provider. - -## Pure offline request-record inspection boundary - -The separately accepted source slice `rangoon_integrations::lnsat_request_inspection` wraps only the pinned pure request-record decoder. Its independently selected complete input context is host-owned; no renderer-supplied path, credential, host-detail accessor or caller-supplied summary route is introduced. Presentation is restricted to the exact fixed-label/count summary or an explicitly mapped closed error envelope. The existing decoder error wire is unchanged. Reported allow, receipt counts and accepted records never become current permission, independently verified completion or reconciliation authority. - -The logical lifecycle separates publication rights from owned-data release. Discard clears retained presentation and invalidates delivery, while the current purge cycle keeps the exact outstanding owner accounted for even after its publication generation is revoked. Late results must be released and cannot restore the view. Discard completes only after owner drain and an exact current instance/view/purge-ticket acknowledgment; Close latches permanent admission closure. A delivery borrow models serialization, not an authenticated native IPC channel. Fixed errors and Debug output exclude raw, selection, host and summary contents. - -No persistence, history, logging/telemetry, clipboard/export, provider/model transmission, live read, session/CSRF, native command or workspace encryption mount is added. Logical release cannot erase caller copies, previous disclosures, swap or crash dumps. Actual acquisition, sensitive selector entry, authenticated renderer delivery/purge, workspace lock/close coupling and platform cleanup require separate accepted adoption packets. The six adoption groups remain unrun. D3a, O1/O2 and the native profile/wire pins are protected; the [source receipt](development.md#offline-request-record-inspection-boundary--october-26-2026) owns exact current validation and review evidence. diff --git a/docs/model-cloud-custody.md b/docs/model-cloud-custody.md index ecf06a5..0f0be75 100644 --- a/docs/model-cloud-custody.md +++ b/docs/model-cloud-custody.md @@ -18,7 +18,7 @@ Use pinned `keyring-core` 1.0.0 with an explicitly constructed store, never its | Windows | `windows-native-keyring-store` 1.1.0 | Credential Manager, explicit Local persistence | | Linux | `zbus-secret-service-keyring-store` 1.0.1 | Secret Service with `crypto-rust`; absence/lock/access denial fails visibly | -The Secret Service adapter explicitly negotiates a DH-encrypted session with the service; this does not attest encryption of its backing files. The native desktop dependency workspace remains separate from the portable Rust 1.85 core. An OS store can prompt for access or unlocking; OS calls may block and are not claimed to support cancellation or a deadline. One custody operation owns the slot until its worker finishes. No overlapping access or automatic retry is allowed. +The Secret Service adapter explicitly negotiates a DH-encrypted session with the service; this does not attest encryption of its backing files. The native desktop dependency workspace remains separate from the portable Rust 1.99.1 core. An OS store can prompt for access or unlocking; OS calls may block and are not claimed to support cancellation or a deadline. One custody operation owns the slot until its worker finishes. No overlapping access or automatic retry is allowed. Store one bounded binary envelope: fixed format marker, 32 random revision bytes, and 1–2,048 ASCII graphic bytes for the credential. Reject whitespace, controls, non-ASCII, empty and oversized credentials without echoing input. Do not assume a provider prefix such as `sk-`. The secret and revision reside together in the OS store; no sidecar or SQLite credential record is written. Fresh replacement gets a fresh random revision. Native secret buffers use zeroizing ownership; no secret-bearing type implements Debug or Serialize. OS/library internal allocations, WebView strings and IPC buffers do not have proven erasure. diff --git a/docs/openhands-comparison.md b/docs/openhands-comparison.md new file mode 100644 index 0000000..f6194d0 --- /dev/null +++ b/docs/openhands-comparison.md @@ -0,0 +1,76 @@ +# Rangoon and OpenHands: execution reuse decision + +Status: source-based assessment and proposed adapter test, October 22, 2026. Not an installed integration or runtime qualification. +Authority: Jeff requested a direct comparison and architectural advantages/faults, with custom execution/scheduling development held pending this comparison. Preserve capability authoring, composition, provenance and evidence inspection. [Development](development.md#openhands-execution-reuse-comparison--october-22-2026) owns evidence; [plan](plan.md#internal-operations-first-delivery--october-22-2026) owns priority. This is supporting research, not another implementation ledger. + +## Exact comparison boundary + +Rangoon application checkout: `codex/ops-local-window`, HEAD `c132ea62bc57b29375ee8c5a3a38ca005462ca40`, including retained uncommitted source. The earlier [Customer Zero source inventory](customer-zero-gap-analysis.md#source-baseline-and-classification) remains applicable; no runtime code changed in this comparison. This assessment checks specific source paths, not all products, vulnerabilities, benchmarks or marketing claims. + +Public OpenHands sources were retrieved without executing them. SDK/Agent Server [v1.58.0](https://github.com/OpenHands/software-agent-sdk/releases/tag/v1.58.0) targets commit `38b6cdcc825df69ffdfe9c50e6635705612575ba`; Automation [1.25.0](https://github.com/OpenHands/automation/releases/tag/1.25.0) targets `850c66835a8176f30c6b0eaf75ca8b656191dad2`. Release metadata and exact source hashes are retained in the evidence directory. These are source/release identities, not tested installed artifacts. Automation's README explicitly labels its interfaces beta. Both inspected repository root licenses are MIT; package/container dependencies and any commercial services require separate review. Do not extrapolate these licenses to the entire OpenHands product family. + +## What is worth preserving + +“Differentiated” here means a concrete complementary ownership boundary against the inspected OpenHands components, not novelty or proof that no competitor has it. + +| Existing Rangoon capability | OpenHands overlap | Decision | +| --- | --- | --- | +| Bounded source inventory with retained bytes, line/range identity and digests: [import](../crates/rangoon-import/src/lib.rs), [domain](../crates/rangoon-domain/src/lib.rs) | SDK loads agent context and skills, including AgentSkills and progressive disclosure; skill handling itself is not unique. | Keep Rangoon's independent source/provenance review. Do not implement another OpenHands skill loader. | +| Pure composition/decomposition recipes, mappings and coverage: [compose](../crates/rangoon-compose/src/lib.rs); store resolves saved inputs and commits revisions | Agent skills/context assemble what an agent consumes. That overlaps prompt/context management, but the inspected SDK skill path is not Rangoon's transactional source-edit workbench. | Keep immutable source-to-output lineage and human review. Validate the actual imported OpenHands context separately. | +| Deterministic compilation and inspectable instruction bundles: [compiler](../crates/rangoon-compile/src/lib.rs), [bundle](../crates/rangoon-compile/src/bundle.rs) | SDK owns runtime agent/tool/context configuration. | Keep the portable authoring artifact and exact conversion report. Export success is not proof OpenHands loaded it or preserved every constraint. | +| Encrypted local content workspace and renderer/native separation: [native startup](../apps/desktop/src/workspace_native_bootstrap.rs), [composition boundary](application-architecture.md#composition-boundary-and-service-extraction) | SDK/server provide conversation/event persistence and selected secret encryption. These have different coverage from whole-workspace confidentiality. | Keep local-first content ownership. Qualify OpenHands event, workspace, log and artifact storage independently; do not claim Rangoon encryption covers them. | +| Cross-provider evidence inspection: [operations](../crates/rangoon-ops/src/lib.rs), [integration decoders](../crates/rangoon-integrations/src/lib.rs) | SDK has its own event stream/history and usage statistics. | Keep native evidence plus provider-specific interpretation and unknown states. Cross-runtime live reconciliation remains planned, not an existing advantage demonstrated end to end. | + +Rangoon's workflow graph is currently an authored definition and structural validator, with execution explicitly unavailable in [workflow source](../crates/rangoon-workflow/src/lib.rs). Its model assistance is advisory, not a coding-agent runner. Neither should be marketed as an existing OpenHands execution competitor. + +## Replace planned duplication with supported interfaces + +| Planned Rangoon work | Reuse candidate and source | Rangoon retains / qualification gap | +| --- | --- | --- | +| Agent reasoning/tool loop, context condensation, conversation lifecycle | SDK `BaseConversation` and remote implementation: [base.py](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-sdk/openhands/sdk/conversation/base.py#L255), `impl/remote_conversation.py` | Request scope, artifact identity and provider adapter; no fork of the loop. | +| Remote run/pause/interrupt and live events | Agent Server [conversation routes](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-agent-server/openhands/agent_server/conversation_router.py#L366) and [event routes](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-agent-server/openhands/agent_server/event_router.py#L213); REST/WebSocket, typed clients | Authenticated narrow adapter, reconnect/event coverage, lifecycle projection and cancellation verification. Pause/interrupt acknowledgements do not prove every child process stopped. | +| Conversation persistence/resume | SDK [state.py](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-sdk/openhands/sdk/conversation/state.py#L453) validates restored ID/tools and persists state/events | Persist Rangoon task-to-native-conversation mapping and recovery intent, not a copied conversation engine. Configure durable storage explicitly; memory-only mode is possible. | +| Cron, webhooks, dispatch, run history | Separate [Automation Service](https://github.com/OpenHands/automation/blob/850c66835a8176f30c6b0eaf75ca8b656191dad2/README.md), scheduler, dispatcher and run routes | Evaluate after one direct Agent Server job; beta API pinning, PostgreSQL and backend operations add deployment cost. No new scheduler by default. Not a demonstrated heterogeneous fleet/GPU-placement substitute. | +| Usage counters and traces | SDK conversation statistics and native event stream; Automation run records | Capture source measurements first. Rangoon's cross-provider reconciliation, reservations and organizational budget semantics remain separate; reported totals are not a hard spending cap. | +| Tool approval prompts | Native confirmation policies and confirmation-response API | Can surface and request native confirmation, but cannot claim exact action authorization from a generic accept response. See the critical boundary below. | + +Recommend a versioned REST adapter to a separately supervised Agent Server for the first test, leaving Python and agent internals outside the Rust/Tauri process. SDK is the engine behind that service; embedding a Python interpreter is unnecessary. Codex is the initiating client/test controller, OpenHands is the executor. A restricted Rangoon MCP entry can be mounted later over the same adapter; no such Rangoon MCP server exists today. Do not assume OpenHands exposes every required operation through MCP or that Codex subscription credentials can be reused as OpenHands model credentials. + +## Architectural advantages and faults + +**Rangoon advantages:** pure transformation crates are reusable without desktop/provider I/O; Rust/store owns authoritative saved-reference resolution and transactions; immutable identities make review and reproducible input selection possible; provider observations do not silently become execution authority. This is a sound control/workbench boundary to preserve. + +**Rangoon gaps:** no qualified durable execution path, task-to-runtime identity mapping or end-to-end proof of effective target configuration; native/provider support is narrower than preview surface area; content storage limits are unsuitable for operational logs; exported instructions do not establish enforcement. Introducing a second agent loop, queue, scheduler and copied event history would increase consistency and recovery burden. Keep one native execution owner and store only necessary Rangoon intent, links, reviews and reconciliation data. + +**OpenHands advantages:** concrete conversation execution, supported remote control APIs, event persistence and separate automation lifecycle already exist in the inspected releases. These can eliminate substantial proposed custom work, subject to actual integration tests. + +**OpenHands fit risks, not a full vulnerability audit:** + +- [Direct `execute_tool`](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-sdk/openhands/sdk/conversation/base.py#L410) explicitly bypasses agent-loop confirmation/security analysis. Terminal/bash/file APIs and another holder of server credentials may also lie outside the one controlled conversation path. A confirmation setting is not universal mediation. +- [ConfirmationResponseRequest](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-agent-server/openhands/agent_server/models.py#L438) contains `accept` and `reason`, not an expected action digest/version. [Acceptance](https://github.com/OpenHands/software-agent-sdk/blob/38b6cdcc825df69ffdfe9c50e6635705612575ba/openhands-agent-server/openhands/agent_server/event_service.py#L2081) calls run; an already-running result is treated as no-op success. The inspected API does not establish atomic compare-and-authorize for the exact action shown in Rangoon. Pre/post readback alone cannot close that race. Strict per-action authorization remains unsupported unless a qualified native/mediated tool boundary provides it. +- SDK state defaults to `NeverConfirm`; local persistence can be disabled. Explicit configuration and effective readback are required. A risk classifier is advisory; it is not an external permission engine. +- [Automation local backend](https://github.com/OpenHands/automation/blob/850c66835a8176f30c6b0eaf75ca8b656191dad2/openhands/automation/backends/local.py#L57) uses an externally managed server and workspace directories; it creates no per-run sandbox. Directory separation is not process/network isolation. [Cancellation](https://github.com/OpenHands/automation/blob/850c66835a8176f30c6b0eaf75ca8b656191dad2/openhands/automation/router.py#L1441) records state and may schedule sandbox cleanup; that is not independently verified process termination or rollback. +- Server secret-field encryption is not whole-event/workspace/log encryption. Service authentication, output confidentiality, telemetry consent, storage retention, dependencies and actual OS/container confinement need explicit pilot configuration and tests. No throughput, high availability, multi-tenant safety or three-OS qualification was measured here. + +## Can Rangoon govern an OpenHands task? + +Yes for task admission, reviewed inputs/configuration, placement constraints actually enforced by the runtime, result inspection and evidence retention. Not yet for a blanket claim that every OpenHands tool action is authorized by Rangoon or LNSAT. + +The proposed boundary is: authenticated caller → Rangoon task admission and immutable input/profile manifest → replaceable adapter → OpenHands conversation in a qualified confined runtime → native events/results → Rangoon evidence/reconciliation. Retain native conversation/action IDs and payload provenance alongside local review records. Mark each control as local admission, native confirmation, runtime-enforced, observed, unsupported or unknown. A task being admitted, a model reporting success, a native confirmation accepted and an externally verified effect are distinct records. + +Do not expose Agent Server credentials or general execution endpoints to the renderer/model. Restrict client access and keep supervisor secrets/control sockets outside executed code. A prompt or API allowlist is insufficient if the task has equivalent host privileges. Use OS/runtime enforcement and externally scoped resource credentials; a later LNSAT-mediated consequential tool must independently prevent alternate routes. Neither LNSAT nor VUSL is required for authoring or this limited adapter evaluation, and no LNSAT/VUSL implementation change is proposed. + +## One isolated Codex-controlled test packet — proposed, not executed + +Owner: Root controls identity/security, adapter semantics, integration and validation. One bounded worker may later own only named fixture/test files; fresh independent reviewer checks the exact packet. Freeze exact source files and validators before implementation. Do not install or start the downloaded sources under this assessment. + +Use a disposable synthetic repository and a separately owned sandboxed Agent Server, pinned release/image digest, explicit persistence and no host home, production paths, inherited credentials or control sockets. Initially use a deterministic local mock model with a fixed tool plan to exercise real OpenHands execution without paid inference; label this transport/execution proof, not autonomous model-quality proof. A genuine model run needs separate funding/credential/egress consent. Codex can drive the fixture harness; Rangoon MCP mounting is a later separately accepted source slice. + +1. Create one Rangoon task/attempt identity and exported instruction/source manifest. Denied admission must cause no executor dispatch. Admitted submission maps durably to exactly one native conversation; duplicate/conflicting submission is checked. +2. Read back effective tool set, context/configuration and confirmation policy; compare retained instruction bytes where the native API exposes them. Report unavailable readback and semantic loss explicitly. No portability pass based only on matching an export hash. +3. Run an allowlisted validator against disposable source. Prove denied host-file, credential, socket/metadata and unapproved-egress probes with synthetic canaries. Mutation of source/execution identities before launch must refuse. +4. Exercise native rejection and approval with retained pending-action evidence. Label them native confirmation only; inject changed/stale pending state to demonstrate that unqualified exact-action approval is refused by Rangoon, not falsely declared enforced. +5. Disconnect Codex/client, reconnect and retrieve the same native conversation/events/artifacts. Restart the service, then reconcile instead of automatically re-executing; capture event gaps/duplicates and saved-message/run-capacity failures. Agent Server documents that a message may be saved before a 429, so retry run rather than blindly resending the message. +6. Cancel during a running tool and independently observe process/descendant termination. Preserve unknown if termination is not established. Capture result/artifact digests, native errors and retained storage/cleanup evidence. + +Acceptance: pass task admission, actual confined execution, effective configuration/readback within explicit coverage, stable identity/reconnect and honest cancellation/evidence. Strict per-action authorization cannot pass on the current unbound confirmation API alone. A missing mandatory control blocks that scope. If OpenHands passes the bounded test, prefer it as the first execution adapter; evaluate Automation independently when scheduled work is actually needed. If it fails, implement only the evidenced missing capability behind a replaceable adapter or seek a supported upstream extension. No custom agent platform, automatic provider fallback or parallel scheduler is justified by this comparison. diff --git a/docs/openshell-observation-connector.md b/docs/openshell-observation-connector.md index 8c57879..c8f937b 100644 --- a/docs/openshell-observation-connector.md +++ b/docs/openshell-observation-connector.md @@ -4,9 +4,9 @@ Status: proposed Intent: [VUSL design request](intent.md#universal-systems-language-design-request--october-16-2026) Owner: Jeff -Last updated: 2026-10-18 +Last updated: 2026-10-20 -This is the proposed D2 contract for **one optional, read-only OpenShell connector**. It refines the [provider-independent interoperability boundary](provider-interoperability.md#independent-engine-connectors--october-16-2026) and [operator-record target](operations-control-plane.md#cross-runtime-operator-record-acceptance-target); neither contract is replaced. [VUSL D0a](universal-systems-observation-profile.md) admits only unverified inert reports. Authenticated connected evidence requires a separately accepted trusted-ingress profile and cannot be inserted into D0a by changing its `authenticity` field. Current `openshell_runtime.rs` O0/O1 is historical combined OpenShell/LNSAT research and cannot serve this independent connector. +This is the proposed D2 contract for **one optional, read-only OpenShell connector**. It refines the [provider-independent interoperability boundary](provider-interoperability.md#independent-engine-connectors--october-16-2026) and [operator-record target](operations-control-plane.md#cross-runtime-operator-record-acceptance-target); neither contract is replaced. The retained [historical RUSL D0a research](universal-systems-observation-profile.md) admitted only unverified inert reports; RUSL is retired as an active contract. It is not a prerequisite or a trusted-ingress path for this native connector. Authenticated connected evidence requires a separately accepted trusted-ingress profile and cannot be inserted into D0a by changing its `authenticity` field. Current `openshell_runtime.rs` O0/O1 is historical combined OpenShell/LNSAT research and cannot serve this independent connector. ## Behavior @@ -72,6 +72,8 @@ Map a native policy decision only to provider-policy evidence. Map a policy-chan | `gap` / `history_unknown` | Stream warning, `OUT_OF_RANGE`, restart/replica cursor-space change, bounded-buffer overflow, collector drop, unavailable workload logs or unknown earlier window. Show exact known window and source; no continuous audit badge. | | `error` | Malformed, over-limit, timeout or source error with bounded diagnostic. A timeout after a read may leave observation incomplete; it says nothing about external effect. | +Internal pending-state readback reuses the existing Host state: a current awaiting review reports `AwaitingConsent`; a current confirmed review reports `ReadyForNativeCredential`; an expired selection reports the fixed `CredentialLeaseExpired` error; a fenced workspace generation reports `Unavailable` before either phase or expiry. Readback is observational and does not consume a reference, renew a deadline, release admission, obtain a credential or start a client. Expired pending custody remains retained until explicit Stop or the existing close path. `ReadyForNativeCredential` describes the review phase only; it is not credential presence, provider connectivity, action approval or execution permission. This corrects the existing C0/C1 state contract without mounting a command or changing `begin_production` availability. + The view distinguishes `not observed`, `source unavailable`, `unsupported`, `not required by this provider` and `verified absent within a qualified finite source/window`; only the last has a proof obligation. An allowed policy rule and a denied request may coexist under different revisions or targets and must remain separate. A changed policy does not rewrite earlier native events. Repeated native IDs within one source become conflict/dedup diagnostics according to the pinned producer contract, never a best-looking winner. Any UI graph has a keyboard-accessible table and exact-source inspector; decorative motion cannot fill missing edges. ## Data, privacy, and permissions @@ -118,7 +120,7 @@ Pin fixture cases for same-name installations with colliding native IDs, one-ins **Operator flow and authority.** A later main-window operator selects one exact HTTPS gateway origin and explicit peer IP/port, trusted root and leaf pin, installation/workspace/sandbox, pinned product version and one bounded `ReadKind` (`protected_check`, `policy_status`, `recent_logs` or `recent_watch`). Native offline validation displays both the origin and selected socket plus data classes before any network call. The first profile never resolves DNS itself; changing the selected socket or TLS peer requires a new review, never an automatic substitution. D2b-2a uses only test-injected dummy bearer leases. Production credential acquisition remains unavailable until a separate native-only input or host-owned opaque OS-secret reference design is accepted and tested on all three OSs; an isolated webview is still a renderer and may not receive a provider bearer. The main window receives only an opaque native reference when that later gate opens. The host owns a zeroizing lease with a short monotonic maximum lifetime; user-supplied expiry metadata is an additional upper bound, not proof of identity or scope. No ambient CLI, environment, browser session, global keychain lookup, refresh flow, operator certificate or admin fallback is allowed. Native one-shot confirmation must bind exact destination, pin, scope, `ReadKind`, data classes, retention mode, workspace generation and credential reference. A claimed reference and its consent are single-use. Renderer confirmation alone has no effect. The first protected read, rather than public Health, reports whether authentication and sandbox read permission work. Consent to read grants no policy, approval, execution or LNSAT authority. -**Session-only first slice (D2b-2a).** Host operations are closed: validate a bounded proposed target without I/O; prepare exact native review; confirm or cancel; begin a finite read; stop; inspect a minimized status/result. Production begin returns `unavailable` until native-only credential acquisition is accepted; only tests inject dummy bearer leases and synthetic TLS peers. No arbitrary URL/method/credential reaches the client after confirmation. The retained one-shot consent stores exactly one `ReadKind`; dispatch calls only its matching closed client method. A different kind refuses before credential/client access, and a health check cannot stand in for protected permission. Every host operation uses the current workspace-client generation; stale, foreign, replayed or pre-lock queued requests refuse before credential access or network. Only one active observation per workspace generation is allowed initially. A new target, pin, scope, read kind or token requires stop and a fresh review. Client callbacks and cancellation survive dropped IPC waiters; lock, close, exit, credential expiry, destination drift and explicit Stop cancel and drain before any completed-lock claim. The native close coordinator must explicitly cancel and drain the OpenShell custody; a generic admission gate alone does not stop an active watch. If drain cannot be proved, show closing/recovery state and refuse a new read. Keep only the existing bounded, redacted `ConnectionCheck`, `PolicyRead`, `LogWindow` or `WatchWindow` projection in host memory. Clear it on Stop/lock/close and never write it to Legacy SQLite, logs, crash diagnostics, VUSL, O1/O2 or disk. D2b-2a does not contact a user gateway or test production OIDC provisioning. +**Session-only first slice (D2b-2a).** Host operations are closed: validate a bounded proposed target without I/O; prepare exact native review; confirm or cancel; begin a finite read; stop; inspect a minimized status/result. Production begin returns `unavailable` until native-only credential acquisition is accepted; only tests inject dummy bearer leases and synthetic TLS peers. No arbitrary URL/method/credential reaches the client after confirmation. The retained one-shot consent stores exactly one `ReadKind`; dispatch calls only its matching closed client method. A different kind refuses before credential/client access, and a health check cannot stand in for protected permission. Every host operation uses the current workspace-client generation; stale, foreign, replayed or pre-lock queued requests refuse before credential access or network. Only one active observation per workspace generation is allowed initially. A new target, pin, scope, read kind or token requires stop and a fresh review. Client callbacks and cancellation survive dropped IPC waiters; lock, close, exit, credential expiry, destination drift and explicit Stop cancel and drain before any completed-lock claim. The native close coordinator must explicitly cancel and drain the OpenShell custody; a generic admission gate alone does not stop an active watch. If drain cannot be proved, show closing/recovery state and refuse a new read. Keep only the existing bounded, redacted `ConnectionCheck`, `PolicyRead`, `LogWindow` or `WatchWindow` projection in host memory. Clear it on Stop/lock/close and never write it to Legacy SQLite, logs, crash diagnostics, a language document, O1/O2 or disk. D2b-2a does not contact a user gateway or test production OIDC provisioning. **Encrypted save and UI gate (D2b-2b).** Separately accept a versioned, allowlisted observation record and retention policy before enabling Save. Save only into the selected, actually unlocked Managed SQLCipher workspace through its current generation-bound native owner; never infer protection from an optional cipher build or a browser fixture. Define exact observation ID, selected installation/workspace/sandbox, source kind, declared versus verified identities, product/protocol pin, policy revision/load state, source and receipt times, cursor-space/continuity/loss, collection window, redaction version and authenticity `unqualified`. Reject raw policy, log text, token, socket, certificate material, arbitrary provider fields and bearer reference. Bound count, bytes and age, support deletion/export semantics and purge the renderer on lock. Save must revalidate the current generation, consent scope, schema and store transaction; a late callback or failed write cannot be reported as saved. UI shows source-qualified session status and gaps in a compact inspector with explicit Start/Stop, never an action approval, per-action decision or continuous-history badge. A later independently reviewed trusted-ingress/O1 mapping profile is required before saved observations become O1/O2 operator history. No second authoritative history is created here. @@ -130,6 +132,201 @@ Pin fixture cases for same-name installations with colliding native IDs, one-ins The synthetic callback has an unwind completion guard: a callback panic becomes a fixed source failure after its arguments unwind, or remains cancelled when Stop/close has already won. Workspace admission remains counted until completion. The guard does not catch the panic, suppress Rust's panic hook, survive process abort or qualify production credential diagnostics. The older canned-expiry fixture proves fixed-error propagation only; it must not be substituted for the real-client expiry tests. Neither client nor composed synthetic tests prove native OIDC custody, actual Tauri event delivery/restart, a released gateway or three-OS qualification. Tauri 2.12.1's separately audited restart exception remains a pre-activation gap; production Start stays unavailable. +### D2b-2b mounting sequence — proposed, October 20, 2026 + +This refines the existing proposed gate; it is not source acceptance or a connection feature. The accepted host/transport and current Managed factory remain the implementation base. Workspace-key custody is not provider-secret custody: `workspace_keys::Store` handles a workspace-bound database-key envelope, and the current cloud credential entry accepts raw webview input that this connector explicitly forbids. Reuse their lifecycle/zeroizing patterns, not their identity namespace or secret-entry route. + +#### End-user workflow and truthful states + +Keep the existing connector catalog, central task and right inspector. Configure one target/read, choose a native credential source, review it in a trusted native surface, perform one finite read, inspect the minimized session result, and explicitly save only after the separate observation-store gate. Configuration drafts and renderer clicks cannot grant native consent. Local authoring remains usable without engines. + +| State | User-facing meaning and action | +| --- | --- | +| Unavailable or incomplete setup | Local work continues. Show the missing capability and requirements; no enabled Start or health-derived connected badge. | +| Review ready | Show target, scope, selected read and session-only handling. Open native review; no secret or provider access has happened. | +| Native credential acquisition | Native-only input or an exact host-owned secret reference; no webview secret field. Cancellation keeps callback custody until actual return. | +| Finite read running | Show the selected read and a persistent Stop action. No fabricated progress or continuous-history claim. | +| Authentication/permission/source failure | Report the fixed native error class, such as “Gateway reported permission denial.” Do not infer verified identity, broaden scope or retry with another credential. | +| Stopped locally | Discard session result. The read may already have completed; this is not provider denial, undo or proof of no effect. Previously saved records remain separate. | +| Unsaved result | Minimized, unqualified session observation. Save stays unavailable with a reason until the observation schema and Managed lifecycle qualify. | +| Locked | Purge the session view and finish trusted drain. Reopening never starts a read or reuses old consent automatically. | + +Simple mode shows target label, read kind, state, primary action and concise help. Advanced details show reviewed nonsecret configuration, fixed protocol/version and explicit gap/loss information. Target origin/socket/pins belong to target review; they are not fields in the future saved observation. Do not expose provider-derived free text, original IDs, opaque credential handles, OS-slot names or raw payloads through an advanced inspector without a separately reviewed display allowlist. The native review can bind a credential handle without printing it as user copy. Preserve keyboard/table inspection, 44px controls, focus recovery, reduced motion and fixed non-secret errors. No marketing mascot, new graphics or shell redesign is needed for this workflow. + +#### Native credential choices and platform evidence + +Recommend a one-shot ephemeral native input path for initial setup, with exact host-owned OS-secret references as a later optional convenience. This is a design recommendation, not an implemented API or permission to enter normal credentials. The renderer receives only an opaque inspection reference and closed status; the native owner keeps the secret. No ambient environment/CLI/session scan, general keychain enumeration, refresh or admin fallback is permitted. Workspace-key slots and provider-secret slots must remain separate. If OS-secret references are later selected, their provisioning, exact namespace/binding, update/deletion and explicit acquisition consent need their own source and OS qualification; a missing reference does not trigger another source. + +Primary API research identifies candidates, not a qualified cross-platform implementation: + +- Apple documents a [masked native text field](https://developer.apple.com/documentation/appkit/nssecuretextfield) and [alert accessory view](https://developer.apple.com/documentation/appkit/nsalert/accessoryview). A parented AppKit integration still needs main-thread, cancellation, cleanup, accessibility and actual native tests. +- Microsoft's [credential-prompt API](https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-creduipromptforwindowscredentialsw) does not allow combining generic credential return with secure-desktop prompting. Its returned buffer requires explicit clearing/freeing. Do not promise a secure-desktop bearer-token prompt or copy incompatible flags; exact generic-token UX and supported bindings remain unselected. +- GTK documents [masked entry and password-purpose guidance](https://docs.gtk.org/gtk3/method.Entry.set_visibility.html). Masking alone proves neither memory erasure nor OS isolation; the actual supported desktop/backend and prompt lifecycle remain unqualified. + +None of these docs establishes secret-free IPC, identical OS semantics, workstation-compromise resistance or Rangoon support. Verify exact bindings/dependencies before any platform implementation. No documentation example or OS prompt was executed in this research. + +#### Windows/Linux input design — research, October 21, 2026 + +This is a platform design continuation, not source acceptance, dependency acquisition or OS qualification. The [platform research receipt](development.md#openshell-platform-input-design--october-21-2026) owns evidence and status. C2a remained unchanged and pending when this platform design closed; Jeff subsequently accepted its separate six-path source/tests scope below. Current Windows/Linux `confirm` and `acquire` still return `native_input_unavailable`; local work remains usable. + +The desktop lock pins Tauri/runtime-wry 2.12.1, `gtk` 0.18.2 and `windows` 0.62.2. Exact cached Tauri source exposes `Window::gtk_window()` as main-thread-only and depends on GTK 3 with `v3_24`, not GTK 4. On Windows its application builder installs a private message hook for menu accelerators. These are bounded source observations, not proof that no extension could ever be added. The exact Windows/GTK binding sources are absent from this host's cache; lock entries alone do not establish available bindings, target compilation or runtime behavior. No package was fetched. A later platform source packet must name exact files, binding features and dependency/target access before implementation. + +| Platform | Candidate and required proof | Current status | +| --- | --- | --- | +| Linux | Reuse Tauri's exact GTK 3 family. An asynchronous parented native dialog and masked entry stay on the GTK main thread. Prove response, destroy, parent loss, cancellation and actual teardown independently. | Design candidate; no backend or native qualification. | +| Windows | Application-owned native dialog with a standard single-line masked edit control. Evaluate a dedicated native GUI thread with its own dialog-message loop before selecting it; prove parent lifetime, cancellation, keyboard routing and thread-owned teardown. | Threading architecture unresolved; no backend or native qualification. | + +**Linux lifetime rule.** GTK documents that [destroying a dialog does not emit its response signal](https://docs.gtk.org/gtk3/class.Dialog.html). Register response, destruction and parent-loss handling before presentation; a response-only waiter can retain admission indefinitely after parent destruction. Use asynchronous signals rather than [`Dialog.run()`'s recursive loop](https://docs.gtk.org/gtk3/method.Dialog.run.html). Both successful response and cancellation must clear the field while valid, request native teardown, and wait for actual destruction plus completion of callbacks retaining request state before returning to the existing Host flight. Queue acceptance, a hidden window or a timeout is not drain proof. Duplicate and late signals must resolve once. Native GTK widgets never cross threads through an unsafe `Send`/`Sync` wrapper. [Masking](https://docs.gtk.org/gtk3/method.Entry.set_visibility.html) does not establish memory erasure; toolkit copies remain outside the owned Rust allocation guarantee. Qualify each supported OS/toolkit/display configuration explicitly; one X11 or Wayland run cannot establish all Linux desktop support. + +The existing facade remains blocking and worker-only: the worker posts a bounded request to GTK's main thread and waits for typed completion on the worker thread, never on the main thread and never while retaining a Host lock. GTK references and callbacks stay exclusively on the main thread. Cancellation dispatches native cleanup through that main thread without taking or holding the Host lock across dispatch/wait. An exactly-once completion transfers only the typed result after actual destruction and callback cleanup; it does not transfer widgets or introduce another session authority. Reject main-thread use and test cancellation while dispatch is queued and while the field is open. If the main loop cannot service cleanup, retain custody rather than report completion. + +**Windows decision gate.** A generic credential-provider prompt is not a direct single-bearer field, and the existing [CredUI flag incompatibility](https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-creduipromptforwindowscredentialsw) remains. Prefer a standard native `EDIT` with [`ES_PASSWORD`](https://learn.microsoft.com/en-us/windows/win32/controls/edit-control-styles), no multiline or case transformation. Microsoft's [modeless-dialog contract](https://learn.microsoft.com/en-us/windows/win32/dlgbox/about-dialog-boxes) requires explicit dialog keyboard routing; ownership alone also does not disable the parent. A same-thread modeless design cannot assume Tauri's existing private hook calls `IsDialogMessage`. Do not replace that hook, install a global keyboard hook, inject an unsupported task-dialog edit control or fork the runtime to bypass review. + +A dedicated GUI thread is a candidate inference, not an accepted solution: obtain the trusted parent through the Tauri `Window`, create/read/clear/destroy native controls on their owning GUI thread, and run that thread's own message loop. Do not accept arbitrary HWND values or make handle wrappers transferable with unsafe traits. Microsoft requires [window destruction on the creating thread](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-destroywindow). Before selecting this candidate, prove cross-thread parent ownership and handle-reuse behavior, dispatcher reentrancy during close, UI initialization, DPI/focus/accessibility, callback unwind containment and actual thread completion. Existing Host generation/deadline checks remain authoritative; a typed cancellation request cannot release admission before the owning thread finishes native cleanup. UI starvation must retain Stopping rather than trigger forced thread termination or false completion. If these obligations cannot be met within a small reviewed boundary, retain Unavailable and revise the candidate. + +**Exact input and privacy.** Preserve the existing nonempty printable-ASCII, 16,384-byte contract without trimming or normalization. [Windows text limits](https://learn.microsoft.com/en-us/windows/win32/controls/em-setlimittext) exclude programmatic `WM_SETTEXT`; [GTK buffer limits](https://docs.gtk.org/gtk3/method.EntryBuffer.set_max_length.html) can truncate existing contents. Proposed handling sets a 16,385-character/code-unit sentinel cap before input, rejects any value above 16,384 bytes or outside printable ASCII, and uses an independent bounded readback. Reject an overflow or clipped sentinel; never submit an accepted-length prefix of a larger input. Windows additionally needs fixed-size wide-buffer readback, invalid UTF-16 refusal and zeroization of owned intermediate buffers. A length-limit notification must not be mistaken for valid input. No input, prefix, hash, original length or toolkit exception enters logs, telemetry, renderer state or test receipts. Native-owned copies still have the explicit toolkit-erasure limitation. No remember option, clipboard scan, prefill, ambient credential lookup, secure-desktop/UAC claim or fallback credential source is added. + +Windows readback must allocate at least 16,386 `u16` slots, including the terminating NUL, so the 16,385-unit sentinel cannot itself be clipped to an accepted 16,384-unit prefix. Pass the actual buffer capacity to the wide-text API. Reject a return count at or above 16,385, a full or unterminated result, inconsistent count/termination, invalid UTF-16 or any non-ASCII value; an empty/failed read also refuses input. Read only on the control's owning thread, without allocating from a reported unbounded length. Boundary tests must exercise the exact native buffer/readback path, not only `SecretInput` validation. These invariants also apply when programmatic text bypasses the widget's input cap. + +**Platform acceptance cases.** Keep the existing six native cases: selected read, review cancellation, queued Stop, open-input Stop, expiry and owned-parent close. Extend each platform's eventual packet with parent destruction without response, delayed cleanup retaining admission, duplicate/late callbacks, empty/non-ASCII/control input, valid 16,384-byte input, refused 16,385-byte input, oversized paste and programmatic text beyond the widget cap. Windows must also cover invalid UTF-16. Verify Tab/Shift-Tab, Escape/Enter, focus return, DPI/scaling, supported accessibility settings and actual display backend. Native event/artifact evidence must distinguish queued, presented, accepted, cleared, destroyed and drained; no forced kill or controller click alone proves completion. Use disposable test credentials and synthetic peers only after explicit native-test acceptance. Compilation and mock tests cannot replace actual OS evidence. Production connection, real credentials/providers, OS vault and all three-OS shipping claims remain separate gates. + +#### First source packet: D2b-2b-C0 credential-selection binding + +**Status: accepted for source and synthetic tests.** Jeff explicitly answered “Accept C0 source/tests” on October 20, 2026. Acceptance covers the seven paths below and memory-only credentials/synthetic TLS peers; it does not accept production Start, native prompts, OS vault access, real providers/credentials, database changes, LNSAT/VUSL edits or publication. C0 adds the missing native-owned credential-selection binding and acquisition custody to the existing Host, using memory-only acquisition doubles and the existing synthetic TLS peer. It is not a new secret store, session manager, credential broker or second authorization engine. It must reuse Host pending/active state, Gate generations, callback custody, cancellation and the client’s existing `BearerLease` deadline checks. `begin_production` remains unavailable. Real native input, OS-secret reads/writes, renderer mounting and provider contact are not part of C0. + +Exact accepted C0 source ownership: + +| Owner | Paths and responsibility | +| --- | --- | +| Root | `apps/desktop/src/openshell_host.rs`: private child-module wiring and exact selection/reference binding in the existing preparation, one-shot confirmation and callback path; preserve existing synthetic contract and shared Stop/close/exit cleanup. | +| Root | New `apps/desktop/src/openshell_credential.rs`: native-only selection/claim types, bounded non-cloneable owning custody and fixed errors; no filesystem, OS vault, process, network or independent registry service. | +| Bounded test worker, integrated by Root | New `apps/desktop/src/openshell_credential_tests.rs` and `apps/desktop/src/openshell_host_tests.rs`: deterministic memory acquisition, exact-context/refusal/callback tests and the existing real-client synthetic peer. Root retains lifetime/security judgment. | +| Root | This specification, `docs/development.md`, `docs/continue.md`: scope, results and handoff only. | + +No `main.rs`, command/capability, renderer, client crate, Gate, database/schema, manifest, lockfile or dependency change belongs to C0. Stop and revise ownership before another production file is needed. Keep the current host/test path intact; do not create a parallel “native session” to avoid updating existing custody. + +The minimal implementation seam is the existing Confirmed-to-Active transition: keep the non-cloneable selection in Pending, move it on confirmation, and acquire only inside the same admitted callback that invokes the finite client. Refactor the current synthetic start continuation rather than adding another runner. Check cancellation, generation and the absolute selection deadline before acquisition and again after acquisition before constructing a lease or client. Cancellation can race an acquisition already beginning; it cannot promise that no acquisition occurred, but it must suppress a late secret and keep admission until actual return. + +Private acquisition failure or missing backend maps to the existing fixed `ClientError::Source`; local Stop remains `Cancelled`, and deadline expiry becomes `CredentialLeaseExpired` unless explicit cancellation has already won. Expiry must not call a generic cancellation method that rewrites its terminal error as user cancellation. None of these statuses is a provider authorization decision. No client-crate error extension belongs to C0. + +Accepted C0 contract: + +1. One selected credential context belongs to the existing one-pending/one-active Host state. Bind an opaque random reference to the exact Host instance, workspace generation, review, origin/socket, root/leaf pins, installation/workspace/sandbox, product/protocol, `ReadKind`, data classes and session-only retention. An inspection copy is not an owning handle, nor can a supplied string deserialize into trusted custody. +2. Selection/reference allocation performs no secret read. A matching native-confirmed claim is consumed once before invoking acquisition. Wrong/foreign/stale/cross-kind context causes zero acquisition and zero client calls; it cannot consume an unrelated valid pending review. A failed acquisition or protected read does not revive the claimed reference. +3. Use one absolute monotonic deadline, at most 120 seconds after selection allocation, for both the reference and resulting lease. Confirmation and acquisition never renew it; an explicit trusted-native expiry may only shorten it. This is a local custody limit, not verification of token claims or provider identity. Reuse the client's 16 KiB secret bound and immutable deadline enforcement; never parse a token to infer authority or refresh it. The accepted source implementation must test both pre-acquisition and post-callback expiry. +4. Retain actual acquisition/callback admission, including dropped IPC waiters, until real return. Stop/lock/close/exit/expiry cancels acceptance; a late secret is dropped without creating a client or retaining a result. A callback that cannot drain keeps closing/recovery state. Timeout never releases custody optimistically, and no second close/generation owner is introduced. +5. Pass a successful dummy secret only through the trusted native/client lease path, never a renderer, debug/error output, disk or observation DTO. Retain fixed error classes; no global OS-slot selection, secret lookup, environment access, generic URL/method or LNSAT operation is introduced. + +C0 acceptance cases: no acquisition before native confirmation; exact healthy claim; denied/cancelled/expired selection; each bound-field change; foreign Host/generation/reference; matching claim replay after success/failure; no extra RPC; acquisition held across Stop/actual close/source exit coordinator; late success after cancellation/expiry; dropped waiter; panic/failed drain; missing acquisition backend; redaction/privacy compile-fail checks; unchanged provider-free source/export behavior. Use the same existing host and finite client paths. The acquisition double must pass its returned lease into the existing real-client callback path; a disconnected mock-only credential pipeline does not satisfy C0. Named validation: nonzero focused credential/host tests, default/no-default desktop suites, formatting, warnings-denied Clippy, normal builds without synthetic-peer support, feature-graph/lockfile and outside-owned preservation, documentation/reference/whitespace checks, and fresh independent source/evidence review. No real OS-vault test or native prompt is authorized by accepting C0. Source refinement: selection metadata is retained in Pending in normal builds, while acquisition traits, secret sealing and callback dispatch remain test-only with no production backend. The private callback reuses the existing Host and client path; active state checks the bound deadline again on final result acceptance. A valid result accepted before expiry remains a session observation, not continuing permission. Privacy checks must establish that owning selection/claim/acquired types do not implement Clone, Debug or Serialize, rather than relying on a private-type import failure. + +C0 uses dummy values only and leaves the client's `String`-taking API intact. A separate bounded [constructor-cleanup correction](development.md#openshell-bearer-constructor-rejection-cleanup--october-20-2026) now wraps the consumed String in `Zeroizing` before any validation and explicitly clears rejected empty, oversized or expired input before returning the same fixed error. The owning guard also remains responsible for Drop cleanup. Safe tests inspect the still-live rejected buffer and preserve the valid 16 KiB boundary, immutable deadline and redacted Debug. This is source-level owned-buffer cleanup, not proof that prior caller/transport copies, allocator pages, swap or crash dumps are erased. The linked receipt owns validation and independent-review status. Exact native acquisition and platform qualification remain prerequisites before real-secret mounting; this correction supplies no secret source, production Start, provider connection or execution authority. The [accepted C0 receipt](development.md#openshell-c0-credential-selection-and-acquisition-custody--october-20-2026) retains its original implementation and validation scope. + +#### C1-M native review/input and actual macOS qualification — proposed source packet + +Status: accepted source/tests. Jeff explicitly answered “Accept C1-M source/tests.” This accepts the 23 paths and six disposable macOS cases below using dummy credentials and local TLS only. The development receipt owns implementation and qualification progress. C0 and the separate client rejection-cleanup correction are completed source prerequisites, not production mounting or provider permission. This packet implements a real native review/input path and exercise it with dummy values and disposable local TLS peers. macOS is the first qualification host available here; Windows and Linux remain required before the initial three-OS profile can ship. Do not present a macOS pass as that profile, a connected production feature, a credential vault or the complete operator-record goal. + +**Source-backed choice.** The existing Apple/Windows/Linux keyring dependencies provide storage, not the required native entry surface. Both desktop entry crates forbid unsafe code. Preserve those bans. Introduce a small desktop-only `rangoon-native-credential-input` crate with a safe typed facade taking a trusted Tauri window, fixed bounded nonsecret display data and native cancellation/completion wiring. No caller-supplied native memory address, raw parent pointer or renderer-selected parent is accepted. A configured nonsecret target origin remains part of the existing trusted selection/review data. Deny unsafe code in the facade/common code; confine necessary AppKit parent retention/FFI to individually justified functions in its macOS implementation, with explicit main-thread, ownership and callback-lifetime proof and independent review. Do not weaken the app-wide ban or add unsafe Send/Sync wrappers for UI objects. Jeff’s explicit C1-M acceptance authorizes this new bounded source/test boundary; it is not an inferred C0 exception or production permission. + +The inspected desktop lock already pins Tauri 2.12.1, objc2 0.6.4, objc2-app-kit/objc2-foundation 0.3.2, block2 0.6.2 and zeroize 1.9.0. Proposal: reuse those exact package identities with the minimal explicit feature closure for NSAlert, NSSecureTextField, NSControl/NSTextField/NSView, NSApplication/NSWindow, main-thread markers, string handling and sheet completion. No extra package/version, installer or dependency fetch is accepted by this proposal. The native-input path may not launch a subprocess or shell/OS scripting helper. The exact qualification child executable is the sole allowed runtime child per case; the named locked/offline Cargo build may run its ordinary compiler/build subprocesses. A missing cached dependency or required extra source path must stop implementation for scope reconciliation. The desktop lock may change only for the new local package and necessary dependency edges; package identities/checksums must remain exact. The new crate declares Rust 1.99.1 and the existing pin validator must check it, including missing/mismatched-manifest regressions. + +| Platform | Current evidence | Required follow-through | +| --- | --- | --- | +| macOS | Tauri's `ns_window` returns an autoreleased native parent pointer; `run_on_main_thread` dispatch exists. Cached AppKit bindings expose a masked field and asynchronous parented sheet completion. This is source evidence, not a safe lifetime or runtime proof. | Retain the parent on the main thread, keep UI objects there, use asynchronous sheets and actual completion/clear acknowledgement, and run the disposable matrix below. | +| Windows | Locked windows crate is 0.62.2; existing keyring crate is not prompt UI. Microsoft's [credential API](https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-creduipromptforwindowscredentialsw) forbids generic return combined with secure-desktop prompting and requires clearing/freeing its output buffer. | Select exact bearer-token UX, length/encoding and cancellation APIs before a separate backend packet. No secure-desktop claim, assumed AppKit equivalence or raw-credential fallback. C1-M returns fixed Unavailable on this platform. | +| Linux | Desktop lock names GTK 0.18.2, but its source is absent from the inspected cache. GTK [entry documentation](https://docs.gtk.org/gtk3/class.Entry.html) supports masking; [Dialog.run](https://docs.gtk.org/gtk3/method.Dialog.run.html) uses a recursive loop, not asynchronous custody proof. | Select pinned GTK/backend and supported desktop, asynchronous response, parent and secret-buffer semantics; obtain dependencies only through a separately accepted gate. C1-M returns fixed Unavailable. | + +These are deliberately visible backend differences; the all-three-OS requirement is unchanged. Apple [masked-field](https://developer.apple.com/documentation/appkit/nssecuretextfield) and [sheet](https://developer.apple.com/documentation/appkit/nsalert/beginsheetmodal(for:completionhandler:)) documentation supplies candidates; actual lifetime safety must follow the pinned Rust/Tauri implementation and executable tests. Masking does not establish process-memory erasure, secure desktop, workstation-compromise resistance or provider authorization. + +**One callback and exact consent.** Reuse the existing Host, selection, generation, one-active admission, completion guard and finite client. Native review itself is a callback: the current metadata-only Pending may not be discarded by Stop while a real sheet is still queued/open. Hold the same actual admission across review, input and read; release only after the real native UI completion/clear acknowledgement and callback return. Refactor phase accounting within the existing Host rather than introducing a second session/drain manager. Native confirmation must match the retained exact review before the one-shot claim is consumed or a secret field acquires input. A renderer boolean is not confirmation. Validate generation/Stop/absolute deadline before presenting, before enabling/acquiring input, after native return, before client construction and final result acceptance. Keep the 120-second selection limit immutable from deliberate review allocation. Native completion can arrive late or twice; consume once, clear late values and keep authoritative terminal state. Never hold Host/Active/Gate mutexes while waiting for UI or network. + +Use one guided native flow, possibly two parented native steps, with fixed review labels, exact nonsecret target/read/scope/pins and session-only handling. Secret input starts only after native confirmation. No prefilled secret, “remember” box, vault lookup, clipboard scan, refresh or token parsing for authority. Explicit user Paste may use the OS control; do not inspect or overwrite the user's clipboard. Accept only a bounded nonempty single-line value compatible with the client header, without silent trim/truncation; reject oversize/invalid input before any connection. The 16 KiB UTF-8 application bound does not claim native toolkit internals never allocate another copy. Move the owned Rust value through the corrected existing lease, with fixed nonsecret errors and redacted/non-Clone/non-Serialize ownership. Clear/dismiss native controls and release retained UI references on the main thread; document remaining toolkit/transport copies instead of claiming total erasure. + +Cancel or parent loss requests cancellation of the same Host flight. Stop/expiry must request native dismissal, reject late input/results and retain actual admission until completion; blocked/starved native delivery leaves Closing, not an optimistic drain. A completed observation accepted before expiry remains a session observation, never permission for a new read. `begin_production` stays unavailable, ordinary command registration/capabilities and renderer remain unchanged, and no real provider is contacted. Only the explicit qualification target composes this shared native path with generated dummy credentials and the actual synthetic client. It must not contain an alternative confirmation/ownership implementation that bypasses the code intended for later mounting. + +Exact accepted source/test ownership (23 paths; source acceptance does not imply validation or qualification): + +| Owner | Exact paths | +| --- | --- | +| Root: isolated native input and safety | New `apps/desktop/native-input/Cargo.toml`, `apps/desktop/native-input/src/lib.rs`, `apps/desktop/native-input/src/macos.rs`, `apps/desktop/native-input/src/tests.rs`. The non-macOS facade returns fixed Unavailable; it does not fabricate another backend. | +| Root: package/host integration and custody | `apps/desktop/Cargo.toml`, `apps/desktop/Cargo.lock`, `apps/desktop/src/main.rs`, `apps/desktop/src/openshell_host.rs`, `apps/desktop/src/openshell_credential.rs`, new `apps/desktop/src/openshell_native_input.rs`. Keep normal Start unavailable and preserve all other command/capability and provider/client/store semantics. | +| Bounded native GPT worker; Root integrates | `apps/desktop/src/openshell_host_tests.rs`, `apps/desktop/src/openshell_credential_tests.rs`; exact-context, consent, queued/open UI custody, cancellation/expiry, replay and unchanged real-client ledgers. Worker is not alone in the tree and must not revert others. | +| Root: explicit qualification target | New `apps/desktop/src/native_credential_qualification.rs`, `apps/desktop/native-credential-qualification/tauri.conf.json`, `apps/desktop/native-credential-qualification/cases.v1.json`, `scripts/qualify-native-credential.py`, `tests/qualify_native_credential_test.py`. | +| Disjoint bounded validator worker; Root integrates | `scripts/check-source-rust.mjs`, `tests/check-source-rust.test.mjs`; enforce the third 1.99.1 manifest without weakening compiler/subprocess identity or offline/install policy. | +| Root: canonical records | This specification, `docs/product-experience.md`, `docs/development.md`, `docs/continue.md`. | + +**Qualification target and six native cases.** Use a separately named Cargo feature and custom test target `native-credential-qualification`, distinct `ai.rangoon.native-credential-qualification` context, no automatic webviews, empty assets, no global Tauri/ordinary setup/plugins, bundling off, and one explicit inline nonlocal capability with no windows/webviews/permissions or remote origins. Validate the generated context before Builder creation as NX-06 does; an empty capability array is insufficient. Create only one plain native parent window owned by that test process. Use an in-memory Gate/Managed witness, generated peer trust material and the real Host/native adapter/client path; do not resolve a normal workspace or initialize a vault/database. Source-free bounded event records report phase/order and fixed outcomes, never token, token digest/length, private trust bytes, arbitrary provider text or normal paths. + +| Case | Required independent result | +| --- | --- | +| `accept-read` | Actual native review and masked dummy input complete; exact protected-check/read RPC ledger; matching unqualified result is accepted once. A screenshot or programmed boolean alone does not prove native confirmation. | +| `cancel-review` | Actual native Cancel; no secret acquisition, socket or RPC; draft/parent focus continuity and admission completes only after native return. | +| `stop-queued` | Hold actual dispatch before presentation; request Host Stop; no sheet/input/read appears; retained callback drains only after queued work really returns. | +| `stop-open` | Actual visible native input held across Stop; persistent Closing while callback is held; native clear/completion, rejected late input and zero read after cancellation. | +| `expire-open` | Begin while valid, hold actual native input across the immutable deadline, dismiss/clear and return fixed expiry; zero client construction/read. No test-created Cancel may replace the expiry oracle. | +| `parent-close` | Close only the owned native parent while review/input is active; cancellation/dismissal and callback admission order remain correct, no orphan prompt or late accepted result. This is input/parent evidence, not the whole production Quit/Lock coordinator. | + +Parent runner builds/selects only the exact emitted custom executable with locked offline dependencies, pins source/config/case-plan/executable hashes and one disposable nonce, drives one case per fresh child, bounds output/time and kills/joins only that child on failure. Native input uses fixed dummy markers; UI automation must claim the exact test process/window, with exclusive test-window use and explicit detection/discard of manual interference. The normal Rangoon/test-vault windows and closed E1c nonce are not reused. Record actual UI evidence and parent-observed outcomes; do not count a mock callback, synthetic UI screenshot or forced termination as a native pass. Offline Python runner tests cover wrong target/hash/case/nonce, truncated/oversized/out-of-order evidence, child timeout and cleanup failure. + +**Controller-attribution correction.** Jeff reported no interaction during the discarded v9 run. The triggering AppKit response remains unattributed; neither the native source nor the runner demonstrates an automatic confirmation path. Before another native attempt, require a fresh parent challenge before launching each case, the full `c1-{case}-{nonce}` context in the owned parent title, review installation and ready record, and a bounded payload-free action journal. Persist controller intent before the UI operation; record its return separately. Native callbacks remain the only confirmation/input/result source. A controller assertion is correlation evidence, not human consent, exclusive desktop ownership or engine authorization. The runner must refuse unexpected phase/result progression, mismatched context, duplicate/stale controls and failed/interfered actions. One serialized owner orders journal writes and native/control observations. After actual clean child exit and existing source/artifact/oracle checks, require a fresh terminal challenge bound to case, nonce, PID and artifact before proceeding. Allow an already-declared UI operation to return after child exit; do not permit a new action after the native result. Programmatic owned-parent close must be labeled as such. Historical v1 receipts remain immutable; the revised private qualification envelope is v2, not a public interoperability contract. The runner always leaves qualificationComplete false. Any later independent UI/evidence acceptance is recorded in a separate bounded assessment; v13 has that assessment linked below. This is a correction within the accepted C1-M paths, not production mounting or permission for a live provider. + +Current bounded evidence: the [guarded v13 matrix](development.md#guarded-native-matrix-accepted--october-21-2026) passes all six macOS synthetic native cases with fresh independent UI/evidence review. This closes that test slice only; real providers, other OS backends and the mounted workflow remain separate stages. The earlier unexplained v9 event remains unattributed and discarded. + +The private controller sequence is deliberately explicit: + +1. Wait for `.start.json`. Compare its complete nonsecret context and artifact identity. Reply on the runner's stdin with only `case`, `nonce`, `kind: "start"` and the exact `challenge`. No child launches before this response. Each case has its own 60-second start gate outside the credential deadline. +2. Wait for the child's launch/ready records. Match the actual test process, full parent/review context and artifact before selecting its native window. Before each UI operation, send an `intent` record containing exact `case`, `nonce`, a new 32-character lowercase-hex `id`, fixed `action`, child `pid`, `artifactSha256` and full `context`. Actions are `review-continue`, `review-cancel`, `input-fill` and `input-submit`; only the selected case's ordered actions are accepted. Wait for the matching flushed `action-intent` journal row before calling the UI tool. Terminal echo is not that acknowledgment. +3. After the UI tool returns, send `kind: "return"`, the same `case`, `nonce` and action `id`, and fixed `outcome: "dispatched"`, `"failed"` or `"interference"`. Never include field contents, UI dumps or tool error text. Dispatched is a controller assertion; native events establish the result. An operation declared before native completion has sixty seconds after child exit to return. This bounds controller transport only: the native credential deadline remains 120 seconds, the child is already gone, and new actions remain refused. Record a terminal click return before attempting post-exit UI observation; an app-quit observation is not a successful UI return. Test controls retain their exact `case`, `nonce`, `command` envelope; the parent journals their intent before forwarding them. Stale generations fail the monitored path rather than silently moving to another case. +4. After a clean child exit and verified raw/source/artifact checks, wait for `.terminal.json` and reply with its exact `handoff` record. Its fresh `terminalId`, case, nonce, PID and artifact must all match within 60 seconds. No handoff is accepted before that terminal request. The next case still requires its own start gate. A missing or refused response stops the matrix; it is not a diagnostic pass. + +Journal writes use one serialized owner and fixed allowlists. Failed attribution terminates only the owned disposable child and remains a failed run; forced termination never qualifies cleanup. These records improve controller correlation without attesting the operating system, identifying an outside actor or replacing independent native UI review. + +Named source acceptance checks: nonzero native-input/C0/host regressions and negative owning-trait/output tests; pinned locked/offline helper, portable workspace and default/no-default desktop tests, format, all-target warnings-denied Clippy and normal builds; new manifest pin regressions; normal feature graph excludes qualification/synthetic support; exact six actual macOS cases with fresh native UI/evidence review; documentation/reference/whitespace and outside-owned/lock identity checks. A Source PASS with missing native cases is not native qualification. Required API/lifetime/feature/dependency surprises stop for reconciliation before scope expansion. Producer cannot approve its own FFI, UI or evidence; Root retains final judgment and later live-connection/release gates. + +This packet excludes actual user secrets, OS vault operations, real provider/target contact, write/execute RPCs, renderer/UI mounting, persistent observations, session reuse/reconnect, LNSAT/VUSL edits, installation/fetch, commit/push/merge/deploy/release. Follow-on Windows/Linux backends and three-OS qualification, truthful mounted one-read UX, durable observations, trusted ingress and complete per-action records remain required. The [connection usability direction](product-experience.md#connected-system-usability--october-20-2026) keeps those stages tied to a useful user workflow; C1-M alone does not complete that workflow. + +#### C2a session inspection source — proposed next packet + +**Status: accepted for source and synthetic tests on October 21, 2026.** Jeff explicitly answered “Accept C2a source/tests (Recommended).” The [C2a development receipt](development.md#openshell-c2a-bounded-session-inspection--october-21-2026) owns source implementation, validation and exact review evidence. This is the source deliverable toward the finite-read screen: one bounded native inspection of the existing Host's session state and completed minimized observation. It supplies the currently missing safe readback layer before commands or renderer mounting. It does not add another session owner, provider envelope or language profile. Windows/Linux native input and the later mounted task remain required parts of the complete workflow. + +**Exact ownership (six paths).** Root owns `apps/desktop/src/openshell_host.rs` for the generation-bound atomic snapshot and private child wiring, and new `apps/desktop/src/openshell_session_view.rs` for the app-private serialized view. A bounded test writer may own new `apps/desktop/src/openshell_session_view_tests.rs`; Root integrates it. Root owns this specification, `docs/development.md` and `docs/continue.md`. No `main.rs`, command registration, capability/build permission, native-input/credential implementation, transport, store/schema, dependency/lockfile, renderer, VUSL or LNSAT file is owned. A newly required production path stops implementation for scope reconciliation. + +**Readback contract.** Add one internal `Host::inspect_session(&WorkspaceRequest)` that admits the selected Managed workspace under the existing Gate, verifies the current generation and snapshots the same retained Host/Active state. Read status and observation coherently rather than composing two separately timed calls to `status()` and `completed_observation()`. Retain immutable `ReadKind` in `Active`, copied from the exact pending Review before callback publication; never recover an active kind from renderer state, a default or a different result. Revalidate the admitted generation/cancellation before returning. Use the existing lock order and bounded copying; do not hold a lock across I/O, await, toolkit dispatch or a user callback. Legacy requests, stale generations, a closing/closed workspace Gate or poisoned custody return a fixed unavailable view without an observation. Host `Closing` caused by session Stop while the workspace remains open is still a visible phase. Do not fabricate source details when unavailable. + +Snapshot ordering has one explicit winner. Acquire Host then Active state in the existing order, capture phase and summary together, and perform the final generation/cancellation checks while the captured state is still protected. Define the snapshot point at the last successful witness check for that captured state, with cancellation also checked before releasing its locks. Cancellation or generation invalidation observed by that point suppresses the observation and selects the appropriate fixed non-completed phase; retain Closing for an active callback that is still draining. If Stop/close wins afterward, the already captured view remains a historical instantaneous snapshot and the next inspection must reflect cancellation or unavailable custody. Never publish `Completed` with a removed/missing summary: if final validation invalidates a candidate, change its phase and remove the summary together. Do not promise atomicity with remote provider state or freshness at a later IPC delivery; that future command must separately revalidate workspace delivery and renderer purge. Deterministic barriers must exercise both sides of this ordering, including a callback completing while Stop waits and a generation fence immediately before final snapshot validation. + +The private output schema is `rangoon.openshell.session-view.v1`, with a maximum encoded size of 8,192 bytes enforced by Rust. Its field names use camelCase, while closed phase/read-kind/error values use snake_case. Every view explicitly states bounded/partial coverage and the omission of native identifiers, source timestamps, policy hashes, provider payloads and target/credential references. Watch producer absence is counted separately from the existing Unknown producer kind; closed loss reasons are deduplicated in a stable order. Encoding refuses overflow atomically rather than returning a truncated prefix. It is a future application display contract, not OpenShell wire support or VUSL. Serialize only explicitly constructed, typed fields; do not derive serialization for `Review`, `ReadOutcome`, `Observation`, `CredentialInspection`, `ProposedTarget` or their nested client records. No inbound view deserialization or renderer-supplied replacement result is added. + +| Output | Exact allowed content | +| --- | --- | +| Envelope | Fixed schema; provider `openshell`; pinned product `v0.1.4`; current closed Host phase or fixed error code; closed selected `ReadKind` only when bound to current retained state; `startAvailable: false`; session-only retention. | +| Provenance | Fixed authenticity `unqualified`, authority `none`, execution `unavailable`, action outcome `unknown`; explicit bounded/partial observation coverage. No runtime authorization or cross-engine relationship is inferred. | +| Protected check | Only the client's closed health and protected policy-load states. The successful protected check is evidence for that selected read, not universal access. | +| Policy status | Active numeric version, queried numeric version and closed load state, and bounded revision count. No policy hash/body, free text or source timestamp. | +| Log window | Bounded returned line count and provider-reported buffer total, explicitly distinguished. Neither count proves history completeness. | +| Watch window | Bounded event count, counts by the existing closed event/producer kinds, existing closed continuity value and deduplicated closed loss reasons. A bounded window is not a continuous subscription or complete audit history. | + +Unavailable views omit the selected read kind and observation; all other phases use only the existing four read-kind variants. Only a completed, current, noncancelled read may include its matching observation summary. Other variants contain no observation. A result accepted before credential expiry may remain a session observation afterward; it grants no fresh request, and Stop/lock/close still suppresses it. View error codes use the existing fixed enum; unknown/unmappable internal state refuses the view rather than using provider error text. The app-private summary must retain redaction/loss meaning, including omitted native identifiers and omitted time/hash detail. Do not invent data absent from the current client, including rule contents, per-action approval, denial, tool execution, costs or telemetry. + +Never include origin/socket, certificates/pins, review or credential references, workspace/installation/sandbox IDs, native event IDs/cursors, digests, paths, raw policy/log/platform text, headers, credentials, raw timestamps or arbitrary provider text. Those values remain in native custody and can be considered for a separately reviewed advanced target inspector later. No second registry or display-state history is created. + +**Acceptance tests.** Cover every pending/active phase and fixed failure; awaiting/confirmed expiry and stale-plus-expired precedence; retained active read-kind identity across Running/Closing/error/completion; exact healthy observation variants through existing synthetic real-client Host callbacks; foreign/Legacy/stale workspace refusal; Stop and actual existing close-coordinator purge before delivery; dropped inspection waiter; concurrent completion/cancellation without a contradictory completed/no-observation view; completed-then-expired historical result; exact field allowlists and canaries for every forbidden identity/text/hash field; malformed/oversized internal projections refusing rather than truncating; and normal production Start still unavailable with zero extra credential or network calls caused by inspection. Preserve all existing Host/credential/native lifecycle tests. Tests against memory doubles alone cannot replace the existing synthetic TLS client composition cases. + +**Named validators.** Pinned locked/offline focused `openshell_host::session_view::` tests with a nonzero count; existing `openshell_host::` regressions; complete desktop default/no-default tests; format and warnings-denied all-target Clippy in both modes; normal default/no-default builds and existing dependency-feature inspection; documentation/reference/whitespace, exact ownership and lockfile preservation; fresh independent read-only source/privacy/evidence review. No rendered or native OS qualification is claimed because the packet mounts no UI. + +This acceptance authorizes only that readback source and synthetic tests, not production Start/Connect, native prompt operation, real provider/credential access, OS vault, persistent observations, trusted O1/O2 ingress, renderer/IPC mounting, engine operation, foreign edits, dependency fetch, publication or release. The implementation must leave a direct path to the later mounted finite-read task; it is not completion of the full delivery table below. + +#### Remaining delivery stages and full support target + +| Stage | Required deliverable before its own acceptance/qualification | +| --- | --- | +| Native input and session mounting | Exact three-OS native input/bindings, parent/Cancel/expiry/drain behavior, finite read commands and a minimized display DTO; actual isolated OS tests with synthetic secrets/peers first. No renderer bearer or production Start by a test flag. Preserve the existing three-OS credential qualification gate before claiming that profile supported. | +| Durable observations | New typed unqualified record family, ID/schema/version, strict field allowlist, measured count/byte/age bounds, Managed Owner transactions, inventory, deletion, retention, and full capture/restore/strict-empty-target parity. Existing source/workflow tables are not a generic provider blob sink. | +| Recovery/export compatibility | Explicit future backup/version/loss rules for observations. Current schemas reject unknown tables; future records must not be silently omitted by older export/restore or invisible to empty-target checks. Managed plaintext archive export remains refused until its own qualified replacement. | +| Trusted operator ingress | Separately reviewed source-qualified mapping into O1/O2 with authenticity, gaps, temporal ordering, provenance and loss. Saving encrypted unqualified data alone never makes authenticated operator history. | +| Qualified engine scenarios | One pinned real OpenShell product and independently one pinned LNSAT product: denied, provider-policy allow versus human approval, changed, repeated and uncertain outcomes, with exact native support/unsupported states. No free-form log classification or cross-engine relation from matching IDs. A verified bridge needs its own mediator/path evidence. | + +C0 is a necessary source component, not completion of this table or of the cross-runtime operator goal. Useful local workbench release remains independent of broad provider coverage. Real credentials/providers, normal user data/keys, target operation, LNSAT/VUSL edits, publication and release remain closed. The [mounting-design receipt](development.md#openshell-native-mounting-design--october-20-2026) owns current evidence and review status. + ### D2b-2a validation bridge — accepted for synthetic source Accepted by Jeff on October 18, 2026: “Accept synthetic validation bridge.” [Intent](intent.md#d2b-2a-synthetic-validation-bridge-acceptance--october-18-2026) owns this acceptance. The following ownership and behavior are accepted only for synthetic test support. The bridge acceptance did not itself authorize the client credential-lifetime correction; that correction now has its own later acceptance below. @@ -156,6 +353,14 @@ Root owns only `apps/desktop/src/openshell_host_tests.rs` and this specification Run nonzero `openshell_host::tests::real_client_` tests in default and encrypted desktop configurations, full desktop regression, warnings-denied desktop Clippy, formatting, default native build/dependency-feature inspection, existing frontend build checks, documentation/diff checks and fresh independent read-only review. Existing full-workspace/client correction evidence remains separate because this continuation changes only desktop tests and status records. Do not claim local socket teardown proves remote credential revocation or provider cancellation. The [composed qualification receipt](development.md#openshell-composed-lease-and-callback-qualification--october-18-2026) records five new tests and 17 passing real-client host tests in each desktop configuration, retained callback/drain evidence and remaining gates. +### Successful transport result before callback return + +The accepted synthetic bridge also needs the ordering where a real client has completed a successful protected/selected read but the host callback has not returned. Use the existing returned-result signal and release barrier; do not substitute a canned success. Before release, no completed observation is visible and callback admission remains owned. A positive control must publish the same minimized result after release. If Stop, workspace close, exit-helper or the native exit source coordinator cancels first, callback completion must retain `Cancelled`, expose no observation, refuse old consent and permit drain only after return. These are source-composition cases with synthetic TLS peers, not a Tauri GUI event run, provider cancellation or external-action evidence. The [composition receipt](development.md#openshell-successful-read-cancellation-composition--october-20-2026) owns exact tests and evidence. + +### Pending-review publication and close ordering + +The accepted D2b-2a generation contract also covers preparation already admitted before close fences the workspace. Preparation must recheck its admission while holding the same host-state mutex that close uses to remove pending reviews, immediately before publication. If close and purge win first, preparation refuses and drops its own lease; if publication wins first, close sees and drops the pending lease. No stale pending review may appear after purge and retain otherwise invisible drain custody. Checking only before waiting for the mutex is insufficient. Keep this internal to the existing host: no second generation, timer, credential, provider operation or close coordinator is needed. The [bounded correction receipt](development.md#openshell-prepareclose-custody-correction--october-20-2026) owns exact source/test scope and validation; it does not mount Start or qualify a new native artifact. + ### Native exit and admission qualification — accepted source prerequisite Accepted by Jeff on October 18, 2026 through the explicit native exit/admission packet reply; [intent](intent.md#native-exitadmission-source-acceptance--october-18-2026) owns acceptance and exact source ownership. The findings below describe the pre-correction baseline. This acceptance does not open the separate actual native event harness. @@ -185,6 +390,37 @@ The source tests exercise this exact router and scheduler, actual synthetic TLS Named validation for this accepted source correction: focused host/lifecycle/event-coordinator tests, default and encrypted desktop suites, warnings-denied desktop Clippy, desktop build and formatting, document checks and fresh independent review. Use injected bounded scheduling/failure seams for deterministic source tests; retain actual native event evidence for `NX-06`. The native harness remains a separate unaccepted packet. The current [audit receipt](development.md#native-exit-and-admission-audit--october-18-2026) records source evidence and review, not a completed correction. +### NX-06 disposable native event qualification — proposed exact packet + +**Authority and status.** This is the next qualification packet after the accepted native exit/admission correction, published through PR #50 at reviewed head `c132ea6` (main merge `cb0e878`). Jeff accepted this exact packet on October 18, 2026. The six disposable macOS cases and two repeats now pass for an x86_64 executable on an arm64 macOS host; [the NX-06 receipt](development.md#nx-06-disposable-macos-native-lifecycle-qualification--october-18-2026) owns exact evidence, failed attempts and remaining gates. This acceptance opens bounded test-source implementation and disposable macOS runs together; no separate request is needed for each named case. Windows/Linux native event qualification remains later work. [Intent](intent.md#nx-06-disposable-native-event-qualification-proposal--october-18-2026) owns acceptance; the development ledger owns actual results. + +**Outcome.** Exercise the actual Tauri Ready/ExitRequested/Exit callbacks, native prevention and reissued exit, live failure anchor and main-thread cleanup with synthetic OpenShell work. Parent-observed process termination must agree with ordered evidence. The harness must not duplicate the production event switch, replace `app.exit` with a recording callback, or count a helper test as native evidence. No claim of encrypted Owner/key release follows from the memory-only fixture. + +**Accepted source ownership:** root owns `apps/desktop/Cargo.toml`, `apps/desktop/src/main.rs`, new `apps/desktop/src/native_exit_qualification.rs`, new `apps/desktop/native-exit-qualification/tauri.conf.json`, the test-only fault helper in `apps/desktop/src/cloud_models.rs`, and new `scripts/qualify-native-exit.py`. Supporting records are this specification and `docs/{intent,continue,development}.md`. No lockfile, dependency, CI workflow, provider client, store schema, renderer, credential implementation or LNSAT change is planned. If additional production files or dependencies become necessary, revise this exact packet before expanding edits. Root retains lifecycle/integration judgment; bounded read-only reviewers inspect isolation and actual evidence. Implementation refinement after acceptance: `apps/desktop/src/openshell_host.rs` additionally owns one `cfg(all(test, feature = "native-exit-qualification"))` child-module declaration. Nesting the harness under the host lets it reuse existing private synthetic consent/callback seams without widening their visibility or changing production behavior. All other ownership remains unchanged. The dependency feature does not expose the client crate's internal socket counter. No-start cases therefore use an inert nonblocking loopback socket sentinel, assert no accepted connection and invoke only the production-unavailable host path; no RPC server/client is started. Active cases use the real TLS peer and its public RPC ledger. This observes the sentinel only, not machine-wide network absence; source isolation review is also required. No client crate edit is made. Initial pre-Builder qualification rejected the alternate filename because pinned `tauri-codegen` 2.7.1 resolves configuration by parent directory and reads its canonical `tauri.conf.json`. The accepted isolation intent is implemented with a dedicated `native-exit-qualification/tauri.conf.json` directory instead; the generated context must still pass exact identifier/capability/asset predicates before Builder. This correction does not modify production config. + +**Entry and build isolation.** Use an explicit Cargo custom test target with `harness = false`, `test = false`, `required-features = ["native-exit-qualification", "encrypted-workspace"]`, sharing `src/main.rs`. Its alternative entry exists only under `cfg(all(test, feature = "native-exit-qualification"))`; ordinary builds retain the normal entry. The new feature has no dependency activation; existing dev-dependencies supply the synthetic peer. The custom target keeps Cocoa's event loop on the process main thread rather than libtest's worker. Before any Tauri builder, accept only one exact closed case argument; missing, unknown or extra arguments exit with a fixed nonzero diagnostic and create no app or listener. This also prevents an indiscriminate all-target/all-feature test invocation from launching the harness. Ordinary `cargo test` must not select this target. A clean verbose compile must show `--cfg test` for this exact custom target and not for the ordinary binary; `harness = false` removes the libtest harness but does not itself establish whether Cargo supplies that cfg. Preserve the actual compiler invocation and target identity as evidence. Capture duplicate-source-target or unused existing test-helper warnings from this unusual target explicitly; do not suppress production warnings or weaken normal warnings-denied Clippy. + +**One shared event path.** Extract the current `main.rs` closure's Ready/ExitRequested/Exit handling into one internal coordinator used by both production and the test target. Preserve ordering and restart pass-through semantics. The test target supplies its separate minimal Builder/setup; it must never call normal production `main`, register ordinary invoke handlers, initialize the dialog plugin, create normal webviews, resolve a normal workspace path, or acquire credentials. Test config has the distinct identifier `ai.rangoon.native-exit-qualification`, no automatic windows and no updater/plugin activation. Generate its real Wry context explicitly with `tauri::generate_context!("native-exit-qualification/tauri.conf.json", test = true, assets = tauri::utils::assets::EmbeddedAssets::new(tauri::utils::assets::phf::Map::new(), &[], tauri::utils::assets::phf::Map::new()))`; the qualification branch must not use the default-context macro or a mock runtime. This uses the pinned runtime asset constructor with empty maps/hash slice, not a new dependency or Tauri test feature. Runtime `EmbeddedAssets` has no `Default` implementation; do not confuse it with the code-generator type. `test = true` suppresses test-binary-incompatible macOS plist generation; it does not substitute a fake event loop. The config must omit frontend distribution/dev URLs, disable global Tauri injection and bundling, and contain exactly one inline capability named `nx06-no-permissions` with empty permissions/windows/webviews, `local = false` and no remote origins. Do not use an empty capability array: pinned Tauri resolves that to discovered capability files. Do not supply additional capability files. This inert selector produces zero effective permission grants while excluding the ordinary desktop capabilities. + +Before constructing any Builder, validate the generated context's exact identifier, window/config restrictions, inline capability and empty asset iterator, and emit only a fixed bounded context-validation record. Parent checks this record before Ready for every case; any mismatch fails before app creation. Source review must additionally verify the literal alternate config path, `test = true`, empty asset provider and absence of extra capability files/production setup. Retain this distinction between zero effective grants and an empty capability list. Register Gate, SourceAccess, WorkspaceClose, OpenShell Host, NativeModel, NativeCloud and Custody before Ready; the real anchor additionally installs Wake/WorkerCleanup. Native cleanup requires these states even when no webview exists. For anchor-eligible cases, SourceAccess uses `close_protocol_fixture`, whose backend is explicitly unavailable and whose lifecycle is memory-only. The sole `anchor-unavailable` exception uses existing `source_state(&gate, Err(StoreError::Unavailable))`, which constructs a non-encrypted unavailable Legacy source without resolving a path or opening storage; this makes the real `install` eligibility check return None. Both fixture forms have no database or key material. The unavailable-anchor case still requires unavailable Production Start and zero connection/RPC proof. Use generated loopback peer credentials and the existing real client/host consent path; no user URL, environment credential discovery or gateway configuration is an input. + +**Controlled observation and faults.** Keep observations under the qualification cfg only: monotonic sequence, case, event kind, admission/refusal state, callback returned/drained state, cleanup phase and coordinator-selected code. They may observe shared branches but cannot select an exit action or synthesize success. Write bounded source-free JSON lines to stdout; parent captures stderr separately with bounds. Do not emit tokens, certificate private keys, source text, user-data paths or arbitrary provider payloads. The isolated child must use a fixed test panic diagnostic for injected poison so default panic output does not expose uncontrolled content; compilation diagnostics stay separate from runtime evidence. For the recovery case, a private cfg-gated NativeCloud helper poisons its real state mutex using the existing test mechanism; the unchanged native purge and NativeHost terminal logic must choose code `4`. For installation failure, preoccupy SourceAccess's notifier slot before actual `install`; do not substitute ordinary Legacy unavailability. Test-only faults must be absent from normal builds. + +| Case | Native proof required | +| --- | --- | +| `idle-clean` | Ready installs the anchor after setup; request a nonterminal ordinary code such as `37`; first event is prevented; actual native cleanup finishes; coordinator reissues `0`; parent observes process code `0`. Original request and final code stay distinct. | +| `active-cancel` | Real synthetic watch starts before native exit. First event fences admission and prevents exit; real client returns `Cancelled`; hold callback custody after that return and verify another native roundtrip while still alive. Release hold, observe callback/drain/cleanup order, then process code `0`. | +| `duplicate-timeout-retry` | Hold callback past the existing 200-by-25ms waiter budget; deliver repeated native ordinary exits. At most one waiter is active; no terminal code or cleanup success appears while held. Admission stays fenced. Release custody and request a fresh ordinary exit; actual cleanup and final `0` follow. Scheduling delays are not treated as a strict five-second wall-time guarantee. | +| `cleanup-failed` | Poison only the fixture NativeCloud state; drive ordinary native exit through the shared callback and unchanged native cleanup; parent observes recovery `4`, not a mocked result. | +| `anchor-unavailable` | Existing `source_state(&gate, Err(StoreError::Unavailable))` supplies the non-encrypted unavailable fixture; actual installation returns None. Production Start returns unavailable; no synthetic connection/RPC occurs. Request ordinary code `37`; parent observes the current no-managed-anchor pass-through code `37`, with no cleanup claim or healthy managed-workspace claim. | +| `anchor-install-failed` | Eligible memory fixture has an occupied notifier; actual install fails and source remains failed closed. Production Start is unavailable with zero read dispatch. Request ordinary code `37`; parent observes current no-anchor pass-through `37`, not a cleanup receipt. This is not the cleanup-failed case. | + +Use phase signals and barriers, not a timing-only sleep, to prove the active phase. Existing source tests retain deterministic worker-spawn failure, panic, wrong-code rejection, late resume and poisoned coordination coverage; they do not become native cases by citation. Restart APIs remain uncalled and NX-05 remains a future pre-invocation guard requirement. The test config has no webviews, so this packet does not qualify renderer purge, OS credential sheets or review-window destruction. + +**Parent runner and failure behavior.** A standard-library Python runner builds the exact custom target with `cargo test --manifest-path apps/desktop/Cargo.toml --test native-exit-qualification --features native-exit-qualification,encrypted-workspace --locked --offline --no-run --message-format=json`. Select only that target's emitted executable; never search for a similarly named normal binary or invoke `open`. Each case gets a fresh process and disposable evidence directory; only the closed case selector is sent to the child. Run sequentially with a 45-second parent deadline per child and bounded output. Fail on missing Ready, unordered/missing required events, unexpected callback/connection, parse/truncation failure, wrong process code, timeout or signal termination. Kill/join only the child created by this runner on timeout and record failure; forced termination never counts as graceful cleanup. Do not use a machine-wide process kill or alter HOME, CODEX_HOME, credentials or production paths. Success is the parent's actual process code plus complete case evidence, not a child's self-reported PASS. + +**Validators and completion gate.** Run existing default/encrypted desktop tests and formatting, normal all-targets warnings-denied Clippy, named synthetic-client/host tests, default/encrypted executable builds, normal dependency feature inspection and a normal-artifact symbol check excluding qualification/test-peer entry points. Verify ordinary `cargo test --no-run` omits the custom target, retain the clean verbose custom-target compiler invocation proving `--cfg test`, and verify the explicitly built target refuses absent/invalid arguments before app creation. Validate the generated alternate context and parent context record as specified above; malformed config/identifier, inherited capabilities or nonempty assets must fail before app creation. Test these context predicates with inert malformed values; source review verifies the macro test-mode flag and shared real-runtime event path. Then run all six cases on macOS, repeat active and timeout/retry cases to expose ordering races, record OS/architecture/toolchains/features/source hashes, and preserve each parent outcome. Fresh independent read-only review must examine exact source diff and raw case evidence, including failed attempts. Document/image/link and diff checks remain required. Any missing case stays incomplete; passing macOS does not qualify Windows/Linux, real providers, normal encrypted storage, install packages or live authority. Source publication, deployment, release and production activation are outside this packet. + ### Credential-lifetime correction — accepted source prerequisite Accepted by Jeff on October 18, 2026 through “accepted keep going”; [intent](intent.md#openshell-credential-lifetime-correction-acceptance--october-18-2026) owns source acceptance. This is separate from the earlier accepted test-support bridge. The following historical findings motivate the accepted correction. The initial October 18 pre-bridge source inspection of `crates/rangoon-openshell-client/src/lib.rs` (historical whole-file SHA-256 `3db4e1945032c119ba76af3453c54fab62b9195168d5d2da6d1722157ee01287`) found three concrete limits: `connect` does not reject an already expired lease before socket/TLS setup; `check_protected_read` can send public Health before checking the lease; and unary waits plus watch headers/messages have RPC/watch bounds without a concurrent lease-expiry bound. `authorization_value` rejects an expired lease only when constructing protected metadata. The existing five-second RPC and thirty-second watch limits are not credential-lifetime enforcement. These are static source findings, not observed provider traffic or a claim of compromise. diff --git a/docs/operations-control-plane.md b/docs/operations-control-plane.md index ba23947..e9de96b 100644 --- a/docs/operations-control-plane.md +++ b/docs/operations-control-plane.md @@ -73,7 +73,7 @@ The operator view should answer, in order: **What was authored? What exact actio #### Cross-system relation proof gate -The existing O1 `ExternalRef` and `FlowContext` remain the local record vocabulary. A future bridge profile must reuse them and the proposed VUSL source-qualified reference rules rather than create a second generic trace ID or mutable joined status. Each relation names two immutable endpoint references, its source and native evidence reference, relation basis (`declared`, `reported` or `verified`), exact product/adapter/contract pins, environment and execution-path scope, observation and receipt times, freshness/invalidation state, and field-level loss. A relation is a separately inspectable fact; it never overwrites either endpoint. No new bridge wire profile or renderer-computed proof is accepted here. +The existing O1 `ExternalRef` and `FlowContext` remain the local record vocabulary. A future reviewed bridge must reuse their source-qualified reference concepts rather than create a second generic trace ID or mutable joined status. RUSL is retired as an active contract; this native relation-proof gate does not depend on a new language profile or VUSL core. Any future VUSL consumer adoption remains a separate reviewed cutover. Each relation names two immutable endpoint references, its source and native evidence reference, relation basis (`declared`, `reported` or `verified`), exact product/adapter/contract pins, environment and execution-path scope, observation and receipt times, freshness/invalidation state, and field-level loss. A relation is a separately inspectable fact; it never overwrites either endpoint. No new bridge wire profile or renderer-computed proof is accepted here. | Relation sought | Minimum proof before a `verified` edge | Otherwise show | | --- | --- | --- | @@ -270,6 +270,14 @@ Management actions are per-adapter capabilities, not generic buttons: inspect, v Every task records actor, target set, exact artifact/configuration and expected prior revision, adapter/product pins, required approval, dispatch identity, per-target acknowledgement, native installed/effective readback, evidence and explicit incomplete/unknown states. Change history and task log are append-only projections over authoritative records; UI refresh or load balancing cannot forge a completed rollout. Per-tenant scope and rate limits apply to search, subscriptions, bulk selection, exports and deployment jobs. This view may inspect independent LNSAT nodes first. A shared LNSAT cluster or remote management API remains unavailable until LNSAT separately qualifies those native contracts. +### Remote files in the shared fleet console — October 26, 2026 + +The [remote setup architecture](application-architecture.md#remote-setup-and-agent-file-management--october-26-2026) extends the same planned inventory design; do not add a competing device registry. Present the fleet entry as **Systems**, with a local workspace plus explicitly enrolled remote hosts. Keep the existing Fleet implementation/catalog terminology where needed until a separately reviewed UI packet mounts this surface. For Rangoon-shared files, each remote host is another explicitly paired Rangoon installation with sharing enabled by its owner. Access shows the peer, acting user/service, granted roots/operations, expiry and revoke action; pairing is not a file grant. A host selection opens Overview, Files, History, Tasks and Configuration/Access according to its actual adapter coverage. No unavailable tab/action pretends to execute a request. Source files remain usable through the local Agent files route. + +Files adds host/root filters to the same compact library/inspector interaction. Every remote row retains its host/root context, relative path, observed/saved/checked times, digest when available, revision linkage and freshness. Same-named files on two hosts are distinct. Bulk actions show the selected host count and per-target success/refusal/unknown counts; one unreachable host cannot clear or certify the others. Overview distinguishes Connection, File access, Runtime coverage and last observation instead of one misleading green status. A disconnected view may inspect authorized cached records, clearly marked offline and dated; content fetch, configuration changes and task controls remain unavailable until separately admitted. + +History joins only recorded target-bound revisions and evidence; remote mtime or connection success never creates lineage. Simple view shows file, host, version/date, change summary and next safe action; Advanced exposes identities, digests, cursor/session, exact UTC/clock provenance and diagnostic codes. Loading, no configured host, no allowed root, no matching file, no permitted content read, unsupported adapter, expired/revoked identity, stale/conflicting data and partial failure need distinct keyboard-accessible states. This is a required UI design, not implemented remote navigation or a connection claim. A graph remains an alternate projection; table and inspection are primary. + ## Provider independence and release sequencing The October 7 [accepted continuation](intent.md) preserves Rangoon ownership of configuration, routing, visibility and evidence while external providers retain their own authorization/enforcement/identity semantics. LNSAT is an optional separate product. Provider allow/no-violations, local content review, approval and execution outcomes never become interchangeable. Reuse the single [provider interoperability contract](provider-interoperability.md) for optional product/version/capability metadata; do not replace or silently remap the frozen operations schemas. diff --git a/docs/operations-local-window.md b/docs/operations-local-window.md index 8416d21..67f0b45 100644 --- a/docs/operations-local-window.md +++ b/docs/operations-local-window.md @@ -104,7 +104,7 @@ No renderer code falls back to full O1 documents. | Object | Exact keys and types | Limit/order | | --- | --- | --- | | `view` | `schemaVersion` = `rangoon.ops.operator-view.v1`; `authority` = `none`; `authenticity` = `unverified`; `eligibility` = `unknown`; `execution` = `unavailable`; `outcome` = `unknown`; `coverage` = `unknown`; `structuralState`; `sourceCounts`; `diagnosticCounts`; `decisionCounts`; `events`; `topology` | One object. All six truth labels fixed. | -| `sourceCounts` | `eventCount`, `producerCount`, `topologyNodeCount`, `topologyEdgeCount` (integers); `recordCounts` (array) | `recordCounts` has exactly 19 `{kind,count}` objects in `RECORD_KINDS` order from O1. Every kind present, zero allowed. | +| `sourceCounts` | `eventCount`, `producerCount`, `topologyNodeCount`, `topologyEdgeCount` (integers); `recordCounts` (array) | `recordCounts` has exactly 19 `{kind,count}` objects in `RECORD_KINDS` order from O1. Every kind present, zero allowed. Each count must equal the number of `events[]` entries with that kind in the whole selected window, regardless of active display filters; equal aggregate totals do not excuse a per-kind mismatch. The renderer rejects a contradictory replacement atomically and keeps any prior valid view labeled as previous. | | `diagnosticCounts` | `structural`, `relationships`, `delegations`, `approvals`, `lifecycle` (integers) | Count diagnostic occurrences within each stage, not distinct affected events. Never combine into a compliance score. | | `decisionCounts` | `evaluation` with `allow`, `deny`, `unknown`; `approvalDecision` with `approve`, `deny`, `abstain`; `authorization` with `reportedIssued`, `reportedRefused`, `reportedExpired`, `reportedRevoked`, `unknown`; `attempt` with `reportedAccepted`, `reportedActive`, `reportedCompleted`, `reportedFailed`, `reportedCancelled`, `outcomeUnknown`, `reportedReconciledCompleted`, `reportedReconciledFailed` (all nonnegative integers) | Count each allowlisted event exactly once in its own kind and reported-value bucket. Every bucket required, including zero. Each group's sum equals the corresponding `sourceCounts.recordCounts` count. No cross-group total, rate, inferred result or model-advice bucket. | | `events[]` | `inputOrdinal`, `producerOrdinal`, `fenceOrdinal`, `sequence` (integers); `recordKind` (enum); `reportedValue` (string enum or `null`); `structuralDiagnostics` (enum array); `issueStages` (enum array); `references` (array) | At most 1,024 rows, exactly one per O1 event, sorted by ascending `inputOrdinal`, beginning at 0 without gaps. `producerOrdinal` and `fenceOrdinal` are dense first-seen indices computed in input-ordinal order; fence indices are scoped to producer. Source IDs never appear. | diff --git a/docs/plan.md b/docs/plan.md index 6a70123..def8625 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -2,21 +2,78 @@ # Plan: Rangoon from capability workbench to governed platform Status: proposed -Authority: [intent.md](intent.md), including the accepted provider-independent continuation; detailed future stage proposals are not implementation or release acceptance +Authority: [intent.md](intent.md), including accepted provider-independent, internal operations-first and personal-completion continuations Owner: Jeff -Last updated: 2026-10-18 +Last updated: 2026-10-25 + + +## Current native recovery packet — October 25, 2026 + +The [E1d-2 packet](encrypted-workspace.md#e1d-2-native-sqlcipher-recovery-copy--october-25-2026) is implemented: the existing SQLCipher backend creates and verifies a canonical encrypted recovery image using a separate native-selected key file. The age experiment is preserved as standalone historical source, excluded from active builds; the active pre-experiment 167-package lock graph is unchanged. + +Five disposable macOS phases demonstrate native backup, original test-key removal, recovery into a fresh independently keyed workspace, a distinct-process reopen and exact test-slot cleanup. Complete canonical archive identity and length match across source, recovered target and restart. This is selected personal-use macOS evidence, not Windows/Linux, normal-profile migration or package-release qualification. The [receipt](development.md#e1d-2-native-encrypted-recovery--october-25-2026) owns current validators and independent review. + +Next: prepare a bounded personal-use packaging/install and recovery-rehearsal packet, keeping normal data/key custody explicit; qualify Windows/Linux key-file custody and GUI separately. One external task remains a separate later adapter gate. Do not reopen crypto selection, scheduler, fleet or protocol work to close this local milestone. Every future publication must include its substantive README update and reviewed final scope. + + +## Immediate security and recovery phase — October 25, 2026 + +Jeff requested addressing the intrusion and plaintext-output gaps. The current [E1d-2 recovery contract](encrypted-workspace.md#e1d-2-native-sqlcipher-recovery-copy--october-25-2026) owns the implemented SQLCipher profile and selected macOS recovery proof. Earlier E1d-0/E1d-1 design and experimental source remain historical checkpoints rather than current backup contracts. Engines, real data/key access, publication and release remain closed. + +1. E1d-0 assessment and independent design review are complete; preserve Managed plaintext-backup refusal and the explicitly readable instruction-export contract. +2. E1d-1 is a retained historical offline codec experiment. Its beta and build-time limitations were not waived. E1d-2 reuses existing SQLCipher without a new runtime crypto dependency or helper process. +3. E1d-2 source, selected-file custody and fresh encrypted recovery now have bounded source and disposable macOS evidence. Retain Windows/Linux, normal-data adoption and release gates; source tests do not establish those outcomes. +4. Qualify one external task through a separately scoped runtime adapter: exact loaded instruction revision, effective policy, real denial and outcome evidence. For OpenShell, audit-only observations never become enforcement coverage. Start with disposable data and independently checked denied-target nonreceipt. + +Recoverable local data now has selected macOS evidence. The next personal-value milestone is a reviewed personal-use build and recovery rehearsal, followed by one useful isolated target workflow. Do not expand scheduler, fleet, marketplace or protocol scope to satisfy this phase. Original files, readable target instruction exports and delivered model context remain outside backup confidentiality. A compromised authorized consumer can copy readable content; a future broker cannot retract it. The [E1d-2 development receipt](development.md#e1d-2-native-encrypted-recovery--october-25-2026) records current assessment and gates; the E1d-0 receipt preserves the earlier assessment. + + +## Personal-use completion — October 24, 2026 + +Authority: [Jeff's personal completion continuation](intent.md#personal-completion-continuation--october-24-2026). Prioritize a usable Rangoon for Jeff; market uniqueness and fundraising do not gate this work. Preserve the existing feature and security boundaries rather than restart the application. + +1. Recover all latest recorded source identities into the durable `codex/personal-workbench-20261024` branch at ``. Preserve the older dirty checkout and website; validate hashes, pinned tooling, renderer checks and fresh independent review. +2. Complete one encrypted local capability workflow: isolated setup/unlock, selected source import/save, derive/edit/review skill, compose selected revisions, compile/export, lock/reopen and verify retained content/provenance. Use disposable records and keys; normal user data and ordinary OS vault remain closed. Fix observed defects in bounded reviewed source slices. Preserve existing native recovery/admission/cancellation rules. +3. Prepare a local personal-use build after the above passes. Packaging/install and access to ordinary data/key custody retain their applicable explicit gates; no source test establishes a production release. Three-OS public qualification remains separate. +4. Add the minimum qualified external executor/inspection adapter useful for Jeff's actual task. Keep OpenHands as a reuse candidate, LNSAT/VUSL independent and optional, and unavailable controls explicit. No requirement to build a scheduler, fleet controller, broad plugin marketplace or new protocol before local usefulness. + +The earlier OpenHands comparative test and enterprise stages remain reference plans; they no longer make market differentiation a prerequisite for the personal local milestone. They do not authorize provider operation. Recovery evidence and current validation belong to the [dated development receipt](development.md#personal-use-source-recovery--october-24-2026). + +## Internal operations-first delivery — October 22, 2026 + +Authority: Jeff's [internal operations-first direction](intent.md#internal-operations-first-direction--october-22-2026). This changes priority, not the separate acceptance of implementation packets or production operations. Reuse the existing local workbench, [operations console/fleet inventory](operations-control-plane.md#fleet-management-console-direction), [distribution/deployment design](application-architecture.md#deployment-tiers-and-distribution) and [adapter developer path](provider-interoperability.md#adapter-sdk-and-independent-foundations--october-20-2026). Do not create parallel inventory, task, evidence or semantic registries. The long-term sections below retain their original proposal status; enterprise scale and fundraising are not prerequisites for a useful internal pilot. + +Customer Zero means Jeff is the first tester of the general product, not that Rangoon becomes a Hypler-specific internal tool. The [Customer Zero source assessment and stages](customer-zero-gap-analysis.md#staging-and-decisions-before-source-acceptance) refine the sequence below. The attachment's complete implementation scope is proposed; finish its architecture/gap review before accepting new source. OpenShell finite-read mounting is a separate connector lane, not the controlling prerequisite for the distributed engineering-job milestone. Existing local/encrypted and three-OS release work remains required for its own claims. + +| Order | Useful outcome | Required proof before expanding | +| --- | --- | --- | +| 1. Reconcile source and choose the pilot runtime | Freeze the task/attempt, storage/security and runtime-adapter boundary for one generalized project-review job. | Complete the Customer Zero audit and independent review. Define immutable execution identities and fail-closed task isolation in the [CZ-1 contract](customer-zero-gap-analysis.md#5-treat-source-review-as-code-execution-inside-an-isolation-boundary). Evaluate one pinned external scheduler/runtime against a minimal supervised runner; decide ownership rather than building duplicate scheduling infrastructure. The current C1-M result remains bounded fixture evidence, not agent execution. | +| 2. Accept one CLI-only durable deterministic job | One independently supervised controller and one isolated worker run an immutable validator/execution profile on pinned source. | Accept an exact source packet first. Prove persistence, idempotency, scoped dispatch, actual isolation/resource denials, execution-profile/input mutation refusal, restart reconciliation, cancellation and artifacts. Closing the initiating CLI cannot lose the job; an uncertain effect cannot be blindly retried. This intermediate gate requires no MCP, paid model or production target. | +| 3. Complete the MCP demonstration and mount task UI | Codex submits and retrieves the qualified job; another authorized client can inspect it after disconnect. | Replay the complete source-to-artifact workflow through MCP before claiming the supplied Customer Zero demonstration. MCP, CLI and UI reuse the task service, typed errors and scope checks. No arbitrary shell/credential fields or MCP-only execution state. Show actual attempts, evidence, missing output and unknown state. | +| 4. Add heterogeneous workers, agent runners and accounting | A second OS worker and separately qualified Codex/Claude or other runner use the same limited contracts. | Benchmark actual capacity; distinguish model advice from coding-agent execution and provider-specific controls. Reconcile estimates/reservations/retries/reported usage/final charges before budget claims. Add a second reference adapter before stabilizing the public SDK. | +| 5. Qualify sustained use and portfolio operations | Faulted synthetic concurrency, limited authorized provider runs and a soak precede separately authorized application operations. | Retain three-OS/local/encrypted/release gates. Portfolio health/readback and later protected actions need versioned interfaces, scope, approval/enforcement and recovery. Production commercial services remain fenced; no raw shell, direct database or deployment authority follows from a successful lab job. | + +Focused product/UI continuation accepted by Jeff: foreground source import, skills, composition/export and evidence inspection; keep diagnostics and sample surfaces secondary. The [experience direction](product-experience.md#focused-workbench-direction--october-22-2026) and [site brief](focused-workbench-site-brief.md) govern terminology and current-versus-planned claims. This accepts the bounded navigation/messaging slice, not provider installation, execution, a public SDK or website publication. The next useful technical milestone remains the isolated OpenHands integration proof, followed by only the UI operations that have qualified. + +Current owner steering: hold custom agent-execution and scheduling implementation pending the [direct OpenHands source comparison and isolated adapter test](openhands-comparison.md). Preserve capability authoring, composition, provenance and inspection. Prefer the supported SDK/Agent Server execution boundary if its bounded test passes; evaluate the separate beta Automation service only when scheduling is required. Do not implement a parallel scheduler or assume native confirmation is exact action authorization. The test packet remains proposed; this comparison opens no installation, model/provider call or live execution. + +The next source packet should serve the durable project-review milestone, reusing existing application contracts and qualified external execution mechanisms. Root owns service/storage/identity/authority decisions and integration; disjoint workers may implement only accepted named files. Freeze exact ownership, versioned task/attempt and storage contracts, runtime selection, data-transfer/isolation limits, typed diagnostics, validators and fresh independent review before implementation. The separate OpenShell command/controller/inspector packet remains proposed; this plan does not open its native mounting or real-credential scope. + +Start with one operator, one lab target and bounded history. Reuse a proven runtime without requiring a new cluster, hosted database or scheduler before the pilot. Later shared Rangoon management state sits behind an authenticated service and reuses typed application contracts; it is not an engine database or network-shared SQLite file. Inventory the hardware and measure representative CPU/GPU/memory workloads before assigning machines or adopting Proxmox/Nomad. No provider install, paid call, credential use, server operation, normal-data/key access, foreign-repository edit or publication is authorized by this documentation packet. ## Universal language design gate -Current accepted direction: RUSL is retired as an active contract. Preserve its old parser and fixtures as inert experimental history until a usable independently developed VUSL core is available and affected consumer tests are updated. Do not build or maintain RUSL readers, converters, aliases, dual-profile handling or a backward-compatibility program without demonstrated need. The [accepted retirement decision](intent.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026) supersedes the historical D0a/D1 roadmap below. +Current accepted direction: RUSL is retired as an active contract. Preserve old parser and fixtures as inert experimental history until a usable independently developed VUSL core is available and affected consumer tests are updated. Do not maintain RUSL readers, converters, aliases, dual-profile handling or a backward-compatibility program without demonstrated need. The [accepted retirement decision](intent.md#rusl-retirement-and-vusl-consumer-sequencing--october-19-2026) supersedes the historical D0a/D1 roadmap below. -Future VUSL adoption must select an exact usable upstream core/artifact, review native-semantic loss/refusal and authority boundaries, update and pass the affected Rangoon tests, and independently review the cutover before deleting old code. The existing spec/fixture provenance record is not that core pin. Until then keep the workspace buildable and existing tests passing. Native OpenShell/LNSAT adapters remain independent and useful local workflows do not acquire a language/core/provider prerequisite. +Future VUSL adoption must pin an exact usable upstream core/artifact, review native-semantic loss/refusal and authority boundaries, update and pass affected Rangoon tests, and independently review the cutover before deleting old code. The spec/fixture provenance record is not that core pin. Keep the workspace buildable and existing tests passing. Native OpenShell/LNSAT adapters remain independent; local workflows have no language/core/provider prerequisite. ### Historical D0a/D1 sequence — retired research track -The paragraphs below retain the earlier design and acceptance history; they do not reopen RUSL implementation or define current VUSL behavior. +The next paragraph preserves earlier design and acceptance history. It does not reopen RUSL implementation or define current VUSL behavior. -Jeff requested a design-only audit before expanding provider coverage. The proposed [VUSL v0.1 language](universal-systems-language.md), narrow [D0a observation profile](universal-systems-observation-profile.md), six [candidate canonical vectors](rusl-d0a-canonical-vectors.json), 11 groups of [candidate negative vectors](rusl-d0a-negative-vectors.json), six complete plus one derived [candidate O1/I1 host-source vectors](rusl-d0a-host-mapping-vectors.json) and [capability/implementation audit](universal-systems-audit.md) define a loss-aware semantic layer above I1/A1/W1/O1, not a replacement authority. Independent review of earlier proposal bytes passes; owner acceptance of a public profile and pinned schema identity remain open. Jeff separately authorized an **experimental pure offline D1 parser** under [intent](intent.md#d1-pure-offline-parser-authorization--october-16-2026). Its unmounted crate validates only candidate inert D0a documents. It cannot mount an adapter, assert compatibility or make candidate bytes a public wire contract. The offline D0a-H source probe now tests O1 reference/refusal shape against these envelopes and I1 H03 non-mapping; full D0a qualification still requires accepted profile/schema identity, complete independent cross-language conformance and a separately reviewed host integration. Jeff next accepted the exact [D0a-H offline O1/I1 source packet](intent.md#d0a-h-offline-host-source-conformance--october-17-2026), which probes validated reference shape and refusal only; it cannot emit D0a observations, assert compatibility or contact a provider. Jeff then accepted the exact internal D0a review snapshot for the [D2a offline OpenShell fixture adapter](intent.md#internal-d0a-profile-and-d2a-offline-adapter--october-17-2026). Public wire/schema acceptance and complete host/cross-language conformance remain open; D2a is typed inert metadata inspection only. D0b action/context commitment is a later separate gate before consequential semantics. Only a later separately consented, pinned read-only adapter may connect to a provider. Keep OpenShell and LNSAT independent and preserve the useful local three-OS workbench path. +Jeff requested a design-only audit before expanding provider coverage. The proposed [RUSL v0.1 language](universal-systems-language.md), narrow [D0a observation profile](universal-systems-observation-profile.md), six [candidate canonical vectors](rusl-d0a-canonical-vectors.json), 11 groups of [candidate negative vectors](rusl-d0a-negative-vectors.json), six complete plus one derived [candidate O1/I1 host-source vectors](rusl-d0a-host-mapping-vectors.json) and [capability/implementation audit](universal-systems-audit.md) define a loss-aware semantic layer above I1/A1/W1/O1, not a replacement authority. Independent review of earlier proposal bytes passes; owner acceptance of a public profile and pinned schema identity remain open. Jeff separately authorized an **experimental pure offline D1 parser** under [intent](intent.md#d1-pure-offline-parser-authorization--october-16-2026). Its unmounted crate validates only candidate inert D0a documents. It cannot mount an adapter, assert compatibility or make candidate bytes a public wire contract. The offline D0a-H source probe now tests O1 reference/refusal shape against these envelopes and I1 H03 non-mapping; full D0a qualification still requires accepted profile/schema identity, complete independent cross-language conformance and a separately reviewed host integration. Jeff next accepted the exact [D0a-H offline O1/I1 source packet](intent.md#d0a-h-offline-host-source-conformance--october-17-2026), which probes validated reference shape and refusal only; it cannot emit D0a observations, assert compatibility or contact a provider. Jeff then accepted the exact internal D0a review snapshot for the [D2a offline OpenShell fixture adapter](intent.md#internal-d0a-profile-and-d2a-offline-adapter--october-17-2026). Public wire/schema acceptance and complete host/cross-language conformance remain open; D2a is typed inert metadata inspection only. D0b action/context commitment is a later separate gate before consequential semantics. Only a later separately consented, pinned read-only adapter may connect to a provider. Keep OpenShell and LNSAT independent and preserve the useful local three-OS workbench path. + +### Independent integration sequence The support goal uses the [cross-runtime operator-record target](operations-control-plane.md#cross-runtime-operator-record-acceptance-target): OpenShell remains the first goal-specific **read-only runtime connector**, with LNSAT evidence as a separate later gate. The proposed [D2 OpenShell specification](openshell-observation-connector.md) and [D3 LNSAT specification](lnsat-evidence-connector.md) each stage offline native-source fixtures before separately consented connected reads. D3 explicitly excludes LNSAT's POST reconciliation route from a read-only adapter. The [cross-system relation proof gate](operations-control-plane.md#cross-system-relation-proof-gate) leaves independent engine observations unlinked unless a later qualified mediator binds one exact attempt; matching names, trace strings or digests do not make a verified edge. Existing Cerbos-first wording elsewhere in this plan describes the lower-risk generic policy-adapter I2 candidate, not a dependency or a broader ordering claim. This design reconciliation itself opened no implementation or engine action; the later accepted D1, D0a-H and D2a source scopes are separately bounded. @@ -187,8 +244,18 @@ The [accepted E1c-2a continuation](intent.md#e1c-2a-closed-native-control-custod ## Active encrypted adoption completion +Next integrated adoption design: [E1c-5 startup and Legacy conversion](encrypted-workspace.md#e1c-5-ordinary-startup-and-legacy-adoption--proposed) covers native classification, complete stable source capture, verified separate encrypted destination, interrupted selection and honest recovery controls. The overall adoption/default switch remains proposed; the selected-artifact E1c-4 observations and independent evidence review are complete within their stated macOS bounds. Jeff accepted the exact unmounted [E1c-5a startup inspection and existing-source capture](encrypted-workspace.md#e1c-5a-startup-inspection-and-existing-source-capture--proposed-source-packet) source and disposable tests on October 19; the [development receipt](development.md#e1c-5a-implementation--october-19-2026) owns implementation evidence. Jeff accepted the [exact E1c-5b conversion/selection source and disposable tests](encrypted-workspace.md#e1c-5b-verified-conversion-and-durable-selection--proposed-source-packet) on October 19. Its strict empty-target restore, native capture custody, bounded cross-root journal and distinct-process equivalence remain unmounted; the [implementation receipt](development.md#e1c-5b-implementation--october-19-2026) owns validation and review. This acceptance does not open ordinary routing or normal data conversion. E1c-5c owns the real native consent/recovery integration and platform tasks after source/fixture evidence. E1d continues to mean encrypted portable archives. No provider or language-specification work is part of this prerequisite. The [E1c-5c startup/recovery design gate](encrypted-workspace.md#e1c-5c-native-startup-and-recovery--design-gate) now addresses the immutable SourceAccess/registry boundary, deferred native Owner binding, exact setup residue, a distinct source-free startup controller and valid-journal recovery. It proposes encrypted default activation and copy-or-Quit Legacy handling; source, default activation and disposable OS-vault/UI qualification still require explicit owner acceptance after independent design review. + Authority: [accepted October 15 continuation](intent.md#encrypted-adoption-completion--october-15-2026). [E1c-1](encrypted-workspace.md#durable-operation-protocol-e1c-1) is implemented and independently source-qualified using the existing Owner/services and exact sixteen-path ownership; the [receipt](development.md#durable-encrypted-recovery-e1c-1--october-15-2026) owns validation and limits. Root produces protected source and documentation; independent review checks protocol before code and final behavior after named validators. Do not add a replacement encryption architecture. Then freeze explicit setup/unlock, failure-driven close/reload, Legacy import and native qualification in separate exact packets before mounting. Graph gestures wait behind the user's storage priority. The completed whole-system audit remains available as a historical source snapshot. +### Goal path after E1c-5b + +The independent-connectors decision remains authority; the older objective's LNSAT-owned OpenShell adapter is not the implementation plan. E1c-5b is verified unmounted source, not ordinary encrypted startup. Complete the reviewed E1c-5c native/default/recovery path and target-specific qualification before connected credentials or retained live observations. The current [development receipt](development.md#e1c-5c-startup-and-recovery-design--october-19-2026) owns evidence and acceptance. + +Then qualify D2b-2b production credential acquisition, native explicit consent, encrypted observation retention/deletion and Stop/close through the already tested read-client/host boundary; D2b-3 must use a selected real released gateway and qualify each client OS. Independently define the next offline LNSAT request-record profile with its native privacy projection before a D3b identity/transport gate. Latest inspected local LNSAT guarded fake dispatch remains test-only and does not close real runtime/effect proof. Neither engine is a prerequisite for local authoring. + +Only a separately accepted O3 native ingress/evidence packet may connect those reads to the complete operator record. Exercise OR-01–OR-12 with real provider evidence where qualified, including denial, approval versus allow, changed/repeated requests, unknown outcomes, cross-engine ID collisions and missing bridge proof. OpenShell text logs are not typed action approval; LNSAT source-only reservations are not consequences. Competitor parity is a target to prove with those workflows, not a completeness claim. Installation/signing/update/recovery and macOS/Windows/Linux release qualification remain required afterward; broad integration coverage is not a prerequisite for shipping the useful local workbench. + ## October 15 audit completion sequence Authority: [accepted whole-system audit](intent.md#whole-system-audit-with-glm--october-15-2026); assessment: [current system audit](system-audit.md#october-15-whole-system-audit-and-completion-map); evidence: [development receipt](development.md#whole-system-audit-with-glm--october-15-2026). This is proposed sequencing within the accepted architecture, not acceptance of every listed implementation. Earlier dated packet plans remain historical. Existing routing, callbacks, close/drain/purge, compact navigation and draft-recovery implementations must be reused. @@ -211,7 +278,7 @@ Root owns protected production code and architecture. Current candidate ownershi Acceptance: source and empty setup; four existing provisioning fault points; dropped result and new Owner/process; malformed/mismatched/unknown recovery state; pre-/post-persistence and terminal-write ambiguity; explicit read-only reconciliation; successful clean restart. Refusal must not open/write vault or regenerate keys, change DB bytes, replay mutation or fall back to plaintext. Verify exact vault/key-generation counters. Fixing provisioning does not close later capability/workflow/composition/restore/deletion interruption cases. -Named validators: pinned Rust 1.98 native formatting, default/encrypted all-target tests, both Clippy modes with `-D warnings`, privacy doctests and encrypted build; authored references/whitespace and outside-owned identity preservation. Use disposable roots/fake vaults. Real process-kill/disk-full, real OS custody and three-OS durability remain explicit later evidence. Rollback is the exact owned incremental patch, never reset/stash of the preserved working tree. +Named validators: pinned Rust 1.99.1 native formatting, default/encrypted all-target tests, both Clippy modes with `-D warnings`, privacy doctests and encrypted build; authored references/whitespace and outside-owned identity preservation. Use disposable roots/fake vaults. Real process-kill/disk-full, real OS custody and three-OS durability remain explicit later evidence. Rollback is the exact owned incremental patch, never reset/stash of the preserved working tree. ### Other bounded follow-up packets @@ -640,11 +707,30 @@ Authority: Jeff's October 8 ISO-readiness question and explicit OpenSSF steering | [ISO/IEC 42001:2023](https://committee.iso.org/cms/live/live/en/sites/isoorg/contents/data/standard/08/12/81230.html) | Proposed AI-management scope; advisory model/provider boundaries and provenance support evidence collection | Product/security owner documents AI roles, risks/impacts, intended use, oversight, evaluation, incidents and continual improvement; no model-quality or governance certification from source tests | | [ISO/IEC 27701:2025](https://www.iso.org/standard/27701) | Privacy-management candidate for personal data handled in support, optional telemetry or hosting; local-first consent is not a privacy-program assessment | Privacy owner identifies controller/processor roles, actual data flows, minimization/retention/deletion, transfers and organizational accountability before hosted adoption | | [OpenSSF OSPS Baseline v2026.08.28](https://baseline.openssf.org/versions/2026-08-28) | Initial assessment target: Level 1, followed by applicability-based Level 2/3; source/license/docs/test evidence exists, full checklist not assessed | Repository/security owner maps every applicable control against this exact revision; verify account MFA, permissions and hosted enforcement separately; close security contact/contribution-process gaps rather than assuming AGENTS.md is public contributor guidance | -| [OpenSSF Best Practices passing criteria](https://www.bestpractices.dev/en/criteria) | Proposed initial badge target; public source, Apache-2.0, test documentation and warnings-denied checks are candidate evidence | Maintainer completes honest criterion-by-criterion assessment with proof, response history and justified applicability; voluntary self-certification is not independent ISO certification; no badge claimed/applied for | +| [OpenSSF Best Practices Passing criteria](https://www.bestpractices.dev/en/criteria/0), checked October 19, 2026 | Accepted development direction: target Passing first; public source, Apache-2.0, test documentation and scoped warnings-denied checks are candidate evidence, not a completed assessment | Maintainer completes the criterion-by-criterion assessment and adoption backlog below with dated proof, response history and justified applicability; no badge claimed or application submitted | | [OpenSSF Scorecard](https://github.com/ossf/scorecard) | Assessment tool, not a normative certification; inspected source-check workflow has read-only contents permissions, full-SHA actions and checkout credential persistence disabled | Maintainer obtains a dated tool/version/commit-bound assessment and inspects individual findings; current score unknown. Check branch protections, workflow privilege, dependency/update policy, SAST and real fuzzing without equating a high score with absence of vulnerabilities | | [SLSA v1.2](https://slsa.dev/spec/v1.2/) | Proposed build-provenance track for actual distributed artifacts; source CI and content bundle checksums are not signed build attestations | Release owner qualifies builder identity/isolation, generated provenance, signing/verification and exact artifact/source/dependency links; choose and prove a build level per artifact before claiming it | -Create one control-to-evidence register in a separately owned readiness packet: reference/version/control ID, scope/applicability and rationale, human owner, implementation/policy path, immutable evidence/commit, check date, gap, remediation packet and independent verification. Keep “planned,” “source implemented,” “runtime qualified,” “assessed” and “certified” separate; no automatic green status from test counts. This section records candidate evidence and next work, not full clause-level conformance. Standards alignment statements must name their scope and unresolved gaps. [Independent certification](https://www.iso.org/certification.html) is a separate organizational process. +### OpenSSF Best Practices adoption plan + +Authority: Jeff's October 19 request to plan adherence to the [Best Practices Badge program](https://openssf.org/projects/best-practices-badge/). Target Passing first; assess Silver/Gold later. Its Passing/Silver/Gold series and OSPS Baseline levels are separate assessments. Neither replaces ISO certification, Scorecard findings or artifact-specific SLSA evidence. Official references above were checked on October 19; capture the exact assessed criteria revision before making a badge claim. + +Delivery sequence, clarified by Jeff on October 19: apply the relevant secure-development practices while building each feature and retain its normal validation evidence. Complete the full Passing assessment, remaining control evidence and product-wide review during V1.0 finalization. Keep feature and workflow mechanics on the active delivery path; badge administration is not a separate stabilization program that displaces that work. Security defects and required product/release gates are addressed when encountered, rather than deferred to the final assessment. Enrollment and any badge claim still require their own completed evidence and publication authorization. + +The table below is a sample backlog, not an assessment register. Grouped IDs do not have equal requirement strength. One later canonical control-to-evidence register will inventory every criterion, badge tier, official MUST/SHOULD/SUGGESTED strength, permitted N/A rationale, owner, evidence and gap; no second register is created here: + +| Workstream / sample Passing criterion IDs | Rangoon action and required evidence | Accountable owner | +| --- | --- | --- | +| Project and contribution: `description_good`, `contribution`, `license_location`, `documentation_interface` | Verify public purpose, contributor guidance, license/notices and real input/output documentation against the delivered application | Maintainer/documentation owner | +| Change and delivery: `repo_track`, `version_unique`, `release_notes`, `delivery_mitm` | Link reviewed changes, unique versions, upgrade/security notes and authenticated distribution to each intended release | Release owner | +| Reporting: `report_process`, `report_responses`, `vulnerability_report_process`, `vulnerability_report_response` | Establish a monitored reporting route and measured response history; vulnerability initial-response target is at most 14 days under the criterion | Jeff/security-response owner | +| Build and testing: `build`, `test`, `test_policy`, `warnings_fixed` | Reproduce documented builds/tests, add meaningful regressions with features and resolve warnings; pending native/platform tests stay visible | Development/QA owner | +| Security: `know_secure_design`, `crypto_call`, `crypto_random`, `no_leaked_credentials`, `vulnerabilities_fixed_60_days` | Retain qualified human security ownership, vetted crypto, key/nonce custody, credential checks and vulnerability remediation evidence | Security/native owner | +| Analysis: `static_analysis`, `static_analysis_fixed`, `dynamic_analysis` | Qualify release analysis tools and resolve confirmed findings; document native/FFI applicability instead of assuming Rust removes all dynamic-analysis concerns | Security/QA owner | + +Next readiness packet inventories every Passing criterion, not only the examples above, and records evidence/gaps in that register. Then close gaps through bounded implementation packets and human review. Assess Silver/Gold only after Passing evidence is complete. Preserve local-first operation and independent product scopes; Rangoon evidence cannot qualify LNSAT or VUSL. Badge enrollment/submission, monitored-contact activation, hosted settings, scanner/CI installation and release changes retain their own concrete authorization. No badge percentage or compliance claim follows from this plan. + +Create that single control-to-evidence register in a separately owned readiness packet: reference/version/control ID, framework/badge tier, requirement strength, scope/applicability and permitted N/A rationale, human owner, implementation/policy path, immutable evidence/commit, check date, gap, remediation packet and independent verification. Keep “planned,” “source implemented,” “runtime qualified,” “assessed” and “certified” separate; no automatic green status from test counts. This section records candidate evidence and next work, not full clause-level conformance. Standards alignment statements must name their scope and unresolved gaps. [Independent certification](https://www.iso.org/certification.html) is a separate organizational process. Immediate readiness backlog, with applicability checked against the pinned framework: verified security contact and coordinated/private vulnerability reporting; contributor process and roles; hosted MFA/least privilege/branch enforcement; dependency inventory and vulnerability/secret scanning policy; qualified threat assessment; build/release provenance, SBOM and distribution notices; and measured recovery evidence. A repository file is not proof that a contact is monitored or a hosted setting enforced. Current synthetic deterministic malformed-input/property tests supplement exact acceptance; they are not coverage-guided fuzzing or an OSS-Fuzz integration. Those need a separately scoped parser/decoder fuzzing packet. @@ -662,7 +748,7 @@ Authority remains accepted intent.md and the existing local-value/encryption seq Small first test packet to freeze after the current E1 slice: controller owns the exact native custody behavior and `apps/desktop/src/models_tests.rs` / `apps/desktop/src/cloud_models_tests.rs`; one native fixture worker owns only `crates/rangoon-model-session/tests/cloud_lifecycle.rs`. Reuse synthetic stores, injected adapters and fake credentials. Require a composed prepare → mutate exact source/revision/profile/credential state → attempt consent/dispatch sequence with zero unauthorized adapter calls, plus cancellation/late-result fencing and no automatic domain writes or authority promotion. Do not start until the controller identifies the production helpers needed to avoid a test-only substitute; any new helper/source file requires a separately frozen scope amendment. No providers, credentials, model install, paid calls, user vault/data, sockets or execution are part of this proposed packet. -Named proposed validators: pinned Rust 1.98 native default/encrypted all-target tests and warnings-denied Clippy, native formatting/privacy checks; pinned Rust 1.85 targeted model-session lifecycle tests and portable format/Clippy; unchanged-workflow/export regression checks proportional to the actual interaction; docs/intent/whitespace; fresh independent review. Record exact source/target/fixture hashes, positive and refusal outcomes, uncertainty and remaining gaps. A red new interaction test becomes a separately reviewed fix, not permission to widen authority or weaken validation. This is a proposal, not a claim that these tests or the stabilization cycle have run. +Named proposed validators: pinned Rust 1.99.1 native default/encrypted all-target tests and warnings-denied Clippy, native formatting/privacy checks; pinned Rust 1.99.1 targeted model-session lifecycle tests and portable format/Clippy; unchanged-workflow/export regression checks proportional to the actual interaction; docs/intent/whitespace; fresh independent review. Record exact source/target/fixture hashes, positive and refusal outcomes, uncertainty and remaining gaps. A red new interaction test becomes a separately reviewed fix, not permission to widen authority or weaken validation. This is a proposal, not a claim that these tests or the stabilization cycle have run. ## Capability-family routing qualification — October 13, 2026 diff --git a/docs/product-experience.md b/docs/product-experience.md index 38c54a4..ff4a3ad 100644 --- a/docs/product-experience.md +++ b/docs/product-experience.md @@ -1,5 +1,51 @@ # Product experience: make the visual promise useful +## CW-1 saved-revision continuation — October 29, 2026 + +Skills gains **Open in Compile** beside its saved-revision actions. It opens that exact saved revision, including a selected historical revision, in the existing Compile workbench and focuses the selected revision/profile area after loading. Choose the format and compile explicitly there; nothing is compiled, exported or executed by navigation. + +If the selected skill has unsaved current edits, save or discard them first; historical view directs the user back to current to do so. Other skill drafts remain intact. Pending work, conflicts and unavailable native access explain why the action is disabled. A failed read stays in Skills. Navigation, selection changes and Lock reject a late handoff; a native identity mismatch never falls back to current head. + +Reuse the existing library/work-area/inspector layout, action styling, theme, focus and reduced-motion rules. No new graph, banner, animation, dependency or permission is added. Focused and full source tests pass; actual 320/768/1440 light/dark, keyboard/focus and failure interactions are still required. CUA cannot start under the current symlinked writable-root configuration, so rendered/native usability is not claimed. [Implementation receipt](development.md#cw-1-saved-revision-compile-handoff--october-29-2026) records the test boundary. + +## BF-2c folder metadata browsing — October 27, 2026 + +Choose folder lists compatible Markdown file metadata in Agent files. Browse relative paths, observed sizes and modified times; search by path/name, use Metadata only, and page through 50 rows. New folder rows appear first while saved sources and explicitly selected files remain available. Clear folder removes the listing from memory. One folder selection replaces the previous folder window; cancelling or failing a replacement keeps prior work. + +Folder rows say Metadata only and Contents not read. Selecting one opens the metadata inspector without a native read. Choose files to inspect uses a separate native picker, followed by the existing Markdown review/find/source workflow. This deliberate extra selection remains until retained row-inspection custody is qualified; no display path becomes file-read permission. Folder records cannot be bulk-checked or handed to Open saved source. Dates do not create revision lineage; modified time is observed filesystem mtime at whole-second precision, while Listed locally is the receiving window's session clock. + +A compact folder strip shows the selected label, count and partial state; Listing details explains exclusions or limits. Defaults: 1000 rows, 10,000 visited entries, depth 16 and a 2 MiB metadata response. Unknown/unavailable/unsupported states stay explicit. Metadata is neither a live synchronized index nor a saved source. Directory handles close before native delivery; Lock purges rows and refuses late repopulation. Local saved/selected workflows remain usable. + +The [development receipt](development.md#bf-2c-native-folder-metadata-workbench--october-27-2026) records pinned native source tests and six synthetic browser layouts. Actual native folder-dialog/OS qualification remains separate before personal files; Windows folder discovery reports unsupported. Next: disposable picker/Lock qualification and retained row inspection, then encrypted organization/history mounting and remote sharing through their existing contracts. + +## WF-1 in-file Find — October 27, 2026 + +Agent files keeps filename filtering and source-text search separate. Open a file, then choose **Find in file** beside the read-only source label. The inline toolbar offers literal text, Match case, a current/total match count and Previous/Next. It starts closed to preserve source space. Enter/Shift+Enter and F3/Shift+F3 move between results; Cmd/Ctrl+F opens it when focus is within Markdown review. These shortcuts do not replace file-library filtering or global browser search outside that review. + +A result opens its folded ancestors and scrolls only the source pane while keyboard focus stays in the current control. Highlights preserve original text and syntax spans. Same-file refreshes preserve query, case, result, folds and focus; Close/Escape clears the query/highlights and returns to Find. Changing files, leaving Agent files or locking the workspace clears Find state. Queries are never persisted or sent to native/provider services. + +Search is single-line, literal and bounded: 256 UTF-16 code units, no NUL, first 1000 non-overlapping matches, with a visible cap when more exist. Case-insensitive matching uses Unicode lowercase with whole original code-point boundaries; it does not promise locale-aware case folding or normalization. Unavailable, invalid, empty and no-match states are distinct. Positions are display offsets only, never authoritative source byte ranges. Existing saved-source handoff and native section-to-Skills behavior remain unchanged. See the [development receipt](development.md#wf-1-in-file-find--october-27-2026). + +## Focused workbench direction — October 22, 2026 + +Authority: Jeff accepted concentrating on the differentiated capability workbench and a bounded OpenHands integration proof, simplifying the UI and preparing matching Rangoon/Hypler site messaging. The [source comparison](openhands-comparison.md) owns integration findings; [plan](plan.md#internal-operations-first-delivery--october-22-2026) owns staging; [development](development.md#focused-workbench-navigation-and-site-brief--october-22-2026) owns exact delivery evidence. The [site brief](focused-workbench-site-brief.md) separates current capability from planned integration and supplies reusable copy. No website publication or external connector activation follows from this request. + +Primary journey: import source → review reusable skills → compose selected revisions → compile/export → inspect available evidence. Preserve original source, revision identity, differences and limitations in the existing inspector. Keep current routes and native contracts stable; visual simplification does not remove provenance or security controls. The first UI-only slice regroups and labels navigation: Workbench, Compose & export, Review, Advanced, Samples & prototypes. Workflow definitions, advisory model guidance, system coverage and the local LNSAT diagnostic remain reachable under Advanced. Evidence inspection does not become a live task console. All twelve route IDs, links, current-item semantics, theme controls, native workspace guard and keyboard/responsive drawer behavior remain intact. + +This first slice changes metadata and secondary-group separation, not disclosure behavior. The design review favored retaining existing compact focus/escape/resize handling over adding nested disclosures now. Advanced and sample groups remain visible in wide navigation; later progressive disclosure must preserve focus and state explicitly. Do not claim this initial regroup completes the full simplification. + +Next experience slice: improve source/library empty states and the selected-skill inspector, show source → revision → composition → export as one coherent record, and make target preparation distinct from effective-configuration readback. An OpenHands setup/run screen follows its accepted adapter contract and isolated proof; until then, no active Connect/Run button or connected badge. System details must identify actual coverage: local admission, native confirmation, runtime-enforced, observed, unsupported or unknown. Readiness details belong in context, not repetitive page-wide essays. + +Reuse OpenHands execution behind a replaceable adapter if qualified. Do not build a custom agent loop/scheduler, parallel workflow engine or new telemetry backend for this UI direction. VUSL and LNSAT retain independent purposes, logos and ownership; their inclusion is neither a mandatory runtime dependency nor a claim of mounted integration. Preserve graph authoring as an alternate editing surface and samples as explicitly synthetic exploration. No new art, motion framework, dependency or runtime permission is needed for this first slice. + +## Foundation identity and adapter developer context — October 20, 2026 + +Authority: Jeff requested independent foundational roles for VUSL and LNSAT, their logos on module/engine identity surfaces, and clearer app context and flow. He also reaffirmed an SDK for other system variants. This accepts bounded UI-only identity and wording work; the SDK question clarifies the existing R9 plan rather than authorizing an executable plugin system or a new shared contract. The development ledger owns progress, evidence and exact paths. + +Show VUSL as Shared language and LNSAT as Authority engine. Use canonical unchanged local marks beside visible names and concise states. VUSL integration remains planned; live LNSAT adapter operations remain unavailable. Keep VUSL outside the authority-engine catalog, permission meters and connection state. Put detailed mechanics in closed, keyboard-accessible disclosures. The engine diagnostic reads only its existing local status command; identity artwork creates no provider call, approval, readiness or runtime dependency. Local capability work remains independent of LNSAT. No new hero, mascot, motion framework or navigation hierarchy is required. + +The [existing adapter developer path](provider-interoperability.md#adapter-sdk-and-independent-foundations--october-20-2026) owns SDK mechanics: VUSL semantics remain upstream; Rangoon adapters declare exact product/version/operation coverage, preserve provenance and expose limitations. A released SDK, plugin loader and VUSL consumer adoption do not exist yet. Offline conformance and the independently qualified reference adapters precede a stable public SDK. Do not turn these planned developer capabilities into active UI controls. + ## UI-V2 reference reconciliation The eight user-supplied images remain structural targets, not operational evidence. Keep the recognizable navigation, task workspace, selection and inspector hierarchy: Skills uses library/editor/provenance; Workflows uses palette/canvas/inspector; Import and Decompose use source/analysis/review; Merge/Split uses inputs/compose/result; Connectors uses catalog/detail; Command Center leads to actual local tasks. The original large mascot and scenic banners are optional marketing art. Daily application surfaces use compact headers and a restrained abstract Rangoon form so record content and actions dominate. User-visible synthetic samples, unavailable connections and unqualified runtime evidence retain explicit labels. This change is presentation-only; it does not infer feature completion from a screenshot. @@ -19,6 +65,33 @@ The abstract form is decorative and replaceable. Jeff's October 18 follow-up fav Authority: [intent.md](intent.md). Jeff's October 5 clarification requires reviewing the supplied images as workflows and building a strong, usable platform, not stopping at styled screens. This record translates that direction into behavior and acceptance. The [architecture plan](plan.md) remains the full sequence; [development.md](development.md) owns implementation evidence. +## Connected-system usability — October 20, 2026 + +Direction: Jeff asked what the engineering means for users and explicitly prioritized ease of use and application dynamics. The following is a proposed experience for the existing optional-system architecture, not an implemented connection or a replacement shell. The [development receipt](development.md#connection-usability-and-native-input-plan--october-20-2026) owns status; the [OpenShell mounting specification](openshell-observation-connector.md#d2b-2b-mounting-sequence--proposed-october-20-2026) owns exact native security and adapter behavior. + +Keep local work, connected-system inspection and consequential action approvals recognizable as different tasks. Opening a local workspace or editing instructions needs no engine. In the existing grouped navigation and library/workspace/inspector layout, a system row answers three questions: what system is selected, what information is available, and what the user can do next. Advanced configuration, capability comparison and technical evidence stay in expandable details. Do not replace the useful task with a catalog of disabled features or persistent readiness essays. + +| User task | Main controls and feedback | Required mechanics | +| --- | --- | --- | +| Add or select a system | Target label, adapter/version, concise setup status and one next action. Preserve the draft when returning from review. | Validate a nonsecret draft locally. No discovery, credential access or provider request follows from opening the page, typing or selecting a card. | +| Review access | Explain which system and read, how data is handled, and the current one-attempt expiry. Advanced shows exact nonsecret target/pin/scope details. | Allocate the existing selection only after the draft is complete and the user deliberately enters review. Native confirmation precedes secret acquisition; no lifetime renewal. | +| Read once | Native input, then “Reading once” with persistent Stop. | One admitted callback owns native review, input and the finite read until actual completion. Local cancellation or expiry cannot release custody early. | +| Inspect result | Timestamp, plain-language source state, “Current session result — not saved,” and Inspect. | Local table/graph selection, pan/zoom, search, filters and inspector expansion operate on the accepted result, without another provider request or prompt. | +| Refresh | Explicit Refresh action; explain when native access is needed again. | Current one-attempt contract requires new selection/consent/acquisition. No hidden polling, reconnect, token reuse or automatic retry. | +| Handle an action request | Separate approval inbox with request, resource/action scope, applicable policy and recorded evidence. | Connecting or allowing a read cannot approve an action. Provider decisions, human reviews, authorization, execution and outcomes remain distinct and provider-specific. | + +Use a single state-appropriate primary action: finish setup, review access, read once, Stop, or inspect result. During cancellation show “Stopping” until the actual native callback returns; then show “Stopped locally” with a short explanation that a provider read might already have completed. Native Cancel restores focus to the initiating task and keeps the nonsecret draft. Lock/close purge session content through existing lifecycle handling. Expiry before result acceptance rejects the in-flight result; expiration of the old credential does not retroactively invalidate an already accepted session observation or grant permission to refresh it. Reopening starts no read and reuses no consent. + +Use precise compact labels: “Not configured,” “Read unavailable,” “Reading once,” “Provider denied this read,” “Read expired,” “Stopped locally,” and “Current session result.” A successful finite read is not a persistent Connected badge. Show a reported gap when the bounded watch projection contains one; a limited window cannot imply complete history. A stale label requires an explicit freshness rule and timestamp. Empty activity means no observations, not healthy/idle systems. Synthetic examples remain opt-in and visibly separate. Provider free text, raw identifiers and secret references do not enter user copy by opening Advanced. + +Each failure should answer which system and step failed, what remains usable, and the next safe action. Keep a concise human message with expandable stable machine code, bounded phase/source metadata and recovery guidance. LLM/debug consumers use explicit fields rather than interpreting prose. Never include credentials, raw provider responses or arbitrary diagnostic text. Preserve provider-native status separately from Rangoon's local review and lifecycle status: local Cancel is not provider denial; an unavailable provider does not disable local authoring; a successful read is not action authority. Shared categories aid navigation, but do not flatten distinct providers into identical authorization semantics. This is the required diagnostics direction; cross-provider implementation and public contracts are not complete. VUSL owns the independent shared semantic language; Rangoon consumes it through a separately qualified integration rather than defining a competing universal format. Current native/input/client diagnostics and qualification events are internal local contracts, not a VUSL wire profile. Rangoon adds human labels, contextual help and safe recovery actions while retaining native codes and provenance; no translation becomes engine authorization. Current consumer adoption remains unfinished. VUSL and LNSAT should appear as distinct branded foundations, with VUSL identified as language/core and LNSAT as optional authorization/evidence integration. Use their maintained local logo assets on relevant cards, details and links, with accessible names and no badge implying unsupported integration. + +A scoped reading session is a subsequent product decision, not a silent relaxation of C0. The current repeated-review/token-entry friction is unsuitable as the final high-volume operations experience. Before promising continuous Live mode, define an explicit session duration, exact read allowlist, provider credential lifetime, cancellation/revocation behavior, bounded traffic/backpressure, gap detection, reconnect policy and native-only secret custody. New action authority is not part of that session. Until that contract and implementation qualify, present the real finite read honestly. No automatic background work is introduced by this UX proposal. + +Interactions should feel responsive through immediate selection, a stable inspector, keyboard shortcuts, local filtering and short restrained transitions. Actual source events may update a graph; decoration must not fabricate traffic. Keep destructive or authority-changing actions explicit. At compact widths use an ordered list and accessible inspector instead of requiring node dragging; retain the same records and action meanings across list and graph views. Controls remain at least 44px where required, with visible focus, reduced motion, forced-color meaning and keyboard alternatives. Preserve original reference hierarchy and restrained abstract art. + +Usability acceptance for the eventual mounted slice: empty/setup states offer one useful next step; Back retains draft; Simple/Advanced causes zero network/secret activity; native Cancel produces zero read and restores focus; Stop remains busy until actual return; denial/source error/expiry/local stop have different recovery copy without fallback/retry; successful result navigation causes zero new RPC; lock/reopen clears the session and starts nothing; the selected record remains synchronized between table/graph/inspector; 320/768/1440 light/dark, forced-color, keyboard and reduced-motion cases retain visible task/action/focus without overflow. Real target qualification and a truthful minimized display DTO are prerequisites for claiming this experience works. + ## UI-U2 shared task navigation Jeff accepted the next shell refinement after UI-U1. The [accepted intent](intent.md#ui-u2-shared-task-navigation-and-compact-shell--october-13-2026) and [visual contract](visual-system.md#ui-u2-shared-task-navigation-and-compact-shell) retain the original grouped sidebar while giving narrow layouts a compact current-task menu. The same real task links and explicit examples should be available across the workbench and both existing playgrounds. Domain state remains with existing controllers. @@ -337,3 +410,148 @@ Jeff's October 8 direction adds setup and data management to the existing workbe Switching presentation level never unlocks data, changes authority, performs a migration or calls a provider. Data-loss warnings, local consent, encryption limits, failures and basic safety remain visible in both modes. Recoverable cancellation, keyboard/focus, reduced motion and stable dark/light artwork remain required. CLI shares the same service boundaries; it is not a raw database editor. This is design direction only: no new screen or native control is mounted by the documentation packet. Workspace-close integration follows [the canonical renderer contract](encrypted-workspace.md#global-renderer-workspace-close-integration). A confirmed lock discards unsaved window drafts/history and fences late results; already-started writes may have completed. Completed lock is distinct from Closing/recovery and never certifies external writes or secure erasure. Ordinary route caching remains useful until explicit close. Legacy stays usable without providers or LNSAT; this UI packet does not activate encrypted storage, setup/unlock or migration. + + +## Technical details and everyday views — October 24, 2026 + +Jeff requested that internal keys and metadata move out of everyday task views. Show the object's name, selected version context, human-readable status, necessary warnings and next actions first. Record identifiers, hashes, schema/contract versions, raw manifests and transport diagnostics belong in explicitly opened Advanced or Technical details views. Use accessible native disclosures, closed on first render; preserve a user's disclosure choice during supported same-view redraws. Exact identities and machine contracts remain unchanged. + +This is progressive disclosure, not a confidentiality boundary. Existing stored API keys, database encryption keys, bearer tokens and other app-managed credential values must never be returned to the main workbench, hidden DOM fields, tooltips, advanced disclosures or logs. Existing explicitly authorized credential-entry flows retain their own contract; this rule does not prohibit their blank entry fields. Credential handling stays in its existing authorized native custody flow. Any future credential entry or reveal requires its own reviewed privacy/security contract. + +Do not collapse blockers, uncertain outcomes, plaintext-output warnings, approval scope or destructive impact summaries. Review/authorization semantics remain visible where an action depends on them. Every object still needs an inspectable exact identity, including objects with duplicate names; removing metadata from the primary view must not remove provenance or change which record an action targets. Duplicate names retain a visible record discriminator and distinct action labels. If shortened discriminators collide, show the complete identifier; deletion previews always expose the exact target in Technical details before confirmation. Preserve open disclosures and summary focus through same-view refresh, without reopening anything after lifecycle disposal. The first implementation applies this pattern to Compile and Workspace; remaining authoring and integration inspectors retain their current behavior until separately refined. + + +## Management usability checkpoint — October 25, 2026 + +Jeff requested checking whether management systems are useful and optimizing them. The [management audit receipt](development.md#management-audit-and-activity-report-optimization--october-25-2026) owns current evidence and the exact source delta. This is an assessment of existing local surfaces, not qualification of a connected operations platform. + +| Surface | Existing behavior | Remaining management gap | Direction | +| --- | --- | --- | --- | +| Sources and skills | Local saved records, immutable revisions, provenance and content review through existing controllers/native services | Bounded folder discovery, durable categories/collections and bulk organization are not established by this audit | Preserve the source → skill → composition → export path; do not substitute a fleet dashboard for content work | +| Workspace data | Inventory, usage limits, dependency-aware deletion previews, additive restore; E1d-2 separately proved selected encrypted recovery on disposable macOS data | Ordinary personal install/data adoption, other-platform custody/GUI and broader filesystem recovery remain unqualified | Keep backup/restore prominent, exact identifiers in details, key custody native and destructive operations explicitly previewed | +| Activity reports | One explicitly selected local report, fixed unverified/no-authority projection, filters, timeline, declared topology and inspector | No live collection, authenticated approval inbox or durable query store | Make offline inspection efficient now; qualify one finite source before continuous telemetry | +| Workflow definitions | Saved structural definitions and revisions with existing editing controls | No qualified executor, deployment controller or durable task supervisor | Keep definition editing separate from runtime actions; preserve the external-runtime adapter direction | +| System coverage | Searchable optional-module reference catalog, comparison and session-only role planning | Catalog entries are not installed adapters, saved assignments or enforceable permissions | Keep unavailable functions explicit; no Connect or Apply action until its native contract is qualified | +| Models and integrations | Bounded advisory and synthetic/source-tested integration seams, with distinct custody boundaries | Mounted real-provider operations, SDK certification, health/reconnect behavior and target readback remain separate work | Finish one target-load/readback proof; do not make broad integration coverage a local-workbench gate | + +The management layer is useful for local content and recovery, but it is not yet a live infrastructure-management product. Preserve that distinction in navigation and copy. An operator's most valuable next step is a qualified constrained target handoff with effective configuration readback, after a separately bounded personal package/recovery rehearsal. Future live sessions require explicit consent, source identity, duration, cancellation/drain, gap/backpressure and reconnect contracts. + +The current activity-report increment uses the existing native DTO without adding a schema or authority field. Producer inventory may include snapshot-prefix-only producers beyond the displayed tail. Both record-library and timeline lists display at most 50 records per page, while counts and the inspector retain the full selected window. Filters do not discard selection; an off-page or filtered selection is labeled and can be revealed. Successful replacement resets filters/page; cancel/failure preserves prior inspection; Clear and workspace-lock purge reset filters and paging. Local filtering, selection, paging and view switching perform no native read. + +Keyboard focus returns to the load action after finite selection, to the page status after paging/reveal, and to the event-number field after Clear filters. Existing decision disclosure state remains preserved across same-route renders. The new controls retain the shared shell, library/working-area/inspector hierarchy, theme tokens and 44 CSS-pixel targets. No animation, framework or dependency is added. Maximum-window DOM reduction is not live throughput qualification; the 1,024-event input bound and existing native validation remain unchanged. Topology rendering and very large relationship detail lists still warrant separate profiling if actual usage exposes a bottleneck. + + +## BF-1 agent-file workbench — October 26, 2026 + +Authority: Jeff's bulk agent-file/UI-overhaul request and [accepted BF-1 intent](intent.md#bf-1-bulk-agent-file-workbench--october-26-2026). The overhaul starts with real file inspection rather than another fleet/demo surface. `#files` is the first Workbench navigation item; Import sources and Skills retain their distinct source-intake and derived-skill editing responsibilities. Existing grouped navigation, current theme, compact technical disclosures and editor/composition/export workflows remain. + +The common view contains a compact task header, search and type/finding facets, paged source rows, local marks and one-file inspector. Native multi-file selection reads at most 32 explicit Markdown files, retaining at most 4 MiB of original content. Each refused item stays visible; count overflow refuses before reading. Once the retained budget is exhausted, further files are not read. One bounded single-file report may have been read and discarded at the overflow boundary. No paths, repository tree or inferred project hierarchy are fabricated. Different selected occurrences retain distinct selection indices even when source names/digests match. + +Existing saved-source metadata is reused from the ordinary scoped startup read, avoiding an extra inventory request. Explicit Reload reads the saved inventory; selected saved checks use the existing non-retaining source-read command and never replace the native source-analysis selection. Query/filter/marks/page/disclosures perform no native operation. Saved checks are sequential and cancellation stops after the current callback drains. Workspace closure clears new controller state/DOM and ignores late results. Only one saved source's full report is retained for inspection; bulk results otherwise keep bounded findings/metadata. Selected unsaved content is frozen as view data and stays in memory, not a new database/tag store. Freezing does not authenticate bytes or erase memory copies. + +The small local rule pack `rangoon.agent-file-checks.v1` reports empty content, possible private-key markers, download-to-shell text patterns and native parser notes. Findings carry rule IDs/version, line context and exact source identity/digest in the inspector. They are advisory review hints, including possible examples/false positives, not defects, trust, approval, permissions or target-loaded-state evidence. Old dates, model names and unfamiliar methods never become outdated claims. Compatibility stays Not assessed until a later versioned primary-evidence catalog can resolve relevant project/target versions. No model, provider, telemetry upload or execution is invoked. + +Normal controls expose Choose files, Reload saved, local marks and bounded checking. Inspection limits and exact IDs/digests are native closed disclosures. Selecting an item opens its inspector; stacked layouts focus/reveal it and Back to files returns to the library. Local list scroll, filter caret, same-record details and current selection survive matching rerenders; paging/filter changes reset the list appropriately. Read failure/cancel preserves prior results; an entirely unread replacement cannot discard the prior selected-file inspection. A partial successful new selection explicitly replaces temporary selected-file results while preserving per-item refusals. Original files never change. Import remains the existing one-file native save path; the import-workbench action does not pretend to save a marked batch. + +The source list is capped at 50 rendered rows per page and a bounded scroll region, with a separate inspector. At narrow widths, filters use two facets below search, bulk controls reveal progressively and secondary limits stay closed. All actionable controls retain 44px targets, keyboard focus, forced-color borders and reduced-motion behavior. Actual synthetic responsive/interaction evidence, performance measurements, limitations and independent review belong to the [development receipt](development.md#bf-1-bulk-agent-file-workbench--october-26-2026); finite browser fixtures do not qualify a real native picker or normal user files. + +### Dates, revision lineage and metadata + +Jeff's follow-up adds explicit dates, timestamps, revisions and supporting metadata. BF-1 displays native workspace `savedAtMs` separately from local session `selectedAtMs` and `checkedAtMs`. Visible row dates and the activity inspector use local dates with seconds; semantic `