Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39a0c54f05 | ||
|
|
99a25f3fa4 | ||
|
|
2795dda52b | ||
|
|
bee85dcdc2 | ||
|
|
62c359c75b | ||
|
|
47b9bc9039 | ||
|
|
cbb6b17da4 | ||
|
|
2c6670a336 | ||
|
|
3463ff8d76 | ||
|
|
63899f9499 | ||
|
|
5023e39485 | ||
|
|
8d9a28dc03 | ||
|
|
0057d5c41e | ||
|
|
b526d1bf81 | ||
|
|
adaa363f7c | ||
|
|
2068f73f6a | ||
|
|
6e22c7d502 | ||
|
|
19b5df46a7 | ||
|
|
edb7544b93 | ||
|
|
ef9f4f5016 | ||
|
|
0b02bbde1e | ||
|
|
3d636a4793 | ||
|
|
929cff898a | ||
|
|
fc897ef569 | ||
|
|
ce833c3475 | ||
|
|
446d84a3b8 | ||
|
|
ed9340e3fa | ||
|
|
a7299c29cb |
No files matched your search
@@ -33,3 +33,6 @@ crates/pipdock-core/tests/fixtures/**/*.json text eol=crlf
|
||||
# get — the rule above would have rewritten a captured document's line endings and quietly made it
|
||||
# something no tool ever emitted. Later rules win, which is what lets this sit as an exception.
|
||||
crates/pipdock-core/tests/fixtures/health/** -text
|
||||
|
||||
# pip-audit captures are a tool's own output, like health/ above.
|
||||
crates/pipdock-core/tests/fixtures/audit/** -text
|
||||
@@ -0,0 +1,9 @@
|
||||
# Changelog
|
||||
|
||||
Kept in [`changelog/`](changelog/), one file per major line, newest release first.
|
||||
|
||||
- **[1.x](changelog/1.x.md)** — 1.0.0 onward
|
||||
- [Conventions and the split rule](changelog/README.md)
|
||||
|
||||
This file is a pointer, not a copy. A single growing changelog is the thing the directory exists to
|
||||
avoid, and two places to write a release note is one place to forget.
|
||||
@@ -1,7 +1,7 @@
|
||||
# PipDock — working notes for Claude
|
||||
|
||||
Windows GUI + CLI for bulk-managing Python packages. Tauri 2 + Rust core + React 19.
|
||||
Repo `poli0981/pipdock` · GPL-3.0-only · **Status: 1.0.0. M1, M2, Phase 3 and Phase 4 all complete — the release pipeline runs, `main` is protected, the manual charter is done, and the legal documents match the code.** Post-1.0 is the P1 wave in `docs/ROADMAP.md`.
|
||||
Repo `poli0981/pipdock` · GPL-3.0-only · **Status: 1.2.0. M1, M2, Phase 3, Phase 4, the P1 wave and the Security tab are all complete.** 1.0.0 shipped the release pipeline, a protected `main`, the manual charter and legal documents that match the code; 1.1.0 added pin auto-suggest, requirements export/import, the cache manager and the `Ctrl+K` palette; 1.2.0 added the Security tab (PRD P1-1), which was the last major P1 item. **What is left of Post-1.0 is two things** — the dependency-graph view (P1-6) and the scheduled check (P1-7) — and neither is near P1-1's readiness; see `docs/ROADMAP.md`.
|
||||
|
||||
## Read the docs before changing anything
|
||||
|
||||
@@ -49,6 +49,15 @@ failed package never aborts a batch (skip-and-continue, then a `"13 successful,
|
||||
|
||||
## Conventions
|
||||
|
||||
- **One session, one slice, one version.** A session takes a single item — a `docs/ROADMAP.md`
|
||||
entry, or something that surfaced while doing one — takes it *deep*, tests it properly, and ships
|
||||
it as one version, plus a patch release if it needs a hotfix. Not several shallow items. The
|
||||
record of what a slice cost goes in ROADMAP; what a *user* would notice goes in `changelog/`.
|
||||
- **The changelog lives in `changelog/`, one file per major line** (`1.x.md`), with a pre-release
|
||||
line getting its own file (`2.0-beta.md`). Root `CHANGELOG.md` is a pointer only. Split a file by
|
||||
minor range at roughly 600 lines and never renumber an existing range file —
|
||||
`changelog/README.md` is the authority.
|
||||
|
||||
- Crates `pipdock-*`; React components prefixed `Pd` (`PdPackageRow`, `PdConflictDialog`)
|
||||
- Tauri identifier `com.skullmute.pipdock`; CLI binary `pipdock`
|
||||
- Frontend lives in `ui/`, but `package.json` sits at the **repo root** so the ops-repo
|
||||
@@ -142,6 +151,28 @@ Three rules from S2/S3 that bind everything after them:
|
||||
the package slice happened to be stale. After a rollback that is exactly the case. A shared reset
|
||||
constant is only correct for fields with a shared key.
|
||||
|
||||
- **A spec can promise a field that has never existed.** SECURITY §6 asked for a *severity* per
|
||||
finding and PRD P1-1 for "severity-sorted"; pip-audit publishes no severity under **either**
|
||||
vulnerability service, and never has. §6 also said pip-audit runs from the Code Health tools venv,
|
||||
which the code had refused since P2 with three tests enforcing the refusal. Both were found by
|
||||
*running the pinned tool and reading its JSON*, not by reading the specs against each other. When
|
||||
a spec sentence describes an external tool, the tool is the authority — and the correction belongs
|
||||
in the spec, not in a workaround that invents the missing field.
|
||||
|
||||
- **A watchdog is a unit, not a number.** `audit::run` inherited Code Health's 120 s `TOOL_TIMEOUT`
|
||||
and hit it on the first real run, reporting `PD-HLT-003` for a tool that was working. Code Health
|
||||
is a linter walking a source tree; an audit is a network fetch. Measured: **68 s cold** for one
|
||||
package, 20.0 s warm for *twelve* — twelve cost 1.4 s more than one, so the cost is a one-off
|
||||
database fetch and package count is not the risk. The same measurement reopened cancellation,
|
||||
which P4 had deferred on Code Health's 1.3 s. **A borrowed constant carries its original units
|
||||
with it.**
|
||||
|
||||
- **Adding a field to a struct that is summed is a bug the suite will not see.** `Target::Audit`
|
||||
gave `cache::Usage` a fourth entry and `total_bytes` still added three — every cache test passed
|
||||
and the number on screen was wrong with nothing to say so. The guard asserts on distinct powers
|
||||
of two so a missing term appears as its own bit rather than as a plausible total. Same shape as
|
||||
the `entryOf` ternary whose last branch was a hand-maintained negation of every case above it.
|
||||
|
||||
- **A dialog is not an enforcement point.** DATA-FLOW §5's three options are what the user *sees*;
|
||||
what stops a removal is `GuardAck` inside `UninstallFlow::execute`, beside `SnapshotProof`. The
|
||||
same shape three times now — `SnapshotProof`, `GuardAck`, and P5's `FixConsent`: the report and
|
||||
@@ -166,7 +197,7 @@ Things worth knowing before you change any of it:
|
||||
|
||||
- **`cargo test` fails when `ui/src/ipc/generated.ts` is stale.** Fix with
|
||||
`cargo run -p xtask -- bindings`; the failure names that command and the first differing line.
|
||||
- **The L4 goldens (`crates/pipdock-cli/tests/golden.rs`, 58 snapshots) are the CLI's output
|
||||
- **The L4 goldens (`crates/pipdock-cli/tests/golden.rs`, 64 snapshots at 1.1.0) are the CLI's output
|
||||
contract.** A diff there is a real behaviour change — re-bless deliberately, never reflexively.
|
||||
They are what made the `core::flow` refactor provably behaviour-preserving.
|
||||
- **Two tests hold the wire format**: `Code::ALL` must serialize as `as_str()`, and no
|
||||
@@ -182,6 +213,48 @@ Things worth knowing before you change any of it:
|
||||
run showed *Back to packages* twice and every suite stayed green. Found by a human using the
|
||||
installed build. When adding a component test, ask what renders it.
|
||||
|
||||
- **A hand-written fixture that matches the docs while the code does not is worse than none.**
|
||||
`fixtures.rs` says so in its own module doc, and `guard_report()` is computed for that reason —
|
||||
but the plan fixture's blockers were hand-written to the shape `plan::Blocker`'s doc describes
|
||||
while `graph::blockers_for` had drifted to building an English sentence. So `PdPreviewDiff`
|
||||
asserted the *right* sentence and proved nothing, the preview shipped reading `scipy requires
|
||||
scipy 1.11.4 requires numpy <1.28.0,>=1.21.6` from S3 to 1.1.0, and no suite could see it. If a
|
||||
fixture's value can be computed by the function that produces it in production, compute it.
|
||||
|
||||
- **A sentence assembled in Rust is a sentence the other head assembles again.** That was the
|
||||
mechanism above: the CLI prints `Blocker.constraint` alone, so building the phrase in core made
|
||||
the *CLI* look right and left the GUI to wrap it in `plan.blocker` a second time. Invariant 4 is
|
||||
not only about translation — a joined string cannot be un-joined by a catalog. Structured fields,
|
||||
one composition per head, as `BrokenDependent`/`PdUninstallDialog` have always done.
|
||||
|
||||
- **Never `sed -i` anything under `tests/fixtures/`.** Git Bash's sed rewrites in text mode and
|
||||
strips every CR, which is exactly what `.gitattributes`' `-text` exists to prevent; one command
|
||||
flattened ten engine fixtures and reported 160 changed lines where one was intended. Use a
|
||||
binary-mode read/write and assert the CRLF count per file.
|
||||
|
||||
- **A parser that is correct for trusted input is a hole for untrusted input.**
|
||||
`graph::Requirement::parse` splits the name at the first space, so `this is not a requirement`
|
||||
parses as package `this` with constraint `is not a requirement` — exactly right for
|
||||
`Requires-Dist` metadata, which never looks like prose, and a spec containing spaces heading for
|
||||
argv the moment the input is a file a user typed. Reuse the parser, then re-validate at the new
|
||||
boundary; SECURITY §2's obligation follows the *input*, not the function.
|
||||
|
||||
- **Before adding a size or a "clear" for something, check it exists.** `LOG_RETENTION_DAYS` has
|
||||
had no reader since it was written, so P1-C's cache manager covers three artefacts rather than
|
||||
the four the roadmap listed. A row reading "logs — 0 B" would have invented a subsystem.
|
||||
|
||||
- **A test can assert a substring you did not think of.** `PdPins.test.tsx` proves the screen
|
||||
offers no way to create a `Hold` pin with `queryByText(/hold/i)` — and **"threshold" matches
|
||||
that.** P1-A's Settings label is "Suggest pinning at" for that reason alone. Before adding copy
|
||||
to a screen, grep its test for regex assertions; a broad `/word/i` over a whole screen is a trap
|
||||
laid for a feature that does not exist yet.
|
||||
|
||||
- **A doc comment describing an intent nothing implements is worse than none.**
|
||||
`ReverseDeps::build` said auto-suggest "may still count" extra-gated edges while
|
||||
`dependent_count` had always filtered them. Whoever built the feature would have believed the
|
||||
comment or the code, and had no way to know which. When you find one, settle it in the comment
|
||||
rather than leaving both readings alive.
|
||||
|
||||
- **A green badge is not a green `main`.** The README badge is per *workflow file* and shows that
|
||||
file's last run, which may be a schedule on a different commit. `main` was red for a day at
|
||||
`3eeda05` — every cargo job failing before a crate compiled — because `Cargo.lock` carried a
|
||||
|
||||
Generated
+4
-4
@@ -3168,7 +3168,7 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pipdock-app"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
dependencies = [
|
||||
"jiff",
|
||||
"pipdock-core",
|
||||
@@ -3188,7 +3188,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pipdock-cli"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
dependencies = [
|
||||
"assert_cmd",
|
||||
"clap",
|
||||
@@ -3203,7 +3203,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pipdock-core"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"insta",
|
||||
@@ -6371,7 +6371,7 @@ checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
dependencies = [
|
||||
"pipdock-core",
|
||||
]
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/pipdock-core", "crates/pipdock-cli", "src-tauri", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.94"
|
||||
license = "GPL-3.0-only"
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
</details>
|
||||
|
||||
## Features (v1)
|
||||
## Features
|
||||
|
||||
| Area | What you get |
|
||||
|---|---|
|
||||
@@ -55,12 +55,15 @@
|
||||
| Updates | Bulk update with group dry-run resolve, held-back explanations, 3-way conflict choices |
|
||||
| Search & Install | Instant fuzzy search over a locally cached PyPI name index (PEP 691), metadata on demand, install queue |
|
||||
| Uninstall | Bulk uninstall with reverse-dependency warnings |
|
||||
| Pins | Exclude packages from bulk updates; auto-suggest pinning heavily-depended-on packages |
|
||||
| Pins | Exclude packages from bulk updates, with a reason. The Pins screen suggests packages a lot of your others depend on, and the threshold is configurable |
|
||||
| Snapshots | Automatic pre-batch snapshots, diff view, one-click rollback |
|
||||
| Engine | pip **or** uv, selectable in Settings (uv auto-detected on first run) |
|
||||
| Code Health | deptry + vulture + ruff against a project folder — unused deps, dead code, style — run from PipDock's own isolated tools env |
|
||||
| pip upkeep | Check & update pip itself per environment |
|
||||
| CLI | `pipdock` — full parity for core operations, JSON output, CI-friendly exit codes |
|
||||
| Requirements | Export an environment as `requirements.txt`; import one and preview what it would install, with every line it will not use reported by number |
|
||||
| Disk usage | See and clear what PipDock has written — snapshots and the Code Health tools environment |
|
||||
| Keyboard | `Ctrl+K` command palette, `Ctrl+1`–`Ctrl+9` tabs, full keyboard traversal |
|
||||
| i18n | English + Tiếng Việt |
|
||||
| Privacy | No telemetry. **PyPI is the only host PipDock connects to.** It does not check for updates, so it never calls home — GitHub and the ruff docs are only ever handed to your browser as a link you clicked |
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# 1.x
|
||||
|
||||
Newest first. See [`README.md`](README.md) for the conventions, and `docs/ROADMAP.md` for what each
|
||||
slice cost and what it taught — that is a different document for a different reader.
|
||||
|
||||
## 1.2.0 — 2026-08-18
|
||||
|
||||
The **Security tab**, which the sidebar has shown greyed out since M2.
|
||||
|
||||
### Added
|
||||
|
||||
- **Security (`Ctrl+7`)** — known advisories against the packages installed in the selected
|
||||
environment, grouped by package. Each carries its id, the versions that fix it, its other ids
|
||||
(which is where the CVE is), the advisory text, and a link to its entry on osv.dev.
|
||||
- **Cancel**, because an audit takes 18–68 seconds — the first one longer, since it builds its own
|
||||
tool environment.
|
||||
- **Save report…**, writing Markdown and JSON beside a path you choose, as Code Health already did.
|
||||
- `pipdock audit` at the command line. **Exit 1 when it finds something**, 0 when it does not, so a
|
||||
script can branch on it.
|
||||
- The Security tool environment is now listed in Settings → disk usage, and can be cleared there.
|
||||
|
||||
### Changed
|
||||
|
||||
- **There is no severity column, and there was never going to be one.** The documentation promised
|
||||
findings sorted by severity; pip-audit publishes no severity at all. Findings are ordered by
|
||||
package, then by whether anything *fixes* them, then by id — the distinction that changes what you
|
||||
can do about one. PipDock does not invent a number to put in the gap.
|
||||
- Advisories come from **PyPI's** advisory data. PipDock still connects to nothing but pypi.org;
|
||||
the osv.dev link is your browser going there after you click it.
|
||||
|
||||
### You will see this once
|
||||
|
||||
**The first-run legal screen appears again.** The licence, disclaimer and third-party notices all
|
||||
described pip-audit as planned and not yet used, and that stopped being true. Your acceptance is
|
||||
recorded against the documents' version, so a change to them asks once more. Nothing else resets.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The update preview named the blocking package twice — *"scipy requires scipy 1.11.4 requires
|
||||
numpy…"*. It now reads once, with the version.
|
||||
- Clearing the cache reported a total that left out one of the two tool environments.
|
||||
|
||||
PRs [#51](https://github.com/poli0981/pipdock/pull/51),
|
||||
[#52](https://github.com/poli0981/pipdock/pull/52),
|
||||
[#53](https://github.com/poli0981/pipdock/pull/53).
|
||||
|
||||
## 1.1.0 — 2026-08-14
|
||||
|
||||
Four smaller features, the day after 1.0.0.
|
||||
|
||||
### Added
|
||||
|
||||
- **Pin auto-suggest** — packages that many others depend on are offered for pinning, on the Pins
|
||||
screen, with the count as the reason. The threshold is in Settings; zero turns it off.
|
||||
- **Export and import** — write an environment as `requirements.txt` or `constraints.txt`, and read
|
||||
a requirements file back in as an install queue. Lines PipDock will not act on (includes,
|
||||
editable installs) are listed rather than silently dropped.
|
||||
- **Disk usage** in Settings — what PipDock has written, and a way to clear the parts that are safe
|
||||
to clear. `index.db` is shown but not clearable: it holds your settings, pins and consent record
|
||||
as well as the package index.
|
||||
- **`Ctrl+K`** — a command palette over every screen and action.
|
||||
|
||||
## 1.0.0 — 2026-08-14
|
||||
|
||||
First public release. Windows.
|
||||
|
||||
Bulk-manage packages across your Python environments, over pip or uv. Every change is previewed
|
||||
before it runs, the environment is snapshotted before it is touched, and a batch reports back
|
||||
package by package rather than stopping at the first failure.
|
||||
|
||||
- **Environments** discovered from the registry, `py -0p`, uv-managed installs and the usual venv
|
||||
folder names, with a *Browse…* fallback still to come.
|
||||
- **Installed / Updates** — the whole environment, what is outdated, and a preview that explains
|
||||
what is holding a package back and which installed package declared the constraint. No engine
|
||||
reports that; PipDock derives it.
|
||||
- **Snapshots and rollback**, including a rollback of a rollback.
|
||||
- **Pins**, so a bulk update leaves what you have chosen to keep.
|
||||
- **An uninstall guard** that refuses a removal other packages depend on, naming them and their
|
||||
constraints.
|
||||
- **Code Health** — deptry, vulture and ruff over a project folder, from an isolated environment
|
||||
PipDock builds for itself, with a gated `ruff --fix`.
|
||||
- **English and Vietnamese** throughout the interface.
|
||||
- **A command line** with the same behaviour, documented exit codes and `--json`.
|
||||
|
||||
No telemetry, no account, no self-update. It connects to pypi.org and nowhere else.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Changelog
|
||||
|
||||
One file per **major line**. `1.x.md` holds every 1.y.z release; `0.x.md` would have held the
|
||||
pre-1.0 ones had any been published (none were — the first release was 1.0.0, and `0.1.0` existed
|
||||
only as a working version in the manifests).
|
||||
|
||||
| File | Covers |
|
||||
|---|---|
|
||||
| [`1.x.md`](1.x.md) | 1.0.0 → current |
|
||||
|
||||
A **pre-release line gets its own file**, named for the line it leads to — `2.0-beta.md` for
|
||||
`2.0.0-beta.1` onward. It is not merged into `2.x.md` when the line goes stable: the beta file is
|
||||
what someone reads to find out *when* a behaviour changed during the run-up, and folding it in
|
||||
would double the length of the file people actually read while losing that.
|
||||
|
||||
## When a major line gets long, split by minor range
|
||||
|
||||
The point of this directory is that a reader opens one file and finds their version without
|
||||
scrolling past releases they do not care about. So the rule is about **reading length**, not about
|
||||
release count:
|
||||
|
||||
**Split when a file passes roughly 600 lines**, into contiguous minor ranges — `1.0-1.4.md`,
|
||||
`1.5-1.9.md` — and leave `1.x.md` as a stub pointing at both, so an old link never 404s. Add the
|
||||
new files to the table above in the same commit.
|
||||
|
||||
Two things that make the split cheap when it comes:
|
||||
|
||||
- **Never renumber an existing file.** A range file is named for the range it holds and keeps that
|
||||
name forever, even after the next split. `1.0-1.4.md` does not become `1.0-1.6.md`.
|
||||
- **Newest first within a file**, so the top of the file is the part most people want and the
|
||||
split point is always at the bottom.
|
||||
|
||||
## What goes in an entry
|
||||
|
||||
One `## x.y.z — YYYY-MM-DD` heading per release, newest first, and under it only what a *user* of
|
||||
PipDock would notice: added, changed, fixed, and anything they have to do (a consent gate that
|
||||
re-shows, a cache that needs clearing). Internals belong in `docs/ROADMAP.md`, which records what a
|
||||
slice cost and what it taught; the two are deliberately different documents for different readers,
|
||||
the way `docs/CLI-GUIDE.md` and `docs/CLI-SPEC.md` are.
|
||||
|
||||
Link the release's PRs. Do not quote commit counts or defect tallies — a number written about the
|
||||
repository inside the repository goes stale the moment it is committed, which
|
||||
`docs/AI-DISCLOSURE.md` learned three times.
|
||||
|
||||
## One version per session
|
||||
|
||||
Each working session takes **one** item — a `docs/ROADMAP.md` entry, or something that surfaced
|
||||
while doing it — takes it deep, tests it properly, and ships it as **one version**, plus a patch
|
||||
release if that version needs a hotfix. That is why entries here are small and frequent rather than
|
||||
large and rare, and it is written down in `CLAUDE.md` under *Conventions*.
|
||||
@@ -238,6 +238,9 @@ enum Command {
|
||||
fix: bool,
|
||||
},
|
||||
|
||||
/// Check the environment against the PyPI advisory database.
|
||||
Audit,
|
||||
|
||||
/// Upgrade pip inside the selected environment.
|
||||
PipUpgrade,
|
||||
|
||||
@@ -386,6 +389,7 @@ async fn main() -> ExitCode {
|
||||
}
|
||||
Command::Schema { type_name } => run::schema(type_name),
|
||||
Command::Env(EnvCommand::Use { path }) => run::env_use(&cli.global, path).await,
|
||||
Command::Audit => run::audit(&cli.global).await,
|
||||
Command::PipUpgrade => run::pip_upgrade(&cli.global).await,
|
||||
Command::Snapshot(SnapshotCommand::Rollback { id }) => {
|
||||
run::snapshot_rollback(&cli.global, id).await
|
||||
|
||||
+177
-11
@@ -316,7 +316,7 @@ pub async fn doctor(opts: &GlobalOpts) -> Result<Exit> {
|
||||
// is optional, and a fresh install exiting 1 because it has not built a tools venv yet would
|
||||
// make `doctor` useless as a health check for everything else.
|
||||
let tools = health::tools_dir(&app_data_dir());
|
||||
let tools_need = health::needs_sync(&tools);
|
||||
let tools_need = health::needs_sync(&tools, health::HEALTH_TOOLS);
|
||||
|
||||
if opts.json {
|
||||
println!(
|
||||
@@ -649,6 +649,22 @@ fn decide(
|
||||
out
|
||||
}
|
||||
|
||||
/// One blocker, as a sentence.
|
||||
///
|
||||
/// Assembled here because this head is English-only (PRD P0-14) and `plan::Blocker` carries data
|
||||
/// rather than phrasing (hard invariant 4). The GUI builds the same sentence from `plan.blocker`
|
||||
/// in its own catalogs; the shape mirrors the guard's, which composes `BrokenDependent` the same
|
||||
/// way a few hundred lines below.
|
||||
///
|
||||
/// No culprit means no culprit: ARCHITECTURE §3 says show the constraint rather than guess.
|
||||
fn blocker_line(b: &plan::Blocker) -> String {
|
||||
match (&b.by, &b.version) {
|
||||
(Some(by), Some(v)) => format!("{by} {v} requires {}", b.constraint),
|
||||
(Some(by), None) => format!("{by} requires {}", b.constraint),
|
||||
(None, _) => b.constraint.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-package prompt from CLI-SPEC §4.
|
||||
fn prompt_decision(held: &plan::HeldBack) -> plan::Decision {
|
||||
use std::io::Write as _;
|
||||
@@ -658,7 +674,7 @@ fn prompt_decision(held: &plan::HeldBack) -> plan::Decision {
|
||||
held.pkg, held.resolved, held.latest
|
||||
);
|
||||
for blocker in &held.blockers {
|
||||
println!(" — {}", blocker.constraint);
|
||||
println!(" — {}", blocker_line(blocker));
|
||||
}
|
||||
print!(" [C]ompatible (default) [S]kip [F]orce latest: ");
|
||||
let _ = std::io::stdout().flush();
|
||||
@@ -716,7 +732,7 @@ fn print_preview(opts: &GlobalOpts, report: &plan::ResolutionReport) {
|
||||
for h in &report.held_back {
|
||||
println!(" {:<32} {} (latest {})", h.pkg, h.resolved, h.latest);
|
||||
for b in &h.blockers {
|
||||
println!(" {}", b.constraint);
|
||||
println!(" {}", blocker_line(b));
|
||||
}
|
||||
if h.blockers.is_empty() {
|
||||
// ARCHITECTURE §3: no culprit is invented, and the row says so plainly rather
|
||||
@@ -804,7 +820,7 @@ pub async fn tools_sync(opts: &GlobalOpts, force: bool, python: Option<&Path>) -
|
||||
let dir = health::tools_dir(&app_data_dir());
|
||||
|
||||
if !force {
|
||||
let need = health::needs_sync(&dir)?;
|
||||
let need = health::needs_sync(&dir, health::HEALTH_TOOLS)?;
|
||||
if !need.is_needed() {
|
||||
if opts.json {
|
||||
println!(
|
||||
@@ -849,8 +865,12 @@ pub async fn tools_sync(opts: &GlobalOpts, force: bool, python: Option<&Path>) -
|
||||
// handler, and the flows build their own tokens for the GUI's `plan_cancel` to reach. Killing
|
||||
// the process still tears the tree down — `exec::TreeGuard`'s job object closes with the last
|
||||
// handle — which is verified rather than assumed: a killed sync leaves no orphan pip.
|
||||
let sink = engine::ProgressSink::new(tx, health::SYNC_STEPS, CancellationToken::new());
|
||||
let manifest = health::sync_tools_venv(&dir, &base, &sink).await;
|
||||
let sink = engine::ProgressSink::new(
|
||||
tx,
|
||||
health::sync_steps(health::HEALTH_TOOLS),
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let manifest = health::sync_tools_venv(&dir, &base, health::HEALTH_TOOLS, &sink).await;
|
||||
drop(sink);
|
||||
let _ = pump.await;
|
||||
let manifest = manifest?;
|
||||
@@ -869,6 +889,143 @@ pub async fn tools_sync(opts: &GlobalOpts, force: bool, python: Option<&Path>) -
|
||||
Ok(Exit::Success)
|
||||
}
|
||||
|
||||
/// `pipdock audit` — CLI-SPEC §3, PRD P1-1.
|
||||
///
|
||||
/// Exits **1 on findings**, the way `health` does: an advisory is a result, not a failure, and a
|
||||
/// script wants to branch on it. A pip-audit that could not run is a different thing and exits on
|
||||
/// its catalog code.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-ENG-001` or `PD-ENV-*` when the environment cannot be read or frozen, `PD-NET-011` when the
|
||||
/// audit venv cannot be bootstrapped.
|
||||
pub async fn audit(opts: &GlobalOpts) -> Result<Exit> {
|
||||
use pipdock_core::audit;
|
||||
|
||||
let env = select_env(opts).await?;
|
||||
let app_data = app_data_dir();
|
||||
let store = Store::open(&app_data)?;
|
||||
let engine = engine::for_id(settings::load(&store)?.engine);
|
||||
drop(store);
|
||||
|
||||
// Taken before the venv is touched, so an unreadable environment fails before a 15-second
|
||||
// bootstrap rather than after one.
|
||||
let freeze = engine.freeze(&env).await?;
|
||||
|
||||
let dir = health::audit_dir(&app_data);
|
||||
let sync_needed = health::needs_sync(&dir, health::AUDIT_TOOLS)?.is_needed();
|
||||
let synced = if sync_needed {
|
||||
health::sync_steps(health::AUDIT_TOOLS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<ProgressEvent>();
|
||||
let quiet = opts.quiet;
|
||||
let pump = tokio::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
if let Some(line) = event.line().filter(|_| !quiet) {
|
||||
eprintln!("{line}");
|
||||
}
|
||||
}
|
||||
});
|
||||
let sink = engine::ProgressSink::new(tx, audit::AUDIT_STEPS + synced, CancellationToken::new());
|
||||
|
||||
let outcome = async {
|
||||
if sync_needed {
|
||||
if !opts.quiet && !opts.json {
|
||||
println!("building the audit environment (first run)…");
|
||||
}
|
||||
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
|
||||
health::sync_tools_venv(&dir, &python, health::AUDIT_TOOLS, &sink).await?;
|
||||
}
|
||||
// Said before the wait rather than after it: 18-68 seconds of silence reads as a hang, and
|
||||
// this is the one command whose cost is a network fetch the user cannot see.
|
||||
if !opts.quiet && !opts.json {
|
||||
println!(
|
||||
"checking {} packages against the advisory database…",
|
||||
freeze.lines().count()
|
||||
);
|
||||
}
|
||||
audit::run(&dir, &env, &freeze, &sink.at(synced)).await
|
||||
}
|
||||
.await;
|
||||
|
||||
drop(sink);
|
||||
let _ = pump.await;
|
||||
let report = outcome?;
|
||||
|
||||
if opts.json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&report).map_err(|e| PdError::new(
|
||||
Code::IntUnexpected,
|
||||
format!("serialize the audit report: {e}")
|
||||
))?
|
||||
);
|
||||
} else {
|
||||
print_audit(&report);
|
||||
}
|
||||
|
||||
// A tool problem outranks the findings: a report with an empty list because pip-audit never ran
|
||||
// must not exit 0 and read as "nothing wrong here".
|
||||
if let Some(problem) = report.problems.first() {
|
||||
return Ok(exit_for(problem.code));
|
||||
}
|
||||
Ok(if report.has_findings() {
|
||||
Exit::PartialFailure
|
||||
} else {
|
||||
Exit::Success
|
||||
})
|
||||
}
|
||||
|
||||
/// The human form of an audit report.
|
||||
fn print_audit(report: &pipdock_core::audit::AuditReport) {
|
||||
if report.cancelled {
|
||||
println!("stopped before it finished; nothing below is complete");
|
||||
}
|
||||
for problem in &report.problems {
|
||||
eprintln!("error[{}]: {}", problem.code, problem.message);
|
||||
}
|
||||
if report.advisories.is_empty() && report.problems.is_empty() {
|
||||
println!(
|
||||
"no known advisories against {} packages (pip-audit {})",
|
||||
report.packages, report.tool_version
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut current = String::new();
|
||||
for a in &report.advisories {
|
||||
let pkg = a.pkg.to_string();
|
||||
if pkg != current {
|
||||
println!("\n{pkg} {}", a.version);
|
||||
current = pkg;
|
||||
}
|
||||
// The fix is the actionable half, so it leads. "no fix" is stated rather than left blank:
|
||||
// an advisory nothing upgrades away is the one worth reading the description for.
|
||||
let fix = if a.fix_versions.is_empty() {
|
||||
"no fix".to_owned()
|
||||
} else {
|
||||
format!("fixed in {}", a.fix_versions.join(", "))
|
||||
};
|
||||
println!(" {:<20} {fix}", a.id);
|
||||
if !a.aliases.is_empty() {
|
||||
println!(" {:<20} {}", "", a.aliases.join(", "));
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"\n{} advisories across {} of {} packages",
|
||||
report.advisories.len(),
|
||||
report
|
||||
.advisories
|
||||
.iter()
|
||||
.map(|a| a.pkg.to_string())
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len(),
|
||||
report.packages
|
||||
);
|
||||
}
|
||||
|
||||
/// `pipdock health`
|
||||
///
|
||||
/// Exits **1 when any tool reported a finding**, 0 when all of them were clean. A linter that
|
||||
@@ -914,7 +1071,7 @@ pub async fn health(
|
||||
};
|
||||
|
||||
let tools_dir = health::tools_dir(&app_data);
|
||||
let sync_needed = health::needs_sync(&tools_dir)?.is_needed();
|
||||
let sync_needed = health::needs_sync(&tools_dir, health::HEALTH_TOOLS)?.is_needed();
|
||||
let run_opts = health::RunOptions {
|
||||
tools: tools.iter().map(|t| t.as_str().to_owned()).collect(),
|
||||
..health::RunOptions::default()
|
||||
@@ -922,7 +1079,12 @@ pub async fn health(
|
||||
|
||||
// The total is decided **before** the first event. A progress bar cannot learn its own total
|
||||
// halfway, and whether a sync is owed is exactly the thing that changes it.
|
||||
let total = health::run_steps(&run_opts) + if sync_needed { health::SYNC_STEPS } else { 0 };
|
||||
let total = health::run_steps(&run_opts)
|
||||
+ if sync_needed {
|
||||
health::sync_steps(health::HEALTH_TOOLS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<ProgressEvent>();
|
||||
let quiet = opts.quiet;
|
||||
let pump = tokio::spawn(async move {
|
||||
@@ -940,14 +1102,18 @@ pub async fn health(
|
||||
println!("building the Code Health tools environment (first run)…");
|
||||
}
|
||||
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
|
||||
health::sync_tools_venv(&tools_dir, &python, &sink).await?;
|
||||
health::sync_tools_venv(&tools_dir, &python, health::HEALTH_TOOLS, &sink).await?;
|
||||
}
|
||||
health::run_tools(
|
||||
&tools_dir,
|
||||
&project,
|
||||
&env,
|
||||
&run_opts,
|
||||
&sink.at(if sync_needed { health::SYNC_STEPS } else { 0 }),
|
||||
&sink.at(if sync_needed {
|
||||
health::sync_steps(health::HEALTH_TOOLS)
|
||||
} else {
|
||||
0
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1173,7 +1339,7 @@ fn print_health(opts: &GlobalOpts, report: &health::HealthReport) {
|
||||
/// `PD-PKG-002` when the shipped pin ledger is malformed — a build-time mistake.
|
||||
pub async fn tools_status(opts: &GlobalOpts) -> Result<Exit> {
|
||||
let dir = health::tools_dir(&app_data_dir());
|
||||
let need = health::needs_sync(&dir)?;
|
||||
let need = health::needs_sync(&dir, health::HEALTH_TOOLS)?;
|
||||
let manifest = health::read_manifest(&dir);
|
||||
|
||||
if opts.json {
|
||||
|
||||
@@ -9,8 +9,11 @@
|
||||
//! * the clap surface — every command's help, which is the flag contract scripts read;
|
||||
//! * the exhaustive exit-code table (CLI-SPEC §5), which the docs call a public contract;
|
||||
//! * the `--json` error envelope;
|
||||
//! * `pipdock schema <T>` for every type in `SCHEMA_TYPES` — 25 as of Phase 3 P3 — which is the
|
||||
//! JSON contract CLI-SPEC §6 promises consumers can pin against.
|
||||
//! * `pipdock schema <T>` for every type in `SCHEMA_TYPES` — the list below, which
|
||||
//! `schema_lists_exactly_the_documented_types` holds to the binary's own — which is the JSON
|
||||
//! contract CLI-SPEC §6 promises consumers can pin against. No count is written here on
|
||||
//! purpose: the one that was ("25 as of Phase 3 P3") was five behind by 1.1.0, and the list is
|
||||
//! both authoritative and one screen down.
|
||||
//!
|
||||
//! That last one earns its keep beyond regression cover: the M2 bridge changes the wire format to
|
||||
//! camelCase and makes `Code` serialize as `PD-*` rather than as its Rust variant name. These
|
||||
@@ -38,6 +41,10 @@ const SCHEMA_TYPES: &[&str] = &[
|
||||
"ResolutionReport",
|
||||
"ExecutionSummary",
|
||||
"Pin",
|
||||
"PinSuggestion",
|
||||
"ParsedRequirements",
|
||||
"CacheUsage",
|
||||
"CacheTarget",
|
||||
"GuardReport",
|
||||
"Diff",
|
||||
"SnapshotMeta",
|
||||
@@ -54,6 +61,7 @@ const SCHEMA_TYPES: &[&str] = &[
|
||||
"Intent",
|
||||
"Code",
|
||||
"HealthReport",
|
||||
"AuditReport",
|
||||
"FixReport",
|
||||
];
|
||||
|
||||
@@ -118,6 +126,7 @@ fn every_command_documents_itself() {
|
||||
"snapshot",
|
||||
"doctor",
|
||||
"health",
|
||||
"audit",
|
||||
"pip-upgrade",
|
||||
"engine",
|
||||
"index",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: "stdout_of(&[cmd, \"--help\"])"
|
||||
---
|
||||
Check the environment against the PyPI advisory database
|
||||
|
||||
Usage: pipdock audit [OPTIONS]
|
||||
|
||||
Options:
|
||||
--env <PATH>
|
||||
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
|
||||
|
||||
--engine <ENGINE>
|
||||
Override the configured engine for this invocation
|
||||
|
||||
Possible values:
|
||||
- pip: `<python> -m pip`
|
||||
- uv: `uv pip --python <python>`
|
||||
|
||||
--json
|
||||
Machine-readable output; NDJSON for streaming commands
|
||||
|
||||
-y, --yes
|
||||
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
|
||||
|
||||
--quiet
|
||||
Reduce log output
|
||||
|
||||
--verbose
|
||||
Increase log output
|
||||
|
||||
--log-file <PATH>
|
||||
Tee logs to a file
|
||||
|
||||
--no-snapshot
|
||||
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
|
||||
|
||||
This is the sole documented escape from DATA-FLOW §9.2, and it exists because a throwaway CI container has nothing to roll back to.
|
||||
|
||||
-h, --help
|
||||
Print help (see a summary with '-h')
|
||||
@@ -19,6 +19,7 @@ Commands:
|
||||
snapshot Manage snapshots
|
||||
doctor Engine check and environment sanity report
|
||||
health Run Code Health (deptry / vulture / ruff) over a project folder
|
||||
audit Check the environment against the PyPI advisory database
|
||||
pip-upgrade Upgrade pip inside the selected environment
|
||||
engine Show or set the configured engine
|
||||
index Index maintenance
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: out
|
||||
---
|
||||
{
|
||||
"$defs": {
|
||||
"Advisory": {
|
||||
"description": "One advisory against one installed distribution.",
|
||||
"properties": {
|
||||
"aliases": {
|
||||
"default": [],
|
||||
"description": "Other ids for the same advisory, which is where the `CVE-*` and `GHSA-*` live.\n\nPRD P1-1 says \"known CVEs\"; a CVE is never the primary id here, so a screen that wants to\nshow one reads this.",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"description": {
|
||||
"description": "The advisory prose, verbatim. Never translated (I18N §2) and never trimmed here.",
|
||||
"type": "string"
|
||||
},
|
||||
"fixVersions": {
|
||||
"default": [],
|
||||
"description": "Versions that fix it. **Empty is meaningful** — an advisory with nowhere to upgrade to —\nand [`sort_advisories`] puts those last rather than hiding them.",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"id": {
|
||||
"description": "pip-audit's primary id — `PYSEC-*` under the default service.",
|
||||
"type": "string"
|
||||
},
|
||||
"pkg": {
|
||||
"$ref": "#/$defs/PkgName",
|
||||
"description": "The installed distribution the advisory is against."
|
||||
},
|
||||
"url": {
|
||||
"description": "The OSV entry, when the id is shaped like one.\n\n**Built from a validated id rather than taken from the tool**, which is the whole\ndifference between this and `PdHealthReport`'s `finding.url`.\n`capabilities/external-links.json` records that ruff's URL is the only one in the\napplication derived from a third party's output; this one is derived from a string PipDock\nhas checked, so widening the allowlist to `osv.dev` does not widen what can reach it.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"version": {
|
||||
"$ref": "#/$defs/Version",
|
||||
"description": "The version installed, not the version that fixes it."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pkg",
|
||||
"version",
|
||||
"id",
|
||||
"description"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"Code": {
|
||||
"description": "Every code PipDock can surface at v1 launch.\n\n`docs/TESTING.md` §2 requires at least one captured stderr fixture per variant before ship;\nthe test that enforces \"no code without fixture\" lives beside the classifiers.",
|
||||
"oneOf": [
|
||||
{
|
||||
"const": "PD-ENV-001",
|
||||
"description": "Interpreter path missing or not executable — the env was deleted or moved.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-ENV-002",
|
||||
"description": "PEP 668 `EXTERNALLY-MANAGED` marker present; mutation blocked by default.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-ENV-003",
|
||||
"description": "`probe.py` exited non-zero or produced unparseable output.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-ENG-001",
|
||||
"description": "pip or uv binary not found.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-ENG-002",
|
||||
"description": "pip older than 22.2, which predates `--dry-run --report`.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-ENG-003",
|
||||
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-ENG-999",
|
||||
"description": "Fallback for engine failures no classifier matched. Always last.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-001",
|
||||
"description": "`ResolutionImpossible` or the uv equivalent: constraints cannot be satisfied.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-002",
|
||||
"description": "Plan older than 10 minutes, or the env's probe hash changed since the preview.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-003",
|
||||
"description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-004",
|
||||
"description": "A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5).\n\nIts own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means \"no\nmatching distribution\" — the opposite of the truth: every package involved exists, and\nthat is precisely why the removal is being refused. A user grepping their logs for a typo\nwould have found this instead.\n\nNot raised when the guard merely *finds* dependents. That is a report the caller shows and\nthe user answers; the code appears only when execution is attempted anyway without the\nuser having accepted the breakage.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-BLD-001",
|
||||
"description": "MSVC build tools required but absent.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-BLD-002",
|
||||
"description": "Build backend failed (`pyproject.toml` error, `metadata-generation-failed`).",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-BLD-003",
|
||||
"description": "Generic sdist wheel-build failure.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PKG-001",
|
||||
"description": "No matching distribution, and metadata shows a requires-python mismatch.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PKG-002",
|
||||
"description": "No matching distribution: name or version typo, or the release is gone.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PKG-003",
|
||||
"description": "The requested release was yanked.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PKG-004",
|
||||
"description": "Downloaded artifact failed hash verification.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-NET-001",
|
||||
"description": "Timeout, connection aborted, or DNS failure.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-NET-002",
|
||||
"description": "TLS/SSL verification failed — typically proxy or AV interception.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-NET-010",
|
||||
"description": "PEP 691 index refresh failed; the stale index stays searchable.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-NET-011",
|
||||
"description": "Code Health tools-venv bootstrap could not reach PyPI.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PRM-001",
|
||||
"description": "`PermissionError` writing site-packages (admin-owned Python).",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PRM-002",
|
||||
"description": "File locked by a running process (`WinError 32`).",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-PRM-003",
|
||||
"description": "A source file in the user's project cannot be written.\n\n**Not `PD-PRM-001`.** That one is scoped to site-packages and its catalogued action is\n\"use a venv\", which is nonsense advice for a read-only `util.py` — the same class of wrong\nanswer P3 removed when a corrupted `ruff.exe` reported `PD-ENG-001`, \"install the engine\".\n\nRaised by PipDock **before anything is written**, never classified from stderr: ruff can\nfail to write a file and still exit 1, which `is_findings_exit` accepts as a clean run, so\na stderr-matched code would arrive after a fix had already reported success.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-SNP-001",
|
||||
"description": "Snapshot write failed before execution. **The plan is aborted; nothing runs.**",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-SNP-002",
|
||||
"description": "A release needed to restore a snapshot is no longer available on PyPI.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-SYS-001",
|
||||
"description": "`MAX_PATH` exceeded without the long-path opt-in.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-SYS-002",
|
||||
"description": "Disk full.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-HLT-001",
|
||||
"description": "A Code Health tool is missing from the tools venv.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-HLT-002",
|
||||
"description": "A Code Health tool exited non-zero.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-HLT-003",
|
||||
"description": "A Code Health tool exceeded its watchdog timeout; partial report shown.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-HLT-004",
|
||||
"description": "`python -m venv` failed while building the tools environment.\n\n**Raised by PipDock, not classified from engine stderr.** Its own code rather than a reused\none: `PD-NET-011` is `Area::Net`, so `run::exit_for` would map a broken interpreter to exit\n6 and a script retrying on network failure would loop forever; `PD-HLT-001` tells the user\nto re-sync, which is the operation that just failed; and a Python built without `venv` is\nnot `PD-INT-001`'s \"a PipDock bug\".",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-INT-001",
|
||||
"description": "A PipDock bug: panic or unexpected state.",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"PkgName": {
|
||||
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
|
||||
"type": "string"
|
||||
},
|
||||
"ToolProblem": {
|
||||
"description": "One tool that was asked to run and did not finish.\n\nDeliberately `PdError`-shaped so the UI can hand it straight to `PdErrorRow` rather than\ninventing a second error presentation for the same catalog codes.",
|
||||
"properties": {
|
||||
"code": {
|
||||
"$ref": "#/$defs/Code",
|
||||
"description": "The catalog code, so the row is localized from the same table as every other error."
|
||||
},
|
||||
"message": {
|
||||
"description": "Developer-facing detail. Never shown as-is (I18N §1).",
|
||||
"type": "string"
|
||||
},
|
||||
"stderrTail": {
|
||||
"description": "Tail of the tool's stderr, capped as ERROR-CATALOG §3 caps every other one.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"tool": {
|
||||
"description": "Which tool: `deptry`, `vulture` or `ruff`.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"tool",
|
||||
"code",
|
||||
"message"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"Version": {
|
||||
"description": "A version string as the engine reported it. Never reshaped or localized (I18N §2).",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"description": "What a Security-tab run produced.\n\nShaped like [`crate::health::HealthReport`] deliberately: a `problems` list rather than an\nearly return, so a failed audit still *returns a report* and the screen renders one error row\ninstead of nothing at all. That shape is what makes a partial result expressible.",
|
||||
"properties": {
|
||||
"advisories": {
|
||||
"default": [],
|
||||
"description": "Deduplicated and ordered by [`sort_advisories`].",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Advisory"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"cancelled": {
|
||||
"default": false,
|
||||
"description": "The user stopped it.\n\nA **state, not an error**, which is the shape `ExecutionSummary.cancelled` established: the\nuser asking a run to stop is not a tool failure, so nothing lands in `problems` and no\ncatalog code is minted for something that went right. It matters here in a way it did not\nfor Code Health, whose runs are 1.3 s — an audit is 18-68 s, which is long enough that\nstopping one is an ordinary thing to want.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"env": {
|
||||
"description": "`canonical_interpreter` of the environment audited. Data, never localized (I18N §2).",
|
||||
"type": "string"
|
||||
},
|
||||
"packages": {
|
||||
"description": "Distributions the freeze document listed.\n\n**Separate from `advisories.len()`**, because \"audited 145 packages and found nothing\" and\n\"audited nothing\" are different answers. A screen that cannot tell them apart tells P4's\nlie — *no issues found* before anything has run.",
|
||||
"format": "uint",
|
||||
"minimum": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"problems": {
|
||||
"description": "Why the run contributed nothing. Empty means it completed.",
|
||||
"items": {
|
||||
"$ref": "#/$defs/ToolProblem"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"ranAt": {
|
||||
"description": "When the run finished, RFC 3339.",
|
||||
"type": "string"
|
||||
},
|
||||
"toolVersion": {
|
||||
"description": "pip-audit's version, out of the audit venv's manifest. Empty if it has never synced.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"env",
|
||||
"ranAt",
|
||||
"toolVersion",
|
||||
"packages"
|
||||
],
|
||||
"title": "AuditReport",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: out
|
||||
---
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"description": "Something the user can be offered a *Clear* button for.",
|
||||
"oneOf": [
|
||||
{
|
||||
"const": "snapshots",
|
||||
"description": "Every snapshot of every environment. Rollback loses its history; nothing else changes.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "tools",
|
||||
"description": "The isolated environment Code Health runs deptry, vulture and ruff from. Rebuilt on the\nnext run, or by `pipdock tools sync`.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "audit",
|
||||
"description": "The isolated environment the Security tab runs pip-audit from. Rebuilt on the next audit.\n\nA **separate** target rather than part of [`Self::Tools`], because it is a separate venv:\nP1-1 kept pip-audit out of Code Health's so that its `msgpack` dependency cannot fail the\nwhole sync. Two directories on disk are two rows here, or \"clear the cache\" would leave one\nof them behind while reporting it gone.",
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"title": "Target"
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: out
|
||||
---
|
||||
{
|
||||
"$defs": {
|
||||
"Entry": {
|
||||
"description": "One line of the cache report.",
|
||||
"properties": {
|
||||
"bytes": {
|
||||
"description": "Bytes on disk, summed recursively.",
|
||||
"format": "uint64",
|
||||
"minimum": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"exists": {
|
||||
"description": "False when nothing is there yet, so the UI can say \"nothing to clear\" rather than \"0 B\".",
|
||||
"type": "boolean"
|
||||
},
|
||||
"path": {
|
||||
"description": "Where it is. Data — shown verbatim, never translated (I18N §2).",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bytes",
|
||||
"path",
|
||||
"exists"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"description": "What PipDock is using, by artefact.",
|
||||
"properties": {
|
||||
"audit": {
|
||||
"$ref": "#/$defs/Entry",
|
||||
"description": "The Security tab's pip-audit environment (PRD P1-1)."
|
||||
},
|
||||
"database": {
|
||||
"$ref": "#/$defs/Entry",
|
||||
"description": "`index.db` — the package index, settings, pins and the consent record. **Not clearable.**"
|
||||
},
|
||||
"root": {
|
||||
"description": "The data root everything below lives in.",
|
||||
"type": "string"
|
||||
},
|
||||
"snapshotCount": {
|
||||
"description": "How many snapshot documents there are, across every environment.",
|
||||
"format": "uint",
|
||||
"minimum": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"snapshots": {
|
||||
"$ref": "#/$defs/Entry",
|
||||
"description": "Snapshots, across every environment."
|
||||
},
|
||||
"tools": {
|
||||
"$ref": "#/$defs/Entry",
|
||||
"description": "The Code Health tools environment."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"root",
|
||||
"database",
|
||||
"snapshots",
|
||||
"tools",
|
||||
"audit",
|
||||
"snapshotCount"
|
||||
],
|
||||
"title": "Usage",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -19,8 +19,15 @@ expression: out
|
||||
"description": "The package imposing the constraint, absent when attribution is ambiguous."
|
||||
},
|
||||
"constraint": {
|
||||
"description": "The constraint text, e.g. `\"requests<2.31\"`.",
|
||||
"description": "The requirement holding the package back, e.g. `\"requests<2.31\"`.\n\n**Data, not a sentence** — hard invariant 4. Until Slice 0 this carried\n`\"scipy 1.11.4 requires numpy <1.28.0,>=1.21.6\"`, a phrase assembled in Rust, which the\nGUI then wrapped in `\"{{by}} requires {{constraint}}\"` and rendered naming the dependent\n**twice**. Only the CLI looked right, because it prints this field alone. The shape here\nnow matches `BrokenDependent.constraint`, which the guard dialog has always composed\ncorrectly.",
|
||||
"type": "string"
|
||||
},
|
||||
"version": {
|
||||
"description": "The installed version of [`Self::by`], when the probe knew it.\n\nSplit out for the same reason [`crate::graph::BrokenDependent`] splits it: the two heads\nphrase this differently — the CLI writes `scipy 1.11.4 requires …` itself, the GUI\ninterpolates `plan.blocker` — and neither can un-join a string Rust joined for it.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: out
|
||||
---
|
||||
{
|
||||
"$defs": {
|
||||
"SkipReason": {
|
||||
"description": "Why a line was not turned into a spec.",
|
||||
"oneOf": [
|
||||
{
|
||||
"const": "include",
|
||||
"description": "`-r` or `-c`: another file, which PipDock has not read.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "not-from-index",
|
||||
"description": "`-e`, or a `name @ url` / VCS requirement: installs from somewhere other than the index.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "option",
|
||||
"description": "An option line (`--index-url`, `--extra-index-url`, …) that changes how *everything*\ninstalls. Honouring one silently would change the meaning of the whole file.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "unparsed",
|
||||
"description": "The line is not a requirement PipDock can parse at all.",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"SkippedLine": {
|
||||
"description": "A line the parser would not turn into an install spec, and what was wrong with it.",
|
||||
"properties": {
|
||||
"line": {
|
||||
"description": "1-based, so it matches what an editor shows.",
|
||||
"format": "uint",
|
||||
"minimum": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"reason": {
|
||||
"$ref": "#/$defs/SkipReason",
|
||||
"description": "Why, as a catalog-style discriminant the UI turns into a sentence."
|
||||
},
|
||||
"text": {
|
||||
"description": "The line, trimmed. Data — shown verbatim, never translated (I18N §2).",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"line",
|
||||
"text",
|
||||
"reason"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"description": "What [`parse`] made of a file.",
|
||||
"properties": {
|
||||
"skipped": {
|
||||
"description": "Everything else, with its line number and reason.",
|
||||
"items": {
|
||||
"$ref": "#/$defs/SkippedLine"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"specs": {
|
||||
"description": "Install specs, in file order, as `Intent::Install` wants them.",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"specs",
|
||||
"skipped"
|
||||
],
|
||||
"title": "ParsedRequirements",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: out
|
||||
---
|
||||
{
|
||||
"$defs": {
|
||||
"PkgName": {
|
||||
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"description": "A package worth pinning, and why — PRD P1-2, UI-SPEC §4.",
|
||||
"properties": {
|
||||
"dependents": {
|
||||
"description": "How many installed packages depend on it.\n\nThe number is the whole argument, so it is carried rather than recomputed for display:\n\"12 packages depend on it\" is what makes the suggestion actionable, and a count the screen\nderived separately would eventually disagree with the one that qualified it.",
|
||||
"format": "uint",
|
||||
"minimum": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"pkg": {
|
||||
"$ref": "#/$defs/PkgName",
|
||||
"description": "The package being suggested."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pkg",
|
||||
"dependents"
|
||||
],
|
||||
"title": "PinSuggestion",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -19,8 +19,15 @@ expression: out
|
||||
"description": "The package imposing the constraint, absent when attribution is ambiguous."
|
||||
},
|
||||
"constraint": {
|
||||
"description": "The constraint text, e.g. `\"requests<2.31\"`.",
|
||||
"description": "The requirement holding the package back, e.g. `\"requests<2.31\"`.\n\n**Data, not a sentence** — hard invariant 4. Until Slice 0 this carried\n`\"scipy 1.11.4 requires numpy <1.28.0,>=1.21.6\"`, a phrase assembled in Rust, which the\nGUI then wrapped in `\"{{by}} requires {{constraint}}\"` and rendered naming the dependent\n**twice**. Only the CLI looked right, because it prints this field alone. The shape here\nnow matches `BrokenDependent.constraint`, which the guard dialog has always composed\ncorrectly.",
|
||||
"type": "string"
|
||||
},
|
||||
"version": {
|
||||
"description": "The installed version of [`Self::by`], when the probe knew it.\n\nSplit out for the same reason [`crate::graph::BrokenDependent`] splits it: the two heads\nphrase this differently — the CLI writes `scipy 1.11.4 requires …` itself, the GUI\ninterpolates `plan.blocker` — and neither can un-join a string Rust joined for it.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: "stderr_of(&[\"schema\", \"NoSuchType\"])"
|
||||
---
|
||||
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, GuardReport, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, FixReport
|
||||
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, AuditReport, FixReport
|
||||
@@ -0,0 +1,757 @@
|
||||
//! pip-audit over an installed environment — PRD P1-1, SECURITY §6.
|
||||
//!
|
||||
//! Runs out of **its own venv** ([`crate::health::AUDIT_TOOLS`], [`crate::health::audit_dir`]) and
|
||||
//! in freeze-file mode, which SP-4 established is the only mode there is: `--path <site-packages>`
|
||||
//! is rejected outright when combined with `--no-deps`, so the environment reaches the tool as a
|
||||
//! `pip freeze` document rather than as a directory.
|
||||
//!
|
||||
//! Four things this module exists to get right, every one measured against the pinned 2.10.1
|
||||
//! rather than read out of a document (`tests/fixtures/audit/`):
|
||||
//!
|
||||
//! 1. **The ids are `PYSEC-*`, because the default vulnerability service is PyPI.** Left as the
|
||||
//! default deliberately: PipDock querying `api.osv.dev` itself would add a second network
|
||||
//! destination and falsify `legal/PRIVACY-POLICY.md` §3's "exactly one destination". Findings
|
||||
//! still *link* to OSV, which is a visit the user's browser makes after a click — the case §3
|
||||
//! already carves out.
|
||||
//! 2. **There is no severity, under either service.** The vuln object carries exactly `id`,
|
||||
//! `fix_versions`, `aliases` and `description`. PRD P1-1's "severity-sorted" and SECURITY §6's
|
||||
//! "(CVE/GHSA id, severity, fixed-in)" were written against a field that has never existed, so
|
||||
//! [`sort_advisories`] sorts by what is real instead.
|
||||
//! 3. **Ids repeat.** The captured run returns ten rows for **eight** advisories; the same
|
||||
//! environment under `--vulnerability-service osv` returns sixteen rows and the *same* eight.
|
||||
//! A count taken before [`dedupe`] is wrong under either service.
|
||||
//! 4. **stderr is not a failure signal.** pip-audit writes a `pip-compile`/hashes advisory on
|
||||
//! every single run. Parse stdout first and classify only if that fails — the rule SP-1 left
|
||||
//! behind for uv, which writes its plan to stderr for the same reason.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::engine::ProgressSink;
|
||||
use crate::errors::{Code, PdError, Result};
|
||||
use crate::exec::Command;
|
||||
use crate::health::{ToolProblem, read_manifest, tool_exe};
|
||||
use crate::model::{ExecMode, PkgName, PyEnv, StepStatus, Version};
|
||||
|
||||
/// Where a finding links. The id is appended after validation — never interpolated raw.
|
||||
const OSV_BASE: &str = "https://osv.dev/vulnerability/";
|
||||
|
||||
/// One advisory against one installed distribution.
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Advisory {
|
||||
/// The installed distribution the advisory is against.
|
||||
pub pkg: PkgName,
|
||||
/// The version installed, not the version that fixes it.
|
||||
pub version: Version,
|
||||
/// pip-audit's primary id — `PYSEC-*` under the default service.
|
||||
pub id: String,
|
||||
/// Other ids for the same advisory, which is where the `CVE-*` and `GHSA-*` live.
|
||||
///
|
||||
/// PRD P1-1 says "known CVEs"; a CVE is never the primary id here, so a screen that wants to
|
||||
/// show one reads this.
|
||||
#[serde(default)]
|
||||
pub aliases: Vec<String>,
|
||||
/// Versions that fix it. **Empty is meaningful** — an advisory with nowhere to upgrade to —
|
||||
/// and [`sort_advisories`] puts those last rather than hiding them.
|
||||
#[serde(default)]
|
||||
pub fix_versions: Vec<String>,
|
||||
/// The advisory prose, verbatim. Never translated (I18N §2) and never trimmed here.
|
||||
pub description: String,
|
||||
/// The OSV entry, when the id is shaped like one.
|
||||
///
|
||||
/// **Built from a validated id rather than taken from the tool**, which is the whole
|
||||
/// difference between this and `PdHealthReport`'s `finding.url`.
|
||||
/// `capabilities/external-links.json` records that ruff's URL is the only one in the
|
||||
/// application derived from a third party's output; this one is derived from a string PipDock
|
||||
/// has checked, so widening the allowlist to `osv.dev` does not widen what can reach it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
/// The OSV entry for an advisory id, or `None` if the id is not shaped like one.
|
||||
///
|
||||
/// The check is a whitelist, not an escape: ASCII letters, digits and `-`, 4 to 64 characters,
|
||||
/// leading letter. Nothing that passes can carry a `/`, `?`, `#`, `:` or `%`, so the result cannot
|
||||
/// be anything but a path segment under [`OSV_BASE`] — which is what lets the opener allowlist
|
||||
/// stay scoped to one host. SECURITY §2's obligation follows the *input*, and this input is a
|
||||
/// third-party tool's JSON.
|
||||
#[must_use]
|
||||
pub fn advisory_url(id: &str) -> Option<String> {
|
||||
let ok = (4..=64).contains(&id.len())
|
||||
&& id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
|
||||
&& id.starts_with(|c: char| c.is_ascii_alphabetic());
|
||||
ok.then(|| format!("{OSV_BASE}{id}"))
|
||||
}
|
||||
|
||||
/// pip-audit's `-f json` document, only the parts PipDock reads.
|
||||
mod raw {
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct Doc {
|
||||
#[serde(default)]
|
||||
pub dependencies: Vec<Dep>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct Dep {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub vulns: Vec<Vuln>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct Vuln {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub fix_versions: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub aliases: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many distributions the run covered, and what it found.
|
||||
///
|
||||
/// The count is separate from `advisories.len()` on purpose: "audited 145 packages, found nothing"
|
||||
/// and "audited nothing" are different answers, and a screen that cannot tell them apart repeats
|
||||
/// P4's *no issues found before anything had run*.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Audited {
|
||||
/// Distributions present in the freeze document.
|
||||
pub packages: usize,
|
||||
/// Deduplicated and sorted.
|
||||
pub advisories: Vec<Advisory>,
|
||||
}
|
||||
|
||||
/// Parse a pip-audit `-f json` document.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-HLT-002` when stdout is not the document `--format json` promises. That is the only failure
|
||||
/// mode here: a non-zero exit is **not** one, because findings exit 1.
|
||||
pub fn parse(stdout: &str) -> Result<Audited> {
|
||||
let doc: raw::Doc = serde_json::from_str(stdout).map_err(|e| {
|
||||
PdError::new(
|
||||
Code::HltToolFailed,
|
||||
format!("pip-audit did not emit the JSON document --format json promises: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut advisories = Vec::new();
|
||||
for dep in &doc.dependencies {
|
||||
// A name pip-audit echoed back out of a freeze document PipDock wrote. Validated anyway:
|
||||
// it is the join key against the installed table, and an unparseable one would be a row
|
||||
// matching nothing rather than a row that is merely wrong.
|
||||
let Ok(pkg) = PkgName::parse(&dep.name) else {
|
||||
continue;
|
||||
};
|
||||
for vuln in &dep.vulns {
|
||||
advisories.push(Advisory {
|
||||
pkg: pkg.clone(),
|
||||
version: Version(dep.version.clone()),
|
||||
url: advisory_url(&vuln.id),
|
||||
id: vuln.id.clone(),
|
||||
aliases: vuln.aliases.clone(),
|
||||
fix_versions: vuln.fix_versions.clone(),
|
||||
description: vuln.description.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Audited {
|
||||
packages: doc.dependencies.len(),
|
||||
advisories: sort_advisories(dedupe(advisories)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Collapse advisories repeated for one package.
|
||||
///
|
||||
/// pip-audit emits the same id more than once — twice each for two of the eight in the captured
|
||||
/// run, and eight times each under the OSV service. The key is `(pkg, id)` rather than `id` alone,
|
||||
/// because one advisory legitimately applies to two different installed packages.
|
||||
#[must_use]
|
||||
pub fn dedupe(advisories: Vec<Advisory>) -> Vec<Advisory> {
|
||||
let mut seen = BTreeSet::new();
|
||||
advisories
|
||||
.into_iter()
|
||||
.filter(|a| seen.insert((a.pkg.clone(), a.id.clone())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Order: package, then whether anything fixes it, then id.
|
||||
///
|
||||
/// **Not severity.** PRD P1-1 asked for severity-sorted and pip-audit has no such field, so this
|
||||
/// sorts by the one distinction that changes what a user can *do*: an advisory with a
|
||||
/// `fix_versions` entry is one the normal Update flow can act on, and an advisory without one is
|
||||
/// not. Inventing a severity — from the id's year, from the description's wording — would be a
|
||||
/// number PipDock made up, shown beside real ones.
|
||||
#[must_use]
|
||||
pub fn sort_advisories(mut advisories: Vec<Advisory>) -> Vec<Advisory> {
|
||||
advisories.sort_by(|a, b| {
|
||||
a.pkg
|
||||
.cmp(&b.pkg)
|
||||
.then(a.fix_versions.is_empty().cmp(&b.fix_versions.is_empty()))
|
||||
.then(a.id.cmp(&b.id))
|
||||
});
|
||||
advisories
|
||||
}
|
||||
|
||||
/// The tool this module drives — one entry of [`crate::health::AUDIT_TOOLS`].
|
||||
///
|
||||
/// Named once so the argv, the manifest lookup and the [`ToolProblem`] row cannot disagree about
|
||||
/// which tool a failure is about.
|
||||
const TOOL: &str = "pip-audit";
|
||||
|
||||
/// How long pip-audit gets before the watchdog takes it.
|
||||
///
|
||||
/// **Not Code Health's `TOOL_TIMEOUT`**, and the difference is not a rounding error. That 120 s is
|
||||
/// sized for a linter walking a source tree; an audit is a *network* operation, and what dominates
|
||||
/// it is a one-off advisory-database fetch rather than the number of packages. Measured on this
|
||||
/// machine, release-irrelevant because the time is all I/O:
|
||||
///
|
||||
/// | Run | Wall clock |
|
||||
/// |---|---|
|
||||
/// | cold cache, **one** package | **68 s** |
|
||||
/// | warm cache, one package | 18.6 s |
|
||||
/// | warm cache, **twelve** packages | 20.0 s |
|
||||
///
|
||||
/// Twelve packages cost 1.4 s more than one, so a 352-package environment is not the risk — a cold
|
||||
/// fetch on a slow link is. The first run written against `TOOL_TIMEOUT` duly hit the watchdog at
|
||||
/// 120 s and reported `PD-HLT-003` for a tool that was working. Ten minutes matches
|
||||
/// `exec::DEFAULT_TIMEOUT`, which is what every other network-bound subprocess already gets.
|
||||
pub const AUDIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
|
||||
|
||||
/// How many steps a run reports, on top of whatever sync the caller had to do first.
|
||||
///
|
||||
/// One, because the freeze is the caller's — see [`run`].
|
||||
pub const AUDIT_STEPS: usize = 1;
|
||||
|
||||
/// What a Security-tab run produced.
|
||||
///
|
||||
/// Shaped like [`crate::health::HealthReport`] deliberately: a `problems` list rather than an
|
||||
/// early return, so a failed audit still *returns a report* and the screen renders one error row
|
||||
/// instead of nothing at all. That shape is what makes a partial result expressible.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuditReport {
|
||||
/// `canonical_interpreter` of the environment audited. Data, never localized (I18N §2).
|
||||
pub env: String,
|
||||
/// When the run finished, RFC 3339.
|
||||
pub ran_at: String,
|
||||
/// pip-audit's version, out of the audit venv's manifest. Empty if it has never synced.
|
||||
pub tool_version: String,
|
||||
/// Distributions the freeze document listed.
|
||||
///
|
||||
/// **Separate from `advisories.len()`**, because "audited 145 packages and found nothing" and
|
||||
/// "audited nothing" are different answers. A screen that cannot tell them apart tells P4's
|
||||
/// lie — *no issues found* before anything has run.
|
||||
pub packages: usize,
|
||||
/// Deduplicated and ordered by [`sort_advisories`].
|
||||
#[serde(default)]
|
||||
pub advisories: Vec<Advisory>,
|
||||
/// Why the run contributed nothing. Empty means it completed.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub problems: Vec<ToolProblem>,
|
||||
/// The user stopped it.
|
||||
///
|
||||
/// A **state, not an error**, which is the shape `ExecutionSummary.cancelled` established: the
|
||||
/// user asking a run to stop is not a tool failure, so nothing lands in `problems` and no
|
||||
/// catalog code is minted for something that went right. It matters here in a way it did not
|
||||
/// for Code Health, whose runs are 1.3 s — an audit is 18-68 s, which is long enough that
|
||||
/// stopping one is an ordinary thing to want.
|
||||
#[serde(default)]
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
impl AuditReport {
|
||||
/// Whether anything was found — the CLI's exit rule.
|
||||
#[must_use]
|
||||
pub fn has_findings(&self) -> bool {
|
||||
!self.advisories.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Audit one environment against its freeze document.
|
||||
///
|
||||
/// **The freeze is passed, not taken.** `Engine::freeze` is the caller's call, for the reason
|
||||
/// `UpdateFlow::start` takes pins rather than a `&Store`: this function would otherwise need an
|
||||
/// engine, which means settings, which means the store — and the store guard cannot be held across
|
||||
/// an await at a command boundary. It also keeps the module testable without a subprocess.
|
||||
///
|
||||
/// A failure does not propagate. It lands in [`AuditReport::problems`] and the report comes back
|
||||
/// anyway, so the screen has an error row and a package count rather than an empty screen.
|
||||
///
|
||||
/// # Errors
|
||||
/// Only if the step name cannot be parsed, which is a compile-time constant and so a bug.
|
||||
pub async fn run(
|
||||
audit_dir: &Path,
|
||||
env: &PyEnv,
|
||||
freeze: &str,
|
||||
sink: &ProgressSink,
|
||||
) -> Result<AuditReport> {
|
||||
let mut report = AuditReport {
|
||||
env: crate::exec::canonical_interpreter(&env.interpreter),
|
||||
ran_at: String::new(),
|
||||
tool_version: read_manifest(audit_dir)
|
||||
.and_then(|m| m.tools.get(TOOL).cloned())
|
||||
.unwrap_or_default(),
|
||||
packages: 0,
|
||||
advisories: Vec::new(),
|
||||
problems: Vec::new(),
|
||||
cancelled: false,
|
||||
};
|
||||
|
||||
let step = sink.at(sink.step);
|
||||
let name = PkgName::parse(TOOL)?;
|
||||
step.started(Some(name.clone()), ExecMode::Isolated);
|
||||
|
||||
match audit_once(audit_dir, freeze, sink).await {
|
||||
Ok(audited) => {
|
||||
report.packages = audited.packages;
|
||||
report.advisories = audited.advisories;
|
||||
step.finished(Some(name), ExecMode::Isolated, StepStatus::Ok);
|
||||
}
|
||||
// **Skipped, not Failed**, and no problem row — S1's rule that a step killed by us is not
|
||||
// a step that went wrong, applied to the one operation long enough for anyone to kill.
|
||||
Err(e) if is_cancellation(&e) => {
|
||||
report.cancelled = true;
|
||||
step.finished(Some(name), ExecMode::Isolated, StepStatus::Skipped);
|
||||
}
|
||||
Err(e) => {
|
||||
report.problems.push(ToolProblem {
|
||||
tool: TOOL.to_owned(),
|
||||
code: e.code,
|
||||
message: e.message,
|
||||
stderr_tail: e.stderr_tail,
|
||||
});
|
||||
step.finished(Some(name), ExecMode::Isolated, StepStatus::Failed);
|
||||
}
|
||||
}
|
||||
|
||||
report.ran_at = jiff::Timestamp::now().to_string();
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Spawn pip-audit over a freeze document and parse what it says.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-HLT-001` when the audit venv has no pip-audit, `PD-HLT-003` on its watchdog, `PD-HLT-002`
|
||||
/// when stdout is not the promised document.
|
||||
async fn audit_once(audit_dir: &Path, freeze: &str, sink: &ProgressSink) -> Result<Audited> {
|
||||
let exe = tool_exe(audit_dir, TOOL);
|
||||
if !exe.is_file() {
|
||||
return Err(PdError::new(
|
||||
Code::HltToolMissing,
|
||||
format!("{TOOL} is not in the audit environment"),
|
||||
));
|
||||
}
|
||||
|
||||
// The environment reaches pip-audit as a *document*, never as a directory: SP-4 found that
|
||||
// `--path <site-packages>` is rejected outright alongside `--no-deps`. Written to the system
|
||||
// temp directory rather than into the user's project or the environment being audited, and
|
||||
// removed on both paths.
|
||||
let freeze_path = crate::exec::write_temp("pipdock-audit", "txt", freeze)?;
|
||||
|
||||
let out = Command::new(&exe)
|
||||
.args(argv(&freeze_path))
|
||||
.timeout(AUDIT_TIMEOUT)
|
||||
.cancel(sink.cancel.clone())
|
||||
.run()
|
||||
.await
|
||||
.map_err(watchdog);
|
||||
|
||||
// **Not gated on the exit code**, which is the trap this module is arranged around. Findings
|
||||
// exit 1, and pip-audit writes a `pip-compile`/hashes advisory to stderr on every single run,
|
||||
// so neither the code nor stderr says whether it worked. stdout does: if the promised document
|
||||
// is there, it ran. SP-1 left the same rule behind for uv, which writes its plan to stderr.
|
||||
let parsed = match out {
|
||||
Ok(out) => parse(&out.stdout).map_err(|e| e.with_stderr(&out.stderr)),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
|
||||
let _ = std::fs::remove_file(&freeze_path);
|
||||
parsed
|
||||
}
|
||||
|
||||
/// The argv SP-4 settled on, and the only mode that works.
|
||||
///
|
||||
/// One flag per entry, so nothing can bundle two arguments into one. `-f json` rather than
|
||||
/// `--format json`: SP-4 and ROADMAP pin the short form while SECURITY §6 writes the long one.
|
||||
/// They are the same flag, and this is the spelling that was actually run.
|
||||
fn argv(freeze: &Path) -> Vec<String> {
|
||||
vec![
|
||||
"-r".to_owned(),
|
||||
freeze.display().to_string(),
|
||||
"--no-deps".to_owned(),
|
||||
"-f".to_owned(),
|
||||
"json".to_owned(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Did the user stop it, or did it break?
|
||||
///
|
||||
/// `exec` reports both through `Code::IntUnexpected`, distinguished only by the message it built
|
||||
/// (`exec::Command::stopped`). Reading the message is unlovely, and it is what P4 warned about
|
||||
/// when it recorded that wiring the token alone would render *"PipDock hit an internal error"* for
|
||||
/// a cancel — the mapping has to be done, not merely enabled.
|
||||
fn is_cancellation(e: &PdError) -> bool {
|
||||
e.code == Code::IntUnexpected && e.message.starts_with("cancelled:")
|
||||
}
|
||||
|
||||
/// Translate `exec`'s vocabulary into this path's.
|
||||
///
|
||||
/// `exec` speaks the *engine's*, and two of its codes are actively wrong here: a watchdog is not
|
||||
/// an internal error, and a tool that will not start is not a missing engine the user should be
|
||||
/// told to go and install. Health's `run_one` needed the same translation for the same reason.
|
||||
fn watchdog(e: PdError) -> PdError {
|
||||
if e.code == Code::IntUnexpected && e.message.contains("timed out") {
|
||||
return PdError::new(
|
||||
Code::HltTimeout,
|
||||
format!("{TOOL} exceeded its {AUDIT_TIMEOUT:?} watchdog; its results are missing"),
|
||||
);
|
||||
}
|
||||
if e.code == Code::EngNotFound {
|
||||
return PdError::new(
|
||||
Code::HltToolMissing,
|
||||
format!(
|
||||
"{TOOL} is in the audit environment but could not be run: {}",
|
||||
e.message
|
||||
),
|
||||
);
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
/// The report as Markdown, for `audit_save_report`.
|
||||
///
|
||||
/// In core rather than in the command for `health::markdown`'s reason: a future `--format md`
|
||||
/// should reuse it rather than grow a second renderer that drifts. English-only, like the CLI —
|
||||
/// this is a document the user saves and sends on, not a screen.
|
||||
///
|
||||
/// **No severity column**, because there is no severity. What replaces it is the thing that
|
||||
/// changes what a reader can do: whether anything fixes it.
|
||||
#[must_use]
|
||||
pub fn markdown(report: &AuditReport) -> String {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "# Security audit\n");
|
||||
let _ = writeln!(out, "- Environment: `{}`", report.env);
|
||||
let _ = writeln!(out, "- Checked: {}", report.ran_at);
|
||||
let _ = writeln!(out, "- pip-audit: {}", report.tool_version);
|
||||
let _ = writeln!(out, "- Packages audited: {}", report.packages);
|
||||
let _ = writeln!(out, "- Advisories: {}", report.advisories.len());
|
||||
if report.cancelled {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\n> Stopped before it finished, so this is incomplete."
|
||||
);
|
||||
}
|
||||
for problem in &report.problems {
|
||||
let _ = writeln!(out, "\n> **{}** {}", problem.code, problem.message);
|
||||
}
|
||||
|
||||
// Stated once, at the top, rather than implied: the source is what a reader has to know to
|
||||
// judge an absence of findings, and DISCLAIMER §4 makes the same point to the same person.
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nAdvisories come from PyPI's advisory data, by way of pip-audit. An advisory database \
|
||||
records what has been reported; it is not a guarantee that a package is safe. PipDock \
|
||||
assigns no severity, because pip-audit publishes none."
|
||||
);
|
||||
|
||||
if report.advisories.is_empty() {
|
||||
let _ = writeln!(out, "\nNo known advisories.");
|
||||
return out;
|
||||
}
|
||||
|
||||
let mut current = String::new();
|
||||
for a in &report.advisories {
|
||||
let pkg = a.pkg.to_string();
|
||||
if pkg != current {
|
||||
let _ = writeln!(out, "\n## {pkg} {}\n", a.version);
|
||||
current = pkg;
|
||||
}
|
||||
let fix = if a.fix_versions.is_empty() {
|
||||
"no fix available".to_owned()
|
||||
} else {
|
||||
format!("fixed in {}", a.fix_versions.join(", "))
|
||||
};
|
||||
let _ = writeln!(out, "### {} — {fix}\n", a.id);
|
||||
if !a.aliases.is_empty() {
|
||||
let _ = writeln!(out, "Also known as: {}\n", a.aliases.join(", "));
|
||||
}
|
||||
if let Some(url) = &a.url {
|
||||
let _ = writeln!(out, "<{url}>\n");
|
||||
}
|
||||
if !a.description.is_empty() {
|
||||
let _ = writeln!(out, "{}\n", a.description);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The pinned 2.10.1 over `urllib3==2.0.0` — see the directory's README for provenance.
|
||||
const CAPTURE: &str = include_str!("../tests/fixtures/audit/urllib3-2.0.0.json");
|
||||
|
||||
#[test]
|
||||
fn the_capture_parses_and_collapses_to_eight() {
|
||||
let got = parse(CAPTURE).expect("the committed capture must parse");
|
||||
|
||||
assert_eq!(got.packages, 1);
|
||||
// Ten rows in the document, eight advisories. Asserted as a number rather than "fewer than
|
||||
// before", because this count is what a Security tab puts on screen.
|
||||
assert_eq!(got.advisories.len(), 8, "ten rows collapse to eight");
|
||||
|
||||
let ids: BTreeSet<&str> = got.advisories.iter().map(|a| a.id.as_str()).collect();
|
||||
assert_eq!(ids.len(), 8, "no id survives twice");
|
||||
assert!(ids.contains("PYSEC-2023-192"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cve_is_an_alias_and_never_the_id() {
|
||||
let got = parse(CAPTURE).expect("parses");
|
||||
|
||||
let a = got
|
||||
.advisories
|
||||
.iter()
|
||||
.find(|a| a.id == "PYSEC-2023-192")
|
||||
.expect("the capture carries it");
|
||||
assert!(a.aliases.contains(&"CVE-2023-43804".to_owned()));
|
||||
assert!(a.aliases.iter().any(|x| x.starts_with("GHSA-")));
|
||||
assert!(
|
||||
!a.id.starts_with("CVE-"),
|
||||
"PRD says CVEs; the id is not one"
|
||||
);
|
||||
assert_eq!(a.fix_versions, ["1.26.17", "2.0.6"]);
|
||||
assert_eq!(a.version.0, "2.0.0", "the installed version, not the fix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_advisory_links_to_its_osv_entry() {
|
||||
let got = parse(CAPTURE).expect("parses");
|
||||
|
||||
for a in &got.advisories {
|
||||
assert_eq!(
|
||||
a.url,
|
||||
Some(format!("{OSV_BASE}{}", a.id)),
|
||||
"{} lost its link",
|
||||
a.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_that_could_escape_the_path_segment_gets_no_link() {
|
||||
// Why the URL is built rather than taken: these are what a compromised — or merely
|
||||
// surprising — tool output could otherwise carry into `opener:allow-open-url`.
|
||||
for bad in [
|
||||
"../../evil",
|
||||
"PYSEC-2023-192/../../x",
|
||||
"PYSEC 2023 192",
|
||||
"javascript:alert(1)",
|
||||
"https://evil.test/x",
|
||||
"PYSEC-2023-192?x=1",
|
||||
"PYSEC-2023-192#f",
|
||||
"%2e%2e",
|
||||
"1PYSEC",
|
||||
"ab",
|
||||
] {
|
||||
assert_eq!(advisory_url(bad), None, "{bad:?} must not become a URL");
|
||||
}
|
||||
|
||||
assert!(advisory_url("PYSEC-2023-192").is_some());
|
||||
assert!(advisory_url("GHSA-v845-jxx5-vc9f").is_some());
|
||||
assert!(advisory_url("CVE-2023-43804").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixable_advisories_sort_ahead_of_unfixable_ones() {
|
||||
// The order PRD P1-1 gets instead of severity, so it is asserted rather than assumed.
|
||||
let mk = |pkg: &str, id: &str, fixes: &[&str]| Advisory {
|
||||
pkg: PkgName::parse(pkg).expect("valid"),
|
||||
version: Version("1.0".to_owned()),
|
||||
id: id.to_owned(),
|
||||
aliases: vec![],
|
||||
fix_versions: fixes.iter().map(|s| (*s).to_owned()).collect(),
|
||||
description: String::new(),
|
||||
url: None,
|
||||
};
|
||||
let got = sort_advisories(vec![
|
||||
mk("zlib-wrapper", "PYSEC-1", &["1.1"]),
|
||||
mk("aiohttp", "PYSEC-3", &[]),
|
||||
mk("aiohttp", "PYSEC-2", &["2.0"]),
|
||||
]);
|
||||
|
||||
let order: Vec<&str> = got.iter().map(|a| a.id.as_str()).collect();
|
||||
assert_eq!(order, ["PYSEC-2", "PYSEC-3", "PYSEC-1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_that_is_not_the_promised_document_is_a_tool_failure() {
|
||||
// Not a panic, and not a silent empty report: pip-audit printing anything else means the
|
||||
// run did not do what was asked, and PD-HLT-002 is the code that says so.
|
||||
let err = parse("Found 10 known vulnerabilities in 1 package").expect_err("not JSON");
|
||||
assert_eq!(err.code, Code::HltToolFailed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_environment_is_zero_advisories_over_a_real_package_count() {
|
||||
let doc =
|
||||
r#"{"dependencies":[{"name":"certifi","version":"2024.2.2","vulns":[]}],"fixes":[]}"#;
|
||||
let got = parse(doc).expect("parses");
|
||||
|
||||
assert_eq!((got.packages, got.advisories.len()), (1, 0));
|
||||
}
|
||||
|
||||
// -- the runner -------------------------------------------------------------
|
||||
|
||||
fn a_python_env() -> PyEnv {
|
||||
PyEnv {
|
||||
interpreter: std::path::PathBuf::from(r"C:\Python312\python.exe"),
|
||||
prefix: std::path::PathBuf::from(r"C:\Python312"),
|
||||
python_version: "3.12.10".to_owned(),
|
||||
externally_managed: false,
|
||||
hidden_user_site: None,
|
||||
source: crate::model::EnvSource::Manual,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_argv_entry_bundles_two_arguments() {
|
||||
// The same guard Code Health's argv has, and for the same reason: a single entry reading
|
||||
// "-f json" is one argument to `CreateProcess`, and the tool would reject it as a flag it
|
||||
// does not have. SECURITY §2's argv-array rule only means anything if the array is split.
|
||||
let argv = argv(std::path::Path::new(r"C:\tmp\freeze.txt"));
|
||||
|
||||
for entry in &argv {
|
||||
assert!(
|
||||
!entry.trim().contains(' ') || entry.ends_with(".txt"),
|
||||
"{entry:?} bundles two arguments"
|
||||
);
|
||||
}
|
||||
assert_eq!(argv[0], "-r");
|
||||
assert_eq!(argv[2], "--no-deps");
|
||||
assert_eq!(
|
||||
&argv[3..],
|
||||
["-f", "json"],
|
||||
"SP-4's spelling, not SECURITY's"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_missing_tool_is_a_problem_on_a_report_rather_than_an_error() {
|
||||
// The shape the screen depends on. An audit venv that has never synced must still produce
|
||||
// a report — with an error row and an honest zero — because returning `Err` here would
|
||||
// leave the Security tab with nothing to render but a blank screen, which is the failure
|
||||
// `PdHealthReport`'s `problems` list exists to prevent.
|
||||
let dir = std::env::temp_dir().join(format!("pipdock-audit-empty-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let sink = ProgressSink::new(tx, AUDIT_STEPS, Default::default());
|
||||
|
||||
let report = run(&dir, &a_python_env(), "urllib3==2.0.0\n", &sink)
|
||||
.await
|
||||
.expect("a failed run still returns a report");
|
||||
|
||||
assert_eq!(report.problems.len(), 1);
|
||||
assert_eq!(report.problems[0].code, Code::HltToolMissing);
|
||||
assert_eq!(report.problems[0].tool, "pip-audit");
|
||||
assert!(report.advisories.is_empty());
|
||||
assert_eq!(report.packages, 0, "nothing was audited, and it says so");
|
||||
assert!(!report.has_findings());
|
||||
assert!(
|
||||
!report.ran_at.is_empty(),
|
||||
"a run that failed still happened"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The whole path against the real tool, which nothing above covers.
|
||||
///
|
||||
/// Needs a synced audit venv, so it is opt-in the way `search_latency` is:
|
||||
///
|
||||
/// ```text
|
||||
/// cargo test -p pipdock-core --lib audit::tests::the_real_tool -- --ignored --nocapture
|
||||
/// ```
|
||||
///
|
||||
/// Point `PIPDOCK_AUDIT_DIR` at a directory whose `.venv\Scripts\pip-audit.exe` exists. The
|
||||
/// freeze below is the SP-4 environment, so a passing run must find the same eight advisories
|
||||
/// the committed fixture carries — which is what makes this a check on the *parser* against a
|
||||
/// live tool rather than only on the tool.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a synced audit venv; run with --ignored and PIPDOCK_AUDIT_DIR"]
|
||||
async fn the_real_tool_finds_what_the_fixture_says() {
|
||||
let Ok(dir) = std::env::var("PIPDOCK_AUDIT_DIR") else {
|
||||
panic!("set PIPDOCK_AUDIT_DIR to a directory holding a synced audit venv");
|
||||
};
|
||||
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let sink = ProgressSink::new(tx, AUDIT_STEPS, Default::default());
|
||||
|
||||
let report = run(
|
||||
std::path::Path::new(&dir),
|
||||
&a_python_env(),
|
||||
"urllib3==2.0.0\n",
|
||||
&sink,
|
||||
)
|
||||
.await
|
||||
.expect("returns a report");
|
||||
|
||||
assert!(report.problems.is_empty(), "{:?}", report.problems);
|
||||
assert_eq!(report.packages, 1);
|
||||
assert_eq!(report.advisories.len(), 8, "the fixture's count, live");
|
||||
assert!(report.advisories.iter().all(|a| a.url.is_some()));
|
||||
}
|
||||
|
||||
/// Cancelling one, against the real tool, because nothing smaller can.
|
||||
///
|
||||
/// `audit_once` checks the executable exists before it spawns anything, so a fake directory
|
||||
/// returns `PD-HLT-001` and never reaches the token — the cancel path is only observable with
|
||||
/// a tool that actually runs. Same opt-in as above.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a synced audit venv; run with --ignored and PIPDOCK_AUDIT_DIR"]
|
||||
async fn a_cancelled_run_is_cancelled_rather_than_failed() {
|
||||
let Ok(dir) = std::env::var("PIPDOCK_AUDIT_DIR") else {
|
||||
panic!("set PIPDOCK_AUDIT_DIR to a directory holding a synced audit venv");
|
||||
};
|
||||
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let token = tokio_util::sync::CancellationToken::new();
|
||||
let sink = ProgressSink::new(tx, AUDIT_STEPS, token.clone());
|
||||
|
||||
// Cancelled while the advisory fetch is in flight — the 18-68 s window this feature exists
|
||||
// to make interruptible.
|
||||
let stopper = tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
|
||||
token.cancel();
|
||||
});
|
||||
let report = run(
|
||||
std::path::Path::new(&dir),
|
||||
&a_python_env(),
|
||||
"urllib3==2.0.0
|
||||
",
|
||||
&sink,
|
||||
)
|
||||
.await
|
||||
.expect("a cancelled run still returns a report");
|
||||
stopper.await.expect("stopper");
|
||||
|
||||
// The whole point of P4's warning: a cancel must not read as `PipDock hit an internal
|
||||
// error`, which is what `PD-INT-001` renders as.
|
||||
assert!(report.cancelled, "a stopped run says so");
|
||||
assert!(
|
||||
report.problems.is_empty(),
|
||||
"a cancel is not a failure: {:?}",
|
||||
report.problems
|
||||
);
|
||||
assert!(report.advisories.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! What PipDock has written to disk, and removing the parts that are safe to remove — PRD P1-4.
|
||||
//!
|
||||
//! # This module introduces the first delete-a-tree in the codebase
|
||||
//!
|
||||
//! Before it, the only removal anywhere outside test scaffolding was one `remove_file` in
|
||||
//! [`crate::snapshot::create`]'s failure path. So the safety design *is* the feature, and it is
|
||||
//! two rules:
|
||||
//!
|
||||
//! 1. **Nothing is removed by path.** A caller names a [`Target`], and this module decides where
|
||||
//! that target lives. There is no function here that takes a path to delete.
|
||||
//! 2. **Every resolved path is checked to be inside the data root** before removal, by
|
||||
//! canonicalized prefix and not by string comparison — see [`clear`].
|
||||
//!
|
||||
//! # Why `index.db` is not a target
|
||||
//!
|
||||
//! It holds the package-name index *and* the settings *and* the pin list *and* the legal-consent
|
||||
//! record, all in one SQLite file (`store::Store`). "Clear the cache" removing a user's pins is
|
||||
//! exactly the kind of surprise `legal/PRIVACY-POLICY.md` §2 had to be corrected for. Its size is
|
||||
//! reported so the number is honest about where the space went; refreshing the index is
|
||||
//! `index refresh`, which replaces rows rather than deleting a file.
|
||||
//!
|
||||
//! # There are no log files
|
||||
//!
|
||||
//! [`crate::LOG_RETENTION_DAYS`] has never had a reader. The only log is the in-memory ring buffer
|
||||
//! behind *Report bug*, and `logs_tail` is still owed. When the logging subsystem lands it becomes
|
||||
//! a fourth entry here; until then, reporting a "logs" line of zero bytes would be inventing a
|
||||
//! thing that does not exist.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::errors::{Code, PdError, Result};
|
||||
|
||||
/// Something the user can be offered a *Clear* button for.
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Target {
|
||||
/// Every snapshot of every environment. Rollback loses its history; nothing else changes.
|
||||
Snapshots,
|
||||
/// The isolated environment Code Health runs deptry, vulture and ruff from. Rebuilt on the
|
||||
/// next run, or by `pipdock tools sync`.
|
||||
Tools,
|
||||
/// The isolated environment the Security tab runs pip-audit from. Rebuilt on the next audit.
|
||||
///
|
||||
/// A **separate** target rather than part of [`Self::Tools`], because it is a separate venv:
|
||||
/// P1-1 kept pip-audit out of Code Health's so that its `msgpack` dependency cannot fail the
|
||||
/// whole sync. Two directories on disk are two rows here, or "clear the cache" would leave one
|
||||
/// of them behind while reporting it gone.
|
||||
Audit,
|
||||
}
|
||||
|
||||
/// One line of the cache report.
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Entry {
|
||||
/// Bytes on disk, summed recursively.
|
||||
pub bytes: u64,
|
||||
/// Where it is. Data — shown verbatim, never translated (I18N §2).
|
||||
pub path: String,
|
||||
/// False when nothing is there yet, so the UI can say "nothing to clear" rather than "0 B".
|
||||
pub exists: bool,
|
||||
}
|
||||
|
||||
/// What PipDock is using, by artefact.
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Usage {
|
||||
/// The data root everything below lives in.
|
||||
pub root: String,
|
||||
/// `index.db` — the package index, settings, pins and the consent record. **Not clearable.**
|
||||
pub database: Entry,
|
||||
/// Snapshots, across every environment.
|
||||
pub snapshots: Entry,
|
||||
/// The Code Health tools environment.
|
||||
pub tools: Entry,
|
||||
/// The Security tab's pip-audit environment (PRD P1-1).
|
||||
pub audit: Entry,
|
||||
/// How many snapshot documents there are, across every environment.
|
||||
pub snapshot_count: usize,
|
||||
}
|
||||
|
||||
impl Usage {
|
||||
/// Everything PipDock has written, including the parts that cannot be cleared.
|
||||
#[must_use]
|
||||
pub fn total_bytes(&self) -> u64 {
|
||||
self.database.bytes + self.snapshots.bytes + self.tools.bytes + self.audit.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes under `path`, following directories and ignoring what cannot be read.
|
||||
///
|
||||
/// An unreadable entry contributes zero rather than failing the report: a size is advisory, and a
|
||||
/// number that is slightly low is more useful than a screen that will not open. Symlinks are not
|
||||
/// followed — `fs::metadata` on the entry would report the target's size and could recurse
|
||||
/// outside the data root, which is the one thing this module is careful about.
|
||||
fn bytes_of(path: &Path) -> u64 {
|
||||
let Ok(meta) = std::fs::symlink_metadata(path) else {
|
||||
return 0;
|
||||
};
|
||||
if meta.is_symlink() {
|
||||
return 0;
|
||||
}
|
||||
if meta.is_file() {
|
||||
return meta.len();
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(path) else {
|
||||
return 0;
|
||||
};
|
||||
entries
|
||||
.filter_map(std::result::Result::ok)
|
||||
.map(|e| bytes_of(&e.path()))
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn entry_at(path: PathBuf) -> Entry {
|
||||
Entry {
|
||||
bytes: bytes_of(&path),
|
||||
exists: path.exists(),
|
||||
path: path.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many `*.meta.json` sidecars there are under the snapshots root.
|
||||
fn count_snapshots(root: &Path) -> usize {
|
||||
let Ok(envs) = std::fs::read_dir(root) else {
|
||||
return 0;
|
||||
};
|
||||
envs.filter_map(std::result::Result::ok)
|
||||
.filter_map(|env| std::fs::read_dir(env.path()).ok())
|
||||
.flat_map(|files| {
|
||||
files.filter_map(std::result::Result::ok).filter(|f| {
|
||||
f.file_name()
|
||||
.to_str()
|
||||
.is_some_and(|n| n.ends_with(".meta.json"))
|
||||
})
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Where a target lives under `app_data`.
|
||||
///
|
||||
/// The only place a `Target` becomes a path, so [`clear`] cannot be handed one from outside.
|
||||
fn path_of(app_data: &Path, target: Target) -> PathBuf {
|
||||
match target {
|
||||
Target::Snapshots => app_data.join(crate::snapshot::SNAPSHOT_DIR),
|
||||
Target::Tools => crate::health::tools_dir(app_data),
|
||||
Target::Audit => crate::health::audit_dir(app_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read what is on disk.
|
||||
///
|
||||
/// # Errors
|
||||
/// Never — an unreadable path reports zero. Returns `Result` so a future variant that must fail
|
||||
/// does not change every caller.
|
||||
pub fn usage(app_data: &Path) -> Result<Usage> {
|
||||
let snapshots = app_data.join(crate::snapshot::SNAPSHOT_DIR);
|
||||
Ok(Usage {
|
||||
root: app_data.display().to_string(),
|
||||
database: entry_at(app_data.join(crate::store::DB_FILE)),
|
||||
snapshot_count: count_snapshots(&snapshots),
|
||||
snapshots: entry_at(snapshots),
|
||||
tools: entry_at(crate::health::tools_dir(app_data)),
|
||||
audit: entry_at(crate::health::audit_dir(app_data)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove a target, returning how many bytes went.
|
||||
///
|
||||
/// **The containment check is the point of this function.** `app_data` arrives from
|
||||
/// [`crate::store::default_app_data`] or from the Tauri app handle, and `target` is an enum — so
|
||||
/// on paper the path cannot escape. The check is here anyway, because the cost of being wrong is
|
||||
/// deleting something outside the data root and the cost of being right is one `canonicalize`.
|
||||
///
|
||||
/// Canonicalized on **both** sides before comparing: a prefix test on unresolved paths is a string
|
||||
/// comparison wearing a `Path`, and on Windows it would pass `data\..\..\Users` and fail a
|
||||
/// perfectly good path that reached here through a junction or a short name.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-INT-001` when the resolved path is not inside `app_data` — which is a bug, not a user
|
||||
/// error, and must be loud. `PD-PRM-002` when something has the files open, which on Windows is
|
||||
/// the ordinary case for a tools venv whose Python is still running.
|
||||
pub fn clear(app_data: &Path, target: Target) -> Result<u64> {
|
||||
let path = path_of(app_data, target);
|
||||
if !path.exists() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let root = app_data.canonicalize().map_err(|e| {
|
||||
PdError::new(
|
||||
Code::IntUnexpected,
|
||||
format!("resolve data root {}: {e}", app_data.display()),
|
||||
)
|
||||
})?;
|
||||
let resolved = path.canonicalize().map_err(|e| {
|
||||
PdError::new(
|
||||
Code::IntUnexpected,
|
||||
format!("resolve {}: {e}", path.display()),
|
||||
)
|
||||
})?;
|
||||
if !resolved.starts_with(&root) {
|
||||
return Err(PdError::new(
|
||||
Code::IntUnexpected,
|
||||
format!(
|
||||
"refusing to remove {} — outside the data root {}",
|
||||
resolved.display(),
|
||||
root.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let bytes = bytes_of(&resolved);
|
||||
std::fs::remove_dir_all(&resolved).map_err(|e| {
|
||||
// Windows holds files open while a process is using them, and a tools venv whose Python is
|
||||
// still running is the ordinary way to hit this — which is a thing the user can act on.
|
||||
PdError::new(
|
||||
Code::PrmFileLocked,
|
||||
format!("remove {}: {e}", resolved.display()),
|
||||
)
|
||||
})?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// Every `Entry` on a `Usage` must reach `total_bytes`.
|
||||
///
|
||||
/// Written because it did not. `audit` was added as a fourth row, reported on screen, and left
|
||||
/// out of the sum — so the total silently under-reported by a whole venv while every existing
|
||||
/// test passed. The assertion is on distinct powers of two so a *missing* term is visible in
|
||||
/// the failure rather than merely a wrong number.
|
||||
#[test]
|
||||
fn every_entry_reaches_the_total() {
|
||||
use super::{Entry, Usage};
|
||||
|
||||
let at = |bytes: u64| Entry {
|
||||
bytes,
|
||||
path: String::new(),
|
||||
exists: true,
|
||||
};
|
||||
let usage = Usage {
|
||||
root: String::new(),
|
||||
database: at(1),
|
||||
snapshots: at(2),
|
||||
tools: at(4),
|
||||
audit: at(8),
|
||||
snapshot_count: 0,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
usage.total_bytes(),
|
||||
15,
|
||||
"a missing term shows up as its own bit"
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
fn temp() -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pipdock-cache-{}",
|
||||
jiff::Timestamp::now().as_nanosecond()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
dir
|
||||
}
|
||||
|
||||
fn write(path: &Path, bytes: usize) {
|
||||
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(path, vec![b'x'; bytes]).expect("write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_install_reports_nothing_rather_than_failing() {
|
||||
let root = temp();
|
||||
let got = usage(&root).expect("usage");
|
||||
assert_eq!(got.total_bytes(), 0);
|
||||
assert!(!got.snapshots.exists);
|
||||
assert!(!got.tools.exists);
|
||||
assert_eq!(got.snapshot_count, 0);
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_are_summed_recursively_and_snapshots_counted_by_sidecar() {
|
||||
let root = temp();
|
||||
write(&root.join("index.db"), 100);
|
||||
write(&root.join("snapshots/envA/2026.freeze.txt"), 30);
|
||||
write(&root.join("snapshots/envA/2026.meta.json"), 20);
|
||||
write(&root.join("snapshots/envB/2027.meta.json"), 10);
|
||||
write(&root.join("tools/.venv/Scripts/python.exe"), 40);
|
||||
|
||||
let got = usage(&root).expect("usage");
|
||||
assert_eq!(got.database.bytes, 100);
|
||||
assert_eq!(got.snapshots.bytes, 60);
|
||||
assert_eq!(got.tools.bytes, 40);
|
||||
assert_eq!(got.total_bytes(), 200);
|
||||
// Counted by sidecar, not by file: a freeze and its meta are one snapshot.
|
||||
assert_eq!(got.snapshot_count, 2);
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_snapshots_leaves_the_database_alone() {
|
||||
// The whole reason `index.db` is not a target: it holds settings, pins and the consent
|
||||
// record as well as the index, and "clear the cache" must never take a user's pins.
|
||||
let root = temp();
|
||||
write(&root.join("index.db"), 100);
|
||||
write(&root.join("snapshots/envA/2026.meta.json"), 20);
|
||||
|
||||
let freed = clear(&root, Target::Snapshots).expect("clear");
|
||||
assert_eq!(freed, 20);
|
||||
assert!(!root.join("snapshots").exists());
|
||||
assert!(root.join("index.db").exists());
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_something_that_is_not_there_is_not_an_error() {
|
||||
// A fresh install has no tools venv, and offering a button that errors is worse than one
|
||||
// that does nothing.
|
||||
let root = temp();
|
||||
assert_eq!(clear(&root, Target::Tools).expect("clear"), 0);
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symlink_contributes_nothing_and_is_not_followed_out_of_the_root() {
|
||||
// `fs::metadata` follows links and would report the target's size — and a recursive walk
|
||||
// that follows one can leave the data root entirely, which is the single thing this
|
||||
// module exists to prevent.
|
||||
let root = temp();
|
||||
write(&root.join("snapshots/envA/2026.meta.json"), 20);
|
||||
let outside = temp();
|
||||
write(&outside.join("big.bin"), 5000);
|
||||
|
||||
#[cfg(windows)]
|
||||
let linked =
|
||||
std::os::windows::fs::symlink_dir(&outside, root.join("snapshots/link")).is_ok();
|
||||
#[cfg(not(windows))]
|
||||
let linked = std::os::unix::fs::symlink(&outside, root.join("snapshots/link")).is_ok();
|
||||
|
||||
let got = usage(&root).expect("usage");
|
||||
if linked {
|
||||
assert_eq!(
|
||||
got.snapshots.bytes, 20,
|
||||
"a symlink must contribute nothing, not 5020"
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
std::fs::remove_dir_all(&outside).ok();
|
||||
}
|
||||
}
|
||||
@@ -506,7 +506,50 @@ mod tests {
|
||||
/// the mistake surfaced. Whether the grandchild is still alive is the only observable that
|
||||
/// distinguishes the two outcomes, so ask the OS.
|
||||
#[cfg(windows)]
|
||||
fn grandchildren_alive(marker: &str) -> usize {
|
||||
/// Wait until `grandchildren_alive` satisfies `want`, or give up.
|
||||
///
|
||||
/// **Replaces a fixed sleep, which is what made this flake.** The setup step asserted the
|
||||
/// fixture had started after 700 ms and the teardown asserted the tree was gone after 800 ms;
|
||||
/// both are fine on an idle developer machine and neither is a promise a loaded CI runner
|
||||
/// keeps. It failed on `fmt · clippy · test` once, on the *setup* assertion — the fixture
|
||||
/// simply had not spawned yet, so the test proved nothing and said so.
|
||||
///
|
||||
/// Polling for the condition keeps the assertions exactly as strict while removing the
|
||||
/// timing guess: a tree that never dies still fails, it just takes the timeout to say so.
|
||||
/// Poll until `want` holds, or give up and report the last answer we actually got.
|
||||
///
|
||||
/// Sixty seconds rather than twenty, and the number is not a guess about the *fixture* — it is
|
||||
/// about the **poll**. Each iteration spawns PowerShell, so twenty seconds of wall clock was
|
||||
/// only a handful of samples on a busy runner rather than the two hundred the 100 ms sleep
|
||||
/// suggests. A failed query is never counted as an observation: it retries, and if none ever
|
||||
/// succeeds the test says so instead of concluding from a number nobody measured.
|
||||
async fn wait_for(marker: &str, want: impl Fn(usize) -> bool) -> usize {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(60);
|
||||
let mut last = None;
|
||||
loop {
|
||||
if let Some(n) = grandchildren_alive(marker) {
|
||||
last = Some(n);
|
||||
if want(n) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return last.expect("the process query never gave a usable answer");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// How many `PING.EXE` grandchildren carry the marker, or `None` when the query itself failed.
|
||||
///
|
||||
/// **`None` is not zero**, and conflating the two is what made this pair of tests flaky in
|
||||
/// both directions. Each call spawns PowerShell and a CIM query, which costs seconds on a
|
||||
/// loaded runner; `.unwrap_or(0)` turned a slow or failed invocation into a confident "no
|
||||
/// processes". At setup that reads as *the fixture never started* — which is how `main` went
|
||||
/// red at `bee85dc` on a change that touched nothing here. At teardown it is worse, because
|
||||
/// the assertion there wants zero: a failed query would have **passed** the test over a
|
||||
/// process tree that was still alive.
|
||||
fn grandchildren_alive(marker: &str) -> Option<usize> {
|
||||
let out = std::process::Command::new("powershell")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
@@ -517,11 +560,11 @@ mod tests {
|
||||
),
|
||||
])
|
||||
.output()
|
||||
.expect("powershell runs");
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap_or(0)
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8_lossy(&out.stdout).trim().parse().ok()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -579,9 +622,8 @@ mod tests {
|
||||
let cmd = a_slow_grandchild(marker).cancel(token.clone());
|
||||
|
||||
let handle = tokio::spawn(async move { cmd.run().await });
|
||||
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||
assert!(
|
||||
grandchildren_alive(marker) > 0,
|
||||
wait_for(marker, |n| n > 0).await > 0,
|
||||
"the fixture never started, so this test proves nothing"
|
||||
);
|
||||
|
||||
@@ -589,10 +631,9 @@ mod tests {
|
||||
let result = handle.await.expect("task joins");
|
||||
assert!(result.is_err(), "a cancelled run must not report success");
|
||||
|
||||
// Termination is asynchronous; give the job a moment to take the tree down.
|
||||
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||
// Termination is asynchronous, so this polls rather than sleeping a guessed interval.
|
||||
assert_eq!(
|
||||
grandchildren_alive(marker),
|
||||
wait_for(marker, |n| n == 0).await,
|
||||
0,
|
||||
"a grandchild outlived cancellation — the job object did not take the tree with it"
|
||||
);
|
||||
@@ -609,9 +650,10 @@ mod tests {
|
||||
let result = cmd.run().await;
|
||||
assert!(result.is_err(), "the watchdog must stop the run");
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||
// Polled rather than slept, for its sibling's reason: 800 ms is fine on an idle machine
|
||||
// and is not a promise a loaded CI runner keeps.
|
||||
assert_eq!(
|
||||
grandchildren_alive(marker),
|
||||
wait_for(marker, |n| n == 0).await,
|
||||
0,
|
||||
"a grandchild outlived the watchdog"
|
||||
);
|
||||
|
||||
@@ -120,7 +120,7 @@ fn pin_list() -> Vec<Pin> {
|
||||
/// subject. `Downgrade` in particular: it is the variant UI-SPEC had no section for, and a
|
||||
/// compatible resolve produces it routinely.
|
||||
fn flow_step() -> crate::flow::FlowStep {
|
||||
use crate::plan::{Blocker, Change, ChangeKind, HeldBack, ImpossibleDetail, ResolutionReport};
|
||||
use crate::plan::{Change, ChangeKind, HeldBack, ImpossibleDetail, ResolutionReport};
|
||||
|
||||
let pkg = |n: &str| PkgName::parse(n).unwrap_or_else(|e| panic!("fixture name {n:?}: {e:?}"));
|
||||
let change = |name: &str, from: Option<&str>, to: &str, kind: ChangeKind| Change {
|
||||
@@ -144,10 +144,7 @@ fn flow_step() -> crate::flow::FlowStep {
|
||||
pkg: pkg("numpy"),
|
||||
resolved: Version("1.26.4".to_owned()),
|
||||
latest: Version("2.5.1".to_owned()),
|
||||
blockers: vec![Blocker {
|
||||
by: Some(pkg("scipy")),
|
||||
constraint: "numpy<1.28.0,>=1.21.6".to_owned(),
|
||||
}],
|
||||
blockers: numpy_blockers(),
|
||||
}],
|
||||
impossible: Some(ImpossibleDetail {
|
||||
explanation: "no version of oldlib is compatible with python 3.12".to_owned(),
|
||||
@@ -200,6 +197,25 @@ fn execution_summary() -> crate::plan::ExecutionSummary {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `numpy` cannot go to `latest`, from the same scenario.
|
||||
///
|
||||
/// **Computed, not written**, for the reason [`guard_report`] gives and for one more, learned the
|
||||
/// expensive way. The hand-written version of this list carried a `constraint` of
|
||||
/// `"numpy<1.28.0,>=1.21.6"` — the shape [`crate::plan::Blocker`]'s own doc describes — while
|
||||
/// `blockers_for` had drifted to emitting a whole English sentence. So `PdPreviewDiff` asserted a
|
||||
/// row the application could not actually render, `PdConflictRow` wrapped the real value in
|
||||
/// `plan.blocker` and named the dependent twice, and every suite stayed green. Slice 0.
|
||||
///
|
||||
/// Two blockers come back rather than the one that was written here: `scipy` and `pandas` both
|
||||
/// declare specifiers that exclude 2.5.1, which is the same fact about the same rows that makes
|
||||
/// this set worth using for the guard.
|
||||
fn numpy_blockers() -> Vec<crate::plan::Blocker> {
|
||||
let target = crate::compat::PyVersion::parse("2.5.1")
|
||||
.unwrap_or_else(|e| panic!("fixture version \"2.5.1\": {e:?}"));
|
||||
let numpy = PkgName::parse("numpy").unwrap_or_else(|e| panic!("fixture name \"numpy\": {e:?}"));
|
||||
crate::graph::ReverseDeps::build_for(&pkg_list(), "3.12.4").blockers_for(&numpy, &target)
|
||||
}
|
||||
|
||||
/// What `uninstall_guard` returns for removing `numpy` from the same scenario.
|
||||
///
|
||||
/// **Computed, not written.** Running the real graph over the real `pkg_list()` is what makes this
|
||||
@@ -313,6 +329,34 @@ fn codes() -> Vec<crate::errors::Code> {
|
||||
/// | `DEP002` `httpx` | unused but not installed here — the same code, no button |
|
||||
/// | `DEP001` `yaml` | a module name that is not a distribution (`PyYAML`), **and** the wrong code for the button twice over |
|
||||
/// | `DEP003` `numpy` | two locations, so the location list is not always a singleton |
|
||||
/// What `audit_run` returns for the SP-4 environment — PRD P1-1.
|
||||
///
|
||||
/// **Computed from the committed capture by the real parser**, never written out. Slice 0 is the
|
||||
/// reason and it is not a general principle here but a specific one: dedup and the fixable-first
|
||||
/// order are exactly what the Security screen renders, both live in `audit.rs`, and a hand-written
|
||||
/// list would let a test assert the right rows while the application produced different ones. That
|
||||
/// is the shape the doubled blocker sentence shipped in.
|
||||
///
|
||||
/// `target-env.json` rather than `urllib3-2.0.0.json` because a screen has to group by package and
|
||||
/// one package cannot show that. Two is what the real environment has: **sixteen rows collapsing
|
||||
/// to thirteen advisories**, five of them against pip itself — which is `Engine::freeze` passing
|
||||
/// `--all`, and a fact the screen should not hide.
|
||||
fn audit_report() -> crate::audit::AuditReport {
|
||||
const CAPTURE: &str = include_str!("../tests/fixtures/audit/target-env.json");
|
||||
|
||||
let audited = crate::audit::parse(CAPTURE)
|
||||
.unwrap_or_else(|e| panic!("the committed pip-audit capture must parse: {e:?}"));
|
||||
crate::audit::AuditReport {
|
||||
env: r"c:\proj\.venv\scripts\python.exe".to_owned(),
|
||||
ran_at: "2026-08-18T09:00:00Z".to_owned(),
|
||||
tool_version: "2.10.1".to_owned(),
|
||||
packages: audited.packages,
|
||||
advisories: audited.advisories,
|
||||
problems: Vec::new(),
|
||||
cancelled: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn health_report() -> crate::health::HealthReport {
|
||||
use crate::health::{
|
||||
DeptryIssue, FixApplicability, HealthReport, RuffFinding, RuffFindings, SourceLocation,
|
||||
@@ -325,7 +369,7 @@ fn health_report() -> crate::health::HealthReport {
|
||||
ran_at: "2026-08-13T09:00:00Z".to_owned(),
|
||||
tool_versions: [
|
||||
("deptry".to_owned(), "0.25.1".to_owned()),
|
||||
("ruff".to_owned(), "0.16.2".to_owned()),
|
||||
("ruff".to_owned(), "0.16.3".to_owned()),
|
||||
("vulture".to_owned(), "2.16".to_owned()),
|
||||
]
|
||||
.into_iter()
|
||||
@@ -534,6 +578,7 @@ pub fn ipc_fixtures() -> serde_json::Result<Vec<(&'static str, String)>> {
|
||||
("snapshot_list.json", render(&snapshot_list())?),
|
||||
("rollback_preview.json", render(&rollback_preview())?),
|
||||
("health_report.json", render(&health_report())?),
|
||||
("audit_report.json", render(&audit_report())?),
|
||||
("health_partial.json", render(&health_partial())?),
|
||||
("codes.json", render(&codes())?),
|
||||
])
|
||||
|
||||
@@ -121,8 +121,14 @@ pub struct ReverseDeps {
|
||||
impl ReverseDeps {
|
||||
/// Build the graph from a full environment listing.
|
||||
///
|
||||
/// Requirements gated behind an extra are recorded but flagged, so callers can decide: the
|
||||
/// uninstall guard ignores them, while pin auto-suggest may still count them.
|
||||
/// Requirements gated behind an extra are recorded but flagged, and **every reader filters
|
||||
/// them out** via [`Requirement::applies_in`]. This comment used to say auto-suggest "may
|
||||
/// still count them", describing an intent nothing implemented — [`Self::dependent_count`]
|
||||
/// delegates to [`Self::dependents_of`] and always has. Post-1.0 P1-A settled it in favour of
|
||||
/// what shipped: a suggestion counts what actually depends on a package *in this environment*,
|
||||
/// which is the same set the uninstall guard warns about. Two features disagreeing about one
|
||||
/// edge rule is the failure mode worth avoiding, and it is the whole reason this lives in Rust
|
||||
/// rather than being recomputed in the frontend.
|
||||
///
|
||||
/// Prefer [`Self::build_for`] wherever the interpreter is known: without it, requirements
|
||||
/// gated on a different `python_version` are treated as if they were in force.
|
||||
@@ -263,13 +269,13 @@ impl ReverseDeps {
|
||||
continue;
|
||||
}
|
||||
if !satisfies(&req.constraint, target) {
|
||||
let named = match self.versions.get(dependent) {
|
||||
Some(v) => format!("{dependent} {v}"),
|
||||
None => dependent.to_string(),
|
||||
};
|
||||
// Three fields, no phrasing: `by` and `version` name the culprit and
|
||||
// `constraint` is the requirement it declared, exactly as `breaking_dependents`
|
||||
// fills `BrokenDependent`. Each head writes its own sentence.
|
||||
out.push(Blocker {
|
||||
by: Some(dependent.clone()),
|
||||
constraint: format!("{named} requires {} {}", pkg, req.constraint),
|
||||
version: self.versions.get(dependent).cloned(),
|
||||
constraint: format!("{pkg}{}", req.constraint),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -607,11 +613,12 @@ mod tests {
|
||||
1,
|
||||
"anyio permits 1.0.9 and must not be named"
|
||||
);
|
||||
// Three fields, no phrasing (hard invariant 4). The CLI joins them with "requires" and
|
||||
// the GUI interpolates `plan.blocker`; a sentence built here is one both heads then have
|
||||
// to un-build, which is how the preview came to name the dependent twice.
|
||||
assert_eq!(blockers[0].by.as_ref(), Some(&pkg("httpx")));
|
||||
assert_eq!(
|
||||
blockers[0].constraint,
|
||||
"httpx 0.23.0 requires httpcore >=0.15.0,<0.16.0"
|
||||
);
|
||||
assert_eq!(blockers[0].version.as_deref(), Some("0.23.0"));
|
||||
assert_eq!(blockers[0].constraint, "httpcore>=0.15.0,<0.16.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -643,12 +650,15 @@ mod tests {
|
||||
|
||||
let g = ReverseDeps::build_for(&dists, "3.12.10");
|
||||
let found = g.blockers_for(&pkg("numpy"), &latest);
|
||||
let named: Vec<&str> = found.iter().map(|b| b.constraint.trim()).collect();
|
||||
let named: Vec<(Option<&str>, &str)> = found
|
||||
.iter()
|
||||
.map(|b| (b.version.as_deref(), b.constraint.trim()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
named,
|
||||
[
|
||||
"pandas 2.1.4 requires numpy <2,>=1.26.0",
|
||||
"statsmodels 0.14.1 requires numpy <2,>=1.18",
|
||||
(Some("2.1.4"), "numpy<2,>=1.26.0"),
|
||||
(Some("0.14.1"), "numpy<2,>=1.18"),
|
||||
],
|
||||
"only the branches in force on 3.12 may be named"
|
||||
);
|
||||
|
||||
@@ -68,11 +68,27 @@ pub const TOOLS_REQUIREMENTS: &str = include_str!(concat!(
|
||||
/// contains `msgpack`, which publishes **no** universal fallback at all and would therefore hard-
|
||||
/// fail under `--only-binary=:all:` on a new CPython.
|
||||
///
|
||||
/// Kept in the ledger so Dependabot keeps bumping it; excluded here. `pins` fails the build's test
|
||||
/// suite if a name below stops resolving, so a Dependabot rename is a `cargo test` failure rather
|
||||
/// than a `PD-HLT-001` on a user's machine.
|
||||
/// Kept in the ledger so Dependabot keeps bumping it; excluded here. `pins_for` fails the build's
|
||||
/// test suite if a name below stops resolving, so a Dependabot rename is a `cargo test` failure
|
||||
/// rather than a `PD-HLT-001` on a user's machine.
|
||||
///
|
||||
/// **P1-1 did not move it in here**, and the reason is the second paragraph above rather than the
|
||||
/// first. Once the Security tab exists, "a feature they cannot reach" stops being true — but the
|
||||
/// msgpack risk does not, and `--only-binary=:all:` is load-bearing (see [`install_pins`]). A
|
||||
/// fourth entry here would mean a CPython with no `msgpack` wheel fails the **whole** sync and
|
||||
/// takes Code Health down with a feature that has nothing to do with it. So pip-audit gets
|
||||
/// [`AUDIT_TOOLS`] and a venv of its own, and the blast radius of that wheel stays inside the tab
|
||||
/// that needs it.
|
||||
pub const HEALTH_TOOLS: &[&str] = &["deptry", "vulture", "ruff"];
|
||||
|
||||
/// The tools installed into the **audit** venv (PRD P1-1).
|
||||
///
|
||||
/// Its own set, and its own directory ([`audit_dir`]), for the reason [`HEALTH_TOOLS`] gives: these
|
||||
/// two venvs fail independently on purpose. Everything else — the manifest, the pin hash, the
|
||||
/// requirements rendering, `needs_sync`, `sync_tools_venv` — is shared and takes the tool list as
|
||||
/// an argument, so there is one bootstrap implementation rather than two that drift.
|
||||
pub const AUDIT_TOOLS: &[&str] = &["pip-audit"];
|
||||
|
||||
/// The oldest interpreter that may host the tools venv.
|
||||
///
|
||||
/// The binding floor is `deptry`'s and `pip-audit`'s `requires_python` of `>=3.10`, which is
|
||||
@@ -90,8 +106,8 @@ pub const MIN_TOOLS_PYTHON: (u32, u32) = crate::envs::MIN_PROBE_PYTHON;
|
||||
///
|
||||
/// * **deptry 0.25.1** — `0` clean, `1` findings
|
||||
/// * **vulture 2.16** — `0` none, `1` invalid input, `2` bad arguments, `3` dead code
|
||||
/// * **ruff 0.16.2** — `0` clean, `1` violations, `2` error (re-checked at 0.16.2 on 2026-08-13;
|
||||
/// 0.16.0 and 0.16.2 produced identical finding sets over two real packages)
|
||||
/// * **ruff 0.16.3** — `0` clean, `1` violations, `2` error (re-checked at 0.16.3 on 2026-08-13;
|
||||
/// 0.16.0 and 0.16.3 produced identical finding sets over two real packages)
|
||||
///
|
||||
/// A pin bump has to re-check this, and its real gate is the fixture corpus plus the integration
|
||||
/// job — not this comment.
|
||||
@@ -110,18 +126,27 @@ pub fn is_findings_exit(tool: &str, code: Option<i32>) -> bool {
|
||||
/// How many steps a sync reports: one venv, one install, one verification per tool.
|
||||
///
|
||||
/// Public because the caller builds the [`ProgressSink`], and a sink whose `total` disagrees with
|
||||
/// what actually runs is a progress bar that stops at four fifths.
|
||||
pub const SYNC_STEPS: usize = 2 + HEALTH_TOOLS.len();
|
||||
/// what actually runs is a progress bar that stops at four fifths. Takes the tool list rather than
|
||||
/// reading [`HEALTH_TOOLS`], because the audit venv installs one tool and would otherwise report a
|
||||
/// five-step sync that runs three.
|
||||
#[must_use]
|
||||
pub const fn sync_steps(tools: &[&str]) -> usize {
|
||||
2 + tools.len()
|
||||
}
|
||||
|
||||
/// The pin set to install, parsed out of the shipped ledger and sorted by normalized name.
|
||||
///
|
||||
/// Takes the tool list rather than assuming [`HEALTH_TOOLS`]: the two venvs render, hash and
|
||||
/// install different subsets of one ledger, and a function that guessed which would be the single
|
||||
/// place they could silently swap.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-PKG-002` when the ledger is malformed, names a version that is not shaped like one, or does
|
||||
/// not contain every entry of [`HEALTH_TOOLS`]. All three are release-time mistakes, which is why
|
||||
/// they surface as a failing test rather than as a runtime error path.
|
||||
pub fn pins() -> Result<Vec<PinnedSpec>> {
|
||||
/// not contain every entry of `tools`. All three are release-time mistakes, which is why they
|
||||
/// surface as a failing test rather than as a runtime error path.
|
||||
pub fn pins_for(tools: &[&str]) -> Result<Vec<PinnedSpec>> {
|
||||
let ledger = parse_ledger(TOOLS_REQUIREMENTS)?;
|
||||
HEALTH_TOOLS
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| {
|
||||
let name = PkgName::parse(tool)?;
|
||||
@@ -170,9 +195,10 @@ pub fn pins_hash(pins: &[PinnedSpec]) -> String {
|
||||
|
||||
/// The requirements file written into the tools directory, and the bytes the hash covers.
|
||||
///
|
||||
/// A **rendering**, not a copy of [`TOOLS_REQUIREMENTS`]. That is what keeps the excluded `pip-audit`
|
||||
/// pin, the ledger's comments and whatever line endings the build machine checked out from reaching
|
||||
/// either the hash or the user's disk. Always LF-terminated.
|
||||
/// A **rendering**, not a copy of [`TOOLS_REQUIREMENTS`]. That is what keeps the *other* venv's
|
||||
/// pins, the ledger's comments and whatever line endings the build machine checked out from
|
||||
/// reaching either the hash or the user's disk. Always LF-terminated. Rendering per set is also
|
||||
/// what makes the two hashes independent, so a `pip-audit` bump does not re-sync Code Health.
|
||||
#[must_use]
|
||||
pub fn requirements_body(pins: &[PinnedSpec]) -> String {
|
||||
pins.iter().fold(String::new(), |mut acc, pin| {
|
||||
@@ -203,6 +229,16 @@ pub fn tools_dir(app_data: &Path) -> PathBuf {
|
||||
app_data.join("tools")
|
||||
}
|
||||
|
||||
/// `<app_data>\audit` — the Security tab's venv (PRD P1-1).
|
||||
///
|
||||
/// A sibling of [`tools_dir`] rather than a directory inside it, so that clearing one is not
|
||||
/// silently clearing the other: `cache::Target` resolves each separately, and CODE-HEALTH-SPEC
|
||||
/// §2's layout describes `tools\` as Code Health's own.
|
||||
#[must_use]
|
||||
pub fn audit_dir(app_data: &Path) -> PathBuf {
|
||||
app_data.join("audit")
|
||||
}
|
||||
|
||||
/// `<tools_dir>\.venv\Scripts\python.exe`.
|
||||
#[must_use]
|
||||
pub fn venv_python(tools_dir: &Path) -> PathBuf {
|
||||
@@ -313,8 +349,8 @@ pub fn read_manifest(tools_dir: &Path) -> Option<ToolsManifest> {
|
||||
/// # Errors
|
||||
/// `PD-PKG-002` when the shipped ledger is malformed — a build-time mistake, surfaced here because
|
||||
/// this is the first thing every caller does.
|
||||
pub fn needs_sync(tools_dir: &Path) -> Result<SyncNeed> {
|
||||
let want = pins_hash(&pins()?);
|
||||
pub fn needs_sync(tools_dir: &Path, tools: &[&str]) -> Result<SyncNeed> {
|
||||
let want = pins_hash(&pins_for(tools)?);
|
||||
|
||||
let Some(manifest) = read_manifest(tools_dir) else {
|
||||
return Ok(SyncNeed::NeverSynced);
|
||||
@@ -328,7 +364,7 @@ pub fn needs_sync(tools_dir: &Path) -> Result<SyncNeed> {
|
||||
if !venv_python(tools_dir).is_file() {
|
||||
return Ok(SyncNeed::InterpreterGone);
|
||||
}
|
||||
for tool in HEALTH_TOOLS {
|
||||
for tool in tools {
|
||||
if !tool_exe(tools_dir, tool).is_file() {
|
||||
return Ok(SyncNeed::ToolMissing {
|
||||
tool: (*tool).to_owned(),
|
||||
@@ -413,7 +449,9 @@ fn validated_version(raw: &str) -> Result<Version> {
|
||||
/// `envs::scan()`, which spawns four subprocesses; a sync is not the place to hide a
|
||||
/// machine-wide sweep, and passing it lets `--python` force a specific interpreter.
|
||||
/// * `sink` carries the [`CancellationToken`](tokio_util::sync::CancellationToken), so a bootstrap
|
||||
/// stops through the same path as everything else. Build it with [`SYNC_STEPS`].
|
||||
/// stops through the same path as everything else. Build it with [`sync_steps`].
|
||||
/// * `tool_set` is [`HEALTH_TOOLS`] or [`AUDIT_TOOLS`], and has to match the directory: the two
|
||||
/// venvs are separate so that one tool's wheel availability cannot break the other's feature.
|
||||
///
|
||||
/// Returns the manifest it wrote, because the caller prints the tool versions and P3's
|
||||
/// `HealthReport.toolVersions` (CODE-HEALTH-SPEC §5) is exactly this map.
|
||||
@@ -427,9 +465,10 @@ fn validated_version(raw: &str) -> Result<Version> {
|
||||
pub async fn sync_tools_venv(
|
||||
tools_dir: &Path,
|
||||
base_python: &Path,
|
||||
tool_set: &[&str],
|
||||
sink: &ProgressSink,
|
||||
) -> Result<ToolsManifest> {
|
||||
let pins = pins()?;
|
||||
let pins = pins_for(tool_set)?;
|
||||
let venv = tools_dir.join(".venv");
|
||||
let requirements = tools_dir.join(REQUIREMENTS_FILE);
|
||||
let manifest_path = tools_dir.join(MANIFEST_FILE);
|
||||
@@ -443,8 +482,8 @@ pub async fn sync_tools_venv(
|
||||
// gone, a torn sync reads as `NeverSynced` and the next run redoes the whole thing.
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
|
||||
// A rendering of the ledger, not a copy: this is where the excluded `pip-audit` pin, the
|
||||
// comments, and whatever line endings the build machine checked out stop.
|
||||
// A rendering of the ledger, not a copy: this is where the *other* venv's pins, the comments,
|
||||
// and whatever line endings the build machine checked out stop.
|
||||
std::fs::write(&requirements, requirements_body(&pins))
|
||||
.map_err(|e| fs_failure("write the tools requirements", &e))?;
|
||||
|
||||
@@ -462,7 +501,7 @@ pub async fn sync_tools_venv(
|
||||
remove_venv(&venv)?;
|
||||
create_venv(base_python, &venv, &sink.at(0)).await?;
|
||||
install_pins(&venv, &requirements, &sink.at(1)).await?;
|
||||
let tools = verify_tools(tools_dir, sink).await?;
|
||||
let tools = verify_tools(tools_dir, tool_set, sink).await?;
|
||||
|
||||
let python = venv_python(tools_dir);
|
||||
let manifest = ToolsManifest {
|
||||
@@ -618,10 +657,14 @@ async fn install_pins(venv: &Path, requirements: &Path, sink: &ProgressSink) ->
|
||||
/// Per-tool and sequential, so `ExecMode::Isolated` is the honest phase. The install exiting zero
|
||||
/// is not proof the console scripts exist: this is the check `PD-HLT-001`'s shipped copy assumes
|
||||
/// somebody performs.
|
||||
async fn verify_tools(tools_dir: &Path, sink: &ProgressSink) -> Result<BTreeMap<String, String>> {
|
||||
async fn verify_tools(
|
||||
tools_dir: &Path,
|
||||
tool_set: &[&str],
|
||||
sink: &ProgressSink,
|
||||
) -> Result<BTreeMap<String, String>> {
|
||||
let mut versions = BTreeMap::new();
|
||||
|
||||
for (i, tool) in HEALTH_TOOLS.iter().enumerate() {
|
||||
for (i, tool) in tool_set.iter().enumerate() {
|
||||
let step = sink.at(2 + i);
|
||||
let name = PkgName::parse(tool)?;
|
||||
step.started(Some(name.clone()), ExecMode::Isolated);
|
||||
@@ -822,23 +865,39 @@ mod tests {
|
||||
/// The gate that turns a Dependabot rename into a `cargo test` failure rather than a
|
||||
/// `PD-HLT-001` on a user's machine.
|
||||
#[test]
|
||||
fn the_ledger_parses_to_exactly_the_three_health_tools() {
|
||||
let pins = pins().expect("the shipped ledger must parse");
|
||||
fn the_ledger_parses_into_two_disjoint_venvs() {
|
||||
let health: Vec<_> = pins_for(HEALTH_TOOLS)
|
||||
.expect("the shipped ledger must parse")
|
||||
.iter()
|
||||
.map(|p| p.name.to_string())
|
||||
.collect();
|
||||
assert_eq!(health, ["deptry", "ruff", "vulture"], "sorted by name");
|
||||
|
||||
let names: Vec<_> = pins.iter().map(|p| p.name.to_string()).collect();
|
||||
assert_eq!(names, ["deptry", "ruff", "vulture"], "sorted by name");
|
||||
// Until P1-1 this asserted that pip-audit reached **no** venv. It has one of its own now,
|
||||
// so the invariant that actually matters is that the two sets are *disjoint*: a CPython
|
||||
// with no `msgpack` wheel has to be able to fail the Security tab without taking Code
|
||||
// Health down with it, and that holds only while nothing is installed into both.
|
||||
let audit: Vec<_> = pins_for(AUDIT_TOOLS)
|
||||
.expect("the shipped ledger must parse")
|
||||
.iter()
|
||||
.map(|p| p.name.to_string())
|
||||
.collect();
|
||||
assert_eq!(audit, ["pip-audit"]);
|
||||
assert!(
|
||||
!health.iter().any(|n| audit.contains(n)),
|
||||
"the two venvs must install disjoint sets — see HEALTH_TOOLS"
|
||||
);
|
||||
|
||||
// The ledger carries pip-audit for the post-1.0 Security tab. It must not be installed.
|
||||
assert!(
|
||||
!names.iter().any(|n| n == "pip-audit"),
|
||||
"pip-audit is in the ledger but must not reach the tools venv — see HEALTH_TOOLS"
|
||||
);
|
||||
assert!(
|
||||
parse_ledger(TOOLS_REQUIREMENTS)
|
||||
.expect("ledger parses")
|
||||
.contains_key(&PkgName::parse("pip-audit").expect("valid name")),
|
||||
"pip-audit must stay in the ledger so Dependabot keeps bumping it"
|
||||
);
|
||||
// Both halves stay in one ledger, which is what keeps Dependabot bumping them together
|
||||
// and what makes a rename a `cargo test` failure rather than a `PD-HLT-001` on a user's
|
||||
// machine.
|
||||
let ledger = parse_ledger(TOOLS_REQUIREMENTS).expect("ledger parses");
|
||||
for tool in HEALTH_TOOLS.iter().chain(AUDIT_TOOLS) {
|
||||
assert!(
|
||||
ledger.contains_key(&PkgName::parse(tool).expect("valid name")),
|
||||
"{tool} must stay in the ledger so Dependabot keeps bumping it"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The CRLF trap, made into a gate.
|
||||
@@ -873,7 +932,7 @@ mod tests {
|
||||
#[test]
|
||||
fn changing_a_version_does_change_the_hash() {
|
||||
let before = "deptry==0.25.1\nvulture==2.16\nruff==0.16.0\n";
|
||||
let after = "deptry==0.25.1\nvulture==2.16\nruff==0.16.2\n";
|
||||
let after = "deptry==0.25.1\nvulture==2.16\nruff==0.16.3\n";
|
||||
|
||||
assert_ne!(hash_of(before), hash_of(after));
|
||||
}
|
||||
@@ -896,12 +955,32 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_written_requirements_are_lf_and_carry_only_the_health_tools() {
|
||||
let body = requirements_body(&pins().expect("ledger parses"));
|
||||
let body = requirements_body(&pins_for(HEALTH_TOOLS).expect("ledger parses"));
|
||||
|
||||
assert!(!body.contains('\r'), "always LF on disk");
|
||||
assert!(!body.contains('#'), "a rendering, not a copy");
|
||||
assert!(!body.contains("pip-audit"));
|
||||
assert!(
|
||||
!body.contains("pip-audit"),
|
||||
"a rendering of this set, not the ledger"
|
||||
);
|
||||
assert_eq!(body.lines().count(), HEALTH_TOOLS.len());
|
||||
|
||||
// And the other direction, which is the half that would have installed nothing at all:
|
||||
// rendering the audit set must produce pip-audit and none of Code Health's.
|
||||
let audit = requirements_body(&pins_for(AUDIT_TOOLS).expect("ledger parses"));
|
||||
assert!(audit.starts_with("pip-audit=="), "{audit:?}");
|
||||
assert_eq!(audit.lines().count(), AUDIT_TOOLS.len());
|
||||
for tool in HEALTH_TOOLS {
|
||||
assert!(
|
||||
!audit.contains(tool),
|
||||
"{tool} must not reach the audit venv"
|
||||
);
|
||||
}
|
||||
assert_ne!(
|
||||
pins_hash(&pins_for(HEALTH_TOOLS).expect("ledger parses")),
|
||||
pins_hash(&pins_for(AUDIT_TOOLS).expect("ledger parses")),
|
||||
"independent hashes are what stop a pip-audit bump re-syncing Code Health"
|
||||
);
|
||||
assert!(body.ends_with('\n'));
|
||||
}
|
||||
|
||||
@@ -912,10 +991,14 @@ mod tests {
|
||||
let dir = scratch("never");
|
||||
|
||||
assert_eq!(
|
||||
needs_sync(&dir).expect("ledger parses"),
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::NeverSynced
|
||||
);
|
||||
assert!(needs_sync(&dir).expect("ledger parses").is_needed());
|
||||
assert!(
|
||||
needs_sync(&dir, HEALTH_TOOLS)
|
||||
.expect("ledger parses")
|
||||
.is_needed()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -926,7 +1009,7 @@ mod tests {
|
||||
std::fs::write(dir.join(MANIFEST_FILE), "{ not json").expect("write");
|
||||
|
||||
assert_eq!(
|
||||
needs_sync(&dir).expect("ledger parses"),
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::NeverSynced
|
||||
);
|
||||
}
|
||||
@@ -935,10 +1018,20 @@ mod tests {
|
||||
fn a_matching_manifest_with_every_tool_present_is_fresh() {
|
||||
let dir = scratch("fresh");
|
||||
write_venv(&dir, HEALTH_TOOLS);
|
||||
write_manifest(&dir, &pins_hash(&pins().expect("ledger parses")));
|
||||
write_manifest(
|
||||
&dir,
|
||||
&pins_hash(&pins_for(HEALTH_TOOLS).expect("ledger parses")),
|
||||
);
|
||||
|
||||
assert_eq!(needs_sync(&dir).expect("ledger parses"), SyncNeed::Fresh);
|
||||
assert!(!needs_sync(&dir).expect("ledger parses").is_needed());
|
||||
assert_eq!(
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::Fresh
|
||||
);
|
||||
assert!(
|
||||
!needs_sync(&dir, HEALTH_TOOLS)
|
||||
.expect("ledger parses")
|
||||
.is_needed()
|
||||
);
|
||||
}
|
||||
|
||||
/// The case a hash comparison alone would call `Fresh`, and the one PD-HLT-001 is about.
|
||||
@@ -946,10 +1039,13 @@ mod tests {
|
||||
fn a_quarantined_tool_is_detected_even_though_the_hash_still_matches() {
|
||||
let dir = scratch("quarantined");
|
||||
write_venv(&dir, &["deptry", "vulture"]); // ruff.exe never written
|
||||
write_manifest(&dir, &pins_hash(&pins().expect("ledger parses")));
|
||||
write_manifest(
|
||||
&dir,
|
||||
&pins_hash(&pins_for(HEALTH_TOOLS).expect("ledger parses")),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
needs_sync(&dir).expect("ledger parses"),
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::ToolMissing {
|
||||
tool: "ruff".to_owned()
|
||||
}
|
||||
@@ -988,9 +1084,9 @@ mod tests {
|
||||
write_venv(&dir, HEALTH_TOOLS);
|
||||
write_manifest(&dir, &"0".repeat(64));
|
||||
|
||||
let want = pins_hash(&pins().expect("ledger parses"));
|
||||
let want = pins_hash(&pins_for(HEALTH_TOOLS).expect("ledger parses"));
|
||||
assert_eq!(
|
||||
needs_sync(&dir).expect("ledger parses"),
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::PinsChanged {
|
||||
from: "0".repeat(64),
|
||||
to: want,
|
||||
@@ -1003,10 +1099,13 @@ mod tests {
|
||||
let dir = scratch("gone");
|
||||
write_venv(&dir, HEALTH_TOOLS);
|
||||
std::fs::remove_file(venv_python(&dir)).expect("remove python");
|
||||
write_manifest(&dir, &pins_hash(&pins().expect("ledger parses")));
|
||||
write_manifest(
|
||||
&dir,
|
||||
&pins_hash(&pins_for(HEALTH_TOOLS).expect("ledger parses")),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
needs_sync(&dir).expect("ledger parses"),
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::InterpreterGone
|
||||
);
|
||||
}
|
||||
@@ -1024,7 +1123,7 @@ mod tests {
|
||||
// about serialization — and it failed on `main`, because that PR's CI predates the health
|
||||
// module. What is being pinned here is that the tools map survives the round trip, not
|
||||
// which version is in it.
|
||||
let pinned = pins()
|
||||
let pinned = pins_for(HEALTH_TOOLS)
|
||||
.expect("ledger parses")
|
||||
.into_iter()
|
||||
.find(|p| p.name.to_string() == "ruff")
|
||||
@@ -1108,8 +1207,11 @@ mod tests {
|
||||
#[test]
|
||||
fn the_step_count_matches_what_the_sync_actually_reports() {
|
||||
// A sink whose total disagrees with what runs is a progress bar that stops at four fifths.
|
||||
assert_eq!(SYNC_STEPS, 2 + HEALTH_TOOLS.len());
|
||||
assert_eq!(SYNC_STEPS, 5);
|
||||
assert_eq!(sync_steps(HEALTH_TOOLS), 2 + HEALTH_TOOLS.len());
|
||||
assert_eq!(sync_steps(HEALTH_TOOLS), 5);
|
||||
// The audit venv installs one tool, so a shared constant would have promised five
|
||||
// steps and run three.
|
||||
assert_eq!(sync_steps(AUDIT_TOOLS), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1221,16 +1323,21 @@ mod tests {
|
||||
}
|
||||
seen
|
||||
});
|
||||
let sink = ProgressSink::new(tx, SYNC_STEPS, Default::default());
|
||||
let sink = ProgressSink::new(tx, sync_steps(HEALTH_TOOLS), Default::default());
|
||||
|
||||
let manifest = sync_tools_venv(&dir, &python, &sink)
|
||||
let manifest = sync_tools_venv(&dir, &python, HEALTH_TOOLS, &sink)
|
||||
.await
|
||||
.expect("bootstrap succeeds");
|
||||
drop(sink);
|
||||
|
||||
assert_eq!(manifest.tools.len(), HEALTH_TOOLS.len());
|
||||
assert_eq!(needs_sync(&dir).expect("ledger parses"), SyncNeed::Fresh);
|
||||
assert_eq!(
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::Fresh
|
||||
);
|
||||
// The exclusion, checked where it actually matters rather than only in the rendering.
|
||||
// Against a real bootstrap rather than a constructed manifest: this is the venv Code
|
||||
// Health runs out of, and pip-audit belongs to the other one.
|
||||
assert!(!manifest.pins.iter().any(|p| p.starts_with("pip-audit")));
|
||||
|
||||
let seen = events.await.expect("collector");
|
||||
@@ -1255,20 +1362,27 @@ mod tests {
|
||||
.expect("this machine has a Python 3.10+");
|
||||
let sink = || {
|
||||
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
ProgressSink::new(tx, SYNC_STEPS, CancellationToken::new())
|
||||
ProgressSink::new(tx, sync_steps(HEALTH_TOOLS), CancellationToken::new())
|
||||
};
|
||||
|
||||
sync_tools_venv(&dir, &python, &sink())
|
||||
sync_tools_venv(&dir, &python, HEALTH_TOOLS, &sink())
|
||||
.await
|
||||
.expect("first bootstrap succeeds");
|
||||
std::fs::remove_file(tool_exe(&dir, "ruff")).expect("quarantine ruff");
|
||||
assert!(needs_sync(&dir).expect("ledger parses").is_needed());
|
||||
assert!(
|
||||
needs_sync(&dir, HEALTH_TOOLS)
|
||||
.expect("ledger parses")
|
||||
.is_needed()
|
||||
);
|
||||
|
||||
sync_tools_venv(&dir, &python, &sink())
|
||||
sync_tools_venv(&dir, &python, HEALTH_TOOLS, &sink())
|
||||
.await
|
||||
.expect("a re-sync must repair it, not fail on it");
|
||||
|
||||
assert_eq!(needs_sync(&dir).expect("ledger parses"), SyncNeed::Fresh);
|
||||
assert_eq!(
|
||||
needs_sync(&dir, HEALTH_TOOLS).expect("ledger parses"),
|
||||
SyncNeed::Fresh
|
||||
);
|
||||
}
|
||||
|
||||
/// A scratch directory of our own, cleaned on entry. Matches `store`'s idiom rather than
|
||||
@@ -1291,7 +1405,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn write_manifest(tools_dir: &Path, hash: &str) {
|
||||
let installed = pins().expect("ledger parses");
|
||||
let installed = pins_for(HEALTH_TOOLS).expect("ledger parses");
|
||||
let manifest = ToolsManifest {
|
||||
pins_hash: hash.to_owned(),
|
||||
pins: installed.iter().map(PinnedSpec::to_requirement).collect(),
|
||||
|
||||
@@ -23,7 +23,9 @@
|
||||
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod audit;
|
||||
pub mod bindings;
|
||||
pub mod cache;
|
||||
pub mod compat;
|
||||
pub mod engine;
|
||||
pub mod envs;
|
||||
@@ -38,6 +40,7 @@ pub mod model;
|
||||
pub mod pins;
|
||||
pub mod plan;
|
||||
pub mod report;
|
||||
pub mod requirements;
|
||||
pub mod settings;
|
||||
pub mod snapshot;
|
||||
pub mod store;
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::errors::{Code, PdError, Result};
|
||||
use crate::model::{PinnedSpec, PkgName, Version};
|
||||
use crate::graph::ReverseDeps;
|
||||
use crate::model::{Dist, PinnedSpec, PkgName, Version};
|
||||
use crate::store::Store;
|
||||
|
||||
/// How a pin constrains a package.
|
||||
@@ -217,6 +218,80 @@ pub fn filter_upgrades(
|
||||
out
|
||||
}
|
||||
|
||||
/// A package worth pinning, and why — PRD P1-2, UI-SPEC §4.
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PinSuggestion {
|
||||
/// The package being suggested.
|
||||
pub pkg: PkgName,
|
||||
/// How many installed packages depend on it.
|
||||
///
|
||||
/// The number is the whole argument, so it is carried rather than recomputed for display:
|
||||
/// "12 packages depend on it" is what makes the suggestion actionable, and a count the screen
|
||||
/// derived separately would eventually disagree with the one that qualified it.
|
||||
pub dependents: usize,
|
||||
}
|
||||
|
||||
/// Packages many others depend on, which a bulk update should probably leave alone.
|
||||
///
|
||||
/// **The advisory half of this module.** [`filter_upgrades`] is enforcement — what a pin *does*;
|
||||
/// this is what the shape of an environment suggests pinning. PRD P1-2: at or above `threshold`
|
||||
/// reverse dependencies, offer a pin.
|
||||
///
|
||||
/// Counts come from [`ReverseDeps::dependent_count`], which counts **in-force** edges only —
|
||||
/// extra-gated and marker-excluded requirements do not qualify a package. That is the same set the
|
||||
/// uninstall guard warns about, and keeping the two identical is the entire reason this is
|
||||
/// computed here rather than in the frontend, which already holds `requires_dist` and could
|
||||
/// plausibly loop over it. Two implementations of one edge rule drift, and the half that drifts
|
||||
/// silently is this one.
|
||||
///
|
||||
/// Takes the pins and the threshold as values rather than a `&Store`: `Store` is not `Sync`, so a
|
||||
/// future holding one is not `Send` and cannot be returned from a Tauri command. [`crate::flow`]
|
||||
/// takes pins for the same reason.
|
||||
///
|
||||
/// Already-pinned packages are dropped — suggesting what the user has already done is noise.
|
||||
/// Nothing records a *rejected* suggestion, so unpinning something re-offers it; that is a known
|
||||
/// rough edge rather than an oversight, and both are on the same screen so it is visible.
|
||||
#[must_use]
|
||||
pub fn suggest(
|
||||
dists: &[Dist],
|
||||
python_version: &str,
|
||||
existing: &[Pin],
|
||||
threshold: usize,
|
||||
) -> Vec<PinSuggestion> {
|
||||
// A threshold of zero would suggest every package in the environment, including the leaves
|
||||
// nothing depends on. Treated as "off" rather than as "suggest everything".
|
||||
if threshold == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let pinned: BTreeSet<&PkgName> = existing.iter().map(|p| &p.pkg).collect();
|
||||
// `build_for`, not `build`: without the interpreter, a requirement gated on some other
|
||||
// `python_version` counts as if it were in force, and the suggestion inherits the same wrong
|
||||
// answer the preview used to give (SP-5).
|
||||
let graph = ReverseDeps::build_for(dists, python_version);
|
||||
|
||||
let mut out: Vec<PinSuggestion> = dists
|
||||
.iter()
|
||||
.filter(|d| !pinned.contains(&d.name))
|
||||
.filter_map(|d| {
|
||||
let dependents = graph.dependent_count(&d.name);
|
||||
(dependents >= threshold).then(|| PinSuggestion {
|
||||
pkg: d.name.clone(),
|
||||
dependents,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Most-depended-upon first, then by name. Stable ordering matters more than it looks: this
|
||||
// list is re-fetched on every visit to the screen, and one that reorders between two identical
|
||||
// reads reads as though the environment changed.
|
||||
out.sort_by(|a, b| b.dependents.cmp(&a.dependents).then(a.pkg.cmp(&b.pkg)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The exact-version requirements `Hold` pins contribute to every plan.
|
||||
///
|
||||
/// These join the guard set [`crate::engine::plan_requirements`] builds, so the resolver treats a
|
||||
@@ -254,6 +329,113 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn dist(name: &str, requires: &[&str]) -> Dist {
|
||||
Dist {
|
||||
name: pkg(name),
|
||||
version: Version("1.0".into()),
|
||||
requires_dist: requires.iter().map(|s| (*s).to_owned()).collect(),
|
||||
requires_python: None,
|
||||
size_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` packages that all depend on `on`, plus `on` itself.
|
||||
fn depended_on_by(on: &str, n: usize) -> Vec<Dist> {
|
||||
std::iter::once(dist(on, &[]))
|
||||
.chain((0..n).map(|i| {
|
||||
let name = format!("app{i}");
|
||||
dist(&name, &[on])
|
||||
}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_below_the_threshold_is_not_suggested() {
|
||||
let dists = depended_on_by("urllib3", 4);
|
||||
assert_eq!(suggest(&dists, "3.12.4", &[], 5), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_is_inclusive() {
|
||||
// PRD P1-2 says "count >= threshold". Off by one here means the default of 5 fires at 6,
|
||||
// and nobody would notice because both are plausible.
|
||||
let dists = depended_on_by("urllib3", 5);
|
||||
let got = suggest(&dists, "3.12.4", &[], 5);
|
||||
assert_eq!(got.len(), 1);
|
||||
assert_eq!(got[0].pkg, pkg("urllib3"));
|
||||
assert_eq!(got[0].dependents, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_pinned_package_is_never_suggested() {
|
||||
// Suggesting what the user has already done is noise, however high the count.
|
||||
let dists = depended_on_by("urllib3", 50);
|
||||
let pins = vec![exclude("urllib3", None)];
|
||||
assert_eq!(suggest(&dists, "3.12.4", &pins, 5), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_gated_dependents_do_not_qualify_a_package() {
|
||||
// The same rule the uninstall guard follows. An extra is not installed unless it was
|
||||
// asked for, so a dependency that exists only under `extra == "socks"` is not a reason to
|
||||
// pin anything — and the guard and the suggestion must agree about which edges are real
|
||||
// or the user is pinning on one rule and being warned on another.
|
||||
let dists: Vec<Dist> = std::iter::once(dist("urllib3", &[]))
|
||||
.chain((0..6).map(|i| {
|
||||
let name = format!("app{i}");
|
||||
dist(&name, &["urllib3; extra == \"socks\""])
|
||||
}))
|
||||
.collect();
|
||||
assert_eq!(suggest(&dists, "3.12.4", &[], 5), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requirements_gated_on_another_python_do_not_qualify_a_package() {
|
||||
// `build_for`, not `build`. With markers unevaluated these six count and urllib3 is
|
||||
// suggested on 3.12 because of constraints that only apply below 3.11.
|
||||
let dists: Vec<Dist> = std::iter::once(dist("urllib3", &[]))
|
||||
.chain((0..6).map(|i| {
|
||||
let name = format!("app{i}");
|
||||
dist(&name, &["urllib3; python_version < \"3.11\""])
|
||||
}))
|
||||
.collect();
|
||||
assert_eq!(suggest(&dists, "3.12.4", &[], 5), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_are_ordered_by_count_then_name() {
|
||||
// The list is re-read on every visit to the screen. One that reorders between two
|
||||
// identical reads reads as though the environment changed under the user.
|
||||
let mut dists = vec![
|
||||
dist("urllib3", &[]),
|
||||
dist("certifi", &[]),
|
||||
dist("idna", &[]),
|
||||
];
|
||||
for i in 0..8 {
|
||||
dists.push(dist(&format!("app{i}"), &["urllib3", "certifi", "idna"]));
|
||||
}
|
||||
// Two more that only reach urllib3, so it leads; certifi and idna tie at 8 and sort by
|
||||
// name.
|
||||
for i in 8..10 {
|
||||
dists.push(dist(&format!("extra{i}"), &["urllib3"]));
|
||||
}
|
||||
|
||||
let got = suggest(&dists, "3.12.4", &[], 5);
|
||||
let names: Vec<&str> = got.iter().map(|s| s.pkg.as_str()).collect();
|
||||
assert_eq!(names, ["urllib3", "certifi", "idna"]);
|
||||
assert_eq!(got[0].dependents, 10);
|
||||
assert_eq!(got[1].dependents, 8);
|
||||
assert_eq!(got[2].dependents, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_threshold_of_zero_suggests_nothing_rather_than_everything() {
|
||||
// The degenerate setting. Every package trivially has >= 0 dependents, so without the
|
||||
// guard this offers to pin the whole environment, leaves included.
|
||||
let dists = depended_on_by("urllib3", 6);
|
||||
assert_eq!(suggest(&dists, "3.12.4", &[], 0), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_version_is_shape_checked_before_it_can_reach_argv() {
|
||||
let store = Store::in_memory().expect("store");
|
||||
|
||||
@@ -86,7 +86,21 @@ pub struct Blocker {
|
||||
/// The package imposing the constraint, absent when attribution is ambiguous.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub by: Option<PkgName>,
|
||||
/// The constraint text, e.g. `"requests<2.31"`.
|
||||
/// The installed version of [`Self::by`], when the probe knew it.
|
||||
///
|
||||
/// Split out for the same reason [`crate::graph::BrokenDependent`] splits it: the two heads
|
||||
/// phrase this differently — the CLI writes `scipy 1.11.4 requires …` itself, the GUI
|
||||
/// interpolates `plan.blocker` — and neither can un-join a string Rust joined for it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
/// The requirement holding the package back, e.g. `"requests<2.31"`.
|
||||
///
|
||||
/// **Data, not a sentence** — hard invariant 4. Until Slice 0 this carried
|
||||
/// `"scipy 1.11.4 requires numpy <1.28.0,>=1.21.6"`, a phrase assembled in Rust, which the
|
||||
/// GUI then wrapped in `"{{by}} requires {{constraint}}"` and rendered naming the dependent
|
||||
/// **twice**. Only the CLI looked right, because it prints this field alone. The shape here
|
||||
/// now matches `BrokenDependent.constraint`, which the guard dialog has always composed
|
||||
/// correctly.
|
||||
pub constraint: String,
|
||||
}
|
||||
|
||||
@@ -267,6 +281,10 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
|
||||
"ResolutionReport" => ResolutionReport,
|
||||
"ExecutionSummary" => ExecutionSummary,
|
||||
"Pin" => crate::pins::Pin,
|
||||
"PinSuggestion" => crate::pins::PinSuggestion,
|
||||
"ParsedRequirements" => crate::requirements::ParsedRequirements,
|
||||
"CacheUsage" => crate::cache::Usage,
|
||||
"CacheTarget" => crate::cache::Target,
|
||||
"GuardReport" => crate::graph::GuardReport,
|
||||
"Diff" => crate::snapshot::Diff,
|
||||
"SnapshotMeta" => crate::snapshot::Meta,
|
||||
@@ -286,6 +304,7 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
|
||||
// into its own TS declaration, so `DeptryIssue` and the rest arrive without being listed.
|
||||
// Registering them separately would emit each twice.
|
||||
"HealthReport" => crate::health::HealthReport,
|
||||
"AuditReport" => crate::audit::AuditReport,
|
||||
"FixReport" => crate::health::fix::FixReport,
|
||||
}
|
||||
}
|
||||
@@ -301,6 +320,10 @@ pub const SCHEMA_TYPES: &[&str] = &[
|
||||
"ResolutionReport",
|
||||
"ExecutionSummary",
|
||||
"Pin",
|
||||
"PinSuggestion",
|
||||
"ParsedRequirements",
|
||||
"CacheUsage",
|
||||
"CacheTarget",
|
||||
"GuardReport",
|
||||
"Diff",
|
||||
"SnapshotMeta",
|
||||
@@ -317,6 +340,7 @@ pub const SCHEMA_TYPES: &[&str] = &[
|
||||
"Intent",
|
||||
"Code",
|
||||
"HealthReport",
|
||||
"AuditReport",
|
||||
"FixReport",
|
||||
];
|
||||
|
||||
@@ -907,6 +931,7 @@ mod tests {
|
||||
latest: Version("2.32.3".into()),
|
||||
blockers: vec![Blocker {
|
||||
by: Some(PkgName::parse("apiclient").unwrap()),
|
||||
version: None,
|
||||
constraint: "requests<2.31".into(),
|
||||
}],
|
||||
};
|
||||
|
||||
@@ -268,7 +268,7 @@ mod tests {
|
||||
assert!(
|
||||
held.blockers[0]
|
||||
.constraint
|
||||
.contains("httpcore >=0.15.0,<0.16.0")
|
||||
.contains("httpcore>=0.15.0,<0.16.0")
|
||||
);
|
||||
assert!(!report.is_clean(), "a held-back package needs a decision");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Reading a `requirements.txt` — PRD P1-3.
|
||||
//!
|
||||
//! **Writing one needs no code.** A `pip freeze` document *is* a requirements file, and
|
||||
//! [`crate::engine::Engine::freeze`] already produces it for snapshots. Export is that string and
|
||||
//! a path. This module is the other direction.
|
||||
//!
|
||||
//! # Why not [`crate::snapshot::parse_freeze`]
|
||||
//!
|
||||
//! That parser is deliberately narrow: `name==version`, nothing else. Its narrowness is what makes
|
||||
//! it the exact complement of [`crate::snapshot::unrestorable_lines`], an invariant a rollback
|
||||
//! preview depends on — so widening it to read a hand-written requirements file would break the
|
||||
//! thing it exists for. A file a person wrote has ranges, extras, markers, hashes, includes and
|
||||
//! comments after the spec, and none of those belong in a freeze.
|
||||
//!
|
||||
//! # What is refused, and why refusing beats guessing
|
||||
//!
|
||||
//! `-r other.txt` and `-c constraints.txt` pull in files PipDock has not read and the user has not
|
||||
//! seen in the preview. `-e .` and direct URLs install from somewhere other than the index. Each
|
||||
//! is **reported by line** rather than skipped, because a silently shorter install list is the
|
||||
//! failure mode DATA-FLOW §9 exists to prevent: the preview would be honest about what it is doing
|
||||
//! and wrong about what the user asked for.
|
||||
|
||||
use crate::graph::Requirement;
|
||||
use crate::model::PkgName;
|
||||
|
||||
/// A line the parser would not turn into an install spec, and what was wrong with it.
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SkippedLine {
|
||||
/// 1-based, so it matches what an editor shows.
|
||||
pub line: usize,
|
||||
/// The line, trimmed. Data — shown verbatim, never translated (I18N §2).
|
||||
pub text: String,
|
||||
/// Why, as a catalog-style discriminant the UI turns into a sentence.
|
||||
pub reason: SkipReason,
|
||||
}
|
||||
|
||||
/// Why a line was not turned into a spec.
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum SkipReason {
|
||||
/// `-r` or `-c`: another file, which PipDock has not read.
|
||||
Include,
|
||||
/// `-e`, or a `name @ url` / VCS requirement: installs from somewhere other than the index.
|
||||
NotFromIndex,
|
||||
/// An option line (`--index-url`, `--extra-index-url`, …) that changes how *everything*
|
||||
/// installs. Honouring one silently would change the meaning of the whole file.
|
||||
Option,
|
||||
/// The line is not a requirement PipDock can parse at all.
|
||||
Unparsed,
|
||||
}
|
||||
|
||||
/// What [`parse`] made of a file.
|
||||
#[derive(
|
||||
Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ParsedRequirements {
|
||||
/// Install specs, in file order, as `Intent::Install` wants them.
|
||||
pub specs: Vec<String>,
|
||||
/// Everything else, with its line number and reason.
|
||||
pub skipped: Vec<SkippedLine>,
|
||||
}
|
||||
|
||||
impl ParsedRequirements {
|
||||
/// True when there is nothing to install.
|
||||
#[must_use]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.specs.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip an end-of-line comment.
|
||||
///
|
||||
/// PEP 508 requires a space before the `#`, which is what makes this safe: a `#` inside a URL
|
||||
/// fragment or a version's local segment has no space in front of it and survives.
|
||||
fn strip_comment(line: &str) -> &str {
|
||||
match line.find(" #") {
|
||||
Some(at) => &line[..at],
|
||||
None => line,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop `--hash=...` fragments and any trailing line-continuation marker.
|
||||
///
|
||||
/// Hashes are pip's integrity check against the index, not part of *what* to install, and PipDock
|
||||
/// does not download the artefact itself. Keeping them would put an unparseable token into argv.
|
||||
fn strip_hashes(line: &str) -> String {
|
||||
line.split_whitespace()
|
||||
.filter(|tok| !tok.starts_with("--hash") && *tok != "\\")
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// Read a requirements file into install specs.
|
||||
///
|
||||
/// Joins continuation lines first, so a requirement split over several physical lines is one
|
||||
/// logical requirement — pip allows it and a file that uses it would otherwise produce one
|
||||
/// unparseable fragment per line.
|
||||
#[must_use]
|
||||
pub fn parse(text: &str) -> ParsedRequirements {
|
||||
let mut out = ParsedRequirements::default();
|
||||
|
||||
// (line number of the *first* physical line, joined text).
|
||||
let mut logical: Vec<(usize, String)> = Vec::new();
|
||||
let mut pending: Option<(usize, String)> = None;
|
||||
for (i, raw) in text.lines().enumerate() {
|
||||
let trimmed = raw.trim();
|
||||
let continues = trimmed.ends_with('\\');
|
||||
let body = trimmed.trim_end_matches('\\').trim();
|
||||
match pending.as_mut() {
|
||||
Some((_, acc)) => {
|
||||
acc.push(' ');
|
||||
acc.push_str(body);
|
||||
}
|
||||
None => pending = Some((i + 1, body.to_owned())),
|
||||
}
|
||||
if !continues && let Some(entry) = pending.take() {
|
||||
logical.push(entry);
|
||||
}
|
||||
}
|
||||
if let Some(entry) = pending.take() {
|
||||
logical.push(entry);
|
||||
}
|
||||
|
||||
for (line, raw) in logical {
|
||||
let body = strip_comment(&raw).trim();
|
||||
if body.is_empty() || body.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let body = strip_hashes(body);
|
||||
let body = body.trim();
|
||||
|
||||
let skip = |reason: SkipReason| SkippedLine {
|
||||
line,
|
||||
text: body.to_owned(),
|
||||
reason,
|
||||
};
|
||||
|
||||
if body.starts_with("-r") || body.starts_with("--requirement") {
|
||||
out.skipped.push(skip(SkipReason::Include));
|
||||
continue;
|
||||
}
|
||||
if body.starts_with("-c") || body.starts_with("--constraint") {
|
||||
out.skipped.push(skip(SkipReason::Include));
|
||||
continue;
|
||||
}
|
||||
if body.starts_with("-e") || body.starts_with("--editable") {
|
||||
out.skipped.push(skip(SkipReason::NotFromIndex));
|
||||
continue;
|
||||
}
|
||||
if body.starts_with('-') {
|
||||
out.skipped.push(skip(SkipReason::Option));
|
||||
continue;
|
||||
}
|
||||
// `name @ url`, and bare URLs. Both install from outside the index, and both would reach
|
||||
// argv as something PipDock never validated.
|
||||
if body.contains('@') || body.contains("://") {
|
||||
out.skipped.push(skip(SkipReason::NotFromIndex));
|
||||
continue;
|
||||
}
|
||||
|
||||
// `Requirement::parse` already understands `name[extras] (spec); marker` and is exercised
|
||||
// against real `Requires-Dist` metadata — the closest thing to a PEP 508 line parser in
|
||||
// the tree, and reusing it is what stops this file inventing a second grammar.
|
||||
//
|
||||
// **But its input is normally trusted and this input is not.** It splits the name at the
|
||||
// first space, so `this is not a requirement` parses happily as name `this` with
|
||||
// constraint `is not a requirement` — which `render` would emit as a spec containing
|
||||
// spaces, straight into argv. `Requires-Dist` never looks like that; a file a person typed
|
||||
// can. So the constraint is checked here, which is the same obligation SECURITY §2 puts on
|
||||
// every other user-supplied version.
|
||||
match Requirement::parse(body) {
|
||||
Some(req) if is_specifier(&req.constraint) => out.specs.push(render(&req)),
|
||||
_ => out.skipped.push(skip(SkipReason::Unparsed)),
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Is this a PEP 440 version specifier set, rather than prose that happened to follow a word?
|
||||
///
|
||||
/// Deliberately a shape check, not a full parse — the same trade [`crate::pins`] makes for a
|
||||
/// `Hold` version, and for the same reason: refusing a legitimate specifier would make a package
|
||||
/// uninstallable, while the job here is only to reject whitespace and anything that is not part
|
||||
/// of a specifier's alphabet. An empty constraint is valid and means "any version".
|
||||
fn is_specifier(raw: &str) -> bool {
|
||||
if raw.is_empty() {
|
||||
return true;
|
||||
}
|
||||
raw.starts_with(['<', '>', '=', '!', '~'])
|
||||
&& raw.chars().all(|c| {
|
||||
c.is_ascii_alphanumeric()
|
||||
|| matches!(
|
||||
c,
|
||||
'<' | '>' | '=' | '!' | '~' | '.' | ',' | '*' | '-' | '_' | '+'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Render a parsed requirement back as a spec `Intent::Install` accepts.
|
||||
///
|
||||
/// **The marker is dropped, and the extras with it.** A marker is a condition on the *installing*
|
||||
/// environment that the resolver evaluates itself, and PipDock's job here is to say which packages
|
||||
/// to ask for. Keeping either would put a token into argv that
|
||||
/// `plan::build_request`'s `name==version` split does not understand.
|
||||
fn render(req: &Requirement) -> String {
|
||||
if req.constraint.is_empty() {
|
||||
req.name.as_str().to_owned()
|
||||
} else {
|
||||
format!("{}{}", req.name.as_str(), req.constraint)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a parse produced, for a caller that wants to check them against what is installed.
|
||||
#[must_use]
|
||||
pub fn names(parsed: &ParsedRequirements) -> Vec<PkgName> {
|
||||
parsed
|
||||
.specs
|
||||
.iter()
|
||||
.filter_map(|s| {
|
||||
let end = s
|
||||
.find(|c: char| !c.is_ascii_alphanumeric() && !matches!(c, '.' | '-' | '_'))
|
||||
.unwrap_or(s.len());
|
||||
PkgName::parse(&s[..end]).ok()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_freeze_document_round_trips() {
|
||||
// The commonest input by far: what PipDock's own export writes.
|
||||
let got = parse("requests==2.32.3\nurllib3==2.2.1\n");
|
||||
assert_eq!(got.specs, ["requests==2.32.3", "urllib3==2.2.1"]);
|
||||
assert!(got.skipped.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_and_unconstrained_names_survive() {
|
||||
let got = parse("django>=5.0,<6\nrich\n");
|
||||
assert_eq!(got.specs, ["django>=5.0,<6", "rich"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_and_blank_lines_say_nothing() {
|
||||
let got = parse("# top\n\nrequests==2.32.3 # pinned by ops\n\n# end\n");
|
||||
assert_eq!(got.specs, ["requests==2.32.3"]);
|
||||
assert!(got.skipped.is_empty(), "a comment is not a skipped line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hash_is_dropped_rather_than_reaching_argv() {
|
||||
// pip's integrity check against the index. PipDock does not fetch the artefact, and the
|
||||
// token is not a thing the engine's spec grammar accepts.
|
||||
let got = parse("requests==2.32.3 --hash=sha256:abc123\n");
|
||||
assert_eq!(got.specs, ["requests==2.32.3"]);
|
||||
assert!(got.skipped.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuation_is_one_requirement_not_two_fragments() {
|
||||
let got = parse("requests==2.32.3 \\\n --hash=sha256:abc \\\n --hash=sha256:def\n");
|
||||
assert_eq!(got.specs, ["requests==2.32.3"]);
|
||||
assert!(got.skipped.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extras_and_markers_are_dropped_from_the_spec() {
|
||||
// Both are conditions the resolver evaluates for itself; neither is part of "which
|
||||
// package". A marker reaching argv is a token `build_request` cannot split.
|
||||
let got = parse("requests[socks]>=2.0; python_version >= \"3.10\"\n");
|
||||
assert_eq!(got.specs, ["requests>=2.0"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_is_reported_by_line_rather_than_skipped_quietly() {
|
||||
// The file it names has not been read and will not appear in the preview. A silently
|
||||
// shorter install list is the failure DATA-FLOW §9 exists to prevent.
|
||||
let got = parse("requests==2.32.3\n-r dev-requirements.txt\n");
|
||||
assert_eq!(got.specs, ["requests==2.32.3"]);
|
||||
assert_eq!(got.skipped.len(), 1);
|
||||
assert_eq!(got.skipped[0].line, 2);
|
||||
assert_eq!(got.skipped[0].reason, SkipReason::Include);
|
||||
assert_eq!(got.skipped[0].text, "-r dev-requirements.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editable_and_url_requirements_are_refused_as_not_from_the_index() {
|
||||
let got = parse("-e .\nfoo @ https://example.invalid/foo.whl\nhttps://x.invalid/b.whl\n");
|
||||
assert!(got.specs.is_empty());
|
||||
assert_eq!(got.skipped.len(), 3);
|
||||
assert!(
|
||||
got.skipped
|
||||
.iter()
|
||||
.all(|s| s.reason == SkipReason::NotFromIndex)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_option_changes_the_whole_file_and_is_refused() {
|
||||
// `--index-url` changes where *everything* comes from. Honouring it silently would make
|
||||
// the preview describe an install from somewhere the user was never shown.
|
||||
let got = parse("--index-url https://internal.invalid/simple\nrequests==2.32.3\n");
|
||||
assert_eq!(got.specs, ["requests==2.32.3"]);
|
||||
assert_eq!(got.skipped[0].reason, SkipReason::Option);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_numbers_are_the_ones_an_editor_shows() {
|
||||
let got = parse("# a\n\n-r b.txt\n");
|
||||
assert_eq!(got.skipped[0].line, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prose_is_reported_rather_than_becoming_a_package_named_after_its_first_word() {
|
||||
// `Requirement::parse` splits the name at the first space, so this yields name `this`
|
||||
// with constraint `is not a requirement` — perfectly reasonable for `Requires-Dist`,
|
||||
// which never looks like prose, and a spec containing spaces heading for argv here.
|
||||
let got = parse("this is not a requirement\n");
|
||||
assert!(got.specs.is_empty(), "got {:?}", got.specs);
|
||||
assert_eq!(got.skipped[0].reason, SkipReason::Unparsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_specifier_shape_pip_accepts_survives_the_check() {
|
||||
// The check is a shape test, not a PEP 440 parse: rejecting a legitimate specifier would
|
||||
// make a package uninstallable, which is the worse failure.
|
||||
for spec in [
|
||||
"requests==2.32.3",
|
||||
"requests>=2.0,<3",
|
||||
"requests~=2.32.0",
|
||||
"requests!=2.31.0",
|
||||
"requests===2.32.3",
|
||||
"requests==2.32.*",
|
||||
"requests>=1.0.0-rc.1",
|
||||
"requests==1!2.0+local.1",
|
||||
] {
|
||||
let got = parse(&format!("{spec}\n"));
|
||||
assert_eq!(got.specs, [spec], "rejected a valid specifier: {spec}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_reads_back_what_was_asked_for() {
|
||||
let parsed = parse("requests==2.32.3\ndjango>=5.0,<6\nrich\n");
|
||||
let read = names(&parsed);
|
||||
let got: Vec<&str> = read.iter().map(PkgName::as_str).collect();
|
||||
assert_eq!(got, ["requests", "django", "rich"]);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use crate::store::Store;
|
||||
const KEY_ENGINE: &str = "settings.engine";
|
||||
const KEY_LOCALE: &str = "settings.locale";
|
||||
const KEY_ALLOW_EXTERNALLY_MANAGED: &str = "settings.allowExternallyManaged";
|
||||
const KEY_PIN_SUGGEST_THRESHOLD: &str = "settings.pinSuggestThreshold";
|
||||
const KEY_CONSENT_HASH: &str = "legal.consentDocsHash";
|
||||
const KEY_CONSENT_AT: &str = "legal.consentAt";
|
||||
|
||||
@@ -37,6 +38,11 @@ pub struct Settings {
|
||||
/// `--break-system-packages` equivalent be passed. PipDock never adds that flag silently —
|
||||
/// hard invariant 5.
|
||||
pub allow_externally_managed: bool,
|
||||
/// How many reverse dependencies qualify a package for a pin suggestion (PRD P1-2).
|
||||
///
|
||||
/// UI-SPEC §4 lists this under Settings' thresholds. Zero means off — see
|
||||
/// [`crate::pins::suggest`], which would otherwise offer to pin every leaf in the environment.
|
||||
pub pin_suggest_threshold: usize,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -48,6 +54,9 @@ impl Default for Settings {
|
||||
engine: EngineId::Pip,
|
||||
locale: None,
|
||||
allow_externally_managed: false,
|
||||
// The const, not a literal 5. It exists so the default has one home, and it lived in
|
||||
// `graph` unread from M2 until P1-A gave it a caller.
|
||||
pin_suggest_threshold: crate::graph::PIN_SUGGEST_THRESHOLD,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,6 +80,13 @@ pub fn load(store: &Store) -> Result<Settings> {
|
||||
if let Some(raw) = store.get(KEY_ALLOW_EXTERNALLY_MANAGED)? {
|
||||
out.allow_externally_managed = raw == "true";
|
||||
}
|
||||
if let Some(raw) = store.get(KEY_PIN_SUGGEST_THRESHOLD)? {
|
||||
// Same rule as the engine key above: an unparseable value keeps the default rather than
|
||||
// failing the load. Settings is where the user would fix it, so it has to open.
|
||||
if let Ok(n) = raw.parse::<usize>() {
|
||||
out.pin_suggest_threshold = n;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -88,6 +104,10 @@ pub fn save(store: &Store, settings: &Settings) -> Result<()> {
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
)?;
|
||||
store.set(
|
||||
KEY_PIN_SUGGEST_THRESHOLD,
|
||||
&settings.pin_suggest_threshold.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -168,6 +188,37 @@ mod tests {
|
||||
assert_eq!(s.engine, EngineId::Pip);
|
||||
assert!(!s.allow_externally_managed, "SECURITY §3: off by default");
|
||||
assert_eq!(s.locale, None, "None means follow the OS");
|
||||
assert_eq!(
|
||||
s.pin_suggest_threshold,
|
||||
crate::graph::PIN_SUGGEST_THRESHOLD,
|
||||
"PRD P1-2's default of 5, from the const rather than a second copy of it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparseable_threshold_falls_back_rather_than_failing() {
|
||||
// Same rule as the engine key: Settings is where a bad value gets fixed, so it must open.
|
||||
let store = store();
|
||||
store
|
||||
.set("settings.pinSuggestThreshold", "lots")
|
||||
.expect("set");
|
||||
assert_eq!(
|
||||
load(&store).expect("load").pin_suggest_threshold,
|
||||
crate::graph::PIN_SUGGEST_THRESHOLD
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_threshold_of_zero_survives_a_round_trip() {
|
||||
// Zero is the "off" setting, so it must not be mistaken for absent and replaced by the
|
||||
// default — which is exactly what a `filter(|n| *n > 0)` in `load` would do.
|
||||
let store = store();
|
||||
let want = Settings {
|
||||
pin_suggest_threshold: 0,
|
||||
..Settings::default()
|
||||
};
|
||||
save(&store, &want).expect("save");
|
||||
assert_eq!(load(&store).expect("load").pin_suggest_threshold, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -177,6 +228,7 @@ mod tests {
|
||||
engine: EngineId::Uv,
|
||||
locale: Some("vi".into()),
|
||||
allow_externally_managed: true,
|
||||
pin_suggest_threshold: 12,
|
||||
};
|
||||
save(&store, &want).expect("save");
|
||||
assert_eq!(load(&store).expect("load"), want);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# pip-audit capture
|
||||
|
||||
SP-4's exit criterion asked for "command line + JSON fixture pinned". The command line was pinned
|
||||
in prose in `spikes/README.md` in Phase 0; **the fixture never was**, and P1-1 needed it.
|
||||
|
||||
Captured 2026-08-18 with the ledger's pinned **pip-audit 2.10.1**, against the spike's own target
|
||||
environment (`spikes/out/target-env`, a Python 3.12 venv holding `urllib3==2.0.0`), by the exact
|
||||
invocation SECURITY §6 and SP-4 settled on:
|
||||
|
||||
```
|
||||
pip-audit -r spikes/out/freeze.txt --no-deps -f json
|
||||
```
|
||||
|
||||
Exit code **1** — findings, not failure.
|
||||
|
||||
Not redacted, and it does not need to be: unlike the pip/uv captures there is no path, no
|
||||
duration, no address and no environment marker in it. The only `://` in the file is inside the
|
||||
advisory prose. `spikes/capture.py` does not produce this, for the same reason it does not produce
|
||||
`health/sample` — reconstructing the seeded environment is the expensive part, not the run.
|
||||
|
||||
## What it pins, and why each matters
|
||||
|
||||
* **`PYSEC-*` ids.** pip-audit's *default* vulnerability service is PyPI, not OSV. That is what
|
||||
lets PipDock keep `legal/PRIVACY-POLICY.md` §3's "exactly one destination" true.
|
||||
* **`aliases` carries the `CVE-*` and `GHSA-*`.** PRD P1-1 says "known CVEs"; the CVE is an alias,
|
||||
never the primary id.
|
||||
* **Duplicate ids.** `PYSEC-2023-192` and `PYSEC-2023-212` each appear **twice**, so the ten rows
|
||||
here are **eight** advisories. The same run under `--vulnerability-service osv` returns sixteen
|
||||
rows and the *same eight* — the set difference is empty in both directions, so the service
|
||||
choice costs no coverage and dedup is load-bearing either way.
|
||||
* **No severity field, under either service.** The keys are exactly `id`, `fix_versions`,
|
||||
`aliases` and `description`; pip-audit's own service model has no severity at all. PRD P1-1's
|
||||
"severity-sorted" and SECURITY §6's "(CVE/GHSA id, severity, fixed-in)" were both written
|
||||
against a field that does not exist, and P1-1 corrects them rather than inventing one.
|
||||
|
||||
`urllib3-2.0.0.stderr.txt` is the companion: pip-audit writes a `pip-compile`/hashes advisory to
|
||||
stderr on **every** run, which must never be read as failure.
|
||||
@@ -0,0 +1 @@
|
||||
{"dependencies": [{"name": "pip", "version": "25.0.1", "vulns": [{"id": "PYSEC-2026-196", "fix_versions": ["26.1.2"], "aliases": ["GHSA-wf93-45jw-7689", "CVE-2026-8643"], "description": "pip would treat console_scripts and gui_scripts as paths instead of file names without sanitizing the resolved absolute path to the installation directory, leading to entry points being installed outside the installation directory."}, {"id": "PYSEC-2026-1795", "fix_versions": ["25.3"], "aliases": ["GHSA-4xh5-x5gv-qwph", "CVE-2025-8869"], "description": "When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a \"fixed\" version for this vulnerability doesn't fix all known vulnerabilities that are remediated by using a Python version that implements PEP 706. Note that this is a vulnerability in pip's fallback implementation of tar extraction for Python versions that don't implement PEP 706 and therefore are not secure to all vulnerabilities in the Python 'tarfile' module. If you're using a Python version that implements PEP 706 then pip doesn't use the \"vulnerable\" fallback code. Mitigations include upgrading to a version of pip that includes the fix, upgrading to a Python version that implements PEP 706 (Python >=3.9.17, >=3.10.12, >=3.11.4, or >=3.12), applying the linked patch, or inspecting source distributions (sdists) before installation as is already a best-practice."}, {"id": "PYSEC-2026-1796", "fix_versions": ["26.0"], "aliases": ["GHSA-6vgw-5pg2-w6jp", "CVE-2026-1703"], "description": "When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation directory, thus isn't able to inject or overwrite executable files in typical situations."}, {"id": "PYSEC-2026-196", "fix_versions": ["26.1.2"], "aliases": ["GHSA-wf93-45jw-7689", "CVE-2026-8643"], "description": "pip would treat console_scripts and gui_scripts as paths instead of file names without sanitizing the resolved absolute path to the installation directory, leading to entry points being installed outside the installation directory."}, {"id": "PYSEC-2026-2875", "fix_versions": ["26.1"], "aliases": ["GHSA-58qw-9mgm-455v", "CVE-2026-3219"], "description": "pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as installing \"incorrect\" files according to the filename of the archive. New behavior only proceeds with installation if the file identifies uniquely as a ZIP or tar archive, not as both."}, {"id": "PYSEC-2026-2876", "fix_versions": ["26.1"], "aliases": ["GHSA-jp4c-xjxw-mgf9", "CVE-2026-6357"], "description": "pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally deferred to increase startup time of the pip CLI. The patch changes self-update functionality to run before wheels are installed to prevent newly-installed modules from being imported shortly after the installation of a wheel package. Users should still review package contents prior to installation."}]}, {"name": "urllib3", "version": "2.0.0", "vulns": [{"id": "PYSEC-2023-192", "fix_versions": ["1.26.17", "2.0.6"], "aliases": ["GHSA-v845-jxx5-vc9f", "CVE-2023-43804"], "description": "urllib3 doesn't treat the `Cookie` HTTP header special or provide any helpers for managing cookies over HTTP, that is the responsibility of the user. However, it is possible for a user to specify a `Cookie` header and unknowingly leak information via HTTP redirects to a different origin if that user doesn't disable redirects explicitly. Users **must** handle redirects themselves instead of relying on urllib3's automatic redirects to achieve safe processing of the `Cookie` header, thus we decided to strip the header by default in order to further protect users who aren't using the correct approach. ## Affected usages We believe the number of usages affected by this advisory is low. It requires all of the following to be true to be exploited: * Using an affected version of urllib3 (patched in v1.26.17 and v2.0.6) * Using the `Cookie` header on requests, which is mostly typical for impersonating a browser. * Not disabling HTTP redirects * Either not using HTTPS or for the origin server to redirect to a malicious origin. ## Remediation * Upgrading to at least urllib3 v1.26.17 or v2.0.6 * Disabling HTTP redirects using `redirects=False` when sending requests. * Not using the `Cookie` header."}, {"id": "PYSEC-2023-192", "fix_versions": ["1.26.17", "2.0.6"], "aliases": ["GHSA-v845-jxx5-vc9f", "CVE-2023-43804"], "description": "urllib3 is a user-friendly HTTP client library for Python. urllib3 dLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"dependencies": [{"name": "urllib3", "version": "2.0.0", "vulns": [{"id": "PYSEC-2023-192", "fix_versions": ["1.26.17", "2.0.6"], "aliases": ["CVE-2023-43804", "GHSA-v845-jxx5-vc9f"], "description": "urllib3 doesn't treat the `Cookie` HTTP header special or provide any helpers for managing cookies over HTTP, that is the responsibility of the user. However, it is possible for a user to specify a `Cookie` header and unknowingly leak information via HTTP redirects to a different origin if that user doesn't disable redirects explicitly. Users **must** handle redirects themselves instead of relying on urllib3's automatic redirects to achieve safe processing of the `Cookie` header, thus we decided to strip the header by default in order to further protect users who aren't using the correct approach. ## Affected usages We believe the number of usages affected by this advisory is low. It requires all of the following to be true to be exploited: * Using an affected version of urllib3 (patched in v1.26.17 and v2.0.6) * Using the `Cookie` header on requests, which is mostly typical for impersonating a browser. * Not disabling HTTP redirects * Either not using HTTPS or for the origin server to redirect to a malicious origin. ## Remediation * Upgrading to at least urllib3 v1.26.17 or v2.0.6 * Disabling HTTP redirects using `redirects=False` when sending requests. * Not using the `Cookie` header."}, {"id": "PYSEC-2023-192", "fix_versions": ["1.26.17", "2.0.6"], "aliases": ["CVE-2023-43804", "GHSA-v845-jxx5-vc9f"], "description": "urllib3 is a user-friendly HTTP client library for Python. urllib3 doesn't treat the `Cookie` HTTP header special or provide any helpers for managing cookies over HTTP, that is the responsibility of the user. However, it is possible for a user to specify a `Cookie` header and unknowingly leak information via HTTP redirects to a different origin if that user doesn't disable redirects explicitly. This issue has been patched in urllib3 version 1.26.17 or 2.0.5."}, {"id": "PYSEC-2023-212", "fix_versions": ["1.26.18", "2.0.7"], "aliases": ["CVE-2023-45803", "GHSA-g4mx-q9vg-27p4"], "description": "urllib3 previously wouldn't remove the HTTP request body when an HTTP redirect response using status 303 \"See Other\" after the request had its method changed from one that could accept a request body (like `POST`) to `GET` as is required by HTTP RFCs. Although the behavior of removing the request body is not specified in the section for redirects, it can be inferred by piecing together information from different sections and we have observed the behavior in other major HTTP client implementations like curl and web browsers. From [RFC 9110 Section 9.3.1](https://www.rfc-editor.org/rfc/rfc9110.html#name-get): > A client SHOULD NOT generate content in a GET request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported. ## Affected usages Because the vulnerability requires a previously trusted service to become compromised in order to have an impact on confidentiality we believe the exploitability of this vulnerability is low. Additionally, many users aren't putting sensitive data in HTTP request bodies, if this is the case then this vulnerability isn't exploitable. Both of the following conditions must be true to be affected by this vulnerability: * If you're using urllib3 and submitting sensitive information in the HTTP request body (such as form data or JSON) * The origin service is compromised and starts redirecting using 303 to a malicious peer or the redirected-to service becomes compromised. ## Remediation You can remediate this vulnerability with any of the following steps: * Upgrade to a patched version of urllib3 (v1.26.18 or v2.0.7) * Disable redirects for services that you aren't expecting to respond with redirects with `redirects=False`. * Disable automatic redirects with `redirects=False` and handle 303 redirects manually by stripping the HTTP request body."}, {"id": "PYSEC-2023-212", "fix_versions": ["1.26.18", "2.0.7"], "aliases": ["CVE-2023-45803", "GHSA-g4mx-q9vg-27p4"], "description": "urllib3 is a user-friendly HTTP client library for Python. urllib3 previously wouldn't remove the HTTP request body when an HTTP redirect response using status 301, 302, or 303 after the request had its method changed from one that could accept a request body (like `POST`) to `GET` as is required by HTTP RFCs. Although this behavior is not specified in the section for redirects, it can be inferred by piecing together information from different sections and we have observed the behavior in other major HTTP client implementations like curl and web browsers. Because the vulnerability requires a previously trusted service to become compromised in order to have an impact on confidentiality we believe the exploitability of this vulnerability is low. Additionally, many users aren't putting seLine truncated
|
||||
@@ -0,0 +1,3 @@
|
||||
WARNING:pip_audit._cli:--no-deps is supported, but users are encouraged to fully hash their pinned dependencies
|
||||
WARNING:pip_audit._cli:Consider using a tool like `pip-compile`: https://pip-tools.readthedocs.io/en/latest/#using-hashes
|
||||
Found 10 known vulnerabilities in 1 package
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
ERROR: Exception:
|
||||
Traceback (most recent call last):
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
@@ -1,3 +1,3 @@
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
@@ -1,3 +1,3 @@
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
@@ -1,5 +1,5 @@
|
||||
ERROR: Cannot install httpcore>=1.0 and httpx==0.23.0 because these package versions have conflicting dependencies.
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
|
||||
@@ -1,5 +1,5 @@
|
||||
ERROR: Could not find a version that satisfies the requirement pipdock-no-such-package-9f3a2b (from versions: none)
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
ERROR: No matching distribution found for pipdock-no-such-package-9f3a2b
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
ERROR: Exception:
|
||||
Traceback (most recent call last):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
ERROR: Ignored the following yanked versions: 1.11.0, 1.14.0rc1
|
||||
ERROR: Could not find a version that satisfies the requirement scipy==1.7.3 (from versions: 0.8.0, 0.9.0, 0.10.0, 0.10.1, 0.11.0, 0.12.0, 0.12.1, 0.13.0, 0.13.1, 0.13.2, 0.13.3, 0.14.0, 0.14.1, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.17.0, 0.17.1, 0.18.0, 0.18.1, 0.19.0, 0.19.1, 1.0.0, 1.0.1, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.4.0, 1.4.1, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.6.0, 1.6.1, 1.9.2, 1.9.3, 1.11.0rc1, 1.11.0rc2, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.12.0rc1, 1.12.0rc2, 1.12.0, 1.13.0rc1, 1.13.0, 1.13.1, 1.14.0rc2, 1.14.0, 1.14.1, 1.15.0rc1, 1.15.0rc2, 1.15.0, 1.15.1, 1.15.2, 1.15.3, 1.16.0rc1, 1.16.0rc2, 1.16.0, 1.16.1, 1.16.2, 1.16.3, 1.17.0rc1, 1.17.0rc2, 1.17.0, 1.17.1, 1.18.0rc1, 1.18.0rc2, 1.18.0)
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
ERROR: No matching distribution found for scipy==1.7.3
|
||||
@@ -1,5 +1,5 @@
|
||||
WARNING: The candidate selected for download or install is a yanked version: 'urllib3' candidate (version 2.0.0 at https://files.pythonhosted.org/packages/ca/25/fe81738a115a2f1005b19bd69b6253b7b5cd6c9119164f13f02ec627fc41/urllib3-2.0.0-py3-none-any.whl (from https://pypi.org/simple/urllib3/) (requires-python:>=3.7))
|
||||
Reason for being yanked: Truncated response bodies when streaming a large compressed body. Upgrade to at least 2.0.2 (See: https://github.com/urllib3/urllib3/issues/3009)
|
||||
|
||||
[notice] A new release of pip is available: 25.0.1 -> 26.1.2
|
||||
[notice] A new release of pip is available: <VERSION> -> <VERSION>
|
||||
[notice] To update, run: <WORK>\venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
@@ -15,4 +15,4 @@ Resolved 1 package in <DURATION>
|
||||
import distutils.core
|
||||
ModuleNotFoundError: No module named 'distutils'
|
||||
|
||||
hint: `distutils` was removed from the standard library in Python 3.12. Consider adding a constraint (like `numpy >1.19.5`) to avoid building a version of `numpy` that depends on `distutils`.
|
||||
hint: `distutils` was removed from the standard library in Python 3.12. Consider adding a constraint (like `numpy >1.19.5`) to avoid building a version of `numpy` that depends on `distutils`.
|
||||
@@ -116,6 +116,8 @@ This table is the surface. A command that is not listed here does not exist; add
|
||||
| `env_scan` | `EnvRow[]` | Discover environments, streaming `scan-progress`. A probe failure is reported on its own row, never fatal to the scan. Carries `pipVersion` and `healthProject`, both read before the probe loop so the store guard is never held across a probe. |
|
||||
| `env_add_manual` | `EnvRow` | Persist an interpreter chosen through *Browse…*. |
|
||||
| `env_probe` | `EnvRow` | Probe one interpreter without persisting it. Takes an optional `source`: absent means *Browse…*, and a **refresh must pass the row's own**, or the row comes back relabelled `manual`. Fills every field `env_scan` does, because `upgradePip` replaces the row wholesale. |
|
||||
| `env_export` | `string` | Write the environment's `Engine::freeze` document to a user-chosen path and return it (PRD P1-3). Byte for byte, with no formatter: a freeze *is* a requirements file, and a constraints file is the same body under a different name. Rust-side for `health_save_report`'s reason — `dialog:allow-save` asks for a path and grants no `fs`. |
|
||||
| `requirements_read` | `ParsedRequirements` | Read a `requirements.txt` into install specs **and whatever it could not use**. The skipped lines are the point: an include or an editable install means the file asks for something PipDock will not do, and the user has to see that before a preview claims to represent their file. |
|
||||
| `pkg_list` | `Dist[]` | Installed distributions, read from `probe.py` rather than the engine — see §4 and DATA-FLOW §7. |
|
||||
| `pkg_outdated` | `OutdatedDist[]` | Outdated distributions, via the configured engine. |
|
||||
| `index_search` | `Hit[]` | Fuzzy search over the in-memory name index. |
|
||||
@@ -130,6 +132,7 @@ This table is the surface. A command that is not listed here does not exist; add
|
||||
| `pin_list` | `Pin[]` | Pins for an environment. |
|
||||
| `pin_add` | `()` | Add or replace a pin. |
|
||||
| `pin_remove` | `bool` | Remove a pin; reports whether one existed. |
|
||||
| `pin_suggestions` | `PinSuggestion[]` | Packages worth pinning, by in-force reverse-dependency count (PRD P1-2). **One probe per call**, which is why UI-SPEC §4 puts this on the Pins screen rather than a sidebar badge — the cost is paid only by someone who opened the tab. |
|
||||
| `snapshot_list` | `SnapshotMeta[]` | Snapshots for an environment, newest first. Takes the `env_hash`, not a `PyEnv`: snapshots outlive the interpreter that made them, and an environment whose Python is gone still has a history worth showing. |
|
||||
| `snapshot_create` | `SnapshotMeta` | Take a snapshot on demand, outside any plan. |
|
||||
| `snapshot_diff` | `Diff` | The environment against a snapshot. Claims no session — browsing a timeline must not start a flow. |
|
||||
@@ -139,10 +142,15 @@ This table is the surface. A command that is not listed here does not exist; add
|
||||
| `health_fix` | `FixReport` | Apply the gated `ruff` fix (P5). **Not `ExecutionSummary`** — there is no plan, no phase and no per-package counts in a fix, and inventing them would be four lies for one operation. Same correction §7 needed for `pip_upgrade`. |
|
||||
| `health_dirty` | `number \| null` | Uncommitted entries in the parked report's project, so the fix confirm can name one. `null` means no repository, no git, or git failed — a courtesy, not a precondition. Asked again inside `health_fix`: this decides what to render, that decides what to allow. |
|
||||
| `health_save_report` | `string[]` | Write a finished report as Markdown **and** JSON beside a user-chosen path, returning both. Rust-side rather than a filesystem capability: `dialog:allow-save` lets the webview ask for a path and nothing more. |
|
||||
| `audit_run` | `AuditReport` | pip-audit over an environment (PRD P1-1). Takes the freeze itself, because pip is invoked with `--all` and uv is not, so the configured engine changes what is audited. Syncs its **own** venv on first use — a `msgpack` wheel gap fails this and leaves Code Health working. pip-audit failing is not an error: it lands in `problems` and the report still returns.
|
||||
| `audit_cancel` | `bool` | Stop a running audit, reporting whether there was one. Exists where `health_run` has no equivalent because an audit is **18-68 s** rather than 1.3 s, dominated by a one-off advisory-database fetch. A cancel is a *state* on the report, never `PD-INT-001`. |
|
||||
| `audit_save_report` | `string[]` | Write a finished audit as Markdown **and** JSON beside a user-chosen path, returning both. `health_save_report`'s shape, for its reasons: `dialog:allow-save` asks for a path and grants no `fs`, and the report comes from the frontend because what the user asked to save is what is on their screen. |
|
||||
| `engine_info` | `EngineInfo[]` | Detected version and availability per engine. Settings shows both, so this returns both. |
|
||||
| `pip_upgrade` | `StepResult` | Upgrade pip itself in the selected environment. **Not `ExecutionSummary`** — there is no plan, no phase and no per-package counts, and inventing them would be four lies for one step. Carries no versions either (`from`/`to` are always absent): the caller re-probes, which it must do anyway to refresh the row. |
|
||||
| `settings_get` | `Settings` | Read stored settings. |
|
||||
| `settings_set` | `Settings` | Persist settings, returning what was actually stored rather than what was sent. |
|
||||
| `cache_usage` | `Usage` | What PipDock has written to its own data directory (PRD P1-4). Never fails as a whole; an unreadable path reports zero bytes. |
|
||||
| `cache_clear` | `number` | Delete one cache target, resolving to the bytes freed. Takes a `Target` **enum, never a path** — `cache::clear` is the only thing that turns one into a directory. `index.db` is deliberately not a target: it holds settings, pins and the consent record as well as the package index, and *clear the cache* must never take a user's pins. |
|
||||
| `legal_consent_get` | `ConsentState` | Whether the legal gate can be skipped for this build's documents. |
|
||||
| `legal_consent_set` | `Consent` | Record acceptance. |
|
||||
| `logs_tail` | `string[]` | Tail of the in-memory log ring buffer, for the console drawer. |
|
||||
|
||||
+19
-1
@@ -3,7 +3,7 @@
|
||||
`docs/CLI-SPEC.md` is the contract: every flag, every exit code, every JSON shape. This is the
|
||||
guide — what you actually type, in the order you would need it.
|
||||
|
||||
Everything here was run against `pipdock 1.0.0` on Windows. Where a number or a code appears, it
|
||||
Everything here was run against `pipdock 1.1.0` on Windows. Where a number or a code appears, it
|
||||
came out of a real invocation, not out of the spec.
|
||||
|
||||
---
|
||||
@@ -335,6 +335,24 @@ pipdock self report-bug
|
||||
|
||||
---
|
||||
|
||||
## What is GUI-only
|
||||
|
||||
1.1.0's four features have **no CLI surface yet**, and that is deliberate rather than an oversight
|
||||
— each would add a subcommand and churn the help goldens for something nothing scripts against
|
||||
today. The logic lives in `pipdock-core` (`pins::suggest`, `requirements::parse`, `cache::usage`),
|
||||
so adding one later is small:
|
||||
|
||||
| Feature | Where it is | Nearest CLI equivalent today |
|
||||
|---|---|---|
|
||||
| Pin suggestions | Pins screen | none — `pin list` shows what you have pinned |
|
||||
| Requirements export | Environments → *Open* | `snapshot create`, then read the `.freeze.txt` |
|
||||
| Requirements import | Environments → *Open* | `install` with the specs, which is what import does anyway |
|
||||
| Disk usage | Settings | `tools status` reports the tools venv; nothing reports sizes |
|
||||
| Command palette | `Ctrl+K` | not applicable |
|
||||
|
||||
If you want one of these on the command line, say so in an
|
||||
[issue](https://github.com/poli0981/pipdock/issues) — the core function is already there.
|
||||
|
||||
## See also
|
||||
|
||||
- [CLI-SPEC.md](CLI-SPEC.md) — the contract: exhaustive flags, JSON shapes, exit codes
|
||||
|
||||
+2
-1
@@ -36,7 +36,8 @@ pipdock update [--all | <pkg...>]
|
||||
pipdock uninstall <pkg...> [--force] # guard names each dependent and its constraint; --force overrides
|
||||
pipdock pin add|remove <pkg> [--reason "…"] | pin list
|
||||
pipdock snapshot list | create | diff <id> | rollback <id|latest>
|
||||
pipdock doctor # engine check + env sanity + (P1) audit summary
|
||||
pipdock doctor # engine check + env sanity
|
||||
pipdock audit # known advisories in the selected environment; exit 1 on findings
|
||||
pipdock health [--path <dir>] [--tool deptry|vulture|ruff] [--fix] # --fix = ruff only, prompts
|
||||
# --yes: proceeds on a clean tree,
|
||||
# REFUSES on a dirty one (exit 2)
|
||||
|
||||
@@ -31,7 +31,7 @@ Bootstrap: on first Health run (or pin-set change), create/sync the venv from `t
|
||||
|
||||
- **pip unconditionally, not "the configured engine".** The venv is created with `python -m venv` and populated with pip whatever the user selected. uv is a preference about the *user's* environments; Health going dark with `PD-ENG-001` because uv is not on PATH would be a failure with no relation to what was asked for, and pip is present wherever Python is.
|
||||
- **No upper Python bound, and no `TOOLS_PYTHON_MAX`.** ROADMAP assumed "deptry ships compiled wheels; no cp314 wheel means an sdist build". deptry does ship a Rust extension but builds it against CPython's **stable ABI** (`deptry-0.25.1-cp310-abi3-win_amd64.whl`), verified installing on 3.12.10 and 3.14.6 from the same file; vulture and ruff are `py3-none-*`. The one version-tagged member of the closure, `tomli`, also publishes a `py3-none-any` fallback. The install passes `--only-binary=:all:`, so a future gap is a clean `PD-NET-011` rather than an sdist build ending at `PD-BLD-001` — which would tell someone who clicked *Health* to install Visual Studio Build Tools.
|
||||
- **The repo's `tools/tools-requirements.txt` is the release-time ledger; the file written into `%LOCALAPPDATA%` is a rendering of it.** The ledger carries a fourth pin, `pip-audit`, for the post-1.0 Security tab (PRD P1-1). Health installs three. Rendering rather than copying is also what keeps the build machine's line endings out of the pin hash, which is taken over the *parsed* pin set for that reason.
|
||||
- **The repo's `tools/tools-requirements.txt` is the release-time ledger; the file written into `%LOCALAPPDATA%` is a rendering of it.** The ledger carries a fourth pin, `pip-audit`, for the Security tab (PRD P1-1). Health installs three, and P1-1 did **not** change that: pip-audit ships in a venv of its own (`health::AUDIT_TOOLS`, `health::audit_dir`) so that its `msgpack` dependency — which publishes no universal wheel — can fail on a new CPython without taking Code Health down with it. `pins_for` renders each set separately, which is what keeps the two pin hashes independent: bumping one tool never re-syncs the other's venv. Rendering rather than copying is also what keeps the build machine's line endings out of the pin hash, which is taken over the *parsed* pin set for that reason.
|
||||
- **A sync rebuilds the venv rather than repairing it, and deletes `manifest.json` first.** `pip install -r` over satisfied pins is a no-op, so repairing a deleted `ruff.exe` installed nothing and then failed verification with `PD-HLT-001` — the state the code tells the user to re-sync out of. Deleting the manifest first means a torn sync reads as "never synced" rather than as a manifest claiming tools that are half-replaced.
|
||||
|
||||
`python -m venv` exiting non-zero is **`PD-HLT-004`**, added in the same slice: `PD-NET-011` is `Area::Net` and would exit 6, so a script retrying on network failure would loop forever against a broken interpreter.
|
||||
|
||||
+5
-5
@@ -60,11 +60,11 @@ PipDock's thesis: **don't reimplement the resolver — explain it.** Wrap pip/uv
|
||||
|
||||
| # | Feature | Notes |
|
||||
|---|---|---|
|
||||
| P1-1 | Security tab | pip-audit (freeze-file mode) listing known CVEs per installed package, severity-sorted. |
|
||||
| P1-2 | Pin auto-suggest | Reverse-dependency count ≥ threshold (default 5, configurable) ⇒ suggest pin with reason. |
|
||||
| P1-3 | Export / import | `requirements.txt` and `constraints.txt` export; import-as-queue. |
|
||||
| P1-4 | Cache manager | Show / purge engine cache (`pip cache`, `uv cache`) and PipDock's index cache. |
|
||||
| P1-5 | Command palette | Ctrl+K fuzzy action launcher (terminal-tech signature feature). |
|
||||
| P1-1 | **Shipped 1.2.0.** Security tab | pip-audit (freeze-file mode) listing known advisories per installed package. **Not severity-sorted, because pip-audit has no severity field** — under either vulnerability service its findings carry only `id`, `fix_versions`, `aliases` and `description`, verified against the pinned 2.10.1. Ordered by package, then by whether anything *fixes* it, then by id: the one distinction that changes what the user can do. The CVE is an **alias**; the primary id is a `PYSEC-*`. |
|
||||
| P1-2 | Pin auto-suggest | **Shipped post-1.0 (P1-A).** Reverse-dependency count ≥ threshold (default 5, configurable in Settings; zero is off) ⇒ suggest pin with reason. Counts in-force edges only — extras and other-Python markers do not qualify a package. |
|
||||
| P1-3 | **Shipped 1.1.0.** Export / import | `requirements.txt` and `constraints.txt` export; import-as-queue. |
|
||||
| P1-4 | **Partly shipped, 1.1.0.** Cache manager | Shows and clears **PipDock's own** disk usage: snapshots and the Code Health tools venv. `index.db` is reported but not clearable — it holds settings, pins and the consent record in the same file, so "clear the cache" must never take them. **The engine caches (`pip cache`, `uv cache`) are not covered** and are a separate item: they belong to the engine, live outside `%LOCALAPPDATA%\PipDock\`, and purging them is a subprocess rather than a file delete. |
|
||||
| P1-5 | **Shipped 1.1.0.** Command palette | Ctrl+K fuzzy action launcher (terminal-tech signature feature). |
|
||||
| P1-6 | Dependency graph view | Visual "who holds this back" graph for a selected package. |
|
||||
| P1-7 | Scheduled check | Optional background outdated-check with toast (no auto-apply, ever). |
|
||||
|
||||
|
||||
+291
-13
@@ -740,7 +740,7 @@ Three things it settled that outlive it:
|
||||
|
||||
## Post-1.0 (P1 wave)
|
||||
|
||||
Security tab (pip-audit), pin auto-suggest, requirements/constraints export-import, cache manager, command palette, dependency graph view, scheduled check. Then P2 candidates by demand: macOS/Linux, per-env engine, elevation broker, winget, JP locale.
|
||||
Security tab (pip-audit), pin auto-suggest, requirements/constraints export-import, cache manager, command palette, dependency graph view, scheduled check. **Five of the seven have shipped** — four in 1.1.0 and the Security tab in 1.2.0; the graph view and the scheduled check remain. Then P2 candidates by demand: macOS/Linux, per-env engine, elevation broker, winget, JP locale.
|
||||
|
||||
**About shipped early, in Phase 4** — see above. Two smaller items were added to this wave rather
|
||||
than done at 1.0:
|
||||
@@ -751,12 +751,217 @@ than done at 1.0:
|
||||
actually done — a hand-maintained inventory of the *direct* dependencies, reconciled against the
|
||||
manifests at each release. Making it true is the item. Doing it at 1.0 would have meant
|
||||
complicating `release.yml` on the first run it had ever had.
|
||||
- **Re-capture the screenshots** once anything visible changes; the seven in `screenshot/` show an
|
||||
eight-entry sidebar.
|
||||
- **Re-capture the screenshots** once anything visible changes. `screenshot/` holds **eight**;
|
||||
seven of them predate the About tab and show an **eight**-entry sidebar, while `about.png` shows
|
||||
nine and a *This build* panel reading `1.0.0`. So every one of them is now stale in at least one
|
||||
way, and the count is worth stating because the sentence here used to read as though there were
|
||||
seven files.
|
||||
|
||||
Also worth doing when the Security tab lands: `capabilities/external-links.json` will need an OSV
|
||||
host, because DISCLAIMER §4 and SECURITY §6 both say findings link to the OSV entry and the current
|
||||
allowlist would reject it — silently, which is the failure mode SECURITY §4 exists to name.
|
||||
~~Also worth doing when the Security tab lands: an OSV host in
|
||||
`capabilities/external-links.json`.~~ **Done in P1-1**, along with the prose §4 requires — and the
|
||||
entry records what makes it different from `docs.astral.sh`: `advisory_url` *builds* the URL from a
|
||||
validated id, so the tool chooses the id and never the destination.
|
||||
|
||||
### The P1 wave, closed — 1.1.0, 2026-08-14
|
||||
|
||||
All four items shipped, in one afternoon after 1.0.0. **The estimate's central claim held for
|
||||
three of them and was wrong about the fourth in a useful direction:** P1-A was mostly already
|
||||
written, P1-B's export needed no code at all, P1-D touched no Rust — and P1-C turned out to have a
|
||||
scope error rather than an effort error.
|
||||
|
||||
| Slice | What it cost |
|
||||
|---|---|
|
||||
| **P1-A** pin auto-suggest | 6 commits. `dependent_count` finally has a caller. |
|
||||
| **P1-B** requirements | 1 commit. Export is `Engine::freeze` and a path; import is a parser. |
|
||||
| **P1-C** cache manager | 1 commit. Three artefacts, not four, and the first delete-a-tree. |
|
||||
| **P1-D** command palette | 1 commit. Frontend only, exactly as estimated. |
|
||||
|
||||
**Four things running it said that reading could not.**
|
||||
|
||||
1. **94 suggestions** on a 352-package environment at the default threshold — a quarter of the
|
||||
install list. Fixed by bounding the view, not by raising the default: a deep tree is where a
|
||||
bulk update is most dangerous.
|
||||
2. **`graph::Requirement::parse` accepts prose.** It splits the name at the first space, so
|
||||
`this is not a requirement` parses as package `this` with constraint `is not a requirement` —
|
||||
correct for `Requires-Dist`, which never looks like that, and a spec containing spaces heading
|
||||
for argv when the input is a file a person typed. P1-B shape-checks the constraint, which is
|
||||
the obligation SECURITY §2 already places on every other user-supplied version.
|
||||
3. **There are no log files.** `LOG_RETENTION_DAYS` has never had a reader. P1-C reports three
|
||||
artefacts; a "logs — 0 B" row would have invented one.
|
||||
4. **The palette's first ranking put an action above the screen it belongs to.** Matching one flat
|
||||
`"${group} ${label}"` string ranked *Download the index* above the Search tab. Label matches now
|
||||
outrank group matches by a margin wider than any tier.
|
||||
|
||||
**Two corrections to the process, both from P1-A and both now in the checklist below.** Adding a
|
||||
command touches **six** places, not five — `golden.rs` keeps its own copy of `SCHEMA_TYPES`. And
|
||||
a generated type must be added to the `import type` list in `ui/src/ipc/index.ts`; `export type *`
|
||||
does not bring it into scope for a wrapper's own signature.
|
||||
|
||||
**What P1 did not do.** No `pipdock pin suggest`, no CLI surface for export/import or the cache —
|
||||
all four are GUI-only, and `pins::suggest`, `requirements::parse` and `cache::usage` are in core
|
||||
precisely so a subcommand is later trivial. No dismissal for a rejected pin suggestion. `index.db`
|
||||
is not a clearable target and will not become one while it holds settings, pins and the consent
|
||||
record in the same file.
|
||||
|
||||
**Still open from the original P1 list:** the Security tab (pip-audit), the dependency-graph view,
|
||||
the scheduled check — and the half of P1-4 this did not do. PRD P1-4 also asked for the *engine*
|
||||
caches (`pip cache`, `uv cache`); those belong to the engine, live outside
|
||||
`%LOCALAPPDATA%\PipDock\`, and purging them is a subprocess rather than a file delete, so they are
|
||||
a different feature wearing the same word. The PRD row now says so rather than reading as done. The Security tab remains the one that needs an OSV host added to
|
||||
`capabilities/external-links.json` — DISCLAIMER §4 and SECURITY §6 both say findings link there,
|
||||
and the allowlist would reject it silently.
|
||||
|
||||
### Slice 0 — preflight before the Security tab — **done 2026-08-18**
|
||||
|
||||
Three commits. Nothing here is a feature; all three are things `main` was already carrying, found
|
||||
while surveying what is left of Post-1.0 (P1-1 Security tab, P1-6 dependency graph, P1-7 scheduled
|
||||
check). Two of the three had to happen before a 39th command could land anyway.
|
||||
|
||||
| | What landed |
|
||||
|---|---|
|
||||
| **Fixtures** | `redact()` covers pip's `[notice] A new release of pip is available:` version pair; nine pip fixtures re-blessed; one byte re-blessed in uv's `build-backend-failure` |
|
||||
| **Core + UI** | `plan::Blocker` becomes `by` / `version` / bare requirement; `run.rs` gains `blocker_line`; `PdConflictRow` composes; `fixtures::numpy_blockers` is **computed**; `PdConflictRow.test.tsx` is new |
|
||||
| **Docs** | ARCHITECTURE §7's five missing rows, a fourth drift test that reads the table, two stale counts |
|
||||
|
||||
**The drift gate could not have stayed green.** pip's upgrade notice states the version that is on
|
||||
PyPI *today*, so it moves with every pip release — and `redact()` stripped the disposable venv path
|
||||
out of the line *below* it while leaving this one alone. pip 26.2.1 shipped on 2026-08-17 and the
|
||||
weekly re-capture failed across all nine pip fixtures carrying the line. The same shape as the five
|
||||
faults in *L2's first runs*: a gate that fires for a reason unrelated to engine behaviour means
|
||||
nothing, and this one was going to fire every Monday.
|
||||
|
||||
**The preview named the dependent twice, and had since S3.** It rendered `scipy requires scipy
|
||||
1.11.4 requires numpy <1.28.0,>=1.21.6`, because `graph::blockers_for` built an English sentence
|
||||
into `Blocker.constraint` while also setting `by`, and `PdConflictRow` passed both to
|
||||
`plan.blocker`, whose template is `{{by}} requires {{constraint}}`. Hard invariant 4 the wrong way
|
||||
round — and the reason it was written that way is instructive: the **CLI** prints that field alone,
|
||||
so the one head it looked right in was the one with no catalog. Each head composes now, exactly as
|
||||
`BrokenDependent` and `PdUninstallDialog` already did.
|
||||
|
||||
**Why every suite was green, which is the part worth keeping.** `PdPreviewDiff.test.tsx` *did*
|
||||
assert this sentence, and asserted the **correct** one — because the fixture's blockers were
|
||||
hand-written to the shape `Blocker`'s own doc describes, while the producer had drifted away from
|
||||
it. `fixtures.rs` says in its own module doc that hand-writing the JSON "would defeat the
|
||||
guarantee", and `guard_report()` is computed for precisely that reason; the plan fixture's blockers
|
||||
were the single exception, and the bug lived in it. They are computed now — which is also why there
|
||||
are two of them: `pandas 2.1.4` and `scipy 1.11.4` both exclude 2.5.1, and only one had ever been
|
||||
written down. **A hand-written fixture that agrees with the documentation while the code disagrees
|
||||
with both is worse than no fixture**: it makes a test that asserts the right thing prove the wrong
|
||||
one.
|
||||
|
||||
**Three process notes.**
|
||||
|
||||
1. **`sed -i` under Git Bash rewrites in text mode and strips CR.** It flattened every CRLF in ten
|
||||
engine fixtures in one command — exactly the byte-exactness `.gitattributes`' `-text` exists to
|
||||
protect, and `git diff --stat` reported 160 changed lines where one was intended. Anything
|
||||
touching `tests/fixtures/**/*.txt` has to go through a binary-mode read/write, asserting the
|
||||
CRLF count per file.
|
||||
2. **ARCHITECTURE §7 now has a test.** Its opening sentence has claimed since M2 that a command not
|
||||
in the table does not exist; the three drift tests never read it, and `every_registered_command_
|
||||
is_declared`'s failure message claimed §7 coverage it did not have. *A spec sentence is not a
|
||||
test* — the fourth time this exact lesson has been recorded here, and the first time on a
|
||||
sentence about the document itself.
|
||||
3. **A count was called stale that was not.** ROADMAP's screenshot note says "the seven in
|
||||
`screenshot/` show an eight-entry sidebar". `screenshot/` holds eight files, so a reader counting
|
||||
files concludes the sentence is wrong. Opening two of the images settles it: seven predate the
|
||||
About tab and do show eight entries, and `about.png` shows nine. Reworded rather than
|
||||
"corrected", because correcting it would have introduced the error.
|
||||
|
||||
### Post-1.0 · P1-1 — the Security tab — **done 2026-08-18**
|
||||
|
||||
Eight commits, and **1.2.0**. The last major P1 item; PRD P1-1 has been on the list since the PRD
|
||||
was written and had a spike behind it from Phase 0.
|
||||
|
||||
| | What landed |
|
||||
|---|---|
|
||||
| **Core** | `health::pins_for`/`sync_steps`/`needs_sync`/`sync_tools_venv` take a tool list; `AUDIT_TOOLS`, `audit_dir`; the whole `audit` module — `Advisory`, `AuditReport`, `parse`, `dedupe`, `sort_advisories`, `advisory_url`, `run`, `markdown`; `cache::Target::Audit` |
|
||||
| **Bridge** | `audit_run`, `audit_cancel`, `audit_save_report`; `AppState.audit` as `Sessions<()>`; the `audit-progress` channel |
|
||||
| **CLI** | `pipdock audit`, exit 1 on findings |
|
||||
| **UI** | `PdSecurity`, `PdAuditReport`, `useSecurityStore` — and `PdSidebar`'s `NOT_YET` is **empty** for the first time |
|
||||
| **Fixtures** | the pip-audit capture SP-4 asked for in Phase 0 and never got, plus a **computed** `audit_report.json` |
|
||||
| **Docs & legal** | PRD P1-1, SECURITY §4/§6, UI-SPEC §4/§5/§6, CLI-SPEC §3, CODE-HEALTH-SPEC §2, `capabilities/external-links.json`, and three `legal/` documents |
|
||||
|
||||
**Three decisions the owner closed before any code**, each of which would have been expensive to
|
||||
reverse:
|
||||
|
||||
1. **pip-audit gets its own venv.** `HEALTH_TOOLS` gave two reasons for excluding it and only one
|
||||
survives the tab existing — "a feature they cannot reach" stops being true, but `msgpack` still
|
||||
publishes no universal wheel, and `--only-binary=:all:` is load-bearing. A fourth entry in
|
||||
Code Health's venv would let a new CPython take Code Health down with the Security tab.
|
||||
2. **The default PyPI vulnerability service, linking out to OSV.** This is what keeps
|
||||
`legal/PRIVACY-POLICY.md` §3's "exactly one destination" **true**, and measuring showed it costs
|
||||
nothing: the same environment under `--vulnerability-service osv` returns the *same eight*
|
||||
advisories, set difference empty in both directions. The 10-vs-16 row difference is pure
|
||||
duplication.
|
||||
3. **The specs get corrected rather than the tool worked around** — see below.
|
||||
|
||||
**Two spec claims were not stale but unimplementable.** SECURITY §6 said pip-audit "runs from the
|
||||
tools venv"; the code had refused that since P2 with three tests enforcing the refusal. And §6 and
|
||||
PRD P1-1 both promised a **severity** — "(CVE/GHSA id, severity, fixed-in)", "severity-sorted" —
|
||||
against a field pip-audit has never had under *either* service. A finding carries `id`,
|
||||
`fix_versions`, `aliases` and `description`, full stop. The order that shipped is package →
|
||||
fixable → id, which is the one distinction that changes what a user can do; a severity derived
|
||||
from the id's year or the prose would be a number PipDock invented, shown beside real ones.
|
||||
|
||||
**SP-4's exit criterion is finally met.** It asked for "command line + JSON fixture pinned" in
|
||||
Phase 0. The command line was pinned in prose; the fixture never was, so every claim about
|
||||
pip-audit's output had gone unchecked for a year of development. Both are committed now, with
|
||||
provenance.
|
||||
|
||||
**Four things found by running, none of them visible in a diff.**
|
||||
|
||||
1. **The watchdog was a linter's.** Written against Code Health's 120 s `TOOL_TIMEOUT`, the first
|
||||
real run hit it and reported `PD-HLT-003` for a tool that was working. Measured afterwards:
|
||||
**68 s cold** for one package, 18.6 s warm for one, **20.0 s warm for twelve**. Twelve cost
|
||||
1.4 s more than one, so the cost is a one-off advisory-database fetch and a 352-package
|
||||
environment is not the risk — a cold fetch on a slow link is. `AUDIT_TIMEOUT` is 600 s,
|
||||
matching `exec::DEFAULT_TIMEOUT`.
|
||||
2. **That number reopened cancellation.** P4 deferred it for Code Health on a measurement of
|
||||
**1.3 s**; 18-68 s is a different answer to the same question. Wired *and* mapped, because P4
|
||||
also recorded that wiring the token alone renders a cancel as "PipDock hit an internal error" —
|
||||
`exec` reports a cancel and a crash through the same `IntUnexpected`. `AuditReport.cancelled` is
|
||||
a state, the step ends `Skipped`, and nothing lands in `problems`.
|
||||
3. **The screen lied while running.** Mid-run the body read *"No audit has run for this
|
||||
environment"* — while an audit was running. The report is cleared before the command, so `shown`
|
||||
is legitimately null during a run and the un-run empty state rendered on that basis. That is
|
||||
P4's "no issues found before anything had run" **inverted**: a true-looking sentence derived
|
||||
from a state the screen had not loaded. Found by clicking Run against a deliberately slow
|
||||
bridge; no test saw it, because every other test renders this screen settled.
|
||||
4. **`total_bytes` under-reported by a whole venv.** Adding `Target::Audit` gave `Usage` a fourth
|
||||
entry and the sum still added three — with every existing cache test passing. A wrong total with
|
||||
nothing to say so is worse than a missing row, so the guard now asserts on distinct powers of
|
||||
two: a missing term shows up as its own bit rather than as a plausible number.
|
||||
|
||||
**The engine changes what is audited, and the tab does not hide it.** `Engine::freeze` passes
|
||||
`--all` on pip and uv has no such flag, so auditing the SP-4 environment reports **five advisories
|
||||
in pip 25.0.1 itself** alongside urllib3's eight. A uv-engine audit of the same environment sees
|
||||
fewer packages.
|
||||
|
||||
**Verified by running, at every level.** `pipdock audit` cold against a real vulnerable environment
|
||||
with an isolated `LOCALAPPDATA`: the audit venv bootstrapped, wrote its manifest, reported 13
|
||||
advisories across 2 packages, `--json` emitted one camelCase document, exit **1**. The second run
|
||||
did no bootstrap, which is `needs_sync` returning `Fresh` for `AUDIT_TOOLS`. The runner and the
|
||||
cancel path were each run against the real tool (`--ignored`, `PIPDOCK_AUDIT_DIR`) and each
|
||||
mutation-checked. The screen was driven in the browser against a stubbed bridge: `audit_run`
|
||||
crosses **once**, all three listens precede it, both package groups render, and Cancel reaches
|
||||
`audit_cancel`.
|
||||
|
||||
**The legal gate re-shows once** for every existing user. `legal/EULA.md`,
|
||||
`THIRD-PARTY-NOTICES.md` and `DISCLAIMER.md` all described pip-audit as planned-and-not-invoked,
|
||||
and all three are in `build.rs`'s `DOCUMENTS`. That is the mechanism working, and it was decided
|
||||
before the work rather than discovered after it.
|
||||
|
||||
**Still owner-verifiable only**, because the stubbed bridge cannot reach them: the save dialog, and
|
||||
clicking an OSV link to confirm the widened allowlist actually opens — which is the one failure
|
||||
mode that is *silent*, and the reason SECURITY §4 requires the widening in prose.
|
||||
|
||||
**Deliberately not done:** no `pipdock audit --fix`, and no auto-upgrade from a finding. SECURITY §6
|
||||
has always said audit never applies anything; "update to fixed version" is the ordinary Update flow,
|
||||
reached by the user.
|
||||
|
||||
**What is left of Post-1.0 is two items**: the dependency-graph view (PRD P1-6) and the scheduled
|
||||
check (PRD P1-7). Both were surveyed on 2026-08-18 and neither is close to P1-1's readiness — see
|
||||
the analysis above for what blocks each.
|
||||
|
||||
### Four items decomposed, easiest first
|
||||
|
||||
@@ -769,7 +974,74 @@ estimating; the interesting work is rarely where it looks.
|
||||
|
||||
---
|
||||
|
||||
#### P1-A · Pin auto-suggest — PRD P1-2, UI-SPEC §4
|
||||
#### P1-A · Pin auto-suggest — PRD P1-2, UI-SPEC §4 — **done 2026-08-14**
|
||||
|
||||
Five commits. The estimate below held: **most of it was already written and had never been
|
||||
called.**
|
||||
|
||||
| | What landed |
|
||||
|---|---|
|
||||
| **Core** | `pins::suggest` — the first caller `graph::dependent_count` has ever had. `PinSuggestion { pkg, dependents }`. `Settings.pin_suggest_threshold`, defaulting to `graph::PIN_SUGGEST_THRESHOLD` rather than a second literal. |
|
||||
| **Bridge** | `pin_suggestions(env)` — store read, guard dropped, then probe. `NOT_YET` unchanged at two. |
|
||||
| **UI** | The suggestion section on Pins, above the list; `useEnvStore.suggestions` keyed on its own `suggestionsFor`; the app's first `type="number"` in Settings. |
|
||||
| **Docs** | UI-SPEC §4 (the section, and the Settings threshold), PRD P1-2 marked shipped. |
|
||||
|
||||
**The one thing only a real environment could say: 94 suggestions.**
|
||||
|
||||
Against `C:\Python314` — 352 packages, the scale fixture — the default threshold of 5 qualifies
|
||||
**94 packages**, a quarter of the environment. The top of the list is right (`setuptools` at 150
|
||||
dependents, then `zope` at 93, `zope-interface` at 86) but a "Worth pinning" section with 94 rows
|
||||
is not a suggestion, it is a second package list.
|
||||
|
||||
Raising the default was the wrong fix: a deep dependency tree is exactly where a bulk update is
|
||||
most dangerous, so it is exactly where the feature has to work. The screen shows the top
|
||||
`SUGGESTIONS_SHOWN = 8` and says how many more qualify — the `RUFF_ROWS_SHOWN` pattern, and for
|
||||
the same reason: the count comes from the **full** list, so a capped view never misreports a total.
|
||||
`pins::suggest` still returns everything at or above the threshold, which is what makes it
|
||||
composable.
|
||||
|
||||
Measured while there, in `--release`: the probe is **605 ms** and the graph build plus the whole
|
||||
suggest pass is **1 ms**. The plan's worry that `dependent_count` looping over 350 packages would
|
||||
be O(n·m) enough to matter was unfounded — the subprocess dominates completely, and there is no
|
||||
case for a batched counts method.
|
||||
|
||||
**Three things the plan had wrong, all found by doing it.**
|
||||
|
||||
1. **A six-place checklist, not five.** `crates/pipdock-cli/tests/golden.rs` keeps its *own* copy of
|
||||
`SCHEMA_TYPES`, and `schema_lists_exactly_the_documented_types` reads the real list back out of
|
||||
the binary to compare — so the copy cannot silently fall behind. It failed exactly as designed
|
||||
and is now in the checklist below.
|
||||
2. **The `/hold/i` trap.** `PdPins.test.tsx` asserts `queryByText(/hold/i)` is absent, to prove the
|
||||
screen offers no way to create a `Hold` pin — and **"threshold" matches that pattern.** Any
|
||||
copy on this screen containing the substring "hold" breaks a test whose subject is something
|
||||
else entirely. The Settings label is worded "Suggest pinning at" for that reason.
|
||||
3. **`ReverseDeps::build`'s doc contradicted `dependent_count`.** It said the guard ignores
|
||||
extra-gated edges "while pin auto-suggest may still count them" — describing an intent nothing
|
||||
implemented, since `dependent_count` delegates to `dependents_of` and always filtered. Settled
|
||||
in favour of what shipped, and the comment now says why: two features disagreeing about one
|
||||
edge rule is exactly the failure that argues for computing this in Rust rather than looping over
|
||||
`requiresDist` in the frontend, which already holds it.
|
||||
|
||||
**Exit criteria, driven in the browser against a stubbed bridge.** The section renders with
|
||||
UI-SPEC §4's sentence and pluralises at 1 and at 12 in both locales; accepting moves the package
|
||||
into the pin list with `12 packages depended on it` already in its reason field, and it does not
|
||||
reappear; `pin_suggestions` crosses the bridge **once** per visit, not twice. The threshold field
|
||||
refuses `abc`, `-1` and `9999` without a write and accepts `3` with exactly one.
|
||||
|
||||
Two mutation checks rather than trusting green: swapping `build_for` for `build` fails the marker
|
||||
case, and `>=` for `>` fails the inclusive-threshold case.
|
||||
|
||||
**Known rough edge, deliberately not fixed:** nothing records a *rejected* suggestion, so unpinning
|
||||
a package re-offers it. A dismissal needs persistence, and both the suggestion and the pin are on
|
||||
the same screen, so it is visible rather than mysterious.
|
||||
|
||||
**Deliberately not done:** no `pipdock pin suggest`. `pins::suggest` is in core so the subcommand
|
||||
is trivial later, but adding one now means a new help golden plus a churned `golden__help-pin.snap`
|
||||
for an advisory feature nothing scripts against yet.
|
||||
|
||||
---
|
||||
|
||||
##### The original estimate, kept for comparison
|
||||
|
||||
**Most of this was built in M2 and never called.** `graph::dependent_count(&pkg) -> usize`
|
||||
(`graph/mod.rs:242`) exists, is documented *"for pin auto-suggest (PRD P1-2)"*, and has no caller
|
||||
@@ -798,7 +1070,7 @@ method that may not be needed.
|
||||
|
||||
---
|
||||
|
||||
#### P1-B · Requirements / constraints export–import — PRD P1-3
|
||||
#### P1-B · Requirements / constraints export–import — PRD P1-3 — **done 2026-08-14**
|
||||
|
||||
**A snapshot's freeze document already *is* a `requirements.txt`** — verbatim `pip freeze --all` /
|
||||
`uv pip freeze` from `Engine::freeze` (`engine/mod.rs:245`). Export is therefore mostly file I/O,
|
||||
@@ -837,7 +1109,7 @@ covers it.
|
||||
|
||||
---
|
||||
|
||||
#### P1-C · Cache manager — PRD P1-4
|
||||
#### P1-C · Cache manager — PRD P1-4 — **done 2026-08-14**
|
||||
|
||||
**Scope it honestly first: there are no log files.** `LOG_RETENTION_DAYS` (`lib.rs:70`) has no
|
||||
reader anywhere. The only "log" that exists is the in-memory ring buffer at `state.rs:373`, and
|
||||
@@ -868,7 +1140,7 @@ sync state and would gain sizes for free.
|
||||
|
||||
---
|
||||
|
||||
#### P1-D · Command palette, `Ctrl+K` — PRD P1-5, UI-SPEC §1
|
||||
#### P1-D · Command palette, `Ctrl+K` — PRD P1-5, UI-SPEC §1 — **done 2026-08-14**
|
||||
|
||||
Frontend only. No new IPC command, no new Rust, no capability change — **every dispatch target
|
||||
already exists** as a store action.
|
||||
@@ -909,10 +1181,16 @@ first four and fail at `cargo test`:
|
||||
2. `src-tauri/src/commands.rs` — the `#[tauri::command]`, with a `# Errors` section naming its
|
||||
catalog codes. **Never hold the store guard across an `await`.**
|
||||
3. `src-tauri/src/lib.rs` — `generate_handler![…]`.
|
||||
4. `ui/src/ipc/index.ts` — the name in `COMMANDS` **and** a hand-written typed wrapper.
|
||||
4. `ui/src/ipc/index.ts` — the name in `COMMANDS` **and** a hand-written typed wrapper. A generated
|
||||
type also needs adding to the `import type { … } from './generated'` list; `export type *` does
|
||||
not bring it into scope for the wrapper's own signature.
|
||||
5. New wire type → `serde` + `schemars::JsonSchema` + `rename_all = "camelCase"`, register in
|
||||
`SCHEMA_TYPES`, `cargo run -p xtask -- bindings`, and bless a new `golden__schema-<T>.snap`
|
||||
plus every schema that embeds it.
|
||||
**both** `schema_for!` and `SCHEMA_TYPES`, `cargo run -p xtask -- bindings`, and bless a new
|
||||
`golden__schema-<T>.snap` plus every schema that embeds it.
|
||||
**And `crates/pipdock-cli/tests/golden.rs`'s own copy of `SCHEMA_TYPES`** — a deliberate second
|
||||
list, guarded by `schema_lists_exactly_the_documented_types`, which reads the real one back out
|
||||
of the binary. Blessing `golden__schema-unknown-type.snap` is expected here: its error message
|
||||
enumerates every known type, so one more schema is a real behaviour change.
|
||||
6. New error code → nine places; CLAUDE.md enumerates them.
|
||||
7. New event channel → `EVENTS` plus a `listen<T>` wrapper.
|
||||
8. `ui/src/test/ipc.ts` — the mock.
|
||||
|
||||
+8
-2
@@ -30,7 +30,7 @@ Environments carrying an `EXTERNALLY-MANAGED` marker are **blocked by default**
|
||||
|
||||
`pypi.org` is the **only** host PipDock itself connects to. It does not update itself (§5), so it has no reason to reach `github.com` — the legal gate and the bug-report deep link hand a URL to the user's browser rather than fetching anything. The webview cannot reach either: `connect-src` in `tauri.conf.json` allows only `'self'` and the IPC origin, so all network access goes through Rust.
|
||||
|
||||
**Three hosts may be handed to the browser, and the allowlist is the record of why.** `capabilities/external-links.json` scopes `opener:allow-open-url` to `https://github.com/*`; to `https://docs.astral.sh/*` since Phase 3 · P4 — every ruff finding carries its own rule page and CODE-HEALTH-SPEC §6 as amended requires using ruff's `url` rather than constructing one; and to `https://poli0981.dev/*` since Phase 4, for the one page the About tab links to that lists every other way to reach the author. None is a connection PipDock makes; all three are URLs it asks the OS to open. The widening is recorded here rather than only in `capabilities/` because an allowlist entry is a change to this document's subject matter, not a config detail — and because the failure mode of *not* widening it is silent: the promise rejects, nothing opens, and nothing anywhere says so.
|
||||
**Three hosts may be handed to the browser, and the allowlist is the record of why.** `capabilities/external-links.json` scopes `opener:allow-open-url` to `https://github.com/*`; to `https://docs.astral.sh/*` since Phase 3 · P4 — every ruff finding carries its own rule page and CODE-HEALTH-SPEC §6 as amended requires using ruff's `url` rather than constructing one; and to `https://osv.dev/*` since P1-1, where every advisory links to its entry and the alternative was a promise that rejects in silence; and to `https://poli0981.dev/*` since Phase 4, for the one page the About tab links to that lists every other way to reach the author. None is a connection PipDock makes; all three are URLs it asks the OS to open. The widening is recorded here rather than only in `capabilities/` because an allowlist entry is a change to this document's subject matter, not a config detail — and because the failure mode of *not* widening it is silent: the promise rejects, nothing opens, and nothing anywhere says so.
|
||||
|
||||
**What the scope actually defends is narrower than it looks.** Most call sites pass module constants no injected string can reach. Two pass data: `PdErrorRow` hands over a URL built in Rust, and `PdHealthReport` hands over `finding.url` — which comes out of **ruff's own JSON** over the user's source tree, and is the only URL in the application derived from a third-party tool's output. `https://docs.astral.sh/*` is precisely what stops that being anything else. That is also why the contact addresses in About are copied to the clipboard rather than opened: a `mailto:` entry would widen the allowlist by a whole URL *scheme*, and re-open a target class for that one call site, to save a paste.
|
||||
|
||||
@@ -48,7 +48,13 @@ Consequences worth knowing: there is no signing keypair to generate or rotate, n
|
||||
|
||||
## 6. Auditing user environments (P1 Security tab)
|
||||
|
||||
pip-audit runs **from the tools venv** in freeze-file mode: snapshot-freeze the target env → `pip-audit -r <freeze> --no-deps --format json` → findings joined to installed rows (CVE/GHSA id, severity, fixed-in). Exact flags validated in spike SP-4 (pip-audit's foreign-env options evolve). Findings link to the OSV entry; "update to fixed version" hands off to the normal Update flow — audit never auto-applies anything.
|
||||
pip-audit runs **from a venv of its own** in freeze-file mode: `Engine::freeze` the target env → `pip-audit -r <freeze> --no-deps -f json` → findings joined to installed rows. Flags validated in SP-4 and pinned by a committed capture (`tests/fixtures/audit/`).
|
||||
|
||||
**Its own venv, not Code Health's**, and that is a correction rather than a detail. This section said "the tools venv" from the day it was written; the code has refused that since P2, because `pip-audit`'s closure contains `msgpack`, which publishes no universal wheel and would hard-fail the whole sync under `--only-binary=:all:` on a new CPython — taking Code Health down with a feature it does not use. `health::AUDIT_TOOLS` and `health::audit_dir` keep the blast radius inside the Security tab.
|
||||
|
||||
**No severity, because pip-audit has none.** This section promised "(CVE/GHSA id, severity, fixed-in)" against a field that does not exist under either vulnerability service; a finding carries `id`, `fix_versions`, `aliases` and `description` and nothing else. Findings are ordered by package, then by whether anything fixes them, then by id. A severity derived from the id's year or the prose would be a number PipDock invented, shown beside real ones.
|
||||
|
||||
**The network surface does not change.** pip-audit's *default* service is PyPI, and it is left there deliberately: §4's table still has one row. Findings **link** to the OSV entry, which is a visit the user's browser makes after a click, and the URL is **built from a validated id** rather than taken from the tool's output. "Update to fixed version" hands off to the normal Update flow — audit never auto-applies anything.
|
||||
|
||||
## 7. Supply chain of PipDock itself
|
||||
|
||||
|
||||
+38
-19
@@ -4,34 +4,53 @@
|
||||
|
||||
## 1. What must never regress
|
||||
|
||||
1. Adapter parsing of pip/uv output (the product stands on it).
|
||||
2. The data-flow invariants (DATA-FLOW §9): no mutation without accepted plan + snapshot.
|
||||
3. Conflict presentation: held-back attribution sentences must match fixture ground truth.
|
||||
4. Skip-and-continue semantics and summary counts.
|
||||
5. Reverse-dependency guard correctness — including that it is *enforced*, not merely reported: a removal the user never accepted must be refused (`GuardAck`, PD-RES-004), and widening a removal must re-run the guard rather than proceed.
|
||||
1. Adapter parsing of pip/uv output (the product stands on it).
|
||||
2. The data-flow invariants (DATA-FLOW §9): no mutation without accepted plan + snapshot.
|
||||
3. Conflict presentation: held-back attribution sentences must match fixture ground truth.
|
||||
4. Skip-and-continue semantics and summary counts.
|
||||
5. Reverse-dependency guard correctness — including that it is *enforced*, not merely reported: a removal the user never accepted must be refused (`GuardAck`, PD-RES-004), and widening a removal must re-run the guard rather than proceed.
|
||||
|
||||
## 2. Layers
|
||||
|
||||
### L1 — Core unit tests (Rust, `cargo test`)
|
||||
|
||||
- **Parser fixtures:** captured real outputs under `tests/fixtures/{pip,uv}/{list,outdated,report,errors}/…` (seeded by spikes SP-1/SP-2, grown from every new engine release and every triaged bug). `insta` snapshot tests assert the normalized `ResolutionReport`. A CI job runs the capture script against the *latest* engine versions weekly and fails on unrecognized shapes → PD-ENG-003 before users hit it.
|
||||
- **Error classifiers:** every catalog code has ≥ 1 stderr fixture; a test enforces "no code without fixture."
|
||||
- **Graph:** reverse-dep construction and blocker attribution over synthetic metadata sets, including cycles and extras (`pkg[extra]`) markers.
|
||||
- **Snapshot diff/rollback planner:** property-style tests — `apply(plan(diff(a,b)), b) == a` over generated freeze pairs, and the **partition**: every significant freeze line is either parsed into a pin or reported unrestorable, never neither. The second is the one a rollback preview stands on — a line both functions dropped disappeared silently, and the preview then promised a restore it could not perform.
|
||||
- **Name/spec validation:** PEP 508/440 accept/reject tables.
|
||||
- **Parser fixtures:** captured real outputs under `tests/fixtures/{pip,uv}/{list,outdated,report,errors}/…` (seeded by spikes SP-1/SP-2, grown from every new engine release and every triaged bug). `insta` snapshot tests assert the normalized `ResolutionReport`. A CI job runs the capture script against the *latest* engine versions weekly and fails on unrecognized shapes → PD-ENG-003 before users hit it.
|
||||
- **Error classifiers:** every catalog code has ≥ 1 stderr fixture; a test enforces "no code without fixture."
|
||||
- **Graph:** reverse-dep construction and blocker attribution over synthetic metadata sets, including cycles and extras (`pkg[extra]`) markers.
|
||||
- **Snapshot diff/rollback planner:** property-style tests — `apply(plan(diff(a,b)), b) == a` over generated freeze pairs, and the **partition**: every significant freeze line is either parsed into a pin or reported unrestorable, never neither. The second is the one a rollback preview stands on — a line both functions dropped disappeared silently, and the preview then promised a restore it could not perform.
|
||||
- **Name/spec validation:** PEP 508/440 accept/reject tables.
|
||||
|
||||
### L2 — Engine integration (disposable venvs, Windows CI runner)
|
||||
|
||||
Each test creates a throwaway venv (`python -m venv` and `uv venv`), then exercises real engines:
|
||||
|
||||
| Scenario | Assertion |
|
||||
|---|---|
|
||||
| Fresh venv + install 3 small pure wheels | summary 3/0; `check` clean |
|
||||
| Seed known conflict (install `A==old` requiring `B<x`, then plan `B` latest) | plan shows held-back with correct blocker; Compatible path succeeds; Force path warns and `check` reports breakage |
|
||||
| Batch with 1 deliberately broken sdist | Phase B isolates it; counts n-1 ok / 1 failed with PD-BLD-*; env passes `check` |
|
||||
| Uninstall a depended-on package | guard lists dependents; `--force` proceeds |
|
||||
| Snapshot → mutate → rollback | env freeze equals snapshot |
|
||||
| PEP 668 marker file planted | PD-ENV-002 block; override path passes flag |
|
||||
Scenario
|
||||
|
||||
Assertion
|
||||
|
||||
Fresh venv + install 3 small pure wheels
|
||||
|
||||
summary 3/0; `check` clean
|
||||
|
||||
Seed known conflict (install `A==old` requiring `B<x`, then plan `B` latest)
|
||||
|
||||
plan shows held-back with correct blocker; Compatible path succeeds; Force path warns and `check` reports breakage
|
||||
|
||||
Batch with 1 deliberately broken sdist
|
||||
|
||||
Phase B isolates it; counts n-1 ok / 1 failed with PD-BLD-*; env passes `check`
|
||||
|
||||
Uninstall a depended-on package
|
||||
|
||||
guard lists dependents; `--force` proceeds
|
||||
|
||||
Snapshot → mutate → rollback
|
||||
|
||||
env freeze equals snapshot
|
||||
|
||||
PEP 668 marker file planted
|
||||
|
||||
PD-ENV-002 block; override path passes flag
|
||||
|
||||
Fixture packages are tiny pinned PyPI wheels (documented list in `tests/integration/pins.toml`) so CI is deterministic; network-touching tests are tagged and can run against a local `pypiserver` mirror when offline determinism is needed.
|
||||
|
||||
@@ -53,4 +72,4 @@ Core target ≥ 85 % line coverage (`cargo llvm-cov`), classifiers and plan modu
|
||||
|
||||
## 4. Manual test charter (per release)
|
||||
|
||||
A short exploratory pass on a real machine: dirty 150+ package env, corporate-proxy simulation (PD-NET-002 copy), non-ASCII Windows username paths, VI locale sweep of all mutation dialogs, cancel mid-Phase-B, and SmartScreen/first-run installer experience.
|
||||
A short exploratory pass on a real machine: dirty 150+ package env, corporate-proxy simulation (PD-NET-002 copy), non-ASCII Windows username paths, VI locale sweep of all mutation dialogs, cancel mid-Phase-B, and SmartScreen/first-run installer experience.
|
||||
+46
-11
@@ -4,7 +4,7 @@
|
||||
|
||||
## 1. Design intent
|
||||
|
||||
PipDock should feel like a **precision instrument docked over a terminal** — the calm confidence of a good TUI with the affordances of a native app. Not a neon cyberpunk cliché, not a generic admin dashboard: restrained phosphor-green on near-black, monospace where data lives, one accent doing real work. Signature moves: a terminal-style **status line** pinned to the bottom, a live **execution console** that streams real engine output, and (P1) a Ctrl+K command palette.
|
||||
PipDock should feel like a **precision instrument docked over a terminal** — the calm confidence of a good TUI with the affordances of a native app. Not a neon cyberpunk cliché, not a generic admin dashboard: restrained phosphor-green on near-black, monospace where data lives, one accent doing real work. Signature moves: a terminal-style **status line** pinned to the bottom, a live **execution console** that streams real engine output, and a **Ctrl+K command palette** (shipped 1.1.0).
|
||||
|
||||
Anti-goals: gradients-everywhere SaaS look, rounded-blob cards, decorative glow. Any glow is functional (focus rings, live-activity pulse) and subtle.
|
||||
|
||||
@@ -95,8 +95,26 @@ budget intact. Neither button is a tab stop — the row is (see §8). Multi-sele
|
||||
`pins::hold_requirements` has no caller and `engine::plan_requirements` restates every package at its
|
||||
*installed* version — a hold at any other version is a promise nothing keeps, and the CLI cannot
|
||||
create one either. With no environment selected the screen says so rather than "no pins": pins are
|
||||
keyed by `env_hash`, so that is not an empty list. (P1) auto-suggest section: "`urllib3` — 12
|
||||
packages depend on it. Pin?".
|
||||
keyed by `env_hash`, so that is not an empty list.
|
||||
|
||||
**The auto-suggest section** — "`urllib3` — 12 packages depend on it. Pin?" — landed post-1.0 as
|
||||
P1-A. It sits *above* the pin list, because it is a prompt to act and the list is a record of
|
||||
having acted, and it is absent entirely when there is nothing to suggest. Accepting writes an
|
||||
ordinary `Exclude` pin with the count as its reason (PRD P1-2's "suggest pin with reason"), which
|
||||
the reason field below can then replace.
|
||||
|
||||
**It shows the top 8 and says how many more qualify.** Measured against the 352-package fixture,
|
||||
the default threshold of 5 qualifies 94 — a quarter of the environment. Raising the default would
|
||||
be the wrong fix, because a deep dependency tree is exactly where a bulk update is most dangerous;
|
||||
the count in the "N more" line comes from the full list, so a capped view never misreports a total.
|
||||
Same rule as `RUFF_ROWS_SHOWN` in the Health report.
|
||||
|
||||
It costs one `probe.py` run, and that is why it is here rather than on a sidebar badge: only
|
||||
someone who opened this tab pays for it. It is also **silent on failure** — this screen's job is
|
||||
listing pins and it does that either way, so an error row about an advisory would be the loudest
|
||||
thing on it. Counts come from `graph::dependent_count`, which counts in-force edges only: the same
|
||||
set the uninstall guard warns about, because a user pinning on one rule and being warned on another
|
||||
is the failure worth designing against.
|
||||
|
||||
**Snapshots** (surfaced under Environments → env detail): timeline of snapshots with trigger label, diff viewer (added/removed/changed in mono), `Rollback…` with its own preview per DATA-FLOW §8.
|
||||
|
||||
@@ -121,7 +139,21 @@ the snapshot's side.
|
||||
|
||||
**Health.** Project-folder picker (persisted per env) → run panel with three result tabs (deptry / vulture / ruff) per CODE-HEALTH-SPEC; `Fix with ruff` gated behind explicit confirm listing file count.
|
||||
|
||||
**Settings.** Engine (pip/uv radio + detected versions), locale (EN/VI), thresholds (pin auto-suggest count, snapshot retention), index refresh, PEP 668 override (off by default, scary copy), *Open logs folder*.
|
||||
**Security.** *Run audit* → advisories grouped by package, each with its id, the versions that fix
|
||||
it (or **no fix**, stated rather than left blank), its aliases — which is where the CVE lives, since
|
||||
pip-audit's primary id is a `PYSEC-*` — the advisory prose verbatim, and a link to its OSV entry.
|
||||
**No severity column**: pip-audit publishes none under either vulnerability service, so the order is
|
||||
package → fixable → id, and inventing a severity would put a number PipDock made up beside real
|
||||
ones (PRD P1-1 is amended to say so). A *Cancel* appears while a run is going, which Code Health has
|
||||
no equivalent of: an audit is 18-68 s against Health's 1.3 s. **The body says nothing while a run is
|
||||
in flight** — not "no audit has run", which is what it said until someone clicked Run against a slow
|
||||
bridge and read it.
|
||||
|
||||
**Settings.** Engine (pip/uv radio + detected versions), locale (EN/VI), **pin auto-suggest count** (P1-A; zero turns suggestions off), snapshot retention, index refresh, PEP 668 override (off by default, scary copy), *Open logs folder*.
|
||||
|
||||
**Disk usage** (P1-C) shows what PipDock has written — snapshots and the Code Health tools venv, each with a *Clear*, and `index.db` reported without one because it holds settings, pins and the consent record in the same file. Three artefacts, not four: there are no log files, `LOG_RETENTION_DAYS` has never had a reader, and a "logs — 0 B" row would invent one.
|
||||
|
||||
The threshold is the app's **first numeric input**, and it sets the rule for the next one: reject at the boundary, never store junk. `<input type="number">` reports `''` for anything it cannot parse, so coercing the raw value writes `0` — which here is a meaningful setting, "off", that the user did not ask for. Its label avoids the word *threshold* on purpose; see `PdPins.test.tsx`'s Hold assertion, which matches `/hold/i`.
|
||||
|
||||
**Legal & About left Settings** in Phase 4 and became the About tab below. Neither is a setting: they are read-only surfaces, and folding them into a screen of controls is what kept them unbuilt for four milestones while every control around them shipped.
|
||||
|
||||
@@ -146,6 +178,7 @@ app lands. Counted by hand in the running app, never inferred from the markup.
|
||||
| Switch engine | **3** | Settings → engine radio → (auto-saved) back |
|
||||
| Run Code Health | **3** | Health → Run (folder persisted) → view (**4** the first time in a project: Health → *Choose folder…* → the OS dialog, which is not PipDock's click → Run → view. The folder is remembered per environment from then on.) |
|
||||
| Fix ruff findings | **3** | ruff tab → *Fix N…* → *Fix* (from a report already on screen; **5** from the landing screen with a folder remembered, which is the owner's ceiling). Cancel holds default focus, so `Enter` without `Tab` cancels. |
|
||||
| Run a security audit | **2** | Security → *Run audit*. Counted in the running app against a stubbed bridge. The first run also builds the audit environment, which is a wait rather than a click. |
|
||||
| Upgrade pip | **2** | *Upgrade pip* → *Upgrade* (Environments is the landing screen, so no tab click). The button appears only when pip is below the 22.2 planner floor — the case the ordinary Updates path cannot fix, because the planner it needs will not run. |
|
||||
|
||||
### Shell rules established by the first installed build (2026-08-13)
|
||||
@@ -179,12 +212,14 @@ a metre of empty surface. Still resizable, and `minWidth`/`minHeight` are unchan
|
||||
`PdEnvSwitcher` alone, which nothing needs while the header shows the selected interpreter and the
|
||||
Environments tab switches it. (ROADMAP and
|
||||
CLAUDE.md both claimed 16 of 16 after S4; the count had quietly folded in components that are not on
|
||||
this list.) Four components not on this list have
|
||||
turned out to be load-bearing and are listed here so the inventory stays honest: `PdErrorRow`
|
||||
(ERROR-CATALOG §3's row, used by every error surface), `PdDialog` (the shared modal §7's destructive
|
||||
confirms need), `PdUninstallDialog` (§5's three options), `PdPinChip` (the 🔒 chip, shared by the
|
||||
table and the Pins screen) and `PdRollbackPreview` (DATA-FLOW §8's preview, including its
|
||||
`PD-SNP-002` list).
|
||||
this list.) **Six** components not on this list have
|
||||
turned out to be load-bearing and are listed here so the inventory stays honest — the number said
|
||||
*four* while naming five for two milestones, which is the counting trap this section exists to
|
||||
avoid: `PdErrorRow` (ERROR-CATALOG §3's row, used by every error surface), `PdDialog` (the shared
|
||||
modal §7's destructive confirms need), `PdUninstallDialog` (§5's three options), `PdPinChip` (the
|
||||
🔒 chip, shared by the table and the Pins screen), `PdRollbackPreview` (DATA-FLOW §8's preview,
|
||||
including its `PD-SNP-002` list) and `PdAuditReport` (P1-1's advisory list). Three more shipped in
|
||||
1.1.0 and are named nowhere in this section: `PdCacheUsage`, `PdPalette` and `PdRequirements`.
|
||||
|
||||
## 7. States & feedback
|
||||
|
||||
@@ -196,7 +231,7 @@ table and the Pins screen) and `PdRollbackPreview` (DATA-FLOW §8's preview, inc
|
||||
|
||||
## 8. Keyboard & accessibility
|
||||
|
||||
Full keyboard traversal: `Ctrl+1..9` sidebar tabs, `/` focuses search, `Space` toggles row selection, `Ctrl+A` select-all-visible, `Enter` primary action, `Esc` closes drawers, and **`←`/`→` move within a focused row** (P6).
|
||||
Full keyboard traversal: `Ctrl+1..9` sidebar tabs, **`Ctrl+K` opens the command palette**, `/` focuses search, `Space` toggles row selection, `Ctrl+A` select-all-visible, `Enter` primary action, `Esc` closes drawers, and **`←`/`→` move within a focused row** (P6).
|
||||
|
||||
**The arrow keys are not decoration, and the gap they close was real.** Making the row the only tab stop is what keeps 200 rows from becoming 600 — but every control inside one is `tabIndex={-1}`, and that left *Pin* and *Remove* reachable by mouse only: a WCAG 2.1.1 failure, found by tabbing to a row in the running app and discovering there was nowhere further to go. `←`/`→` are the ARIA grid pattern's roving tabindex, `Esc` returns focus to the row, and no tab stops are added.
|
||||
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ PipDock blocks modification of externally-managed (PEP 668) Python installations
|
||||
|
||||
## 4. Information accuracy
|
||||
|
||||
Package metadata, latest-version information and code-health reports are derived from third-party sources (PyPI, and deptry/vulture/ruff output) and from heuristics such as reverse-dependency analysis. They may be incomplete, outdated, or wrong — for example, dead-code detection produces false positives on dynamically referenced code, and deptry reports a module name rather than the distribution that provides it. **Review before acting**; PipDock's reports are assistance, not authority. Version 1.0 ships no vulnerability scanning; if a future release adds it, its findings come from the OSV database and this paragraph covers them too.
|
||||
Package metadata, latest-version information and code-health reports are derived from third-party sources (PyPI, and deptry/vulture/ruff output) and from heuristics such as reverse-dependency analysis. They may be incomplete, outdated, or wrong — for example, dead-code detection produces false positives on dynamically referenced code, and deptry reports a module name rather than the distribution that provides it. **Review before acting**; PipDock's reports are assistance, not authority. The Security tab reports known advisories against your installed packages. Those come from **PyPI's advisory data**, by way of pip-audit, and are covered by this paragraph too: an advisory database is a record of what has been reported, not a guarantee that a package is safe or that an absence of findings means there is nothing to find. Each finding links to its entry on osv.dev so you can read the original. PipDock assigns no severity and no risk score, because pip-audit publishes none.
|
||||
|
||||
## 5. Not professional advice; no affiliation
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ PipDock is free software, licensed under the **GNU General Public License, versi
|
||||
|
||||
## 2. What PipDock does (acknowledgment)
|
||||
|
||||
PipDock installs, upgrades, and removes packages in Python environments **at your direction**, by invoking third-party package managers (pip, uv) and analysis tools (deptry, vulture, ruff; pip-audit is planned and is not invoked in version 1.0). These operations modify software environments on your computer and can affect the behavior of your projects. You are responsible for reviewing each preview and confirmation the application presents before applying changes.
|
||||
PipDock installs, upgrades, and removes packages in Python environments **at your direction**, by invoking third-party package managers (pip, uv) and analysis tools (deptry, vulture, ruff, and pip-audit for the Security tab). These operations modify software environments on your computer and can affect the behavior of your projects. You are responsible for reviewing each preview and confirmation the application presents before applying changes.
|
||||
|
||||
## 3. No warranty
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ These run as independent programs from your system or from PipDock's isolated to
|
||||
| deptry | MIT | Code Health — dependency issues |
|
||||
| vulture | MIT | Code Health — dead code |
|
||||
| ruff | MIT | Code Health — lint/format |
|
||||
| pip-audit | Apache-2.0 | Security tab — **not invoked in 1.0**; listed because the tab is planned and this row is where it will belong |
|
||||
| pip-audit | Apache-2.0 | Security tab — known advisories against installed packages. Installed into its own environment, separate from the three above |
|
||||
| CPython | PSF License | the environments themselves |
|
||||
|
||||
## C. Services
|
||||
|
||||
Generated
+68
-68
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "pipdock",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pipdock",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"license": "GPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@tanstack/react-virtual": "^3.14.9",
|
||||
@@ -18,7 +18,7 @@
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-i18next": "^17.0.11",
|
||||
"zustand": "^5.0.14"
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
@@ -36,7 +36,7 @@
|
||||
"jsdom": "^30.0.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.66.0",
|
||||
"typescript-eslint": "^8.67.0",
|
||||
"vite": "^8.2.1",
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
@@ -1842,17 +1842,17 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.66.0.tgz",
|
||||
"integrity": "sha512-p088eaGrzYz1s+7cov0aMOCkNGTJlVxF4jgubf28c8L0Cv9Rloj8YBHnv4hXLq6IIEE1AsjNWavO+k+8kP2Y0A==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.67.0.tgz",
|
||||
"integrity": "sha512-Un7Heoyj65NREbKAyIrFxeM143NZpExWmy1Nep4DLeQOeLlTeumPjoNKnBrU5D5moWXbPJgRa5Uwcdu0faVNGQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/regexpp": "^4.12.2",
|
||||
"@typescript-eslint/scope-manager": "8.66.0",
|
||||
"@typescript-eslint/type-utils": "8.66.0",
|
||||
"@typescript-eslint/utils": "8.66.0",
|
||||
"@typescript-eslint/visitor-keys": "8.66.0",
|
||||
"@typescript-eslint/scope-manager": "8.67.0",
|
||||
"@typescript-eslint/type-utils": "8.67.0",
|
||||
"@typescript-eslint/utils": "8.67.0",
|
||||
"@typescript-eslint/visitor-keys": "8.67.0",
|
||||
"ignore": "^7.0.5",
|
||||
"natural-compare": "^1.4.0",
|
||||
"ts-api-utils": "^2.5.0"
|
||||
@@ -1865,7 +1865,7 @@
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@typescript-eslint/parser": "^8.66.0",
|
||||
"@typescript-eslint/parser": "^8.67.0",
|
||||
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
|
||||
"typescript": ">=4.8.4 <6.1.0"
|
||||
}
|
||||
@@ -1881,16 +1881,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/parser": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.66.0.tgz",
|
||||
"integrity": "sha512-X6ypGChaWYk6PBtUg2BwuTZEFFcHJAtGTVJ9/lCTOufhZ4i9fNolQNnktq+kkMCwMj7V8Svsq7+TxSDslmhE0g==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.67.0.tgz",
|
||||
"integrity": "sha512-fUBfTuuEulWqX6V8+O3PtScV01tzYYRUDTAirHFKoRAt7nOzoGiPt0M/bB47wWNy0coOOcgEwAMUtBpykMxl6w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.66.0",
|
||||
"@typescript-eslint/types": "8.66.0",
|
||||
"@typescript-eslint/typescript-estree": "8.66.0",
|
||||
"@typescript-eslint/visitor-keys": "8.66.0",
|
||||
"@typescript-eslint/scope-manager": "8.67.0",
|
||||
"@typescript-eslint/types": "8.67.0",
|
||||
"@typescript-eslint/typescript-estree": "8.67.0",
|
||||
"@typescript-eslint/visitor-keys": "8.67.0",
|
||||
"debug": "^4.4.3"
|
||||
},
|
||||
"engines": {
|
||||
@@ -1906,14 +1906,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/project-service": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.66.0.tgz",
|
||||
"integrity": "sha512-7MthGPTt4BP69lSryqpqq8HQqxuzynssckL/jyDyk3+TNMQ3y2jFWkptCrktWvBrP+EH787Nl5N5Qpw7WZg+5g==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.67.0.tgz",
|
||||
"integrity": "sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/tsconfig-utils": "^8.66.0",
|
||||
"@typescript-eslint/types": "^8.66.0",
|
||||
"@typescript-eslint/tsconfig-utils": "^8.67.0",
|
||||
"@typescript-eslint/types": "^8.67.0",
|
||||
"debug": "^4.4.3"
|
||||
},
|
||||
"engines": {
|
||||
@@ -1928,14 +1928,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/scope-manager": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.66.0.tgz",
|
||||
"integrity": "sha512-8TGcH25j9zqJ/IULB/ppyhRvxA8QYfFEZ7nfbg6/BN9spDgb8fPWQXlE5l8TWBL50EtUx007uZ1o9VOwrq2/9g==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.67.0.tgz",
|
||||
"integrity": "sha512-EgvsleTwS4E+WzzSvem8fAUubLwatMNF1B5hHSLQxcvs7q2dtRhGyujHwLJSYlG41niJ7GP24Aha2+0mb1b2kg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.66.0",
|
||||
"@typescript-eslint/visitor-keys": "8.66.0"
|
||||
"@typescript-eslint/types": "8.67.0",
|
||||
"@typescript-eslint/visitor-keys": "8.67.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
@@ -1946,9 +1946,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/tsconfig-utils": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.66.0.tgz",
|
||||
"integrity": "sha512-9D5gLYZG4rOjcoag8MQ/fWI8WqA9wcPDyOGyWtWFhvM1lHRbliqUSPIY5J3zqCU1tvSwzXxnnjhQhz5Ne7mJ4g==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.67.0.tgz",
|
||||
"integrity": "sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -1963,15 +1963,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/type-utils": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.66.0.tgz",
|
||||
"integrity": "sha512-LG2dWfjZQQp0ADtAu/EWJVayefGL2UEZ3CDeI44D9v3rXB/WYUqE/jpO28KrEKul5AySrmI+Zh1v6v+xW2U9+g==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.67.0.tgz",
|
||||
"integrity": "sha512-aVWDXbRmdXO9siTfX4ditQI1T9+zVcNazT48EJCD0v40/9RIFoUgZ05CmGEq9H2gixRpjUn/iplwvlcvutJW/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.66.0",
|
||||
"@typescript-eslint/typescript-estree": "8.66.0",
|
||||
"@typescript-eslint/utils": "8.66.0",
|
||||
"@typescript-eslint/types": "8.67.0",
|
||||
"@typescript-eslint/typescript-estree": "8.67.0",
|
||||
"@typescript-eslint/utils": "8.67.0",
|
||||
"debug": "^4.4.3",
|
||||
"ts-api-utils": "^2.5.0"
|
||||
},
|
||||
@@ -1988,9 +1988,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/types": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.66.0.tgz",
|
||||
"integrity": "sha512-H6gcYaSDOyvL3AD/jHUtUFo2jqGgn/F6nuyuZSu0QTesxL+cP4dQoIMrODRofuJC09g64+WgZ6tE19Y1N2YIFQ==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.67.0.tgz",
|
||||
"integrity": "sha512-sBtgslww8nsMYUjhdPBiSyUqSzT8uR6g93A2QXnQC8+cGdjz0CyaOdqHDRJb1AtORbZCNUJBBeFA/tNR2uQmww==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -2002,16 +2002,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.66.0.tgz",
|
||||
"integrity": "sha512-8/x4INiiQb10jGgXYD7116/zQ+OL84ZIFn0za68wwFHCanT/VLbBEroWht8RV8fn0/ZCAoazHLQgwUC0UQcDfg==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.67.0.tgz",
|
||||
"integrity": "sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/project-service": "8.66.0",
|
||||
"@typescript-eslint/tsconfig-utils": "8.66.0",
|
||||
"@typescript-eslint/types": "8.66.0",
|
||||
"@typescript-eslint/visitor-keys": "8.66.0",
|
||||
"@typescript-eslint/project-service": "8.67.0",
|
||||
"@typescript-eslint/tsconfig-utils": "8.67.0",
|
||||
"@typescript-eslint/types": "8.67.0",
|
||||
"@typescript-eslint/visitor-keys": "8.67.0",
|
||||
"debug": "^4.4.3",
|
||||
"minimatch": "^10.2.2",
|
||||
"semver": "^7.7.3",
|
||||
@@ -2043,16 +2043,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/utils": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.66.0.tgz",
|
||||
"integrity": "sha512-jasearZPolBw5NJNYGMwxzHMF83niVWmMU1VdHzG1CyfI2VS7f7nZltnKtHcg20hW+7Uo5GfK4MeDPoU3qI8EA==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.67.0.tgz",
|
||||
"integrity": "sha512-U9D1FdwEWBwok3hxxSdhclMb0twvt9QnjIQ0VfQ1AiX2epnpSgv2ubVDsayOFyY8K6FX+AQ7E0FKWVG3iKsj1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.9.1",
|
||||
"@typescript-eslint/scope-manager": "8.66.0",
|
||||
"@typescript-eslint/types": "8.66.0",
|
||||
"@typescript-eslint/typescript-estree": "8.66.0"
|
||||
"@typescript-eslint/scope-manager": "8.67.0",
|
||||
"@typescript-eslint/types": "8.67.0",
|
||||
"@typescript-eslint/typescript-estree": "8.67.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
@@ -2067,13 +2067,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/visitor-keys": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.66.0.tgz",
|
||||
"integrity": "sha512-dkKR8q+lKciskj1Y3vthHktl+3cMLWGyVUP23bRiPZ5O9BRT++4EqDDV+TVeIKBL1VXVEqrJlz8MYbcnvJcAlg==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.67.0.tgz",
|
||||
"integrity": "sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.66.0",
|
||||
"@typescript-eslint/types": "8.67.0",
|
||||
"eslint-visitor-keys": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
@@ -4186,16 +4186,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/typescript-eslint": {
|
||||
"version": "8.66.0",
|
||||
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.66.0.tgz",
|
||||
"integrity": "sha512-QlEbBPz/RuJ1XUHj29nm3t0F/O/cSlEnntozqPOYHnnTGAXFamnMBu5i9Vn6vhUPHGAjR+Vl+5J8vPN/BMUrJw==",
|
||||
"version": "8.67.0",
|
||||
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.67.0.tgz",
|
||||
"integrity": "sha512-S2udFs8tCKEKffuJ4TB1idGUZiXdCPGi3IPBGWXarbLQ5UPXORV8QEVzJ4gCRduURMb5EkpNCdjbk0eDIuI8Yg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "8.66.0",
|
||||
"@typescript-eslint/parser": "8.66.0",
|
||||
"@typescript-eslint/typescript-estree": "8.66.0",
|
||||
"@typescript-eslint/utils": "8.66.0"
|
||||
"@typescript-eslint/eslint-plugin": "8.67.0",
|
||||
"@typescript-eslint/parser": "8.67.0",
|
||||
"@typescript-eslint/typescript-estree": "8.67.0",
|
||||
"@typescript-eslint/utils": "8.67.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
@@ -4869,9 +4869,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/zustand": {
|
||||
"version": "5.0.14",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.14.tgz",
|
||||
"integrity": "sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g==",
|
||||
"version": "5.0.15",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz",
|
||||
"integrity": "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pipdock",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"description": "A friendly dock for your Python environments — bulk inspect, install, update and clean up Python packages.",
|
||||
"license": "GPL-3.0-only",
|
||||
@@ -35,7 +35,7 @@
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-i18next": "^17.0.11",
|
||||
"zustand": "^5.0.14"
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
@@ -53,7 +53,7 @@
|
||||
"jsdom": "^30.0.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.66.0",
|
||||
"typescript-eslint": "^8.67.0",
|
||||
"vite": "^8.2.1",
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
|
||||
@@ -371,6 +371,19 @@ def redact(text: str, work: Path) -> str:
|
||||
# every run and wildly different between a dev machine and a CI runner.
|
||||
text = re.sub(r"(?m)^\s*-+\s+[^\r\n]*?eta [0-9:]+[ \t]*$", " <PROGRESS>", text)
|
||||
|
||||
# pip's self-upgrade notice names the version that is on PyPI *today* — "[notice] A new
|
||||
# release of pip is available: 25.0.1 -> 26.1.2" — which is a statement about the index,
|
||||
# not about anything the engine did. It moves with every pip release: on 2026-08-17 pip
|
||||
# 26.2.1 shipped and the drift gate failed across all nine pip fixtures carrying this line.
|
||||
# The installed half goes too, because `capture-provenance.json` already records the exact
|
||||
# pip and a runner whose bundled pip moves would otherwise re-break this the same way.
|
||||
# Safe to drop for the usual reason: no `CLASSIFIERS` entry reads a version out of stderr.
|
||||
text = re.sub(
|
||||
r"(A new release of pip is available: )\d[\w.+!-]*( -> )\d[\w.+!-]*",
|
||||
r"\1<VERSION>\2<VERSION>",
|
||||
text,
|
||||
)
|
||||
|
||||
# uv times every phase — "Resolved 3 packages in 775ms", "Checked 8 packages in 1ms". The
|
||||
# counts are signal and stay; the durations are never the same twice. Safe to drop: the uv
|
||||
# adapter only tests `text.contains("Resolved ")` and reads the +/- lines (engine/parse.rs).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "external-links",
|
||||
"description": "Hand a GitHub, ruff-docs or poli0981.dev URL to the user's browser. GitHub: the legal gate links to the five documents (UI-SPEC §4), the summary sheet's Report-bug deep link opens a prefilled issue (ERROR-CATALOG §4), PD-SYS-001 links to the long-paths help, vulture's whitelist help lives there too, and About links to the repository. docs.astral.sh: every ruff finding carries its own rule page, which CODE-HEALTH-SPEC §6 as amended says is keyed by rule NAME and must be used rather than constructed. poli0981.dev: About's links page, the one page listing every other way to reach the author. The webview cannot do this itself: connect-src in tauri.conf.json allows only 'self' and the IPC origin. STILL SCOPED ON PURPOSE — an unscoped opener is a launch-anything primitive reachable from any injected string, which is the same reasoning SECURITY §2 applies to argv arrays. Three hosts is not the same as any host, and each was added because a feature failed silently without it, not to make room. WHAT THIS ACTUALLY DEFENDS is narrower than it looks: most call sites pass module constants no injected string can reach. Two pass data — PdErrorRow's Rust-built URL, and PdHealthReport's finding.url, which comes out of ruff's own JSON over the user's source tree and is the only URL in the application derived from a third-party tool's output. That is the one this list is really bounding, and the reason About copies its contact addresses to the clipboard instead of opening them: a mailto: entry would widen the list by a whole URL scheme and re-open a target class for that call site, to save a paste.",
|
||||
"description": "Hand a GitHub, ruff-docs, poli0981.dev or OSV URL to the user's browser. GitHub: the legal gate links to the five documents (UI-SPEC §4), the summary sheet's Report-bug deep link opens a prefilled issue (ERROR-CATALOG §4), PD-SYS-001 links to the long-paths help, vulture's whitelist help lives there too, and About links to the repository. docs.astral.sh: every ruff finding carries its own rule page, which CODE-HEALTH-SPEC §6 as amended says is keyed by rule NAME and must be used rather than constructed. poli0981.dev: About's links page, the one page listing every other way to reach the author. The webview cannot do this itself: connect-src in tauri.conf.json allows only 'self' and the IPC origin. STILL SCOPED ON PURPOSE — an unscoped opener is a launch-anything primitive reachable from any injected string, which is the same reasoning SECURITY §2 applies to argv arrays. Four hosts is not the same as any host, and each was added because a feature failed silently without it, not to make room. WHAT THIS ACTUALLY DEFENDS is narrower than it looks: most call sites pass module constants no injected string can reach. Two pass data — PdErrorRow's Rust-built URL, and PdHealthReport's finding.url, which comes out of ruff's own JSON over the user's source tree and is the only URL in the application derived from a third-party tool's output. osv.dev: every Security-tab finding carries an advisory entry, which DISCLAIMER §4 and SECURITY §6 both promise a link to — without this the promise rejects and nothing opens, silently. That URL is the SECOND derived from a tool's output, and it is deliberately not the same kind: PdHealthReport hands over ruff's own `finding.url` verbatim, while `audit::advisory_url` BUILDS the URL from an id it has checked against a whitelist of ASCII alphanumerics and hyphen. Nothing that passes that check can contain a slash, colon, question mark, hash or percent, so the result cannot be anything but a path segment under one host — the tool chooses the id, never the destination. That is the one this list is really bounding, and the reason About copies its contact addresses to the clipboard instead of opening them: a mailto: entry would widen the list by a whole URL scheme and re-open a target class for that call site, to save a paste.",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
{
|
||||
@@ -9,7 +9,8 @@
|
||||
"allow": [
|
||||
{ "url": "https://github.com/*" },
|
||||
{ "url": "https://docs.astral.sh/*" },
|
||||
{ "url": "https://poli0981.dev/*" }
|
||||
{ "url": "https://poli0981.dev/*" },
|
||||
{ "url": "https://osv.dev/*" }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
+260
-5
@@ -13,7 +13,7 @@ use pipdock_core::envs::{self, ScanProgress};
|
||||
use pipdock_core::flow;
|
||||
use pipdock_core::index::{self, NameIndex};
|
||||
use pipdock_core::model::{EnvSource, StepResult};
|
||||
use pipdock_core::pins::{self, Pin};
|
||||
use pipdock_core::pins::{self, Pin, PinSuggestion};
|
||||
use pipdock_core::plan::{Decision, ExecutionSummary};
|
||||
use pipdock_core::settings::{self, Consent, Settings};
|
||||
use pipdock_core::snapshot;
|
||||
@@ -339,6 +339,134 @@ pub async fn pin_remove(
|
||||
Ok(pins::remove(&store, &env_hash, &name)?)
|
||||
}
|
||||
|
||||
/// Packages worth pinning, most-depended-upon first — PRD P1-2, UI-SPEC §4.
|
||||
///
|
||||
/// Takes the whole `PyEnv` rather than an `env_hash` for [`pkg_list`]'s reason: it is handed
|
||||
/// straight back from `env_scan`, and the hash is a one-way digest of the interpreter path, so
|
||||
/// there is nothing to resolve it *from*. The hash is derived here instead — the same thing
|
||||
/// `flow::UpdateFlow::start` does.
|
||||
///
|
||||
/// **One probe per call**, and that is why UI-SPEC §4 puts this on the Pins screen rather than on
|
||||
/// a sidebar badge: the count is only paid by someone who opened the tab. The alternative — asking
|
||||
/// the frontend for the `Dist` list it already holds — would send several hundred packages' worth
|
||||
/// of `requires_dist` back across the bridge to save a subprocess.
|
||||
///
|
||||
/// The store guard is dropped before the probe, per [`pkg_outdated`]'s note: holding it across the
|
||||
/// await compiles, passes every test, and freezes `settings_get` and the pin commands for as long
|
||||
/// as the probe takes.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-ENV-001` when the interpreter has gone, `PD-ENV-003` when the probe output is unreadable,
|
||||
/// `PD-INT-001` when the pin table cannot be read.
|
||||
#[tauri::command]
|
||||
pub async fn pin_suggestions(
|
||||
state: tauri::State<'_, AppState>,
|
||||
env: PyEnv,
|
||||
) -> Wire<Vec<PinSuggestion>> {
|
||||
let (existing, threshold) = {
|
||||
let store = state.store.lock().await;
|
||||
let existing = pins::list(&store, &envs::env_hash(&env.interpreter))?;
|
||||
(existing, settings::load(&store)?.pin_suggest_threshold)
|
||||
};
|
||||
let probed = envs::probe(&env.interpreter, env.source).await?;
|
||||
Ok(pins::suggest(
|
||||
&probed.dists,
|
||||
&probed.env.python_version,
|
||||
&existing,
|
||||
threshold,
|
||||
))
|
||||
}
|
||||
|
||||
/// Write the environment out as a `requirements.txt` — PRD P1-3.
|
||||
///
|
||||
/// **The document is `Engine::freeze`'s**, byte for byte, which is the same one a snapshot
|
||||
/// records. A freeze *is* a requirements file, so there is no formatter here and no second idea
|
||||
/// of what an exported environment looks like. A constraints file is the same body under a
|
||||
/// different name; the difference is how the user feeds it back, not what it contains.
|
||||
///
|
||||
/// Writing happens in Rust because `capabilities/default.json` grants `dialog:allow-open` and
|
||||
/// `dialog:allow-save` and deliberately no `fs` permission — the picker returns a path and nothing
|
||||
/// in the webview can act on it. `health_save_report` is the same shape.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-ENG-001` when the engine cannot be spawned, `PD-ENV-*` when the environment cannot be read,
|
||||
/// `PD-SYS-002` when the file cannot be written.
|
||||
#[tauri::command]
|
||||
pub async fn env_export(
|
||||
state: tauri::State<'_, AppState>,
|
||||
env: PyEnv,
|
||||
path: String,
|
||||
) -> Wire<String> {
|
||||
let engine = {
|
||||
let store = state.store.lock().await;
|
||||
engine::for_id(settings::load(&store)?.engine)
|
||||
};
|
||||
let freeze = engine.freeze(&env).await?;
|
||||
let target = std::path::PathBuf::from(&path);
|
||||
std::fs::write(&target, freeze).map_err(|e| {
|
||||
PdError::new(
|
||||
pipdock_core::errors::Code::SysDiskFull,
|
||||
format!("write {}: {e}", target.display()),
|
||||
)
|
||||
})?;
|
||||
Ok(target.display().to_string())
|
||||
}
|
||||
|
||||
/// Read a `requirements.txt` into install specs, with whatever it could not use.
|
||||
///
|
||||
/// Reading happens in Rust for the same reason writing does: the webview has no `fs` permission,
|
||||
/// only the ability to ask for a path.
|
||||
///
|
||||
/// The result is deliberately **not** fed straight into a plan. The skipped lines are the point —
|
||||
/// an include or an editable install means the file asks for something PipDock will not do, and
|
||||
/// the user has to see that before a preview claims to represent their file.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-SYS-002` when the file cannot be read.
|
||||
#[tauri::command]
|
||||
pub async fn requirements_read(
|
||||
path: String,
|
||||
) -> Wire<pipdock_core::requirements::ParsedRequirements> {
|
||||
let text = std::fs::read_to_string(&path).map_err(|e| {
|
||||
PdError::new(
|
||||
pipdock_core::errors::Code::SysDiskFull,
|
||||
format!("read {path}: {e}"),
|
||||
)
|
||||
})?;
|
||||
Ok(pipdock_core::requirements::parse(&text))
|
||||
}
|
||||
|
||||
/// What PipDock has written to disk — PRD P1-4.
|
||||
///
|
||||
/// # Errors
|
||||
/// Never fails as a whole; an unreadable path reports zero bytes.
|
||||
#[tauri::command]
|
||||
pub async fn cache_usage(state: tauri::State<'_, AppState>) -> Wire<pipdock_core::cache::Usage> {
|
||||
Ok(pipdock_core::cache::usage(&state.app_data)?)
|
||||
}
|
||||
|
||||
/// Remove one cache target, resolving to the bytes freed.
|
||||
///
|
||||
/// Takes a `Target` enum, **never a path** — `cache::clear` is the only thing that turns one into
|
||||
/// a location, and it checks the result is inside the data root by canonicalized prefix before
|
||||
/// removing anything. This is the first delete-a-tree in the application, so the surface it is
|
||||
/// reachable through is deliberately as narrow as an enum.
|
||||
///
|
||||
/// `index.db` is not a target: it holds settings, pins and the consent record as well as the
|
||||
/// package index, and "clear the cache" must never take a user's pins.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-PRM-002` when something holds the files open — a tools venv whose Python is still running
|
||||
/// is the ordinary way to hit this on Windows. `PD-INT-001` if the containment check ever fails,
|
||||
/// which would be a bug.
|
||||
#[tauri::command]
|
||||
pub async fn cache_clear(
|
||||
state: tauri::State<'_, AppState>,
|
||||
target: pipdock_core::cache::Target,
|
||||
) -> Wire<u64> {
|
||||
Ok(pipdock_core::cache::clear(&state.app_data, target)?)
|
||||
}
|
||||
|
||||
/// What `index_search` returns.
|
||||
///
|
||||
/// A struct rather than a bare `Hit[]` because "no results" and "the index is not loaded yet" are
|
||||
@@ -882,8 +1010,13 @@ pub async fn health_run(
|
||||
let opts = health::RunOptions::default();
|
||||
|
||||
let outcome = async {
|
||||
let sync_needed = health::needs_sync(&tools_dir)?.is_needed();
|
||||
let total = health::run_steps(&opts) + if sync_needed { health::SYNC_STEPS } else { 0 };
|
||||
let sync_needed = health::needs_sync(&tools_dir, health::HEALTH_TOOLS)?.is_needed();
|
||||
let total = health::run_steps(&opts)
|
||||
+ if sync_needed {
|
||||
health::sync_steps(health::HEALTH_TOOLS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
forward_progress(&app, "health-progress", rx);
|
||||
@@ -891,14 +1024,18 @@ pub async fn health_run(
|
||||
|
||||
if sync_needed {
|
||||
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
|
||||
health::sync_tools_venv(&tools_dir, &python, &sink).await?;
|
||||
health::sync_tools_venv(&tools_dir, &python, health::HEALTH_TOOLS, &sink).await?;
|
||||
}
|
||||
health::run_tools(
|
||||
&tools_dir,
|
||||
&project,
|
||||
&env,
|
||||
&opts,
|
||||
&sink.at(if sync_needed { health::SYNC_STEPS } else { 0 }),
|
||||
&sink.at(if sync_needed {
|
||||
health::sync_steps(health::HEALTH_TOOLS)
|
||||
} else {
|
||||
0
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -940,6 +1077,124 @@ pub async fn health_run(
|
||||
}
|
||||
}
|
||||
|
||||
/// Audit an environment against the PyPI advisory database — PRD P1-1, SECURITY §6.
|
||||
///
|
||||
/// Syncs the audit venv on first use, exactly as [`health_run`] syncs Code Health's: the implicit
|
||||
/// sync belongs to the command that needs it, or the frontend would have two ways to reach one
|
||||
/// operation. It is a *different* venv, and that is the point — a CPython with no `msgpack` wheel
|
||||
/// fails this and leaves Code Health working.
|
||||
///
|
||||
/// **The freeze is taken here, through the configured engine.** Which engine matters: pip is
|
||||
/// invoked with `--all` and includes pip and setuptools, uv has no such flag and omits them, so
|
||||
/// the engine selection changes what is audited. The store guard is read and dropped before any
|
||||
/// subprocess, per [`pkg_outdated`]'s note.
|
||||
///
|
||||
/// **Cancellable, unlike `health_run`.** P4 deferred that for Code Health on a measurement of
|
||||
/// 1.3 s; an audit measures 18-68 s, which is long enough that stopping one is an ordinary thing
|
||||
/// to want. The token is registered beside the slot rather than inside it, so [`audit_cancel`] can
|
||||
/// reach a run the slot no longer owns.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-RES-003` when an audit is already running; `PD-ENG-001` or `PD-ENV-*` when the freeze cannot
|
||||
/// be taken; `PD-NET-011` when the audit venv cannot be bootstrapped. **pip-audit failing is not an
|
||||
/// error** — it lands in `AuditReport.problems` and the report still returns.
|
||||
#[tauri::command]
|
||||
pub async fn audit_run(
|
||||
app: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
env: PyEnv,
|
||||
) -> Wire<pipdock_core::audit::AuditReport> {
|
||||
use pipdock_core::{audit, health};
|
||||
|
||||
state.audit.claim().await?;
|
||||
|
||||
let dir = health::audit_dir(&state.app_data);
|
||||
let outcome = async {
|
||||
let engine = {
|
||||
let store = state.store.lock().await;
|
||||
engine::for_id(settings::load(&store)?.engine)
|
||||
};
|
||||
let freeze = engine.freeze(&env).await?;
|
||||
|
||||
let sync_needed = health::needs_sync(&dir, health::AUDIT_TOOLS)?.is_needed();
|
||||
let synced = if sync_needed {
|
||||
health::sync_steps(health::AUDIT_TOOLS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
forward_progress(&app, "audit-progress", rx);
|
||||
let token = CancellationToken::new();
|
||||
state.audit.set_cancel(Some(token.clone()));
|
||||
let sink = engine::ProgressSink::new(tx, audit::AUDIT_STEPS + synced, token);
|
||||
|
||||
if sync_needed {
|
||||
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
|
||||
health::sync_tools_venv(&dir, &python, health::AUDIT_TOOLS, &sink).await?;
|
||||
}
|
||||
audit::run(&dir, &env, &freeze, &sink.at(synced)).await
|
||||
}
|
||||
.await;
|
||||
|
||||
// Released on both paths, and the token cleared with it: a token left registered would let the
|
||||
// *next* `audit_cancel` stop a run that had not started, which is S5's wedge bug wearing a
|
||||
// different hat.
|
||||
state.audit.release().await;
|
||||
state.audit.set_cancel(None);
|
||||
Ok(outcome?)
|
||||
}
|
||||
|
||||
/// Write a finished audit as Markdown **and** JSON beside a user-chosen path, returning both.
|
||||
///
|
||||
/// `health_save_report`'s shape exactly, including its two reasons. Rust-side rather than through
|
||||
/// a filesystem capability: `dialog:allow-save` lets the webview *ask* for a path and nothing more.
|
||||
/// And it takes the report from the frontend rather than a parked session, because what the user
|
||||
/// asked to save is what is on their screen. Nothing is executed from it.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-SYS-002` when either file cannot be written, `PD-INT-001` if the report cannot be
|
||||
/// serialized.
|
||||
#[tauri::command]
|
||||
pub async fn audit_save_report(
|
||||
report: pipdock_core::audit::AuditReport,
|
||||
path: String,
|
||||
) -> Wire<Vec<String>> {
|
||||
let base = std::path::PathBuf::from(&path);
|
||||
let md = base.with_extension("md");
|
||||
let json = base.with_extension("json");
|
||||
|
||||
let body = pipdock_core::audit::markdown(&report);
|
||||
let document = serde_json::to_string_pretty(&report).map_err(|e| {
|
||||
PdError::new(
|
||||
pipdock_core::errors::Code::IntUnexpected,
|
||||
format!("serialize report: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
for (target, contents) in [(&md, body), (&json, document)] {
|
||||
std::fs::write(target, contents).map_err(|e| {
|
||||
PdError::new(
|
||||
pipdock_core::errors::Code::SysDiskFull,
|
||||
format!("write {}: {e}", target.display()),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Ok(vec![md.display().to_string(), json.display().to_string()])
|
||||
}
|
||||
|
||||
/// Stop a running audit, and say whether there was one.
|
||||
///
|
||||
/// Shaped like [`plan_cancel`] rather than returning `()`: "nothing was running" is a real answer
|
||||
/// and the caller should not have to guess it from a silent success.
|
||||
///
|
||||
/// # Errors
|
||||
/// Never fails.
|
||||
#[tauri::command]
|
||||
pub async fn audit_cancel(state: tauri::State<'_, AppState>) -> Wire<bool> {
|
||||
Ok(state.audit.stop().await)
|
||||
}
|
||||
|
||||
/// Whether the parked report's project has uncommitted work, so the confirm can say so.
|
||||
///
|
||||
/// A command of its own rather than a field on `HealthReport`, because the answer expires: the
|
||||
|
||||
+59
-1
@@ -70,6 +70,11 @@ pub fn run() {
|
||||
commands::pin_list,
|
||||
commands::pin_add,
|
||||
commands::pin_remove,
|
||||
commands::pin_suggestions,
|
||||
commands::env_export,
|
||||
commands::requirements_read,
|
||||
commands::cache_usage,
|
||||
commands::cache_clear,
|
||||
commands::plan_resolve,
|
||||
commands::plan_decide,
|
||||
commands::plan_execute,
|
||||
@@ -87,6 +92,9 @@ pub fn run() {
|
||||
commands::health_dirty,
|
||||
commands::health_fix,
|
||||
commands::health_run,
|
||||
commands::audit_run,
|
||||
commands::audit_cancel,
|
||||
commands::audit_save_report,
|
||||
commands::health_save_report,
|
||||
commands::index_search,
|
||||
commands::index_refresh,
|
||||
@@ -140,6 +148,56 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The commands ARCHITECTURE §7's table documents.
|
||||
///
|
||||
/// §7 opens with *"A command that is not listed here does not exist; adding one means amending
|
||||
/// this section in the same commit"*, and the whole 1.1.0 P1 wave broke that rule — five
|
||||
/// commands landed that the table never gained. The three tests below police `lib.rs`,
|
||||
/// `COMMANDS` and `NOT_YET`; not one of them read the document making the promise, and the
|
||||
/// assertion message of the second even claimed it did. Parsed rather than duplicated, for the
|
||||
/// reason [`registered`] gives.
|
||||
fn documented() -> Vec<String> {
|
||||
let src = include_str!("../../docs/ARCHITECTURE.md");
|
||||
let start = src
|
||||
.find("| Command | Returns | Purpose |")
|
||||
.expect("ARCHITECTURE §7's command table exists");
|
||||
src[start..]
|
||||
.lines()
|
||||
.skip(2)
|
||||
.take_while(|l| l.starts_with("| `"))
|
||||
.filter_map(|l| l.strip_prefix("| `"))
|
||||
.filter_map(|l| l.split(0x60 as char).next())
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_is_in_the_architecture_table() {
|
||||
// Both directions, because a table row for a command nobody registered is the same lie as
|
||||
// a command nobody documented — it just fails later, when someone builds against it.
|
||||
let documented = documented();
|
||||
let mut expected = registered();
|
||||
expected.extend(super::NOT_YET.iter().map(|(n, _)| (*n).to_owned()));
|
||||
|
||||
let undocumented: Vec<&String> = expected
|
||||
.iter()
|
||||
.filter(|c| !documented.contains(c))
|
||||
.collect();
|
||||
assert!(
|
||||
undocumented.is_empty(),
|
||||
"registered or owed but absent from ARCHITECTURE §7: {undocumented:?}"
|
||||
);
|
||||
|
||||
let ghosts: Vec<&String> = documented
|
||||
.iter()
|
||||
.filter(|c| !expected.contains(c))
|
||||
.collect();
|
||||
assert!(
|
||||
ghosts.is_empty(),
|
||||
"ARCHITECTURE §7 documents commands that do not exist: {ghosts:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_declared_command_is_registered_or_owed() {
|
||||
// The failure this catches: `COMMANDS` listed 32 names while 19 were registered, so a
|
||||
@@ -174,7 +232,7 @@ mod tests {
|
||||
.collect();
|
||||
assert!(
|
||||
undeclared.is_empty(),
|
||||
"registered but missing from COMMANDS and ARCHITECTURE §7: {undeclared:?}"
|
||||
"registered but missing from COMMANDS: {undeclared:?}"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -424,6 +424,18 @@ pub struct AppState {
|
||||
/// the user's consent against a report **the server** is holding — the same shape `ack_ok`
|
||||
/// checks a `GuardAck` against the guard that produced it. Typed now so P5 does not redo it.
|
||||
pub health: Sessions<HealthSession>,
|
||||
|
||||
/// The Security tab's slot — PRD P1-1.
|
||||
///
|
||||
/// `Sessions<()>` because nothing is parked: an audit produces a report and hands it straight
|
||||
/// back, with no second call that consumes it the way `health_fix` consumes a `HealthSession`.
|
||||
/// What it is here for is the **token**, which lives beside the slot rather than in it so
|
||||
/// `audit_cancel` can reach a run the slot no longer owns.
|
||||
///
|
||||
/// Its own slot rather than `health`'s, for the reason that one is not `sessions`: an audit
|
||||
/// touches no environment, so refusing it while Code Health runs would be a lock with no
|
||||
/// invariant behind it.
|
||||
pub audit: Sessions<()>,
|
||||
/// Engine output from the current plan, for the bug-report deep link.
|
||||
pub log: std::sync::Arc<LogRing>,
|
||||
}
|
||||
@@ -442,6 +454,7 @@ impl AppState {
|
||||
index: std::sync::Mutex::new(IndexSlot::Cold),
|
||||
sessions: Sessions::default(),
|
||||
health: Sessions::default(),
|
||||
audit: Sessions::default(),
|
||||
log: std::sync::Arc::new(LogRing::default()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PipDock",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"identifier": "com.skullmute.pipdock",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
deptry==0.25.1
|
||||
vulture==2.16
|
||||
ruff==0.16.2
|
||||
ruff==0.16.3
|
||||
|
||||
# P1 (Security tab, PRD P1-1). Pinned now so spike SP-4 has something concrete to invoke while
|
||||
# it settles the foreign-environment audit flags.
|
||||
|
||||
+30
-1
@@ -1,9 +1,10 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { NAV_KEYS } from '@/components/nav'
|
||||
import { PdLegalGate } from '@/components/PdLegalGate'
|
||||
import { PdOfflineBanner } from '@/components/PdOfflineBanner'
|
||||
import { PdPalette } from '@/components/PdPalette'
|
||||
import { PdSidebar } from '@/components/PdSidebar'
|
||||
import { PdStatusLine } from '@/components/PdStatusLine'
|
||||
import { PdUninstallDialog } from '@/components/PdUninstallDialog'
|
||||
@@ -15,6 +16,7 @@ import { PdPackages } from '@/screens/PdPackages'
|
||||
import { PdPins } from '@/screens/PdPins'
|
||||
import { PdPlanPanel } from '@/screens/PdPlanPanel'
|
||||
import { PdSearch } from '@/screens/PdSearch'
|
||||
import { PdSecurity } from '@/screens/PdSecurity'
|
||||
import { PdSettings } from '@/screens/PdSettings'
|
||||
import { PANEL_PHASES } from '@/stores/plan'
|
||||
import { useEnvStore, useLegalStore, usePlanStore, useUiStore } from '@/stores'
|
||||
@@ -31,6 +33,7 @@ const SCREENS: Partial<Record<NavKey, React.ReactNode>> = {
|
||||
search: <PdSearch />,
|
||||
pins: <PdPins />,
|
||||
health: <PdHealth />,
|
||||
security: <PdSecurity />,
|
||||
settings: <PdSettings />,
|
||||
about: <PdAbout />,
|
||||
}
|
||||
@@ -65,6 +68,8 @@ export function App() {
|
||||
const resetPlan = usePlanStore((s) => s.reset)
|
||||
const guardOpen = planPhase === 'guard' && guard !== null
|
||||
const mainRef = useRef<HTMLElement>(null)
|
||||
// Shell state, like `nav` — but local, because nothing outside this component reads it.
|
||||
const [paletteOpen, setPaletteOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
void checkConsent()
|
||||
@@ -99,6 +104,20 @@ export function App() {
|
||||
// guarded neither. The sidebar was disabled and the panel kept rendering, so nothing looked
|
||||
// wrong until the plan finished and dropped the user on a tab they never chose.
|
||||
if (guardOpen || PANEL_PHASES.has(planPhase)) return
|
||||
|
||||
// UI-SPEC §1's Ctrl+K palette. Before the Ctrl+digit branch below, which parses `e.key` as a
|
||||
// number — `'k'` becomes NaN and `NAV_KEYS[NaN]` is undefined, so this was a silent no-op
|
||||
// rather than a collision. `toLowerCase`, because Shift+Ctrl+K reports `'K'`.
|
||||
//
|
||||
// It inherits both refusals above by construction: this line is unreachable while the legal
|
||||
// gate is up, while the guard dialog is open, or while a plan owns the content area — which
|
||||
// is the point. A palette that can navigate during an execution is the defect S3 shipped,
|
||||
// reached through a different door.
|
||||
if (e.ctrlKey && !e.altKey && !e.metaKey && e.key.toLowerCase() === 'k') {
|
||||
e.preventDefault()
|
||||
setPaletteOpen((open) => !open)
|
||||
return
|
||||
}
|
||||
// UI-SPEC §8: `/` focuses search. Guarded against text fields, or it would be impossible to
|
||||
// type a slash into a version specifier.
|
||||
const target = e.target as HTMLElement | null
|
||||
@@ -174,6 +193,16 @@ export function App() {
|
||||
|
||||
<PdStatusLine />
|
||||
|
||||
{/* Outside <main> for `PdUninstallDialog`'s reason: it opens over whatever screen is
|
||||
showing, and mounting it inside one would tie it to that screen's lifetime. */}
|
||||
{paletteOpen ? (
|
||||
<PdPalette
|
||||
onClose={() => {
|
||||
setPaletteOpen(false)
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{/* Outside <main>, because the dialog opens *over* the table the user selected from — they
|
||||
need to still see what they picked while deciding. Mounted here rather than in the row
|
||||
that opened it: `PdPackageTable` renders a ~25-row window, so scrolling would unmount
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* The Security tab's list — PRD P1-1.
|
||||
*
|
||||
* Fed from `audit_report.json`, which is **computed** by `fixtures::audit_report` running the real
|
||||
* `audit::parse` over a real pip-audit capture of the SP-4 environment. Slice 0 is why: a
|
||||
* hand-written fixture that matches the documentation while the code does not makes a test assert
|
||||
* the right thing and prove the wrong one. Dedup and the fixable-first order are exactly what these
|
||||
* assertions read, and both live in Rust.
|
||||
*
|
||||
* The capture has two packages on purpose — one cannot show grouping.
|
||||
*/
|
||||
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { ADVISORY_ROWS_SHOWN, PdAuditReport } from '@/components/PdAuditReport'
|
||||
import type { AuditReport } from '@/ipc'
|
||||
import auditFixture from '@/test/fixtures/audit_report.json'
|
||||
|
||||
const REPORT = auditFixture as AuditReport
|
||||
const ADVISORIES = REPORT.advisories ?? []
|
||||
|
||||
const group = (pkg: string) => {
|
||||
const el = document.querySelector(`[data-pkg="${pkg}"]`)
|
||||
if (el === null) throw new Error(`no group rendered for ${pkg}`)
|
||||
return el as HTMLElement
|
||||
}
|
||||
|
||||
describe('PdAuditReport', () => {
|
||||
it('groups advisories under the package they are against', () => {
|
||||
render(<PdAuditReport report={REPORT} />)
|
||||
|
||||
// Thirteen deduplicated from sixteen rows, across the two packages the environment has.
|
||||
expect(ADVISORIES).toHaveLength(13)
|
||||
expect(within(group('urllib3')).getAllByRole('listitem')).toHaveLength(8)
|
||||
expect(within(group('pip')).getAllByRole('listitem')).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('reports pip itself, because the freeze is taken with --all', () => {
|
||||
// Not incidental. `Engine::freeze` passes `--all` on pip and uv has no such flag, so the
|
||||
// configured engine changes what is audited — and pip being in its own results is the most
|
||||
// visible instance of that.
|
||||
render(<PdAuditReport report={REPORT} />)
|
||||
|
||||
expect(within(group('pip')).getByText(/^pip 25\.0\.1/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the CVE from the aliases, never as the id', () => {
|
||||
// PRD P1-1 says "known CVEs"; pip-audit's primary id is a PYSEC under the default service, so
|
||||
// a screen that read `id` alone would never show a CVE at all.
|
||||
render(<PdAuditReport report={REPORT} />)
|
||||
|
||||
const row = screen.getByText('PYSEC-2023-192').closest('li')
|
||||
expect(row).not.toBeNull()
|
||||
expect(within(row as HTMLElement).getByText(/CVE-2023-43804/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('says "no fix" rather than leaving the badge blank', () => {
|
||||
// An advisory nothing upgrades away is the one worth reading the description for, so the
|
||||
// absence is stated. Built here because the captured environment happens to have a fix for
|
||||
// everything — asserting on a state the fixture cannot reach would be asserting on nothing.
|
||||
const first = ADVISORIES[0]
|
||||
if (first === undefined) throw new Error('the fixture must carry an advisory')
|
||||
const unfixable: AuditReport = {
|
||||
...REPORT,
|
||||
advisories: [{ ...first, fixVersions: [] }],
|
||||
}
|
||||
render(<PdAuditReport report={unfixable} />)
|
||||
|
||||
expect(screen.getByText('no fix')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('links every advisory to its OSV entry', () => {
|
||||
render(<PdAuditReport report={REPORT} />)
|
||||
|
||||
expect(screen.getAllByRole('button', { name: 'OSV entry' })).toHaveLength(13)
|
||||
expect(ADVISORIES.every((a) => a.url?.startsWith('https://osv.dev/vulnerability/'))).toBe(true)
|
||||
})
|
||||
|
||||
it('caps the list without misreporting the total', () => {
|
||||
// The `RUFF_ROWS_SHOWN` guarantee: the count comes from the report, never from the rows on
|
||||
// screen, so a capped view cannot tell the user there are fewer problems than there are.
|
||||
render(<PdAuditReport report={REPORT} rowsShown={3} />)
|
||||
|
||||
expect(screen.getAllByRole('listitem')).toHaveLength(3)
|
||||
expect(screen.getByText(/13 advisories across 2 of 2 packages/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/10 more advisories are not shown/)).toBeInTheDocument()
|
||||
expect(ADVISORY_ROWS_SHOWN).toBe(200)
|
||||
})
|
||||
|
||||
it('says nothing was found only when a report says so', () => {
|
||||
// Reachable only with a report in hand. "Nothing was found" and "nothing has run" are
|
||||
// different claims, and the screen — not this component — owns the second.
|
||||
render(<PdAuditReport report={{ ...REPORT, advisories: [] }} />)
|
||||
|
||||
expect(screen.getByText(/No known advisories against 2 packages/)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('listitem')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* The Security tab's findings — PRD P1-1, SECURITY §6.
|
||||
*
|
||||
* Prop-driven and store-free, the division `PdHealthReport` uses: the screen owns the run, the
|
||||
* errors and the progress, this owns the list. That is what lets it be tested against a generated
|
||||
* fixture with no store at all.
|
||||
*
|
||||
* **Everything pip-audit said is rendered verbatim.** There is no PipDock copy per advisory id and
|
||||
* no rewritten description — I18N §2 keeps ids, versions and tool output out of the catalogs.
|
||||
*
|
||||
* Two things it deliberately does not do:
|
||||
*
|
||||
* 1. **It does not sort.** `audit::sort_advisories` already ordered them — package, then whether
|
||||
* anything fixes it, then id — and a second ordering in the frontend is the drift `pins::suggest`
|
||||
* exists in Rust to prevent.
|
||||
* 2. **It does not show a severity.** pip-audit has no such field under either vulnerability
|
||||
* service, so PRD P1-1's "severity-sorted" describes something that has never existed. Deriving
|
||||
* one from the id's year or the prose would be a number PipDock invented, shown beside real ones.
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdBadge } from '@/components/PdBadge'
|
||||
import { PdEmptyState } from '@/components/PdEmptyState'
|
||||
import { useOpenExternal } from '@/components/useOpenExternal'
|
||||
import type { Advisory, AuditReport } from '@/ipc'
|
||||
|
||||
/**
|
||||
* How many advisory rows to render.
|
||||
*
|
||||
* The `RUFF_ROWS_SHOWN` pattern, for the same reason and with the same guarantee: **the counts
|
||||
* always come from the report**, so a capped list can never misreport a total. Two hundred rather
|
||||
* than ruff's five hundred because each row here carries a description paragraph.
|
||||
*/
|
||||
export const ADVISORY_ROWS_SHOWN = 200
|
||||
|
||||
interface PdAuditReportProps {
|
||||
report: AuditReport
|
||||
/** Overridable so a test need not build two hundred rows. */
|
||||
rowsShown?: number
|
||||
}
|
||||
|
||||
/** One advisory. */
|
||||
function AdvisoryRow({ advisory }: { advisory: Advisory }) {
|
||||
const { t } = useTranslation()
|
||||
const { open, failed } = useOpenExternal()
|
||||
const fixed = advisory.fixVersions ?? []
|
||||
|
||||
return (
|
||||
<li className="rounded-pd border-l-2 border-warn bg-surface p-3">
|
||||
<div className="flex flex-wrap items-baseline gap-2">
|
||||
<code className="font-mono text-data">{advisory.id}</code>
|
||||
{fixed.length === 0 ? (
|
||||
// The row worth reading the description for: nothing to upgrade to. Stated rather than
|
||||
// left blank, which would read as "no information" instead of "no fix".
|
||||
<PdBadge tone="danger" label={t('security.noFix')} />
|
||||
) : (
|
||||
<PdBadge tone="info" label={t('security.fixedIn', { versions: fixed.join(', ') })} />
|
||||
)}
|
||||
{advisory.url === undefined || advisory.url === null ? null : (
|
||||
<button
|
||||
type="button"
|
||||
className="text-data text-accent underline"
|
||||
onClick={() => {
|
||||
open(advisory.url ?? '')
|
||||
}}
|
||||
>
|
||||
{t('security.osv')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(advisory.aliases ?? []).length === 0 ? null : (
|
||||
// The CVE lives here, never in `id` — PRD P1-1 says "known CVEs" and pip-audit's primary
|
||||
// id is a PYSEC under the default service.
|
||||
<p className="mt-1 font-mono text-data text-text-dim">{(advisory.aliases ?? []).join(', ')}</p>
|
||||
)}
|
||||
|
||||
{advisory.description === '' ? null : (
|
||||
<p className="mt-1 text-text-dim">{advisory.description}</p>
|
||||
)}
|
||||
|
||||
{failed ? (
|
||||
// A rejected `opener:allow-open-url` resolves to nothing happening. Silence is the failure
|
||||
// mode SECURITY §4 exists to name, so it is said out loud on the row that tried.
|
||||
<p role="alert" className="mt-1 text-data text-danger">
|
||||
{t('security.linkFailed')}
|
||||
</p>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export function PdAuditReport({ report, rowsShown = ADVISORY_ROWS_SHOWN }: PdAuditReportProps) {
|
||||
const { t } = useTranslation()
|
||||
// Optional on the wire because `#[serde(default)]` makes it so; never absent in practice.
|
||||
const advisories = report.advisories ?? []
|
||||
|
||||
if (advisories.length === 0) {
|
||||
// Only reachable with a report in hand, so this really is "nothing was found" rather than
|
||||
// "nothing has run" — the distinction P4 shipped the wrong side of once. The screen owns the
|
||||
// other case and never routes it here.
|
||||
return (
|
||||
<PdEmptyState
|
||||
message={t('security.clean', { count: report.packages })}
|
||||
hint={t('security.cleanHint', { version: report.toolVersion })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const shown = advisories.slice(0, rowsShown)
|
||||
const remaining = advisories.length - shown.length
|
||||
const packages = new Set(advisories.map((a) => a.pkg)).size
|
||||
|
||||
// Grouped by package as they arrive: core already sorted by package, so a group boundary is just
|
||||
// a change of name. Building a map here would re-impose an order on rows that already have one.
|
||||
const groups: { pkg: string; version: string; rows: Advisory[] }[] = []
|
||||
for (const advisory of shown) {
|
||||
const last = groups.at(-1)
|
||||
if (last?.pkg === advisory.pkg) last.rows.push(advisory)
|
||||
else groups.push({ pkg: advisory.pkg, version: advisory.version, rows: [advisory] })
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label={t('nav.security')}>
|
||||
<p className="text-text-dim">
|
||||
{t('security.summary', {
|
||||
count: advisories.length,
|
||||
packages,
|
||||
total: report.packages,
|
||||
})}
|
||||
</p>
|
||||
|
||||
{groups.map((group) => (
|
||||
<div key={group.pkg} className="mt-4" data-pkg={group.pkg}>
|
||||
<h2 className="font-mono text-data">
|
||||
{`${group.pkg} ${group.version}`}
|
||||
<span className="ml-2 text-text-dim">{`(${String(group.rows.length)})`}</span>
|
||||
</h2>
|
||||
<ul className="mt-1 space-y-1">
|
||||
{group.rows.map((advisory) => (
|
||||
<AdvisoryRow key={`${advisory.pkg}-${advisory.id}`} advisory={advisory} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{remaining > 0 ? (
|
||||
<p className="mt-4 text-text-dim">{t('security.more', { count: remaining })}</p>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* What PipDock has written to disk, and what can be removed — PRD P1-4.
|
||||
*
|
||||
* **Three artefacts, not four.** There are no log files: `LOG_RETENTION_DAYS` has never had a
|
||||
* reader, the only log is the in-memory ring buffer behind *Report bug*, and `logs_tail` is still
|
||||
* owed. A "logs — 0 B" row would be inventing a thing that does not exist.
|
||||
*
|
||||
* **`index.db` has no Clear button**, and its row says why. It holds the package index *and* the
|
||||
* settings *and* the pin list *and* the legal-consent record in one SQLite file, so a "clear the
|
||||
* cache" that removed it would take a user's pins with it — the same class of surprise the privacy
|
||||
* policy had to be corrected for. Its size is still shown, because a report that omitted the
|
||||
* largest thing on disk would be answering a different question than the one the user asked.
|
||||
*
|
||||
* Clearing is confirmed through `PdDialog`, which puts Cancel first and focuses it (UI-SPEC §7).
|
||||
* Removing snapshots is not reversible and the confirm says exactly what is lost.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdDialog } from '@/components/PdDialog'
|
||||
import { PdErrorRow } from '@/components/PdErrorRow'
|
||||
import { cacheClear, cacheUsage, type CacheTarget, type CacheUsage, type PdError } from '@/ipc'
|
||||
import { formatBytes } from '@/screens/rows'
|
||||
import { asPdError, useSettingsStore } from '@/stores'
|
||||
|
||||
/** The rows that can be cleared, in the order they are offered. */
|
||||
const CLEARABLE: readonly CacheTarget[] = ['snapshots', 'tools', 'audit']
|
||||
|
||||
export function PdCacheUsage() {
|
||||
const { t } = useTranslation()
|
||||
const locale = useSettingsStore((s) => s.locale)
|
||||
const [usage, setUsage] = useState<CacheUsage | null>(null)
|
||||
const [error, setError] = useState<PdError | null>(null)
|
||||
const [confirming, setConfirming] = useState<CacheTarget | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
setUsage(await cacheUsage())
|
||||
setError(null)
|
||||
} catch (e) {
|
||||
setError(asPdError(e))
|
||||
}
|
||||
}
|
||||
|
||||
// Once on mount — the numbers only move when PipDock itself writes, and every path that does is
|
||||
// a deliberate action the user just took elsewhere. The promise chain is inline rather than a
|
||||
// call to `load` because `react-hooks/set-state-in-effect` cannot see through an async function,
|
||||
// and the same shape is what `useAppInfo` uses.
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
void cacheUsage().then(
|
||||
(u) => {
|
||||
if (alive) setUsage(u)
|
||||
},
|
||||
(e: unknown) => {
|
||||
if (alive) setError(asPdError(e))
|
||||
},
|
||||
)
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
// A lookup rather than a ternary chain: the chain's last branch was a hand-maintained negation
|
||||
// of every case above it, so adding `audit` as a third target would have silently reported the
|
||||
// tools venv's size on the audit row.
|
||||
const entryOf = (target: CacheTarget) =>
|
||||
({ snapshots: usage?.snapshots, tools: usage?.tools, audit: usage?.audit })[target]
|
||||
|
||||
const doClear = async (target: CacheTarget) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await cacheClear(target)
|
||||
setError(null)
|
||||
await load()
|
||||
} catch (e) {
|
||||
setError(asPdError(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
setConfirming(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<fieldset className="mt-6">
|
||||
<legend className="text-text-dim">{t('cache.title')}</legend>
|
||||
<p className="mt-1 max-w-2xl text-data text-text-dim">{t('cache.intro')}</p>
|
||||
|
||||
{error !== null ? (
|
||||
<div className="mt-2">
|
||||
<PdErrorRow error={error} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{usage === null ? null : (
|
||||
<ul className="mt-2 max-w-2xl space-y-1">
|
||||
<li className="flex flex-wrap items-baseline gap-x-3 rounded-pd border border-border bg-surface px-3 py-1.5">
|
||||
<span className="min-w-0 flex-1 text-data">{t('cache.database')}</span>
|
||||
<code className="font-mono text-data text-text-dim">
|
||||
{formatBytes(usage.database.bytes, locale)}
|
||||
</code>
|
||||
{/* No button, and the reason is on screen rather than only in a comment. */}
|
||||
<span className="w-full text-data text-text-dim">{t('cache.databaseWhy')}</span>
|
||||
</li>
|
||||
|
||||
{CLEARABLE.map((target) => {
|
||||
const entry = entryOf(target)
|
||||
if (entry === undefined) return null
|
||||
return (
|
||||
<li
|
||||
key={target}
|
||||
data-cache={target}
|
||||
className="flex flex-wrap items-baseline gap-x-3 rounded-pd border border-border bg-surface px-3 py-1.5"
|
||||
>
|
||||
<span className="min-w-0 flex-1 text-data">
|
||||
{t(`cache.${target}`)}
|
||||
{target === 'snapshots' && usage.snapshotCount > 0 ? (
|
||||
<span className="ml-1 text-text-dim">
|
||||
{t('cache.snapshotCount', { count: usage.snapshotCount })}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<code className="font-mono text-data text-text-dim">
|
||||
{formatBytes(entry.bytes, locale)}
|
||||
</code>
|
||||
<button
|
||||
type="button"
|
||||
// Nothing there is not an error, so the button simply has nothing to do.
|
||||
disabled={!entry.exists || busy}
|
||||
onClick={() => {
|
||||
setConfirming(target)
|
||||
}}
|
||||
data-action="clear-cache"
|
||||
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim disabled:opacity-40"
|
||||
>
|
||||
{t('cache.clear')}
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{confirming !== null ? (
|
||||
<PdDialog
|
||||
label={t(`cache.${confirming}`)}
|
||||
title={t('cache.confirmTitle')}
|
||||
cancelLabel={t('actions.cancel')}
|
||||
busy={busy}
|
||||
onCancel={() => {
|
||||
setConfirming(null)
|
||||
}}
|
||||
actions={
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
void doClear(confirming)
|
||||
}}
|
||||
data-action="confirm-clear-cache"
|
||||
className="rounded-pd border border-danger px-3 py-1 text-data text-danger disabled:opacity-40"
|
||||
>
|
||||
{t('cache.clear')}
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<p>{t(`cache.confirm.${confirming}`)}</p>
|
||||
</PdDialog>
|
||||
) : null}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* The held-back row — UI-SPEC §4's three-way control, and the blocker sentence under it.
|
||||
*
|
||||
* **Why this file exists.** For two releases the preview rendered `scipy requires scipy 1.11.4
|
||||
* requires numpy <1.28.0,>=1.21.6`: `graph::blockers_for` built a whole English sentence into
|
||||
* `Blocker.constraint` and this component wrapped it in `plan.blocker` a second time. Neither
|
||||
* suite could see it. `PdPreviewDiff.test.tsx` asserted the *right* sentence against a fixture
|
||||
* whose blockers were hand-written to the shape `Blocker`'s own doc describes — a shape core had
|
||||
* stopped producing — and this component had no test of its own at all. The fixture is computed
|
||||
* from the real graph now (`fixtures::numpy_blockers`), so the two cannot drift apart again.
|
||||
*
|
||||
* The blockers here therefore come from that fixture rather than from literals, for the reason
|
||||
* `PdUninstallDialog.test.tsx` gives about `GuardReport`.
|
||||
*/
|
||||
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { PdConflictRow } from '@/components/PdConflictRow'
|
||||
import type { Blocker, FlowStep } from '@/ipc'
|
||||
import flowStep from '@/test/fixtures/flow_step.json'
|
||||
|
||||
const STEP = flowStep as FlowStep
|
||||
if (!('report' in STEP)) throw new Error('the fixture must be a step carrying a report')
|
||||
|
||||
/** The computed blockers holding `numpy` back: `pandas 2.1.4` and `scipy 1.11.4`. */
|
||||
const BLOCKERS = STEP.report.heldBack?.[0]?.blockers ?? []
|
||||
|
||||
function setup(blockers: readonly Blocker[], impossible = false) {
|
||||
const onChoose = vi.fn()
|
||||
render(
|
||||
<ul>
|
||||
<PdConflictRow
|
||||
pkg="numpy"
|
||||
resolved="1.26.4"
|
||||
latest="2.5.1"
|
||||
blockers={blockers}
|
||||
impossible={impossible}
|
||||
value={undefined}
|
||||
onChoose={onChoose}
|
||||
/>
|
||||
</ul>,
|
||||
)
|
||||
return { onChoose }
|
||||
}
|
||||
|
||||
describe('PdConflictRow', () => {
|
||||
it('names each blocker once, with its version and its constraint', () => {
|
||||
// The defect this file was written for. `getByText` is exact by default, so a doubled
|
||||
// dependent name fails here rather than merely looking wrong.
|
||||
setup(BLOCKERS)
|
||||
|
||||
expect(screen.getByText('pandas 2.1.4 requires numpy<2,>=1.26.0')).toBeInTheDocument()
|
||||
expect(screen.getByText('scipy 1.11.4 requires numpy<1.28.0,>=1.21.6')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/requires.*requires/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('drops the version clause when the probe did not know one', () => {
|
||||
setup([{ by: 'scipy', constraint: 'numpy<1.28.0,>=1.21.6' }])
|
||||
|
||||
expect(screen.getByText('scipy requires numpy<1.28.0,>=1.21.6')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an unattributed constraint verbatim rather than inventing a culprit', () => {
|
||||
// ARCHITECTURE §3: if attribution is ambiguous, show the constraint without a culprit. This
|
||||
// is also the shape `PdPreviewDiff` synthesizes for an impossible row.
|
||||
setup([{ constraint: 'no version of oldlib is compatible with python 3.12' }], true)
|
||||
|
||||
expect(
|
||||
screen.getByText('no version of oldlib is compatible with python 3.12'),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('refuses Keep compatible on an impossible row', () => {
|
||||
// `default_decision(is_impossible = true, …)` returns Skip, so the control mirrors the core
|
||||
// rather than offering a choice it would refuse to honour.
|
||||
setup(BLOCKERS, true)
|
||||
|
||||
const group = screen.getByRole('radiogroup', { name: 'numpy' })
|
||||
expect(within(group).getByRole('radio', { name: /keep compatible/i })).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -77,7 +77,14 @@ export function PdConflictRow({
|
||||
<li key={`${b.by ?? ''}-${b.constraint}-${String(i)}`} className="text-data text-text-dim">
|
||||
{b.by == null
|
||||
? b.constraint
|
||||
: t('plan.blocker', { by: b.by, constraint: b.constraint })}
|
||||
: t('plan.blocker', {
|
||||
// Assembled here, from three fields, for the same reason `PdUninstallDialog`
|
||||
// assembles the guard's: a sentence joined in Rust cannot be un-joined by a
|
||||
// catalog. Until Slice 0 `constraint` arrived as a whole English phrase and
|
||||
// this template wrapped it again, naming the dependent twice.
|
||||
by: b.version == null ? b.by : `${b.by} ${b.version}`,
|
||||
constraint: b.constraint,
|
||||
})}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* The command palette.
|
||||
*
|
||||
* `setup.ts` stubs `showModal` by setting `open` and nothing else — no top layer, no focus
|
||||
* containment, no native `cancel` on Escape. So modality is **not** under test here; what is
|
||||
* tested is the policy on top: what filtering shows, what Enter dispatches, and that dispatching
|
||||
* closes before it acts.
|
||||
*/
|
||||
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { PdPalette } from '@/components/PdPalette'
|
||||
import { useEnvStore, useLegalStore, useUiStore } from '@/stores'
|
||||
import { resetStore } from '@/test/stores'
|
||||
|
||||
vi.mock('@/ipc', async () => {
|
||||
const { ipcMock } = await import('@/test/ipc')
|
||||
return ipcMock()
|
||||
})
|
||||
|
||||
function open() {
|
||||
const onClose = vi.fn()
|
||||
render(<PdPalette onClose={onClose} />)
|
||||
return { onClose, input: screen.getByRole('combobox') }
|
||||
}
|
||||
|
||||
const options = () => within(screen.getByRole('listbox')).getAllByRole('option')
|
||||
|
||||
describe('PdPalette', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetStore(useUiStore)
|
||||
resetStore(useEnvStore)
|
||||
resetStore(useLegalStore)
|
||||
})
|
||||
|
||||
it('opens showing every action rather than an empty list', () => {
|
||||
open()
|
||||
// Nine tabs plus the rest. The exact number is not the point; that it is not zero is.
|
||||
expect(options().length).toBeGreaterThan(9)
|
||||
})
|
||||
|
||||
it('filters as you type, and ranks the exact match first', () => {
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'pins' } })
|
||||
expect(options()[0]).toHaveTextContent('Pins')
|
||||
})
|
||||
|
||||
it('navigates with the arrows while the input keeps focus', () => {
|
||||
// The reason this is a listbox with aria-activedescendant rather than a set of tab stops: the
|
||||
// user must be able to keep typing to narrow while moving through what is left.
|
||||
const { input } = open()
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'true')
|
||||
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' })
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'false')
|
||||
expect(options()[1]).toHaveAttribute('aria-selected', 'true')
|
||||
expect(input).toHaveFocus()
|
||||
|
||||
fireEvent.keyDown(input, { key: 'ArrowUp' })
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
||||
it('will not run off either end of the list', () => {
|
||||
const { input } = open()
|
||||
fireEvent.keyDown(input, { key: 'ArrowUp' })
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
||||
it('dispatches the highlighted action on Enter, and closes first', () => {
|
||||
const { input, onClose } = open()
|
||||
fireEvent.change(input, { target: { value: 'health' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
// Closing before running is what stops an action that changes `nav` fighting the dialog for
|
||||
// focus — App moves focus to the new screen's <h1> on every nav change.
|
||||
expect(useUiStore.getState().nav).toBe('health')
|
||||
})
|
||||
|
||||
it('dispatches on click too', () => {
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'search' } })
|
||||
fireEvent.click(options()[0] as HTMLElement)
|
||||
expect(useUiStore.getState().nav).toBe('search')
|
||||
})
|
||||
|
||||
it('reaches an action that is not a tab', () => {
|
||||
// The palette is only worth having if it does more than the sidebar already does.
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'documents' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
expect(useLegalStore.getState().review).toBe(true)
|
||||
})
|
||||
|
||||
it('says so when nothing matches, rather than showing an empty box', () => {
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'zzzzz' } })
|
||||
expect(screen.queryByRole('option')).toBeNull()
|
||||
expect(screen.getByText(/nothing matches/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes on Escape through its own handler', () => {
|
||||
const { onClose } = open()
|
||||
// jsdom does not synthesize the native `cancel` event, so this fires it directly — the same
|
||||
// path a real Escape takes.
|
||||
fireEvent(screen.getByRole('dialog'), new Event('cancel', { cancelable: true }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* The command palette — `Ctrl+K`, PRD P1-5 and UI-SPEC §1's "signature move".
|
||||
*
|
||||
* Frontend only: every action it dispatches already exists as a store action, so there is no new
|
||||
* IPC command, no Rust and no capability change.
|
||||
*
|
||||
* **Not built on `PdDialog`**, which hardcodes a heading and a Cancel-first button row for
|
||||
* destructive confirms — the opposite of what a filter list wants. What is lifted from it is the
|
||||
* part worth reusing: a native `<dialog>` with `showModal()`, which brings the top layer, the
|
||||
* inert backdrop, real focus containment and `Esc` for free, plus the `if (!el.open)` guard that
|
||||
* exists because StrictMode double-invokes the mount effect.
|
||||
*
|
||||
* **It dismisses on backdrop click**, unlike `PdDialog`. That component argues the opposite and is
|
||||
* right to: a mis-click beside a dialog about to delete things must not read as consent. Nothing
|
||||
* here is destructive on its own — every action either navigates or opens something that has its
|
||||
* own confirm — so the convention wins.
|
||||
*
|
||||
* The list is a `listbox` with `aria-activedescendant`, not a set of tab stops: the input keeps
|
||||
* focus while `↑`/`↓` move the selection, which is what lets someone keep typing to narrow.
|
||||
* `aria-selected` is what makes the highlight survive Windows high-contrast mode, where the
|
||||
* `bg-surface-2` tint is erased and `styles.css`'s forced-colors block outlines the selected row
|
||||
* instead.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { NAV_KEYS } from '@/components/nav'
|
||||
import { rank } from '@/components/match'
|
||||
import { useEnvStore, useHealthStore, useIndexStore, useLegalStore, useUiStore } from '@/stores'
|
||||
|
||||
/** One thing the palette can do. */
|
||||
interface Action {
|
||||
/** Stable, and the React key. */
|
||||
id: string
|
||||
/** Already localized. */
|
||||
label: string
|
||||
/** Shown dimmed on the right — which screen or area it belongs to. */
|
||||
group: string
|
||||
run: () => void
|
||||
}
|
||||
|
||||
export function PdPalette({ onClose }: { onClose: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [at, setAt] = useState(0)
|
||||
|
||||
const setNav = useUiStore((s) => s.setNav)
|
||||
const scan = useEnvStore((s) => s.scan)
|
||||
const loadPackages = useEnvStore((s) => s.loadPackages)
|
||||
const loadOutdated = useEnvStore((s) => s.loadOutdated)
|
||||
const takeSnapshot = useEnvStore((s) => s.takeSnapshot)
|
||||
const clearSelection = useEnvStore((s) => s.clearSelection)
|
||||
const refreshIndex = useIndexStore((s) => s.refreshIndex)
|
||||
const clearQueue = useIndexStore((s) => s.clearQueue)
|
||||
const setTab = useHealthStore((s) => s.setTab)
|
||||
const openReview = useLegalStore((s) => s.openReview)
|
||||
|
||||
const actions: Action[] = useMemo(
|
||||
() => [
|
||||
// The nine tabs, every one of which now has a screen: `security` was the last placeholder
|
||||
// and P1-1 filled it.
|
||||
...NAV_KEYS.map((key) => ({
|
||||
id: `nav:${key}`,
|
||||
label: t(`nav.${key}`),
|
||||
group: t('palette.groups.go'),
|
||||
run: () => {
|
||||
setNav(key)
|
||||
},
|
||||
})),
|
||||
{
|
||||
id: 'env:rescan',
|
||||
label: t('actions.rescan'),
|
||||
group: t('nav.environments'),
|
||||
run: () => {
|
||||
setNav('environments')
|
||||
void scan()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'pkg:refresh',
|
||||
label: t('palette.refreshPackages'),
|
||||
group: t('nav.installed'),
|
||||
run: () => {
|
||||
void loadPackages()
|
||||
void loadOutdated()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'pkg:clear-selection',
|
||||
label: t('palette.clearSelection'),
|
||||
group: t('nav.installed'),
|
||||
run: clearSelection,
|
||||
},
|
||||
{
|
||||
id: 'snapshot:take',
|
||||
label: t('snapshots.take'),
|
||||
group: t('snapshots.title'),
|
||||
run: () => {
|
||||
void takeSnapshot()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'index:refresh',
|
||||
label: t('search.refreshIndex'),
|
||||
group: t('nav.search'),
|
||||
run: () => {
|
||||
void refreshIndex()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'index:clear-queue',
|
||||
label: t('palette.clearQueue'),
|
||||
group: t('nav.search'),
|
||||
run: clearQueue,
|
||||
},
|
||||
...(['deptry', 'vulture', 'ruff'] as const).map((tool) => ({
|
||||
id: `health:${tool}`,
|
||||
// The tool's own name, which is data and never translated (I18N §2).
|
||||
label: `${t('nav.health')}: ${tool}`,
|
||||
group: t('nav.health'),
|
||||
run: () => {
|
||||
setNav('health')
|
||||
setTab(tool)
|
||||
},
|
||||
})),
|
||||
{
|
||||
id: 'legal:review',
|
||||
label: t('about.reopen'),
|
||||
group: t('nav.about'),
|
||||
run: openReview,
|
||||
},
|
||||
],
|
||||
[
|
||||
t,
|
||||
setNav,
|
||||
scan,
|
||||
loadPackages,
|
||||
loadOutdated,
|
||||
clearSelection,
|
||||
takeSnapshot,
|
||||
refreshIndex,
|
||||
clearQueue,
|
||||
setTab,
|
||||
openReview,
|
||||
],
|
||||
)
|
||||
|
||||
const shown = useMemo(() => rank(actions, query, (a) => [a.label, a.group]), [actions, query])
|
||||
// Clamped rather than reset: narrowing the list must not silently move the selection to
|
||||
// something the user was not looking at.
|
||||
const active = Math.min(at, Math.max(0, shown.length - 1))
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
// `showModal` throws when the dialog is already open, which React's double-invoked effects in
|
||||
// development make a real case rather than a theoretical one.
|
||||
if (el !== null && !el.open) el.showModal()
|
||||
return () => {
|
||||
if (el !== null && el.open) el.close()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const dispatch = (action: Action | undefined) => {
|
||||
if (action === undefined) return
|
||||
// Closed *before* running, so an action that changes `nav` does not fight the dialog for
|
||||
// focus — `App.tsx` moves focus to the new screen's `<h1>` on every nav change.
|
||||
onClose()
|
||||
action.run()
|
||||
}
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={t('palette.title')}
|
||||
onCancel={(e) => {
|
||||
e.preventDefault()
|
||||
onClose()
|
||||
}}
|
||||
onClick={(e) => {
|
||||
// Backdrop only: clicks inside the panel below stop here first.
|
||||
if (e.target === ref.current) onClose()
|
||||
}}
|
||||
className="mt-24 w-full max-w-xl rounded-pd border border-border bg-surface p-0 text-text backdrop:bg-bg/80"
|
||||
>
|
||||
<div className="p-3">
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-expanded="true"
|
||||
aria-controls="palette-list"
|
||||
aria-activedescendant={shown[active] === undefined ? undefined : `palette-${shown[active].id}`}
|
||||
aria-label={t('palette.title')}
|
||||
placeholder={t('palette.placeholder')}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setAt(0)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
setAt((i) => Math.min(i + 1, shown.length - 1))
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setAt((i) => Math.max(i - 1, 0))
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
dispatch(shown[active])
|
||||
}
|
||||
}}
|
||||
className="w-full rounded-pd border border-border bg-bg px-3 py-1.5 font-mono text-data"
|
||||
/>
|
||||
|
||||
<ul id="palette-list" role="listbox" aria-label={t('palette.title')} className="mt-2 max-h-80 overflow-auto">
|
||||
{shown.map((action, i) => (
|
||||
<li
|
||||
key={action.id}
|
||||
id={`palette-${action.id}`}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
data-action-id={action.id}
|
||||
onClick={() => {
|
||||
dispatch(action)
|
||||
}}
|
||||
className={`flex cursor-pointer items-baseline justify-between gap-3 rounded-pd px-3 py-1.5 text-data ${
|
||||
i === active ? 'bg-surface-2 text-accent' : 'text-text'
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 truncate">{action.label}</span>
|
||||
<span className="shrink-0 text-text-dim">{action.group}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{shown.length === 0 ? (
|
||||
<p className="px-3 py-2 font-mono text-data text-text-dim">
|
||||
{`▸ ${t('palette.noMatch', { query })}`}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
@@ -94,7 +94,7 @@ describe('the 3-way conflict control', () => {
|
||||
// PRD G2: conflicts are explained in one sentence a user can act on.
|
||||
setup()
|
||||
expect(
|
||||
within(rowFor('numpy')).getByText('scipy requires numpy<1.28.0,>=1.21.6'),
|
||||
within(rowFor('numpy')).getByText('scipy 1.11.4 requires numpy<1.28.0,>=1.21.6'),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -106,7 +106,9 @@ describe('the 3-way conflict control', () => {
|
||||
expect(onChoose).not.toHaveBeenCalled()
|
||||
|
||||
const dialog = within(rowFor('numpy')).getByRole('alertdialog')
|
||||
expect(within(dialog).getByText(/breaks scipy/)).toBeInTheDocument()
|
||||
// Both dependents that exclude 2.5.1, from the computed fixture — so this also covers
|
||||
// the plural branch of `forceWarning`, which nothing else does.
|
||||
expect(within(dialog).getByText(/breaks pandas, scipy/)).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Force latest' }))
|
||||
expect(onChoose).toHaveBeenCalledWith('numpy', 'force-latest')
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Export and import a `requirements.txt` — PRD P1-3.
|
||||
*
|
||||
* On the environment detail screen, beside snapshots, because both are *the environment as a
|
||||
* document*: one is PipDock's own record and one is the file the rest of the Python world passes
|
||||
* around. The exported bytes are the engine's `freeze`, which is what a snapshot stores — so there
|
||||
* is one idea of what an environment written down looks like, not two.
|
||||
*
|
||||
* **Import does not install.** It reads, reports, and hands the specs to the ordinary install flow
|
||||
* — which previews, snapshots and confirms like every other mutation. The skipped lines are shown
|
||||
* *before* that, because a file asking for `-r dev.txt` or an editable install is asking for
|
||||
* something PipDock will not do, and a preview that quietly represented a shorter list would be
|
||||
* accurate about itself and wrong about the user's file.
|
||||
*/
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdErrorRow } from '@/components/PdErrorRow'
|
||||
import {
|
||||
envExport,
|
||||
pickOpenFile,
|
||||
pickSavePath,
|
||||
requirementsRead,
|
||||
type ParsedRequirements,
|
||||
type PdError,
|
||||
type PyEnv,
|
||||
} from '@/ipc'
|
||||
import { asPdError, usePlanStore } from '@/stores'
|
||||
|
||||
/** What the save dialog suggests. A filename, not copy — never translated (I18N §2). */
|
||||
const DEFAULT_NAME = 'requirements.txt'
|
||||
|
||||
export function PdRequirements({ env }: { env?: PyEnv | undefined }) {
|
||||
const { t } = useTranslation()
|
||||
const resolve = usePlanStore((s) => s.resolve)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [wrote, setWrote] = useState<string | null>(null)
|
||||
const [read, setRead] = useState<ParsedRequirements | null>(null)
|
||||
const [error, setError] = useState<PdError | null>(null)
|
||||
|
||||
const usable = env !== undefined
|
||||
|
||||
const doExport = async () => {
|
||||
setError(null)
|
||||
setWrote(null)
|
||||
const path = await pickSavePath(t('requirements.exportTitle'), DEFAULT_NAME)
|
||||
// A cancelled picker is not a failure and must not read as one.
|
||||
if (path === null || env === undefined) return
|
||||
setBusy(true)
|
||||
try {
|
||||
setWrote(await envExport(env, path))
|
||||
} catch (e) {
|
||||
setError(asPdError(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const doRead = async () => {
|
||||
setError(null)
|
||||
setWrote(null)
|
||||
setRead(null)
|
||||
const path = await pickOpenFile(t('requirements.importTitle'), ['txt'])
|
||||
if (path === null) return
|
||||
setBusy(true)
|
||||
try {
|
||||
setRead(await requirementsRead(path))
|
||||
} catch (e) {
|
||||
setError(asPdError(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-labelledby="requirements-title" className="mt-4">
|
||||
<h2 id="requirements-title" className="text-text-dim">
|
||||
{t('requirements.title')}
|
||||
</h2>
|
||||
<p className="mt-1 max-w-2xl text-data text-text-dim">{t('requirements.intro')}</p>
|
||||
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!usable || busy}
|
||||
onClick={() => {
|
||||
void doExport()
|
||||
}}
|
||||
data-action="export-requirements"
|
||||
className="rounded-pd border border-border px-3 py-1 text-data disabled:opacity-40"
|
||||
>
|
||||
{t('requirements.export')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!usable || busy}
|
||||
onClick={() => {
|
||||
void doRead()
|
||||
}}
|
||||
data-action="import-requirements"
|
||||
className="rounded-pd border border-border px-3 py-1 text-data disabled:opacity-40"
|
||||
>
|
||||
{t('requirements.import')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error !== null ? (
|
||||
<div className="mt-2">
|
||||
<PdErrorRow error={error} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{wrote !== null ? (
|
||||
// The path, so the user knows where it went rather than trusting that it went somewhere.
|
||||
<p className="mt-2 text-data text-text-dim">
|
||||
{t('requirements.wrote')} <code className="font-mono break-all">{wrote}</code>
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{read !== null ? (
|
||||
<div className="mt-3 rounded-pd border border-border bg-surface p-3">
|
||||
<p className="text-data">
|
||||
{t('requirements.readCount', { count: read.specs.length })}
|
||||
</p>
|
||||
|
||||
{read.skipped.length > 0 ? (
|
||||
<>
|
||||
{/* Before the install button, not after it. These lines are the file asking for
|
||||
something PipDock will not do, and the decision to proceed anyway is only
|
||||
informed if it is made after reading them. */}
|
||||
<p className="mt-2 text-data text-warn">
|
||||
{t('requirements.skippedCount', { count: read.skipped.length })}
|
||||
</p>
|
||||
<ul className="mt-1 space-y-0.5">
|
||||
{read.skipped.map((s) => (
|
||||
<li key={`${String(s.line)}:${s.text}`} className="text-data text-text-dim">
|
||||
<code className="font-mono">{`${String(s.line)}:`}</code>{' '}
|
||||
<code className="font-mono break-all">{s.text}</code>{' '}
|
||||
<span>{t(`requirements.skip.${s.reason}`)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={!usable || read.specs.length === 0}
|
||||
onClick={() => {
|
||||
if (env === undefined) return
|
||||
// The ordinary install flow: preview, snapshot, confirm. Nothing about arriving
|
||||
// from a file earns an exemption from DATA-FLOW §9.
|
||||
void resolve(env, { intent: 'install', specs: read.specs })
|
||||
}}
|
||||
data-action="install-requirements"
|
||||
className="mt-3 rounded-pd bg-accent px-3 py-1 text-data text-bg disabled:opacity-40"
|
||||
>
|
||||
{t('requirements.install', { count: read.specs.length })}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,8 +3,15 @@ import { useTranslation } from 'react-i18next'
|
||||
import { NAV_KEYS, type NavKey } from '@/components/nav'
|
||||
import { PANEL_PHASES, useEnvStore, usePlanStore, useUiStore } from '@/stores'
|
||||
|
||||
/** Tabs whose screens land in a later milestone. Kept in place, not hidden. */
|
||||
const NOT_YET: readonly NavKey[] = ['security']
|
||||
/**
|
||||
* Tabs whose screens land in a later milestone. Kept in place, not hidden.
|
||||
*
|
||||
* **Empty since P1-1**, which gave `security` its screen — it was the last entry. Kept rather than
|
||||
* deleted because the mechanism is the interesting part: a tab without a screen stays visible and
|
||||
* focusable at reduced opacity, since hiding one would renumber every `Ctrl+N` after it and make
|
||||
* the user relearn the map twice.
|
||||
*/
|
||||
const NOT_YET: readonly NavKey[] = []
|
||||
|
||||
/**
|
||||
* The sidebar — UI-SPEC §3 and §8.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* The palette's matcher.
|
||||
*
|
||||
* The ranking rules are SP-3's, learned from nucleo putting `requests-ntlm` above `requests`: a
|
||||
* raw fuzzy score rewards density, so tiers come first and length breaks ties. These cases are
|
||||
* that finding restated over action labels.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { isSubsequence, rank } from '@/components/match'
|
||||
|
||||
const label = (s: string) => [s] as const
|
||||
|
||||
describe('isSubsequence', () => {
|
||||
it('requires order, not merely presence', () => {
|
||||
// The whole reason this is a two-pointer walk. `[...needle].every(c => hay.includes(c))` is
|
||||
// the obvious wrong implementation and would say true here.
|
||||
expect(isSubsequence('slot', 'tools')).toBe(false)
|
||||
expect(isSubsequence('tls', 'tools')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches a prefix, a scattered run and the whole string', () => {
|
||||
expect(isSubsequence('too', 'tools')).toBe(true)
|
||||
expect(isSubsequence('tos', 'tools')).toBe(true)
|
||||
expect(isSubsequence('tools', 'tools')).toBe(true)
|
||||
expect(isSubsequence('toolss', 'tools')).toBe(false)
|
||||
})
|
||||
|
||||
it('is true for an empty needle', () => {
|
||||
expect(isSubsequence('', 'anything')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rank', () => {
|
||||
it('keeps everything, in order, for an empty query', () => {
|
||||
// A palette that opens showing nothing has to be taught before it can be used.
|
||||
const items = ['Updates', 'Search', 'Pins']
|
||||
expect(rank(items, ' ', label)).toEqual(items)
|
||||
})
|
||||
|
||||
it('puts the exact match first, then the prefix, then the subsequence', () => {
|
||||
const got = rank(['Pins and things', 'Pin', 'Pins', 'Preferences in'], 'pin', label)
|
||||
expect(got.slice(0, 3)).toEqual(['Pin', 'Pins', 'Pins and things'])
|
||||
})
|
||||
|
||||
it('prefers the shorter label within a tier', () => {
|
||||
// SP-3's finding in miniature: the short thing containing the query is nearly always the
|
||||
// thing itself, and the longer ones are its variants.
|
||||
expect(rank(['Search settings', 'Search'], 'search', label)).toEqual([
|
||||
'Search',
|
||||
'Search settings',
|
||||
])
|
||||
})
|
||||
|
||||
it('is alphabetical on a full tie, so two identical queries never reorder', () => {
|
||||
expect(rank(['beta', 'alpha'], 'a', label)).toEqual(['alpha', 'beta'])
|
||||
})
|
||||
|
||||
it('drops what does not match at all', () => {
|
||||
expect(rank(['Updates', 'Health'], 'zzz', label)).toEqual([])
|
||||
})
|
||||
|
||||
it('is case-insensitive in both directions', () => {
|
||||
expect(rank(['Health'], 'HEALTH', label)).toEqual(['Health'])
|
||||
expect(rank(['HEALTH'], 'health', label)).toEqual(['HEALTH'])
|
||||
})
|
||||
|
||||
it('puts every label match above every group match', () => {
|
||||
// Found by a failing palette test. With one flat `${group} ${label}` string, typing `search`
|
||||
// ranked *Download the index* — group "Search", a prefix match — above the Search tab, whose
|
||||
// label matched only as a subsequence of `go to search`. Someone typing a screen's name wants
|
||||
// the screen, however weakly the label matched.
|
||||
const items = [
|
||||
{ label: 'Download the index', group: 'Search' },
|
||||
{ label: 'Search', group: 'Go to' },
|
||||
]
|
||||
const got = rank(items, 'search', (i) => [i.label, i.group])
|
||||
expect(got[0]?.label).toBe('Search')
|
||||
})
|
||||
|
||||
it('still finds an item by its group when no label matches', () => {
|
||||
const items = [{ label: 'Download the index', group: 'Search' }]
|
||||
expect(rank(items, 'search', (i) => [i.label, i.group])).toEqual(items)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Ranking a short list of actions against what the user typed — the command palette's matcher.
|
||||
*
|
||||
* **Deliberately not `index_search`.** That command searches 864,000 PyPI *package names* over
|
||||
* IPC, which is the wrong corpus and the wrong cost for thirty actions; a palette that made a
|
||||
* round trip per keystroke would be slower than the thing it exists to speed up. `nucleo` is a
|
||||
* `pipdock-core` dependency and there is no JS fuzzy library, so this is twenty lines instead.
|
||||
*
|
||||
* What it *does* take from `crates/pipdock-core/src/index/mod.rs` is the ranking philosophy, which
|
||||
* was learned the hard way in SP-3: **tiered, not score-ordered.** A raw fuzzy score rewards
|
||||
* density, so a longer name containing the query densely beats the name the user actually typed —
|
||||
* nucleo ranks `requests-ntlm` above `requests`. Exact, then prefix, then subsequence; within a
|
||||
* tier, the shorter label; then alphabetical, so two identical queries never reorder.
|
||||
*/
|
||||
|
||||
/** How a candidate matched, in ranking order. Lower sorts first. */
|
||||
export const enum MatchKind {
|
||||
Exact = 0,
|
||||
Prefix = 1,
|
||||
Subsequence = 2,
|
||||
}
|
||||
|
||||
/**
|
||||
* Is `needle` a subsequence of `haystack`?
|
||||
*
|
||||
* A two-pointer walk, which is the part that is easy to get wrong: `[...needle].every(c =>
|
||||
* haystack.includes(c))` tests *presence*, not order, and would match `slot` against `tools`.
|
||||
* Both are lower-cased by the caller.
|
||||
*/
|
||||
export function isSubsequence(needle: string, haystack: string): boolean {
|
||||
let at = 0
|
||||
for (const c of haystack) {
|
||||
if (c === needle[at]) at += 1
|
||||
if (at === needle.length) return true
|
||||
}
|
||||
return at === needle.length
|
||||
}
|
||||
|
||||
/** How `haystack` matched `needle`, or null when it did not. */
|
||||
export function matchKind(needle: string, haystack: string): MatchKind | null {
|
||||
if (haystack === needle) return MatchKind.Exact
|
||||
if (haystack.startsWith(needle)) return MatchKind.Prefix
|
||||
return isSubsequence(needle, haystack) ? MatchKind.Subsequence : null
|
||||
}
|
||||
|
||||
/**
|
||||
* How much worse a match on the secondary text is than any match on the primary.
|
||||
*
|
||||
* Larger than the widest tier gap, so **every** label match outranks **every** group match. Found
|
||||
* by a test: with one flat text of `"${group} ${label}"`, typing `search` put *Download the index*
|
||||
* — group "Search", so a prefix match — above the Search tab itself, whose label matched only as a
|
||||
* subsequence of `go to search`. Someone typing a screen's name wants the screen.
|
||||
*/
|
||||
const SECONDARY = 10
|
||||
|
||||
/**
|
||||
* Rank `items` against `query`, keeping only what matches.
|
||||
*
|
||||
* `text` returns the primary label and, optionally, a secondary the item may also be found by —
|
||||
* its group. A match on the primary always beats a match on the secondary, whatever the tiers.
|
||||
*
|
||||
* An empty query keeps everything in its original order — a palette that opens showing nothing is
|
||||
* a palette that has to be taught before it can be used.
|
||||
*/
|
||||
export function rank<T>(
|
||||
items: readonly T[],
|
||||
query: string,
|
||||
text: (item: T) => readonly [primary: string, secondary?: string],
|
||||
): T[] {
|
||||
const needle = query.trim().toLowerCase()
|
||||
if (needle === '') return [...items]
|
||||
|
||||
return items
|
||||
.map((item) => {
|
||||
const [primary, secondary] = text(item)
|
||||
const label = primary.toLowerCase()
|
||||
const direct = matchKind(needle, label)
|
||||
if (direct !== null) return { item, label, score: direct }
|
||||
const via = secondary === undefined ? null : matchKind(needle, secondary.toLowerCase())
|
||||
return via === null ? null : { item, label, score: via + SECONDARY }
|
||||
})
|
||||
.filter((r): r is { item: T; label: string; score: number } => r !== null)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.score - b.score ||
|
||||
// The shorter label, because a short one containing the query is nearly always the thing
|
||||
// itself and the longer ones are its variants.
|
||||
a.label.length - b.label.length ||
|
||||
a.label.localeCompare(b.label),
|
||||
)
|
||||
.map((r) => r.item)
|
||||
}
|
||||
+161
-1
@@ -6,6 +6,78 @@
|
||||
// Command signatures are not here — they are not derivable from a schema and stay hand-written
|
||||
// in `./index.ts`.
|
||||
|
||||
/** One advisory against one installed distribution. */
|
||||
export interface Advisory {
|
||||
/**
|
||||
* Other ids for the same advisory, which is where the `CVE-*` and `GHSA-*` live.
|
||||
*
|
||||
* PRD P1-1 says "known CVEs"; a CVE is never the primary id here, so a screen that wants to
|
||||
* show one reads this.
|
||||
*/
|
||||
aliases?: string[];
|
||||
/** The advisory prose, verbatim. Never translated (I18N §2) and never trimmed here. */
|
||||
description: string;
|
||||
/**
|
||||
* Versions that fix it. **Empty is meaningful** — an advisory with nowhere to upgrade to —
|
||||
* and [`sort_advisories`] puts those last rather than hiding them.
|
||||
*/
|
||||
fixVersions?: string[];
|
||||
/** pip-audit's primary id — `PYSEC-*` under the default service. */
|
||||
id: string;
|
||||
/** The installed distribution the advisory is against. */
|
||||
pkg: PkgName;
|
||||
/**
|
||||
* The OSV entry, when the id is shaped like one.
|
||||
*
|
||||
* **Built from a validated id rather than taken from the tool**, which is the whole
|
||||
* difference between this and `PdHealthReport`'s `finding.url`.
|
||||
* `capabilities/external-links.json` records that ruff's URL is the only one in the
|
||||
* application derived from a third party's output; this one is derived from a string PipDock
|
||||
* has checked, so widening the allowlist to `osv.dev` does not widen what can reach it.
|
||||
*/
|
||||
url?: string | null;
|
||||
/** The version installed, not the version that fixes it. */
|
||||
version: Version;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a Security-tab run produced.
|
||||
*
|
||||
* Shaped like [`crate::health::HealthReport`] deliberately: a `problems` list rather than an
|
||||
* early return, so a failed audit still *returns a report* and the screen renders one error row
|
||||
* instead of nothing at all. That shape is what makes a partial result expressible.
|
||||
*/
|
||||
export interface AuditReport {
|
||||
/** Deduplicated and ordered by [`sort_advisories`]. */
|
||||
advisories?: Advisory[];
|
||||
/**
|
||||
* The user stopped it.
|
||||
*
|
||||
* A **state, not an error**, which is the shape `ExecutionSummary.cancelled` established: the
|
||||
* user asking a run to stop is not a tool failure, so nothing lands in `problems` and no
|
||||
* catalog code is minted for something that went right. It matters here in a way it did not
|
||||
* for Code Health, whose runs are 1.3 s — an audit is 18-68 s, which is long enough that
|
||||
* stopping one is an ordinary thing to want.
|
||||
*/
|
||||
cancelled?: boolean;
|
||||
/** `canonical_interpreter` of the environment audited. Data, never localized (I18N §2). */
|
||||
env: string;
|
||||
/**
|
||||
* Distributions the freeze document listed.
|
||||
*
|
||||
* **Separate from `advisories.len()`**, because "audited 145 packages and found nothing" and
|
||||
* "audited nothing" are different answers. A screen that cannot tell them apart tells P4's
|
||||
* lie — *no issues found* before anything has run.
|
||||
*/
|
||||
packages: number;
|
||||
/** Why the run contributed nothing. Empty means it completed. */
|
||||
problems?: ToolProblem[];
|
||||
/** When the run finished, RFC 3339. */
|
||||
ranAt: string;
|
||||
/** pip-audit's version, out of the audit venv's manifest. Empty if it has never synced. */
|
||||
toolVersion: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The package responsible for holding another one back.
|
||||
*
|
||||
@@ -16,8 +88,25 @@
|
||||
export interface Blocker {
|
||||
/** The package imposing the constraint, absent when attribution is ambiguous. */
|
||||
by?: PkgName | null;
|
||||
/** The constraint text, e.g. `"requests<2.31"`. */
|
||||
/**
|
||||
* The requirement holding the package back, e.g. `"requests<2.31"`.
|
||||
*
|
||||
* **Data, not a sentence** — hard invariant 4. Until Slice 0 this carried
|
||||
* `"scipy 1.11.4 requires numpy <1.28.0,>=1.21.6"`, a phrase assembled in Rust, which the
|
||||
* GUI then wrapped in `"{{by}} requires {{constraint}}"` and rendered naming the dependent
|
||||
* **twice**. Only the CLI looked right, because it prints this field alone. The shape here
|
||||
* now matches `BrokenDependent.constraint`, which the guard dialog has always composed
|
||||
* correctly.
|
||||
*/
|
||||
constraint: string;
|
||||
/**
|
||||
* The installed version of [`Self::by`], when the probe knew it.
|
||||
*
|
||||
* Split out for the same reason [`crate::graph::BrokenDependent`] splits it: the two heads
|
||||
* phrase this differently — the CLI writes `scipy 1.11.4 requires …` itself, the GUI
|
||||
* interpolates `plan.blocker` — and neither can un-join a string Rust joined for it.
|
||||
*/
|
||||
version?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,6 +131,28 @@ export interface BrokenDependent {
|
||||
version?: string | null;
|
||||
}
|
||||
|
||||
/** Something the user can be offered a *Clear* button for. */
|
||||
export type CacheTarget =
|
||||
| 'snapshots'
|
||||
| 'tools'
|
||||
| 'audit';
|
||||
|
||||
/** What PipDock is using, by artefact. */
|
||||
export interface CacheUsage {
|
||||
/** The Security tab's pip-audit environment (PRD P1-1). */
|
||||
audit: Entry;
|
||||
/** `index.db` — the package index, settings, pins and the consent record. **Not clearable.** */
|
||||
database: Entry;
|
||||
/** The data root everything below lives in. */
|
||||
root: string;
|
||||
/** How many snapshot documents there are, across every environment. */
|
||||
snapshotCount: number;
|
||||
/** Snapshots, across every environment. */
|
||||
snapshots: Entry;
|
||||
/** The Code Health tools environment. */
|
||||
tools: Entry;
|
||||
}
|
||||
|
||||
/** One line of the preview diff. */
|
||||
export interface Change {
|
||||
/** Version before, absent for a fresh install. */
|
||||
@@ -235,6 +346,16 @@ export interface EngineInfo {
|
||||
version?: string | null;
|
||||
}
|
||||
|
||||
/** One line of the cache report. */
|
||||
export interface Entry {
|
||||
/** Bytes on disk, summed recursively. */
|
||||
bytes: number;
|
||||
/** False when nothing is there yet, so the UI can say "nothing to clear" rather than "0 B". */
|
||||
exists: boolean;
|
||||
/** Where it is. Data — shown verbatim, never translated (I18N §2). */
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** How an environment was discovered. Surfaced as the source chip in the Environments screen. */
|
||||
export type EnvSource =
|
||||
| 'registry'
|
||||
@@ -477,6 +598,14 @@ export interface PackageMeta {
|
||||
version?: string | null;
|
||||
}
|
||||
|
||||
/** What [`parse`] made of a file. */
|
||||
export interface ParsedRequirements {
|
||||
/** Everything else, with its line number and reason. */
|
||||
skipped: SkippedLine[];
|
||||
/** Install specs, in file order, as `Intent::Install` wants them. */
|
||||
specs: string[];
|
||||
}
|
||||
|
||||
/** A pin with the reason the user gave for it. */
|
||||
export interface Pin {
|
||||
/** How it is constrained. */
|
||||
@@ -497,6 +626,20 @@ export type PinMode =
|
||||
| 'exclude'
|
||||
| { hold: { version: Version } };
|
||||
|
||||
/** A package worth pinning, and why — PRD P1-2, UI-SPEC §4. */
|
||||
export interface PinSuggestion {
|
||||
/**
|
||||
* How many installed packages depend on it.
|
||||
*
|
||||
* The number is the whole argument, so it is carried rather than recomputed for display:
|
||||
* "12 packages depend on it" is what makes the suggestion actionable, and a count the screen
|
||||
* derived separately would eventually disagree with the one that qualified it.
|
||||
*/
|
||||
dependents: number;
|
||||
/** The package being suggested. */
|
||||
pkg: PkgName;
|
||||
}
|
||||
|
||||
/** A resolved, exact `name==version` pair. Only these reach a mutating engine command. */
|
||||
export interface PinnedSpec {
|
||||
/** Normalized distribution name. */
|
||||
@@ -676,6 +819,23 @@ export interface RuffFindings {
|
||||
fixableFiles: number;
|
||||
}
|
||||
|
||||
/** Why a line was not turned into a spec. */
|
||||
export type SkipReason =
|
||||
| 'include'
|
||||
| 'not-from-index'
|
||||
| 'option'
|
||||
| 'unparsed';
|
||||
|
||||
/** A line the parser would not turn into an install spec, and what was wrong with it. */
|
||||
export interface SkippedLine {
|
||||
/** 1-based, so it matches what an editor shows. */
|
||||
line: number;
|
||||
/** Why, as a catalog-style discriminant the UI turns into a sentence. */
|
||||
reason: SkipReason;
|
||||
/** The line, trimmed. Data — shown verbatim, never translated (I18N §2). */
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `.meta.json` sidecar (ARCHITECTURE §6).
|
||||
*
|
||||
|
||||
+112
-1
@@ -16,6 +16,7 @@ import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { open, save } from '@tauri-apps/plugin-dialog'
|
||||
|
||||
import type {
|
||||
AuditReport,
|
||||
Decision,
|
||||
Dist,
|
||||
Freshness,
|
||||
@@ -30,7 +31,11 @@ import type {
|
||||
Intent,
|
||||
OutdatedDist,
|
||||
PackageMeta,
|
||||
CacheTarget,
|
||||
CacheUsage,
|
||||
ParsedRequirements,
|
||||
Pin,
|
||||
PinSuggestion,
|
||||
ProgressEvent,
|
||||
PyEnv,
|
||||
HealthReport,
|
||||
@@ -63,12 +68,20 @@ export const COMMANDS = [
|
||||
'pin_list',
|
||||
'pin_add',
|
||||
'pin_remove',
|
||||
'pin_suggestions',
|
||||
'env_export',
|
||||
'requirements_read',
|
||||
'cache_usage',
|
||||
'cache_clear',
|
||||
'snapshot_list',
|
||||
'snapshot_create',
|
||||
'snapshot_diff',
|
||||
'snapshot_rollback_preview',
|
||||
'snapshot_rollback',
|
||||
'health_run',
|
||||
'audit_run',
|
||||
'audit_cancel',
|
||||
'audit_save_report',
|
||||
'health_dirty',
|
||||
'health_fix',
|
||||
'health_save_report',
|
||||
@@ -85,7 +98,12 @@ export const COMMANDS = [
|
||||
export type Command = (typeof COMMANDS)[number]
|
||||
|
||||
/** Tauri event channels, per ARCHITECTURE §7. */
|
||||
export const EVENTS = ['plan-progress', 'scan-progress', 'health-progress'] as const
|
||||
export const EVENTS = [
|
||||
'plan-progress',
|
||||
'scan-progress',
|
||||
'health-progress',
|
||||
'audit-progress',
|
||||
] as const
|
||||
|
||||
export type EventName = (typeof EVENTS)[number]
|
||||
|
||||
@@ -163,6 +181,8 @@ export interface Settings {
|
||||
locale: string | null
|
||||
/** SECURITY §3: off by default, never inferred. */
|
||||
allowExternallyManaged: boolean
|
||||
/** How many dependents qualify a package for a pin suggestion (PRD P1-2). Zero is off. */
|
||||
pinSuggestThreshold: number
|
||||
}
|
||||
|
||||
/** A recorded acceptance of the legal documents. */
|
||||
@@ -222,6 +242,46 @@ export const pinAdd = (envHash: string, pin: Pin): Promise<void> =>
|
||||
export const pinRemove = (envHash: string, pkg: string): Promise<boolean> =>
|
||||
invoke('pin_remove', { envHash, pkg })
|
||||
|
||||
/**
|
||||
* Packages worth pinning, most-depended-upon first (PRD P1-2).
|
||||
*
|
||||
* Takes the whole `PyEnv`, not an `envHash`: the command probes, and an env hash is a one-way
|
||||
* digest of the interpreter path. The threshold and the current pin list are read server-side, so
|
||||
* a caller never has to keep them in step.
|
||||
*
|
||||
* **Costs one probe.** UI-SPEC §4 puts this on the Pins screen for that reason — do not call it
|
||||
* from anything that renders on every environment change.
|
||||
*/
|
||||
export const pinSuggestions = (env: PyEnv): Promise<PinSuggestion[]> =>
|
||||
invoke('pin_suggestions', { env })
|
||||
|
||||
/**
|
||||
* Write the environment out as a `requirements.txt`, resolving to the path written (PRD P1-3).
|
||||
*
|
||||
* The document is the engine's own `freeze`, which is what a snapshot records — so there is one
|
||||
* idea of what an exported environment looks like, not two. Rust does the writing: the webview has
|
||||
* no `fs` permission, only the ability to ask for a path.
|
||||
*/
|
||||
export const envExport = (env: PyEnv, path: string): Promise<string> =>
|
||||
invoke('env_export', { env, path })
|
||||
|
||||
/** Read a `requirements.txt` into install specs, with the lines it could not use. */
|
||||
export const requirementsRead = (path: string): Promise<ParsedRequirements> =>
|
||||
invoke('requirements_read', { path })
|
||||
|
||||
/** What PipDock has written to disk, by artefact (PRD P1-4). */
|
||||
export const cacheUsage = (): Promise<CacheUsage> => invoke('cache_usage')
|
||||
|
||||
/**
|
||||
* Remove one cache target, resolving to the bytes freed.
|
||||
*
|
||||
* A `CacheTarget`, never a path — Rust owns the mapping and checks the result is inside the data
|
||||
* root before removing anything. `index.db` is deliberately not a target: it holds settings, pins
|
||||
* and the consent record as well as the package index.
|
||||
*/
|
||||
export const cacheClear = (target: CacheTarget): Promise<number> =>
|
||||
invoke('cache_clear', { target })
|
||||
|
||||
/**
|
||||
* What `indexSearch` resolves to.
|
||||
*
|
||||
@@ -397,6 +457,29 @@ export const pipUpgrade = (env: PyEnv): Promise<StepResult> => invoke('pip_upgra
|
||||
export const healthRun = (env: PyEnv, project: string): Promise<HealthReport> =>
|
||||
invoke('health_run', { env, project })
|
||||
|
||||
/**
|
||||
* Audit one environment against the PyPI advisory database (PRD P1-1).
|
||||
*
|
||||
* Takes only the environment: the freeze document is Rust's to produce, because which engine is
|
||||
* configured changes what is in it — pip includes pip and setuptools, uv does not.
|
||||
*
|
||||
* Slow by nature. 18-68 s measured, dominated by a one-off advisory-database fetch rather than by
|
||||
* the package count, which is why `auditCancel` exists at all and `health_run` has no equivalent.
|
||||
*/
|
||||
export const auditRun = (env: PyEnv): Promise<AuditReport> => invoke('audit_run', { env })
|
||||
|
||||
/** Stop a running audit; resolves false when there was nothing to stop. */
|
||||
export const auditCancel = (): Promise<boolean> => invoke('audit_cancel')
|
||||
|
||||
/**
|
||||
* Write a finished audit beside `path`, as Markdown and JSON, resolving to both paths.
|
||||
*
|
||||
* The picker only asks for a path; Rust does the writing, because `default.json` grants no `fs`
|
||||
* permission at all. `healthSaveReport` is the same shape.
|
||||
*/
|
||||
export const auditSaveReport = (report: AuditReport, path: string): Promise<string[]> =>
|
||||
invoke('audit_save_report', { report, path })
|
||||
|
||||
/**
|
||||
* Write the report beside `path`, as Markdown and JSON. Returns the two paths written.
|
||||
*
|
||||
@@ -477,6 +560,26 @@ export const pickProjectFolder = async (
|
||||
export const pickSavePath = async (title: string, defaultName: string): Promise<string | null> =>
|
||||
(await save({ title, defaultPath: defaultName })) ?? null
|
||||
|
||||
/**
|
||||
* Ask for one existing file.
|
||||
*
|
||||
* `pickProjectFolder`'s sibling, with `directory: false` — the same `dialog:allow-open` permission
|
||||
* covers both, and neither grants the webview any ability to *read* what it named. That is Rust's
|
||||
* job (`requirements_read`).
|
||||
*/
|
||||
export const pickOpenFile = async (
|
||||
title: string,
|
||||
extensions: string[],
|
||||
): Promise<string | null> => {
|
||||
const chosen = await open({
|
||||
directory: false,
|
||||
multiple: false,
|
||||
title,
|
||||
filters: [{ name: title, extensions }],
|
||||
})
|
||||
return typeof chosen === 'string' ? chosen : null
|
||||
}
|
||||
|
||||
/** Subscribe to discovery progress. Returns the unlisten function. */
|
||||
export const onScanProgress = (handler: (progress: ScanProgress) => void): Promise<UnlistenFn> =>
|
||||
listen<ScanProgress>('scan-progress', (event) => {
|
||||
@@ -497,3 +600,11 @@ export const onHealthProgress = (
|
||||
listen<ProgressEvent>('health-progress', (event) => {
|
||||
handler(event.payload)
|
||||
})
|
||||
|
||||
/** The same payload again, on the Security tab's own channel. */
|
||||
export const onAuditProgress = (
|
||||
handler: (event: ProgressEvent) => void,
|
||||
): Promise<UnlistenFn> =>
|
||||
listen<ProgressEvent>('audit-progress', (event) => {
|
||||
handler(event.payload)
|
||||
})
|
||||
@@ -165,11 +165,53 @@
|
||||
"checkFinding": "{{pkg}} requires {{requirement}}",
|
||||
"done": "Back to packages"
|
||||
},
|
||||
"palette": {
|
||||
"title": "Commands",
|
||||
"placeholder": "Type a command…",
|
||||
"noMatch": "nothing matches “{{query}}”",
|
||||
"refreshPackages": "Refresh the package list",
|
||||
"clearSelection": "Clear the selection",
|
||||
"clearQueue": "Empty the install queue",
|
||||
"groups": {
|
||||
"go": "Go to"
|
||||
}
|
||||
},
|
||||
"pins": {
|
||||
"empty": "no pins in this environment",
|
||||
"emptyHint": "Pin a package from the Installed table to keep bulk updates away from it.",
|
||||
"reasonPlaceholder": "Why is this pinned?",
|
||||
"reasonFor": "Reason for pinning {{pkg}}"
|
||||
"reasonFor": "Reason for pinning {{pkg}}",
|
||||
"suggestTitle": "Worth pinning",
|
||||
"suggestIntro": "These are depended on by a lot of what you have installed, so a bulk update is more likely to disturb something. Pinning keeps them out of Select all — you can still update them one at a time.",
|
||||
"suggest_one": "{{pkg}} — {{count}} package depends on it.",
|
||||
"suggest_other": "{{pkg}} — {{count}} packages depend on it.",
|
||||
"suggestMore_one": "{{count}} more package would qualify. Pin some of these, or raise the count in Settings.",
|
||||
"suggestMore_other": "{{count}} more packages would qualify. Pin some of these, or raise the count in Settings.",
|
||||
"suggestAccept": "Pin",
|
||||
"suggestAcceptFor": "Pin {{pkg}}",
|
||||
"suggestReason_one": "{{count}} package depended on it",
|
||||
"suggestReason_other": "{{count}} packages depended on it"
|
||||
},
|
||||
"requirements": {
|
||||
"title": "Requirements file",
|
||||
"intro": "Write this environment out as a requirements.txt, or read one in. Importing previews and snapshots like any other install — it never writes to the environment on its own.",
|
||||
"export": "Export…",
|
||||
"import": "Import…",
|
||||
"exportTitle": "Save the environment as",
|
||||
"importTitle": "Choose a requirements file",
|
||||
"wrote": "Written to",
|
||||
"readCount_one": "{{count}} package to install.",
|
||||
"readCount_other": "{{count}} packages to install.",
|
||||
"skippedCount_one": "{{count}} line was not used:",
|
||||
"skippedCount_other": "{{count}} lines were not used:",
|
||||
"install_one": "Preview installing {{count}} package",
|
||||
"install_other": "Preview installing {{count}} packages",
|
||||
"skip": {
|
||||
"include": "names another file, which PipDock has not read",
|
||||
"not-from-index": "installs from somewhere other than the package index",
|
||||
"option": "an option that would change how everything installs",
|
||||
"unparsed": "not a requirement PipDock can read"
|
||||
}
|
||||
},
|
||||
"snapshots": {
|
||||
"title": "Snapshots",
|
||||
@@ -206,6 +248,24 @@
|
||||
"manual": "taken by you"
|
||||
}
|
||||
},
|
||||
"cache": {
|
||||
"title": "Disk usage",
|
||||
"intro": "Everything PipDock has written lives under one folder. Clearing any of these loses only what the line says; nothing about your Python environments changes.",
|
||||
"database": "Package index, settings and pins",
|
||||
"databaseWhy": "Not clearable — this one file also holds your settings, your pins and your record of accepting the legal documents. Use Search → Download the index to refresh the package list.",
|
||||
"snapshots": "Snapshots",
|
||||
"snapshotCount_one": "({{count}} snapshot)",
|
||||
"snapshotCount_other": "({{count}} snapshots)",
|
||||
"tools": "Code Health tools",
|
||||
"audit": "Security tool environment",
|
||||
"clear": "Clear",
|
||||
"confirmTitle": "Clear this?",
|
||||
"confirm": {
|
||||
"snapshots": "Every snapshot of every environment is removed, and rollback loses its history. Your installed packages are untouched — this deletes the record, not the environment.",
|
||||
"tools": "The isolated environment deptry, vulture and ruff run from is removed. The next Code Health run rebuilds it, which needs a network connection.",
|
||||
"audit": "The isolated environment pip-audit runs from is removed. The next audit rebuilds it, which takes about a minute. Nothing in your own environments changes."
|
||||
}
|
||||
},
|
||||
"health": {
|
||||
"title": "Code Health",
|
||||
"chooseFolder": "Choose folder…",
|
||||
@@ -265,6 +325,29 @@
|
||||
"fixConfirm": "Fix",
|
||||
"fixConfirmDirty": "Fix anyway"
|
||||
},
|
||||
"security": {
|
||||
"run": "Run audit",
|
||||
"running": "Checking against the advisory database…",
|
||||
"cancelled": "Stopped before it finished, so what follows is incomplete.",
|
||||
"checkedAt": "Checked {{at}} with pip-audit {{version}}",
|
||||
"noEnv": "Select an environment first.",
|
||||
"notRunYet": "No audit has run for this environment.",
|
||||
"notRunYetHint": "The first run builds its own tool environment, which takes about a minute.",
|
||||
"clean_one": "No known advisories against {{count}} package.",
|
||||
"clean_other": "No known advisories against {{count}} packages.",
|
||||
"cleanHint": "Checked with pip-audit {{version}} against PyPI's advisory data.",
|
||||
"summary_one": "{{count}} advisory across {{packages}} of {{total}} packages.",
|
||||
"summary_other": "{{count}} advisories across {{packages}} of {{total}} packages.",
|
||||
"more_one": "{{count}} more advisory is not shown.",
|
||||
"more_other": "{{count}} more advisories are not shown.",
|
||||
"noFix": "no fix",
|
||||
"fixedIn": "fixed in {{versions}}",
|
||||
"osv": "OSV entry",
|
||||
"linkFailed": "That link could not be opened.",
|
||||
"save": "Save report…",
|
||||
"saveTitle": "Save the security audit",
|
||||
"saved": "Saved {{files}}"
|
||||
},
|
||||
"uninstall": {
|
||||
"title": "Remove packages",
|
||||
"titleBreaks": "This removal breaks other packages",
|
||||
@@ -317,6 +400,8 @@
|
||||
"engineDetail": "Which resolver PipDock drives. Both are supported; uv is faster, pip is always present.",
|
||||
"locale": "Language",
|
||||
"localeSystem": "Follow the system",
|
||||
"pinThreshold": "Suggest pinning at",
|
||||
"pinThresholdDetail": "How many other packages must depend on something before the Pins screen suggests pinning it. Zero turns the suggestions off.",
|
||||
"override": "Allow externally managed environments",
|
||||
"overrideDetail": "PEP 668 marks some Pythons as managed by the operating system. Installing into one can break system tools, and there is no undo beyond a snapshot. Leave this off unless you know why you need it.",
|
||||
"saved": "Saved"
|
||||
|
||||
@@ -158,11 +158,47 @@
|
||||
"checkFinding": "{{pkg}} yêu cầu {{requirement}}",
|
||||
"done": "Quay lại danh sách gói"
|
||||
},
|
||||
"palette": {
|
||||
"title": "Lệnh",
|
||||
"placeholder": "Gõ tên một lệnh…",
|
||||
"noMatch": "không có lệnh nào khớp “{{query}}”",
|
||||
"refreshPackages": "Tải lại danh sách gói",
|
||||
"clearSelection": "Bỏ chọn tất cả",
|
||||
"clearQueue": "Xoá hàng đợi cài đặt",
|
||||
"groups": {
|
||||
"go": "Đi tới"
|
||||
}
|
||||
},
|
||||
"pins": {
|
||||
"empty": "môi trường này chưa có gói nào được ghim",
|
||||
"emptyHint": "Ghim một gói từ bảng Đã cài để các lần cập nhật hàng loạt bỏ qua nó.",
|
||||
"reasonPlaceholder": "Vì sao ghim gói này?",
|
||||
"reasonFor": "Lý do ghim {{pkg}}"
|
||||
"reasonFor": "Lý do ghim {{pkg}}",
|
||||
"suggestTitle": "Nên cân nhắc ghim",
|
||||
"suggestIntro": "Rất nhiều gói bạn đang cài phụ thuộc vào những gói này, nên một lần cập nhật hàng loạt dễ làm xáo trộn thứ gì đó. Ghim sẽ giữ chúng ngoài Chọn tất cả — bạn vẫn có thể cập nhật từng gói một.",
|
||||
"suggest_other": "{{pkg}} — {{count}} gói phụ thuộc vào nó.",
|
||||
"suggestMore_other": "Còn {{count}} gói nữa cũng đủ điều kiện. Hãy ghim bớt, hoặc nâng ngưỡng trong Cài đặt.",
|
||||
"suggestAccept": "Ghim",
|
||||
"suggestAcceptFor": "Ghim {{pkg}}",
|
||||
"suggestReason_other": "{{count}} gói đã phụ thuộc vào nó"
|
||||
},
|
||||
"requirements": {
|
||||
"title": "Tệp requirements",
|
||||
"intro": "Ghi môi trường này ra một tệp requirements.txt, hoặc đọc một tệp vào. Khi nhập, PipDock vẫn xem trước và chụp ảnh như mọi lần cài khác — nó không bao giờ tự ghi vào môi trường.",
|
||||
"export": "Xuất…",
|
||||
"import": "Nhập…",
|
||||
"exportTitle": "Lưu môi trường thành",
|
||||
"importTitle": "Chọn tệp requirements",
|
||||
"wrote": "Đã ghi vào",
|
||||
"readCount_other": "{{count}} gói sẽ được cài.",
|
||||
"skippedCount_other": "{{count}} dòng không dùng được:",
|
||||
"install_other": "Xem trước việc cài {{count}} gói",
|
||||
"skip": {
|
||||
"include": "trỏ tới một tệp khác mà PipDock chưa đọc",
|
||||
"not-from-index": "cài từ nơi khác chứ không phải chỉ mục gói",
|
||||
"option": "một tuỳ chọn làm thay đổi cách mọi thứ được cài",
|
||||
"unparsed": "không phải một requirement PipDock đọc được"
|
||||
}
|
||||
},
|
||||
"snapshots": {
|
||||
"title": "Ảnh chụp",
|
||||
@@ -192,6 +228,23 @@
|
||||
"manual": "bạn tự chụp"
|
||||
}
|
||||
},
|
||||
"cache": {
|
||||
"title": "Dung lượng đĩa",
|
||||
"intro": "Mọi thứ PipDock ghi ra đều nằm trong một thư mục. Xoá bất kỳ mục nào cũng chỉ mất đúng thứ ghi trên dòng đó; các môi trường Python của bạn không thay đổi gì.",
|
||||
"database": "Chỉ mục gói, cài đặt và danh sách ghim",
|
||||
"databaseWhy": "Không xoá được — tệp này còn giữ cài đặt, các gói bạn đã ghim và việc bạn đã chấp nhận tài liệu pháp lý. Muốn làm mới danh sách gói, dùng Tìm kiếm → Tải chỉ mục.",
|
||||
"snapshots": "Ảnh chụp",
|
||||
"snapshotCount_other": "({{count}} ảnh chụp)",
|
||||
"tools": "Bộ công cụ Sức khỏe mã",
|
||||
"audit": "Môi trường công cụ bảo mật",
|
||||
"clear": "Xoá",
|
||||
"confirmTitle": "Xoá mục này?",
|
||||
"confirm": {
|
||||
"snapshots": "Toàn bộ ảnh chụp của mọi môi trường sẽ bị xoá, và chức năng hoàn tác mất lịch sử. Các gói đã cài không bị đụng tới — thao tác này xoá bản ghi, không xoá môi trường.",
|
||||
"tools": "Môi trường biệt lập mà deptry, vulture và ruff chạy trong đó sẽ bị xoá. Lần chạy Sức khỏe mã tiếp theo sẽ dựng lại nó, và việc đó cần kết nối mạng.",
|
||||
"audit": "Môi trường biệt lập mà pip-audit chạy trong đó sẽ bị xóa. Lần quét sau sẽ dựng lại, mất khoảng một phút. Các môi trường của bạn không thay đổi."
|
||||
}
|
||||
},
|
||||
"health": {
|
||||
"title": "Sức khỏe mã",
|
||||
"chooseFolder": "Chọn thư mục…",
|
||||
@@ -243,6 +296,26 @@
|
||||
"fixConfirm": "Sửa",
|
||||
"fixConfirmDirty": "Vẫn sửa"
|
||||
},
|
||||
"security": {
|
||||
"run": "Quét bảo mật",
|
||||
"running": "Đang đối chiếu với cơ sở dữ liệu lỗ hổng…",
|
||||
"cancelled": "Đã dừng giữa chừng, nên kết quả bên dưới chưa đầy đủ.",
|
||||
"checkedAt": "Đã kiểm tra {{at}} bằng pip-audit {{version}}",
|
||||
"noEnv": "Hãy chọn một môi trường trước.",
|
||||
"notRunYet": "Chưa quét môi trường này lần nào.",
|
||||
"notRunYetHint": "Lần chạy đầu sẽ dựng môi trường công cụ riêng, mất khoảng một phút.",
|
||||
"clean_other": "Không có lỗ hổng đã biết trong {{count}} gói.",
|
||||
"cleanHint": "Đã kiểm tra bằng pip-audit {{version}} với dữ liệu lỗ hổng của PyPI.",
|
||||
"summary_other": "{{count}} lỗ hổng trên {{packages}} trong tổng số {{total}} gói.",
|
||||
"more_other": "Còn {{count}} lỗ hổng nữa chưa hiển thị.",
|
||||
"noFix": "chưa có bản vá",
|
||||
"fixedIn": "vá ở {{versions}}",
|
||||
"osv": "Trang OSV",
|
||||
"linkFailed": "Không mở được liên kết đó.",
|
||||
"save": "Lưu báo cáo…",
|
||||
"saveTitle": "Lưu báo cáo bảo mật",
|
||||
"saved": "Đã lưu {{files}}"
|
||||
},
|
||||
"uninstall": {
|
||||
"title": "Gỡ gói",
|
||||
"titleBreaks": "Thao tác gỡ này làm hỏng gói khác",
|
||||
@@ -289,6 +362,8 @@
|
||||
"engineDetail": "Bộ giải phụ thuộc mà PipDock điều khiển. Cả hai đều được hỗ trợ; uv nhanh hơn, pip thì luôn có sẵn.",
|
||||
"locale": "Ngôn ngữ",
|
||||
"localeSystem": "Theo hệ thống",
|
||||
"pinThreshold": "Gợi ý ghim khi đạt",
|
||||
"pinThresholdDetail": "Cần bao nhiêu gói khác phụ thuộc vào một gói thì màn hình Ghim mới gợi ý ghim nó. Đặt 0 để tắt gợi ý.",
|
||||
"override": "Cho phép môi trường do hệ thống quản lý",
|
||||
"overrideDetail": "PEP 668 đánh dấu một số bản Python là do hệ điều hành quản lý. Cài vào đó có thể làm hỏng công cụ hệ thống, và không có cách hoàn tác nào ngoài ảnh chụp. Hãy để tắt trừ khi bạn biết rõ vì sao cần bật.",
|
||||
"saved": "Đã lưu"
|
||||
|
||||
@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdEmptyState } from '@/components/PdEmptyState'
|
||||
import { PdErrorRow } from '@/components/PdErrorRow'
|
||||
import { PdRequirements } from '@/components/PdRequirements'
|
||||
import { PdSnapshotTimeline } from '@/components/PdSnapshotTimeline'
|
||||
import { useEnvStore, usePlanStore } from '@/stores'
|
||||
import { useEnvSnapshots } from '@/screens/useEnvSnapshots'
|
||||
@@ -74,6 +75,8 @@ export function PdEnvDetail() {
|
||||
|
||||
<p className="mt-1 font-mono text-data text-text-dim">{openFor}</p>
|
||||
|
||||
<PdRequirements env={env} />
|
||||
|
||||
{usable ? null : (
|
||||
<p className="mt-2 rounded-pd border-l-2 border-warn pl-2 text-data text-text-dim">
|
||||
{t('snapshots.envUnusable')}
|
||||
|
||||
@@ -23,16 +23,25 @@ vi.mock('@/ipc', async () => {
|
||||
|
||||
const PINS = pinFixture as Pin[]
|
||||
|
||||
/** Put the store where it would be after an environment was selected and loaded. */
|
||||
const INTERPRETER = 'C:\\venv\\Scripts\\python.exe'
|
||||
|
||||
/**
|
||||
* Put the store where it would be after an environment was selected and loaded.
|
||||
*
|
||||
* The row carries `env`, because a real one does whenever the probe succeeded — and
|
||||
* `pin_suggestions` takes a whole `PyEnv`, so a fixture without it silently tests the
|
||||
* probe-failed path instead. `env` being optional is the point of the last case below.
|
||||
*/
|
||||
function withEnv(pins: Pin[] = PINS) {
|
||||
useEnvStore.setState({
|
||||
selected: 'C:\\venv\\Scripts\\python.exe',
|
||||
loadedFor: 'C:\\venv\\Scripts\\python.exe',
|
||||
selected: INTERPRETER,
|
||||
loadedFor: INTERPRETER,
|
||||
rows: [
|
||||
{
|
||||
interpreter: 'C:\\venv\\Scripts\\python.exe',
|
||||
interpreter: INTERPRETER,
|
||||
envHash: 'envhash01',
|
||||
source: 'manual',
|
||||
env: { interpreter: INTERPRETER, pythonVersion: '3.12.4', externallyManaged: false },
|
||||
} as never,
|
||||
],
|
||||
pins,
|
||||
@@ -116,6 +125,130 @@ describe('PdPins', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('suggestions', () => {
|
||||
/** Two suggestions, as `pin_suggestions` orders them: most-depended-upon first. */
|
||||
const SUGGESTIONS = [
|
||||
{ pkg: 'urllib3', dependents: 12 },
|
||||
{ pkg: 'certifi', dependents: 1 },
|
||||
]
|
||||
|
||||
it('asks for suggestions once per environment, not once per render', async () => {
|
||||
// Each call is a `probe.py` run. StrictMode double-invokes effects and the store's guard is
|
||||
// checked synchronously for that reason — the same defect `loadSnapshots` records, and the
|
||||
// same one `app_info` shipped with.
|
||||
withEnv()
|
||||
vi.mocked(ipc.pinSuggestions).mockResolvedValue(SUGGESTIONS)
|
||||
const first = render(<PdPins />)
|
||||
await vi.waitFor(() => {
|
||||
expect(ipc.pinSuggestions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
first.unmount()
|
||||
render(<PdPins />)
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByText(/urllib3 — 12 packages depend on it/)).toBeInTheDocument()
|
||||
})
|
||||
expect(ipc.pinSuggestions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('states the count, and pluralises it', async () => {
|
||||
// UI-SPEC §4 fixes this sentence. One dependent is a different sentence from twelve, and a
|
||||
// catalog with only `_other` renders "1 packages" — which is the failure I18N §1 forbids.
|
||||
withEnv()
|
||||
vi.mocked(ipc.pinSuggestions).mockResolvedValue(SUGGESTIONS)
|
||||
render(<PdPins />)
|
||||
|
||||
expect(
|
||||
await screen.findByText('urllib3 — 12 packages depend on it.'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText('certifi — 1 package depends on it.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('pins with the count as the reason, and drops the suggestion', async () => {
|
||||
// PRD P1-2: "suggest pin with reason". The reason is editable below, so this is a starting
|
||||
// point rather than the last word — but a pin with no reason is the mystery the reason
|
||||
// field exists to prevent.
|
||||
withEnv([])
|
||||
vi.mocked(ipc.pinSuggestions).mockResolvedValue(SUGGESTIONS)
|
||||
render(<PdPins />)
|
||||
|
||||
fireEvent.click(await screen.findByLabelText('Pin urllib3'))
|
||||
await vi.waitFor(() => {
|
||||
expect(ipc.pinAdd).toHaveBeenCalledWith('envhash01', {
|
||||
pkg: 'urllib3',
|
||||
mode: 'exclude',
|
||||
reason: '12 packages depended on it',
|
||||
})
|
||||
})
|
||||
// Gone from the section without a second probe: the answer cannot have changed.
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.queryByLabelText('Pin urllib3')).not.toBeInTheDocument()
|
||||
})
|
||||
expect(ipc.pinSuggestions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('caps the list and says how many it did not show', async () => {
|
||||
// Found by running against the 352-package fixture: the default threshold of 5 qualifies 94
|
||||
// packages there. A quarter of the environment is not a suggestion, it is a second package
|
||||
// list — and the deep trees where that happens are exactly where the feature matters, so
|
||||
// the answer is a bounded view, not a higher default.
|
||||
withEnv()
|
||||
vi.mocked(ipc.pinSuggestions).mockResolvedValue(
|
||||
Array.from({ length: 94 }, (_, i) => ({ pkg: `pkg${i}`, dependents: 100 - i })),
|
||||
)
|
||||
render(<PdPins />)
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByText(/86 more packages would qualify/)).toBeInTheDocument()
|
||||
})
|
||||
// The count is from the *full* list, so a capped view never misreports the total.
|
||||
expect(screen.getAllByRole('button', { name: /^Pin pkg/ })).toHaveLength(8)
|
||||
})
|
||||
|
||||
it('renders nothing at all when there is nothing to suggest', () => {
|
||||
// An empty "Worth pinning" heading is a question nobody asked.
|
||||
withEnv()
|
||||
render(<PdPins />)
|
||||
expect(screen.queryByText('Worth pinning')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stays quiet when the suggestion fetch fails', async () => {
|
||||
// Advisory. This screen's job is listing pins, and it does that either way — so a failure
|
||||
// must not put an error row above the thing the user came for.
|
||||
withEnv()
|
||||
vi.mocked(ipc.pinSuggestions).mockRejectedValue({ code: 'PD-ENV-003', message: 'nope' })
|
||||
render(<PdPins />)
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(ipc.pinSuggestions).toHaveBeenCalled()
|
||||
})
|
||||
expect(screen.queryByText('Worth pinning')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
// The list it exists to show is still there.
|
||||
expect(document.querySelector('[data-pin="numpy"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('asks for nothing without an environment', () => {
|
||||
render(<PdPins />)
|
||||
expect(ipc.pinSuggestions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('asks for nothing when the environment could not be probed', () => {
|
||||
// `EnvRow.env` is absent exactly when the probe failed, and a suggestion needs an
|
||||
// interpreter to probe. The pin list still renders — it is keyed by hash and outlives the
|
||||
// Python that made it.
|
||||
useEnvStore.setState({
|
||||
selected: INTERPRETER,
|
||||
loadedFor: INTERPRETER,
|
||||
rows: [{ interpreter: INTERPRETER, envHash: 'envhash01', source: 'manual' } as never],
|
||||
pins: PINS,
|
||||
})
|
||||
render(<PdPins />)
|
||||
|
||||
expect(ipc.pinSuggestions).not.toHaveBeenCalled()
|
||||
expect(document.querySelector('[data-pin="numpy"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('offers no way to create a Hold pin', () => {
|
||||
// `pins::hold_requirements` is dead code and `plan_requirements` restates the *installed*
|
||||
// version, so a hold at another version is a promise nothing keeps. The CLI cannot create one
|
||||
|
||||
@@ -10,13 +10,18 @@
|
||||
* one in principle — but does not offer to create one, because `pins::hold_requirements` is dead
|
||||
* code in the core and `engine::plan_requirements` restates each package at its *installed*
|
||||
* version. A hold at any other version is a promise nothing keeps, and offering it here would be
|
||||
* the interface lying about what the engine does. §4's auto-suggest section is P1 and absent.
|
||||
* the interface lying about what the engine does.
|
||||
*
|
||||
* The reason commits on blur rather than on every keystroke: it is a `pin_add` upsert per commit,
|
||||
* and one round trip per character typed is a lot of SQLite for a text field.
|
||||
*
|
||||
* **The suggestion section is §4's, and it lands here rather than anywhere louder.** It costs one
|
||||
* `probe.py` run, so it is paid by someone who opened this tab — a sidebar badge would charge
|
||||
* every user, including those who never pin anything. It is also silent on failure: this screen's
|
||||
* job is listing pins, and an error row about an *advisory* would be the loudest thing on it.
|
||||
*/
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdEmptyState } from '@/components/PdEmptyState'
|
||||
@@ -25,6 +30,21 @@ import { PdPinChip } from '@/components/PdPinChip'
|
||||
import { useEnvPackages } from '@/screens/useEnvPackages'
|
||||
import { useEnvStore } from '@/stores'
|
||||
|
||||
/**
|
||||
* How many suggestions to offer at once.
|
||||
*
|
||||
* **Measured, not guessed.** Against the 352-package scale fixture the default threshold of 5
|
||||
* qualifies **94** packages — a quarter of the environment, which is not a suggestion but a second
|
||||
* package list. Deep dependency trees are exactly where a bulk update is most dangerous and
|
||||
* therefore exactly where this feature matters, so the answer cannot be "raise the default until
|
||||
* the list is short".
|
||||
*
|
||||
* Bounded here rather than in `pins::suggest`, which correctly returns everything at or above the
|
||||
* threshold: the count below is *from the full list*, so a capped view never misreports the total.
|
||||
* The same rule `PdHealthReport`'s `RUFF_ROWS_SHOWN` follows, for the same reason.
|
||||
*/
|
||||
export const SUGGESTIONS_SHOWN = 8
|
||||
|
||||
export function PdPins() {
|
||||
const { t } = useTranslation()
|
||||
const selected = useEnvStore((s) => s.selected)
|
||||
@@ -32,9 +52,19 @@ export function PdPins() {
|
||||
const listError = useEnvStore((s) => s.listError)
|
||||
const togglePin = useEnvStore((s) => s.togglePin)
|
||||
const updatePin = useEnvStore((s) => s.updatePin)
|
||||
const suggestions = useEnvStore((s) => s.suggestions)
|
||||
const loadSuggestions = useEnvStore((s) => s.loadSuggestions)
|
||||
const acceptSuggestion = useEnvStore((s) => s.acceptSuggestion)
|
||||
|
||||
useEnvPackages()
|
||||
|
||||
// Its own effect rather than a third fetch inside `useEnvPackages`: that hook's two calls share
|
||||
// one `loadedFor` flag, and folding a probe-costing third into it would tie its staleness to
|
||||
// theirs. The store keys this on `suggestionsFor` and refuses a concurrent second call.
|
||||
useEffect(() => {
|
||||
if (selected !== null) void loadSuggestions()
|
||||
}, [selected, loadSuggestions])
|
||||
|
||||
return (
|
||||
<section aria-labelledby="pins-title" className="h-full overflow-auto p-6">
|
||||
<h1 id="pins-title" className="text-accent">
|
||||
@@ -47,6 +77,57 @@ export function PdPins() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Above the list, because it is a prompt to act and the list below is a record of having
|
||||
acted. Absent entirely when there is nothing to suggest — an empty "Worth pinning"
|
||||
heading is a question nobody asked. */}
|
||||
{selected !== null && suggestions.length > 0 ? (
|
||||
<section aria-labelledby="pins-suggest" className="mt-4">
|
||||
<h2 id="pins-suggest" className="text-text-dim">
|
||||
{t('pins.suggestTitle')}
|
||||
</h2>
|
||||
<p className="mt-1 max-w-2xl text-data text-text-dim">{t('pins.suggestIntro')}</p>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{suggestions.slice(0, SUGGESTIONS_SHOWN).map((s) => (
|
||||
<li
|
||||
key={s.pkg}
|
||||
data-suggestion={s.pkg}
|
||||
className="flex items-center gap-3 rounded-pd border border-border bg-surface px-3 py-1.5"
|
||||
>
|
||||
{/* UI-SPEC §4 fixes this sentence: "urllib3 — 12 packages depend on it." The name
|
||||
is data and is interpolated, never translated (I18N §2). */}
|
||||
<span className="min-w-0 flex-1 text-data">
|
||||
{t('pins.suggest', { pkg: s.pkg, count: s.dependents })}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('pins.suggestAcceptFor', { pkg: s.pkg })}
|
||||
onClick={() => {
|
||||
// PRD P1-2: "suggest pin with reason". The count is what justified the
|
||||
// suggestion, so it is what the pin records — and the field below is
|
||||
// editable, so the user can replace it with their own.
|
||||
void acceptSuggestion(
|
||||
s.pkg,
|
||||
t('pins.suggestReason', { count: s.dependents }),
|
||||
)
|
||||
}}
|
||||
data-action="accept-suggestion"
|
||||
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim hover:bg-surface-2"
|
||||
>
|
||||
{t('pins.suggestAccept')}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{/* Never a silent cap. The number comes from the full list, so it is the honest total
|
||||
rather than the length of what is rendered. */}
|
||||
{suggestions.length > SUGGESTIONS_SHOWN ? (
|
||||
<p className="mt-2 text-data text-text-dim">
|
||||
{t('pins.suggestMore', { count: suggestions.length - SUGGESTIONS_SHOWN })}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{selected === null ? (
|
||||
// Pins are stored per `envHash`, so with no environment there is not an empty list — there
|
||||
// is no list. Saying "no pins" here would read as "this environment has none".
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The Security screen — the states around the list, which `PdAuditReport.test.tsx` does not cover.
|
||||
*
|
||||
* It exists because of what it caught. Driving the screen against a deliberately slow bridge showed
|
||||
* the body reading **"No audit has run for this environment"** *while an audit was running*: the
|
||||
* report is cleared before the command, so `shown` is null during a run, and the un-run empty state
|
||||
* was rendered on that basis. That is P4's "no issues found before anything had run" inverted — a
|
||||
* true-looking sentence derived from a state the screen had not loaded — and no test saw it,
|
||||
* because every other test renders this screen settled.
|
||||
*/
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { PdSecurity } from '@/screens/PdSecurity'
|
||||
import type { AuditReport } from '@/ipc'
|
||||
import { useEnvStore, useSecurityStore } from '@/stores'
|
||||
import auditFixture from '@/test/fixtures/audit_report.json'
|
||||
|
||||
vi.mock('@/ipc', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/ipc')>('@/ipc')
|
||||
return { ...actual, auditRun: vi.fn(), auditCancel: vi.fn(), onAuditProgress: vi.fn() }
|
||||
})
|
||||
|
||||
const REPORT = auditFixture as AuditReport
|
||||
const ENV_HASH = 'abc123'
|
||||
|
||||
const ROW = {
|
||||
interpreter: String.raw`C:\proj\.venv\Scripts\python.exe`,
|
||||
source: 'venv' as const,
|
||||
envHash: ENV_HASH,
|
||||
env: {
|
||||
interpreter: String.raw`C:\proj\.venv\Scripts\python.exe`,
|
||||
prefix: String.raw`C:\proj\.venv`,
|
||||
pythonVersion: '3.12.10',
|
||||
externallyManaged: false,
|
||||
source: 'venv' as const,
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useSecurityStore.setState({
|
||||
phase: 'idle',
|
||||
report: null,
|
||||
reportFor: null,
|
||||
error: null,
|
||||
console: [],
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: null,
|
||||
})
|
||||
useEnvStore.setState({ rows: [ROW], selected: ROW.interpreter } as never)
|
||||
})
|
||||
|
||||
describe('PdSecurity', () => {
|
||||
it('says nothing has run when nothing has', () => {
|
||||
render(<PdSecurity />)
|
||||
|
||||
expect(screen.getByText(/No audit has run for this environment/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not claim nothing has run while a run is going', () => {
|
||||
// The defect this file was written for. Asserted as an absence, so it fails if the un-run
|
||||
// empty state comes back — which it would, because `shown` is legitimately null here.
|
||||
useSecurityStore.setState({ phase: 'running' })
|
||||
render(<PdSecurity />)
|
||||
|
||||
expect(screen.queryByText(/No audit has run/)).toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Run audit' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('shows the report only for the environment it belongs to', () => {
|
||||
// `reportFor` is the whole reason the store keeps it: a plain `report` read would leave one
|
||||
// environment's advisories on screen after the user switched to another.
|
||||
useSecurityStore.setState({ phase: 'ready', report: REPORT, reportFor: 'a-different-env' })
|
||||
render(<PdSecurity />)
|
||||
|
||||
expect(screen.queryByText(/13 advisories/)).toBeNull()
|
||||
expect(screen.getByText(/No audit has run for this environment/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the advisories once the report matches', () => {
|
||||
useSecurityStore.setState({ phase: 'ready', report: REPORT, reportFor: ENV_HASH })
|
||||
render(<PdSecurity />)
|
||||
|
||||
expect(screen.getByText(/13 advisories across 2 of 2 packages/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('says a cancelled run was cancelled, and keeps what it got', () => {
|
||||
// A cancel is a state, not an error: no error row, and the partial result stays on screen.
|
||||
useSecurityStore.setState({
|
||||
phase: 'ready',
|
||||
report: { ...REPORT, cancelled: true },
|
||||
reportFor: ENV_HASH,
|
||||
})
|
||||
render(<PdSecurity />)
|
||||
|
||||
expect(screen.getByText(/Stopped before it finished/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/13 advisories/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Security — PRD P1-1, SECURITY §6, UI-SPEC §3's seventh tab.
|
||||
*
|
||||
* The screen owns the run, the errors and the progress; `PdAuditReport` owns the list. Same
|
||||
* division as `PdHealth`/`PdHealthReport`, and it is what lets the list be tested against a
|
||||
* generated fixture with no store at all.
|
||||
*
|
||||
* **Never says "no advisories" before a run.** The screen routes an un-run environment to its own
|
||||
* empty state and only hands a *report* to `PdAuditReport`, because "nothing was found" and
|
||||
* "nothing has run" are different claims and P4 shipped the wrong one once already.
|
||||
*/
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdAuditReport } from '@/components/PdAuditReport'
|
||||
import { PdConsoleDrawer } from '@/components/PdConsoleDrawer'
|
||||
import { PdEmptyState } from '@/components/PdEmptyState'
|
||||
import { PdErrorRow } from '@/components/PdErrorRow'
|
||||
import { auditSaveReport, pickSavePath } from '@/ipc'
|
||||
import type { PdError, ToolProblem } from '@/ipc'
|
||||
import { freshAudit, useEnvStore, useSecurityStore } from '@/stores'
|
||||
|
||||
/** A `ToolProblem` is `PdError`-shaped on purpose, so the row takes it directly. */
|
||||
function asError(problem: ToolProblem): PdError {
|
||||
return {
|
||||
code: problem.code,
|
||||
message: problem.message,
|
||||
...(problem.stderrTail == null ? {} : { stderrTail: problem.stderrTail }),
|
||||
}
|
||||
}
|
||||
|
||||
export function PdSecurity() {
|
||||
const { t } = useTranslation()
|
||||
|
||||
// Per-field selectors throughout, for `PdHealth`'s reason: destructuring the store re-renders a
|
||||
// list of several hundred rows on every unrelated field change, including each progress tick.
|
||||
const rows = useEnvStore((s) => s.rows)
|
||||
const selected = useEnvStore((s) => s.selected)
|
||||
const phase = useSecurityStore((s) => s.phase)
|
||||
const report = useSecurityStore((s) => s.report)
|
||||
const reportFor = useSecurityStore((s) => s.reportFor)
|
||||
const error = useSecurityStore((s) => s.error)
|
||||
const lines = useSecurityStore((s) => s.console)
|
||||
const done = useSecurityStore((s) => s.done)
|
||||
const total = useSecurityStore((s) => s.total)
|
||||
const consoleOpen = useSecurityStore((s) => s.consoleOpen)
|
||||
const setConsoleOpen = useSecurityStore((s) => s.setConsoleOpen)
|
||||
const run = useSecurityStore((s) => s.run)
|
||||
const cancel = useSecurityStore((s) => s.cancel)
|
||||
|
||||
// Where the last save went, so the confirmation names the files rather than merely claiming
|
||||
// success. Screen state, not store state: it describes an action, not a report.
|
||||
const [saved, setSaved] = useState<string[] | null>(null)
|
||||
|
||||
const row = rows.find((r) => r.interpreter === selected)
|
||||
const env = row?.env
|
||||
const running = phase === 'running'
|
||||
// Only when it describes *this* environment — a plain `report` read would show one
|
||||
// environment's advisories after the user switched to another.
|
||||
const shown = row === undefined ? null : freshAudit({ report, reportFor }, row.envHash)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 tabIndex={-1} className="text-accent">
|
||||
{t('nav.security')}
|
||||
</h1>
|
||||
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
data-action="run-audit"
|
||||
disabled={running || env === undefined}
|
||||
onClick={() => {
|
||||
if (env !== undefined && row !== undefined) void run(env, row.envHash)
|
||||
}}
|
||||
className="rounded-pd bg-surface-2 px-3 py-1.5 text-accent disabled:opacity-40"
|
||||
>
|
||||
{t('security.run')}
|
||||
</button>
|
||||
|
||||
{/* Only while a run is going. An audit is 18-68 s — long enough that a user needs a way
|
||||
out, which is the measurement that changed P4's answer for Code Health. */}
|
||||
{running ? (
|
||||
<button
|
||||
type="button"
|
||||
data-action="cancel-audit"
|
||||
onClick={() => {
|
||||
void cancel()
|
||||
}}
|
||||
className="rounded-pd bg-surface-2 px-3 py-1.5 text-text-dim"
|
||||
>
|
||||
{t('actions.cancel')}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{shown === null ? null : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void pickSavePath(t('security.saveTitle'), 'security-audit.md').then((target) => {
|
||||
if (target !== null) void auditSaveReport(shown, target).then(setSaved)
|
||||
})
|
||||
}}
|
||||
className="rounded-pd bg-surface-2 px-3 py-1.5 text-text"
|
||||
>
|
||||
{t('security.save')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setConsoleOpen(!consoleOpen)
|
||||
}}
|
||||
className="ml-auto rounded-pd px-2 py-1 text-data text-text-dim"
|
||||
>
|
||||
{t('status.log')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* One live region for the whole screen. Two would serialize against each other
|
||||
unpredictably — the pair P6 folded for exactly this reason. */}
|
||||
<p aria-live="polite" className="mt-2 text-data text-text-dim">
|
||||
{running ? t('security.running') : saved === null ? '' : t('security.saved', { files: saved.join(', ') })}
|
||||
</p>
|
||||
|
||||
{/* A run that failed outright — as opposed to a tool problem inside a report, below. */}
|
||||
{error === null ? null : (
|
||||
<div className="mt-2">
|
||||
<PdErrorRow error={error} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* pip-audit failed but the report still came back, so the advisories (if any) stay on
|
||||
screen beneath this. `⚠ n` counts these rows, per UI-SPEC §3. */}
|
||||
{(shown?.problems ?? []).map((problem) => (
|
||||
<div key={problem.tool} className="mt-2">
|
||||
<PdErrorRow error={asError(problem)} />
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* **Nothing here while a run is going.** `shown` is null then — the report is cleared before
|
||||
the command so a second run cannot paint the last one's findings under a new timestamp —
|
||||
and rendering the un-run empty state on that basis said *No audit has run for this
|
||||
environment* while one was running. That is P4's "no issues found before anything had
|
||||
run", inverted: a true-looking sentence derived from a state the screen had not loaded.
|
||||
The live region above, the disabled Run and the Cancel beside it already say what is
|
||||
happening, so the body says nothing rather than something false. Found by clicking Run
|
||||
against a deliberately slow bridge; no test asserted on it, because every test that
|
||||
renders this screen renders it settled. */}
|
||||
{shown !== null ? (
|
||||
<div className="mt-4">
|
||||
{shown.cancelled ? (
|
||||
// A cancel is a state, not an error, so it is said plainly and the partial result is
|
||||
// kept rather than thrown away.
|
||||
<p className="text-data text-warn">{t('security.cancelled')}</p>
|
||||
) : null}
|
||||
<p className="text-data text-text-dim">
|
||||
{t('security.checkedAt', { at: shown.ranAt, version: shown.toolVersion })}
|
||||
</p>
|
||||
<div className="mt-2">
|
||||
<PdAuditReport report={shown} />
|
||||
</div>
|
||||
</div>
|
||||
) : running ? null : (
|
||||
<PdEmptyState
|
||||
message={env === undefined ? t('security.noEnv') : t('security.notRunYet')}
|
||||
{...(env === undefined ? {} : { hint: t('security.notRunYetHint') })}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PdConsoleDrawer
|
||||
lines={lines}
|
||||
open={consoleOpen}
|
||||
onClose={() => {
|
||||
setConsoleOpen(false)
|
||||
}}
|
||||
done={done}
|
||||
total={total}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdCacheUsage } from '@/components/PdCacheUsage'
|
||||
import { PdErrorRow } from '@/components/PdErrorRow'
|
||||
import { SUPPORTED_LOCALES, type Locale } from '@/i18n'
|
||||
import { useSettingsStore } from '@/stores'
|
||||
@@ -20,8 +21,17 @@ const ENGINES = ['pip', 'uv'] as const
|
||||
|
||||
export function PdSettings() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const { engine, allowExternallyManaged, locale, loading, error, load, save, setLocale } =
|
||||
useSettingsStore()
|
||||
const {
|
||||
engine,
|
||||
allowExternallyManaged,
|
||||
pinSuggestThreshold,
|
||||
locale,
|
||||
loading,
|
||||
error,
|
||||
load,
|
||||
save,
|
||||
setLocale,
|
||||
} = useSettingsStore()
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
@@ -83,6 +93,29 @@ export function PdSettings() {
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="mt-6" disabled={loading}>
|
||||
<legend className="text-text-dim">{t('settings.pinThreshold')}</legend>
|
||||
<p className="mt-1 max-w-2xl text-data text-text-dim">{t('settings.pinThresholdDetail')}</p>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
max={999}
|
||||
step={1}
|
||||
value={pinSuggestThreshold}
|
||||
aria-label={t('settings.pinThreshold')}
|
||||
onChange={(e) => {
|
||||
// The first number input in the app, so the rule is set here: **reject at the
|
||||
// boundary, never store junk.** `<input type="number">` reports `''` for anything it
|
||||
// cannot parse — including `abc` and a lone `-` — and coercing that would write 0,
|
||||
// which is a meaningful setting ("off") the user did not ask for.
|
||||
const next = Number.parseInt(e.target.value, 10)
|
||||
if (!Number.isFinite(next) || next < 0 || next > 999) return
|
||||
void save({ pinSuggestThreshold: next })
|
||||
}}
|
||||
className="mt-2 w-20 rounded-pd border border-border bg-bg px-2 py-0.5 font-mono text-data"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="mt-6" disabled={loading}>
|
||||
<legend className="text-text-dim">{t('settings.override')}</legend>
|
||||
<label className="mt-2 flex items-start gap-2">
|
||||
@@ -97,6 +130,8 @@ export function PdSettings() {
|
||||
<span className="text-data text-warn">{t('settings.overrideDetail')}</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<PdCacheUsage />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
+82
-2
@@ -26,6 +26,7 @@ import {
|
||||
pinAdd,
|
||||
pinList,
|
||||
pinRemove,
|
||||
pinSuggestions,
|
||||
pipUpgrade,
|
||||
pkgList,
|
||||
pkgOutdated,
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
type OutdatedDist,
|
||||
type PdError,
|
||||
type Pin,
|
||||
type PinSuggestion,
|
||||
type ScanProgress,
|
||||
type Settings,
|
||||
type Diff,
|
||||
@@ -50,7 +52,7 @@ import { joinRows, type LoadState, type PackageRow } from '@/screens/rows'
|
||||
export type EngineId = 'pip' | 'uv'
|
||||
|
||||
/** Turn an unknown rejection into something a screen can render with a code. */
|
||||
function asPdError(e: unknown): PdError {
|
||||
export function asPdError(e: unknown): PdError {
|
||||
return isPdError(e)
|
||||
? e
|
||||
: // A rejection that is not a PdError can only be a bug in the bridge, and PD-INT-001 means
|
||||
@@ -68,6 +70,8 @@ interface SettingsState {
|
||||
* every mutating screen for such an env to show a persistent warning chip while it is set.
|
||||
*/
|
||||
allowExternallyManaged: boolean
|
||||
/** How many dependents qualify a package for a pin suggestion (PRD P1-2). Zero is off. */
|
||||
pinSuggestThreshold: number
|
||||
/** True until the first `settings_get` resolves, so Settings never flashes defaults. */
|
||||
loading: boolean
|
||||
error: PdError | null
|
||||
@@ -80,6 +84,9 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
locale: FALLBACK_LOCALE,
|
||||
engine: 'pip',
|
||||
allowExternallyManaged: false,
|
||||
// Mirrors `graph::PIN_SUGGEST_THRESHOLD`. Only on screen until `load` resolves, which is what
|
||||
// `loading` exists to hide.
|
||||
pinSuggestThreshold: 5,
|
||||
loading: true,
|
||||
error: null,
|
||||
|
||||
@@ -89,6 +96,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
set({
|
||||
engine: s.engine,
|
||||
allowExternallyManaged: s.allowExternallyManaged,
|
||||
pinSuggestThreshold: s.pinSuggestThreshold,
|
||||
loading: false,
|
||||
error: null,
|
||||
})
|
||||
@@ -98,10 +106,11 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
},
|
||||
|
||||
save: async (patch) => {
|
||||
const { engine, allowExternallyManaged } = get()
|
||||
const { engine, allowExternallyManaged, pinSuggestThreshold } = get()
|
||||
const next: Settings = {
|
||||
engine,
|
||||
allowExternallyManaged,
|
||||
pinSuggestThreshold,
|
||||
// The store holds the *resolved* locale; `null` on the wire means "follow the OS", and only
|
||||
// an explicit choice in Settings should overwrite that.
|
||||
locale: null,
|
||||
@@ -112,6 +121,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
set({
|
||||
engine: saved.engine,
|
||||
allowExternallyManaged: saved.allowExternallyManaged,
|
||||
pinSuggestThreshold: saved.pinSuggestThreshold,
|
||||
error: null,
|
||||
})
|
||||
} catch (e) {
|
||||
@@ -188,6 +198,29 @@ interface EnvState {
|
||||
/** Set or clear a pin's reason, leaving its mode alone. `null` clears it. */
|
||||
updatePin: (name: string, reason: string | null) => Promise<void>
|
||||
|
||||
// -- pin auto-suggest, for the Pins screen (PRD P1-2) ----------------------------------------
|
||||
|
||||
suggestions: PinSuggestion[]
|
||||
/**
|
||||
* Which environment `suggestions` describes.
|
||||
*
|
||||
* Its own key rather than reusing `loadedFor`, for the reason `snapshotsFor` is its own: one
|
||||
* flag covering two fetches means the cheaper one's staleness decides the expensive one's. This
|
||||
* fetch costs a `probe.py` run, and `loadedFor` is written by `loadPackages`.
|
||||
*/
|
||||
suggestionsFor: string | null
|
||||
suggestionsLoading: LoadState
|
||||
/**
|
||||
* Fetch suggestions for the selected environment.
|
||||
*
|
||||
* Advisory, so a failure is deliberately silent — there is no `suggestionsError`. The screen it
|
||||
* lives on works without it, and an error row about a *suggestion* would be the loudest thing
|
||||
* on a screen whose actual job is listing pins.
|
||||
*/
|
||||
loadSuggestions: () => Promise<void>
|
||||
/** Accept one: pin it, with the count as its reason. */
|
||||
acceptSuggestion: (name: string, reason: string) => Promise<void>
|
||||
|
||||
// -- the snapshot slice, for the env detail (UI-SPEC §4) -------------------------------------
|
||||
|
||||
/**
|
||||
@@ -231,6 +264,11 @@ const NO_PACKAGES = {
|
||||
outdatedStatus: 'idle' as LoadState,
|
||||
outdatedError: null,
|
||||
selection: new Set<string>(),
|
||||
// Keyed to `selected` like the rest of this slice, so it resets with it. `suggestionsFor` is a
|
||||
// separate *fetch* key, not a separate reset key — the distinction `NO_SNAPSHOTS` documents.
|
||||
suggestions: [] as PinSuggestion[],
|
||||
suggestionsFor: null,
|
||||
suggestionsLoading: 'idle' as LoadState,
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -399,6 +437,40 @@ export const useEnvStore = create<EnvState>((set, get) => ({
|
||||
)
|
||||
},
|
||||
|
||||
loadSuggestions: async () => {
|
||||
const { selected, rows, suggestionsFor, suggestionsLoading } = get()
|
||||
const row = rows.find((r) => r.interpreter === selected)
|
||||
if (row?.env === undefined) return
|
||||
if (suggestionsFor === selected) return
|
||||
// Checked *synchronously*, before any await, for the reason `loadSnapshots` records: React
|
||||
// runs effects twice in development and the second reaches this line before the first has
|
||||
// answered. Without it this is Stage 2's double fetch again — and here each one costs a
|
||||
// `probe.py` run rather than a SQLite read.
|
||||
if (suggestionsLoading === 'loading') return
|
||||
|
||||
set({ suggestionsLoading: 'loading' })
|
||||
try {
|
||||
set({
|
||||
suggestions: await pinSuggestions(row.env),
|
||||
suggestionsFor: selected,
|
||||
suggestionsLoading: 'ready',
|
||||
})
|
||||
} catch {
|
||||
// Advisory. The Pins screen's job is listing pins, and it does that whether or not this
|
||||
// resolved — so a failure leaves the section absent rather than putting an error row above
|
||||
// the thing the user actually came for.
|
||||
set({ suggestionsLoading: 'error' })
|
||||
}
|
||||
},
|
||||
|
||||
acceptSuggestion: async (name, reason) => {
|
||||
// Through `writePin` like every other pin write, so the list is re-read and the selection
|
||||
// pruned identically. Dropping it from `suggestions` locally rather than refetching: the
|
||||
// answer cannot have changed, and a second probe to learn that would be absurd.
|
||||
await writePin(set, get, (envHash) => pinAdd(envHash, { pkg: name, mode: 'exclude', reason }))
|
||||
set((state) => ({ suggestions: state.suggestions.filter((s) => s.pkg !== name) }))
|
||||
},
|
||||
|
||||
openEnv: (interpreter) =>
|
||||
set((state) => ({
|
||||
openFor: interpreter,
|
||||
@@ -616,6 +688,14 @@ export {
|
||||
type TabState,
|
||||
} from '@/stores/health'
|
||||
|
||||
// The Security tab, in its own file for the same reason as Code Health.
|
||||
export {
|
||||
freshAudit,
|
||||
useSecurityStore,
|
||||
type SecurityPhase,
|
||||
type SecurityState,
|
||||
} from '@/stores/security'
|
||||
|
||||
// Search and the dock bay, in their own file for the same reason as the plan store.
|
||||
export {
|
||||
SEARCH_DEBOUNCE_MS,
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* The Security tab — the audit run and its report (PRD P1-1, SECURITY §6).
|
||||
*
|
||||
* Its own file, re-exported from `@/stores`, for the reason `health.ts` is: a domain that owns a
|
||||
* screen owns a file.
|
||||
*
|
||||
* Simpler than `health.ts` in two ways worth naming, because both are absences rather than
|
||||
* omissions. There are **no tabs** — one tool means one list, and a tab strip over a single tool
|
||||
* would be furniture. And the reset key is a **single** `envHash` rather than health's
|
||||
* `{envHash, folder}` pair, because an audit has no project folder: what it reads is the
|
||||
* environment itself.
|
||||
*
|
||||
* It gains one thing health has not: a **cancel**. An audit measures 18-68 s against Code Health's
|
||||
* 1.3 s, which is what changed the answer P4 recorded.
|
||||
*/
|
||||
|
||||
import { create } from 'zustand'
|
||||
|
||||
import {
|
||||
auditCancel,
|
||||
auditRun,
|
||||
isPdError,
|
||||
onAuditProgress,
|
||||
type AuditReport,
|
||||
type PdError,
|
||||
type ProgressEvent,
|
||||
type PyEnv,
|
||||
} from '@/ipc'
|
||||
import { apply, type ConsoleLine } from '@/stores/plan'
|
||||
|
||||
/** Where a run is. */
|
||||
export type SecurityPhase = 'idle' | 'running' | 'ready' | 'failed'
|
||||
|
||||
export interface SecurityState {
|
||||
phase: SecurityPhase
|
||||
/** The report on screen, or null when nothing has run for this environment. */
|
||||
report: AuditReport | null
|
||||
/**
|
||||
* Which environment `report` describes.
|
||||
*
|
||||
* Held separately so a report can never be shown under another environment's name — the same
|
||||
* reason `useHealthStore` keeps `reportFor`, and the reason `freshReport` exists below.
|
||||
*/
|
||||
reportFor: string | null
|
||||
/** A run that failed outright, as opposed to a tool problem inside a report. */
|
||||
error: PdError | null
|
||||
/** Console lines from `audit-progress`, folded by the shared reducer. */
|
||||
console: ConsoleLine[]
|
||||
/**
|
||||
* Steps finished and expected.
|
||||
*
|
||||
* Required by `ConsoleState`, and not decoration: on a cold install `total` is the audit *plus*
|
||||
* the venv bootstrap's steps, so the drawer's "n of m" is the only thing on screen that says the
|
||||
* wait is a build rather than a hang.
|
||||
*/
|
||||
done: number
|
||||
total: number
|
||||
current: string | null
|
||||
consoleOpen: boolean
|
||||
run: (env: PyEnv, envHash: string) => Promise<void>
|
||||
cancel: () => Promise<void>
|
||||
setConsoleOpen: (open: boolean) => void
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleared when the selected environment changes.
|
||||
*
|
||||
* `consoleOpen` is deliberately outside it: which drawer the user left open is a preference about
|
||||
* the screen, not a fact about an environment. Same call `useHealthStore` makes.
|
||||
*/
|
||||
const NO_SECURITY = {
|
||||
phase: 'idle' as SecurityPhase,
|
||||
report: null,
|
||||
reportFor: null,
|
||||
error: null,
|
||||
console: [] as ConsoleLine[],
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: null,
|
||||
}
|
||||
|
||||
const asPdError = (e: unknown): PdError =>
|
||||
isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) }
|
||||
|
||||
let unlisten: (() => void) | undefined
|
||||
|
||||
export const useSecurityStore = create<SecurityState>((set, get) => ({
|
||||
...NO_SECURITY,
|
||||
consoleOpen: false,
|
||||
|
||||
run: async (env, envHash) => {
|
||||
if (get().phase === 'running') return
|
||||
|
||||
// Cleared before subscribing, so a second Run never paints the previous advisories under a new
|
||||
// `ranAt`, and a report the server is about to replace stops being on screen first.
|
||||
set({ ...NO_SECURITY, phase: 'running' })
|
||||
|
||||
// Subscribed before the command. On a cold install the audit venv's bootstrap is the slowest
|
||||
// part of the whole run, and it is emitted before `audit_run` returns anything at all.
|
||||
unlisten?.()
|
||||
unlisten = await onAuditProgress((event: ProgressEvent) => {
|
||||
useSecurityStore.setState((s) => apply(s, event))
|
||||
})
|
||||
|
||||
try {
|
||||
const report = await auditRun(env)
|
||||
set({ report, reportFor: envHash, phase: 'ready', current: null })
|
||||
} catch (e) {
|
||||
set({ phase: 'failed', error: asPdError(e), current: null })
|
||||
} finally {
|
||||
unlisten?.()
|
||||
unlisten = undefined
|
||||
}
|
||||
},
|
||||
|
||||
// Deliberately does **not** set a phase. The run's own `finally` resolves it, and a cancelled
|
||||
// audit still returns a report carrying `cancelled: true` — so setting `idle` here would race
|
||||
// the result and throw away the partial answer the user is entitled to see.
|
||||
cancel: async () => {
|
||||
if (get().phase !== 'running') return
|
||||
await auditCancel()
|
||||
},
|
||||
|
||||
setConsoleOpen: (open) => {
|
||||
set({ consoleOpen: open })
|
||||
},
|
||||
|
||||
reset: () => {
|
||||
unlisten?.()
|
||||
unlisten = undefined
|
||||
set({ ...NO_SECURITY })
|
||||
},
|
||||
}))
|
||||
|
||||
/**
|
||||
* The report, but only if it belongs to this environment.
|
||||
*
|
||||
* A plain function rather than a hook so it stays trivially testable, exactly as
|
||||
* `useHealthStore`'s `freshReport` is — named apart from it because both are re-exported from
|
||||
* `@/stores` and one name cannot mean two shapes.
|
||||
*/
|
||||
export function freshAudit(
|
||||
state: Pick<SecurityState, 'report' | 'reportFor'>,
|
||||
envHash: string,
|
||||
): AuditReport | null {
|
||||
return state.report !== null && state.reportFor === envHash ? state.report : null
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
{
|
||||
"env": "c:\\proj\\.venv\\scripts\\python.exe",
|
||||
"ranAt": "2026-08-18T09:00:00Z",
|
||||
"toolVersion": "2.10.1",
|
||||
"packages": 2,
|
||||
"advisories": [
|
||||
{
|
||||
"pkg": "pip",
|
||||
"version": "25.0.1",
|
||||
"id": "PYSEC-2026-1795",
|
||||
"aliases": [
|
||||
"GHSA-4xh5-x5gv-qwph",
|
||||
"CVE-2025-8869"
|
||||
],
|
||||
"fixVersions": [
|
||||
"25.3"
|
||||
],
|
||||
"description": "When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a \"fixed\" version for this vulnerability doesn't fix all known vulnerabilities that are remediated by using a Python version that implements PEP 706. Note that this is a vulnerability in pip's fallback implementation of tar extraction for Python versions that don't implement PEP 706 and therefore are not secure to all vulnerabilities in the Python 'tarfile' module. If you're using a Python version that implements PEP 706 then pip doesn't use the \"vulnerable\" fallback code. Mitigations include upgrading to a version of pip that includes the fix, upgrading to a Python version that implements PEP 706 (Python >=3.9.17, >=3.10.12, >=3.11.4, or >=3.12), applying the linked patch, or inspecting source distributions (sdists) before installation as is already a best-practice.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1795"
|
||||
},
|
||||
{
|
||||
"pkg": "pip",
|
||||
"version": "25.0.1",
|
||||
"id": "PYSEC-2026-1796",
|
||||
"aliases": [
|
||||
"GHSA-6vgw-5pg2-w6jp",
|
||||
"CVE-2026-1703"
|
||||
],
|
||||
"fixVersions": [
|
||||
"26.0"
|
||||
],
|
||||
"description": "When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation directory, thus isn't able to inject or overwrite executable files in typical situations.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1796"
|
||||
},
|
||||
{
|
||||
"pkg": "pip",
|
||||
"version": "25.0.1",
|
||||
"id": "PYSEC-2026-196",
|
||||
"aliases": [
|
||||
"GHSA-wf93-45jw-7689",
|
||||
"CVE-2026-8643"
|
||||
],
|
||||
"fixVersions": [
|
||||
"26.1.2"
|
||||
],
|
||||
"description": "pip would treat console_scripts and gui_scripts as paths instead of file names without sanitizing the resolved absolute path to the installation directory, leading to entry points being installed outside the installation directory.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-196"
|
||||
},
|
||||
{
|
||||
"pkg": "pip",
|
||||
"version": "25.0.1",
|
||||
"id": "PYSEC-2026-2875",
|
||||
"aliases": [
|
||||
"GHSA-58qw-9mgm-455v",
|
||||
"CVE-2026-3219"
|
||||
],
|
||||
"fixVersions": [
|
||||
"26.1"
|
||||
],
|
||||
"description": "pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as installing \"incorrect\" files according to the filename of the archive. New behavior only proceeds with installation if the file identifies uniquely as a ZIP or tar archive, not as both.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-2875"
|
||||
},
|
||||
{
|
||||
"pkg": "pip",
|
||||
"version": "25.0.1",
|
||||
"id": "PYSEC-2026-2876",
|
||||
"aliases": [
|
||||
"GHSA-jp4c-xjxw-mgf9",
|
||||
"CVE-2026-6357"
|
||||
],
|
||||
"fixVersions": [
|
||||
"26.1"
|
||||
],
|
||||
"description": "pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally deferred to increase startup time of the pip CLI. The patch changes self-update functionality to run before wheels are installed to prevent newly-installed modules from being imported shortly after the installation of a wheel package. Users should still review package contents prior to installation.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-2876"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2023-192",
|
||||
"aliases": [
|
||||
"GHSA-v845-jxx5-vc9f",
|
||||
"CVE-2023-43804"
|
||||
],
|
||||
"fixVersions": [
|
||||
"1.26.17",
|
||||
"2.0.6"
|
||||
],
|
||||
"description": "urllib3 doesn't treat the `Cookie` HTTP header special or provide any helpers for managing cookies over HTTP, that is the responsibility of the user. However, it is possible for a user to specify a `Cookie` header and unknowingly leak information via HTTP redirects to a different origin if that user doesn't disable redirects explicitly. Users **must** handle redirects themselves instead of relying on urllib3's automatic redirects to achieve safe processing of the `Cookie` header, thus we decided to strip the header by default in order to further protect users who aren't using the correct approach. ## Affected usages We believe the number of usages affected by this advisory is low. It requires all of the following to be true to be exploited: * Using an affected version of urllib3 (patched in v1.26.17 and v2.0.6) * Using the `Cookie` header on requests, which is mostly typical for impersonating a browser. * Not disabling HTTP redirects * Either not using HTTPS or for the origin server to redirect to a malicious origin. ## Remediation * Upgrading to at least urllib3 v1.26.17 or v2.0.6 * Disabling HTTP redirects using `redirects=False` when sending requests. * Not using the `Cookie` header.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2023-192"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2023-212",
|
||||
"aliases": [
|
||||
"CVE-2023-45803",
|
||||
"GHSA-g4mx-q9vg-27p4"
|
||||
],
|
||||
"fixVersions": [
|
||||
"1.26.18",
|
||||
"2.0.7"
|
||||
],
|
||||
"description": "urllib3 previously wouldn't remove the HTTP request body when an HTTP redirect response using status 303 \"See Other\" after the request had its method changed from one that could accept a request body (like `POST`) to `GET` as is required by HTTP RFCs. Although the behavior of removing the request body is not specified in the section for redirects, it can be inferred by piecing together information from different sections and we have observed the behavior in other major HTTP client implementations like curl and web browsers. From [RFC 9110 Section 9.3.1](https://www.rfc-editor.org/rfc/rfc9110.html#name-get): > A client SHOULD NOT generate content in a GET request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported. ## Affected usages Because the vulnerability requires a previously trusted service to become compromised in order to have an impact on confidentiality we believe the exploitability of this vulnerability is low. Additionally, many users aren't putting sensitive data in HTTP request bodies, if this is the case then this vulnerability isn't exploitable. Both of the following conditions must be true to be affected by this vulnerability: * If you're using urllib3 and submitting sensitive information in the HTTP request body (such as form data or JSON) * The origin service is compromised and starts redirecting using 303 to a malicious peer or the redirected-to service becomes compromised. ## Remediation You can remediate this vulnerability with any of the following steps: * Upgrade to a patched version of urllib3 (v1.26.18 or v2.0.7) * Disable redirects for services that you aren't expecting to respond with redirects with `redirects=False`. * Disable automatic redirects with `redirects=False` and handle 303 redirects manually by stripping the HTTP request body.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2023-212"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2026-141",
|
||||
"aliases": [
|
||||
"CVE-2026-44431",
|
||||
"GHSA-qccp-gfcp-xxvc"
|
||||
],
|
||||
"fixVersions": [
|
||||
"2.7.0"
|
||||
],
|
||||
"description": "urllib3 is an HTTP client library for Python. From 1.23 to before 2.7.0, cross-origin redirects followed from the low-level API via ProxyManager.connection_from_url().urlopen(..., assert_same_host=False) still forward these sensitive headers. This vulnerability is fixed in 2.7.0.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-141"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2026-1994",
|
||||
"aliases": [
|
||||
"GHSA-2xpw-w6gg-jr37",
|
||||
"CVE-2025-66471"
|
||||
],
|
||||
"fixVersions": [
|
||||
"2.6.0"
|
||||
],
|
||||
"description": "### Impact urllib3's [streaming API](https://urllib3.readthedocs.io/en/2.5.0/advanced-usage.html#streaming-and-i-o) is designed for the efficient handling of large HTTP responses by reading the content in chunks, rather than loading the entire response body into memory at once. When streaming a compressed response, urllib3 can perform decoding or decompression based on the HTTP `Content-Encoding` header (e.g., `gzip`, `deflate`, `br`, or `zstd`). The library must read compressed data from the network and decompress it until the requested chunk size is met. Any resulting decompressed data that exceeds the requested amount is held in an internal buffer for the next read operation. The decompression logic could cause urllib3 to fully decode a small amount of highly compressed data in a single operation. This can result in excessive resource consumption (high CPU usage and massive memory allocation for the decompressed data; CWE-409) on the client side, even if the application only requested a small chunk of data. ### Affected usages Applications and libraries using urllib3 version 2.5.0 and earlier to stream large compressed responses or content from untrusted sources. `stream()`, `read(amt=256)`, `read1(amt=256)`, `read_chunked(amt=256)`, `readinto(b)` are examples of `urllib3.HTTPResponse` method calls using the affected logic unless decoding is disabled explicitly. ### Remediation Upgrade to at least urllib3 v2.6.0 in which the library avoids decompressing data that exceeds the requested amount. If your environment contains a package facilitating the Brotli encoding, upgrade to at least Brotli 1.2.0 or brotlicffi 1.2.0.0 too. These versions are enforced by the `urllib3[brotli]` extra in the patched versions of urllib3. ### Credits The issue was reported by @Cycloctane. Supplemental information was provided by @stamparm during a security audit performed by [7ASecurity](https://7asecurity.com/) and facilitated by [OSTIF](https://ostif.org/).",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1994"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2026-1995",
|
||||
"aliases": [
|
||||
"GHSA-34jh-p97f-mpxf",
|
||||
"CVE-2024-37891"
|
||||
],
|
||||
"fixVersions": [
|
||||
"1.26.19",
|
||||
"2.2.2"
|
||||
],
|
||||
"description": "When using urllib3's proxy support with `ProxyManager`, the `Proxy-Authorization` header is only sent to the configured proxy, as expected. However, when sending HTTP requests *without* using urllib3's proxy support, it's possible to accidentally configure the `Proxy-Authorization` header even though it won't have any effect as the request is not using a forwarding proxy or a tunneling proxy. In those cases, urllib3 doesn't treat the `Proxy-Authorization` HTTP header as one carrying authentication material and thus doesn't strip the header on cross-origin redirects. Because this is a highly unlikely scenario, we believe the severity of this vulnerability is low for almost all users. Out of an abundance of caution urllib3 will automatically strip the `Proxy-Authorization` header during cross-origin redirects to avoid the small chance that users are doing this on accident. Users should use urllib3's proxy support or disable automatic redirects to achieve safe processing of the `Proxy-Authorization` header, but we still decided to strip the header by default in order to further protect users who aren't using the correct approach. ## Affected usages We believe the number of usages affected by this advisory is low. It requires all of the following to be true to be exploited: * Setting the `Proxy-Authorization` header without using urllib3's built-in proxy support. * Not disabling HTTP redirects. * Either not using an HTTPS origin server or for the proxy or target origin to redirect to a malicious origin. ## Remediation * Using the `Proxy-Authorization` header with urllib3's `ProxyManager`. * Disabling HTTP redirects using `redirects=False` when sending requests. * Not using the `Proxy-Authorization` header.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1995"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2026-1996",
|
||||
"aliases": [
|
||||
"GHSA-38jv-5279-wg99",
|
||||
"CVE-2026-21441"
|
||||
],
|
||||
"fixVersions": [
|
||||
"2.6.3"
|
||||
],
|
||||
"description": "### Impact urllib3's [streaming API](https://urllib3.readthedocs.io/en/2.6.2/advanced-usage.html#streaming-and-i-o) is designed for the efficient handling of large HTTP responses by reading the content in chunks, rather than loading the entire response body into memory at once. urllib3 can perform decoding or decompression based on the HTTP `Content-Encoding` header (e.g., `gzip`, `deflate`, `br`, or `zstd`). When using the streaming API, the library decompresses only the necessary bytes, enabling partial content consumption. However, for HTTP redirect responses, the library would read the entire response body to drain the connection and decompress the content unnecessarily. This decompression occurred even before any read methods were called, and configured read limits did not restrict the amount of decompressed data. As a result, there was no safeguard against decompression bombs. A malicious server could exploit this to trigger excessive resource consumption on the client (high CPU usage and large memory allocations for decompressed data; CWE-409). ### Affected usages Applications and libraries using urllib3 version 2.6.2 and earlier to stream content from untrusted sources by setting `preload_content=False` when they do not disable redirects. ### Remediation Upgrade to at least urllib3 v2.6.3 in which the library does not decode content of redirect responses when `preload_content=False`. If upgrading is not immediately possible, disable [redirects](https://urllib3.readthedocs.io/en/2.6.2/user-guide.html#retrying-requests) by setting `redirect=False` for requests to untrusted source.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1996"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2026-1998",
|
||||
"aliases": [
|
||||
"GHSA-gm62-xv2j-4w53",
|
||||
"CVE-2025-66418"
|
||||
],
|
||||
"fixVersions": [
|
||||
"2.6.0"
|
||||
],
|
||||
"description": "## Impact urllib3 supports chained HTTP encoding algorithms for response content according to RFC 9110 (e.g., `Content-Encoding: gzip, zstd`). However, the number of links in the decompression chain was unbounded allowing a malicious server to insert a virtually unlimited number of compression steps leading to high CPU usage and massive memory allocation for the decompressed data. ## Affected usages Applications and libraries using urllib3 version 2.5.0 and earlier for HTTP requests to untrusted sources unless they disable content decoding explicitly. ## Remediation Upgrade to at least urllib3 v2.6.0 in which the library limits the number of links to 5. If upgrading is not immediately possible, use [`preload_content=False`](https://urllib3.readthedocs.io/en/2.5.0/advanced-usage.html#streaming-and-i-o) and ensure that `resp.headers[\"content-encoding\"]` contains a safe number of encodings before reading the response content.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1998"
|
||||
},
|
||||
{
|
||||
"pkg": "urllib3",
|
||||
"version": "2.0.0",
|
||||
"id": "PYSEC-2026-1999",
|
||||
"aliases": [
|
||||
"GHSA-pq67-6m6q-mj2v",
|
||||
"CVE-2025-50181"
|
||||
],
|
||||
"fixVersions": [
|
||||
"2.5.0"
|
||||
],
|
||||
"description": "urllib3 handles redirects and retries using the same mechanism, which is controlled by the `Retry` object. The most common way to disable redirects is at the request level, as follows: ```python resp = urllib3.request(\"GET\", \"https://httpbin.org/redirect/1\", redirect=False) print(resp.status) # 302 ``` However, it is also possible to disable redirects, for all requests, by instantiating a `PoolManager` and specifying `retries` in a way that disable redirects: ```python import urllib3 http = urllib3.PoolManager(retries=0) # should raise MaxRetryError on redirect http = urllib3.PoolManager(retries=urllib3.Retry(redirect=0)) # equivalent to the above http = urllib3.PoolManager(retries=False) # should return the first response resp = http.request(\"GET\", \"https://httpbin.org/redirect/1\") ``` However, the `retries` parameter is currently ignored, which means all the above examples don't disable redirects. ## Affected usages Passing `retries` on `PoolManager` instantiation to disable redirects or restrict their number. By default, requests and botocore users are not affected. ## Impact Redirects are often used to exploit SSRF vulnerabilities. An application attempting to mitigate SSRF or open redirect vulnerabilities by disabling redirects at the PoolManager level will remain vulnerable. ## Remediation You can remediate this vulnerability with the following steps: * Upgrade to a patched version of urllib3. If your organization would benefit from the continued support of urllib3 1.x, please contact [sethmichaellarson@gmail.com](mailto:sethmichaellarson@gmail.com) to discuss sponsorship or contribution opportunities. * Disable redirects at the `request()` level instead of the `PoolManager()` level.",
|
||||
"url": "https://osv.dev/vulnerability/PYSEC-2026-1999"
|
||||
}
|
||||
],
|
||||
"cancelled": false
|
||||
}
|
||||
Vendored
+6
@@ -37,8 +37,14 @@
|
||||
"resolved": "1.26.4",
|
||||
"latest": "2.5.1",
|
||||
"blockers": [
|
||||
{
|
||||
"by": "pandas",
|
||||
"version": "2.1.4",
|
||||
"constraint": "numpy<2,>=1.26.0"
|
||||
},
|
||||
{
|
||||
"by": "scipy",
|
||||
"version": "1.11.4",
|
||||
"constraint": "numpy<1.28.0,>=1.21.6"
|
||||
}
|
||||
]
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
"ranAt": "2026-08-13T09:00:00Z",
|
||||
"toolVersions": {
|
||||
"deptry": "0.25.1",
|
||||
"ruff": "0.16.2",
|
||||
"ruff": "0.16.3",
|
||||
"vulture": "2.16"
|
||||
},
|
||||
"declared": {
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
"ranAt": "2026-08-13T09:00:00Z",
|
||||
"toolVersions": {
|
||||
"deptry": "0.25.1",
|
||||
"ruff": "0.16.2",
|
||||
"ruff": "0.16.3",
|
||||
"vulture": "2.16"
|
||||
},
|
||||
"declared": {
|
||||
|
||||
@@ -31,6 +31,11 @@ export interface IpcMock {
|
||||
pinList: ReturnType<typeof vi.fn>
|
||||
pinAdd: ReturnType<typeof vi.fn>
|
||||
pinRemove: ReturnType<typeof vi.fn>
|
||||
pinSuggestions: ReturnType<typeof vi.fn>
|
||||
envExport: ReturnType<typeof vi.fn>
|
||||
requirementsRead: ReturnType<typeof vi.fn>
|
||||
cacheUsage: ReturnType<typeof vi.fn>
|
||||
cacheClear: ReturnType<typeof vi.fn>
|
||||
planResolve: ReturnType<typeof vi.fn>
|
||||
planDecide: ReturnType<typeof vi.fn>
|
||||
planExecute: ReturnType<typeof vi.fn>
|
||||
@@ -42,9 +47,13 @@ export interface IpcMock {
|
||||
envProbe: ReturnType<typeof vi.fn>
|
||||
pipUpgrade: ReturnType<typeof vi.fn>
|
||||
healthRun: ReturnType<typeof vi.fn>
|
||||
auditRun: ReturnType<typeof vi.fn>
|
||||
auditCancel: ReturnType<typeof vi.fn>
|
||||
auditSaveReport: ReturnType<typeof vi.fn>
|
||||
onHealthProgress: ReturnType<typeof vi.fn>
|
||||
pickProjectFolder: ReturnType<typeof vi.fn>
|
||||
pickSavePath: ReturnType<typeof vi.fn>
|
||||
pickOpenFile: ReturnType<typeof vi.fn>
|
||||
healthSaveReport: ReturnType<typeof vi.fn>
|
||||
healthFix: ReturnType<typeof vi.fn>
|
||||
healthDirty: ReturnType<typeof vi.fn>
|
||||
@@ -66,6 +75,19 @@ export function ipcMock(): IpcMock {
|
||||
pinList: vi.fn().mockResolvedValue([]),
|
||||
pinAdd: vi.fn().mockResolvedValue(undefined),
|
||||
pinRemove: vi.fn().mockResolvedValue(true),
|
||||
// Empty by default: a screen that renders a suggestion section must not get one for free, or
|
||||
// a test asserting the section is absent passes for the wrong reason.
|
||||
pinSuggestions: vi.fn().mockResolvedValue([]),
|
||||
envExport: vi.fn().mockResolvedValue('C:/out/requirements.txt'),
|
||||
requirementsRead: vi.fn().mockResolvedValue({ specs: [], skipped: [] }),
|
||||
cacheUsage: vi.fn().mockResolvedValue({
|
||||
root: 'C:/data',
|
||||
database: { bytes: 0, path: 'C:/data/index.db', exists: false },
|
||||
snapshots: { bytes: 0, path: 'C:/data/snapshots', exists: false },
|
||||
tools: { bytes: 0, path: 'C:/data/tools', exists: false },
|
||||
snapshotCount: 0,
|
||||
}),
|
||||
cacheClear: vi.fn().mockResolvedValue(0),
|
||||
planResolve: vi.fn(),
|
||||
planDecide: vi.fn(),
|
||||
planExecute: vi.fn(),
|
||||
@@ -78,11 +100,15 @@ export function ipcMock(): IpcMock {
|
||||
envProbe: vi.fn(),
|
||||
pipUpgrade: vi.fn().mockResolvedValue(undefined),
|
||||
healthRun: vi.fn(),
|
||||
auditRun: vi.fn(),
|
||||
auditCancel: vi.fn(),
|
||||
auditSaveReport: vi.fn(),
|
||||
onHealthProgress: vi.fn().mockResolvedValue(() => undefined),
|
||||
// Cancelled by default. A picker that silently returned a folder would let a test assert a
|
||||
// run it never actually asked for.
|
||||
pickProjectFolder: vi.fn().mockResolvedValue(null),
|
||||
pickSavePath: vi.fn().mockResolvedValue(null),
|
||||
pickOpenFile: vi.fn().mockResolvedValue(null),
|
||||
healthSaveReport: vi.fn().mockResolvedValue([]),
|
||||
healthFix: vi.fn(),
|
||||
healthDirty: vi.fn().mockResolvedValue(null),
|
||||
|
||||
Reference in new issue
Block a user