Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Require PR disclosures, earlier issues, and a five-PR limit (#21)
Elevatormusic31d6448a5ea5
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 24a0a52..0a3ce35 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -8,6 +8,17 @@ body:Complete each section. Use `unknown`, `not run`, or `not applicable` with a short reason when needed; do not guess. See [CONTRIBUTING.md](https://github.com/Elevatormusic/hermes-warm-compaction/blob/main/CONTRIBUTING.md).Use synthetic messages. Do not paste real or private histories, summaries, full configs, raw requests, credentials, header/query values, account identifiers, or private local paths. Clearly label synthetic fixtures, synthetic summaries, and fake keys or option values used for tests. Do not enable full request dumps to complete this report. Review all output before sharing it. For a security problem, use [private reporting](https://github.com/Elevatormusic/hermes-warm-compaction/security/advisories/new).These fields reduce follow-up requests. A new problem can still need more checks. No production cache reset or model deployment change is required.+ - type: textarea+ id: ai_assistance+ attributes:+ label: AI agent use+ description: If an AI agent helped diagnose the problem or write code, list every harness, exact model, and task. A harness is the app or tool that ran the agent. Otherwise write exactly No AI agent used. Do not include private paths, configs, credentials, or conversations.+ placeholder: |+ Harness:+ Model:+ Work:+ validations:+ required: true- type: textareaid: behaviorattributes:diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 97cb79b..4842bd0 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -2,6 +2,17 @@ name: Feature requestdescription: Propose a change or a new capability.labels: ["enhancement"]body:+ - type: textarea+ id: ai_assistance+ attributes:+ label: AI agent use+ description: If an AI agent helped diagnose the problem or write code, list every harness, exact model, and task. A harness is the app or tool that ran the agent. Otherwise write exactly No AI agent used. Do not include private paths, configs, credentials, or conversations.+ placeholder: |+ Harness:+ Model:+ Work:+ validations:+ required: true- type: textareaid: problemattributes:diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 249d229..5f775ee 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -1,30 +1,42 @@## Problem and change-<!-- Link the issue, or explain why there is none. Give the concrete trigger and before/after behavior. For a bug fix without a complete linked report, include applicable diagnostic fields from CONTRIBUTING.md. -->+<!-- Each author can have at most five open PRs in this repository, including drafts. The new PR counts toward the limit. Closed or merged PRs do not count. The limit applies to Elevatormusic too. An issue is required for every new PR, including drafts, except for a PR authored by Elevatormusic (name is not case-sensitive). Only that author can omit the issue line. AI agent disclosure and the test checkbox are still required. Open the issue first, or use an existing issue for the same change. Replace the line below with Closes #123, Fixes #123, or Resolves #123. The issue must be in this repository and older than this PR. Keep the line outside comments and code blocks. A PR without a required valid earlier issue fails the policy check. Give the concrete trigger and before/after behavior. For a bug fix without a complete linked report, include applicable diagnostic fields from CONTRIBUTING.md. -->++Closes #-Issue:Trigger and before/after:## Scope<!-- State the files/components changed, why they are needed, and any limits or risks. Explain any README Limits or CHANGELOG update that is needed for a behavior change. Use documented Hermes plugin APIs only: no host patch, compressor subclass, or runtime wrapping. -->+## AI agent use++<!-- If an AI agent helped diagnose the problem or write code, list every harness, exact model, and task. A harness is the app or tool that ran the agent. Use plain Harness:, Model:, and Work: lines for each agent, outside comments and code blocks. Start each required line at the left margin, with no leading spaces. Put a blank line after any preceding list or quote. If no AI agent was used, write exactly No AI agent used. Do not guess a model. Do not include private paths, configs, credentials, or conversations. -->+## Check results-<!-- Give the exact command and outcome for each applicable check: passed, failed, skipped, or unavailable. Explain every skipped or unavailable check. A document-only change needs link, form schema (when applicable), and diff checks; it needs no code regression test or model/server details. CI unit and lint checks must pass for every PR. -->+<!-- Every PR, including document and form changes and PRs authored by Elevatormusic, must pass all tests listed in CONTRIBUTING.md and lint. Run them locally or in CI. Give exact commands, versions, and results, or links to all passing CI test jobs for this commit. Do not mark the checkbox while any required test is running, failed, skipped, or unavailable. Do not repeat the full suite locally after it passed in CI. A document-only change needs no new regression test or live model/server details. Check links and form schema when applicable. No live model or performance test is required for the full suite. -->| Check | Exact command | Outcome and evidence || --- | --- | --- || Regression test for a behavior fix (fails before, passes after) | | || Unit tests | | |+| Property tests | | |+| Issue policy tests | | || Lint | | |-| Hermes integration, for changes to Hermes interaction | | |+| Hermes middleware compatibility | | |+| Hermes plugin integration | | |+| Native provider API checks | | |+| Native conversation checks | | || Document links / issue form YAML and schema, when applicable | | || `git diff --check` | `git diff --check` | |+- [ ] I ran all tests listed in CONTRIBUTING.md and all passed.+<!-- For integration, give the exact clean Hermes commit, Python version, and report result. Commands and check limits are in CONTRIBUTING.md. Use placeholders for private paths. -->-Integration versions and report (or not applicable with reason):+Integration versions and reports:## Evidence and limitsdiff --git a/.github/workflows/require-issue.yml b/.github/workflows/require-issue.ymlnew file mode 100644index 0000000..55c1bd9--- /dev/null+++ b/.github/workflows/require-issue.yml@@ -0,0 +1,39 @@+name: Issue first++on:+ pull_request_target:+ types: [opened, reopened, edited, synchronize, ready_for_review]+ workflow_dispatch:+ inputs:+ pr_number:+ description: Pull request number to check without a write+ required: true+ type: string++permissions:+ contents: read+ issues: read+ pull-requests: read++env:+ # Existing pull requests stay outside the policy after edits or reopening.+ ISSUE_POLICY_ACTIVATED_AT: ${{ vars.ISSUE_POLICY_ACTIVATED_AT }}++concurrency:+ group: ${{ github.workflow }}-${{ github.event.number || inputs.pr_number }}+ cancel-in-progress: true++jobs:+ issue-first:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Read the trusted workflow source+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ github.workflow_sha }}+ persist-credentials: false+ - name: Check the PR requirements without a write+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: python3 -B scripts/check_issue_policy.pydiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 08c2052..e48c73a 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -13,6 +13,20 @@ concurrency:cancel-in-progress: truejobs:+ issue-policy:+ name: Issue policy unit tests+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.10"+ - name: Test the policy with fake API data+ run: python -B -m unittest discover -s tests -p "test_issue_policy.py" -v+unit:name: unit (${{ matrix.os }}, ${{ matrix.python-version }})runs-on: ${{ matrix.os }}@@ -62,8 +76,8 @@ jobs:# One stable check name for branch protection: it passes only when every unit job passed.tests-passed:if: always()- needs: unit+ needs: [unit, issue-policy]runs-on: ubuntu-lateststeps:- name: All unit jobs passed- run: test "${{ needs.unit.result }}" = "success"+ run: test "${{ needs.unit.result }}" = "success" && test "${{ needs.issue-policy.result }}" = "success"diff --git a/AGENTS.md b/AGENTS.mdindex 1fdd28a..75c5263 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -36,7 +36,7 @@ Keep default diagnostics and published runtime evidence small and metadata only.## Checks-Use Python 3.10 or later and Git. For Python changes, run:+Use Python 3.10 or later and Git. For every PR, including document and form changes, run all tests in [CONTRIBUTING.md](CONTRIBUTING.md#run-the-checks) and lint. This includes unit, property, policy, and all four loopback Hermes checks. No live model or performance test is required for this suite. These commands are part of the suite:```bashpython -m unittest discover -s tests -p "test_wc_*.py"@@ -45,17 +45,23 @@ ruff check .Use Ruff `0.16.10`, the version used by CI. The [contribution guide](CONTRIBUTING.md#run-the-checks) gives setup and integration commands.-For changes to Hermes interaction, run `scripts/check_plugin_hermes.py` with the Python of a Hermes virtual environment and a clean Hermes checkout. Use its loopback fake server. Record the exact Hermes commit, Python version, command, and report result.+For every PR, run the four Hermes checks with the Python of a Hermes virtual environment and a clean Hermes checkout. Use synthetic data and loopback fake servers. Record the exact Hermes commit, Python version, commands, and report results. Use placeholders for private paths in shared results.-For document or form changes, check local Markdown links, parse issue-form YAML, check the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema), and run `git diff --check`. Keep `AGENTS.md` and `CLAUDE.md` identical in bytes. A document-only change needs no code regression test or live model probe.+For document or form changes, also check local Markdown links, parse issue-form YAML, check the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema), and run `git diff --check`. Keep `AGENTS.md` and `CLAUDE.md` identical in bytes. A document-only change needs no new regression test, but it must pass the full test suite.-Record every applicable check as passed, failed, skipped, or unavailable. Give exact commands and explain skipped or unavailable checks. CI unit and lint checks must pass for every PR.+Record every required check as passed, failed, skipped, or unavailable. Give exact commands and explain failed, skipped, or unavailable checks. Only mark the PR test checkbox after all listed tests passed. A skipped or unavailable test does not satisfy it. CI test and lint checks must pass for every PR.++The full suite can run locally or in CI. Link complete passing CI results for the current PR commit. Do not repeat a complete passing CI suite locally or download Hermes only for that repeat. Do not mark the checkbox while a required CI test is running.Unit tests prove local fixture behavior. Loopback integration checks prove behavior on the named Hermes source. Neither proves a live route, summary quality, cache reuse, or a speed gain. A performance claim needs the synthetic workload, comparison method, versions/settings, run counts, per-run times, token/cache counters, and measurement limits. Report missing counters as unknown.## PR and final report-Use the [PR template](.github/pull_request_template.md). Link the issue, give the concrete trigger and before/after behavior, describe scope and limits, and include exact check results. Use `not applicable` with a reason for runtime sections in a document-only PR.+Use the [PR template](.github/pull_request_template.md). Link the issue, give the concrete trigger and before/after behavior, describe scope and limits, and include exact check results. A document-only PR needs the full synthetic test results, but can mark live provider and performance details `not applicable` with a reason.++A PR authored by `Elevatormusic` is exempt from the issue requirement only. The author name check is not case-sensitive. The limit of five open PRs, AI agent disclosure, and the test checkbox still apply. Count draft PRs and open PRs on all base branches. Closed or merged PRs and ordinary issues do not count. Do not close PRs under this policy. PRs that predate the policy cutoff stay outside the automated check, but they count toward the author's open PR limit for later PRs.++Every issue and PR must declare AI agent use. If agents helped diagnose the problem or write code, list every harness, exact model, and task. Use plain `Harness:`, `Model:`, and `Work:` lines for each agent. If no AI agent was used, write exactly `No AI agent used`. Do not invent a model or include private paths, configs, credentials, or conversations.Before a PR update or publication, check the current branch head, diff, checks, and relevant issue or review comments again. Inspect the full diff for unrelated changes and private data. Do not infer completion from an old check result.diff --git a/CLAUDE.md b/CLAUDE.mdindex 1fdd28a..75c5263 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -36,7 +36,7 @@ Keep default diagnostics and published runtime evidence small and metadata only.## Checks-Use Python 3.10 or later and Git. For Python changes, run:+Use Python 3.10 or later and Git. For every PR, including document and form changes, run all tests in [CONTRIBUTING.md](CONTRIBUTING.md#run-the-checks) and lint. This includes unit, property, policy, and all four loopback Hermes checks. No live model or performance test is required for this suite. These commands are part of the suite:```bashpython -m unittest discover -s tests -p "test_wc_*.py"@@ -45,17 +45,23 @@ ruff check .Use Ruff `0.16.10`, the version used by CI. The [contribution guide](CONTRIBUTING.md#run-the-checks) gives setup and integration commands.-For changes to Hermes interaction, run `scripts/check_plugin_hermes.py` with the Python of a Hermes virtual environment and a clean Hermes checkout. Use its loopback fake server. Record the exact Hermes commit, Python version, command, and report result.+For every PR, run the four Hermes checks with the Python of a Hermes virtual environment and a clean Hermes checkout. Use synthetic data and loopback fake servers. Record the exact Hermes commit, Python version, commands, and report results. Use placeholders for private paths in shared results.-For document or form changes, check local Markdown links, parse issue-form YAML, check the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema), and run `git diff --check`. Keep `AGENTS.md` and `CLAUDE.md` identical in bytes. A document-only change needs no code regression test or live model probe.+For document or form changes, also check local Markdown links, parse issue-form YAML, check the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema), and run `git diff --check`. Keep `AGENTS.md` and `CLAUDE.md` identical in bytes. A document-only change needs no new regression test, but it must pass the full test suite.-Record every applicable check as passed, failed, skipped, or unavailable. Give exact commands and explain skipped or unavailable checks. CI unit and lint checks must pass for every PR.+Record every required check as passed, failed, skipped, or unavailable. Give exact commands and explain failed, skipped, or unavailable checks. Only mark the PR test checkbox after all listed tests passed. A skipped or unavailable test does not satisfy it. CI test and lint checks must pass for every PR.++The full suite can run locally or in CI. Link complete passing CI results for the current PR commit. Do not repeat a complete passing CI suite locally or download Hermes only for that repeat. Do not mark the checkbox while a required CI test is running.Unit tests prove local fixture behavior. Loopback integration checks prove behavior on the named Hermes source. Neither proves a live route, summary quality, cache reuse, or a speed gain. A performance claim needs the synthetic workload, comparison method, versions/settings, run counts, per-run times, token/cache counters, and measurement limits. Report missing counters as unknown.## PR and final report-Use the [PR template](.github/pull_request_template.md). Link the issue, give the concrete trigger and before/after behavior, describe scope and limits, and include exact check results. Use `not applicable` with a reason for runtime sections in a document-only PR.+Use the [PR template](.github/pull_request_template.md). Link the issue, give the concrete trigger and before/after behavior, describe scope and limits, and include exact check results. A document-only PR needs the full synthetic test results, but can mark live provider and performance details `not applicable` with a reason.++A PR authored by `Elevatormusic` is exempt from the issue requirement only. The author name check is not case-sensitive. The limit of five open PRs, AI agent disclosure, and the test checkbox still apply. Count draft PRs and open PRs on all base branches. Closed or merged PRs and ordinary issues do not count. Do not close PRs under this policy. PRs that predate the policy cutoff stay outside the automated check, but they count toward the author's open PR limit for later PRs.++Every issue and PR must declare AI agent use. If agents helped diagnose the problem or write code, list every harness, exact model, and task. Use plain `Harness:`, `Model:`, and `Work:` lines for each agent. If no AI agent was used, write exactly `No AI agent used`. Do not invent a model or include private paths, configs, credentials, or conversations.Before a PR update or publication, check the current branch head, diff, checks, and relevant issue or review comments again. Inspect the full diff for unrelated changes and private data. Do not infer completion from an old check result.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8c66c5d..d3474c2 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -8,6 +8,10 @@ Use the [Bug report form](.github/ISSUE_TEMPLATE/bug_report.yml) for a failure.Complete each bug report section. Give exact versions when you have them. Write `unknown`, `not run`, or `not applicable` with a short reason when you cannot give a value. Do not guess. These fields reduce follow-up requests, but a new or version-specific problem can still need more checks.+Every issue and PR must declare AI agent use. If an AI agent helped diagnose the problem or write code, list every harness, exact model, and task. A harness is the app or tool that ran the agent. Use plain `Harness:`, `Model:`, and `Work:` lines for each agent. Start these lines at the left margin, with no leading spaces. If no AI agent was used, write exactly `No AI agent used`. Do not guess a model or use a default disclosure. Keep private paths, configs, credentials, and conversations out of this statement.++GitHub requires nonempty disclosure text in the issue forms. It does not check the text format. Maintainers review issue disclosures. The `issue-first` workflow validates disclosures in new PRs; it does not validate or close issues.+Include:- The installed plugin version, source commit or install ref, install method, and local edits. Give the running Hermes version and commit, and any local Hermes edits.@@ -36,11 +40,45 @@ Use a clean, isolated Hermes copy for further probes. Keep installed source and## Propose a change-1. Open an issue first for a large change, so that we can agree on the design.+1. Open an issue before you open a pull request. If an issue already covers the same change, use that issue. This rule also applies to small fixes, documents, draft PRs, and dependency updates. A PR authored by `Elevatormusic` is exempt from the issue requirement only; the name check is not case-sensitive. For a large change, agree on the design in the issue before implementation. Report security problems through the private route in [SECURITY.md](SECURITY.md).2. Fork the repository and make a branch from `main`.-3. For a behavior fix, add a test that fails without your change. Then make the change. A document-only change does not need a code test.-4. Run the applicable checks below. Record the exact command and whether it passed, failed, was skipped, or was unavailable. Explain every skipped or unavailable check.-5. Open a pull request. Complete the [PR template](.github/pull_request_template.md): link the issue, state the concrete trigger and before/after behavior, explain the scope, and give check results and limits. If there is no issue, explain why.+3. For a behavior fix, add a test that fails without your change. Then make the change. A document-only change does not need a new regression test, but it must pass the full test suite.+4. Run all tests listed below and lint for every PR, including document and form changes. Run them locally, or let CI run after you open the PR. Record the exact commands, versions, and results, or link the complete passing CI results. Do not repeat the same suite locally if CI already ran it in full. All tests must pass before you mark the required test checkbox. Record a failed, skipped, or unavailable check with its reason; it does not satisfy this requirement.+5. Open a pull request. Complete the [PR template](.github/pull_request_template.md): link the earlier issue, declare AI agent use, state the concrete trigger and before/after behavior, explain the scope, and give check results and limits. Mark `I ran all tests listed in CONTRIBUTING.md and all passed.` only after you ran the full suite and it passed.++### Open pull request limit++Each author can have at most five open pull requests in this repository. The count includes the PR being checked, draft PRs, and open PRs on every base branch. Open PRs that predate policy activation also count. Closed or merged PRs and ordinary issues do not count. The limit applies to every author, including `Elevatormusic`.++The policy check fails a new PR when its author has more than five open PRs. Wait until another PR is merged or close a PR you no longer need. Then ask a maintainer to rerun the failed policy job, or edit the remaining PR description to trigger a new check. GitHub can still create the sixth PR; the required check prevents it from passing the merge policy. The workflow does not close PRs.++PRs opened before policy activation keep their existing exemption from the automated check. They still use open PR slots when a later PR is checked. An API failure or an incomplete PR count fails the check. The check reads the open PR set again before it reports a pass.++### Required issue link++Unless the PR author is `Elevatormusic`, put one of these lines in the PR description. Replace `123` with the issue number:++```text+Closes #123+Fixes #123+Resolves #123+```++Use one complete line at the left margin, with no leading spaces. Keep it outside a comment, code block, raw HTML block, math block, collapsed section, list, or quote. Put a blank line after any preceding list, quote, or HTML block. These format rules also apply to the AI declaration. Put the test checkbox in its own task list, with a blank line before it. Keep the checkbox outside hidden examples too. You can also use the full issue URL, for example `Closes https://github.com/Elevatormusic/hermes-warm-compaction/issues/123`.++The linked item must be an issue in this repository, and it must have been opened before the PR. An issue from another repository or a link to another PR does not count. An existing issue can have a different author or be closed.++GitHub cannot enforce this rule before it creates a PR. The [issue policy workflow](.github/workflows/require-issue.yml) checks each new PR and fails if it has no valid earlier issue, except for PRs authored by `Elevatormusic`. It checks draft PRs too. The author exception applies only to the issue link: the five-open-PR limit, AI agent disclosure, and the test checkbox still apply. If the link is missing, add a valid earlier issue link. If you opened the issue after the PR, open a new PR for that issue. API failures fail the check. The workflow preserves PRs that predate the policy cutoff and does not close any PR.++The workflow reads PR and issue metadata. It checks out the trusted workflow commit and does not run code from the PR. Manual dispatch checks one PR without changing it.++To activate the policy, a maintainer sets the repository variable `ISSUE_POLICY_ACTIVATED_AT` once to the actual activation time in UTC, in `YYYY-MM-DDTHH:MM:SSZ` format. Do not advance this value for later policy edits. A missing or invalid value fails the check. Then require the `issue-first` check in the `main` branch protection settings and allow `pull_request_target` for this workflow in the Actions event policy.++Run its local tests with:++```bash+python -B -m unittest discover -s tests -p "test_issue_policy.py" -v+```Keep each pull request to one subject. The plugin uses documented Hermes plugin APIs only: no patch of Hermes, no subclass of the built-in compressor, and no runtime wrapping of Hermes code. A change that needs one of those cannot be merged.@@ -52,7 +90,9 @@ Agents must read [AGENTS.md](AGENTS.md) before work. [CLAUDE.md](CLAUDE.md) hasYou need Python 3.10 or later and Git. The plugin has no third-party dependency.-For Python changes, run the unit tests, property tests, and lint. These checks use local fixtures. They do not prove deployed compatibility, summary quality, or cache reuse.+Every PR must pass the full suite: unit tests, property tests, issue policy tests, and all four loopback Hermes checks below. Run lint too. This rule includes document and form changes. These checks use synthetic data. They do not prove deployed compatibility, summary quality, or cache reuse. No live model or performance test is required for this suite.++The full suite can run in CI. Link all passing test jobs for the current PR commit, including the Hermes checks, before marking the test checkbox. A running, failed, skipped, or unavailable job is not a passing result. The local commands below provide the same checks when you run them outside CI. You do not need to download a Hermes runtime only to repeat a complete passing CI suite.```bashpython -m unittest discover -s tests -p "test_wc_*.py"@@ -64,6 +104,7 @@ Install the test tools in a separate test environment, then run the property tespython -m pip install -r requirements-test.txtpython -m coverage run -m unittest discover -s tests -p "test_wc_*.py"python -m coverage run --append -m unittest discover -s tests/property -p "test_*.py"+python -B -m unittest discover -s tests -p "test_issue_policy.py" -vpython -m coverage report -m```@@ -76,15 +117,16 @@ pip install ruff==0.16.10ruff check .```-For changes to Hermes interaction, also run the integration check. It runs real Hermes code against a loopback fake server with synthetic conversations. Run it with the Python of a Hermes virtual environment and a **clean** Hermes checkout, not your installed Hermes. Record the exact Hermes commit, Python version, command, and report result:+For every PR, run the middleware and integration checks. They run real Hermes code against loopback fake servers with synthetic data. Run them with the Python of a Hermes virtual environment and a **clean** Hermes checkout, not your installed Hermes. Record the exact Hermes commit, Python version, commands, and report results. Use placeholders for private paths in shared results:```bash+<hermes-venv-python> -B scripts/check_hermes_compatibility.py --hermes-source <clean-hermes-checkout> --report .work/hermes-compatibility-report.json<hermes-venv-python> -B scripts/check_plugin_hermes.py --hermes-source <clean-hermes-checkout> --report .work/plugin-integration-report.json```The integration check covers install, request, compaction, and history behavior on that Hermes version. It does not call a real model or prove live cache reuse or a performance gain. Keep evidence small and metadata only.-For changes to Responses or Anthropic Messages routes, also run both native checks. The provider check uses real Hermes transports and synthetic loopback replies. The conversation check runs the real Hermes agent loop, manual and automatic compaction, native tools, and saved-session reload. Each case uses a fresh process and temporary home. The isolated interpreter needs the Hermes dependencies for both API formats. Use `--dependency-path <dependency-folder>` if those dependencies are in a separate local folder.+For every PR, also run both native checks. The provider check uses real Hermes transports and synthetic loopback replies. The conversation check runs the real Hermes agent loop, manual and automatic compaction, native tools, and saved-session reload. Each case uses a fresh process and temporary home. The isolated interpreter needs the Hermes dependencies for both API formats. Use `--dependency-path <dependency-folder>` if those dependencies are in a separate local folder.```bash<hermes-venv-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes-checkout> --report .work/provider-api-report.json@@ -95,7 +137,7 @@ The [Hermes compatibility workflow](.github/workflows/hermes-compatibility.yml)See [provider support](docs/provider-support.md) for the supported request and authentication limits. A passing local check does not qualify a live provider.-For document or form changes, check local Markdown links and run `git diff --check`. For issue forms, parse the YAML and check its fields against the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema). No live model check is needed for these changes.+Run `git diff --check` for every PR. For document or form changes, also check local Markdown links. For issue forms, parse the YAML and check its fields against the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema). These checks are in addition to the full test suite.CI runs unit and property tests on Python 3.10 to 3.13 (Linux) and on Python 3.12 (Windows and macOS). It saves branch coverage reports for each job and runs lint. A pull request must pass the test and lint checks. The Hermes compatibility workflow also runs on pull requests, pushes to `main`, each day, and by manual dispatch.diff --git a/README.md b/README.mdindex e67b962..95cb601 100644--- a/README.md+++ b/README.md@@ -335,7 +335,7 @@ For native provider edits, run both `scripts/check_provider_apis.py` and `script## Contributing-Bug reports, server results, and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the checks, and [SECURITY.md](SECURITY.md) to report a vulnerability privately. Changes are listed in [CHANGELOG.md](CHANGELOG.md).+Bug reports, server results, and pull requests are welcome. Each author can have at most five open PRs, including drafts. Each new PR must link an earlier issue, such as `Closes #123`; PRs authored by `Elevatormusic` are exempt from the issue rule. Issues and PRs must declare the AI harness and model used, or state that no AI agent was used. Each new PR must also confirm that all tests passed. See [CONTRIBUTING.md](CONTRIBUTING.md) for the rules and checks, and [SECURITY.md](SECURITY.md) to report a vulnerability privately. Changes are listed in [CHANGELOG.md](CHANGELOG.md).## License and creditdiff --git a/scripts/check_issue_policy.py b/scripts/check_issue_policy.pynew file mode 100644index 0000000..1ff0467--- /dev/null+++ b/scripts/check_issue_policy.py@@ -0,0 +1,809 @@+"""Check the issue, open PR limit, AI agent, and test requirements for new PRs.++Use one complete plain line at column zero: Closes #123, Fixes #123, or Resolves #123.+The same keywords can precede an exact HTTPS URL for this repository's issue.+Keywords are not case-sensitive. Comments and code examples do not count.+"""++from __future__ import annotations++import json+import os+import re+from datetime import datetime, timezone+from html import unescape+from pathlib import Path+from unicodedata import category+from urllib.error import HTTPError, URLError+from urllib.parse import urlencode+from urllib.request import HTTPRedirectHandler, Request, build_opener+++class PolicyError(Exception):+ """The check cannot make a safe decision."""+++class ApiError(PolicyError):+ """An API request failed without a policy decision."""++ def __init__(self, status: int | None = None):+ self.status = status+ super().__init__(f"GitHub API request failed (status {status or 'unknown'}).")+++class ResponseTooLarge(ApiError):+ """The API response exceeds the fixed byte limit."""+++class NoRedirect(HTTPRedirectHandler):+ """Keep the token on the fixed GitHub API host."""++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ return None+++class GitHubApi:+ def __init__(self, token: str):+ self.token = token+ self.opener = build_opener(NoRedirect())++ def get(self, path: str) -> dict:+ result = self._read(path)+ if not isinstance(result, dict):+ raise ApiError()+ return result++ def get_list(self, path: str) -> list[dict]:+ result = self._read(path)+ if not isinstance(result, list) or len(result) > 100 or any(not isinstance(item, dict) for item in result):+ raise ApiError()+ return result++ def _read(self, path: str):+ if not isinstance(path, str) or not path.startswith("/repos/") or re.search(r"[\x00-\x20\x7f]", path):+ raise ApiError()+ request = Request(+ "https://api.github.com" + path,+ headers={+ "Authorization": f"Bearer {self.token}",+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ "User-Agent": "warm-compaction-issue-policy",+ },+ )+ try:+ with self.opener.open(request, timeout=30) as response:+ raw = response.read(1024 * 1024 + 1)+ if len(raw) > 1024 * 1024:+ raise ResponseTooLarge()+ return json.loads(raw)+ except HTTPError as error:+ raise ApiError(error.code) from None+ except (URLError, TimeoutError, OSError, ValueError):+ raise ApiError() from None+++def timestamp(value: str) -> datetime:+ if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", value):+ raise PolicyError("A required UTC timestamp is missing or invalid.")+ try:+ return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)+ except ValueError:+ raise PolicyError("A required UTC timestamp is invalid.") from None+++def plain_lines(body: str) -> list[str]:+ """Read bounded column-zero lines outside comments, code, and nested text."""+ if len(body) > 128 * 1024:+ raise PolicyError("The pull request body exceeds the policy size limit.")+ lines = []+ fence = None+ comment = False+ inline_code = None+ html_blocks = []+ raw_html = None+ markup_end = None+ math_block = False+ tag_parts = []+ tag_quote = None+ nested = False+ paragraph = False+ paragraph_start = 0+ link_mode = None+ link_depth = 0+ link_quote = None+ link_angle = False+ link_seen = False+ link_phase = None+ reference_next = None+ comment_end = re.compile(r"--!?>")+ tag_start = re.compile(r"</?[A-Za-z]")+ declaration_start = re.compile(r"<![A-Z]")+ tick_run = re.compile(r"`+")+ hidden_tags = {+ "pre", "code", "script", "style", "textarea", "blockquote", "ul", "ol", "menu", "li", "dl", "dt", "dd",+ "details",+ }+ list_parents = {"ul", "ol", "menu"}+ literal_tags = {"pre", "code", "script", "style", "textarea"}+ raw_literal_tags = literal_tags - {"code"}+ block_tags = (+ "address article aside base basefont blockquote body caption center col colgroup dd details dialog dir div "+ "dl dt fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header hr html iframe "+ "legend li link main menu menuitem nav noframes ol optgroup option p param search section source summary table "+ "tbody td tfoot th thead title tr track ul"+ )+ raw_block_tag = re.compile(r" {0,3}</?(?:" + "|".join(block_tags.split()) + r")(?=[ \t/>]|$)", re.IGNORECASE)+ attribute = r"[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t]*=[ \t]*(?:[^\s\"'=<>`]+|'[^']*'|\"[^\"]*\"))?"+ complete_tag = re.compile(+ r" {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:" + attribute + r")*[ \t]*/?>|</[A-Za-z][A-Za-z0-9-]*[ \t]*>)[ \t]*$"+ )+ math_marker = re.compile(r"(?<!\\)(?:\\\\)*\$\$")+ setext_underline = re.compile(r" {0,3}(?:=+|-+)[ \t]*")+ thematic_break = re.compile(r" {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})")+ reference_start = re.compile(r"\[(?:\\.|[^\]\\]){1,999}\]:")++ def fence_start(line: str):+ marker = re.match(r"^ {0,3}(`{3,}|~{3,})", line)+ if marker and marker[1][0] == "`" and "`" in line[marker.end():]:+ return None+ return marker++ def paragraph_boundary(line: str) -> bool:+ return bool(+ not line.strip(" \t") or fence_start(line) or raw_block_tag.match(line)+ or setext_underline.fullmatch(line) or thematic_break.fullmatch(line)+ or re.match(r" {0,3}<(?:script|pre|style|textarea)(?=[ \t>]|$)", line, re.IGNORECASE)+ or re.match(+ r" {0,3}(?:#{1,6}(?:[ \t]|$)|>|[-+*][ \t]+|[0-9]+[.)][ \t]+|<!--|<\?|<![A-Z]|<!\[CDATA\[)", line,+ )+ )++ body_lines = re.split(r"\r\n|\r|\n", body)+ matched_ticks = set()+ later_ticks = set()+ for line_number in range(len(body_lines) - 1, -1, -1):+ line = body_lines[line_number]+ # Code spans cannot match across these paragraph boundaries.+ boundary = paragraph_boundary(line)+ if boundary:+ later_ticks.clear()+ for marker in reversed(list(tick_run.finditer(line))):+ size = len(marker[0])+ if size in later_ticks:+ matched_ticks.add((line_number, marker.start()))+ later_ticks.add(size)+ if boundary:+ later_ticks.clear()++ def escaped(line: str, index: int) -> bool:+ start = index+ while start and line[start - 1] == "\\":+ start -= 1+ return (index - start) % 2 == 1++ def scan_markup(line: str, allow_inline: bool = True) -> bool:+ nonlocal comment, tag_quote, inline_code, markup_end+ nonlocal link_mode, link_depth, link_quote, link_angle, link_seen, reference_next+ nonlocal link_phase+ hidden = comment or bool(html_blocks) or bool(tag_parts) or inline_code is not None or markup_end is not None+ index = 0+ while index < len(line):+ if link_mode:+ hidden = True+ char = line[index]+ base_depth = 1 if link_mode == "inline" else 0+ if not link_quote and not link_angle:+ if char in " \t":+ if link_phase in {"destination", "after_angle"}:+ if link_depth != base_depth:+ raise PolicyError("A Markdown link target is incomplete or inconsistent.")+ link_phase = "after_destination"+ index += 1+ continue+ closing = link_mode == "inline" and char == ")" and link_depth == 1+ if link_phase in {"after_title", "after_angle"} and not closing:+ raise PolicyError("A Markdown link target is incomplete or inconsistent.")+ if link_phase == "after_destination" and not closing:+ if char not in ("'", '"', "("):+ raise PolicyError("A Markdown link target is incomplete or inconsistent.")+ link_quote = ")" if char == "(" else char+ link_phase = "title"+ index += 1+ continue+ link_seen = link_seen or char not in " \t"+ if char == "\\":+ if link_phase == "start":+ link_phase = "destination"+ index += 2+ continue+ if link_quote:+ if char == link_quote:+ link_quote = None+ link_phase = "after_title"+ elif link_angle:+ if char == ">":+ link_angle = False+ link_phase = "after_angle"+ elif char == "<":+ link_angle = True+ elif char in ("'", '"') and (index == 0 or line[index - 1] in " \t"):+ link_quote = char+ link_phase = "title"+ elif char == "(":+ link_depth += 1+ if link_depth > 32:+ raise PolicyError("A Markdown link target exceeds the nesting limit.")+ elif char == ")":+ link_depth -= 1+ if link_depth < 0:+ raise PolicyError("A Markdown link target is incomplete or inconsistent.")+ if link_mode == "inline" and link_depth == 0:+ link_mode = None+ if link_phase == "start":+ link_phase = "destination"+ index += 1+ continue+ if comment:+ end = comment_end.search(line, index)+ if not end:+ break+ comment = False+ index = end.end()+ continue+ if markup_end is not None:+ end = line.find(markup_end, index)+ if end < 0:+ break+ index = end + len(markup_end)+ markup_end = None+ continue+ if tag_parts:+ char = line[index]+ tag_parts.append(char)+ if tag_quote:+ if char == tag_quote:+ tag_quote = None+ elif char in ("'", '"'):+ tag_quote = char+ elif char == ">":+ text = "".join(tag_parts)+ tag = re.match(r"<(/?)([A-Za-z][A-Za-z0-9:-]*)(?=[\s/>])", text)+ if tag and tag[1]:+ name = tag[2].lower()+ if (+ (name in raw_literal_tags and text.lower() != f"</{name}>")+ or not re.fullmatch(r"</[A-Za-z][A-Za-z0-9:-]*[ \t\n]*>", text)+ ):+ tag = None+ if tag and not tag[1] and re.fullmatch(r"h[1-6]", tag[2], re.IGNORECASE) and not html_blocks:+ lines.append("#")+ if tag and tag[2].lower() in hidden_tags:+ name = tag[2].lower()+ if (+ len(html_blocks) >= 2 and html_blocks[-1] == "li" and html_blocks[-2] in list_parents+ and ((not tag[1] and name == "li") or (tag[1] and name == html_blocks[-2]))+ ):+ # A sibling item or its parent end can omit the li end.+ html_blocks.pop()+ elif (+ len(html_blocks) >= 2 and html_blocks[-2] == "dl" and html_blocks[-1] in {"dt", "dd"}+ and (+ (not tag[1] and name in {"dt", "dd"})+ or (tag[1] and name == "dl" and html_blocks[-1] == "dd")+ )+ ):+ # Description items can omit their defined end tags.+ html_blocks.pop()+ if not tag[1]:+ html_blocks.append(name)+ elif html_blocks and html_blocks[-1] == name:+ html_blocks.pop()+ tag_parts.clear()+ index += 1+ continue+ if inline_code is not None:+ marker = tick_run.search(line, index)+ if not marker:+ break+ index = marker.end()+ if len(marker[0]) == inline_code:+ inline_code = None+ continue+ markdown = allow_inline and not any(tag in literal_tags for tag in html_blocks)+ reference = reference_start.match(line, index) if (+ markdown and index <= 3 and not line[:index].strip(" ")+ ) else None+ if reference:+ link_mode, link_depth, link_seen = "reference", 0, False+ link_phase = "start"+ hidden = True+ index = reference.end()+ elif markdown and line.startswith("](", index) and not escaped(line, index):+ link_mode, link_depth, link_seen = "inline", 1, False+ link_phase = "start"+ hidden = True+ index += 2+ elif markdown and line[index] == "<" and escaped(line, index):+ index += 1+ elif line.startswith("<!--", index):+ comment = True+ hidden = True+ index += 4+ elif line.startswith("<?", index):+ markup_end = "?>"+ hidden = True+ index += 2+ elif line.startswith("<![CDATA[", index):+ markup_end = "]]>"+ hidden = True+ index += 9+ elif declaration_start.match(line, index):+ markup_end = ">"+ hidden = True+ index += 2+ elif tag_start.match(line, index):+ tag_parts.append("<")+ hidden = True+ index += 1+ elif markdown and line[index] == "`":+ marker = tick_run.match(line, index)+ if not escaped(line, index) and (_line_number, index) in matched_ticks:+ inline_code = len(marker[0])+ hidden = True+ index = marker.end()+ else:+ index += 1+ if tag_parts:+ tag_parts.append("\n")+ if link_mode == "reference" and not link_quote and not link_angle and link_depth == 0:+ link_mode = None+ reference_next = None if link_phase == "after_title" else "title" if link_seen else "destination"+ return hidden++ for _line_number, line in enumerate(body_lines):+ was_paragraph = paragraph+ if not was_paragraph:+ paragraph_start = len(lines)+ paragraph = bool(line.strip(" \t"))+ if not line.strip(" \t"):+ nested = False+ inline_code = None+ if raw_html == "blank":+ raw_html = None+ if raw_html:+ paragraph = False+ scan_markup(line, allow_inline=False)+ continue+ if math_block:+ paragraph = False+ if math_marker.search(line):+ math_block = False+ continue+ if inline_code is not None:+ scan_markup(line)+ continue+ if reference_next:+ if reference_next == "destination" or line.lstrip(" \t").startswith(("'", '"', "(")):+ link_mode, link_depth, link_seen = "reference", 0, reference_next == "title"+ link_phase = "after_destination" if link_seen else "start"+ reference_next = None+ if link_mode:+ if (+ paragraph_boundary(line) or link_angle+ or (+ link_seen and not link_quote+ and (+ (link_mode == "inline" and link_depth != 1)+ or (link_mode == "reference" and link_depth != 0)+ or not line.lstrip(" \t").startswith((")", "'", '"', "("))+ )+ )+ ):+ raise PolicyError("A Markdown link target is incomplete or inconsistent.")+ if link_phase in {"destination", "after_angle"}:+ link_phase = "after_destination"+ scan_markup(line)+ continue+ if fence:+ paragraph = False+ content = line.expandtabs(4)+ if fence[2] and content.strip(" \t") and not content.startswith(" " * fence[2]):+ fence = None+ else:+ if fence[2] and content.strip(" \t"):+ nested = True+ content = content[fence[2]:]+ if re.fullmatch(r" {0,3}" + re.escape(fence[0]) + "{" + str(fence[1]) + r",}[ \t]*", content):+ fence = None+ continue+ mark = fence_start(line)+ list_start = re.match(r" {0,3}(?:[-+*]|[0-9]{1,9}[.)])[ \t]+", line)+ list_mark = fence_start(line[list_start.end():]) if list_start else None+ literal_html = any(tag in literal_tags for tag in html_blocks)+ if (+ (html_blocks or not was_paragraph) and not literal_html and not tag_parts and not markup_end and not comment+ and re.match(r"(?: {4}| {0,3}\t)", line)+ ):+ paragraph = False+ continue+ if (mark or list_mark) and not comment and not literal_html and not tag_parts and not markup_end:+ paragraph = False+ if list_mark:+ nested = True+ fence = (list_mark[1][0], len(list_mark[1]), len(list_start[0].expandtabs(4)))+ else:+ fence = (mark[1][0], len(mark[1]), 0)+ continue+ if (+ not comment and not literal_html and not tag_parts and not markup_end+ and re.match(r" {0,3}\$\$", line)+ ):+ paragraph = False+ opening = math_marker.search(line)+ math_block = math_marker.search(line, opening.end()) is None+ continue+ if html_blocks or tag_parts or markup_end:+ starts_raw_close = (+ not literal_html and not comment and not tag_parts and not markup_end+ and re.match(r" {0,3}</", line) is not None and raw_block_tag.match(line) is not None+ )+ scan_markup(line, allow_inline=markup_end is None and not literal_html and not starts_raw_close)+ if literal_html or starts_raw_close or comment or tag_parts or markup_end:+ paragraph = False+ if starts_raw_close:+ # A block HTML close keeps the following lines raw until a blank.+ raw_html = "blank"+ continue+ if not comment:+ # Raw HTML blocks use their Markdown end rule, not a closing tag.+ if re.match(r" {0,3}(?:<\?|<![A-Z]|<!\[CDATA\[)", line):+ paragraph = False+ scan_markup(line, allow_inline=False)+ continue+ if re.match(r" {0,3}<(?:script|pre|style|textarea)(?=[ \t>]|$)", line, re.IGNORECASE):+ paragraph = False+ scan_markup(line, allow_inline=False)+ continue+ if raw_block_tag.match(line) or (not was_paragraph and complete_tag.fullmatch(line)):+ paragraph = False+ raw_html = "blank"+ scan_markup(line, allow_inline=False)+ continue+ # A comment must not change a code fence or join parts of a plain line.+ if not comment and (thematic_break.fullmatch(line) or (was_paragraph and setext_underline.fullmatch(line))):+ if was_paragraph and setext_underline.fullmatch(line):+ # Keep a boundary without accepting a Setext AI heading.+ del lines[paragraph_start:]+ lines.append("#")+ paragraph = False+ nested = False+ continue+ if scan_markup(line):+ if comment or html_blocks or tag_parts or markup_end:+ paragraph = False+ continue+ # Require column zero so list continuations cannot become policy lines.+ list_or_quote = re.match(r" {0,3}(?:[-+*][ \t]+|[0-9]+[.)][ \t]+|>)", line)+ was_nested = nested+ if list_or_quote:+ paragraph = False+ nested = True+ if line.startswith((" ", "\t")):+ continue+ if list_or_quote:+ if was_nested or not re.fullmatch(+ r"- \[[xX]\] I ran all tests listed in CONTRIBUTING\.md and all passed\.", line+ ):+ continue+ elif re.match(r"#{1,6}[ \t]", line):+ paragraph = False+ nested = False+ elif nested:+ continue+ lines.append(line.rstrip(" \t"))+ if link_mode or reference_next == "destination":+ raise PolicyError("A Markdown link target is incomplete or inconsistent.")+ return lines+++def issue_references(body: str, repository: str) -> list[int]:+ """Read explicit references outside comments and code blocks."""+ pattern = re.compile(+ r"(?:Closes|Fixes|Resolves)[ \t]+(?:#([1-9][0-9]*)|"+ + re.escape(f"https://github.com/{repository}/issues/")+ + r"([1-9][0-9]*))",+ re.IGNORECASE,+ )+ numbers = []+ for line in plain_lines(body):+ match = pattern.fullmatch(line)+ if match:+ number = int(match[1] or match[2])+ if number not in numbers:+ numbers.append(number)+ if len(numbers) > 20:+ raise PolicyError("Use at most 20 issue reference lines.")+ return numbers+++def ai_agent_requirement(lines: list[str]) -> str | None:+ """Return a failure reason when the AI agent section is incomplete."""+ headings = [index for index, line in enumerate(lines) if line == "## AI agent use"]+ if len(headings) != 1:+ return "Add one visible section with the exact heading: ## AI agent use."+ section = []+ for line in lines[headings[0] + 1:]:+ if re.match(r"#{1,6}(?:[ \t]|$)", line):+ break+ section.append(line)+ records = [re.fullmatch(r"(Harness|Model|Work):[ \t]*(.*)", line) for line in section]+ records = [record for record in records if record]+ no_agent = section.count("No AI agent used")+ if no_agent:+ if no_agent == 1 and not records:+ return None+ return "Use either No AI agent used or complete agent records, not both."+ if not records:+ return "In ## AI agent use, write No AI agent used or plain Harness:, Model:, and Work: lines."+ if len(records) > 60:+ return "Use at most 20 AI agent records."+ expected = ("Harness", "Model", "Work")+ for index, record in enumerate(records):+ field, value = record.groups()+ if field != expected[index % 3]:+ return "Each AI agent record must have Harness:, Model:, and Work: lines, in that order."+ blank_fillers = "\u115f\u1160\u2800\u3164\uffa0"+ value = "".join(+ char for char in unescape(value) if category(char)[0] != "C" and char not in blank_fillers+ ).strip()+ visible = any(not char.isspace() and category(char)[0] in "LN" for char in value)+ normalized = value.strip("`*_ ").casefold()+ while normalized and (normalized[0].isspace() or category(normalized[0])[0] in "PS"):+ normalized = normalized[1:]+ while normalized and (normalized[-1].isspace() or category(normalized[-1])[0] in "PS"):+ normalized = normalized[:-1]+ placeholders = {+ "...", "…", "todo", "tbd", "unknown", "none", "n/a", "not applicable", "not run",+ "harness", "harness name", "model", "model name", "exact model", "exact model id",+ "work", "task", "task description", "your harness", "your model", "your task",+ "describe work", "describe the work", "describe task", "describe the task",+ "describe what the agent did", "list every harness", "list every model",+ }+ if (+ not visible or normalized in placeholders or re.search(r"<[^>]*>", value)+ or re.fullmatch(r"\[[^]]*\]", value)+ or re.fullmatch(r"(?:replace|enter|insert)[ \t]+(?:value|here|your (?:harness|model|task))", normalized)+ ):+ return f"Give a {field}: value with a letter or number. Template placeholders do not count."+ if len(records) % 3:+ return f"Each AI agent record needs a {expected[len(records) % 3]}: line."+ return None+++def body_requirement(body: str) -> str | None:+ """Check the AI agent statement and the required test confirmation."""+ lines = plain_lines(body)+ reason = ai_agent_requirement(lines)+ if reason:+ return reason+ if not any(re.fullmatch(+ r"- \[[xX]\] I ran all tests listed in CONTRIBUTING\.md and all passed\.", line+ ) for line in lines):+ return "Add the checked line: - [x] I ran all tests listed in CONTRIBUTING.md and all passed."+ return None+++OPEN_PR_LIMIT = 5+OPEN_PR_PAGE_LIMIT = 100+++def author_open_pulls(api, repository: str, author: str, number: int) -> frozenset[int]:+ """Read all open PRs by this author, including drafts and older PRs."""+ page_size = 100+ while True:+ try:+ return _author_open_pulls(api, repository, author, number, page_size)+ except ResponseTooLarge:+ if page_size == 1:+ raise PolicyError(+ "One open issue exceeds the response size limit. The open PR count is unknown."+ ) from None+ # A new page size must start a new complete read at page one.+ page_size = max(1, page_size // 2)+++def _author_open_pulls(api, repository: str, author: str, number: int, page_size: int) -> frozenset[int]:+ """Read a complete author set with one fixed page size."""+ seen = set()+ numbers = set()+ for page in range(1, OPEN_PR_PAGE_LIMIT + 1):+ query = urlencode({+ "state": "open", "creator": author, "sort": "created", "direction": "asc",+ "per_page": page_size, "page": page,+ })+ items = api.get_list(f"/repos/{repository}/issues?{query}")+ if not isinstance(items, list) or len(items) > page_size:+ raise PolicyError("The open PR list is incomplete or inconsistent.")+ for item in items:+ try:+ item_number = item["number"]+ login = item["user"]["login"]+ if (+ not isinstance(item_number, int) or isinstance(item_number, bool) or item_number < 1+ or item_number in seen or item["state"] not in ("open", "closed")+ or not isinstance(login, str) or login.casefold() != author.casefold()+ ):+ raise ValueError+ seen.add(item_number)+ is_pull = "pull_request" in item+ kind = "pull" if is_pull else "issues"+ if item["html_url"].lower() != f"https://github.com/{repository}/{kind}/{item_number}".lower():+ raise ValueError+ if is_pull:+ details = item["pull_request"]+ if not isinstance(details, dict) or details["url"].lower() != (+ f"https://api.github.com/repos/{repository}/pulls/{item_number}".lower()+ ):+ raise ValueError+ merged_at = details.get("merged_at")+ if merged_at is not None:+ timestamp(merged_at)+ if "draft" in item and not isinstance(item["draft"], bool):+ raise ValueError+ if item["state"] == "open" and merged_at is None:+ numbers.add(item_number)+ except (KeyError, TypeError, AttributeError, ValueError):+ raise PolicyError("The open PR list is incomplete or inconsistent.") from None+ if len(items) < page_size:+ if number not in numbers:+ raise PolicyError(+ "The current pull request is missing from the author's open PR list. Run the check again."+ )+ return frozenset(numbers)+ raise PolicyError("The open PR list exceeds the page limit. The count is unknown.")+++def pull_policy_fields(pull: dict) -> tuple:+ """Compare policy inputs without mutable repository and profile metadata."""+ try:+ values = [pull[field] for field in ("number", "body", "created_at", "state", "merged")]+ if (+ not isinstance(pull["number"], int) or isinstance(pull["number"], bool)+ or not isinstance(pull["merged"], bool)+ ):+ raise TypeError+ user = pull["user"]+ values.extend((user["login"].casefold(), user.get("id")))+ for name in ("head", "base"):+ branch = pull.get(name, {})+ if not isinstance(branch, dict):+ raise TypeError+ repository = branch.get("repo")+ if repository is None:+ repository = {}+ elif not isinstance(repository, dict):+ raise TypeError+ values.extend((branch.get("ref"), repository.get("full_name"), repository.get("id")))+ if name == "head":+ values.append(branch.get("sha"))+ return tuple(values)+ except (KeyError, TypeError, AttributeError):+ raise PolicyError("Pull request data is incomplete or inconsistent.") from None+++def check_policy(api, repository: str, number: int, activated_at: str) -> tuple[bool, str]:+ """Check fresh API data. This script has no write operation."""+ activated = timestamp(activated_at)+ pull = api.get(f"/repos/{repository}/pulls/{number}")+ try:+ if (+ pull["number"] != number+ or pull["state"] not in ("open", "closed")+ or not isinstance(pull["merged"], bool)+ or pull["base"]["repo"]["full_name"].lower() != repository.lower()+ ):+ raise ValueError+ if pull["state"] != "open" or pull["merged"]:+ return True, "Skipped: the pull request is closed or merged."+ created_at = timestamp(pull["created_at"])+ if created_at < activated:+ return True, "Skipped: the pull request predates the policy."+ body = pull["body"]+ if body is not None and not isinstance(body, str):+ raise ValueError+ author = pull["user"]["login"]+ if not isinstance(author, str) or not author.strip():+ raise ValueError+ except (KeyError, TypeError, AttributeError, ValueError):+ raise PolicyError("Pull request data is incomplete or inconsistent.") from None++ def finish(passed: bool, message: str) -> tuple[bool, str]:+ open_pulls = None+ if passed:+ open_pulls = author_open_pulls(api, repository, author, number)+ if len(open_pulls) > OPEN_PR_LIMIT:+ passed = False+ message = (+ f"Keep at most {OPEN_PR_LIMIT} open pull requests per author in this repository. "+ f"This author has {len(open_pulls)}, including this PR, drafts, and older open PRs. "+ "Close or merge an existing PR, then run the check again. This check does not close PRs."+ )+ # Check again before reporting a decision based on PR or issue data.+ fresh = api.get(f"/repos/{repository}/pulls/{number}")+ if pull_policy_fields(fresh) != pull_policy_fields(pull):+ raise PolicyError("The pull request changed during the check. Run the check again.")+ if passed and author_open_pulls(api, repository, author, number) != open_pulls:+ raise PolicyError("The author's open PR list changed during the check. Run the check again.")+ return passed, message++ reason = body_requirement(body or "")+ if reason:+ return finish(False, reason)+ if author.casefold() == "elevatormusic":+ return finish(True, "Passed: AI agent and test requirements met; the PR author is exempt from the issue rule.")++ for issue_number in issue_references(body or "", repository):+ try:+ issue = api.get(f"/repos/{repository}/issues/{issue_number}")+ except ApiError as error:+ if error.status == 404:+ continue+ raise+ if issue.get("number") != issue_number:+ raise PolicyError("Issue data is incomplete or inconsistent.")+ if "pull_request" in issue:+ continue+ if (+ not isinstance(issue.get("html_url"), str)+ or issue["html_url"].lower() != f"https://github.com/{repository}/issues/{issue_number}".lower()+ ):+ raise PolicyError("Issue data is incomplete or inconsistent.")+ if timestamp(issue.get("created_at")) < created_at:+ return finish(True, f"Passed: issue #{issue_number} was opened before this pull request.")++ return finish(False, (+ "Add a complete plain line: Closes #123, Fixes #123, or Resolves #123. "+ "Use a real issue in this repository that was opened before the pull request. "+ "The keyword can also precede its exact https://github.com/owner/repo/issues/123 URL. "+ "Comments and code examples do not count."+ ))+++def main() -> int:+ try:+ repository = os.environ.get("GITHUB_REPOSITORY", "")+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):+ raise PolicyError("The repository name is missing or invalid.")+ event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8"))+ event_name = os.environ.get("GITHUB_EVENT_NAME")+ if event_name == "pull_request_target" and event.get("action") in {+ "opened", "reopened", "edited", "synchronize", "ready_for_review"+ }:+ number = event["number"]+ elif event_name == "workflow_dispatch":+ raw_number = event["inputs"]["pr_number"]+ if not isinstance(raw_number, str) or not re.fullmatch(r"[1-9][0-9]*", raw_number):+ raise PolicyError("Enter a positive pull request number.")+ number = int(raw_number)+ else:+ raise PolicyError("This event cannot run the policy check.")+ if not isinstance(number, int) or isinstance(number, bool) or number < 1:+ raise PolicyError("The pull request number is invalid.")+ token = os.environ.get("GITHUB_TOKEN", "")+ if not token:+ raise PolicyError("The GitHub token is missing.")+ passed, message = check_policy(GitHubApi(token), repository, number, os.environ["ISSUE_POLICY_ACTIVATED_AT"])+ print(("" if passed else "::error::") + message)+ return 0 if passed else 1+ except PolicyError as error:+ # Do not print input text, API bodies, or the token.+ print("::error::" + str(error))+ return 1+ except (KeyError, OSError, ValueError, TypeError, AttributeError):+ print("::error::Policy input could not be read.")+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_issue_policy.py b/tests/test_issue_policy.pynew file mode 100644index 0000000..f22bc02--- /dev/null+++ b/tests/test_issue_policy.py@@ -0,0 +1,1875 @@+"""Check the issue policy with fake API replies. No network is used."""++from __future__ import annotations++import copy+import io+import json+import os+import re+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch+from urllib.error import HTTPError, URLError+from urllib.parse import parse_qs, urlsplit++from scripts import check_issue_policy as policy++REPOSITORY = "owner/repo"+ACTIVATED_AT = "2026-10-08T17:09:42Z"+PR_PATH = "/repos/owner/repo/pulls/23"+TEST_CONFIRMATION = "- [x] I ran all tests listed in CONTRIBUTING.md and all passed."+NO_AGENT = "## AI agent use\nNo AI agent used\n\n" + TEST_CONFIRMATION+AGENT_USE = "## AI agent use\nHarness: Codex\nModel: gpt-6.1-sol\nWork: Write policy tests.\n\n" + TEST_CONFIRMATION+++def pull(**changes):+ data = {+ "number": 23,+ "body": "Closes #7\n\n" + NO_AGENT,+ "created_at": "2026-10-08T18:00:00Z",+ "updated_at": "2026-10-08T18:00:00Z",+ "state": "open",+ "merged": False,+ "user": {"login": "contributor"},+ "base": {"repo": {"full_name": REPOSITORY}, "ref": "main", "sha": "base-sha"},+ "head": {"repo": {"full_name": "contributor/fork"}, "ref": "change", "sha": "head-sha"},+ }+ data.update(changes)+ return data+++def issue(number=7, **changes):+ data = {+ "number": number,+ "html_url": f"https://github.com/{REPOSITORY}/issues/{number}",+ "created_at": "2026-10-08T16:00:00Z",+ "state": "open",+ "user": {"login": "another-author"},+ }+ data.update(changes)+ return data+++class FakeApi:+ def __init__(self, *responses, list_responses=None):+ self.responses = list(responses)+ self.paths = []+ self.list_responses = list(list_responses or [])+ self.explicit_list_responses = list_responses is not None+ self.list_paths = []+ self.default_open_pulls = [open_pull(author=responses[0]["user"]["login"])] if (+ responses and isinstance(responses[0], dict) and isinstance(responses[0].get("user", {}).get("login"), str)+ ) else []++ def get_list(self, path):+ self.list_paths.append(path)+ if not self.list_responses:+ if self.explicit_list_responses:+ raise AssertionError("An unexpected list API read was requested.")+ return copy.deepcopy(self.default_open_pulls)+ response = self.list_responses.pop(0)+ if isinstance(response, Exception):+ raise response+ return copy.deepcopy(response)++ def get(self, path):+ self.paths.append(path)+ if not self.responses:+ raise AssertionError("An unexpected API read was requested.")+ response = self.responses.pop(0)+ if isinstance(response, Exception):+ raise response+ return copy.deepcopy(response)+++def open_pull(number=23, author="contributor", **changes):+ data = issue(number, user={"login": author}, html_url=f"https://github.com/{REPOSITORY}/pull/{number}")+ data["pull_request"] = {"url": f"https://api.github.com/repos/{REPOSITORY}/pulls/{number}", "merged_at": None}+ data.update(changes)+ return data+++class OpenPullLimitTests(unittest.TestCase):+ def test_large_later_page_restarts_with_fresh_sets(self):+ first = [open_pull()] + [issue(number, user={"login": "contributor"}) for number in range(100, 199)]+ api = FakeApi(list_responses=[first, policy.ResponseTooLarge(), first[:50], first[50:], [open_pull(24)]])+ self.assertEqual(policy.author_open_pulls(api, REPOSITORY, "contributor", 23), frozenset({23, 24}))+ queries = [parse_qs(urlsplit(path).query) for path in api.list_paths]+ self.assertEqual([(int(q["per_page"][0]), int(q["page"][0])) for q in queries],+ [(100, 1), (100, 2), (50, 1), (50, 2), (50, 3)])++ def test_five_pass_and_six_refuse_after_page_shrink(self):+ for count in (5, 6):+ with self.subTest(count=count):+ items = [open_pull(number) for number in range(23, 23 + count)]+ pages = [policy.ResponseTooLarge(), items]+ if count == 5:+ pages += [policy.ResponseTooLarge(), items]+ api = FakeApi(pull(), issue(), pull(), list_responses=pages)+ self.assertEqual(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0], count == 5)+ self.assertFalse(api.list_responses)++ def test_page_shrink_is_bounded_and_single_item_overflow_refuses(self):+ api = FakeApi(list_responses=[policy.ResponseTooLarge() for _ in range(7)])+ with self.assertRaisesRegex(policy.PolicyError, "size limit.*unknown"):+ policy.author_open_pulls(api, REPOSITORY, "contributor", 23)+ queries = [parse_qs(urlsplit(path).query) for path in api.list_paths]+ self.assertEqual([int(q["per_page"][0]) for q in queries], [100, 50, 25, 12, 6, 3, 1])+ self.assertEqual([q["page"] for q in queries], [["1"]] * 7)++ def test_non_size_api_error_has_no_retry(self):+ api = FakeApi(list_responses=[policy.ApiError(500)])+ with self.assertRaises(policy.ApiError):+ policy.author_open_pulls(api, REPOSITORY, "contributor", 23)+ self.assertEqual(len(api.list_paths), 1)++ def test_small_page_keeps_duplicate_membership_and_size_checks(self):+ cases = [[open_pull(), open_pull()], [open_pull(24)], [open_pull()] * 51]+ for items in cases:+ with self.subTest(length=len(items)):+ api = FakeApi(list_responses=[policy.ResponseTooLarge(), items])+ with self.assertRaises(policy.PolicyError):+ policy.author_open_pulls(api, REPOSITORY, "contributor", 23)++ def test_small_full_page_requires_next_page_and_keeps_page_bound(self):+ items = [open_pull()] + [issue(number, user={"login": "contributor"}) for number in range(100, 149)]+ api = FakeApi(list_responses=[policy.ResponseTooLarge(), items, []])+ self.assertEqual(policy.author_open_pulls(api, REPOSITORY, "contributor", 23), frozenset({23}))+ self.assertEqual(len(api.list_paths), 3)+ api = FakeApi(list_responses=[policy.ResponseTooLarge(), items])+ with patch.object(policy, "OPEN_PR_PAGE_LIMIT", 1):+ with self.assertRaisesRegex(policy.PolicyError, "page limit.*unknown"):+ policy.author_open_pulls(api, REPOSITORY, "contributor", 23)++ def test_small_page_set_change_still_aborts_pass(self):+ first = [open_pull(number) for number in range(23, 28)]+ api = FakeApi(pull(), issue(), pull(), list_responses=[+ policy.ResponseTooLarge(), first, policy.ResponseTooLarge(), first[:-1],+ ])+ with self.assertRaisesRegex(policy.PolicyError, "open PR list changed"):+ policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)++ def test_five_open_prs_pass_after_two_count_reads(self):+ items = [open_pull(number) for number in (23, 24, 25, 26, 27)]+ api = FakeApi(pull(), issue(), pull(), list_responses=[items, items])+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ self.assertEqual(len(api.list_paths), 2)++ def test_six_open_prs_fail(self):+ items = [open_pull(number) for number in (23, 24, 25, 26, 27, 28)]+ api = FakeApi(pull(), issue(), pull(), list_responses=[items])+ passed, message = policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)+ self.assertFalse(passed)+ self.assertIn("5", message)++ def test_owner_has_no_open_pr_limit_exception(self):+ for author in ("Elevatormusic", "ELEVATORMUSIC"):+ with self.subTest(author=author):+ data = pull(user={"login": author}, body=NO_AGENT)+ items = [open_pull(number, author) for number in (23, 24, 25, 26, 27, 28)]+ api = FakeApi(data, data, list_responses=[items])+ passed, message = policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)+ self.assertFalse(passed)+ self.assertIn("6", message)+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_drafts_older_prs_and_all_base_branches_count(self):+ items = [open_pull(number) for number in (23, 24, 25, 26)]+ items += [+ open_pull(27, draft=True, created_at="2026-10-08T17:09:41Z"),+ open_pull(28, base={"ref": "another-branch"}),+ ]+ api = FakeApi(pull(), issue(), pull(), list_responses=[items])+ self.assertFalse(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ query = parse_qs(urlsplit(api.list_paths[0]).query)+ self.assertEqual(query, {+ "state": ["open"], "creator": ["contributor"], "sort": ["created"],+ "direction": ["asc"], "per_page": ["100"], "page": ["1"],+ })++ def test_closed_merged_prs_and_ordinary_issues_do_not_count(self):+ merged = open_pull(29)+ merged["pull_request"]["merged_at"] = "2026-10-08T18:01:00Z"+ items = [open_pull(number) for number in (23, 24, 25, 26, 27)] + [+ open_pull(28, state="closed"), merged, issue(30, user={"login": "contributor"}),+ ]+ api = FakeApi(pull(), issue(), pull(), list_responses=[items, items])+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])++ def test_open_pr_without_optional_merged_timestamp_counts(self):+ items = [open_pull(number) for number in (23, 24, 25, 26, 27)]+ for item in items:+ del item["pull_request"]["merged_at"]+ api = FakeApi(pull(), issue(), pull(), list_responses=[items, items])+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ items.append(open_pull(28))+ del items[-1]["pull_request"]["merged_at"]+ api = FakeApi(pull(), issue(), pull(), list_responses=[items])+ self.assertFalse(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])++ def test_case_insensitive_author(self):+ data = pull(user={"login": "ConTRibutor"})+ items = [open_pull(author="CONTRIBUTOR")]+ api = FakeApi(data, issue(), data, list_responses=[items, items])+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])++ def test_query_values_are_encoded(self):+ author = "contributor&state=all#fragment"+ items = [open_pull(author=author)]+ api = FakeApi(list_responses=[items])+ self.assertEqual(policy.author_open_pulls(api, REPOSITORY, author, 23), frozenset({23}))+ parsed = urlsplit(api.list_paths[0])+ self.assertEqual(parsed.path, "/repos/owner/repo/issues")+ self.assertEqual(parsed.fragment, "")+ self.assertEqual(parse_qs(parsed.query)["creator"], [author])+ self.assertEqual(parse_qs(parsed.query)["state"], ["open"])++ def test_pagination_passes_only_after_all_issue_pages_are_read_twice(self):+ first = [issue(number, user={"login": "contributor"}) for number in range(100, 200)]+ second = [open_pull(number) for number in (23, 24, 25, 26, 27)]+ api = FakeApi(pull(), issue(), pull(), list_responses=[first, second, first, second])+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ self.assertEqual([parse_qs(urlsplit(path).query)["page"] for path in api.list_paths],+ [["1"], ["2"], ["1"], ["2"]])+ self.assertFalse(api.list_responses)++ def test_sixth_pr_on_a_later_page_refuses(self):+ first = [open_pull(number) for number in (23, 24, 25, 26, 27)]+ first += [issue(number, user={"login": "contributor"}) for number in range(100, 195)]+ api = FakeApi(pull(), issue(), pull(), list_responses=[first, [open_pull(28)]])+ self.assertFalse(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ self.assertEqual(len(api.list_paths), 2)++ def test_full_final_page_needs_an_empty_page(self):+ items = [open_pull()] + [issue(number, user={"login": "contributor"}) for number in range(100, 199)]+ api = FakeApi(list_responses=[items, []])+ self.assertEqual(policy.author_open_pulls(api, REPOSITORY, "contributor", 23), frozenset({23}))+ self.assertEqual(len(api.list_paths), 2)++ def test_page_limit_refuses_an_unknown_count(self):+ pages = [+ [open_pull()] + [issue(number, user={"login": "contributor"}) for number in range(100, 199)],+ [issue(number, user={"login": "contributor"}) for number in range(200, 300)],+ ]+ api = FakeApi(list_responses=pages)+ with patch.object(policy, "OPEN_PR_PAGE_LIMIT", 2):+ with self.assertRaisesRegex(policy.PolicyError, "page limit.*unknown"):+ policy.author_open_pulls(api, REPOSITORY, "contributor", 23)+ self.assertEqual(len(api.list_paths), 2)++ def test_current_pr_must_be_present_and_open(self):+ for items in ([], [open_pull(24)], [open_pull(state="closed")]):+ with self.subTest(items=items):+ api = FakeApi(pull(), issue(), pull(), list_responses=[items])+ with self.assertRaisesRegex(policy.PolicyError, "current pull request is missing"):+ policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)++ def test_malformed_list_data_refuses(self):+ cases = [+ {}, None, [None], ["not-an-item"], [open_pull(number=True)], [open_pull(number=0)],+ [open_pull(state="unknown")], [open_pull(user={})], [open_pull(user={"login": "another-author"})],+ [open_pull(html_url="https://github.com/other/repo/pull/23")], [open_pull(html_url=None)],+ [open_pull(pull_request=None)], [open_pull(pull_request={})],+ [open_pull(pull_request={"url": "https://api.example.com/repos/owner/repo/pulls/23", "merged_at": None})],+ [open_pull(pull_request={"url": "https://api.github.com/repos/owner/repo/pulls/23", "merged_at": "bad"})],+ [open_pull(draft="true")], [open_pull()] * 101,+ ]+ for items in cases:+ with self.subTest(items=items):+ with self.assertRaises(policy.PolicyError):+ policy.author_open_pulls(FakeApi(list_responses=[items]), REPOSITORY, "contributor", 23)++ def test_duplicate_items_on_same_or_later_pages_refuse(self):+ first = [open_pull()] + [issue(number, user={"login": "contributor"}) for number in range(100, 199)]+ for pages in ([[open_pull(), open_pull()]], [first, [issue(100, user={"login": "contributor"})]]):+ with self.subTest(pages=len(pages)):+ with self.assertRaisesRegex(policy.PolicyError, "incomplete or inconsistent"):+ policy.author_open_pulls(FakeApi(list_responses=pages), REPOSITORY, "contributor", 23)++ def test_list_api_errors_refuse_on_both_reads_and_later_pages(self):+ first = [open_pull()] + [issue(number, user={"login": "contributor"}) for number in range(100, 199)]+ for status in (None, 403, 404, 429, 500):+ for pages in ([policy.ApiError(status)], [[open_pull()], policy.ApiError(status)],+ [first, policy.ApiError(status)]):+ with self.subTest(status=status, pages=len(pages)):+ api = FakeApi(pull(), issue(), pull(), list_responses=pages)+ with self.assertRaises(policy.ApiError):+ policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)++ def test_open_pr_set_changes_abort_a_pass(self):+ first = [open_pull(number) for number in (23, 24, 25, 26, 27)]+ for last in (first + [open_pull(28)], first[:-1], first[:-1] + [open_pull(28)]):+ with self.subTest(numbers=[item["number"] for item in last]):+ api = FakeApi(pull(), issue(), pull(), list_responses=[first, last])+ with self.assertRaisesRegex(policy.PolicyError, "open PR list changed"):+ policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)++ def test_old_candidate_skips_count_even_above_limit(self):+ api = FakeApi(pull(created_at="2026-10-08T17:09:41Z"), list_responses=[+ [open_pull(number) for number in (23, 24, 25, 26, 27, 28)],+ ])+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ self.assertEqual(api.list_paths, [])+++class ReviewRegressionTests(unittest.TestCase):+ def test_link_destination_cannot_close_details(self):+ body = "<details><summary>Example</summary>\n\n[sample](</details>)\n\nCloses #7\n\n" + NO_AGENT+ body += "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_incomplete_link_cannot_mask_a_raw_html_block(self):+ body = "[sample](target\n<pre>\n)\n\nCloses #7\n\n" + NO_AGENT+ with self.assertRaises(policy.PolicyError):+ policy.body_requirement(body)++ def test_indented_html_cannot_continue_a_bare_link_destination(self):+ body = "[sample](target\n <pre>\n)\n\nCloses #7\n\n" + NO_AGENT+ with self.assertRaises(policy.PolicyError):+ policy.body_requirement(body)++ def test_inline_html_cannot_continue_a_bare_link_destination(self):+ body = "[sample](target\ntext <pre>\n)\n\nCloses #7\n\n" + NO_AGENT+ with self.assertRaises(policy.PolicyError):+ policy.body_requirement(body)++ def test_unquoted_html_cannot_follow_a_link_destination(self):+ body = "[sample](target <pre>)\n\nCloses #7\n\n" + NO_AGENT+ with self.assertRaises(policy.PolicyError):+ policy.body_requirement(body)++ def test_extra_text_cannot_follow_a_completed_link_title(self):+ body = '[sample](target "title" <pre>)\n\nCloses #7\n\n' + NO_AGENT+ with self.assertRaises(policy.PolicyError):+ policy.body_requirement(body)++ def test_raw_html_heading_ends_the_ai_section(self):+ body = "## AI agent use\n\n<h2>Other section</h2>\n\nNo AI agent used\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))++ def test_punctuated_placeholder_values_do_not_supply_disclosure(self):+ for value in ("TODO.", "unknown.", "not run."):+ with self.subTest(value=value):+ body = AGENT_USE.replace("Work: Write policy tests.", "Work: " + value)+ self.assertIsNotNone(policy.body_requirement(body))++ def test_link_destinations_and_titles_keep_details_hidden(self):+ samples = (+ "[sample](</details>)", '[sample](target "</details>")', "[sample](target '</details>')",+ r'[sample](target "escaped \" </details>")', "[id]: </details>", '[id]: target "</details>"',+ )+ for sample in samples:+ with self.subTest(sample=sample):+ body = "<details>\n\n" + sample + "\n\nCloses #7\n\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_incomplete_links_refuse_markdown_block_interruptions(self):+ blocks = (+ "<pre>", "<script>", "<style>", "<textarea>", "<!--", "<?pi", "<!DOCTYPE html>",+ "<:+ for block in blocks:+ with self.subTest(prefix=prefix, block=block):+ with self.assertRaises(policy.PolicyError):+ policy.plain_lines(prefix + block + '\nlast")\n\n')++ def test_multiline_links_preserve_noninterrupting_text_and_type_seven_html(self):+ samples = (+ '[sample](target\n "two\nlines")', '[id]: target\n "two\nlines"',+ "[sample](target\n)", "[sample](\n<span>\n)", '[sample](target\n (title))',+ )+ for sample in samples:+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ for sample in ('[sample](target "first\n<span>\nlast")', '[id]: target "first\n<span>\nlast"'):+ body = "<details>\n\n" + sample + "\n\nCloses #7\n\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_started_link_destinations_cannot_cross_a_line_ending(self):+ for sample in ("[sample](target\nmore)", "[sample](<target\nmore>)", "[id]: <target\nmore>",+ "[sample](target(\nmore))", "[id]: target(\nmore)"):+ with self.subTest(sample=sample):+ with self.assertRaises(policy.PolicyError):+ policy.plain_lines(sample)++ def test_link_targets_refuse_extra_text_after_destination_or_title(self):+ samples = (+ '[sample](target extra)', '[sample](target "title" extra)', '[sample](<target>extra)',+ '[id]: target extra', '[id]: target "title" extra', '[sample](target "title"\n"extra")',+ "[sample](target(</details>))", r"[sample](target\(</details>\))",+ )+ for sample in samples:+ with self.subTest(sample=sample):+ with self.assertRaises(policy.PolicyError):+ policy.plain_lines(sample)++ def test_link_target_guards_preserve_urls_angles_and_titles(self):+ samples = (+ '[sample](https://example.test/path?a=1&b=2)', '[sample](<https://example.test/a path>)',+ '[sample](target(nested))', r'[sample](target\(escaped\))',+ '[sample](target "title")', "[sample](target 'title')", '[id]: <target> "title"',+ )+ for sample in samples:+ with self.subTest(sample=sample):+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_link_suffix_markup_is_still_scanned_after_target_closes(self):+ body = '[sample](target "title")<!--\nCloses #7\n\n' + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ with self.assertRaises(policy.PolicyError):+ policy.plain_lines('[id]: target\n "title"<!--\n\n')++ def test_incomplete_or_deep_link_targets_refuse_unknown_markup(self):+ samples = (+ "[sample](target", '[sample](target "title', "[id]:", "[sample](<target", "[sample](" + "(" * 33,+ )+ for sample in samples:+ with self.subTest(sample=sample):+ with self.assertRaises(policy.PolicyError):+ policy.plain_lines(sample)++ def test_html_heading_levels_end_ai_without_accepting_html_ai_heading(self):+ for level in range(1, 7):+ for disclosure in ("No AI agent used", "Harness: Codex\nModel: test-model\nWork: Test"):+ body = f"## AI agent use\n\n<h{level} title='Other'>Other</h{level}>\n\n" + disclosure+ body += "\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))+ body = f"<h{level}>AI agent use</h{level}>\n\nNo AI agent used\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))++ def test_fake_html_headings_do_not_end_the_ai_section(self):+ for sample in ("`<h2>Other</h2>`", "```\n<h2>Other</h2>\n```", " <h2>Other</h2>",+ "<!-- <h2>Other</h2> -->", "<pre>\n<h2>Other</h2>\n</pre>",+ '<span title="<h2>Other</h2>">text</span>', '[sample](target "<h2>Other</h2>")'):+ with self.subTest(sample=sample):+ body = "## AI agent use\n\n" + sample + "\n\nNo AI agent used\n\n" + TEST_CONFIRMATION+ self.assertIsNone(policy.body_requirement(body))++ def test_placeholder_punctuation_normalization_keeps_real_values(self):+ for field in ("Harness", "Model", "Work"):+ for value in ("(TODO.)", "unknown!", "not run…", "“TODO.”"):+ with self.subTest(field=field, value=value):+ body = re.sub(rf"(?m)^{field}:.*$", f"{field}: {value}", AGENT_USE)+ self.assertIsNotNone(policy.body_requirement(body))+ for value in ("Codex.", "gpt-6.1-sol", "C++", "Test: parser behavior."):+ body = re.sub(rf"(?m)^{field}:.*$", f"{field}: {value}", AGENT_USE)+ self.assertIsNone(policy.body_requirement(body))++ def test_list_fence_close_does_not_open_a_top_level_fence(self):+ body = "- ```text\n example\n ```\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_malformed_literal_closes_do_not_release_policy_lines(self):+ for tag, closing in (("script", "</script/>"), ("pre", "</pre bogus>")):+ with self.subTest(tag=tag):+ body = f"<{tag}>\n{closing}\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_setext_other_section_cannot_supply_missing_ai_disclosure(self):+ for disclosure in ("No AI agent used", "Harness: Codex\nModel: test-model\nWork: Test"):+ with self.subTest(disclosure=disclosure):+ body = "## AI agent use\n\nOther section\n-------------\n" + disclosure + "\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))++ def test_top_level_indented_code_cannot_open_markup_state(self):+ for sample in (" <!--", " <pre>"):+ with self.subTest(sample=sample):+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_list_fences_keep_nested_fields_hidden_and_restore_public_lines(self):+ for prefix in ("- ", "+ ", "* ", "1. ", "123) ", " - "):+ for marker in ("```", "~~~"):+ with self.subTest(prefix=prefix, marker=marker):+ indent = " " * len(prefix)+ nested_body = "Closes #7\n" + NO_AGENT+ sample = prefix + marker + "text\n" + "\n".join(indent + line for line in nested_body.split("\n"))+ sample += "\n" + indent + marker+ self.assertEqual(policy.issue_references(sample, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(sample))+ public = sample + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))+ body = "- ```text\n <!--\n </details>\n <pre>\n ```\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_unclosed_list_fence_ends_when_the_list_container_ends(self):+ body = "- ```text\n example\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ hidden = "- ```text\n Closes #7\n " + NO_AGENT.replace("\n", "\n ")+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))++ def test_literal_raw_ends_need_exact_tag_and_recover_after_real_end(self):+ for tag in ("pre", "script", "style", "textarea"):+ for ending in (f"</{tag}/>", f"</{tag} bogus>", f"</{tag} >", f"</{tag}\n>"):+ with self.subTest(tag=tag, ending=ending):+ body = f"<{tag}>\n{ending}\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + f"\n</{tag.upper()}>\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))+ body = "<code>\n</code >\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_setext_heading_paragraph_cannot_supply_plain_policy_fields(self):+ for underline in ("===", "---"):+ for text in ("No AI agent used", "Harness: Codex\nModel: test-model\nWork: Test"):+ with self.subTest(underline=underline, text=text):+ body = "## AI agent use\n\n" + text + "\n" + underline + "\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))+ body = "Closes #7\n" + underline + "\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ body = "AI agent use\n" + underline + "\nNo AI agent used\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))++ def test_setext_boundaries_preserve_disclosure_in_the_correct_section(self):+ for underline in ("===", "---"):+ body = NO_AGENT.replace(TEST_CONFIRMATION, "Other section\n" + underline + "\n\n" + TEST_CONFIRMATION)+ self.assertIsNone(policy.body_requirement(body))+ for sample in ("```text\nOther section\n---\n```", " Other section\n ---", "<pre>\nOther\n---\n</pre>"):+ body = "## AI agent use\n\n" + sample + "\n\nNo AI agent used\n\n" + TEST_CONFIRMATION+ self.assertIsNone(policy.body_requirement(body))++ def test_indented_code_markup_variants_restore_public_lines(self):+ for indent in (" ", "\t", " \t", " \t"):+ for sample in ("<!--", "<pre>", "<?example", "<![CDATA[", "</details>", "$$"):+ with self.subTest(indent=repr(indent), sample=sample):+ body = indent + sample + "\n" + indent + "Closes #7\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(body))++ def test_indentation_does_not_override_raw_html_or_paragraph_continuations(self):+ for prefix in ("<div>\n", "Prose\n"):+ with self.subTest(prefix=prefix):+ body = prefix + " <!--\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ body = "<pre>\n </pre>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+++ def test_disclosure_values_need_a_letter_or_number(self):+ for field in ("Harness", "Model", "Work"):+ for value in ("-", "?", "!", "@#$", "☀", "&"):+ with self.subTest(field=field, value=value):+ body = re.sub(rf"(?m)^{field}:.*$", f"{field}: {value}", AGENT_USE)+ self.assertIsNotNone(policy.body_requirement(body))++ def test_disclosure_values_allow_unicode_letters_digits_and_model_punctuation(self):+ for field in ("Harness", "Model", "Work"):+ for value in ("模型", "Codex", "123", "١٢٣", "gpt-6.1-sol", "Model (v2): test!"):+ with self.subTest(field=field, value=value):+ body = re.sub(rf"(?m)^{field}:.*$", f"{field}: {value}", AGENT_USE)+ self.assertIsNone(policy.body_requirement(body))++ def test_entity_only_disclosure_values_do_not_supply_visible_content(self):+ body = "## AI agent use\nHarness: \nModel:  \nWork: ​\n\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))++ def test_math_tags_cannot_close_markdown_details(self):+ body = "<details><summary>Example</summary>\n\n" + r"$$\text{</details>}$$"+ body += "\n\nCloses #7\n\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_non_gfm_line_separators_do_not_create_policy_lines(self):+ for separator in ("\u2028", "\u0085"):+ with self.subTest(separator=repr(separator)):+ body = ("Closes #7\n\n" + NO_AGENT).replace("\n", separator)+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_source_interrupts_prose_as_type_six_raw_html(self):+ body = "Prose\n<source>\nCloses #7\n## AI agent use\nNo AI agent used\n\n" + TEST_CONFIRMATION+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_each_disclosure_field_rejects_entity_and_unicode_only_invisible_values(self):+ values = (" ", " ", " ", "​", "⁠", "\u200b", "\u2060",+ "\ufeff", "\u00ad", "\u0301", "\ufe0f", "\u115f", "\u3164", "\u2800")+ for field in ("Harness", "Model", "Work"):+ for value in values:+ with self.subTest(field=field, value=repr(value)):+ body = re.sub(rf"(?m)^{field}:.*$", f"{field}: {value}", AGENT_USE)+ self.assertIsNotNone(policy.body_requirement(body))++ def test_visible_decoded_and_unicode_disclosure_values_still_pass(self):+ for value in ("Codex", "Codex Desktop", "模型", "e\u0301 test", "\u200bCodex", "&nbsp;"):+ with self.subTest(value=value):+ body = AGENT_USE.replace("Harness: Codex", "Harness: " + value)+ self.assertIsNone(policy.body_requirement(body))+ for value in ("TODO", "<harness>", "\u200bTODO\u200b"):+ with self.subTest(value=value):+ body = AGENT_USE.replace("Harness: Codex", "Harness: " + value)+ self.assertIsNotNone(policy.body_requirement(body))++ def test_same_line_and_multiline_math_leave_markdown_containers_hidden(self):+ for tag in ("details", "blockquote", "ul"):+ for expression in (rf"$$\text{{</{tag}>}}$$", "$$\n" + rf"\text{{</{tag}>}}" + "\n$$"):+ with self.subTest(tag=tag, expression=expression):+ body = f"<{tag}>\n\n" + expression + "\n\nCloses #7\n\n" + NO_AGENT + f"\n</{tag}>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_math_delimiters_do_not_override_literal_html_tags_or_attributes(self):+ for tag in ("pre", "code", "script", "style", "textarea"):+ with self.subTest(tag=tag):+ body = f"<{tag}>\n$$</{tag}>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ body = "<details title='\n$$</details>\n'>\n\nCloses #7\n\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_gfm_cr_lf_and_crlf_line_endings_still_pass(self):+ for separator in ("\r", "\n", "\r\n"):+ with self.subTest(separator=repr(separator)):+ body = ("Closes #7\n\n" + NO_AGENT).replace("\n", separator)+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_unicode_separators_cannot_end_raw_html_blocks_as_blank_lines(self):+ for separator in ("\v", "\f", "\x1c", "\x1d", "\x1e", "\u0085", "\u2028", "\u2029", "\u00a0"):+ with self.subTest(separator=repr(separator)):+ body = "<div>\n" + separator + "\nCloses #7\n## AI agent use\nNo AI agent used\n" + TEST_CONFIRMATION+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ for blank in ("", " ", "\t", " \t "):+ body = "<div>\n" + blank + "\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_source_raw_blocks_keep_boundaries_and_recover_after_blank(self):+ for source in ("<source>", "<SOURCE src='example'>", " <source/>", "</source>"):+ with self.subTest(source=source):+ body = "Prose\n" + source + "\nCloses #7\n## AI agent use\nNo AI agent used\n" + TEST_CONFIRMATION+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))+ body = "Prose\n<sources>\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_inline_tick_match_stops_at_setext_and_thematic_boundaries(self):+ for marker in ("---", "===", "***", "=", "--", "_ _ _", "- - -", " *\t* * "):+ with self.subTest(marker=marker):+ body = "Prose `\n" + marker + "\nCloses #7\nanother `\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_setext_and_thematic_end_the_prose_paragraph_before_type_seven_html(self):+ for marker in ("---", "===", "***", "_ _ _"):+ with self.subTest(marker=marker):+ body = "Prose\n" + marker + "\n<span>\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNone(policy.body_requirement(body))++ def test_non_boundaries_keep_matched_inline_spans_and_fences(self):+ for marker in (" ---", "a ===", "* - *", "== text", "\\---"):+ with self.subTest(marker=marker):+ body = "Prose `\n" + marker + "\nCloses #7\nanother `\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNone(policy.body_requirement(body))+ body = "```text\n---\n===\n***\nCloses #7\n```\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNone(policy.body_requirement(body))++ def test_unmatched_inline_ticks_do_not_hide_public_policy_fields(self):+ body = "An unmatched ` example.\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_inline_tick_match_stops_at_heading_boundary(self):+ body = "Prose `\n## AI agent use\nNo AI agent used\nAnother marker `\n\n" + TEST_CONFIRMATION+ self.assertIsNone(policy.body_requirement(body))+ body = "Closes #7\n\n" + AGENT_USE.replace("Work: Write policy tests.", "Work: Check the ` option.")+ self.assertIsNone(policy.body_requirement(body))++ def test_invalid_backtick_fence_info_does_not_hide_public_policy_fields(self):+ body = "```language`\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_escaped_details_close_cannot_release_hidden_policy_fields(self):+ body = "<details><summary>Example</summary>\n\n\\</details>\n\nCloses #7\n\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_unmatched_tick_lengths_are_literal_on_agent_work_line(self):+ for text in ("Use the ` option.", "Use ` and `` markers.", "Use `` and ``` markers."):+ with self.subTest(text=text):+ body = "Closes #7\n\n" + AGENT_USE.replace("Write policy tests.", text)+ self.assertIsNone(policy.body_requirement(body))++ def test_unmatched_ticks_do_not_disable_comments_or_literal_html(self):+ for opening, closing in (("<!--", "-->"), ("<pre>", "</pre>")):+ with self.subTest(opening=opening):+ body = "Example `" + opening + "\nCloses #7\n" + NO_AGENT + "\n" + closing+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_tick_match_stops_at_fence_html_quote_and_list_boundaries(self):+ samples = [+ "```text\n`\n```", "~~~text\n`\n~~~", "<pre>`\n</pre>", "<div>`\n</div>",+ "<!-- ` -->", "<?example `?>", "<![CDATA[`]]>", "<!DOCTYPE example `>",+ "> Another ` marker", "- Another ` marker", "1. Another ` marker",+ ]+ for sample in samples:+ with self.subTest(sample=sample):+ body = "Prose `\n" + sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_type_seven_html_does_not_interrupt_matched_inline_span(self):+ body = "`\n<span>\nexample`\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_type_seven_html_does_not_interrupt_prose_paragraph(self):+ body = "Prose\n<span>\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_fence_info_rules_keep_valid_fences_and_literal_invalid_lines(self):+ for indent in ("", " "):+ for opening in ("```text`", "````text`", r"```text\`", "```text```"):+ with self.subTest(indent=indent, opening=opening):+ body = indent + opening + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ for opening, close in (("```text", "```"), ("````text", "````"), ("~~~text`", "~~~")):+ with self.subTest(indent=indent, opening=opening):+ hidden = indent + opening + "\nCloses #7\n" + NO_AGENT + "\n" + close+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ self.assertIsNone(policy.body_requirement(hidden + "\n\n" + NO_AGENT))++ def test_markdown_html_escape_parity_preserves_real_container_close(self):+ for tag in ("details", "blockquote", "ul"):+ for count in (1, 2, 3, 4):+ with self.subTest(tag=tag, count=count):+ body = f"<{tag}>\n\n" + "\\" * count + f"</{tag}>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [] if count % 2 else [7])+ self.assertEqual(policy.body_requirement(body) is None, count % 2 == 0)+ body += f"\n</{tag}>\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [8] if count % 2 else [7, 8])++ def test_html_escape_rules_stay_literal_in_raw_blocks_and_attributes(self):+ for tag in ("details", "pre", "code", "script", "style", "textarea"):+ with self.subTest(tag=tag):+ body = f"<{tag}>\n\\</{tag}>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ body = "<details><summary title='\\</details>'>Example</summary>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_escaped_html_starts_in_markdown_do_not_open_hidden_contexts(self):+ for opening in ("<details>", "<pre>", "<!--", "<?example", "<![CDATA[", "<!DOCTYPE example"):+ with self.subTest(opening=opening):+ body = "\\" + opening + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_optional_description_item_ends_recover_public_policy_lines(self):+ sample = "<dl>\n<dt>Term\n<dd>Definition\n</dl>"+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_optional_description_siblings_and_nested_lists(self):+ for sample in (+ "<dl><dt>First<dt>Second<dd>One<dd>Two<dt>Last</dt></dl>",+ "<dl><dt>Term<dd><dl><dt>Nested<dd>Definition</dl></dl>",+ "<dl><dt>Term<dd><ul><li>One<li>Two</ul></dl>",+ ):+ with self.subTest(sample=sample):+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_description_list_keeps_hidden_context_and_defined_end_rules(self):+ samples = [+ "`</dl>`", "```\n</dl>\n```", " </dl>", "\t</dl>",+ '<span title="</dl><dt><dd>">text</span>', "<!-- </dl><dt><dd> -->", "<![CDATA[</dl><dt><dd>]]>",+ "</ul>",+ ]+ samples += [f"<{tag}></dl><dt><dd></{tag}>" for tag in ("pre", "code", "script", "style", "textarea")]+ for sample in samples:+ with self.subTest(sample=sample):+ body = "<dl><dt>Term<dd>Definition\n\n" + sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ body = "<dl><dt>Term</dl>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ for outer in ("details", "blockquote"):+ body = f"<{outer}>\n\n<dl><dt>Term<dd>Definition</dl>\n\nCloses #7\n\n{NO_AGENT}"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ body += f"\n</{outer}>\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_description_list_close_keeps_raw_block_until_blank(self):+ body = "Closes #7\n\n<dl><dt>Term<dd>Definition\n\n</dl>\n" + NO_AGENT+ self.assertIsNotNone(policy.body_requirement(body))++ def test_optional_list_item_end_recovers_public_policy_lines(self):+ for sample in ("<ul><li>First<li>Second</ul>", "<ol><li>First<li>Second</li></ol>"):+ with self.subTest(sample=sample):+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_optional_list_ends_keep_nested_lists_and_outer_containers(self):+ for tag in ("ul", "ol", "menu"):+ sample = f"<{tag}><li>First<ol><li>Nested<li>More</ol><li>Last</{tag}>"+ body = sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ for outer in ("details", "blockquote"):+ body = f"<{outer}>\n\n{sample}\n\nCloses #7\n\n{NO_AGENT}\n</{outer}>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ body += "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_optional_list_end_keeps_raw_close_boundary(self):+ body = "Closes #7\n\n<ul><li>Example</ul>\n" + NO_AGENT+ self.assertIsNotNone(policy.body_requirement(body))+ body = "Closes #7\n\n<ul><li>Example\n\n</ul>\n" + NO_AGENT+ self.assertIsNotNone(policy.body_requirement(body))++ def test_fake_optional_list_ends_cannot_release_hidden_fields(self):+ samples = [+ "`</ul>`", "```\n</ul>\n```", " </ul>", "\t</ul>",+ '<span title="</ul><li>">text</span>', "<!-- </ul><li> -->", "<![CDATA[</ul><li>]]>",+ "</ol>",+ ]+ samples += [f"<{tag}></ul><li></{tag}>" for tag in ("pre", "code", "script", "style", "textarea")]+ for sample in samples:+ with self.subTest(sample=sample):+ body = "<ul><li>Example\n\n" + sample + "\n\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_container_close_requires_blank_before_ai_heading(self):+ for tag in ("details", "blockquote"):+ for indent in ("", " "):+ with self.subTest(tag=tag, indent=indent):+ body = f"Closes #7\n\n<{tag}>\nExample\n\nSample\n{indent}</{tag}>\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_container_close_requires_blank_before_test_checkbox(self):+ for tag in ("details", "blockquote"):+ with self.subTest(tag=tag):+ body = "Closes #7\n\n## AI agent use\nNo AI agent used\n\n"+ body += f"<{tag}>\nExample\n\nSample\n</{tag}>\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(body))++ def test_container_close_recovers_ai_heading_after_a_blank_line(self):+ for tag in ("details", "blockquote", "ul", "ol", "li", "dl", "dt", "dd"):+ for indent in ("", " ", " ", " "):+ for blank in ("", " "):+ with self.subTest(tag=tag, indent=indent, blank=blank):+ body = f"Closes #7\n\n<{tag}>\nExample\n\nSample\n{indent}</{tag}>\n{blank}\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_container_close_recovers_test_checkbox_after_a_blank_line(self):+ for tag in ("details", "blockquote"):+ with self.subTest(tag=tag):+ body = "Closes #7\n\n## AI agent use\nNo AI agent used\n\n"+ body += f"<{tag}>\nExample\n\nSample\n</{tag}>\n\n" + TEST_CONFIRMATION+ self.assertIsNone(policy.body_requirement(body))++ def test_literal_close_keeps_the_confirmed_heading_control(self):+ for tag in ("code", "pre", "script", "style", "textarea"):+ with self.subTest(tag=tag):+ body = f"Closes #7\n\n<{tag}>\nExample\n\nSample\n</{tag}>\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_container_close_suffix_is_raw_and_does_not_open_code(self):+ for suffix in ("`", "```", "~~~"):+ with self.subTest(suffix=suffix):+ hidden = "<details>\nExample\n\nSample\n</details>" + suffix + "\nCloses #7"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_details_inline_code_cannot_close_the_container(self):+ hidden = "<details>\n<summary>Example</summary>\n\n`</details>`\n`\nCloses #7\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))++ def test_details_fenced_code_cannot_close_the_container(self):+ hidden = "<details>\n<summary>Example</summary>\n\n```text\n</details>\n```\n\n```\nCloses #7\n"+ hidden += NO_AGENT + "\n```\n\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))++ def test_details_indented_code_cannot_close_the_container(self):+ hidden = "<details>\n<summary>Example</summary>\n\n </details>\n\nCloses #7\n"+ hidden += NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))++ def test_markdown_container_inline_code_preserves_the_real_close(self):+ for tag in ("details", "blockquote", "ul", "ol", "li", "dl", "dt", "dd"):+ for marker in ("`", "``"):+ with self.subTest(tag=tag, marker=marker):+ hidden = f"<{tag}>\n\n{marker}</{tag}>{marker}\nCloses #7\n{NO_AGENT}\n</{tag}>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_multiline_container_code_span_ignores_fake_tags_and_comments(self):+ hidden = "<details>\n<summary>Example</summary>\n\n``\nexample </details>\nexample <!--\nexample <pre>\n``\n\n"+ hidden += "Closes #7\n"+ hidden += NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_container_fences_ignore_fake_tags_and_restore_public_lines(self):+ for tag in ("details", "blockquote", "ul"):+ for marker in ("```", "~~~"):+ for indent in ("", " "):+ with self.subTest(tag=tag, marker=marker, indent=indent):+ hidden = f"<{tag}>\n\n{indent}{marker}text\n</{tag}>\n<!--\n<pre>\n{indent}{marker}\n\n"+ hidden += f"Closes #7\n{NO_AGENT}\n</{tag}>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_container_indented_code_ignores_fake_tags_and_comments(self):+ for tag in ("details", "blockquote", "ul"):+ for indent in (" ", "\t", " \t", " \t"):+ with self.subTest(tag=tag, indent=indent):+ hidden = f"<{tag}>\n\n{indent}</{tag}>\n{indent}<!--\n{indent}<pre>\n\nCloses #7\n"+ hidden += NO_AGENT + f"\n</{tag}>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_literal_tags_keep_tag_behavior_inside_a_markdown_container(self):+ for tag in ("pre", "code", "script", "style", "textarea"):+ with self.subTest(tag=tag):+ hidden = f"<details>\n<summary>Example</summary>\n\n<{tag}>\n```\n</details>\n`</{tag}>`\n\n"+ hidden += "Closes #7\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_processing_instruction_suffix_comment_hides_declarations(self):+ body = "<?example\n?> <!--\nCloses #7\n" + NO_AGENT + "\n-->"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_cdata_suffix_comment_hides_declarations(self):+ body = "<![CDATA[\n]]><!--\nCloses #7\n" + NO_AGENT + "\n-->"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_details_with_blank_lines_hide_declarations(self):+ body = "<details>\n<summary>Example</summary>\n\nCloses #7\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_special_markup_ends_scan_comment_and_pre_suffixes(self):+ for opening, ending in (("<?example", "?>"), ("<![CDATA[", "]]>"), ("<!DOCTYPE example", ">")):+ for separator in ("", "\n"):+ for suffix, closing in (("<!--", "-->"), ("<!--", "--!>"), ("<pre>", "</pre>")):+ with self.subTest(opening=opening, separator=separator, suffix=suffix, closing=closing):+ hidden = opening + separator + ending + suffix + "\nCloses #7\n" + NO_AGENT + "\n" + closing+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_special_markup_after_code_and_tag_suffixes_stays_hidden(self):+ for prefix in ("`\nexample`", "<span>example</span>"):+ for opening, ending in (("<?example", "?>"), ("<![CDATA[", "]]>"), ("<!DOCTYPE example", ">")):+ with self.subTest(prefix=prefix, opening=opening):+ hidden = prefix + opening + "\nCloses #7\n" + NO_AGENT + "\n" + ending + "<!--"+ hidden += "\nCloses #8\n" + NO_AGENT + "\n-->"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #9\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [9])+ self.assertIsNone(policy.body_requirement(public))++ def test_special_markup_contents_do_not_interpret_tags_or_code(self):+ for opening, ending in (("<?example", "?>"), ("<![CDATA[", "]]>"), ("<!DOCTYPE example", ">")):+ with self.subTest(opening=opening):+ content = "<!-- <pre `" if ending == ">" else "<!-- <pre> `"+ hidden = opening + "\n" + content + "\nCloses #7\n" + NO_AGENT + "\n" + ending + "`"+ public = hidden + "\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_special_markup_inside_code_or_quoted_attributes_has_no_effect(self):+ for text in ("<?example", "<![CDATA[", "<!DOCTYPE example"):+ with self.subTest(text=text):+ body = "``\nexample " + text + "``\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ body = "`\nexample`<span title='" + text + "'>\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_unclosed_special_markup_and_details_keep_declarations_hidden(self):+ for opening in ("<?example", "<![CDATA[", "<!DOCTYPE example", "<details>\n<summary>Example</summary>"):+ with self.subTest(opening=opening):+ hidden = opening + "\n\nCloses #7\n" + NO_AGENT+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))++ def test_nested_details_keep_outer_contents_hidden_until_its_close(self):+ hidden = "<details>\n<summary>Outer</summary>\n\n<details>\n<summary>Inner</summary>\n\n</details>"+ hidden += "\n\nCloses #7\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_details_attributes_and_comments_cannot_close_the_container(self):+ for opening in (+ '<details><span title="</details>">', "<details><span title='</details><!--'>",+ '<details><span\ntitle="\n</details>\n">',+ "<details>\n<!--\n</details>\n-->", "<details>\n<!-- </details> --!>",+ "<details>\n<![CDATA[\n</details>\n]]>",+ ):+ with self.subTest(opening=opening):+ hidden = opening + "\n\nCloses #7\n" + NO_AGENT + "\n</span></details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_details_open_flag_keeps_the_strict_plain_line_rule(self):+ for opening in ("<details open>", "<DETAILS open='open'>"):+ with self.subTest(opening=opening):+ hidden = opening + "\n<summary>Example</summary>\n\nCloses #7\n" + NO_AGENT + "\n</details>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_raw_html_block_cannot_supply_declarations(self):+ body = "<div>\nCloses #7\n" + NO_AGENT + "\n</div>"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_markup_after_multiline_inline_code_is_still_scanned(self):+ body = "`\nexample`<!--\nCloses #7\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_block_math_cannot_supply_declarations(self):+ body = "$$\nCloses #7\n" + NO_AGENT + "\n$$"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))++ def test_unrelated_repository_metadata_does_not_abort_a_pass(self):+ first = pull()+ last = copy.deepcopy(first)+ last["head"]["repo"]["stargazers_count"] = 1+ last["base"]["repo"]["updated_at"] = "2026-10-08T18:01:00Z"+ last["user"]["avatar_url"] = "https://example.com/avatar.png"+ self.assertTrue(policy.check_policy(FakeApi(first, issue(), last), REPOSITORY, 23, ACTIVATED_AT)[0])++ def test_checkbox_after_an_example_needs_a_blank_line(self):+ body = NO_AGENT.replace(TEST_CONFIRMATION, "- Example:\n" + TEST_CONFIRMATION)+ self.assertIsNotNone(policy.body_requirement(body))++ def test_raw_html_tag_blocks_need_a_blank_line_after_their_close(self):+ for opening, closing in (+ ("<div>", "</div>"), ("<TABLE>", "</TABLE>"), ("<details>", "</details>"),+ ("<section class='example'>", "</section>"), ("<div\nclass='example'>", "</div>"),+ ("<span>", "</span>"), ("<custom data-value=example>", "</custom>"),+ ("<img src=example.png />", ""), ("</custom>", ""), ("</div>", ""),+ ):+ with self.subTest(opening=opening):+ body = opening + "\nCloses #7\n## AI agent use\nNo AI agent used\n" + TEST_CONFIRMATION+ body += ("\n" + closing if closing else "") + "\nCloses #8"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + "\n\nCloses #9\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [9])+ self.assertIsNone(policy.body_requirement(public))++ def test_raw_html_special_blocks_keep_their_own_end_rule(self):+ for opening, closing in (("<?example", "?>"), ("<!DOCTYPE example", ">"), ("<![CDATA[", "]]>")):+ with self.subTest(opening=opening):+ body = opening + "\n\nCloses #7\n" + NO_AGENT + "\n" + closing+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ public = body + "\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))+ one_line = opening + closing + "\n" + NO_AGENT+ self.assertIsNone(policy.body_requirement(one_line))++ def test_script_pre_style_and_textarea_end_at_the_matching_close(self):+ for tag in ("script", "pre", "style", "textarea"):+ with self.subTest(tag=tag):+ hidden = f"<{tag}>\n`\n\nCloses #7\n{NO_AGENT}\n</{tag}>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_raw_html_does_not_interpret_code_or_math_markers(self):+ for marker in ("```", "`", "$$"):+ with self.subTest(marker=marker):+ body = "<div>\n" + marker + "\nCloses #7\n</div>\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(body))++ def test_text_and_autolinks_do_not_start_a_raw_html_block(self):+ for line in ("<https://example.com>", "<[email protected]>", "2 < 3", "Example: <span>word</span>"):+ with self.subTest(line=line):+ body = line + "\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_inline_code_suffix_comments_and_pre_blocks_hide_declarations(self):+ for marker in ("`", "``"):+ for opening, closing in (("<!--", "-->"), ("<!--", "--!>"), ("<pre>", "</pre>")):+ with self.subTest(marker=marker, opening=opening, closing=closing):+ hidden = marker + "\nexample" + marker + opening + "\nCloses #7\n" + NO_AGENT + "\n" + closing+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))+ hidden = "``\nexample`different``<!--\nCloses #7\n" + NO_AGENT+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])++ def test_inline_code_does_not_interpret_markup_until_it_closes(self):+ for text in ("<!--", "<pre>", "<div>"):+ with self.subTest(text=text):+ body = "``\nexample " + text + "``\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ body = "`\nexample`<span title='<!--'>\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))++ def test_math_opening_content_and_blank_lines_stay_hidden(self):+ for opening in ("$$", "$$x + y", " $$x + y"):+ with self.subTest(opening=opening):+ hidden = opening + "\n\nCloses #7\n" + NO_AGENT + "\n$$"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))+ self.assertIsNotNone(policy.body_requirement("$$\n" + NO_AGENT))++ def test_same_line_and_escaped_math_delimiters_do_not_hide_public_lines(self):+ for line in ("$$x + y$$", r"\$$", "Price: $$", r"$$x + y\\$$"):+ with self.subTest(line=line):+ body = line + "\nCloses #7\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7])+ self.assertIsNone(policy.body_requirement(body))+ body = "$$\n" + r"\$$" + "\nCloses #7\n" + NO_AGENT + "\n$$\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(body, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(body))++ def test_metadata_and_base_commit_changes_do_not_change_the_decision(self):+ for valid in (False, True):+ first = pull() if valid else pull(body="")+ last = copy.deepcopy(first)+ last.update(title="New title", labels=[{"name": "policy"}], draft=True, updated_at="2026-10-08T18:01:00Z")+ last["base"]["sha"] = "unrelated-main-commit"+ last["base"]["repo"]["pushed_at"] = "2026-10-08T18:01:00Z"+ last["user"]["login"] = "CONTRIBUTOR"+ api = FakeApi(first, issue(), last) if valid else FakeApi(first, last)+ self.assertEqual(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0], valid)++ def test_real_policy_field_changes_abort_the_decision(self):+ changes = [+ ("number", 24), ("created_at", "2026-10-08T18:00:01Z"), ("user.login", "other-author"), ("user.id", 42),+ ("head.sha", "new-head"), ("head.ref", "new-ref"), ("head.repo.full_name", "other/fork"),+ ("head.repo.id", 43), ("base.ref", "release"), ("base.repo.full_name", "other/repo"), ("base.repo.id", 44),+ ]+ for path, value in changes:+ for valid in (False, True):+ with self.subTest(path=path, valid=valid):+ first = pull() if valid else pull(body="")+ last = copy.deepcopy(first)+ parts = path.split(".")+ node = last+ for part in parts[:-1]:+ node = node[part]+ node[parts[-1]] = value+ api = FakeApi(first, issue(), last) if valid else FakeApi(first, last)+ with self.assertRaisesRegex(policy.PolicyError, "changed during"):+ policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)++ def test_malformed_recheck_data_fails_closed(self):+ for path, value in (+ ("user", None), ("user", {}), ("head", []), ("base", "bad"), ("head.repo", []),+ ("number", 23.0), ("merged", 0),+ ):+ with self.subTest(path=path):+ last = pull()+ parts = path.split(".")+ node = last+ for part in parts[:-1]:+ node = node[part]+ node[parts[-1]] = value+ with self.assertRaises(policy.PolicyError):+ policy.check_policy(FakeApi(pull(), issue(), last), REPOSITORY, 23, ACTIVATED_AT)++ def test_checkbox_after_a_list_or_quote_needs_its_own_block(self):+ for prefix in ("- Example:", "1. Example:", "> Example:", " - Example:", "- [ ] Example task:"):+ with self.subTest(prefix=prefix):+ body = NO_AGENT.replace(TEST_CONFIRMATION, prefix + "\n" + TEST_CONFIRMATION)+ self.assertIsNotNone(policy.body_requirement(body))+ public = NO_AGENT.replace(TEST_CONFIRMATION, prefix + "\n\n" + TEST_CONFIRMATION)+ self.assertIsNone(policy.body_requirement(public))+ public = NO_AGENT.replace(TEST_CONFIRMATION, "- Example:\n## Tests\n" + TEST_CONFIRMATION)+ self.assertIsNone(policy.body_requirement(public))+++class ParserTests(unittest.TestCase):+ def test_supported_lines_and_duplicates(self):+ body = "Closes #7\nfixes #7\nResolves https://github.com/OWNER/REPO/issues/8 "+ self.assertEqual(policy.issue_references(body, REPOSITORY), [7, 8])++ def test_only_complete_plain_lines_count(self):+ examples = [+ "Related to #7", "Closes #7 because it fails", "- Closes #7", "> Fixes #7", "`Closes #7`",+ " Closes #7", "\tCloses #7", "Closes #0", "Closes #07", "Closes #7, #8",+ " Closes #7", " Closes #7", " Closes #7",+ "Closes other/repo#7", "Closes https://github.com/other/repo/issues/7",+ "Closes http://github.com/owner/repo/issues/7", "Closes https://github.com/owner/repo/pull/7",+ "Closes https://github.com/owner/repo/issues/7?x=1", "[Closes #7](https://example.com)",+ ]+ for body in examples:+ with self.subTest(body=body):+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])++ def test_comments_and_code_do_not_count(self):+ examples = [+ "<!-- Closes #7 -->", "<!--\nCloses #7\n-->", "<!--\nCloses #7",+ "```text\nCloses #7\n```", "~~~\nCloses #7\n~~~", " ```\nCloses #7\n ```",+ "````\n```\nCloses #7\n```\n````", "Closes <!-- example -->#7",+ ]+ for body in examples:+ with self.subTest(body=body):+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertEqual(policy.issue_references("```\nCloses #7\n```\nCloses #8", REPOSITORY), [8])++ def test_limit_bounds_api_reads(self):+ body = "\n".join(f"Closes #{number}" for number in range(1, 22))+ with self.assertRaises(policy.PolicyError):+ policy.issue_references(body, REPOSITORY)++ def test_body_size_is_bounded(self):+ with self.assertRaisesRegex(policy.PolicyError, "size limit"):+ policy.plain_lines("x" * (128 * 1024 + 1))++ def test_ai_records_and_no_agent_statement_pass(self):+ second_agent = "\n\nHarness: Hermes Agent\nModel: example-model-v1\nWork: Diagnose a synthetic failure.\n"+ for body in (NO_AGENT, AGENT_USE, AGENT_USE + second_agent):+ with self.subTest(body=body):+ self.assertIsNone(policy.body_requirement(body))+ concrete_work = AGENT_USE.replace("Write policy tests.", "Replace [x] parser logic.")+ self.assertIsNone(policy.body_requirement(concrete_work))++ def test_agent_record_count_is_bounded(self):+ records = "Harness: Codex\nModel: gpt-6.1-sol\nWork: Write policy tests.\n"+ body = "## AI agent use\n" + records * 21 + TEST_CONFIRMATION+ self.assertIn("at most 20", policy.body_requirement(body))++ def test_ai_section_is_required_and_has_a_boundary(self):+ examples = [+ "No AI agent used\n" + TEST_CONFIRMATION,+ "## AI agent use\n## Tests\nNo AI agent used\n" + TEST_CONFIRMATION,+ NO_AGENT + "\n## AI agent use\nNo AI agent used",+ "## AI Agent Use\nNo AI agent used\n" + TEST_CONFIRMATION,+ ]+ for body in examples:+ with self.subTest(body=body):+ self.assertIsNotNone(policy.body_requirement(body))++ def test_no_agent_statement_is_exact_and_cannot_mix_with_records(self):+ for statement in ("no AI agent used", "No AI agent used.", "- No AI agent used", "> No AI agent used"):+ with self.subTest(statement=statement):+ self.assertIsNotNone(policy.body_requirement(NO_AGENT.replace("No AI agent used", statement)))+ self.assertIsNotNone(policy.body_requirement(AGENT_USE + "\n\nNo AI agent used"))++ def test_each_record_requires_all_fields_and_real_values(self):+ for field, value in (("Harness", "Codex"), ("Model", "gpt-6.1-sol"), ("Work", "Write policy tests.")):+ for replacement in ("", "...", "TODO", "<value>", "[value]", "unknown", "enter value"):+ with self.subTest(field=field, replacement=replacement):+ body = AGENT_USE.replace(f"{field}: {value}", f"{field}: {replacement}")+ self.assertIsNotNone(policy.body_requirement(body))+ with self.subTest(missing=field):+ self.assertIsNotNone(policy.body_requirement(AGENT_USE.replace(f"{field}: {value}\n", "")))+ self.assertIsNotNone(policy.body_requirement(AGENT_USE + "\n\nHarness: Hermes Agent"))++ def test_disclosure_in_comments_or_code_does_not_count(self):+ section = "## AI agent use\nNo AI agent used"+ for hidden in (+ "<!--\n" + section + "\n-->", "```text\n" + section + "\n```",+ "~~~\n" + section + "\n~~~", " ## AI agent use\n No AI agent used",+ " \t## AI agent use\n \tNo AI agent used",+ ):+ with self.subTest(hidden=hidden):+ self.assertIsNotNone(policy.body_requirement(hidden + "\n" + TEST_CONFIRMATION))+ hidden_model = AGENT_USE.replace("Model: gpt-6.1-sol", "<!-- Model: gpt-6.1-sol -->")+ self.assertIsNotNone(policy.body_requirement(hidden_model))++ def test_comments_cannot_turn_code_text_into_assertions(self):+ for end in ("-->", "--!>"):+ with self.subTest(end=end):+ body = f"```text\n<!-- example {end}```\n" + NO_AGENT + "\n```"+ self.assertIsNotNone(policy.body_requirement(body))+ body = f"```text\n<!-- example {end}```\nCloses #7\n```"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(f"```text <!-- example {end}\n" + NO_AGENT + "\n```"))+ self.assertIsNone(policy.body_requirement(f"<!--\n```\n{end}\n" + NO_AGENT))++ def test_both_html_comment_end_tags_restore_public_lines(self):+ for end in ("-->", "--!>"):+ with self.subTest(end=end):+ body = f"Closes #6\n<!--\nCloses #7\n{end}\nCloses #8"+ self.assertEqual(policy.issue_references(body, REPOSITORY), [6, 8])+ hidden = "<!--\n" + NO_AGENT + f"\n{end}"+ self.assertIsNotNone(policy.body_requirement(hidden))+ self.assertIsNone(policy.body_requirement(NO_AGENT + "\n\n" + hidden))+ self.assertIsNone(policy.body_requirement(hidden + "\n\n" + NO_AGENT))+ hidden_ai = f"<!--\n## AI agent use\nNo AI agent used\n{end}\n" + TEST_CONFIRMATION+ self.assertIsNotNone(policy.body_requirement(hidden_ai))+ hidden_test = f"## AI agent use\nNo AI agent used\n<!--\n{TEST_CONFIRMATION}\n{end}"+ self.assertIsNotNone(policy.body_requirement(hidden_test))+ self.assertEqual(policy.issue_references(f"<!-- example {end}Closes #7", REPOSITORY), [])++ def test_multiline_inline_code_does_not_count(self):+ for marker in ("`", "``"):+ with self.subTest(marker=marker):+ self.assertEqual(policy.issue_references(marker + "\nCloses #7\n" + marker, REPOSITORY), [])+ self.assertIsNone(policy.body_requirement(marker + "\n" + NO_AGENT + "\n" + marker))+ visible = marker + "\nexample\n" + marker + "\n\n" + NO_AGENT+ self.assertIsNone(policy.body_requirement(visible))+ self.assertEqual(policy.issue_references("`\n` text `\nCloses #7\n`", REPOSITORY), [])++ def test_html_code_blocks_do_not_count(self):+ for tag in ("pre", "code", "script", "style", "textarea", "PRE"):+ with self.subTest(tag=tag):+ body = f'<{tag} class="example">\nCloses #7\n{NO_AGENT}\n</{tag}>'+ self.assertEqual(policy.issue_references(body, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(body))+ self.assertIsNone(policy.body_requirement(body + "\n\n" + NO_AGENT))+ self.assertIsNotNone(policy.body_requirement("<pre>\n</pre><pre>\n" + NO_AGENT + "\n</pre>"))+ self.assertIsNotNone(policy.body_requirement("<pre\n>\n" + NO_AGENT + "\n</pre>"))++ def test_nested_html_code_stays_hidden_until_the_outer_close(self):+ for outer, inner in (("code", "code"), ("code", "pre"), ("pre", "code")):+ with self.subTest(outer=outer, inner=inner):+ hidden = f"<{outer}><{inner}>\nexample\n</{inner}>\nCloses #7\n{NO_AGENT}\n</{outer}>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_comment_tags_cannot_close_or_hide_an_html_code_block(self):+ for end in ("-->", "--!>"):+ for opening in (f"<code>\n<!--\n</code>\n{end}", f"<code><!-- </code> {end}"):+ with self.subTest(end=end, opening=opening):+ hidden = opening + "\nCloses #7\n" + NO_AGENT + "\n</code>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_quoted_html_attributes_cannot_end_code_or_start_comments(self):+ examples = (+ '<code><span title="</code>">', "<code><span title='</code>'>",+ '<code><span\ntitle="\n</code>\n">', "<code><span\ntitle='\n</code>\n'>",+ '<code><span title="</code><!--">',+ )+ for opening in examples:+ with self.subTest(opening=opening):+ hidden = opening + "\nCloses #7\n" + NO_AGENT + "\n</span></code>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_html_quote_and_list_containers_do_not_count(self):+ for tag in ("blockquote", "ul", "ol", "li", "dl"):+ with self.subTest(tag=tag):+ hidden = f"<{tag}>\nCloses #7\n{NO_AGENT}\n</{tag}>"+ self.assertEqual(policy.issue_references(hidden, REPOSITORY), [])+ self.assertIsNotNone(policy.body_requirement(hidden))+ public = hidden + "\n\nCloses #8\n\n" + NO_AGENT+ self.assertEqual(policy.issue_references(public, REPOSITORY), [8])+ self.assertIsNone(policy.body_requirement(public))++ def test_list_and_quote_continuations_do_not_count(self):+ for prefix in ("- Example:", "1. Example:", "> Example:", " - Example:", " > Example:"):+ for indent in ("", " "):+ with self.subTest(prefix=prefix, indent=indent):+ self.assertEqual(policy.issue_references(prefix + "\n" + indent + "Closes #7", REPOSITORY), [])+ self.assertEqual(policy.issue_references("- Example:\n\nCloses #7", REPOSITORY), [7])+ self.assertIsNotNone(policy.body_requirement("- Example:\n " + NO_AGENT.replace("\n", "\n ")))++ def test_test_confirmation_must_be_visible_exact_and_checked(self):+ examples = [+ "", TEST_CONFIRMATION.replace("[x]", "[ ]"), TEST_CONFIRMATION.replace("all passed.", "all passed"),+ TEST_CONFIRMATION + " except one.", "<!-- " + TEST_CONFIRMATION + " -->",+ "```\n" + TEST_CONFIRMATION + "\n```", "~~~\n" + TEST_CONFIRMATION + "\n~~~",+ " " + TEST_CONFIRMATION, " \t" + TEST_CONFIRMATION, "> " + TEST_CONFIRMATION,+ ]+ for line in examples:+ with self.subTest(line=line):+ reason = policy.body_requirement(NO_AGENT.replace(TEST_CONFIRMATION, line))+ self.assertIn("checked line", reason)+ self.assertIsNone(policy.body_requirement(NO_AGENT.replace("[x]", "[X]")))+++class DecisionTests(unittest.TestCase):+ def check(self, api):+ return policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)++ def test_older_issue_passes_and_pr_is_fetched_again(self):+ api = FakeApi(pull(), issue(), pull())+ passed, message = self.check(api)+ self.assertTrue(passed)+ self.assertIn("#7", message)+ self.assertEqual(api.paths, [PR_PATH, "/repos/owner/repo/issues/7", PR_PATH])++ def test_closed_issue_and_different_author_pass(self):+ api = FakeApi(pull(), issue(state="closed"), pull())+ self.assertTrue(self.check(api)[0])++ def test_equal_or_later_issue_fails(self):+ for created_at in ("2026-10-08T18:00:00Z", "2026-10-08T18:00:01Z"):+ with self.subTest(created_at=created_at):+ api = FakeApi(pull(), issue(created_at=created_at), pull())+ self.assertFalse(self.check(api)[0])++ def test_pr_is_not_an_issue(self):+ api = FakeApi(pull(), issue(pull_request={}, html_url="https://github.com/owner/repo/pull/7"), pull())+ self.assertFalse(self.check(api)[0])++ def test_missing_issue_is_confirmed_invalid(self):+ api = FakeApi(pull(), policy.ApiError(404), pull())+ self.assertFalse(self.check(api)[0])++ def test_missing_and_external_references_fail_without_issue_reads(self):+ for body in (None, "", "Closes https://github.com/another/repo/issues/7", "<!-- Closes #7 -->"):+ with self.subTest(body=body):+ data = pull(body=(body or "") + "\n\n" + NO_AGENT)+ api = FakeApi(data, data)+ self.assertFalse(self.check(api)[0])+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_any_one_valid_issue_passes(self):+ data = pull(body="Closes #7\nFixes #8\n\n" + NO_AGENT)+ api = FakeApi(data, policy.ApiError(404), issue(8), data)+ self.assertTrue(self.check(api)[0])++ def test_api_errors_abort_the_decision(self):+ cases = [+ (policy.ApiError(403),),+ (pull(), policy.ApiError(403)),+ (pull(), policy.ApiError(429)),+ (pull(), policy.ApiError(500)),+ (pull(), policy.ApiError()),+ (pull(), issue(), policy.ApiError(500)),+ ]+ for replies in cases:+ with self.subTest(replies=len(replies)):+ with self.assertRaises(policy.ApiError):+ self.check(FakeApi(*replies))++ def test_bad_issue_data_aborts_the_decision(self):+ cases = [issue(number=8), issue(created_at=None), issue(html_url="https://github.com/other/repo/issues/7")]+ for data in cases:+ with self.subTest(data=data):+ with self.assertRaises(policy.PolicyError):+ self.check(FakeApi(pull(), data))++ def test_changed_pr_aborts_both_pass_and_fail(self):+ changes = [+ {"body": "Closes #8"}, {"state": "closed"}, {"merged": True},+ {"head": {"sha": "new-head"}}, {"base": {"ref": "release", "repo": {"full_name": REPOSITORY}}},+ {"user": {"login": "Elevatormusic"}},+ ]+ for change in changes:+ for valid in (False, True):+ with self.subTest(change=change, valid=valid):+ first = pull() if valid else pull(body="")+ last = copy.deepcopy(first)+ last.update(change)+ api = FakeApi(first, issue(), last) if valid else FakeApi(first, last)+ with self.assertRaisesRegex(policy.PolicyError, "changed during"):+ self.check(api)++ def test_mergeability_calculation_does_not_change_the_policy(self):+ api = FakeApi(pull(mergeable=None), issue(), pull(mergeable=True))+ self.assertTrue(self.check(api)[0])++ def test_closed_or_merged_pr_is_skipped(self):+ for change in ({"state": "closed"}, {"merged": True}):+ api = FakeApi(pull(**change))+ self.assertTrue(self.check(api)[0])+ self.assertEqual(api.paths, [PR_PATH])++ def test_old_pr_is_skipped_even_with_current_edits(self):+ data = pull(created_at="2026-10-08T17:09:41Z", body=None, updated_at="2026-10-09T00:00:00Z")+ api = FakeApi(data)+ self.assertTrue(self.check(api)[0])+ self.assertEqual(api.paths, [PR_PATH])++ def test_owner_is_exempt_only_from_the_issue_requirement(self):+ for login in ("Elevatormusic", "ELEVATORMUSIC", "eLeVaToRmUsIc"):+ with self.subTest(login=login):+ data = pull(user={"login": login}, body=NO_AGENT)+ api = FakeApi(data, data)+ self.assertTrue(self.check(api)[0])+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])+ for body in ("", "## AI agent use\nNo AI agent used", TEST_CONFIRMATION):+ with self.subTest(body=body):+ data = pull(user={"login": "Elevatormusic"}, body=body)+ self.assertFalse(self.check(FakeApi(data, data))[0])++ def test_owner_association_and_fork_owner_cannot_exempt_a_contributor(self):+ data = pull(+ body=NO_AGENT, author_association="OWNER",+ head={"repo": {"full_name": "Elevatormusic/fork", "owner": {"login": "Elevatormusic"}}},+ )+ api = FakeApi(data, data)+ self.assertFalse(self.check(api)[0])+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_body_requirements_fail_before_issue_reads(self):+ for body in ("Closes #7", "Closes #7\n## AI agent use\nNo AI agent used"):+ with self.subTest(body=body):+ data = pull(body=body)+ api = FakeApi(data, data)+ passed, reason = self.check(api)+ self.assertFalse(passed)+ self.assertTrue(reason)+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_agent_disclosure_does_not_replace_a_contributor_issue(self):+ data = pull(body=AGENT_USE)+ api = FakeApi(data, data)+ self.assertFalse(self.check(api)[0])+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_author_race_aborts_owner_exemption(self):+ data = pull(user={"login": "Elevatormusic"}, body=NO_AGENT)+ changed = pull(user={"login": "contributor"}, body=NO_AGENT)+ with self.assertRaisesRegex(policy.PolicyError, "changed during"):+ self.check(FakeApi(data, changed))++ def test_pr_at_activation_is_checked(self):+ data = pull(created_at=ACTIVATED_AT, body="")+ api = FakeApi(data, data)+ self.assertFalse(self.check(api)[0])++ def test_missing_or_invalid_activation_fails_before_api_reads(self):+ for activated_at in (None, "", "invalid", "2026-10-08T17:09:42", "2026-02-30T17:09:42Z"):+ with self.subTest(activated_at=activated_at):+ api = FakeApi()+ with self.assertRaisesRegex(policy.PolicyError, "timestamp"):+ policy.check_policy(api, REPOSITORY, 23, activated_at)+ self.assertEqual(api.paths, [])++ def test_malformed_pr_and_timestamp_fail(self):+ for data in (+ pull(number=24), pull(merged="false"), pull(created_at="invalid"), pull(base={}),+ pull(user={}), pull(user={"login": ""}), pull(user={"login": None}),+ ):+ with self.subTest(data=data):+ with self.assertRaises(policy.PolicyError):+ self.check(FakeApi(data))+++class EntryTests(unittest.TestCase):+ def run_main(self, event_name, event, api):+ with tempfile.TemporaryDirectory() as folder:+ event_path = Path(folder) / "event.json"+ event_path.write_text(json.dumps(event), encoding="utf-8")+ env = {+ "GITHUB_REPOSITORY": REPOSITORY,+ "GITHUB_EVENT_PATH": str(event_path),+ "GITHUB_EVENT_NAME": event_name,+ "GITHUB_TOKEN": "fake-test-token",+ "ISSUE_POLICY_ACTIVATED_AT": ACTIVATED_AT,+ }+ output = io.StringIO()+ with patch.dict(os.environ, env, clear=True), patch.object(policy, "GitHubApi", return_value=api):+ with redirect_stdout(output):+ result = policy.main()+ self.assertNotIn("fake-test-token", output.getvalue())+ return result, output.getvalue()++ def test_old_pr_remains_exempt_for_every_event(self):+ for action in ("opened", "reopened", "edited", "synchronize", "ready_for_review"):+ with self.subTest(action=action):+ api = FakeApi(pull(created_at="2026-10-08T17:09:41Z", body=""))+ result, _ = self.run_main("pull_request_target", {"action": action, "number": 23}, api)+ self.assertEqual(result, 0)+ self.assertEqual(api.paths, [PR_PATH])++ def test_dispatch_reads_fresh_pr_and_never_writes(self):+ data = pull(body="")+ api = FakeApi(data, data)+ result, output = self.run_main("workflow_dispatch", {"inputs": {"pr_number": "23"}}, api)+ self.assertEqual(result, 1)+ self.assertTrue(output.startswith("::error::"))+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_event_body_is_never_used_as_current_data(self):+ api = FakeApi(pull(), issue(), pull())+ result, _ = self.run_main(+ "pull_request_target", {"action": "opened", "number": 23, "pull_request": {"body": "bad"}}, api+ )+ self.assertEqual(result, 0)++ def test_event_actor_and_event_author_cannot_exempt_a_contributor(self):+ data = pull(body=NO_AGENT)+ api = FakeApi(data, data)+ result, _ = self.run_main(+ "pull_request_target",+ {"action": "opened", "number": 23, "sender": {"login": "Elevatormusic"},+ "pull_request": {"user": {"login": "Elevatormusic"}, "body": "Closes #7"}},+ api,+ )+ self.assertEqual(result, 1)+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_fresh_api_owner_controls_exemption(self):+ data = pull(user={"login": "Elevatormusic"}, body=AGENT_USE)+ api = FakeApi(data, data)+ result, _ = self.run_main(+ "pull_request_target",+ {"action": "opened", "number": 23, "sender": {"login": "contributor"},+ "pull_request": {"user": {"login": "contributor"}}},+ api,+ )+ self.assertEqual(result, 0)+ self.assertEqual(api.paths, [PR_PATH, PR_PATH])++ def test_bad_dispatch_input_and_unsupported_events_fail_before_api(self):+ cases = [+ ("workflow_dispatch", {"inputs": {"pr_number": "23; echo unsafe"}}),+ ("workflow_dispatch", {"inputs": {"pr_number": "-1"}}),+ ("workflow_dispatch", {"inputs": {"pr_number": True}}),+ ("pull_request", {"action": "opened", "number": 23}),+ ("pull_request_target", {"action": "closed", "number": 23}),+ ]+ for event_name, event in cases:+ with self.subTest(event_name=event_name, event=event):+ api = FakeApi()+ self.assertEqual(self.run_main(event_name, event, api)[0], 1)+ self.assertEqual(api.paths, [])+++class TransportTests(unittest.TestCase):+ def reply(self, raw):+ class Response:+ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, limit):+ return raw[:limit]++ return Response()++ def test_large_issue_bodies_allow_five_prs_with_smaller_pages(self):+ items = [issue(number, user={"login": "contributor"}, body="x" * 65536) for number in range(100, 124)]+ items += [open_pull(number) for number in (23, 24, 25, 26, 27)]+ requests = []+ api = policy.GitHubApi("fake-test-token")++ def reply(request, timeout):+ parsed = urlsplit(request.full_url)+ if parsed.query:+ query = parse_qs(parsed.query)+ size, page = int(query["per_page"][0]), int(query["page"][0])+ requests.append((size, page))+ result = items[(page - 1) * size:page * size]+ else:+ result = pull() if parsed.path == PR_PATH else issue()+ return self.reply(json.dumps(result).encode())++ with patch.object(api.opener, "open", side_effect=reply):+ self.assertTrue(policy.check_policy(api, REPOSITORY, 23, ACTIVATED_AT)[0])+ self.assertEqual(requests, [(100, 1), (50, 1), (25, 1), (12, 1), (12, 2), (12, 3)] * 2)++ def test_one_oversized_item_refuses_with_fixed_transport_limit(self):+ raw = json.dumps([issue(100, user={"login": "contributor"}, body="x" * (1024 * 1024))]).encode()+ reads = []++ class Response:+ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, limit):+ reads.append(limit)+ return raw[:limit]++ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", return_value=Response()) as opened:+ with self.assertRaisesRegex(policy.PolicyError, "size limit.*unknown"):+ policy.author_open_pulls(api, REPOSITORY, "contributor", 23)+ self.assertEqual(opened.call_count, 7)+ self.assertEqual(reads, [1024 * 1024 + 1] * 7)++ def test_oversized_dict_response_is_typed_without_retry(self):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", return_value=self.reply(b"x" * (1024 * 1024 + 1))) as opened:+ with self.assertRaises(policy.ResponseTooLarge):+ api.get(PR_PATH)+ self.assertEqual(opened.call_count, 1)++ def test_request_is_a_get_to_the_fixed_host(self):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", return_value=self.reply(b'{"number": 7}')) as opened:+ self.assertEqual(api.get("/repos/owner/repo/issues/7"), {"number": 7})+ request = opened.call_args.args[0]+ self.assertEqual(request.full_url, "https://api.github.com/repos/owner/repo/issues/7")+ self.assertEqual(request.get_method(), "GET")+ self.assertIsNone(request.data)+ self.assertEqual(opened.call_args.kwargs, {"timeout": 30})++ def test_http_and_network_errors_are_safe_and_do_not_log_response_data(self):+ errors = [+ HTTPError("https://api.github.com", 403, "private-body", {}, None),+ URLError("private-url-or-token"), TimeoutError("private-url-or-token"),+ ]+ for error in errors:+ with self.subTest(kind=type(error).__name__):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", side_effect=error):+ with self.assertRaises(policy.ApiError) as raised:+ api.get(PR_PATH)+ self.assertNotIn("private", str(raised.exception))+ self.assertNotIn("fake-test-token", str(raised.exception))++ def test_invalid_json_and_large_response_fail(self):+ for raw in (b"not-json", b"[]", b"x" * (1024 * 1024 + 1)):+ with self.subTest(size=len(raw)):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", return_value=self.reply(raw)):+ with self.assertRaises(policy.ApiError):+ api.get(PR_PATH)++ def test_list_request_keeps_the_fixed_host_and_does_not_weaken_dict_checks(self):+ api = policy.GitHubApi("fake-test-token")+ path = "/repos/owner/repo/issues?state=open&creator=contributor&per_page=100&page=1"+ with patch.object(api.opener, "open", return_value=self.reply(b'[{"number": 23}]')) as opened:+ self.assertEqual(api.get_list(path), [{"number": 23}])+ request = opened.call_args.args[0]+ self.assertEqual(request.full_url, "https://api.github.com" + path)+ self.assertEqual(request.get_method(), "GET")+ self.assertIsNone(request.data)+ self.assertEqual(opened.call_args.kwargs, {"timeout": 30})+ with patch.object(api.opener, "open", return_value=self.reply(b'[{"number": 23}]')):+ with self.assertRaises(policy.ApiError):+ api.get(PR_PATH)++ def test_list_invalid_json_type_items_size_and_api_errors_fail(self):+ for raw in (b"not-json", b"{}", b"null", b"[null]", b"[true]", b'["item"]',+ json.dumps([{}] * 101).encode(), b"x" * (1024 * 1024 + 1)):+ with self.subTest(size=len(raw)):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", return_value=self.reply(raw)):+ with self.assertRaises(policy.ApiError):+ api.get_list("/repos/owner/repo/issues")+ for error in (HTTPError("https://api.github.com", 500, "private-body", {}, None),+ URLError("private-url-or-token"), TimeoutError("private-url-or-token")):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open", side_effect=error):+ with self.assertRaises(policy.ApiError) as raised:+ api.get_list("/repos/owner/repo/issues")+ self.assertNotIn("private", str(raised.exception))+ self.assertNotIn("fake-test-token", str(raised.exception))++ def test_invalid_api_paths_fail_before_a_request(self):+ for path in ("@example.com", "//example.com/path", "https://example.com", "/repos/owner/repo\r\nunsafe"):+ for method in ("get", "get_list"):+ with self.subTest(path=path, method=method):+ api = policy.GitHubApi("fake-test-token")+ with patch.object(api.opener, "open") as opened:+ with self.assertRaises(policy.ApiError):+ getattr(api, method)(path)+ opened.assert_not_called()++ def test_redirects_are_not_followed(self):+ self.assertIsNone(policy.NoRedirect().redirect_request(None, None, 302, "", {}, "https://example.com"))+++if __name__ == "__main__":+ unittest.main()