Skip to content

Add empty InlineScriptEnvManager skeleton behind internal flag (PEP 723 PR 4/16)#1610

Merged
StellaHuang95 merged 1 commit into
microsoft:mainfrom
StellaHuang95:pep723-pr4-manager-skeleton
Jun 24, 2026
Merged

Add empty InlineScriptEnvManager skeleton behind internal flag (PEP 723 PR 4/16)#1610
StellaHuang95 merged 1 commit into
microsoft:mainfrom
StellaHuang95:pep723-pr4-manager-skeleton

Conversation

@StellaHuang95

@StellaHuang95 StellaHuang95 commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Part of #1602 (PEP 723 inline script env support). Design doc: #1601.

Roadmap context — where this PR sits

This is PR 4 of 16 in the PEP 723 inline-script roadmap. The full plan lives in #1602; here's a one-line summary of where each PR sits relative to this one:

Phase PR Status
Phase 1 — Foundation PR 1: cache key hash utility in progress
PR 2: cache layout + meta.json sidecar in progress
PR 3: requires-python → interpreter selection in progress
Phase 2 — Manager PR 4: InlineScriptEnvManager skeleton this PR
PR 5: create() happy path not started (needs 1, 2, 3, 4)
PR 6: create() uv-install fallback not started (needs 3, 5)
PR 7: persistence — get / set + Memento not started (needs 4)
PR 8: activation-time discovery not started (needs 2, 4, 7)
Phase 3 — Routing PR 9: route PEP 723 scripts to inline manager not started (needs 4, 7)
PR 10: per-script project registration not started (needs 9)
Phase 3.5 — Cross-repo PR 17 (pyrx), PR 18 (pyrx), PR 19 (vscode-python) not started
Phase 4 — UX PR 11: picker item, PR 12: bulk command not started
Phase 5 — Lifecycle & polish PR 13: clear cache, PR 14: TTL, PR 15: telemetry, PR 16: status bar not started

After PRs 1–4 merge, PR 7 unlocks the largest downstream wave (PR 8, 9, 13, 17, 19) — see the ordering comment on #1602 for the full timeline.

Why a skeleton

The roadmap rolls out across 16 PRs. Landing each one behind a feature gate keeps main shippable at every step and lets reviewers see one concern at a time. This PR is the smallest possible mount point for that gate: an EnvironmentManager implementation that satisfies the interface contract and registers cleanly, but otherwise does nothing.

Every subsequent PR (5–8) replaces one of the no-ops in this skeleton with the real thing.

What this PR does

  1. Adds InlineScriptEnvManager (src/managers/builtin/inlineScriptEnvManager.ts) — implements EnvironmentManager:

    • Metadata: name = "inline-script", displayName = "Inline script environments", iconPath = file-code, preferredPackageManagerId = "ms-python.python:pip".
    • Methods: getEnvironments returns [], get / resolve return undefined, set / refresh are no-ops.
    • Optional methods omitted: create, remove, quickCreateConfig are deliberately not declared so the picker UI hides their entry points until PR 5 lands them.
    • Events: both onDidChangeEnvironments and onDidChangeEnvironment exposed and disposed correctly; never fired by this skeleton.
  2. Adds registerInlineScriptFeatures (src/managers/builtin/inlineScriptMain.ts) — a gated registration helper that reads the internal flag and registers the manager only when on. Wired into the existing Promise.all of manager-registration tasks in extension.ts (alongside system, conda, pyenv, pipenv, poetry, shellStartupVars).

  3. Adds isInlineScriptsFeatureEnabled (src/helpers.ts) — reads python-envs.inlineScripts.enabled. The setting is intentionally NOT declared in package.json, so it does not appear in Settings UI, JSON autocomplete, or settings search. End users never discover it. Devs / CI can opt in by manually adding it to settings.json. Default value false. Gate goes away in PR 16.

User impact

Zero. The feature flag is undeclared in package.json, so:

  • No setting visible in Settings UI search.
  • No autocomplete entry when typing python-envs. in settings.json.
  • No "Preview" badge or any indication the feature exists.
  • No new picker section, no commands, no status-bar changes.
  • No log output on the default level (gate-off path uses traceVerbose).

PR 5–15 will all land behind the same gate; PR 16 removes the gate and declares the public setting for real.

… 4/16)

First PR in Phase 2 of the inline-script roadmap. Lands the empty
manager class and a registration helper gated behind an INTERNAL
flag, so the plumbing for PRs 5-16 can land incrementally without
any user-visible surface.

What is in:

- src/managers/builtin/inlineScriptEnvManager.ts (new)
  Class implementing EnvironmentManager: name="inline-script",
  displayName="Inline script environments", iconPath=file-code,
  preferredPackageManagerId="ms-python.python:pip". Every method is
  a sentinel: getEnvironments returns [], get returns undefined,
  set / refresh are no-ops, resolve returns undefined. Optional
  methods (create, remove, quickCreateConfig) are deliberately
  omitted so the UI hides their entry points until PR 5 lands them.

- src/managers/builtin/inlineScriptMain.ts (new)
  registerInlineScriptFeatures(disposables, log) -- gated
  registration helper. Reads isInlineScriptsFeatureEnabled() and
  returns early (with a traceVerbose, not traceInfo, so no per-
  activation log noise for default users) when the flag is false.
  When true, constructs the manager and registers it.

- src/helpers.ts
  isInlineScriptsFeatureEnabled(): boolean -- reads
  python-envs.inlineScripts.enabled via getConfiguration().get(...).
  The setting is INTENTIONALLY NOT DECLARED in package.json, so:
    - it does not appear in Settings UI
    - it does not appear in JSON autocomplete
    - it does not appear in settings search
    - end users never discover it
  Devs / CI can still opt in by manually adding it to settings.json
  (VS Code will mark it as an unknown setting with a yellow squiggle
  -- that is a feature, not a bug; signals you are on an internal
  flag). The whole gate goes away in PR 16 when the feature ships
  for real.

- src/extension.ts
  Wires registerInlineScriptFeatures into the existing
  Promise.all of manager-registration tasks, alongside system,
  conda, pyenv, pipenv, poetry, and shellStartupVars.

- src/test/managers/builtin/inlineScriptEnvManager.unit.test.ts (new)
  19 tests pinning the skeleton's no-op contract: static metadata,
  all five EnvironmentManager methods, optional methods correctly
  omitted, events exposed but never fired, dispose() is idempotent.

- src/test/managers/builtin/inlineScriptMain.unit.test.ts (new)
  2 tests pinning the gate itself: flag false -> no register call,
  no getPythonApi call, no disposable pushed; flag true -> exactly
  one register call, two disposables pushed (mgr + registration
  handle). These guard the entire "zero user impact" promise
  against future refactors.

- src/test/helpers.inlineScriptsFeature.unit.test.ts (new)
  3 tests covering the feature-flag helper: defaults to false,
  returns true on user-set, reads from the python-envs section.

User impact

Zero. No setting in package.json, so:
- No setting visible in Settings UI search
- No autocomplete entry when typing "python-envs..." in settings.json
- No "Preview" badge or any indication the feature exists
- No empty picker section, no commands, no status-bar changes
- No log output on the default log level

PR 5-15 will land on top of this gate; PR 16 removes the gate and
declares the public setting for real.

Design context

Implements PR 4 in Phase 2 of pep723_design_questions.md. The
internal-flag approach (undeclared setting) is the strictest
interpretation of "zero user impact during incremental rollout" --
discussed in the planning conversation as the alternative to a
declared-but-default-false setting (which would still show in
autocomplete and confuse early adopters).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@StellaHuang95 StellaHuang95 added the feature-request Request for new features or functionality label Jun 24, 2026
@StellaHuang95
StellaHuang95 requested review from edvilme and eleanorjboyd and removed request for edvilme June 24, 2026 23:09
@StellaHuang95
StellaHuang95 enabled auto-merge (squash) June 24, 2026 23:33

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we maybe have it under src/managers/builtin/inlineScriptEnvManager/inlineScriptEnvManager.ts and src/managers/builtin/inlineScriptEnvManager/main.ts ?

l10n.t('Environments built from PEP 723 inline script metadata.'),
true,
);
public readonly iconPath: IconPath = new ThemeIcon('file-code');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice touch :)

@StellaHuang95
StellaHuang95 merged commit 707f2a8 into microsoft:main Jun 24, 2026
45 of 46 checks passed
StellaHuang95 added a commit that referenced this pull request Jul 21, 2026
> Part of #1602 (PEP 723 inline script env support). Design doc: #1601.

### Roadmap context

This is **PR 1 of 16** in the PEP 723 inline-script roadmap. The full
plan lives in #1602.

| Phase | PR | Status |
|---|---|---|
| **Phase 1: Foundation** | **PR 1: cache key hash utility** | **this
PR** |
| | PR 2: cache layout + `meta.json` sidecar | _in progress_ |
| | PR 3: `requires-python` to interpreter selection | _in progress_ |
| **Phase 2: Manager** | PR 4: `InlineScriptEnvManager` skeleton |
merged (#1610) |
| | PR 5: `create()` happy path | not started (needs 1, 2, 3, 4) |
| | PR 6: `create()` uv-install fallback | not started (needs 3, 5) |
| | PR 7: persistence with `get`, `set`, and Memento | _in progress_
(needs 4) |
| | PR 8: activation-time discovery | not started (needs 2, 4, 7) |
| **Phase 3: Routing** | PR 9: route PEP 723 scripts to the inline
manager | not started (needs 4, 7) |
| | PR 10: per-script project registration | not started (needs 9) |
| **Phase 3.5: Cross-repo** | PRs 17-19: Pylance and vscode-python
integration | not started |
| **Phase 4: UX** | PR 11: picker item; PR 12: bulk command | not
started |
| **Phase 5: Lifecycle and polish** | PR 13: clear cache; PR 14: TTL; PR
15: telemetry; PR 16: status bar | not started |

PRs 1-3 are independent Phase 1 utilities that PR 5 will compose when it
implements the environment creation path.

### Why this PR

The cache key decides whether a PEP 723 script reuses an existing
environment or builds a fresh one. Under the dependency-keyed design
from Q4 of #1601, scripts using the same dependencies and interpreter
should share an environment.

Trivial metadata edits such as changing package-name casing, separator
style, whitespace, dependency order, or extras order should not fragment
the cache.

This PR isolates that logic as pure functions with no filesystem access,
global storage dependency, or extension activation behavior. The on-disk
cache layout remains separate in PR 2.

### What this PR does

Adds `src/common/inlineScriptCacheKey.ts` with four exports:

1. **`normalizeDependency(dep)`**

   Canonicalizes common variants of the same requirement:

- Applies PEP 503 normalization to project names and extras: lowercase
and collapse runs of `.`, `_`, and `-` to a single `-`.
   - Sorts and deduplicates extras after normalization.
   - Removes whitespace around version comparison operators.
   - Preserves meaningful version and marker content.
   - Drops empty dependency entries when keys are computed.

   Examples:

   - `Django` and `django` normalize identically.
- `Flask-Login`, `flask_login`, and `flask.login` normalize identically.
   - `requests[Socks,security]` becomes `requests[security,socks]`.
   - `requests < 3` becomes `requests<3`.

This is intentionally not a complete PEP 508 parser. Inputs it cannot
meaningfully parse remain deterministic without attempting semantic
normalization.

2. **`normalizeInterpreterPath(interpreterPath)`**

Uses the existing `normalizePath` helper so Windows path casing and
separator differences do not fragment the cache. POSIX path casing
remains unchanged.

3. **`computeCacheKey({ dependencies, interpreterPath })`**

   - Normalizes, deduplicates, and sorts dependencies.
   - Normalizes the interpreter path.
   - Builds a versioned, labelled payload.
   - Hashes the payload with SHA-256.
   - Returns the first 16 lowercase hexadecimal characters.

The resulting key is deterministic and safe to use as a directory name
under the cache root introduced by PR 2.

4. **`CACHE_KEY_HEX_LENGTH`**

Exposes the key length so callers and tests do not duplicate the value
`16`.

### Caller contract

`interpreterPath` must be absolute, trimmed, and already resolved
through symlinks, for example with `fs.realpath()`.

The utility deliberately performs no I/O. Two different path strings
that resolve to the same executable will therefore produce different
keys unless the caller canonicalizes them first. The creation flow in PR
5 will own that resolution.

### Cache behavior

The script path and raw `requires-python` value are intentionally not
included directly in the key.

- Two scripts with equivalent dependencies and the same selected
interpreter share an environment.
- Moving or renaming a script does not invalidate its environment.
- Adding, removing, or repinning a dependency produces a new key.
- Selecting a different interpreter produces a new key.
- A later PR re-verifies `requires-python` on cache hits in case the
constraint changes without changing the selected interpreter.

This supports the design's two outcomes: reuse an unchanged cache entry
or build a fresh environment. There is no in-place dependency
synchronization path.

### Tests

Adds `src/test/common/inlineScriptCacheKey.unit.test.ts` with 37 unit
tests covering:

- PEP 503 project-name normalization.
- Extras normalization, sorting, deduplication, and whitespace handling.
- Version comparison operators and multi-clause specifiers.
- Empty and duplicate dependency entries.
- Dependency ordering and deterministic output.
- Inputs that should and should not change the key.
- Windows and POSIX interpreter-path behavior.
- Fixed-length lowercase hexadecimal output.
- Filesystem-safe output.
- Pinned caller-contract behavior such as trailing whitespace in
interpreter paths.

Platform behavior is stubbed through `platformUtils`, keeping the suite
independent of the host operating system.

### User impact

**Zero.**

Nothing in the extension calls these helpers yet. This PR adds no
settings, commands, UI, logging, filesystem writes, or activation
behavior. The utility is wired into environment creation in PR 5.

### Design context

This implements the cache-key portion of Q4 in #1601: a pipx-style cache
keyed by normalized dependencies and the selected interpreter.

PEP 503 normalization for project names and extras was added in response
to review feedback on the design PR.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
StellaHuang95 added a commit that referenced this pull request Jul 21, 2026
…guard (PEP 723 PR 2/16) (#1635)

> Part of #1602 (PEP 723 inline script env support). Design doc: #1601.

### Roadmap context

This is **PR 2 of 16** in the PEP 723 inline-script roadmap. The full
plan lives in #1602.

| Phase | PR | Status |
|---|---|---|
| **Phase 1: Foundation** | PR 1: cache key hash utility | in review
(#1634) |
| | **PR 2: cache layout + `meta.json` sidecar** | **this PR** |
| | PR 3: `requires-python` to interpreter selection | _in progress_ |
| **Phase 2: Manager** | PR 4: `InlineScriptEnvManager` skeleton |
merged (#1610) |
| | PR 5: `create()` happy path | not started (needs 1, 2, 3, 4) |
| | PR 6: `create()` uv-install fallback | not started (needs 3, 5) |
| | PR 7: persistence with `get`, `set`, and Memento | _in progress_
(needs 4) |
| | PR 8: activation-time discovery | not started (needs 2, 4, 7) |
| **Phase 3: Routing** | PR 9: route PEP 723 scripts to the inline
manager | not started (needs 4, 7) |
| | PR 10: per-script project registration | not started (needs 9) |
| **Phase 3.5: Cross-repo** | PRs 17-19: Pylance and vscode-python
integration | not started |
| **Phase 4: UX** | PR 11: picker item; PR 12: bulk command | not
started |
| **Phase 5: Lifecycle and polish** | PR 13: clear cache; PR 14: TTL; PR
15: telemetry; PR 16: status bar | not started |

PRs 1-3 are independent Phase 1 utilities that PR 5 will compose when it
implements the environment creation path.

### Why this PR

Q2 and Q3 of #1601 place inline-script environments under
`<globalStorageUri>/script-envs-v1/<cache-key>/` and give each
environment a `.meta.json` sidecar for lifecycle bookkeeping. Those
contracts need to exist before the manager can create, discover, reuse,
or clean up cached environments.

This PR also implements the cache-hit usability guard from Q4 step 4.
Hashing the selected interpreter path catches a switch to a different
Python path, but it does not catch an interpreter being uninstalled from
the same path. The guard detects that stale cache state before the
extension attempts to reuse a broken environment.

The filesystem concerns are kept separate from PR 1's pure hashing logic
and PR 3's interpreter-selection logic.

### What this PR does

Adds `src/common/inlineScriptCacheLayout.ts` with cache path helpers,
typed sidecar I/O, stale-entry selection, and an environment-usability
check.

#### Cache layout

- `getScriptEnvCacheRoot(globalStorageUri)` returns
`<globalStorageUri>/script-envs-v1/`.
- `getScriptEnvDir(globalStorageUri, cacheKey)` returns the directory
for one cached environment.
- `getMetaJsonPath(envDir)` returns `<envDir>/.meta.json`.
- `INLINE_SCRIPT_CACHE_DIR_NAME`, `META_JSON_FILENAME`, and
`META_SCHEMA_VERSION` centralize the on-disk contract.

The cache directory and metadata schema are both versioned. An
incompatible future format should bump the cache directory suffix and
schema version together rather than migrate environments in place.

#### Typed `.meta.json` sidecar

`InlineScriptEnvMeta` contains the fields with concrete downstream
consumers:

- `schemaVersion`: validates the sidecar format.
- `scriptFsPath`: identifies the owning script for lifecycle cleanup.
- `lastUsedAt`: drives TTL eviction.
- `requiresPython?`: supports compatibility revalidation on cache hits.

`readMetaJson(envDir)` never throws. It returns `undefined` with a
warning for missing or non-regular files, files larger than 1 MiB,
malformed JSON, unknown schema versions, invalid field types, and
non-canonical ISO timestamps. Unknown properties are dropped when the
validated object is constructed.

`writeMetaJson(envDir, meta)` ensures the directory exists, writes
formatted JSON to a randomized sibling temporary file, and atomically
renames it to `.meta.json`. If writing or renaming fails, it attempts to
remove the temporary file and rethrows the original error.

#### TTL selection

`selectStaleEntries(entries, now, ttlMs)` is a pure selector used by the
future opportunistic cleanup path.

- An entry is stale only when its age is strictly greater than the TTL.
- Entries exactly at the TTL boundary are retained.
- Future timestamps are retained.
- Entries without `lastUsedAt` are retained because the extension should
not delete data it cannot classify confidently.

The function returns paths to delete; it performs no filesystem walk or
deletion itself.

#### Cache-hit usability guard

`verifyEnvUsable(envDir)` checks whether the cached environment still
has a usable base interpreter. It never throws; failures produce a
warning and return `false`.

- **POSIX:** stats `<envDir>/bin/python`. Because `fs.stat` follows
symlinks, a dead launcher symlink is detected.
- **Windows:** reads `home = ...` from `pyvenv.cfg` and stats
`<home>/python.exe`. Checking `<envDir>/Scripts/python.exe` would be
insufficient because that launcher can remain after the base Python is
uninstalled.

This covers common removal paths such as `pyenv uninstall`, `uv python
uninstall`, Homebrew or apt removal, and Windows Add/Remove Programs.

### Failure policy

The helpers distinguish recoverable cache state from creation-time
failures:

- Metadata reads and usability checks return `undefined` or `false`
rather than throwing, allowing callers to treat invalid cache state as a
miss.
- Metadata writes rethrow because a caller must know that newly created
state was not recorded successfully.
- The TTL selector is pure and cannot delete anything by itself.

### Tests

Adds `src/test/common/inlineScriptCacheLayout.unit.test.ts` with 44
focused unit tests covering:

- Cross-platform cache and sidecar path construction.
- Metadata write/read round trips and concurrent writers.
- Atomic write behavior and temporary-file cleanup.
- Missing, malformed, oversized, and structurally invalid sidecars.
- Schema-version and canonical-timestamp validation.
- TTL boundaries, future timestamps, and missing `lastUsedAt` values.
- POSIX launchers, live symlinks, dead symlinks, and non-file paths.
- Windows `pyvenv.cfg` parsing and missing base interpreters.

Required checks pass on this branch:

- `npm run lint`
- `npm run compile-tests`
- `npm run unittest`: 1418 passing, 0 failing, 4 pending

### User impact

**Zero.**

Nothing in the extension calls these helpers yet. This PR creates no
environments, writes nothing to global storage during activation,
deletes no cache entries, and adds no settings, commands, UI, or logging
on the default execution path.

PR 5 will use the layout and sidecar helpers during creation. PRs 7 and
8 will use them during reuse and activation-time discovery. PRs 13 and
14 will use the cleanup helpers.

### Design context

This implements Q2 (disk location), Q3 (environment contents and sidecar
metadata), Q4 step 4 (base-interpreter existence guard), and the pure
selection portion of Q7 (TTL cleanup) from #1601.

The base-interpreter guard was added in response to review feedback on
the design PR.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
StellaHuang95 added a commit that referenced this pull request Jul 21, 2026
)

> Part of #1602 (PEP 723 inline script env support). Design doc: #1601.

### Roadmap context

This is **PR 3 of 16** in the PEP 723 inline-script roadmap. The full
plan lives in #1602.

| Phase | PR | Status |
|---|---|---|
| **Phase 1: Foundation** | PR 1: cache key hash utility | in review
(#1634) |
| | PR 2: cache layout + `meta.json` sidecar | in review (#1635) |
| | **PR 3: `requires-python` to interpreter selection** | **this PR** |
| **Phase 2: Manager** | PR 4: `InlineScriptEnvManager` skeleton |
merged (#1610) |
| | PR 5: `create()` happy path | not started (needs 1, 2, 3, 4) |
| | PR 6: `create()` uv-install fallback | not started (needs 3, 5) |
| | PR 7: persistence with `get`, `set`, and Memento | _in progress_
(needs 4) |
| | PR 8: activation-time discovery | not started (needs 2, 4, 7) |
| **Phase 3: Routing** | PR 9: route PEP 723 scripts to the inline
manager | not started (needs 4, 7) |
| | PR 10: per-script project registration | not started (needs 9) |
| **Phase 3.5: Cross-repo** | PRs 17-19: Pylance and vscode-python
integration | not started |
| **Phase 4: UX** | PR 11: picker item; PR 12: bulk command | not
started |
| **Phase 5: Lifecycle and polish** | PR 13: clear cache; PR 14: TTL; PR
15: telemetry; PR 16: status bar | not started |

PRs 1-3 are independent Phase 1 utilities that PR 5 will compose when it
implements the environment creation path.

### Why this PR

Before the inline-script manager can create an environment, it needs to
answer two questions from Q4 of #1601:

1. Which installed base interpreter is the newest one compatible with
the script's `requires-python` declaration?
2. If none is compatible, what lower-bound version can the existing uv
installation flow request?

Both decisions are pure functions over an environment list and a PEP 440
specifier. Keeping them outside the manager makes the filtering,
ranking, and fallback rules independently testable without environment
discovery, UI, filesystem access, or process execution.

### What this PR does

Adds `src/common/inlineScriptInterpreter.ts` with two exported helpers.

#### `pickCompatibleInterpreter(installed, requiresPython)`

Filters the supplied environments and returns the newest usable Python 3
interpreter satisfying the script's constraint.

A candidate is rejected when:

- `env.error` is set.
- `env.version` is missing, empty, or does not begin with numeric
release segments.
- The interpreter is not Python 3.
- The version does not satisfy `requiresPython` according to the
existing `matchesPythonVersion` helper.

An undefined, empty, or whitespace-only constraint is treated as
unconstrained. If no candidate qualifies, the function returns
`undefined` so the creation flow can offer the uv fallback.

Candidates are ranked by numeric release segments in descending order. A
leading `v` is tolerated, and prerelease, development, and local
suffixes are ignored for ranking. Ties preserve input order. The input
array is copied before sorting and is never mutated.

Examples:

- No constraint across Python 3.10, 3.11, and 3.12 selects 3.12.
- `>=3.11,<3.13` selects the newest interpreter within that range.
- `==3.12.*` uses the existing wildcard-matching semantics.
- `~=3.12.4` honors the compatible-release upper bound.
- If only Python 2, broken environments, or incompatible versions are
available, the result is `undefined`.

#### Base-interpreter caller contract

`installed` must contain base interpreters only: system Python,
pyenv-installed Python, uv-installed Python, or conda `base`. Derived
environments such as venvs, named conda environments, Poetry
environments, and Pipenv environments must not be used as venv bases.

`api.getEnvironments('global')` is the intended source. The helper still
defensively rejects errored, versionless, unparseable, and non-Python-3
entries.

#### `extractLowerBoundVersion(requiresPython)`

Extracts the tightest usable lower bound for a future `uv python install
<version>` request.

Supported floor-producing forms include:

- `>=3.13` to `3.13`
- `~=3.12.4` to `3.12.4`
- `==3.12.7` to `3.12.7`
- `==3.12.*` to `3.12`
- `>=3.11,>=3.12,<3.14` to `3.12`

When multiple lower bounds are present, the numerically greatest one is
returned.

Recognized operators that do not provide a safe integer floor (`>`, `<`,
`<=`, `!=`, and `===`) are skipped without warning. Malformed clauses,
invalid wildcard placement, and `~=` values without at least major and
minor segments are skipped with `traceWarn`.

A skipped clause does not discard a valid floor from another clause. For
example, `>=3.11,<3.13` returns `3.11`, while an upper-bound-only spec
returns `undefined`.

The extracted value is an installation hint, not a full compatibility
result. PR 6 will re-run `matchesPythonVersion` after uv installs an
interpreter.

### Tests

Adds `src/test/common/inlineScriptInterpreter.unit.test.ts` with 34
focused unit tests covering:

- Empty input and no-compatible-interpreter results.
- Unconstrained and constrained newest-version selection.
- Multi-clause, wildcard, and compatible-release constraints.
- Errored, versionless, unparseable, and Python 2 environments.
- Empty-string constraints and leading `v` prefixes.
- Stable ties and non-mutating input behavior.
- Ranking versions with prerelease, development, and local suffixes.
- Lower-bound extraction for `>=`, `==`, wildcard `==`, and `~=`.
- Tightest-floor selection across multiple clauses.
- Upper-bound-only and unsupported operators.
- Malformed clauses, wildcard misuse, and warning behavior.

Required checks pass on this branch:

- `npm run lint`
- `npm run compile-tests`
- `npm run unittest`: 1418 passing, 0 failing, 4 pending

### User impact

**Zero.**

Nothing in the extension calls these helpers yet. This PR discovers no
interpreters, installs no Python versions, creates no environments, and
adds no settings, commands, UI, filesystem access, or activation
behavior.

PR 5 will call `pickCompatibleInterpreter` for the normal creation path.
PR 6 will call `extractLowerBoundVersion` when no compatible installed
interpreter exists and the user is offered a uv installation.

### Design context

This implements Q4 step 1 from #1601: select the newest installed Python
satisfying `requires-python`, and derive a lower-bound version for the
uv fallback when no installed interpreter qualifies.

It reuses the existing `matchesPythonVersion` implementation rather than
introducing a second PEP 440 matcher.

### Explicit installation consent

Following review feedback, the uv fallback now has an explicit,
informed-consent contract for inline scripts:

- The modal explains the script's `requires-python` constraint and the
exact Python version requested.
- If uv is missing, both the message and action disclose that uv and
Python will be installed.
- No prompt is offered when a compatible concrete install version cannot
be derived.
- Script-controlled prompt text is flattened, bounded, and stripped of
control characters; install versions must be numeric release segments.
- Dismissal performs no installation and remains retryable;
inline-script setup does not inherit the global "Don't ask again"
suppression state.
- Approval forwards the displayed version to `uv python install`, and
installed-version lookup matches release-segment boundaries.

The inline-script manager still has no creation call site in this PR, so
this establishes and tests the consent API without changing current user
behavior. PR 6 will invoke it from the uv fallback.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature-request Request for new features or functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants