diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..8d09ce614 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -122,7 +122,7 @@ Every subcommand accepts the same set of "global" flags via a single shared `Glo | `--no-vlt-install-cleanup` | — | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `false` | bool | Opt out of hosted mode's warm-tree heal for vlt: stale installed copies (`node_modules/.vlt-lock.json` and the stale `node_modules/.vlt/` entries) are left in place after `vlt-lock.json` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`), and the `redirect_vlt_reinstall_required` advisory tells you to run `vlt ci` instead. Stale copies of optional dependencies are always left in place (see `redirect_vlt_reinstall_required`). Other subcommands accept it silently | | `--no-gem-install-refresh` | — | `SOCKET_NO_GEM_INSTALL_REFRESH` | `false` | bool | Opt out of hosted mode's gem stale-install refresh: the gems Bundler already holds for the project (an installed gem under the project and its cached `.gem`, an archive in `vendor/cache`) are left as they are after `Gemfile.lock` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`, of a hosted pin or of a vendored gem; `vendor --revert`), and the `redirect_gem_stale_install` / `upstream_gem_stale_install` warning names the files to remove by hand instead (see the "Gem stale-install guard" section). Other subcommands accept it silently | | `--gem-refresh-shared` | — | `SOCKET_GEM_REFRESH_SHARED` | `false` | bool | Extend the gem stale-install refresh to gem homes OUTSIDE the project (the system gems, `~/.gem`, an rbenv or asdf home) and to project bundle or cache paths that resolve outside the project directory. Off by default: another project on the machine may pin the other build of the same gem version, and its `bundle pristine` then fails on the replaced archive's checksum (see the "Gem stale-install guard" section). Other subcommands accept it silently | -| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default; the one refusal it lifts today is `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. The switch is not specific to Composer: any refusal of vendored mode that rests on the Bazel workspace reads this one. For a project whose build does find the copy. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | **Experimental** (no stability guarantee; see [Bazel workspaces (experimental)](#bazel-workspaces-experimental)). Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default; the one refusal it lifts today is `vendor_composer_bazel_workspace`, which a package meets until `packages` of the lock, or the section of the lock that holds the package, names a vendored copy: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. The switch is not specific to Composer: any refusal of vendored mode that rests on the Bazel workspace reads this one. For a project whose build does find the copy. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" | **`--download-mode` removed (v5.0, MAJOR).** The global `--download-mode` flag and its `SOCKET_DOWNLOAD_MODE` binding are gone, with no alias: passing the flag is a usage error (exit 2) and the env var is ignored. Patch content is always fetched as per-file blobs (`.socket/blobs/`); `.socket/diffs/` archives are obsolete, never read, and removed by the cleanup sweeps. @@ -297,7 +297,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `report` | `--reason ` | — | What the patch broke: the project no longer installs, compiles or builds; its tests fail; it misbehaves when it runs; or something else. Default `other` | | `report` | `--message ` | — | What went wrong, in the user's words. Sent on one line (line breaks and control characters become spaces), with the credentials of any URL and the home directory redacted, cut to 1000 characters; `--dry-run` shows it as it would be sent | | `apply`, `scan`, `vendor` | `--vex` | `SOCKET_VEX` | Generate an OpenVEX 0.2.0 document at this path on a successful run; see "embedded VEX" below | -| `apply`, `scan`, `vendor` | `--vex-product`, `--vex-no-verify`, `--vex-no-bazel`, `--vex-doc-id`, `--vex-compact` | `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | Passthrough to the embedded VEX builder; mirror the standalone `vex` knobs. Inert unless `--vex` is set | +| `apply`, `scan`, `vendor` | `--vex-product`, `--vex-no-verify`, `--vex-no-bazel`, `--vex-doc-id`, `--vex-compact` | `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | Passthrough to the embedded VEX builder; mirror the standalone `vex` knobs. Inert unless `--vex` is set. `--vex-no-bazel` is **Experimental** (Bazel workspaces) | | `scan` | positional `[PATHS]...` | — | (v5.0) Meaning depends on the mode. **Hosted / vendored** (bare `scan` included): each PATH, or directory glob (`apps/*`), is a project directory scanned on its own as if it were `--cwd`. **Agent** (and a mode-less `--prune`/`--global` report): path globs scoping DISCOVERY to packages installed under matching paths (`packages/foo`, `apps/**`). See "Path-scoped scans" below | | `scan` | `--mode ` | — | The documented selector for the three patch-application modes (v5.0 default: `hosted`, except that a `--prune` or `--global`/`--global-prefix` scan with no mode is report-only). v5.0 removes the hidden value aliases `host`/`redirect`/`vendor` (now an invalid-value usage error), and the hidden boolean spellings `--redirect`, `--vendor` and `--apply` (now unknown-argument usage errors). `--sync` selects agent mode, so `--sync` with any other `--mode` is a usage error (exit 2, enforced in `resolve_mode_flags` — clap's `conflicts_with` is value-independent); `--mode agent --sync` is accepted. `--prune` is an orthogonal GC knob and never conflicts. Hosted mode keeps no `.socket/` state and sweeps none, so `--mode hosted --prune` emits an explicit `redirect_prune_ignored` warning (JSON `warnings[]` + stderr) instead of silently dropping that half of the flag. Hosted mode's own state is in the lockfiles: every hosted scan removes the pnpm registry entries no lockfile uses any more, with or without the flag, and under `--prune` the envelope's `gc` counts them (see "pnpm registry route", *Cleanup*) | | `scan` | `--prune` / `--sync` | — | `--prune` = GC after the scan; `--sync` = `--mode agent --prune`. In hosted mode the `.socket/` sweeps do not run (`redirect_prune_ignored` warning), the unused pnpm registry entries go as on every hosted scan, and `gc.removedRegistryEntries` counts them. In every other mode, and with no mode, the GC pass removes those entries itself, from the lockfiles alone | @@ -311,7 +311,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `get` | positional `identifier`; `--id` / `--cve` / `--ghsa` / `--package` (`-p`); `--save-only`; `--mode ` | `SOCKET_SAVE_ONLY` | Patch lookup + consumption mode (v3.6). `--mode` reuses scan's value enum (same hidden value aliases `host`/`redirect`/`vendor`; deliberately no env binding, matching scan). Default (v5.0): the mode the project's patch state records, like scan (see **Mode resolution**), so `hosted` for a project with no state; `agent` (save + apply in place) when `--save-only` or `--global`/`--global-prefix` is given. An explicit `--mode hosted\|vendored` with `--global`/`--global-prefix` is a usage error (exit 2, scan's wording: global installs have no project lockfile). An explicit `--save-only` conflicts with `--mode hosted\|vendored` — rejected with **exit 1** via get's established self-enforced-conflict style (unlike scan's exit-2 mode conflicts; see the exit-code table) | | `remove` | positional `identifier` (target grammar: UUID, PURL with or without version, or exact package name); `--skip-rollback`; `--preserve-state` (v5.0) | `SOCKET_SKIP_ROLLBACK`, `SOCKET_PRESERVE_STATE` | Manifest entry removal. The identifier matches like a `rollback` target (a PyPI name compares by its PEP 503 canonical form). `--preserve-state` is the single-patch twin of `rollback --preserve-state`: restore the tree and unwind the identifier's vendored/hosted wiring, but keep the manifest entry, the vendored artifact + ledger entry, and skip all GC. Combining it with `--skip-rollback` is a self-enforced usage error (exit 2): one flag keeps the tree and drops the state, the other restores the tree and keeps the state — together they select the do-nothing quadrant ("the combination would be a no-op: nothing would change"). The conflict fires whether either flag is spelled on the command line or sourced from its env var | | `rollback` | optional variadic positional `targets` (PURL \| UUID \| package name \| path glob); `--preserve-state` (v5.0) | `SOCKET_PRESERVE_STATE` | Rollback scope. Multiple targets union. A token becomes a path glob ONLY when it is path-SHAPED — contains a separator (`/` or `\`) or a glob metacharacter (`*?[`), or starts with `./`, or is absolute (an npm `@scope/name` is a name, not a path; a relative slash name without glob metacharacters or `.`/`..` segments — composer `vendor/pkg`, a go module path — is a name when it selects a recorded or hosted patch); a `pkg:` prefix is a PURL and every other token keeps the target grammar (UUID, PURL or exact package name), so a mistyped identifier or truncated UUID stays a safe exit-1 "No patch found matching identifier: X" (with a hint suggesting `./X` or `X/**` for directory targeting) instead of silently becoming a path scope. An unparseable glob is a usage error (exit 2) | -| `vex` | `--output` / `-O`, `--product`, `--no-verify`, `--no-bazel`, `--doc-id`, `--compact` | `SOCKET_VEX_OUTPUT`, `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | OpenVEX 0.2.0 document generation; see "vex output channels" below | +| `vex` | `--output` / `-O`, `--product`, `--no-verify`, `--no-bazel`, `--doc-id`, `--compact` | `SOCKET_VEX_OUTPUT`, `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | OpenVEX 0.2.0 document generation; see "vex output channels" below. `--no-bazel` is **Experimental** (Bazel workspaces) | | `repair` | `--download-only` | `SOCKET_DOWNLOAD_ONLY` | Repair-specific cleanup mode (mutually exclusive with `--offline`; combining them is a usage error, exit 2) | **pnpm hosted-mode contract**: `scan --mode hosted` handles block and flow resolutions in legacy `shrinkwrap.yaml` and lockfileVersion 5.x, 6.0, and 9.0. The [pinned compatibility matrix](../../docs/testing/pnpm-compatibility.md) samples pnpm majors 1–12. Early shrinkwrapVersion 3 without a positive minor version is refused with `redirect_pnpm_legacy_lockfile_unsupported`: pnpm 1.0.0 discards hosted URLs even on frozen installs. Upgrade to a tested release (1.43.1 or newer) and regenerate the lock, or use agent mode. @@ -335,7 +335,7 @@ The declaration is what pnpm verifies the lock entries against; the override is The route is taken only when **all** of these hold; otherwise the run takes the `trustLockfile` path below with the locks in the plain shape (a lock half routed would fail to install): (1) the project's own root file is the one pnpm reads (not a workspace member whose settings live in an ancestor file, #880), every governing lock is lockfileVersion 9 (Rush and legacy locks keep their own guidance); (2) every Socket-hosted tarball the governing locks record after the run has a registry: this run was granted it **with** a registry address, or an earlier run routed it, this run was **not** granted it, and the files still route it (the lock keys the release by a registry of the CLI's, the workspace file has its override to that registry, and the registry's address is the directory the tarball is served from). So a run granted only part of the project's patches (a scan of one subtree of a monorepo with one root lock, a search that lists fewer patches than the lock pins) leaves the rest routed and rewrites nothing for them. A pin this run was granted **without** an address is never kept that way (the grant overrules the files), and neither is an ungranted pin the files do not route: either one puts the whole lock on `trustLockfile` and is named. A pin on a patch mirror (`--patch-mirror-url`, experimental) has no address either, whatever its grant carries: see "Patch mirror (experimental)". A tarball is Socket-hosted when this run pinned it or its URL has the patch server's path shape, and every other tarball is the user's own; (3) every pnpm pin of the project (the sources of the #734 rule below, at least one present) proves pnpm 11.20 or newer: the lowest version it admits is 11.20 or higher (`11.28.13`, `^11.20.0`, `>=11.20`, `12`, `>=12`, `12 || 13`, `11.20.0 - 13.0.0`; `>` is read as `>=`, so `>11.19` proves nothing), since older releases write another lock for the same override; a range that reaches below it (`>=11`, `^11`), one the CLI cannot read, or pins that disagree prove nothing; (4) the workspace file can be read, is not a keyless file beside a lock that lists workspace members (#1096), and is a shape a line splice can extend (not a flow-style or indented root, several documents, a `namedRegistries` or `overrides` value on one line, a repeated key, an entry that is not a one-line `key: value`); (5) no override of the user's targets a patched package, by any selector (``, `@`, `>`): pnpm applies one override per dependency, so the CLI's would lose to it or displace it, and the user's is never overwritten. It is looked for in pnpm-workspace.yaml, the one place the gated pnpm releases read overrides from (`pnpm.overrides` and `resolutions` in package.json are not read by pnpm 11.20 and later, measured through 12.22.0); (6) each lock is one the rewrite was captured against: the release is not a `pnpm patch` copy or an npm alias, an importer that depends on it asks through a plain semver range that admits it (not a tag, `catalog:`, `workspace:`, `npm:` or a URL), no importer locks another version of the package through a range that admits the patched one, no package is installed both with and without the release as its peer (pnpm 11 and 12 lock that differently), the release is not installed as another package's optional peer (pnpm resolves that copy around an override, so it would stay unpatched), and every entry of the lock is one run of lines (a `deprecated:` message of several paragraphs, or one that keeps its trailing line breaks, is written with empty lines inside its entry; a message of several lines without one is a block the routed entry simply loses); (7) no package version is pinned to two patches (an override routes a package version to one registry, and a registry serves one patch); (8) `--no-trust-lockfile-config` is not set, or the file already holds the route exactly; (9) in a Bazel workspace, it is certain that no rules_js hub reads a governing lock. One reads it when an `npm.npm_translate_lock` call of aspect_rules_js names it in a plain string, or has a `pnpm_lock` that is not written out as one, whatever else the call says. And one may read it wherever the workspace was not read whole: a file that `MODULE.bazel` includes and that is missing or unreadable, a use of the extension that is not a plain call of a tag, a `WORKSPACE` file that cannot be read or that brings in rules_js (a `load` from `@aspect_rules_js`, a `load` of `npm_translate_lock` from anywhere, or a call of that rule under any name a `load` gives it). A `WORKSPACE` file that is about something else, an `http_archive` of another ruleset say, defines no hub of a pnpm lock and blocks nothing (see "In a Bazel workspace" below). The write respects `--dry-run` and is refused through a symlink. -**In a Bazel workspace.** The lock reader of rules_js takes a routed lock (measured on macOS: rules_js 3.6.0 on Bazel 9.3.2 builds one for a hub without `update_pnpm_lock`, and the built packages hold the patched bytes; rules_js 2.9.3 on Bazel 8.8.2 does too). What holds the route back is the pnpm a hub runs with `update_pnpm_lock`: it sees pnpm-workspace.yaml only where the call lists it, and may be older than pnpm 11.20 (rules_js picks a pnpm 10 where the workspace states none). Run as the hub runs it (`pnpm install --lockfile-only` beside the lock and `package.json`, without the workspace file), pnpm 11.28.13 and 12.22.0 reject a routed lock (`ERR_PNPM_MISSING_NAMED_REGISTRY`, measured). No Bazel leg builds a routed lock with `update_pnpm_lock` yet, so for now every lock that a hub reads is pinned as on a patch service that offers no registry, the files byte for byte, which is the pin the Bazel legs build, and the warning names the call ("… because a Bazel hub reads the pnpm lock (MODULE.bazel:7), and a lock that a hub reads is not routed yet …"; for a project below the Bazel root, "(MODULE.bazel:7, with paths from the root of the Bazel workspace)"); a project routed before the hub was there leaves the route whole on its next scan, the locks and the workspace file together. Under such a hub a hosted scan never deletes pnpm-workspace.yaml, whose label the hub's `data` may name: where the last of a route leaves a file that a routed run created, the file stays as its `packages` list (`packages:` and `- '.'`), and the entries go as elsewhere. Where the hub also hides pnpm-workspace.yaml from a pnpm 11 (`redirect_pnpm_bazel_workspace_hidden`), that answer comes first, while the files are read, and the root lock is not part of the run: nothing in it is pinned or routed, the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned on `trustLockfile`, and a route an earlier run set up is left exactly as it is, in the workspace file and in every lock, because the root lock records the same overrides and is not written. The workspace file is then byte for byte the one it was: the registries still verify the routed releases, so no `trustLockfile: true` is added for them (it would switch the verification off for every entry). Only a release this run pins in the plain shape beside them, in a member's lock, brings the key. A hosted scan takes no unused entry out there either, and what it does to the files does not turn on what it was granted: with a patch for a package of the lock, with none, and with nothing crawled, it leaves the lock and the workspace file as they are and reports `redirect_pnpm_bazel_workspace_hidden` (a run with no npm patch reports it only for a project that holds something of a route; any other project it leaves without a word, as before). The commands that settle a route from the lockfiles alone pin nothing and work as without Bazel: `repair`, `scan --prune` with no mode, `rollback` and `remove`. **They read no Bazel file**, on this route as for every other hosted pin. So under a hub whose `data` lists a pnpm-workspace.yaml that a routed run created, they still delete that file with the last of the route (as `rollback` deletes a `trustLockfile` file hosted mode created), and the build is then handed a missing file. A hosted scan says so before it comes to that (`redirect_pnpm_bazel_workspace_hidden` asks for a comment line in such a file) and never deletes the file itself. **In memory**, "certain" is certain of the files the engine was handed: the Bazel files at the project's own root (`MODULE.bazel`, the `*.MODULE.bazel` files it can include and the `WORKSPACE` files, beside a `pnpm-lock.yaml` or a `pnpm-workspace.yaml`). A Bazel root above the project is not seen there, for the route as for the pin, so a project in a directory of a Bazel workspace is routed in memory where a checkout is not. A pnpm-workspace.yaml that holds nothing but a route and that a hub lists is one of the files `redirect_pnpm_bazel_workspace_hidden` asks for a comment line in: the scan that leaves the route would otherwise leave a file that `rollback` removes. +**In a Bazel workspace.** **Experimental** (Bazel workspaces). The lock reader of rules_js takes a routed lock (measured on macOS: rules_js 3.6.0 on Bazel 9.3.2 builds one for a hub without `update_pnpm_lock`, and the built packages hold the patched bytes; rules_js 2.9.3 on Bazel 8.8.2 does too). What holds the route back is the pnpm a hub runs with `update_pnpm_lock`: it sees pnpm-workspace.yaml only where the call lists it, and may be older than pnpm 11.20 (rules_js picks a pnpm 10 where the workspace states none). Run as the hub runs it (`pnpm install --lockfile-only` beside the lock and `package.json`, without the workspace file), pnpm 11.28.13 and 12.22.0 reject a routed lock (`ERR_PNPM_MISSING_NAMED_REGISTRY`, measured). No Bazel leg builds a routed lock with `update_pnpm_lock` yet, so for now every lock that a hub reads is pinned as on a patch service that offers no registry, the files byte for byte, which is the pin the Bazel legs build, and the warning names the call ("… because a Bazel hub reads the pnpm lock (MODULE.bazel:7), and a lock that a hub reads is not routed yet …"; for a project below the Bazel root, "(MODULE.bazel:7, with paths from the root of the Bazel workspace)"); a project routed before the hub was there leaves the route whole on its next scan, the locks and the workspace file together. Under such a hub a hosted scan never deletes pnpm-workspace.yaml, whose label the hub's `data` may name: where the last of a route leaves a file that a routed run created, the file stays as its `packages` list (`packages:` and `- '.'`), and the entries go as elsewhere. Where the hub also hides pnpm-workspace.yaml from a pnpm 11 (`redirect_pnpm_bazel_workspace_hidden`), that answer comes first, while the files are read, and the root lock is not part of the run: nothing in it is pinned or routed, the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned on `trustLockfile`, and a route an earlier run set up is left exactly as it is, in the workspace file and in every lock, because the root lock records the same overrides and is not written. The workspace file is then byte for byte the one it was: the registries still verify the routed releases, so no `trustLockfile: true` is added for them (it would switch the verification off for every entry). Only a release this run pins in the plain shape beside them, in a member's lock, brings the key. A hosted scan takes no unused entry out there either, and what it does to the files does not turn on what it was granted: with a patch for a package of the lock, with none, and with nothing crawled, it leaves the lock and the workspace file as they are and reports `redirect_pnpm_bazel_workspace_hidden` (a run with no npm patch reports it only for a project that holds something of a route; any other project it leaves without a word, as before). The commands that settle a route from the lockfiles alone pin nothing and work as without Bazel: `repair`, `scan --prune` with no mode, `rollback` and `remove`. **They read no Bazel file**, on this route as for every other hosted pin. So under a hub whose `data` lists a pnpm-workspace.yaml that a routed run created, they still delete that file with the last of the route (as `rollback` deletes a `trustLockfile` file hosted mode created), and the build is then handed a missing file. A hosted scan says so before it comes to that (`redirect_pnpm_bazel_workspace_hidden` asks for a comment line in such a file) and never deletes the file itself. **In memory**, "certain" is certain of the files the engine was handed: the Bazel files at the project's own root (`MODULE.bazel`, the `*.MODULE.bazel` files it can include and the `WORKSPACE` files, beside a `pnpm-lock.yaml` or a `pnpm-workspace.yaml`). A Bazel root above the project is not seen there, for the route as for the pin, so a project in a directory of a Bazel workspace is routed in memory where a checkout is not. A pnpm-workspace.yaml that holds nothing but a route and that a hub lists is one of the files `redirect_pnpm_bazel_workspace_hidden` asks for a comment line in: the scan that leaves the route would otherwise leave a file that `rollback` removes. **What the warning says.** A patch service that gives no pin of the project a registry address offers no route, and the run and its warning are exactly what they were. As soon as one pin has an address, a run that still ends on `trustLockfile` says why, in one sentence of the `redirect_pnpm_trust_lockfile` warning ("Per-package registry verification was not set up because …"): the hosted packages the patch service gave no address for, by `name@version` (the first five, then "and N more"), since one of them puts the whole lock on `trustLockfile`; the hosted packages pinned on a patch mirror, named the same way; pins that do not prove pnpm 11.20; a Bazel hub that reads the lock (9), by the file and line of its call, or what of the Bazel workspace was not read so that one may ("… because a Bazel hub may read the pnpm lock (WORKSPACE:3: it brings in rules_js, and a hub that this file defines is not read) …"); and whichever of (4) to (7) applied, naming the file, the override or the lock entry. With no pnpm pin at all (and not under `--no-trust-lockfile-config`) the sentence is instead that pinning pnpm 11.20 or later (for example with package.json `packageManager`) and re-running the scan switches the project to per-package registry verification. On the route the warning's detail says the file declares the patch server's registry of each patched package (the `socket-` entries, one per patch) and routes each patched release to its own, to commit it alongside the lock, and keeps the rebuild-the-lockfile and clean-reinstall cautions; it carries no whole-lock tradeoff note. **A newer release in range (a note, never a refusal).** An override keyed `@` applies to every dependency whose range admits that version, and a lock records what a transitive dependent resolved, not the range it asked through. So when a governing lock also holds a newer release of a routed package within the routed release's caret range (the same major, or the same minor below 1.0), on the default registry, the detail ends with a note that names the package and both versions: "pnpm-lock.yaml also locks `` at ``, which a range that admits `` may admit too: a package that depends on `` through such a range moves to the patched `@` the next time pnpm resolves (`pnpm add`, `update`, `dedupe`), …". The lock is written as it is (pnpm installs it frozen, and re-locks it unchanged, until a command resolves the project again: see the [pnpm compatibility notes](../../docs/testing/pnpm-compatibility.md) for what each command does). The note is reported on every run that leaves the project routed, a re-run that changes nothing included (in human mode after the one-line reminder), and changes neither the route nor the exit code. @@ -422,7 +422,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Throttling: bounded retry, then a reported failure.** Every patch-API JSON call (the batch query, the per-package patch lists, patch views and VEX record fetches, hosted package references) retries an HTTP `429` or `503` answer up to 3 times (`SOCKET_API_MAX_RETRIES=`, `0`-`10`; `0` = no retry). The wait honors `Retry-After` (delta-seconds or HTTP-date); a `Retry-After` over 30 s is not waited out — the answer is final at once — and one under the jittered first backoff step (`0`, a past date) waits that step instead. Without one it backs off 0.5 s / 1 s / 2 s (each step up to 8 s, with jitter in its upper half). All retries in one run share a 60 s wall-clock window that opens with the run's first retry: a retry whose wait would end after it closes is refused and the answer is final. Parallel requests wait in parallel, so each still gets its retries while the run adds at most about 60 s. Nothing else is retried (401/403 still drive the proxy fallback on the first answer; the public proxy's permanent `503 "Patch API is not configured"` is never retried on any path — the batch query still degrades to the per-package path at once, and a per-package lookup or patch view answering it is the same non-throttle failure it always was, which on the legacy per-package path leaves that package unanswered, see above), and a retried answer folds exactly where the first attempt's would have, so output is identical to an unthrottled run's. A request still throttled after that is a failure in the channel its siblings use: a failed batch is the human `Warning: API batch of failed: ` line and, under `--json`, a run-level `warnings[]` entry `{code: "api_batch_failed", detail: "API batch of failed: "}` (additive; `status` stays `success`, exit 0 — the other batches' packages are reported); a failed per-package patch-list query in the agent / hosted / vendored flows is the human `Warning: could not fetch details for : ` line and, under `--json`, `{code: "patch_details_failed", detail: "could not fetch details for : "}`. When every batch (or every patch-list query) fails, the existing all-failed error envelope and exit 1 apply. The error names the exhausted retry: `Rate limit exceeded (HTTP 429, gave up after 3 retries). Please try again later.` / `API request failed with status 503: (gave up after 3 retries)` (or `(Retry-After s exceeds the 30 s retry cap)` / `(the run's 60 s retry window has closed)`); with retries off it is the pre-retry text. On the token-less legacy per-package proxy path (a proxy without `POST /patch/batch`), a package still throttled (429 / over-capacity 503) after its retries is an unanswered package (see "No patches" needs an answer above): the batch's answered packages are used and it is reported as `patch_lookup_failed` (`partialFailure`, exit 1); when it leaves no package of its batch answered, the batch fails through the batch-failure channel above. Only a PURL the service itself refuses (its own `400`) is skipped individually. Pinned by `tests/scan_api_retry_e2e.rs` and the core crate's `tests/api_retry_e2e.rs`. -**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **The jars of a pinned rules_jvm_external hub join the supplement of a hosted run at the root of a Bazel workspace (additive)**: `scan --mode hosted` (the inferred default included) and `get --mode hosted` take, for each hub of the root `MODULE.bazel` that names a lock (`maven_install.json`), the jar without a classifier of each artifact the hub fetches, at the lock's version, as a Maven package of the project: it counts in `scannedPackages`, and in `lockfileOnlyPackages` with `notInstalled: true` unless a crawl found that version installed, and a patch found for it is pinned in the block of `MODULE.bazel` (the `maven_bazel_*` rows below). A jar whose repository has no known name is such a package too (a patch found for it gets `maven_bazel_artifact`). No jar is guessed for a hub that was not read with certainty: `warnings[]` then carries `maven_bazel_hub_not_read` once, and the jars of the hubs that were read are still looked up. A patch of a hub's jar is a patch of the run like any other, so the run writes for it what `get --mode hosted` writes in that checkout: beside a Gradle build the hosted Gradle pin too (`settings.gradle` and the files under `.socket/gradle/`, with that pin's warnings), and beside a `pom.xml` what the pom lane pins or says (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`, which speak of `pom.xml` alone). **A stale entry of the block is taken out by `scan --mode hosted` (additive)**: when every hub was read and none fetches the jar of an entry at its version any more (the lock moved on, so Bazel stops at the entry), the scan restores it before the rewrite as the withdrawn-pin sweep above restores a pin: the entry alone, under the apply lock, `--dry-run` previewing it, one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "maven_bazel_entry_stale"` and `details.mode: "hosted"`, also on a scan that finds no package; a pin of the same patch in a `pom.xml` or Gradle file stays; a restore that fails is the `redirect_withdrawn_restore_failed` warning. `get` takes no stale entry out, and no scan takes out a stale entry of vendored mode (a `local_repository` over `.socket/vendor/maven//`): its directory and its ledger entry are vendored mode's, so it stays for `rollback `, `remove ` or `vendor --revert`, which take all three out, and `vendor --check` names it. No other mode, no run whose `--ecosystems` leaves Maven out, no `--global` run and no run of a project below the Bazel root takes a package from a hub, gives that warning or takes a stale entry out: its packages are those of the run without the workspace. A run of a project in no Bazel workspace is, byte for byte, the run it was. See docs/ecosystems.md "Bazel workspaces: Maven". +**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **The jars of a pinned rules_jvm_external hub join the supplement of a hosted run at the root of a Bazel workspace (additive)**: **Experimental** (Bazel workspaces). `scan --mode hosted` (the inferred default included) and `get --mode hosted` take, for each hub of the root `MODULE.bazel` that names a lock (`maven_install.json`), the jar without a classifier of each artifact the hub fetches, at the lock's version, as a Maven package of the project: it counts in `scannedPackages`, and in `lockfileOnlyPackages` with `notInstalled: true` unless a crawl found that version installed, and a patch found for it is pinned in the block of `MODULE.bazel` (the `maven_bazel_*` rows below). A jar whose repository has no known name is such a package too (a patch found for it gets `maven_bazel_artifact`). No jar is guessed for a hub that was not read with certainty: `warnings[]` then carries `maven_bazel_hub_not_read` once, and the jars of the hubs that were read are still looked up. A patch of a hub's jar is a patch of the run like any other, so the run writes for it what `get --mode hosted` writes in that checkout: beside a Gradle build the hosted Gradle pin too (`settings.gradle` and the files under `.socket/gradle/`, with that pin's warnings), and beside a `pom.xml` what the pom lane pins or says (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`, which speak of `pom.xml` alone). **A stale entry of the block is taken out by `scan --mode hosted` (additive)**: when every hub was read and none fetches the jar of an entry at its version any more (the lock moved on, so Bazel stops at the entry), the scan restores it before the rewrite as the withdrawn-pin sweep above restores a pin: the entry alone, under the apply lock, `--dry-run` previewing it, one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "maven_bazel_entry_stale"` and `details.mode: "hosted"`, also on a scan that finds no package; a pin of the same patch in a `pom.xml` or Gradle file stays; a restore that fails is the `redirect_withdrawn_restore_failed` warning. `get` takes no stale entry out, and no scan takes out a stale entry of vendored mode (a `local_repository` over `.socket/vendor/maven//`): its directory and its ledger entry are vendored mode's, so it stays for `rollback `, `remove ` or `vendor --revert`, which take all three out, and `vendor --check` names it. No other mode, no run whose `--ecosystems` leaves Maven out, no `--global` run and no run of a project below the Bazel root takes a package from a hub, gives that warning or takes a stale entry out: its packages are those of the run without the workspace. A run of a project in no Bazel workspace is, byte for byte, the run it was. See docs/ecosystems.md "Bazel workspaces: Maven". **Server artifact acquisition (v5.0)**: vendoring downloads the patched artifact for the selected UUID, including on a fresh checkout with no installed package. The CLI no longer downloads pristine packages, stages patch blobs, applies patches to vendor copies, or constructs archives. Backend lock and package-identity checks still run before acquisition; git and custom-registry Cargo sources are refused with `vendor_source_unsupported`. Healthy committed artifacts are reused offline. A changed UUID downloads a fresh server artifact; an unhealthy artifact at the recorded UUID uses the exact redownload procedure below, except that a directory copy whose ledger entry has no file inventory (vendored before v5.0) is rebuilt by its backend from a fresh verified download, and a missing or stale Bun workspace mirror over a healthy canonical tarball is rewritten from that tarball by the backend; those cases report the backend's own failure codes. @@ -430,7 +430,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Rewritten file ownership**: a hosted or vendored rewrite of a project file that already exists (its lockfiles, package manifests and `.npmrc`, and their `rollback` / `remove` / `vendor --revert` restores; not socket-patch's own `.socket/` records) replaces it with a staged file that keeps the old file's permission bits and, best-effort, its owner and group, like npm's write-file-atomic. A root run (a Docker bind mount, `sudo`) leaves a user's `poetry.lock` owned by that user. An unprivileged run can't give a file to another user; it keeps the old group when it belongs to that group, and otherwise the file takes the runner's owner and group, with no warning. -**Vendored group commit (v5.0)**: `vendor`, `scan --mode vendored` and `get --mode vendored` capture every lockfile / manifest / config edit and every ledger save of the run in memory (reads inside the run see them) and commit them ONCE after the per-package loop — including the packages that succeeded in a run where others failed, so a completed run leaves the same files per-package commits would. Captured: every file under the project root outside `.socket/` and outside any git directory (`.socket` and `.git` are matched under every spelling a filesystem folds onto them, such as `.GIT` or `git~1`; no backend writes into a git directory), plus `.socket/vendor/state.json` and `.socket/vendor/redirect-state.json`; artifacts are written directly (see the durability note). A multi-file commit goes through a roll-forward journal, `.socket/vendor/.commit-journal.json` (the new bytes of every changed file, plus the bytes each replaces and their sha256; deleted once the commit completes). **Crash semantics**: before the journal is durable, nothing is committed — the lockfiles and ledgers are the pre-run ones and the run's artifacts are unreferenced orphans; after it, the next command that takes the apply lock replays the journal before reading anything (files already at their new bytes are left alone), so a locked command never observes a half-committed run. **A replay is never silent**: the command that performed it prints `Warning: an interrupted vendored run's commit was finished from its journal: rolled forward ; …` on stderr (in every output mode, `--silent` and `--json` included), and under `--json` the envelope it goes on to print carries the same sentence as a `vendor_commit_recovered` entry in `warnings[]` (an error envelope printed before the command reached its own work may omit the entry; stderr always has the line). **`--dry-run` replays nothing**: a dry run that takes the lock and finds a journal exits 1 with the top-level error `vendor_commit_pending` (the message names the journal and the files it covers), having written nothing; the journal and every file it covers stay as the interruption left them, and the same command without `--dry-run` (or any other lock-taking command) finishes the commit. A journal that matches neither side of some file (edited by hand since the crash) is renamed to `.socket/vendor/.commit-journal.set-aside-.json` (keeping every file's pre-commit bytes) and stderr says what was done (`Warning: an interrupted vendored run's commit could not be finished as written: …`; under `--json` also a `vendor_commit_set_aside` entry in `warnings[]`): the edited files are never written over; when they all still carry the commit's own lines the rest of the commit is finished around them, when none of them does the files the crash had already replaced are put back to their pre-commit bytes, and otherwise nothing is applied. The journal is a file in the working tree, so a checkout can carry one that no crash wrote (a pull request can commit it); a replay therefore writes only what a commit could have journaled. A journal that is unreadable, names a path outside the captured set (an absolute path, a path with a `..` component, an artifact or any other uncaptured file under `.socket/`, anything inside a `.git` directory), or would write through a symbolic link is set aside with nothing applied, not even its other entries. A replay that fails on I/O keeps the journal and fails the lock acquire (`lock_io`, naming the journal). Read-only commands that take no lock (`vex`, `list`, and the lock-free `--dry-run` previews of `scan` and `get`) may observe the interrupted state until then. A re-vendor under a newer uuid removes the replaced uuid's dir only after the commit (its `vendor_stale_artifact_removed` event follows the run's per-package events), and a golang takeover removes the `.socket/go-patches/` copy only after the commit that repoints `go.mod`. A commit never renames over a symbolic link: when a changed file is a symlink, the whole commit is refused before anything is written, with the top-level error `redirect_symlinked_file_unsupported` (exit 1; a `--dry-run` predicts it with a `vendor_would_refuse_symlinked_file` advisory) — the artifact dirs the run's loop added under `.socket/vendor/` are removed, and every package it vendored is reported as a `failed` event with that code instead of `applied` (its per-package `skipped` advisories from the same run, such as `vendor_prebuilt_downloaded`, are dropped). A commit write failure is the top-level error `vendor_commit_failed` (exit 1; the pre-run lockfiles and ledger stay, the artifact dirs the run added are removed and its vendored packages are `failed` events with that code, the same way — unless putting back the files already replaced failed too, in which case the journal is kept, the next locked command finishes the commit, and the per-package events stand). `repair`, `vendor --revert` and `rollback` still save per entry. One undo commits a group of its own (additive): that of a vendored Maven patch whose jar a pinned rules_jvm_external hub of a Bazel workspace takes too (an entry in the block of `MODULE.bazel`), run by `vendor --revert`, `rollback`, `remove` or a scan's prune. The files of the Maven or Gradle build and `MODULE.bazel` are captured and written together, through the journal when they are more than one: a write that fails puts the files already replaced back and fails that entry's undo with every file as it was (the journal is kept when they could not be put back, and the next locked command finishes the commit); a file among them that is a symbolic link fails it before anything is written; the vendored tree and the hub's directory are removed after the commit, and the ledger entry after that. A run that is killed between two of the files leaves the journal with nothing removed: the next locked command finishes the files, and the undo run again removes the rest. See docs/ecosystems.md "Bazel workspaces: Maven". +**Vendored group commit (v5.0)**: `vendor`, `scan --mode vendored` and `get --mode vendored` capture every lockfile / manifest / config edit and every ledger save of the run in memory (reads inside the run see them) and commit them ONCE after the per-package loop — including the packages that succeeded in a run where others failed, so a completed run leaves the same files per-package commits would. Captured: every file under the project root outside `.socket/` and outside any git directory (`.socket` and `.git` are matched under every spelling a filesystem folds onto them, such as `.GIT` or `git~1`; no backend writes into a git directory), plus `.socket/vendor/state.json` and `.socket/vendor/redirect-state.json`; artifacts are written directly (see the durability note). A multi-file commit goes through a roll-forward journal, `.socket/vendor/.commit-journal.json` (the new bytes of every changed file, plus the bytes each replaces and their sha256; deleted once the commit completes). **Crash semantics**: before the journal is durable, nothing is committed — the lockfiles and ledgers are the pre-run ones and the run's artifacts are unreferenced orphans; after it, the next command that takes the apply lock replays the journal before reading anything (files already at their new bytes are left alone), so a locked command never observes a half-committed run. **A replay is never silent**: the command that performed it prints `Warning: an interrupted vendored run's commit was finished from its journal: rolled forward ; …` on stderr (in every output mode, `--silent` and `--json` included), and under `--json` the envelope it goes on to print carries the same sentence as a `vendor_commit_recovered` entry in `warnings[]` (an error envelope printed before the command reached its own work may omit the entry; stderr always has the line). **`--dry-run` replays nothing**: a dry run that takes the lock and finds a journal exits 1 with the top-level error `vendor_commit_pending` (the message names the journal and the files it covers), having written nothing; the journal and every file it covers stay as the interruption left them, and the same command without `--dry-run` (or any other lock-taking command) finishes the commit. A journal that matches neither side of some file (edited by hand since the crash) is renamed to `.socket/vendor/.commit-journal.set-aside-.json` (keeping every file's pre-commit bytes) and stderr says what was done (`Warning: an interrupted vendored run's commit could not be finished as written: …`; under `--json` also a `vendor_commit_set_aside` entry in `warnings[]`): the edited files are never written over; when they all still carry the commit's own lines the rest of the commit is finished around them, when none of them does the files the crash had already replaced are put back to their pre-commit bytes, and otherwise nothing is applied. The journal is a file in the working tree, so a checkout can carry one that no crash wrote (a pull request can commit it); a replay therefore writes only what a commit could have journaled. A journal that is unreadable, names a path outside the captured set (an absolute path, a path with a `..` component, an artifact or any other uncaptured file under `.socket/`, anything inside a `.git` directory), or would write through a symbolic link is set aside with nothing applied, not even its other entries. A replay that fails on I/O keeps the journal and fails the lock acquire (`lock_io`, naming the journal). Read-only commands that take no lock (`vex`, `list`, and the lock-free `--dry-run` previews of `scan` and `get`) may observe the interrupted state until then. A re-vendor under a newer uuid removes the replaced uuid's dir only after the commit (its `vendor_stale_artifact_removed` event follows the run's per-package events), and a golang takeover removes the `.socket/go-patches/` copy only after the commit that repoints `go.mod`. A commit never renames over a symbolic link: when a changed file is a symlink, the whole commit is refused before anything is written, with the top-level error `redirect_symlinked_file_unsupported` (exit 1; a `--dry-run` predicts it with a `vendor_would_refuse_symlinked_file` advisory) — the artifact dirs the run's loop added under `.socket/vendor/` are removed, and every package it vendored is reported as a `failed` event with that code instead of `applied` (its per-package `skipped` advisories from the same run, such as `vendor_prebuilt_downloaded`, are dropped). A commit write failure is the top-level error `vendor_commit_failed` (exit 1; the pre-run lockfiles and ledger stay, the artifact dirs the run added are removed and its vendored packages are `failed` events with that code, the same way — unless putting back the files already replaced failed too, in which case the journal is kept, the next locked command finishes the commit, and the per-package events stand). `repair`, `vendor --revert` and `rollback` still save per entry. One undo commits a group of its own (additive; **Experimental**, Bazel workspaces): that of a vendored Maven patch whose jar a pinned rules_jvm_external hub of a Bazel workspace takes too (an entry in the block of `MODULE.bazel`), run by `vendor --revert`, `rollback`, `remove` or a scan's prune. The files of the Maven or Gradle build and `MODULE.bazel` are captured and written together, through the journal when they are more than one: a write that fails puts the files already replaced back and fails that entry's undo with every file as it was (the journal is kept when they could not be put back, and the next locked command finishes the commit); a file among them that is a symbolic link fails it before anything is written; the vendored tree and the hub's directory are removed after the commit, and the ledger entry after that. A run that is killed between two of the files leaves the journal with nothing removed: the next locked command finishes the files, and the undo run again removes the rest. See docs/ecosystems.md "Bazel workspaces: Maven". `scan --sync` is sugar for `--mode agent --prune` — the canonical single-flag agent-mode bot invocation. `scan --json --sync` discovers, applies, and reconciles state in one pass. @@ -438,7 +438,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Path-scoped scans (`scan [PATHS]...`, v5.0)**: what a PATH means depends on the mode. -**A bare hosted or vendored scan covers the checkout (additive/MINOR).** With no PATH, `scan` in hosted or vendored mode (the inferred default included) scans `--cwd` and every other project directory below it in the same git checkout, exactly as if each had been named as a PATH: its own lockfiles, ledgers, `.socket/` and inferred mode, one `== ==` heading each (`== . ==` for `--cwd` itself), the worst exit code, one `--max-new-patches` budget. A project directory is one the in-memory engine would detect as a root for the same tree: a directory holding a lockfile of a supported npm-family, PyPI, Cargo, RubyGems, Go or Composer format (a manifest alone never makes one; Maven, Gradle, sbt and NuGet projects are scanned only as `--cwd` or a named PATH), found by a walk that honours git's ignore rules (`.gitignore`, the repository's and the user's excludes; a `.ignore` file, which hides files from search tools and not from git, is not read), never follows a link, never enters `node_modules`, `.git`, `.socket`, `.yarn` or `vendor`, and never enters another repository: a directory below `--cwd` that holds a `.git` entry (a submodule, a nested clone) is left to a run of its own, since this checkout does not track its files and its own `socket.yml` was not read. A workspace member whose only lock is one the workspace root's run reads is not a project of its own: a Cargo workspace member's `Cargo.lock`, and a pnpm workspace member's `pnpm-lock.yaml` the root accounts for. Discovered directories are subject to the `socket.yml` path filters and the built-in `test/`, `tests/`, `fixtures/`, `__fixtures__/` and `testdata/` ignores, as glob-matched PATHs are; the ones left out are counted in one stderr note (`Note: N project directories under ignored paths ... were not scanned; name a directory to scan it.`), and naming a directory scans it. `--cwd` itself is scanned whenever it is a project, with or without a lockfile, as before; in hosted mode it also is one as the root of a Bazel workspace whose rules_jvm_external hubs give the scan packages, a `maven_bazel_hub_not_read` warning or a stale entry to take out (the lockfile supplement above), whatever other file it holds. Nothing is searched for, and the run is the single-directory scan it always was, when: `--cwd` is not inside a git checkout (a scan from a home directory never goes looking for projects), a PATH is given, the scope is `--global`/`--global-prefix`, or the mode is agent (an agent-mode scan still names the directories it left; see below). `--json` and `--vex` report on one project directory, so with either a bare scan scans `--cwd` alone and adds the run-level `projects_not_scanned` warning naming the project directories it found and left (`N project directories below this one were not scanned (a, b): --json takes one project directory. Run one scan per directory, e.g. ...`); exit code and status are unchanged. A bare agent-mode scan patches the installed packages its crawl of `--cwd` reads, so it covers the project at `--cwd` alone. It looks for the same project directories below `--cwd` and adds the `projects_not_scanned` warning (stderr `Warning:`, `--json` `warnings[]`) naming the ones whose installed packages that crawl did not read, and the command that reaches the first, asked as the run was (`scan --mode agent`, `scan --sync`, or a bare `scan` when the mode was inferred): `N project directories below this one were not scanned (a, b): an agent-mode scan patches the packages installed for the one project directory it runs in. Run one scan per directory, e.g. `socket-patch scan --mode agent --cwd a``. More than 10 directories are listed as the first 10 `, and N more`. Exit code and status are unchanged. A directory is named when it has an install directory of its own that the crawl from `--cwd` did not read: a `node_modules` the npm walk skips (one under a hidden or build-output directory), a Python environment or a Composer vendor directory inside the project, or a gem home (the project's `vendor/bundle`, or the user-wide homes Bundler installs into by default when `--cwd` holds no Bundler project to read them for). A directory is not named when the run did read its packages (every other `node_modules` below `--cwd`, a gem home or an activated environment both share) or when it has no install directory of its own; the user-wide Python, Cargo and Go stores are never compared. Nothing is looked for with a PATH, a global scope, a non-default `--manifest-path` or outside a git checkout. With nothing found at `--cwd`, a run that names such directories prints `No packages found (see the warning).` in place of the hint to run the package manager's install. A tree too large to search adds a `projects_below_not_searched` warning: some directories may not be named. A tree with more than 500,000 entries is searched only that far, with a stderr warning. +**A bare hosted or vendored scan covers the checkout (additive/MINOR).** With no PATH, `scan` in hosted or vendored mode (the inferred default included) scans `--cwd` and every other project directory below it in the same git checkout, exactly as if each had been named as a PATH: its own lockfiles, ledgers, `.socket/` and inferred mode, one `== ==` heading each (`== . ==` for `--cwd` itself), the worst exit code, one `--max-new-patches` budget. A project directory is one the in-memory engine would detect as a root for the same tree: a directory holding a lockfile of a supported npm-family, PyPI, Cargo, RubyGems, Go or Composer format (a manifest alone never makes one; Maven, Gradle, sbt and NuGet projects are scanned only as `--cwd` or a named PATH), found by a walk that honours git's ignore rules (`.gitignore`, the repository's and the user's excludes; a `.ignore` file, which hides files from search tools and not from git, is not read), never follows a link, never enters `node_modules`, `.git`, `.socket`, `.yarn` or `vendor`, and never enters another repository: a directory below `--cwd` that holds a `.git` entry (a submodule, a nested clone) is left to a run of its own, since this checkout does not track its files and its own `socket.yml` was not read. A workspace member whose only lock is one the workspace root's run reads is not a project of its own: a Cargo workspace member's `Cargo.lock`, and a pnpm workspace member's `pnpm-lock.yaml` the root accounts for. Discovered directories are subject to the `socket.yml` path filters and the built-in `test/`, `tests/`, `fixtures/`, `__fixtures__/` and `testdata/` ignores, as glob-matched PATHs are; the ones left out are counted in one stderr note (`Note: N project directories under ignored paths ... were not scanned; name a directory to scan it.`), and naming a directory scans it. `--cwd` itself is scanned whenever it is a project, with or without a lockfile, as before; in hosted mode it also is one as the root of a Bazel workspace whose rules_jvm_external hubs give the scan packages, a `maven_bazel_hub_not_read` warning or a stale entry to take out (the lockfile supplement above; **Experimental**, Bazel workspaces), whatever other file it holds. Nothing is searched for, and the run is the single-directory scan it always was, when: `--cwd` is not inside a git checkout (a scan from a home directory never goes looking for projects), a PATH is given, the scope is `--global`/`--global-prefix`, or the mode is agent (an agent-mode scan still names the directories it left; see below). `--json` and `--vex` report on one project directory, so with either a bare scan scans `--cwd` alone and adds the run-level `projects_not_scanned` warning naming the project directories it found and left (`N project directories below this one were not scanned (a, b): --json takes one project directory. Run one scan per directory, e.g. ...`); exit code and status are unchanged. A bare agent-mode scan patches the installed packages its crawl of `--cwd` reads, so it covers the project at `--cwd` alone. It looks for the same project directories below `--cwd` and adds the `projects_not_scanned` warning (stderr `Warning:`, `--json` `warnings[]`) naming the ones whose installed packages that crawl did not read, and the command that reaches the first, asked as the run was (`scan --mode agent`, `scan --sync`, or a bare `scan` when the mode was inferred): `N project directories below this one were not scanned (a, b): an agent-mode scan patches the packages installed for the one project directory it runs in. Run one scan per directory, e.g. `socket-patch scan --mode agent --cwd a``. More than 10 directories are listed as the first 10 `, and N more`. Exit code and status are unchanged. A directory is named when it has an install directory of its own that the crawl from `--cwd` did not read: a `node_modules` the npm walk skips (one under a hidden or build-output directory), a Python environment or a Composer vendor directory inside the project, or a gem home (the project's `vendor/bundle`, or the user-wide homes Bundler installs into by default when `--cwd` holds no Bundler project to read them for). A directory is not named when the run did read its packages (every other `node_modules` below `--cwd`, a gem home or an activated environment both share) or when it has no install directory of its own; the user-wide Python, Cargo and Go stores are never compared. Nothing is looked for with a PATH, a global scope, a non-default `--manifest-path` or outside a git checkout. With nothing found at `--cwd`, a run that names such directories prints `No packages found (see the warning).` in place of the hint to run the package manager's install. A tree too large to search adds a `projects_below_not_searched` warning: some directories may not be named. A tree with more than 500,000 entries is searched only that far, with a stderr warning. **What a bare scan patched at and below `--cwd` is listed and rolled back from `--cwd` (additive/MINOR).** A bare scan covers `--cwd` and the project directories below it, so `list` and a bare `rollback` cover the project at `--cwd` and the patched project directories below it. A bare `rollback` reaches exactly as far as a bare scan from the same directory: from an agent-mode project (whose scan covers that project alone) it rolls back that project alone and names the directories below in a `projects_not_rolled_back` warning. `vex`, `apply`, `repair`, `remove` and `rollback ` act on the one project at `--cwd`, and name the patched directories below when `--cwd` holds nothing for them. The directories below are the ones a bare scan covers (`commands/projects_below.rs`: the same root detection and walk, the same `socket.yml` path filters and built-in `test/`, `tests/`, `fixtures/`, `__fixtures__/` and `testdata/` ignores, applied before any file of a directory is read; `SOCKET_NO_SOCKET_YML` bypasses the file here as `--no-socket-yml` does for the scan), kept when they hold patch state: a manifest with records, a vendor ledger with entries, or hosted pins in their lockfiles (a store that cannot be read counts, so the directory's own run reports it). Nothing is searched for when `--cwd` is not inside a git checkout, the scope is `--global`/`--global-prefix`, or `--manifest-path` is not the default (it names the one project the run is about). With no patched directory below, every command is, byte for byte, the single-project run it always was. @@ -454,7 +454,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Vendored entries and the rest of the CLI.** Because nothing is in the manifest, vendored patches are invisible to `apply` (nothing to apply in place) but fully visible to `list` (listed from the ledger, labeled `Mode: vendored (recorded in .socket/vendor/state.json)` in human mode, exit 0 on a vendored-only project), `vex` (attested from the embedded records while a lockfile still wires the artifact — see "Manifest-less VEX"), `repair` (health-checked and rebuilt from the ledger), and `scan --prune` (lockfile-driven reconcile). They are exempt from standalone `vendor`'s manifest reconcile (`reconcile_dropped` never touches `detached` entries) and exit via `remove ` (which reverts them), `vendor --revert`, or `rollback`, whose vendored leg reverts every in-scope ledger entry (unscoped and identifier-scoped runs; path-scoped runs reach them only when an installed copy matches). -`scan --mode hosted` swaps the in-place apply for the registry-redirect pipeline: discover → resolve hosted-patch references (grant token + integrity + per-dep registry override) → rewrite ONLY the patched dependencies' lockfile / registry-config entries to point at the hosted packages. A dep counts as **redirected** only when its hosted-artifact URL (or per-dep registry index URL) actually landed in a project file — a granted reference whose rewriter found nothing to edit is neither counted nor attested. **No ledger (v5.0)**: hosted mode writes ONLY the lockfile / registry-config edits — `.socket/vendor/redirect-state.json` is never written (on success or failure), and a pre-v5 one on disk is ignored (never read for planning, never quarantined, left byte-identical). The lockfiles are the only record of a hosted patch: `list`, `vex`, `rollback`, `remove`, `vendor` and `repair` all discover the hosted pins from them (a hosted URL counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin or under the `--patch-mirror-url` / `SOCKET_PATCH_MIRROR_URL` base), and commit-ready output is just the lockfile / config changes. Cargo and golang are confirmed only by their rewriter's own report (`confirmed_cargo_uuids` / `confirmed_golang_uuids`): a golang dep counts only when its go.mod `replace M V => patch.socket.dev/gopatch/ ` and both go.sum lines are in place (a re-run restores the zip line `go mod tidy` drops while no package of the module is loaded, so a later import still builds), never because the patch-server origin or leftover go.sum lines appear somewhere. Gradle is confirmed the same way (`confirmed_gradle_uuids`): only when the final files hold the owned script, the index row, the live apply line in every build's settings file and the suffixed version in every lock entry of the GA (see [Gradle builds](#gradle-builds-v50)). A golang module that go.mod does not require and go.sum has no zip (`h1:` of the module tree) line for at the patched version is outside the build graph and is refused with `redirect_golang_not_in_module_graph` (nothing written); with a `go.work` in effect the build graph is the workspace's (every `use` member's go.mod, go.sum and `go.work.sum`), so a member raising the module refuses the pin with `redirect_golang_version_mismatch`, and a `go.work` that overrides, ignores or rejects the replace refuses it with `redirect_golang_workspace_conflict` before anything is written. Run in the directory holding the `go.work`, a module the workspace shares (no root `go.mod`, or the root module is a `use` member and another member lists it or `go.work` already holds the Socket replace) is pinned in `go.work` and its two sum lines go into `go.work.sum`, the members' files untouched; a member's own `replace` of it, which the go.work pin would override, refuses it (`redirect_golang_workspace_conflict`); a `/go.mod`-only line doesn't count, since go writes one for every version MVS reads (#509). In a go < 1.17 graph, where `require` holds only lower bounds, the build selects the highest of the required version and go.sum's zip-line versions, and a patch for a lower version warns `redirect_golang_version_mismatch` (nothing written). Only the exact module `patch.socket.dev/gopatch/` is socket-owned; any other module path is refused with `redirect_golang_untrusted_module_path`. A vendored golang module is taken over like cargo and the npm family: its vendor wiring, committed copy and ledger entry are reverted first (`redirect_takeover_reverted_vendored`). A vendored PyPI package (requirements.txt, Poetry, Pipenv, uv, Hatch, PDM, pylock) is taken over the same way: its vendored wiring is restored to the recorded registry entry, its ledger entry and wheel are removed, and it is redirected in the same commit. The Python rewriters treat any non-registry source as user-authored, so without the revert they refused socket-patch's own vendored source and left the project vendored. A vendored Composer package is taken over the same way: its `composer.lock` entry is restored to the recorded pre-vendor entry, its ledger entry and committed copy are removed, and it is redirected in the same commit, so the lock matches a direct hosted scan and `rollback` can restore it from packagist. Without the revert the rewriter edited the vendored entry in place and kept its patch-uuid `dist.reference`, which `rollback` refused. A vendored Composer entry the takeover cannot revert (its vendored ledger entry is missing) is left vendored with `redirect_composer_vendored_entry`, never repointed in place. A takeover revert that leaves vendored wiring in place is refused with `redirect_vendored_revert_failed`. That covers a drift-skipped record (`vendor_lock_entry_drifted`) and a reverted file that still references the artifact (`vendor_revert_residual_reference`). The ledger entry and artifact are kept, and the package stays vendored and skipped. `--dry-run` predicts the same refusal from the same signals instead of previewing `redirect_would_revert_vendored`. The hosted requirements.txt rewriter only rewrites an existing pin in the root `requirements.txt`, so a vendored requirements.txt package whose wiring is a pin in a `-r` include or a `(transitive)` line vendored mode appended is kept vendored, wet and `--dry-run` alike, with `redirect_requirements_takeover_unreachable` (a top-level `warnings[]` entry, and the `errorCode` of the package's `skipped` event). Its wiring, ledger entry and wheel are kept, so it stays vendored and patched (exit 0). The uv and Poetry rewriters are covered the same way: a vendored uv package whose recorded pre-vendor `uv.lock` entry is at another version than the patch (earlier releases pinned such an entry down to the patch's version, where vendored uv now refuses the patch with `pypi_uv_lock_package_missing`; the revert brings the lock's own version back, and hosted mode only pins the version the lock resolves) is kept vendored with `redirect_uv_takeover_version_unreachable`, and a vendored Poetry package on a Poetry 0.x lock (which hosted mode refuses outright) is kept vendored with `redirect_poetry_lock_unsupported`. **Staged takeover (v5.0)**: the takeover is atomic. Each purl's vendored revert is staged in memory (the run's group commit, the same journaled commit vendored mode uses), the hosted rewrite plans against the reverted project, and a staged purl the rewrite does not pin is retracted: every staged revert is undone, that purl keeps its vendored wiring, ledger entry and artifact byte-identical, and the rest are staged and rewritten again. A retracted purl is a `skipped` event whose `errorCode` is the cause: its existing skip reason (unavailable wheel metadata, …), the rewriter warning that names the package (`redirect_yarn_berry_missing_checksum`, `redirect_pypi_platform_wheel`, …), `redirect_requirements_takeover_unreachable`, the rewrite's lock-level refusal (`redirect_yarn_berry_mixed_line_endings`, `redirect_bun_lock_unsupported`, a Gradle planner refusal, …) or `redirect_takeover_not_pinned`; that warning is reported in `warnings[]`, followed by `redirect_takeover_kept_vendored` naming the package. Exit 0: the package stays vendored and patched, never unpatched in both modes. The reverts, the hosted pins and the vendored ledger then reach the disk in one commit, and the reverted artifacts are deleted only after it: a refusal or write failure before the commit writes nothing, a failed commit puts back the files it replaced, and a commit interrupted after its journal was written is finished by the next command that takes the apply lock. `--dry-run` runs the same steps and drops the staged state instead of committing, so its `verified` events and warnings are the wet run's `applied` events and warnings. A hosted run with no takeover stages its writes the same way but commits them without the journal (it writes nothing under `.socket/`): a file that fails to be replaced puts back the ones already replaced, so a failed run leaves no lock half-redirected. Re-runs over already-rewritten output plan from the current lock text and are idempotent (exit 0, lock unchanged). **Lock (v5.0)**: the hosted engine acquires `<.socket>/apply.lock` before its first wet write (the staged takeover reverts) — not on `--dry-run`, and not when the run would write nothing (zero redirects, all skipped) — so previews and no-op runs never create `.socket/`; contention is `lock_held` and a lock-file I/O fault (a read-only project root, a file squatting on `.socket/`) is `lock_io` — both exit 1, refused BEFORE any project file is written, and rendered like every other lock holder: human `Error (): ` on stderr (+ the `--lock-timeout` hint for a live holder); JSON prints the envelope with `status: "error"` and `error: {code: "lock_held" | "lock_io", message}` (no `redirect` payload: nothing was rewritten). **Takeover symlink pre-check (v5.0)**: a vendored→hosted takeover whose recorded wiring file is a symlink is refused up front with `redirect_symlinked_file_unsupported` — wet and `--dry-run` alike, before any revert — so "nothing was written" holds. **Human mode (v5.0)**: hosted `scan` runs discovery and update detection like the other modes, then rewrites without a prompt (scan never prompts) and prints its result line with one row per package it switched (see "Human output conventions"); `--dry-run` previews through the engine, and a detail fetch that leaves nothing to redirect enters the engine as a no-op (`Redirected 0 packages; rewrote 0 files.`, no lock, no `.socket/`). The detail fetch prints the same progress counter and per-package `Warning: could not fetch details for …` lines as the agent arm. An EMPTY hosted discovery prints `No patches available for installed packages.` and exits 0 without entering the engine; a discovery whose every offer is paid-tier for an org without paid access prints `No downloadable patches: every patch found requires a paid Socket plan.`, and exits 0 without entering the engine (the closing lines count what a paid plan would fix and name the plan page) (parity with the agent/vendored arms). Under `--json` (v5.0, MAJOR) the outcome is recorded into the scan envelope: one event per selected patch, sorted by purl, each with `details.mode: "hosted"` — `applied` for a confirmed pin (`verified` under `--dry-run`), `skipped` with the skip reason as `errorCode` (and its detail as `reason`), or `skipped` / `redirect_unconfirmed` for a patch that was granted but no lockfile entry pinning it could be rewritten (the human output's `Not hosted : …` line; more than three such packages share one line that names the first three) — plus a `redirect: {mode: "hosted", rewrittenFiles}` payload (the files rewritten, or that would be). A `skipped` event does not change `status` or the exit code (the hosted exit policy is an open decision, #704). Rewriter warnings carry stable `redirect_*` codes (e.g. `redirect_npm_no_lockfile`, `redirect_gradle_manual_snippet`, `redirect_golang_unsupported`); new codes are additive (MINOR). v5.0 additive codes: `redirect_composer_no_lockfile` / `redirect_gem_no_gemfile` (composer / gem: neither manifest nor lock present — once per run, after the intake gates), `redirect_pypi_no_lockfile` (pypi: a granted patch reached the PyPI rewriters but the project has no root `requirements.txt`, `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock`, PEP 751 / PEP 723 lock or Hatch configuration — once per run, beside each patch's `redirect_unconfirmed` row; #638), `redirect_pypi_pixi_project` (pypi: the same lane in a pixi project — a root `pixi.toml` or `pixi.lock` and no file a PyPI rewriter reads. pixi installs from its own lock, and mostly from conda channels, so no requirements file or other tool's lock would pin anything; said once per run in place of `redirect_pypi_no_lockfile`, with nothing written, and the detail points at agent mode: `scan --mode agent` after `pixi install`, then `apply` after every later `pixi install`. A pixi project whose own files name another lock tool, a `Pipfile` or a `[tool.uv]`, `[tool.poetry]` or `[tool.pdm]` table, keeps `redirect_pypi_no_lockfile` and that tool's lock step; a build backend alone names no such tool), `redirect_gem_bundle_gemfile_unsupported` (gem: `BUNDLE_GEMFILE` — `BUNDLE_GEMFILE:` in the bundler app config, which outranks the environment variable as in `Bundler::Settings`, else the environment variable — names a manifest other than the project's `Gemfile` / `gems.rb`, so no gem is redirected or attested; a value naming one of those two selects that pair even when the other spelling is present), `redirect_gem_bundle_lockfile_unsupported` (gem: bundler 4's custom lockfile — the `BUNDLE_LOCKFILE` environment variable, else `BUNDLE_LOCKFILE:` in the bundler app config, else in the global config — names a lock other than the loaded pair's own `Gemfile.lock` / `gems.locked`, so no gem is redirected or attested rather than pinning a lock bundler ignores), `redirect_gem_twin_manifest_ambiguous` (gem: a `Gemfile` + `gems.rb` twin under default discovery; bundler 1.x loads the `Gemfile` and bundler ≥ 2 loads `gems.rb`, and a lock's `BUNDLED WITH` records which bundler wrote it, not which one installs it, so neither pair is wired or attested — remove the unused spelling or set `BUNDLE_GEMFILE` to the one in use), `redirect_gem_mirror_overrides_source` (gem: Bundler's all-source, exact patch-source or patch-hostname mirror can route the gem's Socket `source:` to an unpatched upstream gem. Intake reads the app config (`BUNDLE_APP_CONFIG`, where a set-but-empty value selects `/config`, honoring `BUNDLE_IGNORE_CONFIG`) and all `BUNDLE_MIRROR__...` variables visible to the scan; app config overrides the environment per encoded key, then `mirror.all` takes precedence over exact source, which takes precedence over hostname. URI matching follows Bundler's whole-URI case folding, default-port/trailing-slash normalization and single slash key alias, not URL prefixes. An exact-source fallback-timeout key without a mirror URL shadows the hostname mirror and fetches that source directly; a configured URL is conservatively refused even if a timeout could bypass an unreachable mirror at install time. Like `redirect_gem_bundle_gemfile_unsupported`, the gate leaves the Gemfile pair byte-identical and confirms no gem redirect. On an embedded `scan --vex`, rediscovered older hosted gem pins may attest only from verified installed bytes: a missing tree is not excused by the lockfile, and `--vex-no-verify` omits those hosted gems with `mirror_overrides_source` rather than trusting their intercepted source. Agent/vendored evidence, unrelated ecosystems and standalone VEX behavior are unchanged. Details identify the setting form and its app/environment origin without printing mirror values or source URLs, which may contain credentials. Remove the applicable all/source/hostname setting (including any slash alias) from that origin and reuse its existing mirror URL under `mirror.https://rubygems.org` to clear the refusal; an environment setting must be unset in the scan/install environment. User-global Bundler config and mirrors set only in a later install environment are not inspected; keep those mirrors scoped to the upstream source too), `redirect_maven_no_pom` (no `pom.xml` and no Gradle build), `redirect_nuget_lock_unparseable` (a present-but-corrupt `packages.lock.json` — warned once, nothing mutated; an absent lock still proceeds; a leading UTF-8 BOM, which dotnet reads past, is not corrupt and is kept on rewrite), `redirect_nuget_lock_other_version` (the lock also resolves the patched id at another version in some target framework: the exact-id `packageSourceMapping` would route that framework to a feed that serves only the patched version, so the dep is skipped with nothing written; only lock entries at the patched version are ever re-pinned, and `resolved` is never rewritten), `redirect_nuget_mapping_set_aside` (v5.0 #462: another source's `packageSourceMapping` also named the patched id exactly — Visual Studio's mapping UI writes such lists — which ties with the Socket source so NuGet would take the package from whichever feed answers first; that pattern, or its whole `` when it was the only one, is commented out in a `` comment while the patch is wired, and `remove` / `rollback` put it back byte-exact), `redirect_nuget_mapping_conflict` (such a pattern sits in markup that cannot go in a comment; the dep is skipped, nothing written). v5.0 #354: when the rewriter creates the `packageSourceMapping`, its `*` catch-all also names the sources NuGet merges in from the user config and every parent directory's config (honoring ``), since NuGet drops every source no pattern names; a fresh config only seeds `nuget.org` when those inherited configs have it (a parent that cleared it for a mirror keeps that choice); when an inherited config already has a `packageSourceMapping` (NuGet merges those too), no catch-all is written at all — only the Socket pattern — so a source the parent restricts is never widened; the exclusivity set-aside exempts only the source the run wires, so a `socket-patch-*` lookalike key or a stale uuid naming the id is set aside too, `redirect_cargo_lock_pkg_ambiguous` (several same-name+version `[[package]]` blocks and none carries the index `source` — transactional skip), `redirect_cargo_dep_overridden` (the crate does not resolve to crates.io because the user overrides it — its one `Cargo.lock` block carries a git / other-registry `source`, as a `[patch]` git or registry override in the root manifest or any cargo config leaves it, or has no `source` while the root `Cargo.toml` / project `.cargo/config*` holds a `[patch]` path entry for it; with no `Cargo.lock`, the same `[patch.crates-io]` / `[patch."https://github.com/rust-lang/crates.io-index"]` entry for the crate, by key or `package = "…"`, in the root `Cargo.toml` or the project `.cargo/config*` — transactional skip, nothing rewritten: a Socket pin would silently replace the user's fork and the then-unused `[patch]` entry breaks `cargo --locked`). Also additive: `redirect_cargo_directory_source` (#455: a cargo config replaces crates.io with an on-disk source through its `[source.crates-io] replace-with` chain — a directory source, as a `cargo vendor` project has, or a `cargo local-registry` — so the project builds every crates.io crate offline from it and a Socket registry pin would break `cargo build --frozen --offline`. The configs read are the ones cargo reads for a build in the scanned directory: the project's own `.cargo/config*`, every parent directory's (a monorepo root) and `$CARGO_HOME`'s. Every cargo dependency is skipped with nothing written, one warning each naming the crate and the config that set the replacement, and the detail points at agent mode, which patches the copy cargo builds in place. A replacement with a registry mirror is not an offline source and is still redirected). Also additive: `redirect_cargo_bazel_config_unread` (Cargo in a Bazel workspace, see the table below). Also additive: `redirect_gem_version_not_locked` (gem: no `GEM` section of the lock lists the crawled `name (version)`, for example a version another project installed into the shared gem home; the gem is skipped with nothing written, so the user's declared constraint and the locked version are never overwritten), `redirect_gem_no_lockfile` (gem: the project has a `Gemfile` / `gems.rb` but no `Gemfile.lock` / `gems.locked`, so nothing records which version it resolves and the crawled version may be another project's copy in the shared gem home; the gem is skipped with nothing written, never pinned over the user's constraint or appended as a new dependency, and the detail asks for `bundle lock` (or `bundle install`) and a re-run). Also v5.0: a registry override of the wrong kind (or none at all) warns the arm's missing-override code for nuget/gem/golang. Refusals stay fail-closed with a diagnosis that names the actual cause: a yarn-berry lock entry resolving through a non-`npm:` protocol keeps `redirect_yarn_berry_unsupported_protocol` with the entry's ACTUAL protocol in the detail — except socket-patch's OWN vendored wiring (a `file:` range into `.socket/vendor/`), which gets the distinct `redirect_yarn_berry_vendored_entry` code whose detail names the retirement path (`remove ` per package, or `vendor --revert` which unwinds every vendored package, then re-run `scan --mode hosted`). Both leave the entry byte-identical; neither changes exit code or status. **yarn berry line endings (v5.0)**: yarn writes a NEW `yarn.lock` with the OS line ending (`os.EOL` — CRLF on Windows) and keeps an existing lock's majority ending on every later write, and a `core.autocrlf` checkout turns an LF lock CRLF on any OS — so a uniformly CRLF lock is rewritten in its own ending: every untouched byte (a leading BOM included) round-trips (and `rollback`'s upstream restore keeps the lock's own ending). A lock that MIXES CRLF and LF (or holds a bare CR) has no single ending to keep — yarn's own `--immutable` check rejects it too (YN0028) — so it is refused untouched with `redirect_yarn_berry_mixed_line_endings` (the detail names `yarn install`, which normalizes it). The root `package.json`, which the rewrite re-renders to add `resolutions`, gets the same gate: a mixed one is refused untouched with the same code — the decision vendored mode takes with `vendor_yarn_berry_mixed_line_endings`, from the same shared berry gate set. This replaces v4's `redirect_yarn_berry_crlf_unsupported`, which refused every CRLF lock and is no longer emitted. A vendored→hosted takeover of a yarn-berry entry is checked against these project gates (mixed `yarn.lock` / `package.json` line endings, unsupported `cacheKey`, a non-zero `.yarnrc.yml` `compressionLevel`) on the project as it is before any revert, because the revert re-renders `package.json` in its majority ending — wet and `--dry-run` alike. A refused purl keeps its vendored wiring, ledger entry and artifact byte-identical, is skipped with the gate's code (reported in `warnings[]`, followed by `redirect_takeover_kept_vendored`) and is never announced as `redirect_takeover_reverted_vendored`. +`scan --mode hosted` swaps the in-place apply for the registry-redirect pipeline: discover → resolve hosted-patch references (grant token + integrity + per-dep registry override) → rewrite ONLY the patched dependencies' lockfile / registry-config entries to point at the hosted packages. A dep counts as **redirected** only when its hosted-artifact URL (or per-dep registry index URL) actually landed in a project file — a granted reference whose rewriter found nothing to edit is neither counted nor attested. **No ledger (v5.0)**: hosted mode writes ONLY the lockfile / registry-config edits — `.socket/vendor/redirect-state.json` is never written (on success or failure), and a pre-v5 one on disk is ignored (never read for planning, never quarantined, left byte-identical). The lockfiles are the only record of a hosted patch: `list`, `vex`, `rollback`, `remove`, `vendor` and `repair` all discover the hosted pins from them (a hosted URL counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin or under the `--patch-mirror-url` / `SOCKET_PATCH_MIRROR_URL` base), and commit-ready output is just the lockfile / config changes. Cargo and golang are confirmed only by their rewriter's own report (`confirmed_cargo_uuids` / `confirmed_golang_uuids`): a golang dep counts only when its go.mod `replace M V => patch.socket.dev/gopatch/ ` and both go.sum lines are in place (a re-run restores the zip line `go mod tidy` drops while no package of the module is loaded, so a later import still builds), never because the patch-server origin or leftover go.sum lines appear somewhere. Gradle is confirmed the same way (`confirmed_gradle_uuids`): only when the final files hold the owned script, the index row, the live apply line in every build's settings file and the suffixed version in every lock entry of the GA (see [Gradle builds](#gradle-builds-v50)). A golang module that go.mod does not require and go.sum has no zip (`h1:` of the module tree) line for at the patched version is outside the build graph and is refused with `redirect_golang_not_in_module_graph` (nothing written); with a `go.work` in effect the build graph is the workspace's (every `use` member's go.mod, go.sum and `go.work.sum`), so a member raising the module refuses the pin with `redirect_golang_version_mismatch`, and a `go.work` that overrides, ignores or rejects the replace refuses it with `redirect_golang_workspace_conflict` before anything is written. Run in the directory holding the `go.work`, a module the workspace shares (no root `go.mod`, or the root module is a `use` member and another member lists it or `go.work` already holds the Socket replace) is pinned in `go.work` and its two sum lines go into `go.work.sum`, the members' files untouched; a member's own `replace` of it, which the go.work pin would override, refuses it (`redirect_golang_workspace_conflict`); a `/go.mod`-only line doesn't count, since go writes one for every version MVS reads (#509). In a go < 1.17 graph, where `require` holds only lower bounds, the build selects the highest of the required version and go.sum's zip-line versions, and a patch for a lower version warns `redirect_golang_version_mismatch` (nothing written). Only the exact module `patch.socket.dev/gopatch/` is socket-owned; any other module path is refused with `redirect_golang_untrusted_module_path`. A vendored golang module is taken over like cargo and the npm family: its vendor wiring, committed copy and ledger entry are reverted first (`redirect_takeover_reverted_vendored`). A vendored PyPI package (requirements.txt, Poetry, Pipenv, uv, Hatch, PDM, pylock) is taken over the same way: its vendored wiring is restored to the recorded registry entry, its ledger entry and wheel are removed, and it is redirected in the same commit. The Python rewriters treat any non-registry source as user-authored, so without the revert they refused socket-patch's own vendored source and left the project vendored. A vendored Composer package is taken over the same way: its `composer.lock` entry is restored to the recorded pre-vendor entry, its ledger entry and committed copy are removed, and it is redirected in the same commit, so the lock matches a direct hosted scan and `rollback` can restore it from packagist. Without the revert the rewriter edited the vendored entry in place and kept its patch-uuid `dist.reference`, which `rollback` refused. A vendored Composer entry the takeover cannot revert (its vendored ledger entry is missing) is left vendored with `redirect_composer_vendored_entry`, never repointed in place. A takeover revert that leaves vendored wiring in place is refused with `redirect_vendored_revert_failed`. That covers a drift-skipped record (`vendor_lock_entry_drifted`) and a reverted file that still references the artifact (`vendor_revert_residual_reference`). The ledger entry and artifact are kept, and the package stays vendored and skipped. `--dry-run` predicts the same refusal from the same signals instead of previewing `redirect_would_revert_vendored`. The hosted requirements.txt rewriter only rewrites an existing pin in the root `requirements.txt`, so a vendored requirements.txt package whose wiring is a pin in a `-r` include or a `(transitive)` line vendored mode appended is kept vendored, wet and `--dry-run` alike, with `redirect_requirements_takeover_unreachable` (a top-level `warnings[]` entry, and the `errorCode` of the package's `skipped` event). Its wiring, ledger entry and wheel are kept, so it stays vendored and patched (exit 0). The uv and Poetry rewriters are covered the same way: a vendored uv package whose recorded pre-vendor `uv.lock` entry is at another version than the patch (earlier releases pinned such an entry down to the patch's version, where vendored uv now refuses the patch with `pypi_uv_lock_package_missing`; the revert brings the lock's own version back, and hosted mode only pins the version the lock resolves) is kept vendored with `redirect_uv_takeover_version_unreachable`, and a vendored Poetry package on a Poetry 0.x lock (which hosted mode refuses outright) is kept vendored with `redirect_poetry_lock_unsupported`. **Staged takeover (v5.0)**: the takeover is atomic. Each purl's vendored revert is staged in memory (the run's group commit, the same journaled commit vendored mode uses), the hosted rewrite plans against the reverted project, and a staged purl the rewrite does not pin is retracted: every staged revert is undone, that purl keeps its vendored wiring, ledger entry and artifact byte-identical, and the rest are staged and rewritten again. A retracted purl is a `skipped` event whose `errorCode` is the cause: its existing skip reason (unavailable wheel metadata, …), the rewriter warning that names the package (`redirect_yarn_berry_missing_checksum`, `redirect_pypi_platform_wheel`, …), `redirect_requirements_takeover_unreachable`, the rewrite's lock-level refusal (`redirect_yarn_berry_mixed_line_endings`, `redirect_bun_lock_unsupported`, a Gradle planner refusal, …) or `redirect_takeover_not_pinned`; that warning is reported in `warnings[]`, followed by `redirect_takeover_kept_vendored` naming the package. Exit 0: the package stays vendored and patched, never unpatched in both modes. The reverts, the hosted pins and the vendored ledger then reach the disk in one commit, and the reverted artifacts are deleted only after it: a refusal or write failure before the commit writes nothing, a failed commit puts back the files it replaced, and a commit interrupted after its journal was written is finished by the next command that takes the apply lock. `--dry-run` runs the same steps and drops the staged state instead of committing, so its `verified` events and warnings are the wet run's `applied` events and warnings. A hosted run with no takeover stages its writes the same way but commits them without the journal (it writes nothing under `.socket/`): a file that fails to be replaced puts back the ones already replaced, so a failed run leaves no lock half-redirected. Re-runs over already-rewritten output plan from the current lock text and are idempotent (exit 0, lock unchanged). **Lock (v5.0)**: the hosted engine acquires `<.socket>/apply.lock` before its first wet write (the staged takeover reverts) — not on `--dry-run`, and not when the run would write nothing (zero redirects, all skipped) — so previews and no-op runs never create `.socket/`; contention is `lock_held` and a lock-file I/O fault (a read-only project root, a file squatting on `.socket/`) is `lock_io` — both exit 1, refused BEFORE any project file is written, and rendered like every other lock holder: human `Error (): ` on stderr (+ the `--lock-timeout` hint for a live holder); JSON prints the envelope with `status: "error"` and `error: {code: "lock_held" | "lock_io", message}` (no `redirect` payload: nothing was rewritten). **Takeover symlink pre-check (v5.0)**: a vendored→hosted takeover whose recorded wiring file is a symlink is refused up front with `redirect_symlinked_file_unsupported` — wet and `--dry-run` alike, before any revert — so "nothing was written" holds. **Human mode (v5.0)**: hosted `scan` runs discovery and update detection like the other modes, then rewrites without a prompt (scan never prompts) and prints its result line with one row per package it switched (see "Human output conventions"); `--dry-run` previews through the engine, and a detail fetch that leaves nothing to redirect enters the engine as a no-op (`Redirected 0 packages; rewrote 0 files.`, no lock, no `.socket/`). The detail fetch prints the same progress counter and per-package `Warning: could not fetch details for …` lines as the agent arm. An EMPTY hosted discovery prints `No patches available for installed packages.` and exits 0 without entering the engine; a discovery whose every offer is paid-tier for an org without paid access prints `No downloadable patches: every patch found requires a paid Socket plan.`, and exits 0 without entering the engine (the closing lines count what a paid plan would fix and name the plan page) (parity with the agent/vendored arms). Under `--json` (v5.0, MAJOR) the outcome is recorded into the scan envelope: one event per selected patch, sorted by purl, each with `details.mode: "hosted"` — `applied` for a confirmed pin (`verified` under `--dry-run`), `skipped` with the skip reason as `errorCode` (and its detail as `reason`), or `skipped` / `redirect_unconfirmed` for a patch that was granted but no lockfile entry pinning it could be rewritten (the human output's `Not hosted : …` line; more than three such packages share one line that names the first three) — plus a `redirect: {mode: "hosted", rewrittenFiles}` payload (the files rewritten, or that would be). A `skipped` event does not change `status` or the exit code (the hosted exit policy is an open decision, #704). Rewriter warnings carry stable `redirect_*` codes (e.g. `redirect_npm_no_lockfile`, `redirect_gradle_manual_snippet`, `redirect_golang_unsupported`); new codes are additive (MINOR). v5.0 additive codes: `redirect_composer_no_lockfile` / `redirect_gem_no_gemfile` (composer / gem: neither manifest nor lock present — once per run, after the intake gates), `redirect_pypi_no_lockfile` (pypi: a granted patch reached the PyPI rewriters but the project has no root `requirements.txt`, `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock`, PEP 751 / PEP 723 lock or Hatch configuration — once per run, beside each patch's `redirect_unconfirmed` row; #638), `redirect_pypi_pixi_project` (pypi: the same lane in a pixi project — a root `pixi.toml` or `pixi.lock` and no file a PyPI rewriter reads. pixi installs from its own lock, and mostly from conda channels, so no requirements file or other tool's lock would pin anything; said once per run in place of `redirect_pypi_no_lockfile`, with nothing written, and the detail points at agent mode: `scan --mode agent` after `pixi install`, then `apply` after every later `pixi install`. A pixi project whose own files name another lock tool, a `Pipfile` or a `[tool.uv]`, `[tool.poetry]` or `[tool.pdm]` table, keeps `redirect_pypi_no_lockfile` and that tool's lock step; a build backend alone names no such tool), `redirect_gem_bundle_gemfile_unsupported` (gem: `BUNDLE_GEMFILE` — `BUNDLE_GEMFILE:` in the bundler app config, which outranks the environment variable as in `Bundler::Settings`, else the environment variable — names a manifest other than the project's `Gemfile` / `gems.rb`, so no gem is redirected or attested; a value naming one of those two selects that pair even when the other spelling is present), `redirect_gem_bundle_lockfile_unsupported` (gem: bundler 4's custom lockfile — the `BUNDLE_LOCKFILE` environment variable, else `BUNDLE_LOCKFILE:` in the bundler app config, else in the global config — names a lock other than the loaded pair's own `Gemfile.lock` / `gems.locked`, so no gem is redirected or attested rather than pinning a lock bundler ignores), `redirect_gem_twin_manifest_ambiguous` (gem: a `Gemfile` + `gems.rb` twin under default discovery; bundler 1.x loads the `Gemfile` and bundler ≥ 2 loads `gems.rb`, and a lock's `BUNDLED WITH` records which bundler wrote it, not which one installs it, so neither pair is wired or attested — remove the unused spelling or set `BUNDLE_GEMFILE` to the one in use), `redirect_gem_mirror_overrides_source` (gem: Bundler's all-source, exact patch-source or patch-hostname mirror can route the gem's Socket `source:` to an unpatched upstream gem. Intake reads the app config (`BUNDLE_APP_CONFIG`, where a set-but-empty value selects `/config`, honoring `BUNDLE_IGNORE_CONFIG`) and all `BUNDLE_MIRROR__...` variables visible to the scan; app config overrides the environment per encoded key, then `mirror.all` takes precedence over exact source, which takes precedence over hostname. URI matching follows Bundler's whole-URI case folding, default-port/trailing-slash normalization and single slash key alias, not URL prefixes. An exact-source fallback-timeout key without a mirror URL shadows the hostname mirror and fetches that source directly; a configured URL is conservatively refused even if a timeout could bypass an unreachable mirror at install time. Like `redirect_gem_bundle_gemfile_unsupported`, the gate leaves the Gemfile pair byte-identical and confirms no gem redirect. On an embedded `scan --vex`, rediscovered older hosted gem pins may attest only from verified installed bytes: a missing tree is not excused by the lockfile, and `--vex-no-verify` omits those hosted gems with `mirror_overrides_source` rather than trusting their intercepted source. Agent/vendored evidence, unrelated ecosystems and standalone VEX behavior are unchanged. Details identify the setting form and its app/environment origin without printing mirror values or source URLs, which may contain credentials. Remove the applicable all/source/hostname setting (including any slash alias) from that origin and reuse its existing mirror URL under `mirror.https://rubygems.org` to clear the refusal; an environment setting must be unset in the scan/install environment. User-global Bundler config and mirrors set only in a later install environment are not inspected; keep those mirrors scoped to the upstream source too), `redirect_maven_no_pom` (no `pom.xml` and no Gradle build), `redirect_nuget_lock_unparseable` (a present-but-corrupt `packages.lock.json` — warned once, nothing mutated; an absent lock still proceeds; a leading UTF-8 BOM, which dotnet reads past, is not corrupt and is kept on rewrite), `redirect_nuget_lock_other_version` (the lock also resolves the patched id at another version in some target framework: the exact-id `packageSourceMapping` would route that framework to a feed that serves only the patched version, so the dep is skipped with nothing written; only lock entries at the patched version are ever re-pinned, and `resolved` is never rewritten), `redirect_nuget_mapping_set_aside` (v5.0 #462: another source's `packageSourceMapping` also named the patched id exactly — Visual Studio's mapping UI writes such lists — which ties with the Socket source so NuGet would take the package from whichever feed answers first; that pattern, or its whole `` when it was the only one, is commented out in a `` comment while the patch is wired, and `remove` / `rollback` put it back byte-exact), `redirect_nuget_mapping_conflict` (such a pattern sits in markup that cannot go in a comment; the dep is skipped, nothing written). v5.0 #354: when the rewriter creates the `packageSourceMapping`, its `*` catch-all also names the sources NuGet merges in from the user config and every parent directory's config (honoring ``), since NuGet drops every source no pattern names; a fresh config only seeds `nuget.org` when those inherited configs have it (a parent that cleared it for a mirror keeps that choice); when an inherited config already has a `packageSourceMapping` (NuGet merges those too), no catch-all is written at all — only the Socket pattern — so a source the parent restricts is never widened; the exclusivity set-aside exempts only the source the run wires, so a `socket-patch-*` lookalike key or a stale uuid naming the id is set aside too, `redirect_cargo_lock_pkg_ambiguous` (several same-name+version `[[package]]` blocks and none carries the index `source` — transactional skip), `redirect_cargo_dep_overridden` (the crate does not resolve to crates.io because the user overrides it — its one `Cargo.lock` block carries a git / other-registry `source`, as a `[patch]` git or registry override in the root manifest or any cargo config leaves it, or has no `source` while the root `Cargo.toml` / project `.cargo/config*` holds a `[patch]` path entry for it; with no `Cargo.lock`, the same `[patch.crates-io]` / `[patch."https://github.com/rust-lang/crates.io-index"]` entry for the crate, by key or `package = "…"`, in the root `Cargo.toml` or the project `.cargo/config*` — transactional skip, nothing rewritten: a Socket pin would silently replace the user's fork and the then-unused `[patch]` entry breaks `cargo --locked`). Also additive: `redirect_cargo_directory_source` (#455: a cargo config replaces crates.io with an on-disk source through its `[source.crates-io] replace-with` chain — a directory source, as a `cargo vendor` project has, or a `cargo local-registry` — so the project builds every crates.io crate offline from it and a Socket registry pin would break `cargo build --frozen --offline`. The configs read are the ones cargo reads for a build in the scanned directory: the project's own `.cargo/config*`, every parent directory's (a monorepo root) and `$CARGO_HOME`'s. Every cargo dependency is skipped with nothing written, one warning each naming the crate and the config that set the replacement, and the detail points at agent mode, which patches the copy cargo builds in place. A replacement with a registry mirror is not an offline source and is still redirected). Also additive: `redirect_cargo_bazel_config_unread` (Cargo in a Bazel workspace, **Experimental**; see the table below). Also additive: `redirect_gem_version_not_locked` (gem: no `GEM` section of the lock lists the crawled `name (version)`, for example a version another project installed into the shared gem home; the gem is skipped with nothing written, so the user's declared constraint and the locked version are never overwritten), `redirect_gem_no_lockfile` (gem: the project has a `Gemfile` / `gems.rb` but no `Gemfile.lock` / `gems.locked`, so nothing records which version it resolves and the crawled version may be another project's copy in the shared gem home; the gem is skipped with nothing written, never pinned over the user's constraint or appended as a new dependency, and the detail asks for `bundle lock` (or `bundle install`) and a re-run). Also v5.0: a registry override of the wrong kind (or none at all) warns the arm's missing-override code for nuget/gem/golang. Refusals stay fail-closed with a diagnosis that names the actual cause: a yarn-berry lock entry resolving through a non-`npm:` protocol keeps `redirect_yarn_berry_unsupported_protocol` with the entry's ACTUAL protocol in the detail — except socket-patch's OWN vendored wiring (a `file:` range into `.socket/vendor/`), which gets the distinct `redirect_yarn_berry_vendored_entry` code whose detail names the retirement path (`remove ` per package, or `vendor --revert` which unwinds every vendored package, then re-run `scan --mode hosted`). Both leave the entry byte-identical; neither changes exit code or status. **yarn berry line endings (v5.0)**: yarn writes a NEW `yarn.lock` with the OS line ending (`os.EOL` — CRLF on Windows) and keeps an existing lock's majority ending on every later write, and a `core.autocrlf` checkout turns an LF lock CRLF on any OS — so a uniformly CRLF lock is rewritten in its own ending: every untouched byte (a leading BOM included) round-trips (and `rollback`'s upstream restore keeps the lock's own ending). A lock that MIXES CRLF and LF (or holds a bare CR) has no single ending to keep — yarn's own `--immutable` check rejects it too (YN0028) — so it is refused untouched with `redirect_yarn_berry_mixed_line_endings` (the detail names `yarn install`, which normalizes it). The root `package.json`, which the rewrite re-renders to add `resolutions`, gets the same gate: a mixed one is refused untouched with the same code — the decision vendored mode takes with `vendor_yarn_berry_mixed_line_endings`, from the same shared berry gate set. This replaces v4's `redirect_yarn_berry_crlf_unsupported`, which refused every CRLF lock and is no longer emitted. A vendored→hosted takeover of a yarn-berry entry is checked against these project gates (mixed `yarn.lock` / `package.json` line endings, unsupported `cacheKey`, a non-zero `.yarnrc.yml` `compressionLevel`) on the project as it is before any revert, because the revert re-renders `package.json` in its majority ending — wet and `--dry-run` alike. A refused purl keeps its vendored wiring, ledger entry and artifact byte-identical, is skipped with the gate's code (reported in `warnings[]`, followed by `redirect_takeover_kept_vendored`) and is never announced as `redirect_takeover_reverted_vendored`. **Attribution gate (v5.0).** A hosted run never leaves wiring that lockfile discovery calls contested: before the rewrite writes any lockfile, the same discovery `vex`, `list`, `rollback`, `remove` and `vendor` read runs over the project as the rewrite would leave it. A candidate whose pin discovery reads but cannot attribute to one package version (a requirements `-r` include resolving the same version from the registry beside a rewired `Pipfile.lock`, #567; a Maven pin in a ``, #260) is left out of the rewrite and reported as a `skipped` event with `errorCode` `redirect_unattributable` (nothing written for it; exit code unchanged). Unchanged: a pin in a file discovery does not read (a pre-2.6 bundler `Gemfile`, locked by the next `bundle install`) keeps the rewriter's verdict, and so does a deliberate partial redirect the run already reports (a bundled or `bun patch`-ed copy left on the registry, a yarn `npm:` alias entry left on the registry with `redirect_yarn_classic_alias_skipped` / `redirect_yarn_berry_alias_skipped` while the package's direct entry is pinned, a dep withheld from the vlt rewrite while a sibling lock takes it), and so does a vendored→hosted takeover: its vendored wiring is reverted in the run's staged overlay before the rewrite plans, and it is redirected when the rewriters pin it (otherwise it is retracted and stays vendored), in a `--dry-run` preview the same. A pin whose own pnpm or yarn lock also installs an unpatched copy of the same `name@version` (a pnpm `file:` directory or tarball dependency; a yarn `file:` / URL / berry `portal:` / `link:` dependency declared under another name) is written too, with a `redirect_copy_unpatched` warning naming that entry, and is not attested. A lockless NuGet / Cargo pin (an exclusive Socket source mapping without `packages.lock.json`, a Cargo registry pin without `Cargo.lock`) is still written, with a `redirect_pin_lockless` warning: no lockfile records its version, so `vex` cannot attest it and `rollback` / `remove` / `vendor` refuse it until the lockfile exists (whether such pins should be written at all is an open decision). The rollout's recorded view uses the same discovery: a uuid a file merely mentions (a stale `package.json` field, an inactive `pdm.lock`, a comment) is not a pin and does not count as already patched. @@ -560,6 +560,14 @@ A patch mirror is a caching proxy the operator runs in front of the patch server * **A run that was not given the mirror leaves its pins alone.** Before the rewrite, a candidate whose patch uuid one of the project's candidate files already pins through a URL in the hosted shape on an origin that is neither Socket's patch server, a configured origin, nor an origin of this run's own grants is `skipped` / `redirect_pin_on_unconfigured_host`, with a warning naming the file, the host and the setting. Nothing is written for it. This holds with or without a mirror configured: a hosted run never moves a pin off a host it does not know onto the patch server. * **In-memory engine.** `hosted-bundle` and the embedding addon have no mirror setting: they write the patch server's own URLs, and they too leave a pin on a host their grants do not name alone (`redirect_pin_on_unconfigured_host`). +### Bazel workspaces (experimental) + +**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the block it keeps in `MODULE.bazel` and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. + +* **The lookup.** A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout (a checkout whose `.git` belongs to a trusted owner; in no such checkout the project's own directory only), holds a regular file named `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`. A link to a regular file counts, and a directory of such a name does not. The name is looked up as Bazel's own client looks it up, by whether a file answers to it: on a disk that folds case a regular file named `workspace` or `Module.bazel` counts, as it does for Bazel itself, and is read as the workspace file it answers for. `SOCKET_NO_BAZEL` is the way out for a checkout where such a file is no workspace. +* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. +* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. + ### socket.yml patch policy (v5.0) A repository can **narrow** what `scan` patches with a `patches` block in its root `socket.yml` (the Socket scanner's config file; `version: 2` keeps every other consumer working — they strip or ignore the block). Usage guide: [repository patch policy](../../docs/configuration.md#repository-patch-policy). @@ -746,7 +754,7 @@ Every VEX statement's impact string records which patch-application mode persist **Unverified statements (`--no-verify`).** `--no-verify` / `--vex-no-verify` (and an ambient `SOCKET_VEX_NO_VERIFY`) skip every on-disk hash check, so a statement emitted under it rests on the patch records and the wiring gates alone — for an agent-mode patch on nothing but the manifest, even when the installed files are unpatched or absent. Such a run is never silent. Each purl it attests ends its impact-statement part with `; not verified on disk`, appended AFTER the marker, so the three marker strings above stay intact as prefixes (`Patched via Socket patch (vendored); not verified on disk`), and the run raises the `vex_not_verified` warning (stderr in human mode, `warnings[]` / `vex.warnings` under `--json`) naming how many statements carry the suffix. The purls an in-run `scan --mode hosted --vex` confirmed are attested from that run's own evidence in either mode and never carry it. A default (verifying) run's document is unchanged: it never contains the suffix. -**The installed tree (`--no-bazel`).** `--no-bazel` / `--vex-no-bazel` (and an ambient `SOCKET_VEX_NO_BAZEL`, read like `SOCKET_VEX_NO_VERIFY`: `1` or `true` sets it, an empty value does not) say that the document describes what the package manager installed, for a repository that ships that tree while a Bazel hub reads the same lock for something else, such as its tests. The Bazel workspace is then not read: no package is attested as `affected` for `vex_bazel_not_in_build`, and the document, the events, the warnings, the exit code and every printed line are those of the same checkout without its Bazel files. Without the option nothing changes, and outside a Bazel workspace the option changes nothing and is accepted silently. `--vex-no-bazel` is inert unless `--vex` is set. +**The installed tree (`--no-bazel`).** **Experimental** (Bazel workspaces). `--no-bazel` / `--vex-no-bazel` (and an ambient `SOCKET_VEX_NO_BAZEL`, read like `SOCKET_VEX_NO_VERIFY`: `1` or `true` sets it, an empty value does not) say that the document describes what the package manager installed, for a repository that ships that tree while a Bazel hub reads the same lock for something else, such as its tests. The Bazel workspace is then not read: no package is attested as `affected` for `vex_bazel_not_in_build`, and the document, the events, the warnings, the exit code and every printed line are those of the same checkout without its Bazel files. Without the option nothing changes, and outside a Bazel workspace the option changes nothing and is accepted silently. `--vex-no-bazel` is inert unless `--vex` is set. **Identifier overrides.** `--product` / `--vex-product` and `--doc-id` / `--vex-doc-id` are emitted with surrounding whitespace trimmed (a blank value means unset). @@ -1727,7 +1735,7 @@ to **six flavors**. | npm / vlt (`vlt-lock.json`, lockfileVersion 0 or 1 — A0 locks without a version and every other version refuse `vendor_lockfile_version_unsupported`; flavor `vlt`) | patched package **directory** `.socket/vendor/npm//[@scope/]-/node_modules//` (the extra `node_modules/` level lets a package `require()` its own name), its `package.json` without `devDependencies`, plus `/.gitignore` (re-includes the payload against the project's ignores, ignores vlt's links inside it) and `/.gitattributes` (the same `* -text -filter -ident -working-tree-encoding` as the tarball flavors) | direct dependencies of the root or a workspace member only: the lock node becomes a `file` node for the directory, its importer edges and outgoing edges are re-keyed, and each importer's `package.json` spec becomes `file:`; every moved entry lands where vlt's serializer puts it. A node whose only extra is one peer context (`ṗ:N`, `peer.N`, `peer.<16 hex>`: from vlt 1.0.8 a root dependency with resolved peers, from rc.15 a workspace member's) becomes a `file` node without the extra, as vlt writes `file:` dependencies, keeping its peer edges; revert restores the extra-bearing DepID. Refused before any write: transitive targets (`vendor_vlt_transitive_unsupported`), two or more instances of one `name@version` or a modifier extra, importer `peer` edges, foreign registries, a git, remote-tarball or local-directory node of the same package name (vlt records no version for it), a package `vlt build` would build in place (`vendor_vlt_build_scripts_unsupported`), a name declared in several dependency fields (`vendor_lock_entry_unsupported`), a spec that disagrees with the lock (`vendor_vlt_lock_out_of_sync`), a payload git would ignore (`vendor_artifact_gitignored`), a purl vendored under another flavor (`vendor_flavor_changed`); era-A locks warn `vendor_vlt_legacy_lockfile`; an optional dependency (or any dependency node_modules still links to its installed upstream copy) gets `vendor_vlt_reinstall_required` | fresh checkout, `vlt ci` with cold caches: the patched bytes load and `vlt-lock.json` stays byte-identical, also through a warm and a cold `vlt install --frozen-lockfile` (checked on 1.2.0, 1.0.10, 1.0.4, 1.0.0-rc.32 and 1.0.0-rc.14, and on every release by `docs/testing/vlt-compatibility.md`); no-op installs, `vlt install `, `uninstall` and `vlt update` keep the direct dependency vendored. `vendor --revert` restores the registry node, edges and specs, keeping what vlt re-laid since, and refuses on drift | | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | -| composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` unless the run has `--allow-vendored-in-bazel` | +| composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | | gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock) | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | @@ -2195,7 +2203,7 @@ Four `SOCKET_CLI_*` names from the sibling JS Socket CLI are additionally accept Empty string means unset at every layer: exported-but-empty flag-bound vars are scrubbed before clap parses, and the API-client resolution filters empty values at each fallback step. -**Child processes do not inherit Socket configuration.** The programs socket-patch runs (package managers and their version-manager shims, interpreters, `git`, and the `extconf.rb` / compiler of a gem's native rebuild) are started without the Socket API token under any name a Socket tool reads it from (`SOCKET_API_TOKEN`, `SOCKET_CLI_API_TOKEN`, `SOCKET_SECURITY_API_TOKEN`, `SOCKET_API_KEY`, `SOCKET_CLI_API_KEY`, `SOCKET_SECURITY_API_KEY`), without `SOCKET_CLI_CONFIG` and `SOCKET_CLI_API_PROXY`, and without every flag-bound variable, peer alias and registry override in the tables below, plus `SOCKET_UPDATE_BASE_URL`. Names are matched exactly: the child's own settings (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, `NPM_TOKEN` and other registry credentials, and any `SOCKET_`-prefixed variable not named here) pass through unchanged. +**Child processes do not inherit Socket configuration.** The programs socket-patch runs (package managers and their version-manager shims, interpreters, `git`, and the `extconf.rb` / compiler of a gem's native rebuild) are started without the Socket API token under any name a Socket tool reads it from (`SOCKET_API_TOKEN`, `SOCKET_CLI_API_TOKEN`, `SOCKET_SECURITY_API_TOKEN`, `SOCKET_API_KEY`, `SOCKET_CLI_API_KEY`, `SOCKET_SECURITY_API_KEY`), without `SOCKET_CLI_CONFIG` and `SOCKET_CLI_API_PROXY`, and without every flag-bound variable, peer alias and registry override in the tables below, plus `SOCKET_UPDATE_BASE_URL`. Names are matched exactly: the child's own settings (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, `NPM_TOKEN` and other registry credentials, and any `SOCKET_`-prefixed variable not named here) pass through unchanged. So do the switches of the user's own that no flag binds and that hold no credential, `SOCKET_NO_CONFIG`, `SOCKET_NO_UPDATE_CHECK` and `SOCKET_NO_BAZEL`: a socket-patch that a spawned program starts honours them as this run does. | Env var | CLI equivalent | Default | Notes | |---|---|---|---| @@ -2227,7 +2235,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `--no-vlt-install-cleanup` | `false` | Hosted mode, `rollback`, `remove`: keep stale vlt installed copies. | | `SOCKET_NO_GEM_INSTALL_REFRESH` | `--no-gem-install-refresh` | `false` | Hosted mode, `rollback`, `remove`: leave the project's stale installed gems and cached archives alone. | | `SOCKET_GEM_REFRESH_SHARED` | `--gem-refresh-shared` | `false` | Hosted mode, `rollback`, `remove`: also refresh stale gems in gem homes outside the project. | -| `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `--allow-vendored-in-bazel` | `false` | Vendored mode: write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. | +| `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `--allow-vendored-in-bazel` | `false` | **Experimental** (Bazel workspaces). Vendored mode: write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. | | `SOCKET_PATCH_VERSION` | `--update ` | (latest) | Local to `--update`; the same pin `install.sh` honors. | | `SOCKET_BATCH_SIZE` | `scan --batch-size` | `500` authenticated / `100` proxy | Local to `scan`. | | `SOCKET_MAX_NEW_PATCHES` | `scan --max-new-patches` | (unlimited) | Local to `scan` (v5.0): a count or `none`; empty is unset, malformed exits 2. | @@ -2241,7 +2249,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_PRESERVE_STATE` | `rollback --preserve-state` / `remove --preserve-state` | `false` | (v5.0) Shared by `rollback`/`remove` (boolish, empty-tolerant parse like the other bool flags): restore the system but keep the local patch state — manifest entries, vendored artifacts + ledger entries — and skip all GC. On `remove`, combining it with `--skip-rollback` is a usage error (exit 2) **whether either side is flag- or env-sourced** (`SOCKET_PRESERVE_STATE=true remove --skip-rollback` exits 2 too). | | `SOCKET_DOWNLOAD_ONLY` | `repair --download-only` | `false` | Local to `repair`. | | `SOCKET_VENDOR_REVERT` | `vendor --revert` | `false` | Local to `vendor`. | -| `SOCKET_VEX` | `apply --vex` / `scan --vex` / `vendor --vex` | (none) | Embedded OpenVEX output path. The `SOCKET_VEX_*` knobs (`_PRODUCT`, `_NO_VERIFY`, `_NO_BAZEL`, `_DOC_ID`, `_COMPACT`) are shared with the standalone `vex` command; on the host commands they bind to `--vex-product` etc. | +| `SOCKET_VEX` | `apply --vex` / `scan --vex` / `vendor --vex` | (none) | Embedded OpenVEX output path. The `SOCKET_VEX_*` knobs (`_PRODUCT`, `_NO_VERIFY`, `_NO_BAZEL`, `_DOC_ID`, `_COMPACT`) are shared with the standalone `vex` command; on the host commands they bind to `--vex-product` etc. `SOCKET_VEX_NO_BAZEL` is **Experimental** (Bazel workspaces). | | `SOCKET_VEX_OUTPUT` | `vex --output` / `-O` | (none) | Local to the standalone `vex`: document output path (required with `--json`). | ### Config-layer toggles (env-only) @@ -2251,6 +2259,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_NO_CONFIG` | `false` | Truthy (`1`/`true`/`yes`/`on`): disable the socket-cli persisted-config fallback layer entirely — pure flag+env behavior. Also the test-hermeticity switch (the workspace `.cargo/config.toml` exports it as `1` for every cargo-run process). | | `SOCKET_NO_API_TOKEN` | `false` | Truthy: ignore **ambient** API tokens (the `SOCKET_API_TOKEN` env var and the socket-cli config token); only an explicit `--api-token` flag authenticates. Peer alias: `SOCKET_CLI_NO_API_TOKEN`. | | `SOCKET_PATCH_MIRROR_AUTHORIZATION` | (none) | **Experimental** (no stability guarantee; see "Patch mirror (experimental)"). The operator's `Authorization` header value for the patch mirror (`Bearer …`, `Basic …`). Sent only with the hosted run's check of the mirror; never written to a file, never passed to a child process, and there is no flag for it. | +| `SOCKET_NO_BAZEL` | `false` | **Experimental** (no stability guarantee; see [Bazel workspaces (experimental)](#bazel-workspaces-experimental)). Truthy (`1`/`true`/`yes`/`on`/`y`/`t`, in any case; an empty or any other value does not set it): for a project that sits in a checkout with a Bazel workspace file and that Bazel does not build. No project is then taken for one in a Bazel workspace, and every command does what it does in a checkout without the workspace file; what an earlier run wrote for Bazel is still listed and undone. There is no flag for it, a run that honours it says nothing, and a child process inherits it, so that a socket-patch which a spawned program starts gives the same run. | | `SOCKET_NO_UPDATE_CHECK` | `false` | Truthy: disable the passive update notice entirely (see "Passive update notice"). Explicit `--update` still works. Also a test-hermeticity switch (the workspace `.cargo/config.toml` exports it as `1` for every cargo-run process). No `SOCKET_CLI_*` alias (socket-cli has no equivalent today). | | `SOCKET_PLAIN` | (unset) | Overrides the detection of an AI coding agent's terminal (see "Human output conventions", **Agents**). Truthy (`1`/`true`/`yes`/`on`/`y`/`t`): the plain output a pipe gets, on a terminal too. Any other value: the full terminal output, whatever agent variable is set. Presentation only: no result, exit code or `--json` document depends on it. | @@ -2432,7 +2441,7 @@ command's integration tests check its output. | `removed` | `remove`, `repair`, `vendor`, `rollback`, `scan --prune` (manifest entries carry `details.manifest: true`), `scan --mode hosted` | A manifest entry or vendored state was removed, or (artifact-level, no `purl`) `.socket/` artifacts were swept — that GC carrier sets `bytes` and is not counted in `summary.removed`; the sweep's totals are the envelope's `gc`. Also artifact-level and uncounted: one event per unused entry of a pnpm registry route taken out (`errorCode: "registry_entry_unused"`). | | `verified` | `apply`, `remove`, `repair`, `vendor`, `rollback`, `get`, `scan` (dry run); `vex`; `--update --dry-run` | The action *would* succeed cleanly (`files` lists previewed changes); `vex`: the patch verified and was attested. | | `rebuilt` | `repair`, `vendor` | A missing/corrupt vendored artifact was restored from its exact server download (v5.0: never a lost ledger entry — see `vendor_ledger_missing`). `summary.rebuilt` counts these. | -| `rolledBack` | `rollback`, `remove`, `scan --mode hosted` | A patched package was restored to its original files (`files` lists them), or (`rollback`) a vendored / hosted wiring was unwound (`details.mode`). `remove`: one per restored installed copy, `details.path` naming it — v5.0, MAJOR: was the GC carrier's `details.rolledBack`. `scan --mode hosted`: a pin whose patch was withdrawn was restored upstream (`errorCode: "patch_withdrawn"`), or a stale entry was taken out of the block in the `MODULE.bazel` of a Bazel workspace (`errorCode: "maven_bazel_entry_stale"`). | +| `rolledBack` | `rollback`, `remove`, `scan --mode hosted` | A patched package was restored to its original files (`files` lists them), or (`rollback`) a vendored / hosted wiring was unwound (`details.mode`). `remove`: one per restored installed copy, `details.path` naming it — v5.0, MAJOR: was the GC carrier's `details.rolledBack`. `scan --mode hosted`: a pin whose patch was withdrawn was restored upstream (`errorCode: "patch_withdrawn"`), or a stale entry was taken out of the block in the `MODULE.bazel` of a Bazel workspace (`errorCode: "maven_bazel_entry_stale"`; **Experimental**, Bazel workspaces). | ### Stable `errorCode` tags @@ -2453,7 +2462,7 @@ command's integration tests check its output. | `download_failed` | `failed` | repair/get/scan: network or 404 on patch fetch. | | `patch_lookup_failed` | `failed` + scan run-level `warnings[]` | scan: the patch API gave no answer for this package while it answered for others (the token-less per-package path: a transport error, a `5xx`, a throttle that outlasted its retries, a response that is not the service's), so the package was NOT checked for patches. One `failed` event per package (`error`: its own error; a scan-level event recorded before the mode runs, so it carries no `details.mode`) and one warning naming them (` of packages could not be checked for patches (…): `); the scan goes on with the answered packages and ends `partialFailure`, exit 1. No package answered is the top-level `api_batch_failed` error instead. | | `offline_missing_sources` / `blob_corrupt` | `failed` (artifact-level: `details.{hash,state}`, no purl) | repair `--offline`: a blob the manifest references is absent (`state: "missing"`; `afterHash` blobs only, as `beforeHash` blobs are fetched on demand) or on disk with bytes that no longer hash to its name (`state: "corrupt"`: a line-ending-converting checkout, a truncated file; `afterHash` and `beforeHash` blobs). Nothing is fetched offline, so each is a failure of the run (exit 1; human: `Error: N blobs are missing|corrupt (offline mode - not downloading):` on stderr, even under `--silent`); a corrupt file is left in place. Online, both kinds are downloaded (a corrupt entry is replaced whole) and the `downloaded` / dry-run `verified` carrier adds `details.corrupt` (how many were corrupt) when non-zero. `apply` and `rollback` name a corrupt blob in their `apply_failed` / `rollback_failed` error (`blob is corrupt … Run \`socket-patch repair\``); they hash a blob only when about to write its bytes. | -| `cleanup_failed` | `skipped` (warning) | repair: an orphan-sweep pass (blobs, diff or package archives) failed mid-way (e.g. permission error). The run continues and exits 0; human mode carries the warning on stderr (not muted by `--silent`). v5.0: `rollback`'s default GC and `remove`'s GC surface the same condition in their run-level `warnings[]` (`remove`: also on stderr in human mode) — same posture, never affects the exit. A hosted `scan` / `get` gives it, in `warnings[]`, when its entry took the place of a vendored one in the block of a Bazel hub and the directory that vendored mode kept for that jar (`.socket/vendor/maven//`) could not be deleted. | +| `cleanup_failed` | `skipped` (warning) | repair: an orphan-sweep pass (blobs, diff or package archives) failed mid-way (e.g. permission error). The run continues and exits 0; human mode carries the warning on stderr (not muted by `--silent`). v5.0: `rollback`'s default GC and `remove`'s GC surface the same condition in their run-level `warnings[]` (`remove`: also on stderr in human mode) — same posture, never affects the exit. A hosted `scan` / `get` gives it, in `warnings[]`, when its entry took the place of a vendored one in the block of a Bazel hub and the directory that vendored mode kept for that jar (`.socket/vendor/maven//`) could not be deleted (**Experimental**, Bazel workspaces). | | `rollback_failed` | `failed` | remove/rollback: file restore could not complete (rollback: no blocking file names a more specific code). The copy is left patched, as it was: restores are staged and deletes planned before the first file changes, and a failure puts the files already changed back (`apply_failed`'s rule; `Cannot roll back: - ` / `Failed to delete : `). | | `already_original` | `skipped` | rollback (v5.0): every file of the copy already matches its `beforeHash`. | | `hash_mismatch` / `file_not_found` / `missing_blob` | `failed` | rollback (v5.0): the copy's first blocking file drifted from both hashes, is missing, or its before-blob is unavailable (`details.filesVerified` names each file). | @@ -2536,7 +2545,7 @@ command's integration tests check its output. | `vendor_yarn_berry_unsupported` | `failed` | vendor (npm): yarn-berry Plug'n'Play layout; use its native `yarn patch` workflow. | | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | -| `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | +| `vendor_composer_bazel_workspace` | `failed` | **Experimental** (Bazel workspaces). vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` or `SOCKET_NO_BAZEL=1`, `vendor --revert`, and a package of a project that uses vendored mode already, by a release before this refusal or by a run with the flag: any package when `packages` of `composer.lock` names a copy under `.socket/vendor/composer`, and a package of `packages-dev` when `packages-dev` names one. Such a package is refused nothing: not a newer patch, not its first patch, not a `scan` or `get` with no `--mode`. A package of `packages` is still refused while only `packages-dev` names a copy, and so is a package the lock does not hold. So the first vendored path in a section a Bazel rule may install is what is refused, and the detail says so. That keeps a setup of an earlier release working and breaks no build: either no Bazel rule installs from that lock, or one does and its build already fails on a path in a section it installs, which one more path there does not change. The section matters because a rule may run `composer install --no-dev`, which reads `packages` alone: a copy that only `packages-dev` names breaks no such build. A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | @@ -2554,7 +2563,7 @@ command's integration tests check its output. | `patch_fetch_failed` (eject) | `failed` | vendor eject (v5.0): a hosted pin's patch record could not be fetched from `…/patches/view/`; the whole eject is refused (`eject_refused`), nothing touched, exit 1. | | `redirect_pnpm_lockfile_elsewhere` / `redirect_workspace_lockfile_elsewhere` / `cargo_manifest_not_workspace_root` (hosted) | top-level `error.code` (`status: "error"`) | scan / get `--mode hosted` (v5.0): the project directory is a workspace member whose lock lives in another directory, so the rewriters, which read only the project directory, would pin nothing, or would pin a lock of its own that its package manager never reads (`redirect_workspace_lockfile_elsewhere`: a `pnpm-lock.yaml` in a member a `pnpm-workspace.yaml` lists, which pnpm ignores for the workspace's shared lock unless the workspace sets `sharedWorkspaceLockfile: false`, checked with pnpm 10.34 and 11.27; a yarn 1 `yarn.lock` in a `package.json` workspace member, which yarn 1.22 never reads; the message names the workspace root to run from) (pnpm: no npm-family lock here, and the nearest ancestor `pnpm-workspace.yaml` or the project's `lockfile-dir` (`.npmrc`) / `lockfileDir` (`pnpm-workspace.yaml`) puts `pnpm-lock.yaml` elsewhere; npm / yarn / Bun, `redirect_workspace_lockfile_elsewhere`: no npm-family lock here, and the nearest ancestor `package.json` whose `workspaces` (array, or the object form's `packages`) matches the directory holds `package-lock.json`, `npm-shrinkwrap.json`, `yarn.lock`, `bun.lock` or `bun.lockb`; a matching root with none of them that is itself listed by an outer root's `workspaces` hands the check to that root; vlt, same code: the nearest ancestor `vlt.json` whose `workspaces` (a string, an array, or an object of groups) matches the directory holds `vlt-lock.json`, or, as vlt falls back to it when `vlt.json` has no `workspaces` field, the `package.json` `workspaces` root above holds `vlt-lock.json`, and the nearer of a `vlt.json` and a `package.json` root is named; `workspaces` patterns use the glob grammar the package managers share: `*`, `?`, `**`, brace sets and sequences (`{a,b}`, `{1..3}`) and character classes (`[a-c]`, `[!a]`), read the way the root's lock's package manager reads them (#1097): extglobs (`@(a|b)`, `?(…)`, `*(…)`, `+(…)`, `!(…)`) match for npm and yarn but not Bun or vlt; for Bun and vlt, `*`, `?` and `**` never match a directory whose name starts with `.` (`packages/*` does not list `packages/.tools`, #1542, #1631) unless the pattern spells the dot (`packages/.tools`, `packages/.*`), while a `!` pattern still excludes one; yarn berry (picomatch) also reads regex groups (`packages/(a|b)`; a group without `|` only in a pattern fast-glob deems dynamic, or in a `!` pattern), the regex quantifiers `?` / `+` after a group, `+` after a class and `+` inside a group, POSIX classes (`[[:alpha:]]`) and `..` segments in a static pattern or after a static prefix (`packages/a/../b` lists `packages/b`; literal in a `!` pattern); a group alternative holding `/` (`(packages/ui|apps/web)`) is matched across components, and a `?` or `+` quantifying such a group fails closed (the pattern lists every directory, and excludes none as a `!` pattern) (#1490); so does a pattern with extglob or regex groups that is past what socket-patch works out — a brace alternative longer than 4,096 characters or with more than 64 groups, or one whose matching against a directory takes more than about a million steps (an ambiguous group such as `*(a|aa)` repeated dozens of times against a name hundreds of characters long) — while a pattern without groups is read whatever its length, and a brace set is expanded to at most 4,096 alternatives and a megabyte of text; a `!` pattern excludes what earlier patterns matched for npm, Bun 1.3+ (a `bun.lock` with a top-level `configVersion`) and vlt, excludes whatever the order for yarn berry (a `yarn.lock` with `__metadata`, where a leading `!(` is an extglob), and is ignored by yarn classic and older Bun (a `bun.lock` without `configVersion`, or a `bun.lockb` alone without the trailing `cNfGvRsN` config-version extension, its binary twin, #1492); only the root's locks whose package manager lists the directory govern it (and are named), and a lockless root lists it when any of them would; when a pnpm workspace also governs the directory, the nearer root is named and a tie goes to `redirect_pnpm_lockfile_elsewhere`; uv (pypi, #1138), `redirect_workspace_lockfile_elsewhere`: the directory holds a `pyproject.toml`, and the nearest ancestor `pyproject.toml` declaring `[tool.uv.workspace]` lists it in `members` (and not in `exclude`), with no standalone project (`[project]`, no workspace) in between, so uv installs it from that root's `uv.lock` (a `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock` or pylock left in the member is never read and does not exempt it); the message says uv workspaces are not patched from their root yet either, and vendored refuses the same layout with `pypi_uv_workspace_unsupported` instead of rewriting a member with Hatch configuration as a lockless Hatch project; a directory whose own locks are all ones its manager never reads inside a workspace member is refused the same way, naming the ignored locks: `package-lock.json` / `npm-shrinkwrap.json` when its `package.json` `workspaces` root holds `package-lock.json` or `npm-shrinkwrap.json` (npm, #1094), `bun.lock` / `bun.lockb` when that root holds `bun.lock` or `bun.lockb` (Bun, #1101), and `vlt-lock.json` in a directory with no `vlt.json` of its own when its vlt workspace root (as above) holds `vlt-lock.json` (vlt, #1134), or, listed or not, when vlt's project root for the directory is another directory holding `vlt-lock.json` (vlt, #1584: the nearest ancestor `vlt.json`, else the outermost directory holding a `package.json` or `node_modules`, the walk ending at a directory holding `.git` and below the home directory, as vlt's own `find("project")` does; the message names that root and says a `vlt.json` in the directory makes it a project of its own); vendored refuses it with `vendor_lockfile_missing`, and `vex` reads the ignored lock as absent, with one `patched_ref_unattributable` warning naming it when it holds Socket references) or rewrite the member as a lockless project (cargo: the vendored workspace-root check). Refused before any takeover or write, `--dry-run` included; the message names the directory to run from; exit 1. Disk runs only (an in-memory project has no ancestors). | | `redirect_pnpm_settings_elsewhere` | top-level `error.code` (`status: "error"`) | scan / get `--mode hosted`: the project directory is a pnpm workspace member (listed by the `packages:` globs of the nearest ancestor `pnpm-workspace.yaml`) with its own v9 `pnpm-lock.yaml` (`sharedWorkspaceLockfile: false`) and no `pnpm-workspace.yaml` of its own, so its pnpm settings come from that ancestor file, which pnpm reads alone (a member's own file is ignored). A directory those globs do not list (no `packages:`, an empty list, a non-matching or `!`-excluded path) is a standalone project on pnpm 11.28+/12 that reads only its own file: it is pinned and gets its own `pnpm-workspace.yaml` like any single project. A root file that does not parse, or whose patterns use braces, classes or extglobs, counts as listing the project. When that file neither carries `trustLockfile: true` nor explicitly sets another value, the trust auto-config has nowhere to go: refused before any takeover or write, `--dry-run` included; the message names the root file to add `trustLockfile: true` to (or `--no-trust-lockfile-config` pins without it); exit 1. Once the root file trusts the lock (or opts out), the member is pinned and no nested `pnpm-workspace.yaml` is created; the `redirect_pnpm_trust_lockfile` warning names the root file. In memory, a member whose lock is demoted into its workspace root (#492) is never refused; one whose lock is not (the workspace root's files do not confirm it pins or ignores that lock, or socket.yml leaves the root out) is refused with this code as its project error, nothing written for it, whenever its lock is v9, the trust auto-config is on and that file may list it (listed, unreadable, or not readable as globs), whatever it says about `trustLockfile`. | -| `redirect_pnpm_bazel_workspace_hidden` | `warnings[]` (warning, one per run) | scan / get `--mode hosted`, dry and wet, and the in-memory engine: the project is in a Bazel workspace where one `npm.npm_translate_lock` call of aspect_rules_js names its `pnpm-lock.yaml` in a plain string, keeps it up to date (`update_pnpm_lock` is `True` or not written out as `True` or `False`), does not list the `pnpm-workspace.yaml` beside the lock in a `data` that is a list of strings (or lists a file that would hold only what hosted mode writes, or one hosted mode does not write `trustLockfile: true` to), and runs a pnpm that the workspace states as 11 or later or in a way that is no version, or states none under a release of aspect_rules_js whose own choice is not known (any but 1.x to 3.x, 4.0.0-alpha.0 and 4.0.0-alpha.1, by `bazel_dep`, a `single_version_override` and `MODULE.bazel.lock`) (the `pnpm_version`, or the `packageManager` of the `pnpm_version_from` file, of the `pnpm.pnpm` tag whose `name` is the repository of the call's `use_pnpm`, `pnpm` without one; a `use_pnpm` whose repository no `use_repo` takes by position under that name, or that no such tag makes unless it is `pnpm`, is no version). The pnpm that Bazel runs would not read the `trustLockfile: true` hosted mode writes, would reject the pinned lock (`ERR_PNPM_TARBALL_URL_MISMATCH`), and `bazel build` would fail. Every root pnpm lock is left untouched and no npm pin is confirmed from it; the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned as without Bazel (in the root lock each package is a `skipped` event: `redirect_unconfirmed`, or `redirect_unattributable` where another npm lock of the project names it, which is then not pinned either), exit 0, `status: "success"`. The detail starts with the file and the line of the call, named as the file writes it (`MODULE.bazel:7: this `npm.npm_translate_lock` …`; `MODULE.bazel:7, with paths from the root of the Bazel workspace: …` for a project below that root) and ends with what to do: `; pnpm-lock.yaml was not rewritten — list `//:pnpm-workspace.yaml` in the `data` of that call and re-run`, with the label of the file beside the lock. Before the label, or alone where the call lists the file: where the file would hold only what hosted mode writes (none, an empty file, the root-only `packages` scaffold, a file of an earlier hosted run), `put a comment line in pnpm-workspace.yaml (create the file where there is none: …)`, because `rollback` removes such a file and the call would name a missing one; where the file says `trustLockfile:` with another value than `true`, or is YAML a line cannot be added to, to set `trustLockfile: true` in it. Where `data` is not written out as a list of strings, the last step is to write it out as one that holds the label. A hub without `update_pnpm_lock`, one that runs pnpm 10 or states no release under a release of the ruleset whose choice is known, one that lists a file of the user's own that takes the setting, a project whose lock no call names and a project in no Bazel workspace are not affected. See docs/ecosystems.md, "Bazel workspaces: npm". | +| `redirect_pnpm_bazel_workspace_hidden` | `warnings[]` (warning, one per run) | **Experimental** (Bazel workspaces). scan / get `--mode hosted`, dry and wet, and the in-memory engine: the project is in a Bazel workspace where one `npm.npm_translate_lock` call of aspect_rules_js names its `pnpm-lock.yaml` in a plain string, keeps it up to date (`update_pnpm_lock` is `True` or not written out as `True` or `False`), does not list the `pnpm-workspace.yaml` beside the lock in a `data` that is a list of strings (or lists a file that would hold only what hosted mode writes, or one hosted mode does not write `trustLockfile: true` to), and runs a pnpm that the workspace states as 11 or later or in a way that is no version, or states none under a release of aspect_rules_js whose own choice is not known (any but 1.x to 3.x, 4.0.0-alpha.0 and 4.0.0-alpha.1, by `bazel_dep`, a `single_version_override` and `MODULE.bazel.lock`) (the `pnpm_version`, or the `packageManager` of the `pnpm_version_from` file, of the `pnpm.pnpm` tag whose `name` is the repository of the call's `use_pnpm`, `pnpm` without one; a `use_pnpm` whose repository no `use_repo` takes by position under that name, or that no such tag makes unless it is `pnpm`, is no version). The pnpm that Bazel runs would not read the `trustLockfile: true` hosted mode writes, would reject the pinned lock (`ERR_PNPM_TARBALL_URL_MISMATCH`), and `bazel build` would fail. Every root pnpm lock is left untouched and no npm pin is confirmed from it; the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned as without Bazel (in the root lock each package is a `skipped` event: `redirect_unconfirmed`, or `redirect_unattributable` where another npm lock of the project names it, which is then not pinned either), exit 0, `status: "success"`. The detail starts with the file and the line of the call, named as the file writes it (`MODULE.bazel:7: this `npm.npm_translate_lock` …`; `MODULE.bazel:7, with paths from the root of the Bazel workspace: …` for a project below that root) and ends with what to do: `; pnpm-lock.yaml was not rewritten — list `//:pnpm-workspace.yaml` in the `data` of that call and re-run`, with the label of the file beside the lock. Before the label, or alone where the call lists the file: where the file would hold only what hosted mode writes (none, an empty file, the root-only `packages` scaffold, a file of an earlier hosted run), `put a comment line in pnpm-workspace.yaml (create the file where there is none: …)`, because `rollback` removes such a file and the call would name a missing one; where the file says `trustLockfile:` with another value than `true`, or is YAML a line cannot be added to, to set `trustLockfile: true` in it. Where `data` is not written out as a list of strings, the last step is to write it out as one that holds the label. A hub without `update_pnpm_lock`, one that runs pnpm 10 or states no release under a release of the ruleset whose choice is known, one that lists a file of the user's own that takes the setting, a project whose lock no call names and a project in no Bazel workspace are not affected. See docs/ecosystems.md, "Bazel workspaces: npm". | | `eject_refused` | top-level `error.code` (`status: "error"`) | vendor eject (v5.0): a record fetch failed or a pin's upstream restore was refused while planning; nothing was changed, exit 1. | | `eject_planned` | `applied` (reason) | vendor eject `--dry-run` (v5.0): the pin would be restored upstream and vendored; nothing written. | | `eject_rolled_back` | warning; `skipped` event | vendor eject (v5.0): a package failed after the restore began; every touched file was put back from the pre-eject snapshot, so the project is still hosted; `partialFailure`, exit 1. Also the `errorCode` of the `skipped` event re-reporting each package the eject had vendored before it was rolled back (not counted in `summary.applied`). | @@ -2617,8 +2626,8 @@ command's integration tests check its output. | `redirect_pin_lockless` | `warnings[]` (warning) | scan/get `--mode hosted` (nuget, cargo): the pin was written without a lockfile that records its version, so `vex` cannot attest it and `rollback` / `remove` / `vendor` refuse it as unattributable. The detail names the lockfile to create (`dotnet restore --use-lock-file`, `cargo generate-lockfile`) before re-running the hosted scan. | | `redirect_pypi_stale_install` | `warnings[]` (warning) | Hosted Python redirect: readable installed files differ from the pinned patched wheel's `RECORD` (or from the patch record, when the wheel cannot judge the copy). Read-only, repeated on re-scan, and excludes the package from same-run VEX. See the "Python stale-install guard" section. | | `redirect_nuget_stale_global_package` / `vendor_nuget_stale_global_package` | `warnings[]` (warning, hosted) / `skipped` (warning, vendor advisory event) | scan `--mode hosted` / `vendor` / `scan --mode vendored` (nuget, v5.0 #352): NuGet's global packages folder (`NUGET_PACKAGES`, else `~/.nuget/packages`) already holds the patched package extracted from other bytes (its `.nupkg.metadata` `contentHash` is not the patched one). A patch keeps the upstream id and version and NuGet restores a package already in that folder without asking any source, so `dotnet restore` would keep the upstream bytes (silently without a lock, NU1403 against the re-pinned lock with one). The detail names the directory and the remedy: delete it, then `dotnet restore` (`dotnet nuget locals global-packages --clear` also works but empties the whole machine-wide folder, and the detail says so); CI caches of that folder must drop it too. Read-only like the gem guard (the folder is shared machine-wide), re-fired on every re-run until the copy is gone, skipped on `--dry-run`; a hosted purl it flags is excluded from the same run's `--vex` `assume_applied` and reported stale. A dir without `.nupkg.metadata` (a legacy `packages/` folder) is never judged. | -| `redirect_bazel_nuget_config_undeclared` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (nuget, additive): a rules_csharp `nuget.from_lock` tag of the root `MODULE.bazel` (or of a file it includes) reads a `packages.lock.json` of the project, or may (its `packages_lock_json` is not a label in a plain string), and the tags do not show that the hub takes its package sources from the `nuget.config` hosted mode writes. The hub has one list of sources, which the last tag with a `nuget_config` or `feeds` decides: that tag names another file or has `feeds` alone, no tag has either, or a tag cannot be read with certainty (it is not a call of its own, passes `**`, or its `nuget_config` is not a label in a plain string). Also given, for every NuGet package of the run, where the tags do show it, a tag has `feeds` and the config names no package source yet: the first source in it would take the place of those `feeds`. Where the tags are in more than one file their order is unknown and every tag with a `nuget_config` or `feeds` must name the config. The hub would download the upstream package and fail the build on the re-pinned `contentHash`, so nothing is written for the package: no `nuget.config`, no lock entry. The package is a `skipped` / `redirect_unconfirmed` event; status and exit are unchanged (exit 0). One warning per package that the run would re-pin in a lock a tag reads (a package refused for another reason keeps that reason's code; a package in no such lock is pinned as without Bazel): the detail starts `@: ::`, says what stands against the pin, and names the way on: the attribute to put on the tag (`nuget_config = "//:"`, with the config as the project directory spells it; the file alone where the tag does not name its lock in a plain string or the config lies outside the package of that label), with the sources or `feeds` to name in that config where the tag had others, or, for a tag that names a NuGet config in a directory above the project, the directory to run the command in (`--cwd`). Never given outside a Bazel workspace, for a project without a lock, or when no tag names one of the project's locks: those runs are unchanged, as is one in a workspace where a part of `MODULE.bazel` cannot be read and the tags that are read show the config. See [Bazel workspaces: NuGet](../../docs/ecosystems.md#bazel-workspaces-nuget). | -| `redirect_bazel_nuget_lock_not_repinned` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (nuget, additive): under the same condition (a `nuget.from_lock` tag reads, or may read, a lock of the project), another tag reads a `packages.lock.json` of the checkout that this run does not re-pin, and that lock holds the package at the patched version with another `contentHash`, or cannot be read; or another tag, beside one that names a lock of the project, does not name its lock in a plain string. The hub holds a package to the `contentHash` of the first lock that names it, so it would refuse the patched package: nothing is written for the package (`skipped` / `redirect_unconfirmed`, exit 0), also when the hub does not read the config yet. Not given when the tags are in one file and a lock of the project that holds the package comes before the other lock, or when the other lock holds the package at another version or already at the patched `contentHash`. The detail starts `@: ::`, names the tag and the lock, and says to run the command in a directory above both locks that holds a solution file or a `nuget.config` (`--cwd`), where the lock of every project is re-pinned; for a tag whose lock is not named, to write its `packages_lock_json` as a label in a plain string. Checked before `redirect_bazel_nuget_config_undeclared`. See [Bazel workspaces: NuGet](../../docs/ecosystems.md#bazel-workspaces-nuget). | +| `redirect_bazel_nuget_config_undeclared` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). scan/get `--mode hosted` in a Bazel workspace (nuget, additive): a rules_csharp `nuget.from_lock` tag of the root `MODULE.bazel` (or of a file it includes) reads a `packages.lock.json` of the project, or may (its `packages_lock_json` is not a label in a plain string), and the tags do not show that the hub takes its package sources from the `nuget.config` hosted mode writes. The hub has one list of sources, which the last tag with a `nuget_config` or `feeds` decides: that tag names another file or has `feeds` alone, no tag has either, or a tag cannot be read with certainty (it is not a call of its own, passes `**`, or its `nuget_config` is not a label in a plain string). Also given, for every NuGet package of the run, where the tags do show it, a tag has `feeds` and the config names no package source yet: the first source in it would take the place of those `feeds`. Where the tags are in more than one file their order is unknown and every tag with a `nuget_config` or `feeds` must name the config. The hub would download the upstream package and fail the build on the re-pinned `contentHash`, so nothing is written for the package: no `nuget.config`, no lock entry. The package is a `skipped` / `redirect_unconfirmed` event; status and exit are unchanged (exit 0). One warning per package that the run would re-pin in a lock a tag reads (a package refused for another reason keeps that reason's code; a package in no such lock is pinned as without Bazel): the detail starts `@: ::`, says what stands against the pin, and names the way on: the attribute to put on the tag (`nuget_config = "//:"`, with the config as the project directory spells it; the file alone where the tag does not name its lock in a plain string or the config lies outside the package of that label), with the sources or `feeds` to name in that config where the tag had others, or, for a tag that names a NuGet config in a directory above the project, the directory to run the command in (`--cwd`). Never given outside a Bazel workspace, for a project without a lock, or when no tag names one of the project's locks: those runs are unchanged, as is one in a workspace where a part of `MODULE.bazel` cannot be read and the tags that are read show the config. See [Bazel workspaces: NuGet](../../docs/ecosystems.md#bazel-workspaces-nuget). | +| `redirect_bazel_nuget_lock_not_repinned` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). scan/get `--mode hosted` in a Bazel workspace (nuget, additive): under the same condition (a `nuget.from_lock` tag reads, or may read, a lock of the project), another tag reads a `packages.lock.json` of the checkout that this run does not re-pin, and that lock holds the package at the patched version with another `contentHash`, or cannot be read; or another tag, beside one that names a lock of the project, does not name its lock in a plain string. The hub holds a package to the `contentHash` of the first lock that names it, so it would refuse the patched package: nothing is written for the package (`skipped` / `redirect_unconfirmed`, exit 0), also when the hub does not read the config yet. Not given when the tags are in one file and a lock of the project that holds the package comes before the other lock, or when the other lock holds the package at another version or already at the patched `contentHash`. The detail starts `@: ::`, names the tag and the lock, and says to run the command in a directory above both locks that holds a solution file or a `nuget.config` (`--cwd`), where the lock of every project is re-pinned; for a tag whose lock is not named, to write its `packages_lock_json` as a label in a plain string. Checked before `redirect_bazel_nuget_config_undeclared`. See [Bazel workspaces: NuGet](../../docs/ecosystems.md#bazel-workspaces-nuget). | | `redirect_gem_stale_install` | `warnings[]` (warning) | scan / get `--mode hosted` (gem): a stale UNPATCHED materialization (installed gem, or committed archive in bundler's cache dir — `vendor/cache` unless `cache_path` moves it) that `bundle install` will reuse instead of fetching the redirected patch, and that the run did not refresh: it is in a shared gem home, or the refresh could not be done (the detail says why) or is turned off. The detail carries the remedy. A human run prints one warning for all of them. Full rules and flavors: the "Gem stale-install guard" section. | | `redirect_gem_install_refreshed` | `warnings[]` (note) | scan / get `--mode hosted` (gem): a stale materialization the run replaced with the sha256-verified patched gem (the detail names the purl and the path). A human run prints a progress line instead. See the "Gem stale-install guard" section. | | `redirect_gem_install_would_refresh` | `warnings[]` (note) | scan / get `--mode hosted --dry-run` (gem): a stale materialization a wet run would replace. Nothing was written or downloaded. | @@ -2626,7 +2635,7 @@ command's integration tests check its output. | `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083, #2093): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | -| `redirect_bazel_gem_checksums_pinned` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (gem, additive): a rules_ruby `ruby.bundle_fetch` call of the root `MODULE.bazel` (or of a file it includes) reads the project's lock, or may (its `gemfile_lock` is not a label in a plain string), and its `gem_checksums` holds a build of the gem that the lock names (`-`, or `--`) to another sha256 than the patched archive has (in either case of its letters), or is not written out as a dict of strings (a constant, an expression, a `**` argument). rules_ruby gives Bazel's downloader that sha256, so the build after a redirect would fail (`Bundler found mismatched checksums`, `Checksum was ... but wanted ...`) or keep the upstream gem: nothing is written for the gem (no `source:` option, no lock change). The gem is a `skipped` / `redirect_unconfirmed` event; status and exit are unchanged (exit 0), and the other gems of the run are rewritten. One warning per gem that the run would otherwise pin (a gem refused for another reason keeps that reason's warning alone). The detail starts `@: \`\` at :`, names each such entry, and says to change it to the sha256 of the patched archive, which it gives, or, where the lock has a `CHECKSUMS` section for Bundler to hold the gem to, to delete the gem from the dict, and to re-run; where further calls hold the gem it ends by naming them (`The same holds for at : ...: change it there too`); socket-patch never edits the call, so an entry changed by hand goes back by hand after a `rollback`. A call counts whether or not it is a statement of its own; an `rb_bundle_fetch` call of the `WORKSPACE` file counts unless a tag of the module files names the lock in a plain string, and `@//` is the main repository there for the name `workspace(name = ...)` gives; what the reader cannot read of the workspace changes nothing. Not given in no Bazel workspace, for a lock no call may read, beside a call without `gem_checksums`, and for an entry that holds the patched sha256 or an empty string. A pin an earlier release wrote stays, is still reported `applied` (and attested by `--vex`), and gets the warning, which then says `the pin an earlier run wrote is left as it is` in place of `redirect skipped` and names `socket-patch rollback pkg:gem/@` (the gem's own pin, never a bare `rollback`, which would unwind every patch) as the other way out. Every call that may read the lock counts, also one whose hub the built targets do not use. The in-memory engine reads the calls where the project's directory is the Bazel root. See [Bazel workspaces: RubyGems](../../docs/ecosystems.md#bazel-workspaces-rubygems). | +| `redirect_bazel_gem_checksums_pinned` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). scan/get `--mode hosted` in a Bazel workspace (gem, additive): a rules_ruby `ruby.bundle_fetch` call of the root `MODULE.bazel` (or of a file it includes) reads the project's lock, or may (its `gemfile_lock` is not a label in a plain string), and its `gem_checksums` holds a build of the gem that the lock names (`-`, or `--`) to another sha256 than the patched archive has (in either case of its letters), or is not written out as a dict of strings (a constant, an expression, a `**` argument). rules_ruby gives Bazel's downloader that sha256, so the build after a redirect would fail (`Bundler found mismatched checksums`, `Checksum was ... but wanted ...`) or keep the upstream gem: nothing is written for the gem (no `source:` option, no lock change). The gem is a `skipped` / `redirect_unconfirmed` event; status and exit are unchanged (exit 0), and the other gems of the run are rewritten. One warning per gem that the run would otherwise pin (a gem refused for another reason keeps that reason's warning alone). The detail starts `@: \`\` at :`, names each such entry, and says to change it to the sha256 of the patched archive, which it gives, or, where the lock has a `CHECKSUMS` section for Bundler to hold the gem to, to delete the gem from the dict, and to re-run; where further calls hold the gem it ends by naming them (`The same holds for at : ...: change it there too`); socket-patch never edits the call, so an entry changed by hand goes back by hand after a `rollback`. A call counts whether or not it is a statement of its own; an `rb_bundle_fetch` call of the `WORKSPACE` file counts unless a tag of the module files names the lock in a plain string, and `@//` is the main repository there for the name `workspace(name = ...)` gives; what the reader cannot read of the workspace changes nothing. Not given in no Bazel workspace, for a lock no call may read, beside a call without `gem_checksums`, and for an entry that holds the patched sha256 or an empty string. A pin an earlier release wrote stays, is still reported `applied` (and attested by `--vex`), and gets the warning, which then says `the pin an earlier run wrote is left as it is` in place of `redirect skipped` and names `socket-patch rollback pkg:gem/@` (the gem's own pin, never a bare `rollback`, which would unwind every patch) as the other way out. Every call that may read the lock counts, also one whose hub the built targets do not use. The in-memory engine reads the calls where the project's directory is the Bazel root. See [Bazel workspaces: RubyGems](../../docs/ecosystems.md#bazel-workspaces-rubygems). | | `redirect_maven_trusted_checksums_maven3_only` / `maven_trusted_checksums_maven3_only` | `warnings[]` (warning) | scan / get `--mode hosted` (the first code) and rollback / remove (the second), Maven: the Trusted Checksums settings hosted mode wrote into `.mvn/maven.config` named the checksums directory through `${session.rootDirectory}`, which stops Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project, and this run respelled that line with `${maven.multiModuleProjectDirectory}` in a project that declares no Maven (no Maven Wrapper naming an Apache Maven release, a root pom of model 4.0.0). Maven 3.9.4 and later 3.x enforce the checksums as before; a Maven 4 build of the project no longer does. Reported once, by the run that changes the line. The remedy for a project Maven 4 builds: declare Maven 4 (a wrapper that pins it, or a root pom of model 4.1.0); the next hosted scan then writes the spelling Maven 4 reads. Status and exit code are unchanged. | | `redirect_maven_version_not_selected` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the build does not resolve the artifact at the patch's base version; the detail names the version Maven selects instead, or says that the build does not resolve the artifact. The run writes nothing for the dep and it is not counted as redirected. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | | `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. The detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). For a single pom the run then writes nothing for the dep. In a reactor the warning is a note on a plan that may still be written: it names the first module whose selection cannot be read and counts the rest; those modules get no new pin, while the modules that are certain are still pinned and a declaration that names the base version is still rewritten, so the dep may be counted as redirected beside this warning. | @@ -2706,21 +2715,21 @@ command's integration tests check its output. | `vendor_pypi_reinstall_required` | `skipped` (advisory; human: `Warning: …`); rollback/remove `warnings[]`; `scan --prune` top-level `warnings[]` (human: `GC: …`) | a PyPI vendored revert (`vendor --revert`, rollback / remove of a vendored entry, the manifest reconcile, `--preserve-state` and `--dry-run` included) of a requirements.txt (pip), PDM, uv or Pipenv entry (#477, #1953). These tools reinstall a same-version package only when the LOCKED candidate is a URL or file that differs from the installed one, so once the lock is back on the registry release a plain `pdm sync` / `pdm install`, `uv sync` or `pipenv sync` reports nothing to do and keeps the vendored build; once a requirements line is back to `name==version`, `pip install -r` (and `uv pip install -r`) reports it already satisfied and keeps it too. The detail names the purl and the reinstall that restores the upstream bytes: `pip uninstall -y ` then `pip install -r ` for each requirements file that wired the entry (or the `uv pip uninstall` / `uv pip install -r` pair), which keeps those files' version ranges, index and hash options, `pdm sync --reinstall` (or recreating the virtualenv / `__pypackages__`), `uv sync --reinstall-package `, or Pipenv's `pipenv run pip uninstall -y && pipenv sync` (the categories from `Pipfile.lock`; `pipenv --rm && pipenv sync` for a clean virtualenv). Poetry, Hatch and PEP 751 entries do not get it. | | `redirect_pypi_reinstall_required` | rollback/remove `warnings[]` (+ human stderr), `vendor --revert` `warnings[]` | a hosted unwind (wet or `--dry-run`) that restored PyPI pins in `pdm.lock`, `uv.lock`, `Pipfile.lock` or a pip requirements file (`*.txt`) to their registry entry: the `vendor_pypi_reinstall_required` rule for hosted pins (the patched build's `direct_url.json` still names the patch server). One run-level warning naming each purl and its reinstall; a pin wired by both a lock and a requirements file (a `uv export` beside `uv.lock`) gets the lock tool's reinstall. | | `redirect_withdrawn_check_failed` | `warnings[]` (warning; human: `Warning: …`) | scan `--mode hosted`: the reference lookup for the uuids the lockfiles pin failed, so the run could not tell whether any was withdrawn. Every pin is kept; status and exit unchanged. See "Withdrawn pins". | -| `redirect_withdrawn_restore_failed` | `warnings[]` (warning; human: `Warning: …` / `Error: …`) | scan `--mode hosted`: a pin whose patch is `withdrawn` / `not_found` could not be restored to its upstream registry entry (the restore refused it, writing the restored files failed, or the apply lock was held). The pin is kept and no `rolledBack` event is recorded for it; the detail names the remedy (`git checkout -- `, or re-run / `socket-patch rollback `). A write failure is one warning naming every pin it kept. Status and exit unchanged, unless the failed write could not put a file back: see `lockfile_write_failed`. Also for a stale entry of a Bazel workspace's block that could not be taken out (`maven_bazel_entry_stale`). | +| `redirect_withdrawn_restore_failed` | `warnings[]` (warning; human: `Warning: …` / `Error: …`) | scan `--mode hosted`: a pin whose patch is `withdrawn` / `not_found` could not be restored to its upstream registry entry (the restore refused it, writing the restored files failed, or the apply lock was held). The pin is kept and no `rolledBack` event is recorded for it; the detail names the remedy (`git checkout -- `, or re-run / `socket-patch rollback `). A write failure is one warning naming every pin it kept. Status and exit unchanged, unless the failed write could not put a file back: see `lockfile_write_failed`. Also for a stale entry of a Bazel workspace's block that could not be taken out (`maven_bazel_entry_stale`; **Experimental**, Bazel workspaces). | | `patch_withdrawn` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted`: the lockfile pinned a patch the server reports `withdrawn` or `not_found`; the pin was restored (dry run: would be) to its upstream registry entry. `reason` names the uuid and status. See "Withdrawn pins". | -| `maven_bazel_entry_stale` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the block in `MODULE.bazel` held an entry of hosted mode for a jar that no pinned rules_jvm_external hub fetches at that version any more, at which Bazel stops ("does not generate repository"); the entry was taken out (dry run: would be), and with the last entry the block. Only when every hub was read, and not in a root, or for a package, that the `socket.yml` policy filters. A pin of the same patch in another build's files (a `pom.xml`, the hosted Gradle index) stays, and so does a stale entry of vendored mode (the lockfile supplement says who takes that one out). `reason` names the uuid. A restore that fails keeps the entry with a `redirect_withdrawn_restore_failed` warning; one that leaves a file half written stops the run (`lockfile_write_failed`, exit 1), also when the scan has no package. See the lockfile supplement and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_entry_stale` | `rolledBack` / `verified` (hosted event) | **Experimental** (Bazel workspaces). scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the block in `MODULE.bazel` held an entry of hosted mode for a jar that no pinned rules_jvm_external hub fetches at that version any more, at which Bazel stops ("does not generate repository"); the entry was taken out (dry run: would be), and with the last entry the block. Only when every hub was read, and not in a root, or for a package, that the `socket.yml` policy filters. A pin of the same patch in another build's files (a `pom.xml`, the hosted Gradle index) stays, and so does a stale entry of vendored mode (the lockfile supplement says who takes that one out). `reason` names the uuid. A restore that fails keeps the entry with a `redirect_withdrawn_restore_failed` warning; one that leaves a file half written stops the run (`lockfile_write_failed`, exit 1), also when the scan has no package. See the lockfile supplement and docs/ecosystems.md "Bazel workspaces: Maven". | | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | -| `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | -| `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | -| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | -| `maven_bazel_unreadable` | agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning); vendored: as `maven_bazel_not_at_root` | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in agent mode (hosted and vendored mode give `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in agent mode, a `maven.override` of the artifact (hosted and vendored mode give `maven_bazel_no_effect`). Hosted and vendored mode also give it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | -| `maven_bazel_hub_not_read` | scan run-level `warnings[]` (human: `Warning: …`); `get --mode hosted`: `warnings[]` | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the scan takes the jars that the pinned rules_jvm_external hubs fetch for packages of the project (the lockfile supplement above), and something of the hubs could not be read with certainty, so it does not know every Maven artifact that Bazel builds through a hub. Given once per run, for the first thing that was not read, whatever the packages: a hub without `lock_file` (the detail then ends with how to pin it), or one of the reasons of `maven_bazel_unreadable` that concern reading the hubs (a tag or a lock that cannot be read, a `maven_install` of a `WORKSPACE` file that Bazel may read, a construct of `MODULE.bazel` the reader does not follow, a block that was changed by hand). `[:]: , so socket-patch does not know every Maven artifact that Bazel builds here through a rules_jvm_external hub: it looks for patches of the ones in the hub locks it read, and of no other`. No jar is guessed for what was not read; the jars of the hubs that were read are scanned, and a patch found for one of them gets no entry while the doubt stands (`maven_bazel_not_pinned` / `maven_bazel_unreadable` below). With no package at all a person reads `No packages found (see the warning).`. Exit code and `status` unchanged. A hosted `get` by advisory, which keeps the releases the project has by the same supplement, gives it too when the advisory has a patch of a Maven artifact. Only in a workspace that has to do with the ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, or a `maven_install.json` lies at the Bazel root. In another Bazel workspace a file that cannot be read gives no such warning, and the run is the one without the workspace. | -| `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. **Vendored mode** (`vendor`, and `scan` / `get --mode vendored`; additive) gives the same codes, but for `maven_bazel_download`, with the same detail, for a jar whose entry it does not write. In a project with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the event is `failed` with the code as its `errorCode` and the detail, without the purl in front, as its `error`, nothing is written and the run exits 1, as for any vendored refusal (before, such a project failed with `vendor_jvm_shape_unsupported`, which a jar that no hub builds still does). Beside such a build that was vendored, the code is a run-level `warnings[]` entry (human: `Warning: …`), the event is `applied` and the exit code is unchanged. With none of these codes vendored mode commits the patched jar under `.socket/vendor/maven//` (`REPO.bazel`, `file/BUILD.bazel`, `file/-.jar`, `.gitignore`), writes the entry that names that directory into the block, in the place of a hosted entry for the same jar, adds the directory's line to `.bazelignore`, and records the patch in the vendor ledger (in a project with no other JVM build: `ecosystem` `maven`, `flavor` `bazel`, the committed jar as `artifact`, no `wiring`); the event is `applied`. `vendor --check` then also fails (`vendor_check_failed`) when that jar is not, byte for byte, the vendored jar the ledger records (beside a Maven or Gradle build the hub's jar is a copy of it), when `REPO.bazel` / `file/BUILD.bazel` is not the file that was written, when the block no longer names the directory or was changed by hand, and when no pinned hub takes the jar at that version any more (the reason names `socket-patch rollback `) or an rc file switches the entry off. `vendor --revert` / `rollback` / `remove` take the entry, the directory and the line out, and a hosted run that puts its entry in the place of the vendored one removes the directory and the line. See docs/ecosystems.md "Bazel workspaces: Maven". | -| `maven_bazel_not_pinned` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: a hub of the workspace has no `lock_file` (also one that only `maven.artifact` or `maven.from_toml` tags make), so Bazel resolves its jars when it builds and none can be replaced. Also given beside a pinned hub that holds the artifact. The detail names the hub's file and line and how to pin it. | -| `maven_bazel_release` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the Bazel release is not known to be 7.4.0 or later, the first with `override_repo` (`.bazeliskrc` or `.bazelversion` names an older one, or neither names a release of three numbers and `MODULE.bazel.lock` is missing or of a format before the one Bazel 7.5.0 writes), or the rules_jvm_external release Bazel selected is not known to be one of 6.4 to 7.2 (`MODULE.bazel.lock` holds the `source.json` of no release of it or of more than one, of a release outside that range, of an older one than the `bazel_dep` of `MODULE.bazel` asks for, or of another one than a `single_version_override` there pins; or an `archive_override`, `git_override`, `local_path_override` or `multiple_version_override` of the ruleset, or a `single_version_override` whose version is no plain string, leaves the release unknown). Versions are compared as Bazel compares them. The detail names the remedy (a `.bazelversion`, one build so that Bazel writes its lock, or an update of socket-patch) or the line of the override. | -| `maven_bazel_artifact` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the repository through which the hub fetches this jar has no known name (a character other than letters, digits, `.`, `_` and `-` in its group, artifact or version), the lock lists no repository for the jar (`m2local`), or the patch comes without the version it is served under or without a sha256. | -| `maven_bazel_no_effect` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the build would pass on the upstream jar with the block in place. The root has a `maven.override` for the artifact, or an rc file of the checkout (`.bazelrc` and what it imports with `import`, `try-import` and `try-import-if-bazel-version`, by a path under `%workspace%/` or a relative one; each read as Bazel reads an rc file: lines joined at a `\` before a line break, comments from a `#`, words without their quotes and escapes) names `--ignore_dev_dependency` without switching it off, or names `enable_bzlmod` other than switched on (Bazel reads `false`, `0`, `no`, `f`, `n` in any case and a `no` before the name as off) while the checkout names no Bazel 9 or later. The detail names the file and the line. | -| `maven_bazel_download` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`, in hosted mode only (a vendored jar is in the checkout): an rc file of the checkout names a downloader config, `--repository_disable_download` or `--vendor_dir`, under which Bazel may not be able to download the patched jar from the Socket patch host. The detail names the file, the line and the option. | +| `bazelignore_not_updated` | run-level `warnings[]` | **Experimental** (Bazel workspaces). Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | +| `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | **Experimental** (Bazel workspaces). Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_unreadable` | agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning); vendored: as `maven_bazel_not_at_root` | **Experimental** (Bazel workspaces). Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in agent mode (hosted and vendored mode give `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in agent mode, a `maven.override` of the artifact (hosted and vendored mode give `maven_bazel_no_effect`). Hosted and vendored mode also give it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. Not given, in any mode, for a jar that no hub that was read fetches in a workspace that has nothing to do with the ruleset and whose files were all read: no `bazel_dep`, `module` or override call of `MODULE.bazel` or of a file it includes has the name `rules_jvm_external` in a plain string, no `WORKSPACE` file that Bazel may read calls `maven_install`, no `maven_install.json` lies at the Bazel root, `MODULE.bazel` does not hold the block of hosted mode (the four signs of `maven_bazel_hub_not_read`), and no file of the workspace that is there was left unread. There an `include` of a file that does not exist, and a statement other than an `include` that the reader does not follow, are about no hub, and the run is the one without the workspace. A file that is there and was not read as a whole (not UTF-8, larger than 1 MiB, a link that leads out of the workspace, text the reader cannot parse, a file past the reader's bounds, a `WORKSPACE` file that cannot be read), and the file of an `include` that the reader does not follow (Bazel 9 takes `include("//:x.MODULE.bazel", dev_dependency = True)`, and that file is not read), may be the one that names the ruleset, and keeps the warning. | +| `maven_bazel_hub_not_read` | scan run-level `warnings[]` (human: `Warning: …`); `get --mode hosted`: `warnings[]` | **Experimental** (Bazel workspaces). scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the scan takes the jars that the pinned rules_jvm_external hubs fetch for packages of the project (the lockfile supplement above), and something of the hubs could not be read with certainty, so it does not know every Maven artifact that Bazel builds through a hub. Given once per run, for the first thing that was not read, whatever the packages: a hub without `lock_file` (the detail then ends with how to pin it), or one of the reasons of `maven_bazel_unreadable` that concern reading the hubs (a tag or a lock that cannot be read, a `maven_install` of a `WORKSPACE` file that Bazel may read, a construct of `MODULE.bazel` the reader does not follow, a block that was changed by hand). `[:]: , so socket-patch does not know every Maven artifact that Bazel builds here through a rules_jvm_external hub: it looks for patches of the ones in the hub locks it read, and of no other`. No jar is guessed for what was not read; the jars of the hubs that were read are scanned, and a patch found for one of them gets no entry while the doubt stands (`maven_bazel_not_pinned` / `maven_bazel_unreadable` below). With no package at all a person reads `No packages found (see the warning).`. Exit code and `status` unchanged. A hosted `get` by advisory, which keeps the releases the project has by the same supplement, gives it too when the advisory has a patch of a Maven artifact. Only in a workspace that has to do with the ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, a `maven_install.json` lies at the Bazel root, or `MODULE.bazel` holds the block of hosted mode (an entry of the block is then not taken out as stale while the doubt stands, and `list` and `vex` say of it that it could not be told whether a hub takes its jar). In another Bazel workspace a file that cannot be read gives no such warning, and the run is the one without the workspace. That holds where the file is there and was not read as a whole too, for which `maven_bazel_unreadable` is given per patch: this warning would come with every hosted scan there, whatever the project holds. A hub that only such a file declares is then not scanned, and the scan does not say so. | +| `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. **Vendored mode** (`vendor`, and `scan` / `get --mode vendored`; additive) gives the same codes, but for `maven_bazel_download`, with the same detail, for a jar whose entry it does not write. In a project with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the event is `failed` with the code as its `errorCode` and the detail, without the purl in front, as its `error`, nothing is written and the run exits 1, as for any vendored refusal (before, such a project failed with `vendor_jvm_shape_unsupported`, which a jar that no hub builds still does). Beside such a build that was vendored, the code is a run-level `warnings[]` entry (human: `Warning: …`), the event is `applied` and the exit code is unchanged. With none of these codes vendored mode commits the patched jar under `.socket/vendor/maven//` (`REPO.bazel`, `file/BUILD.bazel`, `file/-.jar`, `.gitignore`), writes the entry that names that directory into the block, in the place of a hosted entry for the same jar, adds the directory's line to `.bazelignore`, and records the patch in the vendor ledger (in a project with no other JVM build: `ecosystem` `maven`, `flavor` `bazel`, the committed jar as `artifact`, no `wiring`); the event is `applied`. `vendor --check` then also fails (`vendor_check_failed`) when that jar is not, byte for byte, the vendored jar the ledger records (beside a Maven or Gradle build the hub's jar is a copy of it), when `REPO.bazel` / `file/BUILD.bazel` is not the file that was written, when the block no longer names the directory or was changed by hand, and when no pinned hub takes the jar at that version any more (the reason names `socket-patch rollback `) or an rc file switches the entry off. `vendor --revert` / `rollback` / `remove` take the entry, the directory and the line out, and a hosted run that puts its entry in the place of the vendored one removes the directory and the line. See docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_not_pinned` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). As `maven_bazel_not_at_root`: a hub of the workspace has no `lock_file` (also one that only `maven.artifact` or `maven.from_toml` tags make), so Bazel resolves its jars when it builds and none can be replaced. Also given beside a pinned hub that holds the artifact. The detail names the hub's file and line and how to pin it. | +| `maven_bazel_release` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). As `maven_bazel_not_at_root`: the Bazel release is not known to be 7.4.0 or later, the first with `override_repo` (`.bazeliskrc` or `.bazelversion` names an older one, or neither names a release of three numbers and `MODULE.bazel.lock` is missing or of a format before the one Bazel 7.5.0 writes), or the rules_jvm_external release Bazel selected is not known to be one of 6.4 to 7.2 (`MODULE.bazel.lock` holds the `source.json` of no release of it or of more than one, of a release outside that range, of an older one than the `bazel_dep` of `MODULE.bazel` asks for, or of another one than a `single_version_override` there pins; or an `archive_override`, `git_override`, `local_path_override` or `multiple_version_override` of the ruleset, or a `single_version_override` whose version is no plain string, leaves the release unknown). Versions are compared as Bazel compares them. The detail names the remedy (a `.bazelversion`, one build so that Bazel writes its lock, or an update of socket-patch) or the line of the override. | +| `maven_bazel_artifact` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). As `maven_bazel_not_at_root`: the repository through which the hub fetches this jar has no known name (a character other than letters, digits, `.`, `_` and `-` in its group, artifact or version), the lock lists no repository for the jar (`m2local`), or the patch comes without the version it is served under or without a sha256. | +| `maven_bazel_no_effect` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). As `maven_bazel_not_at_root`: the build would pass on the upstream jar with the block in place. The root has a `maven.override` for the artifact, or an rc file of the checkout (`.bazelrc` and what it imports with `import`, `try-import` and `try-import-if-bazel-version`, by a path under `%workspace%/` or a relative one; each read as Bazel reads an rc file: lines joined at a `\` before a line break, comments from a `#`, words without their quotes and escapes) names `--ignore_dev_dependency` without switching it off, or names `enable_bzlmod` other than switched on (Bazel reads `false`, `0`, `no`, `f`, `n` in any case and a `no` before the name as off) while the checkout names no Bazel 9 or later. The detail names the file and the line. | +| `maven_bazel_download` | `warnings[]` (warning; human: `Warning: …`) | **Experimental** (Bazel workspaces). As `maven_bazel_not_at_root`, in hosted mode only (a vendored jar is in the checkout): an rc file of the checkout names a downloader config, `--repository_disable_download` or `--vendor_dir`, under which Bazel may not be able to download the patched jar from the Socket patch host. The detail names the file, the line and the option. | | `vendor_*` / `pypi_*` / `gemfile_*` / `lock_*` / `locked_version_mismatch` / `user_authored_*` / `native_extensions_unsupported` / `platform_gem_unsupported` | `failed`/`skipped` | vendor: per-ecosystem refusal + drift vocabulary; see the Vendor command contract section. New tags are additive (MINOR). | `user_patch_conflict` is a `skipped` event and a scan/apply run warning for packages @@ -3339,7 +3348,8 @@ detail names the entry and the declarations. Like the other unattested references, re-vendoring cannot clear it, so it is not drift. The check never starts an API client or writes lock/recovery files. `--check` conflicts with `--revert`. -One file that the ledger's inventory of a directory artifact does not list is not drift: +One file that the ledger's inventory of a directory artifact does not list is not drift +(**Experimental**, Bazel workspaces, as is the `.bazelignore` line below): the `BUILD.bazel` that rules_rust's cargo-bazel (0.59.0 and newer) writes into a Cargo copy each time Bazel evaluates a crate hub that takes the crate from that path. It is left out of the comparison when it is a regular file of that name in the copy's own @@ -4178,7 +4188,7 @@ match it, withholds the statement: | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | -| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (no build has shown what rules_ruby does with one), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | +| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | **Experimental** (Bazel workspaces). In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (no build has shown what rules_ruby does with one), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index f0a5b1c86..4d255c855 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -7885,8 +7885,12 @@ mod scope_and_hint_tests { /// where it can: that file is no file of the pin it restores. A pin /// of that entry alone is ejected only where the hub is the project's /// one build, and is none of the pins of a project that Maven builds. + /// Whether a hub is a build is read with `SOCKET_NO_BAZEL` from the + /// environment, so the test holds it unset. #[test] + #[serial_test::serial] fn a_takeover_leaves_the_entry_of_a_bazel_hub() { + let _unset = crate::test_env::EnvGuard::unset(socket_patch_core::bazel::OFF_ENV); let pin = |purl: &str, files: &[&str]| HostedPin { purl: purl.to_string(), uuid: "1d3c1fd2-7b4e-4c1a-9f0e-2a3b4c5d6e7f".to_string(), diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 2505e0cfd..bba765d89 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -4033,8 +4033,12 @@ mod bazel_tests { /// project's, changes nothing. Nor does a run with `--vex-no-bazel`, /// whose document is about the installed tree: the step returns before /// it asks about a package, and every set it was given is as it was. + /// The lookup of the workspace reads `SOCKET_NO_BAZEL` from the + /// environment, so the test holds it unset. #[tokio::test] + #[serial_test::serial] async fn the_bazel_step_finds_what_no_hub_builds_in_a_project_run_only() { + let _unset = crate::test_env::EnvGuard::unset(socket_patch_core::bazel::OFF_ENV); let tmp = tempfile::tempdir().unwrap(); let root = std::fs::canonicalize(tmp.path()).unwrap(); let module = "module(name = \"shop\")\n\ diff --git a/crates/socket-patch-cli/src/lib.rs b/crates/socket-patch-cli/src/lib.rs index cde8f4cd7..3439248a1 100644 --- a/crates/socket-patch-cli/src/lib.rs +++ b/crates/socket-patch-cli/src/lib.rs @@ -74,6 +74,12 @@ pub use socket_patch_core::hosted::memory as hosted_memory; pub mod json_envelope; pub mod path_scope; pub(crate) mod telemetry_outcomes; +/// The core unit tests' env guard, compiled into this crate's unit tests +/// too: a test that judges by a variable holds it through the guard. +#[cfg(test)] +#[allow(dead_code)] +#[path = "../../socket-patch-core/src/test_env.rs"] +pub(crate) mod test_env; pub mod ui; pub mod update_notifier; diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs index d77fb6975..a8f49e0a5 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -172,10 +172,12 @@ //! the same. //! - Bazel would read that file as a package of the user's workspace. The //! crate has a dependency ([`DEP`]), so the file names a repository of -//! the hub, which the main repository does not see, and the commands -//! that analyse every target fail on it: `bazel cquery //...` and -//! `bazel query 'deps(//...)'` ([`analyses`]). The line that the scan -//! wrote into `.bazelignore` keeps the copies out of Bazel's packages: +//! the hub, which the main repository does not see, as it does not see +//! `platforms`, which the file names too. The commands that analyse +//! every target fail on the first of the two that Bazel meets: +//! `bazel cquery //...` and `bazel query 'deps(//...)'` ([`analyses`]). +//! The line that the scan wrote into `.bazelignore` keeps the copies out +//! of Bazel's packages: //! `//...` is the user's own target ([`every_target`]), both commands //! pass, and the build is the patched one, because the hub reads the //! copy by its path, not as a package. A user who comments the line out @@ -872,15 +874,42 @@ fn every_target(cell: &Cell) -> Vec { targets } +/// Whether `stderr` says that the main repository does not see a +/// repository that the build file in the copy names: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. The same words about another repository's view +/// are another failure. +fn unseen(stderr: &str) -> bool { + (stderr.split("No repository visible as '@").skip(1)) + .filter_map(|rest| rest.split_once("' from main repository")) + .any(|(repo, _)| { + !repo.contains('\'') && (repo == "platforms" || repo.starts_with("crates__")) + }) +} + +/// [`unseen`] takes the two messages Bazel was seen to print, and neither +/// another repository's name nor another repository's view. +#[test] +fn an_unseen_repository_is_one_the_copy_names_and_the_main_repository_misses() { + let said = |repo: &str, from: &str| { + format!("ERROR: no such package: No repository visible as '@{repo}' from {from}\n") + }; + assert!(unseen(&said("platforms", "main repository"))); + assert!(unseen(&said("crates__dep-1.0.0", "main repository"))); + assert!(!unseen(&said("rules_cc", "main repository"))); + assert!(!unseen(&said("platforms", "repository '@@rules_rust+'"))); + assert!(!unseen("Loading: 0 packages loaded\n")); +} + /// Whether the commands that analyse every target of the checkout of /// `cell` pass: `bazel cquery //...` and `bazel query 'deps(//...)'`, which -/// agree. One that fails has met a repository of the hub, which the main -/// repository does not see. +/// agree. One that fails has met a repository that the build file in the +/// copy names and the main repository does not see ([`unseen`]). fn analyses(cell: &Cell) -> bool { let runs = [("cquery", "//..."), ("query", "deps(//...)")]; let runs = runs.map(|(command, targets)| cell.bazel(command, &[targets])); for run in &runs { - let unseen = run.stderr().contains("No repository visible as '@crates__"); + let unseen = unseen(&run.stderr()); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); @@ -1194,8 +1223,9 @@ fn vendored_from_cargo_with_config() { // package: `//...` is the consumer alone, and the commands that analyse // every target pass. A user who comments the line out has the package // back, where the ruleset writes the build file: `//...` names targets - // there, those commands fail on the repository of the dependency, and - // the file Bazel now reads is a change of the copy again. + // there, those commands fail on a repository that the file names and + // the main repository does not see, and the file Bazel now reads is a + // change of the copy again. assert_eq!(every_target(&cell), [CONSUMER], "{test}"); assert!(analyses(&cell), "{test}: under the line of the scan"); cell.write(".bazelignore", DECLINED); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs index 627d2ae0b..62a3ffb9e 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs @@ -1564,6 +1564,84 @@ fn vendored_mode_goes_on_outside_bazel_and_on_the_users_word() { reverts(ALLOW); } +/// Without a Bazel: a project that a release before the refusal vendored, +/// in a checkout with a Bazel workspace file that no Bazel builds it from. +/// Its lock names the copy of the patch of then, so the project uses +/// vendored mode already and is not declined: the scan in vendored mode +/// vendors a newer patch of the package in the place of the older one, and +/// the scan that names no mode, which such a pipeline runs, then finds the +/// project in sync. +#[test] +fn a_project_vendored_by_an_earlier_release_is_not_declined_a_newer_patch() { + let (flow, newer) = checkout(&[]); + let (cell, upstream) = (&flow.cell, &flow.upstream); + let older = Patched::new(); + let then = registry(upstream); + grant(&then, upstream, &older, &older.package); + let earlier = socket_patch(cell, &then, API, &VENDORED); + assert_eq!(earlier.code, 0, "{}", earlier.dump); + cell.write("MODULE.bazel", ""); + let named = |tree: &Tree| -> Value { + let lock: Value = serde_json::from_slice(&tree[&lock_of(API)]).expect("a lock"); + lock["packages"][0]["dist"]["url"].clone() + }; + assert_eq!(named(&cell.tree()), copy_of(&older).as_str()); + + let scan = socket_patch(cell, &flow.standin, API, &VENDORED); + let said = &scan.dump; + assert_eq!(scan.code, 0, "{said}"); + assert_eq!(scan.envelope["status"], "success", "{said}"); + let update = json!([{ "purl": PURL, "oldUuid": older.uuid, "newUuid": newer.uuid }]); + assert_eq!(scan.envelope["updates"], update, "{said}"); + let vendored = cell.tree(); + assert_eq!(named(&vendored), copy_of(&newer).as_str(), "{said}"); + let source = |patch: &Patched| vendored.get(&format!("{API}/{}/{FILE}", copy_of(patch))); + let patched = newer.package.source.as_bytes(); + assert_eq!(source(&newer).map(Vec::as_slice), Some(patched), "{said}"); + assert_eq!(source(&older), None, "{said}"); + + let again = socket_patch(cell, &flow.standin, API, &["scan", "--yes"]); + assert_eq!(again.code, 0, "{}", again.dump); + assert_eq!(again.envelope["status"], "success", "{}", again.dump); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{}", again.dump); +} + +/// Without a Bazel: a regular file named `workspace`, in lower case, at +/// the root of a checkout that has no Bazel file. On a disk that folds +/// case it is what a lookup of `WORKSPACE` finds, and vendored mode +/// declines the project; on a disk that does not, the project is vendored. +/// The test asks the disk which of the two it runs on and says so. +#[test] +fn a_file_named_workspace_in_lower_case_declines_where_the_disk_folds_case() { + let (flow, patch) = checkout(&["workspace"]); + let before = flow.cell.tree(); + let folds = flow.cell.path("WORKSPACE").is_file(); + if folds { + declines(&flow, API, &VENDORED, 1, "failed", &before); + } else { + vendors(&flow, API, &patch, &before, &[]); + } + let ran = ["does not fold case: vendored", "folds case: declined"][usize::from(folds)]; + println!("a file named `workspace`: the disk {ran}"); +} + +/// Without a Bazel: with `SOCKET_NO_BAZEL=1` vendored mode is not declined +/// in a Bazel workspace. The scan vendors the package as it does in the +/// same checkout without the workspace file, to the byte. +#[test] +fn the_switch_makes_vendored_mode_the_one_of_a_checkout_without_bazel() { + let (flow, _patch) = checkout(&["MODULE.bazel"]); + let origin = flow.standin.origin(); + let packagist = format!("{origin}/{PACKAGIST}"); + let env = [ + ("SOCKET_PATCH_SERVER_URL", origin.as_str()), + ("SOCKET_PACKAGIST_URL", packagist.as_str()), + ]; + let args = [&VENDORED[..], &["--cwd", API]].concat(); + let declined = (flow.cell).off_is_without_bazel(&origin, &args, &env, &["MODULE.bazel"]); + assert_eq!(declined[0]["code"], 1, "{declined:#}"); +} + /// Without a Bazel, a PHP or a Composer: the fixture's directories and the /// legs of its workflow are those of its table. The fixture commits no /// lock, no `vendor/` tree and no root `BUILD.bazel`: the run makes them. diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs index 5901b009f..8983c97d9 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs @@ -1115,6 +1115,32 @@ fn a_project_in_no_bazel_workspace_gets_no_bazelignore() { } } +/// Without a Bazel: with `SOCKET_NO_BAZEL=1` a run that keeps a copy of a +/// Go module in a Bazel workspace writes no `.bazelignore` and says +/// nothing of one: it is the run of the same checkout without its +/// `MODULE.bazel`, to the byte, in vendored and in agent mode. What an +/// earlier run wrote is still undone with the variable set: the revert of +/// a copy takes its pair, and the file that was made for it, away. +#[test] +fn the_switch_adds_no_bazelignore_line_and_still_takes_one_away() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + let modcache = with.modcache.path().to_str().expect("a UTF-8 path"); + let (origin, env) = (with.standin.origin(), [("GOMODCACHE", modcache)]); + let before = cell.tree(); + for mode in [Kept::Vendored, Kept::Agent] { + let beside = cell.off_is_without_bazel(&origin, &mode.scan(), &env, &["MODULE.bazel"]); + let ignored = beside[0]["files"][".bazelignore"].as_str(); + assert_eq!(ignored, Some(mode.ignored("").as_str()), "{beside:#}"); + } + + with.run(&cell, &Kept::Vendored.scan()); + assert!(cell.tree().contains_key(".bazelignore")); + let off = [env[0], ("SOCKET_NO_BAZEL", "1")]; + let undo = cell.socket_patch(&origin, &["vendor", "--revert", "--yes"], &off); + assert_eq!(undo.code, 0, "{}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); +} + /// Without a Bazel: a project that is in no git checkout looks no further /// than its own directory. Below a Bazel root it is patched as anywhere /// else, and gets no line and no warning: nothing above it is read, not diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index dea1f4b94..24fe97f28 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -1234,6 +1234,140 @@ impl Cell { json!([run(&["--json"]), run(&[])]) } + /// What of the workspace copy its regular files ([`Cell::tree`]) do not + /// make anew, each by its path from the copy: a link, a directory that + /// holds nothing, a file with a permission bit to run it, and whatever + /// is neither a file nor a directory. + fn not_made_by_its_files(&self) -> Vec { + use std::os::unix::fs::PermissionsExt; + fn walk(dir: &Path, odd: &mut Vec) { + let entries = std::fs::read_dir(dir).expect("a directory of the copy"); + let entries: Vec<_> = entries.flatten().map(|entry| entry.path()).collect(); + if entries.is_empty() { + odd.push(dir.to_path_buf()); + } + for path in entries { + let meta = std::fs::symlink_metadata(&path).expect("an entry of the copy"); + if meta.is_dir() { + walk(&path, odd); + } else if !meta.is_file() || meta.permissions().mode() & 0o111 != 0 { + odd.push(path); + } + } + } + let (base, mut odd) = (&self.scratch.workspace, Vec::new()); + walk(base, &mut odd); + odd.retain(|path| path != base); + let shown = |path: &PathBuf| match path.strip_prefix(base) { + Ok(from) => from.display().to_string(), + Err(_) => path.display().to_string(), + }; + let mut odd: Vec = odd.iter().map(shown).collect(); + odd.sort(); + odd + } + + /// The workspace copy with the files `files` and nothing else: every + /// file as a new one, with the permission bits of any new file, and no + /// directory but those the files are in. + fn remake(&self, files: &Tree) { + let entries = std::fs::read_dir(&self.scratch.workspace).expect("the workspace copy"); + for entry in entries.flatten() { + let path = entry.path(); + let gone = match entry.file_type().is_ok_and(|kind| kind.is_dir()) { + true => std::fs::remove_dir_all(&path), + false => std::fs::remove_file(&path), + }; + gone.unwrap_or_else(|e| panic!("remove {}: {e}", path.display())); + } + for (rel, bytes) in files { + self.write(rel, bytes); + } + } + + /// `SOCKET_NO_BAZEL=1` makes `socket-patch ` in this checkout the + /// run of the same checkout without its Bazel files `bazel`, to a + /// script (`--json`) and to a person: the exit code, both streams byte + /// for byte, and every file the run left but those ([`undated`]). Each + /// run starts in the checkout as it is now, made anew from its regular + /// files, and the checkout is left so. A checkout that those files do + /// not make anew is refused, with what it holds beside them + /// ([`Cell::not_made_by_its_files`]): a link, an empty directory or an + /// executable file would be gone from the second run on, and the runs + /// would not start alike. The run without the Bazel files passes. + /// Without the variable the same command gives something else in the + /// workspace, which is what this gives: the comparison is of a run that + /// the workspace changes. + pub fn off_is_without_bazel( + &self, + api: &str, + args: &[&str], + env: &[(&str, &str)], + bazel: &[&str], + ) -> Value { + self.without_and_beside(api, args, env, bazel).1 + } + + /// [`Cell::off_is_without_bazel`], with what the run without the Bazel + /// files gave before what the run beside them gave: for a test that + /// also holds what the run with the variable did, which is the first. + pub fn without_and_beside( + &self, + api: &str, + args: &[&str], + env: &[(&str, &str)], + bazel: &[&str], + ) -> (Value, Value) { + let odd = self.not_made_by_its_files(); + assert_eq!( + odd, + Vec::::new(), + "{}: the regular files of this checkout do not make it anew", + self.test + ); + let files = self.tree(); + let mut plain = files.clone(); + plain.retain(|rel, _| !bazel.contains(&rel.as_str())); + let gives = |start: &Tree, env: &[(&str, &str)]| { + let run = |form: &[&str]| { + self.remake(start); + let mut cmd = self.socket_patch_command(api, &[args, form].concat(), env); + let out = cmd.output().expect("spawn socket-patch"); + let text = |bytes: Vec| String::from_utf8_lossy(&bytes).into_owned(); + let mut left = undated(&self.tree()); + left.retain(|rel, _| !bazel.contains(&rel.as_str())); + let left: BTreeMap = left + .into_iter() + .map(|(rel, bytes)| (rel, text(bytes))) + .collect(); + json!({ + "code": out.status.code(), + "stdout": text(out.stdout), + "stderr": text(out.stderr), + "files": left, + }) + }; + json!([run(&["--json"]), run(&[])]) + }; + let off = [env, &[("SOCKET_NO_BAZEL", "1")]].concat(); + let without = gives(&plain, env); + let (switched, beside) = (gives(&files, &off), gives(&files, env)); + self.remake(&files); + let test = &self.test; + let codes = [&without[0]["code"], &without[1]["code"]]; + assert_eq!( + codes, + [&json!(0), &json!(0)], + "{test}: {args:?}: {without:#}" + ); + assert_eq!(switched, without, "{test}: {args:?} with SOCKET_NO_BAZEL=1"); + assert_ne!( + beside, without, + "{test}: {args:?} is no other run in the workspace" + ); + (without, beside) + } + /// Where a flow has `socket-patch` write the VEX document `name`: /// beside the workspace copy, so it is no file of the checkout, and no /// comparison of the checkout's files sees it. @@ -1612,6 +1746,51 @@ fn a_downloader_config_is_named_by_the_option_of_the_release() { } } +/// Without a Bazel: the comparison of a run with the switch +/// ([`Cell::off_is_without_bazel`]) makes the checkout anew from its +/// regular files before each run, so it refuses a checkout that holds +/// what those files do not carry. A link, an empty directory and an +/// executable file are each named, and no run is started. +#[test] +fn a_checkout_its_files_do_not_make_anew_is_refused() { + use std::os::unix::fs::PermissionsExt; + let cell = cell_without_bazel("9.3.2"); + cell.write("MODULE.bazel", ""); + cell.write("dir/file", "x"); + assert_eq!(cell.not_made_by_its_files(), NOTHING); + std::os::unix::fs::symlink("file", cell.path("dir/link")).expect("a link"); + std::fs::create_dir(cell.path("empty")).expect("a directory"); + cell.write("run.sh", "#!/bin/sh\n"); + let runs = std::fs::Permissions::from_mode(0o755); + std::fs::set_permissions(cell.path("run.sh"), runs).expect("the permission bits"); + let odd = ["dir/link", "empty", "run.sh"]; + assert_eq!(cell.not_made_by_its_files(), odd); + let compare = || cell.off_is_without_bazel("http://127.0.0.1:9", &["list"], &[], &[]); + let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(compare)); + assert!(refused.is_err(), "it ran in a checkout it cannot make anew"); + // Nothing was made anew: the three are where they were. + assert_eq!(cell.not_made_by_its_files(), odd); + // Each one alone is enough. + for (keep, gone) in [(0, [1, 2]), (1, [0, 2]), (2, [0, 1])] { + let other = cell_without_bazel("9.3.2"); + other.write("dir/file", "x"); + std::os::unix::fs::symlink("file", other.path("dir/link")).expect("a link"); + std::fs::create_dir(other.path("empty")).expect("a directory"); + other.write("run.sh", "#!/bin/sh\n"); + let runs = std::fs::Permissions::from_mode(0o755); + std::fs::set_permissions(other.path("run.sh"), runs).expect("the permission bits"); + for at in gone { + let path = other.path(odd[at]); + let removed = match path.is_dir() && !path.is_symlink() { + true => std::fs::remove_dir(&path), + false => std::fs::remove_file(&path), + }; + removed.expect("remove it"); + } + assert_eq!(other.not_made_by_its_files(), [odd[keep]]); + } +} + /// Without a Bazel: a document is no file of the checkout it is about, nor /// of a checkout made from it, which has documents of its own. #[test] diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index 94c2855cc..bf203e88a 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -1509,7 +1509,8 @@ fn speaks_of_the_installed_tree(cell: &Cell, standin: &StandIn, patch: &Patched) /// of the same checkout without its `MODULE.bazel`, to a script and to a /// person: the exit code, both streams byte for byte, and what the document /// says. In that checkout, which is no Bazel workspace, the option changes -/// nothing and no run remarks on it. +/// nothing and no run remarks on it. `SOCKET_NO_BAZEL=1`, the switch for a +/// project that Bazel does not build, gives each form that same run. #[test] fn the_option_makes_the_run_the_one_of_a_checkout_without_bazel() { let (cell, standin, patch, entry) = checkout(""); @@ -1546,18 +1547,24 @@ fn the_option_makes_the_run_the_one_of_a_checkout_without_bazel() { let ran = socket_patch(&cell, &standin, &with_option); cell.wrote_in_run(&ran, &document, &claim); } - beside_the_hub.push([gives(&with_option, &env[..2]), gives(args, &env)]); + let switched_off = [env[0], env[1], ("SOCKET_NO_BAZEL", "1")]; + beside_the_hub.push([ + gives(&with_option, &env[..2]), + gives(args, &env), + gives(args, &switched_off), + ]); } let patched = cell.tree(); std::fs::remove_file(cell.path(MODULE)).expect(MODULE); - for ((args, option), [by_option, by_variable]) in forms.iter().zip(&beside_the_hub) { + for ((args, option), [by_option, by_variable, by_switch]) in forms.iter().zip(&beside_the_hub) { let without_bazel = gives(args, &env[..2]); assert_eq!(*by_option, without_bazel, "{args:?} {option}"); assert_eq!( *by_variable, without_bazel, "{args:?}, SOCKET_VEX_NO_BAZEL=1" ); + assert_eq!(*by_switch, without_bazel, "{args:?}, SOCKET_NO_BAZEL=1"); let outside = gives(&[&args[..], &[*option]].concat(), &env[..2]); assert_eq!(outside, without_bazel, "{args:?} {option}, no {MODULE}"); for run in without_bazel.as_array().into_iter().flatten() { @@ -2193,6 +2200,75 @@ fn a_lock_that_a_hub_reads_stays_on_the_trust_pin_where_a_registry_is_offered() assert!(!warned.contains("Bazel"), "{test}: {}", routed.dump); } +/// Without a Bazel: with `SOCKET_NO_BAZEL=1` the hosted scan of +/// [`a_lock_that_a_hub_reads_stays_on_the_trust_pin_where_a_registry_is_offered`] +/// is the scan of the same checkout without its `MODULE.bazel`, to the +/// byte in exit code, both streams and every file it leaves: the lock is +/// routed through the patch's registry, with the registry and the override +/// in `pnpm-workspace.yaml`, and no run says a word of Bazel. Without the +/// variable the scan keeps the lock on the trust pin and its warning names +/// the hub's call, as that test holds. +#[test] +fn the_switch_routes_a_lock_that_a_hub_reads_as_in_a_checkout_without_bazel() { + let (cell, standin, patch, _) = checkout_granted("", false, true); + let test = &cell.test; + std::fs::remove_dir_all(cell.path("node_modules")).expect("the tree"); + proves_pnpm_12(&cell); + let origin = standin.origin(); + let registry = format!("{origin}/{REGISTRY}"); + let env = [ + ("SOCKET_PATCH_SERVER_URL", origin.as_str()), + ("SOCKET_NPM_REGISTRY", registry.as_str()), + ]; + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let (without, beside) = cell.without_and_beside(&origin, &hosted, &env, &[MODULE]); + let file = |run: &Value, rel: &str| run["files"][rel].as_str().unwrap_or_default().to_string(); + + // The run with the variable is the first of these, to the byte: routed. + let name = format!("socket-{}", &patch.uuid[..8]); + let key = format!("'{NAME}@{name}:{VERSION}':"); + for run in without.as_array().expect("the two forms") { + let (lock, workspace) = (file(run, LOCK), file(run, "pnpm-workspace.yaml")); + assert!( + lock.contains(&key) && lock.contains("\noverrides:"), + "{test}: {lock}" + ); + assert!( + workspace.contains("namedRegistries:") + && workspace.contains(&name) + && !workspace.contains("trustLockfile"), + "{test}: {workspace}" + ); + for stream in ["stdout", "stderr"] { + let said = run[stream].as_str().expect("a stream"); + assert!(!said.contains("Bazel"), "{test}: {stream}: {said}"); + } + } + + // Without the variable the hub decides: the trust pin, and the warning. + let entry = format!( + " '{NAME}@{VERSION}':\n resolution: {{integrity: {}, tarball: {origin}{}}}\n", + integrity(&patch.package.tarball), + patch.route + ); + for run in beside.as_array().expect("the two forms") { + let lock = file(run, LOCK); + assert!( + lock.contains(&entry) && !lock.contains("@socket-") && !lock.contains("\noverrides:"), + "{test}: {lock}" + ); + assert_eq!( + file(run, "pnpm-workspace.yaml"), + TRUSTING_WORKSPACE, + "{test}" + ); + } + let said = beside[0]["stdout"].as_str().expect("an envelope"); + let envelope: Value = serde_json::from_str(said).expect("an envelope"); + let warned = envelope["warnings"].to_string(); + assert!(warned.contains(HUB_READS_THE_LOCK), "{test}: {beside:#}"); +} + /// Without a Bazel: the two scans of [`hosted_update_pnpm_lock_on_pnpm_11`] /// and its undo, in a checkout with that hub, for the project at the root /// and for one in a directory of the workspace, whose hub names the lock diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index 6646f9707..6e0d20aac 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -779,6 +779,26 @@ fn a_gem_that_the_hub_holds_to_its_upstream_sha256_is_left_alone() { } } +/// Without a Bazel: with `SOCKET_NO_BAZEL=1` a hosted scan pins the gem +/// that the hub holds to its upstream sha256, as it does in the same +/// checkout without its `MODULE.bazel`, to the byte, and says nothing of +/// the call. Without the variable it leaves the gem alone there. +#[test] +fn the_switch_makes_a_hosted_scan_the_one_of_a_checkout_without_bazel() { + let served = Served::start(&mut cell_without_bazel("9.3.2")); + let sums = [&served.neighbour_gem, &served.upstream_gem].map(|gem| sha256_hex(gem)); + let held = module_pinning(&[(NEIGHBOUR, &sums[0]), (NAME, &sums[1])]); + let cell = checkout(&served, Some(&held)); + let origin = served.standin.origin(); + let rubygems = format!("{origin}/{RUBYGEMS}"); + let env = [("SOCKET_RUBYGEMS_URL", rubygems.as_str())]; + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let left_alone = cell.off_is_without_bazel(&origin, &hosted, &env, &["MODULE.bazel"]); + let said = left_alone[0]["stdout"].as_str().expect("an envelope"); + let envelope: serde_json::Value = serde_json::from_str(said).expect("an envelope"); + assert_eq!(codes_in(&envelope["warnings"]), [HELD], "{left_alone:#}"); +} + /// Without a Bazel: what else a call can say, each as the `MODULE.bazel` /// of the fixture's checkout. A lock without a `CHECKSUMS` section leaves /// the gem as it is too, and its warning does not offer to delete the gem diff --git a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs index 9d67f37b4..08244faea 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs @@ -264,6 +264,17 @@ impl Machine { /// Runs `socket-patch ` in the directory `proj` of the checkout. fn step_in(&self, proj: &std::path::Path, args: &[&str]) -> Ran { + self.step_with(proj, args, &[]) + } + + /// Runs `socket-patch ` in the checkout as it is, with the + /// switch for a project that Bazel does not build. + fn step_off(&self, args: &[&str]) -> Ran { + self.step_with(&self.root.join("proj"), args, &[("SOCKET_NO_BAZEL", "1")]) + } + + /// [`Machine::step_in`] with the variables `env` set as well. + fn step_with(&self, proj: &std::path::Path, args: &[&str], env: &[(&str, &str)]) -> Ran { let m2 = self.root.join("m2"); let before = self.files(); @@ -295,6 +306,7 @@ impl Machine { .env("MAVEN_REPO_LOCAL", &m2) .env("GRADLE_USER_HOME", home.join("gradle")) .env("COURSIER_CACHE", home.join("coursier")) + .envs(env.iter().copied()) .args(args) .args(["--org", ORG, "--api-token", "fake-token"]) .args(["--api-url", &self.api.uri()]); @@ -424,33 +436,31 @@ fn a_maven_project_no_hub_builds_reports_as_without_bazel() { !args.contains(&"--dry-run"), "{args:?}: {without:?}" ); - for bazel in [&other, &elsewhere] { + for bazel in [&other, &elsewhere, &unread_other()] { let beside = machine.run(bazel, true, args); assert_eq!(beside, without, "{args:?} beside {:?}", bazel[0].1); } } } -#[test] -fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { +/// Every command of [`COMMANDS`] in the checkout with the Bazel files +/// `bazel` is the command of the same checkout without them, with one +/// warning more: the code and the detail that `warning` gives for the +/// command's arguments. +fn adds_one_warning(bazel: &Files, warning: &dyn Fn(&[&str]) -> (&'static str, String)) { let machine = Machine::start(); - let [plain, _, _, hub] = checkouts(); + let [plain, ..] = checkouts(); for args in COMMANDS { let (without, beside) = ( machine.run(&plain, true, args), - machine.run(&hub, true, args), + machine.run(bazel, true, args), ); assert_eq!( (beside.code, &beside.wrote), (without.code, &without.wrote), "{args:?}: {beside:?}" ); - // An agent run patches no hub. A hosted run would, and says why it - // does not here: nothing in this checkout names its Bazel. - let (code, detail) = match args[0] { - "get" => ("maven_bazel_release", declined(NO_RELEASE)), - _ => ("maven_bazel_hub_unpatched", HUB_WARNING.to_string()), - }; + let (code, detail) = warning(args); if args.contains(&"--json") { let (mut said, mut expected) = (beside.envelope(), without.envelope()); let warning = json!({ "code": code, "detail": detail }); @@ -485,6 +495,148 @@ fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { } } +#[test] +fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { + let [.., hub] = checkouts(); + // An agent run patches no hub. A hosted run would, and says why it + // does not here: nothing in this checkout names its Bazel. + adds_one_warning(&hub, &|args| match args[0] { + "get" => ("maven_bazel_release", declined(NO_RELEASE)), + _ => ("maven_bazel_hub_unpatched", HUB_WARNING.to_string()), + }); +} + +/// A workspace where a hub may be, with something its reader could not +/// have and no hub that holds the artifact: each command says that it +/// could not tell whether a hub builds the jar, and does what it does +/// without Bazel. One such workspace names the ruleset of a Maven hub and +/// includes a file that does not exist. The others name only another +/// ruleset's and leave a file unread that is there, and may be the one +/// that names it: one includes a file that cannot be parsed, and one has +/// an `include` the reader does not follow (Bazel 9 takes +/// `dev_dependency` there), with the hub of the artifact and all that +/// names the ruleset in the file it would read. With an include that does +/// not exist, that other workspace says nothing +/// ([`a_maven_project_no_hub_builds_reports_as_without_bazel`]). +#[test] +fn a_workspace_that_may_hold_a_hub_and_is_not_read_adds_one_warning() { + let named = "bazel_dep(name = \"rules_jvm_external\", version = \"7.2\")\n\ + include(\"//:more.MODULE.bazel\")\n"; + let named = vec![("MODULE.bazel", named.to_string())]; + let mut open = unread_other(); + open.push(("more.MODULE.bazel", "maven.install(\n".to_string())); + let dev = "include(\"//java:deps.MODULE.bazel\", dev_dependency = True)\n"; + let hub = HUB.replace("//:maven_install", "//java:maven_install"); + let dev = vec![ + ("MODULE.bazel", format!("{OTHER_HUB}{dev}")), + ("java/deps.MODULE.bazel", hub), + ( + "java/maven_install.json", + lock(&[("consumer", "2.0"), ("victim", "1.10.0")]), + ), + ]; + let included = |why: &str| format!("more.MODULE.bazel{why} includes it"); + let rows = [ + (named, included(": it does not exist; MODULE.bazel:2")), + ( + open, + included(":1: a bracket is never closed; MODULE.bazel:6"), + ), + ( + dev, + "MODULE.bazel:6: this `include` cannot be read".to_string(), + ), + ]; + for (bazel, why) in rows { + let unread = format!( + "socket-patch could not tell whether Bazel takes this artifact from a \ + rules_jvm_external hub: {why}" + ); + adds_one_warning(&bazel, &|args| match args[0] { + "get" => ("maven_bazel_unreadable", declined(&unread)), + _ => ("maven_bazel_unreadable", format!("{PURL}: {unread}")), + }); + } +} + +/// `SOCKET_NO_BAZEL=1`, the switch for a project that Bazel does not +/// build: beside a pinned hub that builds the artifact, every command is +/// the command of the checkout without its Bazel files, to the byte. An +/// agent run gives no notice of the hub, a hosted run writes no block and +/// says nothing of one, and a hosted scan takes no jar of the hub for a +/// package. Without the variable each of them does. +#[test] +fn the_switch_makes_a_run_beside_a_hub_the_run_without_bazel() { + let machine = Machine::start(); + let [plain, ..] = checkouts(); + let rows = COMMANDS.map(|args| (true, args)); + for (maven, args) in rows.into_iter().chain([(false, &SCAN[..])]) { + let without = machine.run(&plain, maven, args); + machine.make(&pinned(), maven, true); + assert_eq!(machine.step_off(args), without, "{args:?}"); + assert_ne!(machine.run(&pinned(), maven, args), without, "{args:?}"); + } +} + +/// The words that set the switch are those of every switch that is read +/// from the environment alone: `1`, `true`, `yes`, `on`, `y` and `t`, in +/// any case and with blanks around them. No other value sets it, an empty +/// one included: the run is then the run without the variable, to the +/// byte. +#[test] +fn the_switch_takes_the_words_of_the_other_switches_and_no_other() { + let machine = Machine::start(); + let [plain, ..] = checkouts(); + let args = COMMANDS[0]; + let without = machine.run(&plain, true, args); + let beside = machine.run(&pinned(), true, args); + assert_ne!(beside, without); + let values = [ + ("true", &without), + ("TRUE", &without), + (" Yes ", &without), + ("on", &without), + ("y", &without), + ("T", &without), + ("", &beside), + ("0", &beside), + ("false", &beside), + ("off", &beside), + ("2", &beside), + ("n", &beside), + ("f", &beside), + ("yes!", &beside), + ]; + for (value, expected) in values { + machine.make(&pinned(), true, true); + let proj = machine.root.join("proj"); + let ran = machine.step_with(&proj, args, &[("SOCKET_NO_BAZEL", value)]); + assert_eq!(&ran, expected, "SOCKET_NO_BAZEL={value:?}"); + } +} + +/// What an earlier run wrote for a hub is listed and undone with the +/// switch set: `list` reads the entry of the block as a hosted pin, and +/// `rollback` and `remove` take the block out, to the byte. +#[test] +fn the_switch_leaves_the_block_of_an_earlier_run_listed_and_undone() { + let machine = Machine::start(); + let undos: [&[&str]; 2] = [ + &["rollback", "--yes", "--json"], + &["remove", PURL, "--yes", "--json"], + ]; + for undo in undos { + machine.make(&pinned(), false, false); + assert_eq!(machine.step(COMMANDS[0]).wrote.len(), 1); + let list = machine.step_off(&["list", "--json"]).envelope(); + let pinned_in = &event_for(&list, PURL)["details"]["lockfiles"]; + assert_eq!(*pinned_in, json!(["MODULE.bazel"]), "{list:#}"); + let undone = machine.step_off(undo); + let restored = String::from_utf8_lossy(&undone.wrote[MODULE]); + assert_eq!((undone.code, &*restored), (Some(0), HUB), "{undone:?}"); + } +} + #[test] fn a_hub_only_tree_says_why_the_hub_is_not_patched() { let machine = Machine::start(); @@ -718,6 +870,54 @@ fn a_hosted_run_removes_the_jar_vendored_mode_kept_for_the_hub() { } } +/// With the switch, a hosted run leaves what vendored mode wrote for a hub +/// alone as it is, as the same run does in the checkout without its +/// workspace file: it has no build to pin the artifact in, so the patch +/// stays vendored, with its entry of the block, its directory and its +/// ledger entry. Without the variable the hosted entry takes the place of +/// the vendored one. +#[test] +fn the_switch_leaves_a_vendored_entry_of_the_hub_to_a_hosted_run() { + let machine = Machine::start(); + let proj = machine.root.join("proj"); + // The ledger entry of a patch that only the hub takes: its artifact is + // the jar of the hub's directory, three bytes here, with their sha256. + let jar = format!(".socket/vendor/maven/{UUID}/file/victim-1.10.0.jar"); + let sum = "0163f1eea7894350060624d315234d40c508ab251ba121714e234503045faadd"; + let ledger = json!({ "version": 1, "entries": { PURL: { + "ecosystem": "maven", + "basePurl": PURL, + "uuid": UUID, + "artifact": { "path": jar, "sha256": sum, "size": 3 }, + "wiring": [], + "flavor": "bazel", + } } }); + let make = || { + vendored(&machine, false); + let state = proj.join(".socket/vendor/state.json"); + std::fs::write(state, format!("{ledger:#}\n")).expect("the ledger"); + }; + for args in [COMMANDS[0], &SCAN[..]] { + make(); + std::fs::remove_file(proj.join("MODULE.bazel")).expect("the workspace file"); + let without = machine.step(args); + make(); + let held = machine.files(); + let off = machine.step_off(args); + assert_eq!(off, without, "{args:?}"); + assert_eq!(machine.files(), held, "{args:?}"); + let codes = warning_codes(&off.envelope()); + let kept = codes + .iter() + .any(|code| code == "redirect_takeover_kept_vendored"); + assert!(kept, "{args:?}: {off:?}"); + make(); + let beside = machine.step(args); + let module = String::from_utf8_lossy(&beside.wrote[MODULE]); + assert_eq!(module, format!("{HUB}\n{BLOCK}"), "{args:?}: {beside:?}"); + } +} + /// The Bazel files of a checkout, each with its text. type Files = Vec<(&'static str, String)>; diff --git a/crates/socket-patch-cli/tests/hosted_memory_bazel_off.rs b/crates/socket-patch-cli/tests/hosted_memory_bazel_off.rs new file mode 100644 index 000000000..effd947ea --- /dev/null +++ b/crates/socket-patch-cli/tests/hosted_memory_bazel_off.rs @@ -0,0 +1,261 @@ +//! `SOCKET_NO_BAZEL=1` and the in-memory hosted engine, which judges a +//! Bazel hub from the files handed to it and looks for no workspace on +//! disk: with the variable set, the engine pins what it pins for the same +//! files without their `MODULE.bazel`, and its path selection asks the +//! host for what it asks for the tree without its Bazel files. +//! +//! The engine reads the variable from the environment of its process, so +//! each test holds it through the guard, set or unset, before any server +//! starts, and the two run one after the other. The target is theirs +//! alone: no other test reads the environment beside them. + +use std::collections::BTreeMap; + +use serde_json::Value; +use wiremock::MockServer; + +#[path = "hosted_memory_common/mod.rs"] +mod common; + +use common::*; +use socket_patch_cli::hosted_memory::{select_paths, PathSelection, SelectOptions, TreeEntryInput}; + +/// The core unit tests' env guard, compiled into this test binary too. +#[allow(dead_code)] +#[path = "../../socket-patch-core/src/test_env.rs"] +mod test_env; +use test_env::EnvGuard; + +/// The switch for a project that Bazel does not build. +const OFF: &str = "SOCKET_NO_BAZEL"; + +/// The files of a tree, by path. +type Files = BTreeMap>; + +/// What the engine asks its host to stream of a tree with the files +/// `files`. +fn selection(files: &Files) -> PathSelection { + let blob = |(path, bytes): (&String, &Vec)| TreeEntryInput { + path: path.clone(), + mode: "100644".into(), + kind: "blob".into(), + size: Some(bytes.len() as u64), + }; + let entries: Vec = files.iter().map(blob).collect(); + select_paths(&entries, &SelectOptions::default()) +} + +/// What the engine gives for `files` against the patch API at `server`: +/// the files it changed and the `redirect` block of the root project. +async fn pins(server: &MockServer, files: &Files) -> (Files, Value) { + let mut opts = options(false); + opts.trust_lockfile_config = Some(true); + let output = run_engine(server, build_input(files, &[], opts)).await; + let project = &output.projects[0]; + assert!(project.error.is_none(), "{:?}", project.error); + (engine_changed(&output), sorted_redirect(&project.redirect)) +} + +/// Whether the pnpm lock among `changed` is routed through a named +/// registry: it keys a release by one (`name@socket-:version`). +fn routed(changed: &Files) -> bool { + let lock = changed.get("pnpm-lock.yaml"); + lock.is_some_and(|lock| String::from_utf8_lossy(lock).contains("@socket-")) +} + +/// Trees whose root has every file that the path selection takes for one +/// of a Bazel workspace, beside what makes it ask for them: a pnpm lock, a +/// `pnpm-workspace.yaml` whose only lock is a member's, and a gem lock. +/// Each as the tree without those files and the tree with them. +fn trees_with_bazel_files() -> Vec<(Files, Files)> { + let bazel = [ + "MODULE.bazel", + "WORKSPACE", + "WORKSPACE.bazel", + "WORKSPACE.bzlmod", + "tools/hubs.MODULE.bazel", + ]; + let own: [&[&str]; 3] = [ + &["pnpm-lock.yaml", "package.json"], + &[ + "pnpm-workspace.yaml", + "package.json", + "packages/a/package.json", + "packages/a/pnpm-lock.yaml", + ], + &["Gemfile", "Gemfile.lock"], + ]; + let tree = |names: &[&str]| -> Files { + let file = |name: &&str| (name.to_string(), b"x\n".to_vec()); + names.iter().map(file).collect() + }; + own.iter() + .map(|own| (tree(own), tree(&[*own, &bazel[..]].concat()))) + .collect() +} + +/// One project of the tests: what it is, the patch API that serves its +/// patch, its files without and with the `MODULE.bazel`, what the warnings +/// say beside the hub, and whether the patch service offers the patch's +/// registry (the directory its tarball is served from). +struct Project { + row: String, + server: MockServer, + plain: Files, + beside: Files, + said: &'static str, + offered: bool, +} + +/// A gem lock beside a rules_ruby hub that holds the gem to its upstream +/// sha256, a pnpm lock beside a rules_js hub that hides +/// `pnpm-workspace.yaml` from pnpm 11, and a pnpm lock that a rules_js hub +/// reads, in a project that proves pnpm 12 and is offered the patch's +/// registry. Each starts its patch API: a test holds the variable before +/// it asks for them. +async fn projects() -> Vec { + let ruby = format!( + "bazel_dep(name = \"rules_ruby\", version = \"1.0.0-rc2\")\n\ + ruby = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n\ + ruby.bundle_fetch(\n name = \"bundle\",\n gemfile = \"//:Gemfile\",\n \ + gemfile_lock = \"//:Gemfile.lock\",\n gem_checksums = {{\"rails-7.0.0\": \ + \"{}\"}},\n)\n", + "2".repeat(64) + ); + let js = "module(name = \"app\")\n\ + bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(\n name = \"npm\",\n \ + pnpm_lock = \"//:pnpm-lock.yaml\",\n update_pnpm_lock = True,\n)\n\ + pnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n\ + pnpm.pnpm(name = \"pnpm\", pnpm_version = \"11.28.10\")\n"; + // A hub that only reads the lock: its call is on line 4. + let reads = "module(name = \"app\")\n\ + bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(name = \"npm\", pnpm_lock = \"//:pnpm-lock.yaml\")\n"; + let own: [(&str, &[u8]); 2] = [ + ("pnpm-workspace.yaml", b"# own\npackages:\n - '.'\n"), + ("package.json", br#"{ "name": "root", "private": true }"#), + ]; + let pnpm_12: [(&str, &[u8]); 2] = [ + own[0], + ( + "package.json", + br#"{"name":"app","packageManager":"pnpm@12.22.0","dependencies":{"left-pad":"1.3.0"}}"#, + ), + ]; + // The fixture, the files added to it, its `MODULE.bazel`, what the + // warnings say beside the hub, and whether the registry is offered. + let rows = [ + ( + "redirect/gem/bundler/basic", + &own[..0], + ruby.as_str(), + "redirect_bazel_gem_checksums_pinned", + false, + ), + ( + "redirect/npm/pnpm/basic", + &own[..], + js, + "redirect_pnpm_bazel_workspace_hidden", + false, + ), + ( + "redirect/npm/pnpm/basic", + &pnpm_12[..], + reads, + "a Bazel hub reads the pnpm lock (MODULE.bazel:4)", + true, + ), + ]; + let mut projects = Vec::new(); + for (fixture, more, module, said, offered) in rows { + let dir = fixtures_root().join(fixture); + let server = MockServer::start().await; + let mut patches = patches_from_overrides(&dir.join("overrides.json"), Some(&server.uri())); + for patch in patches.iter_mut().filter(|_| offered) { + let url = patch.reference["url"].as_str().expect("a URL").to_string(); + let directory = &url[..=url.rfind('/').expect("the URL of a tarball")]; + patch.reference["npmRegistryUrl"] = directory.into(); + } + mount_api(&server, &patches).await; + let mut plain = fixture_files(&dir.join("input")); + for (rel, bytes) in more { + plain.insert(rel.to_string(), bytes.to_vec()); + } + let mut beside = plain.clone(); + beside.insert("MODULE.bazel".to_string(), module.as_bytes().to_vec()); + let row = format!("{fixture}, {said}"); + projects.push(Project { + row, + server, + plain, + beside, + said, + offered, + }); + } + projects +} + +/// Without the variable, whatever the shell of the test run exports: the +/// engine leaves the gem lock and the pnpm lock of the hub that hides +/// `pnpm-workspace.yaml` as they are and says why; the lock that a hub +/// only reads is pinned and not routed through the patch's registry, and +/// the engine says that the hub is why. Its selection asks for the +/// `MODULE.bazel` of each, and for every file of a Bazel workspace beside +/// a pnpm lock, a `pnpm-workspace.yaml` or a gem lock. +#[tokio::test] +#[serial_test::serial] +async fn a_hub_keeps_the_engine_from_pinning_or_routing() { + let _unset = EnvGuard::unset(OFF); + for project in projects().await { + let Project { row, said, .. } = &project; + let (changed, redirect) = pins(&project.server, &project.beside).await; + // Beside the hub nothing is pinned, or, where the hub only keeps + // the lock off the registry, the lock is pinned and not routed. + let pinned = changed.contains_key("pnpm-lock.yaml"); + assert_eq!(pinned, project.offered, "{row}: {}", describe(&changed)); + assert!(!routed(&changed), "{row}: {}", describe(&changed)); + assert_eq!(changed.is_empty(), !project.offered, "{row}"); + let warned = redirect["warnings"].to_string(); + assert!(warned.contains(said), "{row}: {redirect:#}"); + let asked = selection(&project.beside).fetch_text; + assert!(asked.iter().any(|path| path == "MODULE.bazel"), "{asked:?}"); + } + for (plain, beside) in &trees_with_bazel_files() { + let asked = selection(beside).fetch_text; + for file in beside.keys().filter(|file| !plain.contains_key(*file)) { + assert!(asked.contains(file), "{file}: {asked:?}"); + } + } +} + +/// With `SOCKET_NO_BAZEL=1` the engine pins each, and says, what it does +/// for the same files without the `MODULE.bazel`, so the third lock is +/// routed, and the selection is the one of the tree without its Bazel +/// files: no file is fetched, and counted against a session's limits, that +/// nothing judges. +#[tokio::test] +#[serial_test::serial] +async fn the_switch_makes_the_engine_pin_as_without_the_bazel_file() { + let _set = EnvGuard::set(OFF, "1"); + for project in projects().await { + let Project { row, server, .. } = &project; + let without = pins(server, &project.plain).await; + assert!(!without.0.is_empty(), "{row}: {:#}", without.1); + // The route is taken where it is offered: the offer is live, and + // the hub was what stood against it. + let offered = project.offered; + assert_eq!(routed(&without.0), offered, "{row}: {:#}", without.1); + assert!(!without.1.to_string().contains("Bazel"), "{row}"); + assert_eq!(pins(server, &project.beside).await, without, "{row}"); + let asked = selection(&project.beside); + assert_eq!(asked, selection(&project.plain), "{row}"); + } + for (plain, beside) in &trees_with_bazel_files() { + assert_eq!(selection(beside), selection(plain), "{:?}", plain.keys()); + } +} diff --git a/crates/socket-patch-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index ea168f952..c999d245a 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -15,6 +15,13 @@ mod common; use common::*; +/// The core unit tests' env guard, compiled into this test binary too: the +/// engine runs in this process, and reads `SOCKET_NO_BAZEL` from it. +#[allow(dead_code)] +#[path = "../../socket-patch-core/src/test_env.rs"] +mod test_env; +use test_env::EnvGuard; + struct Case { /// Fixture dir under `crates/socket-patch-core/tests/fixtures/redirect`. fixture: &'static str, @@ -304,9 +311,12 @@ async fn parity_gemfile_platform_prebuilds() { /// sha256 of the upstream archive there, the checkout and the engine write /// no file and say why in the same words. With the one of the patched /// archive both write what they write without Bazel. The engine is given -/// the files that path selection asks for. +/// the files that path selection asks for. It judges the hub unless +/// `SOCKET_NO_BAZEL` is set, so the test holds the variable unset. #[tokio::test] +#[serial_test::serial] async fn parity_gem_checksums_of_a_bazel_hub_through_selection() { + let _unset = EnvGuard::unset("SOCKET_NO_BAZEL"); let dir = fixtures_root().join("redirect/gem/bundler/basic"); let server = MockServer::start().await; let patches = patches_from_overrides(&dir.join("overrides.json"), Some(&server.uri())); @@ -1588,9 +1598,13 @@ async fn parity_pnpm_member_branch_lock_refusal() { /// engines refuse every pnpm pin with the same warning, nothing written. /// Path selection asks for the `MODULE.bazel` beside the lock. With a /// file of the user's own listed both engines pin the lock; with a listed -/// file that the undo of the pin would remove both pin nothing. +/// file that the undo of the pin would remove both pin nothing. The engine +/// judges the hub unless `SOCKET_NO_BAZEL` is set, so the test holds the +/// variable unset. #[tokio::test] +#[serial_test::serial] async fn parity_pnpm_bazel_hub_that_hides_the_workspace_file() { + let _unset = EnvGuard::unset("SOCKET_NO_BAZEL"); let lock = String::from_utf8(read_fixture("redirect/npm/pnpm/basic/input/pnpm-lock.yaml")).unwrap(); let module = |data: &str| { diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs index 9bb41cd63..1cd6b794e 100644 --- a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs +++ b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs @@ -2625,3 +2625,339 @@ fn vendor_declines_for_a_hub_it_cannot_patch() { let tmp = checkout("other"); assert_refused(tmp.path(), "no_build_file", "no pom.xml"); } + +/// What a run printed and how it ended: the exit code and both streams. +type Said = (Option, String, String); + +/// [`spawn`], with `SOCKET_NO_BAZEL=1` when `off` is set: the switch for a +/// project that Bazel does not build. The port of every loopback address +/// is taken out of what the run printed: the download fixture listens on +/// another one in every run. +fn said(root: &Path, args: &[&str], json: bool, off: bool) -> Said { + let (mut cmd, _fixture) = command(root, args, json); + if off { + cmd.env("SOCKET_NO_BAZEL", "1"); + } + let out = cmd.output().expect("run socket-patch"); + let portless = |bytes: &[u8]| { + let text = String::from_utf8_lossy(bytes); + let mut parts = text.split("127.0.0.1:"); + let mut said = parts.next().unwrap_or_default().to_string(); + for part in parts { + said.push_str("127.0.0.1:"); + said.push_str(part.trim_start_matches(|c: char| c.is_ascii_digit())); + } + said + }; + ( + out.status.code(), + portless(&out.stdout), + portless(&out.stderr), + ) +} + +/// Makes the checkout of [`pinned_hub`] anew under `root`, which every +/// checkout of a test shares so that no path differs between two runs: +/// beside the Maven build of the fixture, or with the hub `alone`. +fn remake(root: &Path, alone: bool) { + for dir in ["proj", "m2"] { + let _ = std::fs::remove_dir_all(root.join(dir)); + } + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + if alone { + only_bazel(root); + } + pinned_hub(root, "foo"); +} + +/// `SOCKET_NO_BAZEL=1`, the switch for a project that Bazel does not +/// build: `vendor` of a Maven patch whose jar a pinned hub builds is the +/// run of the same checkout without its `MODULE.bazel`, to the byte: the +/// exit code, both streams, as a program and as a person reads them, and +/// every file. In a checkout only Bazel builds that is the refusal of a +/// tree without a JVM build. Beside a Maven build it is the vendoring of +/// that build alone: nothing is written for the hub and nothing is said of +/// it, so a Bazel build that is there after all keeps the upstream jar. +/// Without the variable each run writes for the hub. +/// +/// The same over what an earlier run left in the block, which stays as it +/// is: the refusal says nothing of the hub's entry, a run that vendors for +/// a Maven build which came later names no file of the hub among those to +/// commit, and a hosted entry stays where it is: in a checkout only Bazel +/// builds it is none that the run ejects. +#[test] +fn the_switch_makes_a_vendored_run_the_run_without_the_workspace_file() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let module = root.join("proj/MODULE.bazel"); + // What a run said, the workspace file it left, and every other file. + let run = |args: &[&str], json: bool, off: bool| { + let said = said(root, args, json, off); + let mut tree = snapshot(root); + (said, tree.remove("MODULE.bazel").flatten(), tree) + }; + // In the checkout that `prepare` makes: the run without the workspace + // file, which the run with the switch equals and leaves its own + // workspace file as it was, and the run without the variable, which + // is another one. + let three = |prepare: &dyn Fn(), args: &[&str], json: bool| { + prepare(); + std::fs::remove_file(&module).unwrap(); + let without = run(args, json, false); + prepare(); + let held = std::fs::read(&module).unwrap(); + let off = run(args, json, true); + assert_eq!((&off.0, &off.2), (&without.0, &without.2), "{args:?}"); + assert_eq!(off.1.as_ref(), Some(&held), "{args:?}: {off:?}"); + prepare(); + let beside = run(args, json, false); + assert_ne!(beside, off, "{args:?}"); + (without.0, beside) + }; + let unit = format!("{FOO_UNIT}/file/foo-1.0.jar"); + for (alone, json) in [(true, true), (true, false), (false, true), (false, false)] { + let (without, beside) = three(&|| remake(root, alone), &["vendor"], json); + assert_eq!(without.0, Some(i32::from(alone)), "{alone}: {without:?}"); + assert!(beside.2.contains_key(&unit), "{alone} {json}: {beside:?}"); + } + + // A checkout only Bazel builds, which a run without the switch + // vendored for the hub: the refusal is the one of a tree without a + // JVM build, with no word of the entry, which stays. + let vendored = || { + remake(root, true); + ok(root, &["vendor"]); + }; + let (without, beside) = three(&vendored, &["vendor"], true); + let refused: serde_json::Value = serde_json::from_str(&without.1).unwrap(); + assert_eq!(without.0, Some(1), "{without:?}"); + let why = refused["events"][0]["error"].as_str().unwrap_or_default(); + assert!(why.ends_with("build at the project root"), "{without:?}"); + assert_eq!(beside.0 .0, Some(0), "{beside:?}"); + + // A Maven build that came to that checkout later: the run vendors for + // it and names no file of the hub among those to commit. + let later = || { + remake(root, false); + let build = [ + "proj/pom.xml", + "proj/a/pom.xml", + "proj/.mvn/wrapper/maven-wrapper.properties", + ]; + let held = build.map(|rel| std::fs::read(root.join(rel)).unwrap()); + only_bazel(root); + ok(root, &["vendor"]); + for (rel, bytes) in build.iter().zip(&held) { + write(root, rel, bytes); + } + }; + let (without, beside) = three(&later, &["vendor"], false); + assert_eq!(without.0, Some(0), "{without:?}"); + assert!(without.1.contains("Commit .socket/vendor/"), "{without:?}"); + assert!(beside.0 .1.contains("Commit MODULE.bazel"), "{beside:?}"); + + // The hosted entry of the block stays as it is. In a checkout only + // Bazel builds it is no pin that the run ejects, whether the manifest + // holds its patch or not; without the variable the eject asks the API + // for the record of the patch. Beside a Maven build the run vendors + // the patch of the manifest for that build alone. + let hosted = FOO_BLOCK + .replace("local_repository", "http_file") + .replace(":local.bzl", ":http.bzl") + .replace( + &format!(" path = \"{FOO_UNIT}\",\n"), + &format!( + " downloaded_file_path = \"v1/org/example/foo/1.0/foo-1.0.jar\",\n sha256 = \ + \"{}\",\n urls = [\"https://patch.socket.dev/patch-registry/maven/token/\ + {FOO_UUID}/maven2/org/example/foo/1.0-socket.1d3c1fd2/foo-1.0-socket.1d3c1fd2\ + .jar\"],\n", + "a".repeat(64) + ), + ); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let api = runtime.block_on(wiremock::MockServer::start()); + let records = api.uri(); + for (alone, in_manifest) in [(true, true), (true, false), (false, true)] { + let pinned = || { + remake(root, alone); + write( + root, + "proj/MODULE.bazel", + format!("{HUB_MODULE}\n{hosted}").as_bytes(), + ); + let manifest = root.join("proj/.socket/manifest.json"); + let patches = std::fs::read(&manifest).unwrap(); + let patches: serde_json::Value = serde_json::from_slice(&patches).unwrap(); + let mut view = patches["patches"][purl("foo")].clone(); + view["purl"] = purl("foo").into(); + view["publishedAt"] = view["exportedAt"].clone(); + let record = wiremock::ResponseTemplate::new(200).set_body_json(view); + let asked = + wiremock::Mock::given(wiremock::matchers::method("GET")).respond_with(record); + runtime.block_on(api.reset()); + runtime.block_on(asked.mount(&api)); + if !in_manifest { + std::fs::write(&manifest, "{\"patches\": {}}").unwrap(); + } + // The entry is a hosted pin of the jar. + let (_, list) = socket(root, &["list"]); + let pin = |event: &&serde_json::Value| { + event["purl"] == purl("foo") && event["details"]["mode"] == "hosted" + }; + let pins = list["events"].as_array().unwrap().iter().filter(pin); + let files: Vec<_> = pins.map(|pin| &pin["details"]["lockfiles"]).collect(); + assert_eq!(files, [&serde_json::json!(["MODULE.bazel"])], "{list}"); + }; + let args = ["vendor", "--proxy-url", &records]; + let (without, _) = three(&pinned, &args, true); + let code = Some(i32::from(alone && in_manifest)); + assert_eq!(without.0, code, "{alone} {in_manifest}: {without:?}"); + } +} + +/// What a run without the switch wrote for a hub is seen and undone with +/// `SOCKET_NO_BAZEL=1`, all of it: the entry of the block, the directory +/// of the jar, its pair of `.bazelignore` and the ledger entry, in a +/// checkout only Bazel builds and beside a Maven build. `list`, `vex`, +/// the audit and `repair` say what they say without the variable, also of +/// an entry whose jar the hub's lock no longer pins; `repair` puts a +/// directory that was lost whole back where its jar is the vendored +/// artifact; and each undo says what it says without the variable and +/// leaves the checkout as it was before the run, to the byte. +/// +/// Beside a Maven build the hub's directory is a copy that only a run +/// without the variable writes: one that was lost is named by the audit, +/// stays lost through a `vendor` with the variable, and the undo still +/// takes its entry out. +#[test] +fn the_switch_leaves_what_a_vendored_run_wrote_for_a_hub_seen_and_undone() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let foo = purl("foo"); + let vex = root.join("vex.json"); + let document = [ + "vex", + "-O", + vex.to_str().unwrap(), + "--product", + "pkg:generic/x@1", + ]; + for alone in [true, false] { + // The checkout before a run without the switch, and after it. + let vendor = || { + remake(root, alone); + let _ = std::fs::remove_file(&vex); + let pristine = snapshot(root); + ok(root, &["vendor"]); + (pristine, snapshot(root)) + }; + // The hub's lock, moved on to another version of the jar. + let moved = || { + let lock = root.join("proj/maven_install.json"); + let text = std::fs::read_to_string(&lock).unwrap(); + let bumped = text.replace("\"version\": \"1.0\"", "\"version\": \"1.1\""); + assert_ne!(bumped, text); + std::fs::write(&lock, bumped).unwrap(); + text + }; + let (pristine, vendored) = vendor(); + let written = [ + ".bazelignore".to_string(), + ".socket/vendor/state.json".to_string(), + format!("{FOO_UNIT}/REPO.bazel"), + format!("{FOO_UNIT}/file/foo-1.0.jar"), + ]; + for file in &written { + let (before, after) = (pristine.get(file), vendored.get(file)); + assert!(before.is_none() && after.is_some(), "{alone}: {file}"); + } + let block = format!("{HUB_MODULE}\n{FOO_BLOCK}"); + let held = vendored["MODULE.bazel"].as_deref(); + assert_eq!(held, Some(block.as_bytes()), "{alone}"); + + // Seen: each command says what it says without the variable, and + // changes nothing. `repair` has nothing to do and names no patch. + let seen: [&[&str]; 4] = [&["list"], &document, &["vendor", "--check"], &["repair"]]; + for args in seen { + let without = said(root, args, true, false); + assert_eq!(snapshot(root), vendored, "{alone} {args:?}"); + vendor(); + let with = said(root, args, true, true); + assert_eq!(with, without, "{alone} {args:?}"); + assert_eq!(with.0, Some(0), "{alone} {args:?}: {with:?}"); + let named = with.1.contains(&foo); + assert_eq!(named, args != ["repair"], "{alone} {args:?}: {with:?}"); + assert_eq!(snapshot(root), vendored, "{alone} {args:?}"); + } + // The same of an entry whose jar the lock no longer pins, at which + // Bazel stops: the audit names the undo, and the patch of a hub + // alone is not attested. + let stale: [(&[&str], bool); 4] = [ + (&["list"], false), + (&document, alone), + (&["vendor", "--check"], true), + (&["repair"], false), + ]; + for (args, fails) in stale { + moved(); + let without = said(root, args, true, false); + vendor(); + moved(); + let with = said(root, args, true, true); + assert_eq!(with, without, "{alone} {args:?}"); + assert_eq!(with.0, Some(i32::from(fails)), "{alone} {args:?}: {with:?}"); + vendor(); + } + // A directory that was lost whole, where its jar is the vendored + // artifact: `repair` puts every file of it back. Beside a Maven + // build no run with the variable does: the audit names it, and the + // undo takes its entry out. + std::fs::remove_dir_all(root.join("proj").join(FOO_UNIT)).unwrap(); + if alone { + let repaired = said(root, &["repair"], true, true); + assert_eq!(repaired.0, Some(0), "{repaired:?}"); + assert_eq!(snapshot(root), vendored, "{repaired:?}"); + } else { + let lost = snapshot(root); + let audit = said(root, &["vendor", "--check"], true, true); + assert_eq!(audit.0, Some(1), "{audit:?}"); + assert!(audit.1.contains(FOO_UNIT), "{audit:?}"); + let again = said(root, &["vendor"], true, true); + assert_eq!((again.0, snapshot(root)), (Some(0), lost), "{again:?}"); + let undone = said(root, &["vendor", "--revert"], true, true); + assert_eq!((undone.0, snapshot(root)), (Some(0), pristine.clone())); + } + + // Undone, by each command. + let undos: [&[&str]; 3] = [ + &["vendor", "--revert"], + &["rollback", &foo], + &["remove", &foo], + ]; + for (undo, stale) in undos + .iter() + .flat_map(|undo| [(*undo, false), (*undo, true)]) + { + // Each run of the undo, in the checkout as a run without the + // switch left it, with the lock moved on for the run when + // `stale` is set. + let undone = |off: bool| { + vendor(); + let lock = stale.then(moved); + let ran = said(root, undo, true, off); + if let Some(lock) = lock { + write(root, "proj/maven_install.json", lock.as_bytes()); + } + assert_eq!( + snapshot(root), + pristine, + "{alone} {undo:?} {stale}: {ran:?}" + ); + ran + }; + let (without, with) = (undone(false), undone(true)); + assert_eq!(with, without, "{alone} {undo:?} {stale}"); + assert_eq!(with.0, Some(0), "{alone} {undo:?} {stale}: {with:?}"); + } + } +} diff --git a/crates/socket-patch-core/src/bazel/ignore.rs b/crates/socket-patch-core/src/bazel/ignore.rs index 785cf81b4..fc6c9dfd2 100644 --- a/crates/socket-patch-core/src/bazel/ignore.rs +++ b/crates/socket-patch-core/src/bazel/ignore.rs @@ -95,7 +95,10 @@ const MARK: &str = "# socket-patch:"; /// a directory that exists keeps what the file says of it, as does one /// that cannot be probed. A file left empty is deleted. /// Outside a Bazel workspace ([`super::bazel_root`]) nothing is read or -/// written, and that lookup is all the call costs. +/// written, and that lookup is all the call costs. For a user who switched +/// the Bazel support off ([`super::off`]) no pair is added, as outside one; +/// the pair of a directory that is gone still goes, so that the undo of a +/// copy an earlier run made is whole. /// /// The pair follows the directory, not the `replace`: a rollback that /// keeps the copy on disk keeps its BUILD files in the workspace too. @@ -116,8 +119,8 @@ pub async fn sync( cargo: bool, maven: bool, ) -> Result, String> { - let project = project.to_path_buf(); - run_blocking(move || sync_blocking(&project, go, cargo, maven)).await + let (project, adds) = (project.to_path_buf(), !super::off()); + run_blocking(move || sync_blocking(&project, go && adds, cargo && adds, maven && adds)).await } /// The file [`sync`] changed, and the copies its changed lines are about. @@ -147,7 +150,7 @@ fn sync_blocking( cargo: bool, maven: bool, ) -> Result, String> { - let Some(root) = super::bazel_root(project) else { + let Some(root) = super::root_of(project) else { return Ok(None); }; let from_root = from_root(&root, Path::new("")); diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 73eb1d69d..b4c528158 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -484,9 +484,16 @@ pub struct Hubs { asked: Asked, /// Whether the workspace has to do with the ruleset: a call of a file /// that was read names it, its `WORKSPACE` file calls `maven_install`, - /// or a `maven_install.json` lies at the root. In another workspace a - /// doubt is about no hub ([`hub_jars`]). + /// a `maven_install.json` lies at the root, or the root `MODULE.bazel` + /// holds the block, which is written for a hub alone. In another + /// workspace a doubt is about no hub ([`hub_jars`]; [`Hubs::built`] + /// unless `unread`). ruleset: bool, + /// The doubt about a file that is there and was not read as a whole, + /// and may be the one that names the ruleset ([`Workspace::unread`]), + /// or about the `WORKSPACE` file that is not read while Bazel may read + /// it. + unread: Option, } impl Hubs { @@ -622,8 +629,14 @@ impl Hubs { } unread => unread.and_then(Result::err), }; - let ruleset = - named || (calls && legacy.is_some()) || view("maven_install.json") != Entry::Absent; + // The block is an entry for a hub, written or changed by hand: of + // its entries nothing is said as a fact while a doubt stands. + let ours = !block.is_empty() || edited.is_some(); + let ruleset = named + || ours + || (calls && legacy.is_some()) + || view("maven_install.json") != Entry::Absent; + let unread = ws.unread.clone().or_else(|| legacy.clone()); doubts.extend(legacy); Hubs { pinned, @@ -634,10 +647,14 @@ impl Hubs { edited, asked, ruleset, + unread, } } - /// Whether Bazel builds the jar of `group:artifact` at `version`. + /// Whether Bazel builds the jar of `group:artifact` at `version`. Of + /// a jar that no hub fetches it is not known where something was not + /// read, in a workspace that has to do with the ruleset or may: one + /// with a file that is there and was not read as a whole. pub fn built(&self, group: &str, artifact: &str, version: &str) -> Built<'_> { let mut by = Vec::new(); for (hub, lock) in &self.pinned { @@ -650,9 +667,14 @@ impl Hubs { let named = Some(target(&format!("{group}:{artifact}"))); let over = |(of, _): &&(Option, Doubt)| of.is_none() || *of == named; match self.overrides.iter().find(over) { - _ if by.is_empty() => self - .doubt() - .map_or(Built::No, |(doubt, kind)| Built::Unknown(doubt, kind)), + // The doubt that makes the answer: the first one in a workspace + // that has to do with the ruleset, else the one about the file + // that was not read, which another doubt may stand before. + _ if by.is_empty() => { + let unread = || Some((self.unread.as_ref()?, Kind::Unread)); + let doubt = self.doubt().filter(|_| self.ruleset).or_else(unread); + doubt.map_or(Built::No, |(doubt, kind)| Built::Unknown(doubt, kind)) + } Some((Some(_), tag)) => Built::Unknown(tag, Kind::Overridden), Some((None, tag)) => Built::Unknown(tag, Kind::Unread), None => Built::Yes(by), @@ -1553,9 +1575,15 @@ pub struct HubJars { /// the first thing that was not read: no jar is guessed for a hub without /// a lock, or for one whose tags or lock cannot be read. In a workspace /// that has nothing to do with the ruleset there is no hub to read, and -/// no warning. And the entries of hosted mode in the block that are -/// stale, for the run to take out. Nothing for a project below the root, -/// where no entry is written either, and for one in no Bazel workspace. +/// no warning: also where a file of it that is there was not read as a +/// whole, which [`Hubs::built`] takes for a workspace that may have to do +/// with it. That warning is one per patch of a Maven jar. This one would +/// be one per hosted scan, whatever the project holds, and make the root +/// a project of the scan, in every checkout with such a file: so a hub +/// that only such a file declares is not scanned, and the scan does not +/// say so. And the entries of hosted mode in the block that are stale, +/// for the run to take out. Nothing for a project below the root, where +/// no entry is written either, and for one in no Bazel workspace. pub async fn hub_jars(project: &Path) -> HubJars { let project = project.to_path_buf(); run_blocking(move || hub_jars_blocking(&project)).await @@ -1594,6 +1622,9 @@ fn hub_jars_blocking(project: &Path) -> HubJars { ); (HUB_NOT_READ, detail) }); + // Only when every hub was read: one that was not may fetch the jar. + // The block makes the workspace one of the ruleset, so beside a doubt + // the answer for its entries is never `No`. let stale = |patch: &&Patch| { patch.unit().is_none() && hubs.built(&patch.group, &patch.artifact, &patch.version) == Built::No @@ -2409,6 +2440,108 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") assert_eq!(built(&open), "no"); } + /// What was not read is about a hub only in a workspace that has to do + /// with the ruleset, or may: a file that was read names it, a lock of + /// the ruleset's name lies at the root, or a file that is there was not + /// read as a whole, which may be the one that names it. In a workspace + /// of other rulesets whose files were all read no hub builds the jar: + /// an include that does not exist names nothing, and neither does a + /// statement of a file that was read. + #[test] + fn a_doubt_is_about_no_hub_where_nothing_names_the_ruleset() { + let include = "include(\"//:more.MODULE.bazel\")\n"; + let gone = "more.MODULE.bazel:0: it does not exist; MODULE.bazel"; + let go = format!("bazel_dep(name = \"rules_go\", version = \"0.50.1\")\n{include}"); + let dep = go.replace("rules_go", "rules_jvm_external"); + let hub = format!("{PINNED}{include}"); + for (module, lock, said) in [ + (&go, None, "no".to_string()), + (&go, Some(LOCK_SKIPS), format!("{gone}:2 includes it")), + (&dep, None, format!("{gone}:2 includes it")), + (&hub, Some(LOCK_SKIPS), format!("{gone}:9 includes it")), + ] { + let mut files = vec![("MODULE.bazel", module.as_str())]; + files.extend(lock.map(|lock| ("maven_install.json", lock))); + assert_eq!(built(&files), said, "{module} {}", lock.is_some()); + } + let load = go.replace(include, "load(\"//:defs.bzl\", \"deps\")\n"); + assert_eq!(built(&[("MODULE.bazel", &load)]), "no"); + // The included file is there and cannot be parsed, and so the root. + let open = "f(\n"; + let files = [("MODULE.bazel", go.as_str()), ("more.MODULE.bazel", open)]; + let why = "a bracket is never closed"; + let said = format!("more.MODULE.bazel:1: {why}; MODULE.bazel:2 includes it"); + assert_eq!(built(&files), said); + let said = format!("MODULE.bazel:1: {why}"); + assert_eq!(built(&[("MODULE.bazel", open)]), said); + // An `include` that is not followed: 9.3.2 takes `dev_dependency`, + // and the file, with the hub and all that names the ruleset in it, + // is not read. + let dev = "include(\"//java:deps.MODULE.bazel\", dev_dependency = True)\n"; + let said = "MODULE.bazel:2: this `include` cannot be read"; + let root = go.replace(include, dev); + let (hub, lock) = (PINNED.replace("//:maven", "//java:maven"), lock_72()); + let files = [ + ("MODULE.bazel", root.as_str()), + ("java/deps.MODULE.bazel", hub.as_str()), + ("java/maven_install.json", lock.as_str()), + ]; + assert_eq!(built(&files), said); + assert_eq!(built(&files[..1]), said, "the file may be there"); + // The doubt that is named is the one that made the answer. A + // statement the reader does not follow comes first and is about no + // hub; the file that was not read is, and once it reads nothing is. + let load = "load(\"//:defs.bzl\", \"deps\")\n"; + let root = format!("{load}{go}"); + let files = [("MODULE.bazel", root.as_str()), ("more.MODULE.bazel", open)]; + let said = format!("more.MODULE.bazel:1: {why}; MODULE.bazel:3 includes it"); + assert_eq!(built(&files), said); + let read = [files[0], ("more.MODULE.bazel", "x = 1\n")]; + assert_eq!(built(&read), "no"); + // The same for a `WORKSPACE` file that cannot be read. + let files = [("MODULE.bazel", load), ("WORKSPACE", open)]; + assert_eq!(built(&files), format!("WORKSPACE:1: {why}")); + } + + /// The block of the root `MODULE.bazel` is written for a hub alone, so + /// a workspace that holds it has to do with the ruleset, whatever else + /// names it: while something was not read, nothing is said of an entry + /// as a fact. Lockfile discovery says that it could not tell whether a + /// hub takes the jar, a hosted scan warns and takes no entry out, and + /// a jar that no hub fetches is not known to be built by none. Only + /// with everything read is an entry whose jar no hub fetches stale. + #[test] + fn an_entry_of_the_block_is_not_called_stale_while_a_doubt_stands() { + let [_, _, ours] = sample(NETTY_UUID); + let block = ours.strip_prefix(PINNED).expect("the block follows"); + let go = "bazel_dep(name = \"rules_go\", version = \"0.50.1\")\n"; + let doubtful = format!("{go}load(\"//:defs.bzl\", \"deps\")\n{block}"); + let doubt = "MODULE.bazel:2: this `load` cannot be read"; + let unbuilt = |module: &str| { + let dir = project(&[("MODULE.bazel", module)]); + let read = pins(dir.path(), module).expect("the block is ours"); + assert_eq!(read.len(), 1, "{read:?}"); + let unbuilt = read.into_iter().next().and_then(|pin| pin.unbuilt); + ( + unbuilt.expect("no hub was read"), + hub_jars_blocking(dir.path()), + ) + }; + let (why, scanned) = unbuilt(&doubtful); + assert!(why.contains(doubt) && !why.contains("any more"), "{why}"); + assert_eq!(scanned.stale, [], "{scanned:?}"); + let (code, said) = scanned.unread.expect("what the scan did not read"); + assert!(code == HUB_NOT_READ && said.starts_with(doubt), "{said}"); + assert_eq!(built(&[("MODULE.bazel", &doubtful)]), doubt); + // Without the block the same doubt is about no hub. + let without = doubtful.replace(block, ""); + assert_eq!(built(&[("MODULE.bazel", &without)]), "no"); + // With every statement read the entry is stale, as a fact. + let (why, scanned) = unbuilt(&format!("{go}{block}")); + assert!(why.contains("any more"), "{why}"); + assert_eq!((scanned.stale.len(), scanned.unread), (1, None)); + } + /// A project directory with the files `files`, in a checkout of its /// own. fn project(files: &[(&str, &str)]) -> tempfile::TempDir { @@ -2589,7 +2722,11 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") let entry = patch("netty-tcnative-classes", NETTY_UUID); let patched = with_patch(PINNED, LABEL, entry).expect("a block"); let patched_lockless = format!("{patched}\nmaven.install(name = \"tools\")\n"); - let rows: [(&str, &[(&str, &str)], Vec<&str>, Option, bool); 19] = [ + // That block where nothing that was read names the ruleset any + // more, beside a file the reader cannot have. + let orphan = with_patch(go, LABEL, patch("netty-tcnative-classes", NETTY_UUID)); + let orphan = orphan.expect("a block"); + let rows: [(&str, &[(&str, &str)], Vec<&str>, Option, bool); 20] = [ // The jar without a classifier of each artifact, in each format. (PINNED, &[(main, &v2)], netty.clone(), None, false), (PINNED, &[(main, &v3)], netty.clone(), None, false), @@ -2700,6 +2837,16 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") Some(format!("maven_install.json: it does not exist, {NOT_READ}")), false, ), + // Not where something was not read: the file that was not + // read may hold the hub. The block is that workspace's sign of + // the ruleset, so the scan says what it did not read. + ( + &orphan, + &[], + vec![], + Some(format!("{gone}:2 includes it, {NOT_READ}")), + false, + ), ]; for (module, locks, jars, unread, stale) in rows { let dir = project(&[&[("MODULE.bazel", module)], locks].concat()); diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index fe8331b95..e25df7b3b 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -5,9 +5,56 @@ /// `WorkspaceLayout::InWorkspace`). Only a regular file of one of these /// names counts (a link to a file is followed); a directory does not: on a /// disk that folds case, a directory `workspace` answers for `WORKSPACE`. +/// A regular file `workspace` or `Module.bazel` counts on such a disk, as +/// it does for Bazel's client, which tests that the name exists: a +/// workspace is seen where Bazel sees one. [`OFF_ENV`] is the way out for +/// a checkout where such a file is none. pub const WORKSPACE_FILES: [&str; 4] = ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; +/// The variable that switches off everything socket-patch does because a +/// project is in a Bazel workspace: for a project that sits in such a +/// checkout and that Bazel does not build. It is read from the environment +/// alone, in the words of every such switch +/// ([`env_truthy`](crate::utils::socket_cli_config::env_truthy): `1`, +/// `true`, `yes`, `on`, `y` or `t`, in any case), and a run that honours +/// it says nothing. +/// +/// A child process inherits it +/// ([`CHILD_ENV_SCRUB`](crate::utils::process::CHILD_ENV_SCRUB) does not +/// list it): it is the user's word about the checkout, no credential and +/// no flag of this run, and a socket-patch that a spawned program starts +/// there has to give the same run. +pub const OFF_ENV: &str = "SOCKET_NO_BAZEL"; + +/// Whether the user switched the Bazel support off ([`OFF_ENV`]). Then +/// [`bazel_root`] finds no workspace on disk, the view of files handed +/// over in memory holds none ([`workspace::memory`]), and the in-memory +/// path selection asks for none ([`ruby::is_workspace_file`]): one gate +/// for each way a workspace is come by, so that what judges one need not +/// ask. The judgements of vendored mode that go by the block of +/// `MODULE.bazel` without the lookup ask here through one read of it +/// ([`crate::vendor::maven_repo`]). What an earlier run wrote for Bazel +/// is still listed and undone. +pub fn off() -> bool { + crate::utils::socket_cli_config::truthy(&off_env().unwrap_or_default()) +} + +#[cfg(not(test))] +fn off_env() -> Option { + std::env::var(OFF_ENV).ok() +} + +/// The unit tests see the variable only while a guard holds it +/// ([`crate::test_env`]): hundreds of them look a workspace up, and none +/// is to change with what the developer's shell exports. None of them +/// sets it either, since every other test would see it meanwhile: what +/// the switch does is held by tests that start a process of their own. +#[cfg(test)] +fn off_env() -> Option { + crate::test_env::guarded_var(OFF_ENV) +} + pub mod built; pub mod cargo; pub(crate) mod cargo_bazel; @@ -41,12 +88,19 @@ pub struct BazelRoot { /// its `.git` belongs to a trusted owner; in no such checkout only the /// project's own directory is looked at. So nothing above the checkout, or /// above a project outside one, is read, and no file is written there. +/// None for a user who switched the Bazel support off ([`off`]). pub fn bazel_root(project: &Path) -> Option { + (!off()).then(|| root_of(project)).flatten() +} + +/// [`bazel_root`] whatever the switch says: for the one caller that takes +/// away what an earlier run wrote for Bazel ([`ignore::sync`]). +pub(crate) fn root_of(project: &Path) -> Option { let dirs = search_dirs(project); root_in(&dirs, repo_at_end_of(dirs.clone())) } -/// [`bazel_root`] for the walk `dirs`, which ended at the checkout `repo`. +/// [`root_of`] for the walk `dirs`, which ended at the checkout `repo`. fn root_in(dirs: &[PathBuf], repo: Option) -> Option { let within = repo.filter(|repo| repo.trusted).map_or(1, |_| dirs.len()); let at = dirs.iter().take(within).position(|dir| { diff --git a/crates/socket-patch-core/src/bazel/pnpm.rs b/crates/socket-patch-core/src/bazel/pnpm.rs index bbd4d0bee..54189b446 100644 --- a/crates/socket-patch-core/src/bazel/pnpm.rs +++ b/crates/socket-patch-core/src/bazel/pnpm.rs @@ -77,13 +77,13 @@ use super::rc::ModuleLock; use super::starlark::{Arg, Call, File, How, Value}; -use super::workspace::{disk, Doubt, Entry, Extension, Label, Repo, Workspace}; +use super::workspace::{disk, memory, Doubt, Entry, Extension, Label, Repo, Workspace}; use crate::formats::text::strip_bom; use crate::hosted::guidance::{is_trust_scaffold, plan_workspace_trust, TrustPlan}; use crate::patch::redirect::RewriteWarning; use crate::utils::fs::run_blocking; use crate::utils::package_manager::pinned_version; -use crate::vendor::lock_inventory::{MemoryEntry, MemoryProject, ProjectView}; +use crate::vendor::lock_inventory::ProjectView; /// The code of the warning with which hosted mode leaves a pnpm lock as it /// is because of such a hub. @@ -101,15 +101,6 @@ fn extension(name: &'static str) -> Extension<'static> { } } -/// The files of an in-memory project, as the workspace reader takes them. -fn memory(project: &MemoryProject) -> impl Fn(&str) -> Entry + '_ { - |path| match project.get(path) { - Some(MemoryEntry::Text(text)) => Entry::Text(text.to_string()), - Some(_) => Entry::Unreadable("it was not handed in as text".to_string()), - None => Entry::Absent, - } -} - /// What the Bazel workspace of a project says of its pnpm locks: both /// answers of this module, from one read of the workspace ([`hubs`]). #[derive(Debug, Default, Clone, PartialEq)] @@ -200,7 +191,9 @@ pub async fn hubs(view: &ProjectView<'_>, root: bool, members: &[String]) -> Hub /// locks `locks` (paths from the project): on disk the workspace of /// [`super::bazel_root`], read off the async runtime, in memory the /// project itself, whose files are all there is. Nothing outside a Bazel -/// workspace. +/// workspace, and nothing for a user who switched the Bazel support off: +/// on disk no root is found then, and in memory the view holds no file +/// ([`memory`]). async fn read(view: &ProjectView<'_>, locks: &[String]) -> Hubs { match *view { ProjectView::Memory(project) => answer(&memory(project), "", locks), diff --git a/crates/socket-patch-core/src/bazel/ruby.rs b/crates/socket-patch-core/src/bazel/ruby.rs index e6b8662bb..18835a3f1 100644 --- a/crates/socket-patch-core/src/bazel/ruby.rs +++ b/crates/socket-patch-core/src/bazel/ruby.rs @@ -86,9 +86,12 @@ pub type Held = (String, Option>); /// Whether the reader asks for the file `path` of a workspace, by its path /// from the Bazel root: `MODULE.bazel`, a file that one can include, and -/// the names of the `WORKSPACE` file. +/// the names of the `WORKSPACE` file. For a user who switched the Bazel +/// support off ([`super::off`]) it asks for none: the in-memory path +/// selection, which goes by this, then asks its host for no Bazel file. pub fn is_workspace_file(path: &str) -> bool { - path == "MODULE.bazel" || path.ends_with(".MODULE.bazel") || LEGACY.contains(&path) + let named = path == "MODULE.bazel" || path.ends_with(".MODULE.bazel"); + (named || LEGACY.contains(&path)) && !super::off() } /// Whether `call` reads the lock at `lock`, a path from the Bazel root. diff --git a/crates/socket-patch-core/src/bazel/workspace.rs b/crates/socket-patch-core/src/bazel/workspace.rs index 292811c2e..379404fc5 100644 --- a/crates/socket-patch-core/src/bazel/workspace.rs +++ b/crates/socket-patch-core/src/bazel/workspace.rs @@ -40,6 +40,7 @@ use std::path::{Component, Path}; use super::starlark::{self, Bound, Call, File, How, Value, MAX_BYTES, MAX_TOKENS}; use crate::utils::fs::open_regular_file_sync; use crate::utils::group_commit; +use crate::vendor::lock_inventory::{MemoryEntry, MemoryProject}; /// How many files of one workspace are asked for, beside the names of its /// `WORKSPACE` file, and how many bytes are read in all. @@ -122,6 +123,19 @@ pub fn disk_up_to(root: &Path, max: usize) -> impl Fn(&str) -> Entry + '_ { } } +/// The view of the files handed over in memory, for a project that is its +/// own Bazel root. It holds none for a user who switched the Bazel support +/// off ([`super::off`]): whatever judges a workspace from this view then +/// finds none, as [`super::bazel_root`] finds none on disk. +pub fn memory(project: &MemoryProject) -> impl Fn(&str) -> Entry + '_ { + let off = super::off(); + move |path| match project.get(path).filter(|_| !off) { + Some(MemoryEntry::Text(text)) => Entry::Text(text.to_string()), + Some(_) => Entry::Unreadable("it was not handed in as text".to_string()), + None => Entry::Absent, + } +} + /// The text of `from`, read to its end. One byte more than `max` is /// asked for: a file that grew since its size was taken is refused, not /// cut there and read as if it were whole. @@ -282,6 +296,14 @@ pub struct Workspace { /// doubt about every answer of [`Self::tags`], which does not repeat /// them. The first 1,024 are kept. pub doubts: Vec, + /// The first doubt about a file that is there and was not read as a + /// whole: one that cannot be read or parsed, one past a bound, which + /// is not asked for, and the file of an `include` that is not + /// followed, which may be there (9.3.2 takes `dev_dependency` as a + /// second argument, and such a file is not read). What such a file + /// says is not known, the name of a ruleset included. A file that an + /// `include` names and that does not exist says nothing, and is none. + pub unread: Option, /// The file of the older `WORKSPACE` system at the Bazel root, when /// it says more than `workspace(...)`: its name (`WORKSPACE.bzlmod`, /// else `WORKSPACE.bazel`, else `WORKSPACE`, as Bazel takes one) and @@ -395,17 +417,19 @@ impl Workspace { if ws.files.len() + failed.len() == MAX_FILES { let why = format!("it is one more than the {MAX_FILES} files that are asked for{by}"); - ws.doubt(&path, 0, why); + ws.left_unread(&path, 0, why); break; } // What is wrong with the file, and on which line of it: 0 for // the file as a whole. - let file = match view(&path) { + let entry = view(&path); + let there = entry != Entry::Absent; + let file = match entry { Entry::Absent if includer.is_none() => break, Entry::Absent => Err((0, "it does not exist".to_string())), Entry::Unreadable(why) => Err((0, format!("it cannot be read: {why}"))), Entry::Text(text) if text.len() > budget => { - ws.doubt(&path, 0, format!("{OVER_TOTAL}{by}")); + ws.left_unread(&path, 0, format!("{OVER_TOTAL}{by}")); break; } Entry::Text(text) => { @@ -415,7 +439,10 @@ impl Workspace { }; match file { Err((line, why)) => { - ws.doubt(&path, line, format!("{why}{by}")); + match there { + true => ws.left_unread(&path, line, format!("{why}{by}")), + false => ws.doubt(&path, line, format!("{why}{by}")), + } failed.insert(path); } Ok(file) => { @@ -454,6 +481,14 @@ impl Workspace { } } + /// [`Self::doubt`] about a file that is there and is not read as a + /// whole: the first of them is kept as such ([`Self::unread`]). + fn left_unread(&mut self, file: &str, line: usize, why: impl Into) { + let (file, why) = (file.to_string(), why.into()); + self.doubt(&file, line, why.as_str()); + self.unread.get_or_insert(Doubt { file, line, why }); + } + /// Takes from `file` what it says of the workspace itself: the names /// of the root module and of its dependencies, and the files it /// includes, which are returned with the line of each. Whatever of @@ -494,7 +529,11 @@ impl Workspace { }; if !read { let why = format!("this `{}` cannot be read", call.callee); - self.doubt(path, call.line, why); + // The file of an `include` that is not followed may be there. + match call.callee == "include" { + true => self.left_unread(path, call.line, why), + false => self.doubt(path, call.line, why), + } } } for used in &file.uses { @@ -1831,6 +1870,83 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") assert_eq!(ws.tags(&PIP, "parse"), Tags::default()); } + /// A file that is there and is not read as a whole is told from one + /// that an include names and that does not exist: what the first says + /// is not known ([`Workspace::unread`]), and its doubt is kept as the + /// one about such a file, whatever doubt came before it. + #[test] + fn a_file_that_is_there_and_not_read_is_told_from_one_that_is_missing() { + // The file that the second line of the root includes, after a + // statement that the reader does not follow. + let root = "load('//:defs.bzl', 'deps')\ninclude('//:a.MODULE.bazel')\n"; + let unread = |included: Entry| { + let view = |path: &str| match path { + "MODULE.bazel" => Entry::Text(root.to_string()), + "a.MODULE.bazel" => included.clone(), + _ => Entry::Absent, + }; + let ws = Workspace::read(&view); + let first = doubts(&ws.doubts[..1]); + assert_eq!(first, ["MODULE.bazel:1: this `load` cannot be read"]); + ws.unread.map(|doubt| (doubt.file, doubt.line)) + }; + assert_eq!(unread(Entry::Absent), None); + assert_eq!(unread(Entry::Text("x = 1\n".to_string())), None); + // One that includes itself was read. + let cycle = "include('//:a.MODULE.bazel')\n"; + assert_eq!(unread(Entry::Text(cycle.to_string())), None); + let (binary, open) = ("it is not UTF-8", "x = 'never closed\n"); + let at = |line| Some(("a.MODULE.bazel".to_string(), line)); + assert_eq!(unread(Entry::Unreadable(binary.to_string())), at(0)); + assert_eq!(unread(Entry::Text(open.to_string())), at(1)); + // The root file, and a workspace with none. + let no_root = Workspace::read(&|_| Entry::Unreadable("no".to_string())); + let file = no_root.unread.map(|doubt| doubt.file); + assert_eq!(file.as_deref(), Some("MODULE.bazel")); + assert_eq!(Workspace::read(&|_| Entry::Absent).unread, None); + // An `include` that is not followed names a file that may be there + // and is never asked for: 9.3.2 takes the first of these. + for unfollowed in [ + "include('//:a.MODULE.bazel', dev_dependency = True)\n", + "include(NAME)\n", + "x = include('//:a.MODULE.bazel')\n", + ] { + let asked = std::cell::Cell::new(false); + let ws = Workspace::read(&|path| match path { + "MODULE.bazel" => Entry::Text(unfollowed.to_string()), + "a.MODULE.bazel" => { + asked.set(true); + Entry::Text("x = 1\n".to_string()) + } + _ => Entry::Absent, + }); + assert_eq!(ws.unread.as_ref(), ws.doubts.first(), "{unfollowed}"); + assert!(!asked.get(), "{unfollowed}"); + assert_eq!(ws.doubts.len(), 1, "{unfollowed}"); + } + // A statement that is no `include` leaves no file unread. + let load = "load('//:defs.bzl', 'deps')\n"; + let view = |path: &str| match path { + "MODULE.bazel" => Entry::Text(load.to_string()), + _ => Entry::Absent, + }; + let ws = Workspace::read(&view); + assert_eq!((ws.unread, ws.doubts.len()), (None, 1)); + } + + /// The view of files handed over in memory holds what was handed over, + /// a file that is no text as one that cannot be read. + #[test] + fn the_view_of_a_project_in_memory_holds_its_files() { + let mut project = MemoryProject::new(); + project.insert_text("MODULE.bazel", "x = 1\n"); + project.insert_present("WORKSPACE"); + let view = memory(&project); + assert_eq!(view("MODULE.bazel"), Entry::Text("x = 1\n".to_string())); + assert!(matches!(view("WORKSPACE"), Entry::Unreadable(_))); + assert_eq!(view("WORKSPACE.bazel"), Entry::Absent); + } + #[test] fn the_files_of_a_workspace_are_bounded() { // 300 files in a chain: the first 256 are read, and no other is @@ -1849,6 +1965,8 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") let want = "256.MODULE.bazel:0: it is one more than the 256 files that are asked for; \ 255.MODULE.bazel:1 includes it"; assert_eq!(doubts(&ws.doubts), [want]); + // The file past the bound may be there. + assert_eq!(ws.unread.as_ref(), ws.doubts.first()); // Nine files of nearly 1 MiB: the ninth is past 8 MiB. let big = format!("#{}\n", "x".repeat(MAX_BYTES - 64)); let ws = Workspace::read(&|path| match path { @@ -1862,6 +1980,8 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") let want = "8.MODULE.bazel:0: the files of the workspace are larger than 8 MiB in all; \ MODULE.bazel:9 includes it"; assert_eq!(doubts(&ws.doubts), [want]); + // The ninth file is there. + assert_eq!(ws.unread.as_ref(), ws.doubts.first()); // The `WORKSPACE` file is one of the files of the workspace. let (file, why) = ("WORKSPACE.bzlmod".to_string(), OVER_TOTAL.to_string()); assert_eq!(ws.legacy, Some(Err(Doubt { file, line: 0, why }))); diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 0f2616cea..4c08062ed 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -1715,20 +1715,15 @@ pub async fn read_candidate_files_in( // from the checkout on disk, and in memory from the files handed // over, where the project's directory is the Bazel root. A project // in no Bazel workspace, or whose lock no such call may read, gets - // none, and its run is the one it was. + // none, and its run is the one it was. So does every project of a + // user who switched the Bazel support off: no root is found on + // disk then, and the view of the files in memory holds none. let (_, lock) = crate::patch::redirect::gem_pair(&out.files); if out.files.contains_key(lock) { use crate::bazel::ruby::{handed, handed_on_disk, KEY}; - use crate::bazel::workspace::Entry; - use crate::vendor::lock_inventory::MemoryEntry; let held = match view { ProjectView::Memory(project) => { - let file = |path: &str| match project.get(path) { - Some(MemoryEntry::Text(text)) => Entry::Text(text.to_string()), - None => Entry::Absent, - Some(_) => Entry::Unreadable("it was not handed over as text".into()), - }; - handed(&file, lock) + handed(&crate::bazel::workspace::memory(project), lock) } _ => { let root = view.disk_root().expect("a disk view has a root"); diff --git a/crates/socket-patch-core/src/hosted/memory/select.rs b/crates/socket-patch-core/src/hosted/memory/select.rs index 62d0e09a6..6cdd0e556 100644 --- a/crates/socket-patch-core/src/hosted/memory/select.rs +++ b/crates/socket-patch-core/src/hosted/memory/select.rs @@ -170,7 +170,10 @@ fn classify( } // Beside a gem lock, the files of a Bazel workspace at this root: they // say whether a rules_ruby hub holds a gem of the lock to a sha256 of - // its own (`bazel::ruby`). + // its own (`bazel::ruby`). None of them for a user who switched the + // Bazel support off (`is_workspace_file`): no file is then asked for + // that nothing judges, and the selection is the one of the tree + // without its Bazel files. let locks = ["Gemfile.lock", "gems.locked"]; if gems && locks.iter().any(|lock| root_files.contains(lock)) diff --git a/crates/socket-patch-core/src/utils/process.rs b/crates/socket-patch-core/src/utils/process.rs index 134a905a8..86a4c3009 100644 --- a/crates/socket-patch-core/src/utils/process.rs +++ b/crates/socket-patch-core/src/utils/process.rs @@ -50,6 +50,13 @@ pub const PROBE_TIMEOUT: Duration = Duration::from_secs(10); /// The CLI's flag bindings are listed here because core runs the /// children; `socket-patch-cli`'s `args` tests fail when a binding is /// missing. +/// +/// A switch of the user's own that no flag binds and that holds no +/// credential is not listed, and a child inherits it: `SOCKET_NO_CONFIG`, +/// `SOCKET_NO_UPDATE_CHECK`, and `SOCKET_NO_BAZEL` +/// ([`crate::bazel::OFF_ENV`]), which says of the checkout that Bazel +/// does not build it. A socket-patch that a spawned program starts there +/// (a hook of a package manager) has to honour it as this run does. pub const CHILD_ENV_SCRUB: &[&str] = &[ // The Socket API token, under each name a Socket tool reads it from // (this CLI, socket-cli and its legacy spellings, the Python CLI, the @@ -1472,9 +1479,19 @@ pub(crate) mod tests { /// The scrub list names every accepted socket-cli alias and its /// canonical name, each once, and nothing but `SOCKET_*` names: a proxy - /// or registry credential of the package manager's is never on it. + /// or registry credential of the package manager's is never on it. Nor + /// is the switch for a project that Bazel does not build: a child + /// inherits it, so that a socket-patch it starts gives the same run. #[test] fn the_scrub_list_covers_the_peer_aliases_and_only_socket_names() { + assert!(!CHILD_ENV_SCRUB.contains(&crate::bazel::OFF_ENV)); + let mut inherits = command_for(Path::new("/x/git")); + inherits.env(crate::bazel::OFF_ENV, "1"); + scrub_child_env(&mut inherits); + let kept = |(name, value): (&std::ffi::OsStr, Option<&std::ffi::OsStr>)| { + name == crate::bazel::OFF_ENV && value == Some(std::ffi::OsStr::new("1")) + }; + assert!(inherits.get_envs().any(kept)); for (canonical, alias) in crate::utils::env_compat::PEER_ENV_ALIASES { for name in [canonical, alias] { assert!( diff --git a/crates/socket-patch-core/src/utils/socket_cli_config.rs b/crates/socket-patch-core/src/utils/socket_cli_config.rs index 7175eb86c..3933e8d5a 100644 --- a/crates/socket-patch-core/src/utils/socket_cli_config.rs +++ b/crates/socket-patch-core/src/utils/socket_cli_config.rs @@ -56,12 +56,13 @@ fn env_non_empty(name: &str) -> Option { /// — including unset and empty — is false. `pub` so the CLI shares this one /// vocabulary instead of re-declaring it. pub fn env_truthy(name: &str) -> bool { + truthy(&std::env::var(name).unwrap_or_default()) +} + +/// [`env_truthy`] for a value that was read already. +pub fn truthy(value: &str) -> bool { matches!( - std::env::var(name) - .unwrap_or_default() - .trim() - .to_ascii_lowercase() - .as_str(), + value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on" | "y" | "t" ) } diff --git a/crates/socket-patch-core/src/vendor/composer_lock/bazel.rs b/crates/socket-patch-core/src/vendor/composer_lock/bazel.rs index 84fce4bd6..a46521ecc 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock/bazel.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock/bazel.rs @@ -19,14 +19,21 @@ //! both fails the same way (Bazel 9.3.2). So every Composer project in a //! Bazel workspace is declined, and the user's word is the one exception. //! -//! What is declined is the write of that path. A package whose lock entry -//! already names the copy of the same patch is let through: the run leaves -//! the lock as it is, so a project that was vendored before (by an earlier -//! release, or with the flag) keeps passing its in-sync runs. +//! What is declined is the first such path that a rule may install. A +//! package is let through when `packages` of the lock already names a copy +//! under `.socket/vendor/composer`, or when the section that holds the +//! package does: an earlier release vendored there, or the user allowed +//! it. Either no Bazel rule installs from that lock, and then vendored +//! mode works there as it did before this refusal existed; or one does, +//! and its build already fails on a path in a section it installs, which +//! one more path there does not change. The section matters because a rule +//! may install with `--no-dev`, which reads `packages` alone: a copy that +//! only `packages-dev` names breaks no such build, so it lets through the +//! packages of `packages-dev` and no other. use std::path::Path; -use crate::formats::composer::composer_lock_packages; +use crate::formats::composer::{composer_lock_packages, ComposerLockPackage}; use crate::utils::env_compat::env_flag; use crate::utils::fs::{read_regular_to_string, run_blocking}; use crate::utils::pnpm_workspace::without_verbatim_prefix; @@ -43,8 +50,9 @@ pub const CODE: &str = "vendor_composer_bazel_workspace"; /// declines in the project at `project`, each with [`CODE`] and the detail. /// It declines a project in a Bazel workspace /// ([`crate::bazel::bazel_root`]) unless the user allowed it -/// ([`ALLOW_IN_BAZEL_ENV`]), and lets through a package the lock already -/// names by the copy of that patch. Read-only: it looks for the root, reads +/// ([`ALLOW_IN_BAZEL_ENV`]), and lets through a package when `packages` of +/// the lock, or the section that holds the package, already names a +/// vendored copy (the module docs). Read-only: it looks for the root, reads /// the lock, and starts no program. pub async fn refusals<'a>( project: &Path, @@ -74,28 +82,39 @@ async fn refusals_unless<'a>( Bazel rule that runs `composer install` anywhere else does not find it, and the \ build fails; use `--mode hosted`, which names the patched archive by a URL that \ Composer fetches from any directory, or pass `--allow-vendored-in-bazel` if \ - Composer only runs in the project's directory", + Composer only runs in the project's directory (a package is not declined where \ + `packages` of composer.lock, or the section that holds the package, already names \ + a vendored copy)", without_verbatim_prefix(root.dir).display() ); - // A lock that cannot be read wires nothing: the backend says so itself. + // A lock that cannot be read names no copy. let lock = match read_regular_to_string(&project.join(COMPOSER_LOCK)).await { Ok(text) => LOCK_MEMO .parse(text.as_bytes(), || parse_json_text(&text)) .ok(), Err(_) => None, }; - let wired = |purl: &str, uuid: &str| { - let (Some(lock), Some(((vendor, name), _))) = (&lock, parse_composer_purl(purl)) else { - return false; + let entries = lock.as_ref().map(|lock| composer_lock_packages(lock)); + let entries = entries.unwrap_or_default(); + // The sections that name a vendored copy: a rule that installs one of + // them fails already. + let copy = |entry: &&ComposerLockPackage| { + let copy = entry.dist_vendor_path(); + copy.is_some_and(|copy| copy.eco == "composer") + }; + let vendored: Vec<&str> = entries.iter().filter(copy).map(|e| e.section).collect(); + let through = |purl: &str| { + let name = parse_composer_purl(purl).map(|((vendor, name), _)| format!("{vendor}/{name}")); + let held = |entry: &ComposerLockPackage| { + let named = entry.name.zip(name.as_deref()); + let named = named.is_some_and(|(a, b)| a.eq_ignore_ascii_case(b)); + named && vendored.contains(&entry.section) }; - let pkg = format!("{vendor}/{name}"); - composer_lock_packages(lock) - .into_iter() - .any(|p| p.name.is_some_and(|n| n.eq_ignore_ascii_case(&pkg)) && p.wired_to(uuid)) + vendored.contains(&"packages") || entries.iter().any(held) }; candidates .iter() - .filter(|(purl, uuid)| !wired(purl, uuid)) + .filter(|(purl, _)| !through(purl)) .map(|(purl, _)| (*purl, CODE, detail.clone())) .collect() } @@ -142,6 +161,7 @@ mod tests { &*format!("the Bazel workspace at {},", shown.display()), "`--mode hosted`", "`--allow-vendored-in-bazel`", + "(a package is not declined where `packages` of composer.lock, or the section", ]; assert!(named.iter().all(|part| detail.contains(part)), "{detail}"); // The user's word lifts it. @@ -154,35 +174,68 @@ mod tests { assert!(declined(&api, &one).await.is_empty()); } - /// A package the lock already names by the copy of the same patch is - /// let through: the run would leave the lock as it is. Another patch of - /// that package, another package, and a lock that holds the registry - /// entry or cannot be read are declined. + /// A package is let through where `packages` of the lock names a + /// vendored Composer copy, or the section that holds the package does: + /// the package of that copy, a newer patch of it and another package. + /// A copy that only `packages-dev` names lets through no package of + /// `packages`, the one section a rule that installs with `--no-dev` + /// reads, and none that the lock does not hold. A lock that names no + /// copy declines all: one of registry entries, the copy of a sibling + /// project, a copy of another ecosystem's, and one that cannot be read + /// or is not there. #[tokio::test] - async fn a_package_the_lock_already_wires_to_the_patch_is_let_through() { + async fn a_package_is_let_through_where_its_section_names_a_vendored_copy() { let tmp = tempfile::tempdir().unwrap(); let project = tmp.path(); fs::write(project.join("MODULE.bazel"), "").unwrap(); let other = "pkg:composer/acme/gadget@2.0.0"; - let candidates = [(PURL, UUID), (other, UUID)]; - let lock = |dist: serde_json::Value| { - let entries = serde_json::json!([ - { "name": "Acme/Widget", "version": "1.0.0", "dist": dist }, - { "name": "acme/gadget", "version": "2.0.0", - "dist": { "type": "zip", "url": "https://registry.example/gadget.zip" } }, - ]); - let text = serde_json::json!({ "packages": entries, "packages-dev": [] }); + let absent = "pkg:composer/acme/absent@3.0.0"; + let candidates = [ + (PURL, UUID), + (PURL, OTHER_UUID), + (other, UUID), + (absent, UUID), + ]; + let all = [PURL, PURL, other, absent]; + // The lock with `Acme/Widget` at `url` in the section `widget`, and + // the registry's `acme/gadget` in the section `gadget`. + let lock = |widget: &str, url: &str, gadget: &str| { + let mut text = serde_json::json!({ "packages": [], "packages-dev": [] }); + let registry = serde_json::json!({ "name": "acme/gadget", "version": "2.0.0", + "dist": { "type": "zip", "url": "https://registry.example/gadget.zip" } }); + let named = serde_json::json!({ "name": "Acme/Widget", "version": "1.0.0", + "dist": { "type": "path", "url": url, "reference": UUID } }); + text[gadget].as_array_mut().unwrap().push(registry); + text[widget].as_array_mut().unwrap().push(named); fs::write(project.join("composer.lock"), text.to_string()).unwrap(); }; let copy = format!(".socket/vendor/composer/{UUID}/acme/widget@1.0.0"); - lock(serde_json::json!({ "type": "path", "url": copy, "reference": UUID })); - assert_eq!(declined(project, &candidates).await, [other]); - assert_eq!(declined(project, &[(PURL, OTHER_UUID)]).await, [PURL]); - lock(serde_json::json!({ "type": "zip", "url": "https://registry.example/widget.zip" })); - assert_eq!(declined(project, &candidates).await, [PURL, other]); + let (prod, dev) = ("packages", "packages-dev"); + let rows: [(&str, &str, &[&str]); 4] = [ + (prod, prod, &[]), + (prod, dev, &[]), + (dev, dev, &[absent]), + (dev, prod, &[other, absent]), + ]; + for (widget, gadget, expected) in rows { + lock(widget, ©, gadget); + let said = declined(project, &candidates).await; + assert_eq!(said, expected, "the copy in {widget}, gadget in {gadget}"); + } + let not_one = [ + "https://registry.example/widget.zip".to_string(), + format!("../{copy}"), + copy.replace("/composer/", "/npm/"), + ]; + for url in not_one { + for section in [prod, dev] { + lock(section, &url, section); + assert_eq!(declined(project, &candidates).await, all, "{url} {section}"); + } + } fs::write(project.join("composer.lock"), "{").unwrap(); - assert_eq!(declined(project, &candidates).await, [PURL, other]); + assert_eq!(declined(project, &candidates).await, all); fs::remove_file(project.join("composer.lock")).unwrap(); - assert_eq!(declined(project, &candidates).await, [PURL, other]); + assert_eq!(declined(project, &candidates).await, all); } } diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 91e92c51e..85104d5c1 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -270,23 +270,46 @@ pub fn hub_refusals( candidates.iter().filter_map(refused).collect() } +/// Whether this run judges a hub where it does not come by one through +/// the lookup: not for a user who switched the Bazel support off +/// ([`crate::bazel::off`]). With the switch no hub is a build of the +/// project: a run ejects no entry, gives no hub a copy and says nothing of +/// one. The undo, the audit and `repair` do not ask: what an earlier run +/// wrote stays theirs to see. +fn judges_hubs() -> bool { + !crate::bazel::off() +} + +/// The entries of the block in `MODULE.bazel` at the project root, for a +/// run that judges a hub by them: `None` where it judges none +/// ([`judges_hubs`]), asked before anything is read. No entry where the +/// file is not there or holds no block. +async fn judged_block(project_root: &Path) -> Option> { + use crate::bazel::maven::{entries, FILE}; + if !judges_hubs() { + return None; + } + let text = read_regular_to_string(&project_root.join(FILE)).await; + Some(text.map(|text| entries(&text)).unwrap_or_default()) +} + /// Whether the hub of a Bazel workspace is the only build of the project /// that vendored mode can patch: a hosted pin that only the block of /// `MODULE.bazel` wires is ejected there. Elsewhere an eject leaves it, /// and the hub's entry changes only with a run that vendors the same patch -/// for the Maven or Gradle build. +/// for the Maven or Gradle build. The caller holds the pins of the block, +/// which are read whatever the switch says, so nothing is read here. pub fn hub_alone(project_root: &Path) -> bool { - detect_shape(project_root) == super::jvm::Shape::Other + judges_hubs() && detect_shape(project_root) == super::jvm::Shape::Other } /// Whether the block of `MODULE.bazel` at the project root holds the /// vendored entry of the patch `uuid`: a hub builds the jar committed in -/// the directory of that patch. +/// the directory of that patch, which a run gave it or kept for it. pub async fn hub_wired(project_root: &Path, uuid: &str) -> bool { - use crate::bazel::maven::{entries, FILE}; - let text = read_regular_to_string(&project_root.join(FILE)).await; let ours = |patch: &crate::bazel::maven::Patch| patch.uuid == uuid && patch.unit().is_some(); - text.is_ok_and(|text| entries(&text).iter().any(ours)) + let block = judged_block(project_root).await; + block.is_some_and(|block| block.iter().any(ours)) } /// What the refusal of `purl` in a project without a JVM build ends with @@ -294,10 +317,9 @@ pub async fn hub_wired(project_root: &Path, uuid: &str) -> bool { /// hub builds the jar at that version any more, so Bazel stops at the /// entry, and the undo is what takes it out. async fn stale_hub_entry(project_root: &Path, purl: &str) -> String { - use crate::bazel::maven::{entries, FILE}; - let text = read_regular_to_string(&project_root.join(FILE)).await; - let held = text.is_ok_and(|text| entries(&text).iter().any(|patch| patch.purl() == purl)); - match held { + use crate::bazel::maven::FILE; + let block = judged_block(project_root).await; + match block.is_some_and(|block| block.iter().any(|patch| patch.purl() == purl)) { true => format!( "; {FILE} holds an entry for it that no pinned hub takes any more, so Bazel stops \ there: run `socket-patch rollback {purl}`" diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 437316fc8..477191121 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -25,7 +25,8 @@ //! (`vendor_maven_version_not_selected`, a skip too); //! 7. a Composer project in a Bazel workspace //! (`vendor_composer_bazel_workspace`), unless the user allowed it -//! ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's copy +//! ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names a vendored copy +//! in `packages` or in the package's section //! ([`bazel_workspace_refusals`]); //! 8. a Maven jar that only a rules_jvm_external hub of a Bazel workspace //! builds and whose entry cannot be written there (the `maven_bazel_*` diff --git a/docs/configuration.md b/docs/configuration.md index bdd138dd4..4cca0f4c5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -79,6 +79,14 @@ Empty environment values are treated as unset. Enterprise customers and may change in any release: ask Socket for the setup guide. The rules are in the [CLI contract](../crates/socket-patch-cli/CLI_CONTRACT.md#patch-mirror-experimental). +- `SOCKET_NO_BAZEL=1` (experimental, like the Bazel support it switches off) is + for a project that sits in a checkout with a Bazel workspace file and that + Bazel does not build. Every command then treats the project as one in no + Bazel workspace. It takes `1`, `true`, `yes`, `on`, `y` or `t`, has no flag, and + is inherited by the programs socket-patch starts. It is for the whole run: + set it for runs in that project's directory, not for a run over a checkout + that also holds projects Bazel builds. See + [Bazel workspaces: a project that Bazel does not build](ecosystems.md#bazel-workspaces-a-project-that-bazel-does-not-build). - `--offline` prohibits network access. `scan` and `get` require the patch API and refuse offline operation. Other commands can use locally available state; missing records or artifacts can still prevent completion. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1388da628..90cbd6abc 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2265,18 +2265,23 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil rule runs in another directory fails the build with `Source path ... is not found`. Run `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. A test of this repository builds that failure on the three Bazel releases. -- **Hosted Cargo on a hub without `cargo_config`**, which is the hub as the rules_rust README - shows it: the hub's cargo does not see the patch registry that `.cargo/config.toml` defines - (`registry index was not found in any configuration`). Add - `cargo_config = "//:.cargo/config.toml"` to the `crate.from_cargo` call and commit that - file, or use vendored mode, or run `socket-patch rollback`. +- **A hosted Cargo pin that is already in the files, on a hub without `cargo_config`**, which + is the hub as the rules_rust README shows it: the hub's cargo does not see the patch + registry that `.cargo/config.toml` defines + (`registry index was not found in any configuration`). Hosted mode writes no such pin any + more (see the next list), and it leaves one that is there as it is and reports it applied. + Add `cargo_config = "//:.cargo/config.toml"` to the `crate.from_cargo` call and commit that + file, or run `socket-patch rollback`. - **Cargo on a hub with a cargo-bazel lock** (`lockfile`), in hosted and vendored mode: the build stops at ``The current `lockfile` is out of date`` until the repin that message names (`CARGO_BAZEL_REPIN=true bazel build ...`). After it the build is the patched one; in hosted mode the hub needs `cargo_config` as well. -- **Hosted NuGet on a tag without `nuget_config`**: Bazel asks nuget.org alone and the - package fails the lock (`does not match its contentHash in packages.lock.json`). Give the - tag `nuget_config = "//:nuget.config"` and commit that file, which is the shape the table +- **A hosted NuGet pin that is already in the files, under a tag without `nuget_config`**: + Bazel asks nuget.org alone and the package fails the lock + (`does not match its contentHash in packages.lock.json`). Hosted mode writes no such pin + any more (see the next list), and it leaves one that is there as it is and warns + (`redirect_bazel_nuget_config_undeclared`). Give the tag + `nuget_config = "//:nuget.config"` and commit that file, which is the shape the table lists; or run `socket-patch rollback`, which restores the lock and leaves the `nuget.config` it created behind. - **`rollback` of a hosted gem whose `gem_checksums` entry you changed** to the sha256 of @@ -2311,6 +2316,16 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil In these a command exits 0 and the Bazel build passes on the unpatched package: +- **Hosted Cargo on a hub without `cargo_config`.** The hub's cargo would not see the patch + registry, so hosted mode writes nothing for the crate and warns + (`redirect_cargo_bazel_config_unread`). Commit `.cargo/config.toml`, add + `cargo_config = "//:.cargo/config.toml"` to the `crate.from_cargo` call and run the command + again, or use vendored mode: see [Bazel workspaces: Cargo](#bazel-workspaces-cargo). +- **Hosted NuGet on a tag without `nuget_config`.** Bazel would ask nuget.org alone, so + hosted mode writes nothing for the package and warns + (`redirect_bazel_nuget_config_undeclared`). Give the tag + `nuget_config = "//:nuget.config"` and run the command again: see + [Bazel workspaces: NuGet](#bazel-workspaces-nuget). - **Hosted NuGet on a machine without a restore.** `scan` reads no package out of `packages.lock.json`, so where only Bazel ever ran it finds none and writes nothing. Run it where `dotnet restore` has run. @@ -2326,10 +2341,14 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: And three that concern neither: -- **Vendored Cargo under rules_rust 0.75.0**: a build writes a `BUILD.bazel` into the - committed copy, and right after it `vendor --check` exits 1 (`vendor_inventory_mismatch`) - and `vex` writes no document, although the build is the patched one. A second - `scan --mode vendored` puts the copy right. +- **Vendored Cargo under rules_rust 0.75.0, with the `.bazelignore` line of the copies + commented out**: a build writes a `BUILD.bazel` into the committed copy, and right after it + `vendor --check` exits 1 (`vendor_inventory_mismatch`) and `vex` leaves the patch out, + although the build is the patched one. A second `scan --mode vendored` puts the copy right. + Under the line, which the scan writes, that file is no change of the copy: the check passes + and `vex` attests the crate. See + [Bazel workspaces: the build file in a vendored crate](#bazel-workspaces-the-build-file-in-a-vendored-crate) + for the other cases without the line. - **`vex` for a hosted NuGet patch**, on a machine whose NuGet folder still holds the unpatched package, as the one that ran the scan does: it writes no document and exits 1 (`not_applied`), although the Bazel build is the patched one. Where that folder holds @@ -2338,6 +2357,78 @@ And three that concern neither: asks the Socket source for every package of the lock, and Bazel prints a warning with that source's URL, the token in it, for each package the source does not hold. +### Bazel workspaces: a project that Bazel does not build + +Whether Bazel builds a project is not in the checkout's files. socket-patch takes every project +for one of a Bazel workspace when its directory, or one above it up to the root of its git +checkout, holds a Bazel workspace file +([the lookup](#bazel-workspaces-bazelignore)): a PHP or Maven service of a monorepo whose other +parts Bazel builds, and a checkout that kept a `WORKSPACE` file from a trial, are such +projects too. What the sections below then do for it: + +- Composer: vendored mode is declined until the lock names a vendored copy + ([Bazel workspaces: Composer](#bazel-workspaces-composer)). +- Go, Cargo and Maven: the `.bazelignore` at the Bazel root gets two lines for each kind of + copy under `.socket` that a run wrote: the Go module copies, the vendored crates of a crate + hub, the jars that vendored mode keeps for a rules_jvm_external hub + ([Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore)). +- npm: hosted mode writes nothing for a root pnpm lock whose rules_js hub may hide + `pnpm-workspace.yaml` from its pnpm, and does not route a pnpm lock that a hub reads, or + may read, through a named registry ([Bazel workspaces: npm](#bazel-workspaces-npm)). +- Hosted mode leaves a crate, a NuGet package or a gem unpinned, with a warning, when a hub + call of the workspace may read the project's lock and is not written out plainly. +- Maven: hosted and vendored mode patch a pinned rules_jvm_external hub that builds the + artifact, with an entry in the root `MODULE.bazel` (vendored mode also commits the jar + under `.socket/vendor/maven/`), and a run that does not patch such a hub says so, per + patch, when the hub builds the artifact, or may + ([Bazel workspaces: Maven](#bazel-workspaces-maven)). +- VEX: a package is attested `affected` when a hub call names the project's lock. + +`SOCKET_NO_BAZEL=1` in the environment switches all of it off (`1`, `true`, `yes`, `on`, `y` +or `t`, in any case, as for the other switches that are read from the environment alone; an +empty or any other value does not). Every command then does what it does for a project in no +Bazel workspace: the same files, the same output, the same exit code, and no word about the +variable. The in-memory engine asks its host for no Bazel file. A program that socket-patch +starts inherits the variable, so a socket-patch which that program starts (a hook of a +package manager) does the same. There is no flag for it: `vex --no-bazel` is the VEX +step's own option and switches nothing else off. Set it only for a project that Bazel does +not build. For one that Bazel builds, what it switches off is what keeps a command that exits +0 from leaving a build that fails, or one that is not patched. + +The variable is for the whole run, and whether Bazel builds a project is a fact of each +project. A bare `scan` covers every project of a checkout, so with the variable set a project +that Bazel does build is treated the same: it loses every guard above, and the run still +exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a +run over a checkout that also holds projects Bazel builds. There is no setting per project. + +A Maven patch shows what that means. With the variable set, `vendor` beside a Maven or Gradle +build vendors for that build alone, as in a checkout without the workspace file: it edits the +poms, writes the tree under `.socket/vendor/`, exits 0, writes nothing for a hub and says +nothing of one. A Bazel build that is there after all then keeps the upstream jar of a patch +the run reported as vendored. In a checkout that only Bazel builds, `vendor` refuses the patch +for want of a build (`vendor_jvm_shape_unsupported`), as in any tree without a `pom.xml` or a +Gradle build, and a hosted run leaves it unpinned. + +What an earlier run wrote for Bazel is still listed and undone with the variable set: + +- The block that hosted and vendored mode keep in the root `MODULE.bazel` + ([Bazel workspaces: Maven](#bazel-workspaces-maven)): `list`, `vex`, a scan, `vendor --check` + and `repair` read its entries as they do without the variable, an entry of hosted mode as a + hosted pin and one of vendored mode as the wiring of the jar committed under + `.socket/vendor/maven//`. An entry that no pinned hub takes any more still + attests nothing in `vex`, and `vendor --check` still names a vendored one. `rollback` + and `remove` take a hosted entry out; they and `vendor --revert` take a vendored entry out + with its directory and its ledger entry, and the checkout is as it was before the patch. + `repair` puts back a lost directory of a patch that only a hub takes. No entry is written or + replaced: `vendor` leaves a hosted entry where it is, a hosted run leaves a patch that + vendored mode keeps for a hub alone vendored, and a hosted scan takes no stale entry out. + Beside a Maven or Gradle build the hub's directory is a copy that only a `vendor` run + without the variable writes: one that was lost stays lost, `vendor --check` names it, and + the undo still takes its entry out. +- The `.bazelignore` lines: no pair is added, and the pair of a copy that is gone is removed + by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a + scan). + ## Bazel workspaces: npm aspect_rules_js reads the pnpm lock itself, so a hosted pin in `pnpm-lock.yaml` is what the @@ -2685,7 +2776,10 @@ repository has no known name is a package too: a patch found for it gets no entr ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, or a `maven_install.json` lies at the Bazel root. In another Bazel workspace a file that cannot be read is about no hub, and the scan is the one - without the workspace. + without the workspace. The block of hosted mode in `MODULE.bazel` is a fourth such sign. A + hub that is declared only in a file that could not be read, in a workspace with none of + the four, is not scanned, and the scan does not say so: `get --mode hosted` and + `apply` warn there (`maven_bazel_unreadable` below). - **How much is read.** A scan takes its packages from up to 64 MiB of hub locks in one workspace. The first lock that does not fit is not taken, no lock after it is read, and the warning above names it ("the locks of the workspace are larger than 64 MiB in all"). That @@ -2778,6 +2872,15 @@ artifact: - `maven_bazel_unreadable`: whether a hub builds the jar could not be told, for one of the reasons above that concern reading the hubs. The warning names the file, the line and the reason. +- Nothing is said, in any mode, of a jar that no hub fetches in a workspace that has nothing + to do with the ruleset (the four signs under "What was not read" above) and whose files + were all read: there an `include` of a file that does not exist, and a statement other than + an `include` that the reader does not follow, are about no hub, and the run is the one + without the workspace. A file that is there and was not read as a whole (not UTF-8, over + 1 MiB, a link out of the workspace, text the reader cannot parse, a `WORKSPACE` file that + cannot be read) may be the one that names the ruleset, and keeps the warning. So does the + file of an `include` that the reader does not follow: Bazel 9 takes + `include("//:x.MODULE.bazel", dev_dependency = True)`, and that file is not read. - Nothing is said for a jar the block patches, under `--global`, and by a `vendor` whose `--ecosystems` leaves Maven out. @@ -3227,8 +3330,9 @@ adds no line. What the line is for, measured with rules_rust 0.75.0 on Bazel 9.3 tags the crate's library so). That package names repositories only the hub sees, so for a vendored crate with a dependency the commands that analyse every target fail on it: `bazel cquery //...` and `bazel query 'deps(//...)'` end with `No repository visible as - '@crates__' from main repository`. With the line both pass, and `//...` holds - your own targets alone. + '@crates__' from main repository`, or with the same words about `@platforms`, + which the file names too: Bazel reports the first of the two that it meets. With the line + both pass, and `//...` holds your own targets alone. **Under that line, the file is no change of the copy.** `vendor --check` passes, `vex` attests the crate, `repair` has nothing to restore, and a second `scan --mode vendored` @@ -3397,7 +3501,13 @@ line all the same, so that they cannot break the workspace. A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout, holds a regular file `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel` -(the names Bazel itself looks for); the nearest such directory is the Bazel root. The checkout +(the names Bazel itself looks for); the nearest such directory is the Bazel root. On a disk +that folds case a regular file named `workspace` or `Module.bazel` counts too, as it does for +Bazel itself; +[`SOCKET_NO_BAZEL=1`](#bazel-workspaces-a-project-that-bazel-does-not-build) is the way out +for a checkout where such a file is no workspace. No project is in a Bazel workspace for a +run with that variable, which adds no line and still takes away the pair of a copy that is +gone. The checkout is the one the `socket.yml` lookup takes for the repository root: on Unix its `.git` belongs to you, to root, or to the user `sudo` ran for (a root process takes any owner's). A project in no such checkout is looked for in its own directory only: nothing above it is read or written. In @@ -3728,17 +3838,28 @@ socket-patch checks none of these. The switch is not Composer's alone: it lets v write for any package it would decline because the project is in a Bazel workspace, where the build may not find the vendored copy. The Composer refusal is the only such refusal today. -`vendor --revert` is never declined. Neither is a package that is already vendored: where -`composer.lock` already names the copy of the same patch, a vendored run leaves the lock as it -is. So a project that was vendored with the flag, or by an earlier release, keeps passing its -runs without the flag, a `scan` or `get` with no `--mode` included, which runs in vendored mode -there. A new patch for that package, or another package, is declined until the run has the -flag. +`vendor --revert` is never declined. Neither is a package of a project that uses vendored +mode already, by a release before this refusal or with the flag: + +- any package, once `packages` of `composer.lock` names a copy under `.socket/vendor/composer`; +- a package of `packages-dev`, once `packages-dev` names one. + +Every later run for such a package goes on without the flag: a newer patch, the first patch of +another package, and a `scan` or `get` with no `--mode`, which runs in vendored mode there. +This is safe by the rule above. Either no Bazel rule installs from that lock, and then +vendored mode works there as it did before the refusal existed; or one does, and its build +already fails on a path in a section it installs, which one more path there does not change. +The section matters because a rule may run `composer install --no-dev`, which reads `packages` +alone: while only `packages-dev` names a copy, such a build passes, and a package of +`packages` is declined until the run has the flag. `vendor --revert` takes every such path +out again, and the next vendored run is then declined like a first one. Limits: - A project in a Bazel workspace that Bazel does not build, and one that commits its `vendor/` - tree, are declined like any other until they have the flag. + tree, are declined like any other until their lock names a vendored copy as above, or the + run has the flag or + [`SOCKET_NO_BAZEL`](#bazel-workspaces-a-project-that-bazel-does-not-build). - A Bazel root that the lookup does not reach is not seen, and vendored mode goes on there as before: one above the git checkout (a project that is a checkout of its own, such as a submodule, in a Bazel repository), one above a project that is in no checkout or whose diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 2be5dcf83..540b6c18a 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3917 + "max": 3953 }, "lock-readers": { "paths": [