diff --git a/.changelog/release-phar-cadence.md b/.changelog/release-phar-cadence.md new file mode 100644 index 0000000..6b1dc56 --- /dev/null +++ b/.changelog/release-phar-cadence.md @@ -0,0 +1,12 @@ +--- +category: fixed +type: patch +--- + +Build runtime-affecting pull requests once and qualify the same executable on +all supported PHP versions before automatically refreshing their compiled +distribution. Skip rebuilds for documentation-only changes, refuse refreshes +of closed or superseded branches, and qualify the final merged tree before +atomically including the executable in its native version PR. Bind preparation +and exact-head feedback to the qualified source and preserve automatic fragment +pull-request references. diff --git a/.github/workflows/repository-changelog.yml b/.github/workflows/repository-changelog.yml index 8b5d383..a42c817 100644 --- a/.github/workflows/repository-changelog.yml +++ b/.github/workflows/repository-changelog.yml @@ -11,7 +11,13 @@ on: workflow_dispatch: permissions: {} jobs: + quality: + if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/repository-ci.yml + permissions: + contents: read changelog: + if: github.event_name == 'pull_request' || github.event_name == 'pull_request_target' permissions: contents: write pull-requests: write @@ -22,11 +28,99 @@ jobs: with: runs-on: '["ubuntu-latest"]' base-branch: main - managed-branch: changelog/version-recovery-98 + managed-branch: changelog/version-phar source: tags - prepare-release: true + resolve-pull-requests: true + generated-files: '["dist/code-standards"]' + prepare-release: false publish: true publish-app-client-id: 'Iv23liHqRng02H747IYa' publish-environment: release-channels secrets: publish-app-private-key: ${{ secrets.RELEASE_CHANNEL_APP_PRIVATE_KEY }} + version: + needs: quality + if: >- + (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && + github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 15 + concurrency: + group: changelog-${{ github.repository }}-main + cancel-in-progress: false + outputs: + pull-request: ${{ steps.version.outputs.pull-request }} + head-sha: ${{ steps.version.outputs.head-sha }} + permissions: + contents: write + pull-requests: write + issues: read + steps: + - name: Skip a qualification superseded by a newer main + id: base + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + QUALIFIED_BASE: ${{ github.sha }} + shell: bash + run: | + current=$(gh api "repos/$GH_REPO/git/ref/heads/main" --jq '.object.sha') + [[ "$current" =~ ^[0-9a-f]{40}$ ]] + if test "$current" = "$QUALIFIED_BASE"; then + echo 'current=true' >> "$GITHUB_OUTPUT" + else + echo 'current=false' >> "$GITHUB_OUTPUT" + echo 'A newer main superseded this qualification; its run prepares the version.' >> "$GITHUB_STEP_SUMMARY" + fi + - if: steps.base.outputs.current == 'true' + uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + - name: Require the successful qualification's artifact identity + if: steps.base.outputs.current == 'true' + env: + QUALIFIED_ARTIFACT: ${{ needs.quality.outputs.artifact }} + run: test -n "$QUALIFIED_ARTIFACT" + - if: steps.base.outputs.current == 'true' + uses: actions/download-artifact@v8.0.2 + with: + artifact-ids: ${{ needs.quality.outputs.artifact }} + merge-multiple: true + path: ${{ runner.temp }}/phar + - name: Stage the qualified executable as data + if: steps.base.outputs.current == 'true' + run: | + test -f dist/code-standards && test ! -L dist && test ! -L dist/code-standards + test -f "$RUNNER_TEMP/phar/code-standards" && test ! -L "$RUNNER_TEMP/phar/code-standards" + install -m 755 "$RUNNER_TEMP/phar/code-standards" dist/code-standards + - name: Prepare the version with the qualified executable + if: steps.base.outputs.current == 'true' + id: version + uses: php-fast-forward/changelog/.github/actions/version@v0 + with: + base-branch: main + base-ref: ${{ github.sha }} + managed-branch: changelog/version-phar + source: tags + generated-files: '["dist/code-standards"]' + resolve-pull-requests: true + feedback: + needs: version + if: needs.version.outputs.pull-request != '' && needs.version.outputs.head-sha != '' + permissions: + contents: read + pull-requests: write + issues: read + statuses: write + uses: php-fast-forward/changelog/.github/workflows/changelog-pr-status.yml@v0 + with: + pull-request: ${{ fromJSON(needs.version.outputs.pull-request) }} + head-sha: ${{ needs.version.outputs.head-sha }} + base-sha: ${{ github.sha }} + base-branch: main + managed-branch: changelog/version-phar + source: tags + generated-files: '["dist/code-standards"]' + resolve-pull-requests: true diff --git a/.github/workflows/repository-ci.yml b/.github/workflows/repository-ci.yml index 91a9673..662ff9d 100644 --- a/.github/workflows/repository-ci.yml +++ b/.github/workflows/repository-ci.yml @@ -1,19 +1,60 @@ name: 'Repository: Quality' on: pull_request: - push: - branches: [main] workflow_dispatch: + workflow_call: + outputs: + artifact: + description: Fully qualified canonical executable artifact ID. + value: ${{ jobs.compiled.outputs.artifact }} permissions: contents: read jobs: - tests: + inputs: + runs-on: ubuntu-latest + outputs: + build: ${{ steps.inputs.outputs.build }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - id: inputs + env: + BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + EVENT: ${{ github.event_name }} + shell: bash + run: | + if test "$EVENT" != pull_request; then + echo 'build=true' >> "$GITHUB_OUTPUT" + exit 0 + fi + build=true + if git cat-file -e "$BASE^{commit}" 2>/dev/null; then + if test "$EVENT" = pull_request; then + BASE=$(git merge-base "$BASE" "$HEAD") + fi + git diff --no-renames --name-only -z "$BASE" "$HEAD" > "$RUNNER_TEMP/phar-inputs" + build=false + while IFS= read -r -d '' path; do + case "$path" in + tests/Distribution/*|tests/Fixtures/*|.github/workflows/repository-ci.yml|.github/workflows/repository-phar-refresh.yml) build=true ;; + docs/*|.changelog/*|tests/*|.github/*|README.md|CHANGELOG.md|AGENTS.md|.editorconfig|.gitignore|phpunit.xml*) ;; + *) build=true ;; + esac + done < "$RUNNER_TEMP/phar-inputs" + fi + echo "build=$build" >> "$GITHUB_OUTPUT" + build: + needs: inputs + if: needs.inputs.outputs.build == 'true' runs-on: ubuntu-latest timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - php: ['8.3', '8.4', '8.5'] + outputs: + stale: ${{ steps.parity.outputs.stale }} + artifact: ${{ steps.candidate.outputs.artifact-id }} steps: - uses: actions/checkout@v7 with: @@ -21,7 +62,7 @@ jobs: persist-credentials: false - uses: shivammathur/setup-php@v2 with: - php-version: ${{ matrix.php }} + php-version: '8.3' extensions: dom, posix coverage: none tools: composer:v2, box:4.7.1 @@ -29,15 +70,7 @@ jobs: env: COMPOSER_HOME: ${{ runner.temp }}/standards-composer-home COMPOSER_CACHE_DIR: ${{ runner.temp }}/standards-composer-cache - - run: composer validate --strict - - name: Check Composer normalization - env: - STANDARDS_ROOT: ${{ github.workspace }} - STANDARDS_DIRECTORY: ${{ github.workspace }} - run: | - php "$STANDARDS_ROOT/bin/code-standards" normalize-composer "--directory=$STANDARDS_DIRECTORY" - - run: composer check - - name: Qualify ready PHAR distribution and native runtime + - name: Build once with the canonical PHP runtime env: COMPOSER_HOME: ${{ runner.temp }}/standards-phar-composer-home COMPOSER_CACHE_DIR: ${{ runner.temp }}/standards-composer-cache @@ -47,7 +80,6 @@ jobs: box compile --no-parallel --sort-compiled-files --config="$RUNNER_TEMP/standards-runtime/box.json" install -m 755 "$RUNNER_TEMP/standards-runtime/dist/code-standards" "$RUNNER_TEMP/code-standards" box verify "$RUNNER_TEMP/code-standards" - STANDARDS_PHAR="$RUNNER_TEMP/code-standards" vendor/bin/phpunit tests/Distribution/ArchiveTest.php --filter testCompiledDistributionRunsInDisposableConsumers - name: Compare the committed executable before execution id: parity shell: bash @@ -61,10 +93,75 @@ jobs: 1) echo 'stale=true' >> "$GITHUB_OUTPUT" ;; *) exit "$status" ;; esac - - name: Qualify the committed Composer distribution - if: steps.parity.outputs.stale == 'false' + - id: candidate + uses: actions/upload-artifact@v7 + with: + name: code-standards-build-${{ github.event.pull_request.head.sha || github.sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/code-standards + compression-level: 0 + if-no-files-found: error + runtime: + needs: build + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + php: ['8.3', '8.4', '8.5'] + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, posix + coverage: none + tools: composer:v2 + - run: composer install --no-plugins --no-scripts --no-interaction --prefer-dist --no-progress + env: + COMPOSER_HOME: ${{ runner.temp }}/standards-composer-home + COMPOSER_CACHE_DIR: ${{ runner.temp }}/standards-composer-cache + - uses: actions/download-artifact@v8.0.2 + with: + artifact-ids: ${{ needs.build.outputs.artifact }} + merge-multiple: true + path: ${{ runner.temp }}/phar + - name: Qualify the same compiled bytes on every supported PHP + run: | + chmod 755 "$RUNNER_TEMP/phar/code-standards" + STANDARDS_PHAR="$RUNNER_TEMP/phar/code-standards" vendor/bin/phpunit tests/Distribution/ArchiveTest.php --filter testCompiledDistributionRunsInDisposableConsumers + tests: + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + php: ['8.3', '8.4', '8.5'] + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, posix + coverage: none + tools: composer:v2 + - run: composer install --no-plugins --no-scripts --no-interaction --prefer-dist --no-progress + env: + COMPOSER_HOME: ${{ runner.temp }}/standards-composer-home + COMPOSER_CACHE_DIR: ${{ runner.temp }}/standards-composer-cache + - run: composer validate --strict + - name: Check Composer normalization + env: + STANDARDS_ROOT: ${{ github.workspace }} + STANDARDS_DIRECTORY: ${{ github.workspace }} run: | - STANDARDS_PHAR="$GITHUB_WORKSPACE/dist/code-standards" vendor/bin/phpunit tests/Distribution/ArchiveTest.php --filter testCompiledDistributionRunsInDisposableConsumers + php "$STANDARDS_ROOT/bin/code-standards" normalize-composer "--directory=$STANDARDS_DIRECTORY" + - run: composer check - name: Provision isolated Twig evaluation dependencies run: composer install --working-dir=tests/Evaluation/Twig --no-dev --no-plugins --no-scripts --no-interaction --prefer-dist --no-progress env: @@ -77,16 +174,36 @@ jobs: TWIG_EVALUATION_AUTOLOAD: ${{ runner.temp }}/standards-twig-vendor/autoload.php TWIG_EVALUATION_TEMP: ${{ runner.temp }} - run: git diff --exit-code - - name: Retain the reviewed PHP 8.3 build - if: matrix.php == '8.3' + compiled: + needs: [build, tests, runtime] + if: always() && needs.build.result != 'skipped' + runs-on: ubuntu-latest + outputs: + artifact: ${{ needs.build.outputs.artifact }} + steps: + - name: Require successful source and artifact qualification + env: + BUILD: ${{ needs.build.result }} + TESTS: ${{ needs.tests.result }} + RUNTIME: ${{ needs.runtime.result }} + run: | + test "$BUILD" = success && test "$TESTS" = success && test "$RUNTIME" = success + - if: github.event_name == 'pull_request' && needs.build.outputs.stale == 'true' + uses: actions/download-artifact@v8.0.2 + with: + artifact-ids: ${{ needs.build.outputs.artifact }} + merge-multiple: true + path: ${{ runner.temp }}/phar + - name: Retain only a fully qualified update + if: github.event_name == 'pull_request' && needs.build.outputs.stale == 'true' uses: actions/upload-artifact@v7 with: - name: code-standards-${{ steps.parity.outputs.stale == 'true' && 'update-' || '' }}${{ github.event.pull_request.head.sha || github.sha }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/code-standards + name: code-standards-update-${{ github.event.pull_request.head.sha || github.sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/phar/code-standards compression-level: 0 if-no-files-found: error - - name: Require the compiled refresh to pass on its own commit - if: steps.parity.outputs.stale == 'true' + - name: Require the refresh to pass before merge + if: github.event_name == 'pull_request' && needs.build.outputs.stale == 'true' run: | - echo 'The committed executable is stale. The trusted refresh workflow may update this same-repository PR; CI must pass again on that commit.' >&2 + echo 'The executable needs the qualified update. CI must pass on the refreshed commit before merge.' >&2 exit 1 diff --git a/.github/workflows/repository-phar-refresh.yml b/.github/workflows/repository-phar-refresh.yml index 4022123..c295fb5 100644 --- a/.github/workflows/repository-phar-refresh.yml +++ b/.github/workflows/repository-phar-refresh.yml @@ -6,6 +6,7 @@ on: permissions: contents: read actions: read + pull-requests: read concurrency: group: phar-refresh-${{ github.event.workflow_run.head_branch }} cancel-in-progress: false @@ -14,13 +15,31 @@ jobs: if: >- github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'failure' && - github.event.workflow_run.head_repository.full_name == github.repository + github.event.workflow_run.head_repository.full_name == github.repository && + github.event.workflow_run.head_branch != 'main' runs-on: ubuntu-latest timeout-minutes: 5 environment: release-channels steps: + - name: Locate the still-open source pull request + id: pull-request + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + SOURCE_SHA: ${{ github.event.workflow_run.head_sha }} + SOURCE_BRANCH: ${{ github.event.workflow_run.head_branch }} + run: | + branch=$(gh api "repos/$GH_REPO/commits/$SOURCE_SHA/pulls" | jq -r '[.[] | select(.state == "open" and .base.ref == "main" and .head.sha == env.SOURCE_SHA and .head.ref == env.SOURCE_BRANCH and .head.repo.full_name == env.GH_REPO)] | if length == 1 then .[0].head.ref else empty end') + if test -n "$branch"; then + git check-ref-format "refs/heads/$branch" + case "$branch" in main|changelog/version*) exit 0 ;; esac + branch_path=$(printf '%s' "$branch" | jq -sRr @uri) + test "$(gh api "repos/$GH_REPO/branches/$branch_path" --jq .protected)" = false + echo "branch=$branch" >> "$GITHUB_OUTPUT" + fi - name: Download the qualified update, if one was produced id: artifact + if: steps.pull-request.outputs.branch != '' continue-on-error: true uses: actions/download-artifact@v8.0.2 with: @@ -40,10 +59,19 @@ jobs: - if: steps.artifact.outcome == 'success' uses: actions/checkout@v7 with: - ref: ${{ github.event.workflow_run.head_sha }} + ref: ${{ steps.pull-request.outputs.branch }} token: ${{ steps.writer.outputs.token }} - if: steps.artifact.outcome == 'success' + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + SOURCE_SHA: ${{ github.event.workflow_run.head_sha }} + SOURCE_BRANCH: ${{ steps.pull-request.outputs.branch }} run: | + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + gh api "repos/$GH_REPO/commits/$SOURCE_SHA/pulls" | jq -e '[.[] | select(.state == "open" and .base.ref == "main" and .head.sha == env.SOURCE_SHA and .head.ref == env.SOURCE_BRANCH and .head.repo.full_name == env.GH_REPO)] | length == 1' + branch_path=$(printf '%s' "$SOURCE_BRANCH" | jq -sRr @uri) + test "$(gh api "repos/$GH_REPO/branches/$branch_path" --jq .protected)" = false test "$(git log -1 --format=%s)" != 'build: refresh compiled executable' test -f dist/code-standards && test ! -L dist && test ! -L dist/code-standards test -f "$RUNNER_TEMP/phar-update/code-standards" && test ! -L "$RUNNER_TEMP/phar-update/code-standards" @@ -51,7 +79,7 @@ jobs: - if: steps.artifact.outcome == 'success' uses: stefanzweifel/git-auto-commit-action@v7.2.1 with: - branch: ${{ github.event.workflow_run.head_branch }} + branch: ${{ steps.pull-request.outputs.branch }} file_pattern: dist/code-standards commit_message: 'build: refresh compiled executable' skip_checkout: true diff --git a/dist/code-standards b/dist/code-standards index 783a09e..c08760f 100755 Binary files a/dist/code-standards and b/dist/code-standards differ diff --git a/docs/automation.rst b/docs/automation.rst index 8671cd1..9a39c35 100644 --- a/docs/automation.rst +++ b/docs/automation.rst @@ -253,6 +253,14 @@ separate; changing a secret identifier does not repair or retry that transaction Version preparation recovery ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The caller retains automatic fragment pull-request references with +``resolve-pull-requests: true``. Changelog v0.6.0, available through the verified +``v0`` channel, supplies filtered acquisition of original squash-merged PR heads. +This retains references through the repository's large compiled-artifact history +without raising the bounded Git-pack limit or disabling discovery. Historical +tags remain the release source. Signed Bot ownership and managed-file verification +remain in force. + The original ``changelog/version`` branch of PR98 ends at the human merge ``48119d8d4bf3b77d488eba12b1f0515453b3f371``. Its content is the exact automatic merge of the signed Bot head and the then-current main: the remaining managed @@ -260,14 +268,14 @@ patch is byte-identical to the Bot patch, and the human delta is byte-identical to the integrated main delta. This preserves the human work but does not grant the human commit signed Bot ownership. No trailers are forged or waived. -The caller reserves ``changelog/version-recovery-98`` for fresh automation. After -this reviewed caller and a compatible corrected runtime are integrated, the next -trusted main event plans from the fresh main and creates a new signed Bot commit -and version PR on that exclusive branch. The old branch, commit, PR body and +The recovery used ``changelog/version-recovery-98``. The compiled-artifact policy +now reserves ``changelog/version-phar``: its generated-file allowlist changes the +native ownership fingerprint, so it starts an exclusive transaction instead of +adopting the historical recovery head. The old branches, commits, PR bodies and review history remain available. Do not reset, force-update or delete PR98's -branch. If either the fresh main or the reserved recovery branch changes during -preparation, fail closed and re-inspect before proceeding. Close the superseded -PR only after separate authorization and verification of the replacement. +branch. If either main or the managed version branch advances during preparation, +native preflight refuses the stale transaction. See :doc:`phar-distribution` for +the qualified artifact and immutable base binding. A version PR on the recovery branch still requires successful current-head checks, ownership proof and review before an approved merge/publication. This diff --git a/docs/phar-distribution.rst b/docs/phar-distribution.rst index 16c2105..ed9faf4 100644 --- a/docs/phar-distribution.rst +++ b/docs/phar-distribution.rst @@ -13,6 +13,39 @@ CI installs the official Box 4.7.1 PHAR through ``setup-php``. Box is not a Composer dependency of this project or its consumers. Developers do not need to install it or commit a rebuilt executable manually. +Quality compiles once with PHP 8.3 when a PR changes runtime or build inputs, +including the Composer manifests/lock, source, configuration, resources, stub, +compiled executable or distribution tests. Unknown paths also request a build. +Documentation, ordinary tests, changelog fragments and unrelated workflow-only +changes keep the existing executable. An unavailable comparison base requests +a build. Dependabot updates therefore rebuild when they change the locked +runtime; unchanged compiled bytes do not create an autocommit. +PR input selection compares against the merge base, so unrelated changes on +main do not turn an older documentation branch into a runtime change. + +The same built artifact is tested on PHP 8.3, 8.4 and 8.5. There are no three +independent compiler runs. Source checks continue on all three PHP versions. +Artifact consumers use the successful producer's artifact ID; retrying only +failed jobs still downloads that build instead of a nonexistent newer attempt. + +Main always qualifies its final merged tree before version preparation. Its +successful Quality call exports the qualified artifact ID. A separate job checks +out that exact source SHA, stages the artifact as data and calls Changelog's +existing Version Action with the same immutable ``base-ref``. The native writer +includes the selected executable, history and fragment removals in one signed +commit and version PR. An advanced main is refused; a different unqualified +base cannot silently replace the validated commit. No compiler or project PHP +runs with the writer token. The artifact is not rebuilt in the writer. +Version writers share native concurrency without cancelling in-flight writes. +A qualification already superseded by another main is skipped before staging; +native preflight still refuses a later advance during the transaction. + +Preparation, exact-head feedback and publication share +``generated-files: '["dist/code-standards"]'``. This native policy binds the +artifact digest and executable mode to the owned version transaction. The new +exclusive ``changelog/version-phar`` branch starts this policy without adopting +the older recovery branch under a different settings fingerprint. + ``scripts/phar/prepare.php`` has one purpose: prepare a disposable Composer runtime from the existing lock. Tool libraries live in ``require-dev`` alongside contributor tools, so their runtime roots must be selected explicitly from @@ -67,7 +100,7 @@ omits development mappings/packages. See :doc:`api/configuration`. Validation and automatic refresh -------------------------------- -Quality runs on PHP 8.3, 8.4 and 8.5. Box validates its configuration and checks +Source checks and artifact qualification run on PHP 8.3, 8.4 and 8.5. Box validates its configuration and checks the generated PHAR signature. PHPUnit exercises disposable Composer local, global and source installs, exact resource preservation, native check/fix, Rector and magic-number commands, consumer rule loading, CWD and cache cleanup. @@ -80,20 +113,37 @@ authorize execution. Comparison read errors fail; differing bytes require a refresh. Fixed timestamps and sorted entries make repeat builds reproducible in the qualified CI environment, not every arbitrary toolchain. -The PHP 8.3 job uploads its qualified build. A separate workflow accepts updates only -for same-repository PRs, downloads that run's artifact and invokes -``stefanzweifel/git-auto-commit-action`` for ``dist/code-standards`` only. -It does not execute project PHP or the downloaded PHAR. The existing repository -App supplies contents-write access so its commit triggers normal checks again. -The action pushes without force and does not pull or rebase concurrent changes. -An automatic refresh cannot repeatedly refresh its own commit. Forks retain -read-only checks. Missing update artifacts cause no commit. - -The existing ``release-channels`` environment rejects PR merge refs. The refresh -therefore uses GitHub's ``workflow_run`` event from the trusted default branch, -preserving that protection. Its definition must first reach the default branch -before the first live autocommit can be qualified. The initial committed PHAR -comes from the already-qualified PHP 8.3 CI artifact. +Only after every source check and runtime qualification succeeds does CI retain +an update artifact for a stale PR. Its compiled check fails until the refresh +commit passes its own checks. The trusted ``workflow_run`` callback +copies those bytes with the marketplace autocommit Action; it executes neither +the PHAR nor checkout PHP with its writer token. It checks that the same-repository +PR remains open at the source head before checkout and immediately before the +commit. Closed, deleted or advanced branches are not deliberately recreated or +overwritten; a normal push rejects a concurrent non-fast-forward advance. This +is not a compare-and-swap guarantee against a concurrent branch rewind. + +The existing App token triggers checks on the refresh commit. This route selects +unprotected source PR branches targeting main, and excludes main, forks and +native version branches. Only the native version writer changes its owned +transaction. A fork contributor can copy the +qualified artifact into their branch. Installing a development branch gives the +current executable after that branch's refresh and checks finish; an arbitrary +older commit or unvalidated branch cannot contain a later build automatically. +If a merge produces stale committed bytes, main's qualified candidate goes into +the atomic version PR instead of requiring a separate binary repair PR. Until +that PR is merged, the main branch still contains its previous executable. + +Changelog publication verifies the owned transaction and exact approved/merged +trees. The version job explicitly invokes native feedback for the returned PR +number and head SHA, independently of automatic event delivery. Merge only +reviewed version PRs whose current-head checks pass. PRs created with +``GITHUB_TOKEN`` can generate +``opened``, ``synchronize`` and ``reopened`` runs requiring approval; do not +assume those runs execute automatically. Native feedback validates ownership +and generated files; it does not replace code review or the project's Quality +checks. Main's explicit Quality dependency qualifies the immutable source base +independently of that approval-dependent delivery. Publication ----------- diff --git a/tests/Automation/WorkflowContextTest.php b/tests/Automation/WorkflowContextTest.php index b388916..5d7a79b 100644 --- a/tests/Automation/WorkflowContextTest.php +++ b/tests/Automation/WorkflowContextTest.php @@ -90,6 +90,43 @@ public function testReleaseSelectionPreventsOlderMajorAndGlobalPromotions(): voi } } + /** An update may be handed to the writer only after all source and runtime jobs succeeded. */ + public function testCompiledUpdateRejectsFailedSkippedOrCancelledQualification(): void + { + $script = $this->guard('repository-ci.yml', 'Require successful source and artifact qualification'); + $valid = ['BUILD' => 'success', 'TESTS' => 'success', 'RUNTIME' => 'success']; + self::assertSame(0, $this->guardResult($script, $valid)['status']); + foreach (array_keys($valid) as $job) { + foreach (['failure', 'skipped', 'cancelled', ''] as $result) { + self::assertNotSame(0, $this->guardResult($script, [...$valid, $job => $result])['status'], $job . ': ' . $result); + } + } + } + + /** Superseded qualifications skip preparation, while malformed or failed API reads remain errors. */ + public function testVersionPreparationSkipsOnlyAConfirmedNewerMain(): void + { + $script = <<<'BASH' +gh() { + test "$MOCK_FAILURE" = 0 || return "$MOCK_FAILURE" + printf '%s\n' "$MOCK_MAIN" +} +BASH; + $script .= "\n" . $this->guard('repository-changelog.yml', 'Skip a qualification superseded by a newer main'); + $qualified = str_repeat('a', 40); + foreach ([[$qualified, '0', 0, "current=true\n"], [str_repeat('b', 40), '0', 0, "current=false\n"], ['null', '0', 1, ''], [$qualified, '23', 23, '']] as [$current, $failure, $status, $output]) { + $result = $this->guardResult($script, [ + 'MOCK_MAIN' => $current, + 'MOCK_FAILURE' => $failure, + 'QUALIFIED_BASE' => $qualified, + 'GH_REPO' => 'fixture/repo', + 'GITHUB_STEP_SUMMARY' => '/dev/null', + ]); + self::assertSame($status, $result['status']); + self::assertSame($output, $result['output']); + } + } + /** Rejects malformed or ambiguous native identity protocols before emitting any checkout output. */ public function testIdentityProtocolFailsClosedWithoutOutput(): void { diff --git a/tests/Automation/WorkflowTest.php b/tests/Automation/WorkflowTest.php index b099729..5c765f4 100644 --- a/tests/Automation/WorkflowTest.php +++ b/tests/Automation/WorkflowTest.php @@ -29,10 +29,14 @@ public function testConsumerCallerDeclaresOnlyPullRequestsWithoutRemovingQuality self::assertStringContainsString(" magic-numbers: true\n magic-numbers-policy: report", $consumer); $quality = file_get_contents($directory . '/repository-ci.yml'); - self::assertMatchesRegularExpression('~^on:\n pull_request:\n push:\n branches: \[main\]\n workflow_dispatch:\npermissions:~m', $quality); + self::assertMatchesRegularExpression('~^on:\n pull_request:\n workflow_dispatch:\n workflow_call:\n~m', $quality); + self::assertStringContainsString('value: ${{ jobs.compiled.outputs.artifact }}', $quality); self::assertStringContainsString(" tests:\n runs-on: ubuntu-latest", $quality); self::assertStringContainsString("php: ['8.3', '8.4', '8.5']", $quality); self::assertStringContainsString('run: composer check', $quality); + self::assertSame(1, substr_count($quality, 'box compile')); + self::assertStringContainsString('needs: build', $quality); + self::assertStringContainsString('needs: [build, tests, runtime]', $quality); } /** Keeps approved external Actions on stable version labels without duplicating their current versions. */ @@ -48,6 +52,8 @@ public function testExternalActionsUseAllowedProvidersAndStableVersionLabels(): 'stefanzweifel/git-auto-commit-action', 'shivammathur/setup-php', 'php-fast-forward/changelog/.github/workflows/changelog.yml', + 'php-fast-forward/changelog/.github/workflows/changelog-pr-status.yml', + 'php-fast-forward/changelog/.github/actions/version', 'php-fast-forward/code-standards/.github/workflows/code-standards.yml', ]; $files = [ @@ -70,17 +76,18 @@ public function testCommittedPharComparisonPrecedesRuntimeQualification(): void { $workflow = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-ci.yml'); $comparison = strpos($workflow, 'cmp "$RUNNER_TEMP/code-standards" dist/code-standards'); - $execution = strpos($workflow, 'STANDARDS_PHAR="$GITHUB_WORKSPACE/dist/code-standards"'); + $execution = strpos($workflow, 'STANDARDS_PHAR="$RUNNER_TEMP/phar/code-standards"'); self::assertNotFalse($comparison); self::assertNotFalse($execution); self::assertLessThan($execution, $comparison); + self::assertStringNotContainsString('STANDARDS_PHAR="$GITHUB_WORKSPACE/dist/code-standards"', $workflow); } /** Runs the actual parity step against owned fixtures: differences authorize refresh, I/O errors do not. */ public function testBinaryComparisonNeverExecutesCandidateBytesOrMasksReadErrors(): void { $workflow = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-ci.yml'); - self::assertSame(1, preg_match('~id: parity\n shell: bash\n run: \|\n(.*?) - name:~s', $workflow, $matches)); + self::assertSame(1, preg_match('~id: parity\n shell: bash\n run: \|\n(.*?)(?= - )~s', $workflow, $matches)); $script = preg_replace('/^ /m', '', $matches[1]); $directory = sys_get_temp_dir() . '/standards-cmp-' . bin2hex(random_bytes(8)); mkdir($directory . '/dist', 0700, true); @@ -114,15 +121,158 @@ public function testCompiledRefreshNeverExecutesPullRequestCodeWithTheWriter(): self::assertStringNotContainsString('secrets.', $workflow); $refresh = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-phar-refresh.yml'); self::assertStringContainsString('github.event.workflow_run.head_repository.full_name == github.repository', $refresh); - self::assertStringContainsString('ref: ${{ github.event.workflow_run.head_sha }}', $refresh); + self::assertStringContainsString('ref: ${{ steps.pull-request.outputs.branch }}', $refresh); + self::assertStringContainsString('select(.state == "open"', $refresh); + self::assertStringContainsString('test "$(git rev-parse HEAD)" = "$SOURCE_SHA"', $refresh); self::assertStringContainsString('run-id: ${{ github.event.workflow_run.id }}', $refresh); self::assertStringContainsString('file_pattern: dist/code-standards', $refresh); - self::assertStringContainsString('stefanzweifel/git-auto-commit-action@v7.2.1', $refresh); + self::assertStringContainsString('uses: stefanzweifel/git-auto-commit-action@', $refresh); self::assertStringNotContainsString('php ', $refresh); self::assertStringNotContainsString('permission-workflows:', $refresh); self::assertStringNotContainsString('--force', $refresh); } + /** Keeps preparation behind the source/compiled check instead of publishing a stale base. */ + public function testVersionPreparationRequiresSuccessfulBaseQuality(): void + { + $workflow = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-changelog.yml'); + self::assertStringContainsString('uses: ./.github/workflows/repository-ci.yml', $workflow); + self::assertStringContainsString(" version:\n needs: quality\n", $workflow); + self::assertStringContainsString('base-ref: ${{ github.sha }}', $workflow); + self::assertStringContainsString('artifact-ids: ${{ needs.quality.outputs.artifact }}', $workflow); + self::assertStringContainsString('uses: php-fast-forward/changelog/.github/actions/version@v0', $workflow); + self::assertSame(3, substr_count($workflow, "generated-files: '[\"dist/code-standards\"]'")); + self::assertStringContainsString('head-sha: ${{ needs.version.outputs.head-sha }}', $workflow); + self::assertStringContainsString('base-sha: ${{ github.sha }}', $workflow); + self::assertStringContainsString('uses: php-fast-forward/changelog/.github/workflows/changelog-pr-status.yml@v0', $workflow); + self::assertStringContainsString('prepare-release: false', $workflow); + self::assertStringContainsString('group: changelog-${{ github.repository }}-main', $workflow); + self::assertSame(5, substr_count($workflow, "if: steps.base.outputs.current == 'true'")); + self::assertStringContainsString('resolve-pull-requests: true', $workflow); + self::assertStringNotContainsString('box compile', $workflow); + } + + /** A failed-job rerun reuses the successful producer's artifact instead of inventing another attempt. */ + public function testArtifactConsumersUseTheSuccessfulBuildIdentity(): void + { + $workflow = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-ci.yml'); + self::assertStringContainsString('artifact: ${{ steps.candidate.outputs.artifact-id }}', $workflow); + self::assertSame(2, substr_count($workflow, 'artifact-ids: ${{ needs.build.outputs.artifact }}')); + self::assertSame(1, substr_count($workflow, 'name: code-standards-build-')); + } + + /** Exercises the actual classifier with Git changes, including dependency and binary updates. */ + public function testRuntimeInputsRebuildButDocumentationAndOrdinaryTestsDoNot(): void + { + $workflow = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-ci.yml'); + self::assertSame(1, preg_match('~ - id: inputs\n.*? run: \|\n(.*?) build:\n~s', $workflow, $matches)); + $script = preg_replace('/^ /m', '', $matches[1]); + $directory = sys_get_temp_dir() . '/standards-inputs-' . bin2hex(random_bytes(8)); + mkdir($directory, 0700); + $environment = [ + 'GIT_DIR' => false, + 'GIT_WORK_TREE' => false, + 'GIT_INDEX_FILE' => false, + 'GIT_CONFIG_NOSYSTEM' => '1', + 'GIT_CONFIG_GLOBAL' => '/dev/null', + 'GITHUB_OUTPUT' => $directory . '/output', + 'RUNNER_TEMP' => $directory, + ]; + $git = static function (array $arguments) use ($directory, $environment): string { + $process = new Process(['git', '-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false', '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', ...$arguments], $directory, $environment); + $process->mustRun(); + + return trim($process->getOutput()); + }; + try { + $git(['init', '--quiet']); + $git(['commit', '--quiet', '--allow-empty', '-m', 'base']); + foreach (['docs/example.rst' => false, 'tests/UnitTest.php' => false, '.changelog/example.md' => false, 'composer.lock' => true, 'resources/template.txt' => true, 'dist/code-standards' => true, 'tests/Distribution/ArchiveTest.php' => true, 'unknown-input' => true] as $path => $expected) { + $base = $git(['rev-parse', 'HEAD']); + (new Filesystem())->dumpFile($directory . '/' . $path, 'fixture'); + $git(['add', '--', $path]); + $git(['commit', '--quiet', '-m', 'change']); + file_put_contents($directory . '/output', ''); + $process = new Process(['bash', '-e', '-o', 'pipefail', '-c', $script], $directory, $environment + ['BASE' => $base, 'HEAD' => $git(['rev-parse', 'HEAD']), 'EVENT' => 'pull_request']); + $process->mustRun(); + self::assertSame('build=' . ($expected ? 'true' : 'false') . "\n", file_get_contents($directory . '/output'), $path); + } + $ancestor = $git(['rev-parse', 'HEAD']); + $git(['checkout', '--quiet', '-b', 'main-advanced']); + (new Filesystem())->dumpFile($directory . '/src/main-only.php', 'main change'); + $git(['add', 'src/main-only.php']); + $git(['commit', '--quiet', '-m', 'main runtime update']); + $base = $git(['rev-parse', 'HEAD']); + $git(['checkout', '--quiet', '-b', 'docs-branch', $ancestor]); + file_put_contents($directory . '/docs/example.rst', 'documentation update'); + $git(['add', 'docs/example.rst']); + $git(['commit', '--quiet', '-m', 'documentation']); + foreach (['pull_request' => false, 'push' => true] as $event => $expected) { + file_put_contents($directory . '/output', ''); + $process = new Process(['bash', '-e', '-o', 'pipefail', '-c', $script], $directory, $environment + ['BASE' => $base, 'HEAD' => $git(['rev-parse', 'HEAD']), 'EVENT' => $event]); + $process->mustRun(); + self::assertSame('build=' . ($expected ? 'true' : 'false') . "\n", file_get_contents($directory . '/output'), $event); + } + $base = $git(['rev-parse', 'HEAD']); + $git(['mv', 'resources/template.txt', 'docs/retired.md']); + $git(['commit', '--quiet', '-m', 'retire bundled resource']); + file_put_contents($directory . '/output', ''); + $process = new Process(['bash', '-e', '-o', 'pipefail', '-c', $script], $directory, $environment + ['BASE' => $base, 'HEAD' => $git(['rev-parse', 'HEAD']), 'EVENT' => 'pull_request']); + $process->mustRun(); + self::assertSame("build=true\n", file_get_contents($directory . '/output'), 'Moving a resource out of the runtime must rebuild.'); + } finally { + (new Filesystem())->remove($directory); + } + } + + /** Executes the real selector without network; protected and owned version branches are never App targets. */ + public function testRefreshSelectsOnlyOneOpenPullRequestAtTheQualifiedHead(): void + { + $workflow = file_get_contents(dirname(__DIR__, 2) . '/.github/workflows/repository-phar-refresh.yml'); + self::assertSame(1, preg_match('~name: Locate the still-open source pull request\n.*? run: \|\n(.*?)(?= - )~s', $workflow, $matches)); + $script = <<<'BASH' +gh() { + case "$2" in + repos/fixture/standards/commits/*/pulls) printf '%s\n' "$MOCK_PRS" ;; + repos/fixture/standards/branches/*) printf '%s\n' "$MOCK_PROTECTED" ;; + *) return 71 ;; + esac +} +BASH; + $script .= "\n" . preg_replace('/^ /m', '', $matches[1]); + $pullRequest = ['state' => 'open', 'base' => ['ref' => 'main'], 'head' => ['sha' => str_repeat('a', 40), 'ref' => 'dependabot/composer/runtime', 'repo' => ['full_name' => 'fixture/standards']]]; + $closed = $pullRequest; + $closed['state'] = 'closed'; + $advanced = $pullRequest; + $advanced['head']['sha'] = str_repeat('b', 40); + $fork = $pullRequest; + $fork['head']['repo']['full_name'] = 'fork/standards'; + $otherBase = $pullRequest; + $otherBase['base']['ref'] = 'other-line'; + $main = $pullRequest; + $main['head']['ref'] = 'main'; + $managed = $pullRequest; + $managed['head']['ref'] = 'changelog/version-phar'; + $output = tempnam(sys_get_temp_dir(), 'standards-refresh-'); + try { + foreach (['valid' => [$pullRequest], 'closed' => [$closed], 'advanced' => [$advanced], 'fork' => [$fork], 'other-base' => [$otherBase], 'main' => [$main], 'managed' => [$managed], 'protected' => [$pullRequest], 'missing' => [], 'ambiguous' => [$pullRequest, $pullRequest]] as $case => $fixture) { + file_put_contents($output, ''); + $process = new Process(['bash', '-e', '-o', 'pipefail', '-c', $script], env: [ + 'SOURCE_SHA' => $pullRequest['head']['sha'], + 'SOURCE_BRANCH' => $fixture[0]['head']['ref'] ?? $pullRequest['head']['ref'], + 'GH_REPO' => $pullRequest['head']['repo']['full_name'], + 'GITHUB_OUTPUT' => $output, + 'MOCK_PRS' => json_encode($fixture, JSON_THROW_ON_ERROR), + 'MOCK_PROTECTED' => 'protected' === $case ? 'true' : 'false', + ]); + self::assertSame('protected' === $case ? 1 : 0, $process->run(), $process->getErrorOutput()); + self::assertSame('valid' === $case ? 'branch=' . $pullRequest['head']['ref'] . "\n" : '', file_get_contents($output), $case); + } + } finally { + unlink($output); + } + } + /** Prevents silent GITHUB_TOKEN publication by keeping the App identity explicit and publication-only. */ public function testChangelogCallerSelectsTheCompatiblePublicationOnlyApp(): void { @@ -130,7 +280,7 @@ public function testChangelogCallerSelectsTheCompatiblePublicationOnlyApp(): voi self::assertStringContainsString('changelog.yml@v0', $workflow); self::assertStringContainsString("publish-app-client-id: 'Iv23liHqRng02H747IYa'", $workflow); self::assertStringContainsString('publish-environment: release-channels', $workflow); - self::assertStringContainsString('managed-branch: changelog/version-recovery-98', $workflow); + self::assertStringContainsString('managed-branch: changelog/version-phar', $workflow); self::assertStringContainsString('publish-app-private-key: ${{ secrets.RELEASE_CHANNEL_APP_PRIVATE_KEY }}', $workflow); self::assertDoesNotMatchRegularExpression('/^\s+app-client-id:/m', $workflow); self::assertDoesNotMatchRegularExpression('/^\s+app-private-key:/m', $workflow);