diff --git a/.github/workflows/calibration-advisory.yml b/.github/workflows/calibration-advisory.yml deleted file mode 100644 index 6f2b9ac64..000000000 --- a/.github/workflows/calibration-advisory.yml +++ /dev/null @@ -1,301 +0,0 @@ -# Calibration advisory checks — the logic/regex-change backtest (#8139, epic #8082) and the -# counterfactual prompt replay (#8222, sub-epic #8218, epic #8211 track C), merged into ONE workflow -# 2026-07-24: they shared identical scaffolding (dual base/head checkout, npm ci, engine build, D1 -# corpus export, fail-open posture, fork-notice pairing) and overlapping path filters -# (src/services/ai-review.ts triggered BOTH — two runners doing the same npm ci on every judge-prompt -# PR), so one job runs both halves for one setup cost and one runner slot. -# -# BACKTEST half: replays linked_issue_scope_mismatch's recorded raw-context history (#8129/#8130 + -# the #8139 model-response capture) through BOTH the PR's head checkout and its base checkout — -# actually executing the two versions of the detection code, which is why this lives in CI and not in -# ORB's live Worker (the Worker holds credentials and must never execute PR-supplied logic; a CI -# checkout running a PR's own code is the exact trust boundary validate-code/validate-tests already -# use for every PR). -# -# REPLAY half: replays the CANONICAL judge prompt from both checkouts (scripts/print-review-prompt.ts) -# against the recorded raw-context fixture corpus and posts the Pareto-floored comparison. It -# self-gates twice: on the COUNTERFACTUAL_REPLAY_BUDGET spend guard (#8222's requirement — unset, it -# posts a visible skip notice and spends nothing), and on the canonical prompt text actually differing -# between base and head (byte-identical ⇒ nothing to replay), so no extra path filter is needed for -# runs that only touched the backtest's watched paths. -# -# Advisory only (#8105): never a required check, never blocks merge, and every step after setup FAILS -# OPEN (notice + green) — the review engine auto-closes contributor PRs on ANY red check, so this -# workflow's own plumbing must never redden. Each half posts its OWN clearly-labeled PR comment, -# update-in-place keyed on its marker. -name: calibration-advisory - -on: - pull_request: - # Explicit list because the default (opened/synchronize/reopened) omits ready_for_review -- once the - # draft guard below skips draft PRs, marking a PR ready must itself trigger a real run (#6670). - types: [opened, synchronize, reopened, ready_for_review] - # The union of the two halves' watched surfaces. Backtest: exactly the paths whose changes can alter - # linked_issue_scope_mismatch-adjacent detection logic (#8139's Design section). Replay: the judge- - # prompt surface (REVIEW_PROMPT_VERSION + buildSystemPrompt/parseModelReview), which is - # src/services/ai-review.ts — already in the backtest's list, so the union IS the backtest's list. - paths: - - "src/rules/**" - - "src/review/content-lane/**" - - "src/settings/agent-actions.ts" - - "src/services/ai-review.ts" - - "src/services/linked-issue-satisfaction.ts" - -# Least privilege: the checks only read the repo; pull-requests: write is for their advisory comments. -permissions: - contents: read - pull-requests: write - -concurrency: - # pull_request-only workflow, so one ref-scoped group suffices (no push/github.sha split like ci.yml - # needs): a newer push cancels the superseded run — its comments would be overwritten anyway. - group: calibration-advisory-${{ github.ref }} - cancel-in-progress: true - -jobs: - advisory: - name: calibration advisory (backtest + replay) - # Skip draft PRs (#6670, anti-abuse). Fork PRs are excluded at the job level rather than per-step: - # GitHub withholds repo secrets from fork-originated pull_request runs, so the D1 corpus reads below - # are impossible there and the whole job (npm ci included) would be waste — the fork-notice job below - # is this workflow's half of ci.yml's paired fork==true/!=true convention. - if: ${{ github.event.pull_request.draft != true && github.event.pull_request.head.repo.fork != true }} - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - # The PR's base commit, checked out INSIDE the head workspace: the dynamically imported base modules - # resolve bare npm specifiers by walking up from their own directory into the head checkout's - # node_modules, so one `npm ci` serves both sides of every comparison (#8139). - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - path: .advisory-base - persist-credentials: false - - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 - with: - node-version-file: .nvmrc - cache: "npm" - - - name: Install deps - run: npm ci --ignore-scripts - - # Both halves' scripts import @loopover/engine, which resolves to its dist/ build output. - - name: Build engine package - run: npx turbo run build --filter=@loopover/engine - - # --------------------------------------------------------------------------------------------- - # Every step from here down FAILS OPEN (notice + green, never a red check): the review engine - # auto-closes a contributor PR on ANY failed check, required or not — so an advisory job that can - # go red on an infra problem (an under-scoped CLOUDFLARE_API_TOKEN, a D1 outage, a comment-post - # hiccup) would let OUR plumbing close an innocent contributor's PR. "Never blocks merge" (#8105) - # has to hold against this job's own failures, not just its verdicts. - # --------------------------------------------------------------------------------------------- - - # ============================ BACKTEST HALF (#8139) ============================ - # Read-only corpus export (#8084's CLI, reused as-is — no new D1 read code). The wrangler secrets - # are available here because the fork guard above already excluded fork-originated runs. - - name: Export backtest corpus from D1 - id: corpus - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - run: | - if npx tsx scripts/backtest-corpus-export.ts --rule-id linked_issue_scope_mismatch --output backtest-corpus.json --remote; then - echo "available=true" >> "$GITHUB_OUTPUT" - else - echo "available=false" >> "$GITHUB_OUTPUT" - echo "::notice::Corpus export from D1 failed (missing or under-scoped CLOUDFLARE_API_TOKEN — it needs D1 read/write on the loopover database). Logic backtest skipped; advisory only, never fails the PR." - fi - - - name: Run logic backtest - id: backtest - if: ${{ steps.corpus.outputs.available == 'true' }} - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - if npx tsx scripts/backtest-logic-check.ts \ - --rule-id linked_issue_scope_mismatch \ - --corpus backtest-corpus.json \ - --head-root . \ - --base-root .advisory-base \ - --output backtest-comment.md \ - --head-sha "$HEAD_SHA" \ - --base-sha "$BASE_SHA" \ - --persist --remote --db loopover \ - --repo "$GITHUB_REPOSITORY" \ - --pr "$PR_NUMBER"; then - echo "ready=true" >> "$GITHUB_OUTPUT" - else - echo "ready=false" >> "$GITHUB_OUTPUT" - echo "::notice::Logic backtest run failed — no comparison produced. Advisory only, never fails the PR." - fi - - # Update-in-place keyed on the comment marker so a re-run edits the existing comment instead of - # stacking a new one per push. - - name: Post or update the backtest PR comment - if: ${{ steps.backtest.outputs.ready == 'true' }} - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - post_comment() { - marker="" - # --paginate runs the --jq filter once per page, so pin to the first emitted id. - comment_id=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" --paginate \ - --jq "[.[] | select(.body | contains(\"${marker}\")) | .id] | first // empty" | head -n 1) - if [ -n "$comment_id" ]; then - gh api "repos/${GITHUB_REPOSITORY}/issues/comments/${comment_id}" -X PATCH -F body=@backtest-comment.md - else - gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" -F body=@backtest-comment.md - fi - } - if ! post_comment; then - echo "::notice::PR comment post failed — backtest result computed and persisted but not posted. Advisory only, never fails the PR." - fi - - # ============================ REPLAY HALF (#8222) ============================ - # SPEND GUARD (#8222's requirement): the replay costs real model inference, so it is gated on the - # deployment explicitly configuring a budget — the COUNTERFACTUAL_REPLAY_BUDGET repo variable - # (neuron units, see COUNTERFACTUAL_DEFAULT_NEURON_BUDGET) plus the provider endpoint/model. - # #8279: the default provider is Workers AI (the CLOUDFLARE_* secrets above double as its - # credentials — the token needs Workers AI run perms); an explicit COUNTERFACTUAL_OLLAMA_URL - # secret switches to a reachable ollama instead. - - name: Check replay budget configuration - id: budget - env: - REPLAY_BUDGET: ${{ vars.COUNTERFACTUAL_REPLAY_BUDGET }} - REPLAY_MODEL: ${{ vars.COUNTERFACTUAL_REPLAY_MODEL }} - REPLAY_OLLAMA_URL: ${{ secrets.COUNTERFACTUAL_OLLAMA_URL }} - run: | - if [ -n "$REPLAY_BUDGET" ] && [ -n "$REPLAY_MODEL" ]; then - echo "configured=true" >> "$GITHUB_OUTPUT" - if [ -n "$REPLAY_OLLAMA_URL" ]; then echo "provider=ollama" >> "$GITHUB_OUTPUT"; else echo "provider=workers-ai" >> "$GITHUB_OUTPUT"; fi - else - echo "configured=false" >> "$GITHUB_OUTPUT" - echo "::notice::Counterfactual replay skipped: no replay budget configured (set the COUNTERFACTUAL_REPLAY_BUDGET + COUNTERFACTUAL_REPLAY_MODEL repo variables; Workers AI runs on the existing CLOUDFLARE_* secrets, or set COUNTERFACTUAL_OLLAMA_URL to use a reachable ollama). Advisory only, never fails the PR." - fi - - # Cheap self-gate replacing the old workflow's ai-review.ts-only path filter: extract the canonical - # prompt from both checkouts and replay only when the text actually differs — a PR that matched this - # workflow's paths without touching the judge prompt costs two script invocations and stops here. - - name: Extract base/head canonical prompts - if: ${{ steps.budget.outputs.configured == 'true' }} - id: prompts - run: | - if npx tsx scripts/print-review-prompt.ts --root . > head-prompt.txt \ - && npx tsx scripts/print-review-prompt.ts --root .advisory-base > base-prompt.txt \ - && npx tsx scripts/print-review-prompt.ts --root . --version-only > head-version.txt \ - && npx tsx scripts/print-review-prompt.ts --root .advisory-base --version-only > base-version.txt; then - if cmp -s head-prompt.txt base-prompt.txt; then - echo "changed=false" >> "$GITHUB_OUTPUT" - echo "::notice::Canonical judge prompt text is byte-identical across base/head — nothing to replay." - else - echo "changed=true" >> "$GITHUB_OUTPUT" - fi - else - echo "changed=false" >> "$GITHUB_OUTPUT" - echo "::notice::Prompt extraction failed — replay skipped. Advisory only, never fails the PR." - fi - - - name: Export replay corpus from D1 - if: ${{ steps.budget.outputs.configured == 'true' && steps.prompts.outputs.changed == 'true' }} - id: replaycorpus - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - run: | - if npx tsx scripts/backtest-corpus-export.ts --rule-id ai_consensus_defect --output replay-corpus.json --remote; then - echo "available=true" >> "$GITHUB_OUTPUT" - else - echo "available=false" >> "$GITHUB_OUTPUT" - echo "::notice::Corpus export from D1 failed — replay skipped. Advisory only, never fails the PR." - fi - - # Two runs over the IDENTICAL deterministic sample (seed = head SHA, per the design contract's - # per-PR determinism requirement): base prompt first (the baseline artifact), then head with - # --baseline (comparison + comment + persisted run event). - - name: Replay base and head prompts - if: ${{ steps.replaycorpus.outputs.available == 'true' }} - id: replay - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - REPLAY_BUDGET: ${{ vars.COUNTERFACTUAL_REPLAY_BUDGET }} - REPLAY_MODEL: ${{ vars.COUNTERFACTUAL_REPLAY_MODEL }} - REPLAY_OLLAMA_URL: ${{ secrets.COUNTERFACTUAL_OLLAMA_URL }} - REPLAY_PROVIDER: ${{ steps.budget.outputs.provider }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - BASE_VERSION=$(cat base-version.txt) - HEAD_VERSION=$(cat head-version.txt) - if npx tsx scripts/counterfactual-replay.ts \ - --fixtures replay-corpus.json \ - --variant "${BASE_VERSION}@${REPLAY_MODEL}" \ - --prompt-file base-prompt.txt \ - --budget "$REPLAY_BUDGET" \ - --seed-suffix "$HEAD_SHA" \ - --provider "$REPLAY_PROVIDER" \ - --ollama-url "${REPLAY_OLLAMA_URL:-http://localhost:11434}" \ - --out base-scores.json \ - && npx tsx scripts/counterfactual-replay.ts \ - --fixtures replay-corpus.json \ - --variant "${HEAD_VERSION}@${REPLAY_MODEL}" \ - --prompt-file head-prompt.txt \ - --budget "$REPLAY_BUDGET" \ - --seed-suffix "$HEAD_SHA" \ - --provider "$REPLAY_PROVIDER" \ - --ollama-url "${REPLAY_OLLAMA_URL:-http://localhost:11434}" \ - --baseline base-scores.json \ - --base-variant-label "$BASE_VERSION" \ - --comment-out replay-comment.md \ - --head-sha "$HEAD_SHA" --base-sha "$BASE_SHA" \ - --persist --remote --db loopover \ - --repo "$GITHUB_REPOSITORY" --pr "$PR_NUMBER"; then - echo "ready=true" >> "$GITHUB_OUTPUT" - else - echo "ready=false" >> "$GITHUB_OUTPUT" - echo "::notice::Counterfactual replay failed — no comparison produced. Advisory only, never fails the PR." - fi - - - name: Post or update the replay PR comment - if: ${{ steps.replay.outputs.ready == 'true' }} - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - post_comment() { - marker="" - comment_id=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" --paginate \ - --jq "[.[] | select(.body | contains(\"${marker}\")) | .id] | first // empty" | head -n 1) - if [ -n "$comment_id" ]; then - gh api "repos/${GITHUB_REPOSITORY}/issues/comments/${comment_id}" -X PATCH -F body=@replay-comment.md - else - gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" -F body=@replay-comment.md - fi - } - if ! post_comment; then - echo "::notice::PR comment post failed — replay computed and persisted but not posted. Advisory only, never fails the PR." - fi - - # The fork half of ci.yml's paired fork==true/!=true convention: fork-originated pull_request runs get - # no repo secrets, so the D1-backed halves cannot run — say so visibly instead of failing or going - # silent. Advisory only either way; a skipped run never blocks anything (#8105). - fork-notice: - name: calibration advisory (skipped for fork PRs) - if: ${{ github.event.pull_request.draft != true && github.event.pull_request.head.repo.fork == true }} - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - name: Explain the skip - run: echo "::notice::Fork PR — repo secrets are withheld, so the D1-backed calibration advisory checks (logic backtest + counterfactual replay) are skipped. Advisory only; nothing blocks." diff --git a/.github/workflows/verify-public-claims.yml b/.github/workflows/verify-public-claims.yml deleted file mode 100644 index 433f4b5f6..000000000 --- a/.github/workflows/verify-public-claims.yml +++ /dev/null @@ -1,192 +0,0 @@ -# Nightly anonymous verification (#9724, epic #9722). -# -# LoopOver publishes fairness claims and tells a stranger they can check them without asking permission. This -# job IS that stranger, on a schedule. It runs the verifier PUBLISHED ON NPM against PRODUCTION with no -# credentials of any kind, so a regression in the public verification path is caught by us within a cycle -# instead of by an outside reader whenever they happen to look. -# -# THE PUBLISHED TOOL, NOT THE ONE IN THIS TREE. `npx -p @loopover/mcp` deliberately resolves the release on npm -# rather than building from the checkout. What is being asserted is "an outsider succeeds today", and an -# outsider has the published CLI -- so a fix that is merged but unpublished must NOT turn this green. #9962 is -# exactly that failure: the shipped verifier asked `/v1/public/eval-corpus?rule_id=`, the route reads `ruleId`, -# every corpus fetch 400'd, and the tool reported production as unverifiable while production was fine. Both -# sides were individually tested and individually correct. Only running the real pair catches it. -# -# NO CREDENTIALS ON THE VERIFY STEP. The job-level permission is `contents: read`, and the verify step is given -# no token in its environment at all -- `issues: write` and the token live only on the step that files the -# tracking issue, after verification is finished. A verifier that runs with repo credentials is not reproducing -# an outsider's view, and could pass on access a stranger does not have. -# -# TWO SURFACES, because they hold different things (#9940): `api.loopover.ai` serves aggregate stats and -# eval-score records, while the anchored decision ledger lives on the Orb at `shots.loopover.ai`. Checking only -# one leaves the other free to regress silently, so both are verified and reported independently. -name: Verify Public Claims - -on: - schedule: - # 04:12 UTC. Off the hour on purpose: the top of the hour is the busiest slot on GitHub's shared scheduler - # and the most likely to be delayed or dropped, which for a nightly is a silently skipped check. - - cron: "12 4 * * *" - workflow_dispatch: - inputs: - api-base-url: - description: "Base URL for the aggregate/eval surface" - required: false - default: "https://api.loopover.ai" - orb-base-url: - description: "Base URL for the anchored decision ledger" - required: false - default: "https://shots.loopover.ai" - dry-run: - description: "Report the verdict without filing, updating or closing the tracking issue" - required: false - default: "false" - -permissions: - contents: read - -concurrency: - group: verify-public-claims - cancel-in-progress: false - -jobs: - verify: - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - contents: read - issues: write - env: - API_BASE_URL: ${{ inputs.api-base-url || 'https://api.loopover.ai' }} - ORB_BASE_URL: ${{ inputs.orb-base-url || 'https://shots.loopover.ai' }} - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - # `persist-credentials: false` is load-bearing here, not hygiene. actions/checkout defaults to TRUE, - # which writes an authenticated `http.extraheader` into `.git/config` -- so the verify step would run - # with a usable GitHub token sitting on disk, and this job's whole claim is that it reproduces what a - # stranger sees. Withholding the token from the step's `env:` while leaving it in `.git/config` is - # theatre: the credential is still there for anything the step runs to pick up. - # - # Nothing here needs it. The only step that talks to GitHub is the tracking-issue step, which uses - # `gh` with an explicit `GITHUB_TOKEN` in its own environment -- `gh` reads that variable directly and - # never consults git's credential config. - persist-credentials: false - - # DELIBERATELY NO actions/setup-node. This job needs a Node RUNTIME, not this repository's toolchain: - # it runs a published CLI through npx and one checked-in script, and builds nothing. The runner image - # already provides both node and npm, and three workflows here (ci.yml, mcp-release-watch.yml, - # package-release-watch.yml) already rely on that. - # - # Dropping it removes the last action that can write credentials. `actions/setup-node` writes an - # authenticated .npmrc via `auth.configAuthentication(registryUrl)` -- gated behind `if (registryUrl)` - # in its `src/main.ts`, so it was unreachable while that input stayed unset, but "unreachable because - # nobody has added one line yet" is a weaker property than "not present". For a job whose entire claim - # is that it holds no credentials, not present is the one worth having. - # - # The tradeoff is that the Node version is now the runner's rather than .nvmrc's, so it is ASSERTED - # rather than assumed. `--experimental-strip-types` needs 22.6+; if an image ever regresses below that, - # this fails immediately with the fix in the message instead of the nightly quietly breaking. - - name: Require a Node that can strip types - run: | - node -e ' - const [major, minor] = process.versions.node.split(".").map(Number); - if (major > 22 || (major === 22 && minor >= 6)) process.exit(0); - console.error("::error::Node " + process.versions.node + " cannot run --experimental-strip-types (needs 22.6+). Re-add actions/setup-node with node-version-file: .nvmrc."); - process.exit(1); - ' - echo "node $(node --version), npm $(npm --version)" - - # No `npm ci`: this step must not depend on the repository's own dependency tree, because a stranger has - # none. `npx -p @loopover/mcp` fetches the published package exactly as the docs tell a reader to. - - name: Verify published claims anonymously - id: verify - run: | - # No `set -e`: a failing claim exits the verifier non-zero, and that is a RESULT to be captured and - # reported, not a reason to abort before the tracking issue is filed. - set -uo pipefail - run_surface() { - base="$1" - out="$2" - echo "::group::loopover-verify --base-url $base" - # `code` is assigned on its OWN line. `local code=$?` / `code=$(...)` would capture the assignment's - # own status instead of the command's, quietly making every run look like a clean exit 0. - npx --yes -p @loopover/mcp loopover-verify --base-url "$base" --json > "$out" 2>"$out.err" - code=$? - echo "$code" > "$out.code" - cat "$out" - # stderr matters most when stdout is unparseable -- that is the "the verifier itself broke" case, - # and it is the one where the JSON report cannot explain anything. - if [ -s "$out.err" ]; then echo "--- stderr ---"; cat "$out.err"; fi - echo "exit=$code" - echo "::endgroup::" - } - run_surface "$API_BASE_URL" api.json - run_surface "$ORB_BASE_URL" orb.json - # The script appends VERIFY_OK, VERIFY_SUMMARY and the heredoc-delimited body to $GITHUB_OUTPUT - # itself, as one write. Wrapping its stdout in a heredoc here instead would interleave the two - # writers and bury VERIFY_OK inside the body block. - # - # `node --experimental-strip-types`, not `npx tsx`: this file is OURS and already checked out, so - # fetching an unpinned TypeScript runner from the registry to read it would add a second unvetted - # runtime dependency to a job whose one intentional unpinned fetch is the published verifier itself. - # Same invocation `npm run actionlint` already uses for its own TS script. - node --experimental-strip-types scripts/verify-public-claims-report.ts \ - "public API" "$API_BASE_URL" "$(cat api.json.code)" api.json \ - "Orb ledger" "$ORB_BASE_URL" "$(cat orb.json.code)" orb.json - - - name: Report verdict - run: | - { - echo "### Anonymous verification — ${{ steps.verify.outputs.VERIFY_SUMMARY }}" - echo "" - echo "- \`${{ env.API_BASE_URL }}\`" - echo "- \`${{ env.ORB_BASE_URL }}\`" - } >> "$GITHUB_STEP_SUMMARY" - - # Open-or-update on failure, close on recovery. ONE issue, found by exact title, so a persistent outage - # is a single tracked thing rather than a nightly pile -- and so recovery has something unambiguous to - # close. This step is the only one holding a token. - - name: File or close the tracking issue - if: ${{ inputs.dry-run != 'true' }} - env: - GITHUB_TOKEN: ${{ github.token }} - VERIFY_OK: ${{ steps.verify.outputs.VERIFY_OK }} - VERIFY_BODY: ${{ steps.verify.outputs.body }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - TITLE: "verifiability: the nightly anonymous verification run is failing" - run: | - set -euo pipefail - existing=$(gh issue list --state open --search "\"$TITLE\" in:title" --json number,title \ - --jq "map(select(.title == env.TITLE)) | .[0].number // empty") - if [ "$VERIFY_OK" = "true" ]; then - if [ -n "$existing" ]; then - gh issue comment "$existing" --body "Recovered. The nightly anonymous verification run is green again as of [this run]($RUN_URL); closing automatically." - gh issue close "$existing" --reason completed - echo "Closed #$existing on recovery." - else - echo "Green, and nothing was open. Nothing to do." - fi - exit 0 - fi - body="$VERIFY_BODY - - [Failing run]($RUN_URL)" - if [ -n "$existing" ]; then - # Comment rather than overwrite the body: the history of WHICH claims failed on WHICH night is the - # most useful thing on a flapping issue, and rewriting the body destroys it. - gh issue comment "$existing" --body "$body" - echo "::error::Anonymous verification is failing -- updated #$existing." - else - gh issue create --title "$TITLE" --label maintainer-only --assignee JSONbored --body "$body" - echo "::error::Anonymous verification is failing -- tracking issue filed." - fi - - # Last, so the issue is always filed or closed even when the job is about to go red. A red run with no - # issue would be a monitor that notices a problem and then drops it. - - name: Fail the run when a claim failed - if: ${{ steps.verify.outputs.VERIFY_OK != 'true' }} - run: | - echo "::error::One or more published claims could not be verified anonymously." - exit 1 diff --git a/apps/loopover-ui/content/docs/backtest-calibration.mdx b/apps/loopover-ui/content/docs/backtest-calibration.mdx index 28a0eb508..e1010119c 100644 --- a/apps/loopover-ui/content/docs/backtest-calibration.mdx +++ b/apps/loopover-ui/content/docs/backtest-calibration.mdx @@ -40,14 +40,14 @@ confidence-threshold constant, the old and new values are replayed as classifier rule's recorded history, and the comparison is rendered directly into the unified review comment. No code from the PR is ever executed — a threshold is just a number. -**Logic/regex changes** run in a dedicated CI workflow instead, because honestly verifying a +**Logic/regex changes** are checked outside the review pass, because honestly verifying a rewritten detection function requires _executing the PR's own code_ against history — something -the production review service must never do. The workflow checks out both the PR's head and its -base, replays each recorded case's captured raw context through both versions of the detection -function, and posts its own clearly-labeled **"Logic backtest"** PR comment, separate from the -unified review comment. It triggers only for PRs touching the watched detection-logic paths, -skips drafts and forks (fork runs get no secrets), and fails open: an infrastructure problem -produces a skip notice, never a red check. +the production review service must never do. `scripts/backtest-logic-check.ts` loads a corpus +export, replays each recorded case's captured raw context through the detection function from two +checkouts (the PR's head and its base), and writes a clearly-labeled **"Logic backtest"** +comparison, separate from the unified review comment. Run it by hand against your own corpus: the +CI workflow that ran it on this repository's pull requests was retired with the hosted D1 database +it read. ## Reading the comparison @@ -186,19 +186,16 @@ parser or mapping change costs nothing. Exit codes reflect operational success o ### The prompt-change workflow -A PR that touches the reviewer judge-prompt surface (`src/services/ai-review.ts` — bump -`REVIEW_PROMPT_VERSION` whenever a change shapes the judge's verdict) triggers the -`counterfactual-replay` advisory workflow: it extracts the **canonical judge prompt** from both the -base and head checkouts, replays both over the identical seeded sample (seed = head SHA, so re-runs -per push are deterministic), posts the comparison as an update-in-place PR comment, and persists a +A change to the reviewer judge-prompt surface (`src/services/ai-review.ts` — bump +`REVIEW_PROMPT_VERSION` whenever a change shapes the judge's verdict) is checked with +`scripts/counterfactual-replay.ts`, run by hand: give it the **canonical judge prompt** from the base +and head checkouts (`scripts/print-review-prompt.ts` prints it) and it replays both over the identical +seeded sample, prints the comparison, and with `--persist` records a `calibration.counterfactual_backtest_run` event feeding the same REGRESSED-verdict track record as the -threshold and logic backtests. The check spends nothing unless the deployment explicitly configures a -replay budget (repo variables `COUNTERFACTUAL_REPLAY_BUDGET`/`COUNTERFACTUAL_REPLAY_MODEL`) — otherwise -it posts a visible "skipped: no replay budget configured" notice. Provider selection: with a -`COUNTERFACTUAL_OLLAMA_URL` secret set, the check uses that ollama endpoint (a self-hosted runner -reaching its own local model is the zero-marginal-cost shape); without it, the default is the flag-gated -Workers AI fallback on the deployment's existing Cloudflare credentials — OSS models, usage-priced, -dormant until the budget variables exist. +threshold and logic backtests. It stops at its `--budget` (a built-in default when you set none). Its +default provider is a local ollama (`--ollama-url`); `--provider workers-ai` uses Cloudflare credentials +from the environment instead. The CI workflow that ran it on this repository's pull requests was retired +with the hosted D1 database. Advisory forever until a separate, explicit authority decision, exactly like every other backtest gate. ## Self-hosting diff --git a/scripts/backtest-logic-check.ts b/scripts/backtest-logic-check.ts index bf5376020..3ff5545f0 100644 --- a/scripts/backtest-logic-check.ts +++ b/scripts/backtest-logic-check.ts @@ -1,6 +1,6 @@ #!/usr/bin/env node -// Logic/regex-change backtest CLI (#8139, epic #8082) — the CI-side runner .github/workflows/ -// calibration-advisory.yml invokes. Loads a corpus manifest (produced by backtest-corpus-export.ts), +// Logic/regex-change backtest CLI (#8139, epic #8082), run by hand (the CI workflow that invoked it was +// retired with the hosted D1 database it read). Loads a corpus manifest (produced by backtest-corpus-export.ts), // dynamically imports the registered detection function from TWO checkout roots (the PR's head and its base // — the dual checkout is what makes an honest before/after comparison possible), runs the pure core's // scoring/comparison, writes the PR-comment Markdown, and optionally persists the run to D1 via diff --git a/scripts/verify-public-claims-report.ts b/scripts/verify-public-claims-report.ts deleted file mode 100644 index 12ddc35db..000000000 --- a/scripts/verify-public-claims-report.ts +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env node -// #9724: turn one or more `loopover-verify --json` reports into the nightly job's verdict and, when something -// is wrong, the body of the tracking issue a maintainer will actually have to act on. -// -// WHY THIS IS A SCRIPT AND NOT INLINE BASH. The interesting logic here is a judgement -- which claims count as -// a regression, and what a reader needs in order to fix it -- and that judgement is exactly the part that must -// not be discovered to be wrong on the night it first fires. As a pure function it is unit-tested against real -// report shapes, including the shapes that must NOT open an issue. -// -// SKIP IS NOT FAILURE, AND IS NOT SUCCESS EITHER. `loopover-verify` reports a surface it could not obtain as -// `skip`, and the verifier's own header is emphatic that collapsing "could not check" into "checked, fine" is -// how you build a monitor that always says green. So skips never open an issue -- a deployment legitimately -// serves no corpus for a rule, and the public API's ledger is empty BY DESIGN (#9940), which is a permanent, -// expected skip -- but they are always reported in the body, because "we verified nothing at all tonight" is -// something a maintainer reading a green run deserves to see. - -import { pathToFileURL } from "node:url"; -import { readFileSync } from "node:fs"; - -/** One claim as `loopover-verify --json` emits it. Structural, matching the verifier's own reasoning about - * older deployments: the nightly must be able to parse a report from a CLI version it does not control. */ -export type VerifyClaim = { - id?: unknown; - claim?: unknown; - status?: unknown; - detail?: unknown; -}; - -export type VerifyRun = { - /** Human label for the surface, e.g. "public API". Appears in the issue body and the job log. */ - label: string; - baseUrl: string; - /** The CLI's exit code. Non-zero with no failing claim means the tool itself broke -- see below. */ - exitCode: number; - /** Parsed `--json` payload, or null when the CLI produced nothing parseable. */ - report: { results?: unknown } | null; -}; - -export type ClaimLine = { surface: string; status: string; claim: string; detail: string }; - -export type VerificationReport = { - ok: boolean; - failures: ClaimLine[]; - skips: ClaimLine[]; - passes: ClaimLine[]; - title: string; - body: string; -}; - -const str = (value: unknown, fallback = ""): string => (typeof value === "string" ? value : fallback); - -/** PURE. Flatten one run's claims into labelled lines. A report whose `results` is absent or not an array - * yields nothing here; {@link buildVerificationReport} turns that into its own failure rather than letting an - * unreadable report read as "no failures". */ -export function claimLinesFor(run: VerifyRun): ClaimLine[] { - const results = run.report?.results; - if (!Array.isArray(results)) return []; - return results.map((entry) => { - const claim = entry as VerifyClaim; - return { - surface: run.label, - status: str(claim.status, "unknown").toLowerCase(), - claim: str(claim.claim, str(claim.id, "(unnamed claim)")), - detail: str(claim.detail, "(no detail published)"), - }; - }); -} - -/** - * PURE. Decide whether the public verification path is healthy, and write the issue body if it is not. - * - * Four independent things count as broken, and every one after the first is a case that would otherwise - * present as a silent green: - * - * 1. any claim the verifier reports as `fail`; - * 2. a run that produced NO readable report at all (the CLI crashed, the JSON was malformed, npx could not - * resolve the package). Nothing failed, because nothing ran -- which is a regression in the published - * verification path itself, precisely what this job exists to notice; - * 3. a non-zero exit code with no failing claim to explain it. The tool is telling us something went wrong - * in a way its own claim list does not describe, and trusting the empty claim list over the exit code - * would be choosing the more comfortable of two contradictory signals; - * 4. a run in which NOTHING PASSED. This is the one that matters most, and it was found by pointing the real - * verifier at a deliberately wrong base URL: every claim came back `skip` ("/v1/public/eval-scores - * unavailable (HTTP 404)") and the CLI exited 0. Judged claim-by-claim that is four legitimate skips and - * a clean exit -- so the monitor would have reported GREEN against a completely dead endpoint, which is - * the exact failure this job exists to prevent. - * - * The verifier is right to call them skips: from inside a single claim, "this surface is disabled" and - * "this host is wrong" are indistinguishable. The MONITOR has the context the claim lacks -- production is - * supposed to be serving these -- so requiring at least one positively verified claim per surface is a - * judgement that belongs here rather than in the CLI. - * - * The floor is one, not a proportion, because the two surfaces are legitimately lopsided and both must - * clear it with room to spare (measured against production): `api.loopover.ai` passes record-digests, - * corpus-commitments and stats-parity while skipping anchor-checkpoint (its ledger is empty BY DESIGN, - * #9940), and `shots.loopover.ai` passes anchor-checkpoint while skipping the other three (it does not - * publish stats). A threshold like "most claims pass" would fail the Orb on a healthy night. - */ -export function buildVerificationReport(runs: readonly VerifyRun[]): VerificationReport { - const all = runs.flatMap(claimLinesFor); - const failures = all.filter((line) => line.status === "fail"); - const skips = all.filter((line) => line.status === "skip"); - const passes = all.filter((line) => line.status === "pass"); - - const brokenRuns = runs.filter((run) => run.report === null || !Array.isArray(run.report.results)); - const unexplained = runs.filter( - (run) => run.exitCode !== 0 && !brokenRuns.includes(run) && !claimLinesFor(run).some((line) => line.status === "fail"), - ); - // Case 4. Only for runs that produced a readable report -- a broken run is already reported as such, and - // saying "and also nothing passed" about it would be two findings for one cause. - const verifiedNothing = runs.filter((run) => !brokenRuns.includes(run) && !claimLinesFor(run).some((line) => line.status === "pass")); - - const ok = failures.length === 0 && brokenRuns.length === 0 && unexplained.length === 0 && verifiedNothing.length === 0; - const title = TRACKING_ISSUE_TITLE; - if (ok) { - return { ok, failures, skips, passes, title, body: "" }; - } - - const lines: string[] = [ - "The nightly anonymous verification run failed. These are LoopOver's own published claims, checked the way", - "an outsider checks them: the verifier published on npm, run against production, with no credentials of any", - "kind. A failure here means a stranger following the walkthrough right now gets the same result.", - "", - ]; - - for (const run of brokenRuns) { - lines.push(`### ${run.label} — the verifier produced no readable report`, ""); - lines.push( - `\`${run.baseUrl}\` exited ${run.exitCode} without emitting parseable \`--json\` output. Nothing was checked, which`, - "is itself the regression: the published verification path did not run. Check the job log for the raw output.", - "", - ); - } - - for (const run of unexplained) { - lines.push(`### ${run.label} — non-zero exit with no failing claim`, ""); - lines.push( - `\`${run.baseUrl}\` exited ${run.exitCode} but reported no \`fail\` claim. The tool is signalling a problem its own`, - "claim list does not describe; the exit code is the signal to trust here, not the empty list.", - "", - ); - } - - for (const run of verifiedNothing) { - lines.push(`### ${run.label} — nothing was verified`, ""); - lines.push( - `Every claim against \`${run.baseUrl}\` came back skipped, so not one published commitment was actually`, - "recomputed. The most common cause is that the surface is not reachable at that host at all -- a wrong or", - "renamed base URL returns 404 for every endpoint, which the verifier reports claim-by-claim as \"unavailable\"", - "and exits 0. A healthy surface always positively verifies at least one claim.", - "", - ); - } - - if (failures.length > 0) { - lines.push("### Failing claims", ""); - lines.push("| Surface | Claim | Detail |", "| --- | --- | --- |"); - for (const line of failures) lines.push(`| ${line.surface} | ${escapeCell(line.claim)} | ${escapeCell(line.detail)} |`); - lines.push(""); - } - - if (skips.length > 0) { - // Reported, never counted. A permanent skip is expected (the public API's ledger is empty by design), but a - // NEW one next to a failure is often the actual cause, so it has to be visible in the same body. - lines.push("### Skipped (not counted as failures)", ""); - lines.push("| Surface | Claim | Detail |", "| --- | --- | --- |"); - for (const line of skips) lines.push(`| ${line.surface} | ${escapeCell(line.claim)} | ${escapeCell(line.detail)} |`); - lines.push(""); - } - - lines.push("### Reproduce", ""); - lines.push("```bash"); - for (const run of runs) lines.push(`npx -p @loopover/mcp loopover-verify --base-url ${run.baseUrl}`); - lines.push("```", ""); - lines.push( - "This issue is updated in place while the failure persists and closed automatically by the next green run,", - "so it never needs manual triage to stay accurate. Filed by `.github/workflows/verify-public-claims.yml` (#9724).", - ); - - return { ok, failures, skips, passes, title, body: lines.join("\n") }; -} - -/** The single tracking issue's title. A CONSTANT, not templated with a date or a claim name: the workflow finds - * the existing issue by exact title, and anything varying per run would file a new issue every night instead of - * updating one. */ -export const TRACKING_ISSUE_TITLE = "verifiability: the nightly anonymous verification run is failing"; - -/** Markdown table cells cannot contain a raw pipe or newline; verifier details legitimately contain both. */ -export function escapeCell(value: string): string { - return value.replace(/\|/g, "\\|").replace(/\r?\n/g, " "); -} - -/** PURE. The one-line job summary, printed whether or not anything failed. */ -export function summarize(report: VerificationReport): string { - return `${report.passes.length} passed, ${report.failures.length} failed, ${report.skips.length} skipped`; -} - -/** Parse one run from the CLI's stdout. Never throws: unparseable output IS a result (see case 2 above). */ -export function parseRun(label: string, baseUrl: string, exitCode: number, stdout: string): VerifyRun { - try { - const parsed: unknown = JSON.parse(stdout); - if (parsed === null || typeof parsed !== "object") return { label, baseUrl, exitCode, report: null }; - return { label, baseUrl, exitCode, report: parsed as { results?: unknown } }; - } catch { - return { label, baseUrl, exitCode, report: null }; - } -} - -/** The heredoc delimiter for the multi-line `body` output. GitHub requires a delimiter that does not occur in - * the value; this one is long and structured enough that verifier prose cannot collide with it, and - * {@link renderGithubOutput} asserts that rather than assuming it. */ -export const OUTPUT_DELIMITER = "VERIFY_BODY_EOF_9d3f1c"; - -/** - * PURE. The exact bytes to append to `$GITHUB_OUTPUT`. - * - * Built here, as one string, rather than by the workflow shell echoing around the script's stdout. That shape - * was subtly broken: the script appending its own scalars while the shell wrapped its stdout in a heredoc - * interleaves the two writers, and `VERIFY_OK=` lands INSIDE the body block -- leaving the workflow reading an - * empty verdict and, because an empty string is not `"true"`, filing an outage issue on a healthy night. - */ -export function renderGithubOutput(report: VerificationReport): string { - if (report.body.includes(OUTPUT_DELIMITER)) { - // Unreachable with the delimiter above, but an unguarded heredoc is an output-injection primitive: a body - // containing the delimiter would terminate the block early and let the rest be parsed as more outputs. - throw new Error("verification body contains the output delimiter"); - } - return [`VERIFY_OK=${report.ok ? "true" : "false"}`, `VERIFY_SUMMARY=${summarize(report)}`, `body<<${OUTPUT_DELIMITER}`, report.body, OUTPUT_DELIMITER, ""].join("\n"); -} - -/** PURE. Parse the CLI's positional arguments into runs. Four per surface. */ -export function parseArgs(argv: readonly string[], readFile: (path: string) => string): VerifyRun[] { - const runs: VerifyRun[] = []; - for (let index = 0; index < argv.length; index += 4) { - const label = argv[index] ?? ""; - const baseUrl = argv[index + 1] ?? ""; - const exitCode = Number.parseInt(argv[index + 2] ?? "", 10); - const file = argv[index + 3] ?? ""; - let stdout = ""; - try { - stdout = readFile(file); - } catch { - // An unreadable capture file is the same finding as unparseable output: nothing was verified. - } - // A non-numeric exit code is treated as a failure rather than a zero -- "we could not tell how it exited" - // must never be the optimistic branch. - runs.push(parseRun(label, baseUrl, Number.isFinite(exitCode) ? exitCode : 1, stdout)); - } - return runs; -} - -/** CLI: `verify-public-claims-report.ts