# BDD drift check (playwright adapter)
# ---------------------------------------------------------------------------
# Runs @pound79/specproof-traceability on every PR and posts/updates a sticky
# comment listing any drifted spec<->impl<->feature links, then fails the job
# so drift can't merge silently. This is the CI half of specproof's "generation
# = AI, detection = deterministic CLI" split (see docs/adr/0004): without it,
# `--strict` only protects repos that remember to run it by hand.
#
# No `paths:` filter on purpose. specproof-check hashes only the refs
# recorded in traceability.yaml and finishes in a few seconds regardless of
# repo size, so scoping the trigger by path risks the exact failure mode this
# check exists to catch — a link edited/added outside the filtered globs
# silently skipping review.
# ---------------------------------------------------------------------------
name: BDD drift check

# `pull_request` (not `pull_request_target`) on purpose: this job checks out
# and processes untrusted PR code, and pull_request_target would hand that
# code a write-capable token. The trade-off — fork PRs get a read-only token
# and skip the comment job — is handled below via annotations + job failure.
on:
  pull_request:

# Least privilege: the drift-check job checks out the PR and runs code fetched
# from npm, so it gets a read-only token. Only the comment job, which checks out
# nothing and runs no PR or registry code, may write the PR comment.
# This assumes GitHub-hosted runners. On a self-hosted runner, the npx cache
# (~/.npm/_npx), ~/.npmrc and proxy settings carry over between jobs and
# repositories, so isolate the runner per job before using this workflow.
permissions:
  contents: read

# One run per PR: a newer push cancels the older run, so a slower run for an
# older commit cannot finish last and overwrite the newer report.
concurrency:
  group: specproof-drift-check-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  drift-check:
    name: specproof-check --strict
    runs-on: ubuntu-latest
    timeout-minutes: 10
    # The id of the report this attempt uploaded, empty when none was uploaded.
    outputs:
      report-artifact-id: ${{ steps.upload.outputs.artifact-id }}
    steps:
      # persist-credentials: false keeps the token out of .git/config, where the
      # code run below (from the PR and from npm) could read it.
      - name: Checkout
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false

      - name: Use Node.js
        uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with:
          node-version: 24

      # specproof-check runs with defaults when there is no config file (for
      # using the engine without one), and then does not scan .feature files
      # that no link registers. specproof init always writes the config, so a
      # PR that deletes it must not turn --strict into a check of registered
      # features only. Protect the config with CODEOWNERS as well (see
      # docs/security-model.md in the specproof repository).
      - name: Require the specproof config
        run: |
          # -L also accepts a broken symlink, so specproof-check reports it as such.
          missing() { [ ! -e "$1" ] && [ ! -L "$1" ]; }
          if missing "$GITHUB_WORKSPACE/specproof.config.yaml" && missing "$GITHUB_WORKSPACE/specproof.config.yml"; then
            echo "::error::specproof.config.yaml (or .yml) is missing at the repository root; specproof-check would skip unregistered .feature files without it."
            exit 1
          fi

      # --strict escalates structural warnings (unreviewed draft markers,
      # disallowed @fixme/@skip/@fail tags, @out-of-scope without a reason comment,
      # empty links) to failures, not just hash drift. --json is captured to
      # drift-report.json for the comment job; --github-annotations writes
      # "::warning file=...::" lines to this step's own log (stderr), independent
      # of the JSON on stdout, so GitHub also surfaces each drifted ref inline on
      # the PR's "Files changed" tab even if the comment job is skipped.
      #
      # npx runs outside the checkout ($RUNNER_TEMP) so npm reads no .npmrc that
      # the PR could add (registry, proxy, scoped registries), with the registry
      # pinned and install scripts off. --root points the check at the checkout.
      #
      # continue-on-error + `id: check` defer the pass/fail decision to the
      # last step, so the report is still uploaded when the check fails.
      - name: Run specproof-check
        id: check
        continue-on-error: true
        working-directory: ${{ runner.temp }}
        env:
          npm_config_ignore_scripts: "true"
        run: |
          npx -y --registry=https://registry.npmjs.org -p @pound79/specproof-traceability@0.6.0 specproof-check \
            --root "$GITHUB_WORKSPACE" --strict --json --github-annotations > "$RUNNER_TEMP/drift-report.json"

      - name: Upload drift report
        id: upload
        if: ${{ !cancelled() }}
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: drift-report
          path: ${{ runner.temp }}/drift-report.json
          if-no-files-found: warn
          retention-days: 1
          overwrite: true # a re-run of the job uploads the report again

      - name: Fail if drift or strict warnings were found
        if: steps.check.outcome == 'failure'
        run: exit 1

  # Fork PRs run with a read-only GITHUB_TOKEN regardless of the `permissions:`
  # block, so posting a comment would fail with a 403. Skip the comment there;
  # the annotations and the drift-check job failure still surface the result.
  # !cancelled(): the comment is still posted/updated when drift-check fails,
  # but a superseded run (concurrency) is not kept alive the way always() would.
  comment:
    name: drift-check comment
    needs: drift-check
    if: ${{ !cancelled() && github.event.pull_request.head.repo.full_name == github.repository }}
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      pull-requests: write # to upsert the drift-report comment
    steps:
      # Download by the id this run's drift-check attempt uploaded, not by name:
      # after a re-run that produced no report, a name lookup would pick up the
      # previous attempt's artifact and repost a stale result. No id (setup
      # failed before the report) leaves no file, which the script reports.
      - name: Download drift report
        if: ${{ needs.drift-check.outputs.report-artifact-id != '' }}
        continue-on-error: true
        uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with:
          artifact-ids: ${{ needs.drift-check.outputs.report-artifact-id }}

      - name: Comment on PR
        uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0
        with:
          script: |
            const fs = require('fs');
            const marker = '<!-- specproof-drift-check -->';

            // npx 自体が失敗すると report は空か壊れている。そのときも下で既存のコメントを書き換え、
            // 前のコミットの結果（clean など）を残さない。
            let report;
            try {
              const parsed = JSON.parse(fs.readFileSync('drift-report.json', 'utf8'));
              if (typeof parsed !== 'object' || parsed === null) throw new Error('not a JSON object');
              report = parsed;
            } catch (error) {
              core.warning(`specproof-drift-check: could not read drift-report.json: ${error.message}`);
            }

            const { owner, repo } = context.repo;
            const issue_number = context.payload.pull_request.number;

            const headSha = context.payload.pull_request.head.sha;
            // pull_request checkout verifies the merge commit, not the PR head alone.
            const checked = `Checked commit \`${context.sha.slice(0, 7)}\` (PR head \`${headSha.slice(0, 7)}\`).`;

            const comments = await github.paginate(github.rest.issues.listComments, {
              owner,
              repo,
              issue_number,
            });
            const existing = comments
              .filter((c) => c.user?.type === 'Bot' &&
                c.user.login === 'github-actions[bot]' && c.body?.startsWith(marker))
              .sort((a, b) => b.id - a.id)[0];

            // 投稿対象の探索後、各書き込みの直前に head を照合する。
            // コメントのページ取得中に head が進んだ実行も投稿しない。
            const isCurrentHead = async () => {
              const { data: currentPr } = await github.rest.pulls.get({
                owner,
                repo,
                pull_number: issue_number,
              });
              if (currentPr.head.sha === headSha) return true;
              core.notice(
                `specproof-drift-check: skipped the comment for ${headSha.slice(0, 7)}; the PR head is now ${currentPr.head.sha.slice(0, 7)}`,
              );
              return false;
            };

            if (report === undefined) {
              if (!existing) return;
              if (!(await isCurrentHead())) return;
              await github.rest.issues.updateComment({
                owner,
                repo,
                comment_id: existing.id,
                body: `${marker}\n### BDD drift check: report unavailable\n\n${checked}\n\nThe drift report could not be read, so the previous result no longer applies. See the drift-check job log.`,
              });
              return;
            }

            // report の文字列は PR の内容（パス・見出し・link id）から作られ、report は PR の
            // コードを checkout したジョブから届く。全項目を未信頼として Markdown・HTML・メンションに
            // 解釈させない。
            // 改行・制御文字と、表示順を入れ替える bidi 制御文字・BOM を ? に潰し、中身のどの
            // バッククォートの並びより長いフェンスで囲んだコードスパンに入れる（CommonMark の
            // 規則で中身から閉じられない）。
            const code = (value) => {
              const text = String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\ufeff\p{Bidi_Control}]/gu, '?');
              const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
              const fence = '`'.repeat(longest + 1);
              return `${fence} ${text} ${fence}`;
            };

            const isClean = report.clean && report.warnings.length === 0;

            if (isClean) {
              // Nothing drifted and no prior comment to clear — stay silent
              // rather than adding a "clean" comment to every PR.
              if (!existing) return;
              if (!(await isCurrentHead())) return;
              await github.rest.issues.updateComment({
                owner,
                repo,
                comment_id: existing.id,
                body: `${marker}\n### BDD drift check: clean\n\n${checked}\n\nNo drift or warnings detected.`,
              });
              return;
            }

            const linkIds = [...new Set(report.entries.map((e) => e.linkId))];
            const driftSection = linkIds
              .map((linkId) => {
                const rows = report.entries
                  .filter((e) => e.linkId === linkId)
                  .map((e) => {
                    const location = e.heading ? `${code(e.path)} § ${code(e.heading)}` : code(e.path);
                    return `  - ${code(e.side)} ${location} — **${code(e.status)}**`;
                  })
                  .join('\n');
                return `- **${code(linkId)}**\n${rows}`;
              })
              .join('\n');

            // failsUnderStrict reflects each warning's kind (unregistered-impl
            // / unregistered-spec-heading and the feature lint kinds are advisory
            // unless the repo opts in via strictUnregisteredImpl /
            // strictUnregisteredSpecHeadings / strictFeatureLint;
            // possible-contradiction is always advisory — see docs/config-schema.md). Treat a missing field (older
            // specproof-check) as hard so unknown warning kinds never get
            // silently buried in the collapsed section.
            const hardWarnings = report.warnings.filter((w) => w.failsUnderStrict !== false);
            const advisoryWarnings = report.warnings.filter((w) => w.failsUnderStrict === false);

            const hardWarningSection =
              hardWarnings.length === 0
                ? ''
                : `\n\n**Warnings (fail under \`--strict\`):**\n${hardWarnings
                    .map((w) => `- ${code(w.message)}`)
                    .join('\n')}`;

            const advisoryWarningSection =
              advisoryWarnings.length === 0
                ? ''
                : `\n\n<details><summary>Advisory warnings (do not fail the check) — ${advisoryWarnings.length}</summary>\n\n${advisoryWarnings
                    .map((w) => `- ${code(w.message)}`)
                    .join('\n')}\n\n</details>`;

            const warningSection = hardWarningSection + advisoryWarningSection;

            const driftSummary =
              linkIds.length === 0
                ? hardWarnings.length > 0
                  ? '**No hash drift** — failing on `--strict` warning(s) only.'
                  : '**No hash drift** — advisory warning(s) only (does not fail the check).'
                : `**${Number(report.driftCount)} drifted reference(s) across ${Number(report.driftLinkCount)} link(s):**\n\n${driftSection}`;

            // Advisory-only runs exit 0 — the comment must not claim drift
            // was detected, and sync/update remediation would be misleading.
            const advisoryOnly = linkIds.length === 0 && hardWarnings.length === 0;
            const title = advisoryOnly
              ? 'BDD drift check: advisory warnings'
              : 'BDD drift check: drift detected';
            const remediation = advisoryOnly
              ? 'Advisory warnings are informational and do not fail the check. ' +
                'To enforce them, opt in via `strictUnregisteredImpl` / ' +
                '`strictUnregisteredSpecHeadings` in `specproof.config.yaml`.'
              : 'Run `/specproof-sync <link-id>` to bring the feature back in sync, then push again. ' +
                'If the change is already reflected, run `specproof-update` locally and commit the refreshed `traceability.yaml`.';

            // The checked commit goes before report-derived text, which an
            // unclosed HTML comment or Markdown in a path could otherwise hide.
            const body =
              `${marker}\n### ${title}\n\n${checked}\n\n${driftSummary}${warningSection}\n\n${remediation}`;

            if (!(await isCurrentHead())) return;
            if (existing) {
              await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
            } else {
              await github.rest.issues.createComment({ owner, repo, issue_number, body });
            }

