diff --git a/.github/workflows/differential.yml b/.github/workflows/differential.yml index 0f54606..17dad25 100644 --- a/.github/workflows/differential.yml +++ b/.github/workflows/differential.yml @@ -13,6 +13,20 @@ jobs: timeout-minutes: 20 env: COMPOSER_AUTH: ${{ secrets.COMPOSER_AUTH_JSON }} + RUNTIME_TEST_DB_HOST: '127.0.0.1:3306' + RUNTIME_TEST_DB_USER: root + RUNTIME_TEST_DB_PASSWORD: runtime-ci-fixture + services: + database: + image: mariadb:11.4 + env: + MARIADB_ROOT_PASSWORD: runtime-ci-fixture + MARIADB_ROOT_HOST: '%' + ports: + - 3306:3306 + options: >- + --health-cmd="healthcheck.sh --connect --innodb_initialized" + --health-interval=5s --health-timeout=5s --health-retries=20 steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Set up compatible oracle PHP @@ -31,13 +45,13 @@ jobs: coverage: none - name: Install candidate dependencies run: composer install --no-interaction --no-progress --no-plugins --no-scripts - - name: Install VCS fixture tools - run: sudo apt-get update -qq && sudo apt-get install -y -qq mercurial subversion - - name: Verify real VCS integrations - run: php vendor/bin/phpunit --filter VcsIgnoreStepTest --no-progress --fail-on-skipped + - name: Install VCS and database fixture tools + run: sudo apt-get update -qq && sudo apt-get install -y -qq mercurial subversion mariadb-client + - name: Prepare pinned WordPress and WP-CLI fixtures + run: python3 tools/ci-fixtures.py - name: Verify executed evidence for every parity row run: | - php vendor/bin/phpunit --no-progress + php vendor/bin/phpunit --no-progress --fail-on-skipped php vendor/bin/phpunit --no-logging --list-tests-xml build/test-list.xml python3 -m unittest discover -s tools/tests python3 tools/parity-evidence.py @@ -51,4 +65,5 @@ jobs: build/differential/report.json build/parity-evidence.json build/phpunit.xml + build/ci-fixtures/manifest.json if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index 74c40ed..3327ed6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,8 +1,8 @@ # SymPress Runtime agent contract -## Current gate +## Current delivery state -The project owner approved Phase 0 and authorized Phase 1 on 2026-09-29. Implement the foundation according to the accepted ADRs. Consumer migration remains in Phase 6. +The project owner approved Phase 0 on 2026-09-29 and subsequently authorized PR review and merges. Phases 1–6 are merged. Implement review corrections according to the accepted ADRs and track fresh evidence in `docs/acceptance.md`; do not treat historical phase reports as current completion claims. ## Implementation contract after approval diff --git a/CHANGELOG.md b/CHANGELOG.md index b3f3580..70cc1ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,14 @@ ## Unreleased - Approved source-derived WP Starter parity inventory and architecture decisions. -- Begin the isolated Composer/standalone runner, configuration/schema, CLI and service foundation. -- Add real Composer fixture tests and PHP 8.5 / PHPUnit 13 quality gates. +- Implement isolated Composer and standalone setup, all twelve default steps, configuration validation, extension services/events, legacy API adapters and migration diagnostics. +- Generate WordPress configuration with an independent environment-parser payload, stable salts, managed sections, environment caches and production dumps. +- Add kernel diagnostics, cache maintenance and optional boot ownership. +- Preserve WPackagist/private/path package installation and bounded offline recovery after Composer plugins are disabled. +- Preserve correctly installed root and nested layouts, and replace URL-dropin symlinks only after download verification. +- Restore early Composer autoload through `wp-config-autoload` (enabled by default in legacy profiles), and bound service downloads through `download-max-bytes`. +- Honor disabled compatibility for legacy environment sentinels and constant mappings, including cached and dumped environments. +- Provide deployment and user guides, explicit upstream interface attribution, and a CI suite requiring real database/WordPress/WP-CLI fixtures with no skipped tests. +- Add real Composer fixture tests, pinned differential comparisons and PHP 8.5 / PHPUnit 13 quality gates. -This is an incomplete development branch, not a production release or a completed drop-in replacement. +Unreleased work remains subject to the acceptance record; passing a fixture suite does not establish compatibility with every third-party extension or installer layout. diff --git a/NOTICE b/NOTICE index 799daa6..c341f79 100644 --- a/NOTICE +++ b/NOTICE @@ -13,6 +13,16 @@ resources/legacy-mu-loader.php.txt and resources/legacy-mu-loader-dev.php.txt ar the pinned upstream MU loader templates, retained only for byte-exact recognition of generated files during migration. +Source-derived API compatibility files (verified against upstream dev revision +059bbc9198ac51dee86c5233b6b006ca4d8008a4): +- src/Process/PhpTool.php adapts src/Cli/PhpTool.php: tool interface method + signatures, with SymPress namespace and service types. +- src/Step/NullStep.php adapts src/Step/NullStep.php: extensible no-op step + contract and return values, using SymPress StepInterface. +- src/Step/ScriptHaltSignal.php adapts src/Step/ScriptHaltSignal.php: propagation + and step-halting factories/accessors, with readonly promoted properties. +These adaptations remain covered by the following retained upstream MIT notice. + The MIT License (MIT) Copyright (c) 2023 Giuseppe Mazzapica and contributors. diff --git a/README.md b/README.md index 6728056..f54fd2a 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # SymPress Runtime -`sympress/runtime` will replace WP Starter across the SymPress ecosystem. +`sympress/runtime` provides Composer project setup and generated WordPress runtime configuration for SymPress, with WP Starter migration support. -**Status: Phases 1-5 are available as stacked draft PRs. Phase 6 implements migration and compatibility diagnostics; full parity acceptance and consumer migration remain open. Phase 0 was approved on 2026-09-29.** +**Status: Phases 1–6 are merged. Review corrections and final parity acceptance are tracked in [the acceptance record](docs/acceptance.md). No stable release or universal drop-in acceptance is claimed.** Requires PHP 8.5 and Symfony 8.1. The Composer plugin runs application code in a separate PHP process. The standalone binary also recovers standard WordPress package paths after `composer install --no-plugins`, before loading project code. WPackagist, private repositories and local Composer packages keep the regular installer workflow; dependency resolution and downloads stay with Composer. See [the package-layout boundaries](docs/adr/0019-standalone-wordpress-package-layout.md) and [the acceptance record](docs/acceptance.md). @@ -15,6 +15,13 @@ composer qa All twelve inventoried setup steps are implemented, together with scripts/events, extension autoloading, legacy step adapters, environment dumps and cache flushing. Kernel maintenance, optional boot ownership and doctor/check support standalone, Composer and kernel-console workflows. Tests cover isolated Composer execution, independent generated configuration, real WordPress/WP-CLI/VCS fixtures and an actual compiled kernel on a read-only filesystem. +- [Getting started](docs/getting-started.md) +- [Settings cheat sheet](docs/settings-cheat-sheet.md) +- [Environment, caches and dumps](docs/environment.md) +- [Generated wp-config and sections](docs/wp-config.md) +- [Setup steps](docs/steps.md) +- [WP-CLI](docs/wp-cli.md) +- [Deployment and payload retention](docs/deployment.md) - [Parity acceptance matrix](docs/parity.md) - [Source evidence and reproducibility](docs/source-evidence.md) - [Architecture decisions](docs/adr/README.md) diff --git a/docs/acceptance.md b/docs/acceptance.md index 42b5054..7c9af0c 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -1,12 +1,12 @@ # Runtime acceptance record -The implementation is available through the six stacked Runtime PRs, ending at [Phase 6](https://github.com/SymPress/runtime/pull/6). Consumer changes are separate drafts: [starter #29](https://github.com/SymPress/starter/pull/29) and [demo #49](https://github.com/SymPress/demo/pull/49). Their lockfiles pin Runtime commit `cfc5ffd`. This record deliberately keeps final acceptance open. +All six Runtime implementation PRs are merged; [Phase 6](https://github.com/SymPress/runtime/pull/6) merged as `b1c166205cd907b93a216b82b65b2d49ffec3f32` on 2026-09-30. Review corrections are being validated on top of that baseline. Consumer changes remain separate open PRs: [starter #29](https://github.com/SymPress/starter/pull/29) and [demo #49](https://github.com/SymPress/demo/pull/49). Their final dependency locks and checks must be verified after the Runtime corrections merge. This record deliberately keeps final acceptance open. ## Reproduced evidence -- Full local package QA passes with 1,043 tests / 7,298 assertions, no skips, coding standards and PHPStan max. +- Full local package QA after the review corrections passes with 1,059 tests / 7,365 assertions, no skips, coding standards and PHPStan max. - All 407 source-inventory rows map to executed PHPUnit behavioral tests. The evidence checker also rejects duplicate or unknown IDs, missing results, failed tests and skipped-only rows. It does not claim complete branch coverage from a passing test count. -- The isolated differential harness passes 249 cases against the exact release and development commits in `upstream-inventory.json`. It compares constant types and values, environment precedence, generated configuration execution, cache behavior, content hashes/links, WP-CLI arguments, lifecycle callbacks, extension loading, effective step order, all nineteen section edits, MU-loader execution, parsed WP-CLI YAML and active env-example assignments. Intentional differences are asserted as exact expected values, not unrestricted exclusions. +- The isolated differential harness passes 251 cases against the exact release and development commits in `upstream-inventory.json`, including early Composer classes and hooks. It compares constant types and values, environment precedence, generated configuration execution, cache behavior, content hashes/links, WP-CLI arguments, lifecycle callbacks, extension loading, effective step order, all nineteen section edits, MU-loader execution, parsed WP-CLI YAML and active env-example assignments. Intentional differences are asserted as exact expected values, not unrestricted exclusions. - Real WordPress SHORTINIT connects to a disposable MariaDB database without a Composer autoloader. Its production build dump also boots under an unprivileged identity with read-only project files and unchanged file hashes. A separate actual SiteKernel test loads a precompiled production container under the same permission constraint. - Fresh, separate DDEV starter and demo projects install WordPress, authenticate into the admin dashboard, boot the kernel once and run `wp console debug:container`. Browser checks capture HTTP 200 responses and zero JavaScript errors. Starter QA passes 6 tests / 47 assertions; demo QA passes 27 tests / 213 assertions plus REST/block/render/ORM smoke. - Repeated normal Composer installation, a global `composer install --no-plugins`, and the standalone runner preserve 543 starter and 664 demo artifact hashes/link targets. The replay follows each project's configured content path and includes built demo assets and the deterministic package-layout record. Both consumer QA suites pass again after this recovery. @@ -15,13 +15,21 @@ The implementation is available through the six stacked Runtime PRs, ending at [ ## Open acceptance gates 1. **Layout boundary review.** The reproduced starter/demo and WPackagist no-plugins gaps are fixed by offline package placement and metadata/autoload recovery, documented in [ADR 0019](adr/0019-standalone-wordpress-package-layout.md). Root-directory installs, overlapping package destinations and arbitrary third-party installer semantics still require the regular Composer installers. Unknown destination conflicts fail while preserving files. This is a deliberate safety boundary, not a claim that every possible Composer installer layout has been verified. -2. **Consumer CI access.** The [QA PHPUnit 13 PR](https://github.com/SymPress/qa/pull/3) and Runtime phases 1–5 were reviewed and merged after successful CI. All six Runtime PRs passed remote QA before the final Phase 6 review fixes; those fixes pass the complete local suite above and require their own final CI result before merging. Starter and demo still need CI read access to the private Runtime repository and must move their dependency to Runtime main after Phase 6 merges. No CI credentials or repository access have been changed. +2. **Corrected revision and consumer CI.** The [QA PHPUnit 13 PR](https://github.com/SymPress/qa/pull/3) and all Runtime phases are merged. The review corrections pass full local QA and differential comparisons; their no-skip integration CI result remains required. Consumer PRs must install the reviewed Runtime revision with their own CI credentials and pass their checks before merging. GitHub rejects deploy keys for Runtime; a read credential is still needed, and no rejected key or temporary SSH secret was retained. 3. **Final parity sign-off.** Matrix rows remain `partial` until the preceding gates are resolved and the complete acceptance record is reviewed. The implementation and behavioral evidence are present; there is no claim of complete drop-in acceptance yet. ## Review corrections The standards review found that offline recovery restrictions also rejected already-correct root and nested package layouts. Preparation now preserves those regular-installer layouts, with regression tests for repeated setup and rejection without mutation when recovery is actually required. The specification review found that URL dropins ignored `--force` when the destination was a symlink. Verified downloads now replace only the link; failed checksum verification leaves the link and its source intact. Both corrections are covered by the full local suite above. +The subsequent independent review identified missing early project autoload, unbounded service downloads, missing fixture enforcement in CI and incomplete user/deployment documentation. [ADR 0020](adr/0020-early-autoload-and-download-limits.md) records the implementation corrections. User guides now include required payload deployment and rollback-safe retention; old payloads are never automatically pruned. NOTICE identifies the three source-derived API files individually. + +Final source review also found legacy loaded-marker/constant-mapping controls remained active with compatibility disabled. Runner, generated configuration, doctor and cached/dumped environments now honor that switch. Regression tests cover ignored legacy controls, retained native controls, name-only diagnostics and cache-mode mismatches. + +The consumer URL correction restores `WP_SITEURL=${WP_HOME}`. Both Nginx configurations are byte-identical to their original PR bases. Starter setup/dry-run defaults agree; its updated QA passes 7 tests / 49 assertions. Demo QA passes 27 tests / 213 assertions plus live runtime smoke. Fresh browser sessions verify root login form actions, root admin dashboards, HTTP 200 homepages and no JavaScript errors. Existing cached environment values were cleared with Runtime's cache-flush command. + +The differential workflow now provisions disposable MariaDB, mysqlcheck, Git/Hg/SVN and pinned SHA-256-verified WordPress 7.1.1/WP-CLI 2.12.0 fixtures before running the **entire** PHPUnit suite with `--fail-on-skipped`. The generic reusable QA job may still lack integration fixtures; its green result alone is not full integration evidence. `tools/ci-fixtures.py` was exercised locally, and all six fixture-dependent DB/WordPress/WP-CLI/read-only tests passed (81 assertions, no skips) using its downloaded artifacts. A successful remote run of the corrected workflow remains required. + ## Reproduction Run `composer qa` with the dedicated `RUNTIME_TEST_DB_HOST`, `RUNTIME_TEST_WORDPRESS_DIR` and `RUNTIME_TEST_WPCLI_BOOTSTRAP` fixtures configured. Then run: diff --git a/docs/adr/0005-compatibility-and-differences.md b/docs/adr/0005-compatibility-and-differences.md index 5857ff8..94b2d87 100644 --- a/docs/adr/0005-compatibility-and-differences.md +++ b/docs/adr/0005-compatibility-and-differences.md @@ -18,7 +18,7 @@ The feature union stays available. Differences below are scoped behaviors with s | D10 | WP Starter deletes package dropin source directories after publishing; this can break symlinks or destroy package contents. | Publish safely and retain sources; transactional replacement, no dangling links. Move-content remains explicitly available. | | D11 | Source supports ten static dropin filenames; current WordPress has additional entries. | Use the verified current core catalog plus upstream union, including multisite. Unknown dropin support remains via the R option and explicit map. | | D12 | R global script names are pre-wpstarter/post-wpstarter; brief calls them pre-/post-. D adds halt signals; automatic errors can be swallowed. | Support canonical run names, bare names and legacy aliases. Preserve halt/propagation controls, report aggregate failure with nonzero exit; isolate callback failures as documented. | -| D13 | Generated config imports vendor/autoload.php and upstream/Symfony classes. | Generate a self-contained bootstrap artifact; no Composer classloader required for WordPress config runtime. Keep extension autoload as a runner feature and let the existing MU package load application dependencies. ADR 0006. | +| D13 | Generated config imports vendor/autoload.php and upstream/Symfony classes. | The environment parser uses a self-contained bootstrap artifact. Native `wp-config-autoload=false` permits configuration runtime without Composer; `true` restores early project autoload after WordPress's hook API. Both legacy profiles default true and migration records that behavior. Runner extension autoload remains separate. ADR 0006 and ADR 0020; exact `release/early-project-autoload` and `dev/early-project-autoload` differential cases retain upstream hook/class availability. | | D14 | Legacy constructors/callbacks can require Composer internals. | Preserve equivalent operations through native services, provide adapters where type-compatible, and report concrete PHP rewrites. No false promise that arbitrary Composer-typed callbacks run unchanged; ADR 0004. | | D15 | Section editors use regex replacement strings that interpret dollar/backslash content. R also repeats identical append/prepend calls and throws on a missing section; D deduplicates by call site and leaves missing sections unchanged. | Resolve the generated target, keep replacement text literal, and consistently use D's call-site deduplication and missing-section no-op behavior. This preserves editable sections while making repeated generation safe. All nineteen sections have explicit R/D differential cases. | | D16 | DB flags can short-circuit on any existing flag; failure paths can conflict with immutable env writes. R probes DB in selected mode; D limits automatic preflight to full runs. | Keep profile-specific behavior; native enabled preflight runs before selected steps except listing, validates complete externally supplied status, reports unknown separately and writes a consistent result once. Preserve valid/env/exists/installed evaluation order and health checks. | diff --git a/docs/adr/0006-runtime-generation.md b/docs/adr/0006-runtime-generation.md index 852cca3..317f341 100644 --- a/docs/adr/0006-runtime-generation.md +++ b/docs/adr/0006-runtime-generation.md @@ -4,11 +4,11 @@ Status: accepted by the project owner on 2026-09-29 with Phase 0 approval. ## Constraint -The work order requires Symfony Dotenv parsing and a generated wp-config without a Composer dependency at runtime. Upstream templates directly require Composer autoload and WordPressEnvBridge. Simply renaming that require would violate the requested boundary. A build-time dump alone would lose first-request dotenv parsing and therefore is not a full replacement. +The work order requires Symfony Dotenv parsing and the ability to run generated wp-config without Composer. Upstream templates additionally load Composer early so application files can register hooks and use vendor classes. These are separate capabilities: the parser must remain independent while early project autoload remains available. ADR 0020 corrects the initial unconditional omission discovered during review. A build-time dump alone would lose first-request dotenv parsing and therefore is not a full replacement. ## Decision -Build a versioned, self-contained bootstrap payload from the runtime's own environment implementation and a narrowly scoped Symfony Dotenv distribution. Embed it in, or emit it alongside, the generated wp-config with direct requires only. It must contain every transitive parser class it uses and no calls to vendor/autoload.php, Composer APIs or runner DI. The exact payload format is an implementation detail to validate in Phase 2; the boundary is an acceptance test that removes vendor/autoload.php before executing the generated config against stub WordPress files. +Build a versioned, self-contained bootstrap payload from the runtime's own environment implementation and a narrowly scoped Symfony Dotenv distribution. Emit it alongside generated wp-config with direct requires only. The payload contains every transitive parser class it uses and no calls to vendor/autoload.php, Composer APIs or runner DI. It is published under `var/runtime//`. With `wp-config-autoload=false`, acceptance tests remove vendor/autoload.php before executing generated configuration. Legacy profiles enable early application autoload by default; this explicit application dependency does not change the parser payload's independence. See [deployment](../deployment.md) for mandatory publication and rollback-safe retention. Keep upstream section identifiers and placeholder compatibility in the generated main file. Native generated artifacts have explicit ownership/version markers. The payload is deterministic for a given runtime version and settings. Build-time dump bypasses parser work but does not replace the parser capability. Atomic replacement must not leave main file and payload on incompatible versions. diff --git a/docs/adr/0020-early-autoload-and-download-limits.md b/docs/adr/0020-early-autoload-and-download-limits.md new file mode 100644 index 0000000..3c60513 --- /dev/null +++ b/docs/adr/0020-early-autoload-and-download-limits.md @@ -0,0 +1,23 @@ +# ADR 0020: Preserve early project autoload and bound service downloads + +Status: implemented review correction; final suite and CI evidence tracked in [acceptance](../acceptance.md). + +## Early application autoload + +WP Starter loads WordPress's hook API before requiring the project Composer autoloader. Its `autoload.files` entries can therefore register hooks before environment-specific PHP, the early hook and ordinary plugins run. Unconditionally omitting Composer lost that capability for general projects even though SymPress consumers supplied a later MU/kernel bootstrap. + +Add boolean `wp-config-autoload`, false by default in native mode and true in both legacy profiles. An explicit value overrides the profile. Require the configured vendor autoloader once immediately after `wp-includes/plugin.php`, before environment PHP and early hooks. Keep the scoped environment-parser payload independent of Composer. Migration writes the inherited true setting and explains the early hook/class dependency; changing to native is an explicit semantic choice. + +The differential cases `release/early-project-autoload` and `dev/early-project-autoload` execute Composer files, an environment PHP file and an early hook against upstream and Runtime. They assert hook API/class availability, order and single execution. The explicit-false/native fixtures continue to prove generated-config independence. Edited `AUTOLOAD` sections and custom templates remain the project owner's responsibility. + +## Download memory bound + +Add positive integer `download-max-bytes`, default 16777216 (16 MiB), to the URL-download service. Disable response buffering, reject an oversized declared Content-Length and count streamed bytes so absent or misleading headers cannot evade the limit. Verification and size checks complete before publication; failure preserves the existing destination. Projects may explicitly raise the limit for a trusted larger dropin/artifact. + +This applies to downloads through `UrlDownloader`, including dropins, extension services and WP-CLI's PHAR, release metadata and checksum sidecars. WP-CLI additionally retains its SHA-512 verification contract. SHA-256 configuration accepts normalized case; regression coverage includes uppercase input. HTTPS/checksum policies remain independently configurable and unchanged by the byte limit. + +## Disabled compatibility controls + +The final review found that disabling compatibility still honored `WPSTARTER_ENV_LOADED` and `WP_STARTER_ENV_TO_CONST`. Propagate the compatibility flag through runner loading, generated configuration, caches, dumps and doctor. Disabled mode ignores both legacy controls while retaining their native replacements and WordPress environment aliases. Enabled legacy controls emit deduplicated name-only diagnostics. Include the small diagnostic helper in the scoped payload so request-time parsing remains self-contained. + +Cache metadata now records compatibility mode; missing metadata denotes the former enabled behavior. Reject mismatches and require a cache flush or dump rebuild, rather than letting a warm cache reintroduce values produced by disabled legacy controls. Cold parsing, generated requests, runner dumps and warm dump loading have regression coverage. diff --git a/docs/adr/README.md b/docs/adr/README.md index 7062d19..824fdf1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -26,3 +26,4 @@ Implementation decisions after Phase 0: 17. [Consumer CLI isolation and link replacement](0017-consumer-cli-isolation-and-link-replacement.md) 18. [Relative environment example directories](0018-relative-environment-example-directory.md) 19. [Standalone WordPress package layouts](0019-standalone-wordpress-package-layout.md) +20. [Early project autoload and bounded service downloads](0020-early-autoload-and-download-limits.md) diff --git a/docs/configuration.md b/docs/configuration.md index d5279ce..a308bd5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -12,7 +12,7 @@ Draft 2020-12 schemas are in `schema/runtime.schema.json` and `schema/runtime-ex ## Native defaults -Internal context fields listed below are readable by steps but rejected in user configuration. They are populated from the actual invocation. This table documents the configuration contract; some options take effect only in subsequent implementation phases. +Internal context fields listed below are readable by steps but rejected in user configuration. They are populated from the actual invocation. These options are implemented; profile-dependent behavior is described below and in the linked user guides. | Option | Native default | | --- | --- | @@ -53,12 +53,14 @@ Internal context fields listed below are readable by steps but rejected in user | `wp-cli-commands` | `[]` | | `wp-cli-files` | `[]` | | `wp-version` | `null` | +| `wp-config-autoload` | `false` | | `compatibility` | `true` | | `compatibility-profile` | `"native"` | | `env-local-overrides` | `true` | | `allow-insecure-downloads` | `false` | | `download-checksums` | `[]` | | `require-download-checksums` | `false` | +| `download-max-bytes` | `16777216` | | `kernel-boot` | `false` | | `kernel-build-id` | `null` | @@ -66,4 +68,8 @@ Internal fields: `composer-updated-packages`, `is-composer-install`, `is-compose Ask values never block a noninteractive run. Confirmation defaults to yes unless a feature explicitly specifies no (notably unknown dropins). Five invalid answers fall back to the question's configured default. The `prevent-overwrite` list matches normalized root-relative paths using `fnmatch` without backslash escaping. Native unmarked files require confirmation or `--force`; existing directories and symlinks are never replaced by file writes. -Download checksum and kernel options are reserved with validation in this phase; their effects remain tracked in the parity matrix. `steps` is the native DI contribution list/map. `wp-cli-files` accepts PHP paths or descriptors with `file`, `args` and `skip-wordpress`; command providers remain lazy until the WP-CLI phase. +`steps` is the native DI contribution list/map. `wp-cli-files` accepts PHP paths or descriptors with `file`, `args` and `skip-wordpress`; command providers remain lazy until WP-CLI execution. [WP-CLI](wp-cli.md) describes their order and failure behavior. + +`wp-config-autoload` is false in the native profile and true in `release-3.0.1` and `upstream-dev`. It loads the configured Composer autoloader after WordPress's hook API and before environment PHP/early hooks. The independent environment parser is always shipped in the generated payload. [Migration](migration.md) explains preserving this behavior when changing profiles. + +`download-checksums` maps URLs to expected SHA-256 digests. `require-download-checksums=true` rejects downloads without a configured digest; `allow-insecure-downloads` defaults to false. `download-max-bytes` is a positive integer, defaulting to 16 MiB, and bounds downloads through the URL-download service, including WP-CLI PHARs, release metadata and checksum sidecars. Raise it explicitly for a larger trusted artifact. WP-CLI PHAR verification additionally uses its SHA-512 contract. See [the settings cheat sheet](settings-cheat-sheet.md) and [kernel integration](kernel-integration.md). diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..d678774 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,25 @@ +# Deployment and payload retention + +`var/runtime//` is required application code. Generated `wp-config.php` references its `bootstrap.php` on every request. **Do not exclude all of `var/` or clear `var/runtime` as a cache cleanup.** Each immutable payload includes its manifest, scoped environment classes, Symfony Dotenv/Process source and license notices. + +Deploy these artifacts together with the reviewed lockfile/application release: + +| Artifact | Requirement | +| --- | --- | +| Generated `wp-config.php` and core-parent proxy | Match the selected profile, path layout and payload | +| `var/runtime//` | Include every payload referenced by an active or rollback configuration | +| Generated `index.php`, MU loader and optional kernel bootstrap | Keep consistent with installed core/content packages | +| `.env.dump.php` when using build dumps | Private per-environment input; PHP-readable; contains secrets | +| `.env`/environment PHP/early hooks when used | Supply securely, outside public access; do not publish secrets in artifacts/logs | +| WordPress core, installed plugin/theme/MU packages and application vendor | Required by application features; early autoload explicitly requires vendor | +| Kernel build ID and precompiled production cache | Preserve the selected environment/build relationship for read-only operation | + +`var/runtime/package-layout.json` records package identities/paths for later offline repair; retain it when the deployment will rerun setup. `var/runtime/package-backups/` contains preserved package trees, not automatically disposable cache. Manage them under the same reviewed retention policy as deployment backups. + +Build in the destination release layout where possible. Generated configuration uses relative paths, so moving the whole tree while preserving relationships is supported by those path expressions. Changing the relative core/content/vendor/environment locations requires regeneration. Dumps can contain absolute application values; compiled kernel caches, Composer path-repository links and application artifacts can also depend on the build root. Rebuild those for the destination, or explicitly verify their portability before switching traffic. Do not assume a relocated directory is a validated deployment. + +Generate the environment dump and warm the application's production kernel cache before making the release read-only. Default private-file mode is 0600: provision the PHP runtime identity/ownership so it can read required configuration and secrets without making them public. Verify a real WordPress request and kernel boot under that identity with writes disabled. + +Publish complete releases atomically and retain the previous configuration, its referenced payloads and matching application packages for rollback. Payload cleanup is deliberately not automatic. Before manually removing an old fingerprint, inventory references from every active and retained release, account for workers/in-flight requests and rollback windows, then remove only explicitly unreferenced directories. Do not infer safety from file age or the newest fingerprint alone; never traverse symlinks during cleanup. Keeping an old payload is preferable to breaking an active or rollback release. + +For in-place deployments, publish the payload before changing the configuration reference and preserve the previous pair until rollback is no longer needed. Prefer release-directory switching when application/vendor changes must be coordinated. The existing exception rollback for package recovery is not a crash-recovery journal; retain backups and inspect an interrupted recovery before rerunning it. diff --git a/docs/environment.md b/docs/environment.md new file mode 100644 index 0000000..fd87698 --- /dev/null +++ b/docs/environment.md @@ -0,0 +1,22 @@ +# Environment, caches and dumps + +Native environment selection uses `WP_ENVIRONMENT_TYPE`, then `WP_ENV`, then `WORDPRESS_ENV`. Legacy profiles preserve their reverse legacy selector precedence. Selection is stable for one load: a later file cannot redirect the loader into another environment chain. The raw environment is retained for environment-specific filenames; WordPress and the kernel receive the canonical local/development/staging/production value. Unknown values use the documented production fallback and diagnostics. + +With native defaults, precedence from lowest to highest is `.env`, `.env.local`, `.env.{rawEnvironment}`, `.env.{rawEnvironment}.local`, then actual process environment. Raw `test` omits generic `.env.local`. Legacy profiles default to the two-file `.env`/`.env.{rawEnvironment}` chain until `env-local-overrides` is enabled. `env-dir` and `env-file` change the base location/name. A set `SYMPRESS_RUNTIME_ENV_LOADED` or compatible `WPSTARTER_ENV_LOADED` marker bypasses all dotenv parsing. + +Values are made available through the environment reader and superglobals. The reader does not trust HTTP request headers as deployment selectors. Standard WordPress constants use the catalog's explicit casts; missing, empty, invalid, false and zero are distinct. `SYMPRESS_RUNTIME_ENV_TO_CONST` adds named constant conversions using comma-separated `NAME:TYPE` entries; `WP_STARTER_ENV_TO_CONST` is its deprecated compatibility control. Consult the [catalog/parity reference](parity.md#core-constant-catalog-every-constant-is-an-acceptance-row) for the supported names and tested types. Type names include `bool`, `int`, `float`, `int_or_bool`, `string_or_bool`, `string` and `octal_mod`; `raw_string` is available in upstream-dev/native but absent from the release profile. Native also accepts `int|bool`, `string|bool`, `raw-string` and `mod`. Existing constants are retained rather than redefined. + +`compatibility=false` ignores both `WPSTARTER_ENV_LOADED` and `WP_STARTER_ENV_TO_CONST`; their native counterparts remain available. Cache/dump compatibility modes must match. Flush runtime caches and rebuild deployment dumps when changing that mode; see [migration](migration.md). + +The generated configuration can execute `{rawEnvironment}.php` from `env-bootstrap-dir` and the configured `early-hook-file`. Treat them as trusted application PHP. Enable `wp-config-autoload` when these files need Composer classes; legacy profiles enable it by default. WordPress's hook API is available before project autoload, so Composer `autoload.files` can register early hooks. + +Runtime caching writes `.env.cached.php` in the environment directory when eligible. Local/development-mode requests and `sympress.runtime.skip-cache-env` can suppress caching; the filter receives the raw environment as its second parameter. Cached values never override actual process values. + +```sh +vendor/bin/sympress-runtime dump-env production +vendor/bin/sympress-runtime flush-env-cache +``` + +`dump-env` produces a private `.env.dump.php` for the selected raw environment. A valid dump takes precedence over `.env.cached.php` and disables request-time cache writes. Process values still override dumped values. A conflicting actual environment selector causes dump creation/loading to fail rather than silently use another environment. `flush-env-cache` removes the runtime cache only; it never removes the deployment dump. Rebuild or explicitly retire the dump when changing its environment or baked configuration. + +Dumps/caches may contain database credentials and must stay outside public access and version control. Defaults use mode 0600; the deployed PHP identity must be able to read required private files. Prepare ownership and compiled kernel caches during the build, then verify a read-only production request. See [deployment](deployment.md) for the parser payload, relocation and rollback requirements. diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..708c749 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,47 @@ +# Getting started + +Use PHP 8.5, Composer 2 with plugin API 2.6 or newer, and access to the private SymPress package registry/repositories. Runtime uses Symfony 8.1. There is no stable Runtime release yet: install the reviewed development revision through your existing authenticated Composer repository configuration and commit the resulting lockfile. + +For an existing WP Starter project, start with [migration](migration.md); keep its profile and generated files until the transition has been reviewed. For a new project, require `sympress/runtime` and your chosen WordPress core package. Plugins/themes continue to come from WPackagist, private repositories or Composer path repositories. Runtime does not resolve dependencies or download WordPress core. + +Configure Composer's installer permissions and paths before installation. This is a minimal root manifest fragment; merge it into the existing project rather than replacing its requirements or scripts: + +```json +{ + "config": { + "allow-plugins": { + "sympress/runtime": true, + "composer/installers": true, + "johnpbloch/wordpress-core-installer": true + } + }, + "extra": { + "wordpress-install-dir": "public/wp", + "wordpress-content-dir": "public/wp-content", + "installer-paths": { + "public/wp-content/plugins/{$name}/": ["type:wordpress-plugin"], + "public/wp-content/mu-plugins/{$name}/": ["type:wordpress-muplugin"], + "public/wp-content/themes/{$name}/": ["type:wordpress-theme"] + }, + "sympress-runtime": {"compatibility-profile": "native"} + } +} +``` + +Create a private `.env` with your actual database credentials and site URL. Never commit secrets. For example, the nonsecret selectors are `WP_ENVIRONMENT_TYPE=development`, `DB_HOST=127.0.0.1` and `WP_HOME=https://example.test`; set `DB_NAME`, `DB_USER` and `DB_PASSWORD` for your database. Runtime creates configuration and content artifacts, but a WordPress database installation still needs your project's installation command or WP-CLI. + +```sh +composer install +vendor/bin/sympress-runtime validate +vendor/bin/sympress-runtime --list-steps +vendor/bin/sympress-runtime -n +vendor/bin/sympress-runtime doctor --json +``` + +Composer install/update already invokes setup when the Runtime plugin is enabled. The explicit standalone invocation above is useful to verify repeatability. Read `doctor` results before deployment: exit 1 means failure; exit 2 means unresolved checks without a known failure. + +Set the web document root to `public` for this layout. Commit the manifest, lockfile, application configuration and source; deploy generated configuration and its parser payload as described in [deployment](deployment.md). Native configuration does not load Composer during WordPress bootstrap unless `wp-config-autoload=true`; enable that option if early hooks or plugins need the project's Composer graph. A project with its own MU/kernel bootstrap can retain the native default. + +Set `WP_SITEURL` to the public WordPress URL your web server actually serves. In the SymPress starter/demo routing, it is `${WP_HOME}`: the existing server rules map root login/admin endpoints to the physical core directory. Do not append `/wp` merely because Composer stores core in `public/wp`. + +For a plugins-disabled build, run `composer install --no-plugins` followed by the standalone binary. Recovery covers the standard installers' distinct in-project directories. Root/nested layouts and arbitrary third-party installers retain the [documented boundaries](adr/0019-standalone-wordpress-package-layout.md). diff --git a/docs/kernel-integration.md b/docs/kernel-integration.md index f335a59..7739d92 100644 --- a/docs/kernel-integration.md +++ b/docs/kernel-integration.md @@ -19,8 +19,12 @@ Doctor exits with 0 when applicable checks pass, 1 on a failure, or 2 when a che `kernel-cache` preserves other environments and asset directories. It honors APP_CACHE_DIR and APP_BUILD_DIR and removes separately located discovery metadata. Unsafe or escaping symlink paths fail before any clearing. Align explicit SiteKernel environment overrides before running maintenance. +This is an explicit command-only step: Composer update does not automatically run it. A deployment requiring a deliberate clear or new build ID must invoke it and warm the selected environment before traffic switches. + To request a generated kernel MU plugin, set `kernel-boot: true`. A package that already owns boot can declare `extra.sympress-runtime.boots-kernel: true`; existing SymPress App boot entry files are also detected. The runtime never adds a second generated owner. Previously generated boot files are removed when another owner appears or the option is disabled; unmanaged files remain untouched. Set `kernel-build-id` to an explicit deployment identifier, or generate one with the command above. Normal setup does not rotate IDs. The generated configuration defines SYMPRESS_KERNEL_BUILD_ID from the environment, configured fallback or persisted deployment ID, while preserving an existing constant. Persist `var/runtime/{environment}/kernel-build-id.json` with the deployment artifacts if you use command-generated IDs. Build dumps and kernel caches are separate artifacts. Generate the environment dump and warm the kernel before making production files read-only. The runtime package's tests verify an actual compiled kernel reading a dump without writable project files; consumer deployment and admin smoke still need their own verification. + +The generated environment-parser payload under `var/runtime//` is another required artifact, even when the kernel is absent. It must survive cache cleanup and accompany its generated configuration. See [deployment and rollback-safe payload retention](deployment.md). diff --git a/docs/migration.md b/docs/migration.md index 86e863c..1f6bbe3 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -11,6 +11,10 @@ vendor/bin/sympress-runtime migrate The command reads inline `extra.wpstarter`, referenced JSON and root `wpstarter.json`, followed by native sources. Native values win and root files win within each family. It writes `sympress-runtime.json`, preserving the resolved compatibility profile and explicitly recording changed defaults. `skip-db-check=true` becomes `db-check=false`. Option paths remain relative to the project root. +Keep `release-3.0.1` or `upstream-dev` while preserving the corresponding WP Starter behavior. Selecting `native` is a separate behavior change: explicit step selections override configured skips, `WP_ENVIRONMENT_TYPE` has first selector priority, local dotenv overrides are enabled, and VCS/step ordering differs. Renaming configuration keys alone does not require switching profiles. Review [ADR 0005](adr/0005-compatibility-and-differences.md) before making that decision. + +Legacy profiles default `wp-config-autoload` to true; migration records that inherited value explicitly. It loads the actual configured vendor autoloader after WordPress's hook API and before environment PHP and `early-hook-file`, preserving Composer `autoload.files` callbacks and vendor classes at that stage. Retain it if any early code/plugin relies on this behavior. Native defaults false; the environment parser itself remains independent of Composer either way. Existing edited `AUTOLOAD` sections are preserved, so inspect regeneration diagnostics and custom templates rather than assuming an option change rewrote hand-maintained PHP. + | Option | Behavior | | --- | --- | | `--output=` | Choose a target inside the project; point `extra.sympress-runtime` to it when it is not the root default | @@ -27,3 +31,7 @@ After review, remove `extra.wpstarter`, archive the old root config, replace the Compatibility remains available until PHP and configuration migration are complete. Legacy configuration sources, extension metadata and lifecycle names produce diagnostics; loaded PHP references report each legacy symbol once per invocation. Eager type aliases preserve PHP parameter checking without loading the old package. Set `compatibility=false` after removing old sources, extension types/metadata, lifecycle names and deprecated options. It disables generated getter/filter adapters and rejects remaining legacy configuration/metadata clearly. HTTP deprecations go to the log and the WordPress deprecation action, never into the response body. Regenerate the runtime files, validate, run doctor, and verify WordPress login, MU-loader ownership, kernel boot and `wp console debug:container` in a fresh environment before switching production. The migration command alone is not a full parity or deployment acceptance result. + +With `compatibility=false`, `WPSTARTER_ENV_LOADED` and `WP_STARTER_ENV_TO_CONST` no longer control parsing or constant creation. Replace them with `SYMPRESS_RUNTIME_ENV_LOADED` and `SYMPRESS_RUNTIME_ENV_TO_CONST` if those capabilities are needed. Enabled legacy controls emit name-only deprecation diagnostics, without exposing values or writing into HTTP responses. WordPress environment aliases such as `WP_ENV` remain supported. + +Caches and build dumps record the compatibility mode. Earlier formats without that field are treated as compatibility-enabled. After disabling compatibility, run `vendor/bin/sympress-runtime flush-env-cache` and regenerate any build dump with `vendor/bin/sympress-runtime dump-env ` before deploying the new generated configuration. A mode mismatch fails explicitly instead of restoring constants derived through legacy controls. diff --git a/docs/parity.md b/docs/parity.md index b52e3f6..dfde49e 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -175,7 +175,7 @@ Native default order is the twelve-step sequence in the work order. Actual upstr | Feature | Upstream reference | Behavior and edge cases | Proposed implementation | Planned test ID | Status | Difference | | --- | --- | --- | --- | --- | --- | --- | | Early plugin API | R/D template ABSPATH | Define ABSPATH with trailing slash before requiring wp-includes/plugin.php; hooks available before env bootstrap and early hooks. | Generation/WpConfig | `PAR-WP-001` | partial | Parity | -| Runtime bootstrap | R/D template AUTOLOAD; W | No Composer autoloader needed to run generated configuration; self-contained parser bridge; project/MU still can use Composer. | Generation/BootstrapPayload | `PAR-WP-002` | partial | D13 | +| Runtime bootstrap | R/D template AUTOLOAD; W | Independent parser payload; native/explicit false works without Composer. wp-config-autoload=true loads project files after hook API and before env/early hooks; legacy profiles default true. | Generation/BootstrapPayload | `PAR-WP-002` | partial | D13, ADR 0020 | | Early PHP file ordering | R/D template ENV_VARIABLES/EARLY_HOOKS | Environment file after constants and before salts/DB/early-hook/defaults as template order; early hook after DB setup and before defaults; absent/unreadable skips. | Generation/WpConfig | `PAR-WP-003` | partial | Parity | | Local defaults | R/D template DEFAULT_ENV | WP_LOCAL_DEV=true, WP_DEVELOPMENT_MODE=all then development defaults; pre-defined values always win. | Generation/WpConfig | `PAR-WP-004` | partial | Parity | | Development defaults | R/D template DEFAULT_ENV | DEBUG=true, DEBUG_DISPLAY=true, DEBUG_LOG=false, SAVEQUERIES=true, SCRIPT_DEBUG=true, DISABLE_FATAL_ERROR_HANDLER=true (WP_ prefix where applicable). | Generation/WpConfig | `PAR-WP-005` | partial | Parity | diff --git a/docs/phase6-progress.md b/docs/phase6-progress.md index a148aeb..e9ce036 100644 --- a/docs/phase6-progress.md +++ b/docs/phase6-progress.md @@ -1,5 +1,7 @@ # Phase 6 progress +Historical implementation record for the merged Phase 6 PR. The subsequent review corrections and current merge/consumer gates are maintained in [acceptance.md](acceptance.md); counts below describe the Phase 6 baseline. + Migration and compatibility finalization are implemented. Full local QA passes with **1,043 tests / 7,298 assertions**, coding standards and PHPStan max, including live database and WordPress fixtures with no skips. A fresh complete differential run passes **249 cases** against both pinned upstream baselines. The consumer follow-up additionally tests forced content-link replacement, both stock legacy MU-loader templates, WP-CLI's JSON option rewrite, exact legacy slugs, profile ordering and offline WordPress package-layout recovery. Review regression tests cover normal root/nested layouts and verified URL downloads replacing existing links only with explicit force. Tests cover migration source precedence, explicit profile/default preservation, disabled DB-check conversion, source retention, private atomic output, dry-run, conflicts/force, symlinks and outside-root rejection, second-run no-op, exact static PHP findings and Composer command forwarding. An actual PHP HTTP server proves deprecations never contaminate response bodies or reveal environment values. Legacy child-process tests preserve typed interfaces and service injection and verify deduplicated diagnostics. @@ -8,4 +10,4 @@ Consumer migration work is isolated in `../.worktrees/runtime-starter` (base `66 All 407 matrix rows now have executed passing behavioral evidence. The generated-artifact and nineteen-section differential cases pass. Normal Composer, global `--no-plugins` and standalone reruns preserve 543 starter and 664 demo artifact hashes/links. Runtime now repairs standard WordPress package placement and Composer metadata before loading project code, preserving regular WPackagist/private/path repository installation. Real WPackagist plugin/theme/core tests pass locally and in their dedicated GitHub job. See [acceptance.md](acceptance.md) and ADR 0019 for the tested boundary. The consumer lockfiles temporarily use the private Runtime review branch and need retargeting after its PR stack is accepted. WP-CLI 2.12 emits upstream PHP 8.5 deprecation messages; smoke command exit codes and behavior pass. -The separate `sympress/qa` PHPUnit 13 PR and Runtime phases 1–5 were reviewed and merged with user authorization after successful CI. All Runtime phase PRs passed remote QA before the final review corrections; Phase 6 is awaiting the checks for those corrections. Starter and demo CI cannot yet download the private Runtime repository. Read access remains pending clarification, and no credentials or access settings have been changed. +The separate `sympress/qa` PHPUnit 13 PR and all Runtime phases have been merged with user authorization. Phase 6 merged on 2026-09-30. Consumer dependency retargeting, CI access and final acceptance are follow-up gates; consult the current PR checks and acceptance record rather than treating the earlier access failure as a current diagnosis. diff --git a/docs/settings-cheat-sheet.md b/docs/settings-cheat-sheet.md new file mode 100644 index 0000000..9fac22f --- /dev/null +++ b/docs/settings-cheat-sheet.md @@ -0,0 +1,30 @@ +# Settings cheat sheet + +Put settings in `extra.sympress-runtime` (an object or a root-relative JSON path) or `sympress-runtime.json`. Root configuration wins within the native family; native sources win over legacy sources. Arrays replace rather than merge recursively. [Configuration](configuration.md) contains the complete default table and internal fields; [CLI](cli.md) lists every command and flag. + +| Task | Settings | Behavior | +| --- | --- | --- | +| Retain WP Starter semantics | `compatibility-profile: "release-3.0.1"` or `"upstream-dev"` | Retains the selected reference's defaults and ordering; keep while migrating | +| Finish legacy migration | `compatibility: false` | Rejects legacy configuration/API usage; does not itself select the native profile | +| Early Composer classes/hooks | `wp-config-autoload: true` | Require project autoload before environment PHP and early hooks; legacy default is true | +| Select environment files | `env-dir`, `env-file`, `env-bootstrap-dir`, `early-hook-file` | Project-relative paths; `.env` and project root are defaults | +| Local overrides | `env-local-overrides: true` | Native default; legacy defaults false | +| Runtime cache/example | `cache-env`, `env-example` | Both default true; a build dump takes precedence over runtime caching | +| Build without DB access | `db-check: false` | Disable DB preflight; deprecated `skip-db-check` is translated by migration | +| Bootstrap without installed core | `require-wp: false` | Changes preflight; steps that need real core still require their inputs | +| Protect artifacts | `prevent-overwrite: ["relative/path", "pattern/*"]` | Root-relative patterns; review `--force` and existing-file rules before use | +| Publish local content | `content-dev-dir`, `content-dev-op` | Default `content-dev`, operation `auto`; absent input is optional | +| Publish dropins | `dropins`, `dropins-op`, `unknown-dropins` | File, directory or URL sources; unknown dropins require explicit handling | +| Move core content | `move-content` | Default false; opt in deliberately | +| Retain bundled themes | `register-theme-folder` | Default false; adds the core themes directory | +| Verify Git/Hg/SVN ignores | `check-vcs-ignore`, `create-vcs-ignore-file` | Both default true; VCS availability is diagnosed | +| Control routine steps | `skip-steps`, `custom-steps`, `steps`, `command-steps` | Native explicit selection overrides configured skips; command-only steps need explicit selection | +| Lifecycle callbacks | `scripts`, `autoload`, `templates-dir` | Run-only PHP autoload, scripts and template overrides; [extension API](custom-steps.md) | +| Run WP-CLI | `install-wp-cli`, `wp-cli-files`, `wp-cli-commands` | Package preferred over verified PHAR; eval files precede commands | +| Pin/report core version | `wp-version` | Optional version override used by version discovery | +| Verify downloads | `download-checksums`, `require-download-checksums` | SHA-256 mapping by URL, optionally mandatory | +| Bound downloads | `download-max-bytes` | Positive integer bytes; default 16777216 (16 MiB) for URL service downloads | +| Permit insecure transport | `allow-insecure-downloads` | Default false; opt in only for a deliberately trusted source | +| Kernel ownership/build | `kernel-boot`, `kernel-build-id` | Boot ownership opt-in; stable build identity, not regenerated on every install | + +The top-level Composer extras `wordpress-install-dir` and `wordpress-content-dir` are outside the Runtime settings object. Configure `installer-paths` consistently with them; changing a Runtime path does not rewrite arbitrary third-party installer rules. See [steps](steps.md) for all twelve slugs and [environment](environment.md) for constant casts. diff --git a/docs/steps.md b/docs/steps.md new file mode 100644 index 0000000..0ede973 --- /dev/null +++ b/docs/steps.md @@ -0,0 +1,26 @@ +# Setup steps + +Native full-run order is shown below. Each step can be selected by slug: `vendor/bin/sympress-runtime -n wpconfig index`. WP-CLI runs last even in an explicit selection. Configured skips and optional features govern whether a listed step performs work; listing a step does not imply its inputs exist. + +| Slug | Work and principal settings | +| --- | --- | +| `checkpaths` | Validate installed core/autoload paths and prepare content directories | +| `wpconfig` | Generate configuration/proxy and scoped environment payload; preserve salts/sections | +| `index` | Generate the front controller for the configured core location | +| `flushenvcache` | Invalidate the runtime environment cache; retain deployment dumps | +| `muloader` | Generate the MU package loader; retire recognized stock legacy loaders safely | +| `envexample` | Generate the environment example when `env-example` is enabled | +| `dropins` | Publish configured files/directories/verified URLs using `dropins-op` | +| `movecontent` | Move core content when `move-content` enables it | +| `publishcontentdev` | Publish `content-dev-dir` through the chosen copy/move/symlink/auto operation | +| `vcsignorecheck` | Check/create relevant ignore rules using `check-vcs-ignore` and `create-vcs-ignore-file` | +| `wpcliconfig` | Generate WP-CLI path/bootstrap configuration | +| `wpcli` | Execute configured eval files and command providers after setup | + +Release-3.0.1 retains its automatic order without the VCS check; that step is still available explicitly. Upstream-dev places `wpcliconfig` before `vcsignorecheck`. Native explicit selection takes precedence over `skip-steps`/`--skip-custom`; legacy profiles retain their upstream selection rules. Do not switch to native just to rename the package during migration. + +`kernel-cache` is command-only and therefore does not automatically flush caches after Composer update. Select it when the deployment needs explicit cache invalidation; optional `--generate-build-id` writes a new stable deployment ID. `kernel-boot` reconciles boot ownership when configured. See [kernel integration](kernel-integration.md). + +Custom steps implement the public step contracts and can use dependency injection, priorities, optional/blocking/file-creation behavior and lifecycle callbacks. `command-steps` contributes explicit-only work. Extension packages use `sympress-runtime-extension`; compatibility also recognizes `wpstarter-extension`. The complete [service and extension guide](custom-steps.md) describes registration and the process-isolated callback context. + +All publication paths preserve unrelated data and validate their boundaries. `--force` is an explicit overwrite decision, not permission to traverse external links or replace arbitrary directories. URL dropins are verified and size-bounded before their destination changes. A failed step returns nonzero; blocking errors stop subsequent work. diff --git a/docs/test-plan.md b/docs/test-plan.md index 6369180..d3f91de 100644 --- a/docs/test-plan.md +++ b/docs/test-plan.md @@ -1,6 +1,6 @@ # Verification and phased delivery -Status: planned. No PHPUnit, differential, DDEV or Composer integration test has been executed for this new package in Phase 0. +This is the historical Phase 0 verification plan. The phases have since been implemented and merged; [acceptance](acceptance.md) records executed evidence and remaining gates. The requirements below remain the verification contract, not a claim that the project has never been tested. ## Test identity and traceability @@ -68,4 +68,4 @@ Fresh `ddev composer install`, setup and real WordPress database installation mu ## Documentation delivery -Implementation phases add and maintain README, Getting Started, Configuration, Settings Cheat Sheet, Environment, wp-config/Sections, Steps, CLI, WP-CLI, Custom Steps/Extensions, SymPress Integration and Migration guides. Add CHANGELOG, SECURITY, LICENSE and actual NOTICE attribution. Code/comments/docs/commit messages remain English. Current documents describe proposals only. +Maintain README, Getting Started, Configuration, Settings Cheat Sheet, Environment, wp-config/Sections, Steps, CLI, WP-CLI, Custom Steps/Extensions, SymPress Integration, Migration and Deployment guides. Keep CHANGELOG, SECURITY, LICENSE and NOTICE attribution current. Code/comments/docs/commit messages remain English. Phase progress/review files retain historical evidence; the README and acceptance record are the current entry points. diff --git a/docs/wp-cli.md b/docs/wp-cli.md new file mode 100644 index 0000000..14259f6 --- /dev/null +++ b/docs/wp-cli.md @@ -0,0 +1,30 @@ +# WP-CLI + +Runtime first resolves an installed WP-CLI Composer package, then the project's PHAR. `install-wp-cli` controls whether a missing PHAR can be downloaded. The built-in tool requires its release SHA-512 checksum and fails closed on verification errors. A checksum fetched from the same release origin verifies bytes against that origin; it is not an independent authenticity guarantee. + +The shared `download-max-bytes` limit also bounds the PHAR, release metadata and checksum sidecar downloads. Its default is 16 MiB; set an explicit larger positive byte count if a trusted release requires it. Oversized responses fail before replacing an existing artifact. + +`wpcliconfig` generates the configured core path and any bootstrap needed by the selected profile. `wpcli` runs last and processes `wp-cli-files` before `wp-cli-commands`. Providers are evaluated only when this step executes, not during validation or listing. Commands use WP-CLI syntax including the leading `wp`, for example: + +```json +{ + "wp-cli-files": [ + {"file": "dev-ops/prepare.php", "args": ["example"], "skip-wordpress": true} + ], + "wp-cli-commands": ["wp core version", "wp option get home"] +} +``` + +Each file entry can also be a simple PHP path. Paths are project-relative; descriptors supply ordered arguments and `skip-wordpress` for code that must run without loading WordPress. WP-CLI exposes eval-file arguments as `$args`. Missing or unreadable eval files are reported and skipped, preserving upstream behavior. A failed executed command fails the step and stops the remaining commands. + +Command lists may be inline, loaded from JSON or returned by trusted PHP providers. PHP providers receive `$services` (`SymPress\Runtime\Services`) so they can inspect the environment and DB state lazily. Do not put secrets into logged command strings. Quotes and argument boundaries are preserved by the process/tool APIs; use the documented command form rather than appending shell redirections. + +```sh +vendor/bin/sympress-runtime -n wpcliconfig wpcli +php wp-cli.phar core version +php wp-cli.phar console doctor --json +``` + +The last command additionally requires the SymPress kernel console integration. It accepts WP-CLI's rewrite of `--json` to `--format=json`. WP-CLI may emit its own PHP-version deprecations; Runtime diagnostics redact their structured configuration output but do not claim to suppress all upstream messages. + +Standalone and Composer execution share the same services and generated configuration. `wp-config-autoload` determines early Composer loading for WordPress requests and must agree with application/MU bootstrap ownership. See [migration](migration.md), [sections](wp-config.md) and [CLI](cli.md). diff --git a/docs/wp-config.md b/docs/wp-config.md new file mode 100644 index 0000000..b8f4028 --- /dev/null +++ b/docs/wp-config.md @@ -0,0 +1,28 @@ +# Generated wp-config and sections + +The `wpconfig` step generates the main configuration at the project root in native/upstream-dev profiles. The release-3.0.1 profile uses the core parent. A proxy in the core parent is generated when required. Both files are parsed before publication. Native unmarked files require overwrite approval; protected paths, symlinks and directories retain their documented guards. Existing salts and edited managed sections are preserved during regeneration. + +The configuration loads WordPress's hook API, optionally the project Composer autoloader, and a scoped parser from `var/runtime//bootstrap.php`. That payload is required on every request: it is a deployment artifact, not disposable cache. `wp-config-autoload` defaults false natively and true in legacy profiles. With it disabled, the environment parser works without Composer; application hooks that use Composer classes still need their own bootstrap. + +Sections use PHP labels and paired comments, for example: + +```php +BEFORE_BOOTSTRAP : { + // Trusted project PHP. +} #@@/BEFORE_BOOTSTRAP +``` + +All nineteen sections are supported: `DEBUG_INFO_INIT`, `ABSPATH`, `AUTOLOAD`, `WPS_GETENV_FUNCTION`, `ENV_VARIABLES`, `KEYS`, `DB_SETUP`, `EARLY_HOOKS`, `DEFAULT_ENV`, `SSL_FIX`, `URL_CONSTANTS`, `THEMES_REGISTER`, `ADMIN_COLOR`, `ENV_CACHE`, `DEBUG_INFO`, `GETENV_FILTER`, `BEFORE_BOOTSTRAP`, `CLEAN_UP`, `WP_CLI_HACK`. + +Custom steps obtain the editor through `$services->wpConfigSectionEditor()`: + +```php +$editor = $services->wpConfigSectionEditor(); +$editor->append('BEFORE_BOOTSTRAP', 'define("PROJECT_BOOTSTRAPPED", true);'); +``` + +`sectionContent()` reads the normalized body. `append()` and `prepend()` add content with a call-site/content marker so a repeated invocation from that location is a no-op. `replace()` replaces the body; `delete()` empties it while retaining the section. Names are case-insensitive. Missing sections are a no-op for edits and read as an empty string. Dollar signs/backslashes in inserted PHP stay literal. These semantics intentionally fix the legacy editor's replacement and duplicate edge cases; exact differences are recorded in [ADR 0005, D15](adr/0005-compatibility-and-differences.md). + +Keep section delimiters intact. Regeneration retains edited bodies, including manually maintained early autoload code; changing configuration options does not silently discard those edits. Review preservation diagnostics after template/configuration upgrades. Custom templates take responsibility for their bootstrap and must be tested with real WordPress, WP-CLI and the selected autoload policy. + +The generated paths are relative where the layout permits, but unchanged relative paths are only one part of relocation. Environment dumps and compiled kernel/application files can contain absolute paths. Follow [deployment](deployment.md) before moving artifacts to another root. diff --git a/schema/runtime.schema.json b/schema/runtime.schema.json index 73f8f62..d910fbb 100644 --- a/schema/runtime.schema.json +++ b/schema/runtime.schema.json @@ -4,6 +4,14 @@ "title": "SymPress Runtime configuration", "type": "object", "properties": { + "wp-config-autoload": { + "$ref": "#/$defs/boolean" + }, + "download-max-bytes": { + "type": "integer", + "minimum": 1, + "default": 16777216 + }, "cache-env": { "$ref": "#/$defs/boolean" }, diff --git a/src/Compatibility/Migration.php b/src/Compatibility/Migration.php index d89bdb4..4e202bc 100644 --- a/src/Compatibility/Migration.php +++ b/src/Compatibility/Migration.php @@ -109,6 +109,7 @@ public function run(array $extra, string $output = 'sympress-runtime.json', bool 'provenance' => $provenance, 'findings' => $findings, 'next' => [ + 'wp-config-autoload preserves early project Composer autoload in legacy profiles. Keep it enabled when environment PHP files, early hooks or plugins need vendor classes or Composer files hooks; native defaults to false.', 'Review PHP findings, custom templates and generated files; dynamic references require manual inspection.', 'Remove extra.wpstarter and archive wpstarter.json after review; originals are retained by this command.', 'Use extra.sympress-runtime for a non-default output path; option paths remain relative to the project root.', diff --git a/src/Config/Options.php b/src/Config/Options.php index a54b404..f5afeeb 100644 --- a/src/Config/Options.php +++ b/src/Config/Options.php @@ -43,12 +43,14 @@ final class Options 'unknown-dropins' => false, 'wp-cli-commands' => [], 'wp-cli-files' => [], + 'wp-config-autoload' => false, 'wp-version' => null, 'compatibility' => true, 'compatibility-profile' => 'native', 'env-local-overrides' => true, 'allow-insecure-downloads' => false, 'download-checksums' => [], + 'download-max-bytes' => 16777216, 'require-download-checksums' => false, 'kernel-boot' => false, 'kernel-build-id' => null, @@ -68,6 +70,7 @@ public static function defaults(string $profile): array if ($profile !== 'native') { $defaults['autoload'] = 'wpstarter-autoload.php'; $defaults['env-local-overrides'] = false; + $defaults['wp-config-autoload'] = true; } if ($profile === 'release-3.0.1') { $defaults['content-dev-op'] = 'symlink'; diff --git a/src/Config/Validator.php b/src/Config/Validator.php index 4ac514e..c0aff60 100644 --- a/src/Config/Validator.php +++ b/src/Config/Validator.php @@ -20,7 +20,7 @@ public function validate(string $key, mixed $value): Result $validated = match ($key) { 'cache-env', 'install-wp-cli', 'require-wp', 'skip-db-check', 'compatibility', 'env-local-overrides', 'allow-insecure-downloads', 'require-download-checksums', - 'kernel-boot' => $this->boolean($value), + 'kernel-boot', 'wp-config-autoload' => $this->boolean($value), 'check-vcs-ignore', 'create-vcs-ignore-file', 'move-content', 'register-theme-folder', 'unknown-dropins' => $this->boolOrAsk($value), 'db-check' => is_string($value) && strtolower($value) === 'health' ? 'health' : $this->boolean($value), @@ -42,6 +42,7 @@ public function validate(string $key, mixed $value): Result 'wp-version' => $this->version($value), 'compatibility-profile' => $this->profile($value), 'download-checksums' => $this->checksums($value), + 'download-max-bytes' => $this->positiveInteger($value), 'kernel-build-id' => $this->buildId($value), default => $value, }; @@ -59,6 +60,15 @@ private function boolean(mixed $value): bool return $bool; } + private function positiveInteger(mixed $value): int + { + if (!is_int($value) || $value < 1) { + throw new InvalidArgumentException('Expected a positive integer byte limit.'); + } + + return $value; + } + private function boolOrAsk(mixed $value): bool|string { return $value === 'ask' ? 'ask' : $this->boolean($value); diff --git a/src/Console/Doctor.php b/src/Console/Doctor.php index 5985bf5..b7fdcaf 100644 --- a/src/Console/Doctor.php +++ b/src/Console/Doctor.php @@ -58,7 +58,7 @@ public function inspect(): array throw new RuntimeException('Invalid compatibility profile.'); } $env = $dump - ? EnvReader::buildFromCacheDump($environmentDirectory . '/.env.dump.php', $profile) + ? EnvReader::buildFromCacheDump($environmentDirectory . '/.env.dump.php', $profile, compatibility: $this->config['compatibility']->is(true)) : (new EnvFactory($this->config, $this->paths))->create(); $kernel = new KernelPaths($env, $this->paths); $canonical = $kernel->environment(); diff --git a/src/Download/UrlDownloader.php b/src/Download/UrlDownloader.php index 1d09c7e..28c34bf 100644 --- a/src/Download/UrlDownloader.php +++ b/src/Download/UrlDownloader.php @@ -7,6 +7,7 @@ use SymPress\Runtime\Config\Config; use SymPress\Runtime\Filesystem\Filesystem; use Symfony\Contracts\HttpClient\HttpClientInterface; +use Symfony\Contracts\HttpClient\ResponseInterface; use Throwable; final class UrlDownloader @@ -65,7 +66,7 @@ private function download(string $url): string } for ($redirects = 0; $redirects <= 5; ++$redirects) { $this->validateUrl($url); - $response = $this->http->request('GET', $url, ['max_redirects' => 0, 'timeout' => 15, 'max_duration' => 60, 'verify_peer' => true, 'verify_host' => true]); + $response = $this->http->request('GET', $url, ['max_redirects' => 0, 'timeout' => 15, 'max_duration' => 60, 'verify_peer' => true, 'verify_host' => true, 'buffer' => false]); $status = $response->getStatusCode(); if (in_array($status, [301, 302, 303, 307, 308], true)) { $next = $response->getInfo('redirect_url'); @@ -80,7 +81,7 @@ private function download(string $url): string $response->cancel(); throw new DownloadException('Download failed with HTTP status ' . $status . '.'); } - $body = $response->getContent(false); + $body = $this->boundedContent($response); if (is_string($checksum) && !hash_equals($checksum, hash('sha256', $body))) { throw new DownloadException('Downloaded content does not match its SHA256 checksum.'); } @@ -91,6 +92,32 @@ private function download(string $url): string throw new DownloadException('Download exceeded the redirect limit.'); } + private function boundedContent(ResponseInterface $response): string + { + try { + $limit = $this->config['download-max-bytes']->unwrap(); + if (!is_int($limit) || $limit < 1) { + throw new DownloadException('Download byte limit must be a positive integer.'); + } + $length = $response->getHeaders(false)['content-length'][0] ?? null; + if (is_string($length) && ctype_digit($length) && (float) $length > $limit) { + throw new DownloadException('Download exceeds the configured byte limit.'); + } + $body = ''; + foreach ($this->http->stream($response) as $chunk) { + $content = $chunk->getContent(); + if (strlen($content) > $limit - strlen($body)) { + throw new DownloadException('Download exceeds the configured byte limit.'); + } + $body .= $content; + } + + return $body; + } finally { + $response->cancel(); + } + } + private function validateUrl(string $url): void { $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME)); diff --git a/src/Env/EnvFactory.php b/src/Env/EnvFactory.php index b135967..c71ef16 100644 --- a/src/Env/EnvFactory.php +++ b/src/Env/EnvFactory.php @@ -27,7 +27,7 @@ public function createForEnvironment(?string $environment = null): EnvReader if (!is_string($profile) || !is_string($file) || !is_string($directory)) { throw new RuntimeException('Invalid environment loader configuration.'); } - $reader = new EnvReader(profile: $profile); + $reader = new EnvReader(profile: $profile, compatibility: $this->config['compatibility']->is(true)); $reader->loadChain($file, $directory, $this->config['env-local-overrides']->is(true), $environment); return $reader; diff --git a/src/Env/EnvReader.php b/src/Env/EnvReader.php index 7e4d76d..42185d7 100644 --- a/src/Env/EnvReader.php +++ b/src/Env/EnvReader.php @@ -58,7 +58,7 @@ final class EnvReader private readonly Dotenv $dotenv; private readonly Filters $filters; - public function __construct(?Dotenv $dotenv = null, private readonly string $profile = 'native') + public function __construct(?Dotenv $dotenv = null, private readonly string $profile = 'native', private readonly bool $compatibility = true) { $this->dotenv = $dotenv ?? new Dotenv($profile === 'native' ? 'WP_ENVIRONMENT_TYPE' : 'WP_ENV', 'WP_DEBUG'); $this->filters = new Filters($profile); @@ -262,9 +262,9 @@ public function hasCachedValues(): bool return $this->fromCache && $this->cache !== []; } - public static function buildFromCacheDump(string $file, string $profile = 'native', ?string $environment = null): self + public static function buildFromCacheDump(string $file, string $profile = 'native', ?string $environment = null, bool $compatibility = true): self { - $reader = new self(profile: $profile); + $reader = new self(profile: $profile, compatibility: $compatibility); if (!is_file($file) || !is_readable($file)) { return $reader; } @@ -296,6 +296,7 @@ public function dumpCached(string $file): bool $payload = [ 'format' => 1, 'profile' => $this->profile, + 'compatibility' => $this->compatibility, 'environment' => $this->determineEnvType(), 'values' => $this->cache, 'loaded' => array_keys($this->raw), @@ -334,6 +335,9 @@ private function restoreCache(mixed $data, ?string $environment): void if (!is_array($data) || ($data['format'] ?? null) !== 1 || ($data['profile'] ?? null) !== $this->profile || !is_string($data['environment'] ?? null)) { throw new RuntimeException('Environment cache format or profile is invalid.'); } + if (($data['compatibility'] ?? true) !== $this->compatibility) { + throw new RuntimeException('Environment cache compatibility mode changed; flush the cache or rebuild the environment dump.'); + } if ($environment === null) { foreach ($this->profile === 'native' ? ['WP_ENVIRONMENT_TYPE', 'WP_ENV', 'WORDPRESS_ENV'] : self::WP_STARTER_ENV_VARS as $name) { $external = $this->externalValue($name); @@ -441,7 +445,13 @@ public function setupConstants(): void $this->define($name); } foreach (['WP_STARTER_ENV_TO_CONST', 'SYMPRESS_RUNTIME_ENV_TO_CONST'] as $option) { + if ($option === 'WP_STARTER_ENV_TO_CONST' && !$this->compatibility) { + continue; + } $list = $this->read($option); + if ($option === 'WP_STARTER_ENV_TO_CONST' && is_string($list) && $list !== '') { + LegacyDeprecation::report($option, 'SYMPRESS_RUNTIME_ENV_TO_CONST'); + } foreach (is_string($list) ? explode(',', $list) : [] as $item) { [$name, $type] = array_pad(explode(':', trim($item), 2), 2, ''); if ($name === '') { @@ -497,9 +507,16 @@ private function define(string $name): void private function sentinel(): bool { foreach (['SYMPRESS_RUNTIME_ENV_LOADED', 'WPSTARTER_ENV_LOADED'] as $name) { - if (array_key_exists($name, $_ENV) || array_key_exists($name, $_SERVER) || getenv($name) !== false) { - return true; + if ($name === 'WPSTARTER_ENV_LOADED' && !$this->compatibility) { + continue; + } + if (!array_key_exists($name, $_ENV) && !array_key_exists($name, $_SERVER) && getenv($name) === false) { + continue; + } + if ($name === 'WPSTARTER_ENV_LOADED') { + LegacyDeprecation::report($name, 'SYMPRESS_RUNTIME_ENV_LOADED'); } + return true; } return false; diff --git a/src/Env/LegacyDeprecation.php b/src/Env/LegacyDeprecation.php new file mode 100644 index 0000000..aa4bbe1 --- /dev/null +++ b/src/Env/LegacyDeprecation.php @@ -0,0 +1,25 @@ + $reported */ + static $reported = []; + if (isset($reported[$name])) { + return; + } + $reported[$name] = true; + if (function_exists('sympress_runtime_deprecated')) { + sympress_runtime_deprecated($name, $replacement); + return; + } + // Never put deprecations into HTTP or machine-readable command output. + error_log($name . ' is deprecated; use ' . $replacement . '.'); + } +} diff --git a/src/Generation/RuntimeBundleBuilder.php b/src/Generation/RuntimeBundleBuilder.php index cd8a1f5..a4b895c 100644 --- a/src/Generation/RuntimeBundleBuilder.php +++ b/src/Generation/RuntimeBundleBuilder.php @@ -79,7 +79,7 @@ private function sources(): array $process = dirname((string) (new ReflectionClass(Process::class))->getFileName()); $environment = dirname((string) (new ReflectionClass(EnvReader::class))->getFileName()); $sources = []; - foreach (['EnvReader', 'Filters', 'EnvironmentName', 'ConstantCatalog'] as $class) { + foreach (['EnvReader', 'Filters', 'EnvironmentName', 'ConstantCatalog', 'LegacyDeprecation'] as $class) { $sources['Env/' . $class . '.php'] = $this->read($environment . '/' . $class . '.php'); } $sources['Dotenv/Dotenv.php'] = $this->read($dotenv . '/Dotenv.php'); diff --git a/src/Generation/WpConfigGenerator.php b/src/Generation/WpConfigGenerator.php index eeddee5..b6048fb 100644 --- a/src/Generation/WpConfigGenerator.php +++ b/src/Generation/WpConfigGenerator.php @@ -70,6 +70,8 @@ public function generate(bool $force = false, bool $primaryApproved = false): bo 'LEGACY_PROJECT_PATH' => $this->expression($directory, $this->config['compatibility-profile']->is('release-3.0.1') ? $environment : $this->paths->root()), 'CONTENT_PATH' => $this->expression($directory, $this->paths->wpContent()), 'PAYLOAD_PATH' => $this->expression($directory, $bundle->loader), + 'PROJECT_AUTOLOAD_PATH' => $this->expression($directory, $this->paths->vendor('autoload.php')), + 'PROJECT_AUTOLOAD_ENABLED' => $this->config['wp-config-autoload']->is(true) ? 'true' : 'false', 'PAYLOAD_ID' => var_export($bundle->fingerprint, true), 'PROFILE' => var_export($this->config['compatibility-profile']->unwrap(), true), 'ENV_FILENAME' => var_export($this->config['env-file']->unwrap(), true), diff --git a/templates/wp-config.php b/templates/wp-config.php index 54cff2c..c001b67 100644 --- a/templates/wp-config.php +++ b/templates/wp-config.php @@ -11,6 +11,9 @@ } #@@/ABSPATH AUTOLOAD : { + if ({{{PROJECT_AUTOLOAD_ENABLED}}}) { + require_once {{{PROJECT_AUTOLOAD_PATH}}}; + } $runtimeReaderClass = require {{{PAYLOAD_PATH}}}; defined('SYMPRESS_RUNTIME_PATH') || define('SYMPRESS_RUNTIME_PATH', {{{ROOT_PATH}}}); defined('SYMPRESS_RUNTIME_ENV_PATH') || define('SYMPRESS_RUNTIME_ENV_PATH', {{{ENV_PATH}}}); @@ -29,8 +32,8 @@ $usingEnvDump = is_file($envDumpFile); global $sympressRuntimeEnvironment; $sympressRuntimeEnvironment = $usingEnvDump || {{{CACHE_ENABLED}}} - ? $runtimeReaderClass::buildFromCacheDump($usingEnvDump ? $envDumpFile : $envCacheFile, {{{PROFILE}}}) - : new $runtimeReaderClass(profile: {{{PROFILE}}}); + ? $runtimeReaderClass::buildFromCacheDump($usingEnvDump ? $envDumpFile : $envCacheFile, {{{PROFILE}}}, compatibility: {{{COMPATIBILITY}}}) + : new $runtimeReaderClass(profile: {{{PROFILE}}}, compatibility: {{{COMPATIBILITY}}}); if (!function_exists('sympress_runtime_getenv')) { function sympress_runtime_getenv(?string $name): bool|int|float|string|object|null { diff --git a/tests/Config/OptionsTest.php b/tests/Config/OptionsTest.php index 0aaa954..f8b1a09 100644 --- a/tests/Config/OptionsTest.php +++ b/tests/Config/OptionsTest.php @@ -44,6 +44,8 @@ public static function values(): iterable yield 'PAR-OPT-031 unknown-dropins' => ['unknown-dropins', 'ask', 'ask']; yield 'PAR-OPT-032 wp-cli-commands' => ['wp-cli-commands', ['wp option get home'], ['wp option get home']]; yield 'PAR-OPT-034 wp-version' => ['wp-version', '6.8', '6.8.0']; + yield 'project autoload option' => ['wp-config-autoload', true, true]; + yield 'download byte limit' => ['download-max-bytes', 1024, 1024]; } #[DataProvider('values')] @@ -109,4 +111,12 @@ public function testEveryRecognizedOptionHasAnExplicitSchemaProperty(): void self::assertArrayHasKey($option, $schema['properties'], $option); } } + + public function testDownloadByteLimitMustBeAPositiveInteger(): void + { + foreach ([0, -1, '1024', 1.5, false, null] as $value) { + $config = new Config(['download-max-bytes' => $value], new Validator(new Paths($this->root))); + self::assertArrayHasKey('download-max-bytes', $config->errors()); + } + } } diff --git a/tests/Contract/UrlDownloaderTest.php b/tests/Contract/UrlDownloaderTest.php index 1fdd973..db54aa9 100644 --- a/tests/Contract/UrlDownloaderTest.php +++ b/tests/Contract/UrlDownloaderTest.php @@ -17,6 +17,40 @@ final class UrlDownloaderTest extends TemporaryProject { + public function testStreamLimitRejectsLargeBodiesBeforeReplacingTargets(): void + { + $this->write('artifact', 'original'); + $responses = [ + new MockResponse('abcde', ['response_headers' => ['content-length: 5']]), + new MockResponse((static function (): iterable { + yield 'ab'; + yield 'cde'; + })()), + new MockResponse((static function (): iterable { + yield 'ab'; + yield 'cd'; + })()), + ]; + $http = new MockHttpClient($responses); + $downloader = $this->downloader($http, ['download-max-bytes' => 4]); + for ($attempt = 0; $attempt < 2; ++$attempt) { + self::assertFalse($downloader->save('https://example.test/file', $this->root . '/artifact')); + self::assertStringContainsString('byte limit', $downloader->error()); + self::assertSame('original', file_get_contents($this->root . '/artifact')); + } + self::assertTrue($downloader->save('https://example.test/file', $this->root . '/artifact')); + self::assertSame('abcd', file_get_contents($this->root . '/artifact')); + $larger = $this->downloader(new MockHttpClient(new MockResponse('abcde')), ['download-max-bytes' => 5]); + self::assertSame('abcde', $larger->fetch('https://example.test/file')); + } + + public function testUppercaseChecksumsAreAccepted(): void + { + $url = 'https://example.test/file'; + $downloader = $this->downloader(new MockHttpClient(new MockResponse('verified')), ['download-checksums' => [$url => strtoupper(hash('sha256', 'verified'))]]); + self::assertSame('verified', $downloader->fetch($url)); + } + /** @param array $options */ private function downloader(MockHttpClient $http, array $options = []): UrlDownloader { @@ -83,6 +117,7 @@ public function testInsecureOptInDoesNotDisableTlsVerificationAndEmptyFileCanBeS self::assertTrue($options['verify_peer']); self::assertTrue($options['verify_host']); self::assertSame(0, $options['max_redirects']); + self::assertFalse($options['buffer']); return new MockResponse(''); }); diff --git a/tests/Integration/EnvironmentTest.php b/tests/Integration/EnvironmentTest.php index 56a320f..7902d54 100644 --- a/tests/Integration/EnvironmentTest.php +++ b/tests/Integration/EnvironmentTest.php @@ -93,6 +93,39 @@ public function testLoadedMarkersBypassEvenMalformedMainAndAppendedFiles(): void self::assertSame(['production', null], $actual); } + #[Group('PAR-ENV-005')] + public function testNativeLoadedMarkerStillBypassesParsingWithCompatibilityDisabled(): void + { + $this->write('.env', 'malformed main'); + $actual = $this->runPhp(<<<'PHP' +$_ENV['SYMPRESS_RUNTIME_ENV_LOADED'] = false; +$reader = new SymPress\Runtime\Env\EnvReader(compatibility: false); +$reader->loadChain(); +echo json_encode([$reader->determineEnvType(), $reader->read('RTV_MISSING')]); +PHP); + self::assertSame(['production', null], $actual); + } + + #[Group('PAR-ENV-022')] + public function testCacheCannotReintroduceLegacyConstantMappingsAfterDisablingCompatibility(): void + { + $this->write('.env', "WP_STARTER_ENV_TO_CONST=RTV_OLD:string\nRTV_OLD=value\n"); + $actual = $this->runPhp(<<<'PHP' +$reader = new SymPress\Runtime\Env\EnvReader(); +$reader->loadChain(); +$reader->setupConstants(); +$reader->dumpCached('.env.cached.php'); +$data = require '.env.cached.php'; +try { + SymPress\Runtime\Env\EnvReader::buildFromCacheDump('.env.cached.php', compatibility: false); + echo json_encode(['incorrectly accepted']); +} catch (RuntimeException $error) { + echo json_encode([$data['compatibility'], str_contains($error->getMessage(), 'compatibility mode changed')]); +} +PHP); + self::assertSame([true, true], $actual); + } + #[Group('PAR-ENV-002')] public function testInterpolationIgnoresRequestHeadersAndKeepsTrustedFileValues(): void { diff --git a/tests/Integration/MigrationTest.php b/tests/Integration/MigrationTest.php index bc509f0..4a485d4 100644 --- a/tests/Integration/MigrationTest.php +++ b/tests/Integration/MigrationTest.php @@ -48,6 +48,9 @@ public function testMigratesSourcePrecedenceDefaultsAndDeprecatedDatabaseFlagWit self::assertSame('custom.env', $config['env-file']); self::assertSame('wpstarter-autoload.php', $config['autoload']); self::assertFalse($config['env-local-overrides']); + self::assertTrue($config['wp-config-autoload']); + self::assertSame('release-3.0.1 default', $report['provenance']['wp-config-autoload']); + self::assertStringContainsString('wp-config-autoload', implode(' ', $report['next'])); self::assertFalse($config['db-check']); self::assertArrayNotHasKey('skip-db-check', $config); self::assertSame($original, file_get_contents($this->root . '/composer.json')); @@ -81,6 +84,15 @@ public function testDryRunCollisionForceAndOriginalProtection(): void self::assertTrue(is_link($this->root . '/linked.json')); } + public function testMigrationPreservesExplicitProjectAutoloadOptOut(): void + { + $this->fixture(['wpstarter' => ['wp-config-autoload' => false]]); + $run = $this->migrate(); + self::assertSame(0, $run->getExitCode(), $run->getErrorOutput()); + $config = json_decode((string) file_get_contents($this->root . '/sympress-runtime.json'), true, flags: JSON_THROW_ON_ERROR); + self::assertFalse($config['wp-config-autoload']); + } + #[Group('PAR-SYM-008')] public function testStaticFindingsIdentifyLegacyAndComposerImportsWithoutRunningProviders(): void { diff --git a/tests/Integration/WpConfigTest.php b/tests/Integration/WpConfigTest.php index 6724b2f..d5566c5 100644 --- a/tests/Integration/WpConfigTest.php +++ b/tests/Integration/WpConfigTest.php @@ -18,6 +18,68 @@ final class WpConfigTest extends TemporaryProject { + #[Group('PAR-SYM-009')] + public function testDisabledCompatibilityIgnoresLegacyEnvironmentControlsInGeneratedAndRunnerBoots(): void + { + $this->fixture(['compatibility' => false]); + $this->write('.env', "DB_NAME=from-file\nWP_ENV=stage\nWP_STARTER_ENV_TO_CONST=RTV_OLD:string\nRTV_OLD=legacy\nSYMPRESS_RUNTIME_ENV_TO_CONST=RTV_NEW:string\nRTV_NEW=native\n"); + $generated = $this->generate(environment: ['WPSTARTER_ENV_LOADED' => '1']); + self::assertSame(0, $generated->getExitCode(), $generated->getErrorOutput()); + $actual = $this->boot('echo json_encode([DB_NAME, defined("RTV_OLD"), RTV_NEW, WP_ENV, WP_ENVIRONMENT_TYPE, $GLOBALS["deprecated"] ?? []]);', environment: ['WPSTARTER_ENV_LOADED' => '1']); + self::assertSame(['from-file', false, 'native', 'stage', 'staging', []], $actual); + $dump = $this->generate(['dump-env', 'stage'], ['WPSTARTER_ENV_LOADED' => '1']); + self::assertSame(0, $dump->getExitCode(), $dump->getErrorOutput()); + $this->write('.env', 'malformed file bypassed by dump'); + self::assertSame(['from-file', false, 'native', 'stage', 'staging', []], $this->boot('echo json_encode([DB_NAME, defined("RTV_OLD"), RTV_NEW, WP_ENV, WP_ENVIRONMENT_TYPE, $GLOBALS["deprecated"] ?? []]);')); + } + + #[Group('PAR-SYM-009')] + public function testEnabledLegacyEnvironmentControlsReportTheirNamesOnceWithoutValues(): void + { + $this->fixture(); + $this->write('.env', 'malformed file bypassed by sentinel'); + self::assertSame(0, $this->generate()->getExitCode()); + $actual = $this->boot('echo json_encode([RTV_OLD, $GLOBALS["deprecated"] ?? []]);', environment: ['WPSTARTER_ENV_LOADED' => '1', 'WP_STARTER_ENV_TO_CONST' => 'RTV_OLD:string', 'RTV_OLD' => 'synthetic-value']); + self::assertSame(['synthetic-value', ['WPSTARTER_ENV_LOADED', 'WP_STARTER_ENV_TO_CONST']], $actual); + } + + /** @return iterable */ + public static function projectAutoloadModes(): iterable + { + yield 'native default' => ['native', null, false]; + yield 'native opt in' => ['native', true, true]; + yield 'release default' => ['release-3.0.1', null, true]; + yield 'release opt out' => ['release-3.0.1', false, false]; + yield 'dev default' => ['upstream-dev', null, true]; + yield 'dev opt out' => ['upstream-dev', false, false]; + } + + #[DataProvider('projectAutoloadModes')] + #[Group('PAR-WP-002')] + public function testProjectAutoloadPreservesHookOrderAndHonorsProfileAndExplicitOverrides(string $profile, ?bool $option, bool $enabled): void + { + $settings = ['compatibility-profile' => $profile, 'env-bootstrap-dir' => 'configuration', 'early-hook-file' => 'early.php']; + if ($option !== null) { + $settings['wp-config-autoload'] = $option; + } + $this->fixture($settings); + $this->write('.env', "WP_ENV=development\nWP_ENVIRONMENT_TYPE=development\n"); + $this->write('configuration/development.php', 'write('early.php', 'write('custom-dependencies/autoload.php', ' "registered");'); + $vendor = $this->root . '/custom-dependencies'; + $generated = $this->generate(environment: ['COMPOSER_VENDOR_DIR' => $vendor]); + self::assertSame(0, $generated->getExitCode(), $generated->getErrorOutput()); + $actual = $this->boot('echo json_encode([$GLOBALS["trace"], apply_filters("fixture_vendor", "absent"), class_exists("ProjectVendorProbe", false)]);'); + self::assertSame($enabled + ? [['autoload hooks ready', 'vendor env', 'vendor early'], 'registered', true] + : [['env without vendor', 'early without vendor'], 'absent', false], $actual); + if (!$enabled) { + return; + } + self::assertSame([3], $this->boot('require_once __DIR__ . "/custom-dependencies/autoload.php"; echo json_encode([count($GLOBALS["trace"])]);')); + } + #[Group('PAR-WP-010')] public function testDatabaseDefaultsAndExplicitValuesSurviveGeneratedBoot(): void { diff --git a/tools/ci-fixtures.py b/tools/ci-fixtures.py new file mode 100644 index 0000000..4f3f832 --- /dev/null +++ b/tools/ci-fixtures.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Fetch pinned, integrity-checked fixtures for the mandatory integration suite.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import tarfile +import tempfile +import urllib.request + + +FIXTURES = { + "wordpress.tar.gz": ( + "https://wordpress.org/wordpress-7.1.1.tar.gz", + "3996fee13448ef12e07e9f0c77db2f655ffa1b7cde71c80a4965d3bf1fb956b3", + ), + "wp-cli.phar": ( + "https://github.com/wp-cli/wp-cli/releases/download/v2.12.0/wp-cli-2.12.0.phar", + "ce34ddd838f7351d6759068d09793f26755463b4a4610a5a5c0a97b68220d85c", + ), +} + + +def download(url, target, expected): + digest = hashlib.sha256() + total = 0 + with urllib.request.urlopen(url, timeout=60) as response, target.open("wb") as output: + while chunk := response.read(1024 * 1024): + total += len(chunk) + if total > 64 * 1024 * 1024: + raise RuntimeError("CI fixture exceeds the 64 MiB archive limit") + digest.update(chunk) + output.write(chunk) + if digest.hexdigest() != expected: + raise RuntimeError("CI fixture checksum mismatch: " + target.name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--directory", default="build/ci-fixtures") + args = parser.parse_args() + destination = Path(args.directory).resolve() + if destination.exists(): + raise RuntimeError("Use a fresh fixture directory; existing files are not replaced") + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".ci-fixtures-", dir=destination.parent) as temporary: + stage = Path(temporary) + for filename, (url, digest) in FIXTURES.items(): + download(url, stage / filename, digest) + with tarfile.open(stage / "wordpress.tar.gz") as archive: + archive.extractall(stage, filter="data") + (stage / "wordpress.tar.gz").unlink() + if not (stage / "wordpress/wp-settings.php").is_file(): + raise RuntimeError("WordPress fixture is incomplete") + (stage / "manifest.json").write_text(json.dumps(FIXTURES, indent=2) + "\n") + stage.rename(destination) + variables = { + "RUNTIME_TEST_WORDPRESS_DIR": str(destination / "wordpress"), + "RUNTIME_TEST_WPCLI_BOOTSTRAP": str(destination / "wp-cli.phar"), + } + if env_file := os.environ.get("GITHUB_ENV"): + with open(env_file, "a", encoding="utf-8") as output: + for name, value in variables.items(): + output.write(f"{name}={value}\n") + print(json.dumps(variables)) + + +if __name__ == "__main__": + main() diff --git a/tools/consumer-smoke.mjs b/tools/consumer-smoke.mjs index 857c862..daf8526 100644 --- a/tools/consumer-smoke.mjs +++ b/tools/consumer-smoke.mjs @@ -28,11 +28,13 @@ try { assert.doesNotMatch(await page.locator('body').innerText(), /Fatal error:|There has been a critical error|Error establishing a database connection/); await page.screenshot({ path: path.join(outputDirectory, `${name}-home.png`), fullPage: true }); await page.goto(`${env.WP_HOME}/wp-login.php`, { waitUntil: 'domcontentloaded' }); + assert.equal(new URL(page.url()).pathname, '/wp-login.php', 'Login must remain at the public root.'); + assert.equal(new URL(await page.locator('#loginform').getAttribute('action'), page.url()).pathname, '/wp-login.php', 'Login POST must use the public root.'); await page.locator('#user_login').fill(env.WP_ADMIN_USERNAME); await page.locator('#user_pass').fill(env.WP_ADMIN_PASSWORD); await page.locator('#wp-submit').click(); await page.getByRole('heading', { name: 'Dashboard', exact: true }).waitFor(); - assert.match(page.url(), /\/wp-admin\//); + assert.equal(new URL(page.url()).pathname, '/wp-admin/', 'Dashboard must remain at the public root.'); assert.equal(await page.locator('#adminmenu').count(), 1); await page.screenshot({ path: path.join(outputDirectory, `${name}-admin.png`), fullPage: true }); assert.deepEqual(errors, [], 'Browser JavaScript must not fail.'); diff --git a/tools/differential/run.py b/tools/differential/run.py index d10bf5d..09722ba 100644 --- a/tools/differential/run.py +++ b/tools/differential/run.py @@ -162,6 +162,48 @@ def compare_generated(work, baseline, autoload, args, report): print(f"PASS {baseline}/cache/{mode}: exact runtime reports", flush=True) +def compare_project_autoload(work, baseline, autoload, args, report): + oracle = autoload.parent.parent + candidate = work / (baseline + "-early-project-autoload") + candidate.mkdir() + options = {"db-check": False, "require-wp": False, "cache-env": False, "env-dir": ".", "env-bootstrap-dir": "configuration", "early-hook-file": "early.php"} + for project in [oracle, candidate]: + core_fixture(project, "development") + (project / ".env.cached.php").unlink(missing_ok=True) + (project / "configuration").mkdir(exist_ok=True) + (project / "vendor-probe.php").write_text('