Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

ci: harden AI review label selection and catalog (#6161)

LearningCircuit358da5a9a72e
diff --git a/.file-whitelist.txt b/.file-whitelist.txt
index ccaeda038d..ab20f60444 100644
--- a/.file-whitelist.txt
+++ b/.file-whitelist.txt
@@ -28,6 +28,7 @@
^package\.json$
^package-lock\.json$
^lighthouserc\.json$
+^\.github/ai-review-label-policy\.json$
^tests/(.*/)?package\.json$
^tests/(.*/)?package-lock\.json$
^tests/settings/golden_master_settings\.json$
diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
index ef1eaa83e3..053926868a 100644
--- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
+++ b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
@@ -6,7 +6,15 @@ Fixes #
By default, this PR runs the unit/lint checks. Heavy E2E suites are label-gated — add the label that matches what you touched so the relevant workflow runs:
-- `test:puppeteer` or `test:e2e` — Puppeteer E2E suite (~30–60 min; uses paid LLM/search API quotas).
+- `test:puppeteer` — Puppeteer E2E suite (~30–60 min; uses paid LLM/search API quotas). `test:e2e` is a legacy alias.
+- `test:notes` — focused Notes Playwright E2E suite (re-runs on later pushes while the label remains).
+- `test:ui-full-shards` — full sharded UI matrix plus the strict Docker CI graph (expensive).
- `ldr_research` or `ldr_research_static` — LDR research integration workflow that posts findings as a PR comment.
+The AI reviewer can recommend these selectors but never applies them: each one
+spends paid API quota and CI wall-clock, so a maintainer makes that call. Most
+of these workflows also trigger on `labeled` only, which a label added with the
+reviewer's `GITHUB_TOKEN` cannot start; `test:notes` is the exception, since it
+re-runs on every push while the label is present.
+
WebKit/Mobile Safari tests run on the daily 02:00 UTC schedule and at release; the responsive UI suite runs at release and on manual dispatch.
diff --git a/.github/ai-review-label-policy.json b/.github/ai-review-label-policy.json
new file mode 100644
index 0000000000..74dab3583a
--- /dev/null
+++ b/.github/ai-review-label-policy.json
@@ -0,0 +1,54 @@
+{
+ "apply": [
+ "accessibility",
+ "api",
+ "benchmark-needed",
+ "breaking-change",
+ "bugfix",
+ "ci-cd",
+ "code-quality",
+ "configuration",
+ "critical-changes",
+ "css",
+ "database",
+ "dependencies",
+ "developer-experience",
+ "docker",
+ "documentation",
+ "enhancement",
+ "feature",
+ "github-actions",
+ "javascript",
+ "library",
+ "llm-providers",
+ "maintenance",
+ "metrics",
+ "news",
+ "performance",
+ "privacy",
+ "python",
+ "rag",
+ "refactoring",
+ "research",
+ "research-quality",
+ "research-speed",
+ "security",
+ "snappy",
+ "technical-debt",
+ "tests",
+ "ui-ux",
+ "visualization"
+ ],
+ "recommend": [
+ "ldr_research",
+ "ldr_research_static",
+ "test:notes",
+ "test:puppeteer",
+ "test:ui-full-shards"
+ ],
+ "aliases": {
+ "bug": "bugfix",
+ "test:e2e": "test:puppeteer",
+ "testing": "tests"
+ }
+}
diff --git a/.github/labels.yml b/.github/labels.yml
index 2071b21cba..6c7cbd8c85 100644
--- a/.github/labels.yml
+++ b/.github/labels.yml
@@ -1,58 +1,229 @@
-# PR triage labels managed declaratively by .github/workflows/labels-sync.yml.
-# This file is an additive sync — labels not listed here are left untouched.
-# Persistent labels (applied at PR open by .github/workflows/pr-triage.yml):
+# Automation-relevant labels managed by .github/workflows/labels-sync.yml.
+# This file is additive: labels not listed here are left untouched.
+
+# PR author classification (applied by .github/workflows/pr-triage.yml).
- name: external-contributor
color: 'cccccc'
- description: PR from someone outside the maintainer team
+ description: Human-authored PR whose author is not a repository owner, organization member, or collaborator.
- name: first-time-contributor
color: 'c2e0c6'
- description: First contribution to this repo
+ description: GitHub reports this as the author's first contribution to this repository.
- name: bot
color: 'ededed'
- description: PR opened by an automated account
-- name: needs-rework
- color: 'e99695'
- description: PR needs substantive rework before it can be reviewed in depth
-# Lifecycle labels (toggled per-PR by .github/workflows/pr-triage.yml):
+ description: PR opened by a bot account or recognized automation account.
+
+# PR review lifecycle (toggled by .github/workflows/pr-triage.yml).
- name: needs-codeowner-review
color: 'fbca04'
- description: Awaiting first review from a global codeowner
+ description: Needs an initial or renewed decision from a global codeowner.
- name: awaiting-author
color: 'd4c5f9'
- description: Codeowner requested changes; ball is with author
+ description: A global codeowner requested changes; author action is needed.
- name: awaiting-codeowner
color: 'fef2c0'
- description: Author has responded; needs codeowner re-review
-# LDR research trigger labels (used by .github/workflows/e2e-research-test.yml
-# and .github/workflows/issue-research.yml — applied manually by maintainers,
-# auto-removed by the workflow after the run completes).
-# Descriptions are phrased as direct instructions so the AI code reviewer
-# (.github/workflows/ai-code-reviewer.yml) can decide when to apply them.
+ description: The PR was updated or marked ready after requested changes; global codeowner re-review is needed.
+
+# PR topic labels. .github/workflows/pr-triage.yml applies these
+# deterministically from the changed paths; they are also in the AI reviewer's
+# allowlist (.github/ai-review-label-policy.json), so a review can apply them
+# too. Neither source is exclusive.
+- name: github-actions
+ color: '1f2328'
+ description: 'Changes to GitHub Actions workflows. Release notes: 🔧 CI/CD & Maintenance (8/20).'
+- name: ci-cd
+ color: '57606a'
+ description: 'CI/CD pipeline, GitHub Actions, or build changes. Release notes: 🔧 CI/CD & Maintenance (8/20).'
+- name: docker
+ color: '2496ed'
+ description: 'Docker, containerization, or deployment changes. Release notes: 🐳 Docker (15/20).'
+- name: documentation
+ color: '0075ca'
+ description: 'Documentation changes. Release notes: 📚 Documentation (7/20).'
+- name: tests
+ color: 'bfe5bf'
+ description: 'Adds, updates, or fixes tests. Release notes: 🧪 Tests (priority 11/20).'
+- name: database
+ color: '0e8a16'
+ description: 'Database schema, migration, or storage changes. Release notes: 🗄️ Database Changes (6/20).'
+- name: configuration
+ color: 'd4c5f9'
+ description: 'Configuration or settings changes. Release notes: ⚙️ Configuration (priority 12/20).'
+- name: dependencies
+ color: '0e4f5c'
+ description: 'Updates project dependencies (packages, libraries). Release notes: ⬆️ Dependencies (9/20).'
+- name: research
+ color: '0e8a16'
+ description: 'Research functionality changes. Release notes: 🔍 Research Features (16/20).'
+- name: python
+ color: '3572a5'
+ description: 'Python code changes. Release notes: 🐍 Python Changes (priority 13/20).'
+- name: javascript
+ color: 'f1e05a'
+ description: 'JavaScript code changes (.js/.mjs). Release notes: 🎨 Frontend Changes (14/20).'
+- name: css
+ color: 'fbb6c4'
+ description: 'CSS and styling changes. Release notes: 🎨 Frontend Changes (14/20).'
+
+# Semantic PR labels the AI reviewer may apply. The authoritative allowlist is
+# .github/ai-review-label-policy.json; unknown model suggestions are rejected.
+- name: accessibility
+ color: 'a8c5e1'
+ description: 'Accessibility improvements (a11y). Release notes: 🎨 Frontend Changes (14/20).'
+- name: api
+ color: '0366d6'
+ description: API routes, request/response contracts, or client-facing API behavior.
+- name: benchmark-needed
+ color: 'fbca04'
+ description: Change may affect runtime performance; a compare_configurations() benchmark run is wanted.
+- name: breaking-change
+ color: 'a01441'
+ description: 'Introduces breaking API change requiring user action. Release notes: 💥 Breaking Changes (2/20).'
+- name: bugfix
+ color: 'f8b4b4'
+ description: 'Fix for a reported bug (PR-only). Release notes: 🐛 Bug Fixes (4/20).'
+- name: code-quality
+ color: '0366d6'
+ description: 'Readability, maintainability, or robustness work. Release notes: 🧹 Code Quality (10/20).'
+- name: critical-changes
+ color: 'a01441'
+ description: 'Changes to critical system components. Release notes: 💥 Breaking Changes (2/20).'
+- name: developer-experience
+ color: '7057ff'
+ description: 'Improvements to developer workflow, tooling, or DX. Release notes: 🧹 Code Quality (10/20).'
+- name: enhancement
+ color: 'a2eeef'
+ description: 'Improvement to an existing feature. Release notes: ✨ New Features (priority 3/20).'
+- name: feature
+ color: '2da44e'
+ description: 'New user-facing feature. Release notes: ✨ New Features (priority 3/20).'
+- name: library
+ color: '0366d6'
+ description: Document library, collections, ingestion, or library search behavior.
+- name: llm-providers
+ color: '0366d6'
+ description: LLM provider integrations, response compatibility, model discovery, or provider configuration.
+- name: maintenance
+ color: 'afb8c1'
+ description: 'Repo maintenance, tooling updates, or non-functional changes. Release notes: 🔧 CI/CD (8/20).'
+- name: metrics
+ color: '0e8a16'
+ description: 'Metrics, monitoring, or analytics changes. Release notes: 📊 Metrics & Analytics (17/20).'
+- name: news
+ color: '0366d6'
+ description: News search, subscriptions, scheduling, or news user interfaces.
+- name: performance
+ color: 'ff9248'
+ description: 'Speed, memory, or resource efficiency improvement. Release notes: ⚡ Performance (5/20).'
+- name: privacy
+ color: '0366d6'
+ description: Privacy, data egress, telemetry, or handling of sensitive user data.
+- name: rag
+ color: '0366d6'
+ description: Retrieval, indexing, embeddings, vector stores, or retrieval-augmented generation.
+- name: refactoring
+ color: '0e8a16'
+ description: 'Code restructuring without changing behavior. Release notes: 🧹 Code Quality (10/20).'
+- name: research-quality
+ color: '5319e7'
+ description: 'Improvements to research output quality. Release notes: 🔍 Research Features (16/20).'
+- name: research-speed
+ color: '0e8a16'
+ description: 'Improvements to research execution speed. Release notes: 🔍 Research Features (16/20).'
+- name: security
+ color: 'd73a4a'
+ description: 'Security fix or hardening. Release notes: 🔒 Security Updates (1/20, highest precedence).'
+- name: snappy
+ color: '00d084'
+ description: 'UI/UX responsiveness and app feel. Release notes: 🎨 Frontend Changes (14/20).'
+- name: technical-debt
+ color: 'fbca04'
+ description: 'Addresses accumulated technical debt. Release notes: 🧹 Code Quality (10/20).'
+- name: ui-ux
+ color: 'f9c4d2'
+ description: 'User interface or user experience improvements. Release notes: 🎨 Frontend Changes (14/20).'
+- name: visualization
+ color: '1d76db'
+ description: 'Data visualization or chart changes. Release notes: 🎨 Frontend Changes (14/20).'
+
+# AI-reviewer recommendations for opt-in, resource-intensive checks. The
+# reviewer lists these in its review and a maintainer applies the label,
+# because starting these workflows spends paid API quota and CI wall-clock and
+# that call belongs to a human. Most of them also trigger on `labeled` only,
+# which GITHUB_TOKEN-created label events cannot start; test:notes is the
+# exception (it also triggers on synchronize), so cost is the standing reason.
- name: ldr_research
color: '7057ff'
- description: Apply for substantive logic/architecture changes — when in doubt, add it. Runs full LDR research.
+ description: AI reviewer may recommend on PRs; maintainers apply or re-add for PR-diff or issue-context research.
- name: ldr_research_static
color: '7057ff'
- description: Cheaper variant of ldr_research for routine code changes — favor running this over no analysis.
-# E2E test trigger labels (used by .github/workflows/puppeteer-e2e-tests.yml).
-# Both labels trigger the same Puppeteer suite; descriptions guide the AI
-# reviewer toward running the suite for any PR that touches the web stack.
+ description: AI reviewer may recommend a low-cost smoke test; maintainers apply or re-add for a fixed LDR query.
- name: 'test:puppeteer'
color: '0e8a16'
- description: Apply if PR touches UI, web routes, auth, or templates — when in doubt, add it. Runs Puppeteer E2E.
+ description: 'UI, routes, auth or templates: AI reviewer may recommend; maintainers apply or re-add for paid E2E.'
- name: 'test:e2e'
color: '1d76db'
- description: Alias for test:puppeteer (same Puppeteer workflow). Apply one; both trigger the same job.
-# Full sharded UI test trigger (used by .github/workflows/ui-full-shards.yml).
-# Invokes docker-tests.yml with strict-mode=true so the 14-way ui-tests matrix
-# runs. Heavy — re-runs the full docker-tests job graph including pytest.
+ description: Legacy alias of test:puppeteer for UI, routes, auth or template changes; prefer test:puppeteer.
- name: 'test:ui-full-shards'
color: '0e8a16'
- description: Apply if PR touches puppeteer test infra or you want all 14 UI shards — costs ~45 min CI time.
-# Human-only signal labels — must NOT be set by any workflow, bot, or AI
-# reviewer. These exist to communicate a human judgement that automation
-# cannot make. If you find a workflow or hook applying one of these,
-# that's a bug — remove the automation, don't extend the label list.
+ description: 'Wide UI or template changes: AI reviewer may recommend; maintainers apply or re-add (strict CI).'
+- name: 'test:notes'
+ color: '0e8a16'
+ description: 'Notes UI/API changes: AI reviewer may recommend; maintainers apply or re-add for Playwright E2E.'
+
+# Security-sensitive path signals applied by danger-zone-alert.yml.
+- name: touches-authentication
+ color: 'd93f0b'
+ description: Modifies login, sessions, passwords, auth DB, or tenant isolation.
+- name: touches-encryption
+ color: 'b60205'
+ description: Modifies at-rest crypto, credential storage, or backup encryption.
+- name: touches-web-hardening
+ color: 'fbca04'
+ description: Modifies CSP, SSRF, CSRF, rate-limit, headers, validators, or hardening config.
+
+# Manual security-review signal. The danger-zone workflow emits a neutral
+# check and the three path labels above; it does not apply this label.
+- name: security-review-needed
+ color: 'ededed'
+ description: 'Requires security review before merge. Release notes: 🚧 Review & Blocked Items (19/20).'
+
+# Workflow/control labels. These are deliberately excluded from the AI
+# reviewer's output allowlist.
+- name: ai_code_review
+ color: '6f42c1'
+ description: 'Maintainer-only: apply or re-add to run AI code review. Release notes: 🔄 Automation (18/20).'
+- name: claude-review
+ color: 'ededed'
+ description: 'Maintainer-only: apply or re-add to run Claude code review.'
+- name: automation
+ color: '8b949e'
+ description: 'Automation or scripting changes. Release notes: 🔄 Branch Syncs & Automation (18/20).'
+- name: sync
+ color: 'ededed'
+ description: 'Branch synchronization PR. Release notes: 🔄 Branch Syncs & Automation (18/20).'
+- name: auto-merge
+ color: 'ededed'
+ description: 'PR approved for automatic merging. Release notes: 🔄 Branch Syncs & Automation (18/20).'
+- name: merge-blocked
+ color: 'ededed'
+ description: 'PR is blocked from merging. Release notes: 🚧 Review & Blocked Items (19/20).'
+- name: conflicts
+ color: 'ededed'
+ description: 'PR has merge conflicts needing resolution. Release notes: 🚧 Review & Blocked Items (19/20).'
+
+# Legacy names retained for historical issues and PRs. The AI policy maps them
+# to the canonical PR label and never applies the legacy name to new PRs.
+- name: bug
+ color: 'd73a4a'
+ description: 'Reports an unexpected problem. Issue-only label — use `bugfix` for PRs.'
+- name: testing
+ color: '0366d6'
+ description: Legacy label for test changes; use tests for new pull requests.
+
+# Human-only signal labels: workflows and AI reviewers must never apply these.
+- name: needs-rework
+ color: 'e99695'
+ description: PR needs substantive rework before it can be reviewed in depth
- name: code-ready
color: '006b75'
description: Code looks technically ready; still needs CI + approver. Apply manually — never auto-applied.
diff --git a/.github/release.yml b/.github/release.yml
index 150c5eadca..ec42496002 100644
--- a/.github/release.yml
+++ b/.github/release.yml
@@ -11,12 +11,10 @@ changelog:
labels:
- feature
- enhancement
- - dev-enhancement
- title: 🐛 Bug Fixes
labels:
- bug
- bugfix
- - dev-bugfix
- title: ⚡ Performance Improvements
labels:
- performance
@@ -36,6 +34,7 @@ changelog:
- dependencies
- title: 🧹 Code Quality & Refactoring
labels:
+ - code-quality
- refactoring
- technical-debt
- developer-experience
@@ -67,7 +66,6 @@ changelog:
- title: 📊 Metrics & Analytics
labels:
- metrics
- - benchmark-results
- title: 🔄 Branch Syncs & Automation
labels:
- sync
diff --git a/.github/scripts/combine-ai-reviews.sh b/.github/scripts/combine-ai-reviews.sh
index bc03be63ca..3e0eaeea0b 100755
--- a/.github/scripts/combine-ai-reviews.sh
+++ b/.github/scripts/combine-ai-reviews.sh
@@ -26,14 +26,20 @@
#
# Writes (into <work_dir>):
# comment_body.md - the combined sticky-comment body
-# labels.txt - deduped labels, one per line (may be empty)
+# labels.txt - approved labels to apply, one per line (may be empty)
+# trigger_labels.txt - CI trigger labels to recommend, one per line
+# rejected_labels.json - model-suggested labels rejected by policy
# decision.txt - "pass" or "fail"
# success_count.txt - number of reviewers that produced a usable review
+# And, transiently, requested_labels.jsonl (the per-reviewer suggestion
+# accumulator): removed once the policy filter has read it, on the success
+# path only — an abnormal termination (e.g. the caller's job timing out)
+# can leave it behind, so the workflow's Cleanup step also removes it.
#
# Logs ::group:: sections and debug output to stderr (kept off stdout so the
# output files are the only contract). Exit status is 0 even when every
# reviewer failed — the caller inspects success_count.txt and decides whether
-# to fail the workflow. A non-zero exit means a usage error only.
+# to fail the workflow. A non-zero exit indicates a usage, policy configuration, or assembly error.
set -euo pipefail
@@ -51,11 +57,66 @@ fi
DEBUG_MODE="${DEBUG_MODE:-false}"
HEAD_SHA="${HEAD_SHA:-}"
+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
+AI_LABEL_POLICY_FILE="${AI_LABEL_POLICY_FILE:-$SCRIPT_DIR/../ai-review-label-policy.json}"
+
+# Model output is untrusted. Keep label mutation behind a repository-owned
+# allowlist so a hostile diff cannot create persistent label names, apply
+# human-only/control labels, or seed text that is replayed into future review
+# prompts. A missing or malformed policy is a fail-closed configuration error.
+#
+# Validation reads the policy the same way the filter below does — through
+# --slurpfile, taking $policy[0]. `jq -e FILE` would instead take its exit
+# status from the *last* document in the file, so a two-document file whose
+# first document allows human-only labels would validate clean and then be
+# applied. Requiring exactly one document closes that validate-vs-use gap.
+if ! jq -n --slurpfile policy "$AI_LABEL_POLICY_FILE" -e '
+ ($policy | length) == 1 and
+ ($policy[0] |
+ type == "object" and
+ (.apply | type == "array") and
+ (.recommend | type == "array") and
+ (.aliases | type == "object") and
+ ([.apply[], .recommend[], (.aliases | keys[]), (.aliases[])]
+ | all(type == "string" and length > 0)) and
+ ((.apply | unique | length) == (.apply | length)) and
+ ((.recommend | unique | length) == (.recommend | length)) and
+ (. as $p
+ | [$p.apply[] | . as $label
+ | select($p.recommend | index($label))]
+ | length == 0))
+' >/dev/null; then
+ echo "error: invalid AI label policy: $AI_LABEL_POLICY_FILE" >&2
+ exit 2
+fi
+
+# Model output is unbounded, and .labels_added is the only part of it that is
+# aggregated across reviewers. Two limits keep it away from argv: Linux caps a
+# single execve argument at MAX_ARG_STRLEN (128 KiB), so passing the growing
+# accumulator as `jq --argjson "$ACC"` made jq fail to start once the models
+# had produced ~128 KiB of label text — and under `set -euo pipefail` that
+# aborted the whole script before *any* output file was written, sinking every
+# reviewer and posting no comment at all.
+# 1. MAX_LABELS_* bounds one reviewer's suggestion list. A real review names
+# a handful of labels; anything past these bounds is malformed output and
+# its labels are dropped wholesale — but unlike a non-object response
+# above, only the label channel degrades: the review body is kept, the
+# verdict still counts toward success_count and can still flip
+# decision.txt to "fail", and the drop is reported (see the oversized-
+# reviewer warning below) rather than silently discarding the reviewer.
+# 2. The accumulator lives in a file read with --slurpfile, so even N
+# at-the-limit reviewers can never reach the argv cap.
+MAX_LABELS_PER_REVIEWER=200
+MAX_LABELS_BYTES=16384
COMBINED_REVIEW=""
-ALL_LABELS=""
+# One compact JSON array per reviewer, one per line; --slurpfile reads them
+# back as an array of arrays that the filter concatenates.
+REQUESTED_LABELS_FILE="$WORK_DIR/requested_labels.jsonl"
+: > "$REQUESTED_LABELS_FILE"
ANY_FAIL="false"
SUCCESS_COUNT=0
+OVERSIZED_LABEL_REVIEWERS=0
# Assemble the combined comment in model order. Reviewers are anonymized as
# "Reviewer N" — the model -> number mapping appears only in the (debug) logs
@@ -87,23 +148,52 @@ for i in "${!MODELS[@]}"; do
# out never sets a verdict, so it can never flip the aggregate decision to
# "fail" — only a model that returns a valid "fail" verdict does. Sensitive raw
# output is never written to the comment.
- # Require a JSON *object*: a bare `jq .` accepts any valid JSON, including a
- # top-level string/array/number that a refusing or misbehaving model might
- # emit ("I refuse to review this"). That would pass the gate and then crash
- # the `.review` access below under `set -e`, sinking *every* reviewer and
- # writing no output at all. `type == "object"` rejects non-objects so they
- # degrade to a per-reviewer failure note, preserving the others.
- if [ "$EXIT_CODE" -ne 0 ] || [ -z "$AI_RESPONSE" ] || ! echo "$AI_RESPONSE" | jq -e 'type == "object"' >/dev/null 2>&1; then
+ # Require exactly one JSON *object* document: a bare `jq .` accepts any
+ # valid JSON, including a top-level string/array/number that a refusing or
+ # misbehaving model might emit ("I refuse to review this"), and also takes
+ # its status from the *last* document of a concatenated multi-document
+ # response (`{...}{...}`), so a permissive trailing object would pass this
+ # gate while every earlier document's fields (labels_added included) are
+ # still walked below. `jq -s` slurps the whole response into an array first
+ # so a non-object *and* a multi-document response are both rejected here,
+ # degrading to a per-reviewer failure note and preserving the others.
+ if [ "$EXIT_CODE" -ne 0 ] || [ -z "$AI_RESPONSE" ] || ! echo "$AI_RESPONSE" | jq -es 'length == 1 and (.[0] | type) == "object"' >/dev/null 2>&1; then
echo "⚠️ Reviewer #$REVIEWER_NUM did not return a usable review (exit $EXIT_CODE)" >&2
REVIEW_BODY="_This reviewer could not complete its review (see workflow logs for details)._"
- LABELS=""
+ REVIEW_LABELS_JSON='[]'
else
REVIEW_RAW=$(echo "$AI_RESPONSE" | jq -r '.review // "No review provided"')
# Trim whitespace with tr (the verdict is a single token). The previous
# `| xargs` aborted the entire script on an unbalanced quote in the value,
# which—inside this per-reviewer loop—would sink every reviewer.
DECISION=$(echo "$AI_RESPONSE" | jq -r '.fail_pass_workflow // "uncertain"' | tr -d '[:space:]')
- LABELS=$(echo "$AI_RESPONSE" | jq -r '.labels_added[]? // empty')
+ # Preserve each suggestion as a JSON string until policy filtering. Reading
+ # raw strings line-by-line would turn a single malicious value containing a
+ # newline into two apparently valid label names.
+ REVIEW_LABELS_JSON=$(echo "$AI_RESPONSE" | jq -c \
+ --argjson max_entries "$MAX_LABELS_PER_REVIEWER" \
+ --argjson max_bytes "$MAX_LABELS_BYTES" '
+ if (.labels_added? | type) == "array"
+ and (.labels_added | length) <= $max_entries
+ and (.labels_added | tojson | utf8bytelength) <= $max_bytes
+ then
+ [.labels_added[] | select(type == "string")]
+ else
+ []
+ end
+ ')
+ # Distinguish "no usable labels" from "suggestion list over the bound" so
+ # the drop is reported rather than silent. Both yield [] above.
+ if [ "$REVIEW_LABELS_JSON" = "[]" ] && echo "$AI_RESPONSE" | jq -e \
+ --argjson max_entries "$MAX_LABELS_PER_REVIEWER" \
+ --argjson max_bytes "$MAX_LABELS_BYTES" '
+ (.labels_added? | type) == "array"
+ and (((.labels_added | length) > $max_entries)
+ or ((.labels_added | tojson | utf8bytelength) > $max_bytes))
+ ' >/dev/null 2>&1; then
+ echo "⚠️ Reviewer #$REVIEWER_NUM returned an oversized labels_added list (limit ${MAX_LABELS_PER_REVIEWER} entries / ${MAX_LABELS_BYTES} bytes); all of its label suggestions were dropped" >&2
+ OVERSIZED_LABEL_REVIEWERS=$((OVERSIZED_LABEL_REVIEWERS + 1))
+ fi
SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
[ "$DECISION" = "fail" ] && ANY_FAIL="true"
@@ -124,13 +214,102 @@ for i in "${!MODELS[@]}"; do
# renders (command substitution strips trailing newlines, so the separator
# must precede the heading, not follow the previous body).
COMBINED_REVIEW=$(printf '%s\n\n### 👤 Reviewer %s\n\n%s' "$COMBINED_REVIEW" "$REVIEWER_NUM" "$REVIEW_BODY")
- [ -n "$LABELS" ] && ALL_LABELS=$(printf '%s\n%s' "$ALL_LABELS" "$LABELS")
+ # Append, never re-pass through argv (see MAX_LABELS_* above). printf is a
+ # bash builtin, so no execve happens here regardless of payload size.
+ printf '%s\n' "$REVIEW_LABELS_JSON" >> "$REQUESTED_LABELS_FILE"
echo "::endgroup::" >&2
done
-# Aggregate labels (union across reviewers) and the pass/fail decision (request
-# changes if ANY reviewer did).
-LABELS=$(printf '%s\n' "$ALL_LABELS" | sed '/^[[:space:]]*$/d' | sort -u)
+# Normalize aliases and split model suggestions into ordinary labels that may
+# be applied and CI-trigger labels that are recommendations only. The split
+# exists because those workflows cost real money and wall-clock time (paid
+# browser E2E, full sharded UI matrices, live research runs), so the decision
+# to spend that stays with a maintainer rather than with model output driven by
+# an untrusted diff. A maintainer applying the label also keeps the downstream
+# workflow's normal fork-token and secret restrictions in place.
+#
+# Most of those workflows trigger on `labeled` only, and GitHub does not start
+# a pull_request:labeled run from a label added with GITHUB_TOKEN, so applying
+# them here would also strand them. test:notes is the exception — it triggers
+# on synchronize as well and would re-run on the next push — so do not rely on
+# that mechanism as the safeguard; the cost handoff above is the reason.
+FILTERED_LABELS_JSON=$(jq -cn \
+ --slurpfile requested_docs "$REQUESTED_LABELS_FILE" \
+ --slurpfile policy "$AI_LABEL_POLICY_FILE" '
+ ($requested_docs | add // []) as $requested
+ | $policy[0] as $p
+ | [
+ $requested[]
+ | select(
+ type == "string" and
+ length > 0 and
+ length <= 100 and
+ (test("[[:cntrl:]]") | not)
+ )
+ | ($p.aliases[.] // .)
+ ]
+ | unique as $normalized
+ | {
+ apply: [
+ $normalized[]
+ | . as $label
+ | select($p.apply | index($label))
+ ],
+ recommend: [
+ $normalized[]
+ | . as $label
+ | select($p.recommend | index($label))
+ ],
+ rejected: [
+ $requested[]
+ | . as $original
+ | if (
+ type == "string" and
+ length > 0 and
+ length <= 100 and
+ (test("[[:cntrl:]]") | not)
+ ) then
+ ($p.aliases[.] // .) as $normalized_label
+ | select(
+ (($p.apply | index($normalized_label)) == null) and
+ (($p.recommend | index($normalized_label)) == null)
+ )
+ | $original
+ else
+ $original
+ end
+ ] | unique
+ }
+ | if (.recommend | index("ldr_research")) != null then
+ .recommend |= map(select(. != "ldr_research_static"))
+ else
+ .
+ end
+ ')
+
+rm -f "$REQUESTED_LABELS_FILE"
+
+LABELS=$(printf '%s' "$FILTERED_LABELS_JSON" | jq -r '.apply[]')
+TRIGGER_LABELS=$(printf '%s' "$FILTERED_LABELS_JSON" | jq -r '.recommend[]')
+REJECTED_LABELS_JSON=$(printf '%s' "$FILTERED_LABELS_JSON" | jq -c '.rejected')
+
+if [ -n "$TRIGGER_LABELS" ]; then
+ # Backticks are intentional literal Markdown, not shell expansion.
+ # shellcheck disable=SC2016
+ TRIGGER_BULLETS=$(printf '%s\n' "$TRIGGER_LABELS" | sed 's/^/- `/; s/$/`/')
+ COMBINED_REVIEW=$(printf '%s\n\n### 🧪 Suggested CI\n\nThe AI review recommends these opt-in checks. A maintainer must apply or re-add each label to start its workflow:\n\n%s' \
+ "$COMBINED_REVIEW" "$TRIGGER_BULLETS")
+fi
+
+REJECTED_LABEL_COUNT=$(printf '%s' "$REJECTED_LABELS_JSON" | jq 'length')
+if [ "$REJECTED_LABEL_COUNT" -gt 0 ]; then
+ echo "Ignored $REJECTED_LABEL_COUNT label suggestion(s) that were not allowed by policy." >&2
+fi
+if [ "$OVERSIZED_LABEL_REVIEWERS" -gt 0 ]; then
+ echo "Dropped every label suggestion from $OVERSIZED_LABEL_REVIEWERS reviewer(s) whose labels_added exceeded the size bound." >&2
+fi
+
+# Aggregate pass/fail decision (request changes if ANY usable reviewer did).
if [ "$ANY_FAIL" = "true" ]; then
DECISION="fail"
else
@@ -151,5 +330,7 @@ COMMENT_BODY=$(printf '%s\n\n## 🤖 AI Code Review (%s %s)%s\n\n---\n%s\n\n_Las
printf '%s' "$COMMENT_BODY" > "$WORK_DIR/comment_body.md"
printf '%s' "$LABELS" > "$WORK_DIR/labels.txt"
+printf '%s' "$TRIGGER_LABELS" > "$WORK_DIR/trigger_labels.txt"
+printf '%s' "$REJECTED_LABELS_JSON" > "$WORK_DIR/rejected_labels.json"
printf '%s' "$DECISION" > "$WORK_DIR/decision.txt"
printf '%s' "$SUCCESS_COUNT" > "$WORK_DIR/success_count.txt"
diff --git a/.github/workflows/ai-code-reviewer.yml b/.github/workflows/ai-code-reviewer.yml
index 7b4c5f9959..c933ea9dd2 100644
--- a/.github/workflows/ai-code-reviewer.yml
+++ b/.github/workflows/ai-code-reviewer.yml
@@ -8,10 +8,11 @@ name: AI Code Reviewer
# PR in the repo.
#
# Residual risk accepted: the diff text goes into the LLM prompt, so a
-# hostile diff can try to steer the posted comment or labels (prompt
-# injection). The maintainer-applied label gate plus the advisory-only
-# decision (FAIL_ON_REQUESTED_CHANGES defaults to false) bound that
-# blast radius, and it exists for internal PRs too.
+# hostile diff can try to steer the posted comment or label suggestions
+# (prompt injection). The maintainer-applied label gate, repository-owned
+# label allowlist, and advisory-only decision (FAIL_ON_REQUESTED_CHANGES
+# defaults to false) bound that blast radius, and it exists for internal
+# PRs too.
on:
# zizmor: ignore[dangerous-triggers] — pull_request_target is required so
@@ -131,7 +132,6 @@ jobs:
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO_FULL_NAME: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
- FAIL_ON_REQUESTED_CHANGES: ${{ vars.FAIL_ON_REQUESTED_CHANGES || 'false' }}
DEBUG_MODE: ${{ vars.DEBUG_MODE || 'false' }}
run: |
echo "Running AI code review..."
@@ -196,6 +196,29 @@ jobs:
DECISION="$(cat decision.txt)"
SUCCESS_COUNT="$(cat success_count.txt)"
+ # Surface the suggestions policy dropped on the run summary page, so
+ # a maintainer can see what the model asked for (a missing catalog
+ # entry, a hallucinated name, an attempt at a human-only label)
+ # without opening the job log. The names are model-controlled, so
+ # each one is JSON-string-escaped with `tojson` (that neutralises
+ # any newline) and then fenced in backticks (that neutralises
+ # Markdown/HTML markup — links, images, raw tags — which `tojson`
+ # alone does not escape); any literal backtick already in the name
+ # is stripped first so it cannot break out of that fence. The list
+ # is capped.
+ REJECTED_COUNT="$(jq 'length' rejected_labels.json 2>/dev/null || echo 0)"
+ if [ "$REJECTED_COUNT" -gt 0 ] && [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then
+ {
+ echo "### Suggested but not applied ($REJECTED_COUNT)"
+ echo
+ jq -r '.[:20][] | "- `" + (gsub("`"; "") | tojson) + "`"' rejected_labels.json
+ if [ "$REJECTED_COUNT" -gt 20 ]; then
+ echo "- ... and $((REJECTED_COUNT - 20)) more"
+ fi
+ echo
+ } >> "$GITHUB_STEP_SUMMARY" || true
+ fi
+
# Post (or update) the reviews as a single sticky PR comment. On each
# push we edit the same comment in place instead of stacking a new one
# per push. The hidden marker identifies our comment specifically, so
@@ -224,18 +247,29 @@ jobs:
printf '%s' "$COMMENT_BODY" | gh pr comment "$PR_NUMBER" --repo "$REPO_FULL_NAME" -F -
fi
- # Add labels to PR. Iterate line-by-line (labels.txt is one label per
- # line) rather than word-splitting, so a multi-word label such as
- # "good first issue" is treated as a single label, not three.
+ # Add only repository-approved labels to the PR. The assembly helper
+ # has already normalized aliases and filtered model suggestions
+ # through .github/ai-review-label-policy.json. Unknown labels are
+ # rejected rather than created: arbitrary model-controlled label
+ # names would pollute repository metadata and then be replayed in the
+ # available-label context of future reviews.
+ #
+ # CI trigger suggestions are deliberately absent from labels.txt and
+ # instead appear in the review's "Suggested CI" section. Those
+ # workflows cost real money and wall-clock time (paid browser E2E,
+ # the full sharded UI matrix, live research runs), so the decision to
+ # spend it stays with a maintainer rather than with model output
+ # steered by an untrusted diff.
+ #
+ # Not because the labels would always be inert: most of those
+ # workflows trigger on `labeled` only, and GITHUB_TOKEN-created label
+ # events do not start a pull_request:labeled run — but test:notes
+ # also triggers on `synchronize` while the label is present, so it
+ # *would* run on the next push. The cost handoff is the reason.
echo "Labels to add: $LABELS"
while IFS= read -r label; do
[ -n "$label" ] || continue
echo "Adding label: $label"
- if gh label create "$label" --color "0366d6" --description "Auto-created by AI reviewer" 2>/dev/null; then
- echo "Created new label: $label"
- else
- echo "Label already exists: $label"
- fi
if gh issue edit "$PR_NUMBER" --add-label "$label" 2>/dev/null; then
echo "Successfully added label: $label"
else
@@ -280,7 +314,7 @@ jobs:
echo "✅ AI review completed successfully ($SUCCESS_COUNT/${#MODELS[@]} reviewers)"
- name: Fail Workflow if Requested
- if: env.FAIL_ON_REQUESTED_CHANGES == 'true' && steps.ai-review.outputs.DECISION == 'fail'
+ if: vars.FAIL_ON_REQUESTED_CHANGES == 'true' && steps.ai-review.outputs.DECISION == 'fail'
run: |
echo "❌ AI requested changes and FAIL_ON_REQUESTED_CHANGES is enabled. Failing workflow."
echo "The review has been posted above. Please address the requested changes."
@@ -291,8 +325,12 @@ jobs:
run: |
rm -f diff.txt
# Per-reviewer response/log/exit-code files from the parallel fan-out,
- # plus the assembly helper's output files.
- rm -f resp_*.json err_*.log code_* comment_body.md labels.txt decision.txt success_count.txt
+ # plus the assembly helper's output files. requested_labels.jsonl is
+ # normally removed by the helper itself once the policy filter has
+ # read it (combine-ai-reviews.sh), but that only happens on its
+ # success path — an abnormal termination mid-run (e.g. the job
+ # timing out) can leave it behind, so it is also swept up here.
+ rm -f resp_*.json err_*.log code_* comment_body.md labels.txt trigger_labels.txt rejected_labels.json decision.txt success_count.txt requested_labels.jsonl
# Only remove ai_response.txt if it exists (only created in debug mode)
if [ -f "ai_response.txt" ]; then
rm -f ai_response.txt
diff --git a/.github/workflows/playwright-notes-tests.yml b/.github/workflows/playwright-notes-tests.yml
index 2c3838fd81..489eedc6b9 100644
--- a/.github/workflows/playwright-notes-tests.yml
+++ b/.github/workflows/playwright-notes-tests.yml
@@ -1,6 +1,6 @@
name: Playwright Notes Tests
-# Runs when a PR carries the test:notes / test:ui label. `synchronize` is
+# Runs when a PR carries the test:notes label. `synchronize` is
# in the trigger list so a labeled PR RE-RUNS on every push — with
# `labeled` alone the suite ran exactly once at label time, and later
# commits merged with no notes check at all (the label-time result went
@@ -23,8 +23,7 @@ jobs:
# so pushes to an already-labeled PR re-run the suite.
if: |
github.event_name != 'pull_request' ||
- contains(github.event.pull_request.labels.*.name, 'test:notes') ||
- contains(github.event.pull_request.labels.*.name, 'test:ui')
+ contains(github.event.pull_request.labels.*.name, 'test:notes')
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5579f96d4b..2a97563b96 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -158,7 +158,7 @@ jobs:
# ============================================================================
# Verifies the notes feature (create/edit/delete, mobile-nav Notes-entry
# regression guard) via a real server + Chromium. playwright-notes-tests.yml
- # only runs its job on `pull_request` when labeled test:notes/test:ui — but
+ # only runs its job on `pull_request` when labeled test:notes — but
# its `if:` gates on `github.event_name != 'pull_request'`, which is true
# for this workflow_call (release.yml's own trigger is push/workflow_dispatch,
# never pull_request; workflow_call does not overwrite github.event_name —
diff --git a/.github/workflows/ui-full-shards.yml b/.github/workflows/ui-full-shards.yml
index 0c9b9093ee..15cfeab289 100644
--- a/.github/workflows/ui-full-shards.yml
+++ b/.github/workflows/ui-full-shards.yml
@@ -1,9 +1,9 @@
-name: UI Tests (Full 14 Shards via Label)
+name: UI Tests (Full Shards via Label)
# Triggered by adding the `test:ui-full-shards` label to a PR.
-# Calls docker-tests.yml with strict-mode=true so the sharded ui-tests
-# matrix runs — it's otherwise gated on strict-mode and only fires at
-# release time.
+# Calls docker-tests.yml with strict-mode=true so the complete sharded UI
+# matrix runs — it is otherwise gated on strict-mode and only fires at release
+# time. Avoid embedding the current shard count here because the matrix evolves.
#
# NOTE on duplicated work: docker-tests.yml in strict mode runs its FULL
# job graph (image build, pytest, infra, etc.), so triggering this label
diff --git a/.gitignore b/.gitignore
index f6b84bd6ad..a7bd35c64c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -98,6 +98,7 @@ src/local_deep_research/web/static/css/themes.css
!.github/
!.github/**/*.yml
!.github/**/*.yaml
+!.github/ai-review-label-policy.json
!.github/**/*.md
!.github/**/*.sh
!.github/**/*.py
diff --git a/changelog.d/+label-ai-reviewer.bugfix.md b/changelog.d/+label-ai-reviewer.bugfix.md
new file mode 100644
index 0000000000..f058c5ad71
--- /dev/null
+++ b/changelog.d/+label-ai-reviewer.bugfix.md
@@ -0,0 +1 @@
+Constrain AI review labels to the repository catalog, replace placeholder descriptions, and surface resource-intensive test selections as maintainer-approved recommendations. Label suggestions are accumulated through a file rather than a jq command-line argument, and a per-reviewer size bound rejects an oversized `labels_added` list, so a large model response can no longer abort the review helper before it writes its comment and label files.
diff --git a/docs/AI_Code_Reviewer_Setup.md b/docs/AI_Code_Reviewer_Setup.md
index cb43f3f787..ed2f9aa09a 100644
--- a/docs/AI_Code_Reviewer_Setup.md
+++ b/docs/AI_Code_Reviewer_Setup.md
@@ -56,7 +56,7 @@ minimax/minimax-m3, z-ai/glm-5.2
Notes:
- Separate models with **commas** (spaces around them are fine and trimmed). A space-separated value is treated as a *single* model name and will fail.
- Each model is shown anonymously as **Reviewer 1**, **Reviewer 2**, … (the model→reviewer mapping appears only in the workflow logs), so readers judge the feedback rather than the model.
-- All reviews are collected into one sticky PR comment. Labels are unioned across reviewers; if `FAIL_ON_REQUESTED_CHANGES` is enabled, the workflow fails when **any** reviewer requests changes. This is deliberately "any" rather than a majority vote — a single model catching a real blocker shouldn't be outvoted — and it only takes effect when you opt into `FAIL_ON_REQUESTED_CHANGES` (off by default). A reviewer that errors out (rather than returning a verdict) never counts as a "fail"; it just shows a note in its section.
+- All reviews are collected into one sticky PR comment. Approved label suggestions are unioned across reviewers; unknown and control labels are discarded. If `FAIL_ON_REQUESTED_CHANGES` is enabled, the workflow fails when **any** reviewer requests changes. This is deliberately "any" rather than a majority vote — a single model catching a real blocker shouldn't be outvoted — and it only takes effect when you opt into `FAIL_ON_REQUESTED_CHANGES` (off by default). A reviewer that errors out (rather than returning a verdict) never counts as a "fail"; it just shows a note in its section.
- Models run **in parallel**, so the job's wall-clock is the slowest single review rather than the sum. Each model still makes its own set of GitHub API calls for context, so a very long list means many concurrent calls; two or three models are well within limits.
## Usage
@@ -71,6 +71,38 @@ To trigger an AI review on a PR:
The review will automatically start and post results as a comment when complete.
+### Label suggestions and opt-in CI
+
+The reviewer may apply semantic labels from the repository-owned allowlist in
+`.github/ai-review-label-policy.json`. It cannot create new labels or apply
+human-only, lifecycle, or workflow-control labels.
+
+Resource-intensive test and research labels are handled as recommendations.
+They appear under **Suggested CI** in the review comment, and a maintainer then
+applies or re-adds the appropriate label to start the workflow:
+
+- `test:puppeteer` — paid Puppeteer browser E2E
+- `test:notes` — focused Notes Playwright E2E
+- `test:ui-full-shards` — complete sharded UI matrix plus strict Docker CI
+- `ldr_research` / `ldr_research_static` — PR-diff or fixed-query research
+
+The handoff exists because each of these workflows spends paid API quota and
+CI wall-clock, so the decision to start one stays with a maintainer rather than
+with model output steered by the PR diff. It also preserves GitHub's normal
+read-only-token and secret restrictions for fork PRs.
+
+Do not reach for `GITHUB_TOKEN` label application as a shortcut. GitHub does
+not start a second workflow from a label event created with the first
+workflow's `GITHUB_TOKEN`, so `test:puppeteer`, `test:ui-full-shards`, and the
+`ldr_research` selectors (all `labeled`-only triggers) would simply be stranded
+— but `test:notes` also triggers on `synchronize`, so applying it here *would*
+run the suite on the next push. The cost handoff, not the token behavior, is
+what makes this the right split.
+
+`test:notes` does not require repository secrets. Puppeteer, LDR research, and
+the strict UI wrapper may lack credentials or write permissions on fork PRs;
+do not replace those protections with a privileged checkout of fork code.
+
### Re-running Reviews
To re-run the AI review after making changes:
diff --git a/tests/ci/test_combine_ai_reviews.py b/tests/ci/test_combine_ai_reviews.py
index f276e744e0..ebc1fdf732 100644
--- a/tests/ci/test_combine_ai_reviews.py
+++ b/tests/ci/test_combine_ai_reviews.py
@@ -100,6 +100,10 @@ def run_combine(work_dir, reviewers, *, head_sha="abc1234def", debug=False):
"models": models,
"comment": (work_dir / "comment_body.md").read_text(),
"labels": (work_dir / "labels.txt").read_text(),
+ "trigger_labels": (work_dir / "trigger_labels.txt").read_text(),
+ "rejected_labels": json.loads(
+ (work_dir / "rejected_labels.json").read_text()
+ ),
"decision": (work_dir / "decision.txt").read_text(),
"success_count": (work_dir / "success_count.txt").read_text(),
"stderr": result.stderr,
@@ -132,7 +136,9 @@ def test_two_reviewers_pass_and_fail(tmp_path):
assert "Race condition." in c
# Aggregation: any fail -> fail; labels unioned + sorted; both succeeded.
assert out["decision"] == "fail"
- assert out["labels"].split() == ["bug", "enhancement"]
+ # `bug` is issue-only in this repository; PR reviews canonicalize it to
+ # the PR-specific `bugfix` label.
+ assert out["labels"].split() == ["bugfix", "enhancement"]
assert out["success_count"] == "2"
@@ -216,7 +222,321 @@ def test_labels_are_unioned_and_deduped(tmp_path):
},
],
)
- assert out["labels"].split() == ["bug", "enhancement", "security"]
+ assert out["labels"].split() == ["bugfix", "enhancement", "security"]
+
+
+def test_label_policy_separates_ci_recommendations_from_applied_labels(
+ tmp_path,
+):
+ out = run_combine(
+ tmp_path,
+ [
+ {
+ "code": 0,
+ "resp": make_response(
+ "UI changes.",
+ "pass",
+ ["test:e2e", "test:ui-full-shards", "security"],
+ ),
+ }
+ ],
+ )
+
+ assert out["labels"].split() == ["security"]
+ # The legacy alias is canonicalized before presenting the recommendation.
+ assert out["trigger_labels"].split() == [
+ "test:puppeteer",
+ "test:ui-full-shards",
+ ]
+ assert "### 🧪 Suggested CI" in out["comment"]
+ assert "- `test:puppeteer`" in out["comment"]
+ assert "A maintainer must apply or re-add each label" in out["comment"]
+
+
+def test_label_policy_rejects_unknown_human_only_and_control_char_labels(
+ tmp_path,
+):
+ control_label = "security\nfeature"
+ out = run_combine(
+ tmp_path,
+ [
+ {
+ "code": 0,
+ "resp": make_response(
+ "Hostile suggestions.",
+ "pass",
+ [
+ "security",
+ "code-ready",
+ "code-ready-preliminary",
+ "invented-by-model",
+ control_label,
+ ],
+ ),
+ }
+ ],
+ )
+
+ assert out["labels"].split() == ["security"]
+ assert out["trigger_labels"] == ""
+ assert out["rejected_labels"] == [
+ "code-ready",
+ "code-ready-preliminary",
+ "invented-by-model",
+ control_label,
+ ]
+ # A newline inside one untrusted suggestion must not split into two allowed
+ # labels (`security` + `feature`).
+ assert "feature" not in out["labels"].split()
+
+
+def test_entry_count_bound_pins_the_label_flood(tmp_path):
+ """A flood past MAX_LABELS_PER_REVIEWER alone is dropped; the run still
+ produces output.
+
+ 201 short entries trips only the entry-count bound: the whole array is a
+ few hundred bytes, nowhere near MAX_LABELS_BYTES. Remove
+ MAX_LABELS_PER_REVIEWER (keep MAX_LABELS_BYTES) and this fixture is no
+ longer oversized by either bound, so it fails on ``rejected_labels`` —
+ the flood's 201 junk names get filtered and unioned in normally instead
+ of being dropped wholesale, and the "oversized" stderr warning
+ disappears. See test_byte_size_bound_pins_the_label_flood for the
+ complementary fixture that pins MAX_LABELS_BYTES alone.
+ """
+ flood = [f"flood-{i:03d}" for i in range(201)]
+ assert len(flood) > 200, "fixture must exceed MAX_LABELS_PER_REVIEWER alone"
+ assert len(json.dumps(flood)) < 16384, (
+ "fixture must stay under MAX_LABELS_BYTES so only the entry-count "
+ "bound is pinned"
+ )
+
+ out = run_combine(
+ tmp_path,
+ [
+ {"code": 0, "resp": make_response("Flooding.", "pass", flood)},
+ {
+ "code": 0,
+ "resp": make_response("Real review.", "pass", ["security"]),
+ },
+ ],
+ )
+
+ # The legitimate reviewer is unaffected: the flood is one reviewer's
+ # malformed output, exactly like a non-object response.
+ assert out["labels"].split() == ["security"]
+ assert out["comment"].startswith("<!-- ai-code-review:sticky -->")
+ assert "Real review." in out["comment"]
+ assert out["success_count"] == "2"
+ assert out["decision"] == "pass"
+ # Dropped wholesale, so the flood is not echoed back through the rejected
+ # list either (which is written into the run summary).
+ assert out["rejected_labels"] == []
+ assert "oversized labels_added" in out["stderr"]
+
+
+def test_byte_size_bound_pins_the_label_flood(tmp_path):
+ """A flood past MAX_LABELS_BYTES alone is dropped; the run still produces
+ output.
+
+ 30 entries of 1 KB each trips only the byte-size bound: 30 entries is far
+ under MAX_LABELS_PER_REVIEWER (200), but ~30 KB of text is well past
+ MAX_LABELS_BYTES (16 KiB). This is the bound that matters most for the
+ run-summary path (N7): with only the entry-count bound in force, a
+ handful of very large entries could still push tens of megabytes into
+ $GITHUB_STEP_SUMMARY. Remove MAX_LABELS_BYTES (keep
+ MAX_LABELS_PER_REVIEWER) and this fixture is no longer oversized by
+ either bound, so it fails the same way the entry-count test does when its
+ own bound is removed.
+ """
+ flood = [f"flood-{i:03d}-" + ("x" * 1000) for i in range(30)]
+ assert len(flood) < 200, "fixture must stay under MAX_LABELS_PER_REVIEWER"
+ assert len(json.dumps(flood)) > 16384, (
+ "fixture must exceed MAX_LABELS_BYTES so only the byte-size bound is "
+ "pinned"
+ )
+
+ out = run_combine(
+ tmp_path,
+ [
+ {"code": 0, "resp": make_response("Flooding.", "pass", flood)},
+ {
+ "code": 0,
+ "resp": make_response("Real review.", "pass", ["security"]),
+ },
+ ],
+ )
+
+ assert out["labels"].split() == ["security"]
+ assert out["comment"].startswith("<!-- ai-code-review:sticky -->")
+ assert "Real review." in out["comment"]
+ assert out["success_count"] == "2"
+ assert out["decision"] == "pass"
+ assert out["rejected_labels"] == []
+ assert "oversized labels_added" in out["stderr"]
+
+
+def test_many_reviewers_under_the_bound_do_not_overflow_argv(tmp_path):
+ """The accumulator must never be an execve argument, bound or no bound.
+
+ The per-reviewer bound alone is not enough: ten reviewers each staying
+ *under* it still add up to ~145 KB, past MAX_ARG_STRLEN. Put the
+ accumulation back on ``jq --argjson "$ACC"`` and this test fails with
+ returncode 126 and "Argument list too long"; the file-based --slurpfile
+ accumulator is what makes the total size irrelevant.
+ """
+
+ def suggestions(reviewer):
+ return ["b" * 66 + f"{reviewer}{i:03d}" for i in range(199)]
+
+ per_reviewer = len(json.dumps(suggestions(0), separators=(",", ":")))
+ assert per_reviewer < 16384, "each reviewer must stay under the size bound"
+ assert per_reviewer * 10 > 131072, "the total must exceed MAX_ARG_STRLEN"
+
+ reviewers = [
+ {"code": 0, "resp": make_response(f"r{n}", "pass", suggestions(n))}
+ for n in range(9)
+ ]
+ reviewers.append(
+ {
+ "code": 0,
+ "resp": make_response(
+ "Real review.", "pass", suggestions(9)[:198] + ["security"]
+ ),
+ }
+ )
+
+ out = run_combine(tmp_path, reviewers)
+
+ assert out["labels"].split() == ["security"]
+ assert "Real review." in out["comment"]
+ assert out["success_count"] == "10"
+ assert len(out["rejected_labels"]) == 199 * 10 - 1
+
+
+def test_label_suggestions_at_the_size_bound_are_still_policy_filtered(
+ tmp_path,
+):
+ # The bound must reject only floods. A 200-entry list — far beyond any real
+ # review, still well under the argv cap — is filtered normally rather than
+ # discarded, so tightening the bound to something a genuine review could
+ # hit fails here.
+ suggestions = [f"invented-{i:03d}" for i in range(199)] + ["security"]
+ out = run_combine(
+ tmp_path,
+ [{"code": 0, "resp": make_response("Many.", "pass", suggestions)}],
+ )
+
+ assert out["labels"].split() == ["security"]
+ assert len(out["rejected_labels"]) == 199
+ assert "oversized labels_added" not in out["stderr"]
+
+
+def test_multi_document_label_policy_is_rejected(tmp_path):
+ """Validation must read the same document the filter applies.
+
+ ``jq -e FILE`` takes its exit status from the *last* document in the file,
+ while the filter reads ``$policy[0]`` — the first. A two-document file whose
+ first document allows human-only labels therefore validated clean and was
+ then applied. Revert the validator to ``jq -e FILE`` and this test fails:
+ the helper exits 0 and writes ``code-ready`` into labels.txt.
+ """
+ permissive = {
+ "apply": ["security", "code-ready"],
+ "recommend": [],
+ "aliases": {},
+ }
+ strict = {"apply": ["security"], "recommend": [], "aliases": {}}
+ policy_path = tmp_path / "policy.json"
+ policy_path.write_text(f"{json.dumps(permissive)}\n{json.dumps(strict)}\n")
+
+ (tmp_path / "code_0").write_text("0")
+ (tmp_path / "resp_0.json").write_text(
+ make_response("x", "pass", ["security", "code-ready"])
+ )
+ (tmp_path / "err_0.log").write_text("")
+ result = subprocess.run(
+ ["bash", str(SCRIPT), str(tmp_path), "model"],
+ capture_output=True,
+ text=True,
+ env={
+ "AI_LABEL_POLICY_FILE": str(policy_path),
+ "PATH": os.environ["PATH"],
+ },
+ )
+
+ assert result.returncode == 2
+ assert "invalid AI label policy" in result.stderr
+ assert not (tmp_path / "labels.txt").exists()
+
+
+def test_label_policy_normalizes_legacy_pr_labels(tmp_path):
+ out = run_combine(
+ tmp_path,
+ [
+ {
+ "code": 0,
+ "resp": make_response(
+ "Legacy labels.",
+ "pass",
+ ["bug", "testing", "code-quality"],
+ ),
+ }
+ ],
+ )
+
+ assert out["labels"].split() == ["bugfix", "code-quality", "tests"]
+ assert out["rejected_labels"] == []
+
+
+def test_full_research_recommendation_wins_over_static(tmp_path):
+ out = run_combine(
+ tmp_path,
+ [
+ {
+ "code": 0,
+ "resp": make_response(
+ "Research requested.",
+ "pass",
+ ["ldr_research_static", "ldr_research"],
+ ),
+ }
+ ],
+ )
+
+ assert out["trigger_labels"].split() == ["ldr_research"]
+ assert "ldr_research_static" not in out["comment"]
+
+
+ "policy",
+ [
+ None,
+ {},
+ {
+ "apply": ["security"],
+ "recommend": ["security"],
+ "aliases": {},
+ },
+ ],
+ ids=["missing", "malformed", "overlapping-sets"],
+)
+def test_missing_or_invalid_label_policy_fails_closed(tmp_path, policy):
+ policy_path = tmp_path / "policy.json"
+ if policy is not None:
+ policy_path.write_text(json.dumps(policy))
+
+ result = subprocess.run(
+ ["bash", str(SCRIPT), str(tmp_path), "model"],
+ capture_output=True,
+ text=True,
+ env={
+ "AI_LABEL_POLICY_FILE": str(policy_path),
+ "PATH": os.environ["PATH"],
+ },
+ )
+
+ assert result.returncode == 2
+ assert "invalid AI label policy" in result.stderr
def test_model_names_never_leak_into_comment(tmp_path):
@@ -281,7 +601,48 @@ def test_valid_json_non_object_does_not_sink_other_reviewers(tmp_path):
assert "Real review." in c
assert c.count("could not complete its review") == 2
assert out["success_count"] == "1"
- assert out["labels"].split() == ["bug"]
+ assert out["labels"].split() == ["bugfix"]
+
+
+def test_multi_document_review_response_is_rejected(tmp_path):
+ """A concatenated multi-document response must not bypass the object gate.
+
+ `jq -e 'type == "object"'` takes its exit status from the *last* JSON
+ document in the stream, so a two-document response `{...}{...}` — each
+ document individually a well-formed, in-bounds object — passed the old
+ gate and then had every document's `labels_added` walked and appended to
+ the accumulator, silently doubling (or smuggling) label suggestions past
+ the per-reviewer bound. Revert the `jq -es 'length == 1 and ...'` guard to
+ the bare `jq -e 'type == "object"'` and this fails: `security` reaches
+ labels.txt from a reviewer that should have been rejected outright.
+ """
+ doc1 = json.loads(make_response("First doc.", "pass", ["security"]))
+ doc2 = json.loads(make_response("Second doc.", "fail", ["code-ready"]))
+ multi_doc_resp = json.dumps(doc1) + json.dumps(doc2)
+
+ out = run_combine(
+ tmp_path,
+ [
+ {"code": 0, "resp": multi_doc_resp},
+ {
+ "code": 0,
+ "resp": make_response("Real review.", "pass", ["bug"]),
+ },
+ ],
+ )
+
+ c = out["comment"]
+ assert "could not complete its review" in c
+ assert "Real review." in c
+ assert out["success_count"] == "1"
+ # No label from either document of the rejected multi-document response
+ # reaches the applied set or even the rejected-suggestions list.
+ assert out["labels"].split() == ["bugfix"]
+ assert "security" not in out["rejected_labels"]
+ assert "code-ready" not in out["rejected_labels"]
+ # The rejected reviewer's (fail-verdict) document must not flip the
+ # aggregate decision either — it never counted as a usable review.
+ assert out["decision"] == "pass"
def test_weird_verdict_string_does_not_crash(tmp_path):
@@ -335,7 +696,7 @@ def test_mixed_pass_fail_error_aggregation(tmp_path):
# labels union only from successful reviewers; exactly one failure note.
assert out["success_count"] == "2"
assert out["decision"] == "fail"
- assert out["labels"].split() == ["bug", "enhancement"]
+ assert out["labels"].split() == ["bugfix", "enhancement"]
assert out["comment"].count("could not complete its review") == 1
@@ -387,7 +748,7 @@ def test_four_reviewers_keep_order(tmp_path):
def test_usage_errors_exit_nonzero(tmp_path):
- # The script's only non-zero exits: bad work_dir and zero model args.
+ # Usage errors fail before review assembly or label-policy output.
env = {**os.environ}
no_dir = subprocess.run(
["bash", str(SCRIPT), str(tmp_path / "does-not-exist"), "m"],
diff --git a/tests/ci/test_label_workflow_contracts.py b/tests/ci/test_label_workflow_contracts.py
new file mode 100644
index 0000000000..c83167ce80
--- /dev/null
+++ b/tests/ci/test_label_workflow_contracts.py
@@ -0,0 +1,339 @@
+"""Contracts for repository labels and label-driven workflows.
+
+These tests keep the declarative catalog, PR triage, AI-review policy, and
+label-triggered checks from drifting apart. They intentionally require no
+GitHub API access.
+"""
+
+import json
+import re
+from itertools import chain
+from pathlib import Path
+
+import yaml
+
+
+ROOT = Path(__file__).resolve().parents[2]
+LABELS_PATH = ROOT / ".github" / "labels.yml"
+POLICY_PATH = ROOT / ".github" / "ai-review-label-policy.json"
+RELEASE_PATH = ROOT / ".github" / "release.yml"
+TRIAGE_PATH = ROOT / ".github" / "workflows" / "pr-triage.yml"
+AI_REVIEW_PATH = ROOT / ".github" / "workflows" / "ai-code-reviewer.yml"
+
+
+def _catalog():
+ entries = yaml.safe_load(LABELS_PATH.read_text())
+ return {entry["name"]: entry for entry in entries}, entries
+
+
+def _policy():
+ return json.loads(POLICY_PATH.read_text())
+
+
+def _sections():
+ """Map each labels.yml section header to the label names declared under it.
+
+ Sections are the `#` comment blocks in the file; a blank line ends one. The
+ grouping is what lets the tests below assert a *property* of a section
+ ("nothing a human or a workflow owns is AI-selectable") instead of freezing
+ a list of names that silently goes stale when a label is added.
+ """
+ sections = {}
+ header = None
+ pending = []
+ for line in LABELS_PATH.read_text().splitlines():
+ stripped = line.strip()
+ if stripped.startswith("#"):
+ pending.append(stripped.lstrip("#").strip())
+ elif not stripped:
+ pending = []
+ elif stripped.startswith("- name:"):
+ if pending:
+ header = " ".join(pending)
+ pending = []
+ name = yaml.safe_load(stripped[len("- name:") :].strip())
+ sections.setdefault(header, []).append(name)
+ return sections
+
+
+def _labels_in_sections(*keys):
+ sections = _sections()
+ found = set()
+ for key in keys:
+ matching = [
+ names
+ for header, names in sections.items()
+ if header and key in header
+ ]
+ assert matching, (
+ f"labels.yml has no section whose header mentions {key!r}"
+ )
+ for names in matching:
+ found.update(names)
+ return found
+
+
+def _label_trigger_set():
+ """Labels that any workflow uses to decide whether to run."""
+ referenced = set()
+ for path in (ROOT / ".github" / "workflows").glob("*.yml"):
+ text = path.read_text()
+ referenced.update(
+ re.findall(r"github\.event\.label\.name\s*==\s*'([^']+)'", text)
+ )
+ referenced.update(
+ re.findall(
+ r"contains\(github\.event\.pull_request\.labels\.\*\.name,\s*'([^']+)'\)",
+ text,
+ )
+ )
+ return referenced
+
+
+def test_label_catalog_is_valid_and_has_no_placeholder_descriptions():
+ catalog, entries = _catalog()
+
+ assert len(catalog) == len(entries), "label names must be unique"
+ for name, entry in catalog.items():
+ assert re.fullmatch(r"[0-9a-fA-F]{6}", entry["color"]), name
+ assert entry["description"].strip(), name
+ assert len(entry["description"]) <= 100, name
+ assert entry["description"] != "Auto-created by AI reviewer", name
+
+
+def test_every_pr_triage_label_is_declared():
+ catalog, _ = _catalog()
+ workflow = TRIAGE_PATH.read_text()
+
+ topic_labels = set(re.findall(r",\s*'([^']+)'\],", workflow))
+ state_labels = set(
+ re.findall(
+ r"(?:labels\.push|removeLabel|current\.includes)\('([^']+)'\)",
+ workflow,
+ )
+ )
+ state_labels.update(re.findall(r"addLabels\(\['([^']+)'\]\)", workflow))
+ referenced = topic_labels | state_labels
+
+ assert referenced
+ assert referenced <= catalog.keys(), referenced - catalog.keys()
+
+
+def test_ai_label_policy_only_uses_declared_labels():
+ catalog, _ = _catalog()
+ policy = _policy()
+ apply = set(policy["apply"])
+ recommend = set(policy["recommend"])
+ aliases = policy["aliases"]
+ referenced = apply | recommend | set(aliases) | set(aliases.values())
+
+ assert referenced <= catalog.keys(), referenced - catalog.keys()
+ assert not (apply & recommend)
+
+
+def test_every_catalog_label_belongs_to_exactly_one_section():
+ # Safety net for _sections()'s line-prefix scan: it keys off the literal
+ # `- name:` prefix, so a label whose YAML fields are reordered (a
+ # perfectly valid `- color: ...` / `name: ...` block) or otherwise fails
+ # to match is silently dropped from every section instead of raising.
+ # Any test built on top of _sections()/_labels_in_sections() (below) would
+ # then just see one fewer label without noticing. Asserting totality here
+ # means that drop always fails loudly, in one place, by name.
+ catalog, _ = _catalog()
+ assert set(chain(*_sections().values())) == catalog.keys()
+
+
+def test_ai_label_policy_excludes_human_and_workflow_control_state():
+ # Inverted derivation: forbidden is *everything in the catalog that is
+ # not* in a section the AI reviewer is explicitly allowed to select from,
+ # rather than an enumeration of the sections that are off-limits. That
+ # makes "forbidden" the safe default — a label under a new or renamed
+ # section (a header this test has never heard of) lands in forbidden
+ # until someone deliberately adds its section to the allowlist below,
+ # instead of silently escaping the check the way an enumerated forbidden
+ # list would (a stale name — there used to be an undeclared
+ # `code-ready-preliminary` here — could also sit in that list doing
+ # nothing).
+ catalog, _ = _catalog()
+ policy = _policy()
+ selectable = set(policy["apply"]) | set(policy["recommend"])
+ ai_selectable = _labels_in_sections(
+ "PR topic labels",
+ "Semantic PR labels the AI reviewer may apply",
+ "AI-reviewer recommendations for opt-in",
+ )
+ forbidden = catalog.keys() - ai_selectable
+
+ # Guard against the derivation silently collapsing to a near-empty set.
+ assert len(forbidden) >= 17, sorted(forbidden)
+ assert {"code-ready", "needs-rework", "ai_code_review"} <= forbidden
+ assert selectable.isdisjoint(forbidden), selectable & forbidden
+
+
+def test_ai_reviewer_never_creates_model_suggested_labels():
+ workflow = AI_REVIEW_PATH.read_text()
+
+ assert "gh label create" not in workflow
+ assert "Auto-created by AI reviewer" not in workflow
+ assert ".github/ai-review-label-policy.json" in workflow
+
+
+def test_pull_request_target_reviewer_keeps_the_trusted_checkout_invariant():
+ # Structural, not textual, but narrowly scoped: this covers actions/
+ # checkout's `with.ref` and `with.persist-credentials` only. A textual
+ # search for one spelling of the head ref missed the others
+ # (`github.head_ref`, `refs/pull/N/merge`, a pre-fetched `origin/pr-head`,
+ # a quoted expression); asserting that no `ref:` is pinned at all catches
+ # every spelling of *that shape* — an actions/checkout step pinning a ref —
+ # including ones nobody has thought of yet. A deliberate literal base ref
+ # would be safe but still has to come through here. It does NOT catch a
+ # `run:` step doing its own `git checkout` of the fetched PR-head ref (the
+ # second assertion below covers exactly that one shape) or a `uses:`-only
+ # job with no `steps:` at all.
+ workflow = yaml.safe_load(AI_REVIEW_PATH.read_text())
+ # PyYAML resolves the bare `on:` key to the boolean True.
+ triggers = workflow.get("on", workflow.get(True))
+ assert "pull_request_target" in triggers
+
+ checkouts = [
+ step
+ for job in workflow["jobs"].values()
+ for step in job.get("steps", [])
+ if str(step.get("uses", "")).startswith("actions/checkout@")
+ ]
+
+ assert checkouts, "the reviewer must check out the trusted base branch"
+ for step in checkouts:
+ options = step.get("with") or {}
+ assert "ref" not in options, (
+ f"checkout step {step.get('name')!r} pins ref: {options.get('ref')!r}; "
+ "pull_request_target must keep its default (base branch) checkout "
+ "so fork-controlled files are never executed with secrets in scope"
+ )
+ assert options.get("persist-credentials") is False, step.get("name")
+
+ # The PR head is legitimately fetched (as data, via `git fetch ...
+ # refs/pull/$PR_NUMBER/head`) for the diff; it must never also be checked
+ # out. Revert: replace the `git fetch` + `git diff origin/$BASE_REF...
+ # origin/pr-head` pair with `git checkout origin/pr-head` (or any `git
+ # checkout` of a `refs/pull/...` ref) in a `run:` step and this fails.
+ reviewer_job = workflow["jobs"]["comprehensive-review"]
+ for step in reviewer_job.get("steps", []):
+ run = step.get("run")
+ if not isinstance(run, str):
+ continue
+ for line in run.splitlines():
+ assert not (
+ "git checkout" in line
+ and ("origin/pr-head" in line or "refs/pull/" in line)
+ ), (
+ f"step {step.get('name')!r} run line checks out a PR head ref: {line!r}"
+ )
+
+
+def test_label_triggered_workflows_only_reference_declared_labels():
+ catalog, _ = _catalog()
+ referenced = _label_trigger_set()
+
+ assert referenced <= catalog.keys(), referenced - catalog.keys()
+ assert "test:notes" in referenced
+ assert "test:ui" not in referenced
+
+
+def test_no_workflow_trigger_label_is_ai_applicable():
+ """The central invariant of the AI label policy.
+
+ Every label that decides whether some workflow runs must stay out of
+ `apply` — that array is what the reviewer writes straight onto the PR with
+ `gh issue edit --add-label`, from output steered by an untrusted diff.
+ `recommend` is the correct home for them: it only prints a suggestion.
+ Move `test:notes` from `recommend` to `apply` and this test fails, where
+ every other contract here still passes.
+ """
+ policy = _policy()
+ triggers = _label_trigger_set()
+
+ assert triggers, "no label-triggered workflows found — the sweep broke"
+ assert triggers.isdisjoint(policy["apply"]), triggers & set(policy["apply"])
+
+
+def test_rejected_label_suggestions_reach_the_run_summary():
+ # Structural: pulled from this one step's parsed `run:` string, not a
+ # `workflow.index()` window over the whole file — that whole-file version
+ # both fails spuriously if any *earlier* step also writes to
+ # $GITHUB_STEP_SUMMARY and would pass just as well if the block moved
+ # into an unrelated step. The helper writes rejected_labels.json, but only
+ # a count ever reached stderr, so a maintainer could not see *which*
+ # suggestions were dropped without digging through the job log. Delete
+ # the summary block, or wrap it in a constant-false guard
+ # (`if false; then ... fi`) so it can never run, and this fails.
+ workflow = yaml.safe_load(AI_REVIEW_PATH.read_text())
+ job = workflow["jobs"]["comprehensive-review"]
+ step = next(step for step in job["steps"] if step.get("id") == "ai-review")
+ run = step.get("run", "")
+
+ assert "GITHUB_STEP_SUMMARY" in run, (
+ "the reviewer job must write the dropped suggestions somewhere a "
+ "maintainer sees without opening the job log"
+ )
+ assert "rejected_labels.json" in run
+ assert "Suggested but not applied" in run
+ assert "if false" not in run, (
+ "the summary block must not be dead-guarded behind a constant-false "
+ "condition"
+ )
+
+
+def test_release_categories_only_reference_declared_labels():
+ catalog, _ = _catalog()
+ release_config = yaml.safe_load(RELEASE_PATH.read_text())
+ referenced = {
+ label
+ for category in release_config["changelog"]["categories"]
+ for label in category["labels"]
+ if label != "*"
+ }
+
+ assert referenced <= catalog.keys(), referenced - catalog.keys()
+
+
+def test_ci_recommendation_descriptions_explain_the_human_handoff():
+ catalog, _ = _catalog()
+ policy = _policy()
+
+ for name in policy["recommend"]:
+ description = catalog[name]["description"]
+ assert "AI reviewer may recommend" in description, name
+ assert "apply or re-add" in description, name
+
+
+def test_legacy_aliases_point_to_canonical_labels():
+ policy = _policy()
+
+ assert policy["aliases"]["bug"] == "bugfix"
+ assert policy["aliases"]["testing"] == "tests"
+ assert policy["aliases"]["test:e2e"] == "test:puppeteer"
+
+
+def test_requested_changes_option_is_visible_to_the_failure_step():
+ workflow = yaml.safe_load(AI_REVIEW_PATH.read_text())
+ job = workflow["jobs"]["comprehensive-review"]
+ step = next(
+ step
+ for step in job["steps"]
+ if step.get("name") == "Fail Workflow if Requested"
+ )
+ condition = step["if"]
+ option = "FAIL_ON_REQUESTED_CHANGES"
+ # A flag declared on a sibling step is not visible here. Both a direct
+ # repository variable and a workflow/job/this-step env binding are valid.
+ references = re.findall(rf"\b(env|vars)\.{option}\b", condition)
+ assert references, "failure must remain an explicit configured opt-in"
+ available_env = {
+ **workflow.get("env", {}),
+ **job.get("env", {}),
+ **step.get("env", {}),
+ }
+ if "env" in references:
+ assert option in available_env, "failure flag is scoped to another step"
+ assert "steps.ai-review.outputs.DECISION" in condition