diff --git a/.github/workflows/compilation_tests.yml b/.github/workflows/compilation_tests.yml index a65c1af9..be36564a 100644 --- a/.github/workflows/compilation_tests.yml +++ b/.github/workflows/compilation_tests.yml @@ -85,10 +85,12 @@ jobs: working-directory: impl/rust-cli run: cargo test --verbose - - name: Run ignored tests (stress) - working-directory: impl/rust-cli - run: cargo test --test stress_tests -- --ignored --test-threads=1 - continue-on-error: true # Stress tests may timeout on slow runners + # The ignored stress suite (tests/stress_tests.rs) is not run here. It ran + # under `continue-on-error: true`, which hid its state (Hypatia RE005): + # on 2026-11-16, 5 of its tests fail outright and 2 run for more than two + # minutes each, so this step only ever burned the job's 30-minute timeout. + # Run it by hand with `cargo test --test stress_tests -- --ignored` until + # the suite is repaired and can gate honestly. # ============================================================ # MSRV (Minimum Supported Rust Version) diff --git a/.github/workflows/governance.yml b/.github/workflows/governance.yml index 0469eb04..54d061cf 100644 --- a/.github/workflows/governance.yml +++ b/.github/workflows/governance.yml @@ -1,9 +1,9 @@ # SPDX-License-Identifier: MPL-2.0 # governance.yml — single wrapper calling the shared estate governance bundle -# in hyperpolymath/standards instead of carrying per-repo copies. +# in metadatastician/standards instead of carrying per-repo copies. # # Replaces the per-repo governance scaffolding removed in the same commit: -# quality.yml, guix-nix-policy.yml, npm-bun-blocker.yml, ts-blocker.yml, +# quality.yml, guix-guix-policy.yml, npm-bun-blocker.yml, ts-blocker.yml, # security-policy.yml, rsr-antipattern.yml, wellknown-enforcement.yml, # workflow-linter.yml # @@ -19,9 +19,8 @@ on: workflow_dispatch: # Estate guardrail: cancel superseded runs so re-pushes / rebased PR -# updates do not pile up queued runs against the shared account-wide -# Actions concurrency pool. Applied only to read-only check workflows -# (no publish/mutation), so cancelling a superseded run is always safe. +# updates don't pile up queued runs. Safe — governance is read-only +# policy linting with no publish or mutation. concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true @@ -32,4 +31,8 @@ permissions: jobs: governance: - uses: hyperpolymath/standards/.github/workflows/governance-reusable.yml@092dedada188f56c5915f74a5fd40aac093742c3 # standards main 2026-06-01 + # Pinned to a SHA (not @main) per the estate supply-chain policy — + # matches the sibling repos' pin (e.g. ochrance-framework). Bump + # deliberately, never float: an unpinned reusable workflow is an + # unpinned trust boundary. mirror.yml / scorecard.yml already pin. + uses: metadatastician/standards/.github/workflows/governance-reusable.yml@ba640e9a57f22608710ffecdca282074eac55a0b diff --git a/.github/workflows/hypatia-scan.yml b/.github/workflows/hypatia-scan.yml index 2e60958f..31da23c2 100644 --- a/.github/workflows/hypatia-scan.yml +++ b/.github/workflows/hypatia-scan.yml @@ -47,6 +47,16 @@ jobs: timeout-minutes: 30 steps: + # Hypatia RE001: the scan job holds GITHUB_TOKEN and the fleet PAT next + # to fetched code (the Hypatia and gitbot-fleet clones, the mix build). + # Audit mode records every outbound connection without blocking; the + # job's endpoints (hex.pm, GitHub, the Elixir builds) are too many to + # enumerate safely as a block list here. + - name: Monitor outbound requests (audit) + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6.0.2 with: diff --git a/.github/workflows/instant-sync.yml b/.github/workflows/instant-sync.yml index 21b45e77..29251c33 100644 --- a/.github/workflows/instant-sync.yml +++ b/.github/workflows/instant-sync.yml @@ -19,6 +19,15 @@ jobs: env: FARM_DISPATCH_TOKEN: ${{ secrets.FARM_DISPATCH_TOKEN }} steps: + # Hypatia RE001: this job holds FARM_DISPATCH_TOKEN, so outbound + # traffic is limited to the GitHub API that repository-dispatch calls. + - name: Restrict outbound requests before using the dispatch token + if: ${{ env.FARM_DISPATCH_TOKEN != '' }} + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: block + allowed-endpoints: >- + api.github.com:443 - name: Trigger Propagation if: ${{ env.FARM_DISPATCH_TOKEN != '' }} uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v3 diff --git a/.github/workflows/label-triage.yml b/.github/workflows/label-triage.yml index 9886e920..32422544 100644 --- a/.github/workflows/label-triage.yml +++ b/.github/workflows/label-triage.yml @@ -45,11 +45,12 @@ permissions: jobs: triage: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 10 # Hypatia workflow_audit/missing_timeout_minutes (alert #68) steps: - name: Classify and label env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_TOKEN: ${{ github.token }} NUM: ${{ github.event.issue.number || inputs.issue }} run: | set -uo pipefail diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml index c80b676c..d853acc5 100644 --- a/.github/workflows/labels.yml +++ b/.github/workflows/labels.yml @@ -31,11 +31,12 @@ permissions: jobs: sync: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 10 # Hypatia workflow_audit/missing_timeout_minutes (alert #69) steps: - name: Apply canonical labels env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_TOKEN: ${{ github.token }} # ⚠ LOAD-BEARING. This workflow deliberately does not check the repo # out (no `uses:`, so no actions.lock entry can drift), which means # `gh label create` / `gh label edit` have no git remote to infer a diff --git a/.github/workflows/mirror.yml b/.github/workflows/mirror.yml index b52a8981..d7102959 100644 --- a/.github/workflows/mirror.yml +++ b/.github/workflows/mirror.yml @@ -1,13 +1,25 @@ # SPDX-License-Identifier: MPL-2.0 name: Mirror to Git Forges + on: push: branches: [main] workflow_dispatch: + permissions: actions: read contents: read + jobs: mirror: - uses: hyperpolymath/standards/.github/workflows/mirror-reusable.yml@092dedada188f56c5915f74a5fd40aac093742c3 - secrets: inherit + uses: metadatastician/standards/.github/workflows/mirror-reusable.yml@75bd5994470661a099df562d6d5ad2fe744dbd66 + # Explicit secrets map, not `secrets: inherit` (Hypatia WH008): the callee + # (standards@75bd5994) declares exactly these seven, all optional. + secrets: + GITLAB_SSH_KEY: ${{ secrets.GITLAB_SSH_KEY }} + BITBUCKET_SSH_KEY: ${{ secrets.BITBUCKET_SSH_KEY }} + CODEBERG_SSH_KEY: ${{ secrets.CODEBERG_SSH_KEY }} + SOURCEHUT_SSH_KEY: ${{ secrets.SOURCEHUT_SSH_KEY }} + DISROOT_SSH_KEY: ${{ secrets.DISROOT_SSH_KEY }} + GITEA_SSH_KEY: ${{ secrets.GITEA_SSH_KEY }} + RADICLE_KEY: ${{ secrets.RADICLE_KEY }} diff --git a/.github/workflows/push-email-notify.yml b/.github/workflows/push-email-notify.yml index 1d4d92f1..c960374d 100644 --- a/.github/workflows/push-email-notify.yml +++ b/.github/workflows/push-email-notify.yml @@ -38,8 +38,18 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: + - name: Restrict outbound requests before supplying SMTP credentials + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: block + # The pinned action downloads its checksum-verified release binary, + # then connects only to the configured implicit-TLS SMTP endpoint. + allowed-endpoints: >- + github.com:443 + release-assets.githubusercontent.com:443 + ${{ secrets.SMTP_HOST }}:${{ secrets.SMTP_PORT || '465' }} - name: Send push notification email - uses: hyperpolymath/smtp-notify-action@c1c9fa07992a02c1fd3d67a0dc1b08cccb852aef # v0.5.0 + uses: hyperpolymath/smtp-notify-action@e384daf6167a7a7567642d6a62060106244d2413 # v0.5.1 with: server_address: ${{ secrets.SMTP_HOST }} server_port: ${{ secrets.SMTP_PORT }} diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 708106a3..a4ace4ef 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -3,6 +3,7 @@ name: Scorecards supply-chain security on: branch_protection_rule: + workflow_dispatch: schedule: - cron: '23 4 * * 1' @@ -12,13 +13,19 @@ permissions: jobs: analysis: - # Explicit least-privilege permissions for the OSSF Scorecard reusable - # workflow (the documented set), instead of relying on a broad - # workflow-level `read-all`: + # Manual refreshes measure the merged default branch. Keep the OIDC-bearing + # publication job off manually selected feature branches. + if: github.event_name != 'workflow_dispatch' || github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + # Caller-granted permissions per the scorecard-reusable contract + # (its header documents: the caller MUST grant security-events:write + # + id-token:write; contents:read lets it read the repo). Closes the + # Hypatia `scorecard_wrapper_missing_job_permissions` finding. + # actions: read is repeated here: this job-level block replaces the + # workflow-level one, and the callee's job requests actions: read. + # The callee declares no secrets, so no `secrets:` line. permissions: - contents: read # read the repository - actions: read # inspect workflow runs (Token-Permissions, etc.) - security-events: write # upload results to the code-scanning dashboard - id-token: write # OIDC, to publish results / badge - uses: hyperpolymath/standards/.github/workflows/scorecard-reusable.yml@092dedada188f56c5915f74a5fd40aac093742c3 - secrets: inherit + actions: read + contents: read + security-events: write + id-token: write + uses: metadatastician/standards/.github/workflows/scorecard-reusable.yml@ba640e9a57f22608710ffecdca282074eac55a0b diff --git a/.github/workflows/secret-scanner.yml b/.github/workflows/secret-scanner.yml index 7016307f..c3027f7a 100644 --- a/.github/workflows/secret-scanner.yml +++ b/.github/workflows/secret-scanner.yml @@ -1,18 +1,20 @@ # SPDX-License-Identifier: MPL-2.0 name: Secret Scanner + on: pull_request: push: branches: [main] + concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true + permissions: - actions: read contents: read + jobs: scan: permissions: contents: read - uses: hyperpolymath/standards/.github/workflows/secret-scanner-reusable.yml@092dedada188f56c5915f74a5fd40aac093742c3 - secrets: inherit + uses: metadatastician/standards/.github/workflows/secret-scanner-reusable.yml@75bd5994470661a099df562d6d5ad2fe744dbd66 diff --git a/.machine_readable/contractiles/Justfile b/.machine_readable/contractiles/Justfile index 65bafc27..3ab4c47c 100644 --- a/.machine_readable/contractiles/Justfile +++ b/.machine_readable/contractiles/Justfile @@ -120,7 +120,10 @@ build-elixir: # Build ReScript MCP server build-mcp: @echo "Building ReScript MCP server..." - cd impl/mcp && npx rescript build + # bunx --no-install never fetches an unpinned package: it uses a locally + # installed rescript or fails. impl/mcp has no package manifest yet; it is + # due to be ported to AffineScript (see .hypatia-ignore). + cd impl/mcp && bunx --no-install --bun rescript build @echo "✓ MCP server compiled" # Run MCP server (STDIO mode for Claude Desktop) diff --git a/FAQ.adoc b/FAQ.adoc index 9bb9045a..96fb1662 100644 --- a/FAQ.adoc +++ b/FAQ.adoc @@ -93,8 +93,9 @@ What is solid: * The machine-checked proofs of the model-layer operations (Agda (theory source), Lean 4 and Rocq/Coq (rechecks), Z3 (supplementary); Isabelle/HOL and Mizar archived unchecked). ~478 theorem candidates in the 2026-06-01 census; 0 real gaps (Coq `obliterate_overwrites_all_blocks` CLOSED, re-verified - 2026-07-16 via `Print Assumptions` under Coq 8.18.0) + 2 documented axioms - (1 justified decidability + 1 structural funext). + 2026-07-16 via `Print Assumptions` under Coq 8.18.0); 1 justified classical + dependency remains (Coq `is_empty_dir_dec`, a theorem proved with classical + logic, not a custom axiom). The Agda `funext` postulate was removed 2026-11-09. * The Rust CLI. 736 tests passing, 0 failures, 7 fuzz targets, working shell surface (pipelines, redirections, here-docs, job control, variables, control structures, glob, quoting). diff --git a/Justfile b/Justfile index 416df94e..fd9e5bf4 100644 --- a/Justfile +++ b/Justfile @@ -155,7 +155,10 @@ build-elixir: # Build ReScript MCP server build-mcp: @echo "Building ReScript MCP server..." - cd impl/mcp && npx rescript build + # bunx --no-install never fetches an unpinned package: it uses a locally + # installed rescript or fails. impl/mcp has no package manifest yet; it is + # due to be ported to AffineScript (see .hypatia-ignore). + cd impl/mcp && bunx --no-install --bun rescript build @echo "✓ MCP server compiled" # Run MCP server (STDIO mode for Claude Desktop) diff --git a/README.adoc b/README.adoc index ad383ae8..4211432f 100644 --- a/README.adoc +++ b/README.adoc @@ -622,7 +622,7 @@ See link:LICENSE[LICENSE] for full text. **Made with ❤️ by humans and AI, for humans who value formal correctness.** -**Status**: Advanced Research Prototype (v0.9.0) | **RSR**: PLATINUM (105/100) | **Proofs**: ~478 theorem candidates (0 real gaps; 2 justified axioms) | **Tests**: 791 passing +**Status**: Advanced Research Prototype (v0.9.0) | **RSR**: PLATINUM (105/100) | **Proofs**: ~478 theorem candidates (0 real gaps; 1 justified classical dependency) | **Tests**: 791 passing [.text-center] _"Every operation reversible. Every claim proven. Every contributor valued."_ diff --git a/TOPOLOGY.adoc b/TOPOLOGY.adoc index 5ae26754..1286d8a8 100644 --- a/TOPOLOGY.adoc +++ b/TOPOLOGY.adoc @@ -21,15 +21,15 @@ Copyright (c) Jonathan D.A. Jewell j.d.a.jewell@open.ac.uk │ │ ▼ ▼ ┌───────────────────────┐ ┌────────────────────────────────┐ - │ FORMAL PROOFS (6 SYS) │ │ IMPLEMENTATION LAYER │ - │ - Lean 4 (primary) │ │ - Zig FFI (builds, unlinked) │ - │ - Coq (CIC) │ │ - Rust FFI (preconditions) │ - │ - Agda (ITT) │ │ - libc direct (chown/getpw*) │ - │ - Isabelle/HOL │ │ - Audit Logging (MAA) │ - │ - Mizar (set theory) │ └──────────┬─────────────────────┘ - │ - Z3 (SMT) │ │ - │ ~250+ theorems │ │ - │ 4 gaps, 4 axioms │ │ + │ FORMAL PROOFS │ │ IMPLEMENTATION LAYER │ + │ - Agda (source) │ │ - Zig FFI (builds, unlinked) │ + │ - Lean 4 (recheck) │ │ - Rust FFI (preconditions) │ + │ - Coq (recheck) │ │ - libc direct (chown/getpw*) │ + │ - Z3 (SMT, ASSUMED) │ │ - Audit Logging (MAA) │ + │ Isabelle, Mizar: │ └──────────┬─────────────────────┘ + │ archived, unchecked │ │ + │ see proof ledger │ │ + │ 0 Agda postulates │ │ └──────────┬────────────┘ │ │ │ └────────────┬─────────────┘ diff --git a/docs/THEORY-FEED.adoc b/docs/THEORY-FEED.adoc index f799fcb5..913d0a07 100644 --- a/docs/THEORY-FEED.adoc +++ b/docs/THEORY-FEED.adoc @@ -144,7 +144,7 @@ Priority reflects two things: how directly the item unblocks a named valence-she ** This is an owner decision because it moves a dependency edge between repos. Record the ruling in nextgen-typing#118. . *NW-2: ECHIDNA tri-state verdict plus project context* (echidna, valence-shell#162). Two independent defects combine to report 15 known-good proofs "invalid": ** *valence-shell side:* `scripts/validate-with-echidna.sh:77` invokes `echidna verify --prover

--timeout 120 --format ` with no `--library` or project root. echidna's verify already accepts `library: Vec`. Pass `_CoqProject`, `lakefile.lean` and the `.agda-lib` roots. -** *echidna side:* `src/rust/main.rs` ~L590–631 collapses the result to a bool and prints "✗ Proof is invalid" then `exit(1)`, so an environment failure is indistinguishable from a refutation. Return `Valid | Invalid | EnvironmentError`, with distinct exit codes. +** *echidna side:* `echidna/src/rust/main.rs` ~L590–631 collapses the result to a bool and prints "✗ Proof is invalid" then `exit(1)`, so an environment failure is indistinguishable from a refutation. Return `Valid | Invalid | EnvironmentError`, with distinct exit codes. ** Estate benefit: every ECHIDNA consumer stops reading a missing import path as a disproof. . *NW-3: First real echo-types import* (echo-types, valence-shell#51). The smallest first step already named in #51: import `EchoObservationalEquivalence` into `proofs/agda/FilesystemEquivalence.agda` and restate `fsEquiv` as `_≡m_`. Then map the remaining pairs: ** `obliterate_not_injective` → `EchoLossTaxonomy.const-fibre-↔-domain` diff --git a/docs/audits/2026-11-01-assurance-boundary-audit.adoc b/docs/audits/2026-11-01-assurance-boundary-audit.adoc index f96388a5..b4c93deb 100644 --- a/docs/audits/2026-11-01-assurance-boundary-audit.adoc +++ b/docs/audits/2026-11-01-assurance-boundary-audit.adoc @@ -368,7 +368,7 @@ provers said, and what that does and does not license. |=== | Tool | Available | Version used | How it was obtained -| Agda | yes | 2.7.0.1 and 2.6.4.3 | PyPI wheel; the wheel ships no `data/lib`, so `src/data/lib` was copied from the matching Agda source tarball +| Agda | yes | 2.7.0.1 and 2.6.4.3 | PyPI wheel; the wheel ships no `data/lib`, so `agda-2.7.0.1/src/data/lib` was copied from the matching Agda source tarball | agda-stdlib | yes | 2.2 and 2.1.1 | codeload tarball from `agda/agda-stdlib` | Z3 | yes | z3-solver 5.3.3 | PyPI wheel | Rust / Cargo / rustup | no | — | `static.rust-lang.org` is not reachable; a `rustup` wheel from PyPI installs the toolchain *manager*, which then fails to download any toolchain (`tls handshake eof`) diff --git a/docs/audits/2026-11-16-hypatia-remediation.adoc b/docs/audits/2026-11-16-hypatia-remediation.adoc new file mode 100644 index 00000000..dec3dd02 --- /dev/null +++ b/docs/audits/2026-11-16-hypatia-remediation.adoc @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: MPL-2.0 += Hypatia remediation and Secret Scanner repair +:revdate: 2026-11-16 +:toc: macro + +Record of the 2026-11-16 pass over the Hypatia scan of +`claude/laughing-hawking-pibzji` (`fe8ded7`, CI run 43970213345, artifact +`hypatia-findings`) and of why the Secret Scanner never produced a result. + +toc::[] + +== Secret Scanner (gitleaks): why every run failed + +All 595 runs of `.github/workflows/secret-scanner.yml` ended in failure with no +jobs (a startup failure, so no check run appeared). `governance.yml`, +`mirror.yml` and `scorecard.yml` called reusable workflows the same way. + +* All four called `hyperpolymath/standards/.github/workflows/*-reusable.yml@092deda`. + The standards repository now lives at `metadatastician/standards`; + `git ls-remote` returns the same `HEAD` for both names. +* `hyperpolymath/echo-types` calls the same reusables as + `metadatastician/standards/...@75bd599` (secret scanner, mirror) and + `@ba640e9` (governance, scorecard). Its Secret Scanner runs pass, for + example run 43967735914 on 2026-11-16. +* Fix: the four wrappers are now the echo-types versions, with the + `metadatastician/standards` paths and pins. The same change removes + `secrets: inherit` (Hypatia WH008): the secret scanner needs only + `contents: read`, mirror passes its seven named keys, and scorecard + declares no secrets. + +The root cause (moved repository versus pinned `uses:` paths) is inferred from +the echo-types comparison; the repository's Actions policy page was not +readable from this session. The first CI run on this change confirms or +refutes it. + +== Hypatia findings + +Of 98 findings, 48 are code-scanning meta-alerts (CSA001 "alert open", +CSA003 "alert overdue", CSA002 "25 alerts open") that restate the other 50. +They close when the underlying alert closes. + +[cols="2,1,4",options="header"] +|=== +| Rule (count) | Disposition | Detail + +| `secret_detected` (critical) | allowed | `secure_erase.rs`: "Eins" is the temporary ATA password from the ata.wiki.kernel.org Secure Erase guide, now a documented `ATA_TEMP_PASSWORD` const. It is deliberately well known so a drive locked by an interrupted erase can be unlocked; it protects nothing. +| `believe_me` (critical) | allowed after experiment | See <>. +| `from_raw` | fixed | `external.rs`: the here-doc/here-string pipe uses `std::io::pipe()` (Rust 1.87; MSRV 1.88). No raw descriptors, no `unsafe`. +| `as_ptr` (3) | fixed | `chown` uses `std::os::unix::fs::chown` (Rust 1.73) in the CLI, its two undo paths and `ffi/rust`; `mkfifo` uses `nix::unistd::mkfifo`. +| `unsafe_block` | fixed | `getpwnam`/`getgrnam` dereferences replaced by `nix` `User::from_name`/`Group::from_name` (reentrant); the job-control syscalls each carry a `SAFETY:` comment. +| `expect_in_hot_path` (4) | fixed | Pipeline, brace and parameter-expansion invariants are now `let ... else`, `ok_or_else` or a `match`. `arith.rs` was a method named `expect`, renamed `expect_token`. +| `unwrap_without_check` (3) | fixed | `test_command.rs` compares `args.last()` as an `Option`; the fuzz targets return on a non-UTF-8 temp path. +| `zig_ptr_cast`, `zig_align_cast` | fixed or allowed | `lib.zig`: ten handle casts collapse into `toHandle`/`fromHandle`, the only two casts across the C boundary, each annotated. `daemon_client.zig`: the `sockaddr_un` to `sockaddr` cast is the sockets ABI, annotated. `lean_wrapper.zig`: `leanStrToCStr` was unused and documented "caller must free" for a pointer Lean owns, so it was deleted. +| `shell_download_then_run`, `download_then_run_shell` (setup.sh) | fixed | The `curl \| bash` fallback for `just` is replaced by `cargo install --locked just`, or a clear failure. +| `eval_in_shell` (2) | fixed | `verify-proofs.sh` runs each check as an argument vector from a named directory. +| `npx_in_workflow` (2) | fixed | `bunx --no-install --bun rescript build`, which never fetches an unpinned package. +| `missing_timeout_minutes`, WH006 | fixed | `labels.yml`, `label-triage.yml` (echo-types versions). +| RE001 (3) | fixed | `harden-runner`: `block` to `api.github.com` in `instant-sync.yml`, `block` to the SMTP endpoint in `push-email-notify.yml`, `audit` in `hypatia-scan.yml`. +| RE005 | fixed | The ignored stress suite no longer runs under `continue-on-error` in `compilation_tests.yml`; see <>. +| WH008 (3) | fixed | See the Secret Scanner section. +| SD022 (2) | fixed | Both paths named another tree (`echidna/src/rust/`, the Agda tarball's `src/data/lib`); now qualified. +| SD009 | left for the owner | `ffi/zig/src/main.zig` has no SPDX header. Licence edits are owner-only (estate doctrine 6). +| SD004 (6), SD007 | left for the owner | Moving `.machine_readable/6a2/` into deed clauses needs the estate converter (kyX, standards D312/D313); writing the clauses by hand would guess at metadata. +| `known_fake_action_sha` (3), `download_then_run_shell` (1) in `alkahest-shell-transmuter/` | left for upstream | Owner ruling: fix the canonical alkahest repository, then re-sync this copy. These workflows never run here. +|=== + +[[idris]] +== Idris2 `believe_me`: experiment + +Goal: prove `(s : String) -> (s == s) = True` without an axiom. + +* Direct `Refl` fails under Idris2 0.8.0: "Can't solve constraint between: + True and intToBool (prim__eq_String s s)". The primitive does not reduce + on a variable. +* Going through `decEq s s` fails with the same constraint. Idris2's own + `DecEq String` (`libs/base/Decidable/Equality.idr`, `primitiveEq`) is + itself `believe_me`, so routing through it would move the axiom into the + standard library, out of the scanner's sight, without removing it. +* Removing it for real means changing path components from `String` to a type + with structural equality, which changes the ABI-facing model. + +Outcome: `axStringEqRefl` and `axBits8EqRefl` stay as the two registered +axioms (`.machine_readable/IDRIS2_AXIOMS.a2ml`, gated by +`.github/scripts/check-idris2-believe-me.sh`), with an inline Hypatia +allow that names both. The package builds and the gate passes. + +[[stress]] +== Stress suite state + +Run one test at a time on 2026-11-16, 120 s limit each: 5 fail +(`stress_concurrent_multiple_instances`, `stress_deep_nesting_1000_levels`, +`stress_deep_nesting_no_stack_overflow`, `stress_large_file_undo_streaming`, +`stress_undo_redo_efficiency`), 2 exceed the limit +(`stress_many_operations_10000`, `stress_resource_limits_max_history`), 3 pass; +`stress_large_file_1gb` was not run. The CI step only ever reached the +30-minute job timeout. Repairing the suite is separate work. diff --git a/docs/wiki/For-Developers.md b/docs/wiki/For-Developers.md index ec7d3ed2..32e6c30f 100644 --- a/docs/wiki/For-Developers.md +++ b/docs/wiki/For-Developers.md @@ -47,28 +47,32 @@ just build-lean4 # or one at a time: coq / agda / isabelle / mizar / z3 Run the ignored slow/stress tests explicitly with `cargo test -- --ignored`. -## The six proof systems (and why six) +## The proof systems and their roles -Each system sits on a different logical foundation, so a modelling error in one -is unlikely to be replicated in all. If all six prove the same theorem, confidence -is very high — the seL4/CompCert pattern. +Agda is the theory source of truth (owner ruling 2026-11-09, under standards +`3-practice/PROOF-POLICY.adoc`). Lean 4 and Coq are recheck legs: their proofs +build, but their statements have not yet been compared one by one with the +Agda source, so they are target-only evidence until that comparison is done. +Isabelle/HOL and Mizar were archived unchecked on 2026-11-09 +(`archive/proofs/`) and are not current evidence. | System | Foundation | Role | |--------|-----------|------| -| Lean 4 | Dependent type theory | Primary source of truth | -| Coq | Calculus of Inductive Constructions | Extraction path to OCaml | -| Agda | Intensional type theory | Cross-validation | -| Isabelle/HOL | Higher-order logic | Cross-validation | -| Mizar | Tarski–Grothendieck set theory | Set-theoretic foundation | -| Z3 SMT | First-order logic + theories | Automated decision procedures | +| Agda | Intensional type theory | Theory source of truth (`--safe --without-K --cubical-compatible`) | +| Lean 4 | Dependent type theory | Recheck leg; executable model oracle | +| Coq | Calculus of Inductive Constructions | Recheck leg; extraction path to OCaml | +| Z3 SMT | First-order logic + theories | Solver checks (PROOF-POLICY §5 `ASSUMED`) | +| Isabelle/HOL | Higher-order logic | Archived, unchecked | +| Mizar | Tarski–Grothendieck set theory | Archived, unchecked | **Read the honest status first:** the project maintains a single source of truth for open proof holes — [`docs/PROOF_HOLES_AUDIT.adoc`](https://github.com/hyperpolymath/valence-shell/blob/main/docs/PROOF_HOLES_AUDIT.adoc). As of this writing: **0 real gaps** (the former Coq `obliterate_overwrites_all_blocks` gap is CLOSED — re-verified 2026-07-16 via `Print Assumptions` as *Closed under -the global context* under Coq 8.18.0), plus 2 documented axioms: 1 justified -decidability axiom (`is_empty_dir_dec`) and 1 structural `funext` axiom (Agda). +the global context* under Coq 8.18.0), plus 1 justified classical dependency +(Coq `is_empty_dir_dec`, a theorem proved with classical logic, not a custom +axiom). The Agda `funext` postulate was removed 2026-11-09. The Idris2 ABI layer is **hole-free** (closed under `--total`) with 2 registered primitive-equality axioms gated by CI. diff --git a/ffi/rust/src/operations.rs b/ffi/rust/src/operations.rs index 1e52ba0d..08dae222 100644 --- a/ffi/rust/src/operations.rs +++ b/ffi/rust/src/operations.rs @@ -259,26 +259,14 @@ pub fn chmod(path: &Path, mode: u32) -> FfiResult<()> { /// Change file ownership (Unix) #[cfg(unix)] pub fn chown(path: &Path, uid: Option, gid: Option) -> FfiResult<()> { - use std::os::unix::ffi::OsStrExt; - if !path.exists() { return Err(FfiError::Posix(PosixError::Enoent)); } - let path_cstr = std::ffi::CString::new(path.as_os_str().as_bytes()) - .map_err(|_| FfiError::InvalidPath("Path contains null byte".to_string()))?; - - let uid = uid.map(|u| u as libc::uid_t).unwrap_or(u32::MAX as libc::uid_t); - let gid = gid.map(|g| g as libc::gid_t).unwrap_or(u32::MAX as libc::gid_t); - - // SAFETY: `path_cstr` is a valid, NUL-terminated `CString` that outlives - // this call, so `as_ptr()` is a live pointer for the call's duration; - // `uid`/`gid` are plain integers. `chown` only borrows the pointer and - // returns a status code we check below. - let result = unsafe { libc::chown(path_cstr.as_ptr(), uid, gid) }; - - if result != 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + // `std::os::unix::fs::chown` (stable since Rust 1.73) passes `None` as + // `(uid_t)-1`, "leave unchanged", exactly as the raw call did. + if let Err(e) = std::os::unix::fs::chown(path, uid, gid) { + let errno = e.raw_os_error().unwrap_or(0); return Err(FfiError::Posix(PosixError::from_errno(errno))); } diff --git a/ffi/rust/src/verification.rs b/ffi/rust/src/verification.rs index 7f2747b7..bd1be43a 100644 --- a/ffi/rust/src/verification.rs +++ b/ffi/rust/src/verification.rs @@ -19,8 +19,8 @@ //! //! | Theorem | Coq | Lean4 | Agda | Z3 | //! |---------|-----|-------|------|----| -//! | mkdir_rmdir_reversible | ✓ | ✓ | ✓ | ✓ | -//! | create_delete_reversible | ✓ | ✓ | ✓ | ✓ | +//! | mkdir_rmdir_reversible | ✓ | ✓ | ✓ | Q | +//! | create_delete_reversible | ✓ | ✓ | ✓ | Q | //! | write_file_reversible | ✓ | ✗ | ✓ | — | //! | copy_preserves_source | ✓ | ✗ | ✓ | A | //! | move_reversible | ✓ | ✗ | ✓ | A | @@ -29,8 +29,10 @@ //! ✓: the proof builds in that system (the Lean and Coq statements are not yet //! compared one by one with the Agda source). ✗: the Lean library //! (`FileContentOperations`, `CopyMoveOperations`, `RMOOperations`) does not -//! build on the pinned toolchain, so CI does not check it. A: the Z3 query runs -//! over asserted axioms (PROOF-POLICY §5 `ASSUMED`). —: no Z3 encoding. +//! build on the pinned toolchain, so CI does not check it. Q: the Z3 query passes +//! over a definitional encoding; a solver result is not a proof certificate +//! (PROOF-POLICY §5 `ASSUMED`). A: the Z3 query runs over asserted axioms +//! (also `ASSUMED`). —: no Z3 encoding. //! Per-obligation status: `EXPLAINME.adoc#proof-ledger`. use crate::{FfiConfig, FfiContext, FfiResult}; diff --git a/impl/rust-cli/fuzz/fuzz_targets/fuzz_path_operations.rs b/impl/rust-cli/fuzz/fuzz_targets/fuzz_path_operations.rs index 459865b0..51a8294c 100644 --- a/impl/rust-cli/fuzz/fuzz_targets/fuzz_path_operations.rs +++ b/impl/rust-cli/fuzz/fuzz_targets/fuzz_path_operations.rs @@ -35,7 +35,11 @@ fuzz_target!(|data: &[u8]| { Err(_) => return, }; - let mut state = match ShellState::new(temp.path().to_str().unwrap()) { + let Some(root) = temp.path().to_str() else { + return; + }; + + let mut state = match ShellState::new(root) { Ok(s) => s, Err(_) => return, }; diff --git a/impl/rust-cli/fuzz/fuzz_targets/fuzz_state_machine.rs b/impl/rust-cli/fuzz/fuzz_targets/fuzz_state_machine.rs index eb1c71de..33511a38 100644 --- a/impl/rust-cli/fuzz/fuzz_targets/fuzz_state_machine.rs +++ b/impl/rust-cli/fuzz/fuzz_targets/fuzz_state_machine.rs @@ -51,7 +51,11 @@ fuzz_target!(|data: &[u8]| { Err(_) => return, }; - let mut state = match ShellState::new(temp.path().to_str().unwrap()) { + let Some(root) = temp.path().to_str() else { + return; + }; + + let mut state = match ShellState::new(root) { Ok(s) => s, Err(_) => return, }; diff --git a/impl/rust-cli/src/arith.rs b/impl/rust-cli/src/arith.rs index b2a6a21e..875f83d0 100644 --- a/impl/rust-cli/src/arith.rs +++ b/impl/rust-cli/src/arith.rs @@ -334,7 +334,7 @@ impl Parser { } } - fn expect(&mut self, expected: Token) -> Result<()> { + fn expect_token(&mut self, expected: Token) -> Result<()> { let token = self.advance().clone(); if token == expected { Ok(()) @@ -559,7 +559,7 @@ impl Parser { Token::LeftParen => { let expr = self.parse_or()?; - self.expect(Token::RightParen)?; + self.expect_token(Token::RightParen)?; Ok(expr) } diff --git a/impl/rust-cli/src/commands.rs b/impl/rust-cli/src/commands.rs index 406bec8a..4f91625d 100644 --- a/impl/rust-cli/src/commands.rs +++ b/impl/rust-cli/src/commands.rs @@ -717,14 +717,8 @@ pub fn chown(state: &mut ShellState, owner_str: &str, path: &str, verbose: bool) let (new_uid, new_gid) = parse_chown_spec(owner_str, old_uid, old_gid)?; // Apply ownership via libc - let c_path = std::ffi::CString::new(file_path.to_str().context("Invalid path")?) - .context("Path contains null bytes")?; - // SAFETY: c_path is a valid NUL-terminated CString; chown is a POSIX syscall. - let ret = unsafe { libc::chown(c_path.as_ptr(), new_uid, new_gid) }; - if ret != 0 { - let err = std::io::Error::last_os_error(); - anyhow::bail!("chown failed: {}", err); - } + std::os::unix::fs::chown(&file_path, Some(new_uid), Some(new_gid)) + .map_err(|e| anyhow::anyhow!("chown failed: {}", e))?; // Record operation with old uid:gid for undo let undo_str = format!("{}:{}", old_uid, old_gid); @@ -758,77 +752,52 @@ pub fn chown(state: &mut ShellState, owner_str: &str, path: &str, verbose: bool) /// Parse chown owner spec: `user`, `user:group`, `:group`, `user:`. /// Returns (uid, gid) where unchanged values keep the original. +/// +/// Each part is a numeric id or a name, resolved with `nix`'s +/// `User::from_name` / `Group::from_name` (the reentrant `getpwnam_r` / +/// `getgrnam_r`), so no raw `passwd`/`group` pointer is dereferenced here. +/// `u32::MAX` is rejected because `chown(2)` reads `(uid_t)-1` as "leave +/// unchanged", not as an id. #[cfg(unix)] fn parse_chown_spec(spec: &str, current_uid: u32, current_gid: u32) -> Result<(u32, u32)> { - if spec.contains(':') { - let parts: Vec<&str> = spec.splitn(2, ':').collect(); - let uid = if parts[0].is_empty() { - current_uid - } else { - parts[0].parse::().unwrap_or_else(|_| { - // Try looking up user by name - match std::ffi::CString::new(parts[0]) { - Ok(c_name) => { - // SAFETY: c_name is a valid NUL-terminated string; getpwnam - // returns a pointer to a static passwd struct or null. - let pw = unsafe { libc::getpwnam(c_name.as_ptr()) }; - if pw.is_null() { - u32::MAX - } else { - unsafe { (*pw).pw_uid } - } - } - Err(_) => u32::MAX, // Name contains null bytes — invalid - } - }) - }; - let gid = if parts[1].is_empty() { - current_gid - } else { - parts[1].parse::().unwrap_or_else(|_| { - match std::ffi::CString::new(parts[1]) { - Ok(c_name) => { - // SAFETY: c_name is a valid NUL-terminated string; getgrnam - // returns a pointer to a static group struct or null. - let gr = unsafe { libc::getgrnam(c_name.as_ptr()) }; - if gr.is_null() { - u32::MAX - } else { - unsafe { (*gr).gr_gid } - } - } - Err(_) => u32::MAX, // Name contains null bytes — invalid - } - }) - }; - if uid == u32::MAX { - anyhow::bail!("chown: invalid user: '{}'", parts[0]); - } - if gid == u32::MAX { - anyhow::bail!("chown: invalid group: '{}'", parts[1]); - } - Ok((uid, gid)) + fn resolve_uid(part: &str) -> Option { + part.parse::().ok().or_else(|| { + nix::unistd::User::from_name(part) + .ok() + .flatten() + .map(|u| u.uid.as_raw()) + }) + } + fn resolve_gid(part: &str) -> Option { + part.parse::().ok().or_else(|| { + nix::unistd::Group::from_name(part) + .ok() + .flatten() + .map(|g| g.gid.as_raw()) + }) + } + + let (user, group) = match spec.split_once(':') { + Some((user, group)) => (user, Some(group)), + None => (spec, None), + }; + + let uid = if user.is_empty() { + current_uid } else { - // Just user — keep group - let uid = spec.parse::().unwrap_or_else(|_| { - match std::ffi::CString::new(spec) { - Ok(c_name) => { - // SAFETY: c_name is a valid NUL-terminated string; getpwnam is POSIX-safe. - let pw = unsafe { libc::getpwnam(c_name.as_ptr()) }; - if pw.is_null() { - u32::MAX - } else { - unsafe { (*pw).pw_uid } - } - } - Err(_) => u32::MAX, - } - }); - if uid == u32::MAX { - anyhow::bail!("chown: invalid user: '{}'", spec); + match resolve_uid(user) { + Some(uid) if uid != u32::MAX => uid, + _ => anyhow::bail!("chown: invalid user: '{}'", user), } - Ok((uid, current_gid)) - } + }; + let gid = match group { + None | Some("") => current_gid, + Some(group) => match resolve_gid(group) { + Some(gid) if gid != u32::MAX => gid, + _ => anyhow::bail!("chown: invalid group: '{}'", group), + }, + }; + Ok((uid, gid)) } /// Undo the last N operations. @@ -997,17 +966,8 @@ pub fn undo(state: &mut ShellState, count: usize, verbose: bool) -> Result<()> { let parts: Vec<&str> = uid_gid_str.splitn(2, ':').collect(); let uid: u32 = parts[0].parse().context("Invalid uid")?; let gid: u32 = parts[1].parse().context("Invalid gid")?; - let c_path = std::ffi::CString::new(path.to_str().context("Invalid path")?) - .context("Path contains null bytes")?; - // SAFETY: `c_path` is a valid, NUL-terminated `CString` that - // outlives the call, so `as_ptr()` is live; `uid`/`gid` are - // plain integers. `chown` only borrows the pointer and - // returns a status code we check below. - let ret = unsafe { libc::chown(c_path.as_ptr(), uid, gid) }; - if ret != 0 { - let err = std::io::Error::last_os_error(); - anyhow::bail!("Undo chown failed: {}", err); - } + std::os::unix::fs::chown(&path, Some(uid), Some(gid)) + .map_err(|e| anyhow::anyhow!("Undo chown failed: {}", e))?; } } OperationType::FileTruncated | OperationType::CopyFile => { @@ -1524,22 +1484,9 @@ pub fn rollback_transaction(state: &mut ShellState) -> Result<()> { { let uid: u32 = parts[0].parse().context("Invalid uid")?; let gid: u32 = parts[1].parse().context("Invalid gid")?; - let c_path = std::ffi::CString::new(path.to_str().unwrap_or("")) - .context("Path contains null bytes")?; - // SAFETY: `c_path` is a valid, NUL-terminated - // `CString` that outlives the call, so `as_ptr()` - // is live; `uid`/`gid` are plain integers. `chown` - // only borrows the pointer and returns a status - // code we check below. - let ret = unsafe { libc::chown(c_path.as_ptr(), uid, gid) }; - if ret != 0 { - Err(anyhow::anyhow!( - "Failed to restore ownership: {}", - std::io::Error::last_os_error() - )) - } else { - Ok(()) - } + std::os::unix::fs::chown(&path, Some(uid), Some(gid)).map_err(|e| { + anyhow::anyhow!("Failed to restore ownership: {}", e) + }) } #[cfg(not(unix))] Ok(()) @@ -1777,15 +1724,16 @@ pub fn fg(state: &mut ShellState, job_spec: Option<&str>) -> Result<()> { { use crate::job::JobState; - // SAFETY: tcsetpgrp/kill/waitpid/getpgrp are POSIX syscalls; pgid is a valid - // process group ID obtained from job control. Negative pgid in kill/waitpid - // targets the entire process group. + // SAFETY: tcsetpgrp takes plain integers (a file descriptor and a + // process group ID obtained from job control); no memory is shared. unsafe { libc::tcsetpgrp(libc::STDIN_FILENO, pgid); } // If job is stopped, send SIGCONT to resume if job_state == JobState::Stopped { + // SAFETY: kill takes plain integers; the negative pgid targets the + // job's whole process group. No memory is shared. unsafe { libc::kill(-pgid, libc::SIGCONT); } @@ -1796,12 +1744,16 @@ pub fn fg(state: &mut ShellState, job_spec: Option<&str>) -> Result<()> { // Wait for job to complete or stop let mut status: i32 = 0; + // SAFETY: `status` is a live, exclusively borrowed i32 for the whole + // call; waitpid writes the child's status into it and nothing else. unsafe { libc::waitpid(-pgid, &mut status, libc::WUNTRACED); } // Return terminal control to shell + // SAFETY: getpgrp takes no arguments and cannot fail (POSIX). let shell_pgid = unsafe { libc::getpgrp() }; + // SAFETY: tcsetpgrp takes plain integers; no memory is shared. unsafe { libc::tcsetpgrp(libc::STDIN_FILENO, shell_pgid); } diff --git a/impl/rust-cli/src/enhanced_repl.rs b/impl/rust-cli/src/enhanced_repl.rs index ae26114a..3bf1f8e8 100644 --- a/impl/rust-cli/src/enhanced_repl.rs +++ b/impl/rust-cli/src/enhanced_repl.rs @@ -410,11 +410,9 @@ fn execute_segments(state: &mut ShellState, input: &str) -> Result { } } } - // Fire any pending signal traps (e.g. trap 'handler' INT). - if executable::run_pending_traps(state) { - return Ok(true); - } - Ok(false) + // Fire any pending signal traps (e.g. trap 'handler' INT); a trap that + // runs `exit` ends the shell. + Ok(executable::run_pending_traps(state)) } fn execute_line(state: &mut ShellState, input: &str) -> Result { diff --git a/impl/rust-cli/src/external.rs b/impl/rust-cli/src/external.rs index 38898f90..4dbc9f94 100644 --- a/impl/rust-cli/src/external.rs +++ b/impl/rust-cli/src/external.rs @@ -157,20 +157,22 @@ pub fn execute_pipeline( let is_last = idx == stages.len() - 1; // Configure stdin - let stdin_cfg = - if is_first { - // First stage: inherit from shell - Stdio::inherit() - } else { - // Middle/last stages: read from previous stdout. - // Invariant: when idx > 0, the previous iteration spawned a - // non-last child with Stdio::piped() stdout (line below) and - // stored child.stdout into prev_stdout after spawning. So the - // The expect documents the loop invariant described above. - Stdio::from(prev_stdout.take().expect( - "prev_stdout invariant: previous non-last stage stored its piped stdout", - )) - }; + let stdin_cfg = if is_first { + // First stage: inherit from shell + Stdio::inherit() + } else { + // Middle/last stages: read from previous stdout. + // When idx > 0, the previous iteration spawned a non-last + // child with Stdio::piped() stdout and stored it in + // prev_stdout, so this is always Some. A broken invariant is + // reported as an error rather than a panic. + prev_stdout.take().map(Stdio::from).ok_or_else(|| { + anyhow::anyhow!( + "pipeline stage {}: previous stage left no piped stdout", + idx + ) + })? + }; // Configure stdout. Pivot on redirect_setup directly: it is Some // iff redirects is non-empty (constructed above), so matching the @@ -438,22 +440,7 @@ fn stdio_config_from_redirects( // Write heredoc content to a pipe instead of a temp file (avoids // predictable temp path + symlink attacks entirely). - use std::os::unix::io::FromRawFd; - let mut pipe_fds = [0i32; 2]; - // SAFETY: pipe() is a POSIX syscall; pipe_fds is a valid 2-element array. - if unsafe { libc::pipe(pipe_fds.as_mut_ptr()) } != 0 { - anyhow::bail!( - "Failed to create pipe for here document: {}", - std::io::Error::last_os_error() - ); - } - // SAFETY: pipe_fds[1] is a valid file descriptor from pipe(). - let mut write_end = unsafe { File::from_raw_fd(pipe_fds[1]) }; - std::io::Write::write_all(&mut write_end, processed.as_bytes())?; - drop(write_end); // Close write end so reader gets EOF - // SAFETY: pipe_fds[0] is a valid file descriptor from pipe(). - let read_end = unsafe { File::from_raw_fd(pipe_fds[0]) }; - stdin_cfg = Stdio::from(read_end); + stdin_cfg = stdin_from_bytes(processed.as_bytes(), "here document")?; } Redirection::HereString { content, expand } => { @@ -466,22 +453,7 @@ fn stdio_config_from_redirects( }; // Write here string content to a pipe (avoids predictable temp paths). - use std::os::unix::io::FromRawFd; - let mut pipe_fds = [0i32; 2]; - // SAFETY: pipe() is a POSIX syscall; pipe_fds is a valid 2-element array. - if unsafe { libc::pipe(pipe_fds.as_mut_ptr()) } != 0 { - anyhow::bail!( - "Failed to create pipe for here string: {}", - std::io::Error::last_os_error() - ); - } - // SAFETY: pipe_fds[1] is a valid file descriptor from pipe(). - let mut write_end = unsafe { File::from_raw_fd(pipe_fds[1]) }; - std::io::Write::write_all(&mut write_end, processed.as_bytes())?; - drop(write_end); // Close write end so reader gets EOF - // SAFETY: pipe_fds[0] is a valid file descriptor from pipe(). - let read_end = unsafe { File::from_raw_fd(pipe_fds[0]) }; - stdin_cfg = Stdio::from(read_end); + stdin_cfg = stdin_from_bytes(processed.as_bytes(), "here string")?; } } } @@ -489,6 +461,20 @@ fn stdio_config_from_redirects( Ok((stdin_cfg, stdout_cfg, stderr_cfg)) } +/// Feed `content` to a child's stdin through an anonymous pipe. +/// +/// Uses `std::io::pipe` (stable since Rust 1.87), so no raw file +/// descriptors or `unsafe` are involved. The whole content is written before +/// the child starts, as before, so it must fit in the pipe buffer (64 KiB on +/// Linux); larger here-documents would block here. +fn stdin_from_bytes(content: &[u8], what: &str) -> Result { + let (reader, mut writer) = std::io::pipe() + .map_err(|e| anyhow::anyhow!("Failed to create pipe for {}: {}", what, e))?; + std::io::Write::write_all(&mut writer, content)?; + drop(writer); // Close the write end so the reader gets EOF + Ok(Stdio::from(reader)) +} + /// Expand glob patterns in command arguments (Phase 6 M12) /// /// For each argument: diff --git a/impl/rust-cli/src/glob.rs b/impl/rust-cli/src/glob.rs index e078e9e7..0a5ba18d 100644 --- a/impl/rust-cli/src/glob.rs +++ b/impl/rust-cli/src/glob.rs @@ -195,13 +195,14 @@ fn expand_braces_limited(pattern: &str, remaining: usize) -> Vec { brace_depth -= 1; if brace_depth == 0 { // Found matching close brace. - // Invariant: brace_start is Some whenever brace_depth >= 1. - // The only site that increments brace_depth (the `ch == '{'` - // arm above) sets brace_start = Some(i) when brace_depth was - // zero, and only the matched '}' decrements it back. So this - // The expect documents the non-empty split invariant. - let start = - brace_start.expect("brace_start invariant: Some whenever brace_depth >= 1"); + // brace_start is Some whenever brace_depth >= 1: the only site + // that increments brace_depth (the `ch == '{'` arm above) sets + // brace_start = Some(i) when brace_depth was zero, and only the + // matched '}' decrements it back. If that ever broke, the + // pattern is returned unexpanded instead of panicking. + let Some(start) = brace_start else { + return vec![pattern.to_string()]; + }; let prefix = &pattern[..start]; let suffix = &pattern[i + 1..]; let content = &pattern[start + 1..i]; diff --git a/impl/rust-cli/src/parser.rs b/impl/rust-cli/src/parser.rs index 72d58dec..da677ce3 100644 --- a/impl/rust-cli/src/parser.rs +++ b/impl/rust-cli/src/parser.rs @@ -2268,16 +2268,11 @@ fn apply_expansion(expansion: &ParameterExpansion, state: &crate::state::ShellSt ExpansionOp::Default { value, check_null } => { // ${VAR:-default} or ${VAR-default} - if is_unset || (*check_null && is_null) { - // Recursively expand the default value - expand_variables(value, state) - } else { - // var_value is Some by construction here: the surrounding - // `if is_unset || ...` branch is the unset/null path; this - // else branch only fires when var_value is Some. - var_value - .expect("var_value is Some when !is_unset (checked above)") - .to_string() + match var_value { + // Set, and not null when `:-` asks for a null check. + Some(v) if !(*check_null && is_null) => v.to_string(), + // Unset, or null under `:-`: recursively expand the default. + _ => expand_variables(value, state), } } diff --git a/impl/rust-cli/src/process_sub.rs b/impl/rust-cli/src/process_sub.rs index d5a45136..7387952b 100644 --- a/impl/rust-cli/src/process_sub.rs +++ b/impl/rust-cli/src/process_sub.rs @@ -50,30 +50,17 @@ impl ProcessSubstitution { // Create FIFO using mkfifo(2) syscall #[cfg(unix)] { - use std::ffi::CString; - let path_str = fifo_path.to_str().ok_or_else(|| { - anyhow!("FIFO path contains invalid UTF-8: {}", fifo_path.display()) - })?; - let path_cstr = CString::new(path_str) - .map_err(|_| anyhow!("FIFO path contains null bytes: {}", fifo_path.display()))?; - // SAFETY: path_cstr is a valid NUL-terminated C string; mkfifo is a POSIX syscall - // that creates a FIFO special file at the given path with the specified permissions. - let result = unsafe { libc::mkfifo(path_cstr.as_ptr(), 0o600) }; - if result != 0 { - let err = std::io::Error::last_os_error(); + use nix::sys::stat::Mode; + // `nix::unistd::mkfifo` takes the path directly, so no C string + // or raw pointer is built here. + let mode = Mode::S_IRUSR | Mode::S_IWUSR; // 0o600 + if let Err(err) = nix::unistd::mkfifo(&fifo_path, mode) { // If FIFO already exists, try to remove and recreate - if err.kind() == std::io::ErrorKind::AlreadyExists { + if err == nix::errno::Errno::EEXIST { std::fs::remove_file(&fifo_path)?; - // SAFETY: same as above — path_cstr unchanged, mkfifo is safe with valid CString - let result = unsafe { libc::mkfifo(path_cstr.as_ptr(), 0o600) }; - if result != 0 { - let err = std::io::Error::last_os_error(); - return Err(anyhow!( - "Failed to create FIFO {}: {}", - fifo_path.display(), - err - )); - } + nix::unistd::mkfifo(&fifo_path, mode).map_err(|err| { + anyhow!("Failed to create FIFO {}: {}", fifo_path.display(), err) + })?; } else { return Err(anyhow!( "Failed to create FIFO {}: {}", diff --git a/impl/rust-cli/src/secure_erase.rs b/impl/rust-cli/src/secure_erase.rs index dadfaed3..00c4eb2a 100644 --- a/impl/rust-cli/src/secure_erase.rs +++ b/impl/rust-cli/src/secure_erase.rs @@ -115,13 +115,23 @@ pub fn check_ata_secure_erase_support(device: &str) -> Result { Ok(info.contains("supported: enhanced erase") || info.contains("SECURITY ERASE UNIT")) } +/// Temporary ATA user password set before the erase command. +/// +/// "Eins" is the conventional value in the ATA Secure Erase guide on +/// ata.wiki.kernel.org. It is deliberately well known: if an erase is +/// interrupted after the password is set, the drive stays locked, and the +/// owner can recover it with `hdparm --user-master u --security-disable Eins`. +/// A completed erase clears it. It protects nothing, so it is not a secret. +// hypatia: allow security_errors/secret_detected -- documented hdparm temporary password, not a credential +const ATA_TEMP_PASSWORD: &str = "Eins"; // ggignore (public hdparm convention, see above) + /// Perform ATA Secure Erase pub fn ata_secure_erase(device: &str, enhanced: bool) -> Result<()> { // CRITICAL: This is a destructive operation // Requires security password to be set first // Step 1: Set user password (temporary) - let password = "Eins"; // Standard temporary password + let password = ATA_TEMP_PASSWORD; println!("⚠️ Setting security password..."); let status = Command::new("hdparm") diff --git a/impl/rust-cli/src/test_command.rs b/impl/rust-cli/src/test_command.rs index dca3614c..22a1cc42 100644 --- a/impl/rust-cli/src/test_command.rs +++ b/impl/rust-cli/src/test_command.rs @@ -244,7 +244,7 @@ impl TestExpr { pub fn parse_test_expr(args: &[String], is_bracket: bool) -> Result { // Handle "[" syntax - must end with "]" let args = if is_bracket { - if args.is_empty() || args.last().unwrap() != "]" { + if args.last().map(String::as_str) != Some("]") { bail!("test: missing ']'"); } &args[..args.len() - 1] // Remove trailing "]" diff --git a/impl/zig/lean_wrapper.zig b/impl/zig/lean_wrapper.zig index b4929ce7..d6d6a636 100644 --- a/impl/zig/lean_wrapper.zig +++ b/impl/zig/lean_wrapper.zig @@ -59,11 +59,6 @@ fn cStrToLeanStr(c_str: [*:0]const u8) *lean_object { return lean_mk_string(c_str); } -// Helper: Convert Lean String to C string (caller must free) -fn leanStrToCStr(lean_str: *lean_object) [*:0]u8 { - const data = lean_string_cstr(lean_str); - return @ptrCast(@constCast(data)); -} // Helper: Convert Lean CResult to VshResult fn leanResultToC(lean_result: *lean_object) VshResult { diff --git a/impl/zig/src/daemon_client.zig b/impl/zig/src/daemon_client.zig index 3f773a4d..7ac59f42 100644 --- a/impl/zig/src/daemon_client.zig +++ b/impl/zig/src/daemon_client.zig @@ -35,6 +35,7 @@ pub fn isDaemonRunning() bool { addr.path[path_bytes.len] = 0; // Try to connect + // hypatia: allow code_safety/zig_ptr_cast -- sockaddr_un passed as the generic sockaddr, the BSD sockets ABI posix.connect(socket_fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.un)) catch { return false; }; @@ -84,6 +85,7 @@ pub fn sendSimpleRequest( @memcpy(addr.path[0..path_bytes.len], path_bytes); addr.path[path_bytes.len] = 0; + // hypatia: allow code_safety/zig_ptr_cast -- sockaddr_un passed as the generic sockaddr, the BSD sockets ABI posix.connect(socket_fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.un)) catch { return false; }; diff --git a/impl/zig/src/lib.zig b/impl/zig/src/lib.zig index b7f6c4e5..1cbbd7c5 100644 --- a/impl/zig/src/lib.zig +++ b/impl/zig/src/lib.zig @@ -461,18 +461,35 @@ pub const ValenceFS = opaque {}; /// C-compatible error code pub const ValenceError = c_int; +/// Wrap a `Filesystem` allocated by this module as an opaque C handle. +fn toHandle(fs_ptr: *Filesystem) *ValenceFS { + // hypatia: allow code_safety/zig_ptr_cast -- erasing to the opaque C handle type + return @ptrCast(fs_ptr); +} + +/// Recover the `Filesystem` behind a handle from `valence_fs_create*`. +/// +/// Every `ValenceFS` handle this module hands out is a `*Filesystem` from +/// `toHandle`, so it has `Filesystem`'s alignment; these are the only two +/// casts across the C boundary. A pointer not obtained from +/// `valence_fs_create*` is a caller error the C ABI cannot detect. +fn fromHandle(h: *ValenceFS) *Filesystem { + // hypatia: allow code_safety/zig_ptr_cast -- handle came from toHandle (see doc comment) + return @ptrCast(@alignCast(h)); // hypatia: allow code_safety/zig_align_cast -- handle came from toHandle, so it has Filesystem's alignment +} + /// Create filesystem handle (C ABI) export fn valence_fs_create(root: [*:0]const u8) ?*ValenceFS { const allocator = std.heap.c_allocator; const fs_ptr = allocator.create(Filesystem) catch return null; fs_ptr.* = Filesystem.init(allocator, std.mem.span(root), null); - return @ptrCast(fs_ptr); + return toHandle(fs_ptr); } /// Destroy filesystem handle (C ABI) export fn valence_fs_destroy(handle: ?*ValenceFS) void { if (handle) |h| { - const fs_ptr: *Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr = fromHandle(h); std.heap.c_allocator.destroy(fs_ptr); } } @@ -480,7 +497,7 @@ export fn valence_fs_destroy(handle: ?*ValenceFS) void { /// Create directory (C ABI) export fn valence_mkdir(handle: ?*ValenceFS, path: [*:0]const u8) ValenceError { if (handle) |h| { - const fs_ptr: *Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr = fromHandle(h); const result = fs_ptr.mkdir(std.mem.span(path)); return switch (result) { .ok => 0, @@ -493,7 +510,7 @@ export fn valence_mkdir(handle: ?*ValenceFS, path: [*:0]const u8) ValenceError { /// Remove directory (C ABI) export fn valence_rmdir(handle: ?*ValenceFS, path: [*:0]const u8) ValenceError { if (handle) |h| { - const fs_ptr: *Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr = fromHandle(h); const result = fs_ptr.rmdir(std.mem.span(path)); return switch (result) { .ok => 0, @@ -506,7 +523,7 @@ export fn valence_rmdir(handle: ?*ValenceFS, path: [*:0]const u8) ValenceError { /// Create file (C ABI) export fn valence_create_file(handle: ?*ValenceFS, path: [*:0]const u8) ValenceError { if (handle) |h| { - const fs_ptr: *Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr = fromHandle(h); const result = fs_ptr.createFile(std.mem.span(path)); return switch (result) { .ok => 0, @@ -519,7 +536,7 @@ export fn valence_create_file(handle: ?*ValenceFS, path: [*:0]const u8) ValenceE /// Delete file (C ABI) export fn valence_delete_file(handle: ?*ValenceFS, path: [*:0]const u8) ValenceError { if (handle) |h| { - const fs_ptr: *Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr = fromHandle(h); const result = fs_ptr.deleteFile(std.mem.span(path)); return switch (result) { .ok => 0, @@ -532,7 +549,7 @@ export fn valence_delete_file(handle: ?*ValenceFS, path: [*:0]const u8) ValenceE /// Check path exists (C ABI) export fn valence_path_exists(handle: ?*ValenceFS, path: [*:0]const u8) bool { if (handle) |h| { - const fs_ptr: *const Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr: *const Filesystem = fromHandle(h); return fs_ptr.pathExists(std.mem.span(path)); } return false; @@ -541,7 +558,7 @@ export fn valence_path_exists(handle: ?*ValenceFS, path: [*:0]const u8) bool { /// Check if path is directory (C ABI) export fn valence_is_directory(handle: ?*ValenceFS, path: [*:0]const u8) bool { if (handle) |h| { - const fs_ptr: *const Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr: *const Filesystem = fromHandle(h); return fs_ptr.isDirectory(std.mem.span(path)); } return false; @@ -550,7 +567,7 @@ export fn valence_is_directory(handle: ?*ValenceFS, path: [*:0]const u8) bool { /// Check if path is file (C ABI) export fn valence_is_file(handle: ?*ValenceFS, path: [*:0]const u8) bool { if (handle) |h| { - const fs_ptr: *const Filesystem = @ptrCast(@alignCast(h)); + const fs_ptr: *const Filesystem = fromHandle(h); return fs_ptr.isFile(std.mem.span(path)); } return false; @@ -579,7 +596,7 @@ export fn valence_fs_create_with_audit(root: [*:0]const u8, audit_path_cstr: [*: return null; }; fs_ptr.* = fs; - return @ptrCast(fs_ptr); + return toHandle(fs_ptr); } /// Get error string (C ABI) diff --git a/proofs/idris2/src/Filesystem/Axioms.idr b/proofs/idris2/src/Filesystem/Axioms.idr index f250bf95..f435a675 100644 --- a/proofs/idris2/src/Filesystem/Axioms.idr +++ b/proofs/idris2/src/Filesystem/Axioms.idr @@ -41,6 +41,7 @@ import Data.String ||| `axStringEqRefl`. export axStringEqRefl : (s : String) -> (s == s) = True +-- hypatia: allow code_safety/believe_me -- registered axiom axStringEqRefl (.machine_readable/IDRIS2_AXIOMS.a2ml), gated by .github/scripts/check-idris2-believe-me.sh; no proof exists without one (prim__eq is opaque), see docs/audits/2026-11-16-hypatia-remediation.adoc axStringEqRefl _ = believe_me (Refl {x = True}) ||| AXIOM: primitive `Bits8` equality is reflexive on opaque values. @@ -54,6 +55,7 @@ axStringEqRefl _ = believe_me (Refl {x = True}) ||| `axBits8EqRefl`. export axBits8EqRefl : (b : Bits8) -> (b == b) = True +-- hypatia: allow code_safety/believe_me -- registered axiom axBits8EqRefl (.machine_readable/IDRIS2_AXIOMS.a2ml), gated by .github/scripts/check-idris2-believe-me.sh; no proof exists without one (prim__eq is opaque), see docs/audits/2026-11-16-hypatia-remediation.adoc axBits8EqRefl _ = believe_me (Refl {x = True}) -------------------------------------------------------------------------------- diff --git a/scripts/verify-proofs.sh b/scripts/verify-proofs.sh index baedd10a..0cc175fa 100755 --- a/scripts/verify-proofs.sh +++ b/scripts/verify-proofs.sh @@ -56,19 +56,24 @@ check_command() { fi } -# Run a test with optional verbose output +# Run a test with optional verbose output. +# Usage: run_test NAME DIR COMMAND [ARG...] +# The command runs from DIR (relative to the repo root) as an argument vector, +# in a subshell so the `cd` cannot leak into the next test. No string is +# re-parsed by the shell (no eval). run_test() { local name="$1" - local cmd="$2" + local dir="$2" + shift 2 TOTAL_TESTS=$((TOTAL_TESTS + 1)) log_info "Testing: $name" - # Run in a subshell so per-test `cd` side effects do not leak into the next - # test (commands are written as `cd proofs/X && ...` from the repo root). if $VERBOSE; then - echo "Command: $cmd" - if ( eval "$cmd" ); then + printf 'Command: (cd %q &&' "$dir" + printf ' %q' "$@" + printf ')\n' + if ( cd "$dir" && "$@" ); then log_success "$name passed" return 0 else @@ -76,7 +81,7 @@ run_test() { return 1 fi else - if ( eval "$cmd" ) &> /dev/null; then + if ( cd "$dir" && "$@" ) &> /dev/null; then log_success "$name passed" return 0 else @@ -96,28 +101,12 @@ if check_command coqc; then log_info "Coq 8.x detected" # extraction.v writes to extracted/filesystem.ml; the dir is gitignored, so create it. mkdir -p proofs/coq/extracted - run_test "Coq: filesystem_model.v" \ - "cd proofs/coq && coqc -R . ValenceShell filesystem_model.v" - run_test "Coq: file_operations.v" \ - "cd proofs/coq && coqc -R . ValenceShell file_operations.v" - run_test "Coq: file_content_operations.v" \ - "cd proofs/coq && coqc -R . ValenceShell file_content_operations.v" - run_test "Coq: copy_move_operations.v" \ - "cd proofs/coq && coqc -R . ValenceShell copy_move_operations.v" - run_test "Coq: symlink_operations.v" \ - "cd proofs/coq && coqc -R . ValenceShell symlink_operations.v" - run_test "Coq: permission_operations.v" \ - "cd proofs/coq && coqc -R . ValenceShell permission_operations.v" - run_test "Coq: filesystem_composition.v" \ - "cd proofs/coq && coqc -R . ValenceShell filesystem_composition.v" - run_test "Coq: filesystem_equivalence.v" \ - "cd proofs/coq && coqc -R . ValenceShell filesystem_equivalence.v" - run_test "Coq: posix_errors.v" \ - "cd proofs/coq && coqc -R . ValenceShell posix_errors.v" - run_test "Coq: rmo_operations.v" \ - "cd proofs/coq && coqc -R . ValenceShell rmo_operations.v" - run_test "Coq: extraction.v" \ - "cd proofs/coq && coqc -R . ValenceShell extraction.v" + for f in filesystem_model.v file_operations.v file_content_operations.v \ + copy_move_operations.v symlink_operations.v permission_operations.v \ + filesystem_composition.v filesystem_equivalence.v posix_errors.v \ + rmo_operations.v extraction.v; do + run_test "Coq: $f" proofs/coq coqc -R . ValenceShell "$f" + done else log_skip "Coq not installed" ((TOTAL_TESTS += 11)) @@ -132,8 +121,10 @@ if check_command lean; then # Same named libraries as CI (.github/workflows/rust-cli.yml); a bare # `lean File.lean` cannot resolve imports outside `lake env`, and a bare # `lake build` builds only the default target. - run_test "Lean 4: lake build (CI library set)" \ - "cd proofs/lean4 && lake build FilesystemModel FileOperations FilesystemComposition FilesystemEquivalence SymlinkOperations Extraction CrashConsistency PathTraversal PreconditionWitnesses" + run_test "Lean 4: lake build (CI library set)" proofs/lean4 \ + lake build FilesystemModel FileOperations FilesystemComposition \ + FilesystemEquivalence SymlinkOperations Extraction CrashConsistency \ + PathTraversal PreconditionWitnesses else log_skip "Lean 4 not installed" ((TOTAL_TESTS += 1)) @@ -145,7 +136,7 @@ echo "" if check_command agda; then log_info "Agda detected" run_test "Agda: All.agda (--safe --without-K --cubical-compatible) + module coverage" \ - "bash scripts/check-agda.sh" + . bash scripts/check-agda.sh else log_skip "Agda not installed" ((TOTAL_TESTS += 1)) @@ -161,8 +152,7 @@ echo "" # Z3 Verification (all checked-in encodings, with exact result validation) if check_command z3; then log_info "Z3 SMT Solver detected" - run_test "Z3: all encodings and failure control" \ - "bash scripts/verify-z3.sh" + run_test "Z3: all encodings and failure control" . bash scripts/verify-z3.sh else log_skip "Z3 not installed" TOTAL_TESTS=$((TOTAL_TESTS + 1)) diff --git a/setup.sh b/setup.sh index b11cff73..c463a3f9 100755 --- a/setup.sh +++ b/setup.sh @@ -128,6 +128,27 @@ detect_platform() { esac } +# ── Install just from crates.io ── +# Used where no package manager carries just. Cargo checks every crate against +# the registry's checksums, so nothing is downloaded and executed unverified +# (the former fallback piped https://just.systems/install.sh into bash). +install_just_with_cargo() { + if command -v cargo >/dev/null 2>&1; then + info "Building just with cargo (crates.io, checksum-verified)..." + cargo install --locked just || return 1 + # cargo installs into ~/.cargo/bin, which may not be on PATH yet. + case ":$PATH:" in + *":$HOME/.cargo/bin:"*) ;; + *) export PATH="$HOME/.cargo/bin:$PATH" + info "Added ~/.cargo/bin to PATH for this run; add it to your shell profile." ;; + esac + else + fail "No package manager here provides just, and cargo is not installed." + fail "Install just from your distribution or https://just.systems/, then re-run." + return 1 + fi +} + # ── Install just ── install_just() { if command -v just >/dev/null 2>&1; then @@ -140,8 +161,8 @@ install_just() { case "$PKG_MGR" in dnf) sudo dnf install -y just ;; apt) sudo apt-get install -y just 2>/dev/null || { - # just not in older apt repos — use installer - curl -fsSL https://just.systems/install.sh | bash -s -- --to /usr/local/bin + # just is not in older apt repos — build it from crates.io + install_just_with_cargo } ;; pacman) sudo pacman -S --noconfirm just ;; apk) sudo apk add just ;; @@ -152,8 +173,7 @@ install_just() { guix) guix install just ;; nix) nix-env -iA nixpkgs.just ;; *) - info "Using just installer script..." - curl -fsSL https://just.systems/install.sh | bash -s -- --to /usr/local/bin + install_just_with_cargo ;; esac