From 279dea342c0b8848ea2c84eb032602b6243962f8 Mon Sep 17 00:00:00 2001 From: Carlos Bravo <37012961+cbravobernal@users.noreply.github.com> Date: Mon, 11 May 2026 16:13:29 +0200 Subject: [PATCH 1/6] chore(env): start RP pipeline 49843-wp-env-default-port-fallback Phase 0 of Radical Pipelines. Sets up project conventions (.claude/rp.md) and writes the phase-0 prompt artifact for issue WordPress/gutenberg#49843. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/rp.md | 48 +++++++++++ .../prompt.md | 80 +++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 .claude/rp.md create mode 100644 .pipelines/49843-wp-env-default-port-fallback/prompt.md diff --git a/.claude/rp.md b/.claude/rp.md new file mode 100644 index 00000000000000..9351b9a8e0d494 --- /dev/null +++ b/.claude/rp.md @@ -0,0 +1,48 @@ +## Managing tasks + +Tasks are tracked as GitHub Issues on WordPress/gutenberg. +Use `gh issue view `, `gh issue create`, `gh issue list` via Bash. +Link the related issue in the pipeline prompt and PR body. + +## Pipeline slugs + +Format: `-`. +If no related issue exists, drop the prefix and use the kebab phrase alone. +Example: `49843-wp-env-default-port-fallback`. + +## Worktrees + +Use Claude Code's EnterWorktree tool for every pipeline. +The tool creates an isolated git worktree on a fresh branch and auto-cleans on ExitWorktree if no changes landed. +Do not use raw `git worktree`. + +## Branch names + +Format: `try/`. +Created via EnterWorktree at pipeline start. EnterWorktree's default branch name does not match this convention; rename with `git branch -m` immediately after entering the worktree. + +## Pipeline artifact folders + +Path: `.pipelines//`. +Committed inside the pipeline branch so artifacts are inspectable by reviewers and downstream phases. +Maintainers may remove the folder before squash-merging if it should not land on trunk. + +## Spawning teams of agents + +Use Claude Code's Agent tool. One Agent call per role. +Map radical-pipelines roles to subagent_type: +- spec-writer, plan-writer, implementer, doc-writer => general-purpose +- spec-reviewer, plan-reviewer, implementer-reviewer, doc-reviewer => general-purpose with adversarial-review prompt +- exploratory research within a phase => Explore +- architecture planning => Plan +Pass: pipeline slug, artifact folder, exact artifact paths to read/write, role-specific conventions, review iteration N for reviewers. +Launch independent agents in parallel (single message, multiple Agent blocks). + +## Commits + +Conventional Commits. Subject <= 72 chars. +Scope = top-level package or area: `feat(env): ...`, `fix(block-editor): ...`, `docs(env): ...`, `test(env): ...`. +Body only when 'why' is non-obvious. +Always include trailer: +Co-Authored-By: Claude Opus 4.7 (1M context) +Do not amend; create new commits when hooks fail. diff --git a/.pipelines/49843-wp-env-default-port-fallback/prompt.md b/.pipelines/49843-wp-env-default-port-fallback/prompt.md new file mode 100644 index 00000000000000..ea12335c98862c --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/prompt.md @@ -0,0 +1,80 @@ +# Phase 0 — Prompt + +## Pipeline slug + +`49843-wp-env-default-port-fallback` + +## Linked GitHub issue + +WordPress/gutenberg#49843 — "wp-env: consideration of active ports". + +## Background + +`@wordpress/env` (the wp-env CLI) starts a WordPress development environment in Docker on port `8888` (development) and `8889` (tests) by default. When either port is already in use on the host (a very common situation on machines that run other local dev stacks), the start command fails with a Docker port-binding error and the contributor has to either free the port or write a `.wp-env.json` with explicit port overrides before they can continue. + +PR #74472 added an opt-in `--auto-port` CLI flag (and `"autoPort": true` config option) that scans for an available port when the configured one is busy. That PR landed as opt-in because an earlier "always on" version broke PHP unit tests and changed long-standing default behavior. CI determinism is preserved through a `process.env.CI` guard inside `load-config.js`. + +The remaining gap is the out-of-the-box experience requested in #49843: a developer who has never configured `.wp-env.json` should be able to run `wp-env start` even when 8888 or 8889 are taken by another process, without learning about a flag. + +## Goal of this pipeline + +Allow `wp-env start` (and any other command that resolves ports) to fall back automatically to the next free port when the **default** ports 8888 (development) and 8889 (tests) are busy, without requiring `--auto-port`. + +User-set ports — anything the contributor explicitly wrote in `.wp-env.json`, `.wp-env.override.json`, an environment variable override, or any other supported override mechanism — must NOT be silently replaced. They keep today's behavior: Docker (or the existing strict pre-flight) reports a "port busy" error so the contributor knows their explicit choice was honored. + +The opt-in `--auto-port` flag and `"autoPort": true` config option must keep working for the case where contributors *want* their explicit ports to also auto-fall-back. Setting `"autoPort": false` explicitly must still force strict behavior on default ports too. + +The `process.env.CI` determinism guard must keep applying — CI runs must not silently move ports around. + +## Out of scope + +- Phase 2 (Design doc) of the pipeline. RP does not implement it yet. +- MySQL port behavior (`mysqlPort`) — already supports Docker-native auto-assignment via `null`. +- Any change to the Docker layer, the WordPress runtime, or the public TypeScript types beyond what this feature needs. +- Renaming or deprecating `--auto-port` / `"autoPort"`. +- Cross-package refactors. Stay inside `packages/env/`. + +## Acceptance criteria (high-level — refined in phase 1 spec) + +1. With no `.wp-env.json` in the project (or one that does not set `port` / `testsPort`), running `wp-env start` while 8888 is occupied succeeds and binds the development environment to the next free port (8890, 8891, ...). Same for 8889 and the tests environment. +2. With `.wp-env.json` (or override / env var) explicitly setting `port: 9000`, running `wp-env start` while 9000 is occupied fails with the existing "port busy" message; it does NOT silently move to 9001. +3. With `--auto-port` (or `"autoPort": true`), explicit ports also auto-fall-back, matching today's behavior of PR #74472. +4. With `"autoPort": false` set explicitly, default ports do NOT auto-fall-back; a port-busy failure surfaces. (Hard opt-out for users who want determinism but not via `CI=1`.) +5. `CI=1` continues to disable all auto-fallback regardless of other settings. +6. Existing unit tests in `packages/env/lib/test/` and `packages/env/lib/config/test/` continue to pass; new tests cover the four behaviors above. +7. README and CHANGELOG updated to describe the new default behavior and the `"autoPort": false` opt-out. + +## Anti-goals / things the pipeline should NOT do + +- Do not introduce new top-level config options unless strictly necessary. Reuse `autoPort` as a tri-state (`undefined` / `true` / `false`) instead of inventing a second flag. +- Do not change `DEFAULT_ENVIRONMENT_CONFIG.port` or `testsPort` away from `8888` / `8889`. +- Do not break `appendPortToWPConfigs` or the `WP_HOME` / `WP_SITEURL` rewriting that depends on the resolved port. +- Do not silently print "moved port" messages with no way to suppress them; reuse the existing CLI spinner / informational message used by `--auto-port` today. + +## Reference material + +- Issue: https://github.com/WordPress/gutenberg/issues/49843 +- Prior PR (opt-in `--auto-port`): https://github.com/WordPress/gutenberg/pull/74472 +- Key source files: + - `packages/env/lib/resolve-available-ports.js` + - `packages/env/lib/config/load-config.js` + - `packages/env/lib/config/post-process-config.js` + - `packages/env/lib/config/parse-config.js` + - `packages/env/lib/cli.js` + - `packages/env/README.md` + - `packages/env/CHANGELOG.md` + +## Artifacts produced by this pipeline + +Inside `.pipelines/49843-wp-env-default-port-fallback/`: + +- `prompt.md` (this file) +- `spec.md` + `spec-review-N.md` +- `plan.md` + `plan-review-N.md` +- (No `design-doc.md` — phase 2 not implemented in RP yet.) +- `code-review-N.md` (implementation phase reviews; the implementation itself lands as code in `packages/env/`) +- `docs-review-N.md` (documentation phase reviews; doc changes land in README/CHANGELOG) + +## Final deliverable + +A draft GitHub PR against `WordPress/gutenberg` `trunk` from branch `try/49843-wp-env-default-port-fallback`, linking #49843, summarizing the change, and listing the acceptance criteria in its test plan. From 95046217a4127d7b41ca19ca0b39fc7f08f5eca4 Mon Sep 17 00:00:00 2001 From: Carlos Bravo <37012961+cbravobernal@users.noreply.github.com> Date: Mon, 11 May 2026 16:26:05 +0200 Subject: [PATCH 2/6] docs(env): RP phase 1 spec for 49843-wp-env-default-port-fallback Adds spec.md (round-2 revision) plus spec-review-1.md (REJECTED, 2 blockers + 6 minors) and spec-review-2.md (APPROVED) produced by the spec-writer / spec-reviewer team for the autonomous Radical Pipelines run. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../spec-review-1.md | 249 +++++++++++++++++ .../spec-review-2.md | 183 +++++++++++++ .../spec.md | 253 ++++++++++++++++++ 3 files changed, 685 insertions(+) create mode 100644 .pipelines/49843-wp-env-default-port-fallback/spec-review-1.md create mode 100644 .pipelines/49843-wp-env-default-port-fallback/spec-review-2.md create mode 100644 .pipelines/49843-wp-env-default-port-fallback/spec.md diff --git a/.pipelines/49843-wp-env-default-port-fallback/spec-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/spec-review-1.md new file mode 100644 index 00000000000000..c33a2cf8ad2236 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/spec-review-1.md @@ -0,0 +1,249 @@ +# Spec Review — Iteration 1 + +Pipeline: `49843-wp-env-default-port-fallback` +Reviewer role: spec-reviewer (adversarial) +Artifacts under review: +- `prompt.md` +- `spec.md` + +This review is adversarial. The default posture is rejection unless the spec is demonstrably complete, testable, traceable, and free of cross-phase leakage. + +--- + +## 1. Traceability — every requirement / AC mapped back to the prompt + +Mapping each spec item to the sentence(s) in `prompt.md` it derives from. "OK" = direct trace, "PARTIAL" = trace exists but is loose, "CREEP" = no trace. + +### Requirements + +| Req | Prompt anchor (verbatim or near-verbatim) | Verdict | +|-----|-------------------------------------------|---------| +| R1 (default dev port fallback) | Goal: "Allow `wp-env start` ... to fall back automatically to the next free port when the **default** ports 8888 (development) and 8889 (tests) are busy". AC1. | OK | +| R2 (default tests port fallback, independent) | AC1 second sentence: "Same for 8889 and the tests environment." Goal: "8888 (development) and 8889 (tests)". | OK. The "independently of the development port" wording is a reasonable extrapolation, not creep. | +| R3 (user-set ports never silently moved) | Goal §2: "User-set ports — anything the contributor explicitly wrote in `.wp-env.json`, `.wp-env.override.json`, an environment variable override, or any other supported override mechanism — must NOT be silently replaced." AC2. | OK | +| R4 (`--auto-port` / `"autoPort": true` keeps PR #74472 semantics) | Goal §3: "The opt-in `--auto-port` flag and `"autoPort": true` config option must keep working...". AC3. | OK | +| R5 (`"autoPort": false` is a hard opt-out for default ports) | Goal §3: "Setting `"autoPort": false` explicitly must still force strict behavior on default ports too." AC4. | OK | +| R6 (tri-state semantics for `autoPort`) | Anti-goal: "Reuse `autoPort` as a tri-state (`undefined` / `true` / `false`) instead of inventing a second flag." | OK | +| R7 (`CI=1` continues to disable all auto-fallback) | Background: "CI determinism is preserved through a `process.env.CI` guard inside `load-config.js`." AC5. Goal §4: "The `process.env.CI` determinism guard must keep applying — CI runs must not silently move ports around." | OK | +| R8 (resolved port is downstream source of truth) | Anti-goal: "Do not break `appendPortToWPConfigs` or the `WP_HOME` / `WP_SITEURL` rewriting that depends on the resolved port." | OK | +| R9 (default port constants unchanged) | Anti-goal: "Do not change `DEFAULT_ENVIRONMENT_CONFIG.port` or `testsPort` away from `8888` / `8889`." | OK | +| R10 (no rename / deprecation of `--auto-port`) | Out of scope: "Renaming or deprecating `--auto-port` / `"autoPort"`." | OK | +| R11 (informational message reuses existing channel) | Anti-goal: "Do not silently print 'moved port' messages with no way to suppress them; reuse the existing CLI spinner / informational message used by `--auto-port` today." | OK | +| R12 (existing test suites stay green) | AC6: "Existing unit tests in `packages/env/lib/test/` and `packages/env/lib/config/test/` continue to pass". | OK | +| R13 (new tests cover four primary behaviors) | AC6: "new tests cover the four behaviors above." | OK | +| R14 (README and CHANGELOG updated) | AC7. | OK | +| R15 (scope confined to `packages/env/`) | Out of scope: "Cross-package refactors. Stay inside `packages/env/`." | OK | + +No requirement is wholly unsupported. **No CREEP findings at the requirement level.** + +### Acceptance Criteria + +| AC | Trace | Verdict | +|----|-------|---------| +| AC1 (default dev port) | Prompt AC1 first half. | OK | +| AC2 (default tests port, independent) | Prompt AC1 second half. | OK | +| AC3 (explicit port strict by default) | Prompt AC2. | OK | +| AC4 (`--auto-port` falls back on explicit ports) | Prompt AC3. | OK | +| AC5 (`"autoPort": false` strict on defaults) | Prompt AC4. | OK | +| AC6 (`CI=1` disables all auto-fallback) | Prompt AC5. | OK | +| AC7 (informational message contract) | Prompt anti-goal on "moved port" messages. | OK | +| AC8 (CI guard regression test exists) | Prompt §"Background" + AC5 (regression-protection is a reasonable spec extrapolation). | OK — defensible but borderline. See finding F-1. | +| AC9 (resolved port flows downstream) | Prompt anti-goal about `appendPortToWPConfigs` / `WP_HOME` / `WP_SITEURL`. | OK | +| AC10 (existing tests stay green) | Prompt AC6. | OK | + +--- + +## 2. Completeness — prompt criteria / constraints not covered + +Walking the prompt's enumerated items and checking coverage in the spec. + +- **Prompt AC1** → R1, R2, AC1, AC2. Covered. +- **Prompt AC2** → R3, AC3. Covered. +- **Prompt AC3** → R4, AC4. Covered. +- **Prompt AC4** → R5, AC5. Covered. +- **Prompt AC5** → R7, AC6. Covered. +- **Prompt AC6** → R12, R13, AC10, AC8. Covered. +- **Prompt AC7** → R14. Covered. +- **Prompt anti-goal "do not introduce new top-level config options"** → R6. Covered. +- **Prompt anti-goal "do not change `DEFAULT_ENVIRONMENT_CONFIG.port` / `testsPort`"** → R9. Covered. +- **Prompt anti-goal "do not break `appendPortToWPConfigs` / `WP_HOME` / `WP_SITEURL`"** → R8, AC9. Covered. +- **Prompt anti-goal "do not silently print 'moved port' messages with no way to suppress; reuse existing channel"** → R11, AC7. Covered. +- **Prompt out-of-scope: phase 2 design doc, `mysqlPort`, Docker layer, runtime, types, renaming `--auto-port`, cross-package refactors** → §5 of spec. Covered. +- **Prompt §"Final deliverable" (draft PR against `trunk` from `try/49843-wp-env-default-port-fallback`, links #49843, lists ACs in test plan)** → **NOT covered** in spec. See **F-2** below. + +### Findings — completeness + +- **F-2 (MAJOR).** The prompt's "Final deliverable" section pins the PR target (`WordPress/gutenberg` `trunk`), the source branch (`try/49843-wp-env-default-port-fallback`), the requirement that the PR link `#49843`, and that the test plan list the acceptance criteria. None of these appear as a spec requirement or AC. While most of this is plumbing the doc-writer / orchestrator handles, the "test plan lists the acceptance criteria" obligation is a deliverable-shaped requirement and should be either explicitly captured (e.g. as R16) or explicitly delegated out of spec scope with a one-line note. Right now it is silently dropped. + +- **F-3 (MINOR).** Prompt §"Background" specifies that PR #74472 "broke PHP unit tests" when it was always-on. The spec does not call out PHP unit tests at all (R12/AC10 only mention `lib/test/` and `lib/config/test/`, i.e. JS unit tests). If PHP unit tests in `phpunit/` are sensitive to wp-env default ports, the spec should say so. If they are not, the spec should explicitly note that "no PHP-side regression is expected because the change is JS-only". Either way, the silence is a gap. + +--- + +## 3. Testability — is each AC automatable, manually verifiable, or untestable? + +| AC | Automatable? | Notes | +|----|--------------|-------| +| AC1 | YES (with port-binding stub or fake `net.createServer`-style harness in unit tests). The "8888 busy" precondition can be simulated; PR #74472's existing tests for `--auto-port` confirm this is feasible. | OK | +| AC2 | YES, same harness, additionally exercising the dev/tests independence. | OK | +| AC3 | YES, unit-testable through the config layer + port resolver, without spinning up Docker. | OK | +| AC4 | YES, same. | OK | +| AC5 | YES, same. | OK | +| AC6 | YES via `process.env.CI` mutation in tests, mirroring PR #74472's existing pattern. | OK | +| AC7 ("Informational message contract") | PARTIAL. "Same channel as `--auto-port` today" is testable only insofar as the test can assert which channel is used. The AC does not name the channel concretely (it intentionally defers to "the existing one"), which makes the assertion mechanism shaky: a refactor that swaps the spinner for a different but equivalent channel could pass or fail arbitrarily. **Finding F-4.** | +| AC8 | YES — explicitly demands an automated test, which is the right framing. | OK | +| AC9 | PARTIAL. Asserting that `WP_HOME` / `WP_SITEURL` reflect the resolved port is unit-testable. Asserting that "the URL printed by the CLI" matches the bound port leans into integration territory; without a Docker-up step, the test can only inspect the value the CLI *intends* to print, not the live HTTP response. The AC blurs unit-vs-integration. **Finding F-5.** | +| AC10 | YES — pure regression check. | OK | + +### Findings — testability + +- **F-4 (MAJOR).** AC7 is currently underspecified for automated assertion. It says the message goes through "the same spinner/informational channel that `--auto-port` uses today" without naming an observable contract (e.g. "via the same `info`/`log` helper", "as a non-throwing return", "rendered through the existing yargs/ora stream"). A test cannot mechanically verify "same channel as today" without a stable identifier for that channel. The spec should either (a) state the observable contract in WHAT terms (e.g. "the message MUST appear on stderr/stdout in the same form the existing `--auto-port` spinner emits, including the existing message prefix/format"), or (b) reduce the AC to "no new always-on log lines are introduced; messages only appear when a fallback occurred", which is independently testable. As written, AC7 risks producing flaky or trivially-passing tests. + +- **F-5 (MINOR).** AC9 needs a clearer split between "values inside the merged config object reflect the resolved port" (unit-testable, this is what R8 actually demands) and "the running HTTP server is reachable at the printed URL" (integration). The spec hints at both; the plan phase will need a clear signal which one is in scope. Recommend tightening AC9 to the unit-testable subset and explicitly leaving live reachability to manual PR test plan. + +- **F-6 (MINOR).** No AC explicitly verifies R6 (tri-state semantics) at the boundary between CLI parsing and config merge. R6 is a structural requirement; without a dedicated AC, it is verified only transitively through AC3+AC4+AC5. That is *probably* sufficient, but a one-line AC ("Given an unset `--auto-port` flag and unset `autoPort` config field, the resolved `autoPort` MUST be distinguishable from explicit `false`") would close OQ1 from the test side rather than leaving it as an unobserved invariant. + +--- + +## 4. Phase boundary — does the spec leak HOW into WHAT? + +The spec is generally disciplined about staying at WHAT. A few sentences cross the line or come close. + +- **F-7 (MINOR — phase leak).** §3 R6: "No new top-level config option is introduced for this distinction." This is a *constraint* (which is fine) but it implicitly prescribes the design (reuse `autoPort`). The constraint comes from the prompt's anti-goal, so it traces. Acceptable, but right at the line. + +- **F-8 (MINOR — phase leak).** §3 R3 enumerates concrete user-source mechanisms: "root `.wp-env.json`, `.wp-env.override.json`, environment variable override, or any other documented override mechanism". This mostly mirrors the prompt language. Acceptable. + +- **F-9 (NIT — phase leak).** §6 A1 names "`port-utils`-style helper". This is a hint at file organization. Bracketing it as "the existing port-availability scanning utility used by PR #74472" without the `port-utils`-style nickname would be cleaner. Not a blocker; rewrite is trivial. + +- **F-10 (NIT — phase leak).** §6 A2 names `packages/env/lib/config/load-config.js` directly. This is a file path — borderline HOW. It traces to the prompt's reference list, so it is defensible as scoping rather than design. Borderline acceptable. + +- **F-11 (NIT — phase leak).** §8 OQ3 mentions "sentinel, separate object, post-process flag, etc." as possible mechanisms. The spec correctly defers the choice to the plan phase, but enumerating implementation options inside the spec is a soft phase leak. Recommend: drop the parenthetical enumeration; just say "the plan phase chooses the mechanism". + +No critical phase-boundary violations. The spec does not specify file layout, function names, or refactor steps. + +--- + +## 5. Out-of-scope completeness — does spec match prompt? + +Comparing prompt §"Out of scope" against spec §5. + +| Prompt out-of-scope item | Spec §5 covers? | +|--------------------------|-----------------| +| Phase 2 design doc | YES | +| `mysqlPort` behavior | YES | +| Docker layer / runtime / public TS types | YES (split into 3 bullets in spec) | +| Renaming or deprecating `--auto-port` / `"autoPort"` | YES | +| Cross-package refactors; stay inside `packages/env/` | YES | + +Spec §5 also adds: changing default port constants, always-on chatter / new suppression flag, telemetry/analytics, behavior under non-CI automation environments, new top-level config options. All trace cleanly to prompt anti-goals or are sensible scope-fencing. + +No omissions, no contradictions. + +--- + +## 6. Risk coverage — are the prompt's stated risks reflected with mitigations? + +The prompt names four risk threads: + +1. **CI determinism** → Spec R-CI + R7 + AC6 + AC8. Covered. +2. **Silent moves of explicit ports** → Spec R-Explicit + R3 + AC3. Covered. +3. **Breaking opt-in flag (`--auto-port`)** → Spec R-OptIn + R4 + AC4. Covered. +4. **Stale snapshots** → Spec R-Snapshots + R12 + AC10. Covered. + +Spec also adds R-OptOut, R-UX, R-DownstreamURL, R-PortCollision. All four are reasonable extensions, each tied to a requirement. + +### Findings — risk coverage + +- **F-12 (MINOR).** Spec lacks a risk for **"`autoPort` tri-state coercion at the CLI boundary loses the `undefined` state"**. This is OQ1 in the spec's open-questions section, but it is also a substantive risk: if yargs collapses `undefined` → `false`, the entire feature silently regresses to today's behavior on default ports. It deserves a dedicated risk entry (e.g. R-TriState) with a mitigation that the plan phase must surface and test for, not just an open question. Without this, the risk lives only as a passive Q rather than a tracked threat. + +- **F-13 (MINOR).** Spec lacks a risk for **"port-resolution race / TOCTOU"**: scanning a port as free, then Docker tries to bind it and someone else has grabbed it in the interim. Today's `--auto-port` has the same exposure, so this might be inherited rather than new — but the spec should at least say "inherited from PR #74472, no new mitigation required" so the plan phase does not re-litigate it. + +--- + +## 7. Open question triage + +| OQ | Spec's framing | Triage verdict | Justification | +|----|----------------|----------------|---------------| +| OQ1 (tri-state coercion at CLI boundary) | "spec assumes solvable per A3" | **(c) Resolvable by reading existing code** — and **escalate to a risk (F-12)**. The plan phase can answer this in minutes by reading `packages/env/lib/cli.js` to see how yargs is configured for `--auto-port`. No owner input required. NOT a spec blocker. | +| OQ2 (per-environment `autoPort`) | "spec treats whatever PR #74472 surface allows as the contract" | **(c) Resolvable by reading existing code.** Read `parse-config.js` / `post-process-config.js` to see whether `autoPort` is per-env or root-only. The deferral is fine. | +| OQ3 (provenance tracking for "user-set" ports) | Deferred to plan phase | **(b) Acceptable to defer.** This is a design decision and the spec correctly stays out of it. | +| OQ4 (multiple override layers — is `.wp-env.override.json` user-set?) | Spec answers YES, defers confirmation to plan | **(b) Acceptable to defer.** Spec gives the answer, plan confirms feasibility. | +| OQ5 (`WP_ENV_PORT` / env-var overrides — exact list) | Defers enumeration to plan against `parse-config.js` | **(c) Resolvable by reading existing code.** No owner input needed. | +| OQ6 (no upward port available — failure mode) | "spec assumes existing scanner has defined failure mode" | **(c) Resolvable by reading existing code.** Read `resolve-available-ports.js`. | +| OQ7 (interaction with stop/destroy + persisted state) | Spec asserts "re-resolve on each `start`", treats persisted-state changes as out of scope unless plan finds a blocker | **(b) Acceptable to defer with the spec's stated default.** This is a sensible call. | +| OQ8 (`CI` truthiness semantics) | "plan phase reuses existing rule verbatim" | **(c) Resolvable by reading existing code.** Read the existing guard in `load-config.js`. | + +**No open question is a blocker for entering the plan phase.** Most can be resolved by reading existing source; a couple are appropriate design deferrals. OQ1 should be promoted to a tracked risk regardless (F-12). + +--- + +## 8. Other findings + +- **F-1 (NIT).** AC8 ("CI guard regression test exists") is a meta-AC about the test suite rather than about user-observable behavior. It is *useful* (the prompt explicitly warns about CI determinism regressing), and AC8 traces defensibly, but it is structurally an instruction to the implementer phase rather than a behavioral acceptance. Consider rephrasing as "a named, documented test asserts CI guard behavior, such that removing the guard fails the test" — same intent, expressed as a checkable observable rather than a "test exists" assertion. + +- **F-14 (NIT).** §4 AC2 says "binds to the next available port above 8889" — but the spec elsewhere (R1) says "the next available port" without the "above" directionality. The prompt itself only says "next free port (8890, 8891, ...)", which implies upward scanning. The spec should be consistent: either both ACs say "above" or neither does, and the directionality should be one explicit requirement (e.g. an addendum to R1: "scanning proceeds upward from the configured port"). Currently it is implied by example, not stated. + +- **F-15 (NIT).** No requirement covers the contract that **wp-env-internal commands other than `start` that resolve ports** (e.g. `run`, `clean`, `logs`) also see the resolved fallback port. The prompt's goal opens with "Allow `wp-env start` (and any other command that resolves ports) to fall back automatically". The "(and any other command that resolves ports)" parenthetical is dropped from the spec. Recommend an explicit one-liner (an addendum to R8 or a new R) so the plan phase does not narrowly fix `start` and leave `run` confused. + +- **F-16 (NIT).** The spec does not state what happens to **already-running environments** that were started under the old behavior. A user with a previously-bound 8888 environment runs `wp-env start` again with the new code — does state get re-resolved? OQ7 hints at this but treats it as "default expectation" without a requirement. If the answer is "behavior is unchanged for environments started before the upgrade; only new starts are affected", say so. If not, define it. + +--- + +## 9. Severity rollup + +- **Blockers (must fix before plan phase): 2** + - **F-2** — "Final deliverable" obligations from the prompt (PR target/branch/issue link, test-plan-lists-ACs) are silently dropped. Either add as R16 or explicitly delegate out of spec scope with one line. + - **F-4** — AC7 ("informational message contract") is not mechanically testable as written. Tighten it to an observable contract or reduce its scope. + +- **Major (should fix before plan phase): 0** (F-2 and F-4 already blocker-level) + +- **Minor (worth fixing, not blocking): 6** + - F-3 (PHP unit tests silence — say something either way) + - F-5 (AC9 unit/integration split unclear) + - F-6 (no direct AC for R6 tri-state at the boundary) + - F-12 (OQ1 should also be a tracked risk R-TriState) + - F-13 (port-resolution TOCTOU — say "inherited, no new mitigation") + - F-15 ("any other command that resolves ports" dropped from spec) + +- **Nits (polish): 5** — F-1, F-7, F-9, F-10, F-11, F-14, F-16. Address opportunistically. + +--- + +## 10. Suggested concrete revisions (prioritized) + +For the spec-writer's next iteration, in priority order: + +1. **(Blocker, F-2)** Add either a new requirement R16 or a clearly-labeled "Spec scope handoff" subsection capturing the prompt's "Final deliverable" obligations: PR targets `trunk` from `try/49843-wp-env-default-port-fallback`, body links #49843, test plan enumerates the acceptance criteria. Suggested wording: *"R16 — PR test plan enumerates the acceptance criteria. The final draft PR's body MUST list AC1–AC10 (or their post-revision equivalents) so reviewers can map each AC to a verification step."* + +2. **(Blocker, F-4)** Rewrite AC7 to express an observable contract. Suggested replacement: + - **Then** the message is emitted only when a fallback actually occurred (no message on the no-fallback path), + - **And** the message is emitted through the same output mechanism (same logger / spinner instance / stream) that `--auto-port` uses today, such that adding a new output path would be a detectable regression in the test suite, + - **And** no new flag is required to suppress the message. + +3. **(Minor, F-3)** Add one sentence to R12 or the assumptions section addressing PHP unit tests: either include `phpunit/` in the regression scope, or explicitly state "no PHP-side regression is expected because changes are JS-only inside `packages/env/`". + +4. **(Minor, F-5)** Split AC9: tighten the in-scope assertion to the merged-config layer (`WP_HOME`, `WP_SITEURL`, `appendPortToWPConfigs` inputs reflect the resolved port) and move "live HTTP reachability" into the manual PR test plan, or say so explicitly. + +5. **(Minor, F-6)** Add an AC verifying R6 directly at the CLI/config boundary: *"Given `--auto-port` unset and `autoPort` unset in config, when configuration is resolved, then the effective `autoPort` value is distinguishable from an explicit `false` (i.e. the tri-state survives end-to-end)."* + +6. **(Minor, F-12)** Promote OQ1 to a tracked risk R-TriState in §7 with an explicit mitigation (the plan phase MUST verify the tri-state survives CLI parsing; an automated test asserts the distinction). + +7. **(Minor, F-13)** Add a one-line note (under §7 or §8) acknowledging port-bind TOCTOU as inherited from PR #74472, with no new mitigation required. + +8. **(Minor, F-15)** Add one sentence to R8 (or a new R) capturing "any other command that resolves ports" — `run`, `clean`, `logs`, etc. — also sees the resolved fallback port. + +9. **(Nits, F-1/F-7/F-9/F-10/F-11/F-14/F-16)** Polish pass: reword AC8 to a behavioral observable; drop the `port-utils`-style nickname in A1; drop the "(sentinel, separate object, post-process flag)" enumeration in OQ3; make the upward-scan directionality explicit in R1 instead of by example; add one sentence on already-running environments. + +--- + +## Verdict + +**REJECTED — REVISIONS REQUESTED** + +The spec is structurally strong: traceability is excellent, out-of-scope handling is thorough, the prompt's named risks are all reflected with mitigations, the open questions are correctly flagged rather than silently invented away, and the spec stays disciplined about WHAT vs. HOW. Were it not for two specific gaps, this would be approvable. + +The two blockers: + +- **F-2** drops the prompt's "Final deliverable" obligations (especially "PR test plan enumerates the acceptance criteria"). Without capturing this, downstream phases lose a checkable handoff. +- **F-4** leaves AC7 mechanically untestable by stating "same channel as today" without an observable contract; the test that satisfies this AC would be flaky or trivial. + +Address F-2 and F-4 (and ideally the six minor findings) and resubmit. The open questions are appropriately deferred and do not block planning, but OQ1 should also be promoted to a risk entry (F-12). diff --git a/.pipelines/49843-wp-env-default-port-fallback/spec-review-2.md b/.pipelines/49843-wp-env-default-port-fallback/spec-review-2.md new file mode 100644 index 00000000000000..b84f108eeea651 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/spec-review-2.md @@ -0,0 +1,183 @@ +# Spec Review — Iteration 2 + +Pipeline: `49843-wp-env-default-port-fallback` +Reviewer role: spec-reviewer (adversarial) +Artifacts under review: +- `prompt.md` +- `spec.md` (v2) +- `spec-review-1.md` (for verifying the round-1 findings landed) + +This review is adversarial. The default posture is rejection. This iteration must additionally verify each round-1 finding closed correctly without over-correction or revision-log drift. + +--- + +## 1. Round-1 finding disposition (the round-2 obligation) + +Walking every finding from `spec-review-1.md` and checking whether the v2 spec actually closes it. "CLOSED" requires the closure to land in the spec body, not just be claimed in the revision log. + +### Blockers + +| Finding | Round-1 ask | v2 closure | Verdict | +|---------|-------------|------------|---------| +| **F-2** — "Final deliverable" obligations dropped (PR target, branch, issue link, test plan lists ACs) | Add a tracked spec requirement or a labeled handoff section | §9 "Spec scope handoff (final-deliverable obligations)" added with PR target, source branch, issue link, AC enumeration. **R16** added making the AC-enumeration obligation a tracked requirement, with explicit traceability to prompt §"Final deliverable". §9 also clearly states these are deliverable obligations rather than user-observable behaviors of `wp-env`, which avoids conflating phases. | **CLOSED** | +| **F-4** — AC7 mechanically untestable as written | Express as observable contract (no message on no-fallback path; goes through same logger/spinner/stream as today; no new suppression flag) | AC7 rewritten verbatim along the suggested observable contract: "emitted only when a fallback actually occurred", "through the same output mechanism — the same logger function, spinner instance, or stream — that `--auto-port` uses today, such that introducing a new output path would be a detectable regression in the test suite", "no new flag is required to suppress the message". R11 tightened to match. | **CLOSED** | + +### Minors + +| Finding | Round-1 ask | v2 closure | Verdict | +|---------|-------------|------------|---------| +| **F-3** — PHP unit test silence | Either include `phpunit/` in regression scope, or state "no PHP regression expected because JS-only" | R17 added: explicitly scopes regression coverage as JS-only inside `packages/env/`, mandates `composer test` green check during implementation, and treats unexpected PHP failure as a spec-level escalation. R-PHPRegress added to §7 referencing PR #74472's prior breakage. | **CLOSED** | +| **F-5** — AC9 unit/integration split unclear | Tighten in-scope assertion to merged-config layer; move live HTTP to manual PR test plan | AC9 split into AC9a (automated config-layer assertion: merged-config values for `WP_HOME`, `WP_SITEURL`, `appendPortToWPConfigs` reflect the resolved port) and AC9b (manual reachability per PR test plan). §5 also restates that live HTTP integration testing is out of scope for the automated suite. | **CLOSED** | +| **F-6** — No direct AC for R6 tri-state at the boundary | Add an AC asserting unset is distinguishable from explicit `false` after config resolution | AC11 added with the suggested wording: "Given `--auto-port` unset and `autoPort` unset in config, when configuration is resolved, then the effective `autoPort` value is distinguishable from explicit `false` ... an automated test asserts this distinction so a future refactor that collapses `undefined → false` fails the test." R6 also extended with end-to-end survival language. | **CLOSED** | +| **F-12** — OQ1 should also be a tracked risk R-TriState | Promote OQ1 to a §7 risk with mitigation; reference AC11 | R-TriState added to §7 with concrete failure scenario (yargs collapsing `undefined → false`), explicit mitigation referencing R6 + AC11, and a directive that the plan phase MUST verify the existing yargs configuration in `packages/env/lib/cli.js`. OQ1 removed from §8. (Note: §8 is now renumbered OQ1–OQ7; the tri-state question is fully migrated to a risk, not duplicated.) | **CLOSED** | +| **F-13** — TOCTOU note missing | Add a one-line note acknowledging port-bind race as inherited from PR #74472 | R-TOCTOU added to §7: "Inherited from PR #74472; no new mitigation required beyond what `--auto-port` already does today. The plan phase need not re-litigate this." | **CLOSED** | +| **F-15** — "any other command that resolves ports" dropped from spec | Add explicit coverage for `run`, `clean`, `logs`, etc. | R8 expanded with an explicit clause naming `run`, `clean`, `logs`, `destroy`, `stop` and requiring the resolved fallback port to flow into those code paths. AC9c added covering the same observable. | **CLOSED** | + +### Nits + +| Finding | Round-1 ask | v2 closure | Verdict | +|---------|-------------|------------|---------| +| **F-1** — Reword AC8 as a behavioral observable | "such that removing the guard fails the test" framing | AC8 reworded: "a named, documented test asserts ... such that **removing the guard fails the test**". | **CLOSED** | +| **F-7** — R6 phase-leak ("no new top-level config option") | Already acceptable in round 1; no action required | No change. Acceptable. | **N/A — round-1 said "right at the line" but acceptable** | +| **F-8** — R3 enumerates concrete user-source mechanisms | Already acceptable in round 1; no action required | No change. Acceptable. | **N/A — already accepted** | +| **F-9** — Drop "`port-utils`-style" nickname in A1 | Replace with "the existing port-availability scanning utility used by PR #74472" | A1 reworded exactly as suggested: "The existing port-availability scanning utility used by PR #74472 ...". Nickname removed. | **CLOSED** | +| **F-10** — A2 names `load-config.js` (borderline HOW) | Round 1 said "borderline acceptable"; no explicit ask | No change; A2 still names the file, which is defensible as scoping. | **ACCEPTED — no closure required** | +| **F-11** — Drop "(sentinel, separate object, post-process flag)" enumeration in OQ3 (now OQ2) | Just say "the plan phase chooses the mechanism" | OQ2 (formerly OQ3) reworded: "The plan phase chooses the mechanism." Enumeration dropped. | **CLOSED** | +| **F-14** — Inconsistent upward-scan directionality | State directionality as an explicit requirement, not by example | R1 extended: "scanning **upward** from the configured default". R2 reuses "the same upward-scan directionality applies." AC1 names the upward direction explicitly; AC2's heading and body say "upward scan" / "scanning upward from `8889`". | **CLOSED** | +| **F-16** — Already-running environments | Add one sentence on already-running environments | OQ6 expanded: "an environment started under the old behavior (pre-upgrade) that is still running when the user upgrades wp-env: behavior is treated as unchanged for that already-running environment until the next `start` re-resolves." | **CLOSED** | + +**Round-1 disposition summary:** All 2 blockers and all 6 minors land in the spec body in the form the round-1 review asked for. All addressable nits land too. No round-1 finding is left unaddressed. + +--- + +## 2. Revision-log accuracy check (round-2-specific) + +Walking each revision-log claim against the spec body to detect drift. + +| Log claim | Body evidence | Drift? | +|-----------|---------------|--------| +| F-2 → §9 added; R16 added | §9 present with the listed content (PR target/branch/issue link/AC enumeration); R16 present in §3 with the cited prompt trace | None | +| F-4 → AC7 rewritten; R11 tightened | AC7 §4 rewritten with the three-clause observable contract; R11 §3 reflects "only on a real move" + "would be a detectable regression in the test suite" | None | +| F-3 → R17 added; R-PHPRegress added | R17 present in §3 with `composer test` mandate; R-PHPRegress present in §7 referencing PR #74472 | None | +| F-5 → AC9 split into AC9a/AC9b | AC9a and AC9b present in §4; §5 also explicitly restates that live HTTP integration testing is out of scope | None | +| F-6 → AC11 added | AC11 present in §4 with the boundary check wording | None | +| F-12 → R-TriState added; OQ1 removed from §8 | R-TriState present in §7; §8 renumbered (OQ1–OQ7) with no tri-state OQ remaining; A3 also references R-TriState | None | +| F-13 → R-TOCTOU added | R-TOCTOU present in §7 | None | +| F-15 → R8 extended; AC9c added | R8 contains the explicit list (`run`, `clean`, `logs`, `destroy`, `stop`); AC9c added in §4 | None | +| F-1, F-9, F-11, F-14, F-16 nits | AC8 reworded; A1 cleaned; OQ2 (formerly OQ3) trimmed; R1/R2 + AC1/AC2 made directional; OQ6 extended for already-running envs | None | + +**No revision-log drift detected.** Every claim in the log is backed by a corresponding edit in the spec body. + +--- + +## 3. Over-correction watch (round-2-specific) + +Checking whether any closure introduced HOW-leaks or scope inflation. + +- **R8 expansion (F-15 closure).** The extension names CLI commands (`run`, `clean`, `logs`, `destroy`, `stop`). These are user-observable command names already present in the wp-env CLI surface — they are WHAT the user types, not HOW the implementation routes them. **No leak.** +- **AC9a closure (F-5).** Names `WP_HOME`, `WP_SITEURL`, `appendPortToWPConfigs`. These are anchored to the prompt's anti-goal ("Do not break `appendPortToWPConfigs` or the `WP_HOME` / `WP_SITEURL` rewriting"). They are scoping anchors traced from the prompt. **No leak.** +- **R17 closure (F-3).** Mandates `composer test` runs during implementation. This is a process obligation on the implementer phase, not a design prescription. The risk it mitigates (R-PHPRegress) is grounded in the prompt's background section. **No leak; no scope inflation.** +- **R-TriState mitigation language (F-12 closure).** "The plan phase MUST verify the existing `--auto-port` yargs configuration in `packages/env/lib/cli.js` and define how the tri-state is preserved before implementation begins." This names a file path (`cli.js`), which is borderline — but the prompt's reference list already names `packages/env/lib/cli.js`, so this is scoping anchored to the prompt. **Acceptable; no fresh HOW.** +- **AC11 (F-6 closure).** Asserts a behavioral observable ("distinguishable from explicit `false`") and explicitly says "an automated test asserts this distinction" without prescribing the test mechanism. **No leak.** +- **§9 "Spec scope handoff" (F-2 closure).** Carefully labels itself as deliverable obligations, not acceptance criteria of the code change. This is exactly the framing round-1 asked for. **No scope inflation; correctly distinguishes WHAT-the-code-does from WHAT-the-PR-contains.** + +**No over-correction detected.** The closures stay inside the prompt's bounds and at the WHAT layer. + +--- + +## 4. Re-checking traceability for the v2 additions + +| New / changed item | Trace | +|--------------------|-------| +| R16 (PR test plan enumerates ACs) | Prompt §"Final deliverable": "summarizing the change, and listing the acceptance criteria in its test plan." | OK | +| R17 (JS-only regression scope; `composer test` mandate) | Prompt §"Background": "an earlier 'always on' version broke PHP unit tests" | OK | +| AC9a / AC9b / AC9c | AC9a/b: prompt anti-goal on `appendPortToWPConfigs`/`WP_HOME`/`WP_SITEURL`; AC9c: prompt §"Goal of this pipeline" — "(and any other command that resolves ports)" | OK | +| AC11 | Prompt anti-goal: "Reuse `autoPort` as a tri-state (`undefined` / `true` / `false`)" | OK | +| R-PHPRegress | Prompt §"Background" PR #74472 history | OK | +| R-TOCTOU | Acknowledged inheritance from PR #74472; not a new obligation | OK (no trace required for an "inherited, no new mitigation" risk) | +| R-TriState | Prompt anti-goal on tri-state `autoPort` | OK | +| §9 "Spec scope handoff" | Prompt §"Final deliverable" | OK | +| Upward-scan directionality (R1/R2/AC1/AC2) | Prompt AC1: "the next free port (8890, 8891, ...)" implies upward; spec now states it explicitly. | OK | + +**All v2 additions trace cleanly.** No CREEP introduced by the round-2 revision. + +--- + +## 5. Re-checking testability for the v2 additions + +| AC | Automatable? | Notes | +|----|--------------|-------| +| AC7 (rewritten) | YES — the three-clause contract gives a test the hooks it needs: assert a "no fallback path" produces no message; assert the fallback path goes through the same logger function or spinner instance the test can spy on; assert no new flag exists to suppress. | Round-1 F-4 closed in a testable form | +| AC9a | YES — pure config-layer assertion against the merged config object | OK | +| AC9b | NO (manual) — explicitly delegated to the PR test plan | Correctly out of automated scope | +| AC9c | YES — exercise `run`/`clean`/etc. with a stubbed prior fallback resolution and assert each command sees the resolved port | OK | +| AC11 | YES — invoke config resolution with both inputs unset; assert the resolved `autoPort` is observably not equal to `false` | OK | + +All new ACs are either automatable or correctly labeled manual. + +--- + +## 6. Re-checking phase boundary for the v2 additions + +- **§9 (handoff)** — explicitly labeled as deliverable obligations, not behavioral ACs. Correct framing; no leak. +- **R17** — process obligation on the implementer phase ("MUST run `composer test` ... before requesting review"). This is a process gate, not a code design. Acceptable. +- **R-TriState mitigation** — names `cli.js` (a file already in the prompt's reference list). Borderline-acceptable as scoping. +- **R8 expansion** — names CLI command surface, not internals. Acceptable. +- **AC11** — asserts an observable, defers test mechanism to plan. Acceptable. + +No fresh phase-boundary violations introduced in v2. + +--- + +## 7. Open question triage (re-check) + +§8 in v2 has 7 OQs (OQ1–OQ7) — OQ1 from v1 was correctly migrated to R-TriState in §7, and the remaining v1 OQs were renumbered. Spot-checking: + +| v2 OQ | Was v1 OQ | Triage | +|-------|-----------|--------| +| OQ1 (per-environment `autoPort`) | v1 OQ2 | Resolvable by reading existing code; defer to plan | +| OQ2 (provenance tracking) | v1 OQ3 | Acceptable design deferral | +| OQ3 (multiple override layers) | v1 OQ4 | Acceptable deferral with stated default | +| OQ4 (env-var override list) | v1 OQ5 | Resolvable by reading existing code | +| OQ5 (no upward port available) | v1 OQ6 | Resolvable by reading existing code | +| OQ6 (stop/destroy + persisted state + already-running envs) | v1 OQ7, extended for F-16 | Acceptable deferral with stated default | +| OQ7 (`CI` truthiness) | v1 OQ8 | Resolvable by reading existing code | + +**No OQ is a blocker for entering the plan phase.** The migration is clean and the renumbering is consistent. + +--- + +## 8. New findings introduced in v2 + +None. The revision is targeted: it closes the listed round-1 findings without rewriting unrelated material. No new requirements snuck in beyond what was asked for. No prior requirements were softened or dropped. + +--- + +## 9. Severity rollup + +- **Blockers: 0** +- **Major: 0** +- **Minor: 0** +- **Nits: 0** + +--- + +## Verdict + +**APPROVED** + +Round-1 findings closed: +- **F-2 (blocker)** — closed by §9 + R16 +- **F-4 (blocker)** — closed by AC7 rewrite + R11 tightening +- **F-3 (minor)** — closed by R17 + R-PHPRegress +- **F-5 (minor)** — closed by AC9 split into AC9a/AC9b +- **F-6 (minor)** — closed by AC11 +- **F-12 (minor)** — closed by R-TriState (OQ1 correctly migrated and removed from §8) +- **F-13 (minor)** — closed by R-TOCTOU +- **F-15 (minor)** — closed by R8 expansion + AC9c +- **F-1, F-9, F-11, F-14, F-16 (nits)** — all closed in the polish pass +- **F-7, F-8, F-10 (nits)** — round 1 already accepted these as borderline-acceptable; no action required + +Open questions accepted as deferrable to the plan phase: OQ1 (per-env `autoPort`), OQ2 (provenance mechanism), OQ3 (multi-layer overrides), OQ4 (env-var override list), OQ5 (no-upward-port failure mode), OQ6 (stop/destroy + already-running env behavior), OQ7 (`CI` truthiness rule). All are either resolvable by reading existing code in the plan phase or are acceptable design deferrals with the spec's stated default. + +The spec is complete, testable, traceable to the prompt, free of cross-phase HOW-leakage, and consistent with the host project's conventions in `AGENTS.md` and `.claude/rp.md`. The revision log accurately reflects the body changes, and the round-2 closures did not over-correct or inflate scope. Ready for the plan phase. diff --git a/.pipelines/49843-wp-env-default-port-fallback/spec.md b/.pipelines/49843-wp-env-default-port-fallback/spec.md new file mode 100644 index 00000000000000..e5eb1fe00ef06a --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/spec.md @@ -0,0 +1,253 @@ +# Phase 1 — Spec + +## Revision log + +Round 2 revisions, in response to `spec-review-1.md`: + +- **F-2 (blocker)** — Added §9 "Spec scope handoff (final-deliverable obligations)" capturing the prompt's PR target (`trunk`), source branch (`try/49843-wp-env-default-port-fallback`), `#49843` link, and the requirement that the test plan enumerate ACs. Also added **R16** so the AC-enumeration obligation is a tracked spec requirement, not a side note. +- **F-4 (blocker)** — Rewrote **AC7** as an observable contract: message MUST be emitted only when a fallback occurred, MUST go through the same logger / spinner / output mechanism that `--auto-port` uses today (such that introducing a new output path would be a detectable test regression), and no new suppression flag MUST be required. Tightened **R11** correspondingly. +- **F-3 (minor)** — Added **R17** explicitly scoping regression coverage to JS unit tests inside `packages/env/` and noting "no PHP-side regression is expected because changes are JS-only inside `packages/env/`". Added matching risk **R-PHPRegress** in §7 referencing PR #74472's earlier always-on attempt that broke PHP unit tests, with a concrete mitigation: the implementer phase MUST run `composer test` (or the equivalent PHP unit suite) at least once and confirm green before requesting review, and any unexpected PHP failure becomes a spec-level escalation. +- **F-5 (minor)** — Split **AC9** into **AC9a** (unit-testable: merged-config values used by `WP_HOME` / `WP_SITEURL` / `appendPortToWPConfigs` reflect the resolved port) and **AC9b** (manual / PR test plan: live HTTP reachability at the printed URL). The spec now states which AC the automated suite must cover and which the PR test plan handles. +- **F-6 (minor)** — Added **AC11** verifying R6 directly at the CLI/config boundary: an unset `--auto-port` flag combined with an unset `autoPort` config field MUST be distinguishable from explicit `false` after configuration is resolved. +- **F-12 (minor)** — Promoted OQ1 to a tracked risk **R-TriState** in §7 with mitigation (plan phase MUST confirm tri-state survival from CLI through merge; an automated test asserts the distinction — covered by AC11). Removed OQ1 from §8. +- **F-13 (minor)** — Added a one-line risk **R-TOCTOU** in §7 acknowledging port-bind race as inherited from PR #74472, no new mitigation required. +- **F-15 (minor)** — Added explicit "any other command that resolves ports" coverage to **R8** and a new **AC9c** so commands beyond `start` (e.g. `run`, `clean`, `logs`) also see the resolved fallback port. +- **F-1, F-9, F-11, F-14, F-16 (nits)** — Reworded AC8 as a behavioral observable; dropped the "`port-utils`-style" nickname in A1; dropped the "(sentinel, separate object, post-process flag)" enumeration in OQ3 (now OQ2); added explicit upward-scan directionality to R1; added one sentence (now part of OQ6) on already-running environments. + +--- + +Pipeline: `49843-wp-env-default-port-fallback` +Linked issue: WordPress/gutenberg#49843 +Scope: `packages/env/` (the `@wordpress/env` CLI). No other packages. + +This spec describes WHAT must be true after the change ships. It does not propose a design, file layout, or implementation. The plan phase owns those. + +--- + +## 1. Goal statement + +A contributor who runs `wp-env start` for the first time, with no `.wp-env.json` (or with a `.wp-env.json` that does not pin `port` / `testsPort`), must succeed even when the default ports `8888` (development) or `8889` (tests) are already bound by another process on the host. `@wordpress/env` resolves the next available port automatically and starts the environment there. Contributors who explicitly configured a port keep today's behavior — the start fails loudly so their explicit choice is honored — unless they have separately opted into auto-fallback for explicit ports via `--auto-port` / `"autoPort": true`. + +--- + +## 2. Stakeholders + +- **First-time and casual contributors to WordPress/Gutenberg.** They get a working dev environment from `npm install && npm run wp-env start` even when 8888/8889 are taken by another local stack, without needing to learn `.wp-env.json`, `--auto-port`, or Docker port-binding errors. +- **Plugin and theme authors using `@wordpress/env` standalone.** Same out-of-the-box win: they do not need to author config to get a usable dev URL on a busy laptop. +- **Existing wp-env users who have pinned ports.** They are explicitly protected: their pinned port will not be silently moved. Behavior on their machines is unchanged unless they opt in. +- **CI operators (Gutenberg core CI and downstream consumers).** They are explicitly protected: the existing `process.env.CI` guard keeps default-port fallback disabled, so test suites that key off `8888` / `8889` stay deterministic. +- **Maintainers of `packages/env/`.** They get the smaller out-of-box-friction support load promised by issue #49843, with the same opt-in/opt-out surface they shipped in PR #74472, just extended to the unconfigured case. + +The change reaches stakeholders through: + +- the next `@wordpress/env` release on npm, +- the bundled `wp-env` CLI used inside the gutenberg monorepo, +- `packages/env/README.md` documenting the new default and the `"autoPort": false` opt-out, +- `packages/env/CHANGELOG.md`. + +--- + +## 3. Requirements + +Each requirement is atomic, testable, and traceable to a sentence in `prompt.md`. "Default port" means a port whose value comes from `DEFAULT_ENVIRONMENT_CONFIG` and was not overridden by `.wp-env.json`, `.wp-env.override.json`, an environment variable, a CLI flag, or any other supported override mechanism. + +1. **R1 — Auto-fallback on unconfigured default development port.** When the development port is a default (not user-set) and the resolved port is busy on the host, `wp-env start` MUST resolve to the next available port — scanning **upward** from the configured default — and proceed. (Traces to: prompt §"Goal of this pipeline"; AC1.) +2. **R2 — Auto-fallback on unconfigured default tests port.** R1 also applies to the tests port (`testsPort`, default `8889`) independently of the development port; the same upward-scan directionality applies. (Traces to: AC1.) +3. **R3 — User-set ports are never silently moved by default.** When a port value originates from any user-supplied source (root `.wp-env.json`, `.wp-env.override.json`, environment variable override, or any other documented override mechanism), and that port is busy, `wp-env start` MUST surface the existing port-busy failure and MUST NOT pick a different port. (Traces to: prompt §"Goal of this pipeline" paragraph 2; AC2.) +4. **R4 — `--auto-port` and `"autoPort": true` keep their PR #74472 semantics.** When the user opts in via the CLI flag or the config field, auto-fallback MUST apply to all ports — both default and user-set. (Traces to: prompt §"Goal of this pipeline" paragraph 3; AC3; anti-goal "Do not introduce new top-level config options".) +5. **R5 — Explicit `"autoPort": false` is a hard opt-out, even for default ports.** When the user has set `"autoPort": false` in config (any layer), default-port fallback MUST NOT happen; a port-busy failure surfaces as it does today. This MUST work without setting `CI=1`. (Traces to: prompt §"Goal of this pipeline" paragraph 3; AC4; anti-goal about reusing `autoPort` as tri-state.) +6. **R6 — `autoPort` is interpreted as tri-state.** The semantics MUST distinguish three states: `undefined` (unset → new "auto on defaults only" behavior), `true` (full opt-in, today's behavior), `false` (full opt-out). No new top-level config option is introduced for this distinction. The tri-state MUST survive end-to-end from CLI parsing through config merge so that "unset" is observably distinct from explicit `false`. (Traces to: prompt §"Anti-goals".) +7. **R7 — `CI=1` continues to disable all auto-fallback.** When `process.env.CI` is truthy, auto-fallback MUST NOT happen for any port, regardless of `autoPort` value or whether the port is default or user-set. (Traces to: prompt §"Background"; AC5.) +8. **R8 — Resolved port is the source of truth for downstream URL/config rewriting, across all wp-env commands that resolve ports.** Any consumer that today reads the resolved port (e.g. `appendPortToWPConfigs`, `WP_HOME`, `WP_SITEURL`) MUST receive the post-fallback port, so the started environment is reachable at the URL the CLI prints. This contract applies not only to `start` but to any other wp-env command that resolves ports (e.g. `run`, `clean`, `logs`, `destroy`, `stop`); the resolved fallback port MUST flow through to those code paths so they operate against the actually-bound environment. (Traces to: prompt §"Goal of this pipeline" — "(and any other command that resolves ports)" — and prompt §"Anti-goals".) +9. **R9 — Default port constants are unchanged.** `DEFAULT_ENVIRONMENT_CONFIG.port` and `testsPort` MUST remain `8888` and `8889`. The fallback is a runtime resolution step, not a default value change. (Traces to: prompt §"Anti-goals".) +10. **R10 — Existing CLI flags are not renamed or deprecated.** `--auto-port` and `"autoPort"` keep their existing names, types, and CLI surface. (Traces to: prompt §"Out of scope".) +11. **R11 — Informational CLI output for fallback reuses the existing channel and only fires on a real move.** When auto-fallback moves a port (whether on a default port via the new behavior or on an explicit port via `--auto-port`), the CLI MUST inform the user via the same logger / spinner / output mechanism already used by `--auto-port` today, such that introducing a new output path would be a detectable regression in the test suite. The message MUST NOT fire on the no-fallback path. No new always-on chatter is introduced and no new suppression flag is required. (Traces to: prompt §"Anti-goals".) +12. **R12 — Existing JS test suites stay green.** All existing JS unit tests in `packages/env/lib/test/` and `packages/env/lib/config/test/` MUST continue to pass. Snapshots that legitimately change must be reviewed and intentional. (Traces to: AC6.) +13. **R13 — New tests cover the primary behaviors.** New automated tests MUST cover: R1+R2 (default fallback), R3 (explicit-port strict), R4 (`autoPort: true` still falls back on explicit ports), R5 (`autoPort: false` strict on defaults), R7 (CI guard), and R6 (tri-state survives end-to-end). (Traces to: AC6.) +14. **R14 — Documentation updated.** `packages/env/README.md` MUST describe the new default behavior and the `"autoPort": false` opt-out. `packages/env/CHANGELOG.md` MUST list the user-visible change under the next unreleased version. (Traces to: AC7.) +15. **R15 — Scope confinement.** All code changes MUST live inside `packages/env/`. No edits to other packages, the Docker layer, the WordPress runtime, or public TypeScript types beyond what this feature strictly requires. (Traces to: prompt §"Out of scope".) +16. **R16 — PR test plan enumerates the acceptance criteria.** The final draft PR's body MUST list the acceptance criteria (AC1 through the highest-numbered AC defined here, including AC9a/AC9b/AC9c sub-criteria) so reviewers can map each AC to a verification step in the PR description. (Traces to: prompt §"Final deliverable" — "summarizing the change, and listing the acceptance criteria in its test plan".) +17. **R17 — Regression scope is explicitly JS-only.** Because the change is confined to JS inside `packages/env/`, no PHP-side regression is expected. The implementer phase MUST nevertheless run the project's PHP unit suite (`composer test` or equivalent) at least once and confirm it remains green before requesting review, since PR #74472's earlier always-on attempt at this feature broke PHP unit tests. Any unexpected PHP failure during implementation becomes a spec-level escalation. (Traces to: prompt §"Background" — "an earlier 'always on' version broke PHP unit tests".) + +--- + +## 4. Acceptance criteria + +Given/When/Then form. Each criterion is independently verifiable by an automated test in `packages/env/` or by the documented manual reproduction in the final PR's test plan. + +### AC1 — Default development port falls back automatically (upward scan) + +- **Given** a project with no `.wp-env.json` (or one that does not set `port`), +- **And** port `8888` on the host is bound by another process, +- **And** `process.env.CI` is unset, +- **When** the contributor runs `wp-env start`, +- **Then** the start command succeeds, +- **And** the development environment is bound to the next available port found by scanning **upward** from `8888` (e.g. `8890`), +- **And** the CLI informs the user via the same output mechanism that `--auto-port` uses today (see AC7). + +### AC2 — Default tests port falls back automatically (independent of dev port, upward scan) + +- **Given** the same conditions as AC1 but with `8889` busy and `8888` free, +- **When** `wp-env start` runs, +- **Then** the development environment binds to `8888` and the tests environment binds to the next available port found by scanning upward from `8889`. + +### AC3 — Explicitly configured port stays strict by default + +- **Given** a `.wp-env.json` that sets `"port": 9000`, +- **And** port `9000` on the host is bound by another process, +- **And** neither `--auto-port` nor `"autoPort": true` is set, +- **When** `wp-env start` runs, +- **Then** the start fails with the existing port-busy error message, +- **And** no other port is silently used. + +### AC4 — `--auto-port` / `"autoPort": true` still falls back on explicit ports + +- **Given** a `.wp-env.json` that sets `"port": 9000`, +- **And** port `9000` on the host is bound, +- **And** the contributor runs `wp-env start --auto-port` (or sets `"autoPort": true`), +- **When** the command runs, +- **Then** the start succeeds against the next available port above `9000`, +- **And** the CLI informs the user via the same output mechanism that `--auto-port` uses today (see AC7). + +### AC5 — `"autoPort": false` opts out of default-port fallback too + +- **Given** a `.wp-env.json` that sets `"autoPort": false` and does NOT set `port`, +- **And** port `8888` on the host is bound, +- **And** `process.env.CI` is unset, +- **When** `wp-env start` runs, +- **Then** the start fails with the existing port-busy error message, +- **And** no other port is silently used. + +### AC6 — `CI=1` continues to disable all auto-fallback + +- **Given** `process.env.CI` is truthy, +- **And** port `8888` on the host is bound, +- **And** the project has no `.wp-env.json` (or has any `autoPort` value, including `true`), +- **When** `wp-env start` runs, +- **Then** the start fails with the existing port-busy error message, +- **And** no other port is silently used. + +### AC7 — Informational message contract (observable) + +- **Given** any scenario in which auto-fallback moves a port (AC1, AC2, AC4), +- **When** the CLI emits the "moved port" notice, +- **Then** the message is emitted only when a fallback actually occurred (no message on the no-fallback path), +- **And** the message is emitted through the same output mechanism — the same logger function, spinner instance, or stream — that `--auto-port` uses today, such that introducing a new output path would be a detectable regression in the test suite, +- **And** no new flag is required to suppress the message. + +### AC8 — CI guard regression is detectable + +- **Given** the implementation of R7, +- **When** the test suite runs, +- **Then** a named, documented test asserts that `process.env.CI === '1'` (or other truthy values defined by the inherited guard) disables fallback regardless of `autoPort` state, such that **removing the guard fails the test**. + +### AC9a — Resolved port flows downstream into merged config (automated) + +- **Given** a fallback occurred per AC1, +- **When** the merged configuration object is computed, +- **Then** the values used for `WP_HOME`, `WP_SITEURL`, and the inputs to `appendPortToWPConfigs` all reflect the post-fallback port. This is unit-testable at the config layer without requiring Docker. + +### AC9b — Live reachability at printed URL (manual / PR test plan) + +- **Given** a fallback occurred per AC1, +- **When** the environment is up on the contributor's machine, +- **Then** the URL printed by the CLI is reachable via HTTP. This is verified manually as part of the PR test plan rather than in the automated suite. + +### AC9c — Other wp-env commands see the resolved fallback port + +- **Given** a previous `wp-env start` resolved the development environment to a fallback port (e.g. `8890`), +- **When** a subsequent wp-env command that resolves ports (`run`, `clean`, `logs`, `destroy`, `stop`, etc.) runs in the same project, +- **Then** that command operates against the actually-bound port, not against the original default `8888`. + +### AC10 — Existing tests stay green + +- **Given** the change is implemented, +- **When** `npm run test:unit packages/env` (and the equivalent for `packages/env/lib/config/test/`) runs, +- **Then** all previously passing tests still pass, +- **And** any snapshot changes are reviewed and intentional, not incidental. + +### AC11 — `autoPort` tri-state survives end-to-end (boundary check for R6) + +- **Given** `--auto-port` unset on the CLI invocation and `autoPort` unset in config, +- **When** configuration is resolved, +- **Then** the effective `autoPort` value is **distinguishable** from an explicit `false` (i.e. the tri-state is preserved through CLI parsing and config merge), +- **And** an automated test asserts this distinction so a future refactor that collapses `undefined → false` fails the test. + +--- + +## 5. Out of scope + +Restated and extended from the prompt. + +- **Phase 2 design doc.** RP does not implement a separate design-doc phase yet; the spec → plan → implementation chain proceeds directly. +- **`mysqlPort` behavior.** Already supports Docker-native auto-assignment via `null`; not touched here. +- **Docker layer changes.** No changes to Docker image, Compose generation strategy, or container networking beyond what consuming the resolved port already requires. +- **WordPress runtime changes.** No PHP, no WordPress core, no theme/plugin runtime behavior. +- **Public TypeScript type surface.** No new exported types or breaking changes to existing ones beyond what this feature minimally needs. +- **Renaming or deprecating `--auto-port` / `"autoPort"`.** The names stay. No deprecation warning is added. +- **New top-level config options.** Reuse `autoPort` as a tri-state instead of inventing a second flag. +- **Cross-package refactors.** All changes live inside `packages/env/`. +- **Changing default port constants.** `8888` / `8889` stay as the defaults. +- **Always-on "moved port" chatter, or new flag to suppress it.** Reuse the existing `--auto-port` output mechanism. +- **Telemetry, analytics, or remote reporting** of fallback events. +- **Behavior under non-`CI` automation environments** that do not set `CI`. Those continue to be treated as ordinary developer machines (auto-fallback applies on defaults). Setting `"autoPort": false` is the documented opt-out for such cases. +- **Live HTTP integration testing in the automated suite.** Reachability is verified manually per AC9b in the PR test plan; the automated suite stops at AC9a's config-layer assertions. + +--- + +## 6. Assumptions + +These are treated as true without separate verification. If any turns out to be false, the plan or implementation phase must surface it. + +- **A1.** The existing port-availability scanning utility used by PR #74472 correctly detects busy ports on the host, scans upward, and can take an `exclude` list so the dev and tests resolutions do not collide. +- **A2.** The existing `process.env.CI` guard in `packages/env/lib/config/load-config.js` is the only CI-determinism gate that needs to keep applying; no other package or process needs to be taught about it. +- **A3.** The current CLI has a place where `--auto-port` is parsed and merged into config such that a tri-state `autoPort` (`undefined` / `true` / `false`) can be represented end-to-end without ambiguity. (See R-TriState risk in §7: if the existing CLI/yargs layer coerces missing `--auto-port` to `false`, the plan phase must define how the tri-state survives; AC11 guarantees a regression test exists.) +- **A4.** "User-set" can be detected in config processing by tracking whether `port` / `testsPort` came from `DEFAULT_ENVIRONMENT_CONFIG` versus from a user source. The exact mechanism is a design concern, not a spec concern. +- **A5.** The "informational message" output mechanism used by today's `--auto-port` is appropriate for the new default-fallback case too, both in tone and verbosity. No separate UX research is required. +- **A6.** README and CHANGELOG conventions in `packages/env/` are stable; the doc-writer phase can update them in place without coordinating release notes elsewhere. +- **A7.** `npm run test:unit` for `packages/env/` is sufficient to validate R12; the wp-env package does not have hidden integration tests outside the `lib/test/` and `lib/config/test/` trees that require separate invocation. +- **A8.** Existing snapshots in `packages/env/lib/test/` are stable enough that the only legitimate snapshot churn comes from this change, so any churn is reviewable. + +--- + +## 7. Risks and mitigations + +- **R-CI — CI determinism regresses.** A future contributor refactors port resolution and accidentally drops the `process.env.CI` gate, silently moving ports in CI runs and breaking suites that key off `8888` / `8889`. **Mitigation:** R7 + AC8 mandate a named test that asserts the CI guard such that removing the guard fails the test. +- **R-Explicit — A user-set port is silently moved.** A contributor pinned `port: 9000` for a reason (proxy, hosts file, integration with another tool); silently moving to 9001 produces a working-but-wrong environment. **Mitigation:** R3 + R6 (tri-state `autoPort`) keep explicit ports strict by default; AC3 covers it with an automated test. +- **R-OptIn — `--auto-port` opt-in is broken by the refactor.** Contributors who already rely on `--auto-port` to escape pinned-port conflicts find their workflow regressed. **Mitigation:** R4 + AC4 require that `true` continues to override everything (default and explicit), preserving PR #74472 semantics. +- **R-OptOut — No way to opt out without `CI=1`.** A contributor wants strict default-port behavior locally without polluting their environment with `CI=1`. **Mitigation:** R5 + AC5 make `"autoPort": false` a documented hard opt-out. +- **R-Snapshots — Test snapshots in `packages/env/lib/test/` go stale.** Tri-stating `autoPort` and threading "user-set" provenance can ripple into serialized config snapshots. **Mitigation:** R12 explicitly calls out keeping existing tests green; the implementer phase reviews each snapshot diff for intent; AC10 makes "intentional snapshot diffs only" a checkable criterion. +- **R-UX — Always-on port-moved chatter annoys users.** If the informational message fires noisily even when no move happened, it becomes spam. **Mitigation:** R11 + AC7 constrain the message to actual moves and to the existing output mechanism. +- **R-DownstreamURL — Resolved port not propagated.** The dev environment starts on a moved port but the printed URL, `WP_HOME`, or `appendPortToWPConfigs` still reflect the original, leaving the user with a broken-looking site. Or, secondarily, the `start` path is patched but other commands (`run`, `clean`, `logs`) still consult the original default. **Mitigation:** R8 + AC9a + AC9c require the resolved port to be the source of truth downstream and across commands. +- **R-PortCollision — Dev and tests resolve to the same port.** Both default ports are busy and the scan produces overlapping next-free ports. **Mitigation:** Assumption A1 covers `exclude`-list support. If A1 turns out to be false, the plan phase must add coordination as a design concern. +- **R-TriState — `autoPort` tri-state collapses at the CLI boundary.** If the existing yargs definition coerces an unset `--auto-port` to `false` (or any layer collapses `undefined → false`), the entire feature silently regresses to today's behavior on default ports — the new R1/R2 paths never fire because every config is interpreted as "explicit opt-out". **Mitigation:** R6 + AC11 require the tri-state to survive end-to-end with an automated boundary test that asserts unset is distinguishable from explicit `false`. The plan phase MUST verify the existing `--auto-port` yargs configuration in `packages/env/lib/cli.js` and define how the tri-state is preserved before implementation begins. +- **R-PHPRegress — PHP unit tests regress.** PR #74472's earlier always-on attempt at this feature broke PHP unit tests, which is why it shipped opt-in instead. Even though this revision is JS-only, anything that changes wp-env's default behavior risks tripping PHP suites that consume wp-env-derived URLs or ports. **Mitigation:** R17 mandates a `composer test` (or equivalent PHP unit suite) green check during implementation before review; any unexpected PHP failure escalates back to spec/plan rather than being silently worked around. +- **R-TOCTOU — Port-bind race.** A port reads as free during the scan but is grabbed by another process before Docker binds it. **Mitigation:** Inherited from PR #74472; no new mitigation required beyond what `--auto-port` already does today. The plan phase need not re-litigate this. + +--- + +## 8. Open questions + +The prompt does not pin these down. They are flagged for the plan phase, not invented here. + +- **OQ1 — Per-environment `autoPort`.** Can `autoPort` be set per-environment (e.g. only for `tests`, not `development`) under existing config-merging rules, or is it root-only? The prompt does not say; the spec treats whatever the existing PR #74472 surface allows as the contract. +- **OQ2 — Provenance tracking for "user-set" ports.** The spec requires distinguishing default vs. user-set ports (R3, R6) but does not specify how. The plan phase chooses the mechanism. +- **OQ3 — Multiple override layers.** When `port` comes from `.wp-env.override.json` but the base `.wp-env.json` did not set it, is that "user-set"? The spec answers yes (any user-supplied source counts as user-set per R3) but the plan phase should confirm the override-merging code can be taught this distinction. +- **OQ4 — `WP_ENV_PORT` / environment-variable overrides.** The prompt mentions "environment variable override" as a user-set source. The exact list of env vars wp-env honors as user-set port sources should be enumerated by the plan phase against the current `parse-config.js` code, not invented here. +- **OQ5 — Behavior when no upward port is available.** The prompt does not specify the failure mode if scanning runs out of ports. The spec assumes the existing scanner already has a defined failure mode (per A1); the plan phase should confirm and, if needed, surface a sensible error. +- **OQ6 — Interaction with `wp-env destroy` / `wp-env stop` and persisted state, including already-running environments.** If a previous run bound the dev environment to `8890` via fallback, do subsequent `stop`/`destroy`/`start` cycles need to remember the port, or do they re-resolve each time? Likewise, an environment started under the old behavior (pre-upgrade) that is still running when the user upgrades wp-env: behavior is treated as unchanged for that already-running environment until the next `start` re-resolves. The prompt is silent. The spec treats re-resolution on each `start` as the default expectation, with persisted-state changes considered out of scope unless the plan phase finds a concrete blocker. +- **OQ7 — `CI` truthiness semantics.** `process.env.CI` can be `"true"`, `"1"`, `"false"`, or any string; today's guard's exact truthiness rule (per the existing PR #74472 implementation) is the contract this spec inherits. The plan phase should confirm the existing rule and reuse it verbatim, not redefine it. + +--- + +## 9. Spec scope handoff (final-deliverable obligations) + +Captured here so they are not silently dropped. These obligations come from prompt §"Final deliverable" and are the spec's contract with the orchestration / doc-writer / PR-creation phases. The spec does not own their execution, but it does own that they are not forgotten. + +- **PR target.** Final draft PR opens against `WordPress/gutenberg` `trunk`. +- **Source branch.** PR is opened from branch `try/49843-wp-env-default-port-fallback` (provisioned via the EnterWorktree convention in `.claude/rp.md`). +- **Issue link.** PR body links `#49843`. +- **Test plan content.** Per **R16**, the PR body's test plan section enumerates the acceptance criteria defined in §4 of this spec (AC1–AC11, including AC9a/AC9b/AC9c) so reviewers can map each AC to a verification step. +- **PR is a draft until docs and code-review phases sign off.** The spec does not gate final ready-for-review; it simply pins the deliverable shape. + +These obligations are NOT acceptance criteria of the code change itself (they are not user-observable behaviors of `wp-env`); they are deliverable obligations of the pipeline. Capturing them here closes the F-2 gap from spec-review-1 without conflating "what the code does" with "what the PR contains". From a4f5221b812d5d97a1b1890e13d4ed10c8cec7c8 Mon Sep 17 00:00:00 2001 From: Carlos Bravo <37012961+cbravobernal@users.noreply.github.com> Date: Mon, 11 May 2026 16:51:31 +0200 Subject: [PATCH 3/6] docs(env): RP phase 3 plan for 49843-wp-env-default-port-fallback Adds plan.md (round-2 revision) plus plan-review-1.md (REJECTED, 3 blockers + 8 minors) and plan-review-2.md (APPROVED) produced by the plan-writer / plan-reviewer team. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../plan-review-1.md | 155 ++++++++ .../plan-review-2.md | 158 ++++++++ .../plan.md | 348 ++++++++++++++++++ 3 files changed, 661 insertions(+) create mode 100644 .pipelines/49843-wp-env-default-port-fallback/plan-review-1.md create mode 100644 .pipelines/49843-wp-env-default-port-fallback/plan-review-2.md create mode 100644 .pipelines/49843-wp-env-default-port-fallback/plan.md diff --git a/.pipelines/49843-wp-env-default-port-fallback/plan-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/plan-review-1.md new file mode 100644 index 00000000000000..d981d79bea8153 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/plan-review-1.md @@ -0,0 +1,155 @@ +# Plan review — Iteration 1 + +Pipeline: `49843-wp-env-default-port-fallback` +Reviewer role: plan-reviewer (adversarial) +Reviewing: `plan.md` (single iteration so far) +Source-citations verified by reading: `packages/env/lib/config/parse-config.js`, `packages/env/lib/config/load-config.js`, `packages/env/lib/config/post-process-config.js`, `packages/env/lib/config/merge-configs.js`, `packages/env/lib/resolve-available-ports.js`, `packages/env/lib/port-utils.js`, `packages/env/lib/cli.js`, `packages/env/lib/commands/start.js`, `packages/env/lib/commands/stop.js`, `packages/env/lib/commands/status.js`, `packages/env/lib/commands/{clean,destroy,cleanup,logs,reset,run}.js`, `packages/env/lib/runtime/docker/build-docker-compose-config.js`, `packages/env/lib/config/get-config-from-environment-vars.js`, `packages/env/lib/test/cli.js`, `packages/env/lib/test/build-docker-compose-config.js`, `packages/env/lib/config/test/parse-config.js`, `packages/env/README.md`, `packages/env/CHANGELOG.md`, the `packages/env/lib/test/__snapshots__/` and `packages/env/lib/config/test/__snapshots__/` directories. + +--- + +## Summary + +The plan resolves OQ1-OQ7 with mostly correct evidence and traces every spec AC to at least one step. Most cited line numbers are accurate. The shape of the design (tri-state `autoPort: null`, per-port `defaultOriginPorts` Set, per-port `strict` flag in `resolveConfigPorts`, spinner.info from `createPortResolver`) is consistent with the spec. + +However, the plan has **three blockers** that will cause the implementer to either ship something that fails the existing test suite, or has to invent ad-hoc fixes mid-implementation: + +1. The plan changes `parseConfig`'s return shape (Step 3) from `WPRootConfig` to `{ config, defaultOriginPorts }`. This silently breaks ~25 existing call sites in `packages/env/lib/config/test/parse-config.js` (every `parsed = await parseConfig(...)` followed by `expect( parsed )...`). The plan does not list these tests as "Modified", does not include them in Step 12's snapshot sweep, and does not mention the structural change at all in the test plan. AC10 explicitly requires existing tests stay green; this is a guaranteed regression. +2. The plan changes `DEFAULT_ENVIRONMENT_CONFIG.autoPort` from `false` to `null` (Step 1). The test fixture `DEFAULT_CONFIG` at `packages/env/lib/config/test/parse-config.js:21-71` has `autoPort: false` hardcoded and is `toEqual()`-compared against `parseConfig` output in many tests (lines 91, 193, 232, 293, 305, 506, 537, 560, etc.). The plan only mentions modifying the named test `should accept autoPort as a boolean`. Every other test that compares against the `DEFAULT_CONFIG` fixture will fail. Again breaks AC10. +3. The plan unconditionally creates the port resolver whenever `autoPortMode !== 'off'` (Step 2). Today, `phpmyadminPort` is only resolved when `--auto-port` is on; the plan would now also auto-resolve `phpmyadminPort` non-strictly in the new `defaults-only` mode. For a contributor who has `phpmyadmin: true, phpmyadminPort: 8080` (user-set) and no explicit `autoPort`, this silently moves their phpmyadmin port if 8080 is busy — a regression of the "user-set ports are never silently moved" contract (R3) for the phpmyadmin case. The plan does not analyze this behavior change. Either the plan needs to thread `defaultOriginPorts` for phpmyadminPort too (mirroring the HTTP ports), or it needs to special-case phpmyadminPort to keep today's behavior (only resolved when `autoPortMode === 'all'`), or the spec needs to be amended to acknowledge phpmyadminPort moves silently in defaults-only. None of those is in the plan. + +In addition, several **non-blocking findings** below should be addressed before approval. + +--- + +## Verified citations (correct) + +- `parse-config.js:86-111` `DEFAULT_ENVIRONMENT_CONFIG`: confirmed (`autoPort: false` at line 93). Step 1's target. +- `parse-config.js:124-167` merge sequence: confirmed. +- `parse-config.js:284-344` `getEnvironmentVarOverrides`: confirmed. +- `parse-config.js:390-397` `parseRootConfig`'s `autoPort` block: confirmed (does NOT assign when `undefined`). +- `parse-config.js:483` `case 'autoPort':` in the switch: confirmed. +- `load-config.js:96-109` (`shouldAutoPort` block): confirmed (lines 96-109 contain the exact block plan rewrites). +- `load-config.js:102-104` `process.env.CI` guard: confirmed verbatim (`if ( process.env.CI ) { shouldAutoPort = false; }`). +- `load-config.js:90-94` `parseConfig` call site: confirmed. +- `post-process-config.js:24-43` exported function with `{ portResolver }` destructure: confirmed. +- `post-process-config.js:35-42` resolveConfigPorts call: confirmed (lines 35-37 specifically). +- `resolve-available-ports.js:38-90` `createPortResolver`: confirmed. +- `resolve-available-ports.js:50` `resolve(preferredPort, configPath, strict = false)`: confirmed third-arg already supports strict. +- `resolve-available-ports.js:74-87` non-strict branch: confirmed (lines 74-87). +- `resolve-available-ports.js:75-78` `usedPorts` exclude: confirmed. +- `resolve-available-ports.js:84-87` error wrapping: confirmed. +- `resolve-available-ports.js:100-130` `resolveConfigPorts`: confirmed; the loop body matches. +- `resolve-available-ports.js:101-127` PORT_DEFINITIONS loop: confirmed. +- `resolve-available-ports.js:121-126` phpmyadminPort behavior: confirmed (lines 121-127 cover both HTTP and phpmyadmin in the same loop, no special branching). +- `port-utils.js:51-80` `findAvailablePort` with throw: confirmed (`No available port found in range ${ startPort }-${ maxPort }.` at lines 77-79). +- `cli.js:154-159` `--auto-port` yargs definition: confirmed (`type: 'boolean'`, no `default`). +- `cli.js:24-93` `withSpinner` (plan also says `cli.js:46-92` for spinner: that range is accurate for the rejection branches). +- `start.js:55-59` `loadConfig({ resolvePorts: true, autoPort, spinner })`: confirmed. +- `stop.js:21-31` consumes cached compose by container name: confirmed (`loadConfig` is called WITHOUT `resolvePorts`, so no resolution; runtime stop operates on `dockerComposeConfigPath`). +- `lib/test/cli.js:35-52` tri-state CLI assertions: confirmed (`undefined`, `true`, `false`). +- `get-config-from-environment-vars.js:36-72` env-var enumeration: confirmed (`WP_ENV_PORT`, `WP_ENV_TESTS_PORT`, `WP_ENV_MYSQL_PORT`, `WP_ENV_TESTS_MYSQL_PORT`, `WP_ENV_PHPMYADMIN_PORT`, `WP_ENV_TESTS_PHPMYADMIN_PORT` are the port-yielding ones; OQ4 resolution is correct). +- README `autoPort` row at line 609 and "Automatic Port Selection" at lines 620-630: confirmed. +- CHANGELOG `## Unreleased` at line 3: confirmed. + +## Verified citations (wrong — would mislead the implementer) + +- `build-docker-compose-config.js:173, 267` — the file is **not** at `packages/env/lib/build-docker-compose-config.js` as suggested by the bare reference style elsewhere in the plan. The actual path is `packages/env/lib/runtime/docker/build-docker-compose-config.js`. The line numbers (173 and 267) are correct *for that path* — line 173 is the `developmentPorts = ` interpolation and line 267 is the `testsPorts = ` interpolation. The implementer should be steered to the runtime/docker subpath. (Non-blocking but should be corrected.) + +--- + +## Findings + +### B1 (Blocker) — Step 3 silently breaks every existing parseConfig test +Step 3 changes `parseConfig`'s return value from `WPRootConfig` (the merged config object) to `{ config, defaultOriginPorts }`. The existing test file `packages/env/lib/config/test/parse-config.js` calls `parseConfig` ~25 times and asserts shape against the result directly (e.g. `expect( parsed ).toEqual( DEFAULT_CONFIG )` at line 91, `expect( parsed.coreSource )...` at line 101, `expect( parsed.autoPort ).toEqual( true )` at line 206). With the new shape, every such assertion is either a structural mismatch (`{ config, defaultOriginPorts }` vs the inner config) or `parsed.autoPort` becomes `undefined`. AC10 demands "existing tests stay green". The test plan in §3 lists exactly one modified test (`should accept autoPort as a boolean`) but does not acknowledge the wholesale refactor. Fix: either (a) explicitly enumerate every existing parse-config test as "Modified" with the new destructure pattern, or (b) attach `defaultOriginPorts` as a non-enumerable property on the returned config (the plan listed this as an alternative and explicitly rejected it, but it would preserve API compatibility with the test suite). The plan must commit to one of those before implementation begins. + +### B2 (Blocker) — DEFAULT_CONFIG fixture in tests is not updated +Step 1 changes `DEFAULT_ENVIRONMENT_CONFIG.autoPort` from `false` to `null`. The test fixture `DEFAULT_CONFIG` at `packages/env/lib/config/test/parse-config.js:21-71` has `autoPort: false` hardcoded (line 24) and is used as the expected value in `expect( parsed ).toEqual( DEFAULT_CONFIG )` (line 91) and as a spread base in many other assertions (lines 166, 232, 293, 305, etc.). Step 12's snapshot sweep does not catch this because it is not a snapshot — it is an inline fixture. The plan does not list this fixture update under Step 10 ("modified" tests) or anywhere else. Without it, the suite is red on the very first commit. Fix: explicitly call out "update `DEFAULT_CONFIG.autoPort` from `false` to `null` in `packages/env/lib/config/test/parse-config.js`" as part of Step 1 or Step 10. + +### B3 (Blocker) — phpmyadminPort silently auto-moves under defaults-only mode (R3 regression) +Step 2 says "Always create a portResolver when resolvePorts is true and autoPortMode !== 'off'", and Step 5 says for phpmyadminPort: "keep today's behavior (always non-strict via findAvailablePort) … Implement as `strict = false`." But TODAY, when `--auto-port` is off, `portResolver` is never created, so `resolveConfigPorts` never runs for phpmyadminPort either. The plan would change behavior so that under the new default-only mode (the common case for a contributor with no `autoPort` setting), a user-set `phpmyadminPort: 8080` that happens to be busy gets silently moved. That violates R3 ("user-set ports are never silently moved") for the phpmyadmin case, even though phpmyadminPort is technically out of the explicit HTTP-port scope. The plan needs to either (a) thread the same `defaultOriginPorts` provenance for phpmyadminPort and apply the same `strict = ! defaultOriginPorts.has(...)` rule, (b) special-case phpmyadminPort so the resolver only runs in `'all'` mode (preserving today's behavior verbatim), or (c) escalate to spec to explicitly accept this regression. As written, this is a silent behavior change not analyzed in the plan. + +### F1 (Non-blocker) — `build-docker-compose-config.js` path is ambiguous +The plan refers to `build-docker-compose-config.js:173, 267` without the `runtime/docker/` prefix. The line numbers are accurate but the file lives at `packages/env/lib/runtime/docker/build-docker-compose-config.js`, not at `packages/env/lib/build-docker-compose-config.js`. The test file at `packages/env/lib/test/build-docker-compose-config.js` is unrelated (it imports from the runtime path). Clarify the cited path so the implementer does not chase a non-existent file. + +### F2 (Non-blocker) — Snapshot drift assessment is incomplete +Step 12 says "If `config-integration.js.snap` changes (e.g. because `null` now appears for `autoPort`), inspect the diff." But `grep -n autoPort` against both snapshot files (`packages/env/lib/test/__snapshots__/md5.js.snap` and `packages/env/lib/config/test/__snapshots__/config-integration.js.snap`) returns zero hits today. There is no `autoPort` in the snapshots, so no drift is expected from that field. The snapshot risk the plan should call out instead is the `build-docker-compose-config.js` test file (not snapshot-based, but assertion-based on hardcoded `8888`/`8889`); however that file does NOT use `parseConfig` end-to-end — it constructs synthetic configs with explicit ports. So the plan's worry about snapshot churn is overstated and the actual fixture-update risk (B2 above) is missed. + +### F3 (Non-blocker) — AC4 lacks a behavior-level integration test +The test plan covers AC4 only at the routing-matrix level ("uses non-strict mode for all ports under autoPortMode=all"). Spec AC4 reads as a Given/When/Then on `loadConfig` end-to-end (".wp-env.json sets port: 9000 + --auto-port + 9000 busy → start succeeds against next port above 9000"). The mirror to AC5's `loadConfig`-level test would be a `loadConfig with CLI autoPort=true and explicit user port falls back when port is busy` integration test in `config-integration.js`. The plan covers AC5 with such a test but not AC4. Strictly, the routing-matrix test plus the existing `--auto-port` test path may be enough for this change, but the asymmetry is worth flagging. + +### F4 (Non-blocker) — Step 6 spinner re-arming claim under-specified +Step 6 says "call `spinner.info(...)` followed by `spinner.start()` to re-arm the spinner (the existing `withSpinner` in `cli.js:24-93` expects the spinner to remain active until the command resolves)." Reading `cli.js:24-93`, `spinner.info` is `ora`'s API which does change the spinner state, and `spinner.start()` is needed afterward to resume. The plan's instinct is correct but it does not cite where in the existing code the same pattern is used (`start.js:101` and `start.js:113` both do `spinner.warn(...); spinner.start();` — that is the precedent). Citing that precedent would make the implementer's job clearer. Also: the test plan asserts `spinner.start was called to re-arm` but does not assert the order of calls (info before start). Minor. + +### F5 (Non-blocker) — OQ7 resolution slightly imprecise +The plan says about `process.env.CI` truthiness: "JavaScript truthy semantics: `"true"`, `"1"`, `"false"` (non-empty string), and any non-empty string are all truthy; `undefined`/empty string/`"0"` is also truthy in string form (`"0"` is truthy as a string)." This is internally inconsistent — `undefined` is NOT truthy in JS, and `""` is NOT truthy. The plan probably meant "non-empty string", but as written the sentence contradicts itself. This is reused from spec OQ7 verbatim and does not affect correctness (the implementation is `if ( process.env.CI )` which the plan correctly preserves), but the wording should be cleaned up to avoid confusing the implementer. + +### F6 (Non-blocker) — JSDoc updates are mentioned twice but never staged in test plan +Steps 1, 2, 7 each say "update the JSDoc". No verification step asserts the JSDoc reflects the new tri-state. Not critical (JSDoc is non-functional) but worth a single-line note in Step 12 that the JSDoc updates were performed. + +### F7 (Non-blocker) — Sequencing line is wrong about parallel/serial +§4 says: "Serial (must run in order): step 1 → step 2 → steps 4/5/7 → step 10/11 → step 12." But step 4 depends on step 3 (per Step 4's own "Depends on. Step 3" line), so the serial chain should read "step 1 → step 2 → step 3 → steps 4/5 → step 7 → step 10/11 → step 12" with step 3 also serial, not "parallelizable with step 1". And step 6 (described as parallelizable with step 1) actually should be parallel with step 5 since both touch the same file (`resolve-available-ports.js`) — so they cannot literally be done in parallel by separate workers, only by sequential editing of the same file. The plan's parallelism statement is thus aspirational but technically wrong. Minor for a single implementer; matters for an agent team. + +### F8 (Non-blocker) — Rollback paragraph could mention the snapshot +§7 ("Rollback") says "A clean `git revert ` restores the prior PR #74472 opt-in-only behavior with no downstream cleanup needed: there is no migration, no persisted state, no schema change, and no public API surface change." This is correct as far as wp-env's own surface goes, but the plan does not call out that since cached `docker-compose.yml` files contain hardcoded resolved ports, an environment that started under the new default-fallback behavior on (say) 8890 will keep its cached compose pinned to 8890 until the user runs `start` again. Post-revert, that already-running environment continues to work, but newly-started ones (without `--auto-port`) on a busy 8888 will start failing again. Worth one sentence so the reverting maintainer knows to communicate this in the revert message. + +--- + +## AC coverage matrix (audited) + +| AC | Plan step(s) | Test(s) | OK? | +|---|---|---|---| +| AC1 | Steps 1, 2, 3, 4, 5 | parse-config provenance tests + "uses non-strict mode for default-origin ports" + "tri-state autoPort: unset triggers defaults-only mode" | Yes | +| AC2 | Steps 1, 2, 3, 4, 5 | same as AC1 (covers both env keys symmetrically) | Yes | +| AC3 | Steps 1, 2, 3, 4, 5 | "uses strict mode for non-default-origin ports under autoPortMode=defaults-only" + four parse-config provenance tests | Yes | +| AC4 | Steps 2, 5 | "uses non-strict mode for all ports under autoPortMode=all" + "CLI autoPort=true and user config autoPort=false has CLI win" | Partial (see F3) | +| AC5 | Steps 1, 2, 5 | "uses strict mode for all ports under autoPortMode=off" + "loadConfig with autoPort:false in user config skips fallback" | Yes | +| AC6 | Step 2 (CI guard preserved) | "loadConfig with CI=1 disables fallback regardless of autoPort:true" + "even when autoPort is unset" | Yes | +| AC7 | Step 6 | four resolver-notice tests including the no-console regression guard | Yes | +| AC8 | Step 2 + Step 10 named test | "CI=1 disables fallback regardless of autoPort:true" is the named regression detector | Yes | +| AC9a | Step 4 (post-process threading) | "postProcessConfig threads autoPortMode and defaultOriginPorts to portResolver" asserts WP_HOME/WP_SITEURL reflect resolved port | Yes | +| AC9b | Manual recipe in §3 of plan | PR test plan recipe enumerated | Yes (manual per spec) | +| AC9c | Inherited from cached compose pattern | None automated; manual per recipe | Yes (manual per spec; rationale documented) | +| AC10 | Step 12 | Snapshot sweep — but B1 and B2 mean existing tests will fail without fixture/return-shape updates | **No** — broken by B1/B2 | +| AC11 | Steps 1, 2, 7 | "should accept autoPort as a boolean" (modified to assert default is null) + "tri-state autoPort: unset triggers defaults-only mode" | Yes | + +All ACs have at least one plan step targeting them. AC10 is technically covered by Step 12 but B1 and B2 will make it fail in practice. + +--- + +## OQ resolution audit + +| OQ | Plan resolution | Source verified? | Verdict | +|---|---|---|---| +| OQ1 (per-environment autoPort) | Root-only per `parse-config.js:483` and `:390-397` | Yes | Correct | +| OQ2 (provenance mechanism) | `defaultOriginPorts` Set built in parseConfig | Citation correct (`parse-config.js:124-167`) | Correct shape, but see B1 about return-value impact | +| OQ3 (multi-layer overrides) | Any non-default layer counts | Yes | Correct | +| OQ4 (env-var sources) | `WP_ENV_PORT`, `WP_ENV_TESTS_PORT` in scope | Verified at `get-config-from-environment-vars.js:38,40` | Correct | +| OQ5 (no upward port available) | Throws via `port-utils.js:77-79`, wrapped at `resolve-available-ports.js:84-87` | Yes | Correct | +| OQ6 (re-resolution on every start) | Confirmed by tracing start.js → load-config.js → post-process → resolveConfigPorts → mutates config.env[env].port; build-docker-compose interpolates that into cached YAML; downstream commands operate on cached YAML by container name | Yes (verified `stop.js:21-31` does NOT call loadConfig with resolvePorts; `clean/destroy/cleanup/logs/run/status` likewise omit `resolvePorts`) | Correct | +| OQ7 (CI truthiness) | Inherit verbatim from `load-config.js:102-104` | Yes — but see F5 about wording | Correct in substance | + +--- + +## Verification of required-check items from the team prompt + +1. **Spec AC coverage** — All ACs have at least one plan step. Coverage matrix above. (All ACs covered, none uncovered.) +2. **Step traceability** — Each step traces to ACs in its own "Spec ACs covered" line. No over-scoping detected. +3. **Source-code feasibility** — Citations are largely accurate; the only path ambiguity is `build-docker-compose-config.js` (F1). +4. **OQ resolutions** — All seven OQs resolved with valid evidence; OQ7 wording is internally inconsistent but not wrong in substance. +5. **Test plan completeness** — Major gap: B1 and B2 (parseConfig return-shape change and DEFAULT_CONFIG fixture); minor gap: B3 (phpmyadminPort behavior change unanalyzed); F3 (AC4 lacks behavior-level integration test). +6. **Sequencing** — F7: serial chain is wrong about step 3, and step 6 cannot literally be parallel with step 5 (same file). +7. **PHP-regression risk** — `composer test` is invoked at gates 2 and 4 per §4. Concrete checkpoint exists. OK. +8. **Scope confinement** — All file paths live inside `packages/env/`. OK. +9. **Rollback** — Concrete enough to act on, but should mention the cached-compose-pinning side effect (F8). + +--- + +## Verdict + +``` +REJECTED — REVISIONS REQUESTED +``` + +Three blockers must be addressed before this plan can drive an implementation: (B1) the `parseConfig` return-shape change breaks ~25 existing tests with no acknowledgment in the test plan; (B2) the `DEFAULT_CONFIG` fixture in `parse-config.js` tests is not updated when the default `autoPort` value changes; (B3) `phpmyadminPort` will silently move under the new defaults-only mode whenever a user has set it, which is a quiet R3 regression the plan does not analyze. + +The non-blocking findings (F1–F8) should also be cleaned up but are not gates. diff --git a/.pipelines/49843-wp-env-default-port-fallback/plan-review-2.md b/.pipelines/49843-wp-env-default-port-fallback/plan-review-2.md new file mode 100644 index 00000000000000..4e6f08a9e1f113 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/plan-review-2.md @@ -0,0 +1,158 @@ +# Plan review — Iteration 2 + +Pipeline: `49843-wp-env-default-port-fallback` +Reviewer role: plan-reviewer (adversarial) +Reviewing: `plan.md` (round 2 revision) +Prior review: `plan-review-1.md` +Source-citations re-verified by reading: `packages/env/lib/config/parse-config.js`, `packages/env/lib/config/load-config.js`, `packages/env/lib/config/post-process-config.js`, `packages/env/lib/config/merge-configs.js`, `packages/env/lib/resolve-available-ports.js`, `packages/env/lib/cli.js`, `packages/env/lib/commands/start.js`, `packages/env/lib/commands/stop.js`, `packages/env/lib/runtime/docker/build-docker-compose-config.js`, `packages/env/lib/config/get-config-from-environment-vars.js`, `packages/env/lib/test/cli.js`, `packages/env/lib/config/test/parse-config.js`, `packages/env/README.md`, `packages/env/CHANGELOG.md`, plus a directory listing of `packages/env/lib/runtime/docker/` and the snapshot directories under `packages/env/lib/{,config/}test/__snapshots__/`. + +--- + +## Summary + +Round 2 closes all three round-1 blockers and every minor finding (F1–F8) at the artifact level. The non-enumerable-property design (B1 fix) is well-grounded: I re-read `merge-configs.js` and confirmed both iteration sites (`for ( const option in config )` at line 39 and `for ( const option in toMerge )` at line 81) use `for…in`, which is well-defined in JavaScript to skip non-enumerable own properties. Jest's `toEqual` also walks own-enumerable properties only. The DEFAULT_CONFIG fixture update (B2 fix) is now an explicit Step 1 sub-step, and the phpmyadminPort regression (B3 fix) is sealed by a per-port skip rule with a dedicated regression test. + +Spot-checks of cited line numbers all matched the source. The plan reads as feasible and complete. Approving. + +--- + +## Round-1 finding closure audit + +| Round-1 finding | Status | Where in plan v2 | +|---|---|---| +| **B1** — `parseConfig` return-shape change broke ~25 existing tests | **CLOSED** | Revision log entry "B1"; Step 3 (return shape unchanged; `__defaultOriginPorts` attached non-enumerably via `Object.defineProperty`); Step 2 ("call to `parseConfig` at `load-config.js:90-94` is **unchanged in shape**"); Step 4 (reads `config.__defaultOriginPorts`); test plan §3 row "`__defaultOriginPorts is invisible to mergeConfigs and toEqual (regression guard for B1 / non-enumerable contract)`". | +| **B2** — DEFAULT_CONFIG fixture not updated | **CLOSED** | Revision log entry "B2"; Step 1 sub-step 4 explicitly calls out the fixture edit at `parse-config.js test:24` and enumerates affected `toEqual` / spread sites (lines 91, 166, 193, 232, 293, 305, 500, 531, 557); test plan §3 row "Modified — `DEFAULT_CONFIG` fixture"; Step 12 inline-fixture verification line. | +| **B3** — phpmyadminPort silent move under defaults-only mode | **CLOSED** | Revision log entry "B3"; Step 5 per-port skip rule under `autoPortMode === 'defaults-only'` (`continue` for `property !== 'port'`); Step 1 plan summary §1 ("phpmyadminPort is **only** auto-resolved under `'all'` mode"); test plan §3 has two regression-detector rows: "`postProcessConfig with autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)`" and "`resolveConfigPorts under autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)`"; Risks §6 "R-PhpmyadminMove (B3)". | +| **F1** — `build-docker-compose-config.js` path ambiguity | **CLOSED** | Revision log entry "F1"; OQ6 resolution (§1) cites the full path `packages/env/lib/runtime/docker/build-docker-compose-config.js:173,267`. I verified the path/file existence — the directory listing of `packages/env/lib/runtime/docker/` contains `build-docker-compose-config.js` and there is no file at `packages/env/lib/build-docker-compose-config.js`. | +| **F2** — Snapshot drift assessment incomplete | **CLOSED** | Revision log entry "F2"; Step 12 explicitly states "no snapshot diffs" expected, with the `grep autoPort` evidence cited. I re-verified — `grep autoPort` against `packages/env/lib/config/test/__snapshots__/config-integration.js.snap` and `packages/env/lib/test/__snapshots__/md5.js.snap` returns zero hits today. (Note: only `config-integration.js.snap` actually exists in `packages/env/lib/config/test/__snapshots__/`; `packages/env/lib/test/__snapshots__/` is empty in this checkout. The plan over-cites a non-existent file but the substantive claim — no `autoPort` in any snapshot — holds.) | +| **F3** — AC4 lacks behavior-level integration test | **CLOSED** | Revision log entry "F3"; test plan §3 row "`loadConfig with CLI autoPort=true and explicit user port falls back when port is busy (AC4 behavior-level)`"; mirrors the AC5 integration test as requested. | +| **F4** — Spinner re-arming pattern under-specified | **CLOSED** | Revision log entry "F4"; Step 6 now cites `start.js:98-101`, `start.js:105-112`, and `start.js:169-193` as precedents (verified — `start.js:98-101` is the `spinner.warn(...); spinner.start();` block for the missing `.wp-env.json` case; `start.js:105-112` is the testsEnvironment deprecation warning; `start.js:169-193` uses `spinner.info(...)` followed by `spinner.start()` in `checkForLegacyInstall`). Test plan asserts call order via `mock.invocationCallOrder`. | +| **F5** — OQ7 truthiness wording inconsistent | **CLOSED** | Revision log entry "F5"; OQ7 resolution in §1 now reads "all non-empty strings are truthy; empty string and `undefined` are falsy" — clean and correct. The implementation is unchanged. | +| **F6** — JSDoc updates not staged for verification | **CLOSED** | Revision log entry "F6"; Step 12 now has a JSDoc-review checklist enumerating all five JSDoc sites (parse-config typedef, load-config, post-process-config, resolve-available-ports, commands/start). | +| **F7** — Sequencing wrong about parallelism | **CLOSED** | Revision log entry "F7"; §4 now shows Step 3 as serial (must precede Step 4) and notes Steps 5/6 are sequential within `resolve-available-ports.js`. The single-implementer ordering and the multi-agent worker plan both reflect this realistically. | +| **F8** — Rollback paragraph missing cached-compose note | **CLOSED** | Revision log entry "F8"; §7 ends with a "Cached compose caveat." paragraph describing the post-fallback port pinned in `~/.wp-env//docker-compose.yml`, the behavior of already-running environments, and the recommended one-line note for the revert PR. | + +Net: **3 of 3 blockers CLOSED, 8 of 8 minor findings CLOSED, 0 NOT CLOSED, 0 PARTIALLY CLOSED.** + +--- + +## Non-enumerable-property design verification (round-2-specific check) + +Plan v2's B1 fix hinges on the claim that attaching `__defaultOriginPorts` as a non-enumerable property to the merged config will be invisible to `mergeConfig` iteration, JSON serialization, and Jest `toEqual`. I verified each leg: + +- **`mergeConfig` iteration.** `packages/env/lib/config/merge-configs.js` line 39: `for ( const option in config ) {` — `for…in` walks own-and-inherited enumerable keys. Non-enumerable own properties are skipped. (Same at line 81: `for ( const option in toMerge )`.) `mergeConfigs` is the only consumer along the parseConfig → loadConfig → postProcessConfig path that iterates the config object's keys generically. Other call sites (e.g. `appendPortToWPConfigs`, `validatePortUniqueness`) read named properties (`config.env`, `config.env[env].port`, etc.) and never iterate the root object. So the non-enumerable property cannot leak into the merge path. +- **JSON serialization.** `JSON.stringify` walks own-enumerable properties; non-enumerable properties are omitted. Plan's regression test "`__defaultOriginPorts is invisible to mergeConfigs and toEqual`" asserts `JSON.parse(JSON.stringify(parsed))` drops the property, locking this in. +- **Jest `toEqual`.** Jest's recursive equality compares own-enumerable properties; non-enumerable own properties are not compared. So `expect( parsed ).toEqual( DEFAULT_CONFIG )` continues to pass even though `parsed` carries the extra hidden property. The same regression test asserts this. +- **Object iteration mechanism in the actual code path.** I confirmed the iteration mechanism inside `mergeConfig` is `for…in`, **not** `Object.keys` / `Object.entries` / spread-into-new-object. (All three of those would also skip non-enumerable properties — `Object.keys`/`Object.entries` walk own-enumerable; object spread `{...config}` also copies only own-enumerable properties — so even a future refactor that switches mechanisms would preserve the contract. But as written today, the mechanism is `for…in`.) + +The trick works as plan v2 claims. No risk of leakage along the existing code paths. + +--- + +## Spot-check of cited line numbers in plan v2 + +I picked five citations across the plan and re-read each in the source. + +1. **`parse-config.js:86-111` `DEFAULT_ENVIRONMENT_CONFIG` with `autoPort: false` at line 93.** Verified — `DEFAULT_ENVIRONMENT_CONFIG` opens at line 86 and closes at line 111; `autoPort: false,` is line 93 verbatim. Step 1 sub-step 1 target. +2. **`parse-config.js test:21-71` inline `DEFAULT_CONFIG` fixture, `autoPort: false` at line 24.** Verified — fixture spans lines 21–70; `autoPort: false,` is at line 24. Step 1 sub-step 4 target. +3. **`load-config.js:96-109` `shouldAutoPort` block.** Verified — lines 96–109 contain the `let portResolver; if ( resolvePorts ) { let shouldAutoPort = …; if ( process.env.CI ) { shouldAutoPort = false; } if ( shouldAutoPort ) { portResolver = createPortResolver( spinner ); } }` block exactly as described in Step 2. +4. **`resolve-available-ports.js:50` `resolve(preferredPort, configPath, strict = false)`.** Verified — line 50 reads `async resolve( preferredPort, configPath, strict = false ) {` with `strict` as the third parameter and a default of `false`. Step 5's claim that the resolver already supports the third arg is correct. +5. **`runtime/docker/build-docker-compose-config.js:173, 267` port interpolation sites.** Verified — line 173 is `` const developmentPorts = `\${WP_ENV_PORT:-${ config.env.development.port }}:80`; `` and line 267 is `` const testsPorts = `\${WP_ENV_TESTS_PORT:-${ config.env.tests.port }}:80`; ``. OQ6 resolution claim correct. + +Bonus spot-checks (not strictly required but useful): +- `cli.js:154-159` `--auto-port` yargs definition: confirmed at lines 154–158, `type: 'boolean'`, no `default` → missing arg is `undefined`. +- `lib/test/cli.js:35-52` tri-state assertions: confirmed (lines 35–52 cover `start` parses with no flag → `autoPort` undefined; with `--auto-port` → `true`; with `--no-auto-port` → `false`). +- `start.js:55-59` `loadConfig({ resolvePorts: true, autoPort, spinner })`: confirmed. +- `stop.js:21-31` consumes cached compose without `resolvePorts`: confirmed (`stop.js:26` calls `loadConfig(path.resolve('.'), customConfigPath)` with no third arg, so `resolvePorts` defaults to `false`). +- `get-config-from-environment-vars.js:36-72` env-var enumeration: confirmed (`WP_ENV_PORT` line 38, `WP_ENV_TESTS_PORT` line 40, plus mysql/phpmyadmin variants — OQ4 resolution scope correct). +- README `autoPort` row at line 609 and "Automatic Port Selection" at lines 620–630: confirmed. +- CHANGELOG `## Unreleased` at line 3: confirmed. + +All cited line numbers in plan v2 match the source. No drift. + +--- + +## Over-correction / new-scope check + +I scanned plan v2 for design that goes beyond what the spec requires: + +- The non-enumerable-property design is the minimal mechanism that satisfies AC10 + R3 / R6 without breaking existing tests. Not over-correction; it is the smallest fix for B1. +- The phpmyadminPort `continue` skip in Step 5 is the smallest fix that preserves today's behavior verbatim. The spec explicitly puts phpmyadminPort out of scope (§5 of the spec), so refusing to extend the resolver to it is *under*-engineering on purpose, not over-correction. Good. +- The new behavior-level integration test for AC4 (F3) is symmetric with the existing AC5 integration test. Not new scope; just covering an already-required AC at the boundary level. +- The JSDoc-review checklist in Step 12 is documentation hygiene tied to the typedef changes the plan already requires; not new scope. +- The cached-compose caveat in §7 is informational text, not new design. + +No over-correction or new-scope detected. + +--- + +## Revision-log drift check + +I read each revision-log entry against the corresponding body section. + +- **B1** ↔ Step 3 (rewritten to attach non-enumerably), Step 2 (parseConfig call shape unchanged), Step 4 (reads `config.__defaultOriginPorts`): consistent. +- **B2** ↔ Step 1 sub-step 4 (fixture edit explicit) and test plan §3 row "Modified — `DEFAULT_CONFIG` fixture": consistent. Revision log also notes the `should accept autoPort as a boolean` test is unaffected by the fixture change because it asserts only `parsed.autoPort` — verified by reading `parse-config.js test:196-207`, the test indeed only asserts `parsed.autoPort` and does not use `DEFAULT_CONFIG`. +- **B3** ↔ Step 5 per-port skip rule and the two regression-detector tests in test plan §3: consistent. +- **F1** ↔ OQ6 resolution in §1 cites the full path: consistent. +- **F2** ↔ Step 12 inline-fixture verification + grep evidence + Step 1 sub-step 4 cross-reference: consistent. +- **F3** ↔ test plan §3 new row for AC4 behavior-level test: consistent. +- **F4** ↔ Step 6 cites the `spinner.warn(...); spinner.start();` precedent in `start.js:98-101` and `start.js:105-112`, plus `spinner.info(...)` precedent in `start.js:169-193`; test plan asserts call order: consistent. +- **F5** ↔ OQ7 wording in §1 cleaned up: consistent. +- **F6** ↔ Step 12 JSDoc-review checklist: consistent. +- **F7** ↔ §4 sequencing diagram showing Step 3 serial and Steps 5/6 sequential: consistent. +- **F8** ↔ §7 "Cached compose caveat." paragraph: consistent. + +No drift between revision log and body. + +--- + +## AC coverage matrix (re-audited for round 2) + +| AC | Plan step(s) | Test(s) | OK? | +|---|---|---|---| +| AC1 | Steps 1, 2, 3, 4, 5 | parse-config provenance tests + integration test "no user autoPort and busy default port falls back via defaults-only mode" + "uses strict mode for non-default-origin ports and non-strict for default-origin ports" | Yes | +| AC2 | Steps 1, 2, 3, 4, 5 | same as AC1 (covers both env keys symmetrically) | Yes | +| AC3 | Steps 1, 2, 3, 4, 5 | "routes user-set port to strict and default-origin port to non-strict" + four parse-config provenance tests (local / env.tests / override / WP_ENV_PORT) + matching WP_ENV_TESTS_PORT test | Yes | +| AC4 | Steps 2, 5 | routing-matrix test + "CLI autoPort=true and user config autoPort=false has CLI win" + new behavior-level integration test "CLI autoPort=true and explicit user port falls back when port is busy" | Yes (F3 closed) | +| AC5 | Steps 1, 2, 5 | "autoPortMode=off" routing test + "loadConfig with autoPort:false in user config skips fallback even on default ports" | Yes | +| AC6 | Step 2 (CI guard) | "CI=1 disables fallback regardless of autoPort:true" + "CI=1 disables fallback even when autoPort is unset" | Yes | +| AC7 | Step 6 | five resolver-notice tests (emits-once-and-re-arms / not-emitted-on-no-move / not-emitted-on-strict-fail / no-console-write-regression / silent-without-spinner) | Yes | +| AC8 | Step 2 + named test | "CI=1 disables fallback regardless of autoPort:true" is the named regression detector | Yes | +| AC9a | Step 4 | "postProcessConfig threads autoPortMode and defaultOriginPorts to resolveConfigPorts" asserts WP_HOME/WP_SITEURL reflect resolved port | Yes | +| AC9b | Manual recipe in §3 | PR test plan recipe enumerated | Yes (manual per spec) | +| AC9c | Inherited from cached compose pattern | None automated; manual per recipe (rationale documented) | Yes (manual per spec) | +| AC10 | Step 12 + back-compat tests | Full-suite green; B1 / B2 fixes mean existing tests now stay green | Yes (B1 + B2 closed) | +| AC11 | Steps 1, 2, 7 | "should accept autoPort as a tri-state (null default, true, false)" + integration test asserting tri-state survives end-to-end | Yes | + +All ACs covered with at least one automated test or a documented manual verification per spec. + +--- + +## Verification of required-check items from the team prompt + +1. **Each round-1 finding now closed.** All B1, B2, B3 and F1–F8 are CLOSED with cited sections (table above). +2. **Non-enumerable trick verified in actual code path.** `merge-configs.js:39` and `:81` use `for…in` (verified by reading the file) and `for…in` skips non-enumerable properties (well-defined JS). The plan also locks the contract with a regression test that asserts `propertyIsEnumerable === false` and `JSON.parse(JSON.stringify(parsed))` drops the property. +3. **Five line-number spot-checks.** All five (`parse-config.js:86-111`/`:93`, `parse-config.js test:21-71`/`:24`, `load-config.js:96-109`, `resolve-available-ports.js:50`, `runtime/docker/build-docker-compose-config.js:173`/`:267`) match the source exactly. +4. **Over-correction / new scope.** None detected. The B1/B2/B3 fixes are minimal; the new AC4 test is symmetric with an existing AC5 test; phpmyadminPort is intentionally left out of scope as the spec requires. +5. **Revision-log drift.** None detected. Each log entry maps cleanly to a body change. + +--- + +## Minor observations (non-blocking) + +These are not gates; documenting them so the implementer is not surprised. + +- **N1.** Step 12 mentions running `grep` against `packages/env/lib/test/__snapshots__/md5.js.snap`; that file does not exist in the current checkout (the directory `packages/env/lib/test/__snapshots__/` is empty). The substantive claim (no `autoPort` references in any snapshot) holds because the only existing snapshot file (`packages/env/lib/config/test/__snapshots__/config-integration.js.snap`) contains no `autoPort`. The plan slightly over-cites; this does not affect correctness. +- **N2.** The plan uses a non-enumerable, non-writable, non-configurable property descriptor (`Object.defineProperty(merged, '__defaultOriginPorts', { value: …, enumerable: false, writable: false, configurable: false })`). That is correct and safe, but the implementer should be aware that any future code path that tries to overwrite `merged.__defaultOriginPorts` will silently fail in non-strict mode and throw in strict mode. The plan does not have such an overwrite path, and the wp-env package opts in to `'use strict'` at the file level (e.g. `parse-config.js:1`), so an accidental overwrite would throw — which is actually the desired behavior. No action required; just noting for the implementer. + +--- + +## Verdict + +``` +APPROVED +``` + +All three round-1 blockers (B1, B2, B3) are closed with concrete plan changes that are grounded in re-verified source citations. All eight minor findings (F1–F8) are closed. The non-enumerable-property design works as the plan claims — the `for…in` iteration in `merge-configs.js` is well-defined to skip non-enumerable own properties, Jest `toEqual` and `JSON.stringify` likewise ignore them, and a dedicated regression test locks the contract. Spot-checks of five cited line numbers all matched the source. No over-correction, no new scope, no revision-log drift detected. + +The plan is ready to drive implementation. diff --git a/.pipelines/49843-wp-env-default-port-fallback/plan.md b/.pipelines/49843-wp-env-default-port-fallback/plan.md new file mode 100644 index 00000000000000..58ef8e185d46a3 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/plan.md @@ -0,0 +1,348 @@ +# Phase 2 — Implementation plan + +Pipeline: `49843-wp-env-default-port-fallback` +Spec: `spec.md` (round 2 APPROVED). +Scope: `packages/env/` only. + +--- + +## Revision log + +Round 2 revisions, in response to `plan-review-1.md`: + +- **B1 (blocker)** — `parseConfig` return shape change broke ~25 existing tests. Resolved by changing the design: instead of returning `{ config, defaultOriginPorts }`, attach `defaultOriginPorts` to the returned config object as a **non-enumerable** property named `__defaultOriginPorts` (a `Set`). Existing destructurings, `expect( parsed ).toEqual( DEFAULT_CONFIG )` calls, and `Object.keys` / `for…in` iteration in `mergeConfig` (`merge-configs.js:39,81`) all skip non-enumerable properties, so the existing test suite is unchanged. The plan now uses this single approach (Step 3 rewritten); the consumer in `load-config.js` reads `config.__defaultOriginPorts` (Step 2 updated), and `postProcessConfig` reads it from the same config object (Step 4 updated). This also removes the need to change the call shape in `load-config.js:90-94`. +- **B2 (blocker)** — `DEFAULT_ENVIRONMENT_CONFIG.autoPort` flip from `false` to `null` breaks the `DEFAULT_CONFIG` fixture at `parse-config.js:21-71` (line 24) which is consumed by `toEqual( DEFAULT_CONFIG )` and spread-based assertions throughout the file. Resolved by making "update the test fixture" an explicit sub-step of Step 1 (point 4) AND by enumerating the affected assertions in the test plan §3 row "Modified — `DEFAULT_CONFIG` fixture". Also the modified test `should accept autoPort as a boolean` (line 196) is unaffected by this fixture change because it asserts only `parsed.autoPort` (not `toEqual( DEFAULT_CONFIG )`). +- **B3 (blocker)** — `phpmyadminPort` would silently auto-move under `defaults-only` mode. Resolved by extending the strict-routing rule in `resolveConfigPorts` (Step 5) so that under `autoPortMode='defaults-only'`, **only HTTP ports (`property === 'port'`) get any non-strict treatment**; for `phpmyadminPort` the resolver is skipped entirely (no resolver call at all), preserving today's behavior verbatim — today phpmyadminPort is only resolved when `--auto-port` is set, which corresponds to the new `autoPortMode='all'` mode. This avoids both the silent-move regression and any need to thread provenance for phpmyadminPort. Spec is unchanged (phpmyadminPort is out of scope per §5). +- **F1 (minor)** — `build-docker-compose-config.js` path is `packages/env/lib/runtime/docker/build-docker-compose-config.js` (verified: the file at `packages/env/lib/build-docker-compose-config.js` does NOT exist; only the one under `runtime/docker/` and its test at `packages/env/lib/test/build-docker-compose-config.js`). All references in the plan now use the full path. +- **F2 (minor)** — Snapshot drift expectation is corrected: `grep autoPort` against `packages/env/lib/test/__snapshots__/md5.js.snap` and `packages/env/lib/config/test/__snapshots__/config-integration.js.snap` returns zero hits, so no `autoPort`-related snapshot churn is expected. The real fixture risk (the inline `DEFAULT_CONFIG` at `parse-config.js:21-71`, line 24) is now called out in Step 1 sub-step 4 and re-confirmed in Step 12. +- **F3 (minor)** — Added an AC4 behavior-level integration test (`loadConfig with CLI autoPort=true and explicit user port falls back when port is busy`) in `config-integration.js`, matching the symmetry of the AC5 integration test. +- **F4 (minor)** — Step 6 now cites the existing `start.js:98-101` and `start.js:105-112` precedent of `spinner.warn(...); spinner.start();` and the test plan asserts call order (`spinner.info` before `spinner.start`). +- **F5 (minor)** — OQ7 wording is cleaned up; the resolution now reads correctly: "all non-empty strings are truthy; empty string and `undefined` are falsy". The implementation is unchanged (`if ( process.env.CI )`). +- **F6 (minor)** — Step 12 now includes a JSDoc-review checklist line (verify the `WPRootConfigOptions` typedef in `parse-config.js`, the `loadConfig` JSDoc in `load-config.js`, and the `start` JSDoc in `commands/start.js` reflect the new tri-state). +- **F7 (minor)** — Sequencing diagram in §4 corrected: step 3 is serial (must precede step 4), and step 6 cannot run literally in parallel with step 5 because both edit the same file. Updated to show realistic ordering for both single-implementer and multi-agent scenarios. +- **F8 (minor)** — §7 Rollback paragraph extended with a one-sentence note about cached `docker-compose.yml` files retaining post-fallback ports across a revert. + +--- + +## 1. Plan summary + +The chosen design shape: extend the existing `--auto-port` / `autoPort` machinery (PR #74472) with two narrow tweaks rather than introduce parallel code paths. + +1. **Tri-state `autoPort`.** Change `DEFAULT_ENVIRONMENT_CONFIG.autoPort` from `false` to `null` so that the "unset" state survives merging. CLI parsing already preserves `undefined`/`true`/`false` (verified — see OQ-resolutions). `load-config.js` becomes the single point where the tri-state is interpreted into a runtime decision: `'all'` (today's PR #74472 behavior) | `'defaults-only'` (new behavior) | `'off'` (explicit opt-out). +2. **Per-port "user-set" provenance, attached as a non-enumerable property.** Track which environment ports came from `DEFAULT_ENVIRONMENT_CONFIG` versus from any user source (root `.wp-env.json`, `.wp-env.override.json`, env vars). The mechanism is a small `Set` (`__defaultOriginPorts`) built in `parseConfig` (in `parse-config.js`), attached to the returned config via `Object.defineProperty(config, '__defaultOriginPorts', { value: …, enumerable: false })`. `mergeConfig` in `merge-configs.js:39,81` iterates with `for ( const option in config )` which excludes non-enumerable properties, so existing tests' `toEqual` and destructure expectations are untouched. `loadConfig` reads `config.__defaultOriginPorts` and threads it into `postProcessConfig` → `resolveConfigPorts`. `resolveConfigPorts` then decides per-port whether to use the existing `findAvailablePort` (auto-fallback) or the existing `isPortAvailable` strict path, based on `(autoPortMode, isDefaultOrigin, property)`. + +The port resolver is invoked from `loadConfig` whenever EITHER `autoPortMode === 'all'` (today's PR #74472 contract) OR `autoPortMode === 'defaults-only'` (the new behavior). In the new mode, only HTTP ports (`property === 'port'`) participate in the routing decision; `phpmyadminPort` is **only** auto-resolved under `'all'` mode (preserving today's behavior verbatim). The `process.env.CI` guard stays in `load-config.js` and short-circuits both modes by forcing `'off'`. The "moved port" notice (R11/AC7) is added to `createPortResolver` so it fires only when the resolved port differs from the preferred port and goes through the same `spinner` instance the resolver already accepts. + +No new top-level config option is introduced. No new CLI flag is introduced. No package boundary is crossed. `appendPortToWPConfigs` is unchanged: it already consumes `config.env[env].port`, which now reflects the resolved port (R8 / AC9a). For other commands (R8 / AC9c), the existing pattern of writing the resolved port into the cached `docker-compose.yml` during `start` already covers `stop`/`destroy`/`logs`/`run` because they operate against the cached compose file by container name; no additional port re-resolution is needed in those commands. + +### Resolution of OQ1–OQ7 (each cited to source) + +- **OQ1 — Per-environment `autoPort`.** Resolved: root-only. `parse-config.js:481-493` lists `autoPort` in the switch's case-block of `parseEnvironmentConfig` (specifically `case 'autoPort':` at line 483), allowed only when `options.rootConfig` is true. `parse-config.js:390-397` parses it only on the root config path. Plan inherits root-only and does not extend it. +- **OQ2 — Provenance tracking mechanism.** Resolved: a `Set` (`defaultOriginPorts`) built in `parseConfig` (in `parse-config.js`) and attached to the returned config object as a non-enumerable property `__defaultOriginPorts`. The Set is populated as the inverse of "any non-default config layer set this key" — see step 3. Citation: `parse-config.js:130-167` shows the merge order (`localConfig`, `overrideConfig`, `defaultConfig` from `getDefaultConfig`, `environmentVarOverrides`); each non-default layer can be inspected for whether it provided `port`/`testsPort`/`env.development.port`/`env.tests.port`. The non-enumerable approach is chosen so `mergeConfig` (which iterates via `for…in` at `merge-configs.js:39,81`) does not see it during merging and so existing tests' `toEqual(DEFAULT_CONFIG)` assertions remain unchanged. +- **OQ3 — Multiple override layers.** Resolved: any non-default layer (`localConfig`, `overrideConfig`, `environmentVarOverrides`) that sets the port marks the port as "user-set". Citation: same `parse-config.js:130-167` merge sequence; environment vars are produced by `getEnvironmentVarOverrides` at `parse-config.js:284-344` and we inspect the same struct that already exists. +- **OQ4 — env-var sources for ports.** Resolved: enumerated from `get-config-from-environment-vars.js:36-72` — the user-set port-yielding env vars are `WP_ENV_PORT`, `WP_ENV_TESTS_PORT`, `WP_ENV_MYSQL_PORT`, `WP_ENV_TESTS_MYSQL_PORT`, `WP_ENV_PHPMYADMIN_PORT`, and `WP_ENV_TESTS_PHPMYADMIN_PORT`. Of these, only `WP_ENV_PORT` and `WP_ENV_TESTS_PORT` are in scope of this feature (HTTP ports). `mysqlPort` is out of scope per spec §5; `phpmyadminPort` is out of scope per spec §5 and per the B3 resolution above (see Step 5). +- **OQ5 — Behavior when no upward port is available.** Resolved: re-use existing failure mode. `port-utils.js:51-80` already throws `Error('No available port found in range ${startPort}-${maxPort}.')` and that error is wrapped in `resolve-available-ports.js:84-87` into `Could not find available port for : ...`. Plan does not change this; the error already surfaces to the spinner via `withSpinner` in `cli.js:24-93` (rejection branch at lines 46-92). +- **OQ6 — Re-resolution on every `start`; downstream commands consume cached compose.** Resolved: confirmed by tracing — `start.js:55-59` calls `loadConfig({ resolvePorts: true, ... })`, `post-process-config.js:35-37` writes the resolved port into `config.env[env].port` (and therefore into the env-merged config consumed by `appendPortToWPConfigs` at `post-process-config.js:39`), `runtime/docker/build-docker-compose-config.js:173,267` interpolates that port into the cached `docker-compose.yml`, and downstream commands such as `stop.js:21-31` operate on `dockerComposeConfigPath` by container name (no port re-resolution). So a stale running environment from a prior wp-env version is unaffected until the next `start`, which re-resolves freshly. No persisted-state file is needed. +- **OQ7 — `CI` truthiness.** Resolved: inherit verbatim from `load-config.js:102-104` — `if ( process.env.CI )`. JavaScript truthy semantics: any non-empty string is truthy (so `"true"`, `"1"`, `"false"`, `"0"`, etc. are all truthy as strings); `undefined` and the empty string are falsy. The plan does not redefine this; it relies on the existing one-liner. + +No OQs are deferred to "the implementer will figure it out". Zero blockers. + +--- + +## 2. Steps + +### Step 1 — Make `autoPort` tri-state at the config-default layer + +- **Goal.** Stop collapsing `undefined → false` at the default-config layer so that "unset" survives merging and is observable inside `load-config.js`. +- **Files touched.** + - `packages/env/lib/config/parse-config.js` + - `packages/env/lib/config/test/parse-config.js` (fixture only — see sub-step 4) +- **Change description.** + 1. In `DEFAULT_ENVIRONMENT_CONFIG` (currently `parse-config.js:86-111`, specifically line 93), change `autoPort: false` to `autoPort: null`. `null` is the sentinel for "user did not set this" (chosen over `undefined` so the key stays present after `mergeConfigs` for snapshot/typedef stability). + 2. In the `WPRootConfigOptions` typedef comment block (`parse-config.js:32-44`, specifically the `@property` line at line 38), update the `autoPort` `@property` line to `boolean|null` and refine the description to "Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports)." + 3. In `parseRootConfig`, the existing block at `parse-config.js:390-397` already only assigns `parsedConfig.autoPort` when `rawConfig.autoPort !== undefined`; no change there. The change at the default layer is sufficient because the merge in `mergeConfigs` will now leave a non-user-set `autoPort` as `null`. + 4. **Update the inline test fixture `DEFAULT_CONFIG` in `packages/env/lib/config/test/parse-config.js:21-71`, line 24: change `autoPort: false` to `autoPort: null`.** This fixture is `toEqual()`-compared at `parse-config.js test:91, 193, 232, 293, 305` and is used as a spread base at `parse-config.js test:166, 232, 305, 500, 531, 557` (`...DEFAULT_CONFIG`, `...DEFAULT_CONFIG.env.development`). The single fixture edit fixes all of those in one step. The named test `'should accept autoPort as a boolean'` at `parse-config.js test:196-207` does NOT use `DEFAULT_CONFIG` and is updated separately in Step 10 (it must additionally assert that the **default** is `null`). +- **Spec ACs covered.** AC11, AC1, AC2, AC5 (foundational — all rely on this). +- **Depends on.** None. + +### Step 2 — Reinterpret `autoPort` in `loadConfig` as tri-state + +- **Goal.** Replace the binary on/off interpretation in `load-config.js` with a tri-state interpretation, and decide whether to invoke the port resolver. +- **Files touched.** + - `packages/env/lib/config/load-config.js` +- **Change description.** + - At `load-config.js:96-109`, replace the existing block that computes `shouldAutoPort` with a new computation that yields one of three values for an internal variable `autoPortMode`: `'all'` (today's PR #74472 behavior — `true`), `'defaults-only'` (new behavior — `null`/`undefined`), or `'off'` (explicit opt-out — `false`). Source precedence is unchanged: CLI `autoPort` parameter beats `config.autoPort`. + - Mapping: CLI `true` → `'all'`; CLI `false` → `'off'`; CLI `undefined` AND `config.autoPort === true` → `'all'`; CLI `undefined` AND `config.autoPort === false` → `'off'`; CLI `undefined` AND (`config.autoPort === null` or `undefined`) → `'defaults-only'`. + - The existing `process.env.CI` guard (lines 102-104) is rewritten to force `autoPortMode = 'off'` when CI is truthy. (Same observable behavior, slightly different shape so the guard sits in front of the resolver gate.) + - Always create a `portResolver` when `resolvePorts` is true and `autoPortMode !== 'off'`. (Today the resolver is only created when `shouldAutoPort` is truthy. The new resolver still behaves correctly with no default-origin ports — see step 5 for the per-port routing — but it must exist so `defaults-only` mode can fire on default HTTP ports.) + - Read `config.__defaultOriginPorts` from the parsed config (a `Set`; see Step 3) — fall back to `new Set()` if the property is absent. Pass it through to `postProcessConfig` along with `autoPortMode`. The signature of `postProcessConfig` is extended to accept `{ portResolver, autoPortMode, defaultOriginPorts }` (see step 4). + - Update the JSDoc on `loadConfig` to describe the new tri-state. + - The call to `parseConfig` at `load-config.js:90-94` is **unchanged in shape** — `parseConfig` still returns the merged config object directly (the `__defaultOriginPorts` is a non-enumerable property attached to that object). +- **Spec ACs covered.** AC1, AC2, AC3, AC4, AC5, AC6, AC11. +- **Depends on.** Step 1. + +### Step 3 — Track default-origin port provenance in `parseConfig` + +- **Goal.** Build a `Set` (`defaultOriginPorts`) listing port keys whose value came from `DEFAULT_ENVIRONMENT_CONFIG` and was NOT overridden by any user-supplied source (root or override JSON, or environment variable). Attach it to the returned config object as a non-enumerable property. +- **Files touched.** + - `packages/env/lib/config/parse-config.js` +- **Change description.** + - In `parseConfig` (`parse-config.js:124-168`), after computing `localConfig`, `overrideConfig`, and `environmentVarOverrides` (lines 129-158) and BEFORE the final `return mergeConfigs(...)` at lines 162-167, build a `defaultOriginPorts` Set. + - Implement as a small helper `function computeDefaultOriginPorts(localConfig, overrideConfig, envVarOverrides)` returning a `Set` containing zero or more of `'development.port'` and `'tests.port'`. + - For each of the two HTTP ports (`'development.port'`, `'tests.port'`), the port is "default-origin" iff none of the following provided it: + - `localConfig?.port` (root-level, hoisted to development by `mergeRootToEnvironments` later). + - `localConfig?.testsPort` (root-level, hoisted to tests). + - `localConfig?.env?.development?.port` / `localConfig?.env?.tests?.port` (env-specific). + - The same five paths on `overrideConfig`. + - `envVarOverrides.port` (set by `getEnvironmentVarOverrides` at `parse-config.js:301-304` when `WP_ENV_PORT` is defined; same for `testsPort` at lines 316-319). + - Note: `envVarOverrides.env.development.port` and `envVarOverrides.env.tests.port` are also set in those same blocks; either one being present is sufficient signal. + - Capture the merge result in a local `merged` variable instead of returning it directly, then attach the Set: + - `Object.defineProperty(merged, '__defaultOriginPorts', { value: defaultOriginPortsSet, enumerable: false, writable: false, configurable: false })`. + - Return `merged`. + - Why non-enumerable: `mergeConfig` in `merge-configs.js` iterates via `for ( const option in ... )` at lines 39 and 81. Non-enumerable properties are skipped by `for…in`. `JSON.stringify` and `Object.keys` also skip them. `expect( parsed ).toEqual( DEFAULT_CONFIG )` (Jest) compares own-enumerable properties only. Therefore attaching `__defaultOriginPorts` does not affect `mergeConfig`, JSON serialization, or Jest equality checks. (Verified semantics; see existing tests at `packages/env/lib/config/test/parse-config.js:91, 193, 232, 293, 305, 506, 537, 560`.) + - The `parseConfigFile` and `parseRootConfig` internals do not need to know about provenance; only `parseConfig` itself does, because it has visibility into all four sources at once. + - `getConfigFilePath` exports — unchanged. +- **Spec ACs covered.** AC1, AC2, AC3, AC5. +- **Depends on.** Step 1 (the default `autoPort` change is independent, but Step 3 must run before Step 4 can consume its output). + +### Step 4 — Thread `defaultOriginPorts` through `postProcessConfig` + +- **Goal.** Hand the per-port provenance to the place that decides `findAvailablePort` vs. `isPortAvailable` strict. +- **Files touched.** + - `packages/env/lib/config/post-process-config.js` +- **Change description.** + - Update the exported `postProcessConfig` signature from `(config, { portResolver })` (currently `post-process-config.js:24-27`) to `(config, { portResolver, autoPortMode = 'off', defaultOriginPorts = new Set() })`. Defaults preserve current behavior for the existing call sites that do not opt in. + - In the body, where the existing call `await resolveConfigPorts( config, portResolver )` is at line 36, change it to `await resolveConfigPorts( config, portResolver, { autoPortMode, defaultOriginPorts } )`. + - No other behavior in `postProcessConfig` changes. `mergeRootToEnvironments`, `appendPortToWPConfigs`, and `validatePortUniqueness` are untouched. + - Update the JSDoc to describe the two new options. +- **Spec ACs covered.** AC1, AC2, AC3, AC5, AC9a. +- **Depends on.** Step 3. + +### Step 5 — Per-port strict/non-strict routing in `resolveConfigPorts` + +- **Goal.** Use the per-port provenance + tri-state to decide, for each port, whether to call the existing `findAvailablePort` (auto-fallback) path, the existing `isPortAvailable` strict path, or skip the port entirely (preserving today's behavior). +- **Files touched.** + - `packages/env/lib/resolve-available-ports.js` +- **Change description.** + - Update the exported `resolveConfigPorts(config, portResolver)` signature (currently `resolve-available-ports.js:100`) to `resolveConfigPorts(config, portResolver, { autoPortMode = 'off', defaultOriginPorts = new Set() } = {})`. + - Inside the loop over `PORT_DEFINITIONS` (currently `resolve-available-ports.js:101-127`), add a small early-exit and a `strict` decision: + - **Per-port skip rule** (preserves today's behavior for `phpmyadminPort` under the new mode): + - If `autoPortMode === 'defaults-only'` AND `property !== 'port'` (i.e. `phpmyadminPort`): `continue` — skip this port entirely. Today phpmyadminPort is only resolved when `--auto-port` is on (because the resolver itself is only created in that case); under `'defaults-only'` we keep that exact behavior verbatim by skipping the port. (B3 resolution.) + - **Strict decision** for the remaining ports: + - If `autoPortMode === 'off'` → `strict = true`. (Note: in this branch the resolver is never created in `load-config.js`, so this case is unreachable in production. We still set it defensively for correctness when the function is unit-tested.) + - If `autoPortMode === 'all'` → `strict = false`. (Today's PR #74472 behavior, including the existing `phpmyadminPort` non-strict path which we preserve here when the property is `phpmyadminPort` because the skip rule above does not apply.) + - If `autoPortMode === 'defaults-only'` AND `property === 'port'`: `strict = ! defaultOriginPorts.has( '${env}.port' )`. That is, default-origin ports get auto-fallback (strict=false); user-set ports stay strict (AC1, AC2, AC3). + - Pass `strict` as the third argument to `portResolver.resolve(preferredPort, configPath, strict)` — the resolver already supports this third parameter at `resolve-available-ports.js:50`. + - `createPortResolver` is updated separately in step 6 for the messaging contract; the `resolve` signature here is unchanged. + - The `PREFERRED_PORTS` table (`resolve-available-ports.js:23-26`) and the lookup `currentValue ?? PREFERRED_PORTS[ key ]` (line 113) are unchanged. + - Update the JSDoc on `resolveConfigPorts` to document the two new options. +- **Spec ACs covered.** AC1, AC2, AC3, AC4, AC5, AC9a. +- **Depends on.** Steps 2, 3, 4. + +### Step 6 — Add the "moved port" notice to `createPortResolver` + +- **Goal.** Implement R11 / AC7: emit an informational message via the existing spinner, only when the resolved port differs from the preferred port, with no new flag and no separate output channel. +- **Files touched.** + - `packages/env/lib/resolve-available-ports.js` +- **Change description.** + - Inside `createPortResolver`'s returned `resolve` method, in the non-strict branch (currently `resolve-available-ports.js:74-87`), after `findAvailablePort` resolves to `resolvedPort` and BEFORE `usedPorts.push( resolvedPort )` (line 80), compare `resolvedPort` to `preferredPort`. When they differ AND `spinner` exists, call: + - `spinner.info( 'Port ${preferredPort} (${configPath}) was busy; using ${resolvedPort} instead.' )` (exact message format chosen for clarity; the test in step 11 asserts a regex containing both port numbers and the string "busy"). + - Followed by `spinner.start()` to re-arm the spinner. Precedent: `start.js:98-101` and `start.js:105-112` use this exact `spinner.warn(...); spinner.start();` pattern; `start.js:169-193` uses `spinner.info(...)` followed by `spinner.start()`. + - The strict branch (lines 56-72) is unchanged — when the port is busy in strict mode, the existing `throw new Error(...)` at lines 65-69 already surfaces via the spinner's `fail` path in `withSpinner` (`cli.js:46-92`). No "moved" notice fires on the strict path (matches AC7's "only when a fallback actually occurred"). + - When `spinner` is undefined (test path), suppress the notice silently. Implementation guard: `if ( spinner && resolvedPort !== preferredPort ) { ... }`. + - The notice MUST go through the same `spinner` instance that `--auto-port` already uses today (the one passed into `createPortResolver(spinner)`); do NOT introduce a new logger, console call, or stream. AC7's "regression detectable" clause means the test in step 11 asserts the call goes through the spinner (`spinner.info` was called) and that there is **no** `console.log` / `console.info` / `process.stdout.write` invocation. +- **Spec ACs covered.** AC1, AC2, AC4, AC7. +- **Depends on.** Step 5 (sequencing — both edit `resolve-available-ports.js`; step 5 lands first, then step 6 modifies `createPortResolver` in the same file). + +### Step 7 — Wire `start` to pass tri-state and provenance to `loadConfig` + +- **Goal.** Surface the new options on the call-site, and verify nothing else needs to change in `start.js`. +- **Files touched.** + - `packages/env/lib/commands/start.js` +- **Change description.** + - No public signature change. The existing `loadConfig( path.resolve('.'), customConfigPath, { resolvePorts: true, autoPort, spinner })` call at `start.js:55-59` already passes `autoPort` from yargs (which is `undefined` / `true` / `false`); the new tri-state interpretation in `load-config.js` (step 2) consumes that directly. Confirm by tracing: `cli.js:154-158` defines `--auto-port` as `type: 'boolean'` with no `default`, so missing → `undefined`; explicit `--auto-port` → `true`; explicit `--no-auto-port` → `false`. (Verified in `lib/test/cli.js:35-52`.) + - Update the JSDoc on `start` (`start.js:21-34`, specifically line 32 for `options.autoPort`) to describe `autoPort` as tri-state. +- **Spec ACs covered.** AC11 (CLI boundary preservation), AC1–AC6 (consumer correctness). +- **Depends on.** Step 2. + +### Step 8 — Documentation: README + +- **Goal.** Document the new default behavior and the `"autoPort": false` opt-out. +- **Files touched.** + - `packages/env/README.md` +- **Change description.** + - In the config table at `README.md:609`, update the `"autoPort"` row: change Default from `false` to `null` and rewrite the Description to "Tri-state: when unset (`null`), default ports `8888`/`8889` automatically fall back to the next available port if busy; explicitly `true` enables fallback for all ports including user-set ones; explicitly `false` disables fallback even on default ports." + - In the "Automatic Port Selection" section at `README.md:620-630`, rewrite to reflect the new contract: (a) by default, when the contributor has not pinned a port, busy default ports auto-fall-back upward; (b) explicitly configured ports remain strict unless `--auto-port` / `"autoPort": true` is set; (c) `"autoPort": false` is the opt-out for the default-fallback behavior; (d) `CI=1` continues to disable all auto-fallback. + - Keep the existing example `wp-env start --auto-port` and explain it still applies when contributors want explicit ports to also auto-fall-back. +- **Spec ACs covered.** AC documentation in spec §3 R14. +- **Depends on.** Step 2 (so that the documented semantics match implementation). + +### Step 9 — Documentation: CHANGELOG + +- **Goal.** List the user-visible change under the next unreleased version. +- **Files touched.** + - `packages/env/CHANGELOG.md` +- **Change description.** + - Under the existing `## Unreleased` heading at `CHANGELOG.md:3`, add a `### New Features` (or `### Enhancements`) subsection describing: "Default ports `8888` and `8889` now automatically fall back to the next available port when busy and the contributor has not set a port explicitly. Set `"autoPort": false` in `.wp-env.json` to opt out, or `CI=1` for CI runs." Reference issue `#49843`. + - Do NOT add a "breaking change" entry — the change is additive on the unset-port path; explicit ports are unchanged. +- **Spec ACs covered.** AC documentation in spec §3 R14. +- **Depends on.** Step 8 (so wording is consistent). + +### Step 10 — Unit tests for tri-state and provenance plumbing + +- **Goal.** Add automated tests covering AC1, AC2, AC3, AC4, AC5, AC6, AC9a, AC11. +- **Files touched.** + - `packages/env/lib/config/test/parse-config.js` + - `packages/env/lib/config/test/post-process-config.js` + - `packages/env/lib/config/test/config-integration.js` + - `packages/env/lib/test/resolve-available-ports.js` +- **Change description.** See test plan §3 below for the table. The DEFAULT_CONFIG fixture edit is in Step 1 (sub-step 4), not here. +- **Spec ACs covered.** AC1, AC2, AC3, AC4, AC5, AC6, AC8, AC9a, AC11. +- **Depends on.** Steps 1–7. + +### Step 11 — Unit tests for the "moved port" notice + +- **Goal.** Lock in AC7's "same output mechanism" contract such that introducing a new output path is a detectable regression. +- **Files touched.** + - `packages/env/lib/test/resolve-available-ports.js` +- **Change description.** See test plan §3 below. +- **Spec ACs covered.** AC7. +- **Depends on.** Step 6. + +### Step 12 — Snapshot, fixture, and JSDoc verification sweep + +- **Goal.** Verify snapshot churn is intentional and limited; verify all fixture and JSDoc updates landed. +- **Files touched.** + - `packages/env/lib/config/test/__snapshots__/config-integration.js.snap` (only if it changes — which is NOT expected; see verification below). +- **Change description.** + - Run `npm run test:unit -- packages/env` after steps 1–11 land. **Expectation:** no snapshot diffs (verified — `grep autoPort packages/env/lib/config/test/__snapshots__/config-integration.js.snap` and `… packages/env/lib/test/__snapshots__/md5.js.snap` both return zero hits today, so flipping `autoPort: false → null` does not affect any serialized snapshot). If a snapshot DOES change unexpectedly, inspect the diff before accepting; a sudden snapshot diff after this PR would indicate a regression and should be investigated rather than blanket-accepted with `--updateSnapshot`. AC10 requires this discipline. + - **Inline-fixture verification.** Confirm `DEFAULT_CONFIG.autoPort === null` in `packages/env/lib/config/test/parse-config.js:24` (changed in Step 1 sub-step 4). Confirm no other inline fixtures contain `autoPort: false` that need updating: `grep -rn "autoPort" packages/env/lib/`. Expected matches: `parse-config.js` (default), `parse-config.js test` (one fixture line + the named test + the `non-boolean autoPort` validation test), `load-config.js` (the new tri-state computation), `post-process-config.js` (the new option threading), `resolve-available-ports.js` (the new routing), `config-integration.js` (new integration tests). No other matches expected. + - **JSDoc verification checklist.** Confirm the JSDoc updates from steps 1, 2, 5, 7 landed: + - `parse-config.js` `WPRootConfigOptions` typedef line for `autoPort` reads `boolean|null` with the tri-state description. + - `load-config.js` `loadConfig` JSDoc describes `autoPort` as tri-state. + - `post-process-config.js` `postProcessConfig` JSDoc describes the two new options (`autoPortMode`, `defaultOriginPorts`). + - `resolve-available-ports.js` `resolveConfigPorts` JSDoc describes the two new options. + - `commands/start.js` `start` JSDoc line 32 describes `autoPort` as tri-state. +- **Spec ACs covered.** AC10. +- **Depends on.** All prior steps. + +--- + +## 3. Test plan + +| Test file | New / Modified | `it` name | Spec AC | Description | +|---|---|---|---|---| +| `packages/env/lib/config/test/parse-config.js` | **Modified — fixture** | `DEFAULT_CONFIG` fixture at line 21-71 | AC11 | Change `autoPort: false` to `autoPort: null` at line 24. Single edit; cascades through all `toEqual( DEFAULT_CONFIG )` and `...DEFAULT_CONFIG`-spread assertions (lines 91, 166, 193, 232, 293, 305, 500, 531, 557). Done in Step 1 sub-step 4. | +| `packages/env/lib/config/test/parse-config.js` | Modified | `should accept autoPort as a boolean` (line 196) | AC11 | Augment the existing assertion (`expect( parsed.autoPort ).toEqual( true )`) with a second case asserting that when no autoPort is set in any source, `parsed.autoPort` is `null` (the new default). Update the test name to `should accept autoPort as a tri-state (null default, true, false)`. | +| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig attaches __defaultOriginPorts as a non-enumerable Set with both http ports when no user config sets them` | AC1, AC2 | With `readRawConfigFile.mockResolvedValue(null)` and no env vars set, the returned config has a `__defaultOriginPorts` Set containing exactly `'development.port'` and `'tests.port'`. Also assert `Object.propertyIsEnumerable.call(parsed, '__defaultOriginPorts')` is `false`. | +| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits development.port from __defaultOriginPorts when local config sets root port` | AC3 | Local config sets `port: 9000`; Set contains `'tests.port'` but NOT `'development.port'`. | +| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits tests.port from __defaultOriginPorts when local config sets env.tests.port` | AC3 | Local config sets `env.tests.port: 9001`; Set contains `'development.port'` but NOT `'tests.port'`. | +| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits development.port from __defaultOriginPorts when override config sets port` | AC3 | `.wp-env.override.json` sets `port: 9000`; Set contains `'tests.port'` but NOT `'development.port'`. | +| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits development.port from __defaultOriginPorts when WP_ENV_PORT is set` | AC3 (R3 env-var clause), OQ4 | Set `process.env.WP_ENV_PORT = '4321'` before call (the existing `afterEach` at line 79-86 already cleans this up); assert Set lacks `'development.port'`. | +| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits tests.port from __defaultOriginPorts when WP_ENV_TESTS_PORT is set` | AC3 (R3 env-var clause), OQ4 | Mirror of above for `WP_ENV_TESTS_PORT`. | +| `packages/env/lib/config/test/parse-config.js` | New | `__defaultOriginPorts is invisible to mergeConfigs and toEqual (regression guard for B1 / non-enumerable contract)` | AC10 | Construct a fresh `parseConfig` result, run `JSON.parse(JSON.stringify(parsed))`, assert `__defaultOriginPorts` is absent in the round-trip, AND assert `expect(parsed).toEqual(DEFAULT_CONFIG)` still passes (i.e. `toEqual` does not see `__defaultOriginPorts`). This is the regression detector for any future change that flips the property to enumerable. | +| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig threads autoPortMode and defaultOriginPorts to resolveConfigPorts` | AC9a | Use a fake `portResolver` whose `resolve` is a `jest.fn()` returning `8890`; pass `{ portResolver, autoPortMode: 'defaults-only', defaultOriginPorts: new Set([ 'development.port', 'tests.port' ]) }` and a config with `env.development.port: 8888`, `env.tests.port: 8889`, plus `config: { WP_HOME: 'http://localhost', WP_SITEURL: 'http://localhost' }`. Assert `portResolver.resolve` is called with `(8888, 'env.development.port', false)` AND `(8889, 'env.tests.port', false)`. Assert the post-process result has `env.development.port === 8890` (from the mock return) and `env.development.config.WP_HOME === 'http://localhost:8890'` (i.e. `appendPortToWPConfigs` consumed the resolved port). | +| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig with autoPortMode=defaults-only routes user-set port to strict and default-origin port to non-strict` | AC1, AC2, AC3 | Pass `defaultOriginPorts: new Set([ 'development.port' ])` (i.e. tests port is user-set); assert the resolver call for `env.development.port` has third arg `false` and for `env.tests.port` has third arg `true`. | +| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig with autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)` | AC10, R3 | Provide a config with `env.development.port: 8888` and `env.development.phpmyadminPort: 8080`, `defaultOriginPorts: new Set([ 'development.port' ])`. Assert `portResolver.resolve` is called once for `'env.development.port'` and is NEVER called with `configPath` containing `'phpmyadminPort'`. This guards against the B3 regression where phpmyadminPort would silently auto-move under defaults-only mode. | +| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig with autoPortMode=all routes both http ports AND phpmyadminPort non-strict (preserves PR #74472 behavior)` | AC4 | Config with all three ports populated; `defaultOriginPorts: new Set()`; assert `resolver.resolve` is called for HTTP ports AND phpmyadminPort, all with `strict=false`. | +| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig defaults to autoPortMode=off and routes ports strict (back-compat)` | AC10 | Call `postProcessConfig(config, { portResolver })` with NO `autoPortMode` / `defaultOriginPorts` (the existing call shape from before this PR). Assert the resolver receives `strict=true` for HTTP ports and is also called for phpmyadminPort (because the skip rule only applies to `'defaults-only'`). This guards the back-compat default in Step 4. | +| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with no user autoPort and busy default port falls back via defaults-only mode` | AC1, AC11 | With no user config, mock the port resolver path: spy on `createPortResolver` to verify it IS created (not skipped). Mock `findAvailablePort` to return `8890` for preferred `8888`. Assert `config.env.development.port === 8890` and `config.env.development.config.WP_HOME === 'http://localhost:8890'`. | +| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with autoPort:false in user config skips fallback even on default ports` | AC5 | With `.wp-env.json` containing `{ "autoPort": false }`, mock `isPortAvailable` to return `false` for 8888 → assert `loadConfig` rejects with the strict port-busy error. | +| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CI=1 disables fallback regardless of autoPort:true` | AC6, AC8 | Set `process.env.CI = '1'`, set user config `{ "autoPort": true }`, mock the port-availability layer so 8888 is busy → assert `loadConfig` rejects with the strict port-busy error. The named test exists so removing the `if ( process.env.CI )` guard in `load-config.js` causes this test to fail — this is the AC8 regression detector. Cleanup `delete process.env.CI` in `afterEach`. | +| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CI=1 disables fallback even when autoPort is unset` | AC6 | Same as above but with no `autoPort` key in the config. | +| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CLI autoPort=true and user config autoPort=false has CLI win` | AC4 (precedence) | Asserts existing precedence (CLI beats config) is preserved by setting `customConfigPath` to a config with `autoPort: false` and passing `autoPort: true` in options; mock `findAvailablePort` to return a moved port; assert the moved port flows through. | +| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CLI autoPort=true and explicit user port falls back when port is busy (AC4 behavior-level)` | AC4 | Mirror of the AC5 integration test. With `.wp-env.json` setting `port: 9000` and CLI `autoPort: true`, mock `findAvailablePort` to return `9001`; assert `config.env.development.port === 9001` and `WP_HOME` reflects 9001. (Addresses F3.) | +| `packages/env/lib/test/resolve-available-ports.js` | Existing — keep | `should resolve a port in non-strict mode` (line 19) | AC1 | Existing test — keep; still asserts `findAvailablePort` is hit for non-strict calls. | +| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=defaults-only uses strict mode for non-default-origin ports and non-strict for default-origin ports` | AC1, AC2, AC3 | Mocks `findAvailablePort`/`isPortAvailable`. Calls `resolveConfigPorts(config, resolver, { autoPortMode: 'defaults-only', defaultOriginPorts: new Set([ 'development.port' ]) })` with both env ports populated. Asserts `findAvailablePort` was called for dev port (preferred 8888), `isPortAvailable` was called (strict path) for tests port (preferred 8889). | +| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)` | AC10, R3 | Config with `env.development.port: 8888, phpmyadminPort: 8080`. Call resolver with `defaultOriginPorts: new Set([ 'development.port' ])`. Assert `findAvailablePort` called for HTTP port only; `findAvailablePort` NOT called for phpmyadminPort; `isPortAvailable` NOT called for phpmyadminPort. | +| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=all uses non-strict mode for all ports including phpmyadminPort` | AC4 | All ports get `findAvailablePort` (preserves PR #74472 behavior). | +| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=off uses strict mode for HTTP ports and still resolves phpmyadminPort non-strictly` | AC5, AC10 | Defensive coverage for the per-port skip rule's non-`defaults-only` branch. Also documents that in production `'off'` never reaches this function (resolver is not created). | +| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver emits spinner.info exactly once when fallback occurs and re-arms the spinner` | AC7 | Mock spinner with `info: jest.fn()` and `start: jest.fn()`. Mock `findAvailablePort` to return `8890` when preferred is `8888`. Call `resolver.resolve(8888, 'env.development.port')`. Assert `spinner.info` was called exactly once with a string matching `/8888.*busy.*8890/i`, and `spinner.start` was called after `spinner.info` (assert via `info.mock.invocationCallOrder[0] < start.mock.invocationCallOrder[0]`). | +| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver does NOT emit spinner.info when the preferred port is available (no move occurred)` | AC7 | Mock `findAvailablePort` to return the preferred port. Assert `spinner.info` was NOT called. | +| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver does NOT emit spinner.info on the strict failure path` | AC7 | Strict mode + busy port → `isPortAvailable` returns `false` → throws. Assert `spinner.info` was NOT called. | +| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver does not write to console or process.stdout when fallback occurs (regression guard)` | AC7 | Spy on `console.log`, `console.info`, `console.warn`, `process.stdout.write`. After a fallback, none of them were called. (This is the "introducing a new output path is a detectable regression" assertion from AC7. Restore the spies in `afterEach`.) | +| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver suppresses the notice silently when no spinner is provided` | AC7 (test-path safety) | Call `createPortResolver()` with no args; mock `findAvailablePort` to return a different port; assert no throw and no console output. | + +End-to-end / manual repro for **AC9b** is documented in the PR body, NOT in the automated suite (per spec §5 and AC9b). The PR test plan must include the recipe: + +> 1. Bind 8888 manually: `python3 -m http.server 8888 &` +> 2. From a fresh project with no `.wp-env.json`, run `wp-env start`. +> 3. Confirm CLI prints a "moved port" info line referencing 8890 (or next free). +> 4. Browse to the printed URL; confirm WP loads and admin login works. +> 5. Free 8888, run `wp-env stop && wp-env start`; confirm the env re-resolves (may go back to 8888). + +This recipe is referenced from the PR body's test plan checklist as the AC9b verification. + +**AC9c (other commands)** is verified manually as part of the same recipe (steps 4 supplemented by `wp-env logs`, `wp-env run cli wp option get siteurl`, `wp-env stop`, `wp-env destroy --force`). No new automated test is added in this phase because the existing pattern (commands consume the cached `docker-compose.yml`) is unchanged by this PR — we are not regressing AC9c, we are inheriting the existing guarantee. The plan acknowledges this rather than expanding scope. + +--- + +## 4. Sequencing and parallelism + +For a single implementer, the realistic ordering (respecting both dependency graph and same-file edits) is: + +1. **Step 1** (default flip + fixture update; touches `parse-config.js` and its test fixture). +2. **Step 3** (`__defaultOriginPorts` provenance; touches `parse-config.js` only — the helper and the property attachment). +3. **Step 2** (`load-config.js` tri-state + threading). +4. **Step 4** (`post-process-config.js` option threading). +5. **Step 5** (`resolve-available-ports.js` per-port routing). +6. **Step 6** (`resolve-available-ports.js` notice — same file as step 5; sequential edit). +7. **Step 7** (`commands/start.js` JSDoc only). +8. **Steps 10 + 11** (tests). +9. **Step 12** (verification sweep). +10. **Steps 8 + 9** (documentation — can land at any point after Step 2; deferred to last so wording is informed by the implementation). + +Multi-agent worker plan (if parallelism is desired): + +- Worker A handles `parse-config.js` (Steps 1 + 3) and updates the test fixture. +- Worker B waits for Worker A to commit, then handles `load-config.js` (Step 2), `post-process-config.js` (Step 4), and `resolve-available-ports.js` (Steps 5 + 6 sequentially within the same file). +- Worker C handles docs (Steps 8 + 9) after Worker B's interface lands. +- Tests (Steps 10 + 11) and the verification sweep (Step 12) are owned by a single coordinator after all workers have committed. + +**Verification gates** (run during implementation, not just at the end): + +1. **After step 5 lands**: run `npm run test:unit -- packages/env/lib/config/test/post-process-config.js packages/env/lib/test/resolve-available-ports.js` to confirm the routing matrix works before writing the integration tests. +2. **After step 7 lands**: run `npm run test:unit -- packages/env` to confirm the full unit-test suite stays green; this is the early regression radar — if any unit test is unexpectedly red, escalate before continuing. Also run `composer test` from repo root to catch any unexpected PHP-side coupling early (per **R17 / R-PHPRegress**). +3. **After step 11 lands**: run `npm run lint:js -- packages/env` to catch style issues before docs. +4. **After step 12 lands**: run `composer test` again from repo root. Per **R17 / R-PHPRegress**, this is mandatory before review even though changes are JS-only. If any PHP test fails unexpectedly, escalate to spec/plan rather than work around silently. + +--- + +## 5. Verification strategy + +| AC | Verification command / test name | +|---|---| +| AC1 | `npm run test:unit -- packages/env -t "no user autoPort and busy default port falls back via defaults-only mode"` and `… -t "uses strict mode for non-default-origin ports and non-strict for default-origin ports"`. Manual: AC9b recipe steps 1–4. | +| AC2 | `npm run test:unit -- packages/env -t "uses strict mode for non-default-origin ports and non-strict for default-origin ports"` (covers both env keys symmetrically). | +| AC3 | `npm run test:unit -- packages/env -t "routes user-set port to strict and default-origin port to non-strict"` plus the four `parse-config.js` provenance tests for local / override / `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`. | +| AC4 | `npm run test:unit -- packages/env -t "autoPortMode=all"` and `… -t "CLI autoPort=true and user config autoPort=false has CLI win"` and `… -t "CLI autoPort=true and explicit user port falls back when port is busy"` (the new behavior-level integration test). | +| AC5 | `npm run test:unit -- packages/env -t "autoPortMode=off"` and `… -t "autoPort:false in user config skips fallback even on default ports"`. | +| AC6 | `npm run test:unit -- packages/env -t "CI=1 disables fallback"` (both variants). | +| AC7 | The five `createPortResolver` notice tests in `resolve-available-ports.js` (emits-once-and-re-arms / not-emitted-on-no-move / not-emitted-on-strict-fail / no-console-write-regression / silent-without-spinner). | +| AC8 | `npm run test:unit -- packages/env -t "CI=1 disables fallback regardless of autoPort:true"` — this is the named regression-detector test. Removing the `if ( process.env.CI )` guard in `load-config.js` makes this test fail. | +| AC9a | `npm run test:unit -- packages/env -t "threads autoPortMode and defaultOriginPorts to resolveConfigPorts"` — asserts merged config's `WP_HOME`/`WP_SITEURL` reflect the resolved port. | +| AC9b | Manual reproduction documented in PR body test plan. | +| AC9c | Manual reproduction documented in PR body test plan (no new automated test; covered by inherited compose-file guarantee). | +| AC10 | `npm run test:unit -- packages/env` (entire suite) green; the new "non-enumerable contract" test plus the back-compat `postProcessConfig` test plus the snapshot-no-drift expectation in Step 12. | +| AC11 | `npm run test:unit -- packages/env -t "tri-state"` plus `… -t "should accept autoPort as a tri-state"` (modified test). | + +--- + +## 6. Risks and mitigations + +- **R-TriState** — collapsed at the config layer because `DEFAULT_ENVIRONMENT_CONFIG.autoPort` is `false`. **Mitigation in plan.** Step 1 changes the default to `null`; step 2 reinterprets it; AC11 + the modified `should accept autoPort as a tri-state` test catch a future regression. The CLI side is already safe (verified — `lib/test/cli.js:35-52` already asserts `undefined`/`true`/`false`). +- **R-NonEnumerable** — `__defaultOriginPorts` becomes enumerable in a future refactor and starts leaking into `mergeConfig` iteration, JSON serialization, or `toEqual` assertions. **Mitigation in plan.** A dedicated regression test (`__defaultOriginPorts is invisible to mergeConfigs and toEqual`) asserts both `propertyIsEnumerable === false` and that `JSON.stringify` round-trip drops the property. Flipping it to enumerable fails the test. +- **R-TOCTOU** — port reads as free during the scan but is grabbed before Docker binds. **Mitigation in plan.** Inherited from PR #74472 — the plan does not change the existing `findAvailablePort` / `isPortAvailable` call sites, so the existing TOCTOU window is unchanged. Spec explicitly does not require a new mitigation. +- **R-PHPRegress** — PR #74472's earlier always-on attempt broke PHP tests. **Mitigation in plan.** `composer test` is invoked twice during implementation per §4 verification gates 2 and 4; any failure escalates rather than gets worked around. The plan also keeps the change tightly scoped to JS in `packages/env/` (per R15) so PHP coupling surfaces are minimized. +- **R-Snapshots** — snapshot drift. **Mitigation in plan.** Step 12 explicitly states that no snapshot diff is expected (verified — `grep autoPort` against both snapshot files returns zero hits today). Any unexpected diff is treated as a regression to investigate, not as routine updateSnapshot fodder. The real risk (the inline `DEFAULT_CONFIG` fixture at `parse-config.js test:21-71`) is addressed in Step 1 sub-step 4, not Step 12. +- **R-DownstreamURL** — resolved port not propagated. **Mitigation in plan.** Verified by tracing: `appendPortToWPConfigs` already runs after `resolveConfigPorts` in the existing `postProcessConfig` flow (`post-process-config.js:35-39`), so no new wiring needed; the AC9a test asserts the propagation explicitly via `WP_HOME`. +- **R-PortCollision** — dev and tests resolve to the same port. **Mitigation in plan.** Inherited: `createPortResolver`'s `usedPorts` array is passed as `exclude` to `findAvailablePort` (`resolve-available-ports.js:75-78`); already correct. +- **R-PhpmyadminMove (B3)** — phpmyadminPort silently auto-moves when a contributor has set it explicitly and runs under the new defaults-only mode. **Mitigation in plan.** Step 5's per-port skip rule under `autoPortMode === 'defaults-only'` skips `phpmyadminPort` entirely, preserving today's behavior verbatim (today phpmyadminPort is only resolved when `--auto-port` is on). The `postProcessConfig` test `… skips phpmyadminPort entirely` and the `resolveConfigPorts` test `… skips phpmyadminPort entirely` are the regression detectors. + +--- + +## 7. Rollback + +If a regression surfaces post-merge: revert this PR. The change is additive at the boundary (one default-value flip, one tri-state interpretation, one provenance-tracking helper, one routing matrix, one spinner notice, one README/CHANGELOG update). A clean `git revert ` restores the prior PR #74472 opt-in-only behavior with no downstream cleanup needed: there is no migration, no persisted state, no schema change, and no public API surface change. Contributors who relied on the new default-fallback behavior would temporarily need to add `--auto-port` to recover it; everyone else is unaffected. + +**Cached compose caveat.** Environments that were `start`ed under the new default-fallback behavior have their resolved port pinned in the cached `docker-compose.yml` at `~/.wp-env//docker-compose.yml`. After a revert, those already-running environments continue working unchanged (the cached compose still references the post-fallback port; `stop`/`destroy` operate by container name). However, a contributor who deletes the cache or runs `wp-env destroy && wp-env start` post-revert on a host where 8888 is busy will once again see the original port-busy failure. This is worth a one-line note in the revert PR's body so the reverting maintainer can communicate it. From e25c07d738c7099011c7083d2f884eaf73084431 Mon Sep 17 00:00:00 2001 From: Carlos Bravo <37012961+cbravobernal@users.noreply.github.com> Date: Mon, 11 May 2026 17:19:38 +0200 Subject: [PATCH 4/6] feat(env): auto-fall-back to free port when defaults busy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When `wp-env start` runs with no explicit port configuration, the default ports 8888 (development) and 8889 (tests) now scan upward to the next free port if they are busy, instead of failing the start. User-set ports keep today's strict behavior — Docker reports a port conflict and the start fails — so an explicit `port: 9000` in `.wp-env.json` is never silently moved. `autoPort` becomes tri-state: unset (default) -> defaults-only fallback; `true` -> all ports fall back, matching the prior opt-in `--auto-port` flag from #74472; `false` -> hard opt-out, even default ports stay strict. The existing `process.env.CI` guard keeps CI runs deterministic regardless of the setting. Closes part of #49843. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../code-review-1.md | 487 ++++++++++++++++++ packages/env/lib/commands/start.js | 20 +- packages/env/lib/config/load-config.js | 55 +- packages/env/lib/config/parse-config.js | 116 ++++- .../env/lib/config/post-process-config.js | 15 +- .../env/lib/config/test/config-integration.js | 181 +++++++ packages/env/lib/config/test/parse-config.js | 142 ++++- .../lib/config/test/post-process-config.js | 240 +++++++++ packages/env/lib/resolve-available-ports.js | 58 ++- .../env/lib/test/resolve-available-ports.js | 249 ++++++++- 10 files changed, 1512 insertions(+), 51 deletions(-) create mode 100644 .pipelines/49843-wp-env-default-port-fallback/code-review-1.md diff --git a/.pipelines/49843-wp-env-default-port-fallback/code-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/code-review-1.md new file mode 100644 index 00000000000000..ddb605997d73f7 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/code-review-1.md @@ -0,0 +1,487 @@ +# Phase 4 — Code review + +Iteration 1. + +Pipeline: `49843-wp-env-default-port-fallback` +Spec: `spec.md` (round 2 APPROVED). +Plan: `plan.md` (round 2 APPROVED). +Reviewed artifact: 9 staged files, 0 commits. + +--- + +## Method + +I verified the staged diff (`git diff --staged --stat` showed 9 files, ++1016 / −42), read every changed file end-to-end against the spec ACs and +plan steps 1–12, ran the project's unit suite, ran Prettier on the +staged files, and inspected the existing baseline for the lint blocker +the implementer flagged. + +## Diff hygiene check + +`git status --short` reports exactly the 9 files authorized by plan +§2. No unauthorized files (no `block-editor`, no `core-data`, no +`lib/compat/`, no `tools/`): + +``` +M packages/env/lib/commands/start.js +M packages/env/lib/config/load-config.js +M packages/env/lib/config/parse-config.js +M packages/env/lib/config/post-process-config.js +M packages/env/lib/config/test/config-integration.js +M packages/env/lib/config/test/parse-config.js +M packages/env/lib/config/test/post-process-config.js +M packages/env/lib/resolve-available-ports.js +M packages/env/lib/test/resolve-available-ports.js +``` + +`git diff --staged -- packages/env/**/__snapshots__/` is empty. **Zero +snapshot drift**, matching plan §6 R-Snapshots expectation. + +## Test run (mandated by the role) + +``` +$ npm run test:unit -- packages/env +… +Test Suites: 18 passed, 18 total +Tests: 181 passed, 181 total +Snapshots: 8 passed, 8 total +Time: 1.664 s +``` + +Matches the implementer's reported count exactly. No skipped tests. + +## Lint blocker provenance + +`ls /Users/carlos/Developer/wp-plugins/gutenberg/node_modules/eslint-plugin-react-hooks` +returns `No such file or directory` on the parent checkout. The +implementer's claim that the lint failure is pre-existing and unrelated +to this work is **confirmed**. Not a blocker for this review. The +docs-phase or PR description MUST acknowledge it so the maintainer +knows the lint command was not run as configured. + +Prettier was run on the 9 staged files and reports `All matched files +use Prettier code style!`. Standalone ESLint on the staged files via +`eslint --no-config-lookup` is a reasonable substitute — accepted. + +--- + +## AC coverage matrix + +For each AC I cite the test (file + `it` name) and the production code +path it exercises. + +### AC1 — Default development port falls back automatically (upward scan) + +- **Test:** `config-integration.js:236` `with no user autoPort and busy + default port falls back via defaults-only mode (AC1)`. Mocks + `findAvailablePort` to return 8890 for preferred 8888; asserts + `config.env.development.port === 8890` and `WP_HOME === + 'http://localhost:8890'`. +- **Production code path:** `load-config.js:101–106` maps unset + `autoPort` to `autoPortMode='defaults-only'`, `load-config.js:114–116` + creates the resolver, `resolve-available-ports.js:140–149` routes + default-origin HTTP ports as non-strict, `resolve-available-ports.js:75–78` + calls `findAvailablePort`. **Covered.** +- Upward-scan directionality is inherited from `port-utils.js` + (unchanged); no spec violation. + +### AC2 — Default tests port falls back independently (upward scan) + +- **Test:** `resolve-available-ports.js:165` `under autoPortMode=defaults-only + uses strict mode for non-default-origin ports and non-strict for default-origin ports` + asserts the dev-default→non-strict / tests-user-set→strict matrix + symmetrically. The post-process-config sibling test (line ~351) + `threads autoPortMode and defaultOriginPorts to resolveConfigPorts` + covers both http ports as non-strict in the same call. **Covered.** + +### AC3 — Explicitly configured port stays strict by default + +- **Production path:** `parse-config.js:213–273` (the new + `computeDefaultOriginPorts` + `layerSetsDevelopmentPort`/ + `layerSetsTestsPort` helpers) excludes a user-set key from + `__defaultOriginPorts`. `resolve-available-ports.js:147–149` then + computes `strict = ! defaultOriginPorts.has(key)` → user-set ports + go strict. +- **Tests:** Four `parse-config.js` provenance tests cover local + config, override config, `WP_ENV_PORT`, `WP_ENV_TESTS_PORT` + (lines ~632, ~648, ~666, ~677). `post-process-config.js:425` + `with autoPortMode=defaults-only routes user-set port to strict and + default-origin port to non-strict` and + `resolve-available-ports.js:165` cover the routing side. **Covered.** + +### AC4 — `--auto-port` / `"autoPort": true` still falls back on explicit ports + +- **Tests:** `config-integration.js:341` `with CLI autoPort=true and + user config autoPort=false has CLI win (AC4 precedence)`. The new + F3 integration test at `config-integration.js:367` `with CLI + autoPort=true and explicit user port falls back when port is busy + (AC4 behavior-level)` asserts the moved port flows all the way + through to `WP_HOME`. Sibling unit-level tests at + `resolve-available-ports.js:226` and `post-process-config.js:524` + assert `autoPortMode='all'` routes every port non-strict. +- **Production path:** `load-config.js:101` `effectiveAutoPort === + true` → `'all'`. `resolve-available-ports.js:145` `autoPortMode === + 'all'` → `strict = false` for every port (skip rule does not + trigger because the rule requires `defaults-only`). **Covered.** + +### AC5 — `"autoPort": false` opts out of default-port fallback too + +- **Test:** `config-integration.js:265` `with autoPort:false in user + config skips fallback even on default ports (AC5)`. Asserts + `findAvailablePort` was never called. +- **Production path:** `load-config.js:103` `effectiveAutoPort === + false` → `'off'`; `load-config.js:114` resolver not created. + **Covered.** The test name carries `AC5` so a future refactor that + collapses the false branch would fail this test by name. + +### AC6 — `CI=1` continues to disable all auto-fallback + +- **Tests:** `config-integration.js:288` `with CI=1 disables fallback + regardless of autoPort:true in user config (AC6 + AC8 regression + detector)` and `config-integration.js:319` `with CI=1 disables + fallback even when autoPort is unset (AC6)`. +- **Production path:** `load-config.js:109–112` — the + `process.env.CI` guard overwrites `autoPortMode` to `'off'`. CI + cleanup is correctly handled by the new `originalCI` save/restore + in `beforeEach`/`afterEach`. **Covered.** + +### AC7 — Informational message contract (observable) + +- **Tests (five):** `resolve-available-ports.js:309` `emits spinner.info + exactly once when fallback occurs and re-arms the spinner`; + line 329 `does NOT emit spinner.info when the preferred port is + available`; line 340 `does NOT emit spinner.info on the strict + failure path`; line 352 `does not write to console or process.stdout + when fallback occurs (regression guard)`; line 386 `suppresses the + notice silently when no spinner is provided (test-path safety)`. +- **Production path:** `resolve-available-ports.js:80–90` — + `if ( spinner && resolvedPort !== preferredPort )` guard, message, + then `spinner.start()` re-arm. The order assertion + (`info.mock.invocationCallOrder[0] < start.mock.invocationCallOrder[0]`) + is well-formed and exercises the re-arm sequence the plan requires. + **Covered.** The "no console output" regression detector exactly + matches the spec's "introducing a separate output path would be a + detectable regression" clause. + +### AC8 — CI guard regression is detectable + +- **Test:** `config-integration.js:288` carries the explicit name + `(AC6 + AC8 regression detector)` and the comment "Removing the + `if ( process.env.CI )` guard in load-config.js would call + findAvailablePort and fail this expectation." Verified by reading + the test body. **Covered.** + +### AC9a — Resolved port flows downstream into merged config + +- **Test:** `post-process-config.js:351` `threads autoPortMode and + defaultOriginPorts to resolveConfigPorts` asserts + `processed.env.development.config.WP_HOME === 'http://localhost:8890'` + and the same for `WP_SITEURL`. The integration test + `config-integration.js:236` also asserts the same end-to-end through + `loadConfig`. +- **Production path:** `post-process-config.js:37–40` calls + `resolveConfigPorts` first; line 42 then calls + `appendPortToWPConfigs`. Order preserved. **Covered.** + +### AC9b — Live reachability (manual) + +- Out of scope for the automated suite per spec §5 / plan §3 trailer. + Verification deferred to the PR test plan. **Acknowledged; not a + code-review blocker.** + +### AC9c — Other wp-env commands see the resolved fallback port + +- No new automated test (plan §3 trailer documents this — the + guarantee is inherited from the unchanged cached-compose contract). +- Plan §1 Step 1 traces `start.js → loadConfig → postProcessConfig → + build-docker-compose-config.js` to confirm the resolved port is + what `runtime/docker/build-docker-compose-config.js:173,267` writes + into the cached compose file, which `stop.js`/`destroy.js`/etc. + consume by container name. I spot-checked + `packages/env/lib/runtime/docker/build-docker-compose-config.js` — + not touched in this diff, so the contract is preserved. **Covered + by inheritance; verification deferred to manual PR test plan steps.** + +### AC10 — Existing tests stay green; snapshots intentional + +- 181 / 181 unit tests pass. +- Zero snapshot drift in `__snapshots__/` directories. +- The non-enumerable contract test at `parse-config.js:715` + (`__defaultOriginPorts is invisible to mergeConfigs and toEqual`) + asserts `JSON.parse(JSON.stringify(parsed)).__defaultOriginPorts` + is `undefined` AND `expect(parsed).toEqual(DEFAULT_CONFIG)` still + passes AND `Object.keys(parsed)` does not contain the property. + This is a strong regression detector for plan §6 R-NonEnumerable. +- The back-compat test `post-process-config.js:583` `defaults to + autoPortMode=off and routes ports strict (back-compat for callers + that do not pass options)` guarantees callers that bypass the new + options keep working. **Covered.** + +### AC11 — `autoPort` tri-state survives end-to-end + +- **Test:** `parse-config.js:196` (renamed) `should accept autoPort + as a tri-state (null default, true, false)` asserts three distinct + values: default `null`, explicit `true`, explicit `false`. The + test ends with `expect( parsedFalse.autoPort ).not.toBeNull()` + which is the spec's "observably distinct" requirement. +- The default-config flip at `parse-config.js:93` + (`autoPort: null`) and the validator change at line 493–504 (`null` + passes the boolean check) together guarantee the tri-state survives + parse → merge. `load-config.js:101–107` consumes the tri-state. + **Covered.** + +--- + +## Plan adherence + +| Step | Status | Notes | +|---|---|---| +| 1 — default flip + fixture | Done | `parse-config.js:93` is `null`; test fixture line 24 updated to `null`. JSDoc updated. | +| 2 — `load-config.js` tri-state | Done | Block at `load-config.js:96–122` matches plan exactly (CLI beats config; CI forces `'off'`; resolver created only when `resolvePorts && mode !== 'off'`). JSDoc updated. | +| 3 — `__defaultOriginPorts` provenance | Done | Helper functions land at `parse-config.js:194–273`. Non-enumerable property attached at line 175. The four user-source layers are inspected as specified. | +| 4 — `postProcessConfig` threading | Done | Signature change + JSDoc at `post-process-config.js:24–35`. Defaults preserve back-compat. | +| 5 — per-port routing in `resolveConfigPorts` | Done | Skip rule at `resolve-available-ports.js:128–135`; strict decision at lines 136–151. Matches plan's three-mode matrix. | +| 6 — moved-port notice in `createPortResolver` | Done | `resolve-available-ports.js:80–90`. Guarded by `spinner && resolvedPort !== preferredPort`; `spinner.start()` re-arms. | +| 7 — `start.js` JSDoc | Done | One-line JSDoc tri-state description at `start.js:32`. No public signature change. | +| 8 — README | **Deferred to phase 5** | Acceptable per role brief. | +| 9 — CHANGELOG | **Deferred to phase 5** | Acceptable per role brief. | +| 10 — tests (tri-state + provenance) | Done | All planned test rows in §3 are present; the `'off'`-mode test for phpmyadminPort was correctly adjusted (see deviation note below). | +| 11 — tests (moved-port notice) | Done | Five spinner tests land at `resolve-available-ports.js:309–411`. | +| 12 — verification sweep | Partial | Snapshot/JSDoc/fixture sweep done. **`composer test` from plan §4 verification gate 4 was not run** — see PHP test deferral section below. | + +### Deviations from plan + +1. **Plan §3 row for `'off'`-mode phpmyadminPort test (line 259) says + "still resolves phpmyadminPort non-strictly".** The implementation + in plan Step 5 reads "If `autoPortMode === 'off'` → `strict = true`", + so phpmyadminPort under `'off'` is actually resolved **strictly**. + The implementer correctly aligned the test + (`resolve-available-ports.js:262` asserts `isPortAvailable.toHaveBeenCalledWith(8080)` + and `findAvailablePort.not.toHaveBeenCalled()`). This is a plan + text error, not a code error. The test name was also adjusted to + "still resolves phpmyadminPort **strictly**" which is consistent + with the implementation. **Deviation accepted; the test correctly + guards Step 5's actual strict-decision rule.** + +2. **Validator at `parse-config.js:493–504` allows `null` to pass + silently** but still emits "must be a boolean" if a non-null, + non-boolean is provided. The user-visible error message is + slightly inaccurate (it implies only boolean is allowed, but null + is also accepted). However, `null` is not a value a contributor + would ever write in `.wp-env.json` (it would parse as `null` only + if they explicitly typed it, which would behave the same as + omitting the key). **Accepted as written.** Optional tightening + for future: update the error message to "must be a boolean or + null" — non-blocking nit. + +3. The implementer reported running `eslint --no-config-lookup` and + `prettier --check` instead of `npm run lint:js` because the + parent checkout is missing `eslint-plugin-react-hooks`. I + confirmed the missing dep is pre-existing. **Accepted as a valid + substitute for this review iteration.** Docs phase or PR + description must acknowledge. + +4. The implementer reported skipping `composer test` because wp-env + is not running. See PHP test deferral section. + +--- + +## Test correctness audit + +I read every new test and checked for the four common cheats. Findings: + +- **No empty assertions.** Every `it` block ends in an `expect(…)` + call against a meaningful value. +- **No mocks swallowing the call.** Where `jest.fn()` mocks are used + (`portResolver.resolve`, `findAvailablePort`, `isPortAvailable`), + the tests assert against `.mock.calls` or against the returned + config object, not against the input. +- **No tautological assertions** (asserting on inputs). The + `__defaultOriginPorts` provenance tests all assert against + `parsed.__defaultOriginPorts.has(…)` — i.e. against the result of + `parseConfig`, not against the mocks. +- **AC4 / AC5 / AC8 integration tests correctly assert observable + behavior** (`findAvailablePort.toHaveBeenCalled()` / + `not.toHaveBeenCalled()` plus the resolved port in the returned + config), not just internal state. +- The non-enumerable contract test (`parse-config.js:715`) is + particularly well-constructed: it asserts the property is + invisible to JSON serialization, to `Object.keys`, and to Jest's + `toEqual` deep-equal in a single test. A future refactor that + flips the property to enumerable fails this test. +- The "moved-port notice" tests correctly assert call order + (`info.mock.invocationCallOrder[0] < start.mock.invocationCallOrder[0]`) + — this is the right way to assert ordering between two mock fns. +- The "no console output" regression detector spies on + `console.log`, `console.info`, `console.warn`, and + `process.stdout.write`, and restores them in `finally`. Correctly + scoped and cleaned up. + +**No test cheats detected.** + +--- + +## Behavior verification (production code path) + +### `parse-config.js` `__defaultOriginPorts` provenance + +- Line 167–175 captures `mergeConfigs` result in `merged`, computes + `defaultOriginPorts`, attaches via `Object.defineProperty(merged, + '__defaultOriginPorts', { value: …, enumerable: false, writable: + false, configurable: false })`. **All three flags are tightened + beyond the default;** the property is also non-writable and + non-configurable, making the contract harder to accidentally + break. Good defensive choice. +- `merge-configs.js` `for (const option in config)` is unchanged. + `for…in` excludes non-enumerable own properties, so the provenance + Set never leaks into the merge. The dedicated test at + `parse-config.js:715` (`JSON round-trip drops the property; toEqual + still passes`) is the regression detector. +- The helpers `layerSetsDevelopmentPort` / `layerSetsTestsPort` + correctly inspect both root-level (`port` / `testsPort`) and + env-specific (`env.development.port` / `env.tests.port`) paths, + plus the env-var-derived layer. **Matches plan §2 Step 3 exactly.** +- One reviewer concern: the helpers inspect `layer.env?.development?.port` + with `?? undefined` semantics; an explicit `port: 0` would count + as "user-set". That is the right behavior (zero is a port value + the user typed). No issue. + +### `load-config.js` tri-state resolution + +- `effectiveAutoPort = autoPort !== undefined ? autoPort : config.autoPort` + — CLI beats config. CLI `false` short-circuits to `'off'`; CLI + `true` short-circuits to `'all'`. CLI `undefined` defers to + `config.autoPort`. +- `config.autoPort` is `true`/`false`/`null` (after Step 1's default + flip; `null` is the "unset" sentinel). When `effectiveAutoPort === + true` → `'all'`; `=== false` → `'off'`; **else** (which covers + `null`, `undefined`, and any other unexpected value) → `'defaults-only'`. + This `else` branch correctly handles the case where `config.autoPort` + is undefined (defensive), `null`, or genuinely unset. +- CI guard at line 109 is reached **after** the tri-state mapping + and unconditionally forces `'off'`. Test + `config-integration.js:288` (CI=1 + `autoPort: true` → no + fallback) proves the guard is in front of the resolver creation. + +### `resolve-available-ports.js` per-port routing + +- Skip rule at line 128–135: `if ( autoPortMode === 'defaults-only' + && property !== 'port' ) continue;` — exactly preserves today's + phpmyadminPort behavior under the new mode (B3 fix). +- Strict decision at line 136–151: matches plan's matrix + (`'off'`→true, `'all'`→false, `'defaults-only'` HTTP → + `! defaultOriginPorts.has(key)`). +- `portResolver.resolve(preferredPort, configPath, strict)` — third + argument was already supported by `createPortResolver`'s + `resolve` method (line 50 in the unchanged baseline section). + +### `createPortResolver` info notice + +- Guard at line 85: `if ( spinner && resolvedPort !== preferredPort )`. + Fires **only when both are true**. When `spinner` is undefined → + silent. When `resolvedPort === preferredPort` → silent. The two + tests at `resolve-available-ports.js:329` (no move) and `:386` (no + spinner) confirm both branches. +- Notice goes through `spinner.info(…)` followed by `spinner.start()` + to re-arm. Matches the precedent at `commands/start.js:98–101` and + `:169–193` cited in plan §F4. +- Strict branch (lines 56–72) **does not** reach the notice code — + the throw happens earlier. The test at `resolve-available-ports.js:340` + confirms `spinner.info` is not called on strict failure. + +### `commands/start.js` JSDoc + +- Line 32: `@param {boolean|undefined} options.autoPort Tri-state: + …` — describes all three states. **No public signature change.** + +--- + +## PHP test deferral decision + +- `composer test` was not run because wp-env is not running locally + in this worktree. The plan §4 verification gates 2 and 4 both + mandate `composer test`, and spec **R17 / R-PHPRegress** explicitly + ties this to PR #74472's history of breaking PHP tests with the + always-on default-fallback approach. +- **Decision: accepted as a deferred checkpoint, NOT a blocker for + this code review.** Rationale: + - This change is JS-only inside `packages/env/`. No PHP file + changed in the staged diff. + - The PHP suite depends on `wp-env` running, which is a + side-effectful operation the implementer is correct to avoid + in the middle of an implementation cycle. + - The 181/181 JS-test green plus zero snapshot drift makes a + PHP regression unlikely; if one surfaces, it surfaces at the + checkpoint without harm. +- **Explicit checkpoint:** `composer test` MUST run green **after** + the docs phase commits and **before** the PR is opened (i.e. as + part of the pipeline's "ready for review" gate, not before this + code-review verdict). The docs-phase reviewer or the PR-opening + step inherits responsibility for confirming the gate. + +--- + +## Open issues raised by the implementer + +1. **parse-config validator allows `null` but error message says + "must be a boolean".** Minor cosmetic. **Accepted as written.** + Optional polish: update the message in a follow-up; non-blocking + here. +2. **AC5 / AC6 integration test phrasing carries AC tags inline.** + This is helpful for future maintenance and matches plan §5's + "named regression detector" intent. **Accepted.** +3. **PHP gate deferral.** **Accepted as a documented checkpoint + before PR open.** See section above. +4. **Lint blocker (`eslint-plugin-react-hooks` missing).** Confirmed + pre-existing on the parent checkout. **Accepted; not a blocker.** + Prettier on staged files passes; eslint via `--no-config-lookup` + is an acceptable substitute. Docs phase or PR description must + note that `npm run lint:js` is currently broken in the parent + tree. + +--- + +## Verdict + +``` +APPROVED +``` + +The 9 staged files faithfully implement plan steps 1–7 and 10–12, and +the test suite covers every code-eligible AC (AC1, AC2, AC3, AC4, AC5, +AC6, AC7, AC8, AC9a, AC10, AC11). AC9b and AC9c are correctly deferred +to the manual PR test plan per spec §5. All 181 unit tests pass; zero +snapshot drift; no unauthorized files touched; the non-enumerable +contract for `__defaultOriginPorts` is independently regression-guarded. +The one plan-vs-implementation deviation (Plan §3 row 259 wording on +`'off'`-mode phpmyadminPort) is a plan documentation error that the +implementer correctly resolved in favor of the implementation logic +defined elsewhere in the plan. + +### Conditions that MUST hold before the PR is opened (not blocking this iteration) + +1. **README updated** per plan Step 8 — describes the new default + behavior, the `"autoPort": false` opt-out, and updates the config + table row for `autoPort` (default `null`, tri-state description). +2. **CHANGELOG updated** per plan Step 9 — `Unreleased` entry under + `### New Features` or `### Enhancements`, referencing `#49843`. +3. **`composer test` runs green** from repo root with wp-env running, + per spec R17 / plan §4 verification gate 4. Any failure escalates + to spec/plan, not silently worked around. +4. **PR body test plan enumerates AC1 through AC11** (including + AC9a/AC9b/AC9c) per spec §9 + R16. +5. **PR body includes the AC9b manual reproduction recipe** from + plan §3 (bind 8888 with `python3 -m http.server`, run wp-env + start, browse to the printed URL, verify, then stop and restart). +6. **PR body acknowledges the pre-existing `npm run lint:js` + breakage** (missing `eslint-plugin-react-hooks` in the parent + checkout) so the maintainer knows lint was not run as configured. + This is a host-project issue, not a regression introduced by this + PR. +7. **PR is opened against `WordPress/gutenberg` `trunk` from branch + `try/49843-wp-env-default-port-fallback`**, links `#49843`, and + is filed as a draft per spec §9. + +All ACs in scope for the automated suite are satisfied. Implementation +is ready for the documentation phase. diff --git a/packages/env/lib/commands/start.js b/packages/env/lib/commands/start.js index 91da7f592c7b46..be54bb70d4af90 100644 --- a/packages/env/lib/commands/start.js +++ b/packages/env/lib/commands/start.js @@ -21,16 +21,16 @@ const { getRuntime, getSavedRuntime, saveRuntime } = require( '../runtime' ); /** * Starts the development server. * - * @param {Object} options - * @param {Object} options.spinner A CLI spinner which indicates progress. - * @param {boolean} options.update If true, update sources. - * @param {string} options.xdebug The Xdebug mode to set. - * @param {string} options.spx The SPX mode to set. - * @param {boolean} options.scripts Indicates whether or not lifecycle scripts should be executed. - * @param {boolean} options.debug True if debug mode is enabled. - * @param {string} options.runtime The runtime to use ('docker' or 'playground'). - * @param {boolean} options.autoPort If true, automatically find available ports when configured ports are busy. - * @param {string|null} options.config Path to a custom .wp-env.json configuration file. + * @param {Object} options + * @param {Object} options.spinner A CLI spinner which indicates progress. + * @param {boolean} options.update If true, update sources. + * @param {string} options.xdebug The Xdebug mode to set. + * @param {string} options.spx The SPX mode to set. + * @param {boolean} options.scripts Indicates whether or not lifecycle scripts should be executed. + * @param {boolean} options.debug True if debug mode is enabled. + * @param {string} options.runtime The runtime to use ('docker' or 'playground'). + * @param {boolean|undefined} options.autoPort Tri-state: `true` enables automatic port fallback for every port (including user-set ones); `false` disables fallback even on default ports; `undefined` (the typical case — flag not supplied) defers to `.wp-env.json`'s `autoPort` field, where unset/`null` means "auto-fallback only on default ports `8888`/`8889`". + * @param {string|null} options.config Path to a custom .wp-env.json configuration file. */ module.exports = async function start( { spinner, diff --git a/packages/env/lib/config/load-config.js b/packages/env/lib/config/load-config.js index 89fb07a2595c19..72ed01dfa33ba2 100644 --- a/packages/env/lib/config/load-config.js +++ b/packages/env/lib/config/load-config.js @@ -37,12 +37,12 @@ const { createPortResolver } = require( '../resolve-available-ports' ); /** * Loads any configuration from a given directory. * - * @param {string} configDirectoryPath The directory we want to load the config from. - * @param {string|null} customConfigPath Optional custom config file path. - * @param {Object} options Options for loading the config. - * @param {boolean} options.resolvePorts Whether HTTP ports should be resolved for this command. - * @param {boolean} options.autoPort CLI override for automatic port selection. - * @param {Object} options.spinner A CLI spinner used by the port resolver. + * @param {string} configDirectoryPath The directory we want to load the config from. + * @param {string|null} customConfigPath Optional custom config file path. + * @param {Object} options Options for loading the config. + * @param {boolean} options.resolvePorts Whether HTTP ports should be resolved for this command. + * @param {boolean|undefined} options.autoPort Tri-state CLI override for automatic port selection: `true` enables fallback for all ports, `false` disables fallback even on default ports, `undefined` defers to `config.autoPort` (which itself is tri-state — `null`/`undefined` means "fallback only on default ports"). + * @param {Object} options.spinner A CLI spinner used by the port resolver. * * @return {Promise} The config object we've loaded. */ @@ -93,25 +93,44 @@ module.exports = async function loadConfig( customConfigPath ); - let portResolver; - if ( resolvePorts ) { - let shouldAutoPort = - autoPort !== undefined ? autoPort : config.autoPort; + // Compute the tri-state auto-port mode. Precedence: CLI option beats + // config.autoPort. CLI `true`/`false` are explicit; `undefined` defers + // to the parsed config value (which itself is tri-state — `null` / + // `undefined` means "unset, use the new defaults-only behavior"). + let autoPortMode; + const effectiveAutoPort = + autoPort !== undefined ? autoPort : config.autoPort; + if ( effectiveAutoPort === true ) { + autoPortMode = 'all'; + } else if ( effectiveAutoPort === false ) { + autoPortMode = 'off'; + } else { + autoPortMode = 'defaults-only'; + } - // Automatic port selection is undesirable in CI where determinism matters. - if ( process.env.CI ) { - shouldAutoPort = false; - } + // Automatic port selection is undesirable in CI where determinism matters. + if ( process.env.CI ) { + autoPortMode = 'off'; + } - if ( shouldAutoPort ) { - portResolver = createPortResolver( spinner ); - } + let portResolver; + if ( resolvePorts && autoPortMode !== 'off' ) { + portResolver = createPortResolver( spinner ); } + // Read the per-port provenance attached by `parseConfig`. Falls back to + // an empty set so callers that bypass `parseConfig` (e.g. some tests) + // keep working. + const defaultOriginPorts = config.__defaultOriginPorts ?? new Set(); + // Make sure to perform any additional post-processing that // may be needed before the config object is ready for // consumption elsewhere in the tool. - config = await postProcessConfig( config, { portResolver } ); + config = await postProcessConfig( config, { + portResolver, + autoPortMode, + defaultOriginPorts, + } ); return { name: path.basename( configDirectoryPath ), diff --git a/packages/env/lib/config/parse-config.js b/packages/env/lib/config/parse-config.js index 9ee50cdd5275f0..1de3563a4b110a 100644 --- a/packages/env/lib/config/parse-config.js +++ b/packages/env/lib/config/parse-config.js @@ -35,7 +35,7 @@ const mergeConfigs = require( './merge-configs' ); * @typedef WPRootConfigOptions * @property {number} port The port to use in the development environment. * @property {number} testsPort The port to use in the tests environment. - * @property {boolean} autoPort Whether to automatically select a nearby available HTTP port. + * @property {boolean|null} autoPort Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports). * @property {Object.} lifecycleScripts The scripts to run at certain points in the command lifecycle. * @property {Object.} lifecycleScripts.afterStart The script to run after the "start" command has completed. * @property {Object.} lifecycleScripts.afterClean The script to run after the "clean" command has completed. @@ -90,7 +90,7 @@ const DEFAULT_ENVIRONMENT_CONFIG = { themes: [], port: 8888, testsPort: 8889, - autoPort: false, + autoPort: null, mysqlPort: null, phpmyadmin: false, phpmyadminPort: null, @@ -159,12 +159,115 @@ async function parseConfig( // Merge all of our configs so that we have a complete object // containing the desired options in order of precedence. - return mergeConfigs( + const merged = mergeConfigs( defaultConfig, localConfig ?? {}, overrideConfig ?? {}, environmentVarOverrides ); + + // Track which HTTP ports came from `DEFAULT_ENVIRONMENT_CONFIG` versus + // any user-supplied source. This is consumed by the port resolver to + // decide whether to silently fall back to the next available port (for + // default-origin ports) or to surface a strict port-busy error (for + // user-set ports). Stored as a non-enumerable property so it does not + // participate in `mergeConfig` iteration, JSON serialization, or + // `toEqual` equality checks performed elsewhere. + const defaultOriginPorts = computeDefaultOriginPorts( + localConfig, + overrideConfig, + environmentVarOverrides + ); + Object.defineProperty( merged, '__defaultOriginPorts', { + value: defaultOriginPorts, + enumerable: false, + writable: false, + configurable: false, + } ); + + return merged; +} + +/** + * Computes the set of HTTP port keys whose effective value comes from + * `DEFAULT_ENVIRONMENT_CONFIG` (i.e. no user-supplied source provided them). + * + * The returned Set contains zero or more of the strings `'development.port'` + * and `'tests.port'`. Each key is included when none of the user-supplied + * sources (root `.wp-env.json`, `.wp-env.override.json`, or environment + * variables) provide a value for that port. + * + * @param {Object|null} localConfig The parsed local config, or null when absent. + * @param {Object|null} overrideConfig The parsed override config, or null when absent. + * @param {Object} environmentVarOverrides The config-shaped object derived from env vars. + * + * @return {Set} The set of default-origin port keys. + */ +function computeDefaultOriginPorts( + localConfig, + overrideConfig, + environmentVarOverrides +) { + const result = new Set(); + + const isDevelopmentPortUserSet = + layerSetsDevelopmentPort( localConfig ) || + layerSetsDevelopmentPort( overrideConfig ) || + layerSetsDevelopmentPort( environmentVarOverrides ); + + const isTestsPortUserSet = + layerSetsTestsPort( localConfig ) || + layerSetsTestsPort( overrideConfig ) || + layerSetsTestsPort( environmentVarOverrides ); + + if ( ! isDevelopmentPortUserSet ) { + result.add( 'development.port' ); + } + if ( ! isTestsPortUserSet ) { + result.add( 'tests.port' ); + } + + return result; +} + +/** + * Whether the given config layer provides a value for the development HTTP port. + * + * @param {Object|null|undefined} layer The config layer to inspect. + * + * @return {boolean} True when the layer sets the development port. + */ +function layerSetsDevelopmentPort( layer ) { + if ( ! layer ) { + return false; + } + if ( layer.port !== undefined ) { + return true; + } + if ( layer.env?.development?.port !== undefined ) { + return true; + } + return false; +} + +/** + * Whether the given config layer provides a value for the tests HTTP port. + * + * @param {Object|null|undefined} layer The config layer to inspect. + * + * @return {boolean} True when the layer sets the tests port. + */ +function layerSetsTestsPort( layer ) { + if ( ! layer ) { + return false; + } + if ( layer.testsPort !== undefined ) { + return true; + } + if ( layer.env?.tests?.port !== undefined ) { + return true; + } + return false; } /** @@ -388,7 +491,12 @@ async function parseRootConfig( configFile, rawConfig, options ) { parsedConfig.testsPort = rawConfig.testsPort; } if ( rawConfig.autoPort !== undefined ) { - if ( typeof rawConfig.autoPort !== 'boolean' ) { + // `null` is a valid tri-state value meaning "unset" (the default). + // Only user-provided autoPort values must be booleans. + if ( + rawConfig.autoPort !== null && + typeof rawConfig.autoPort !== 'boolean' + ) { throw new ValidationError( `Invalid ${ configFile }: "autoPort" must be a boolean.` ); diff --git a/packages/env/lib/config/post-process-config.js b/packages/env/lib/config/post-process-config.js index 13cd180e68c21c..d04b0d90c693fd 100644 --- a/packages/env/lib/config/post-process-config.js +++ b/packages/env/lib/config/post-process-config.js @@ -15,15 +15,17 @@ const { resolveConfigPorts } = require( '../resolve-available-ports' ); /** * Performs any additional post-processing on the config object. * - * @param {WPEnvironmentConfig} config The config to process. - * @param {Object} options Options for post-processing. - * @param {Object} options.portResolver An optional port resolver for automatic port selection. + * @param {WPEnvironmentConfig} config The config to process. + * @param {Object} options Options for post-processing. + * @param {Object} options.portResolver An optional port resolver for automatic port selection. + * @param {'off'|'all'|'defaults-only'} options.autoPortMode The auto-port routing mode. `'off'` disables fallback (strict); `'all'` enables fallback for every port (today's PR #74472 behavior); `'defaults-only'` enables fallback only on default-origin HTTP ports (the new default behavior). Defaults to `'off'` so existing call sites that do not opt in keep their current behavior. + * @param {Set} options.defaultOriginPorts The set of port keys (e.g. `'development.port'`, `'tests.port'`) whose effective value comes from the default config rather than any user-supplied source. Used by `'defaults-only'` mode to decide which ports may auto-fall-back. Defaults to an empty set. * * @return {Promise} The config after post-processing. */ module.exports = async function postProcessConfig( config, - { portResolver } = {} + { portResolver, autoPortMode = 'off', defaultOriginPorts = new Set() } = {} ) { // Make sure that we're operating on a config object that has // complete environment configs for convenience. @@ -33,7 +35,10 @@ module.exports = async function postProcessConfig( // but before appending ports to URLs. This way appendPortToWPConfigs // uses the resolved ports and we don't need to fix URLs afterward. if ( portResolver ) { - config = await resolveConfigPorts( config, portResolver ); + config = await resolveConfigPorts( config, portResolver, { + autoPortMode, + defaultOriginPorts, + } ); } config = appendPortToWPConfigs( config ); diff --git a/packages/env/lib/config/test/config-integration.js b/packages/env/lib/config/test/config-integration.js index d503a35163f5dd..2440dbf9b453b5 100644 --- a/packages/env/lib/config/test/config-integration.js +++ b/packages/env/lib/config/test/config-integration.js @@ -12,6 +12,7 @@ const { existsSync } = require( 'fs' ); const loadConfig = require( '../load-config' ); const detectDirectoryType = require( '../detect-directory-type' ); const md5 = require( '../../md5' ); +const { findAvailablePort, isPortAvailable } = require( '../../port-utils' ); jest.mock( 'fs', () => ( { promises: { @@ -23,6 +24,8 @@ jest.mock( 'fs', () => ( { existsSync: jest.fn().mockReturnValue( false ), } ) ); +jest.mock( '../../port-utils' ); + // This mocks a small response with a format matching the stable-check API. // It makes getLatestWordPressVersion resolve to "100.0.0". jest.mock( 'got', () => @@ -43,9 +46,17 @@ jest.mock( 'got', () => jest.mock( '../detect-directory-type', () => jest.fn() ); describe( 'Config Integration', () => { + // Save the inherited CI value so we can restore it after each test + // (the new tests below stomp on `process.env.CI` to assert the guard). + let originalCI; + beforeEach( () => { process.env.WP_ENV_HOME = '/cache'; detectDirectoryType.mockResolvedValue( null ); + originalCI = process.env.CI; + // Force-disable CI for tests that exercise the auto-fallback paths. + // Tests that need CI on opt back in explicitly. + delete process.env.CI; } ); afterEach( () => { @@ -55,6 +66,13 @@ describe( 'Config Integration', () => { delete process.env.WP_ENV_TESTS_PORT; delete process.env.WP_ENV_TESTS_MYSQL_PORT; delete process.env.WP_ENV_LIFECYCLE_SCRIPT_AFTER_START; + // Restore the inherited CI value, if any. + if ( originalCI === undefined ) { + delete process.env.CI; + } else { + process.env.CI = originalCI; + } + jest.clearAllMocks(); } ); it( 'should use default configuration', async () => { @@ -204,6 +222,169 @@ describe( 'Config Integration', () => { expect( config ).toMatchSnapshot(); } ); + describe( 'auto-port fallback (tri-state autoPort)', () => { + const stubSpinner = () => ( { + text: '', + info: jest.fn(), + start: jest.fn(), + fail: jest.fn(), + warn: jest.fn(), + stop: jest.fn(), + } ); + + it( 'with no user autoPort and busy default port falls back via defaults-only mode (AC1)', async () => { + readFile.mockImplementation( async () => { + throw { code: 'ENOENT' }; + } ); + + // Default port 8888 is busy; the resolver should hand back 8890. + findAvailablePort.mockImplementation( ( { preferredPort } ) => { + if ( preferredPort === 8888 ) { + return Promise.resolve( 8890 ); + } + return Promise.resolve( preferredPort ); + } ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + expect( config.env.development.port ).toEqual( 8890 ); + expect( config.env.development.config.WP_HOME ).toEqual( + 'http://localhost:8890' + ); + expect( config.env.development.config.WP_SITEURL ).toEqual( + 'http://localhost:8890' + ); + } ); + + it( 'with autoPort:false in user config skips fallback even on default ports (AC5)', async () => { + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { autoPort: false } ); + } + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockResolvedValue( 8890 ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + // autoPort:false forces 'off' mode, so the auto-fallback path + // (`findAvailablePort`) is never called. The default port stays + // as configured; any port-busy error surfaces later at the + // Docker bind layer with the existing message. + expect( findAvailablePort ).not.toHaveBeenCalled(); + expect( config.env.development.port ).toEqual( 8888 ); + } ); + + it( 'with CI=1 disables fallback regardless of autoPort:true in user config (AC6 + AC8 regression detector)', async () => { + process.env.CI = '1'; + + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { autoPort: true } ); + } + throw { code: 'ENOENT' }; + } ); + + // Mock both port-utils functions so we can detect which path + // (if any) was taken. Strict path uses isPortAvailable; + // auto-fallback path uses findAvailablePort. + findAvailablePort.mockResolvedValue( 8890 ); + isPortAvailable.mockResolvedValue( true ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + // AC8 regression detector: even with autoPort:true the CI guard + // forces 'off' mode, so the resolver is not created at all and + // the auto-fallback path (`findAvailablePort`) is never called. + // Removing the `if ( process.env.CI )` guard in load-config.js + // would call findAvailablePort and fail this expectation. + expect( findAvailablePort ).not.toHaveBeenCalled(); + // Default port stays as configured because no resolver fired. + expect( config.env.development.port ).toEqual( 8888 ); + } ); + + it( 'with CI=1 disables fallback even when autoPort is unset (AC6)', async () => { + process.env.CI = '1'; + + readFile.mockImplementation( async () => { + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockResolvedValue( 8890 ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + // CI guard short-circuits the new defaults-only mode. + expect( findAvailablePort ).not.toHaveBeenCalled(); + expect( config.env.development.port ).toEqual( 8888 ); + } ); + + it( 'with CLI autoPort=true and user config autoPort=false has CLI win (AC4 precedence)', async () => { + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { autoPort: false } ); + } + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockImplementation( ( { preferredPort } ) => { + if ( preferredPort === 8888 ) { + return Promise.resolve( 8890 ); + } + return Promise.resolve( preferredPort ); + } ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + autoPort: true, + spinner: stubSpinner(), + } ); + + // CLI true wins over config false → fallback fired. + expect( config.env.development.port ).toEqual( 8890 ); + } ); + + it( 'with CLI autoPort=true and explicit user port falls back when port is busy (AC4 behavior-level)', async () => { + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { port: 9000 } ); + } + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockImplementation( ( { preferredPort } ) => { + if ( preferredPort === 9000 ) { + return Promise.resolve( 9001 ); + } + return Promise.resolve( preferredPort ); + } ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + autoPort: true, + spinner: stubSpinner(), + } ); + + expect( config.env.development.port ).toEqual( 9001 ); + expect( config.env.development.config.WP_HOME ).toEqual( + 'http://localhost:9001' + ); + } ); + } ); + describe( 'cache directory naming', () => { beforeEach( () => { readFile.mockImplementation( async () => { diff --git a/packages/env/lib/config/test/parse-config.js b/packages/env/lib/config/test/parse-config.js index 7d0803af3cdef3..e8e70a5340dba7 100644 --- a/packages/env/lib/config/test/parse-config.js +++ b/packages/env/lib/config/test/parse-config.js @@ -21,7 +21,7 @@ jest.mock( '../../wordpress', () => ( { const DEFAULT_CONFIG = { port: 8888, testsPort: 8889, - autoPort: false, + autoPort: null, mysqlPort: null, phpmyadmin: false, phpmyadminPort: null, @@ -193,7 +193,13 @@ describe( 'parseConfig', () => { expect( parsed ).toEqual( expected ); } ); - it( 'should accept autoPort as a boolean', async () => { + it( 'should accept autoPort as a tri-state (null default, true, false)', async () => { + // 1. With no user config, the default is `null` (the new tri-state + // "unset" sentinel — distinguishable from explicit `false`). + const defaultParsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( defaultParsed.autoPort ).toBeNull(); + + // 2. Explicit `true` survives merge. readRawConfigFile.mockImplementation( async ( configFile ) => { if ( configFile === '/test/gutenberg/.wp-env.json' ) { return { @@ -201,9 +207,21 @@ describe( 'parseConfig', () => { }; } } ); + const parsedTrue = await parseConfig( '/test/gutenberg', '/cache' ); + expect( parsedTrue.autoPort ).toEqual( true ); - const parsed = await parseConfig( '/test/gutenberg', '/cache' ); - expect( parsed.autoPort ).toEqual( true ); + // 3. Explicit `false` survives merge and is observably distinct + // from the default `null` (this is the AC11 boundary check). + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.json' ) { + return { + autoPort: false, + }; + } + } ); + const parsedFalse = await parseConfig( '/test/gutenberg', '/cache' ); + expect( parsedFalse.autoPort ).toEqual( false ); + expect( parsedFalse.autoPort ).not.toBeNull(); } ); it( 'should parse core, plugin, theme, and mapping sources', async () => { @@ -590,4 +608,120 @@ describe( 'parseConfig', () => { ) ); } ); + + describe( '__defaultOriginPorts provenance', () => { + it( 'attaches __defaultOriginPorts as a non-enumerable Set with both http ports when no user config sets them', async () => { + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + + expect( parsed.__defaultOriginPorts ).toBeInstanceOf( Set ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( true ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + expect( parsed.__defaultOriginPorts.size ).toBe( 2 ); + + expect( + Object.prototype.propertyIsEnumerable.call( + parsed, + '__defaultOriginPorts' + ) + ).toBe( false ); + } ); + + it( 'omits development.port from __defaultOriginPorts when local config sets root port', async () => { + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.json' ) { + return { port: 9000 }; + } + } ); + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( false ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + } ); + + it( 'omits tests.port from __defaultOriginPorts when local config sets env.tests.port', async () => { + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.json' ) { + return { + env: { + tests: { port: 9001 }, + }, + }; + } + } ); + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( true ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + false + ); + } ); + + it( 'omits development.port from __defaultOriginPorts when override config sets port', async () => { + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.override.json' ) { + return { port: 9000 }; + } + } ); + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( false ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + } ); + + it( 'omits development.port from __defaultOriginPorts when WP_ENV_PORT is set', async () => { + process.env.WP_ENV_PORT = '4321'; + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( false ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + } ); + + it( 'omits tests.port from __defaultOriginPorts when WP_ENV_TESTS_PORT is set', async () => { + process.env.WP_ENV_TESTS_PORT = '5432'; + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( true ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + false + ); + } ); + + it( '__defaultOriginPorts is invisible to mergeConfigs and toEqual (regression guard for non-enumerable contract)', async () => { + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + + // JSON round-trip must drop the non-enumerable property. + const roundTripped = JSON.parse( JSON.stringify( parsed ) ); + expect( roundTripped.__defaultOriginPorts ).toBeUndefined(); + + // `toEqual` against the publicly-known DEFAULT_CONFIG must still + // pass (i.e. Jest's deep-equal does not consider the + // non-enumerable property). + expect( parsed ).toEqual( DEFAULT_CONFIG ); + + // `Object.keys` / `for…in` / `Object.entries` must all skip it. + expect( Object.keys( parsed ) ).not.toContain( + '__defaultOriginPorts' + ); + } ); + } ); } ); diff --git a/packages/env/lib/config/test/post-process-config.js b/packages/env/lib/config/test/post-process-config.js index d66e096991dd37..67f5af21a04b6c 100644 --- a/packages/env/lib/config/test/post-process-config.js +++ b/packages/env/lib/config/test/post-process-config.js @@ -348,6 +348,246 @@ describe( 'postProcessConfig', () => { } ); } ); + describe( 'port resolver routing (autoPortMode + defaultOriginPorts)', () => { + it( 'threads autoPortMode and defaultOriginPorts to resolveConfigPorts', async () => { + // Mock the resolver to return distinct fallback ports so the + // post-processed config does not trip validatePortUniqueness. + const portResolver = { + resolve: jest + .fn() + .mockResolvedValueOnce( 8890 ) + .mockResolvedValueOnce( 8891 ), + }; + + const processed = await postProcessConfig( + { + env: { + development: { + port: 8888, + config: { + WP_HOME: 'http://localhost', + WP_SITEURL: 'http://localhost', + }, + }, + tests: { + port: 8889, + config: { + WP_HOME: 'http://localhost', + WP_SITEURL: 'http://localhost', + }, + }, + }, + }, + { + portResolver, + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ + 'development.port', + 'tests.port', + ] ), + } + ); + + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + false + ); + // Resolved port flows into the merged env config and into + // appendPortToWPConfigs's WP_HOME / WP_SITEURL outputs. + expect( processed.env.development.port ).toEqual( 8890 ); + expect( processed.env.development.config.WP_HOME ).toEqual( + 'http://localhost:8890' + ); + expect( processed.env.development.config.WP_SITEURL ).toEqual( + 'http://localhost:8890' + ); + expect( processed.env.tests.port ).toEqual( 8891 ); + expect( processed.env.tests.config.WP_HOME ).toEqual( + 'http://localhost:8891' + ); + } ); + + it( 'with autoPortMode=defaults-only routes user-set port to strict and default-origin port to non-strict', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { port: 8888 }, + tests: { port: 9001 }, + }, + }, + { + portResolver, + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ 'development.port' ] ), + } + ); + + // development.port is default-origin → non-strict (false). + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + // tests.port is user-set → strict (true). + expect( portResolver.resolve ).toHaveBeenCalledWith( + 9001, + 'env.tests.port', + true + ); + } ); + + it( 'with autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { + port: 8889, + }, + }, + }, + { + portResolver, + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ + 'development.port', + 'tests.port', + ] ), + } + ); + + // Resolver was called for HTTP ports. + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + false + ); + // Resolver was NEVER called for phpmyadminPort under + // defaults-only mode (preserving today's behavior verbatim + // where phpmyadminPort is only auto-resolved under --auto-port). + const phpmyadminCalls = portResolver.resolve.mock.calls.filter( + ( call ) => call[ 1 ].includes( 'phpmyadminPort' ) + ); + expect( phpmyadminCalls ).toHaveLength( 0 ); + } ); + + it( 'with autoPortMode=all routes both http ports AND phpmyadminPort non-strict (preserves PR #74472 behavior)', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }, + { + portResolver, + autoPortMode: 'all', + defaultOriginPorts: new Set(), + } + ); + + // All three ports get the non-strict (false) third argument. + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8080, + 'env.development.phpmyadminPort', + false + ); + } ); + + it( 'defaults to autoPortMode=off and routes ports strict (back-compat for callers that do not pass options)', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }, + { portResolver } + ); + + // All ports get strict=true under the default 'off' mode. + // Note that 'off' does NOT skip phpmyadminPort — only + // 'defaults-only' does (the skip rule is mode-specific). + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + true + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + true + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8080, + 'env.development.phpmyadminPort', + true + ); + } ); + } ); + describe( 'testsEnvironment', () => { it( 'should ignore env overrides entirely when testsEnvironment is false', async () => { const processed = await postProcessConfig( { diff --git a/packages/env/lib/resolve-available-ports.js b/packages/env/lib/resolve-available-ports.js index 81e0584c8e62c6..a6cce60da9caa8 100644 --- a/packages/env/lib/resolve-available-ports.js +++ b/packages/env/lib/resolve-available-ports.js @@ -77,6 +77,18 @@ function createPortResolver( spinner ) { exclude: usedPorts, } ); + // Inform the user via the existing spinner channel when the + // preferred port was busy and we fell back to a different + // one. Reuses the same spinner instance the resolver already + // holds — introducing a separate logger or stream would be + // a regression detected by the test suite (AC7). + if ( spinner && resolvedPort !== preferredPort ) { + spinner.info( + `Port ${ preferredPort } (${ configPath }) was busy; using ${ resolvedPort } instead.` + ); + spinner.start(); + } + usedPorts.push( resolvedPort ); return resolvedPort; @@ -93,11 +105,18 @@ function createPortResolver( spinner ) { * Resolves available ports on a config object. Iterates over the * defined port properties and resolves each one that has a value. * - * @param {Object} config The config object (after mergeRootToEnvironments). - * @param {Object} portResolver A port resolver created by `createPortResolver`. + * @param {Object} config The config object (after mergeRootToEnvironments). + * @param {Object} portResolver A port resolver created by `createPortResolver`. + * @param {Object} [options] Routing options. + * @param {'off'|'all'|'defaults-only'} [options.autoPortMode] The auto-port routing mode. `'off'` forces strict per-port (production never reaches this branch because the resolver itself is not created in `'off'` mode). `'all'` mirrors today's `--auto-port` behavior — every port (including phpmyadminPort) auto-falls-back. `'defaults-only'` only auto-falls-back HTTP ports whose value originated from the default config; user-set HTTP ports stay strict, and `phpmyadminPort` is skipped entirely (preserving today's behavior verbatim — phpmyadminPort is only resolved when the user explicitly opts in via `--auto-port`). + * @param {Set} [options.defaultOriginPorts] The set of port keys (e.g. `'development.port'`, `'tests.port'`) whose effective value comes from the default config rather than any user-supplied source. Used by `'defaults-only'` mode. * @return {Promise} The config with resolved ports. */ -async function resolveConfigPorts( config, portResolver ) { +async function resolveConfigPorts( + config, + portResolver, + { autoPortMode = 'off', defaultOriginPorts = new Set() } = {} +) { for ( const { env, property } of PORT_DEFINITIONS ) { const currentValue = config.env[ env ][ property ]; @@ -107,6 +126,14 @@ async function resolveConfigPorts( config, portResolver ) { continue; } + // Per-port skip rule. Under `defaults-only` mode we deliberately + // do not resolve `phpmyadminPort` at all so its behavior is + // identical to today's: it is only auto-resolved when the user + // has explicitly opted in via `--auto-port` (the `'all'` mode). + if ( autoPortMode === 'defaults-only' && property !== 'port' ) { + continue; + } + // Use a well-known preferred port when one isn't explicitly set. // For explicit ports, use the configured value. const key = `${ env }.${ property }`; @@ -117,12 +144,31 @@ async function resolveConfigPorts( config, portResolver ) { continue; } - // When --auto-port is active (the only time this runs), - // always auto-fallback to an available port. + // Decide whether this port participates in auto-fallback. + // - `'off'` → strict (defensive; the resolver is normally not + // created in this mode, so this branch is reachable only when + // the function is unit-tested directly). + // - `'all'` → non-strict for every port. Preserves today's + // `--auto-port` behavior, including the phpmyadminPort path. + // - `'defaults-only'` → non-strict only for HTTP ports whose value + // came from `DEFAULT_ENVIRONMENT_CONFIG`. User-set HTTP ports + // stay strict so the existing port-busy error surfaces. + let strict; + if ( autoPortMode === 'off' ) { + strict = true; + } else if ( autoPortMode === 'all' ) { + strict = false; + } else { + // 'defaults-only' — only `property === 'port'` reaches here + // because of the skip rule above. + strict = ! defaultOriginPorts.has( key ); + } + const configPath = `env.${ key }`; config.env[ env ][ property ] = await portResolver.resolve( preferredPort, - configPath + configPath, + strict ); } diff --git a/packages/env/lib/test/resolve-available-ports.js b/packages/env/lib/test/resolve-available-ports.js index 049ab6c8e4db0b..385c22588bab7e 100644 --- a/packages/env/lib/test/resolve-available-ports.js +++ b/packages/env/lib/test/resolve-available-ports.js @@ -77,7 +77,9 @@ describe( 'resolve-available-ports', () => { }, }; - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); // Null ports should be resolved using preferred ports. expect( findAvailablePort ).toHaveBeenCalledWith( @@ -101,7 +103,9 @@ describe( 'resolve-available-ports', () => { }, }; - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); expect( config.env.development.port ).toBe( 9000 ); expect( config.env.tests.port ).toBe( 9001 ); @@ -125,7 +129,9 @@ describe( 'resolve-available-ports', () => { }, }; - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); // phpmyadminPort should use findAvailablePort (non-strict), // not isPortAvailable (strict), even with an explicit value. @@ -145,11 +151,246 @@ describe( 'resolve-available-ports', () => { }; findAvailablePort.mockResolvedValue( 8888 ); - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); // phpmyadminPort is undefined so should not trigger any resolution. expect( config.env.development.phpmyadminPort ).toBeUndefined(); expect( config.env.tests.phpmyadminPort ).toBeUndefined(); } ); + + it( 'under autoPortMode=defaults-only uses strict mode for non-default-origin ports and non-strict for default-origin ports', async () => { + findAvailablePort.mockImplementation( ( { preferredPort } ) => + Promise.resolve( preferredPort ) + ); + isPortAvailable.mockResolvedValue( true ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { port: 8888 }, + tests: { port: 9001 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ 'development.port' ] ), + } ); + + // Default-origin development port → non-strict (findAvailablePort). + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8888 } ) + ); + // User-set tests port → strict (isPortAvailable). + expect( isPortAvailable ).toHaveBeenCalledWith( 9001 ); + } ); + + it( 'under autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)', async () => { + findAvailablePort.mockImplementation( ( { preferredPort } ) => + Promise.resolve( preferredPort ) + ); + isPortAvailable.mockResolvedValue( true ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ + 'development.port', + 'tests.port', + ] ), + } ); + + // HTTP ports were resolved. + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8888 } ) + ); + // phpmyadminPort was NOT resolved through either path. + expect( findAvailablePort ).not.toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8080 } ) + ); + expect( isPortAvailable ).not.toHaveBeenCalledWith( 8080 ); + // And its value is left untouched. + expect( config.env.development.phpmyadminPort ).toEqual( 8080 ); + } ); + + it( 'under autoPortMode=all uses non-strict mode for all ports including phpmyadminPort', async () => { + findAvailablePort.mockImplementation( ( { preferredPort } ) => + Promise.resolve( preferredPort ) + ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); + + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8888 } ) + ); + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8889 } ) + ); + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8080 } ) + ); + expect( isPortAvailable ).not.toHaveBeenCalled(); + } ); + + it( 'under autoPortMode=off uses strict mode for HTTP ports and still resolves phpmyadminPort strictly', async () => { + isPortAvailable.mockResolvedValue( true ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'off', + } ); + + expect( isPortAvailable ).toHaveBeenCalledWith( 8888 ); + expect( isPortAvailable ).toHaveBeenCalledWith( 8889 ); + expect( isPortAvailable ).toHaveBeenCalledWith( 8080 ); + expect( findAvailablePort ).not.toHaveBeenCalled(); + } ); + } ); + + describe( 'createPortResolver moved-port notice (R11 / AC7)', () => { + const stubSpinner = () => ( { + text: '', + info: jest.fn(), + start: jest.fn(), + } ); + + it( 'emits spinner.info exactly once when fallback occurs and re-arms the spinner', async () => { + findAvailablePort.mockResolvedValue( 8890 ); + const spinner = stubSpinner(); + + const resolver = createPortResolver( spinner ); + await resolver.resolve( 8888, 'env.development.port' ); + + expect( spinner.info ).toHaveBeenCalledTimes( 1 ); + expect( spinner.info.mock.calls[ 0 ][ 0 ] ).toMatch( + /8888.*busy.*8890/i + ); + // Spinner is re-armed after the info notice (matches the + // existing `spinner.warn(...); spinner.start();` precedent in + // commands/start.js). + expect( spinner.start ).toHaveBeenCalled(); + expect( spinner.info.mock.invocationCallOrder[ 0 ] ).toBeLessThan( + spinner.start.mock.invocationCallOrder[ 0 ] + ); + } ); + + it( 'does NOT emit spinner.info when the preferred port is available (no move occurred)', async () => { + // findAvailablePort returns the preferred port itself — + // signalling no fallback was needed. + findAvailablePort.mockResolvedValue( 8888 ); + const spinner = stubSpinner(); + + const resolver = createPortResolver( spinner ); + await resolver.resolve( 8888, 'env.development.port' ); + + expect( spinner.info ).not.toHaveBeenCalled(); + } ); + + it( 'does NOT emit spinner.info on the strict failure path', async () => { + isPortAvailable.mockResolvedValue( false ); + const spinner = stubSpinner(); + + const resolver = createPortResolver( spinner ); + await expect( + resolver.resolve( 9000, 'env.development.port', true ) + ).rejects.toThrow( /Port 9000.*is busy/ ); + + expect( spinner.info ).not.toHaveBeenCalled(); + } ); + + it( 'does not write to console or process.stdout when fallback occurs (regression guard)', async () => { + findAvailablePort.mockResolvedValue( 8890 ); + + const consoleLog = jest + .spyOn( console, 'log' ) + .mockImplementation( () => {} ); + const consoleInfo = jest + .spyOn( console, 'info' ) + .mockImplementation( () => {} ); + const consoleWarn = jest + .spyOn( console, 'warn' ) + .mockImplementation( () => {} ); + const stdoutWrite = jest + .spyOn( process.stdout, 'write' ) + .mockImplementation( () => true ); + + try { + const resolver = createPortResolver( stubSpinner() ); + await resolver.resolve( 8888, 'env.development.port' ); + + // AC7: introducing a separate output channel would be a + // detectable regression. None of these were called. + expect( consoleLog ).not.toHaveBeenCalled(); + expect( consoleInfo ).not.toHaveBeenCalled(); + expect( consoleWarn ).not.toHaveBeenCalled(); + expect( stdoutWrite ).not.toHaveBeenCalled(); + } finally { + consoleLog.mockRestore(); + consoleInfo.mockRestore(); + consoleWarn.mockRestore(); + stdoutWrite.mockRestore(); + } + } ); + + it( 'suppresses the notice silently when no spinner is provided (test-path safety)', async () => { + findAvailablePort.mockResolvedValue( 8890 ); + + const consoleLog = jest + .spyOn( console, 'log' ) + .mockImplementation( () => {} ); + const consoleInfo = jest + .spyOn( console, 'info' ) + .mockImplementation( () => {} ); + + try { + // No spinner argument — must not throw and must not + // silently log to console as a fallback channel. + const resolver = createPortResolver(); + await expect( + resolver.resolve( 8888, 'env.development.port' ) + ).resolves.toEqual( 8890 ); + + expect( consoleLog ).not.toHaveBeenCalled(); + expect( consoleInfo ).not.toHaveBeenCalled(); + } finally { + consoleLog.mockRestore(); + consoleInfo.mockRestore(); + } + } ); } ); } ); From d0d26f80110484d35c858087a48f4683a6253f47 Mon Sep 17 00:00:00 2001 From: Carlos Bravo <37012961+cbravobernal@users.noreply.github.com> Date: Mon, 11 May 2026 17:45:01 +0200 Subject: [PATCH 5/6] docs(env): document default auto-port fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updates packages/env/README.md (autoPort tri-state row, rewritten "Automatic Port Selection" section, --auto-port options block) and packages/env/CHANGELOG.md ("Unreleased" → "New Features" bullet referencing #49843 and #74472). Refines the --auto-port describe string in lib/cli.js so wp-env start --help no longer claims that the flag is required for default-port fallback. Includes RP phase 5 review artifacts (docs-review-1 REJECTED, 1 blocker; docs-review-2 APPROVED) produced by the doc-writer / doc-reviewer team. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../docs-review-1.md | 430 ++++++++++++++++++ .../docs-review-2.md | 302 ++++++++++++ packages/env/CHANGELOG.md | 4 + packages/env/README.md | 28 +- packages/env/lib/cli.js | 2 +- 5 files changed, 757 insertions(+), 9 deletions(-) create mode 100644 .pipelines/49843-wp-env-default-port-fallback/docs-review-1.md create mode 100644 .pipelines/49843-wp-env-default-port-fallback/docs-review-2.md diff --git a/.pipelines/49843-wp-env-default-port-fallback/docs-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/docs-review-1.md new file mode 100644 index 00000000000000..6c89a8fe521593 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/docs-review-1.md @@ -0,0 +1,430 @@ +# Phase 5 — Documentation review + +Iteration 1. + +Pipeline: `49843-wp-env-default-port-fallback` +Spec: `spec.md` (round 2 APPROVED). +Plan: `plan.md` (round 2 APPROVED). +Code-review: `code-review-1.md` (APPROVED, with conditions deferred to docs/PR phases). +Reviewed artifact: working-tree changes to `packages/env/README.md` and `packages/env/CHANGELOG.md` (no doc-writer commit yet). + +--- + +## Method + +I read the prompt, spec, plan, and code-review-1 end-to-end. I read the +implementation diff (`git diff HEAD~1 HEAD -- packages/env/`) and +cross-checked the doc-writer's working-tree diff (`git diff -- packages/env/README.md +packages/env/CHANGELOG.md`) against the implementation. I read the +relevant source files (`load-config.js`, `parse-config.js`, +`post-process-config.js`, `resolve-available-ports.js`, `commands/start.js`, +`cli.js`) to verify every doc claim. I ran `npm run lint:js -- packages/env` +from the repo root. I attempted `npm run test:unit -- packages/env`; that +command failed due to a sibling-worktree Haste-map collision unrelated to +this change (see §Lint and tests below). + +## Diff hygiene + +`git status --short` reports exactly two modified files: + +``` +M packages/env/CHANGELOG.md +M packages/env/README.md +``` + +Both are inside `packages/env/`. **No scope creep**. ✅ + +--- + +## Required check 1 — README accuracy + +I cross-checked every claim in the README diff against the implementation +on HEAD. + +### Tri-state semantics + +README config-table row (line 609) for `"autoPort"` reads: + +> Tri-state automatic HTTP port selection. When `null` (the default), the +> default ports `8888`/`8889` automatically fall back to the next available +> port if busy, but explicitly configured ports stay strict. Set to `true` +> to also fall back on user-set ports. Set to `false` to opt out entirely, +> including on the default ports. + +Source verification: +- `parse-config.js:93` — `autoPort: null` is the default in + `DEFAULT_ENVIRONMENT_CONFIG`. ✅ +- `parse-config.js:494-501` — validator allows `null`, `true`, `false`. ✅ +- `load-config.js:96-112` — tri-state mapping: `true → 'all'`, + `false → 'off'`, anything else (including `null`/`undefined`) → + `'defaults-only'`. ✅ +- `resolve-available-ports.js:128-149` — under `'defaults-only'`, + `port` (HTTP) routes per provenance; `phpmyadminPort` is skipped; + under `'all'`, every port is non-strict; under `'off'`, every port + is strict. ✅ + +The README claim that `false` "opts out entirely, including on the +default ports" is accurate. + +### CI guard + +README "Automatic Port Selection" final paragraph: + +> Automatic port selection is also disabled whenever the `CI` environment +> variable is set, regardless of the `autoPort` value, so test runs stay +> deterministic. + +Source verification: `load-config.js:109-112` — `if ( process.env.CI ) { autoPortMode = 'off'; }` +runs **after** the tri-state mapping and unconditionally forces `'off'`, +which then prevents the resolver from being created at line 114. The +"regardless of the `autoPort` value" clause is correct: `autoPortMode = 'off'` +is set after the user-state-derived mapping. ✅ + +### "User-set ports stay strict" claim + +README §2 paragraph and "Automatic Port Selection" §2: + +> Ports you set explicitly (in `.wp-env.json`, in `.wp-env.override.json`, +> or via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`) are never silently moved. + +Source verification: +- `parse-config.js:213-273` — `computeDefaultOriginPorts` / + `layerSetsDevelopmentPort` / `layerSetsTestsPort` inspect + `localConfig`, `overrideConfig`, and `environmentVarOverrides` for + `port`, `testsPort`, `env.development.port`, `env.tests.port`. ✅ +- `resolve-available-ports.js:136-149` — under `'defaults-only'` mode, + `strict = ! defaultOriginPorts.has( key )`. ✅ + +The list `(port / testsPort / WP_ENV_PORT / WP_ENV_TESTS_PORT)` exactly +matches the env-var enumeration the plan resolved in OQ4 against +`get-config-from-environment-vars.js:36-72`. ✅ + +**Minor finding (non-blocker):** The README does not mention the +nested form `env.development.port` / `env.tests.port` even though the +implementation honors it (verified at `parse-config.js:243` and `:266`). +A contributor who pins ports per-environment via the `env` block has the +same protection; the README's enumeration is accurate but +non-exhaustive. Acceptable as-is for a user-facing doc. + +### Informational notice description + +README "Automatic Port Selection" §1: + +> The CLI prints a one-line notice through the same spinner used for +> other start-time messages so you can see which port was actually +> bound. + +Source verification: `resolve-available-ports.js:80-90` — +`if ( spinner && resolvedPort !== preferredPort ) { spinner.info(...); spinner.start(); }`. +The notice is gated on (a) a spinner being present and (b) an actual +move. It uses the same `spinner` instance the resolver was constructed +with (passed in by `load-config.js:114` from `loadConfig`'s +`{ spinner }` option, originally from `cli.js`'s `withSpinner`). ✅ + +### Example `.wp-env.json` block + +```json +{ + "autoPort": false +} +``` + +Validator at `parse-config.js:494-503` accepts `boolean` and `null` for +root-level `autoPort`. `false` is valid. ✅ + +### README §2 ("Check the port number") paragraph + +> By default `wp-env` tries port 8888, meaning that the local +> environment will be available at http://localhost:8888. If 8888 is +> busy on your host and you have not configured a port explicitly, +> `wp-env` automatically falls back to the next available port and +> prints the resolved port at start time … + +Accurate. The "tries" wording (vs. the previous "uses") correctly +softens the previous fixed-port claim now that fallback is the default. +Cross-references to "Automatic Port Selection" point at the right +anchor. + +--- + +## Required check 2 — CHANGELOG entry + +CHANGELOG diff: + +``` +## Unreleased + +### New Features + +- The default ports `8888` (development) and `8889` (tests) now automatically … +``` + +Verification against the file's existing conventions: + +- **Placement under `## Unreleased`.** ✅ The entry lands at lines 5-7 + immediately after the `## Unreleased` heading on line 3. +- **Heading style.** Surrounding entries use `### New Features`, + `### Enhancements`, `### Bug Fixes`, `### Breaking Changes`, + `### Deprecation`, `### Internal`. The chosen `### New Features` + matches the existing entry on line 31 ("Added `--auto-port` flag …") + which describes a sibling feature, so it is the natural choice. ✅ +- **Tone.** The entry reads as a concise user-visible feature + description with the opt-out documented inline. Consistent with + surrounding `### New Features` bullets (e.g. lines 33, 43-47). ✅ +- **Link format.** `([#49843](https://github.com/WordPress/gutenberg/issues/49843), [#74472](https://github.com/WordPress/gutenberg/pull/74472))`. + The format `([#NNN](URL))` matches existing entries (e.g. line 11: + `([#20569](https://github.com/WordPress/gutenberg/issues/20569))`, + line 33's `--auto-port` entry similarly references the PR). ✅ +- **Length.** The bullet is one long sentence (~340 characters). + Surrounding bullets in the file vary widely; e.g. line 11 is ~280 + chars, line 33 is similar to this one in length. Acceptable. The + semicolon-separated multi-clause structure is heavy for a CHANGELOG + bullet but defensible because the feature has three distinct facets + (default behavior, opt-in semantics for explicit ports, opt-out + via `false`). **Non-blocker.** + +**Minor finding (non-blocker):** The link includes the **issue** for +`#49843` (correct; that's the feature request) and the **PR** for +`#74472` (correct; that's the prior `--auto-port` PR). Both targets +exist. This dual-link pattern is unusual for the CHANGELOG (most +entries link a single `#NNN`) but it's coherent with the spec, which +explicitly threads the new behavior through PR #74472's machinery. + +--- + +## Required check 3 — JSDoc cross-check + +I read the JSDoc in every touched source file to verify the tri-state +is described consistently. + +| File | Symbol | JSDoc state | Verdict | +|---|---|---|---| +| `commands/start.js` | `start` `@param options.autoPort` (line 32) | `{boolean\|undefined}` … "Tri-state: `true` enables … fallback for every port …; `false` disables … even on default ports; `undefined` (the typical case — flag not supplied) defers to `.wp-env.json`'s `autoPort` field, where unset/`null` means 'auto-fallback only on default ports'." | ✅ Tri-state described. | +| `config/load-config.js` | `loadConfig` `@param options.autoPort` (line 44) | `{boolean\|undefined}` … "Tri-state CLI override … `true` enables fallback for all ports, `false` disables fallback even on default ports, `undefined` defers to `config.autoPort` (which itself is tri-state — `null`/`undefined` means 'fallback only on default ports')." | ✅ Tri-state described. | +| `config/parse-config.js` | `WPRootConfigOptions.autoPort` (line 38) | `{boolean\|null}` … "Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports)." | ✅ Tri-state described. | +| `config/post-process-config.js` | `postProcessConfig` (lines 18-22) | New `@param options.autoPortMode` describes `'off'`/`'all'`/`'defaults-only'` semantics; `@param options.defaultOriginPorts` describes the Set semantics. | ✅ Both new options documented. | +| `resolve-available-ports.js` | `resolveConfigPorts` (lines 108-115) | Same two new `@param`s with full mode descriptions including the phpmyadminPort skip rule. | ✅ Both new options documented. | +| `resolve-available-ports.js` | `createPortResolver` `resolve` method (lines 42-49) | Adds `@param strict` "When true, fail if the port is busy instead of finding an alternative." | ✅ Already correct. | +| `resolve-available-ports.js` | `createPortResolver` itself (line 35) | "Creates a port resolver that tracks used ports." Brief but accurate. The new "moved port" notice is documented inline at the call site (lines 80-86 inline comment) rather than in the function-level JSDoc. **Acceptable.** | + +**No stale JSDoc found.** ✅ + +--- + +## Required check 4 — Doc-writer's flagged Open Issue 2 (`lib/cli.js` describe string) + +The role brief flags this for adversarial assessment. My verdict: +**leaving the describe string untouched is NOT acceptable; it must be +updated for approval.** + +### Evidence + +`lib/cli.js:154-158` defines the `--auto-port` flag with this `describe`: + +> 'Automatically find available ports when configured ports are busy. +> Overrides the .wp-env.json "autoPort" setting.' + +Two reasons this string is now actively misleading: + +1. **It implies `--auto-port` is the only path to auto-fallback.** + Post-this-PR, default ports auto-fall-back without the flag. A + contributor who reads the CLI help and concludes "ports only + auto-move when I pass `--auto-port`" will be wrong, and on a busy + host they will be confused when the start succeeds on a different + port without their having passed the flag. +2. **It understates what the flag now buys.** The flag now means "also + auto-fall-back on user-set ports", not the previous "auto-fall-back + on busy ports at all". A user reading this in `wp-env start --help` + has no way to discover the new explicit-port semantic. + +**Surface where this string is rendered:** +- `wp-env start --help` (yargs auto-generates from `describe`). +- `packages/env/README.md:368-369` reproduces the help output verbatim + in the `### wp-env start` section. So the README *itself* contains + the stale string in a code block, even though the doc-writer + correctly updated the prose elsewhere. This contradicts the prose at + README lines 605-630 that the doc-writer rewrote. **The README is + internally inconsistent until cli.js is updated** (or until the + rendered help block in README is hand-edited, which is brittle and + risks drifting from the actual CLI output). + +### On the role-brief's "do not change source code" caveat + +The brief notes: "the role brief said 'Do NOT change behavior, source +code under `lib/` (other than JSDoc cleanup if strictly needed)'. A +user-facing string is not strictly source behavior; verdict is yours." + +A `yargs` `describe` string is a documentation surface masquerading +as source code. It is rendered to the user without any code path +executing it as logic. Treating it as documentation rather than +behavior is the correct read. The plan §2 Step 7 explicitly listed +`commands/start.js` JSDoc updates as in-scope for the implementation +phase; an analogous CLI describe-string update is materially the same +kind of doc work and falls within the docs-phase remit. + +**Decision: this is a blocker for approval.** The CLI describe string +must be rewritten to reflect the new tri-state contract before the PR +opens. Recommended substance (doc-writer chooses exact wording): + +> "Force automatic port selection for every port (including ones you +> explicitly set in .wp-env.json). By default, only the standard +> ports 8888/8889 fall back automatically; this flag extends that to +> user-configured ports. Equivalent to setting `autoPort: true`." + +### Knock-on + +If the cli.js describe string is updated, the README `wp-env start --help` +block at lines 368-369 must be regenerated to match (or hand-edited +to match the new describe text). The doc-writer should do both in +the same change. + +--- + +## Required check 5 — Coverage of spec acceptance criteria with user-facing surface + +For each AC with a user-facing surface, I checked whether the README +covers it. + +| AC | User-facing surface? | README coverage | +|---|---|---| +| AC1 — default dev port falls back | Yes | ✅ "Automatic Port Selection" §1; §2 "Check the port number" updated. | +| AC2 — default tests port falls back | Yes | ✅ Same section. The 8889 case is implicit ("default ports `8888`/`8889`"); reasonable for a user-facing README. | +| AC3 — explicit port stays strict | Yes | ✅ "Automatic Port Selection" §2 ("Ports you set explicitly … are never silently moved"). | +| AC4 — `--auto-port` / `autoPort: true` falls back on explicit ports | Yes | ✅ "Automatic Port Selection" §3 with example. | +| AC5 — `autoPort: false` opt-out | Yes | ✅ "Automatic Port Selection" §4 with JSON example. | +| AC6 — `CI=1` disables fallback | Yes | ✅ Final paragraph of "Automatic Port Selection". | +| AC7 — informational message contract | Partial | ✅ The README mentions "prints a one-line notice through the same spinner". Adequate for a user doc. | +| AC8 — CI guard regression detector | No (test-only) | n/a | +| AC9a — resolved port flows downstream | No (internal) | n/a | +| AC9b — live reachability | PR test plan, not README | n/a (deferred to PR body per spec §5). | +| AC9c — other commands see fallback port | Implicit | ✅ Inherited from cached compose; not a separate doc claim to make. | +| AC10 — existing tests stay green | No (test-only) | n/a | +| AC11 — tri-state survives end-to-end | No (test-only / typedef) | ✅ Surface is the `autoPort` row in the schema table; covered. | + +**Coverage finding:** the README does NOT mention the upward-scan +directionality explicitly in the §2 paragraph ("Check the port number") +even though spec R1/R2 require upward scan and the source enforces it. +The "Automatic Port Selection" §1 does say "scans upward to the next +available port (for example: `8888` → `8890` → `8891`, ...)". Adequate. +✅ + +**Coverage finding:** the README also does not mention the "`8888` → +**`8890`** → `8891`" jump-by-2 pattern's reason (both 8888 and 8889 are +checked-or-busy; the example skips 8889 because it's the default tests +port). Could mislead a reader into thinking the scanner goes by 2s. +**Non-blocker** but a nicety. + +--- + +## Required check 6 — Tone and style + +I compared the new README prose against the surrounding sections. + +- "Check the port number" §2 retains its existing imperative voice + ("By default …", "You can configure …"). The added clause about + fallback uses a parallel construction. ✅ +- "Automatic Port Selection" §§1-4 use the same paragraph cadence and + code-block style (sh fence for CLI, json fence for config) as the + surrounding sections. ✅ +- The em-dash and en-dash usage matches surrounding prose (e.g. the + hyphenated "auto-fall-back" mirrors the spec's terminology and is + used consistently). ✅ +- The new bullet in CHANGELOG is one long sentence with semicolons. + Slightly heavier than the surrounding `### New Features` entries + (e.g. line 33's single-sentence simpler bullet) but defensible + because three distinct semantic facets are bundled. **Non-blocker.** + +**No jarring deviations.** + +--- + +## Required check 7 — Lint and tests + +- `npm run lint:js -- packages/env` from the repo root: **PASSES** + (exit 0). Note: this contradicts the code-review-1 finding that + `eslint-plugin-react-hooks` was missing on the parent checkout; the + dep is now present (likely installed since the code-review-1 ran). + This is not a docs-phase concern; the docs changes do not touch + any lint-relevant code. +- `npm run test:unit -- packages/env` from the repo root: **FAILS** with + a Jest Haste-map duplicate-package collision because sibling + worktrees in the parent checkout (`/Users/carlos/Developer/wp-plugins/gutenberg/.pi/worktrees/77766-popover-bind/packages/compose/package.json`) + collide with this worktree's copy. **This is a host-environment issue + unrelated to the docs changes** (no test sources are touched in this + iteration's diff). The code-review-1 already confirmed 181/181 tests + pass in a clean run; running tests from this worktree's perspective + with the sibling worktree present is not feasible without disturbing + unrelated work. **Accepted as a documented host-environment + limitation, not a regression.** The doc-writer's claim that lint / + test pass with the docs changes is **partially verified**: lint + confirmed clean; tests confirmed clean by inheritance from + code-review-1's run on the same source files (no test code was + touched in the docs phase). + +--- + +## Required check 8 — No scope creep + +`git status --short` shows only `packages/env/README.md` and +`packages/env/CHANGELOG.md`. **Both inside `packages/env/`**. ✅ + +--- + +## Summary of findings + +### Blockers (1) + +1. **CLI `--auto-port` describe string in `lib/cli.js:154-158` must + be updated** to reflect the new tri-state semantics. As filed, the + string is actively misleading: it implies `--auto-port` is the only + path to auto-fallback (no longer true) and understates the flag's + new meaning ("also fall back on user-set ports"). The string is a + user-facing surface rendered in `wp-env start --help` and + reproduced verbatim in `README.md:368-369`, which makes the README + internally inconsistent: the prose elsewhere correctly describes + the new behavior, but the embedded help block contradicts it. A + yargs `describe` is documentation, not behavior, and falls within + the docs phase's remit. **Required for approval.** + +### Non-blocker findings + +- README §"Automatic Port Selection" §2 lists the user-set sources as + `port` / `testsPort` / `WP_ENV_PORT` / `WP_ENV_TESTS_PORT` but does + not mention the nested `env.development.port` / `env.tests.port` + form (which is also honored). Acceptable as-is for a user doc; + optional polish. +- The CHANGELOG bullet is long and semicolon-separated. Style is + defensible; could be tightened in a future polish pass. +- The `8888` → `8890` example in "Automatic Port Selection" §1 might + read as "scanner skips by 2" without context. Optional clarification + could note "8889 is reserved as the default tests port". +- README `wp-env start --help` reproduction at lines 368-369 will need + to be regenerated once the cli.js describe string is updated, or it + will continue to drift. + +--- + +## Verdict + +``` +REJECTED +``` + +The README and CHANGELOG prose changes are accurate, well-placed, and +match the implementation across all eight required checks except for +one: the unupdated CLI `--auto-port` `describe` string in `lib/cli.js` +leaves the help-text surface (and the README block that reproduces it) +contradicting the rest of the documentation. A `yargs` `describe` is +documentation, not behavior, and is within the docs phase's remit. + +The doc-writer should: + +1. Update `lib/cli.js:154-158`'s `--auto-port` `describe` to reflect + the new tri-state contract (suggested wording in §"Required check + 4" above). +2. Regenerate the `wp-env start --help` code block in + `packages/env/README.md:343-369` so it matches the new describe + text. +3. Re-request review. + +All other aspects of the documentation are correct and complete. diff --git a/.pipelines/49843-wp-env-default-port-fallback/docs-review-2.md b/.pipelines/49843-wp-env-default-port-fallback/docs-review-2.md new file mode 100644 index 00000000000000..64993f54b52184 --- /dev/null +++ b/.pipelines/49843-wp-env-default-port-fallback/docs-review-2.md @@ -0,0 +1,302 @@ +# Phase 5 — Documentation review + +Iteration 2. + +Pipeline: `49843-wp-env-default-port-fallback` +Spec: `spec.md` (round 2 APPROVED). +Plan: `plan.md` (round 2 APPROVED). +Code-review: `code-review-1.md` (APPROVED with conditions deferred to docs/PR phases). +Prior docs review: `docs-review-1.md` (REJECTED — single blocker on stale `--auto-port` describe string in `lib/cli.js` and the README mirror). +Reviewed artifact: staged changes to `packages/env/CHANGELOG.md`, `packages/env/README.md`, and `packages/env/lib/cli.js` (3 files, +25 / −9). + +--- + +## Method + +I read the spec, plan, code-review-1, and docs-review-1 end-to-end. I read the +staged diff (`git diff --staged -- packages/env/lib/cli.js packages/env/README.md +packages/env/CHANGELOG.md`) end-to-end. I cross-checked the new `--auto-port` +describe string in `lib/cli.js` against its mirror in `packages/env/README.md`'s +`### wp-env start` help block byte-for-byte. I verified the README's +"Automatic Port Selection" prose still reads consistently with the new help-text +description. I verified the CHANGELOG entry still accurately reflects the +implementation. I confirmed no scope creep beyond the three authorized files +(no JSDoc, no test changes). I ran `npm run lint:js -- packages/env` and +`npx jest packages/env --config test/unit/jest.config.js` from inside the +worktree to bypass the host-environment Haste-map collision documented in +docs-review-1. + +--- + +## Round 1 blocker — closed + +The single round-1 blocker was the stale `--auto-port` describe string at +`lib/cli.js:154-158` and its mirror in `README.md` (the `### wp-env start` +help-output code block). Round 2 updates both: + +### `lib/cli.js:157` (source of truth, rendered by yargs in `wp-env start --help`) + +``` +'Also fall back to the next available port when explicitly configured ports are busy. By default, only the standard ports 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" setting.' +``` + +### `README.md:368-371` (mirror, displayed inside the documented `wp-env start` help block) + +The README presents the same string wrapped to fit yargs' rendered column +width: + +``` + --auto-port Also fall back to the next available port when explicitly + configured ports are busy. By default, only the standard ports + 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" + setting. [boolean] +``` + +### Byte-for-byte equivalence check + +I extracted the unwrapped string text from both surfaces (collapsing the +README's yargs line wraps and leading whitespace) and confirmed they are +identical (193 chars in both; equality check returned `True`). The README +mirror is an accurate reproduction of the yargs-rendered output of the +new `lib/cli.js` describe string. **No drift between source and mirror.** +✅ + +### Substantive accuracy of the new describe string (against the implementation) + +I cross-checked all three claims the new describe makes: + +1. **"Also fall back to the next available port when explicitly configured + ports are busy."** — `load-config.js:101` maps CLI `autoPort: true` → + `autoPortMode = 'all'`; `resolve-available-ports.js:144-146` under `'all'` + sets `strict = false` for every port (HTTP and `phpmyadminPort`). So + passing `--auto-port` extends fallback to user-set ports (which would be + strict under `'defaults-only'` because the provenance Set excludes + user-set keys). ✅ +2. **"By default, only the standard ports 8888/8889 auto-fall-back."** — + `parse-config.js:93` defaults `autoPort` to `null`; `load-config.js:101-107` + maps `null` (via the `else` branch) → `autoPortMode = 'defaults-only'`; + `resolve-available-ports.js:128-149` under `'defaults-only'` skips + `phpmyadminPort` entirely and routes HTTP ports per `defaultOriginPorts`. + So the bare default does indeed fall back only on the standard + `8888`/`8889` (assuming no user override). ✅ +3. **"Overrides the .wp-env.json `autoPort` setting."** — `load-config.js:96-98` + establishes `effectiveAutoPort = autoPort !== undefined ? autoPort : + config.autoPort`, so the CLI value wins whenever it is supplied (and + `cli.js:155-156` defines `--auto-port` as a boolean with no default, so + "undefined" maps to "flag not passed"). ✅ + +The describe string is accurate at every clause. ✅ + +### Round 1 knock-on (regenerate the README help block) — closed + +Round 1 also flagged that the README `wp-env start --help` block at the old +line 368-369 had to be regenerated once the cli.js describe was updated. +The diff confirms both edits happened in lockstep — the new describe text +appears in `lib/cli.js:157` AND in the README help block, with the README's +yargs line-wrapping matching the column layout yargs produces for a string +of this length. ✅ + +### Round 1 verdict on the prose changes — re-confirmed + +Round 1 rated the README prose ("Automatic Port Selection" §§1–4, the +`autoPort` schema-table row, the §2 "Check the port number" paragraph) and +the CHANGELOG entry as accurate and well-placed. I re-verified each below. + +--- + +## Required check 1 — README "Automatic Port Selection" prose internal consistency + +I re-read the `### Automatic Port Selection` section after the cli.js edit +to confirm there is no contradiction between the new help-text claim and +the prose. The relevant sentences: + +- README §1 (line 624): "By default, `wp-env` tries the standard ports + (`8888` for development, `8889` for tests). If you have not configured + a port explicitly and one of those defaults is busy on the host, `wp-env` + scans upward to the next available port…" — consistent with the help + text's "By default, only the standard ports 8888/8889 auto-fall-back". +- README §2 (line 626): "Ports that you configured yourself … are never + silently moved. If your configured port is busy, the start fails…" — + consistent with the help text's implicit promise that `--auto-port` is + the way to extend fallback to "explicitly configured ports". +- README §3 (line 628): "If you want auto-fallback to apply to your + configured ports too, pass the `--auto-port` flag (or set `"autoPort": + true` in `.wp-env.json`)" — exactly the same proposition as the help + text's first sentence, in user-facing prose. +- README §4 (line 634): `"autoPort": false` opt-out — consistent with the + schema-table row at line 611 ("Set to `false` to opt out entirely, + including on the default ports"). +- README final paragraph (line 642): `CI=1` continues to disable fallback + — consistent with `load-config.js:109-112` (CI guard fires after the + tri-state mapping and unconditionally forces `'off'`). + +**No internal contradiction.** The new help text reads as a one-paragraph +summary of what the four prose paragraphs spell out in detail. ✅ + +--- + +## Required check 2 — CHANGELOG accuracy (re-confirmed; no revision needed) + +The CHANGELOG entry at `packages/env/CHANGELOG.md:5-7` reads: + +> The default ports `8888` (development) and `8889` (tests) now automatically +> fall back to the next available port when busy, so `wp-env start` works out +> of the box on hosts where those ports are taken; explicitly configured ports +> keep today's strict behavior unless `--auto-port` / `"autoPort": true` is +> passed, and the new `"autoPort": false` opt-out disables fallback even on +> the defaults. ([#49843](https://github.com/WordPress/gutenberg/issues/49843), +> [#74472](https://github.com/WordPress/gutenberg/pull/74472)) + +Each clause re-verified against the implementation: +- "default ports `8888` and `8889` now automatically fall back" → matches + `load-config.js:107` `autoPortMode = 'defaults-only'` for `null` / + `undefined` config. +- "explicitly configured ports keep today's strict behavior unless + `--auto-port` / `"autoPort": true` is passed" → matches the per-port + routing in `resolve-available-ports.js:147-148` (`strict = ! + defaultOriginPorts.has(key)` under `'defaults-only'`). +- "`"autoPort": false` opt-out disables fallback even on the defaults" + → matches `load-config.js:103` (`effectiveAutoPort === false` → + `'off'`). + +The entry was not touched in round 2; it remains accurate. **No revision +needed.** ✅ + +--- + +## Required check 3 — Scope confinement + +`git status --short`: + +``` +M packages/env/CHANGELOG.md +M packages/env/README.md +M packages/env/lib/cli.js +``` + +`git diff --stat`: empty (everything is staged). All three files are inside +`packages/env/`. **No JSDoc files touched** (verified — `parse-config.js`, +`load-config.js`, `post-process-config.js`, `resolve-available-ports.js`, +`commands/start.js` are all clean). **No test files touched** (verified — +`packages/env/lib/test/`, `packages/env/lib/config/test/` clean). **No +snapshot files touched.** ✅ + +The only diff in `lib/cli.js` is the single string literal at line 157 +(the describe string). No code-path change, no signature change, no +yargs option-shape change. ✅ + +--- + +## Required check 4 — Lint and tests + +- `npm run lint:js -- packages/env` from this worktree's repo root: + **PASSES** (exit 0). The `eslint-plugin-react-hooks` issue + code-review-1 mentioned has been resolved at the parent-checkout level, + so the configured lint script now runs cleanly. The doc-writer's docs + edits do not touch any lint-relevant code. +- `npm run test:unit -- packages/env` from the repo root: **FAILS** with + the same Jest Haste-map duplicate-package collision documented in + docs-review-1 (sibling worktrees in the parent checkout supply + duplicate `package.json` for `@wordpress/compose`). **This is a + host-environment limitation, not a regression.** +- I bypassed the collision by running Jest directly from inside this + worktree: + ``` + $ npx jest packages/env --config test/unit/jest.config.js + … + Test Suites: 18 passed, 18 total + Tests: 181 passed, 181 total + Snapshots: 8 passed, 8 total + Time: 2.478 s + ``` + **181 / 181 pass; 8 / 8 snapshots pass.** Matches the code-review-1 + baseline exactly. ✅ + +--- + +## Required check 5 — No new gaps appeared since round 1 + +Beyond the round-1 blocker (now closed) and the round-1 non-blocker findings +(see below), I scanned the round-2 diff for any new contradictions, missing +coverage, or stale references introduced by the doc-writer: + +- **No new prose claims** beyond the help-text describe string. The README + body and CHANGELOG were unchanged from round 1. The describe-string update + is additive; it does not invalidate any claim elsewhere. +- **No new examples introduced.** The README's existing `wp-env start + --auto-port` example and `"autoPort": false` JSON snippet are unchanged. +- **No reference drift** (the help block at `README.md:368-371` is the only + mirror of the cli.js describe, and both were updated in lockstep). +- **No new file modified** beyond `lib/cli.js` (and the README block that + reproduces its output). JSDoc and tests are still untouched. ✅ + +--- + +## Round 1 non-blocker findings — re-confirmed as still non-blockers + +I re-checked each of round 1's non-blocker findings to ensure none escalated: + +1. **README §"Automatic Port Selection" §2 enumerates user-set sources as + `port` / `testsPort` / `WP_ENV_PORT` / `WP_ENV_TESTS_PORT` but does not + mention nested `env.development.port` / `env.tests.port`.** Still true + in round 2; the doc-writer did not expand the enumeration. **Still + acceptable** for a user-facing README. +2. **CHANGELOG bullet is long and semicolon-separated.** Unchanged in + round 2. Still defensible because the feature has three semantic facets. + **Non-blocker.** +3. **`8888` → `8890` example might read as "scanner skips by 2".** + Unchanged in round 2. **Non-blocker.** +4. **Validator at `parse-config.js:493-504` says "must be a boolean" even + though it now accepts `null`.** Unchanged in round 2 (out of docs scope + anyway). The code-review-1 already accepted this as a minor cosmetic + issue. **Non-blocker.** + +None of these escalated to a blocker in round 2. ✅ + +--- + +## Required check 6 — Verify no scope creep into PR-phase obligations + +Round 1 noted the following round-1 conditions that the code-review-1 +deferred to "before PR opens": + +- README updated → Done (round 1, re-confirmed clean in round 2). +- CHANGELOG updated → Done (round 1, re-confirmed clean in round 2). +- `composer test` runs green → Out of docs phase; deferred to PR-opening + step. +- PR body test plan enumerates AC1–AC11 → PR-phase obligation, not docs. +- PR body includes AC9b reproduction recipe → PR-phase obligation, not docs. +- PR body acknowledges the (now-resolved) lint-deps issue → PR-phase + obligation; in round 2 the lint dep is present so this notice may no + longer be needed. +- PR opened against `trunk` from `try/49843-wp-env-default-port-fallback`, + links `#49843`, draft → PR-phase obligation. + +The doc-writer correctly stayed within the docs-phase remit and did not +overreach into PR-body content. ✅ + +--- + +## Verdict + +``` +APPROVED +``` + +The round-1 blocker is closed. The new `--auto-port` describe string in +`packages/env/lib/cli.js:157` is byte-for-byte identical (193 chars +unwrapped) to its mirror in `packages/env/README.md:368-371`'s help block. +The new string is substantively accurate against the implementation: +default ports auto-fall-back without the flag, the flag extends fallback +to user-set ports, and the flag overrides the `.wp-env.json` `autoPort` +field. The README "Automatic Port Selection" prose, the schema-table row, +and the CHANGELOG entry remain consistent with the new help text — no +contradictions surfaced. Scope is confined to the three authorized files; +no JSDoc, no tests, no snapshots touched. Lint exits 0; the JS unit suite +passes 181 / 181 (run via `npx jest` from inside the worktree to bypass +the host-environment Haste-map collision documented in docs-review-1). + +Documentation phase is complete and ready to hand off to the PR-creation +step. The deferred conditions from code-review-1 (composer test, +PR body content) remain pre-PR-open obligations and are out of scope for +the docs phase. diff --git a/packages/env/CHANGELOG.md b/packages/env/CHANGELOG.md index 711daa1573e16f..6a29673fb1aa9c 100644 --- a/packages/env/CHANGELOG.md +++ b/packages/env/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### New Features + +- The default ports `8888` (development) and `8889` (tests) now automatically fall back to the next available port when busy, so `wp-env start` works out of the box on hosts where those ports are taken; explicitly configured ports keep today's strict behavior unless `--auto-port` / `"autoPort": true` is passed, and the new `"autoPort": false` opt-out disables fallback even on the defaults. ([#49843](https://github.com/WordPress/gutenberg/issues/49843), [#74472](https://github.com/WordPress/gutenberg/pull/74472)) + ## 11.5.0 (2026-04-29) ## 11.4.0 (2026-04-15) diff --git a/packages/env/README.md b/packages/env/README.md index ed41743236e958..0f53425efd78eb 100644 --- a/packages/env/README.md +++ b/packages/env/README.md @@ -139,7 +139,7 @@ In this table, by default, you should see two entries: `wordpress` with port 888 ### 2. Check the port number -By default `wp-env` uses port 8888, meaning that the local environment will be available at http://localhost:8888. +By default `wp-env` tries port 8888, meaning that the local environment will be available at http://localhost:8888. If 8888 is busy on your host and you have not configured a port explicitly, `wp-env` automatically falls back to the next available port and prints the resolved port at start time — see [Automatic Port Selection](#automatic-port-selection) for the full contract and how to opt out. You can configure the port that `wp-env` uses so that it doesn't clash with another server by specifying the `WP_ENV_PORT` environment variable when starting `wp-env`: @@ -149,7 +149,7 @@ $ WP_ENV_PORT=3333 wp-env start Running `docker ps` and inspecting the `PORTS` column allows you to determine which port `wp-env` is currently using. -You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence. +You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence. Ports you set explicitly (in `.wp-env.json`, in `.wp-env.override.json`, or via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`) are never silently moved; if you need them to also auto-fall-back when busy, see the `--auto-port` flag in [Automatic Port Selection](#automatic-port-selection). ### 3. Restart `wp-env` with updates @@ -365,8 +365,10 @@ Options: [string] --scripts Execute any configured lifecycle scripts. [boolean] [default: true] - --auto-port Automatically find available ports when configured ports are - busy. [boolean] + --auto-port Also fall back to the next available port when explicitly + configured ports are busy. By default, only the standard ports + 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" + setting. [boolean] ``` ### `wp-env stop` @@ -606,7 +608,7 @@ To enable editor autocomplete and validation, add a `$schema` key: | `"port"` | `integer` | `8888` | The port number to use for the installation. | | `"testsEnvironment"` | `boolean` | `false` | _Deprecated._ Whether to create a separate test environment with its own database and containers. Use `--config` with a separate config file instead. | | `"testsPort"` | `integer` | `8889` | The port number for the test site. | -| `"autoPort"` | `boolean` | `false` | Whether to automatically find available HTTP ports when configured ports are busy. | +| `"autoPort"` | `boolean\|null`| `null` (defaults only) | Tri-state automatic HTTP port selection. When `null` (the default), the default ports `8888`/`8889` automatically fall back to the next available port if busy, but explicitly configured ports stay strict. Set to `true` to also fall back on user-set ports. Set to `false` to opt out entirely, including on the default ports. | | `"config"` | `Object` | See below. | Mapping of wp-config.php constants to their desired values. | | `"mappings"` | `Object` | `"{}"` | Mapping of WordPress directories to local directories to be mounted in the WordPress instance. | | `"mysqlPort"` | `integer` | `null` (randomly assigned) | The MySQL port number to expose. | @@ -619,15 +621,25 @@ _Note: the port number environment variable (`WP_ENV_PORT`) takes precedence ove ### Automatic Port Selection -By default, `wp-env` uses fixed ports (`8888` for development, `8889` for tests). If a port is busy, Docker will report an error at start time. +By default, `wp-env` tries the standard ports (`8888` for development, `8889` for tests). If you have not configured a port explicitly and one of those defaults is busy on the host, `wp-env` scans upward to the next available port (for example: `8888` → `8890` → `8891`, ...) and starts the environment there. The CLI prints a one-line notice through the same spinner used for other start-time messages so you can see which port was actually bound. -To opt in to automatic port selection, pass the `--auto-port` flag: +Ports that you configured yourself — through `port` / `testsPort` in `.wp-env.json`, in `.wp-env.override.json`, via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`, or any combination — are never silently moved. If your configured port is busy, the start fails with the existing port-conflict error so your explicit choice is honored. + +If you want auto-fallback to apply to your configured ports too, pass the `--auto-port` flag (or set `"autoPort": true` in `.wp-env.json`): ```sh wp-env start --auto-port ``` -When `--auto-port` (or `"autoPort": true`) is enabled and a configured port is busy, `wp-env` scans upward from the configured port to find the next available one (for example: `8888`, `8889`, `8890`, ...). Automatic port selection is disabled when `CI` is set. +To opt out of the default-port fallback as well — for example, when you want a hard guarantee that `wp-env` only ever binds `8888`/`8889` — set `"autoPort": false` in `.wp-env.json`: + +```json +{ + "autoPort": false +} +``` + +Automatic port selection is also disabled whenever the `CI` environment variable is set, regardless of the `autoPort` value, so test runs stay deterministic. Several types of strings can be passed into the `core`, `plugins`, `themes`, and `mappings` fields. diff --git a/packages/env/lib/cli.js b/packages/env/lib/cli.js index 9452fce24707c0..e5619861c714bc 100644 --- a/packages/env/lib/cli.js +++ b/packages/env/lib/cli.js @@ -154,7 +154,7 @@ module.exports = function cli() { args.option( 'auto-port', { type: 'boolean', describe: - 'Automatically find available ports when configured ports are busy. Overrides the .wp-env.json "autoPort" setting.', + 'Also fall back to the next available port when explicitly configured ports are busy. By default, only the standard ports 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" setting.', } ); }, withSpinner( env.start ) From 00ef5a1f85ff6b328be67502a7d5c782f0fb708f Mon Sep 17 00:00:00 2001 From: Carlos Bravo <37012961+cbravobernal@users.noreply.github.com> Date: Mon, 11 May 2026 20:00:14 +0200 Subject: [PATCH 6/6] chore: drop Radical Pipelines artifacts before review Removes .claude/rp.md and .pipelines/49843-wp-env-default-port-fallback/. The pipeline conventions and per-phase review artifacts were useful during authoring but should not land on trunk. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/rp.md | 48 -- .../code-review-1.md | 487 ------------------ .../docs-review-1.md | 430 ---------------- .../docs-review-2.md | 302 ----------- .../plan-review-1.md | 155 ------ .../plan-review-2.md | 158 ------ .../plan.md | 348 ------------- .../prompt.md | 80 --- .../spec-review-1.md | 249 --------- .../spec-review-2.md | 183 ------- .../spec.md | 253 --------- 11 files changed, 2693 deletions(-) delete mode 100644 .claude/rp.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/code-review-1.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/docs-review-1.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/docs-review-2.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/plan-review-1.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/plan-review-2.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/plan.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/prompt.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/spec-review-1.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/spec-review-2.md delete mode 100644 .pipelines/49843-wp-env-default-port-fallback/spec.md diff --git a/.claude/rp.md b/.claude/rp.md deleted file mode 100644 index 9351b9a8e0d494..00000000000000 --- a/.claude/rp.md +++ /dev/null @@ -1,48 +0,0 @@ -## Managing tasks - -Tasks are tracked as GitHub Issues on WordPress/gutenberg. -Use `gh issue view `, `gh issue create`, `gh issue list` via Bash. -Link the related issue in the pipeline prompt and PR body. - -## Pipeline slugs - -Format: `-`. -If no related issue exists, drop the prefix and use the kebab phrase alone. -Example: `49843-wp-env-default-port-fallback`. - -## Worktrees - -Use Claude Code's EnterWorktree tool for every pipeline. -The tool creates an isolated git worktree on a fresh branch and auto-cleans on ExitWorktree if no changes landed. -Do not use raw `git worktree`. - -## Branch names - -Format: `try/`. -Created via EnterWorktree at pipeline start. EnterWorktree's default branch name does not match this convention; rename with `git branch -m` immediately after entering the worktree. - -## Pipeline artifact folders - -Path: `.pipelines//`. -Committed inside the pipeline branch so artifacts are inspectable by reviewers and downstream phases. -Maintainers may remove the folder before squash-merging if it should not land on trunk. - -## Spawning teams of agents - -Use Claude Code's Agent tool. One Agent call per role. -Map radical-pipelines roles to subagent_type: -- spec-writer, plan-writer, implementer, doc-writer => general-purpose -- spec-reviewer, plan-reviewer, implementer-reviewer, doc-reviewer => general-purpose with adversarial-review prompt -- exploratory research within a phase => Explore -- architecture planning => Plan -Pass: pipeline slug, artifact folder, exact artifact paths to read/write, role-specific conventions, review iteration N for reviewers. -Launch independent agents in parallel (single message, multiple Agent blocks). - -## Commits - -Conventional Commits. Subject <= 72 chars. -Scope = top-level package or area: `feat(env): ...`, `fix(block-editor): ...`, `docs(env): ...`, `test(env): ...`. -Body only when 'why' is non-obvious. -Always include trailer: -Co-Authored-By: Claude Opus 4.7 (1M context) -Do not amend; create new commits when hooks fail. diff --git a/.pipelines/49843-wp-env-default-port-fallback/code-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/code-review-1.md deleted file mode 100644 index ddb605997d73f7..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/code-review-1.md +++ /dev/null @@ -1,487 +0,0 @@ -# Phase 4 — Code review - -Iteration 1. - -Pipeline: `49843-wp-env-default-port-fallback` -Spec: `spec.md` (round 2 APPROVED). -Plan: `plan.md` (round 2 APPROVED). -Reviewed artifact: 9 staged files, 0 commits. - ---- - -## Method - -I verified the staged diff (`git diff --staged --stat` showed 9 files, -+1016 / −42), read every changed file end-to-end against the spec ACs and -plan steps 1–12, ran the project's unit suite, ran Prettier on the -staged files, and inspected the existing baseline for the lint blocker -the implementer flagged. - -## Diff hygiene check - -`git status --short` reports exactly the 9 files authorized by plan -§2. No unauthorized files (no `block-editor`, no `core-data`, no -`lib/compat/`, no `tools/`): - -``` -M packages/env/lib/commands/start.js -M packages/env/lib/config/load-config.js -M packages/env/lib/config/parse-config.js -M packages/env/lib/config/post-process-config.js -M packages/env/lib/config/test/config-integration.js -M packages/env/lib/config/test/parse-config.js -M packages/env/lib/config/test/post-process-config.js -M packages/env/lib/resolve-available-ports.js -M packages/env/lib/test/resolve-available-ports.js -``` - -`git diff --staged -- packages/env/**/__snapshots__/` is empty. **Zero -snapshot drift**, matching plan §6 R-Snapshots expectation. - -## Test run (mandated by the role) - -``` -$ npm run test:unit -- packages/env -… -Test Suites: 18 passed, 18 total -Tests: 181 passed, 181 total -Snapshots: 8 passed, 8 total -Time: 1.664 s -``` - -Matches the implementer's reported count exactly. No skipped tests. - -## Lint blocker provenance - -`ls /Users/carlos/Developer/wp-plugins/gutenberg/node_modules/eslint-plugin-react-hooks` -returns `No such file or directory` on the parent checkout. The -implementer's claim that the lint failure is pre-existing and unrelated -to this work is **confirmed**. Not a blocker for this review. The -docs-phase or PR description MUST acknowledge it so the maintainer -knows the lint command was not run as configured. - -Prettier was run on the 9 staged files and reports `All matched files -use Prettier code style!`. Standalone ESLint on the staged files via -`eslint --no-config-lookup` is a reasonable substitute — accepted. - ---- - -## AC coverage matrix - -For each AC I cite the test (file + `it` name) and the production code -path it exercises. - -### AC1 — Default development port falls back automatically (upward scan) - -- **Test:** `config-integration.js:236` `with no user autoPort and busy - default port falls back via defaults-only mode (AC1)`. Mocks - `findAvailablePort` to return 8890 for preferred 8888; asserts - `config.env.development.port === 8890` and `WP_HOME === - 'http://localhost:8890'`. -- **Production code path:** `load-config.js:101–106` maps unset - `autoPort` to `autoPortMode='defaults-only'`, `load-config.js:114–116` - creates the resolver, `resolve-available-ports.js:140–149` routes - default-origin HTTP ports as non-strict, `resolve-available-ports.js:75–78` - calls `findAvailablePort`. **Covered.** -- Upward-scan directionality is inherited from `port-utils.js` - (unchanged); no spec violation. - -### AC2 — Default tests port falls back independently (upward scan) - -- **Test:** `resolve-available-ports.js:165` `under autoPortMode=defaults-only - uses strict mode for non-default-origin ports and non-strict for default-origin ports` - asserts the dev-default→non-strict / tests-user-set→strict matrix - symmetrically. The post-process-config sibling test (line ~351) - `threads autoPortMode and defaultOriginPorts to resolveConfigPorts` - covers both http ports as non-strict in the same call. **Covered.** - -### AC3 — Explicitly configured port stays strict by default - -- **Production path:** `parse-config.js:213–273` (the new - `computeDefaultOriginPorts` + `layerSetsDevelopmentPort`/ - `layerSetsTestsPort` helpers) excludes a user-set key from - `__defaultOriginPorts`. `resolve-available-ports.js:147–149` then - computes `strict = ! defaultOriginPorts.has(key)` → user-set ports - go strict. -- **Tests:** Four `parse-config.js` provenance tests cover local - config, override config, `WP_ENV_PORT`, `WP_ENV_TESTS_PORT` - (lines ~632, ~648, ~666, ~677). `post-process-config.js:425` - `with autoPortMode=defaults-only routes user-set port to strict and - default-origin port to non-strict` and - `resolve-available-ports.js:165` cover the routing side. **Covered.** - -### AC4 — `--auto-port` / `"autoPort": true` still falls back on explicit ports - -- **Tests:** `config-integration.js:341` `with CLI autoPort=true and - user config autoPort=false has CLI win (AC4 precedence)`. The new - F3 integration test at `config-integration.js:367` `with CLI - autoPort=true and explicit user port falls back when port is busy - (AC4 behavior-level)` asserts the moved port flows all the way - through to `WP_HOME`. Sibling unit-level tests at - `resolve-available-ports.js:226` and `post-process-config.js:524` - assert `autoPortMode='all'` routes every port non-strict. -- **Production path:** `load-config.js:101` `effectiveAutoPort === - true` → `'all'`. `resolve-available-ports.js:145` `autoPortMode === - 'all'` → `strict = false` for every port (skip rule does not - trigger because the rule requires `defaults-only`). **Covered.** - -### AC5 — `"autoPort": false` opts out of default-port fallback too - -- **Test:** `config-integration.js:265` `with autoPort:false in user - config skips fallback even on default ports (AC5)`. Asserts - `findAvailablePort` was never called. -- **Production path:** `load-config.js:103` `effectiveAutoPort === - false` → `'off'`; `load-config.js:114` resolver not created. - **Covered.** The test name carries `AC5` so a future refactor that - collapses the false branch would fail this test by name. - -### AC6 — `CI=1` continues to disable all auto-fallback - -- **Tests:** `config-integration.js:288` `with CI=1 disables fallback - regardless of autoPort:true in user config (AC6 + AC8 regression - detector)` and `config-integration.js:319` `with CI=1 disables - fallback even when autoPort is unset (AC6)`. -- **Production path:** `load-config.js:109–112` — the - `process.env.CI` guard overwrites `autoPortMode` to `'off'`. CI - cleanup is correctly handled by the new `originalCI` save/restore - in `beforeEach`/`afterEach`. **Covered.** - -### AC7 — Informational message contract (observable) - -- **Tests (five):** `resolve-available-ports.js:309` `emits spinner.info - exactly once when fallback occurs and re-arms the spinner`; - line 329 `does NOT emit spinner.info when the preferred port is - available`; line 340 `does NOT emit spinner.info on the strict - failure path`; line 352 `does not write to console or process.stdout - when fallback occurs (regression guard)`; line 386 `suppresses the - notice silently when no spinner is provided (test-path safety)`. -- **Production path:** `resolve-available-ports.js:80–90` — - `if ( spinner && resolvedPort !== preferredPort )` guard, message, - then `spinner.start()` re-arm. The order assertion - (`info.mock.invocationCallOrder[0] < start.mock.invocationCallOrder[0]`) - is well-formed and exercises the re-arm sequence the plan requires. - **Covered.** The "no console output" regression detector exactly - matches the spec's "introducing a separate output path would be a - detectable regression" clause. - -### AC8 — CI guard regression is detectable - -- **Test:** `config-integration.js:288` carries the explicit name - `(AC6 + AC8 regression detector)` and the comment "Removing the - `if ( process.env.CI )` guard in load-config.js would call - findAvailablePort and fail this expectation." Verified by reading - the test body. **Covered.** - -### AC9a — Resolved port flows downstream into merged config - -- **Test:** `post-process-config.js:351` `threads autoPortMode and - defaultOriginPorts to resolveConfigPorts` asserts - `processed.env.development.config.WP_HOME === 'http://localhost:8890'` - and the same for `WP_SITEURL`. The integration test - `config-integration.js:236` also asserts the same end-to-end through - `loadConfig`. -- **Production path:** `post-process-config.js:37–40` calls - `resolveConfigPorts` first; line 42 then calls - `appendPortToWPConfigs`. Order preserved. **Covered.** - -### AC9b — Live reachability (manual) - -- Out of scope for the automated suite per spec §5 / plan §3 trailer. - Verification deferred to the PR test plan. **Acknowledged; not a - code-review blocker.** - -### AC9c — Other wp-env commands see the resolved fallback port - -- No new automated test (plan §3 trailer documents this — the - guarantee is inherited from the unchanged cached-compose contract). -- Plan §1 Step 1 traces `start.js → loadConfig → postProcessConfig → - build-docker-compose-config.js` to confirm the resolved port is - what `runtime/docker/build-docker-compose-config.js:173,267` writes - into the cached compose file, which `stop.js`/`destroy.js`/etc. - consume by container name. I spot-checked - `packages/env/lib/runtime/docker/build-docker-compose-config.js` — - not touched in this diff, so the contract is preserved. **Covered - by inheritance; verification deferred to manual PR test plan steps.** - -### AC10 — Existing tests stay green; snapshots intentional - -- 181 / 181 unit tests pass. -- Zero snapshot drift in `__snapshots__/` directories. -- The non-enumerable contract test at `parse-config.js:715` - (`__defaultOriginPorts is invisible to mergeConfigs and toEqual`) - asserts `JSON.parse(JSON.stringify(parsed)).__defaultOriginPorts` - is `undefined` AND `expect(parsed).toEqual(DEFAULT_CONFIG)` still - passes AND `Object.keys(parsed)` does not contain the property. - This is a strong regression detector for plan §6 R-NonEnumerable. -- The back-compat test `post-process-config.js:583` `defaults to - autoPortMode=off and routes ports strict (back-compat for callers - that do not pass options)` guarantees callers that bypass the new - options keep working. **Covered.** - -### AC11 — `autoPort` tri-state survives end-to-end - -- **Test:** `parse-config.js:196` (renamed) `should accept autoPort - as a tri-state (null default, true, false)` asserts three distinct - values: default `null`, explicit `true`, explicit `false`. The - test ends with `expect( parsedFalse.autoPort ).not.toBeNull()` - which is the spec's "observably distinct" requirement. -- The default-config flip at `parse-config.js:93` - (`autoPort: null`) and the validator change at line 493–504 (`null` - passes the boolean check) together guarantee the tri-state survives - parse → merge. `load-config.js:101–107` consumes the tri-state. - **Covered.** - ---- - -## Plan adherence - -| Step | Status | Notes | -|---|---|---| -| 1 — default flip + fixture | Done | `parse-config.js:93` is `null`; test fixture line 24 updated to `null`. JSDoc updated. | -| 2 — `load-config.js` tri-state | Done | Block at `load-config.js:96–122` matches plan exactly (CLI beats config; CI forces `'off'`; resolver created only when `resolvePorts && mode !== 'off'`). JSDoc updated. | -| 3 — `__defaultOriginPorts` provenance | Done | Helper functions land at `parse-config.js:194–273`. Non-enumerable property attached at line 175. The four user-source layers are inspected as specified. | -| 4 — `postProcessConfig` threading | Done | Signature change + JSDoc at `post-process-config.js:24–35`. Defaults preserve back-compat. | -| 5 — per-port routing in `resolveConfigPorts` | Done | Skip rule at `resolve-available-ports.js:128–135`; strict decision at lines 136–151. Matches plan's three-mode matrix. | -| 6 — moved-port notice in `createPortResolver` | Done | `resolve-available-ports.js:80–90`. Guarded by `spinner && resolvedPort !== preferredPort`; `spinner.start()` re-arms. | -| 7 — `start.js` JSDoc | Done | One-line JSDoc tri-state description at `start.js:32`. No public signature change. | -| 8 — README | **Deferred to phase 5** | Acceptable per role brief. | -| 9 — CHANGELOG | **Deferred to phase 5** | Acceptable per role brief. | -| 10 — tests (tri-state + provenance) | Done | All planned test rows in §3 are present; the `'off'`-mode test for phpmyadminPort was correctly adjusted (see deviation note below). | -| 11 — tests (moved-port notice) | Done | Five spinner tests land at `resolve-available-ports.js:309–411`. | -| 12 — verification sweep | Partial | Snapshot/JSDoc/fixture sweep done. **`composer test` from plan §4 verification gate 4 was not run** — see PHP test deferral section below. | - -### Deviations from plan - -1. **Plan §3 row for `'off'`-mode phpmyadminPort test (line 259) says - "still resolves phpmyadminPort non-strictly".** The implementation - in plan Step 5 reads "If `autoPortMode === 'off'` → `strict = true`", - so phpmyadminPort under `'off'` is actually resolved **strictly**. - The implementer correctly aligned the test - (`resolve-available-ports.js:262` asserts `isPortAvailable.toHaveBeenCalledWith(8080)` - and `findAvailablePort.not.toHaveBeenCalled()`). This is a plan - text error, not a code error. The test name was also adjusted to - "still resolves phpmyadminPort **strictly**" which is consistent - with the implementation. **Deviation accepted; the test correctly - guards Step 5's actual strict-decision rule.** - -2. **Validator at `parse-config.js:493–504` allows `null` to pass - silently** but still emits "must be a boolean" if a non-null, - non-boolean is provided. The user-visible error message is - slightly inaccurate (it implies only boolean is allowed, but null - is also accepted). However, `null` is not a value a contributor - would ever write in `.wp-env.json` (it would parse as `null` only - if they explicitly typed it, which would behave the same as - omitting the key). **Accepted as written.** Optional tightening - for future: update the error message to "must be a boolean or - null" — non-blocking nit. - -3. The implementer reported running `eslint --no-config-lookup` and - `prettier --check` instead of `npm run lint:js` because the - parent checkout is missing `eslint-plugin-react-hooks`. I - confirmed the missing dep is pre-existing. **Accepted as a valid - substitute for this review iteration.** Docs phase or PR - description must acknowledge. - -4. The implementer reported skipping `composer test` because wp-env - is not running. See PHP test deferral section. - ---- - -## Test correctness audit - -I read every new test and checked for the four common cheats. Findings: - -- **No empty assertions.** Every `it` block ends in an `expect(…)` - call against a meaningful value. -- **No mocks swallowing the call.** Where `jest.fn()` mocks are used - (`portResolver.resolve`, `findAvailablePort`, `isPortAvailable`), - the tests assert against `.mock.calls` or against the returned - config object, not against the input. -- **No tautological assertions** (asserting on inputs). The - `__defaultOriginPorts` provenance tests all assert against - `parsed.__defaultOriginPorts.has(…)` — i.e. against the result of - `parseConfig`, not against the mocks. -- **AC4 / AC5 / AC8 integration tests correctly assert observable - behavior** (`findAvailablePort.toHaveBeenCalled()` / - `not.toHaveBeenCalled()` plus the resolved port in the returned - config), not just internal state. -- The non-enumerable contract test (`parse-config.js:715`) is - particularly well-constructed: it asserts the property is - invisible to JSON serialization, to `Object.keys`, and to Jest's - `toEqual` deep-equal in a single test. A future refactor that - flips the property to enumerable fails this test. -- The "moved-port notice" tests correctly assert call order - (`info.mock.invocationCallOrder[0] < start.mock.invocationCallOrder[0]`) - — this is the right way to assert ordering between two mock fns. -- The "no console output" regression detector spies on - `console.log`, `console.info`, `console.warn`, and - `process.stdout.write`, and restores them in `finally`. Correctly - scoped and cleaned up. - -**No test cheats detected.** - ---- - -## Behavior verification (production code path) - -### `parse-config.js` `__defaultOriginPorts` provenance - -- Line 167–175 captures `mergeConfigs` result in `merged`, computes - `defaultOriginPorts`, attaches via `Object.defineProperty(merged, - '__defaultOriginPorts', { value: …, enumerable: false, writable: - false, configurable: false })`. **All three flags are tightened - beyond the default;** the property is also non-writable and - non-configurable, making the contract harder to accidentally - break. Good defensive choice. -- `merge-configs.js` `for (const option in config)` is unchanged. - `for…in` excludes non-enumerable own properties, so the provenance - Set never leaks into the merge. The dedicated test at - `parse-config.js:715` (`JSON round-trip drops the property; toEqual - still passes`) is the regression detector. -- The helpers `layerSetsDevelopmentPort` / `layerSetsTestsPort` - correctly inspect both root-level (`port` / `testsPort`) and - env-specific (`env.development.port` / `env.tests.port`) paths, - plus the env-var-derived layer. **Matches plan §2 Step 3 exactly.** -- One reviewer concern: the helpers inspect `layer.env?.development?.port` - with `?? undefined` semantics; an explicit `port: 0` would count - as "user-set". That is the right behavior (zero is a port value - the user typed). No issue. - -### `load-config.js` tri-state resolution - -- `effectiveAutoPort = autoPort !== undefined ? autoPort : config.autoPort` - — CLI beats config. CLI `false` short-circuits to `'off'`; CLI - `true` short-circuits to `'all'`. CLI `undefined` defers to - `config.autoPort`. -- `config.autoPort` is `true`/`false`/`null` (after Step 1's default - flip; `null` is the "unset" sentinel). When `effectiveAutoPort === - true` → `'all'`; `=== false` → `'off'`; **else** (which covers - `null`, `undefined`, and any other unexpected value) → `'defaults-only'`. - This `else` branch correctly handles the case where `config.autoPort` - is undefined (defensive), `null`, or genuinely unset. -- CI guard at line 109 is reached **after** the tri-state mapping - and unconditionally forces `'off'`. Test - `config-integration.js:288` (CI=1 + `autoPort: true` → no - fallback) proves the guard is in front of the resolver creation. - -### `resolve-available-ports.js` per-port routing - -- Skip rule at line 128–135: `if ( autoPortMode === 'defaults-only' - && property !== 'port' ) continue;` — exactly preserves today's - phpmyadminPort behavior under the new mode (B3 fix). -- Strict decision at line 136–151: matches plan's matrix - (`'off'`→true, `'all'`→false, `'defaults-only'` HTTP → - `! defaultOriginPorts.has(key)`). -- `portResolver.resolve(preferredPort, configPath, strict)` — third - argument was already supported by `createPortResolver`'s - `resolve` method (line 50 in the unchanged baseline section). - -### `createPortResolver` info notice - -- Guard at line 85: `if ( spinner && resolvedPort !== preferredPort )`. - Fires **only when both are true**. When `spinner` is undefined → - silent. When `resolvedPort === preferredPort` → silent. The two - tests at `resolve-available-ports.js:329` (no move) and `:386` (no - spinner) confirm both branches. -- Notice goes through `spinner.info(…)` followed by `spinner.start()` - to re-arm. Matches the precedent at `commands/start.js:98–101` and - `:169–193` cited in plan §F4. -- Strict branch (lines 56–72) **does not** reach the notice code — - the throw happens earlier. The test at `resolve-available-ports.js:340` - confirms `spinner.info` is not called on strict failure. - -### `commands/start.js` JSDoc - -- Line 32: `@param {boolean|undefined} options.autoPort Tri-state: - …` — describes all three states. **No public signature change.** - ---- - -## PHP test deferral decision - -- `composer test` was not run because wp-env is not running locally - in this worktree. The plan §4 verification gates 2 and 4 both - mandate `composer test`, and spec **R17 / R-PHPRegress** explicitly - ties this to PR #74472's history of breaking PHP tests with the - always-on default-fallback approach. -- **Decision: accepted as a deferred checkpoint, NOT a blocker for - this code review.** Rationale: - - This change is JS-only inside `packages/env/`. No PHP file - changed in the staged diff. - - The PHP suite depends on `wp-env` running, which is a - side-effectful operation the implementer is correct to avoid - in the middle of an implementation cycle. - - The 181/181 JS-test green plus zero snapshot drift makes a - PHP regression unlikely; if one surfaces, it surfaces at the - checkpoint without harm. -- **Explicit checkpoint:** `composer test` MUST run green **after** - the docs phase commits and **before** the PR is opened (i.e. as - part of the pipeline's "ready for review" gate, not before this - code-review verdict). The docs-phase reviewer or the PR-opening - step inherits responsibility for confirming the gate. - ---- - -## Open issues raised by the implementer - -1. **parse-config validator allows `null` but error message says - "must be a boolean".** Minor cosmetic. **Accepted as written.** - Optional polish: update the message in a follow-up; non-blocking - here. -2. **AC5 / AC6 integration test phrasing carries AC tags inline.** - This is helpful for future maintenance and matches plan §5's - "named regression detector" intent. **Accepted.** -3. **PHP gate deferral.** **Accepted as a documented checkpoint - before PR open.** See section above. -4. **Lint blocker (`eslint-plugin-react-hooks` missing).** Confirmed - pre-existing on the parent checkout. **Accepted; not a blocker.** - Prettier on staged files passes; eslint via `--no-config-lookup` - is an acceptable substitute. Docs phase or PR description must - note that `npm run lint:js` is currently broken in the parent - tree. - ---- - -## Verdict - -``` -APPROVED -``` - -The 9 staged files faithfully implement plan steps 1–7 and 10–12, and -the test suite covers every code-eligible AC (AC1, AC2, AC3, AC4, AC5, -AC6, AC7, AC8, AC9a, AC10, AC11). AC9b and AC9c are correctly deferred -to the manual PR test plan per spec §5. All 181 unit tests pass; zero -snapshot drift; no unauthorized files touched; the non-enumerable -contract for `__defaultOriginPorts` is independently regression-guarded. -The one plan-vs-implementation deviation (Plan §3 row 259 wording on -`'off'`-mode phpmyadminPort) is a plan documentation error that the -implementer correctly resolved in favor of the implementation logic -defined elsewhere in the plan. - -### Conditions that MUST hold before the PR is opened (not blocking this iteration) - -1. **README updated** per plan Step 8 — describes the new default - behavior, the `"autoPort": false` opt-out, and updates the config - table row for `autoPort` (default `null`, tri-state description). -2. **CHANGELOG updated** per plan Step 9 — `Unreleased` entry under - `### New Features` or `### Enhancements`, referencing `#49843`. -3. **`composer test` runs green** from repo root with wp-env running, - per spec R17 / plan §4 verification gate 4. Any failure escalates - to spec/plan, not silently worked around. -4. **PR body test plan enumerates AC1 through AC11** (including - AC9a/AC9b/AC9c) per spec §9 + R16. -5. **PR body includes the AC9b manual reproduction recipe** from - plan §3 (bind 8888 with `python3 -m http.server`, run wp-env - start, browse to the printed URL, verify, then stop and restart). -6. **PR body acknowledges the pre-existing `npm run lint:js` - breakage** (missing `eslint-plugin-react-hooks` in the parent - checkout) so the maintainer knows lint was not run as configured. - This is a host-project issue, not a regression introduced by this - PR. -7. **PR is opened against `WordPress/gutenberg` `trunk` from branch - `try/49843-wp-env-default-port-fallback`**, links `#49843`, and - is filed as a draft per spec §9. - -All ACs in scope for the automated suite are satisfied. Implementation -is ready for the documentation phase. diff --git a/.pipelines/49843-wp-env-default-port-fallback/docs-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/docs-review-1.md deleted file mode 100644 index 6c89a8fe521593..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/docs-review-1.md +++ /dev/null @@ -1,430 +0,0 @@ -# Phase 5 — Documentation review - -Iteration 1. - -Pipeline: `49843-wp-env-default-port-fallback` -Spec: `spec.md` (round 2 APPROVED). -Plan: `plan.md` (round 2 APPROVED). -Code-review: `code-review-1.md` (APPROVED, with conditions deferred to docs/PR phases). -Reviewed artifact: working-tree changes to `packages/env/README.md` and `packages/env/CHANGELOG.md` (no doc-writer commit yet). - ---- - -## Method - -I read the prompt, spec, plan, and code-review-1 end-to-end. I read the -implementation diff (`git diff HEAD~1 HEAD -- packages/env/`) and -cross-checked the doc-writer's working-tree diff (`git diff -- packages/env/README.md -packages/env/CHANGELOG.md`) against the implementation. I read the -relevant source files (`load-config.js`, `parse-config.js`, -`post-process-config.js`, `resolve-available-ports.js`, `commands/start.js`, -`cli.js`) to verify every doc claim. I ran `npm run lint:js -- packages/env` -from the repo root. I attempted `npm run test:unit -- packages/env`; that -command failed due to a sibling-worktree Haste-map collision unrelated to -this change (see §Lint and tests below). - -## Diff hygiene - -`git status --short` reports exactly two modified files: - -``` -M packages/env/CHANGELOG.md -M packages/env/README.md -``` - -Both are inside `packages/env/`. **No scope creep**. ✅ - ---- - -## Required check 1 — README accuracy - -I cross-checked every claim in the README diff against the implementation -on HEAD. - -### Tri-state semantics - -README config-table row (line 609) for `"autoPort"` reads: - -> Tri-state automatic HTTP port selection. When `null` (the default), the -> default ports `8888`/`8889` automatically fall back to the next available -> port if busy, but explicitly configured ports stay strict. Set to `true` -> to also fall back on user-set ports. Set to `false` to opt out entirely, -> including on the default ports. - -Source verification: -- `parse-config.js:93` — `autoPort: null` is the default in - `DEFAULT_ENVIRONMENT_CONFIG`. ✅ -- `parse-config.js:494-501` — validator allows `null`, `true`, `false`. ✅ -- `load-config.js:96-112` — tri-state mapping: `true → 'all'`, - `false → 'off'`, anything else (including `null`/`undefined`) → - `'defaults-only'`. ✅ -- `resolve-available-ports.js:128-149` — under `'defaults-only'`, - `port` (HTTP) routes per provenance; `phpmyadminPort` is skipped; - under `'all'`, every port is non-strict; under `'off'`, every port - is strict. ✅ - -The README claim that `false` "opts out entirely, including on the -default ports" is accurate. - -### CI guard - -README "Automatic Port Selection" final paragraph: - -> Automatic port selection is also disabled whenever the `CI` environment -> variable is set, regardless of the `autoPort` value, so test runs stay -> deterministic. - -Source verification: `load-config.js:109-112` — `if ( process.env.CI ) { autoPortMode = 'off'; }` -runs **after** the tri-state mapping and unconditionally forces `'off'`, -which then prevents the resolver from being created at line 114. The -"regardless of the `autoPort` value" clause is correct: `autoPortMode = 'off'` -is set after the user-state-derived mapping. ✅ - -### "User-set ports stay strict" claim - -README §2 paragraph and "Automatic Port Selection" §2: - -> Ports you set explicitly (in `.wp-env.json`, in `.wp-env.override.json`, -> or via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`) are never silently moved. - -Source verification: -- `parse-config.js:213-273` — `computeDefaultOriginPorts` / - `layerSetsDevelopmentPort` / `layerSetsTestsPort` inspect - `localConfig`, `overrideConfig`, and `environmentVarOverrides` for - `port`, `testsPort`, `env.development.port`, `env.tests.port`. ✅ -- `resolve-available-ports.js:136-149` — under `'defaults-only'` mode, - `strict = ! defaultOriginPorts.has( key )`. ✅ - -The list `(port / testsPort / WP_ENV_PORT / WP_ENV_TESTS_PORT)` exactly -matches the env-var enumeration the plan resolved in OQ4 against -`get-config-from-environment-vars.js:36-72`. ✅ - -**Minor finding (non-blocker):** The README does not mention the -nested form `env.development.port` / `env.tests.port` even though the -implementation honors it (verified at `parse-config.js:243` and `:266`). -A contributor who pins ports per-environment via the `env` block has the -same protection; the README's enumeration is accurate but -non-exhaustive. Acceptable as-is for a user-facing doc. - -### Informational notice description - -README "Automatic Port Selection" §1: - -> The CLI prints a one-line notice through the same spinner used for -> other start-time messages so you can see which port was actually -> bound. - -Source verification: `resolve-available-ports.js:80-90` — -`if ( spinner && resolvedPort !== preferredPort ) { spinner.info(...); spinner.start(); }`. -The notice is gated on (a) a spinner being present and (b) an actual -move. It uses the same `spinner` instance the resolver was constructed -with (passed in by `load-config.js:114` from `loadConfig`'s -`{ spinner }` option, originally from `cli.js`'s `withSpinner`). ✅ - -### Example `.wp-env.json` block - -```json -{ - "autoPort": false -} -``` - -Validator at `parse-config.js:494-503` accepts `boolean` and `null` for -root-level `autoPort`. `false` is valid. ✅ - -### README §2 ("Check the port number") paragraph - -> By default `wp-env` tries port 8888, meaning that the local -> environment will be available at http://localhost:8888. If 8888 is -> busy on your host and you have not configured a port explicitly, -> `wp-env` automatically falls back to the next available port and -> prints the resolved port at start time … - -Accurate. The "tries" wording (vs. the previous "uses") correctly -softens the previous fixed-port claim now that fallback is the default. -Cross-references to "Automatic Port Selection" point at the right -anchor. - ---- - -## Required check 2 — CHANGELOG entry - -CHANGELOG diff: - -``` -## Unreleased - -### New Features - -- The default ports `8888` (development) and `8889` (tests) now automatically … -``` - -Verification against the file's existing conventions: - -- **Placement under `## Unreleased`.** ✅ The entry lands at lines 5-7 - immediately after the `## Unreleased` heading on line 3. -- **Heading style.** Surrounding entries use `### New Features`, - `### Enhancements`, `### Bug Fixes`, `### Breaking Changes`, - `### Deprecation`, `### Internal`. The chosen `### New Features` - matches the existing entry on line 31 ("Added `--auto-port` flag …") - which describes a sibling feature, so it is the natural choice. ✅ -- **Tone.** The entry reads as a concise user-visible feature - description with the opt-out documented inline. Consistent with - surrounding `### New Features` bullets (e.g. lines 33, 43-47). ✅ -- **Link format.** `([#49843](https://github.com/WordPress/gutenberg/issues/49843), [#74472](https://github.com/WordPress/gutenberg/pull/74472))`. - The format `([#NNN](URL))` matches existing entries (e.g. line 11: - `([#20569](https://github.com/WordPress/gutenberg/issues/20569))`, - line 33's `--auto-port` entry similarly references the PR). ✅ -- **Length.** The bullet is one long sentence (~340 characters). - Surrounding bullets in the file vary widely; e.g. line 11 is ~280 - chars, line 33 is similar to this one in length. Acceptable. The - semicolon-separated multi-clause structure is heavy for a CHANGELOG - bullet but defensible because the feature has three distinct facets - (default behavior, opt-in semantics for explicit ports, opt-out - via `false`). **Non-blocker.** - -**Minor finding (non-blocker):** The link includes the **issue** for -`#49843` (correct; that's the feature request) and the **PR** for -`#74472` (correct; that's the prior `--auto-port` PR). Both targets -exist. This dual-link pattern is unusual for the CHANGELOG (most -entries link a single `#NNN`) but it's coherent with the spec, which -explicitly threads the new behavior through PR #74472's machinery. - ---- - -## Required check 3 — JSDoc cross-check - -I read the JSDoc in every touched source file to verify the tri-state -is described consistently. - -| File | Symbol | JSDoc state | Verdict | -|---|---|---|---| -| `commands/start.js` | `start` `@param options.autoPort` (line 32) | `{boolean\|undefined}` … "Tri-state: `true` enables … fallback for every port …; `false` disables … even on default ports; `undefined` (the typical case — flag not supplied) defers to `.wp-env.json`'s `autoPort` field, where unset/`null` means 'auto-fallback only on default ports'." | ✅ Tri-state described. | -| `config/load-config.js` | `loadConfig` `@param options.autoPort` (line 44) | `{boolean\|undefined}` … "Tri-state CLI override … `true` enables fallback for all ports, `false` disables fallback even on default ports, `undefined` defers to `config.autoPort` (which itself is tri-state — `null`/`undefined` means 'fallback only on default ports')." | ✅ Tri-state described. | -| `config/parse-config.js` | `WPRootConfigOptions.autoPort` (line 38) | `{boolean\|null}` … "Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports)." | ✅ Tri-state described. | -| `config/post-process-config.js` | `postProcessConfig` (lines 18-22) | New `@param options.autoPortMode` describes `'off'`/`'all'`/`'defaults-only'` semantics; `@param options.defaultOriginPorts` describes the Set semantics. | ✅ Both new options documented. | -| `resolve-available-ports.js` | `resolveConfigPorts` (lines 108-115) | Same two new `@param`s with full mode descriptions including the phpmyadminPort skip rule. | ✅ Both new options documented. | -| `resolve-available-ports.js` | `createPortResolver` `resolve` method (lines 42-49) | Adds `@param strict` "When true, fail if the port is busy instead of finding an alternative." | ✅ Already correct. | -| `resolve-available-ports.js` | `createPortResolver` itself (line 35) | "Creates a port resolver that tracks used ports." Brief but accurate. The new "moved port" notice is documented inline at the call site (lines 80-86 inline comment) rather than in the function-level JSDoc. **Acceptable.** | - -**No stale JSDoc found.** ✅ - ---- - -## Required check 4 — Doc-writer's flagged Open Issue 2 (`lib/cli.js` describe string) - -The role brief flags this for adversarial assessment. My verdict: -**leaving the describe string untouched is NOT acceptable; it must be -updated for approval.** - -### Evidence - -`lib/cli.js:154-158` defines the `--auto-port` flag with this `describe`: - -> 'Automatically find available ports when configured ports are busy. -> Overrides the .wp-env.json "autoPort" setting.' - -Two reasons this string is now actively misleading: - -1. **It implies `--auto-port` is the only path to auto-fallback.** - Post-this-PR, default ports auto-fall-back without the flag. A - contributor who reads the CLI help and concludes "ports only - auto-move when I pass `--auto-port`" will be wrong, and on a busy - host they will be confused when the start succeeds on a different - port without their having passed the flag. -2. **It understates what the flag now buys.** The flag now means "also - auto-fall-back on user-set ports", not the previous "auto-fall-back - on busy ports at all". A user reading this in `wp-env start --help` - has no way to discover the new explicit-port semantic. - -**Surface where this string is rendered:** -- `wp-env start --help` (yargs auto-generates from `describe`). -- `packages/env/README.md:368-369` reproduces the help output verbatim - in the `### wp-env start` section. So the README *itself* contains - the stale string in a code block, even though the doc-writer - correctly updated the prose elsewhere. This contradicts the prose at - README lines 605-630 that the doc-writer rewrote. **The README is - internally inconsistent until cli.js is updated** (or until the - rendered help block in README is hand-edited, which is brittle and - risks drifting from the actual CLI output). - -### On the role-brief's "do not change source code" caveat - -The brief notes: "the role brief said 'Do NOT change behavior, source -code under `lib/` (other than JSDoc cleanup if strictly needed)'. A -user-facing string is not strictly source behavior; verdict is yours." - -A `yargs` `describe` string is a documentation surface masquerading -as source code. It is rendered to the user without any code path -executing it as logic. Treating it as documentation rather than -behavior is the correct read. The plan §2 Step 7 explicitly listed -`commands/start.js` JSDoc updates as in-scope for the implementation -phase; an analogous CLI describe-string update is materially the same -kind of doc work and falls within the docs-phase remit. - -**Decision: this is a blocker for approval.** The CLI describe string -must be rewritten to reflect the new tri-state contract before the PR -opens. Recommended substance (doc-writer chooses exact wording): - -> "Force automatic port selection for every port (including ones you -> explicitly set in .wp-env.json). By default, only the standard -> ports 8888/8889 fall back automatically; this flag extends that to -> user-configured ports. Equivalent to setting `autoPort: true`." - -### Knock-on - -If the cli.js describe string is updated, the README `wp-env start --help` -block at lines 368-369 must be regenerated to match (or hand-edited -to match the new describe text). The doc-writer should do both in -the same change. - ---- - -## Required check 5 — Coverage of spec acceptance criteria with user-facing surface - -For each AC with a user-facing surface, I checked whether the README -covers it. - -| AC | User-facing surface? | README coverage | -|---|---|---| -| AC1 — default dev port falls back | Yes | ✅ "Automatic Port Selection" §1; §2 "Check the port number" updated. | -| AC2 — default tests port falls back | Yes | ✅ Same section. The 8889 case is implicit ("default ports `8888`/`8889`"); reasonable for a user-facing README. | -| AC3 — explicit port stays strict | Yes | ✅ "Automatic Port Selection" §2 ("Ports you set explicitly … are never silently moved"). | -| AC4 — `--auto-port` / `autoPort: true` falls back on explicit ports | Yes | ✅ "Automatic Port Selection" §3 with example. | -| AC5 — `autoPort: false` opt-out | Yes | ✅ "Automatic Port Selection" §4 with JSON example. | -| AC6 — `CI=1` disables fallback | Yes | ✅ Final paragraph of "Automatic Port Selection". | -| AC7 — informational message contract | Partial | ✅ The README mentions "prints a one-line notice through the same spinner". Adequate for a user doc. | -| AC8 — CI guard regression detector | No (test-only) | n/a | -| AC9a — resolved port flows downstream | No (internal) | n/a | -| AC9b — live reachability | PR test plan, not README | n/a (deferred to PR body per spec §5). | -| AC9c — other commands see fallback port | Implicit | ✅ Inherited from cached compose; not a separate doc claim to make. | -| AC10 — existing tests stay green | No (test-only) | n/a | -| AC11 — tri-state survives end-to-end | No (test-only / typedef) | ✅ Surface is the `autoPort` row in the schema table; covered. | - -**Coverage finding:** the README does NOT mention the upward-scan -directionality explicitly in the §2 paragraph ("Check the port number") -even though spec R1/R2 require upward scan and the source enforces it. -The "Automatic Port Selection" §1 does say "scans upward to the next -available port (for example: `8888` → `8890` → `8891`, ...)". Adequate. -✅ - -**Coverage finding:** the README also does not mention the "`8888` → -**`8890`** → `8891`" jump-by-2 pattern's reason (both 8888 and 8889 are -checked-or-busy; the example skips 8889 because it's the default tests -port). Could mislead a reader into thinking the scanner goes by 2s. -**Non-blocker** but a nicety. - ---- - -## Required check 6 — Tone and style - -I compared the new README prose against the surrounding sections. - -- "Check the port number" §2 retains its existing imperative voice - ("By default …", "You can configure …"). The added clause about - fallback uses a parallel construction. ✅ -- "Automatic Port Selection" §§1-4 use the same paragraph cadence and - code-block style (sh fence for CLI, json fence for config) as the - surrounding sections. ✅ -- The em-dash and en-dash usage matches surrounding prose (e.g. the - hyphenated "auto-fall-back" mirrors the spec's terminology and is - used consistently). ✅ -- The new bullet in CHANGELOG is one long sentence with semicolons. - Slightly heavier than the surrounding `### New Features` entries - (e.g. line 33's single-sentence simpler bullet) but defensible - because three distinct semantic facets are bundled. **Non-blocker.** - -**No jarring deviations.** - ---- - -## Required check 7 — Lint and tests - -- `npm run lint:js -- packages/env` from the repo root: **PASSES** - (exit 0). Note: this contradicts the code-review-1 finding that - `eslint-plugin-react-hooks` was missing on the parent checkout; the - dep is now present (likely installed since the code-review-1 ran). - This is not a docs-phase concern; the docs changes do not touch - any lint-relevant code. -- `npm run test:unit -- packages/env` from the repo root: **FAILS** with - a Jest Haste-map duplicate-package collision because sibling - worktrees in the parent checkout (`/Users/carlos/Developer/wp-plugins/gutenberg/.pi/worktrees/77766-popover-bind/packages/compose/package.json`) - collide with this worktree's copy. **This is a host-environment issue - unrelated to the docs changes** (no test sources are touched in this - iteration's diff). The code-review-1 already confirmed 181/181 tests - pass in a clean run; running tests from this worktree's perspective - with the sibling worktree present is not feasible without disturbing - unrelated work. **Accepted as a documented host-environment - limitation, not a regression.** The doc-writer's claim that lint / - test pass with the docs changes is **partially verified**: lint - confirmed clean; tests confirmed clean by inheritance from - code-review-1's run on the same source files (no test code was - touched in the docs phase). - ---- - -## Required check 8 — No scope creep - -`git status --short` shows only `packages/env/README.md` and -`packages/env/CHANGELOG.md`. **Both inside `packages/env/`**. ✅ - ---- - -## Summary of findings - -### Blockers (1) - -1. **CLI `--auto-port` describe string in `lib/cli.js:154-158` must - be updated** to reflect the new tri-state semantics. As filed, the - string is actively misleading: it implies `--auto-port` is the only - path to auto-fallback (no longer true) and understates the flag's - new meaning ("also fall back on user-set ports"). The string is a - user-facing surface rendered in `wp-env start --help` and - reproduced verbatim in `README.md:368-369`, which makes the README - internally inconsistent: the prose elsewhere correctly describes - the new behavior, but the embedded help block contradicts it. A - yargs `describe` is documentation, not behavior, and falls within - the docs phase's remit. **Required for approval.** - -### Non-blocker findings - -- README §"Automatic Port Selection" §2 lists the user-set sources as - `port` / `testsPort` / `WP_ENV_PORT` / `WP_ENV_TESTS_PORT` but does - not mention the nested `env.development.port` / `env.tests.port` - form (which is also honored). Acceptable as-is for a user doc; - optional polish. -- The CHANGELOG bullet is long and semicolon-separated. Style is - defensible; could be tightened in a future polish pass. -- The `8888` → `8890` example in "Automatic Port Selection" §1 might - read as "scanner skips by 2" without context. Optional clarification - could note "8889 is reserved as the default tests port". -- README `wp-env start --help` reproduction at lines 368-369 will need - to be regenerated once the cli.js describe string is updated, or it - will continue to drift. - ---- - -## Verdict - -``` -REJECTED -``` - -The README and CHANGELOG prose changes are accurate, well-placed, and -match the implementation across all eight required checks except for -one: the unupdated CLI `--auto-port` `describe` string in `lib/cli.js` -leaves the help-text surface (and the README block that reproduces it) -contradicting the rest of the documentation. A `yargs` `describe` is -documentation, not behavior, and is within the docs phase's remit. - -The doc-writer should: - -1. Update `lib/cli.js:154-158`'s `--auto-port` `describe` to reflect - the new tri-state contract (suggested wording in §"Required check - 4" above). -2. Regenerate the `wp-env start --help` code block in - `packages/env/README.md:343-369` so it matches the new describe - text. -3. Re-request review. - -All other aspects of the documentation are correct and complete. diff --git a/.pipelines/49843-wp-env-default-port-fallback/docs-review-2.md b/.pipelines/49843-wp-env-default-port-fallback/docs-review-2.md deleted file mode 100644 index 64993f54b52184..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/docs-review-2.md +++ /dev/null @@ -1,302 +0,0 @@ -# Phase 5 — Documentation review - -Iteration 2. - -Pipeline: `49843-wp-env-default-port-fallback` -Spec: `spec.md` (round 2 APPROVED). -Plan: `plan.md` (round 2 APPROVED). -Code-review: `code-review-1.md` (APPROVED with conditions deferred to docs/PR phases). -Prior docs review: `docs-review-1.md` (REJECTED — single blocker on stale `--auto-port` describe string in `lib/cli.js` and the README mirror). -Reviewed artifact: staged changes to `packages/env/CHANGELOG.md`, `packages/env/README.md`, and `packages/env/lib/cli.js` (3 files, +25 / −9). - ---- - -## Method - -I read the spec, plan, code-review-1, and docs-review-1 end-to-end. I read the -staged diff (`git diff --staged -- packages/env/lib/cli.js packages/env/README.md -packages/env/CHANGELOG.md`) end-to-end. I cross-checked the new `--auto-port` -describe string in `lib/cli.js` against its mirror in `packages/env/README.md`'s -`### wp-env start` help block byte-for-byte. I verified the README's -"Automatic Port Selection" prose still reads consistently with the new help-text -description. I verified the CHANGELOG entry still accurately reflects the -implementation. I confirmed no scope creep beyond the three authorized files -(no JSDoc, no test changes). I ran `npm run lint:js -- packages/env` and -`npx jest packages/env --config test/unit/jest.config.js` from inside the -worktree to bypass the host-environment Haste-map collision documented in -docs-review-1. - ---- - -## Round 1 blocker — closed - -The single round-1 blocker was the stale `--auto-port` describe string at -`lib/cli.js:154-158` and its mirror in `README.md` (the `### wp-env start` -help-output code block). Round 2 updates both: - -### `lib/cli.js:157` (source of truth, rendered by yargs in `wp-env start --help`) - -``` -'Also fall back to the next available port when explicitly configured ports are busy. By default, only the standard ports 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" setting.' -``` - -### `README.md:368-371` (mirror, displayed inside the documented `wp-env start` help block) - -The README presents the same string wrapped to fit yargs' rendered column -width: - -``` - --auto-port Also fall back to the next available port when explicitly - configured ports are busy. By default, only the standard ports - 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" - setting. [boolean] -``` - -### Byte-for-byte equivalence check - -I extracted the unwrapped string text from both surfaces (collapsing the -README's yargs line wraps and leading whitespace) and confirmed they are -identical (193 chars in both; equality check returned `True`). The README -mirror is an accurate reproduction of the yargs-rendered output of the -new `lib/cli.js` describe string. **No drift between source and mirror.** -✅ - -### Substantive accuracy of the new describe string (against the implementation) - -I cross-checked all three claims the new describe makes: - -1. **"Also fall back to the next available port when explicitly configured - ports are busy."** — `load-config.js:101` maps CLI `autoPort: true` → - `autoPortMode = 'all'`; `resolve-available-ports.js:144-146` under `'all'` - sets `strict = false` for every port (HTTP and `phpmyadminPort`). So - passing `--auto-port` extends fallback to user-set ports (which would be - strict under `'defaults-only'` because the provenance Set excludes - user-set keys). ✅ -2. **"By default, only the standard ports 8888/8889 auto-fall-back."** — - `parse-config.js:93` defaults `autoPort` to `null`; `load-config.js:101-107` - maps `null` (via the `else` branch) → `autoPortMode = 'defaults-only'`; - `resolve-available-ports.js:128-149` under `'defaults-only'` skips - `phpmyadminPort` entirely and routes HTTP ports per `defaultOriginPorts`. - So the bare default does indeed fall back only on the standard - `8888`/`8889` (assuming no user override). ✅ -3. **"Overrides the .wp-env.json `autoPort` setting."** — `load-config.js:96-98` - establishes `effectiveAutoPort = autoPort !== undefined ? autoPort : - config.autoPort`, so the CLI value wins whenever it is supplied (and - `cli.js:155-156` defines `--auto-port` as a boolean with no default, so - "undefined" maps to "flag not passed"). ✅ - -The describe string is accurate at every clause. ✅ - -### Round 1 knock-on (regenerate the README help block) — closed - -Round 1 also flagged that the README `wp-env start --help` block at the old -line 368-369 had to be regenerated once the cli.js describe was updated. -The diff confirms both edits happened in lockstep — the new describe text -appears in `lib/cli.js:157` AND in the README help block, with the README's -yargs line-wrapping matching the column layout yargs produces for a string -of this length. ✅ - -### Round 1 verdict on the prose changes — re-confirmed - -Round 1 rated the README prose ("Automatic Port Selection" §§1–4, the -`autoPort` schema-table row, the §2 "Check the port number" paragraph) and -the CHANGELOG entry as accurate and well-placed. I re-verified each below. - ---- - -## Required check 1 — README "Automatic Port Selection" prose internal consistency - -I re-read the `### Automatic Port Selection` section after the cli.js edit -to confirm there is no contradiction between the new help-text claim and -the prose. The relevant sentences: - -- README §1 (line 624): "By default, `wp-env` tries the standard ports - (`8888` for development, `8889` for tests). If you have not configured - a port explicitly and one of those defaults is busy on the host, `wp-env` - scans upward to the next available port…" — consistent with the help - text's "By default, only the standard ports 8888/8889 auto-fall-back". -- README §2 (line 626): "Ports that you configured yourself … are never - silently moved. If your configured port is busy, the start fails…" — - consistent with the help text's implicit promise that `--auto-port` is - the way to extend fallback to "explicitly configured ports". -- README §3 (line 628): "If you want auto-fallback to apply to your - configured ports too, pass the `--auto-port` flag (or set `"autoPort": - true` in `.wp-env.json`)" — exactly the same proposition as the help - text's first sentence, in user-facing prose. -- README §4 (line 634): `"autoPort": false` opt-out — consistent with the - schema-table row at line 611 ("Set to `false` to opt out entirely, - including on the default ports"). -- README final paragraph (line 642): `CI=1` continues to disable fallback - — consistent with `load-config.js:109-112` (CI guard fires after the - tri-state mapping and unconditionally forces `'off'`). - -**No internal contradiction.** The new help text reads as a one-paragraph -summary of what the four prose paragraphs spell out in detail. ✅ - ---- - -## Required check 2 — CHANGELOG accuracy (re-confirmed; no revision needed) - -The CHANGELOG entry at `packages/env/CHANGELOG.md:5-7` reads: - -> The default ports `8888` (development) and `8889` (tests) now automatically -> fall back to the next available port when busy, so `wp-env start` works out -> of the box on hosts where those ports are taken; explicitly configured ports -> keep today's strict behavior unless `--auto-port` / `"autoPort": true` is -> passed, and the new `"autoPort": false` opt-out disables fallback even on -> the defaults. ([#49843](https://github.com/WordPress/gutenberg/issues/49843), -> [#74472](https://github.com/WordPress/gutenberg/pull/74472)) - -Each clause re-verified against the implementation: -- "default ports `8888` and `8889` now automatically fall back" → matches - `load-config.js:107` `autoPortMode = 'defaults-only'` for `null` / - `undefined` config. -- "explicitly configured ports keep today's strict behavior unless - `--auto-port` / `"autoPort": true` is passed" → matches the per-port - routing in `resolve-available-ports.js:147-148` (`strict = ! - defaultOriginPorts.has(key)` under `'defaults-only'`). -- "`"autoPort": false` opt-out disables fallback even on the defaults" - → matches `load-config.js:103` (`effectiveAutoPort === false` → - `'off'`). - -The entry was not touched in round 2; it remains accurate. **No revision -needed.** ✅ - ---- - -## Required check 3 — Scope confinement - -`git status --short`: - -``` -M packages/env/CHANGELOG.md -M packages/env/README.md -M packages/env/lib/cli.js -``` - -`git diff --stat`: empty (everything is staged). All three files are inside -`packages/env/`. **No JSDoc files touched** (verified — `parse-config.js`, -`load-config.js`, `post-process-config.js`, `resolve-available-ports.js`, -`commands/start.js` are all clean). **No test files touched** (verified — -`packages/env/lib/test/`, `packages/env/lib/config/test/` clean). **No -snapshot files touched.** ✅ - -The only diff in `lib/cli.js` is the single string literal at line 157 -(the describe string). No code-path change, no signature change, no -yargs option-shape change. ✅ - ---- - -## Required check 4 — Lint and tests - -- `npm run lint:js -- packages/env` from this worktree's repo root: - **PASSES** (exit 0). The `eslint-plugin-react-hooks` issue - code-review-1 mentioned has been resolved at the parent-checkout level, - so the configured lint script now runs cleanly. The doc-writer's docs - edits do not touch any lint-relevant code. -- `npm run test:unit -- packages/env` from the repo root: **FAILS** with - the same Jest Haste-map duplicate-package collision documented in - docs-review-1 (sibling worktrees in the parent checkout supply - duplicate `package.json` for `@wordpress/compose`). **This is a - host-environment limitation, not a regression.** -- I bypassed the collision by running Jest directly from inside this - worktree: - ``` - $ npx jest packages/env --config test/unit/jest.config.js - … - Test Suites: 18 passed, 18 total - Tests: 181 passed, 181 total - Snapshots: 8 passed, 8 total - Time: 2.478 s - ``` - **181 / 181 pass; 8 / 8 snapshots pass.** Matches the code-review-1 - baseline exactly. ✅ - ---- - -## Required check 5 — No new gaps appeared since round 1 - -Beyond the round-1 blocker (now closed) and the round-1 non-blocker findings -(see below), I scanned the round-2 diff for any new contradictions, missing -coverage, or stale references introduced by the doc-writer: - -- **No new prose claims** beyond the help-text describe string. The README - body and CHANGELOG were unchanged from round 1. The describe-string update - is additive; it does not invalidate any claim elsewhere. -- **No new examples introduced.** The README's existing `wp-env start - --auto-port` example and `"autoPort": false` JSON snippet are unchanged. -- **No reference drift** (the help block at `README.md:368-371` is the only - mirror of the cli.js describe, and both were updated in lockstep). -- **No new file modified** beyond `lib/cli.js` (and the README block that - reproduces its output). JSDoc and tests are still untouched. ✅ - ---- - -## Round 1 non-blocker findings — re-confirmed as still non-blockers - -I re-checked each of round 1's non-blocker findings to ensure none escalated: - -1. **README §"Automatic Port Selection" §2 enumerates user-set sources as - `port` / `testsPort` / `WP_ENV_PORT` / `WP_ENV_TESTS_PORT` but does not - mention nested `env.development.port` / `env.tests.port`.** Still true - in round 2; the doc-writer did not expand the enumeration. **Still - acceptable** for a user-facing README. -2. **CHANGELOG bullet is long and semicolon-separated.** Unchanged in - round 2. Still defensible because the feature has three semantic facets. - **Non-blocker.** -3. **`8888` → `8890` example might read as "scanner skips by 2".** - Unchanged in round 2. **Non-blocker.** -4. **Validator at `parse-config.js:493-504` says "must be a boolean" even - though it now accepts `null`.** Unchanged in round 2 (out of docs scope - anyway). The code-review-1 already accepted this as a minor cosmetic - issue. **Non-blocker.** - -None of these escalated to a blocker in round 2. ✅ - ---- - -## Required check 6 — Verify no scope creep into PR-phase obligations - -Round 1 noted the following round-1 conditions that the code-review-1 -deferred to "before PR opens": - -- README updated → Done (round 1, re-confirmed clean in round 2). -- CHANGELOG updated → Done (round 1, re-confirmed clean in round 2). -- `composer test` runs green → Out of docs phase; deferred to PR-opening - step. -- PR body test plan enumerates AC1–AC11 → PR-phase obligation, not docs. -- PR body includes AC9b reproduction recipe → PR-phase obligation, not docs. -- PR body acknowledges the (now-resolved) lint-deps issue → PR-phase - obligation; in round 2 the lint dep is present so this notice may no - longer be needed. -- PR opened against `trunk` from `try/49843-wp-env-default-port-fallback`, - links `#49843`, draft → PR-phase obligation. - -The doc-writer correctly stayed within the docs-phase remit and did not -overreach into PR-body content. ✅ - ---- - -## Verdict - -``` -APPROVED -``` - -The round-1 blocker is closed. The new `--auto-port` describe string in -`packages/env/lib/cli.js:157` is byte-for-byte identical (193 chars -unwrapped) to its mirror in `packages/env/README.md:368-371`'s help block. -The new string is substantively accurate against the implementation: -default ports auto-fall-back without the flag, the flag extends fallback -to user-set ports, and the flag overrides the `.wp-env.json` `autoPort` -field. The README "Automatic Port Selection" prose, the schema-table row, -and the CHANGELOG entry remain consistent with the new help text — no -contradictions surfaced. Scope is confined to the three authorized files; -no JSDoc, no tests, no snapshots touched. Lint exits 0; the JS unit suite -passes 181 / 181 (run via `npx jest` from inside the worktree to bypass -the host-environment Haste-map collision documented in docs-review-1). - -Documentation phase is complete and ready to hand off to the PR-creation -step. The deferred conditions from code-review-1 (composer test, -PR body content) remain pre-PR-open obligations and are out of scope for -the docs phase. diff --git a/.pipelines/49843-wp-env-default-port-fallback/plan-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/plan-review-1.md deleted file mode 100644 index d981d79bea8153..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/plan-review-1.md +++ /dev/null @@ -1,155 +0,0 @@ -# Plan review — Iteration 1 - -Pipeline: `49843-wp-env-default-port-fallback` -Reviewer role: plan-reviewer (adversarial) -Reviewing: `plan.md` (single iteration so far) -Source-citations verified by reading: `packages/env/lib/config/parse-config.js`, `packages/env/lib/config/load-config.js`, `packages/env/lib/config/post-process-config.js`, `packages/env/lib/config/merge-configs.js`, `packages/env/lib/resolve-available-ports.js`, `packages/env/lib/port-utils.js`, `packages/env/lib/cli.js`, `packages/env/lib/commands/start.js`, `packages/env/lib/commands/stop.js`, `packages/env/lib/commands/status.js`, `packages/env/lib/commands/{clean,destroy,cleanup,logs,reset,run}.js`, `packages/env/lib/runtime/docker/build-docker-compose-config.js`, `packages/env/lib/config/get-config-from-environment-vars.js`, `packages/env/lib/test/cli.js`, `packages/env/lib/test/build-docker-compose-config.js`, `packages/env/lib/config/test/parse-config.js`, `packages/env/README.md`, `packages/env/CHANGELOG.md`, the `packages/env/lib/test/__snapshots__/` and `packages/env/lib/config/test/__snapshots__/` directories. - ---- - -## Summary - -The plan resolves OQ1-OQ7 with mostly correct evidence and traces every spec AC to at least one step. Most cited line numbers are accurate. The shape of the design (tri-state `autoPort: null`, per-port `defaultOriginPorts` Set, per-port `strict` flag in `resolveConfigPorts`, spinner.info from `createPortResolver`) is consistent with the spec. - -However, the plan has **three blockers** that will cause the implementer to either ship something that fails the existing test suite, or has to invent ad-hoc fixes mid-implementation: - -1. The plan changes `parseConfig`'s return shape (Step 3) from `WPRootConfig` to `{ config, defaultOriginPorts }`. This silently breaks ~25 existing call sites in `packages/env/lib/config/test/parse-config.js` (every `parsed = await parseConfig(...)` followed by `expect( parsed )...`). The plan does not list these tests as "Modified", does not include them in Step 12's snapshot sweep, and does not mention the structural change at all in the test plan. AC10 explicitly requires existing tests stay green; this is a guaranteed regression. -2. The plan changes `DEFAULT_ENVIRONMENT_CONFIG.autoPort` from `false` to `null` (Step 1). The test fixture `DEFAULT_CONFIG` at `packages/env/lib/config/test/parse-config.js:21-71` has `autoPort: false` hardcoded and is `toEqual()`-compared against `parseConfig` output in many tests (lines 91, 193, 232, 293, 305, 506, 537, 560, etc.). The plan only mentions modifying the named test `should accept autoPort as a boolean`. Every other test that compares against the `DEFAULT_CONFIG` fixture will fail. Again breaks AC10. -3. The plan unconditionally creates the port resolver whenever `autoPortMode !== 'off'` (Step 2). Today, `phpmyadminPort` is only resolved when `--auto-port` is on; the plan would now also auto-resolve `phpmyadminPort` non-strictly in the new `defaults-only` mode. For a contributor who has `phpmyadmin: true, phpmyadminPort: 8080` (user-set) and no explicit `autoPort`, this silently moves their phpmyadmin port if 8080 is busy — a regression of the "user-set ports are never silently moved" contract (R3) for the phpmyadmin case. The plan does not analyze this behavior change. Either the plan needs to thread `defaultOriginPorts` for phpmyadminPort too (mirroring the HTTP ports), or it needs to special-case phpmyadminPort to keep today's behavior (only resolved when `autoPortMode === 'all'`), or the spec needs to be amended to acknowledge phpmyadminPort moves silently in defaults-only. None of those is in the plan. - -In addition, several **non-blocking findings** below should be addressed before approval. - ---- - -## Verified citations (correct) - -- `parse-config.js:86-111` `DEFAULT_ENVIRONMENT_CONFIG`: confirmed (`autoPort: false` at line 93). Step 1's target. -- `parse-config.js:124-167` merge sequence: confirmed. -- `parse-config.js:284-344` `getEnvironmentVarOverrides`: confirmed. -- `parse-config.js:390-397` `parseRootConfig`'s `autoPort` block: confirmed (does NOT assign when `undefined`). -- `parse-config.js:483` `case 'autoPort':` in the switch: confirmed. -- `load-config.js:96-109` (`shouldAutoPort` block): confirmed (lines 96-109 contain the exact block plan rewrites). -- `load-config.js:102-104` `process.env.CI` guard: confirmed verbatim (`if ( process.env.CI ) { shouldAutoPort = false; }`). -- `load-config.js:90-94` `parseConfig` call site: confirmed. -- `post-process-config.js:24-43` exported function with `{ portResolver }` destructure: confirmed. -- `post-process-config.js:35-42` resolveConfigPorts call: confirmed (lines 35-37 specifically). -- `resolve-available-ports.js:38-90` `createPortResolver`: confirmed. -- `resolve-available-ports.js:50` `resolve(preferredPort, configPath, strict = false)`: confirmed third-arg already supports strict. -- `resolve-available-ports.js:74-87` non-strict branch: confirmed (lines 74-87). -- `resolve-available-ports.js:75-78` `usedPorts` exclude: confirmed. -- `resolve-available-ports.js:84-87` error wrapping: confirmed. -- `resolve-available-ports.js:100-130` `resolveConfigPorts`: confirmed; the loop body matches. -- `resolve-available-ports.js:101-127` PORT_DEFINITIONS loop: confirmed. -- `resolve-available-ports.js:121-126` phpmyadminPort behavior: confirmed (lines 121-127 cover both HTTP and phpmyadmin in the same loop, no special branching). -- `port-utils.js:51-80` `findAvailablePort` with throw: confirmed (`No available port found in range ${ startPort }-${ maxPort }.` at lines 77-79). -- `cli.js:154-159` `--auto-port` yargs definition: confirmed (`type: 'boolean'`, no `default`). -- `cli.js:24-93` `withSpinner` (plan also says `cli.js:46-92` for spinner: that range is accurate for the rejection branches). -- `start.js:55-59` `loadConfig({ resolvePorts: true, autoPort, spinner })`: confirmed. -- `stop.js:21-31` consumes cached compose by container name: confirmed (`loadConfig` is called WITHOUT `resolvePorts`, so no resolution; runtime stop operates on `dockerComposeConfigPath`). -- `lib/test/cli.js:35-52` tri-state CLI assertions: confirmed (`undefined`, `true`, `false`). -- `get-config-from-environment-vars.js:36-72` env-var enumeration: confirmed (`WP_ENV_PORT`, `WP_ENV_TESTS_PORT`, `WP_ENV_MYSQL_PORT`, `WP_ENV_TESTS_MYSQL_PORT`, `WP_ENV_PHPMYADMIN_PORT`, `WP_ENV_TESTS_PHPMYADMIN_PORT` are the port-yielding ones; OQ4 resolution is correct). -- README `autoPort` row at line 609 and "Automatic Port Selection" at lines 620-630: confirmed. -- CHANGELOG `## Unreleased` at line 3: confirmed. - -## Verified citations (wrong — would mislead the implementer) - -- `build-docker-compose-config.js:173, 267` — the file is **not** at `packages/env/lib/build-docker-compose-config.js` as suggested by the bare reference style elsewhere in the plan. The actual path is `packages/env/lib/runtime/docker/build-docker-compose-config.js`. The line numbers (173 and 267) are correct *for that path* — line 173 is the `developmentPorts = ` interpolation and line 267 is the `testsPorts = ` interpolation. The implementer should be steered to the runtime/docker subpath. (Non-blocking but should be corrected.) - ---- - -## Findings - -### B1 (Blocker) — Step 3 silently breaks every existing parseConfig test -Step 3 changes `parseConfig`'s return value from `WPRootConfig` (the merged config object) to `{ config, defaultOriginPorts }`. The existing test file `packages/env/lib/config/test/parse-config.js` calls `parseConfig` ~25 times and asserts shape against the result directly (e.g. `expect( parsed ).toEqual( DEFAULT_CONFIG )` at line 91, `expect( parsed.coreSource )...` at line 101, `expect( parsed.autoPort ).toEqual( true )` at line 206). With the new shape, every such assertion is either a structural mismatch (`{ config, defaultOriginPorts }` vs the inner config) or `parsed.autoPort` becomes `undefined`. AC10 demands "existing tests stay green". The test plan in §3 lists exactly one modified test (`should accept autoPort as a boolean`) but does not acknowledge the wholesale refactor. Fix: either (a) explicitly enumerate every existing parse-config test as "Modified" with the new destructure pattern, or (b) attach `defaultOriginPorts` as a non-enumerable property on the returned config (the plan listed this as an alternative and explicitly rejected it, but it would preserve API compatibility with the test suite). The plan must commit to one of those before implementation begins. - -### B2 (Blocker) — DEFAULT_CONFIG fixture in tests is not updated -Step 1 changes `DEFAULT_ENVIRONMENT_CONFIG.autoPort` from `false` to `null`. The test fixture `DEFAULT_CONFIG` at `packages/env/lib/config/test/parse-config.js:21-71` has `autoPort: false` hardcoded (line 24) and is used as the expected value in `expect( parsed ).toEqual( DEFAULT_CONFIG )` (line 91) and as a spread base in many other assertions (lines 166, 232, 293, 305, etc.). Step 12's snapshot sweep does not catch this because it is not a snapshot — it is an inline fixture. The plan does not list this fixture update under Step 10 ("modified" tests) or anywhere else. Without it, the suite is red on the very first commit. Fix: explicitly call out "update `DEFAULT_CONFIG.autoPort` from `false` to `null` in `packages/env/lib/config/test/parse-config.js`" as part of Step 1 or Step 10. - -### B3 (Blocker) — phpmyadminPort silently auto-moves under defaults-only mode (R3 regression) -Step 2 says "Always create a portResolver when resolvePorts is true and autoPortMode !== 'off'", and Step 5 says for phpmyadminPort: "keep today's behavior (always non-strict via findAvailablePort) … Implement as `strict = false`." But TODAY, when `--auto-port` is off, `portResolver` is never created, so `resolveConfigPorts` never runs for phpmyadminPort either. The plan would change behavior so that under the new default-only mode (the common case for a contributor with no `autoPort` setting), a user-set `phpmyadminPort: 8080` that happens to be busy gets silently moved. That violates R3 ("user-set ports are never silently moved") for the phpmyadmin case, even though phpmyadminPort is technically out of the explicit HTTP-port scope. The plan needs to either (a) thread the same `defaultOriginPorts` provenance for phpmyadminPort and apply the same `strict = ! defaultOriginPorts.has(...)` rule, (b) special-case phpmyadminPort so the resolver only runs in `'all'` mode (preserving today's behavior verbatim), or (c) escalate to spec to explicitly accept this regression. As written, this is a silent behavior change not analyzed in the plan. - -### F1 (Non-blocker) — `build-docker-compose-config.js` path is ambiguous -The plan refers to `build-docker-compose-config.js:173, 267` without the `runtime/docker/` prefix. The line numbers are accurate but the file lives at `packages/env/lib/runtime/docker/build-docker-compose-config.js`, not at `packages/env/lib/build-docker-compose-config.js`. The test file at `packages/env/lib/test/build-docker-compose-config.js` is unrelated (it imports from the runtime path). Clarify the cited path so the implementer does not chase a non-existent file. - -### F2 (Non-blocker) — Snapshot drift assessment is incomplete -Step 12 says "If `config-integration.js.snap` changes (e.g. because `null` now appears for `autoPort`), inspect the diff." But `grep -n autoPort` against both snapshot files (`packages/env/lib/test/__snapshots__/md5.js.snap` and `packages/env/lib/config/test/__snapshots__/config-integration.js.snap`) returns zero hits today. There is no `autoPort` in the snapshots, so no drift is expected from that field. The snapshot risk the plan should call out instead is the `build-docker-compose-config.js` test file (not snapshot-based, but assertion-based on hardcoded `8888`/`8889`); however that file does NOT use `parseConfig` end-to-end — it constructs synthetic configs with explicit ports. So the plan's worry about snapshot churn is overstated and the actual fixture-update risk (B2 above) is missed. - -### F3 (Non-blocker) — AC4 lacks a behavior-level integration test -The test plan covers AC4 only at the routing-matrix level ("uses non-strict mode for all ports under autoPortMode=all"). Spec AC4 reads as a Given/When/Then on `loadConfig` end-to-end (".wp-env.json sets port: 9000 + --auto-port + 9000 busy → start succeeds against next port above 9000"). The mirror to AC5's `loadConfig`-level test would be a `loadConfig with CLI autoPort=true and explicit user port falls back when port is busy` integration test in `config-integration.js`. The plan covers AC5 with such a test but not AC4. Strictly, the routing-matrix test plus the existing `--auto-port` test path may be enough for this change, but the asymmetry is worth flagging. - -### F4 (Non-blocker) — Step 6 spinner re-arming claim under-specified -Step 6 says "call `spinner.info(...)` followed by `spinner.start()` to re-arm the spinner (the existing `withSpinner` in `cli.js:24-93` expects the spinner to remain active until the command resolves)." Reading `cli.js:24-93`, `spinner.info` is `ora`'s API which does change the spinner state, and `spinner.start()` is needed afterward to resume. The plan's instinct is correct but it does not cite where in the existing code the same pattern is used (`start.js:101` and `start.js:113` both do `spinner.warn(...); spinner.start();` — that is the precedent). Citing that precedent would make the implementer's job clearer. Also: the test plan asserts `spinner.start was called to re-arm` but does not assert the order of calls (info before start). Minor. - -### F5 (Non-blocker) — OQ7 resolution slightly imprecise -The plan says about `process.env.CI` truthiness: "JavaScript truthy semantics: `"true"`, `"1"`, `"false"` (non-empty string), and any non-empty string are all truthy; `undefined`/empty string/`"0"` is also truthy in string form (`"0"` is truthy as a string)." This is internally inconsistent — `undefined` is NOT truthy in JS, and `""` is NOT truthy. The plan probably meant "non-empty string", but as written the sentence contradicts itself. This is reused from spec OQ7 verbatim and does not affect correctness (the implementation is `if ( process.env.CI )` which the plan correctly preserves), but the wording should be cleaned up to avoid confusing the implementer. - -### F6 (Non-blocker) — JSDoc updates are mentioned twice but never staged in test plan -Steps 1, 2, 7 each say "update the JSDoc". No verification step asserts the JSDoc reflects the new tri-state. Not critical (JSDoc is non-functional) but worth a single-line note in Step 12 that the JSDoc updates were performed. - -### F7 (Non-blocker) — Sequencing line is wrong about parallel/serial -§4 says: "Serial (must run in order): step 1 → step 2 → steps 4/5/7 → step 10/11 → step 12." But step 4 depends on step 3 (per Step 4's own "Depends on. Step 3" line), so the serial chain should read "step 1 → step 2 → step 3 → steps 4/5 → step 7 → step 10/11 → step 12" with step 3 also serial, not "parallelizable with step 1". And step 6 (described as parallelizable with step 1) actually should be parallel with step 5 since both touch the same file (`resolve-available-ports.js`) — so they cannot literally be done in parallel by separate workers, only by sequential editing of the same file. The plan's parallelism statement is thus aspirational but technically wrong. Minor for a single implementer; matters for an agent team. - -### F8 (Non-blocker) — Rollback paragraph could mention the snapshot -§7 ("Rollback") says "A clean `git revert ` restores the prior PR #74472 opt-in-only behavior with no downstream cleanup needed: there is no migration, no persisted state, no schema change, and no public API surface change." This is correct as far as wp-env's own surface goes, but the plan does not call out that since cached `docker-compose.yml` files contain hardcoded resolved ports, an environment that started under the new default-fallback behavior on (say) 8890 will keep its cached compose pinned to 8890 until the user runs `start` again. Post-revert, that already-running environment continues to work, but newly-started ones (without `--auto-port`) on a busy 8888 will start failing again. Worth one sentence so the reverting maintainer knows to communicate this in the revert message. - ---- - -## AC coverage matrix (audited) - -| AC | Plan step(s) | Test(s) | OK? | -|---|---|---|---| -| AC1 | Steps 1, 2, 3, 4, 5 | parse-config provenance tests + "uses non-strict mode for default-origin ports" + "tri-state autoPort: unset triggers defaults-only mode" | Yes | -| AC2 | Steps 1, 2, 3, 4, 5 | same as AC1 (covers both env keys symmetrically) | Yes | -| AC3 | Steps 1, 2, 3, 4, 5 | "uses strict mode for non-default-origin ports under autoPortMode=defaults-only" + four parse-config provenance tests | Yes | -| AC4 | Steps 2, 5 | "uses non-strict mode for all ports under autoPortMode=all" + "CLI autoPort=true and user config autoPort=false has CLI win" | Partial (see F3) | -| AC5 | Steps 1, 2, 5 | "uses strict mode for all ports under autoPortMode=off" + "loadConfig with autoPort:false in user config skips fallback" | Yes | -| AC6 | Step 2 (CI guard preserved) | "loadConfig with CI=1 disables fallback regardless of autoPort:true" + "even when autoPort is unset" | Yes | -| AC7 | Step 6 | four resolver-notice tests including the no-console regression guard | Yes | -| AC8 | Step 2 + Step 10 named test | "CI=1 disables fallback regardless of autoPort:true" is the named regression detector | Yes | -| AC9a | Step 4 (post-process threading) | "postProcessConfig threads autoPortMode and defaultOriginPorts to portResolver" asserts WP_HOME/WP_SITEURL reflect resolved port | Yes | -| AC9b | Manual recipe in §3 of plan | PR test plan recipe enumerated | Yes (manual per spec) | -| AC9c | Inherited from cached compose pattern | None automated; manual per recipe | Yes (manual per spec; rationale documented) | -| AC10 | Step 12 | Snapshot sweep — but B1 and B2 mean existing tests will fail without fixture/return-shape updates | **No** — broken by B1/B2 | -| AC11 | Steps 1, 2, 7 | "should accept autoPort as a boolean" (modified to assert default is null) + "tri-state autoPort: unset triggers defaults-only mode" | Yes | - -All ACs have at least one plan step targeting them. AC10 is technically covered by Step 12 but B1 and B2 will make it fail in practice. - ---- - -## OQ resolution audit - -| OQ | Plan resolution | Source verified? | Verdict | -|---|---|---|---| -| OQ1 (per-environment autoPort) | Root-only per `parse-config.js:483` and `:390-397` | Yes | Correct | -| OQ2 (provenance mechanism) | `defaultOriginPorts` Set built in parseConfig | Citation correct (`parse-config.js:124-167`) | Correct shape, but see B1 about return-value impact | -| OQ3 (multi-layer overrides) | Any non-default layer counts | Yes | Correct | -| OQ4 (env-var sources) | `WP_ENV_PORT`, `WP_ENV_TESTS_PORT` in scope | Verified at `get-config-from-environment-vars.js:38,40` | Correct | -| OQ5 (no upward port available) | Throws via `port-utils.js:77-79`, wrapped at `resolve-available-ports.js:84-87` | Yes | Correct | -| OQ6 (re-resolution on every start) | Confirmed by tracing start.js → load-config.js → post-process → resolveConfigPorts → mutates config.env[env].port; build-docker-compose interpolates that into cached YAML; downstream commands operate on cached YAML by container name | Yes (verified `stop.js:21-31` does NOT call loadConfig with resolvePorts; `clean/destroy/cleanup/logs/run/status` likewise omit `resolvePorts`) | Correct | -| OQ7 (CI truthiness) | Inherit verbatim from `load-config.js:102-104` | Yes — but see F5 about wording | Correct in substance | - ---- - -## Verification of required-check items from the team prompt - -1. **Spec AC coverage** — All ACs have at least one plan step. Coverage matrix above. (All ACs covered, none uncovered.) -2. **Step traceability** — Each step traces to ACs in its own "Spec ACs covered" line. No over-scoping detected. -3. **Source-code feasibility** — Citations are largely accurate; the only path ambiguity is `build-docker-compose-config.js` (F1). -4. **OQ resolutions** — All seven OQs resolved with valid evidence; OQ7 wording is internally inconsistent but not wrong in substance. -5. **Test plan completeness** — Major gap: B1 and B2 (parseConfig return-shape change and DEFAULT_CONFIG fixture); minor gap: B3 (phpmyadminPort behavior change unanalyzed); F3 (AC4 lacks behavior-level integration test). -6. **Sequencing** — F7: serial chain is wrong about step 3, and step 6 cannot literally be parallel with step 5 (same file). -7. **PHP-regression risk** — `composer test` is invoked at gates 2 and 4 per §4. Concrete checkpoint exists. OK. -8. **Scope confinement** — All file paths live inside `packages/env/`. OK. -9. **Rollback** — Concrete enough to act on, but should mention the cached-compose-pinning side effect (F8). - ---- - -## Verdict - -``` -REJECTED — REVISIONS REQUESTED -``` - -Three blockers must be addressed before this plan can drive an implementation: (B1) the `parseConfig` return-shape change breaks ~25 existing tests with no acknowledgment in the test plan; (B2) the `DEFAULT_CONFIG` fixture in `parse-config.js` tests is not updated when the default `autoPort` value changes; (B3) `phpmyadminPort` will silently move under the new defaults-only mode whenever a user has set it, which is a quiet R3 regression the plan does not analyze. - -The non-blocking findings (F1–F8) should also be cleaned up but are not gates. diff --git a/.pipelines/49843-wp-env-default-port-fallback/plan-review-2.md b/.pipelines/49843-wp-env-default-port-fallback/plan-review-2.md deleted file mode 100644 index 4e6f08a9e1f113..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/plan-review-2.md +++ /dev/null @@ -1,158 +0,0 @@ -# Plan review — Iteration 2 - -Pipeline: `49843-wp-env-default-port-fallback` -Reviewer role: plan-reviewer (adversarial) -Reviewing: `plan.md` (round 2 revision) -Prior review: `plan-review-1.md` -Source-citations re-verified by reading: `packages/env/lib/config/parse-config.js`, `packages/env/lib/config/load-config.js`, `packages/env/lib/config/post-process-config.js`, `packages/env/lib/config/merge-configs.js`, `packages/env/lib/resolve-available-ports.js`, `packages/env/lib/cli.js`, `packages/env/lib/commands/start.js`, `packages/env/lib/commands/stop.js`, `packages/env/lib/runtime/docker/build-docker-compose-config.js`, `packages/env/lib/config/get-config-from-environment-vars.js`, `packages/env/lib/test/cli.js`, `packages/env/lib/config/test/parse-config.js`, `packages/env/README.md`, `packages/env/CHANGELOG.md`, plus a directory listing of `packages/env/lib/runtime/docker/` and the snapshot directories under `packages/env/lib/{,config/}test/__snapshots__/`. - ---- - -## Summary - -Round 2 closes all three round-1 blockers and every minor finding (F1–F8) at the artifact level. The non-enumerable-property design (B1 fix) is well-grounded: I re-read `merge-configs.js` and confirmed both iteration sites (`for ( const option in config )` at line 39 and `for ( const option in toMerge )` at line 81) use `for…in`, which is well-defined in JavaScript to skip non-enumerable own properties. Jest's `toEqual` also walks own-enumerable properties only. The DEFAULT_CONFIG fixture update (B2 fix) is now an explicit Step 1 sub-step, and the phpmyadminPort regression (B3 fix) is sealed by a per-port skip rule with a dedicated regression test. - -Spot-checks of cited line numbers all matched the source. The plan reads as feasible and complete. Approving. - ---- - -## Round-1 finding closure audit - -| Round-1 finding | Status | Where in plan v2 | -|---|---|---| -| **B1** — `parseConfig` return-shape change broke ~25 existing tests | **CLOSED** | Revision log entry "B1"; Step 3 (return shape unchanged; `__defaultOriginPorts` attached non-enumerably via `Object.defineProperty`); Step 2 ("call to `parseConfig` at `load-config.js:90-94` is **unchanged in shape**"); Step 4 (reads `config.__defaultOriginPorts`); test plan §3 row "`__defaultOriginPorts is invisible to mergeConfigs and toEqual (regression guard for B1 / non-enumerable contract)`". | -| **B2** — DEFAULT_CONFIG fixture not updated | **CLOSED** | Revision log entry "B2"; Step 1 sub-step 4 explicitly calls out the fixture edit at `parse-config.js test:24` and enumerates affected `toEqual` / spread sites (lines 91, 166, 193, 232, 293, 305, 500, 531, 557); test plan §3 row "Modified — `DEFAULT_CONFIG` fixture"; Step 12 inline-fixture verification line. | -| **B3** — phpmyadminPort silent move under defaults-only mode | **CLOSED** | Revision log entry "B3"; Step 5 per-port skip rule under `autoPortMode === 'defaults-only'` (`continue` for `property !== 'port'`); Step 1 plan summary §1 ("phpmyadminPort is **only** auto-resolved under `'all'` mode"); test plan §3 has two regression-detector rows: "`postProcessConfig with autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)`" and "`resolveConfigPorts under autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)`"; Risks §6 "R-PhpmyadminMove (B3)". | -| **F1** — `build-docker-compose-config.js` path ambiguity | **CLOSED** | Revision log entry "F1"; OQ6 resolution (§1) cites the full path `packages/env/lib/runtime/docker/build-docker-compose-config.js:173,267`. I verified the path/file existence — the directory listing of `packages/env/lib/runtime/docker/` contains `build-docker-compose-config.js` and there is no file at `packages/env/lib/build-docker-compose-config.js`. | -| **F2** — Snapshot drift assessment incomplete | **CLOSED** | Revision log entry "F2"; Step 12 explicitly states "no snapshot diffs" expected, with the `grep autoPort` evidence cited. I re-verified — `grep autoPort` against `packages/env/lib/config/test/__snapshots__/config-integration.js.snap` and `packages/env/lib/test/__snapshots__/md5.js.snap` returns zero hits today. (Note: only `config-integration.js.snap` actually exists in `packages/env/lib/config/test/__snapshots__/`; `packages/env/lib/test/__snapshots__/` is empty in this checkout. The plan over-cites a non-existent file but the substantive claim — no `autoPort` in any snapshot — holds.) | -| **F3** — AC4 lacks behavior-level integration test | **CLOSED** | Revision log entry "F3"; test plan §3 row "`loadConfig with CLI autoPort=true and explicit user port falls back when port is busy (AC4 behavior-level)`"; mirrors the AC5 integration test as requested. | -| **F4** — Spinner re-arming pattern under-specified | **CLOSED** | Revision log entry "F4"; Step 6 now cites `start.js:98-101`, `start.js:105-112`, and `start.js:169-193` as precedents (verified — `start.js:98-101` is the `spinner.warn(...); spinner.start();` block for the missing `.wp-env.json` case; `start.js:105-112` is the testsEnvironment deprecation warning; `start.js:169-193` uses `spinner.info(...)` followed by `spinner.start()` in `checkForLegacyInstall`). Test plan asserts call order via `mock.invocationCallOrder`. | -| **F5** — OQ7 truthiness wording inconsistent | **CLOSED** | Revision log entry "F5"; OQ7 resolution in §1 now reads "all non-empty strings are truthy; empty string and `undefined` are falsy" — clean and correct. The implementation is unchanged. | -| **F6** — JSDoc updates not staged for verification | **CLOSED** | Revision log entry "F6"; Step 12 now has a JSDoc-review checklist enumerating all five JSDoc sites (parse-config typedef, load-config, post-process-config, resolve-available-ports, commands/start). | -| **F7** — Sequencing wrong about parallelism | **CLOSED** | Revision log entry "F7"; §4 now shows Step 3 as serial (must precede Step 4) and notes Steps 5/6 are sequential within `resolve-available-ports.js`. The single-implementer ordering and the multi-agent worker plan both reflect this realistically. | -| **F8** — Rollback paragraph missing cached-compose note | **CLOSED** | Revision log entry "F8"; §7 ends with a "Cached compose caveat." paragraph describing the post-fallback port pinned in `~/.wp-env//docker-compose.yml`, the behavior of already-running environments, and the recommended one-line note for the revert PR. | - -Net: **3 of 3 blockers CLOSED, 8 of 8 minor findings CLOSED, 0 NOT CLOSED, 0 PARTIALLY CLOSED.** - ---- - -## Non-enumerable-property design verification (round-2-specific check) - -Plan v2's B1 fix hinges on the claim that attaching `__defaultOriginPorts` as a non-enumerable property to the merged config will be invisible to `mergeConfig` iteration, JSON serialization, and Jest `toEqual`. I verified each leg: - -- **`mergeConfig` iteration.** `packages/env/lib/config/merge-configs.js` line 39: `for ( const option in config ) {` — `for…in` walks own-and-inherited enumerable keys. Non-enumerable own properties are skipped. (Same at line 81: `for ( const option in toMerge )`.) `mergeConfigs` is the only consumer along the parseConfig → loadConfig → postProcessConfig path that iterates the config object's keys generically. Other call sites (e.g. `appendPortToWPConfigs`, `validatePortUniqueness`) read named properties (`config.env`, `config.env[env].port`, etc.) and never iterate the root object. So the non-enumerable property cannot leak into the merge path. -- **JSON serialization.** `JSON.stringify` walks own-enumerable properties; non-enumerable properties are omitted. Plan's regression test "`__defaultOriginPorts is invisible to mergeConfigs and toEqual`" asserts `JSON.parse(JSON.stringify(parsed))` drops the property, locking this in. -- **Jest `toEqual`.** Jest's recursive equality compares own-enumerable properties; non-enumerable own properties are not compared. So `expect( parsed ).toEqual( DEFAULT_CONFIG )` continues to pass even though `parsed` carries the extra hidden property. The same regression test asserts this. -- **Object iteration mechanism in the actual code path.** I confirmed the iteration mechanism inside `mergeConfig` is `for…in`, **not** `Object.keys` / `Object.entries` / spread-into-new-object. (All three of those would also skip non-enumerable properties — `Object.keys`/`Object.entries` walk own-enumerable; object spread `{...config}` also copies only own-enumerable properties — so even a future refactor that switches mechanisms would preserve the contract. But as written today, the mechanism is `for…in`.) - -The trick works as plan v2 claims. No risk of leakage along the existing code paths. - ---- - -## Spot-check of cited line numbers in plan v2 - -I picked five citations across the plan and re-read each in the source. - -1. **`parse-config.js:86-111` `DEFAULT_ENVIRONMENT_CONFIG` with `autoPort: false` at line 93.** Verified — `DEFAULT_ENVIRONMENT_CONFIG` opens at line 86 and closes at line 111; `autoPort: false,` is line 93 verbatim. Step 1 sub-step 1 target. -2. **`parse-config.js test:21-71` inline `DEFAULT_CONFIG` fixture, `autoPort: false` at line 24.** Verified — fixture spans lines 21–70; `autoPort: false,` is at line 24. Step 1 sub-step 4 target. -3. **`load-config.js:96-109` `shouldAutoPort` block.** Verified — lines 96–109 contain the `let portResolver; if ( resolvePorts ) { let shouldAutoPort = …; if ( process.env.CI ) { shouldAutoPort = false; } if ( shouldAutoPort ) { portResolver = createPortResolver( spinner ); } }` block exactly as described in Step 2. -4. **`resolve-available-ports.js:50` `resolve(preferredPort, configPath, strict = false)`.** Verified — line 50 reads `async resolve( preferredPort, configPath, strict = false ) {` with `strict` as the third parameter and a default of `false`. Step 5's claim that the resolver already supports the third arg is correct. -5. **`runtime/docker/build-docker-compose-config.js:173, 267` port interpolation sites.** Verified — line 173 is `` const developmentPorts = `\${WP_ENV_PORT:-${ config.env.development.port }}:80`; `` and line 267 is `` const testsPorts = `\${WP_ENV_TESTS_PORT:-${ config.env.tests.port }}:80`; ``. OQ6 resolution claim correct. - -Bonus spot-checks (not strictly required but useful): -- `cli.js:154-159` `--auto-port` yargs definition: confirmed at lines 154–158, `type: 'boolean'`, no `default` → missing arg is `undefined`. -- `lib/test/cli.js:35-52` tri-state assertions: confirmed (lines 35–52 cover `start` parses with no flag → `autoPort` undefined; with `--auto-port` → `true`; with `--no-auto-port` → `false`). -- `start.js:55-59` `loadConfig({ resolvePorts: true, autoPort, spinner })`: confirmed. -- `stop.js:21-31` consumes cached compose without `resolvePorts`: confirmed (`stop.js:26` calls `loadConfig(path.resolve('.'), customConfigPath)` with no third arg, so `resolvePorts` defaults to `false`). -- `get-config-from-environment-vars.js:36-72` env-var enumeration: confirmed (`WP_ENV_PORT` line 38, `WP_ENV_TESTS_PORT` line 40, plus mysql/phpmyadmin variants — OQ4 resolution scope correct). -- README `autoPort` row at line 609 and "Automatic Port Selection" at lines 620–630: confirmed. -- CHANGELOG `## Unreleased` at line 3: confirmed. - -All cited line numbers in plan v2 match the source. No drift. - ---- - -## Over-correction / new-scope check - -I scanned plan v2 for design that goes beyond what the spec requires: - -- The non-enumerable-property design is the minimal mechanism that satisfies AC10 + R3 / R6 without breaking existing tests. Not over-correction; it is the smallest fix for B1. -- The phpmyadminPort `continue` skip in Step 5 is the smallest fix that preserves today's behavior verbatim. The spec explicitly puts phpmyadminPort out of scope (§5 of the spec), so refusing to extend the resolver to it is *under*-engineering on purpose, not over-correction. Good. -- The new behavior-level integration test for AC4 (F3) is symmetric with the existing AC5 integration test. Not new scope; just covering an already-required AC at the boundary level. -- The JSDoc-review checklist in Step 12 is documentation hygiene tied to the typedef changes the plan already requires; not new scope. -- The cached-compose caveat in §7 is informational text, not new design. - -No over-correction or new-scope detected. - ---- - -## Revision-log drift check - -I read each revision-log entry against the corresponding body section. - -- **B1** ↔ Step 3 (rewritten to attach non-enumerably), Step 2 (parseConfig call shape unchanged), Step 4 (reads `config.__defaultOriginPorts`): consistent. -- **B2** ↔ Step 1 sub-step 4 (fixture edit explicit) and test plan §3 row "Modified — `DEFAULT_CONFIG` fixture": consistent. Revision log also notes the `should accept autoPort as a boolean` test is unaffected by the fixture change because it asserts only `parsed.autoPort` — verified by reading `parse-config.js test:196-207`, the test indeed only asserts `parsed.autoPort` and does not use `DEFAULT_CONFIG`. -- **B3** ↔ Step 5 per-port skip rule and the two regression-detector tests in test plan §3: consistent. -- **F1** ↔ OQ6 resolution in §1 cites the full path: consistent. -- **F2** ↔ Step 12 inline-fixture verification + grep evidence + Step 1 sub-step 4 cross-reference: consistent. -- **F3** ↔ test plan §3 new row for AC4 behavior-level test: consistent. -- **F4** ↔ Step 6 cites the `spinner.warn(...); spinner.start();` precedent in `start.js:98-101` and `start.js:105-112`, plus `spinner.info(...)` precedent in `start.js:169-193`; test plan asserts call order: consistent. -- **F5** ↔ OQ7 wording in §1 cleaned up: consistent. -- **F6** ↔ Step 12 JSDoc-review checklist: consistent. -- **F7** ↔ §4 sequencing diagram showing Step 3 serial and Steps 5/6 sequential: consistent. -- **F8** ↔ §7 "Cached compose caveat." paragraph: consistent. - -No drift between revision log and body. - ---- - -## AC coverage matrix (re-audited for round 2) - -| AC | Plan step(s) | Test(s) | OK? | -|---|---|---|---| -| AC1 | Steps 1, 2, 3, 4, 5 | parse-config provenance tests + integration test "no user autoPort and busy default port falls back via defaults-only mode" + "uses strict mode for non-default-origin ports and non-strict for default-origin ports" | Yes | -| AC2 | Steps 1, 2, 3, 4, 5 | same as AC1 (covers both env keys symmetrically) | Yes | -| AC3 | Steps 1, 2, 3, 4, 5 | "routes user-set port to strict and default-origin port to non-strict" + four parse-config provenance tests (local / env.tests / override / WP_ENV_PORT) + matching WP_ENV_TESTS_PORT test | Yes | -| AC4 | Steps 2, 5 | routing-matrix test + "CLI autoPort=true and user config autoPort=false has CLI win" + new behavior-level integration test "CLI autoPort=true and explicit user port falls back when port is busy" | Yes (F3 closed) | -| AC5 | Steps 1, 2, 5 | "autoPortMode=off" routing test + "loadConfig with autoPort:false in user config skips fallback even on default ports" | Yes | -| AC6 | Step 2 (CI guard) | "CI=1 disables fallback regardless of autoPort:true" + "CI=1 disables fallback even when autoPort is unset" | Yes | -| AC7 | Step 6 | five resolver-notice tests (emits-once-and-re-arms / not-emitted-on-no-move / not-emitted-on-strict-fail / no-console-write-regression / silent-without-spinner) | Yes | -| AC8 | Step 2 + named test | "CI=1 disables fallback regardless of autoPort:true" is the named regression detector | Yes | -| AC9a | Step 4 | "postProcessConfig threads autoPortMode and defaultOriginPorts to resolveConfigPorts" asserts WP_HOME/WP_SITEURL reflect resolved port | Yes | -| AC9b | Manual recipe in §3 | PR test plan recipe enumerated | Yes (manual per spec) | -| AC9c | Inherited from cached compose pattern | None automated; manual per recipe (rationale documented) | Yes (manual per spec) | -| AC10 | Step 12 + back-compat tests | Full-suite green; B1 / B2 fixes mean existing tests now stay green | Yes (B1 + B2 closed) | -| AC11 | Steps 1, 2, 7 | "should accept autoPort as a tri-state (null default, true, false)" + integration test asserting tri-state survives end-to-end | Yes | - -All ACs covered with at least one automated test or a documented manual verification per spec. - ---- - -## Verification of required-check items from the team prompt - -1. **Each round-1 finding now closed.** All B1, B2, B3 and F1–F8 are CLOSED with cited sections (table above). -2. **Non-enumerable trick verified in actual code path.** `merge-configs.js:39` and `:81` use `for…in` (verified by reading the file) and `for…in` skips non-enumerable properties (well-defined JS). The plan also locks the contract with a regression test that asserts `propertyIsEnumerable === false` and `JSON.parse(JSON.stringify(parsed))` drops the property. -3. **Five line-number spot-checks.** All five (`parse-config.js:86-111`/`:93`, `parse-config.js test:21-71`/`:24`, `load-config.js:96-109`, `resolve-available-ports.js:50`, `runtime/docker/build-docker-compose-config.js:173`/`:267`) match the source exactly. -4. **Over-correction / new scope.** None detected. The B1/B2/B3 fixes are minimal; the new AC4 test is symmetric with an existing AC5 test; phpmyadminPort is intentionally left out of scope as the spec requires. -5. **Revision-log drift.** None detected. Each log entry maps cleanly to a body change. - ---- - -## Minor observations (non-blocking) - -These are not gates; documenting them so the implementer is not surprised. - -- **N1.** Step 12 mentions running `grep` against `packages/env/lib/test/__snapshots__/md5.js.snap`; that file does not exist in the current checkout (the directory `packages/env/lib/test/__snapshots__/` is empty). The substantive claim (no `autoPort` references in any snapshot) holds because the only existing snapshot file (`packages/env/lib/config/test/__snapshots__/config-integration.js.snap`) contains no `autoPort`. The plan slightly over-cites; this does not affect correctness. -- **N2.** The plan uses a non-enumerable, non-writable, non-configurable property descriptor (`Object.defineProperty(merged, '__defaultOriginPorts', { value: …, enumerable: false, writable: false, configurable: false })`). That is correct and safe, but the implementer should be aware that any future code path that tries to overwrite `merged.__defaultOriginPorts` will silently fail in non-strict mode and throw in strict mode. The plan does not have such an overwrite path, and the wp-env package opts in to `'use strict'` at the file level (e.g. `parse-config.js:1`), so an accidental overwrite would throw — which is actually the desired behavior. No action required; just noting for the implementer. - ---- - -## Verdict - -``` -APPROVED -``` - -All three round-1 blockers (B1, B2, B3) are closed with concrete plan changes that are grounded in re-verified source citations. All eight minor findings (F1–F8) are closed. The non-enumerable-property design works as the plan claims — the `for…in` iteration in `merge-configs.js` is well-defined to skip non-enumerable own properties, Jest `toEqual` and `JSON.stringify` likewise ignore them, and a dedicated regression test locks the contract. Spot-checks of five cited line numbers all matched the source. No over-correction, no new scope, no revision-log drift detected. - -The plan is ready to drive implementation. diff --git a/.pipelines/49843-wp-env-default-port-fallback/plan.md b/.pipelines/49843-wp-env-default-port-fallback/plan.md deleted file mode 100644 index 58ef8e185d46a3..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/plan.md +++ /dev/null @@ -1,348 +0,0 @@ -# Phase 2 — Implementation plan - -Pipeline: `49843-wp-env-default-port-fallback` -Spec: `spec.md` (round 2 APPROVED). -Scope: `packages/env/` only. - ---- - -## Revision log - -Round 2 revisions, in response to `plan-review-1.md`: - -- **B1 (blocker)** — `parseConfig` return shape change broke ~25 existing tests. Resolved by changing the design: instead of returning `{ config, defaultOriginPorts }`, attach `defaultOriginPorts` to the returned config object as a **non-enumerable** property named `__defaultOriginPorts` (a `Set`). Existing destructurings, `expect( parsed ).toEqual( DEFAULT_CONFIG )` calls, and `Object.keys` / `for…in` iteration in `mergeConfig` (`merge-configs.js:39,81`) all skip non-enumerable properties, so the existing test suite is unchanged. The plan now uses this single approach (Step 3 rewritten); the consumer in `load-config.js` reads `config.__defaultOriginPorts` (Step 2 updated), and `postProcessConfig` reads it from the same config object (Step 4 updated). This also removes the need to change the call shape in `load-config.js:90-94`. -- **B2 (blocker)** — `DEFAULT_ENVIRONMENT_CONFIG.autoPort` flip from `false` to `null` breaks the `DEFAULT_CONFIG` fixture at `parse-config.js:21-71` (line 24) which is consumed by `toEqual( DEFAULT_CONFIG )` and spread-based assertions throughout the file. Resolved by making "update the test fixture" an explicit sub-step of Step 1 (point 4) AND by enumerating the affected assertions in the test plan §3 row "Modified — `DEFAULT_CONFIG` fixture". Also the modified test `should accept autoPort as a boolean` (line 196) is unaffected by this fixture change because it asserts only `parsed.autoPort` (not `toEqual( DEFAULT_CONFIG )`). -- **B3 (blocker)** — `phpmyadminPort` would silently auto-move under `defaults-only` mode. Resolved by extending the strict-routing rule in `resolveConfigPorts` (Step 5) so that under `autoPortMode='defaults-only'`, **only HTTP ports (`property === 'port'`) get any non-strict treatment**; for `phpmyadminPort` the resolver is skipped entirely (no resolver call at all), preserving today's behavior verbatim — today phpmyadminPort is only resolved when `--auto-port` is set, which corresponds to the new `autoPortMode='all'` mode. This avoids both the silent-move regression and any need to thread provenance for phpmyadminPort. Spec is unchanged (phpmyadminPort is out of scope per §5). -- **F1 (minor)** — `build-docker-compose-config.js` path is `packages/env/lib/runtime/docker/build-docker-compose-config.js` (verified: the file at `packages/env/lib/build-docker-compose-config.js` does NOT exist; only the one under `runtime/docker/` and its test at `packages/env/lib/test/build-docker-compose-config.js`). All references in the plan now use the full path. -- **F2 (minor)** — Snapshot drift expectation is corrected: `grep autoPort` against `packages/env/lib/test/__snapshots__/md5.js.snap` and `packages/env/lib/config/test/__snapshots__/config-integration.js.snap` returns zero hits, so no `autoPort`-related snapshot churn is expected. The real fixture risk (the inline `DEFAULT_CONFIG` at `parse-config.js:21-71`, line 24) is now called out in Step 1 sub-step 4 and re-confirmed in Step 12. -- **F3 (minor)** — Added an AC4 behavior-level integration test (`loadConfig with CLI autoPort=true and explicit user port falls back when port is busy`) in `config-integration.js`, matching the symmetry of the AC5 integration test. -- **F4 (minor)** — Step 6 now cites the existing `start.js:98-101` and `start.js:105-112` precedent of `spinner.warn(...); spinner.start();` and the test plan asserts call order (`spinner.info` before `spinner.start`). -- **F5 (minor)** — OQ7 wording is cleaned up; the resolution now reads correctly: "all non-empty strings are truthy; empty string and `undefined` are falsy". The implementation is unchanged (`if ( process.env.CI )`). -- **F6 (minor)** — Step 12 now includes a JSDoc-review checklist line (verify the `WPRootConfigOptions` typedef in `parse-config.js`, the `loadConfig` JSDoc in `load-config.js`, and the `start` JSDoc in `commands/start.js` reflect the new tri-state). -- **F7 (minor)** — Sequencing diagram in §4 corrected: step 3 is serial (must precede step 4), and step 6 cannot run literally in parallel with step 5 because both edit the same file. Updated to show realistic ordering for both single-implementer and multi-agent scenarios. -- **F8 (minor)** — §7 Rollback paragraph extended with a one-sentence note about cached `docker-compose.yml` files retaining post-fallback ports across a revert. - ---- - -## 1. Plan summary - -The chosen design shape: extend the existing `--auto-port` / `autoPort` machinery (PR #74472) with two narrow tweaks rather than introduce parallel code paths. - -1. **Tri-state `autoPort`.** Change `DEFAULT_ENVIRONMENT_CONFIG.autoPort` from `false` to `null` so that the "unset" state survives merging. CLI parsing already preserves `undefined`/`true`/`false` (verified — see OQ-resolutions). `load-config.js` becomes the single point where the tri-state is interpreted into a runtime decision: `'all'` (today's PR #74472 behavior) | `'defaults-only'` (new behavior) | `'off'` (explicit opt-out). -2. **Per-port "user-set" provenance, attached as a non-enumerable property.** Track which environment ports came from `DEFAULT_ENVIRONMENT_CONFIG` versus from any user source (root `.wp-env.json`, `.wp-env.override.json`, env vars). The mechanism is a small `Set` (`__defaultOriginPorts`) built in `parseConfig` (in `parse-config.js`), attached to the returned config via `Object.defineProperty(config, '__defaultOriginPorts', { value: …, enumerable: false })`. `mergeConfig` in `merge-configs.js:39,81` iterates with `for ( const option in config )` which excludes non-enumerable properties, so existing tests' `toEqual` and destructure expectations are untouched. `loadConfig` reads `config.__defaultOriginPorts` and threads it into `postProcessConfig` → `resolveConfigPorts`. `resolveConfigPorts` then decides per-port whether to use the existing `findAvailablePort` (auto-fallback) or the existing `isPortAvailable` strict path, based on `(autoPortMode, isDefaultOrigin, property)`. - -The port resolver is invoked from `loadConfig` whenever EITHER `autoPortMode === 'all'` (today's PR #74472 contract) OR `autoPortMode === 'defaults-only'` (the new behavior). In the new mode, only HTTP ports (`property === 'port'`) participate in the routing decision; `phpmyadminPort` is **only** auto-resolved under `'all'` mode (preserving today's behavior verbatim). The `process.env.CI` guard stays in `load-config.js` and short-circuits both modes by forcing `'off'`. The "moved port" notice (R11/AC7) is added to `createPortResolver` so it fires only when the resolved port differs from the preferred port and goes through the same `spinner` instance the resolver already accepts. - -No new top-level config option is introduced. No new CLI flag is introduced. No package boundary is crossed. `appendPortToWPConfigs` is unchanged: it already consumes `config.env[env].port`, which now reflects the resolved port (R8 / AC9a). For other commands (R8 / AC9c), the existing pattern of writing the resolved port into the cached `docker-compose.yml` during `start` already covers `stop`/`destroy`/`logs`/`run` because they operate against the cached compose file by container name; no additional port re-resolution is needed in those commands. - -### Resolution of OQ1–OQ7 (each cited to source) - -- **OQ1 — Per-environment `autoPort`.** Resolved: root-only. `parse-config.js:481-493` lists `autoPort` in the switch's case-block of `parseEnvironmentConfig` (specifically `case 'autoPort':` at line 483), allowed only when `options.rootConfig` is true. `parse-config.js:390-397` parses it only on the root config path. Plan inherits root-only and does not extend it. -- **OQ2 — Provenance tracking mechanism.** Resolved: a `Set` (`defaultOriginPorts`) built in `parseConfig` (in `parse-config.js`) and attached to the returned config object as a non-enumerable property `__defaultOriginPorts`. The Set is populated as the inverse of "any non-default config layer set this key" — see step 3. Citation: `parse-config.js:130-167` shows the merge order (`localConfig`, `overrideConfig`, `defaultConfig` from `getDefaultConfig`, `environmentVarOverrides`); each non-default layer can be inspected for whether it provided `port`/`testsPort`/`env.development.port`/`env.tests.port`. The non-enumerable approach is chosen so `mergeConfig` (which iterates via `for…in` at `merge-configs.js:39,81`) does not see it during merging and so existing tests' `toEqual(DEFAULT_CONFIG)` assertions remain unchanged. -- **OQ3 — Multiple override layers.** Resolved: any non-default layer (`localConfig`, `overrideConfig`, `environmentVarOverrides`) that sets the port marks the port as "user-set". Citation: same `parse-config.js:130-167` merge sequence; environment vars are produced by `getEnvironmentVarOverrides` at `parse-config.js:284-344` and we inspect the same struct that already exists. -- **OQ4 — env-var sources for ports.** Resolved: enumerated from `get-config-from-environment-vars.js:36-72` — the user-set port-yielding env vars are `WP_ENV_PORT`, `WP_ENV_TESTS_PORT`, `WP_ENV_MYSQL_PORT`, `WP_ENV_TESTS_MYSQL_PORT`, `WP_ENV_PHPMYADMIN_PORT`, and `WP_ENV_TESTS_PHPMYADMIN_PORT`. Of these, only `WP_ENV_PORT` and `WP_ENV_TESTS_PORT` are in scope of this feature (HTTP ports). `mysqlPort` is out of scope per spec §5; `phpmyadminPort` is out of scope per spec §5 and per the B3 resolution above (see Step 5). -- **OQ5 — Behavior when no upward port is available.** Resolved: re-use existing failure mode. `port-utils.js:51-80` already throws `Error('No available port found in range ${startPort}-${maxPort}.')` and that error is wrapped in `resolve-available-ports.js:84-87` into `Could not find available port for : ...`. Plan does not change this; the error already surfaces to the spinner via `withSpinner` in `cli.js:24-93` (rejection branch at lines 46-92). -- **OQ6 — Re-resolution on every `start`; downstream commands consume cached compose.** Resolved: confirmed by tracing — `start.js:55-59` calls `loadConfig({ resolvePorts: true, ... })`, `post-process-config.js:35-37` writes the resolved port into `config.env[env].port` (and therefore into the env-merged config consumed by `appendPortToWPConfigs` at `post-process-config.js:39`), `runtime/docker/build-docker-compose-config.js:173,267` interpolates that port into the cached `docker-compose.yml`, and downstream commands such as `stop.js:21-31` operate on `dockerComposeConfigPath` by container name (no port re-resolution). So a stale running environment from a prior wp-env version is unaffected until the next `start`, which re-resolves freshly. No persisted-state file is needed. -- **OQ7 — `CI` truthiness.** Resolved: inherit verbatim from `load-config.js:102-104` — `if ( process.env.CI )`. JavaScript truthy semantics: any non-empty string is truthy (so `"true"`, `"1"`, `"false"`, `"0"`, etc. are all truthy as strings); `undefined` and the empty string are falsy. The plan does not redefine this; it relies on the existing one-liner. - -No OQs are deferred to "the implementer will figure it out". Zero blockers. - ---- - -## 2. Steps - -### Step 1 — Make `autoPort` tri-state at the config-default layer - -- **Goal.** Stop collapsing `undefined → false` at the default-config layer so that "unset" survives merging and is observable inside `load-config.js`. -- **Files touched.** - - `packages/env/lib/config/parse-config.js` - - `packages/env/lib/config/test/parse-config.js` (fixture only — see sub-step 4) -- **Change description.** - 1. In `DEFAULT_ENVIRONMENT_CONFIG` (currently `parse-config.js:86-111`, specifically line 93), change `autoPort: false` to `autoPort: null`. `null` is the sentinel for "user did not set this" (chosen over `undefined` so the key stays present after `mergeConfigs` for snapshot/typedef stability). - 2. In the `WPRootConfigOptions` typedef comment block (`parse-config.js:32-44`, specifically the `@property` line at line 38), update the `autoPort` `@property` line to `boolean|null` and refine the description to "Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports)." - 3. In `parseRootConfig`, the existing block at `parse-config.js:390-397` already only assigns `parsedConfig.autoPort` when `rawConfig.autoPort !== undefined`; no change there. The change at the default layer is sufficient because the merge in `mergeConfigs` will now leave a non-user-set `autoPort` as `null`. - 4. **Update the inline test fixture `DEFAULT_CONFIG` in `packages/env/lib/config/test/parse-config.js:21-71`, line 24: change `autoPort: false` to `autoPort: null`.** This fixture is `toEqual()`-compared at `parse-config.js test:91, 193, 232, 293, 305` and is used as a spread base at `parse-config.js test:166, 232, 305, 500, 531, 557` (`...DEFAULT_CONFIG`, `...DEFAULT_CONFIG.env.development`). The single fixture edit fixes all of those in one step. The named test `'should accept autoPort as a boolean'` at `parse-config.js test:196-207` does NOT use `DEFAULT_CONFIG` and is updated separately in Step 10 (it must additionally assert that the **default** is `null`). -- **Spec ACs covered.** AC11, AC1, AC2, AC5 (foundational — all rely on this). -- **Depends on.** None. - -### Step 2 — Reinterpret `autoPort` in `loadConfig` as tri-state - -- **Goal.** Replace the binary on/off interpretation in `load-config.js` with a tri-state interpretation, and decide whether to invoke the port resolver. -- **Files touched.** - - `packages/env/lib/config/load-config.js` -- **Change description.** - - At `load-config.js:96-109`, replace the existing block that computes `shouldAutoPort` with a new computation that yields one of three values for an internal variable `autoPortMode`: `'all'` (today's PR #74472 behavior — `true`), `'defaults-only'` (new behavior — `null`/`undefined`), or `'off'` (explicit opt-out — `false`). Source precedence is unchanged: CLI `autoPort` parameter beats `config.autoPort`. - - Mapping: CLI `true` → `'all'`; CLI `false` → `'off'`; CLI `undefined` AND `config.autoPort === true` → `'all'`; CLI `undefined` AND `config.autoPort === false` → `'off'`; CLI `undefined` AND (`config.autoPort === null` or `undefined`) → `'defaults-only'`. - - The existing `process.env.CI` guard (lines 102-104) is rewritten to force `autoPortMode = 'off'` when CI is truthy. (Same observable behavior, slightly different shape so the guard sits in front of the resolver gate.) - - Always create a `portResolver` when `resolvePorts` is true and `autoPortMode !== 'off'`. (Today the resolver is only created when `shouldAutoPort` is truthy. The new resolver still behaves correctly with no default-origin ports — see step 5 for the per-port routing — but it must exist so `defaults-only` mode can fire on default HTTP ports.) - - Read `config.__defaultOriginPorts` from the parsed config (a `Set`; see Step 3) — fall back to `new Set()` if the property is absent. Pass it through to `postProcessConfig` along with `autoPortMode`. The signature of `postProcessConfig` is extended to accept `{ portResolver, autoPortMode, defaultOriginPorts }` (see step 4). - - Update the JSDoc on `loadConfig` to describe the new tri-state. - - The call to `parseConfig` at `load-config.js:90-94` is **unchanged in shape** — `parseConfig` still returns the merged config object directly (the `__defaultOriginPorts` is a non-enumerable property attached to that object). -- **Spec ACs covered.** AC1, AC2, AC3, AC4, AC5, AC6, AC11. -- **Depends on.** Step 1. - -### Step 3 — Track default-origin port provenance in `parseConfig` - -- **Goal.** Build a `Set` (`defaultOriginPorts`) listing port keys whose value came from `DEFAULT_ENVIRONMENT_CONFIG` and was NOT overridden by any user-supplied source (root or override JSON, or environment variable). Attach it to the returned config object as a non-enumerable property. -- **Files touched.** - - `packages/env/lib/config/parse-config.js` -- **Change description.** - - In `parseConfig` (`parse-config.js:124-168`), after computing `localConfig`, `overrideConfig`, and `environmentVarOverrides` (lines 129-158) and BEFORE the final `return mergeConfigs(...)` at lines 162-167, build a `defaultOriginPorts` Set. - - Implement as a small helper `function computeDefaultOriginPorts(localConfig, overrideConfig, envVarOverrides)` returning a `Set` containing zero or more of `'development.port'` and `'tests.port'`. - - For each of the two HTTP ports (`'development.port'`, `'tests.port'`), the port is "default-origin" iff none of the following provided it: - - `localConfig?.port` (root-level, hoisted to development by `mergeRootToEnvironments` later). - - `localConfig?.testsPort` (root-level, hoisted to tests). - - `localConfig?.env?.development?.port` / `localConfig?.env?.tests?.port` (env-specific). - - The same five paths on `overrideConfig`. - - `envVarOverrides.port` (set by `getEnvironmentVarOverrides` at `parse-config.js:301-304` when `WP_ENV_PORT` is defined; same for `testsPort` at lines 316-319). - - Note: `envVarOverrides.env.development.port` and `envVarOverrides.env.tests.port` are also set in those same blocks; either one being present is sufficient signal. - - Capture the merge result in a local `merged` variable instead of returning it directly, then attach the Set: - - `Object.defineProperty(merged, '__defaultOriginPorts', { value: defaultOriginPortsSet, enumerable: false, writable: false, configurable: false })`. - - Return `merged`. - - Why non-enumerable: `mergeConfig` in `merge-configs.js` iterates via `for ( const option in ... )` at lines 39 and 81. Non-enumerable properties are skipped by `for…in`. `JSON.stringify` and `Object.keys` also skip them. `expect( parsed ).toEqual( DEFAULT_CONFIG )` (Jest) compares own-enumerable properties only. Therefore attaching `__defaultOriginPorts` does not affect `mergeConfig`, JSON serialization, or Jest equality checks. (Verified semantics; see existing tests at `packages/env/lib/config/test/parse-config.js:91, 193, 232, 293, 305, 506, 537, 560`.) - - The `parseConfigFile` and `parseRootConfig` internals do not need to know about provenance; only `parseConfig` itself does, because it has visibility into all four sources at once. - - `getConfigFilePath` exports — unchanged. -- **Spec ACs covered.** AC1, AC2, AC3, AC5. -- **Depends on.** Step 1 (the default `autoPort` change is independent, but Step 3 must run before Step 4 can consume its output). - -### Step 4 — Thread `defaultOriginPorts` through `postProcessConfig` - -- **Goal.** Hand the per-port provenance to the place that decides `findAvailablePort` vs. `isPortAvailable` strict. -- **Files touched.** - - `packages/env/lib/config/post-process-config.js` -- **Change description.** - - Update the exported `postProcessConfig` signature from `(config, { portResolver })` (currently `post-process-config.js:24-27`) to `(config, { portResolver, autoPortMode = 'off', defaultOriginPorts = new Set() })`. Defaults preserve current behavior for the existing call sites that do not opt in. - - In the body, where the existing call `await resolveConfigPorts( config, portResolver )` is at line 36, change it to `await resolveConfigPorts( config, portResolver, { autoPortMode, defaultOriginPorts } )`. - - No other behavior in `postProcessConfig` changes. `mergeRootToEnvironments`, `appendPortToWPConfigs`, and `validatePortUniqueness` are untouched. - - Update the JSDoc to describe the two new options. -- **Spec ACs covered.** AC1, AC2, AC3, AC5, AC9a. -- **Depends on.** Step 3. - -### Step 5 — Per-port strict/non-strict routing in `resolveConfigPorts` - -- **Goal.** Use the per-port provenance + tri-state to decide, for each port, whether to call the existing `findAvailablePort` (auto-fallback) path, the existing `isPortAvailable` strict path, or skip the port entirely (preserving today's behavior). -- **Files touched.** - - `packages/env/lib/resolve-available-ports.js` -- **Change description.** - - Update the exported `resolveConfigPorts(config, portResolver)` signature (currently `resolve-available-ports.js:100`) to `resolveConfigPorts(config, portResolver, { autoPortMode = 'off', defaultOriginPorts = new Set() } = {})`. - - Inside the loop over `PORT_DEFINITIONS` (currently `resolve-available-ports.js:101-127`), add a small early-exit and a `strict` decision: - - **Per-port skip rule** (preserves today's behavior for `phpmyadminPort` under the new mode): - - If `autoPortMode === 'defaults-only'` AND `property !== 'port'` (i.e. `phpmyadminPort`): `continue` — skip this port entirely. Today phpmyadminPort is only resolved when `--auto-port` is on (because the resolver itself is only created in that case); under `'defaults-only'` we keep that exact behavior verbatim by skipping the port. (B3 resolution.) - - **Strict decision** for the remaining ports: - - If `autoPortMode === 'off'` → `strict = true`. (Note: in this branch the resolver is never created in `load-config.js`, so this case is unreachable in production. We still set it defensively for correctness when the function is unit-tested.) - - If `autoPortMode === 'all'` → `strict = false`. (Today's PR #74472 behavior, including the existing `phpmyadminPort` non-strict path which we preserve here when the property is `phpmyadminPort` because the skip rule above does not apply.) - - If `autoPortMode === 'defaults-only'` AND `property === 'port'`: `strict = ! defaultOriginPorts.has( '${env}.port' )`. That is, default-origin ports get auto-fallback (strict=false); user-set ports stay strict (AC1, AC2, AC3). - - Pass `strict` as the third argument to `portResolver.resolve(preferredPort, configPath, strict)` — the resolver already supports this third parameter at `resolve-available-ports.js:50`. - - `createPortResolver` is updated separately in step 6 for the messaging contract; the `resolve` signature here is unchanged. - - The `PREFERRED_PORTS` table (`resolve-available-ports.js:23-26`) and the lookup `currentValue ?? PREFERRED_PORTS[ key ]` (line 113) are unchanged. - - Update the JSDoc on `resolveConfigPorts` to document the two new options. -- **Spec ACs covered.** AC1, AC2, AC3, AC4, AC5, AC9a. -- **Depends on.** Steps 2, 3, 4. - -### Step 6 — Add the "moved port" notice to `createPortResolver` - -- **Goal.** Implement R11 / AC7: emit an informational message via the existing spinner, only when the resolved port differs from the preferred port, with no new flag and no separate output channel. -- **Files touched.** - - `packages/env/lib/resolve-available-ports.js` -- **Change description.** - - Inside `createPortResolver`'s returned `resolve` method, in the non-strict branch (currently `resolve-available-ports.js:74-87`), after `findAvailablePort` resolves to `resolvedPort` and BEFORE `usedPorts.push( resolvedPort )` (line 80), compare `resolvedPort` to `preferredPort`. When they differ AND `spinner` exists, call: - - `spinner.info( 'Port ${preferredPort} (${configPath}) was busy; using ${resolvedPort} instead.' )` (exact message format chosen for clarity; the test in step 11 asserts a regex containing both port numbers and the string "busy"). - - Followed by `spinner.start()` to re-arm the spinner. Precedent: `start.js:98-101` and `start.js:105-112` use this exact `spinner.warn(...); spinner.start();` pattern; `start.js:169-193` uses `spinner.info(...)` followed by `spinner.start()`. - - The strict branch (lines 56-72) is unchanged — when the port is busy in strict mode, the existing `throw new Error(...)` at lines 65-69 already surfaces via the spinner's `fail` path in `withSpinner` (`cli.js:46-92`). No "moved" notice fires on the strict path (matches AC7's "only when a fallback actually occurred"). - - When `spinner` is undefined (test path), suppress the notice silently. Implementation guard: `if ( spinner && resolvedPort !== preferredPort ) { ... }`. - - The notice MUST go through the same `spinner` instance that `--auto-port` already uses today (the one passed into `createPortResolver(spinner)`); do NOT introduce a new logger, console call, or stream. AC7's "regression detectable" clause means the test in step 11 asserts the call goes through the spinner (`spinner.info` was called) and that there is **no** `console.log` / `console.info` / `process.stdout.write` invocation. -- **Spec ACs covered.** AC1, AC2, AC4, AC7. -- **Depends on.** Step 5 (sequencing — both edit `resolve-available-ports.js`; step 5 lands first, then step 6 modifies `createPortResolver` in the same file). - -### Step 7 — Wire `start` to pass tri-state and provenance to `loadConfig` - -- **Goal.** Surface the new options on the call-site, and verify nothing else needs to change in `start.js`. -- **Files touched.** - - `packages/env/lib/commands/start.js` -- **Change description.** - - No public signature change. The existing `loadConfig( path.resolve('.'), customConfigPath, { resolvePorts: true, autoPort, spinner })` call at `start.js:55-59` already passes `autoPort` from yargs (which is `undefined` / `true` / `false`); the new tri-state interpretation in `load-config.js` (step 2) consumes that directly. Confirm by tracing: `cli.js:154-158` defines `--auto-port` as `type: 'boolean'` with no `default`, so missing → `undefined`; explicit `--auto-port` → `true`; explicit `--no-auto-port` → `false`. (Verified in `lib/test/cli.js:35-52`.) - - Update the JSDoc on `start` (`start.js:21-34`, specifically line 32 for `options.autoPort`) to describe `autoPort` as tri-state. -- **Spec ACs covered.** AC11 (CLI boundary preservation), AC1–AC6 (consumer correctness). -- **Depends on.** Step 2. - -### Step 8 — Documentation: README - -- **Goal.** Document the new default behavior and the `"autoPort": false` opt-out. -- **Files touched.** - - `packages/env/README.md` -- **Change description.** - - In the config table at `README.md:609`, update the `"autoPort"` row: change Default from `false` to `null` and rewrite the Description to "Tri-state: when unset (`null`), default ports `8888`/`8889` automatically fall back to the next available port if busy; explicitly `true` enables fallback for all ports including user-set ones; explicitly `false` disables fallback even on default ports." - - In the "Automatic Port Selection" section at `README.md:620-630`, rewrite to reflect the new contract: (a) by default, when the contributor has not pinned a port, busy default ports auto-fall-back upward; (b) explicitly configured ports remain strict unless `--auto-port` / `"autoPort": true` is set; (c) `"autoPort": false` is the opt-out for the default-fallback behavior; (d) `CI=1` continues to disable all auto-fallback. - - Keep the existing example `wp-env start --auto-port` and explain it still applies when contributors want explicit ports to also auto-fall-back. -- **Spec ACs covered.** AC documentation in spec §3 R14. -- **Depends on.** Step 2 (so that the documented semantics match implementation). - -### Step 9 — Documentation: CHANGELOG - -- **Goal.** List the user-visible change under the next unreleased version. -- **Files touched.** - - `packages/env/CHANGELOG.md` -- **Change description.** - - Under the existing `## Unreleased` heading at `CHANGELOG.md:3`, add a `### New Features` (or `### Enhancements`) subsection describing: "Default ports `8888` and `8889` now automatically fall back to the next available port when busy and the contributor has not set a port explicitly. Set `"autoPort": false` in `.wp-env.json` to opt out, or `CI=1` for CI runs." Reference issue `#49843`. - - Do NOT add a "breaking change" entry — the change is additive on the unset-port path; explicit ports are unchanged. -- **Spec ACs covered.** AC documentation in spec §3 R14. -- **Depends on.** Step 8 (so wording is consistent). - -### Step 10 — Unit tests for tri-state and provenance plumbing - -- **Goal.** Add automated tests covering AC1, AC2, AC3, AC4, AC5, AC6, AC9a, AC11. -- **Files touched.** - - `packages/env/lib/config/test/parse-config.js` - - `packages/env/lib/config/test/post-process-config.js` - - `packages/env/lib/config/test/config-integration.js` - - `packages/env/lib/test/resolve-available-ports.js` -- **Change description.** See test plan §3 below for the table. The DEFAULT_CONFIG fixture edit is in Step 1 (sub-step 4), not here. -- **Spec ACs covered.** AC1, AC2, AC3, AC4, AC5, AC6, AC8, AC9a, AC11. -- **Depends on.** Steps 1–7. - -### Step 11 — Unit tests for the "moved port" notice - -- **Goal.** Lock in AC7's "same output mechanism" contract such that introducing a new output path is a detectable regression. -- **Files touched.** - - `packages/env/lib/test/resolve-available-ports.js` -- **Change description.** See test plan §3 below. -- **Spec ACs covered.** AC7. -- **Depends on.** Step 6. - -### Step 12 — Snapshot, fixture, and JSDoc verification sweep - -- **Goal.** Verify snapshot churn is intentional and limited; verify all fixture and JSDoc updates landed. -- **Files touched.** - - `packages/env/lib/config/test/__snapshots__/config-integration.js.snap` (only if it changes — which is NOT expected; see verification below). -- **Change description.** - - Run `npm run test:unit -- packages/env` after steps 1–11 land. **Expectation:** no snapshot diffs (verified — `grep autoPort packages/env/lib/config/test/__snapshots__/config-integration.js.snap` and `… packages/env/lib/test/__snapshots__/md5.js.snap` both return zero hits today, so flipping `autoPort: false → null` does not affect any serialized snapshot). If a snapshot DOES change unexpectedly, inspect the diff before accepting; a sudden snapshot diff after this PR would indicate a regression and should be investigated rather than blanket-accepted with `--updateSnapshot`. AC10 requires this discipline. - - **Inline-fixture verification.** Confirm `DEFAULT_CONFIG.autoPort === null` in `packages/env/lib/config/test/parse-config.js:24` (changed in Step 1 sub-step 4). Confirm no other inline fixtures contain `autoPort: false` that need updating: `grep -rn "autoPort" packages/env/lib/`. Expected matches: `parse-config.js` (default), `parse-config.js test` (one fixture line + the named test + the `non-boolean autoPort` validation test), `load-config.js` (the new tri-state computation), `post-process-config.js` (the new option threading), `resolve-available-ports.js` (the new routing), `config-integration.js` (new integration tests). No other matches expected. - - **JSDoc verification checklist.** Confirm the JSDoc updates from steps 1, 2, 5, 7 landed: - - `parse-config.js` `WPRootConfigOptions` typedef line for `autoPort` reads `boolean|null` with the tri-state description. - - `load-config.js` `loadConfig` JSDoc describes `autoPort` as tri-state. - - `post-process-config.js` `postProcessConfig` JSDoc describes the two new options (`autoPortMode`, `defaultOriginPorts`). - - `resolve-available-ports.js` `resolveConfigPorts` JSDoc describes the two new options. - - `commands/start.js` `start` JSDoc line 32 describes `autoPort` as tri-state. -- **Spec ACs covered.** AC10. -- **Depends on.** All prior steps. - ---- - -## 3. Test plan - -| Test file | New / Modified | `it` name | Spec AC | Description | -|---|---|---|---|---| -| `packages/env/lib/config/test/parse-config.js` | **Modified — fixture** | `DEFAULT_CONFIG` fixture at line 21-71 | AC11 | Change `autoPort: false` to `autoPort: null` at line 24. Single edit; cascades through all `toEqual( DEFAULT_CONFIG )` and `...DEFAULT_CONFIG`-spread assertions (lines 91, 166, 193, 232, 293, 305, 500, 531, 557). Done in Step 1 sub-step 4. | -| `packages/env/lib/config/test/parse-config.js` | Modified | `should accept autoPort as a boolean` (line 196) | AC11 | Augment the existing assertion (`expect( parsed.autoPort ).toEqual( true )`) with a second case asserting that when no autoPort is set in any source, `parsed.autoPort` is `null` (the new default). Update the test name to `should accept autoPort as a tri-state (null default, true, false)`. | -| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig attaches __defaultOriginPorts as a non-enumerable Set with both http ports when no user config sets them` | AC1, AC2 | With `readRawConfigFile.mockResolvedValue(null)` and no env vars set, the returned config has a `__defaultOriginPorts` Set containing exactly `'development.port'` and `'tests.port'`. Also assert `Object.propertyIsEnumerable.call(parsed, '__defaultOriginPorts')` is `false`. | -| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits development.port from __defaultOriginPorts when local config sets root port` | AC3 | Local config sets `port: 9000`; Set contains `'tests.port'` but NOT `'development.port'`. | -| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits tests.port from __defaultOriginPorts when local config sets env.tests.port` | AC3 | Local config sets `env.tests.port: 9001`; Set contains `'development.port'` but NOT `'tests.port'`. | -| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits development.port from __defaultOriginPorts when override config sets port` | AC3 | `.wp-env.override.json` sets `port: 9000`; Set contains `'tests.port'` but NOT `'development.port'`. | -| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits development.port from __defaultOriginPorts when WP_ENV_PORT is set` | AC3 (R3 env-var clause), OQ4 | Set `process.env.WP_ENV_PORT = '4321'` before call (the existing `afterEach` at line 79-86 already cleans this up); assert Set lacks `'development.port'`. | -| `packages/env/lib/config/test/parse-config.js` | New | `parseConfig omits tests.port from __defaultOriginPorts when WP_ENV_TESTS_PORT is set` | AC3 (R3 env-var clause), OQ4 | Mirror of above for `WP_ENV_TESTS_PORT`. | -| `packages/env/lib/config/test/parse-config.js` | New | `__defaultOriginPorts is invisible to mergeConfigs and toEqual (regression guard for B1 / non-enumerable contract)` | AC10 | Construct a fresh `parseConfig` result, run `JSON.parse(JSON.stringify(parsed))`, assert `__defaultOriginPorts` is absent in the round-trip, AND assert `expect(parsed).toEqual(DEFAULT_CONFIG)` still passes (i.e. `toEqual` does not see `__defaultOriginPorts`). This is the regression detector for any future change that flips the property to enumerable. | -| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig threads autoPortMode and defaultOriginPorts to resolveConfigPorts` | AC9a | Use a fake `portResolver` whose `resolve` is a `jest.fn()` returning `8890`; pass `{ portResolver, autoPortMode: 'defaults-only', defaultOriginPorts: new Set([ 'development.port', 'tests.port' ]) }` and a config with `env.development.port: 8888`, `env.tests.port: 8889`, plus `config: { WP_HOME: 'http://localhost', WP_SITEURL: 'http://localhost' }`. Assert `portResolver.resolve` is called with `(8888, 'env.development.port', false)` AND `(8889, 'env.tests.port', false)`. Assert the post-process result has `env.development.port === 8890` (from the mock return) and `env.development.config.WP_HOME === 'http://localhost:8890'` (i.e. `appendPortToWPConfigs` consumed the resolved port). | -| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig with autoPortMode=defaults-only routes user-set port to strict and default-origin port to non-strict` | AC1, AC2, AC3 | Pass `defaultOriginPorts: new Set([ 'development.port' ])` (i.e. tests port is user-set); assert the resolver call for `env.development.port` has third arg `false` and for `env.tests.port` has third arg `true`. | -| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig with autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)` | AC10, R3 | Provide a config with `env.development.port: 8888` and `env.development.phpmyadminPort: 8080`, `defaultOriginPorts: new Set([ 'development.port' ])`. Assert `portResolver.resolve` is called once for `'env.development.port'` and is NEVER called with `configPath` containing `'phpmyadminPort'`. This guards against the B3 regression where phpmyadminPort would silently auto-move under defaults-only mode. | -| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig with autoPortMode=all routes both http ports AND phpmyadminPort non-strict (preserves PR #74472 behavior)` | AC4 | Config with all three ports populated; `defaultOriginPorts: new Set()`; assert `resolver.resolve` is called for HTTP ports AND phpmyadminPort, all with `strict=false`. | -| `packages/env/lib/config/test/post-process-config.js` | New | `postProcessConfig defaults to autoPortMode=off and routes ports strict (back-compat)` | AC10 | Call `postProcessConfig(config, { portResolver })` with NO `autoPortMode` / `defaultOriginPorts` (the existing call shape from before this PR). Assert the resolver receives `strict=true` for HTTP ports and is also called for phpmyadminPort (because the skip rule only applies to `'defaults-only'`). This guards the back-compat default in Step 4. | -| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with no user autoPort and busy default port falls back via defaults-only mode` | AC1, AC11 | With no user config, mock the port resolver path: spy on `createPortResolver` to verify it IS created (not skipped). Mock `findAvailablePort` to return `8890` for preferred `8888`. Assert `config.env.development.port === 8890` and `config.env.development.config.WP_HOME === 'http://localhost:8890'`. | -| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with autoPort:false in user config skips fallback even on default ports` | AC5 | With `.wp-env.json` containing `{ "autoPort": false }`, mock `isPortAvailable` to return `false` for 8888 → assert `loadConfig` rejects with the strict port-busy error. | -| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CI=1 disables fallback regardless of autoPort:true` | AC6, AC8 | Set `process.env.CI = '1'`, set user config `{ "autoPort": true }`, mock the port-availability layer so 8888 is busy → assert `loadConfig` rejects with the strict port-busy error. The named test exists so removing the `if ( process.env.CI )` guard in `load-config.js` causes this test to fail — this is the AC8 regression detector. Cleanup `delete process.env.CI` in `afterEach`. | -| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CI=1 disables fallback even when autoPort is unset` | AC6 | Same as above but with no `autoPort` key in the config. | -| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CLI autoPort=true and user config autoPort=false has CLI win` | AC4 (precedence) | Asserts existing precedence (CLI beats config) is preserved by setting `customConfigPath` to a config with `autoPort: false` and passing `autoPort: true` in options; mock `findAvailablePort` to return a moved port; assert the moved port flows through. | -| `packages/env/lib/config/test/config-integration.js` | New | `loadConfig with CLI autoPort=true and explicit user port falls back when port is busy (AC4 behavior-level)` | AC4 | Mirror of the AC5 integration test. With `.wp-env.json` setting `port: 9000` and CLI `autoPort: true`, mock `findAvailablePort` to return `9001`; assert `config.env.development.port === 9001` and `WP_HOME` reflects 9001. (Addresses F3.) | -| `packages/env/lib/test/resolve-available-ports.js` | Existing — keep | `should resolve a port in non-strict mode` (line 19) | AC1 | Existing test — keep; still asserts `findAvailablePort` is hit for non-strict calls. | -| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=defaults-only uses strict mode for non-default-origin ports and non-strict for default-origin ports` | AC1, AC2, AC3 | Mocks `findAvailablePort`/`isPortAvailable`. Calls `resolveConfigPorts(config, resolver, { autoPortMode: 'defaults-only', defaultOriginPorts: new Set([ 'development.port' ]) })` with both env ports populated. Asserts `findAvailablePort` was called for dev port (preferred 8888), `isPortAvailable` was called (strict path) for tests port (preferred 8889). | -| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)` | AC10, R3 | Config with `env.development.port: 8888, phpmyadminPort: 8080`. Call resolver with `defaultOriginPorts: new Set([ 'development.port' ])`. Assert `findAvailablePort` called for HTTP port only; `findAvailablePort` NOT called for phpmyadminPort; `isPortAvailable` NOT called for phpmyadminPort. | -| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=all uses non-strict mode for all ports including phpmyadminPort` | AC4 | All ports get `findAvailablePort` (preserves PR #74472 behavior). | -| `packages/env/lib/test/resolve-available-ports.js` | New | `resolveConfigPorts under autoPortMode=off uses strict mode for HTTP ports and still resolves phpmyadminPort non-strictly` | AC5, AC10 | Defensive coverage for the per-port skip rule's non-`defaults-only` branch. Also documents that in production `'off'` never reaches this function (resolver is not created). | -| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver emits spinner.info exactly once when fallback occurs and re-arms the spinner` | AC7 | Mock spinner with `info: jest.fn()` and `start: jest.fn()`. Mock `findAvailablePort` to return `8890` when preferred is `8888`. Call `resolver.resolve(8888, 'env.development.port')`. Assert `spinner.info` was called exactly once with a string matching `/8888.*busy.*8890/i`, and `spinner.start` was called after `spinner.info` (assert via `info.mock.invocationCallOrder[0] < start.mock.invocationCallOrder[0]`). | -| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver does NOT emit spinner.info when the preferred port is available (no move occurred)` | AC7 | Mock `findAvailablePort` to return the preferred port. Assert `spinner.info` was NOT called. | -| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver does NOT emit spinner.info on the strict failure path` | AC7 | Strict mode + busy port → `isPortAvailable` returns `false` → throws. Assert `spinner.info` was NOT called. | -| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver does not write to console or process.stdout when fallback occurs (regression guard)` | AC7 | Spy on `console.log`, `console.info`, `console.warn`, `process.stdout.write`. After a fallback, none of them were called. (This is the "introducing a new output path is a detectable regression" assertion from AC7. Restore the spies in `afterEach`.) | -| `packages/env/lib/test/resolve-available-ports.js` | New | `createPortResolver suppresses the notice silently when no spinner is provided` | AC7 (test-path safety) | Call `createPortResolver()` with no args; mock `findAvailablePort` to return a different port; assert no throw and no console output. | - -End-to-end / manual repro for **AC9b** is documented in the PR body, NOT in the automated suite (per spec §5 and AC9b). The PR test plan must include the recipe: - -> 1. Bind 8888 manually: `python3 -m http.server 8888 &` -> 2. From a fresh project with no `.wp-env.json`, run `wp-env start`. -> 3. Confirm CLI prints a "moved port" info line referencing 8890 (or next free). -> 4. Browse to the printed URL; confirm WP loads and admin login works. -> 5. Free 8888, run `wp-env stop && wp-env start`; confirm the env re-resolves (may go back to 8888). - -This recipe is referenced from the PR body's test plan checklist as the AC9b verification. - -**AC9c (other commands)** is verified manually as part of the same recipe (steps 4 supplemented by `wp-env logs`, `wp-env run cli wp option get siteurl`, `wp-env stop`, `wp-env destroy --force`). No new automated test is added in this phase because the existing pattern (commands consume the cached `docker-compose.yml`) is unchanged by this PR — we are not regressing AC9c, we are inheriting the existing guarantee. The plan acknowledges this rather than expanding scope. - ---- - -## 4. Sequencing and parallelism - -For a single implementer, the realistic ordering (respecting both dependency graph and same-file edits) is: - -1. **Step 1** (default flip + fixture update; touches `parse-config.js` and its test fixture). -2. **Step 3** (`__defaultOriginPorts` provenance; touches `parse-config.js` only — the helper and the property attachment). -3. **Step 2** (`load-config.js` tri-state + threading). -4. **Step 4** (`post-process-config.js` option threading). -5. **Step 5** (`resolve-available-ports.js` per-port routing). -6. **Step 6** (`resolve-available-ports.js` notice — same file as step 5; sequential edit). -7. **Step 7** (`commands/start.js` JSDoc only). -8. **Steps 10 + 11** (tests). -9. **Step 12** (verification sweep). -10. **Steps 8 + 9** (documentation — can land at any point after Step 2; deferred to last so wording is informed by the implementation). - -Multi-agent worker plan (if parallelism is desired): - -- Worker A handles `parse-config.js` (Steps 1 + 3) and updates the test fixture. -- Worker B waits for Worker A to commit, then handles `load-config.js` (Step 2), `post-process-config.js` (Step 4), and `resolve-available-ports.js` (Steps 5 + 6 sequentially within the same file). -- Worker C handles docs (Steps 8 + 9) after Worker B's interface lands. -- Tests (Steps 10 + 11) and the verification sweep (Step 12) are owned by a single coordinator after all workers have committed. - -**Verification gates** (run during implementation, not just at the end): - -1. **After step 5 lands**: run `npm run test:unit -- packages/env/lib/config/test/post-process-config.js packages/env/lib/test/resolve-available-ports.js` to confirm the routing matrix works before writing the integration tests. -2. **After step 7 lands**: run `npm run test:unit -- packages/env` to confirm the full unit-test suite stays green; this is the early regression radar — if any unit test is unexpectedly red, escalate before continuing. Also run `composer test` from repo root to catch any unexpected PHP-side coupling early (per **R17 / R-PHPRegress**). -3. **After step 11 lands**: run `npm run lint:js -- packages/env` to catch style issues before docs. -4. **After step 12 lands**: run `composer test` again from repo root. Per **R17 / R-PHPRegress**, this is mandatory before review even though changes are JS-only. If any PHP test fails unexpectedly, escalate to spec/plan rather than work around silently. - ---- - -## 5. Verification strategy - -| AC | Verification command / test name | -|---|---| -| AC1 | `npm run test:unit -- packages/env -t "no user autoPort and busy default port falls back via defaults-only mode"` and `… -t "uses strict mode for non-default-origin ports and non-strict for default-origin ports"`. Manual: AC9b recipe steps 1–4. | -| AC2 | `npm run test:unit -- packages/env -t "uses strict mode for non-default-origin ports and non-strict for default-origin ports"` (covers both env keys symmetrically). | -| AC3 | `npm run test:unit -- packages/env -t "routes user-set port to strict and default-origin port to non-strict"` plus the four `parse-config.js` provenance tests for local / override / `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`. | -| AC4 | `npm run test:unit -- packages/env -t "autoPortMode=all"` and `… -t "CLI autoPort=true and user config autoPort=false has CLI win"` and `… -t "CLI autoPort=true and explicit user port falls back when port is busy"` (the new behavior-level integration test). | -| AC5 | `npm run test:unit -- packages/env -t "autoPortMode=off"` and `… -t "autoPort:false in user config skips fallback even on default ports"`. | -| AC6 | `npm run test:unit -- packages/env -t "CI=1 disables fallback"` (both variants). | -| AC7 | The five `createPortResolver` notice tests in `resolve-available-ports.js` (emits-once-and-re-arms / not-emitted-on-no-move / not-emitted-on-strict-fail / no-console-write-regression / silent-without-spinner). | -| AC8 | `npm run test:unit -- packages/env -t "CI=1 disables fallback regardless of autoPort:true"` — this is the named regression-detector test. Removing the `if ( process.env.CI )` guard in `load-config.js` makes this test fail. | -| AC9a | `npm run test:unit -- packages/env -t "threads autoPortMode and defaultOriginPorts to resolveConfigPorts"` — asserts merged config's `WP_HOME`/`WP_SITEURL` reflect the resolved port. | -| AC9b | Manual reproduction documented in PR body test plan. | -| AC9c | Manual reproduction documented in PR body test plan (no new automated test; covered by inherited compose-file guarantee). | -| AC10 | `npm run test:unit -- packages/env` (entire suite) green; the new "non-enumerable contract" test plus the back-compat `postProcessConfig` test plus the snapshot-no-drift expectation in Step 12. | -| AC11 | `npm run test:unit -- packages/env -t "tri-state"` plus `… -t "should accept autoPort as a tri-state"` (modified test). | - ---- - -## 6. Risks and mitigations - -- **R-TriState** — collapsed at the config layer because `DEFAULT_ENVIRONMENT_CONFIG.autoPort` is `false`. **Mitigation in plan.** Step 1 changes the default to `null`; step 2 reinterprets it; AC11 + the modified `should accept autoPort as a tri-state` test catch a future regression. The CLI side is already safe (verified — `lib/test/cli.js:35-52` already asserts `undefined`/`true`/`false`). -- **R-NonEnumerable** — `__defaultOriginPorts` becomes enumerable in a future refactor and starts leaking into `mergeConfig` iteration, JSON serialization, or `toEqual` assertions. **Mitigation in plan.** A dedicated regression test (`__defaultOriginPorts is invisible to mergeConfigs and toEqual`) asserts both `propertyIsEnumerable === false` and that `JSON.stringify` round-trip drops the property. Flipping it to enumerable fails the test. -- **R-TOCTOU** — port reads as free during the scan but is grabbed before Docker binds. **Mitigation in plan.** Inherited from PR #74472 — the plan does not change the existing `findAvailablePort` / `isPortAvailable` call sites, so the existing TOCTOU window is unchanged. Spec explicitly does not require a new mitigation. -- **R-PHPRegress** — PR #74472's earlier always-on attempt broke PHP tests. **Mitigation in plan.** `composer test` is invoked twice during implementation per §4 verification gates 2 and 4; any failure escalates rather than gets worked around. The plan also keeps the change tightly scoped to JS in `packages/env/` (per R15) so PHP coupling surfaces are minimized. -- **R-Snapshots** — snapshot drift. **Mitigation in plan.** Step 12 explicitly states that no snapshot diff is expected (verified — `grep autoPort` against both snapshot files returns zero hits today). Any unexpected diff is treated as a regression to investigate, not as routine updateSnapshot fodder. The real risk (the inline `DEFAULT_CONFIG` fixture at `parse-config.js test:21-71`) is addressed in Step 1 sub-step 4, not Step 12. -- **R-DownstreamURL** — resolved port not propagated. **Mitigation in plan.** Verified by tracing: `appendPortToWPConfigs` already runs after `resolveConfigPorts` in the existing `postProcessConfig` flow (`post-process-config.js:35-39`), so no new wiring needed; the AC9a test asserts the propagation explicitly via `WP_HOME`. -- **R-PortCollision** — dev and tests resolve to the same port. **Mitigation in plan.** Inherited: `createPortResolver`'s `usedPorts` array is passed as `exclude` to `findAvailablePort` (`resolve-available-ports.js:75-78`); already correct. -- **R-PhpmyadminMove (B3)** — phpmyadminPort silently auto-moves when a contributor has set it explicitly and runs under the new defaults-only mode. **Mitigation in plan.** Step 5's per-port skip rule under `autoPortMode === 'defaults-only'` skips `phpmyadminPort` entirely, preserving today's behavior verbatim (today phpmyadminPort is only resolved when `--auto-port` is on). The `postProcessConfig` test `… skips phpmyadminPort entirely` and the `resolveConfigPorts` test `… skips phpmyadminPort entirely` are the regression detectors. - ---- - -## 7. Rollback - -If a regression surfaces post-merge: revert this PR. The change is additive at the boundary (one default-value flip, one tri-state interpretation, one provenance-tracking helper, one routing matrix, one spinner notice, one README/CHANGELOG update). A clean `git revert ` restores the prior PR #74472 opt-in-only behavior with no downstream cleanup needed: there is no migration, no persisted state, no schema change, and no public API surface change. Contributors who relied on the new default-fallback behavior would temporarily need to add `--auto-port` to recover it; everyone else is unaffected. - -**Cached compose caveat.** Environments that were `start`ed under the new default-fallback behavior have their resolved port pinned in the cached `docker-compose.yml` at `~/.wp-env//docker-compose.yml`. After a revert, those already-running environments continue working unchanged (the cached compose still references the post-fallback port; `stop`/`destroy` operate by container name). However, a contributor who deletes the cache or runs `wp-env destroy && wp-env start` post-revert on a host where 8888 is busy will once again see the original port-busy failure. This is worth a one-line note in the revert PR's body so the reverting maintainer can communicate it. diff --git a/.pipelines/49843-wp-env-default-port-fallback/prompt.md b/.pipelines/49843-wp-env-default-port-fallback/prompt.md deleted file mode 100644 index ea12335c98862c..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/prompt.md +++ /dev/null @@ -1,80 +0,0 @@ -# Phase 0 — Prompt - -## Pipeline slug - -`49843-wp-env-default-port-fallback` - -## Linked GitHub issue - -WordPress/gutenberg#49843 — "wp-env: consideration of active ports". - -## Background - -`@wordpress/env` (the wp-env CLI) starts a WordPress development environment in Docker on port `8888` (development) and `8889` (tests) by default. When either port is already in use on the host (a very common situation on machines that run other local dev stacks), the start command fails with a Docker port-binding error and the contributor has to either free the port or write a `.wp-env.json` with explicit port overrides before they can continue. - -PR #74472 added an opt-in `--auto-port` CLI flag (and `"autoPort": true` config option) that scans for an available port when the configured one is busy. That PR landed as opt-in because an earlier "always on" version broke PHP unit tests and changed long-standing default behavior. CI determinism is preserved through a `process.env.CI` guard inside `load-config.js`. - -The remaining gap is the out-of-the-box experience requested in #49843: a developer who has never configured `.wp-env.json` should be able to run `wp-env start` even when 8888 or 8889 are taken by another process, without learning about a flag. - -## Goal of this pipeline - -Allow `wp-env start` (and any other command that resolves ports) to fall back automatically to the next free port when the **default** ports 8888 (development) and 8889 (tests) are busy, without requiring `--auto-port`. - -User-set ports — anything the contributor explicitly wrote in `.wp-env.json`, `.wp-env.override.json`, an environment variable override, or any other supported override mechanism — must NOT be silently replaced. They keep today's behavior: Docker (or the existing strict pre-flight) reports a "port busy" error so the contributor knows their explicit choice was honored. - -The opt-in `--auto-port` flag and `"autoPort": true` config option must keep working for the case where contributors *want* their explicit ports to also auto-fall-back. Setting `"autoPort": false` explicitly must still force strict behavior on default ports too. - -The `process.env.CI` determinism guard must keep applying — CI runs must not silently move ports around. - -## Out of scope - -- Phase 2 (Design doc) of the pipeline. RP does not implement it yet. -- MySQL port behavior (`mysqlPort`) — already supports Docker-native auto-assignment via `null`. -- Any change to the Docker layer, the WordPress runtime, or the public TypeScript types beyond what this feature needs. -- Renaming or deprecating `--auto-port` / `"autoPort"`. -- Cross-package refactors. Stay inside `packages/env/`. - -## Acceptance criteria (high-level — refined in phase 1 spec) - -1. With no `.wp-env.json` in the project (or one that does not set `port` / `testsPort`), running `wp-env start` while 8888 is occupied succeeds and binds the development environment to the next free port (8890, 8891, ...). Same for 8889 and the tests environment. -2. With `.wp-env.json` (or override / env var) explicitly setting `port: 9000`, running `wp-env start` while 9000 is occupied fails with the existing "port busy" message; it does NOT silently move to 9001. -3. With `--auto-port` (or `"autoPort": true`), explicit ports also auto-fall-back, matching today's behavior of PR #74472. -4. With `"autoPort": false` set explicitly, default ports do NOT auto-fall-back; a port-busy failure surfaces. (Hard opt-out for users who want determinism but not via `CI=1`.) -5. `CI=1` continues to disable all auto-fallback regardless of other settings. -6. Existing unit tests in `packages/env/lib/test/` and `packages/env/lib/config/test/` continue to pass; new tests cover the four behaviors above. -7. README and CHANGELOG updated to describe the new default behavior and the `"autoPort": false` opt-out. - -## Anti-goals / things the pipeline should NOT do - -- Do not introduce new top-level config options unless strictly necessary. Reuse `autoPort` as a tri-state (`undefined` / `true` / `false`) instead of inventing a second flag. -- Do not change `DEFAULT_ENVIRONMENT_CONFIG.port` or `testsPort` away from `8888` / `8889`. -- Do not break `appendPortToWPConfigs` or the `WP_HOME` / `WP_SITEURL` rewriting that depends on the resolved port. -- Do not silently print "moved port" messages with no way to suppress them; reuse the existing CLI spinner / informational message used by `--auto-port` today. - -## Reference material - -- Issue: https://github.com/WordPress/gutenberg/issues/49843 -- Prior PR (opt-in `--auto-port`): https://github.com/WordPress/gutenberg/pull/74472 -- Key source files: - - `packages/env/lib/resolve-available-ports.js` - - `packages/env/lib/config/load-config.js` - - `packages/env/lib/config/post-process-config.js` - - `packages/env/lib/config/parse-config.js` - - `packages/env/lib/cli.js` - - `packages/env/README.md` - - `packages/env/CHANGELOG.md` - -## Artifacts produced by this pipeline - -Inside `.pipelines/49843-wp-env-default-port-fallback/`: - -- `prompt.md` (this file) -- `spec.md` + `spec-review-N.md` -- `plan.md` + `plan-review-N.md` -- (No `design-doc.md` — phase 2 not implemented in RP yet.) -- `code-review-N.md` (implementation phase reviews; the implementation itself lands as code in `packages/env/`) -- `docs-review-N.md` (documentation phase reviews; doc changes land in README/CHANGELOG) - -## Final deliverable - -A draft GitHub PR against `WordPress/gutenberg` `trunk` from branch `try/49843-wp-env-default-port-fallback`, linking #49843, summarizing the change, and listing the acceptance criteria in its test plan. diff --git a/.pipelines/49843-wp-env-default-port-fallback/spec-review-1.md b/.pipelines/49843-wp-env-default-port-fallback/spec-review-1.md deleted file mode 100644 index c33a2cf8ad2236..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/spec-review-1.md +++ /dev/null @@ -1,249 +0,0 @@ -# Spec Review — Iteration 1 - -Pipeline: `49843-wp-env-default-port-fallback` -Reviewer role: spec-reviewer (adversarial) -Artifacts under review: -- `prompt.md` -- `spec.md` - -This review is adversarial. The default posture is rejection unless the spec is demonstrably complete, testable, traceable, and free of cross-phase leakage. - ---- - -## 1. Traceability — every requirement / AC mapped back to the prompt - -Mapping each spec item to the sentence(s) in `prompt.md` it derives from. "OK" = direct trace, "PARTIAL" = trace exists but is loose, "CREEP" = no trace. - -### Requirements - -| Req | Prompt anchor (verbatim or near-verbatim) | Verdict | -|-----|-------------------------------------------|---------| -| R1 (default dev port fallback) | Goal: "Allow `wp-env start` ... to fall back automatically to the next free port when the **default** ports 8888 (development) and 8889 (tests) are busy". AC1. | OK | -| R2 (default tests port fallback, independent) | AC1 second sentence: "Same for 8889 and the tests environment." Goal: "8888 (development) and 8889 (tests)". | OK. The "independently of the development port" wording is a reasonable extrapolation, not creep. | -| R3 (user-set ports never silently moved) | Goal §2: "User-set ports — anything the contributor explicitly wrote in `.wp-env.json`, `.wp-env.override.json`, an environment variable override, or any other supported override mechanism — must NOT be silently replaced." AC2. | OK | -| R4 (`--auto-port` / `"autoPort": true` keeps PR #74472 semantics) | Goal §3: "The opt-in `--auto-port` flag and `"autoPort": true` config option must keep working...". AC3. | OK | -| R5 (`"autoPort": false` is a hard opt-out for default ports) | Goal §3: "Setting `"autoPort": false` explicitly must still force strict behavior on default ports too." AC4. | OK | -| R6 (tri-state semantics for `autoPort`) | Anti-goal: "Reuse `autoPort` as a tri-state (`undefined` / `true` / `false`) instead of inventing a second flag." | OK | -| R7 (`CI=1` continues to disable all auto-fallback) | Background: "CI determinism is preserved through a `process.env.CI` guard inside `load-config.js`." AC5. Goal §4: "The `process.env.CI` determinism guard must keep applying — CI runs must not silently move ports around." | OK | -| R8 (resolved port is downstream source of truth) | Anti-goal: "Do not break `appendPortToWPConfigs` or the `WP_HOME` / `WP_SITEURL` rewriting that depends on the resolved port." | OK | -| R9 (default port constants unchanged) | Anti-goal: "Do not change `DEFAULT_ENVIRONMENT_CONFIG.port` or `testsPort` away from `8888` / `8889`." | OK | -| R10 (no rename / deprecation of `--auto-port`) | Out of scope: "Renaming or deprecating `--auto-port` / `"autoPort"`." | OK | -| R11 (informational message reuses existing channel) | Anti-goal: "Do not silently print 'moved port' messages with no way to suppress them; reuse the existing CLI spinner / informational message used by `--auto-port` today." | OK | -| R12 (existing test suites stay green) | AC6: "Existing unit tests in `packages/env/lib/test/` and `packages/env/lib/config/test/` continue to pass". | OK | -| R13 (new tests cover four primary behaviors) | AC6: "new tests cover the four behaviors above." | OK | -| R14 (README and CHANGELOG updated) | AC7. | OK | -| R15 (scope confined to `packages/env/`) | Out of scope: "Cross-package refactors. Stay inside `packages/env/`." | OK | - -No requirement is wholly unsupported. **No CREEP findings at the requirement level.** - -### Acceptance Criteria - -| AC | Trace | Verdict | -|----|-------|---------| -| AC1 (default dev port) | Prompt AC1 first half. | OK | -| AC2 (default tests port, independent) | Prompt AC1 second half. | OK | -| AC3 (explicit port strict by default) | Prompt AC2. | OK | -| AC4 (`--auto-port` falls back on explicit ports) | Prompt AC3. | OK | -| AC5 (`"autoPort": false` strict on defaults) | Prompt AC4. | OK | -| AC6 (`CI=1` disables all auto-fallback) | Prompt AC5. | OK | -| AC7 (informational message contract) | Prompt anti-goal on "moved port" messages. | OK | -| AC8 (CI guard regression test exists) | Prompt §"Background" + AC5 (regression-protection is a reasonable spec extrapolation). | OK — defensible but borderline. See finding F-1. | -| AC9 (resolved port flows downstream) | Prompt anti-goal about `appendPortToWPConfigs` / `WP_HOME` / `WP_SITEURL`. | OK | -| AC10 (existing tests stay green) | Prompt AC6. | OK | - ---- - -## 2. Completeness — prompt criteria / constraints not covered - -Walking the prompt's enumerated items and checking coverage in the spec. - -- **Prompt AC1** → R1, R2, AC1, AC2. Covered. -- **Prompt AC2** → R3, AC3. Covered. -- **Prompt AC3** → R4, AC4. Covered. -- **Prompt AC4** → R5, AC5. Covered. -- **Prompt AC5** → R7, AC6. Covered. -- **Prompt AC6** → R12, R13, AC10, AC8. Covered. -- **Prompt AC7** → R14. Covered. -- **Prompt anti-goal "do not introduce new top-level config options"** → R6. Covered. -- **Prompt anti-goal "do not change `DEFAULT_ENVIRONMENT_CONFIG.port` / `testsPort`"** → R9. Covered. -- **Prompt anti-goal "do not break `appendPortToWPConfigs` / `WP_HOME` / `WP_SITEURL`"** → R8, AC9. Covered. -- **Prompt anti-goal "do not silently print 'moved port' messages with no way to suppress; reuse existing channel"** → R11, AC7. Covered. -- **Prompt out-of-scope: phase 2 design doc, `mysqlPort`, Docker layer, runtime, types, renaming `--auto-port`, cross-package refactors** → §5 of spec. Covered. -- **Prompt §"Final deliverable" (draft PR against `trunk` from `try/49843-wp-env-default-port-fallback`, links #49843, lists ACs in test plan)** → **NOT covered** in spec. See **F-2** below. - -### Findings — completeness - -- **F-2 (MAJOR).** The prompt's "Final deliverable" section pins the PR target (`WordPress/gutenberg` `trunk`), the source branch (`try/49843-wp-env-default-port-fallback`), the requirement that the PR link `#49843`, and that the test plan list the acceptance criteria. None of these appear as a spec requirement or AC. While most of this is plumbing the doc-writer / orchestrator handles, the "test plan lists the acceptance criteria" obligation is a deliverable-shaped requirement and should be either explicitly captured (e.g. as R16) or explicitly delegated out of spec scope with a one-line note. Right now it is silently dropped. - -- **F-3 (MINOR).** Prompt §"Background" specifies that PR #74472 "broke PHP unit tests" when it was always-on. The spec does not call out PHP unit tests at all (R12/AC10 only mention `lib/test/` and `lib/config/test/`, i.e. JS unit tests). If PHP unit tests in `phpunit/` are sensitive to wp-env default ports, the spec should say so. If they are not, the spec should explicitly note that "no PHP-side regression is expected because the change is JS-only". Either way, the silence is a gap. - ---- - -## 3. Testability — is each AC automatable, manually verifiable, or untestable? - -| AC | Automatable? | Notes | -|----|--------------|-------| -| AC1 | YES (with port-binding stub or fake `net.createServer`-style harness in unit tests). The "8888 busy" precondition can be simulated; PR #74472's existing tests for `--auto-port` confirm this is feasible. | OK | -| AC2 | YES, same harness, additionally exercising the dev/tests independence. | OK | -| AC3 | YES, unit-testable through the config layer + port resolver, without spinning up Docker. | OK | -| AC4 | YES, same. | OK | -| AC5 | YES, same. | OK | -| AC6 | YES via `process.env.CI` mutation in tests, mirroring PR #74472's existing pattern. | OK | -| AC7 ("Informational message contract") | PARTIAL. "Same channel as `--auto-port` today" is testable only insofar as the test can assert which channel is used. The AC does not name the channel concretely (it intentionally defers to "the existing one"), which makes the assertion mechanism shaky: a refactor that swaps the spinner for a different but equivalent channel could pass or fail arbitrarily. **Finding F-4.** | -| AC8 | YES — explicitly demands an automated test, which is the right framing. | OK | -| AC9 | PARTIAL. Asserting that `WP_HOME` / `WP_SITEURL` reflect the resolved port is unit-testable. Asserting that "the URL printed by the CLI" matches the bound port leans into integration territory; without a Docker-up step, the test can only inspect the value the CLI *intends* to print, not the live HTTP response. The AC blurs unit-vs-integration. **Finding F-5.** | -| AC10 | YES — pure regression check. | OK | - -### Findings — testability - -- **F-4 (MAJOR).** AC7 is currently underspecified for automated assertion. It says the message goes through "the same spinner/informational channel that `--auto-port` uses today" without naming an observable contract (e.g. "via the same `info`/`log` helper", "as a non-throwing return", "rendered through the existing yargs/ora stream"). A test cannot mechanically verify "same channel as today" without a stable identifier for that channel. The spec should either (a) state the observable contract in WHAT terms (e.g. "the message MUST appear on stderr/stdout in the same form the existing `--auto-port` spinner emits, including the existing message prefix/format"), or (b) reduce the AC to "no new always-on log lines are introduced; messages only appear when a fallback occurred", which is independently testable. As written, AC7 risks producing flaky or trivially-passing tests. - -- **F-5 (MINOR).** AC9 needs a clearer split between "values inside the merged config object reflect the resolved port" (unit-testable, this is what R8 actually demands) and "the running HTTP server is reachable at the printed URL" (integration). The spec hints at both; the plan phase will need a clear signal which one is in scope. Recommend tightening AC9 to the unit-testable subset and explicitly leaving live reachability to manual PR test plan. - -- **F-6 (MINOR).** No AC explicitly verifies R6 (tri-state semantics) at the boundary between CLI parsing and config merge. R6 is a structural requirement; without a dedicated AC, it is verified only transitively through AC3+AC4+AC5. That is *probably* sufficient, but a one-line AC ("Given an unset `--auto-port` flag and unset `autoPort` config field, the resolved `autoPort` MUST be distinguishable from explicit `false`") would close OQ1 from the test side rather than leaving it as an unobserved invariant. - ---- - -## 4. Phase boundary — does the spec leak HOW into WHAT? - -The spec is generally disciplined about staying at WHAT. A few sentences cross the line or come close. - -- **F-7 (MINOR — phase leak).** §3 R6: "No new top-level config option is introduced for this distinction." This is a *constraint* (which is fine) but it implicitly prescribes the design (reuse `autoPort`). The constraint comes from the prompt's anti-goal, so it traces. Acceptable, but right at the line. - -- **F-8 (MINOR — phase leak).** §3 R3 enumerates concrete user-source mechanisms: "root `.wp-env.json`, `.wp-env.override.json`, environment variable override, or any other documented override mechanism". This mostly mirrors the prompt language. Acceptable. - -- **F-9 (NIT — phase leak).** §6 A1 names "`port-utils`-style helper". This is a hint at file organization. Bracketing it as "the existing port-availability scanning utility used by PR #74472" without the `port-utils`-style nickname would be cleaner. Not a blocker; rewrite is trivial. - -- **F-10 (NIT — phase leak).** §6 A2 names `packages/env/lib/config/load-config.js` directly. This is a file path — borderline HOW. It traces to the prompt's reference list, so it is defensible as scoping rather than design. Borderline acceptable. - -- **F-11 (NIT — phase leak).** §8 OQ3 mentions "sentinel, separate object, post-process flag, etc." as possible mechanisms. The spec correctly defers the choice to the plan phase, but enumerating implementation options inside the spec is a soft phase leak. Recommend: drop the parenthetical enumeration; just say "the plan phase chooses the mechanism". - -No critical phase-boundary violations. The spec does not specify file layout, function names, or refactor steps. - ---- - -## 5. Out-of-scope completeness — does spec match prompt? - -Comparing prompt §"Out of scope" against spec §5. - -| Prompt out-of-scope item | Spec §5 covers? | -|--------------------------|-----------------| -| Phase 2 design doc | YES | -| `mysqlPort` behavior | YES | -| Docker layer / runtime / public TS types | YES (split into 3 bullets in spec) | -| Renaming or deprecating `--auto-port` / `"autoPort"` | YES | -| Cross-package refactors; stay inside `packages/env/` | YES | - -Spec §5 also adds: changing default port constants, always-on chatter / new suppression flag, telemetry/analytics, behavior under non-CI automation environments, new top-level config options. All trace cleanly to prompt anti-goals or are sensible scope-fencing. - -No omissions, no contradictions. - ---- - -## 6. Risk coverage — are the prompt's stated risks reflected with mitigations? - -The prompt names four risk threads: - -1. **CI determinism** → Spec R-CI + R7 + AC6 + AC8. Covered. -2. **Silent moves of explicit ports** → Spec R-Explicit + R3 + AC3. Covered. -3. **Breaking opt-in flag (`--auto-port`)** → Spec R-OptIn + R4 + AC4. Covered. -4. **Stale snapshots** → Spec R-Snapshots + R12 + AC10. Covered. - -Spec also adds R-OptOut, R-UX, R-DownstreamURL, R-PortCollision. All four are reasonable extensions, each tied to a requirement. - -### Findings — risk coverage - -- **F-12 (MINOR).** Spec lacks a risk for **"`autoPort` tri-state coercion at the CLI boundary loses the `undefined` state"**. This is OQ1 in the spec's open-questions section, but it is also a substantive risk: if yargs collapses `undefined` → `false`, the entire feature silently regresses to today's behavior on default ports. It deserves a dedicated risk entry (e.g. R-TriState) with a mitigation that the plan phase must surface and test for, not just an open question. Without this, the risk lives only as a passive Q rather than a tracked threat. - -- **F-13 (MINOR).** Spec lacks a risk for **"port-resolution race / TOCTOU"**: scanning a port as free, then Docker tries to bind it and someone else has grabbed it in the interim. Today's `--auto-port` has the same exposure, so this might be inherited rather than new — but the spec should at least say "inherited from PR #74472, no new mitigation required" so the plan phase does not re-litigate it. - ---- - -## 7. Open question triage - -| OQ | Spec's framing | Triage verdict | Justification | -|----|----------------|----------------|---------------| -| OQ1 (tri-state coercion at CLI boundary) | "spec assumes solvable per A3" | **(c) Resolvable by reading existing code** — and **escalate to a risk (F-12)**. The plan phase can answer this in minutes by reading `packages/env/lib/cli.js` to see how yargs is configured for `--auto-port`. No owner input required. NOT a spec blocker. | -| OQ2 (per-environment `autoPort`) | "spec treats whatever PR #74472 surface allows as the contract" | **(c) Resolvable by reading existing code.** Read `parse-config.js` / `post-process-config.js` to see whether `autoPort` is per-env or root-only. The deferral is fine. | -| OQ3 (provenance tracking for "user-set" ports) | Deferred to plan phase | **(b) Acceptable to defer.** This is a design decision and the spec correctly stays out of it. | -| OQ4 (multiple override layers — is `.wp-env.override.json` user-set?) | Spec answers YES, defers confirmation to plan | **(b) Acceptable to defer.** Spec gives the answer, plan confirms feasibility. | -| OQ5 (`WP_ENV_PORT` / env-var overrides — exact list) | Defers enumeration to plan against `parse-config.js` | **(c) Resolvable by reading existing code.** No owner input needed. | -| OQ6 (no upward port available — failure mode) | "spec assumes existing scanner has defined failure mode" | **(c) Resolvable by reading existing code.** Read `resolve-available-ports.js`. | -| OQ7 (interaction with stop/destroy + persisted state) | Spec asserts "re-resolve on each `start`", treats persisted-state changes as out of scope unless plan finds a blocker | **(b) Acceptable to defer with the spec's stated default.** This is a sensible call. | -| OQ8 (`CI` truthiness semantics) | "plan phase reuses existing rule verbatim" | **(c) Resolvable by reading existing code.** Read the existing guard in `load-config.js`. | - -**No open question is a blocker for entering the plan phase.** Most can be resolved by reading existing source; a couple are appropriate design deferrals. OQ1 should be promoted to a tracked risk regardless (F-12). - ---- - -## 8. Other findings - -- **F-1 (NIT).** AC8 ("CI guard regression test exists") is a meta-AC about the test suite rather than about user-observable behavior. It is *useful* (the prompt explicitly warns about CI determinism regressing), and AC8 traces defensibly, but it is structurally an instruction to the implementer phase rather than a behavioral acceptance. Consider rephrasing as "a named, documented test asserts CI guard behavior, such that removing the guard fails the test" — same intent, expressed as a checkable observable rather than a "test exists" assertion. - -- **F-14 (NIT).** §4 AC2 says "binds to the next available port above 8889" — but the spec elsewhere (R1) says "the next available port" without the "above" directionality. The prompt itself only says "next free port (8890, 8891, ...)", which implies upward scanning. The spec should be consistent: either both ACs say "above" or neither does, and the directionality should be one explicit requirement (e.g. an addendum to R1: "scanning proceeds upward from the configured port"). Currently it is implied by example, not stated. - -- **F-15 (NIT).** No requirement covers the contract that **wp-env-internal commands other than `start` that resolve ports** (e.g. `run`, `clean`, `logs`) also see the resolved fallback port. The prompt's goal opens with "Allow `wp-env start` (and any other command that resolves ports) to fall back automatically". The "(and any other command that resolves ports)" parenthetical is dropped from the spec. Recommend an explicit one-liner (an addendum to R8 or a new R) so the plan phase does not narrowly fix `start` and leave `run` confused. - -- **F-16 (NIT).** The spec does not state what happens to **already-running environments** that were started under the old behavior. A user with a previously-bound 8888 environment runs `wp-env start` again with the new code — does state get re-resolved? OQ7 hints at this but treats it as "default expectation" without a requirement. If the answer is "behavior is unchanged for environments started before the upgrade; only new starts are affected", say so. If not, define it. - ---- - -## 9. Severity rollup - -- **Blockers (must fix before plan phase): 2** - - **F-2** — "Final deliverable" obligations from the prompt (PR target/branch/issue link, test-plan-lists-ACs) are silently dropped. Either add as R16 or explicitly delegate out of spec scope with one line. - - **F-4** — AC7 ("informational message contract") is not mechanically testable as written. Tighten it to an observable contract or reduce its scope. - -- **Major (should fix before plan phase): 0** (F-2 and F-4 already blocker-level) - -- **Minor (worth fixing, not blocking): 6** - - F-3 (PHP unit tests silence — say something either way) - - F-5 (AC9 unit/integration split unclear) - - F-6 (no direct AC for R6 tri-state at the boundary) - - F-12 (OQ1 should also be a tracked risk R-TriState) - - F-13 (port-resolution TOCTOU — say "inherited, no new mitigation") - - F-15 ("any other command that resolves ports" dropped from spec) - -- **Nits (polish): 5** — F-1, F-7, F-9, F-10, F-11, F-14, F-16. Address opportunistically. - ---- - -## 10. Suggested concrete revisions (prioritized) - -For the spec-writer's next iteration, in priority order: - -1. **(Blocker, F-2)** Add either a new requirement R16 or a clearly-labeled "Spec scope handoff" subsection capturing the prompt's "Final deliverable" obligations: PR targets `trunk` from `try/49843-wp-env-default-port-fallback`, body links #49843, test plan enumerates the acceptance criteria. Suggested wording: *"R16 — PR test plan enumerates the acceptance criteria. The final draft PR's body MUST list AC1–AC10 (or their post-revision equivalents) so reviewers can map each AC to a verification step."* - -2. **(Blocker, F-4)** Rewrite AC7 to express an observable contract. Suggested replacement: - - **Then** the message is emitted only when a fallback actually occurred (no message on the no-fallback path), - - **And** the message is emitted through the same output mechanism (same logger / spinner instance / stream) that `--auto-port` uses today, such that adding a new output path would be a detectable regression in the test suite, - - **And** no new flag is required to suppress the message. - -3. **(Minor, F-3)** Add one sentence to R12 or the assumptions section addressing PHP unit tests: either include `phpunit/` in the regression scope, or explicitly state "no PHP-side regression is expected because changes are JS-only inside `packages/env/`". - -4. **(Minor, F-5)** Split AC9: tighten the in-scope assertion to the merged-config layer (`WP_HOME`, `WP_SITEURL`, `appendPortToWPConfigs` inputs reflect the resolved port) and move "live HTTP reachability" into the manual PR test plan, or say so explicitly. - -5. **(Minor, F-6)** Add an AC verifying R6 directly at the CLI/config boundary: *"Given `--auto-port` unset and `autoPort` unset in config, when configuration is resolved, then the effective `autoPort` value is distinguishable from an explicit `false` (i.e. the tri-state survives end-to-end)."* - -6. **(Minor, F-12)** Promote OQ1 to a tracked risk R-TriState in §7 with an explicit mitigation (the plan phase MUST verify the tri-state survives CLI parsing; an automated test asserts the distinction). - -7. **(Minor, F-13)** Add a one-line note (under §7 or §8) acknowledging port-bind TOCTOU as inherited from PR #74472, with no new mitigation required. - -8. **(Minor, F-15)** Add one sentence to R8 (or a new R) capturing "any other command that resolves ports" — `run`, `clean`, `logs`, etc. — also sees the resolved fallback port. - -9. **(Nits, F-1/F-7/F-9/F-10/F-11/F-14/F-16)** Polish pass: reword AC8 to a behavioral observable; drop the `port-utils`-style nickname in A1; drop the "(sentinel, separate object, post-process flag)" enumeration in OQ3; make the upward-scan directionality explicit in R1 instead of by example; add one sentence on already-running environments. - ---- - -## Verdict - -**REJECTED — REVISIONS REQUESTED** - -The spec is structurally strong: traceability is excellent, out-of-scope handling is thorough, the prompt's named risks are all reflected with mitigations, the open questions are correctly flagged rather than silently invented away, and the spec stays disciplined about WHAT vs. HOW. Were it not for two specific gaps, this would be approvable. - -The two blockers: - -- **F-2** drops the prompt's "Final deliverable" obligations (especially "PR test plan enumerates the acceptance criteria"). Without capturing this, downstream phases lose a checkable handoff. -- **F-4** leaves AC7 mechanically untestable by stating "same channel as today" without an observable contract; the test that satisfies this AC would be flaky or trivial. - -Address F-2 and F-4 (and ideally the six minor findings) and resubmit. The open questions are appropriately deferred and do not block planning, but OQ1 should also be promoted to a risk entry (F-12). diff --git a/.pipelines/49843-wp-env-default-port-fallback/spec-review-2.md b/.pipelines/49843-wp-env-default-port-fallback/spec-review-2.md deleted file mode 100644 index b84f108eeea651..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/spec-review-2.md +++ /dev/null @@ -1,183 +0,0 @@ -# Spec Review — Iteration 2 - -Pipeline: `49843-wp-env-default-port-fallback` -Reviewer role: spec-reviewer (adversarial) -Artifacts under review: -- `prompt.md` -- `spec.md` (v2) -- `spec-review-1.md` (for verifying the round-1 findings landed) - -This review is adversarial. The default posture is rejection. This iteration must additionally verify each round-1 finding closed correctly without over-correction or revision-log drift. - ---- - -## 1. Round-1 finding disposition (the round-2 obligation) - -Walking every finding from `spec-review-1.md` and checking whether the v2 spec actually closes it. "CLOSED" requires the closure to land in the spec body, not just be claimed in the revision log. - -### Blockers - -| Finding | Round-1 ask | v2 closure | Verdict | -|---------|-------------|------------|---------| -| **F-2** — "Final deliverable" obligations dropped (PR target, branch, issue link, test plan lists ACs) | Add a tracked spec requirement or a labeled handoff section | §9 "Spec scope handoff (final-deliverable obligations)" added with PR target, source branch, issue link, AC enumeration. **R16** added making the AC-enumeration obligation a tracked requirement, with explicit traceability to prompt §"Final deliverable". §9 also clearly states these are deliverable obligations rather than user-observable behaviors of `wp-env`, which avoids conflating phases. | **CLOSED** | -| **F-4** — AC7 mechanically untestable as written | Express as observable contract (no message on no-fallback path; goes through same logger/spinner/stream as today; no new suppression flag) | AC7 rewritten verbatim along the suggested observable contract: "emitted only when a fallback actually occurred", "through the same output mechanism — the same logger function, spinner instance, or stream — that `--auto-port` uses today, such that introducing a new output path would be a detectable regression in the test suite", "no new flag is required to suppress the message". R11 tightened to match. | **CLOSED** | - -### Minors - -| Finding | Round-1 ask | v2 closure | Verdict | -|---------|-------------|------------|---------| -| **F-3** — PHP unit test silence | Either include `phpunit/` in regression scope, or state "no PHP regression expected because JS-only" | R17 added: explicitly scopes regression coverage as JS-only inside `packages/env/`, mandates `composer test` green check during implementation, and treats unexpected PHP failure as a spec-level escalation. R-PHPRegress added to §7 referencing PR #74472's prior breakage. | **CLOSED** | -| **F-5** — AC9 unit/integration split unclear | Tighten in-scope assertion to merged-config layer; move live HTTP to manual PR test plan | AC9 split into AC9a (automated config-layer assertion: merged-config values for `WP_HOME`, `WP_SITEURL`, `appendPortToWPConfigs` reflect the resolved port) and AC9b (manual reachability per PR test plan). §5 also restates that live HTTP integration testing is out of scope for the automated suite. | **CLOSED** | -| **F-6** — No direct AC for R6 tri-state at the boundary | Add an AC asserting unset is distinguishable from explicit `false` after config resolution | AC11 added with the suggested wording: "Given `--auto-port` unset and `autoPort` unset in config, when configuration is resolved, then the effective `autoPort` value is distinguishable from explicit `false` ... an automated test asserts this distinction so a future refactor that collapses `undefined → false` fails the test." R6 also extended with end-to-end survival language. | **CLOSED** | -| **F-12** — OQ1 should also be a tracked risk R-TriState | Promote OQ1 to a §7 risk with mitigation; reference AC11 | R-TriState added to §7 with concrete failure scenario (yargs collapsing `undefined → false`), explicit mitigation referencing R6 + AC11, and a directive that the plan phase MUST verify the existing yargs configuration in `packages/env/lib/cli.js`. OQ1 removed from §8. (Note: §8 is now renumbered OQ1–OQ7; the tri-state question is fully migrated to a risk, not duplicated.) | **CLOSED** | -| **F-13** — TOCTOU note missing | Add a one-line note acknowledging port-bind race as inherited from PR #74472 | R-TOCTOU added to §7: "Inherited from PR #74472; no new mitigation required beyond what `--auto-port` already does today. The plan phase need not re-litigate this." | **CLOSED** | -| **F-15** — "any other command that resolves ports" dropped from spec | Add explicit coverage for `run`, `clean`, `logs`, etc. | R8 expanded with an explicit clause naming `run`, `clean`, `logs`, `destroy`, `stop` and requiring the resolved fallback port to flow into those code paths. AC9c added covering the same observable. | **CLOSED** | - -### Nits - -| Finding | Round-1 ask | v2 closure | Verdict | -|---------|-------------|------------|---------| -| **F-1** — Reword AC8 as a behavioral observable | "such that removing the guard fails the test" framing | AC8 reworded: "a named, documented test asserts ... such that **removing the guard fails the test**". | **CLOSED** | -| **F-7** — R6 phase-leak ("no new top-level config option") | Already acceptable in round 1; no action required | No change. Acceptable. | **N/A — round-1 said "right at the line" but acceptable** | -| **F-8** — R3 enumerates concrete user-source mechanisms | Already acceptable in round 1; no action required | No change. Acceptable. | **N/A — already accepted** | -| **F-9** — Drop "`port-utils`-style" nickname in A1 | Replace with "the existing port-availability scanning utility used by PR #74472" | A1 reworded exactly as suggested: "The existing port-availability scanning utility used by PR #74472 ...". Nickname removed. | **CLOSED** | -| **F-10** — A2 names `load-config.js` (borderline HOW) | Round 1 said "borderline acceptable"; no explicit ask | No change; A2 still names the file, which is defensible as scoping. | **ACCEPTED — no closure required** | -| **F-11** — Drop "(sentinel, separate object, post-process flag)" enumeration in OQ3 (now OQ2) | Just say "the plan phase chooses the mechanism" | OQ2 (formerly OQ3) reworded: "The plan phase chooses the mechanism." Enumeration dropped. | **CLOSED** | -| **F-14** — Inconsistent upward-scan directionality | State directionality as an explicit requirement, not by example | R1 extended: "scanning **upward** from the configured default". R2 reuses "the same upward-scan directionality applies." AC1 names the upward direction explicitly; AC2's heading and body say "upward scan" / "scanning upward from `8889`". | **CLOSED** | -| **F-16** — Already-running environments | Add one sentence on already-running environments | OQ6 expanded: "an environment started under the old behavior (pre-upgrade) that is still running when the user upgrades wp-env: behavior is treated as unchanged for that already-running environment until the next `start` re-resolves." | **CLOSED** | - -**Round-1 disposition summary:** All 2 blockers and all 6 minors land in the spec body in the form the round-1 review asked for. All addressable nits land too. No round-1 finding is left unaddressed. - ---- - -## 2. Revision-log accuracy check (round-2-specific) - -Walking each revision-log claim against the spec body to detect drift. - -| Log claim | Body evidence | Drift? | -|-----------|---------------|--------| -| F-2 → §9 added; R16 added | §9 present with the listed content (PR target/branch/issue link/AC enumeration); R16 present in §3 with the cited prompt trace | None | -| F-4 → AC7 rewritten; R11 tightened | AC7 §4 rewritten with the three-clause observable contract; R11 §3 reflects "only on a real move" + "would be a detectable regression in the test suite" | None | -| F-3 → R17 added; R-PHPRegress added | R17 present in §3 with `composer test` mandate; R-PHPRegress present in §7 referencing PR #74472 | None | -| F-5 → AC9 split into AC9a/AC9b | AC9a and AC9b present in §4; §5 also explicitly restates that live HTTP integration testing is out of scope | None | -| F-6 → AC11 added | AC11 present in §4 with the boundary check wording | None | -| F-12 → R-TriState added; OQ1 removed from §8 | R-TriState present in §7; §8 renumbered (OQ1–OQ7) with no tri-state OQ remaining; A3 also references R-TriState | None | -| F-13 → R-TOCTOU added | R-TOCTOU present in §7 | None | -| F-15 → R8 extended; AC9c added | R8 contains the explicit list (`run`, `clean`, `logs`, `destroy`, `stop`); AC9c added in §4 | None | -| F-1, F-9, F-11, F-14, F-16 nits | AC8 reworded; A1 cleaned; OQ2 (formerly OQ3) trimmed; R1/R2 + AC1/AC2 made directional; OQ6 extended for already-running envs | None | - -**No revision-log drift detected.** Every claim in the log is backed by a corresponding edit in the spec body. - ---- - -## 3. Over-correction watch (round-2-specific) - -Checking whether any closure introduced HOW-leaks or scope inflation. - -- **R8 expansion (F-15 closure).** The extension names CLI commands (`run`, `clean`, `logs`, `destroy`, `stop`). These are user-observable command names already present in the wp-env CLI surface — they are WHAT the user types, not HOW the implementation routes them. **No leak.** -- **AC9a closure (F-5).** Names `WP_HOME`, `WP_SITEURL`, `appendPortToWPConfigs`. These are anchored to the prompt's anti-goal ("Do not break `appendPortToWPConfigs` or the `WP_HOME` / `WP_SITEURL` rewriting"). They are scoping anchors traced from the prompt. **No leak.** -- **R17 closure (F-3).** Mandates `composer test` runs during implementation. This is a process obligation on the implementer phase, not a design prescription. The risk it mitigates (R-PHPRegress) is grounded in the prompt's background section. **No leak; no scope inflation.** -- **R-TriState mitigation language (F-12 closure).** "The plan phase MUST verify the existing `--auto-port` yargs configuration in `packages/env/lib/cli.js` and define how the tri-state is preserved before implementation begins." This names a file path (`cli.js`), which is borderline — but the prompt's reference list already names `packages/env/lib/cli.js`, so this is scoping anchored to the prompt. **Acceptable; no fresh HOW.** -- **AC11 (F-6 closure).** Asserts a behavioral observable ("distinguishable from explicit `false`") and explicitly says "an automated test asserts this distinction" without prescribing the test mechanism. **No leak.** -- **§9 "Spec scope handoff" (F-2 closure).** Carefully labels itself as deliverable obligations, not acceptance criteria of the code change. This is exactly the framing round-1 asked for. **No scope inflation; correctly distinguishes WHAT-the-code-does from WHAT-the-PR-contains.** - -**No over-correction detected.** The closures stay inside the prompt's bounds and at the WHAT layer. - ---- - -## 4. Re-checking traceability for the v2 additions - -| New / changed item | Trace | -|--------------------|-------| -| R16 (PR test plan enumerates ACs) | Prompt §"Final deliverable": "summarizing the change, and listing the acceptance criteria in its test plan." | OK | -| R17 (JS-only regression scope; `composer test` mandate) | Prompt §"Background": "an earlier 'always on' version broke PHP unit tests" | OK | -| AC9a / AC9b / AC9c | AC9a/b: prompt anti-goal on `appendPortToWPConfigs`/`WP_HOME`/`WP_SITEURL`; AC9c: prompt §"Goal of this pipeline" — "(and any other command that resolves ports)" | OK | -| AC11 | Prompt anti-goal: "Reuse `autoPort` as a tri-state (`undefined` / `true` / `false`)" | OK | -| R-PHPRegress | Prompt §"Background" PR #74472 history | OK | -| R-TOCTOU | Acknowledged inheritance from PR #74472; not a new obligation | OK (no trace required for an "inherited, no new mitigation" risk) | -| R-TriState | Prompt anti-goal on tri-state `autoPort` | OK | -| §9 "Spec scope handoff" | Prompt §"Final deliverable" | OK | -| Upward-scan directionality (R1/R2/AC1/AC2) | Prompt AC1: "the next free port (8890, 8891, ...)" implies upward; spec now states it explicitly. | OK | - -**All v2 additions trace cleanly.** No CREEP introduced by the round-2 revision. - ---- - -## 5. Re-checking testability for the v2 additions - -| AC | Automatable? | Notes | -|----|--------------|-------| -| AC7 (rewritten) | YES — the three-clause contract gives a test the hooks it needs: assert a "no fallback path" produces no message; assert the fallback path goes through the same logger function or spinner instance the test can spy on; assert no new flag exists to suppress. | Round-1 F-4 closed in a testable form | -| AC9a | YES — pure config-layer assertion against the merged config object | OK | -| AC9b | NO (manual) — explicitly delegated to the PR test plan | Correctly out of automated scope | -| AC9c | YES — exercise `run`/`clean`/etc. with a stubbed prior fallback resolution and assert each command sees the resolved port | OK | -| AC11 | YES — invoke config resolution with both inputs unset; assert the resolved `autoPort` is observably not equal to `false` | OK | - -All new ACs are either automatable or correctly labeled manual. - ---- - -## 6. Re-checking phase boundary for the v2 additions - -- **§9 (handoff)** — explicitly labeled as deliverable obligations, not behavioral ACs. Correct framing; no leak. -- **R17** — process obligation on the implementer phase ("MUST run `composer test` ... before requesting review"). This is a process gate, not a code design. Acceptable. -- **R-TriState mitigation** — names `cli.js` (a file already in the prompt's reference list). Borderline-acceptable as scoping. -- **R8 expansion** — names CLI command surface, not internals. Acceptable. -- **AC11** — asserts an observable, defers test mechanism to plan. Acceptable. - -No fresh phase-boundary violations introduced in v2. - ---- - -## 7. Open question triage (re-check) - -§8 in v2 has 7 OQs (OQ1–OQ7) — OQ1 from v1 was correctly migrated to R-TriState in §7, and the remaining v1 OQs were renumbered. Spot-checking: - -| v2 OQ | Was v1 OQ | Triage | -|-------|-----------|--------| -| OQ1 (per-environment `autoPort`) | v1 OQ2 | Resolvable by reading existing code; defer to plan | -| OQ2 (provenance tracking) | v1 OQ3 | Acceptable design deferral | -| OQ3 (multiple override layers) | v1 OQ4 | Acceptable deferral with stated default | -| OQ4 (env-var override list) | v1 OQ5 | Resolvable by reading existing code | -| OQ5 (no upward port available) | v1 OQ6 | Resolvable by reading existing code | -| OQ6 (stop/destroy + persisted state + already-running envs) | v1 OQ7, extended for F-16 | Acceptable deferral with stated default | -| OQ7 (`CI` truthiness) | v1 OQ8 | Resolvable by reading existing code | - -**No OQ is a blocker for entering the plan phase.** The migration is clean and the renumbering is consistent. - ---- - -## 8. New findings introduced in v2 - -None. The revision is targeted: it closes the listed round-1 findings without rewriting unrelated material. No new requirements snuck in beyond what was asked for. No prior requirements were softened or dropped. - ---- - -## 9. Severity rollup - -- **Blockers: 0** -- **Major: 0** -- **Minor: 0** -- **Nits: 0** - ---- - -## Verdict - -**APPROVED** - -Round-1 findings closed: -- **F-2 (blocker)** — closed by §9 + R16 -- **F-4 (blocker)** — closed by AC7 rewrite + R11 tightening -- **F-3 (minor)** — closed by R17 + R-PHPRegress -- **F-5 (minor)** — closed by AC9 split into AC9a/AC9b -- **F-6 (minor)** — closed by AC11 -- **F-12 (minor)** — closed by R-TriState (OQ1 correctly migrated and removed from §8) -- **F-13 (minor)** — closed by R-TOCTOU -- **F-15 (minor)** — closed by R8 expansion + AC9c -- **F-1, F-9, F-11, F-14, F-16 (nits)** — all closed in the polish pass -- **F-7, F-8, F-10 (nits)** — round 1 already accepted these as borderline-acceptable; no action required - -Open questions accepted as deferrable to the plan phase: OQ1 (per-env `autoPort`), OQ2 (provenance mechanism), OQ3 (multi-layer overrides), OQ4 (env-var override list), OQ5 (no-upward-port failure mode), OQ6 (stop/destroy + already-running env behavior), OQ7 (`CI` truthiness rule). All are either resolvable by reading existing code in the plan phase or are acceptable design deferrals with the spec's stated default. - -The spec is complete, testable, traceable to the prompt, free of cross-phase HOW-leakage, and consistent with the host project's conventions in `AGENTS.md` and `.claude/rp.md`. The revision log accurately reflects the body changes, and the round-2 closures did not over-correct or inflate scope. Ready for the plan phase. diff --git a/.pipelines/49843-wp-env-default-port-fallback/spec.md b/.pipelines/49843-wp-env-default-port-fallback/spec.md deleted file mode 100644 index e5eb1fe00ef06a..00000000000000 --- a/.pipelines/49843-wp-env-default-port-fallback/spec.md +++ /dev/null @@ -1,253 +0,0 @@ -# Phase 1 — Spec - -## Revision log - -Round 2 revisions, in response to `spec-review-1.md`: - -- **F-2 (blocker)** — Added §9 "Spec scope handoff (final-deliverable obligations)" capturing the prompt's PR target (`trunk`), source branch (`try/49843-wp-env-default-port-fallback`), `#49843` link, and the requirement that the test plan enumerate ACs. Also added **R16** so the AC-enumeration obligation is a tracked spec requirement, not a side note. -- **F-4 (blocker)** — Rewrote **AC7** as an observable contract: message MUST be emitted only when a fallback occurred, MUST go through the same logger / spinner / output mechanism that `--auto-port` uses today (such that introducing a new output path would be a detectable test regression), and no new suppression flag MUST be required. Tightened **R11** correspondingly. -- **F-3 (minor)** — Added **R17** explicitly scoping regression coverage to JS unit tests inside `packages/env/` and noting "no PHP-side regression is expected because changes are JS-only inside `packages/env/`". Added matching risk **R-PHPRegress** in §7 referencing PR #74472's earlier always-on attempt that broke PHP unit tests, with a concrete mitigation: the implementer phase MUST run `composer test` (or the equivalent PHP unit suite) at least once and confirm green before requesting review, and any unexpected PHP failure becomes a spec-level escalation. -- **F-5 (minor)** — Split **AC9** into **AC9a** (unit-testable: merged-config values used by `WP_HOME` / `WP_SITEURL` / `appendPortToWPConfigs` reflect the resolved port) and **AC9b** (manual / PR test plan: live HTTP reachability at the printed URL). The spec now states which AC the automated suite must cover and which the PR test plan handles. -- **F-6 (minor)** — Added **AC11** verifying R6 directly at the CLI/config boundary: an unset `--auto-port` flag combined with an unset `autoPort` config field MUST be distinguishable from explicit `false` after configuration is resolved. -- **F-12 (minor)** — Promoted OQ1 to a tracked risk **R-TriState** in §7 with mitigation (plan phase MUST confirm tri-state survival from CLI through merge; an automated test asserts the distinction — covered by AC11). Removed OQ1 from §8. -- **F-13 (minor)** — Added a one-line risk **R-TOCTOU** in §7 acknowledging port-bind race as inherited from PR #74472, no new mitigation required. -- **F-15 (minor)** — Added explicit "any other command that resolves ports" coverage to **R8** and a new **AC9c** so commands beyond `start` (e.g. `run`, `clean`, `logs`) also see the resolved fallback port. -- **F-1, F-9, F-11, F-14, F-16 (nits)** — Reworded AC8 as a behavioral observable; dropped the "`port-utils`-style" nickname in A1; dropped the "(sentinel, separate object, post-process flag)" enumeration in OQ3 (now OQ2); added explicit upward-scan directionality to R1; added one sentence (now part of OQ6) on already-running environments. - ---- - -Pipeline: `49843-wp-env-default-port-fallback` -Linked issue: WordPress/gutenberg#49843 -Scope: `packages/env/` (the `@wordpress/env` CLI). No other packages. - -This spec describes WHAT must be true after the change ships. It does not propose a design, file layout, or implementation. The plan phase owns those. - ---- - -## 1. Goal statement - -A contributor who runs `wp-env start` for the first time, with no `.wp-env.json` (or with a `.wp-env.json` that does not pin `port` / `testsPort`), must succeed even when the default ports `8888` (development) or `8889` (tests) are already bound by another process on the host. `@wordpress/env` resolves the next available port automatically and starts the environment there. Contributors who explicitly configured a port keep today's behavior — the start fails loudly so their explicit choice is honored — unless they have separately opted into auto-fallback for explicit ports via `--auto-port` / `"autoPort": true`. - ---- - -## 2. Stakeholders - -- **First-time and casual contributors to WordPress/Gutenberg.** They get a working dev environment from `npm install && npm run wp-env start` even when 8888/8889 are taken by another local stack, without needing to learn `.wp-env.json`, `--auto-port`, or Docker port-binding errors. -- **Plugin and theme authors using `@wordpress/env` standalone.** Same out-of-the-box win: they do not need to author config to get a usable dev URL on a busy laptop. -- **Existing wp-env users who have pinned ports.** They are explicitly protected: their pinned port will not be silently moved. Behavior on their machines is unchanged unless they opt in. -- **CI operators (Gutenberg core CI and downstream consumers).** They are explicitly protected: the existing `process.env.CI` guard keeps default-port fallback disabled, so test suites that key off `8888` / `8889` stay deterministic. -- **Maintainers of `packages/env/`.** They get the smaller out-of-box-friction support load promised by issue #49843, with the same opt-in/opt-out surface they shipped in PR #74472, just extended to the unconfigured case. - -The change reaches stakeholders through: - -- the next `@wordpress/env` release on npm, -- the bundled `wp-env` CLI used inside the gutenberg monorepo, -- `packages/env/README.md` documenting the new default and the `"autoPort": false` opt-out, -- `packages/env/CHANGELOG.md`. - ---- - -## 3. Requirements - -Each requirement is atomic, testable, and traceable to a sentence in `prompt.md`. "Default port" means a port whose value comes from `DEFAULT_ENVIRONMENT_CONFIG` and was not overridden by `.wp-env.json`, `.wp-env.override.json`, an environment variable, a CLI flag, or any other supported override mechanism. - -1. **R1 — Auto-fallback on unconfigured default development port.** When the development port is a default (not user-set) and the resolved port is busy on the host, `wp-env start` MUST resolve to the next available port — scanning **upward** from the configured default — and proceed. (Traces to: prompt §"Goal of this pipeline"; AC1.) -2. **R2 — Auto-fallback on unconfigured default tests port.** R1 also applies to the tests port (`testsPort`, default `8889`) independently of the development port; the same upward-scan directionality applies. (Traces to: AC1.) -3. **R3 — User-set ports are never silently moved by default.** When a port value originates from any user-supplied source (root `.wp-env.json`, `.wp-env.override.json`, environment variable override, or any other documented override mechanism), and that port is busy, `wp-env start` MUST surface the existing port-busy failure and MUST NOT pick a different port. (Traces to: prompt §"Goal of this pipeline" paragraph 2; AC2.) -4. **R4 — `--auto-port` and `"autoPort": true` keep their PR #74472 semantics.** When the user opts in via the CLI flag or the config field, auto-fallback MUST apply to all ports — both default and user-set. (Traces to: prompt §"Goal of this pipeline" paragraph 3; AC3; anti-goal "Do not introduce new top-level config options".) -5. **R5 — Explicit `"autoPort": false` is a hard opt-out, even for default ports.** When the user has set `"autoPort": false` in config (any layer), default-port fallback MUST NOT happen; a port-busy failure surfaces as it does today. This MUST work without setting `CI=1`. (Traces to: prompt §"Goal of this pipeline" paragraph 3; AC4; anti-goal about reusing `autoPort` as tri-state.) -6. **R6 — `autoPort` is interpreted as tri-state.** The semantics MUST distinguish three states: `undefined` (unset → new "auto on defaults only" behavior), `true` (full opt-in, today's behavior), `false` (full opt-out). No new top-level config option is introduced for this distinction. The tri-state MUST survive end-to-end from CLI parsing through config merge so that "unset" is observably distinct from explicit `false`. (Traces to: prompt §"Anti-goals".) -7. **R7 — `CI=1` continues to disable all auto-fallback.** When `process.env.CI` is truthy, auto-fallback MUST NOT happen for any port, regardless of `autoPort` value or whether the port is default or user-set. (Traces to: prompt §"Background"; AC5.) -8. **R8 — Resolved port is the source of truth for downstream URL/config rewriting, across all wp-env commands that resolve ports.** Any consumer that today reads the resolved port (e.g. `appendPortToWPConfigs`, `WP_HOME`, `WP_SITEURL`) MUST receive the post-fallback port, so the started environment is reachable at the URL the CLI prints. This contract applies not only to `start` but to any other wp-env command that resolves ports (e.g. `run`, `clean`, `logs`, `destroy`, `stop`); the resolved fallback port MUST flow through to those code paths so they operate against the actually-bound environment. (Traces to: prompt §"Goal of this pipeline" — "(and any other command that resolves ports)" — and prompt §"Anti-goals".) -9. **R9 — Default port constants are unchanged.** `DEFAULT_ENVIRONMENT_CONFIG.port` and `testsPort` MUST remain `8888` and `8889`. The fallback is a runtime resolution step, not a default value change. (Traces to: prompt §"Anti-goals".) -10. **R10 — Existing CLI flags are not renamed or deprecated.** `--auto-port` and `"autoPort"` keep their existing names, types, and CLI surface. (Traces to: prompt §"Out of scope".) -11. **R11 — Informational CLI output for fallback reuses the existing channel and only fires on a real move.** When auto-fallback moves a port (whether on a default port via the new behavior or on an explicit port via `--auto-port`), the CLI MUST inform the user via the same logger / spinner / output mechanism already used by `--auto-port` today, such that introducing a new output path would be a detectable regression in the test suite. The message MUST NOT fire on the no-fallback path. No new always-on chatter is introduced and no new suppression flag is required. (Traces to: prompt §"Anti-goals".) -12. **R12 — Existing JS test suites stay green.** All existing JS unit tests in `packages/env/lib/test/` and `packages/env/lib/config/test/` MUST continue to pass. Snapshots that legitimately change must be reviewed and intentional. (Traces to: AC6.) -13. **R13 — New tests cover the primary behaviors.** New automated tests MUST cover: R1+R2 (default fallback), R3 (explicit-port strict), R4 (`autoPort: true` still falls back on explicit ports), R5 (`autoPort: false` strict on defaults), R7 (CI guard), and R6 (tri-state survives end-to-end). (Traces to: AC6.) -14. **R14 — Documentation updated.** `packages/env/README.md` MUST describe the new default behavior and the `"autoPort": false` opt-out. `packages/env/CHANGELOG.md` MUST list the user-visible change under the next unreleased version. (Traces to: AC7.) -15. **R15 — Scope confinement.** All code changes MUST live inside `packages/env/`. No edits to other packages, the Docker layer, the WordPress runtime, or public TypeScript types beyond what this feature strictly requires. (Traces to: prompt §"Out of scope".) -16. **R16 — PR test plan enumerates the acceptance criteria.** The final draft PR's body MUST list the acceptance criteria (AC1 through the highest-numbered AC defined here, including AC9a/AC9b/AC9c sub-criteria) so reviewers can map each AC to a verification step in the PR description. (Traces to: prompt §"Final deliverable" — "summarizing the change, and listing the acceptance criteria in its test plan".) -17. **R17 — Regression scope is explicitly JS-only.** Because the change is confined to JS inside `packages/env/`, no PHP-side regression is expected. The implementer phase MUST nevertheless run the project's PHP unit suite (`composer test` or equivalent) at least once and confirm it remains green before requesting review, since PR #74472's earlier always-on attempt at this feature broke PHP unit tests. Any unexpected PHP failure during implementation becomes a spec-level escalation. (Traces to: prompt §"Background" — "an earlier 'always on' version broke PHP unit tests".) - ---- - -## 4. Acceptance criteria - -Given/When/Then form. Each criterion is independently verifiable by an automated test in `packages/env/` or by the documented manual reproduction in the final PR's test plan. - -### AC1 — Default development port falls back automatically (upward scan) - -- **Given** a project with no `.wp-env.json` (or one that does not set `port`), -- **And** port `8888` on the host is bound by another process, -- **And** `process.env.CI` is unset, -- **When** the contributor runs `wp-env start`, -- **Then** the start command succeeds, -- **And** the development environment is bound to the next available port found by scanning **upward** from `8888` (e.g. `8890`), -- **And** the CLI informs the user via the same output mechanism that `--auto-port` uses today (see AC7). - -### AC2 — Default tests port falls back automatically (independent of dev port, upward scan) - -- **Given** the same conditions as AC1 but with `8889` busy and `8888` free, -- **When** `wp-env start` runs, -- **Then** the development environment binds to `8888` and the tests environment binds to the next available port found by scanning upward from `8889`. - -### AC3 — Explicitly configured port stays strict by default - -- **Given** a `.wp-env.json` that sets `"port": 9000`, -- **And** port `9000` on the host is bound by another process, -- **And** neither `--auto-port` nor `"autoPort": true` is set, -- **When** `wp-env start` runs, -- **Then** the start fails with the existing port-busy error message, -- **And** no other port is silently used. - -### AC4 — `--auto-port` / `"autoPort": true` still falls back on explicit ports - -- **Given** a `.wp-env.json` that sets `"port": 9000`, -- **And** port `9000` on the host is bound, -- **And** the contributor runs `wp-env start --auto-port` (or sets `"autoPort": true`), -- **When** the command runs, -- **Then** the start succeeds against the next available port above `9000`, -- **And** the CLI informs the user via the same output mechanism that `--auto-port` uses today (see AC7). - -### AC5 — `"autoPort": false` opts out of default-port fallback too - -- **Given** a `.wp-env.json` that sets `"autoPort": false` and does NOT set `port`, -- **And** port `8888` on the host is bound, -- **And** `process.env.CI` is unset, -- **When** `wp-env start` runs, -- **Then** the start fails with the existing port-busy error message, -- **And** no other port is silently used. - -### AC6 — `CI=1` continues to disable all auto-fallback - -- **Given** `process.env.CI` is truthy, -- **And** port `8888` on the host is bound, -- **And** the project has no `.wp-env.json` (or has any `autoPort` value, including `true`), -- **When** `wp-env start` runs, -- **Then** the start fails with the existing port-busy error message, -- **And** no other port is silently used. - -### AC7 — Informational message contract (observable) - -- **Given** any scenario in which auto-fallback moves a port (AC1, AC2, AC4), -- **When** the CLI emits the "moved port" notice, -- **Then** the message is emitted only when a fallback actually occurred (no message on the no-fallback path), -- **And** the message is emitted through the same output mechanism — the same logger function, spinner instance, or stream — that `--auto-port` uses today, such that introducing a new output path would be a detectable regression in the test suite, -- **And** no new flag is required to suppress the message. - -### AC8 — CI guard regression is detectable - -- **Given** the implementation of R7, -- **When** the test suite runs, -- **Then** a named, documented test asserts that `process.env.CI === '1'` (or other truthy values defined by the inherited guard) disables fallback regardless of `autoPort` state, such that **removing the guard fails the test**. - -### AC9a — Resolved port flows downstream into merged config (automated) - -- **Given** a fallback occurred per AC1, -- **When** the merged configuration object is computed, -- **Then** the values used for `WP_HOME`, `WP_SITEURL`, and the inputs to `appendPortToWPConfigs` all reflect the post-fallback port. This is unit-testable at the config layer without requiring Docker. - -### AC9b — Live reachability at printed URL (manual / PR test plan) - -- **Given** a fallback occurred per AC1, -- **When** the environment is up on the contributor's machine, -- **Then** the URL printed by the CLI is reachable via HTTP. This is verified manually as part of the PR test plan rather than in the automated suite. - -### AC9c — Other wp-env commands see the resolved fallback port - -- **Given** a previous `wp-env start` resolved the development environment to a fallback port (e.g. `8890`), -- **When** a subsequent wp-env command that resolves ports (`run`, `clean`, `logs`, `destroy`, `stop`, etc.) runs in the same project, -- **Then** that command operates against the actually-bound port, not against the original default `8888`. - -### AC10 — Existing tests stay green - -- **Given** the change is implemented, -- **When** `npm run test:unit packages/env` (and the equivalent for `packages/env/lib/config/test/`) runs, -- **Then** all previously passing tests still pass, -- **And** any snapshot changes are reviewed and intentional, not incidental. - -### AC11 — `autoPort` tri-state survives end-to-end (boundary check for R6) - -- **Given** `--auto-port` unset on the CLI invocation and `autoPort` unset in config, -- **When** configuration is resolved, -- **Then** the effective `autoPort` value is **distinguishable** from an explicit `false` (i.e. the tri-state is preserved through CLI parsing and config merge), -- **And** an automated test asserts this distinction so a future refactor that collapses `undefined → false` fails the test. - ---- - -## 5. Out of scope - -Restated and extended from the prompt. - -- **Phase 2 design doc.** RP does not implement a separate design-doc phase yet; the spec → plan → implementation chain proceeds directly. -- **`mysqlPort` behavior.** Already supports Docker-native auto-assignment via `null`; not touched here. -- **Docker layer changes.** No changes to Docker image, Compose generation strategy, or container networking beyond what consuming the resolved port already requires. -- **WordPress runtime changes.** No PHP, no WordPress core, no theme/plugin runtime behavior. -- **Public TypeScript type surface.** No new exported types or breaking changes to existing ones beyond what this feature minimally needs. -- **Renaming or deprecating `--auto-port` / `"autoPort"`.** The names stay. No deprecation warning is added. -- **New top-level config options.** Reuse `autoPort` as a tri-state instead of inventing a second flag. -- **Cross-package refactors.** All changes live inside `packages/env/`. -- **Changing default port constants.** `8888` / `8889` stay as the defaults. -- **Always-on "moved port" chatter, or new flag to suppress it.** Reuse the existing `--auto-port` output mechanism. -- **Telemetry, analytics, or remote reporting** of fallback events. -- **Behavior under non-`CI` automation environments** that do not set `CI`. Those continue to be treated as ordinary developer machines (auto-fallback applies on defaults). Setting `"autoPort": false` is the documented opt-out for such cases. -- **Live HTTP integration testing in the automated suite.** Reachability is verified manually per AC9b in the PR test plan; the automated suite stops at AC9a's config-layer assertions. - ---- - -## 6. Assumptions - -These are treated as true without separate verification. If any turns out to be false, the plan or implementation phase must surface it. - -- **A1.** The existing port-availability scanning utility used by PR #74472 correctly detects busy ports on the host, scans upward, and can take an `exclude` list so the dev and tests resolutions do not collide. -- **A2.** The existing `process.env.CI` guard in `packages/env/lib/config/load-config.js` is the only CI-determinism gate that needs to keep applying; no other package or process needs to be taught about it. -- **A3.** The current CLI has a place where `--auto-port` is parsed and merged into config such that a tri-state `autoPort` (`undefined` / `true` / `false`) can be represented end-to-end without ambiguity. (See R-TriState risk in §7: if the existing CLI/yargs layer coerces missing `--auto-port` to `false`, the plan phase must define how the tri-state survives; AC11 guarantees a regression test exists.) -- **A4.** "User-set" can be detected in config processing by tracking whether `port` / `testsPort` came from `DEFAULT_ENVIRONMENT_CONFIG` versus from a user source. The exact mechanism is a design concern, not a spec concern. -- **A5.** The "informational message" output mechanism used by today's `--auto-port` is appropriate for the new default-fallback case too, both in tone and verbosity. No separate UX research is required. -- **A6.** README and CHANGELOG conventions in `packages/env/` are stable; the doc-writer phase can update them in place without coordinating release notes elsewhere. -- **A7.** `npm run test:unit` for `packages/env/` is sufficient to validate R12; the wp-env package does not have hidden integration tests outside the `lib/test/` and `lib/config/test/` trees that require separate invocation. -- **A8.** Existing snapshots in `packages/env/lib/test/` are stable enough that the only legitimate snapshot churn comes from this change, so any churn is reviewable. - ---- - -## 7. Risks and mitigations - -- **R-CI — CI determinism regresses.** A future contributor refactors port resolution and accidentally drops the `process.env.CI` gate, silently moving ports in CI runs and breaking suites that key off `8888` / `8889`. **Mitigation:** R7 + AC8 mandate a named test that asserts the CI guard such that removing the guard fails the test. -- **R-Explicit — A user-set port is silently moved.** A contributor pinned `port: 9000` for a reason (proxy, hosts file, integration with another tool); silently moving to 9001 produces a working-but-wrong environment. **Mitigation:** R3 + R6 (tri-state `autoPort`) keep explicit ports strict by default; AC3 covers it with an automated test. -- **R-OptIn — `--auto-port` opt-in is broken by the refactor.** Contributors who already rely on `--auto-port` to escape pinned-port conflicts find their workflow regressed. **Mitigation:** R4 + AC4 require that `true` continues to override everything (default and explicit), preserving PR #74472 semantics. -- **R-OptOut — No way to opt out without `CI=1`.** A contributor wants strict default-port behavior locally without polluting their environment with `CI=1`. **Mitigation:** R5 + AC5 make `"autoPort": false` a documented hard opt-out. -- **R-Snapshots — Test snapshots in `packages/env/lib/test/` go stale.** Tri-stating `autoPort` and threading "user-set" provenance can ripple into serialized config snapshots. **Mitigation:** R12 explicitly calls out keeping existing tests green; the implementer phase reviews each snapshot diff for intent; AC10 makes "intentional snapshot diffs only" a checkable criterion. -- **R-UX — Always-on port-moved chatter annoys users.** If the informational message fires noisily even when no move happened, it becomes spam. **Mitigation:** R11 + AC7 constrain the message to actual moves and to the existing output mechanism. -- **R-DownstreamURL — Resolved port not propagated.** The dev environment starts on a moved port but the printed URL, `WP_HOME`, or `appendPortToWPConfigs` still reflect the original, leaving the user with a broken-looking site. Or, secondarily, the `start` path is patched but other commands (`run`, `clean`, `logs`) still consult the original default. **Mitigation:** R8 + AC9a + AC9c require the resolved port to be the source of truth downstream and across commands. -- **R-PortCollision — Dev and tests resolve to the same port.** Both default ports are busy and the scan produces overlapping next-free ports. **Mitigation:** Assumption A1 covers `exclude`-list support. If A1 turns out to be false, the plan phase must add coordination as a design concern. -- **R-TriState — `autoPort` tri-state collapses at the CLI boundary.** If the existing yargs definition coerces an unset `--auto-port` to `false` (or any layer collapses `undefined → false`), the entire feature silently regresses to today's behavior on default ports — the new R1/R2 paths never fire because every config is interpreted as "explicit opt-out". **Mitigation:** R6 + AC11 require the tri-state to survive end-to-end with an automated boundary test that asserts unset is distinguishable from explicit `false`. The plan phase MUST verify the existing `--auto-port` yargs configuration in `packages/env/lib/cli.js` and define how the tri-state is preserved before implementation begins. -- **R-PHPRegress — PHP unit tests regress.** PR #74472's earlier always-on attempt at this feature broke PHP unit tests, which is why it shipped opt-in instead. Even though this revision is JS-only, anything that changes wp-env's default behavior risks tripping PHP suites that consume wp-env-derived URLs or ports. **Mitigation:** R17 mandates a `composer test` (or equivalent PHP unit suite) green check during implementation before review; any unexpected PHP failure escalates back to spec/plan rather than being silently worked around. -- **R-TOCTOU — Port-bind race.** A port reads as free during the scan but is grabbed by another process before Docker binds it. **Mitigation:** Inherited from PR #74472; no new mitigation required beyond what `--auto-port` already does today. The plan phase need not re-litigate this. - ---- - -## 8. Open questions - -The prompt does not pin these down. They are flagged for the plan phase, not invented here. - -- **OQ1 — Per-environment `autoPort`.** Can `autoPort` be set per-environment (e.g. only for `tests`, not `development`) under existing config-merging rules, or is it root-only? The prompt does not say; the spec treats whatever the existing PR #74472 surface allows as the contract. -- **OQ2 — Provenance tracking for "user-set" ports.** The spec requires distinguishing default vs. user-set ports (R3, R6) but does not specify how. The plan phase chooses the mechanism. -- **OQ3 — Multiple override layers.** When `port` comes from `.wp-env.override.json` but the base `.wp-env.json` did not set it, is that "user-set"? The spec answers yes (any user-supplied source counts as user-set per R3) but the plan phase should confirm the override-merging code can be taught this distinction. -- **OQ4 — `WP_ENV_PORT` / environment-variable overrides.** The prompt mentions "environment variable override" as a user-set source. The exact list of env vars wp-env honors as user-set port sources should be enumerated by the plan phase against the current `parse-config.js` code, not invented here. -- **OQ5 — Behavior when no upward port is available.** The prompt does not specify the failure mode if scanning runs out of ports. The spec assumes the existing scanner already has a defined failure mode (per A1); the plan phase should confirm and, if needed, surface a sensible error. -- **OQ6 — Interaction with `wp-env destroy` / `wp-env stop` and persisted state, including already-running environments.** If a previous run bound the dev environment to `8890` via fallback, do subsequent `stop`/`destroy`/`start` cycles need to remember the port, or do they re-resolve each time? Likewise, an environment started under the old behavior (pre-upgrade) that is still running when the user upgrades wp-env: behavior is treated as unchanged for that already-running environment until the next `start` re-resolves. The prompt is silent. The spec treats re-resolution on each `start` as the default expectation, with persisted-state changes considered out of scope unless the plan phase finds a concrete blocker. -- **OQ7 — `CI` truthiness semantics.** `process.env.CI` can be `"true"`, `"1"`, `"false"`, or any string; today's guard's exact truthiness rule (per the existing PR #74472 implementation) is the contract this spec inherits. The plan phase should confirm the existing rule and reuse it verbatim, not redefine it. - ---- - -## 9. Spec scope handoff (final-deliverable obligations) - -Captured here so they are not silently dropped. These obligations come from prompt §"Final deliverable" and are the spec's contract with the orchestration / doc-writer / PR-creation phases. The spec does not own their execution, but it does own that they are not forgotten. - -- **PR target.** Final draft PR opens against `WordPress/gutenberg` `trunk`. -- **Source branch.** PR is opened from branch `try/49843-wp-env-default-port-fallback` (provisioned via the EnterWorktree convention in `.claude/rp.md`). -- **Issue link.** PR body links `#49843`. -- **Test plan content.** Per **R16**, the PR body's test plan section enumerates the acceptance criteria defined in §4 of this spec (AC1–AC11, including AC9a/AC9b/AC9c) so reviewers can map each AC to a verification step. -- **PR is a draft until docs and code-review phases sign off.** The spec does not gate final ready-for-review; it simply pins the deliverable shape. - -These obligations are NOT acceptance criteria of the code change itself (they are not user-observable behaviors of `wp-env`); they are deliverable obligations of the pipeline. Capturing them here closes the F-2 gap from spec-review-1 without conflating "what the code does" with "what the PR contains".