diff --git a/.changelog/optional-skills-setup.md b/.changelog/optional-skills-setup.md new file mode 100644 index 0000000000..7afe3f4849 --- /dev/null +++ b/.changelog/optional-skills-setup.md @@ -0,0 +1,6 @@ +--- +category: added +type: minor +--- + +Add opt-in `setup:skills` (`skills:setup`) to install LLM Skills as a consumer development dependency and configure sources through its official CLI. Preserve existing skills policies, register non-empty local skill payloads for DevTools itself, pin external DevTools skills to the executing source commit or an explicit ref, and add the Changelog source at `^0.4.0`. Support read-only previews and optional deferred synchronization. diff --git a/.changelog/tooling-capability-profiles.md b/.changelog/tooling-capability-profiles.md new file mode 100644 index 0000000000..ba642d02d5 --- /dev/null +++ b/.changelog/tooling-capability-profiles.md @@ -0,0 +1,12 @@ +--- +category: added +type: minor +--- + +Adds versioned project capability profiles, interactive setup and tooling status +without installing additional tools. Standards and reports honor explicit +tests, quality, docs and metrics selections, reject invalid profiles and fail +when no checks are selected or a required selected tool is unavailable. Projects +without dev-tools.json retain the full legacy pipeline. This establishes the +selection contract for future optional runtimes; the bundled distribution is +unchanged. diff --git a/README.md b/README.md index 71b34c15ea..a7032e2529 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,10 @@ across Fast Forward libraries. wiki generation gracefully when no runnable PHP surface exists - Works both as a Composer plugin and as a local binary - Preserves local overrides through consumer-first configuration resolution +- Supports selecting available checks per project through a versioned + [tooling capability profile](docs/commands/capability-profiles.rst) +- Provides optional [guided skills setup](docs/commands/setup-skills.rst) + through LLM Skills. ## šŸš€ Installation diff --git a/dev-tools.json b/dev-tools.json new file mode 100644 index 0000000000..e89f4aea87 --- /dev/null +++ b/dev-tools.json @@ -0,0 +1,4 @@ +{ + "version": 1, + "capabilities": ["tests", "quality", "docs", "metrics", "dependencies"] +} diff --git a/docs/commands/capability-profiles.rst b/docs/commands/capability-profiles.rst new file mode 100644 index 0000000000..700b74f48f --- /dev/null +++ b/docs/commands/capability-profiles.rst @@ -0,0 +1,106 @@ +Project Capability Profiles +=========================== + +Use a project profile to choose which capabilities the ``standards`` and +``reports`` aggregators execute. Selection does not change the package's +bundled Composer requirements, install tools or download a smaller runtime. +Individual commands remain explicitly invokable regardless of the selection. + +Configuration +------------- + +The profile is ``dev-tools.json`` in the selected working project directory: + +.. code-block:: json + + { + "version": 1, + "capabilities": ["tests", "quality"] + } + +Only ``version`` and ``capabilities`` are accepted. Version must be the integer +``1``. Capabilities must be a list of distinct supported strings; unknown keys, +names, duplicate names, invalid JSON and other versions fail validation. +A malformed existing file is preserved when configuration fails. + +When the file is absent, aggregators retain their legacy full execution plan. +An explicit empty list is different: no checks are selected, so aggregators +fail rather than report a successful empty run. Removing the profile restores +the legacy plan; selecting every capability creates an explicit plan that also +applies project applicability and availability checks. + +.. list-table:: + :header-rows: 1 + + * - Capability + - Aggregate behavior + * - ``tests`` + - ``reports`` runs tests with coverage when the project exposes testable + PHP source; ``standards`` delegates to that reporting plan. + * - ``quality`` + - ``standards`` runs ``refactor``, ``phpdoc`` and ``code-style``. + * - ``docs`` + - ``reports`` generates documentation when guides or API directories exist. + * - ``metrics`` + - ``reports`` runs the metrics stage. + * - ``dependencies`` + - Records dependency-analysis selection and tool availability. Run + ``dependencies`` explicitly; it is not added to either aggregate plan. + +Configure with setup +-------------------- + +``setup`` (alias ``tooling:configure``) offers an interactive multiple-choice +selection. Its default is the existing profile, or all capabilities when no +profile exists. Explicit options work without a prompt: + +.. code-block:: bash + + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" setup + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" setup --capability=tests --capability=quality --dry-run --no-interaction + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" setup --capability=tests --capability=quality --no-interaction + +Use an exact published CLI version exposing these commands; see +:doc:`../getting-started/installation`. When developing DevTools itself, replace +the CPX invocation with ``php bin/dev-tools``. + +``--capability`` is repeatable and replaces the complete selection rather than +adding entries to the previous profile. Non-interactive setup requires at +least one explicit capability. ``--dry-run`` prints the proposed profile without +writing it. Repeating the same selection does not rewrite the file; capabilities +are stored in canonical order. Setup writes only the profile and installs no +dependencies or repository assets. Commit the reviewed profile with the project. + +Inspect selection and availability +--------------------------------- + +.. code-block:: bash + + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" tooling:status + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" tooling:status --json + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" tooling:status --pretty-json + +Status reports every capability's ``selected`` and ``available`` flags, missing +binary names and resolved binary paths. Structured output contains ``version``, +``profile`` and ``capabilities``; ``profile`` is ``null`` in legacy mode. +Availability checks existing executable files. It does not prove compatible +versions, project readiness or a successful quality run, and does not install +missing tools. A successful status command means inspection succeeded; inspect +the individual availability flags before running an aggregate. + +Aggregate failures +------------------ + +With an explicit profile, aggregates fail when no selected checks apply or +required binaries for their execution plan are missing. For example: + +* ``["quality"]`` runs the three quality phases in ``standards`` but gives + ``reports`` no applicable stage. +* ``["docs"]`` fails ``reports`` when the project has neither guides nor API + directories. +* ``["dependencies"]`` gives neither aggregate an applicable stage; invoke + dependency analysis directly. + +Output-directory options such as ``reports --metrics=...`` choose paths for an +enabled stage; they do not enable a capability omitted from the profile. +See :doc:`standards` and :doc:`reports` for execution order and output options. diff --git a/docs/commands/index.rst b/docs/commands/index.rst index ae1a63998f..233b717ab8 100644 --- a/docs/commands/index.rst +++ b/docs/commands/index.rst @@ -7,6 +7,7 @@ Detailed documentation for each dev-tools command. :maxdepth: 1 standards + capability-profiles tests changelog dependencies @@ -19,6 +20,7 @@ Detailed documentation for each dev-tools command. reports agents skills + setup-skills sync self-update funding diff --git a/docs/commands/reports.rst b/docs/commands/reports.rst index 262c41eced..4add1a44a8 100644 --- a/docs/commands/reports.rst +++ b/docs/commands/reports.rst @@ -6,15 +6,21 @@ Generates the frontpage for Fast Forward documentation. Description ----------- -The ``reports`` command generates the documentation frontpage, runs tests with -coverage, and generates code metrics. It combines: +Without ``dev-tools.json``, ``reports`` retains the legacy reporting plan: - ``docs --target`` - generates API documentation - ``tests --coverage`` - generates test coverage reports - ``metrics --target`` - generates PhpMetrics HTML and JSON reports -The documentation build runs in parallel with PHPUnit, and the metrics step -runs after PHPUnit so it can reuse the generated JUnit report. +With an explicit :doc:`capability-profiles` selection, only selected applicable +``docs``, ``tests`` and ``metrics`` stages run. Documentation requires guides or +API directories; tests require testable PHP source. Metrics remains applicable +to repository metadata/history. ``quality`` and ``dependencies`` do not add +report stages. The command fails if the profile is invalid, no selected stage +applies or a required tool is unavailable. + +When both are enabled, documentation runs in parallel with PHPUnit. Metrics +runs after PHPUnit when coverage is enabled so it can reuse its JUnit report. Usage ----- @@ -29,17 +35,18 @@ Options ------- ``--target`` (optional) - The target directory for the generated documentation. + The target directory for generated documentation when that stage is enabled. Default: selected workspace directory, ``.dev-tools`` unless ``--workspace-dir`` or ``FAST_FORWARD_WORKSPACE_DIR`` is configured. ``--coverage, -c`` (optional) - The target directory for the generated test coverage report. + The target directory for test coverage when the tests stage is enabled. Default: selected workspace ``coverage`` directory, usually ``.dev-tools/coverage``. ``--metrics`` (optional) - The target directory for the generated metrics report. + The target directory for metrics when that stage is enabled. Passing this + option does not enable ``metrics`` in the project profile. Default: selected workspace ``metrics`` directory, usually ``.dev-tools/metrics``. @@ -99,15 +106,16 @@ Exit Codes * - Code - Meaning * - 0 - - Success. Documentation, coverage, and metrics generated successfully. + - Success. The planned report stages completed successfully. * - 1 - - Failure. One or more report stages failed. + - Failure. A stage failed, required tools are unavailable, the profile is + invalid or no selected stages apply. Behavior --------- -- Runs ``docs`` in parallel with ``tests --coverage``. -- Runs ``metrics --target`` after tests so the JUnit report is available. +- Runs enabled ``docs`` in parallel with enabled ``tests --coverage``. +- Runs enabled ``metrics --target`` after tests when both are selected. - Cache stays enabled by default for nested cache-aware steps; omit both flags to keep the command default, pass ``--cache`` to force it on, and pass ``--no-cache`` to force it off. @@ -123,9 +131,9 @@ Behavior - When ``--json`` or ``--pretty-json`` is active, it forwards JSON mode to the ``docs``, ``tests``, and ``metrics`` subprocesses and suppresses transient progress output where those tools support it. -- Nested ``docs`` and ``tests`` stages can now skip gracefully with warnings in - guide-only or automation-only repositories, while ``reports`` still returns a - successful aggregate result for the stages that were actually generated. +- Without a profile, nested ``docs`` and ``tests`` stages retain their legacy + graceful-skip behavior. With a profile, report selection is filtered by + applicability first and an empty plan fails. - Passes ``--junit /junit.xml`` to the metrics step. - Used by the ``standards`` command as the final phase. - This is the reporting stage used by GitHub Pages. diff --git a/docs/commands/setup-skills.rst b/docs/commands/setup-skills.rst new file mode 100644 index 0000000000..460cdf6b3a --- /dev/null +++ b/docs/commands/setup-skills.rst @@ -0,0 +1,120 @@ +setup:skills +============ + +Opts a project into LLM Skills through its official Composer commands. The +alias is ``skills:setup``. This setup is independent of ordinary quality runs +and ``dev-tools:sync``; LLM Skills remains an optional consumer integration. + +Usage +----- + +.. code-block:: bash + + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" setup:skills --dry-run + cpx --skip-local "fast-forward/dev-tools:$DEV_TOOLS_VERSION" setup:skills + +Select an exact published DevTools version exposing this command. When +working on DevTools itself, use ``php bin/dev-tools setup:skills``. The selected +working directory must contain the project's ``composer.json``; use the global +``--working-dir`` option to target another project. + +Options +------- + +``--dry-run`` + Prints the planned commands without executing them. It does not install + packages, generate configuration, fetch skill donors or copy skills. + +``--no-sync`` + Executes dependency/configuration setup and source registration but omits + the final ``composer skills:update``. Official source registration may still + download and validate donor payloads; this is not an offline mode or dry run. + +``--dev-tools-ref=`` + Explicitly chooses the external DevTools GitHub skill ref in a consumer. + Without it, setup uses a 40-character hexadecimal source commit recorded for + the executing DevTools Composer installation. If that metadata is missing + or unsuitable, setup fails before writes and requests an explicit non-empty + ref. Choose a reviewed release commit or supported ref; setup does not fall + back to a moving branch. The DevTools repository uses its local payload and + does not need this external source. + +What setup changes +------------------ + +1. Reads the consumer manifest and checks its existing Composer plugin policy. + An explicit denial of ``llm/skills``, including a matching wildcard or global + false policy, stops setup before mutations. Otherwise setup enables only + the required plugin entry when it is not already allowed. +2. Adds ``llm/skills:^1.15`` to the consumer's ``require-dev`` if neither + dependency section already declares it. Existing constraints and placement, + including a production ``require`` entry, are preserved. If the declared + package is not installed, setup runs Composer install. These dependency + operations disable plugins and scripts and respect ``config.vendor-dir``. +3. If ``skills.json`` is absent, invokes official ``composer skills:init`` in + quick mode with synchronization deferred, target ``.agents/skills``, + Composer trust ``fast-forward/*``, auto-sync enabled and discovery disabled. + The official CLI generates the file; DevTools does not maintain a separate + JSON writer or configuration schema. +4. Registers applicable sources with official ``composer skills:add`` and + synchronization deferred, as described below. +5. Unless ``--no-sync`` is selected, invokes ``composer skills:update`` to copy + the configured skills through LLM Skills. + +There is no global installation or addition of LLM Skills to DevTools' core +requirements. The consumer's manifest, lockfile and plugin policy are the +relevant dependency changes; inspect and commit the intended results together. +Installing instructions does not install the external tools they describe. + +Source registration +------------------- + +.. list-table:: + :header-rows: 1 + + * - Source + - When included + - Ref or location + * - Project-local skills + - Any project with at least one ``SKILL.md`` at the payload root or nested + below it; an absent, empty or unrelated directory is not registered. + - ``./resources/skills`` with ``--from=dir``. + * - External DevTools skills + - Consumer projects, including consumers that also own local skills. + The DevTools repository itself omits this remote source. + - ``php-fast-forward/dev-tools`` at the recorded source commit or explicit + ``--dev-tools-ref``. + * - Changelog skills + - Both consumers and the DevTools repository. + - ``php-fast-forward/changelog`` at ``^0.4.0``. + +The Changelog constraint admits compatible 0.4.x releases; it is not an exact +commit pin. Subsequent updates follow that selected range through LLM Skills. +A consumer's own local payload complements its external DevTools source rather +than replacing it. Source identity, payload validation and installation metadata +remain owned by the official LLM Skills implementation. + +Existing configuration and repeated setup +----------------------------------------- + +An existing ``skills.json`` skips initialization; setup never passes ``--force`` +to reinitialize it. Official source registration updates matching sources while +preserving their selected skill allowlists and unrelated configuration. +Previously chosen trust and synchronization policies remain in place. + +For a new file, LLM Skills 1.15 applies its own defaults and omissions. Its init +options do not expose ``trusted-replace`` or ``vendor-sources`` switches, so +setup does not promise those fields or an exact hand-written JSON layout. +Advanced policy can be reviewed through the official configuration contract; +existing values are not rewritten to match a DevTools template. + +Repeat setup to register current payloads and synchronize again. It does not +add another dependency entry when LLM Skills is already declared. Commands stop +on failure, but completed earlier steps may have changed the project. Inspect +``composer.json``, ``composer.lock``, ``skills.json`` and LLM Skills' generated +state before retrying; setup does not claim an atomic rollback across Composer +and network operations. + +See :doc:`../usage/syncing-packaged-skills` for ongoing updates and donor +ownership policy. LLM Skills does not synchronize generic workflows, hooks, +metadata or arbitrary project-agent prompts. diff --git a/docs/commands/standards.rst b/docs/commands/standards.rst index 122b245fea..e92d2b26ee 100644 --- a/docs/commands/standards.rst +++ b/docs/commands/standards.rst @@ -6,13 +6,20 @@ Runs Fast Forward code standards checks. Description ----------- -The ``standards`` command runs the full quality pipeline: +Without ``dev-tools.json``, ``standards`` retains the full legacy pipeline: 1. ``refactor`` - Rector code refactoring 2. ``phpdoc`` - PHPDoc checks and fixes 3. ``code-style`` - Code style checking 4. ``reports`` - Documentation and test reports +With an explicit :doc:`capability-profiles` selection, ``quality`` enables the +first three phases. Selecting any of ``tests``, ``docs`` or ``metrics`` enables +``reports``, which applies the selected capabilities and project applicability. +``dependencies`` remains an explicit command and does not add a standards +phase. A profile with no standards checks, missing required tools or a report +plan with no applicable checks fails instead of succeeding without execution. + Usage ----- @@ -57,7 +64,8 @@ Exit Codes * - 0 - Success. All checks passed. * - 1 - - Failure. One or more checks failed. + - Failure. A selected check failed, required tools are unavailable, the + profile is invalid or no selected checks apply. Behavior --------- diff --git a/docs/usage/syncing-packaged-skills.rst b/docs/usage/syncing-packaged-skills.rst index aba19c58d2..f3181b4bc7 100644 --- a/docs/usage/syncing-packaged-skills.rst +++ b/docs/usage/syncing-packaged-skills.rst @@ -5,6 +5,9 @@ The ``skills`` command keeps the consumer repository's ``.agents/skills`` directory aligned with the skills shipped inside ``fast-forward/dev-tools``. +For guided optional adoption through LLM Skills, see +:doc:`../commands/setup-skills`. + Why This Command Exists ----------------------- diff --git a/docs/usage/testing-and-coverage.rst b/docs/usage/testing-and-coverage.rst index c4623d1d85..b89d25f6c9 100644 --- a/docs/usage/testing-and-coverage.rst +++ b/docs/usage/testing-and-coverage.rst @@ -67,6 +67,12 @@ When ``tests`` itself runs in structured mode, DevTools also forces the reporter path for the PHPUnit subprocess so the nested payload remains compact and parseable for bots and agent workflows. +Desktop notification delivery is synchronous in the PHPUnit process. The +subscriber does not fork a second reporting/shutdown lifecycle. Transport +exceptions remain visible through PHPUnit's subscriber warnings and configured +warning/exit policies. Packaged extension registration and default profiles +remain unchanged; this delivery change introduces no notification opt-in policy. + Programmatic Coverage Access ----------------------------- @@ -86,6 +92,58 @@ external tooling or build custom reports: $summary->percentage(); // e.g., 84.52 $summary->percentageAsString(); // e.g., "84.52%" +``FastForward\DevTools\PhpUnit\Coverage\MinimumCoverageResolver`` is a final +readonly invocable validator with signature ``__invoke(?string $value): ?float``. +It trims the supplied string and returns ``null`` for null or blank input, +disabling the threshold. Numeric percentages from ``0`` through ``100`` +inclusive return a float. Invalid values throw ``InvalidArgumentException`` +with the existing messages: + +- ``The --min-coverage option MUST be a numeric percentage.`` for non-numeric input; +- ``The --min-coverage option MUST be between 0 and 100.`` for an out-of-range percentage. + +The validator reads no environment or console state. ``TestsCommand`` still +selects the CLI value first, reads ``FAST_FORWARD_MIN_COVERAGE`` only when +that value is null, and passes the selected value to this validator. + +Programmatic Bootstrap and Result Interpretation +------------------------------------------------ + +``FastForward\DevTools\PhpUnit\Bootstrap\BootstrapShimGenerator`` accepts +``generate($projectBootstrap, $cacheDirectory, $runtimeAutoload = null)``. +It writes and returns a bootstrap shim under the cache directory. The shim +loads the project bootstrap first, then the selected runtime autoloader if that +file exists. Pass an explicit isolated runtime autoloader when the caller owns +that runtime; omitting it retains the current DevTools runtime resolution and +the existing consumer-first loading order. + +``FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter`` is an +invocable, final readonly helper that interprets captured process output +without starting a process, reading files or writing console output: + +.. code-block:: php + + use FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter; + + $interpret = new ProcessResultInterpreter(); + $payload = $interpret($capturedOutput, $exitCode); + +The helper retains the reporter payload shape. A nonzero process exit code or +an explicit reporter ``result`` of ``failure`` produces ``failure``; exit code +``0`` does not override a reporter failure. Multiple complete reporter objects +also produce ``failure``, even when each reports success, and preserve the full +trimmed captured output as ``raw_output``. ``TestsCommand`` propagates a +structured failure as command failure even when the process queue exits ``0``. + +Decoded fields from a single reporter payload are retained. Human-readable or +malformed output keeps the existing trimmed ``raw_output`` fallback; when a +recognized final reporter object follows supplemental text, that text is +preserved there instead. Empty output returns only the exit-code-derived +result. Recovery from malformed output has a bounded scan budget. Exhausting +that budget returns failure with the complete captured output, even when an +ambiguous stream ends with a success object. This helper does not define a +separate versioned result schema. + When to Override Locally ------------------------ @@ -98,5 +156,5 @@ agent-oriented JSON output. .. note:: - Desktop notifications are a convenience feature, not a requirement. Test - execution still works when the notification transport is unavailable. + Notification transport errors are not silently ignored. PHPUnit's subscriber + warning and exit policies determine their effect on the completed test run. diff --git a/src/Console/Command/ReportsCommand.php b/src/Console/Command/ReportsCommand.php index a241d38ddf..d51ccc3550 100644 --- a/src/Console/Command/ReportsCommand.php +++ b/src/Console/Command/ReportsCommand.php @@ -27,6 +27,9 @@ use FastForward\DevTools\Process\ProcessBuilderInterface; use FastForward\DevTools\Process\ProcessQueueInterface; use FastForward\DevTools\Path\ManagedWorkspace; +use FastForward\DevTools\Tooling\ToolingProfile; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use Throwable; use Psr\Log\LogLevel; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; @@ -55,11 +58,13 @@ final class ReportsCommand extends Command * @param ProcessBuilderInterface $processBuilder the builder instance used to construct execution processes * @param ProcessQueueInterface $processQueue the execution queue mechanism for running sub-processes * @param ProjectCapabilitiesResolverInterface $projectCapabilitiesResolver the resolver for project capability detection + * @param ?ToolingProfileInterface $toolingProfile */ public function __construct( private readonly ProcessBuilderInterface $processBuilder, private readonly ProcessQueueInterface $processQueue, private readonly ProjectCapabilitiesResolverInterface $projectCapabilitiesResolver, + private readonly ?ToolingProfileInterface $toolingProfile = null, ) { parent::__construct(); } @@ -129,6 +134,40 @@ protected function execute(InputInterface $input, OutputInterface $output): int $coveragePath = (string) $input->getOption('coverage'); $metricsPath = (string) $input->getOption('metrics'); + try { + $profile = $this->toolingProfile ?? new ToolingProfile(); + $selection = $profile->read(); + $projectCapabilities = $this->projectCapabilitiesResolver->resolve(); + $runDocs = null === $selection || (\in_array( + 'docs', + $selection, + true + ) && $projectCapabilities->canGenerateDocs()); + $runTests = $projectCapabilities->canRunTests() && (null === $selection || \in_array( + 'tests', + $selection, + true + )); + $runMetrics = null === $selection || (\in_array( + 'metrics', + $selection, + true + ) && $projectCapabilities->canGenerateMetrics()); + if (null !== $selection) { + $required = [ + ...($runDocs ? ['docs'] : []), + ...($runTests ? ['tests'] : []), + ...($runMetrics ? ['metrics'] : []), + ]; + if ([] === $required) { + return $this->failure('No applicable report checks are selected in dev-tools.json.', $input); + } + $profile->assertAvailable($required); + } + } catch (Throwable $exception) { + return $this->failure($exception->getMessage(), $input); + } + $this->log('Generating frontpage for Fast Forward documentation...', $input); $docsBuilder = $this->processBuilder @@ -138,9 +177,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->withArgument('--coverage-summary') ->withArgument('--coverage', $coveragePath); - $metricsBuilder = $this->processBuilder - ->withArgument('--junit', $coveragePath . '/junit.xml') - ->withArgument('--target', $metricsPath); + $metricsBuilder = $this->processBuilder; + if (null === $selection || $runTests) { + $metricsBuilder = $metricsBuilder->withArgument('--junit', $coveragePath . '/junit.xml'); + } + $metricsBuilder = $metricsBuilder->withArgument('--target', $metricsPath); if (! $jsonOutput) { $docsBuilder = $docsBuilder->withArgument('--ansi'); @@ -168,7 +209,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $docsBuilder = $docsBuilder->withArgument('--pretty-json'); } - $docs = $docsBuilder->build([DevToolsPathResolver::getBinaryPath(), 'docs']); + $docs = $runDocs ? $docsBuilder->build([DevToolsPathResolver::getBinaryPath(), 'docs']) : null; if (null !== $cacheArgument) { $coverageBuilder = $coverageBuilder->withArgument($cacheArgument); @@ -190,11 +231,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int $coverageBuilder = $coverageBuilder->withArgument('--pretty-json'); } - $projectCapabilities = $this->projectCapabilitiesResolver->resolve(); - if ($projectCapabilities->canRunTests()) { + if ($runTests) { $coverage = $coverageBuilder->build([DevToolsPathResolver::getBinaryPath(), 'tests']); $this->processQueue->add(process: $coverage, label: 'Generating Coverage Report'); - } else { + } elseif (null === $selection || \in_array('tests', $selection, true)) { $this->log( 'Skipping coverage report because no tests directory or PHP source files were detected.', $input, @@ -214,10 +254,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $metricsBuilder = $metricsBuilder->withArgument('--pretty-json'); } - $metrics = $metricsBuilder->build([DevToolsPathResolver::getBinaryPath(), 'metrics']); - - $this->processQueue->add(process: $docs, detached: true, label: 'Generating API Docs Report'); - $this->processQueue->add(process: $metrics, label: 'Generating Metrics Report'); + if (null !== $docs) { + $this->processQueue->add(process: $docs, detached: true, label: 'Generating API Docs Report'); + } + if ($runMetrics) { + $metrics = $metricsBuilder->build([DevToolsPathResolver::getBinaryPath(), 'metrics']); + $this->processQueue->add(process: $metrics, label: 'Generating Metrics Report'); + } $result = $this->processQueue->run($processOutput); diff --git a/src/Console/Command/SetupCommand.php b/src/Console/Command/SetupCommand.php new file mode 100644 index 0000000000..25f34c0256 --- /dev/null +++ b/src/Console/Command/SetupCommand.php @@ -0,0 +1,115 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Console\Command; + +use FastForward\DevTools\Tooling\ToolingProfile; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Throwable; + +use function Safe\json_encode; + +/** + * Selects project capabilities without installing their runtime dependencies. + * + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +#[AsCommand(name: 'setup', description: 'Select project tooling capabilities without installing tools.', aliases: [ + 'tooling:configure', +])] +final class SetupCommand extends Command +{ + /** + * @param ToolingProfileInterface $profile the project profile store + */ + public function __construct( + private readonly ToolingProfileInterface $profile + ) { + parent::__construct(); + } + + /** + * Defines explicit selection and preview options. + */ + protected function configure(): void + { + $this->addOption( + 'capability', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'Select a capability; repeat for multiple capabilities.' + ) + ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Preview the profile without writing it.'); + } + + /** + * Validates the existing file before any write or interactive selection. + * + * @param InputInterface $input command arguments and options + * @param OutputInterface $output command output + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + try { + $current = $this->profile->read(); + $selected = $input->getOption('capability'); + if ([] === $selected) { + if (! $input->isInteractive()) { + $io->error('Choose at least one --capability in non-interactive mode.'); + + return self::FAILURE; + } + $defaults = array_keys( + array_intersect(ToolingProfile::CAPABILITIES, $current ?? ToolingProfile::CAPABILITIES) + ); + $selected = $io->choice( + 'Select project capabilities', + ToolingProfile::CAPABILITIES, + [] === $defaults ? null : implode(',', $defaults), + true + ); + } + $selected = ToolingProfile::normalize($selected); + $changed = $this->profile->configure($selected, (bool) $input->getOption('dry-run')); + $output->writeln(json_encode([ + 'version' => 1, + 'capabilities' => $selected, + ], \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR)); + $io->success( + $input->getOption( + 'dry-run' + ) ? 'Profile preview; no files changed.' : ($changed ? 'Project profile saved; no tools installed.' : 'Project profile unchanged.') + ); + + return self::SUCCESS; + } catch (Throwable $exception) { + $io->error($exception->getMessage()); + + return self::FAILURE; + } + } +} diff --git a/src/Console/Command/SkillsSetupCommand.php b/src/Console/Command/SkillsSetupCommand.php new file mode 100644 index 0000000000..f73be0c2cd --- /dev/null +++ b/src/Console/Command/SkillsSetupCommand.php @@ -0,0 +1,269 @@ +addOption( + 'dry-run', + null, + InputOption::VALUE_NONE, + 'Preview commands without installing or writing files.' + ) + ->addOption('no-sync', null, InputOption::VALUE_NONE, 'Configure sources without the final skills:update.') + ->addOption( + 'dev-tools-ref', + null, + InputOption::VALUE_REQUIRED, + 'Explicit GitHub ref for external DevTools skills.' + ); + } + + /** + * @param InputInterface $input the setup options + * @param OutputInterface $output the output destination + * + * @return int + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + try { + $commands = $this->plan($input); + } catch (Throwable $exception) { + $output->writeln('' . $exception->getMessage() . ''); + + return self::FAILURE; + } + + foreach ($commands as $arguments) { + $process = $this->processBuilder->build($arguments); + $process->setWorkingDirectory(getcwd()); + $output->writeln($process->getCommandLine(), OutputInterface::OUTPUT_RAW); + + if ($input->getOption('dry-run')) { + continue; + } + + $this->processQueue->add($process, label: 'Configuring optional LLM Skills'); + if (self::SUCCESS !== $this->processQueue->run($output)) { + return self::FAILURE; + } + } + + return self::SUCCESS; + } + + /** + * Plans every operation before permitting consumer writes. + * + * @param InputInterface $input the setup options + * + * @return list> + */ + private function plan(InputInterface $input): array + { + $contents = $this->filesystem->readFile('composer.json'); + $manifest = json_decode($contents, true); + if (! \is_array($manifest) || ! str_starts_with(ltrim($contents), '{')) { + throw new RuntimeException('The consumer composer.json MUST contain an object.'); + } + + $self = 'fast-forward/dev-tools' === ($manifest['name'] ?? null); + $ref = $self ? null : $this->resolveDevToolsRef($input); + $commands = []; + $approval = $manifest['config']['allow-plugins'] ?? []; + $allowed = null; + + if (\is_bool($approval)) { + $allowed = $approval; + } elseif (\is_array($approval)) { + foreach ($approval as $pattern => $enabled) { + if (fnmatch((string) $pattern, 'llm/skills')) { + $allowed = $enabled; + break; + } + } + } + + if (false === $allowed) { + throw new RuntimeException( + 'Existing Composer policy denies llm/skills; update that policy explicitly before setup.' + ); + } + + if (true !== $allowed) { + $commands[] = ['composer', '--no-plugins', '--no-scripts', 'config', 'allow-plugins.llm/skills', 'true']; + } + + $vendorDirectory = $manifest['config']['vendor-dir'] ?? 'vendor'; + if (! \is_string($vendorDirectory) || '' === trim($vendorDirectory)) { + throw new RuntimeException('The Composer vendor-dir MUST be a non-empty string.'); + } + + if (! isset($manifest['require-dev']['llm/skills']) && ! isset($manifest['require']['llm/skills'])) { + $commands[] = [ + 'composer', + 'require', + '--dev', + 'llm/skills:^1.15', + '--no-plugins', + '--no-scripts', + '--no-interaction', + ]; + } elseif (! $this->filesystem->exists(rtrim($vendorDirectory, '/\\') . '/llm/skills/composer.json')) { + $commands[] = ['composer', 'install', '--no-plugins', '--no-scripts', '--no-interaction']; + } + + if (! $this->filesystem->exists('skills.json')) { + $commands[] = [ + 'composer', + 'skills:init', + '--quick', + '--no-sync', + '--target=.agents/skills', + '--trust=fast-forward/*', + '--auto-sync', + '--no-discovery', + '--no-interaction', + ]; + } + + if ($this->hasLocalSkills()) { + $commands[] = [ + 'composer', + 'skills:add', + './resources/skills', + '--from=dir', + '--no-sync', + '--no-interaction', + ]; + } + + if (! $self) { + $commands[] = [ + 'composer', + 'skills:add', + 'php-fast-forward/dev-tools', + '--ref=' . $ref, + '--no-sync', + '--no-interaction', + ]; + } + + $commands[] = [ + 'composer', + 'skills:add', + 'php-fast-forward/changelog', + '--ref=^0.4.0', + '--no-sync', + '--no-interaction', + ]; + if (! $input->getOption('no-sync')) { + $commands[] = ['composer', 'skills:update', '--no-interaction']; + } + + return $commands; + } + + /** + * Resolves an explicitly chosen ref or the executing installation's source commit. + * + * @param InputInterface $input the setup options + * + * @return string + */ + private function resolveDevToolsRef(InputInterface $input): string + { + $ref = $input->getOption('dev-tools-ref'); + if (\is_string($ref) && '' !== trim($ref)) { + return trim($ref); + } + + if (null !== $ref) { + throw new RuntimeException('--dev-tools-ref MUST be non-empty.'); + } + + if (InstalledVersions::isInstalled('fast-forward/dev-tools')) { + $reference = InstalledVersions::getReference('fast-forward/dev-tools'); + if (\is_string($reference) && 1 === preg_match('/\A[0-9a-f]{40}\z/i', $reference)) { + return $reference; + } + } + + throw new RuntimeException( + 'Cannot verify the executing DevTools source ref; provide --dev-tools-ref explicitly.' + ); + } + + /** + * @return bool + */ + private function hasLocalSkills(): bool + { + if (! $this->filesystem->exists('resources/skills')) { + return false; + } + + return $this->finderFactory->create() + ->files() + ->ignoreDotFiles(false) + ->name('SKILL.md') + ->in('resources/skills') + ->hasResults(); + } +} diff --git a/src/Console/Command/StandardsCommand.php b/src/Console/Command/StandardsCommand.php index 3222223ba7..7e6345026e 100644 --- a/src/Console/Command/StandardsCommand.php +++ b/src/Console/Command/StandardsCommand.php @@ -26,6 +26,9 @@ use FastForward\DevTools\Path\ManagedWorkspace; use FastForward\DevTools\Process\ProcessBuilderInterface; use FastForward\DevTools\Process\ProcessQueueInterface; +use FastForward\DevTools\Tooling\ToolingProfile; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use Throwable; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -51,10 +54,12 @@ final class StandardsCommand extends Command /** * @param ProcessBuilderInterface $processBuilder * @param ProcessQueueInterface $processQueue + * @param ?ToolingProfileInterface $toolingProfile */ public function __construct( private readonly ProcessBuilderInterface $processBuilder, private readonly ProcessQueueInterface $processQueue, + private readonly ?ToolingProfileInterface $toolingProfile = null, ) { parent::__construct(); } @@ -106,9 +111,29 @@ protected function execute(InputInterface $input, OutputInterface $output): int $commands = []; $fix = (bool) $input->getOption('fix'); + try { + $profile = $this->toolingProfile ?? new ToolingProfile(); + $selection = $profile->read(); + $planned = ['refactor', 'phpdoc', 'code-style', 'reports']; + if (null !== $selection) { + $planned = \in_array('quality', $selection, true) ? ['refactor', 'phpdoc', 'code-style'] : []; + if ([] !== array_intersect($selection, ['tests', 'docs', 'metrics'])) { + $planned[] = 'reports'; + } + if ([] === $planned) { + return $this->failure('No standards checks are selected in dev-tools.json.', $input); + } + if (\in_array('quality', $selection, true)) { + $profile->assertAvailable(['quality']); + } + } + } catch (Throwable $exception) { + return $this->failure($exception->getMessage(), $input); + } + $this->log('Running code standards checks...', $input); - foreach (['refactor', 'phpdoc', 'code-style', 'reports'] as $command) { + foreach ($planned as $command) { $commands[] = $command; $processBuilder = $this->processBuilder; diff --git a/src/Console/Command/TestsCommand.php b/src/Console/Command/TestsCommand.php index f07cf79eae..7a17f9a7dc 100644 --- a/src/Console/Command/TestsCommand.php +++ b/src/Console/Command/TestsCommand.php @@ -19,7 +19,6 @@ namespace FastForward\DevTools\Console\Command; -use JsonException; use FastForward\DevTools\Console\Command\Traits\LogsCommandResults; use FastForward\DevTools\Console\Input\HasCacheOption; use FastForward\DevTools\Console\Input\HasJsonOption; @@ -29,6 +28,8 @@ use FastForward\DevTools\Path\DevToolsPathResolver; use FastForward\DevTools\PhpUnit\Bootstrap\BootstrapShimGenerator; use FastForward\DevTools\PhpUnit\Coverage\CoverageSummaryLoaderInterface; +use FastForward\DevTools\PhpUnit\Coverage\MinimumCoverageResolver; +use FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter; use FastForward\DevTools\Process\ProcessBuilderInterface; use FastForward\DevTools\Process\ProcessQueueInterface; use FastForward\DevTools\Path\ManagedWorkspace; @@ -45,9 +46,6 @@ use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Process; -use function is_numeric; -use function Safe\json_decode; -use function Safe\preg_match; /** * Facilitates the execution of the PHPUnit testing framework. @@ -83,6 +81,8 @@ final class TestsCommand extends Command * @param ProcessQueueInterface $processQueue the queue used to execute PHPUnit * @param ProjectCapabilitiesResolverInterface $projectCapabilitiesResolver the project capability resolver * @param EnvironmentInterface $environment the environment resolver for CLI-scoped flags + * @param ProcessResultInterpreter $processResultInterpreter the reusable captured-output interpreter + * @param MinimumCoverageResolver $minimumCoverageResolver the reusable percentage validator */ public function __construct( private readonly CoverageSummaryLoaderInterface $coverageSummaryLoader, @@ -94,6 +94,8 @@ public function __construct( private readonly ProcessQueueInterface $processQueue, private readonly ProjectCapabilitiesResolverInterface $projectCapabilitiesResolver, private readonly EnvironmentInterface $environment, + private readonly ProcessResultInterpreter $processResultInterpreter = new ProcessResultInterpreter(), + private readonly MinimumCoverageResolver $minimumCoverageResolver = new MinimumCoverageResolver(), ) { parent::__construct(); } @@ -253,7 +255,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int $result = $this->processQueue->run($processOutput); $processResultContext = $this->resolveProcessResultContext($processOutput, $result, $structuredOutput); - if (self::SUCCESS !== $result) { + if (self::SUCCESS !== $result + || ($structuredOutput && 'failure' === $processResultContext['output']['result'])) { return $this->failure('PHPUnit tests failed.', $input, $processResultContext); } @@ -341,34 +344,10 @@ private function forceAgentReporter(Process $process): void */ private function resolveStructuredProcessResultPayload(OutputInterface $processOutput, int $exitCode): array { - $payload = [ - 'result' => self::SUCCESS === $exitCode ? 'success' : 'failure', - ]; - - if (! $processOutput instanceof BufferedOutput) { - return $payload; - } - - $rawOutput = trim($processOutput->fetch()); - - if ('' === $rawOutput) { - return $payload; - } - - [$decoded, $supplementalOutput] = $this->decodeStructuredProcessOutput($rawOutput); - - if (\is_array($decoded)) { - $payload = [ - ...$decoded, - 'result' => $payload['result'], - ]; - } - - if (null !== $supplementalOutput) { - $payload['raw_output'] = $supplementalOutput; - } - - return $payload; + return ($this->processResultInterpreter)( + $processOutput instanceof BufferedOutput ? $processOutput->fetch() : '', + $exitCode, + ); } /** @@ -409,42 +388,6 @@ private function withStructuredCoverageValidationContext( return $context; } - /** - * Attempts to decode structured PHPUnit output while preserving any - * non-JSON prelude that was emitted before the final reporter payload. - * - * @param string $rawOutput the captured subprocess output - * - * @return array{array|null, string|null} decoded payload and preserved supplemental output - */ - private function decodeStructuredProcessOutput(string $rawOutput): array - { - try { - $decoded = json_decode($rawOutput, true); - - return [\is_array($decoded) ? $decoded : null, null]; - } catch (JsonException) { - } - - if (1 !== preg_match('/^(?P.*?)(?P\{\s*"result".*)$/s', $rawOutput, $matches)) { - return [null, $rawOutput]; - } - - try { - $decoded = json_decode($matches['payload'], true); - } catch (JsonException) { - return [null, $rawOutput]; - } - - if (! \is_array($decoded)) { - return [null, $rawOutput]; - } - - $prefix = trim($matches['prefix']); - - return [$decoded, '' === $prefix ? null : $prefix]; - } - /** * Safely constructs an absolute path tied to a defined capability option. * @@ -519,23 +462,7 @@ private function resolveMinimumCoverage(InputInterface $input): ?float $minimumCoverage ??= $this->resolveMinimumCoverageFromEnvironment(); - if (false === $minimumCoverage || '' === trim((string) $minimumCoverage)) { - return null; - } - - $minimumCoverage = trim((string) $minimumCoverage); - - if (! is_numeric($minimumCoverage)) { - throw new InvalidArgumentException('The --min-coverage option MUST be a numeric percentage.'); - } - - $minimumCoverage = (float) $minimumCoverage; - - if (0.0 > $minimumCoverage || 100.0 < $minimumCoverage) { - throw new InvalidArgumentException('The --min-coverage option MUST be between 0 and 100.'); - } - - return $minimumCoverage; + return ($this->minimumCoverageResolver)(false === $minimumCoverage ? null : (string) $minimumCoverage); } /** diff --git a/src/Console/Command/ToolingStatusCommand.php b/src/Console/Command/ToolingStatusCommand.php new file mode 100644 index 0000000000..2405b1170e --- /dev/null +++ b/src/Console/Command/ToolingStatusCommand.php @@ -0,0 +1,104 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Console\Command; + +use FastForward\DevTools\Console\Input\HasJsonOption; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Throwable; + +use function Safe\json_encode; + +/** + * Reports project selection and the availability of existing tool binaries. + * + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +#[AsCommand( + name: 'tooling:status', + description: 'Show selected capabilities and available tool binaries.', + aliases: [] +)] +final class ToolingStatusCommand extends Command +{ + use HasJsonOption; + + /** + * @param ToolingProfileInterface $profile the project profile store + */ + public function __construct( + private readonly ToolingProfileInterface $profile + ) { + parent::__construct(); + } + + /** + * Defines structured output options. + */ + protected function configure(): void + { + $this->addJsonOption(); + } + + /** + * Reads capability metadata without installing or modifying anything. + * + * @param InputInterface $input command options + * @param OutputInterface $output metadata output + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + try { + $status = $this->profile->status(); + if ($this->isJsonOutput($input)) { + $output->writeln(json_encode([ + 'version' => 1, + 'profile' => $this->profile->read(), + 'capabilities' => $status, + ], \JSON_THROW_ON_ERROR | ($this->isPrettyJsonOutput($input) ? \JSON_PRETTY_PRINT : 0))); + } else { + $rows = []; + foreach ($status as $capability => $metadata) { + $rows[] = [ + $capability, + $metadata['selected'] ? 'yes' : 'no', + $metadata['available'] ? 'yes' : 'no', + implode(', ', $metadata['missing']), + ]; + } + (new SymfonyStyle($input, $output))->table( + ['Capability', 'Selected', 'Available', 'Missing tools'], + $rows + ); + } + + return self::SUCCESS; + } catch (Throwable $exception) { + (new SymfonyStyle($input, $output))->error($exception->getMessage()); + + return self::FAILURE; + } + } +} diff --git a/src/Container/ServiceProvider/DevToolsServiceProvider.php b/src/Container/ServiceProvider/DevToolsServiceProvider.php index 2a6191be81..b56c6784fe 100644 --- a/src/Container/ServiceProvider/DevToolsServiceProvider.php +++ b/src/Container/ServiceProvider/DevToolsServiceProvider.php @@ -94,6 +94,8 @@ use FastForward\DevTools\SelfUpdate\VersionCheckNotifierInterface; use FastForward\DevTools\SelfUpdate\WorkingDirectorySwitcher; use FastForward\DevTools\SelfUpdate\WorkingDirectorySwitcherInterface; +use FastForward\DevTools\Tooling\ToolingProfile; +use FastForward\DevTools\Tooling\ToolingProfileInterface; use Interop\Container\ServiceProviderInterface; use Psr\Clock\ClockInterface; use Psr\Log\LoggerInterface; @@ -125,6 +127,7 @@ class DevToolsServiceProvider implements ServiceProviderInterface public function getFactories(): array { return [ + ToolingProfileInterface::class => get(ToolingProfile::class), // Process EnvironmentInterface::class => get(Environment::class), RuntimeEnvironmentInterface::class => get(RuntimeEnvironment::class), diff --git a/src/PhpUnit/Bootstrap/BootstrapShimGenerator.php b/src/PhpUnit/Bootstrap/BootstrapShimGenerator.php index 0fb9aecbc9..9304f2ded4 100644 --- a/src/PhpUnit/Bootstrap/BootstrapShimGenerator.php +++ b/src/PhpUnit/Bootstrap/BootstrapShimGenerator.php @@ -44,14 +44,21 @@ public function __construct( * * @param string $projectBootstrap the consumer-project bootstrap path * @param string $cacheDirectory the cache directory where the shim SHOULD be stored + * @param string|null $runtimeAutoload the explicit runtime autoloader, defaulting to the current DevTools runtime * * @return string the generated bootstrap shim path */ - public function generate(string $projectBootstrap, string $cacheDirectory): string - { + public function generate( + string $projectBootstrap, + string $cacheDirectory, + ?string $runtimeAutoload = null, + ): string { $bootstrapShim = Path::join($cacheDirectory, 'bootstrap.php'); - $this->filesystem->dumpFile($bootstrapShim, $this->render($projectBootstrap)); + $this->filesystem->dumpFile($bootstrapShim, $this->render( + $projectBootstrap, + $runtimeAutoload ?? DevToolsPathResolver::getRuntimeAutoloadPath(), + )); return $bootstrapShim; } @@ -60,13 +67,12 @@ public function generate(string $projectBootstrap, string $cacheDirectory): stri * Renders the bootstrap shim contents. * * @param string $projectBootstrap the consumer-project bootstrap path + * @param string $runtimeAutoload the runtime autoloader selected by the caller * * @return string the bootstrap shim source code */ - private function render(string $projectBootstrap): string + private function render(string $projectBootstrap, string $runtimeAutoload): string { - $devToolsAutoload = DevToolsPathResolver::getRuntimeAutoloadPath(); - return <<export($projectBootstrap)}; - if (file_exists({$this->export($devToolsAutoload)})) { - require_once {$this->export($devToolsAutoload)}; + if (file_exists({$this->export($runtimeAutoload)})) { + require_once {$this->export($runtimeAutoload)}; } PHP; } diff --git a/src/PhpUnit/Coverage/MinimumCoverageResolver.php b/src/PhpUnit/Coverage/MinimumCoverageResolver.php new file mode 100644 index 0000000000..af5f7d6ff7 --- /dev/null +++ b/src/PhpUnit/Coverage/MinimumCoverageResolver.php @@ -0,0 +1,64 @@ + + * @copyright Copyright (c) 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\PhpUnit\Coverage; + +use InvalidArgumentException; + +use function is_numeric; + +/** + * Resolves the existing minimum-coverage percentage independently of CLI input. + * + * @copyright Copyright (c) 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +final readonly class MinimumCoverageResolver +{ + /** + * Validates a caller-selected threshold without reading environment or console state. + * + * @param string|null $value the configured threshold, or null when no threshold was selected + * + * @return float|null the percentage, or null when no threshold is configured + * + * @throws InvalidArgumentException when the value is not a percentage between zero and one hundred + */ + public function __invoke(?string $value): ?float + { + $value = trim($value ?? ''); + + if ('' === $value) { + return null; + } + + if (! is_numeric($value)) { + throw new InvalidArgumentException('The --min-coverage option MUST be a numeric percentage.'); + } + + $percentage = (float) $value; + + if (0.0 > $percentage || 100.0 < $percentage) { + throw new InvalidArgumentException('The --min-coverage option MUST be between 0 and 100.'); + } + + return $percentage; + } +} diff --git a/src/PhpUnit/Event/TestSuite/JoliNotifExecutionFinishedSubscriber.php b/src/PhpUnit/Event/TestSuite/JoliNotifExecutionFinishedSubscriber.php index fa8e94d192..a433ba7e47 100644 --- a/src/PhpUnit/Event/TestSuite/JoliNotifExecutionFinishedSubscriber.php +++ b/src/PhpUnit/Event/TestSuite/JoliNotifExecutionFinishedSubscriber.php @@ -48,10 +48,8 @@ * the relevant failure and error counters, followed by expanded telemetry * details. * - * When process forking support is available, notification delivery SHOULD be - * delegated to a child process so the main PHPUnit process MAY continue - * shutting down without waiting for the desktop notification transport to - * complete. + * Notification delivery MUST remain in the PHPUnit process so an exception + * cannot resume a forked copy of its reporting and shutdown lifecycle. * * @codeCoverageIgnore */ @@ -80,11 +78,9 @@ public function __construct( * * This method MUST build the final notification payload using the computed * title, execution summary, and telemetry details. - * When process forking is available, the parent process SHALL return - * immediately after a successful fork, and the child process SHALL send - * the notification and terminate explicitly. When forking support is not - * available, or the fork attempt fails, the notification MUST still be - * delivered synchronously so functional behavior remains unchanged. + * Delivery is synchronous. Transport exceptions remain visible to PHPUnit + * through its subscriber-error handling; this method MUST NOT duplicate + * the runner or suppress its warning and exit policies. * * @param ExecutionFinished $event the emitted PHPUnit execution finished * event @@ -98,17 +94,7 @@ public function notify(ExecutionFinished $event): void ->setBody($this->getBody() . $this->getTelemetryBody($event)) ->setIcon(DevToolsPathResolver::getResourcesPath('phpunit.avif')); - $pid = \function_exists('pcntl_fork') ? pcntl_fork() : -1; - - if ($pid > 0) { - return; - } - $this->notifier->send($notification); - - if (0 === $pid) { - exit(0); - } } /** diff --git a/src/PhpUnit/Result/ProcessResultInterpreter.php b/src/PhpUnit/Result/ProcessResultInterpreter.php new file mode 100644 index 0000000000..afe5b79a2b --- /dev/null +++ b/src/PhpUnit/Result/ProcessResultInterpreter.php @@ -0,0 +1,207 @@ + + * @copyright Copyright (c) 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\PhpUnit\Result; + +use JsonException; + +use function Safe\json_decode; + +/** + * Interprets captured PHPUnit output without console or process dependencies. + * + * A failed process or reporter MUST remain a failure. Multiple reporter + * payloads MUST NOT be interpreted as one successful execution. + * + * @copyright Copyright (c) 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +final readonly class ProcessResultInterpreter +{ + /** + * Limits recovery work to a fixed multiple of the captured output length. + */ + private const int SCAN_WORK_PER_BYTE = 4; + + /** + * Preserves reporter fields while rejecting failed or ambiguous results. + * + * @param string $rawOutput the captured process output + * @param int $exitCode the exit status returned by process execution + * + * @return array the interpreted reporter payload + */ + public function __invoke(string $rawOutput, int $exitCode): array + { + $payload = [ + 'result' => 0 === $exitCode ? 'success' : 'failure', + ]; + $rawOutput = trim($rawOutput); + + if ('' === $rawOutput) { + return $payload; + } + + $supplementalOutput = null; + + try { + $decoded = json_decode($rawOutput, true); + } catch (JsonException) { + $decoded = null; + $reports = $this->findReporterPayloads($rawOutput); + $supplementalOutput = $rawOutput; + + if (null === $reports || 1 < \count($reports)) { + return [ + 'result' => 'failure', + 'raw_output' => $rawOutput, + ]; + } + + if ([] !== $reports) { + [$start, $end, $report] = $reports[0]; + + if ('' === trim(substr($rawOutput, $end + 1))) { + $decoded = $report; + $prefix = trim(substr($rawOutput, 0, $start)); + $supplementalOutput = '' === $prefix ? null : $prefix; + } elseif ('failure' === $report['result']) { + $payload['result'] = 'failure'; + } + } + } + + if (\is_array($decoded)) { + $payload = [ + ...$decoded, + 'result' => 'failure' === ($decoded['result'] ?? null) ? 'failure' : $payload['result'], + ]; + } + + if (null !== $supplementalOutput) { + $payload['raw_output'] = $supplementalOutput; + } + + return $payload; + } + + /** + * Finds complete reporter objects, recovering after malformed diagnostic prefixes. + * + * Valid outer objects consume their nested objects so nested result fields + * are never counted as additional reports. + * + * @param string $rawOutput the captured output containing diagnostics or multiple documents + * + * @return list}>|null reporter objects, or null when recovery exhausts its work budget + */ + private function findReporterPayloads(string $rawOutput): ?array + { + $reports = []; + $length = \strlen($rawOutput); + $remaining = $length * self::SCAN_WORK_PER_BYTE; + + for ($start = 0; $start < $length; ++$start) { + if ('{' !== $rawOutput[$start]) { + continue; + } + + $end = $this->findObjectEnd($rawOutput, $start, $remaining); + + if (null === $end) { + if (0 === $remaining) { + return null; + } + + continue; + } + + try { + $decoded = json_decode(substr($rawOutput, $start, $end - $start + 1), true); + } catch (JsonException) { + continue; + } + + if (\is_array($decoded) && \in_array($decoded['result'] ?? null, ['success', 'failure'], true)) { + $reports[] = [$start, $end, $decoded]; + + if (2 === \count($reports)) { + return $reports; + } + } + + $start = $end; + } + + return $reports; + } + + /** + * Locates one balanced object independently of preceding malformed text. + * + * @param string $rawOutput the captured process output + * @param int $start the opening brace offset + * @param int $remaining the remaining shared byte-inspection budget + * + * @return int|null the closing brace offset, or null for an incomplete object + */ + private function findObjectEnd(string $rawOutput, int $start, int &$remaining): ?int + { + $depth = 0; + $quoted = false; + $escaped = false; + $length = \strlen($rawOutput); + + for ($end = $start; $end < $length; ++$end) { + if (0 === $remaining) { + return null; + } + + --$remaining; + $character = $rawOutput[$end]; + + if ($quoted) { + if ("\n" === $character || "\r" === $character) { + return null; + } + + if ($escaped) { + $escaped = false; + } elseif ('\\' === $character) { + $escaped = true; + } elseif ('"' === $character) { + $quoted = false; + } + + continue; + } + + if ('"' === $character) { + $quoted = true; + } elseif ('{' === $character) { + ++$depth; + } elseif ('}' === $character && 0 === --$depth) { + return $end; + } + } + + return null; + } +} diff --git a/src/Tooling/ToolingProfile.php b/src/Tooling/ToolingProfile.php new file mode 100644 index 0000000000..3c563ed8ca --- /dev/null +++ b/src/Tooling/ToolingProfile.php @@ -0,0 +1,207 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tooling; + +use FastForward\DevTools\Filesystem\Filesystem; +use FastForward\DevTools\Filesystem\FilesystemInterface; +use FastForward\DevTools\Path\DevToolsPathResolver; +use FastForward\DevTools\Path\WorkingProjectPathResolver; +use InvalidArgumentException; +use JsonException; +use RuntimeException; +use stdClass; +use Symfony\Component\Process\ExecutableFinder; + +use function Safe\json_decode; +use function Safe\json_encode; + +/** + * Owns the versioned project profile and reports existing tool availability. + * + * Reading and configuring profiles MUST NOT install dependencies. + * + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +final readonly class ToolingProfile implements ToolingProfileInterface +{ + public const string FILE = 'dev-tools.json'; + + public const array CAPABILITIES = ['tests', 'quality', 'docs', 'metrics', 'dependencies']; + + private const array BINARIES = [ + 'tests' => ['phpunit'], + 'quality' => ['rector', 'php-cs-fixer', 'ecs'], + 'docs' => ['phpdoc'], + 'metrics' => ['phpmetrics'], + 'dependencies' => ['swiss-knife', 'composer-dependency-analyser'], + ]; + + /** + * @param FilesystemInterface $filesystem project file operations + * @param ExecutableFinder $executables resolves Composer on PATH without invoking it + */ + public function __construct( + private FilesystemInterface $filesystem = new Filesystem(), + private ExecutableFinder $executables = new ExecutableFinder(), + ) {} + + /** + * @return list|null the explicit selection, or null for legacy behavior + */ + public function read(): ?array + { + $path = WorkingProjectPathResolver::getProjectPath(self::FILE); + if (! $this->filesystem->exists($path)) { + return null; + } + + try { + $profile = json_decode($this->filesystem->readFile($path), false, 512, \JSON_THROW_ON_ERROR); + } catch (JsonException $exception) { + throw new InvalidArgumentException( + 'Invalid dev-tools.json: ' . $exception->getMessage(), + previous: $exception + ); + } + + if (! $profile instanceof stdClass + || [] !== array_diff(array_keys(get_object_vars($profile)), ['version', 'capabilities']) + || ($profile->version ?? null) !== 1 + || ! isset($profile->capabilities) + || ! \is_array($profile->capabilities) + ) { + throw new InvalidArgumentException('dev-tools.json must contain only version: 1 and a capabilities array.'); + } + + return self::normalize($profile->capabilities); + } + + /** + * Validates and canonically orders the selected capabilities. + * + * @param array $capabilities candidate capability names + * + * @return list + */ + public static function normalize(array $capabilities): array + { + if (! array_is_list($capabilities)) { + throw new InvalidArgumentException('Capabilities must be a list.'); + } + $selected = []; + foreach ($capabilities as $capability) { + if (! \is_string($capability) || ! \in_array($capability, self::CAPABILITIES, true)) { + throw new InvalidArgumentException('Unknown capability. Choose: ' . implode( + ', ', + self::CAPABILITIES + ) . '.'); + } + if (\in_array($capability, $selected, true)) { + throw new InvalidArgumentException('Duplicate capability: ' . $capability . '.'); + } + $selected[] = $capability; + } + + return array_values(array_intersect(self::CAPABILITIES, $selected)); + } + + /** + * Writes a validated selection only when it changes; malformed files are preserved. + * + * @param list $capabilities selected capabilities + * @param bool $dryRun whether to preview without writing + */ + public function configure(array $capabilities, bool $dryRun = false): bool + { + $current = $this->read(); + $selected = self::normalize($capabilities); + if ($current === $selected) { + return false; + } + if (! $dryRun) { + $this->filesystem->dumpFile( + WorkingProjectPathResolver::getProjectPath(self::FILE), + json_encode([ + 'version' => 1, + 'capabilities' => $selected, + ], \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR) . "\n", + ); + } + + return true; + } + + /** + * @return array, binaries: array}> + */ + public function status(): array + { + $selected = $this->read() ?? self::CAPABILITIES; + $status = []; + foreach (self::BINARIES as $capability => $names) { + $binaries = []; + $missing = []; + foreach ($names as $name) { + $path = DevToolsPathResolver::getPreferredToolBinaryPath($name); + $binaries[$name] = $path; + if (! is_file($path) || ! is_executable($path)) { + $missing[] = $name; + } + } + if (\in_array($capability, ['quality', 'dependencies'], true)) { + $composer = $this->executables->find('composer'); + $binaries['composer'] = $composer ?? ''; + if (null === $composer) { + $missing[] = 'composer'; + } + } + if ('quality' === $capability && ! $this->filesystem->exists( + DevToolsPathResolver::getRuntimeVendorPath('ergebnis/composer-normalize/composer.json') + )) { + $missing[] = 'ergebnis/composer-normalize'; + } + $status[$capability] = [ + 'selected' => \in_array($capability, $selected, true), + 'available' => [] === $missing, + 'missing' => $missing, + 'binaries' => $binaries, + ]; + } + + return $status; + } + + /** + * @param list $capabilities capabilities required by the execution plan + */ + public function assertAvailable(array $capabilities): void + { + $status = $this->status(); + foreach ($capabilities as $capability) { + if (! $status[$capability]['available']) { + throw new RuntimeException('Selected capability ' . $capability . ' is missing tools: ' . implode( + ', ', + $status[$capability]['missing'] + ) . '.'); + } + } + } +} diff --git a/src/Tooling/ToolingProfileInterface.php b/src/Tooling/ToolingProfileInterface.php new file mode 100644 index 0000000000..cd9f7a47d2 --- /dev/null +++ b/src/Tooling/ToolingProfileInterface.php @@ -0,0 +1,50 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tooling; + +/** + * Reads explicit project capability selections without installing tools. + * + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +interface ToolingProfileInterface +{ + /** + * @return list|null null retains the legacy full suite + */ + public function read(): ?array; + + /** + * @param list $capabilities explicit selected capabilities + * @param bool $dryRun + */ + public function configure(array $capabilities, bool $dryRun = false): bool; + + /** + * @return array, binaries: array}> + */ + public function status(): array; + + /** + * @param list $capabilities capabilities required by the current execution plan + */ + public function assertAvailable(array $capabilities): void; +} diff --git a/tests/Console/Command/ReportsCommandTest.php b/tests/Console/Command/ReportsCommandTest.php index 3030591410..dab47a5167 100644 --- a/tests/Console/Command/ReportsCommandTest.php +++ b/tests/Console/Command/ReportsCommandTest.php @@ -47,6 +47,8 @@ use Psr\Log\LoggerInterface; use FastForward\DevTools\Tests\Container\UsesContainerFactory; use ReflectionMethod; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use RuntimeException; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -88,6 +90,8 @@ final class ReportsCommandTest extends TestCase private ReportsCommand $command; + private ObjectProphecy $profile; + /** * @return void */ @@ -136,10 +140,14 @@ protected function setUp(): void $this->projectCapabilitiesResolver->resolve() ->willReturn($this->createProjectCapabilities(canRunTests: true)); + $this->profile = $this->prophesize(ToolingProfileInterface::class); + $this->profile->read() + ->willReturn(null); $this->command = new ReportsCommand( $this->processBuilder->reveal(), $this->processQueue->reveal(), $this->projectCapabilitiesResolver->reveal(), + $this->profile->reveal(), ); } @@ -356,6 +364,83 @@ private function executeCommand(): int ->invoke($this->command, $this->input->reveal(), $this->output->reveal()); } + /** + * @return void + */ + #[Test] + public function explicitMetricsProfileWillRunOnlyMetrics(): void + { + $this->processBuilder->withArgument('--junit', Argument::any())->shouldNotBeCalled(); + $this->profile->read() + ->willReturn(['metrics']); + $this->profile->assertAvailable(['metrics'])->shouldBeCalledOnce(); + $this->projectCapabilitiesResolver->resolve() + ->willReturn(new ProjectCapabilities([], null, false, false, false, false)); + $this->processBuilder->build([DevToolsPathResolver::getBinaryPath(), 'docs'])->shouldNotBeCalled(); + $this->processBuilder->build([DevToolsPathResolver::getBinaryPath(), 'tests'])->shouldNotBeCalled(); + $this->processQueue->add($this->process->reveal(), Argument::cetera())->shouldBeCalledOnce(); + $this->processQueue->run($this->output->reveal()) + ->willReturn(0); + + self::assertSame(0, $this->executeCommand()); + } + + /** + * @return void + */ + #[Test] + public function explicitTestsProfileWillRunOnlyCoverageWhenApplicable(): void + { + $this->profile->read() + ->willReturn(['tests']); + $this->profile->assertAvailable(['tests'])->shouldBeCalledOnce(); + $this->projectCapabilitiesResolver->resolve() + ->willReturn(new ProjectCapabilities(['src'], 'Example', false, true, false, true)); + $this->processBuilder->build([DevToolsPathResolver::getBinaryPath(), 'docs'])->shouldNotBeCalled(); + $this->processBuilder->build([DevToolsPathResolver::getBinaryPath(), 'metrics'])->shouldNotBeCalled(); + $this->processQueue->add($this->process->reveal(), Argument::cetera())->shouldBeCalledOnce(); + $this->processQueue->run($this->output->reveal()) + ->willReturn(0); + + self::assertSame(0, $this->executeCommand()); + } + + /** + * @return void + */ + #[Test] + public function selectedTestsWithoutPhpSourceWillFailInsteadOfReportingAnEmptySuccess(): void + { + $this->profile->read() + ->willReturn(['tests']); + $this->projectCapabilitiesResolver->resolve() + ->willReturn(new ProjectCapabilities([], null, false, true, false, false)); + $this->processQueue->add(Argument::cetera())->shouldNotBeCalled(); + $this->logger->error( + 'No applicable report checks are selected in dev-tools.json.', + Argument::any() + )->shouldBeCalledOnce(); + + self::assertSame(1, $this->executeCommand()); + } + + /** + * @return void + */ + #[Test] + public function missingSelectedMetricsWillFailWithoutRunningOtherCapabilities(): void + { + $this->profile->read() + ->willReturn(['metrics']); + $this->projectCapabilitiesResolver->resolve() + ->willReturn(new ProjectCapabilities([], null, false, false, false, false)); + $this->profile->assertAvailable(['metrics'])->willThrow(new RuntimeException('Missing phpmetrics.')); + $this->processQueue->add(Argument::cetera())->shouldNotBeCalled(); + $this->logger->error('Missing phpmetrics.', Argument::any())->shouldBeCalledOnce(); + + self::assertSame(1, $this->executeCommand()); + } + /** * @param bool $canRunTests * diff --git a/tests/Console/Command/SetupCommandTest.php b/tests/Console/Command/SetupCommandTest.php new file mode 100644 index 0000000000..26151dc49e --- /dev/null +++ b/tests/Console/Command/SetupCommandTest.php @@ -0,0 +1,139 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\Console\Command; + +use FastForward\DevTools\Console\Command\SetupCommand; +use FastForward\DevTools\Tooling\ToolingProfile; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\Attributes\UsesClass; +use PHPUnit\Framework\TestCase; +use Prophecy\Argument; +use Prophecy\PhpUnit\ProphecyTrait; +use Symfony\Component\Console\Tester\CommandTester; + +/** + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversClass(SetupCommand::class)] +#[UsesClass(ToolingProfile::class)] +final class SetupCommandTest extends TestCase +{ + use ProphecyTrait; + + /** + * @return void + */ + #[Test] + public function repeatableCapabilitiesWillPersistWithoutInteractiveInput(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->read() + ->willReturn(null); + $profile->configure(['tests', 'docs'], false)->shouldBeCalledOnce()->willReturn(true); + $tester = new CommandTester(new SetupCommand($profile->reveal())); + + self::assertSame(0, $tester->execute([ + '--capability' => ['docs', 'tests'], + ], [ + 'interactive' => false, + ])); + self::assertStringContainsString('no tools installed', $tester->getDisplay()); + } + + /** + * @return void + */ + #[Test] + public function dryRunWillForwardPreviewWithoutWriting(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->read() + ->willReturn(null); + $profile->configure(['metrics'], true)->shouldBeCalledOnce()->willReturn(true); + $tester = new CommandTester(new SetupCommand($profile->reveal())); + + self::assertSame(0, $tester->execute([ + '--capability' => ['metrics'], + '--dry-run' => true, + ], [ + 'interactive' => false, + ])); + self::assertStringContainsString('no files changed', $tester->getDisplay()); + } + + /** + * @return void + */ + #[Test] + public function interactiveSelectionWillPersistChosenCapabilities(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->read() + ->willReturn(null); + $profile->configure(['tests', 'metrics'], false)->shouldBeCalledOnce()->willReturn(true); + $tester = new CommandTester(new SetupCommand($profile->reveal())); + $tester->setInputs(['0,3']); + + self::assertSame(0, $tester->execute([], [ + 'interactive' => true, + ])); + } + + /** + * @return void + */ + #[Test] + public function missingNoninteractiveSelectionWillFailWithoutWriting(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->read() + ->willReturn(null); + $profile->configure(Argument::cetera())->shouldNotBeCalled(); + $tester = new CommandTester(new SetupCommand($profile->reveal())); + + self::assertSame(1, $tester->execute([], [ + 'interactive' => false, + ])); + } + + /** + * @return void + */ + #[Test] + public function malformedProfileWillFailBeforeAnyOverwrite(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->read() + ->willThrow(new InvalidArgumentException('Malformed dev-tools.json.')); + $profile->configure(Argument::cetera())->shouldNotBeCalled(); + $tester = new CommandTester(new SetupCommand($profile->reveal())); + + self::assertSame(1, $tester->execute([ + '--capability' => ['tests'], + ], [ + 'interactive' => false, + ])); + self::assertStringContainsString('Malformed dev-tools.json', $tester->getDisplay()); + } +} diff --git a/tests/Console/Command/SkillsSetupCommandTest.php b/tests/Console/Command/SkillsSetupCommandTest.php new file mode 100644 index 0000000000..aae761341c --- /dev/null +++ b/tests/Console/Command/SkillsSetupCommandTest.php @@ -0,0 +1,410 @@ +filesystem = new SymfonyFilesystem(); + $this->previousDirectory = getcwd(); + $this->workspace = sys_get_temp_dir() . '/skills-setup-' . bin2hex(random_bytes(8)); + $this->filesystem->mkdir($this->workspace); + $this->workspace = realpath($this->workspace); + chdir($this->workspace); + $this->writeManifest(); + $this->filesystem->dumpFile('runner.php', <<<'PHP' + [], 'aliases' => []])); + } + if (in_array('skills:add', $arguments, true)) { + $offset = array_search('skills:add', $arguments, true); + $name = $arguments[$offset + 1]; + $config = json_decode(file_get_contents('skills.json'), true); + $config['fixture-sources'][$name] = $arguments; + file_put_contents('skills.json', json_encode($config)); + } + PHP); + $builder = $this->prophesize(ProcessBuilderInterface::class); + $test = $this; + $builder->build(Argument::type('array'))->will(static function (array $arguments) use ($test): Process { + $test->commands[] = $arguments[0]; + + return new Process([\PHP_BINARY, $test->workspace . '/runner.php', ...$arguments[0]]); + }); + $queue = $this->prophesize(ProcessQueueInterface::class); + $queue->add(Argument::type(Process::class), false, false, Argument::type('string')) + ->will(static function (array $arguments) use ($test): void { + $test->queued = $arguments[0]; + }); + $queue->run(Argument::type(OutputInterface::class))->will(static fn(): int => $test->queued->run()); + $this->tester = new CommandTester(new SkillsSetupCommand( + $builder->reveal(), + $queue->reveal(), + new Filesystem(), + new FinderFactory(), + )); + } + + /** + * @return void + */ + protected function tearDown(): void + { + chdir($this->previousDirectory); + $this->filesystem->remove($this->workspace); + } + + /** + * @return void + */ + #[Test] + public function externalSetupWillInstallOnlySkillsAndUseOfficialCliWithPinnedSources(): void + { + self::assertSame(0, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertSame([ + ['composer', '--no-plugins', '--no-scripts', 'config', 'allow-plugins.llm/skills', 'true'], + ['composer', 'require', '--dev', 'llm/skills:^1.15', '--no-plugins', '--no-scripts', '--no-interaction'], + [ + 'composer', + 'skills:init', + '--quick', + '--no-sync', + '--target=.agents/skills', + '--trust=fast-forward/*', + '--auto-sync', + '--no-discovery', + '--no-interaction', + ], + ['composer', 'skills:add', 'php-fast-forward/dev-tools', '--ref=v2.0.0', '--no-sync', '--no-interaction'], + ['composer', 'skills:add', 'php-fast-forward/changelog', '--ref=^0.4.0', '--no-sync', '--no-interaction'], + ['composer', 'skills:update', '--no-interaction'], + ], $this->commands); + self::assertCount(6, file('calls.jsonl')); + } + + /** + * @return void + */ + #[Test] + public function dryRunWillNotExecuteComposerOrCreateConfiguration(): void + { + $before = file_get_contents('composer.json'); + self::assertSame(0, $this->tester->execute([ + '--dry-run' => true, + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertSame($before, file_get_contents('composer.json')); + self::assertFileDoesNotExist('skills.json'); + self::assertFileDoesNotExist('calls.jsonl'); + self::assertStringContainsString('skills:init', $this->tester->getDisplay()); + } + + /** + * @return iterable + */ + public static function localPayloads(): iterable + { + yield 'missing directory' => [null]; + yield 'empty directory' => ['']; + yield 'unrelated file only' => ['README.md']; + yield 'root skill' => ['SKILL.md']; + yield 'nested skill' => ['nested/skill/SKILL.md']; + } + + /** + * @param string|null $payload + * + * @return void + */ + #[Test] + #[DataProvider('localPayloads')] + public function selfSetupWillRegisterOnlyDirectoriesContainingSkillPayloads(?string $payload): void + { + $this->writeManifest('fast-forward/dev-tools'); + if (null !== $payload) { + $this->filesystem->mkdir('resources/skills'); + if ('' !== $payload) { + $this->filesystem->dumpFile('resources/skills/' . $payload, 'payload'); + } + } + + self::assertSame(0, $this->tester->execute([])); + $local = array_values( + array_filter($this->commands, static fn(array $command): bool => \in_array( + './resources/skills', + $command, + true + )) + ); + self::assertCount(null !== $payload && str_ends_with($payload, 'SKILL.md') ? 1 : 0, $local); + self::assertStringNotContainsString('php-fast-forward/dev-tools', $this->tester->getDisplay()); + } + + /** + * @return void + */ + #[Test] + public function repeatSetupWillPreserveExistingPolicyAndAvoidReinitializationOrReinstallation(): void + { + $this->writeManifest('fixture/consumer', [ + 'require-dev' => [ + 'llm/skills' => '^1.15', + ], + 'config' => [ + 'allow-plugins' => [ + 'other/plugin' => true, + 'llm/skills' => true, + ], + ], + ]); + $this->filesystem->dumpFile('vendor/llm/skills/composer.json', '{}'); + $policy = [ + 'target' => '.custom/skills', + 'aliases' => ['.alias/skills'], + 'discovery' => true, + 'dependencies' => [ + 'composer' => [ + 'trusted' => ['custom/*'], + ], + ], + 'sources' => [[ + 'from' => 'github', + 'package' => 'custom/repo', + 'ref' => 'v1', + ]], + ]; + $this->filesystem->dumpFile('skills.json', json_encode($policy)); + $manifestBefore = file_get_contents('composer.json'); + + self::assertSame(0, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + '--no-sync' => true, + ])); + $first = file_get_contents('skills.json'); + self::assertSame(0, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + '--no-sync' => true, + ])); + self::assertSame($first, file_get_contents('skills.json')); + self::assertSame($manifestBefore, file_get_contents('composer.json')); + $actual = json_decode($first, true); + unset($actual['fixture-sources']); + self::assertSame($policy, $actual); + self::assertCount(4, $this->commands); + self::assertStringNotContainsString('skills:init', $this->tester->getDisplay()); + } + + /** + * @return void + */ + #[Test] + public function failureWillStopBeforeAnyLaterSetupCommands(): void + { + $this->filesystem->dumpFile('fail', 'require'); + + self::assertSame(1, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertCount(2, $this->commands); + self::assertFileDoesNotExist('skills.json'); + } + + /** + * @return void + */ + #[Test] + public function explicitPluginDenialWillFailBeforeAnyMutation(): void + { + $this->writeManifest('fixture/consumer', [ + 'config' => [ + 'allow-plugins' => [ + 'llm/skills' => false, + ], + ], + ]); + + self::assertSame(1, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertSame([], $this->commands); + self::assertFileDoesNotExist('calls.jsonl'); + } + + /** + * @return void + */ + #[Test] + public function automaticSourceWillUseExecutingComposerReference(): void + { + $reference = str_repeat('a', 40); + $fixture = InstalledVersions::getAllRawData()[0]; + $fixture['versions']['fast-forward/dev-tools']['reference'] = $reference; + $vendor = $this->workspace . '/installed-fixture/vendor'; + $this->filesystem->dumpFile( + $vendor . '/composer/installed.php', + 'register(true); + try { + self::assertSame(0, $this->tester->execute([])); + self::assertContains('--ref=' . $reference, $this->commands[3]); + } finally { + $loader->unregister(); + } + } + + /** + * @return void + */ + #[Test] + public function emptyExplicitRefWillFailBeforeAnyMutation(): void + { + self::assertSame(1, $this->tester->execute([ + '--dev-tools-ref' => ' ', + ])); + self::assertSame([], $this->commands); + self::assertFileDoesNotExist('calls.jsonl'); + self::assertFileDoesNotExist('skills.json'); + } + + /** + * @return void + */ + #[Test] + public function consumerLocalSkillsWillBeRegisteredAlongsideExternalDevToolsSource(): void + { + $this->filesystem->dumpFile('resources/skills/SKILL.md', 'consumer skill'); + self::assertSame(0, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertContains( + ['composer', 'skills:add', './resources/skills', '--from=dir', '--no-sync', '--no-interaction'], + $this->commands + ); + self::assertContains( + ['composer', 'skills:add', 'php-fast-forward/dev-tools', '--ref=v2.0.0', '--no-sync', '--no-interaction'], + $this->commands + ); + } + + /** + * @return void + */ + #[Test] + public function productionDependencyWillKeepItsConstraintAndPlacementWhileInstallingMissingVendor(): void + { + $this->writeManifest('fixture/consumer', [ + 'require' => [ + 'llm/skills' => '^1.15.2', + ], + ]); + $before = file_get_contents('composer.json'); + self::assertSame(0, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertContains( + ['composer', 'install', '--no-plugins', '--no-scripts', '--no-interaction'], + $this->commands + ); + self::assertSame( + [], + array_values(array_filter( + $this->commands, + static fn(array $command): bool => \in_array('require', $command, true) + )) + ); + self::assertSame($before, file_get_contents('composer.json')); + } + + /** + * @return void + */ + #[Test] + public function arrayManifestWillFailBeforeAnyMutation(): void + { + $this->filesystem->dumpFile('composer.json', '[]'); + self::assertSame(1, $this->tester->execute([ + '--dev-tools-ref' => 'v2.0.0', + ])); + self::assertSame([], $this->commands); + self::assertFileDoesNotExist('calls.jsonl'); + } + + /** + * @param string $name + * @param array $extra + * + * @return void + */ + private function writeManifest(string $name = 'fixture/consumer', array $extra = []): void + { + $this->filesystem->dumpFile('composer.json', json_encode([ + 'name' => $name, + ...$extra, + ])); + } +} diff --git a/tests/Console/Command/StandardsCommandTest.php b/tests/Console/Command/StandardsCommandTest.php index 75660ef7fa..4adfd985d1 100644 --- a/tests/Console/Command/StandardsCommandTest.php +++ b/tests/Console/Command/StandardsCommandTest.php @@ -46,6 +46,8 @@ use Psr\Log\LoggerInterface; use FastForward\DevTools\Tests\Container\UsesContainerFactory; use ReflectionMethod; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use RuntimeException; use FastForward\DevTools\Path\ManagedWorkspace; use FastForward\DevTools\Path\DevToolsPathResolver; use Symfony\Component\Console\Input\InputInterface; @@ -78,6 +80,8 @@ final class StandardsCommandTest extends TestCase private StandardsCommand $command; + private ObjectProphecy $profile; + /** * @return void */ @@ -111,7 +115,14 @@ protected function setUp(): void $this->processBuilder->build(Argument::any()) ->willReturn($this->prophesize(Process::class)->reveal()); - $this->command = new StandardsCommand($this->processBuilder->reveal(), $this->processQueue->reveal()); + $this->profile = $this->prophesize(ToolingProfileInterface::class); + $this->profile->read() + ->willReturn(null); + $this->command = new StandardsCommand( + $this->processBuilder->reveal(), + $this->processQueue->reveal(), + $this->profile->reveal() + ); } /** @@ -269,7 +280,7 @@ public function executeWillFailForAnActualSubprocessWithExitCodeTwo(): void ); $this->processBuilder->build(Argument::any()) ->will(static fn(): Process => new Process([PHP_BINARY, '-r', 'exit(2);'])); - $this->command = new StandardsCommand($this->processBuilder->reveal(), $queue); + $this->command = new StandardsCommand($this->processBuilder->reveal(), $queue, $this->profile->reveal()); $this->logger->log( 'info', 'Running code standards checks...', @@ -291,6 +302,77 @@ public static function failureExitCodes(): iterable } } + /** + * @return void + */ + #[Test] + public function explicitQualityWillRunOnlyTheThreeQualityPhases(): void + { + $this->profile->read() + ->willReturn(['quality']); + $this->profile->assertAvailable(['quality'])->shouldBeCalledOnce(); + $this->processQueue->add(Argument::type(Process::class), Argument::cetera())->shouldBeCalledTimes(3); + $this->processBuilder->build([DevToolsPathResolver::getBinaryPath(), 'reports'])->shouldNotBeCalled(); + $this->processQueue->run($this->output->reveal()) + ->willReturn(0); + + self::assertSame(0, $this->invokeExecute()); + } + + /** + * @return void + */ + #[Test] + public function explicitTestsWillRunReportsWithoutQuality(): void + { + $this->profile->read() + ->willReturn(['tests']); + $this->processBuilder->build([DevToolsPathResolver::getBinaryPath(), 'reports'])->shouldBeCalledOnce() + ->willReturn(new Process(['true'])); + $this->processQueue->add(Argument::type(Process::class), Argument::cetera())->shouldBeCalledOnce(); + $this->processQueue->run($this->output->reveal()) + ->willReturn(0); + + self::assertSame(0, $this->invokeExecute()); + } + + /** + * @return void + */ + #[Test] + public function explicitEmptyProfileWillFailWithoutQueuingChecks(): void + { + $this->profile->read() + ->willReturn([]); + $this->processQueue->add(Argument::cetera())->shouldNotBeCalled(); + $this->logger->error( + 'No standards checks are selected in dev-tools.json.', + Argument::any() + )->shouldBeCalledOnce(); + + self::assertSame(1, $this->invokeExecute()); + } + + /** + * @return void + */ + #[Test] + public function missingSelectedQualityToolWillFailBeforeRunning(): void + { + $this->profile->read() + ->willReturn(['quality']); + $this->profile->assertAvailable(['quality'])->willThrow( + new RuntimeException('Selected quality tool is missing.') + ); + $this->processQueue->add(Argument::cetera())->shouldNotBeCalled(); + $this->logger->error('Selected quality tool is missing.', Argument::any())->shouldBeCalledOnce(); + + self::assertSame(1, $this->invokeExecute()); + } + + /** + * @return int + */ private function invokeExecute(): int { return (new ReflectionMethod($this->command, 'execute')) diff --git a/tests/Console/Command/TestsCommandTest.php b/tests/Console/Command/TestsCommandTest.php index e397be7c9a..64ec4a7c76 100644 --- a/tests/Console/Command/TestsCommandTest.php +++ b/tests/Console/Command/TestsCommandTest.php @@ -30,6 +30,8 @@ use FastForward\DevTools\PhpUnit\Bootstrap\BootstrapShimGenerator; use FastForward\DevTools\PhpUnit\Coverage\CoverageSummary; use FastForward\DevTools\PhpUnit\Coverage\CoverageSummaryLoaderInterface; +use FastForward\DevTools\PhpUnit\Coverage\MinimumCoverageResolver; +use FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter; use FastForward\DevTools\Process\ProcessBuilder; use FastForward\DevTools\Process\ProcessQueueInterface; use FastForward\DevTools\Path\ManagedWorkspace; @@ -41,6 +43,7 @@ use FastForward\DevTools\Environment\Environment as DevToolsEnvironment; use FastForward\DevTools\Environment\RuntimeEnvironment; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\Attributes\UsesTrait; @@ -66,6 +69,8 @@ #[CoversClass(TestsCommand::class)] #[UsesClass(BootstrapShimGenerator::class)] #[UsesClass(CoverageSummary::class)] +#[UsesClass(MinimumCoverageResolver::class)] +#[UsesClass(ProcessResultInterpreter::class)] #[UsesClass(ContainerFactory::class)] #[UsesClass(DevToolsServiceProvider::class)] #[UsesClass(DevToolsPathResolver::class)] @@ -493,6 +498,50 @@ public function executeWillKeepTheExitCodeDerivedFailureResultAuthoritative(): v self::assertSame(TestsCommand::FAILURE, $this->invokeExecute()); } + /** + * @param string $rawOutput the captured reporter output + * + * @return void + */ + #[Test] + #[DataProvider('reportedFailuresWithZeroExit')] + public function executeWillRejectReportedFailureOrAmbiguousOutputDespiteZeroExitCode(string $rawOutput): void + { + $this->input->getOption('json') + ->willReturn(true); + $this->processQueue->add( + Argument::type(Process::class), + false, + false, + 'Running PHPUnit Tests', + )->shouldBeCalledOnce(); + $this->processQueue->run(Argument::type(OutputInterface::class)) + ->will(static function (array $arguments) use ($rawOutput): int { + $arguments[0]->write($rawOutput); + + return TestsCommand::SUCCESS; + })->shouldBeCalledOnce(); + $this->logger->log(Argument::cetera())->shouldNotBeCalled(); + $this->logger->error( + 'PHPUnit tests failed.', + Argument::that(static fn(array $context): bool => $context['input'] instanceof InputInterface + && 'failure' === ($context['output']['result'] ?? null)), + )->shouldBeCalledOnce(); + $this->output->writeln(Argument::cetera())->shouldNotBeCalled(); + + self::assertSame(TestsCommand::FAILURE, $this->invokeExecute()); + } + + /** + * @return iterable + */ + public static function reportedFailuresWithZeroExit(): iterable + { + yield 'explicit failure from warning' => ['{"result":"failure","summary":{"tests":1,"warnings":1}}']; + yield 'successful and failed reporters' => ["{\"result\":\"success\"}\n{\"result\":\"failure\"}"]; + yield 'two successful reporters remain ambiguous' => ["{\"result\":\"success\"}\n{\"result\":\"success\"}"]; + } + /** * @return void */ diff --git a/tests/Console/Command/ToolingStatusCommandTest.php b/tests/Console/Command/ToolingStatusCommandTest.php new file mode 100644 index 0000000000..228d4af968 --- /dev/null +++ b/tests/Console/Command/ToolingStatusCommandTest.php @@ -0,0 +1,131 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\Console\Command; + +use FastForward\DevTools\Console\Command\ToolingStatusCommand; +use FastForward\DevTools\Console\Input\HasJsonOption; +use FastForward\DevTools\Tooling\ToolingProfileInterface; +use FastForward\DevTools\Container\ContainerFactory; +use FastForward\DevTools\Container\ServiceProvider\DevToolsServiceProvider; +use FastForward\DevTools\Path\DevToolsPathResolver; +use FastForward\DevTools\Environment\RuntimeEnvironmentInterface; +use FastForward\DevTools\Tests\Container\UsesContainerFactory; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\Attributes\UsesTrait; +use PHPUnit\Framework\Attributes\UsesClass; +use PHPUnit\Framework\TestCase; +use Prophecy\PhpUnit\ProphecyTrait; +use Symfony\Component\Console\Tester\CommandTester; + +use function Safe\json_decode; + +/** + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversClass(ToolingStatusCommand::class)] +#[UsesTrait(HasJsonOption::class)] +#[UsesClass(ContainerFactory::class)] +#[UsesClass(DevToolsServiceProvider::class)] +#[UsesClass(DevToolsPathResolver::class)] +final class ToolingStatusCommandTest extends TestCase +{ + use ProphecyTrait; + use UsesContainerFactory; + + /** + * @return void + */ + #[Test] + public function textStatusWillDisplaySelectionAndMissingTools(): void + { + $environment = $this->prophesize(RuntimeEnvironmentInterface::class); + $environment->isAgentPresent() + ->willReturn(false); + $this->setContainerEntry(RuntimeEnvironmentInterface::class, $environment->reveal()); + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->status() + ->willReturn([ + 'tests' => [ + 'selected' => true, + 'available' => false, + 'missing' => ['phpunit'], + 'binaries' => [], + ], + ]); + $tester = new CommandTester(new ToolingStatusCommand($profile->reveal())); + + self::assertSame(0, $tester->execute([])); + self::assertStringContainsString('Missing tools', $tester->getDisplay()); + self::assertStringContainsString('phpunit', $tester->getDisplay()); + } + + /** + * @return void + */ + #[Test] + public function invalidProfileWillReturnFailureWithoutPretendingToolsAreAvailable(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $profile->status() + ->willThrow(new InvalidArgumentException('Invalid profile schema.')); + $tester = new CommandTester(new ToolingStatusCommand($profile->reveal())); + + self::assertSame(1, $tester->execute([ + '--json' => true, + ])); + self::assertStringContainsString('Invalid profile schema', $tester->getDisplay()); + } + + /** + * @return void + */ + #[Test] + public function structuredStatusWillDistinguishSelectedAndAvailableWithoutInstalling(): void + { + $profile = $this->prophesize(ToolingProfileInterface::class); + $metadata = [ + 'tests' => [ + 'selected' => true, + 'available' => false, + 'missing' => ['phpunit'], + 'binaries' => [ + 'phpunit' => '/runtime/vendor/bin/phpunit', + ], + ], + ]; + $profile->status() + ->willReturn($metadata); + $profile->read() + ->willReturn(['tests']); + $tester = new CommandTester(new ToolingStatusCommand($profile->reveal())); + + self::assertSame(0, $tester->execute([ + '--json' => true, + ])); + self::assertSame([ + 'version' => 1, + 'profile' => ['tests'], + 'capabilities' => $metadata, + ], json_decode($tester->getDisplay(), true)); + } +} diff --git a/tests/Distribution/PhpUnitNotificationLifecycleTest.php b/tests/Distribution/PhpUnitNotificationLifecycleTest.php new file mode 100644 index 0000000000..1cb8f885a2 --- /dev/null +++ b/tests/Distribution/PhpUnitNotificationLifecycleTest.php @@ -0,0 +1,215 @@ + + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\Distribution; + +use Composer\Autoload\ClassLoader; +use DOMDocument; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use ReflectionClass; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Process\Process; + +use function random_bytes; +use function Safe\file_get_contents; +use function Safe\json_decode; +use function Safe\realpath; + +/** + * Notification delivery MUST NOT duplicate PHPUnit shutdown output or reports. + * + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversNothing] +final class PhpUnitNotificationLifecycleTest extends TestCase +{ + /** + * Provides successful and failing notification transports. + * + * @return iterable + */ + public static function notificationOutcomes(): iterable + { + yield 'notification succeeds' => [false]; + yield 'notification throws' => [true]; + } + + /** + * Verifies that notification delivery preserves the PHPUnit reporting lifecycle. + * + * @param bool $throws whether notification transport throws after recording its invocation + * + * @return void + */ + #[Test] + #[DataProvider('notificationOutcomes')] + public function notificationWillLeaveOneAgentReportAndOneValidJunitDocument(bool $throws): void + { + $filesystem = new Filesystem(); + $workspace = sys_get_temp_dir() . '/phpunit-notification-' . bin2hex(random_bytes(8)); + $packageRoot = realpath(\dirname(__DIR__, 2)); + $classLoaderFile = (new ReflectionClass(ClassLoader::class))->getFileName(); + self::assertIsString($classLoaderFile); + $vendor = \dirname($classLoaderFile, 2); + + try { + $filesystem->mkdir($workspace); + $filesystem->dumpFile($workspace . '/bootstrap.php', <<<'PHP' + dumpFile($workspace . '/LifecycleExtension.php', <<<'PHP' + getFileName(); + if ($source !== getenv('FIXTURE_PACKAGE_ROOT') . '/src/PhpUnit/Event/TestSuite/JoliNotifExecutionFinishedSubscriber.php') { + throw new RuntimeException('The notification subscriber was not loaded from the current checkout.'); + } + $tracer = new EventTracer(); + $notifier = new class implements NotifierInterface { + public function send(Notification $notification): bool + { + file_put_contents(__DIR__ . '/notifications.log', "sent\n", FILE_APPEND | LOCK_EX); + if ('1' === getenv('FIXTURE_NOTIFIER_THROWS')) { + throw new RuntimeException('Synthetic notification transport failure.'); + } + return true; + } + }; + $facade->registerTracer($tracer); + $facade->registerSubscriber(new JoliNotifExecutionFinishedSubscriber($tracer, $notifier)); + } + } + PHP); + $filesystem->dumpFile($workspace . '/ConsumerTest.php', <<<'PHP' + dumpFile($workspace . '/phpunit.xml', <<<'XML' + + + + + + + + + + + XML); + $process = new Process([ + \PHP_BINARY, + $vendor . '/phpunit/phpunit/phpunit', + '--configuration', + $workspace . '/phpunit.xml', + '--no-progress', + '--colors=never', + $workspace . '/ConsumerTest.php', + ], $workspace, [ + 'FIXTURE_VENDOR' => $vendor, + 'FIXTURE_PACKAGE_ROOT' => $packageRoot, + 'FIXTURE_NOTIFIER_THROWS' => $throws ? '1' : '0', + 'AI_AGENT' => 'fast-forward/dev-tools', + 'INFECTION' => false, + 'XDEBUG_MODE' => 'off', + ]); + $process->setTimeout(15); + $process->run(); + + if ($throws) { + self::assertNotSame(0, $process->getExitCode(), $process->getOutput() . $process->getErrorOutput()); + } else { + self::assertSame(0, $process->getExitCode(), $process->getOutput() . $process->getErrorOutput()); + } + self::assertFileExists($workspace . '/junit.xml'); + self::assertFileExists($workspace . '/notifications.log'); + $junit = file_get_contents($workspace . '/junit.xml'); + $output = $process->getOutput(); + $notifications = file_get_contents($workspace . '/notifications.log'); + $diagnostic = \sprintf( + 'Agent result keys: %d; XML declarations: %d; notifications: %d. Output: %s', + substr_count($output, '"result"'), + substr_count($junit, 'loadXML($junit)); + self::assertSame('testsuites', $document->documentElement->tagName); + self::assertSame(1, $document->getElementsByTagName('testcase')->length); + self::assertSame("sent\n", $notifications); + } finally { + $filesystem->remove($workspace); + } + } +} diff --git a/tests/Distribution/TestingPayloadTest.php b/tests/Distribution/TestingPayloadTest.php new file mode 100644 index 0000000000..3f91ccdb36 --- /dev/null +++ b/tests/Distribution/TestingPayloadTest.php @@ -0,0 +1,221 @@ + + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\Distribution; + +use Composer\Autoload\ClassLoader; +use PharData; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use ReflectionClass; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Process\Process; + +use function Safe\file_get_contents; +use function Safe\json_decode; +use function Safe\realpath; + +/** + * Packaged testing seams MUST execute outside the checkout using public dependencies. + * + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversNothing] +final class TestingPayloadTest extends TestCase +{ + /** + * @return void + */ + #[Test] + #[RunInSeparateProcess] + #[PreserveGlobalState(false)] + public function archiveWillExecuteTestingSeamsWithoutOriginalDevToolsSourceLoader(): void + { + $filesystem = new Filesystem(); + $workspace = sys_get_temp_dir() . '/testing-payload-' . bin2hex(random_bytes(8)); + $packageRoot = \dirname(__DIR__, 2); + $payload = $workspace . '/payload'; + $consumer = $workspace . '/consumer'; + + try { + $filesystem->mkdir([$payload, $consumer]); + $payload = realpath($payload); + $consumer = realpath($consumer); + $archive = new Process([ + 'composer', + '--no-plugins', + '--no-scripts', + '--no-interaction', + 'archive', + '--format=tar', + '--dir=' . $workspace, + '--file=testing-payload', + ], $packageRoot, [ + 'COMPOSER_DISABLE_NETWORK' => '1', + 'GIT_OPTIONAL_LOCKS' => '0', + ]); + $archive->setTimeout(60); + $archive->run(); + self::assertSame(0, $archive->getExitCode(), $archive->getOutput() . $archive->getErrorOutput()); + $archivePath = $workspace . '/testing-payload.tar'; + self::assertFileExists($archivePath); + (new PharData($archivePath))->extractTo($payload); + + foreach ([ + 'src/PhpUnit/Result/ProcessResultInterpreter.php', + 'src/PhpUnit/Bootstrap/BootstrapShimGenerator.php', + 'src/PhpUnit/Coverage/MinimumCoverageResolver.php', + 'phpunit.xml', + 'resources/phpunit.avif', + ] as $path) { + self::assertFileExists($payload . '/' . $path); + } + + foreach (['docs', 'tests'] as $directory) { + self::assertDirectoryDoesNotExist($payload . '/' . $directory); + } + + $manifest = '{"name":"fixture/consumer","require":{"php":"^8.3"}}'; + $bootstrap = 'dumpFile($consumer . '/composer.json', $manifest); + $filesystem->dumpFile($consumer . '/bootstrap.php', $bootstrap); + $filesystem->dumpFile($runtimePath, $runtime); + $filesystem->dumpFile($workspace . '/probe.php', <<<'PHP' + $paths) { + if (!str_starts_with($namespace, 'FastForward\\')) { + $dependencies->addPsr4($namespace, $paths); + } + } + $classMap = []; + foreach (require $vendor . '/composer/autoload_classmap.php' as $class => $file) { + if (!str_starts_with($class, 'FastForward\\')) { + $classMap[$class] = $file; + } + } + $dependencies->addClassMap($classMap); + $dependencies->register(); + foreach (require $vendor . '/composer/autoload_files.php' as $file) { + if (str_contains(str_replace('\\', '/', $file), '/thecodingmachine/safe/')) { + require_once $file; + } + } + if (class_exists(FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter::class) + || class_exists(FastForward\DevTools\PhpUnit\Bootstrap\BootstrapShimGenerator::class)) { + throw new RuntimeException('Public dependency loader unexpectedly provides DevTools source.'); + } + spl_autoload_register(static function (string $class) use ($payload): void { + $prefix = 'FastForward\\DevTools\\'; + if (str_starts_with($class, $prefix)) { + $path = $payload . '/src/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php'; + if (!is_file($path)) { + throw new RuntimeException('Packaged source is missing: ' . $class); + } + require $path; + } + }, true, true); + $interpreter = new FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter(); + $generator = new FastForward\DevTools\PhpUnit\Bootstrap\BootstrapShimGenerator( + new FastForward\DevTools\Filesystem\Filesystem(), + ); + $minimum = new FastForward\DevTools\PhpUnit\Coverage\MinimumCoverageResolver(); + $shim = $generator->generate($consumer . '/bootstrap.php', $consumer . '/cache', $runtime); + require $shim; + $extensionCompatible = class_exists(FastForward\DevTools\PhpUnit\Runner\Extension\DevToolsExtension::class) + && is_a( + FastForward\DevTools\PhpUnit\Runner\Extension\DevToolsExtension::class, + PHPUnit\Runner\Extension\Extension::class, + true, + ); + $sources = []; + foreach (get_declared_classes() as $class) { + if (str_starts_with($class, 'FastForward\\DevTools\\')) { + $source = (new ReflectionClass($class))->getFileName(); + if (!is_string($source) || !str_starts_with($source, $payload . '/src/')) { + throw new RuntimeException('DevTools class loaded outside the packaged payload: ' . $class); + } + $sources[] = $class; + } + } + echo json_encode([ + 'result' => $interpreter("Coverage prelude\n{\"result\":\"success\",\"summary\":{\"tests\":1}}", 2), + 'minimum' => $minimum(' 8e1 '), + 'extension_compatible' => $extensionCompatible, + 'order' => $GLOBALS['bootstrap_order'], + 'sources' => $sources, + ], JSON_THROW_ON_ERROR); + PHP); + $classLoaderFile = (new ReflectionClass(ClassLoader::class))->getFileName(); + self::assertIsString($classLoaderFile); + $process = new Process([ + \PHP_BINARY, + $workspace . '/probe.php', + \dirname($classLoaderFile, 2), + $payload, + $consumer, + $runtimePath, + ], $consumer); + $process->setTimeout(10); + $process->run(); + + self::assertSame(0, $process->getExitCode(), $process->getOutput() . $process->getErrorOutput()); + $output = json_decode($process->getOutput(), true, flags: \JSON_THROW_ON_ERROR); + self::assertSame([ + 'result' => 'failure', + 'summary' => [ + 'tests' => 1, + ], + 'raw_output' => 'Coverage prelude', + ], $output['result']); + self::assertSame(80, $output['minimum']); + self::assertTrue($output['extension_compatible']); + self::assertSame(['consumer', 'runtime'], $output['order']); + self::assertContains( + 'FastForward\\DevTools\\PhpUnit\\Result\\ProcessResultInterpreter', + $output['sources'] + ); + self::assertContains( + 'FastForward\\DevTools\\PhpUnit\\Bootstrap\\BootstrapShimGenerator', + $output['sources'] + ); + self::assertContains( + 'FastForward\\DevTools\\PhpUnit\\Coverage\\MinimumCoverageResolver', + $output['sources'] + ); + self::assertSame($manifest, file_get_contents($consumer . '/composer.json')); + self::assertSame($bootstrap, file_get_contents($consumer . '/bootstrap.php')); + self::assertSame($runtime, file_get_contents($runtimePath)); + } finally { + $filesystem->remove($workspace); + } + } +} diff --git a/tests/PhpUnit/Bootstrap/BootstrapShimExecutionTest.php b/tests/PhpUnit/Bootstrap/BootstrapShimExecutionTest.php new file mode 100644 index 0000000000..32b5217a4a --- /dev/null +++ b/tests/PhpUnit/Bootstrap/BootstrapShimExecutionTest.php @@ -0,0 +1,211 @@ + + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\PhpUnit\Bootstrap; + +use Composer\Autoload\ClassLoader; +use FastForward\DevTools\Filesystem\FilesystemInterface; +use FastForward\DevTools\Path\DevToolsPathResolver; +use FastForward\DevTools\PhpUnit\Bootstrap\BootstrapShimGenerator; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\Attributes\UsesClass; +use PHPUnit\Framework\TestCase; +use Prophecy\Argument; +use Prophecy\PhpUnit\ProphecyTrait; +use ReflectionClass; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Process\Process; + +use function Safe\file_get_contents; +use function Safe\json_decode; + +/** + * Generated shims MUST preserve consumer autoload precedence and bootstrap failures. + * + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversClass(BootstrapShimGenerator::class)] +#[UsesClass(DevToolsPathResolver::class)] +final class BootstrapShimExecutionTest extends TestCase +{ + use ProphecyTrait; + + private Filesystem $filesystem; + + private string $consumer; + + private BootstrapShimGenerator $generator; + + /** + * @return void + */ + protected function setUp(): void + { + $this->filesystem = new Filesystem(); + $this->consumer = sys_get_temp_dir() . '/testing-bootstrap-' . bin2hex(random_bytes(8)); + $this->filesystem->dumpFile($this->consumer . '/composer.json', '{"name":"fixture/consumer"}'); + $filesystem = $this->prophesize(FilesystemInterface::class); + $writer = $this->filesystem; + $filesystem->dumpFile(Argument::type('string'), Argument::type('string')) + ->will(static function (array $arguments) use ($writer): void { + $writer->dumpFile(...$arguments); + }) + ->shouldBeCalledOnce(); + $this->generator = new BootstrapShimGenerator($filesystem->reveal()); + } + + /** + * @return void + */ + protected function tearDown(): void + { + $this->filesystem->remove($this->consumer); + } + + /** + * @return void + */ + #[Test] + public function consumerBootstrapWillTakePrecedenceOverPreloadedRuntimeAutoloader(): void + { + $bootstrap = <<<'PHP' + consumer . '/composer.json'); + $this->filesystem->dumpFile($this->consumer . '/bootstrap.php', $bootstrap); + $this->filesystem->dumpFile($this->consumer . '/ConsumerFilesystem.php', <<<'PHP' + generator->generate($this->consumer . '/bootstrap.php', $this->consumer . '/cache'); + $process = $this->runShim($shim, <<<'PHP' + require $argv[2]; + require $argv[1]; + echo json_encode([ + 'origin' => Symfony\Component\Filesystem\Filesystem::ORIGIN, + 'runtime_available' => class_exists(Symfony\Component\Filesystem\Path::class), + ], JSON_THROW_ON_ERROR); + PHP); + + self::assertSame(0, $process->getExitCode(), $process->getErrorOutput()); + self::assertSame([ + 'origin' => 'consumer', + 'runtime_available' => true, + ], json_decode($process->getOutput(), true, flags: \JSON_THROW_ON_ERROR)); + self::assertSame($bootstrap, file_get_contents($this->consumer . '/bootstrap.php')); + self::assertSame($manifest, file_get_contents($this->consumer . '/composer.json')); + } + + /** + * @return void + */ + #[Test] + public function explicitRuntimeAutoloadWillLoadAfterConsumerWithoutRetainingDevToolsPath(): void + { + $bootstrap = 'consumer . '/composer.json'); + $runtimeAutoload = $this->consumer . "/runtime's files/autoload.php"; + $this->filesystem->dumpFile($this->consumer . '/bootstrap.php', $bootstrap); + $this->filesystem->dumpFile($runtimeAutoload, $runtime); + $shim = $this->generator->generate( + $this->consumer . '/bootstrap.php', + $this->consumer . '/cache', + $runtimeAutoload, + ); + $process = $this->runShim($shim, <<<'PHP' + require $argv[1]; + echo json_encode($GLOBALS['bootstrap_order'], JSON_THROW_ON_ERROR); + PHP); + + self::assertSame(0, $process->getExitCode(), $process->getErrorOutput()); + self::assertSame( + ['consumer', 'runtime'], + json_decode($process->getOutput(), true, flags: \JSON_THROW_ON_ERROR) + ); + self::assertStringContainsString(var_export($runtimeAutoload, true), file_get_contents($shim)); + self::assertStringNotContainsString( + var_export(DevToolsPathResolver::getRuntimeAutoloadPath(), true), + file_get_contents($shim), + ); + self::assertSame($bootstrap, file_get_contents($this->consumer . '/bootstrap.php')); + self::assertSame($runtime, file_get_contents($runtimeAutoload)); + self::assertSame($manifest, file_get_contents($this->consumer . '/composer.json')); + } + + /** + * @return void + */ + #[Test] + public function missingConsumerBootstrapWillFailBeforeContinuingExecution(): void + { + $manifest = file_get_contents($this->consumer . '/composer.json'); + $missingBootstrap = $this->consumer . '/missing-bootstrap.php'; + $shim = $this->generator->generate($missingBootstrap, $this->consumer . '/cache'); + $process = $this->runShim($shim, <<<'PHP' + require $argv[2]; + require $argv[1]; + echo 'bootstrap unexpectedly continued'; + PHP); + + self::assertNotSame(0, $process->getExitCode()); + self::assertStringContainsString($missingBootstrap, $process->getErrorOutput()); + self::assertStringNotContainsString('bootstrap unexpectedly continued', $process->getOutput()); + self::assertFileDoesNotExist($missingBootstrap); + self::assertSame($manifest, file_get_contents($this->consumer . '/composer.json')); + } + + /** + * @param string $shim the generated bootstrap shim path + * @param string $code the PHP code executed in the fixture process + * + * @return Process the completed fixture process + */ + private function runShim(string $shim, string $code): Process + { + $classLoaderFile = (new ReflectionClass(ClassLoader::class))->getFileName(); + self::assertIsString($classLoaderFile); + $runtimeAutoload = \dirname($classLoaderFile, 2) . '/autoload.php'; + $process = new Process([ + \PHP_BINARY, + '-d', + 'display_errors=stderr', + '-r', + $code, + $shim, + $runtimeAutoload, + ], $this->consumer); + $process->setTimeout(10); + $process->run(); + + return $process; + } +} diff --git a/tests/PhpUnit/Coverage/MinimumCoverageResolverTest.php b/tests/PhpUnit/Coverage/MinimumCoverageResolverTest.php new file mode 100644 index 0000000000..1b60cdcba8 --- /dev/null +++ b/tests/PhpUnit/Coverage/MinimumCoverageResolverTest.php @@ -0,0 +1,99 @@ + + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\PhpUnit\Coverage; + +use FastForward\DevTools\PhpUnit\Coverage\MinimumCoverageResolver; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * Minimum coverage parsing MUST preserve the existing numeric percentage contract. + * + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversClass(MinimumCoverageResolver::class)] +final class MinimumCoverageResolverTest extends TestCase +{ + /** + * @param string|null $value the configured threshold + * @param float|null $expected the expected resolved percentage + * + * @return void + */ + #[Test] + #[DataProvider('acceptedValues')] + public function invokeWillResolveOptionalPercentage(?string $value, ?float $expected): void + { + self::assertSame($expected, (new MinimumCoverageResolver())($value)); + } + + /** + * @param string $value the invalid configured threshold + * @param string $message the expected validation error + * + * @return void + */ + #[Test] + #[DataProvider('rejectedValues')] + public function invokeWillRejectInvalidPercentage(string $value, string $message): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + (new MinimumCoverageResolver())($value); + } + + /** + * @return iterable + */ + public static function acceptedValues(): iterable + { + yield 'absent' => [null, null]; + yield 'empty' => ['', null]; + yield 'whitespace' => [" \n\t ", null]; + yield 'lower boundary' => ['0', 0.0]; + yield 'upper boundary' => ['100', 100.0]; + yield 'trimmed decimal' => [' 80.5 ', 80.5]; + yield 'leading decimal point' => ['.5', 0.5]; + yield 'positive sign' => ['+75', 75.0]; + yield 'exponent upper boundary' => ['1e2', 100.0]; + yield 'negative exponent' => ['5e-1', 0.5]; + } + + /** + * @return iterable + */ + public static function rejectedValues(): iterable + { + $numericMessage = 'The --min-coverage option MUST be a numeric percentage.'; + $rangeMessage = 'The --min-coverage option MUST be between 0 and 100.'; + + yield 'not numeric' => ['invalid', $numericMessage]; + yield 'percentage suffix' => ['80%', $numericMessage]; + yield 'negative percentage' => ['-0.1', $rangeMessage]; + yield 'above upper boundary' => ['100.1', $rangeMessage]; + yield 'exponent outside range' => ['1e3', $rangeMessage]; + } +} diff --git a/tests/PhpUnit/Result/ProcessResultInterpreterTest.php b/tests/PhpUnit/Result/ProcessResultInterpreterTest.php new file mode 100644 index 0000000000..27d88f8b5c --- /dev/null +++ b/tests/PhpUnit/Result/ProcessResultInterpreterTest.php @@ -0,0 +1,282 @@ + + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\PhpUnit\Result; + +use FastForward\DevTools\PhpUnit\Result\ProcessResultInterpreter; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * Process interpretation MUST reject reported failures and ambiguous reporter output. + * + * @copyright 2026 Felipe SayĆ£o Lobato Abreu + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversClass(ProcessResultInterpreter::class)] +final class ProcessResultInterpreterTest extends TestCase +{ + /** + * @param string $rawOutput the captured process output + * @param int $exitCode the process exit status + * @param array $expected + * + * @return void + */ + #[Test] + #[DataProvider('processOutputs')] + public function invokeWillPreserveLegacyProcessPayload(string $rawOutput, int $exitCode, array $expected): void + { + self::assertSame($expected, (new ProcessResultInterpreter())($rawOutput, $exitCode)); + } + + /** + * @param string $rawOutput the captured output containing multiple reporter payloads + * + * @return void + */ + #[Test] + #[DataProvider('multipleReporterOutputs')] + public function invokeWillRejectMultipleReporterPayloadsDespiteZeroExitCode(string $rawOutput): void + { + $result = (new ProcessResultInterpreter())($rawOutput, 0); + + self::assertSame('failure', $result['result']); + self::assertSame(trim($rawOutput), $result['raw_output']); + } + + /** + * @return iterable + */ + public static function multipleReporterOutputs(): iterable + { + $success = '{"result":"success","summary":{"tests":1}}'; + $failure = '{"result":"failure","summary":{"warnings":1}}'; + $nested = '{"result":"success","details":{"message":"literal } { \\"result\\":\\"failure\\"","context":{"brace":"}"}}}'; + + yield 'all successful reporters' => [$success . "\n" . $success]; + yield 'all failed reporters' => [$failure . "\n" . $failure]; + yield 'success then failure' => [$success . "\n" . $failure]; + yield 'failure then success' => [$failure . "\n" . $success]; + yield 'adjacent reporters without newline' => [$success . $failure]; + yield 'coverage prelude and mixed reporters' => ["Coverage prelude\n" . $success . "\n" . $failure]; + yield 'pretty printed reporters' => [ + "{\n \"result\": \"success\",\n \"summary\": {\n \"tests\": 1\n }\n}\n{\n \"result\": \"failure\",\n \"summary\": {\n \"warnings\": 1\n }\n}", + ]; + yield 'nested objects and braces in strings before failure' => [$nested . "\n" . $failure]; + yield 'unmatched opening brace in prelude' => ["notice {\n" . $failure . "\n" . $success]; + yield 'first reporter result is not its first key' => [ + '{"summary":{},"result":"failure"}' . "\n" . $success, + ]; + yield 'unterminated quoted prelude before reporters' => [ + "notice \"unterminated\n" . $failure . "\n" . $success, + ]; + yield 'malformed quoted object prefix before failure and success reporters' => [ + 'notice {"broken {"result":"failure"}' . "\n" . '{"result":"success"}', + ]; + } + + /** + * @return iterable}> + */ + public static function processOutputs(): iterable + { + yield 'malformed recovery budget exhaustion fails closed' => [ + str_repeat('{', 1000), + 0, + [ + 'result' => 'failure', + 'raw_output' => str_repeat('{', 1000), + ], + ]; + yield 'empty successful output' => [ + '', 0, [ + 'result' => 'success', + ]]; + yield 'whitespace failed output' => [ + " \n\t ", 1, [ + 'result' => 'failure', + ]]; + yield 'JSON summary' => [ + ' {"result":"success","summary":{"tests":2,"assertions":3}} ', + 0, + [ + 'result' => 'success', + 'summary' => [ + 'tests' => 2, + 'assertions' => 3, + ], + ], + ]; + yield 'nonzero exit overrides reporter success' => [ + '{"result":"success","summary":{"tests":1}}', + 2, + [ + 'result' => 'failure', + 'summary' => [ + 'tests' => 1, + ], + ], + ]; + yield 'explicit reporter failure survives zero exit' => [ + '{"result":"failure","details":{"message":"reported failure"}}', + 0, + [ + 'result' => 'failure', + 'details' => [ + 'message' => 'reported failure', + ], + ], + ]; + yield 'single reporter with nested objects and braces in strings' => [ + '{"result":"success","details":{"message":"literal } { \\"result\\":\\"failure\\"","context":{"brace":"}"}}}', + 0, + [ + 'result' => 'success', + 'details' => [ + 'message' => 'literal } { "result":"failure"', + 'context' => [ + 'brace' => '}', + ], + ], + ], + ]; + yield 'one reporter with nested result objects after prelude' => [ + "notice {\n{\"result\":\"success\",\"details\":{\"nested\":{\"result\":\"failure\"}}}", + 0, + [ + 'result' => 'success', + 'details' => [ + 'nested' => [ + 'result' => 'failure', + ], + ], + 'raw_output' => 'notice {', + ], + ]; + yield 'nested result in diagnostic JSON prefix is not an independent reporter' => [ + '{"context":{"result":"failure"}}' . "\n" . '{"result":"success"}', + 0, + [ + 'result' => 'success', + 'raw_output' => '{"context":{"result":"failure"}}', + ], + ]; + yield 'explicit failure with coverage prelude survives zero exit' => [ + "Coverage prelude\n{\"result\":\"failure\",\"summary\":{\"warnings\":1}}", + 0, + [ + 'result' => 'failure', + 'summary' => [ + 'warnings' => 1, + ], + 'raw_output' => 'Coverage prelude', + ], + ]; + yield 'text before JSON is retained' => [ + " \nCoverage: 75%\n\n{\"result\":\"success\",\"summary\":{\"tests\":1}}\n ", + 0, + [ + 'result' => 'success', + 'summary' => [ + 'tests' => 1, + ], + 'raw_output' => 'Coverage: 75%', + ], + ]; + yield 'invalid raw output is trimmed and retained' => [ + " \nPHPUnit could not start\n ", + 1, + [ + 'result' => 'failure', + 'raw_output' => 'PHPUnit could not start', + ], + ]; + yield 'malformed trailing JSON retains whole output' => [ + "Prelude\n{\"result\":\"success\",\"summary\":", + 1, + [ + 'result' => 'failure', + 'raw_output' => "Prelude\n{\"result\":\"success\",\"summary\":", + ], + ]; + yield 'text after JSON retains whole output' => [ + "Prelude\n{\"result\":\"success\"}\nTrailing output", + 0, + [ + 'result' => 'success', + 'raw_output' => "Prelude\n{\"result\":\"success\"}\nTrailing output", + ], + ]; + yield 'valid JSON string is discarded' => [ + '"plain string"', 0, [ + 'result' => 'success', + ]]; + yield 'valid JSON number is discarded' => [ + '42', 1, [ + 'result' => 'failure', + ]]; + yield 'valid JSON boolean is discarded' => [ + 'false', 0, [ + 'result' => 'success', + ]]; + yield 'valid JSON null is discarded' => [ + 'null', 0, [ + 'result' => 'success', + ]]; + yield 'reporter raw output survives without prelude' => [ + '{"result":"success","raw_output":"reporter detail"}', + 0, + [ + 'result' => 'success', + 'raw_output' => 'reporter detail', + ], + ]; + yield 'prelude overrides reporter raw output' => [ + "Coverage prelude\n{\"result\":\"success\",\"raw_output\":\"reporter detail\"}", + 0, + [ + 'result' => 'success', + 'raw_output' => 'Coverage prelude', + ], + ]; + yield 'prelude permits summary before reporter result' => [ + "Prelude\n{\"summary\":{\"tests\":1},\"result\":\"success\"}", + 0, + [ + 'summary' => [ + 'tests' => 1, + ], + 'result' => 'success', + 'raw_output' => 'Prelude', + ], + ]; + yield 'explicit reporter failure with trailing diagnostics' => [ + "{\"result\":\"failure\"}\nTrailing diagnostics", + 0, + [ + 'result' => 'failure', + 'raw_output' => "{\"result\":\"failure\"}\nTrailing diagnostics", + ], + ]; + } +} diff --git a/tests/Tooling/ToolingProfileTest.php b/tests/Tooling/ToolingProfileTest.php new file mode 100644 index 0000000000..3b275a4361 --- /dev/null +++ b/tests/Tooling/ToolingProfileTest.php @@ -0,0 +1,277 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\Tooling; + +use FastForward\DevTools\Filesystem\FilesystemInterface; +use FastForward\DevTools\Filesystem\Filesystem; +use RuntimeException; +use Symfony\Component\Process\ExecutableFinder; +use FastForward\DevTools\Path\DevToolsPathResolver; +use FastForward\DevTools\Path\WorkingProjectPathResolver; +use FastForward\DevTools\Tooling\ToolingProfile; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\Attributes\UsesClass; +use PHPUnit\Framework\TestCase; +use Prophecy\Argument; +use Prophecy\PhpUnit\ProphecyTrait; +use Prophecy\Prophecy\ObjectProphecy; + +use function Safe\chdir; +use function Safe\file_put_contents; +use function Safe\getcwd; +use function Safe\mkdir; + +/** + * @copyright 2026 Fast Forward + * @license https://opensource.org/licenses/MIT MIT License + */ +#[CoversClass(ToolingProfile::class)] +#[UsesClass(WorkingProjectPathResolver::class)] +#[UsesClass(DevToolsPathResolver::class)] +#[UsesClass(Filesystem::class)] +final class ToolingProfileTest extends TestCase +{ + use ProphecyTrait; + + private ObjectProphecy $filesystem; + + private ToolingProfile $profile; + + private string $path; + + /** + * @return void + */ + protected function setUp(): void + { + $this->path = WorkingProjectPathResolver::getProjectPath('dev-tools.json'); + $this->filesystem = $this->prophesize(FilesystemInterface::class); + $this->filesystem->exists(Argument::any())->willReturn(false); + $this->profile = new ToolingProfile($this->filesystem->reveal()); + } + + /** + * @return void + */ + #[Test] + public function absentProfileWillRetainLegacySelection(): void + { + $this->filesystem->exists($this->path) + ->willReturn(false); + self::assertNull($this->profile->read()); + } + + /** + * @return void + */ + #[Test] + public function emptyExplicitProfileWillRemainDistinctFromAnAbsentProfile(): void + { + $this->existing('{"version":1,"capabilities":[]}'); + self::assertSame([], $this->profile->read()); + } + + /** + * @param string $json + * + * @return void + */ + #[Test] + #[DataProvider('invalidProfiles')] + public function invalidSchemaWillBeRejectedWithoutWriting(string $json): void + { + $this->existing($json); + $this->filesystem->dumpFile(Argument::cetera())->shouldNotBeCalled(); + $this->expectException(InvalidArgumentException::class); + $this->profile->configure(['tests']); + } + + /** + * @return iterable + */ + public static function invalidProfiles(): iterable + { + yield 'broken json' => ['{']; + yield 'root list' => ['[]']; + yield 'missing version' => ['{"capabilities":[]}']; + yield 'string version' => ['{"version":"1","capabilities":[]}']; + yield 'future version' => ['{"version":2,"capabilities":[]}']; + yield 'missing capabilities' => ['{"version":1}']; + yield 'object capabilities' => ['{"version":1,"capabilities":{}}']; + yield 'unknown key' => ['{"version":1,"capabilities":[],"install":true}']; + yield 'unknown capability' => ['{"version":1,"capabilities":["unknown"]}']; + yield 'duplicate capability' => ['{"version":1,"capabilities":["tests","tests"]}']; + yield 'non-string capability' => ['{"version":1,"capabilities":[false]}']; + } + + /** + * @return void + */ + #[Test] + public function configureWillWriteCanonicalSelectionOnlyWhenChanged(): void + { + $this->filesystem->exists($this->path) + ->willReturn(false); + $this->filesystem->dumpFile( + $this->path, + Argument::that(static fn(string $content): bool => json_decode($content, true) === [ + 'version' => 1, + 'capabilities' => ['tests', 'docs'], + ]) + )->shouldBeCalledOnce(); + + self::assertTrue($this->profile->configure(['docs', 'tests'])); + } + + /** + * @return void + */ + #[Test] + public function unchangedSelectionWillPreserveExistingFormatting(): void + { + $this->existing('{"version":1,"capabilities":["docs","tests"]}'); + $this->filesystem->dumpFile(Argument::cetera())->shouldNotBeCalled(); + + self::assertFalse($this->profile->configure(['tests', 'docs'])); + } + + /** + * @return void + */ + #[Test] + public function dryRunWillReportChangeWithoutWriting(): void + { + $this->filesystem->exists($this->path) + ->willReturn(false); + $this->filesystem->dumpFile(Argument::cetera())->shouldNotBeCalled(); + + self::assertTrue($this->profile->configure(['quality'], true)); + } + + /** + * @return void + */ + #[Test] + public function statusWillReportSelectionSeparatelyFromPreferredBinaryAvailability(): void + { + $this->existing('{"version":1,"capabilities":["tests"]}'); + $status = $this->profile->status(); + + self::assertSame(ToolingProfile::CAPABILITIES, array_keys($status)); + self::assertTrue($status['tests']['selected']); + self::assertFalse($status['docs']['selected']); + self::assertSame( + DevToolsPathResolver::getPreferredToolBinaryPath('phpunit'), + $status['tests']['binaries']['phpunit'] + ); + self::assertSame([], $status['tests']['missing']); + self::assertTrue($status['tests']['available']); + $this->profile->assertAvailable(['tests']); + } + + /** + * @return void + */ + #[Test] + public function missingExecutableWillFailEvenWhenAConsumerBinaryFileExists(): void + { + $original = getcwd(); + $directory = sys_get_temp_dir() . '/tooling-profile-' . bin2hex(random_bytes(4)); + mkdir($directory . '/vendor/bin', 0o777, true); + file_put_contents($directory . '/vendor/bin/phpunit', 'not executable'); + + try { + chdir($directory); + $profile = new ToolingProfile(); + self::assertFalse($profile->status()['tests']['available']); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Selected capability tests is missing tools: phpunit.'); + $profile->assertAvailable(['tests']); + } finally { + chdir($original); + (new Filesystem())->remove($directory); + } + } + + /** + * @param string $json + * + * @return void + */ + private function existing(string $json): void + { + $this->filesystem->exists($this->path) + ->willReturn(true); + $this->filesystem->readFile($this->path) + ->willReturn($json); + } + + /** + * @return void + */ + #[Test] + public function absentComposerWillMakeQualityAndDependenciesUnavailableDespiteInstalledEngines(): void + { + $this->existing('{"version":1,"capabilities":["quality","dependencies"]}'); + $this->filesystem->exists( + DevToolsPathResolver::getRuntimeVendorPath('ergebnis/composer-normalize/composer.json') + )->willReturn(true); + $executables = $this->prophesize(ExecutableFinder::class); + $executables->find('composer') + ->willReturn(null); + $profile = new ToolingProfile($this->filesystem->reveal(), $executables->reveal()); + $status = $profile->status(); + + foreach (['quality', 'dependencies'] as $capability) { + self::assertFalse($status[$capability]['available']); + self::assertSame(['composer'], $status[$capability]['missing']); + foreach ($status[$capability]['binaries'] as $name => $path) { + if ('composer' !== $name) { + self::assertTrue(is_executable($path), $path); + } + } + } + } + + /** + * @return void + */ + #[Test] + public function qualityWillRequireNormalizerInTheToolRuntimeInsteadOfTheConsumer(): void + { + $this->existing('{"version":1,"capabilities":["quality"]}'); + $manifest = DevToolsPathResolver::getRuntimeVendorPath('ergebnis/composer-normalize/composer.json'); + $this->filesystem->exists($manifest) + ->willReturn(false) + ->shouldBeCalledOnce(); + $executables = $this->prophesize(ExecutableFinder::class); + $executables->find('composer') + ->willReturn('/tools/composer'); + + $status = (new ToolingProfile($this->filesystem->reveal(), $executables->reveal()))->status(); + + self::assertFalse($status['quality']['available']); + self::assertSame(['ergebnis/composer-normalize'], $status['quality']['missing']); + self::assertSame('/tools/composer', $status['quality']['binaries']['composer']); + } +}