From d566569e8eed5d4773320cb681dc7270a0726717 Mon Sep 17 00:00:00 2001 From: "Codex (gpt-6-astra)" Date: Wed, 9 Sep 2026 00:06:37 +0200 Subject: [PATCH 1/4] fix: accept future model versions under trusted harness domains --- .github/workflows/attestations.yaml | 72 +--- .github/workflows/quality.yaml | 3 + .gitignore | 3 + .pre-commit-config.yaml | 10 +- authors.yaml | 20 +- .../openspec/specs/commit-attribution/spec.md | 89 ++++ scripts/author-identity.py | 241 +++++++++++ scripts/check-authorship | 95 +++++ tests/test_author_identity.py | 372 +++++++++++++++++ tests/test_authorship_integration.py | 389 ++++++++++++++++++ 10 files changed, 1225 insertions(+), 69 deletions(-) create mode 100644 docs/openspec/specs/commit-attribution/spec.md create mode 100755 scripts/author-identity.py create mode 100755 scripts/check-authorship create mode 100644 tests/test_author_identity.py create mode 100644 tests/test_authorship_integration.py diff --git a/.github/workflows/attestations.yaml b/.github/workflows/attestations.yaml index 620e553..de9622b 100644 --- a/.github/workflows/attestations.yaml +++ b/.github/workflows/attestations.yaml @@ -26,67 +26,27 @@ jobs: steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: + # The checker, helper, and policy share the trusted base. + ref: ${{ github.event.pull_request.base.sha }} fetch-depth: 0 - - env: - GH_TOKEN: ${{ github.token }} + - name: Verify commit authorship + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} PR_NUMBER: ${{ github.event.pull_request.number }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} run: | - set -o pipefail + set -euo pipefail git fetch --quiet origin "pull/$PR_NUMBER/head" - base=$(git merge-base HEAD "$HEAD_SHA") \ + checked_out=$(git rev-parse HEAD) \ + || { echo "could not resolve the checked-out base"; exit 1; } + [ "$checked_out" = "$BASE_SHA" ] \ + || { echo "the trusted checkout does not match the pull request base"; exit 1; } + range_base=$(git merge-base "$BASE_SHA" "$HEAD_SHA") \ || { echo "could not resolve the merge base; deepen the fetch and rerun"; exit 1; } - # authors.yaml is read from the base ref, deliberately: a pull - # request must not grant itself an identity. An identity lands - # on the default branch first; the commits that use it follow - # in a later pull request. - # Section-aware reads: an entry under trailers: is valid only - # as a Co-Authored-By line. Reading both lists with one grep - # would let a trailer alias validate a wrong author field. - mapfile -t identities < <(awk '/^[^ #]/ { s = /^authors:/ } s && /^ - / { sub(/^ - /, ""); print }' authors.yaml) - mapfile -t trailer_identities < <(awk '/^[^ #]/ { s = /^trailers:/ } s && /^ - / { sub(/^ - /, ""); print }' authors.yaml) - [ "${#identities[@]}" -gt 0 ] || { echo "authors.yaml lists no identities"; exit 1; } - listed() { - for identity in "${identities[@]}"; do - [ "$1" = "$identity" ] && return 0 - done - return 1 - } - trailer_listed() { - for identity in "${trailer_identities[@]}"; do - [ "$1" = "$identity" ] && return 0 - done - return 1 - } - # The range and trailer reads are captured before their loops - # so a failed git invocation fails the check instead of - # feeding an empty loop that passes green. - # Merge commits stay in the range: a merge answers for its - # author like any other commit. - range=$(git log --format='%H%x09%an <%ae>' "$base..$HEAD_SHA") \ - || { echo "could not list commits in $base..$HEAD_SHA"; exit 1; } - failures=0 - while IFS=$'\t' read -r commit author; do - [ -n "$commit" ] || continue - if ! listed "$author"; then - echo "$commit: author '$author' is not in authors.yaml (expected 'Display Name (model-id)
')" - failures=1 - fi - trailers=$(git show -s --format='%(trailers:key=Co-Authored-By,valueonly)' "$commit") \ - || { echo "$commit: could not read Co-Authored-By trailers"; exit 1; } - while read -r trailer; do - [ -n "$trailer" ] || continue - if [ "$trailer" = "$author" ]; then - echo "$commit: author repeated as Co-Authored-By" - failures=1 - elif ! listed "$trailer" && ! trailer_listed "$trailer"; then - echo "$commit: Co-Authored-By '$trailer' is neither a listed identity nor a listed trailer attribution" - failures=1 - fi - done <<< "$trailers" - done <<< "$range" - [ "$failures" -eq 0 ] && echo "every commit in the range carries a listed identity." - exit "$failures" + bash "$GITHUB_WORKSPACE/scripts/check-authorship" \ + --from-ref "$range_base" \ + --to-ref "$HEAD_SHA" \ + --authors-file "$GITHUB_WORKSPACE/authors.yaml" spec: name: spec/presence @@ -103,7 +63,7 @@ jobs: files=$(gh api --paginate "repos/${{ github.repository }}/pulls/$PR_NUMBER/files?per_page=100" \ --jq '[.[] | .filename, (.previous_filename // empty)]' | jq -s -r 'add // [] | .[]') \ || { echo "could not read the changed files; rerun the check"; exit 1; } - protected='^(\.github/workflows/|\.githooks/|templates/|schemas/|\.macroscope/)|^(\.pre-commit-config\.yaml|\.gitleaks\.toml)$' + protected='^(\.github/workflows/|\.githooks/|templates/|schemas/|\.macroscope/)|^(\.pre-commit-config\.yaml|\.gitleaks\.toml|authors\.yaml|scripts/check-authorship|scripts/author-identity\.py)$' spec_tree='^docs/(specs|openspec)/' touched=$(printf '%s\n' "$files" | grep -E "$protected" || true) if [ -z "$touched" ]; then diff --git a/.github/workflows/quality.yaml b/.github/workflows/quality.yaml index 2e96acc..87d819d 100644 --- a/.github/workflows/quality.yaml +++ b/.github/workflows/quality.yaml @@ -77,6 +77,9 @@ jobs: tar -xzf "gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" gitleaks sudo install gitleaks /usr/local/bin/gitleaks + - name: Authorship regression tests + run: python3 -m unittest discover -s tests -p 'test_author*.py' + - name: Commit-stage checks uses: j178/prek-action@5337cb91e0fa35a7ff31b9ca345126d8bbbcdf16 # v2 diff --git a/.gitignore b/.gitignore index a9b45e0..d8a5fe3 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,6 @@ Cargo.lock # SpecStory writes transcripts to the working layer, not the repository. .specstory/ + +# Python test bytecode stays local. +__pycache__/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1e491ea..fb1f5f9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -88,7 +88,7 @@ repos: - id: semgrep name: semgrep OWASP - entry: semgrep scan --config=p/owasp-top-ten --metrics=off --quiet . + entry: semgrep scan --config=p/owasp-top-ten --metrics=off --disable-version-check --quiet . language: system pass_filenames: false stages: [pre-push] @@ -99,3 +99,11 @@ repos: language: system pass_filenames: false stages: [pre-push] + + - id: check-authorship + name: authorship (push range) + entry: bash scripts/check-authorship + language: system + pass_filenames: false + always_run: true + stages: [pre-push] diff --git a/authors.yaml b/authors.yaml index 6ccd727..bf26f10 100644 --- a/authors.yaml +++ b/authors.yaml @@ -1,15 +1,6 @@ -# Identities for the ci/authorship check. Two lists, two policies. -# -# authors: valid as the commit author, and as a Co-Authored-By trailer. -# The author field MUST match one entry exactly. Model identities carry -# the model id in parentheses and a non-routable per-model address. -# -# trailers: valid ONLY as a Co-Authored-By trailer, never as the author. -# These are the attribution lines coding harnesses append to the commit -# message. They form a second provenance channel: the author names who -# made the commit, the trailer names who helped or which tool assisted. -# Keeping them separate means a wrong author field can never validate -# through a trailer alias. +# Commit attribution policy. Human identities and vendor aliases stay explicit. +# Model identities use matching IDs and an approved harness domain. +# See docs/openspec/specs/commit-attribution/spec.md for the contract. authors: - Martin Zeman - Claude (claude) @@ -27,3 +18,8 @@ trailers: - Claude Opus 5 - Claude Opus 4.8 - Claude Sonnet 5 + +model_domains: + - claude.noreply.nexus.local + - codex.noreply.nexus.local + - grok.noreply.nexus.local diff --git a/docs/openspec/specs/commit-attribution/spec.md b/docs/openspec/specs/commit-attribution/spec.md new file mode 100644 index 0000000..523dcdb --- /dev/null +++ b/docs/openspec/specs/commit-attribution/spec.md @@ -0,0 +1,89 @@ +# Commit Attribution Specification + +## Purpose + +The authorship check validates declared commit attribution under trusted repository policy. +It does not prove which model executed the work. + +## Requirements + +### Requirement: Future Model Identities + +The check MUST accept exact `authors:` entries and formatted model identities under trusted harness domains. +A formatted identity MUST use `Display Name (model-id) `. +The display and address IDs MUST match after context normalization. +A model ID MUST contain lowercase ASCII alphanumeric segments separated by dots or hyphens. +The domain MUST match an approved `.noreply.nexus.local` entry exactly. +New model versions under approved domains MUST require no catalog update. +Human identities and vendor aliases MUST remain exact policy entries. + +#### Scenario: Future version + +- **WHEN** an unlisted Fable 5.2 or Astra identity has matching IDs under an approved harness domain +- **THEN** the check accepts the identity + +#### Scenario: Mismatch or domain spoofing + +- **WHEN** the model IDs differ or the domain adds a suffix to an approved domain +- **THEN** the check rejects the identity + +### Requirement: Trusted Domain Policy + +The check MUST read `model_domains:` from trusted `authors.yaml`. +When the list is absent, the check MUST infer domains from valid model entries in trusted `authors:`. +An explicit list MUST replace inference, including `model_domains: []`. +Trailer-only entries MUST NOT grant model domains. +The check MUST reject malformed policy before it examines the commit range. + +#### Scenario: Legacy policy + +- **WHEN** trusted policy lists model authors and omits `model_domains:` +- **THEN** the check accepts future model IDs under those author domains + +#### Scenario: Explicit empty list + +- **WHEN** trusted policy declares `model_domains: []` +- **THEN** the check accepts only exact author entries + +#### Scenario: Trailer-only domain + +- **WHEN** a domain appears only in a trailer entry +- **THEN** the check rejects an unlisted author under that domain + +### Requirement: Trusted Execution and Commit Range + +CI MUST execute the checker and helper from the exact pull request base checkout. +CI MUST use the policy from that same checkout. +CI MUST inspect every commit from the merge base to the pull request head, including merge commits. +Local pre-push checks MUST use the same checker with `origin/main:authors.yaml`. +The check MUST fail when policy, commit references, or history reads fail. +Head changes MUST NOT authorize their own identities or replace CI checker code. +Authorship source and policy changes MUST receive the existing specification-presence check. + +#### Scenario: Head policy change + +- **WHEN** a head adds its own unapproved domain or changes the checker +- **THEN** CI uses base code and base policy to evaluate that head + +#### Scenario: Local outgoing range + +- **WHEN** a push contains an invalid author in any outgoing commit +- **THEN** the pre-push check rejects the range and names the commit + +### Requirement: Contributor Identity + +The check MUST accept exact `trailers:` entries only as contributors. +It MUST reject an author repeated as a contributor by normalized model ID and harness domain. +Normalization MUST remove an explicit trailing `[1m]` annotation. +It MUST map `claude-fable-51m` and `claude-opus-51m` to their respective version 5 IDs. +Other IDs ending in `1m` MUST retain their identity. + +#### Scenario: Trailer alias used as author + +- **WHEN** a commit uses an exact trailer-only alias as its author +- **THEN** the check rejects the commit + +#### Scenario: Author repeated through an alias + +- **WHEN** the contributor differs only by display name or a recognized context annotation +- **THEN** the check rejects the repeated author diff --git a/scripts/author-identity.py b/scripts/author-identity.py new file mode 100755 index 0000000..385ce80 --- /dev/null +++ b/scripts/author-identity.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Check attribution syntax against trusted policy, not model execution. + +The policy uses plain YAML block lists. Quoted values, aliases, tags, and +multiline scalars are outside this restricted format. +""" + +import argparse +import json +import re +import sys +from dataclasses import dataclass +from pathlib import Path + + +class PolicyError(ValueError): + """The trusted policy is missing or malformed.""" + + +class IdentityError(ValueError): + """The identity does not satisfy the policy.""" + + +@dataclass(frozen=True) +class Policy: + authors: tuple[str, ...] + trailers: tuple[str, ...] = () + model_domains: tuple[str, ...] = () + + +MODEL_ID = re.compile(r"[a-z0-9]+(?:[.-][a-z0-9]+)*\Z", re.ASCII) +HARNESS = re.compile(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*\Z", re.ASCII) +DOMAIN_SUFFIX = ".noreply.nexus.local" +LEGACY_MODELS = { + "claude-fable-51m": "claude-fable-5", + "claude-opus-51m": "claude-opus-5", +} + + +def canonical_model_id(model: str) -> str: + """Remove an explicit context suffix or a known historical alias.""" + model = model.removesuffix("[1m]") + if not MODEL_ID.fullmatch(model): + raise IdentityError( + "model ID must use lowercase ASCII letters, digits, dots, and hyphens" + ) + return LEGACY_MODELS.get(model, model) + + +def _address(identity: str) -> tuple[str, str, str]: + if not identity or not identity.isprintable() or identity != identity.strip(): + raise IdentityError( + "identity must contain printable text without surrounding whitespace" + ) + match = re.fullmatch(r"([^<>]+) <([^<>\s@]+)@([^<>\s@]+)>", identity) + if not match or not match[1].strip() or match[1] != match[1].strip(): + raise IdentityError("identity must use 'Display Name
'") + return match[1], match[2], match[3] + + +def _model(identity: str) -> tuple[str, str]: + name, local, domain = _address(identity) + match = re.fullmatch(r"(.+) \(([^()]*)\)", name) + if not match or not match[1].strip() or match[1] != match[1].strip(): + raise IdentityError( + "model identity must include a final parenthesized model ID" + ) + model = canonical_model_id(match[2]) + if canonical_model_id(local) != model: + raise IdentityError("display model ID and address model ID must match") + return domain, model + + +def _valid_domain(domain: str) -> bool: + return domain.endswith(DOMAIN_SUFFIX) and bool( + HARNESS.fullmatch(domain[: -len(DOMAIN_SUFFIX)]) + ) + + +def parse_policy(text: str) -> Policy: + """Parse the supported YAML subset and reject ambiguous policy data.""" + text = text.replace("\r\n", "\n") + if any(not character.isprintable() and character != "\n" for character in text): + raise PolicyError("policy contains a control character") + lists: dict[str, list[str]] = {} + section = None + empty_sections = set() + for number, line in enumerate(text.split("\n"), 1): + if not line.strip() or line.lstrip().startswith("#"): + continue + header = re.fullmatch(r"([a-z_]+):(?:[ ]*(\[\]))?[ ]*", line) + if header: + section = header[1] + if section not in {"authors", "trailers", "model_domains"}: + raise PolicyError(f"line {number}: unknown policy key") + if section in lists: + raise PolicyError(f"line {number}: duplicate policy key") + lists[section] = [] + if header[2]: + empty_sections.add(section) + continue + item = re.fullmatch(r" - (\S(?:.*\S)?)", line) + if not item or section is None or section in empty_sections: + raise PolicyError( + f"line {number}: expected a plain list entry with four spaces" + ) + value = item[1] + if value[0] in "[]{}&*!|>'\"%@`" or " #" in value or ": " in value: + raise PolicyError(f"line {number}: unsupported YAML scalar") + if value in lists[section]: + raise PolicyError(f"line {number}: duplicate policy entry") + lists[section].append(value) + if not lists.get("authors"): + raise PolicyError("policy must contain a nonempty authors list") + for identity in lists["authors"] + lists.get("trailers", []): + try: + _, _, domain = _address(identity) + if domain.lower().endswith(DOMAIN_SUFFIX): + if not _valid_domain(domain): + raise IdentityError( + "listed model identity has an invalid harness domain" + ) + _model(identity) + except IdentityError as error: + raise PolicyError(f"invalid listed identity: {error}") from error + if set(lists["authors"]) & set(lists.get("trailers", [])): + raise PolicyError("an identity appears in both authors and trailers") + if "model_domains" in lists: + domains = lists["model_domains"] + else: + # Legacy policy already names its approved harnesses through authors. + # Trailer-only aliases cannot grant author permissions. + domains = sorted( + { + _address(author)[2] + for author in lists["authors"] + if _valid_domain(_address(author)[2]) + } + ) + if any(not _valid_domain(domain) for domain in domains): + raise PolicyError("model domains must use '.noreply.nexus.local'") + return Policy( + tuple(lists["authors"]), tuple(lists.get("trailers", [])), tuple(domains) + ) + + +def load_policy(path: str | Path) -> Policy: + try: + return parse_policy(Path(path).read_text(encoding="utf-8")) + except (OSError, UnicodeError) as error: + raise PolicyError(f"cannot read policy: {error}") from error + + +def validate_identity(policy: Policy, identity: str, *, trailer: bool = False) -> None: + """Raise IdentityError unless the identity is valid in the selected role.""" + _address(identity) + if identity in policy.authors: + return + if identity in policy.trailers: + if trailer: + return + raise IdentityError("a trailer-only alias cannot be the commit author") + domain, _ = _model(identity) + if domain not in policy.model_domains: + raise IdentityError("model domain is not trusted by the policy") + + +def identity_key(policy: Policy, identity: str) -> tuple[str, ...]: + """Return a canonical key for a valid author or contributor identity.""" + validate_identity(policy, identity, trailer=True) + try: + domain, model = _model(identity) + except IdentityError: + return "exact", identity + if _valid_domain(domain): + return "model", domain, model + return "exact", identity + + +def resolve_identity(policy: Policy, model: str, harness: str = "") -> str: + """Resolve an existing identity or format one for a trusted harness.""" + model = canonical_model_id(model) + if harness and not HARNESS.fullmatch(harness): + raise IdentityError("harness must be a lowercase ASCII slug") + domain = harness + DOMAIN_SUFFIX + matches = [] + for identity in policy.authors: + try: + listed_domain, listed_model = _model(identity) + if listed_model == model and (not harness or listed_domain == domain): + matches.append(identity) + except IdentityError: + continue + if len(matches) > 1: + raise IdentityError("model and harness match multiple listed identities") + if matches: + return matches[0] + if not harness: + raise IdentityError("provide a harness for a new model identity") + if domain not in policy.model_domains: + raise IdentityError("model domain is not trusted by the policy") + identity = f"{harness.title()} ({model}) <{model}@{domain}>" + validate_identity(policy, identity) + return identity + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False) + commands = parser.add_subparsers(dest="command", required=True) + for name in ("check-policy", "validate", "key", "resolve"): + command = commands.add_parser(name, allow_abbrev=False) + command.add_argument("--policy", required=True) + if name in {"validate", "key"}: + command.add_argument("--identity", required=True) + if name == "validate": + command.add_argument("--trailer", action="store_true") + if name == "resolve": + command.add_argument("--model", required=True) + command.add_argument("--harness", default="") + args = parser.parse_args(argv) + try: + policy = load_policy(args.policy) + if args.command == "validate": + validate_identity(policy, args.identity, trailer=args.trailer) + elif args.command == "key": + print( + json.dumps(identity_key(policy, args.identity), separators=(",", ":")) + ) + elif args.command == "resolve": + print(resolve_identity(policy, args.model, args.harness)) + except PolicyError as error: + print(f"author-identity: {error}", file=sys.stderr) + return 2 + except IdentityError as error: + print(f"author-identity: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check-authorship b/scripts/check-authorship new file mode 100755 index 0000000..7b543ab --- /dev/null +++ b/scripts/check-authorship @@ -0,0 +1,95 @@ +#!/bin/bash +# Check commit attribution with the trusted base policy. +# CI supplies its base policy path. Local checks read origin/main. +set -o pipefail + +from="${PRE_COMMIT_FROM_REF:-}" +to="${PRE_COMMIT_TO_REF:-HEAD}" +authors_file="" +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) || exit 1 +helper="$script_dir/author-identity.py" + +usage() { + echo "usage: scripts/check-authorship [--from-ref ] [--to-ref ] [--authors-file ]" >&2 + exit 2 +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --from-ref) + [ "$#" -ge 2 ] || usage + from=$2 + shift 2 + ;; + --to-ref) + [ "$#" -ge 2 ] || usage + to=$2 + shift 2 + ;; + --authors-file) + [ "$#" -ge 2 ] || usage + authors_file=$2 + shift 2 + ;; + *) usage ;; + esac +done + +if [ -n "$authors_file" ]; then + authors_source=$authors_file +else + authors_source="origin/main:authors.yaml" + authors_file=$(mktemp) || exit 1 + trap 'rm -f -- "$authors_file"' EXIT + trap 'exit 1' HUP INT TERM + git show "$authors_source" > "$authors_file" \ + || { echo "check-authorship: cannot read $authors_source. Fetch origin/main."; exit 1; } +fi +python3 "$helper" check-policy --policy "$authors_file" || exit $? + +to_commit=$(git rev-parse --verify "$to^{commit}" 2>/dev/null) \ + || { echo "check-authorship: cannot resolve target commit $to"; exit 1; } + +# A new remote branch has a zero from-ref. +case "$from" in + '' | 0000000000000000000000000000000000000000) + from=$(git merge-base origin/main "$to_commit" 2>/dev/null) \ + || { echo "check-authorship: cannot resolve origin/main. Set PRE_COMMIT_FROM_REF."; exit 1; } + ;; +esac +from_commit=$(git rev-parse --verify "$from^{commit}" 2>/dev/null) \ + || { echo "check-authorship: cannot resolve base commit $from"; exit 1; } + +# Capture each Git read before its loop so a failed read fails the check. +range=$(git log --format='%H' "$from_commit..$to_commit") \ + || { echo "check-authorship: cannot list commits in $from_commit..$to_commit"; exit 1; } +failures=0 +while IFS= read -r commit; do + [ -n "$commit" ] || continue + author=$(git show -s --format='%an <%ae>' "$commit") \ + || { echo "$commit: cannot read author"; exit 1; } + author_key="" + if python3 "$helper" validate --policy "$authors_file" --identity "$author"; then + author_key=$(python3 "$helper" key --policy "$authors_file" --identity "$author") || exit 1 + else + echo "$commit: author '$author' does not satisfy $authors_source" + failures=1 + fi + trailers=$(git show -s --format='%(trailers:key=Co-Authored-By,valueonly)' "$commit") \ + || { echo "$commit: cannot read Co-Authored-By trailers"; exit 1; } + while IFS= read -r trailer; do + [ -n "$trailer" ] || continue + if python3 "$helper" validate --policy "$authors_file" --identity "$trailer" --trailer; then + trailer_key=$(python3 "$helper" key --policy "$authors_file" --identity "$trailer") || exit 1 + if [ "$trailer_key" = "$author_key" ]; then + echo "$commit: author repeated as Co-Authored-By" + failures=1 + fi + else + echo "$commit: Co-Authored-By '$trailer' does not satisfy $authors_source" + failures=1 + fi + done <<< "$trailers" +done <<< "$range" +[ "$failures" -ne 0 ] || echo "Every commit in $from_commit..$to_commit satisfies $authors_source." +exit "$failures" diff --git a/tests/test_author_identity.py b/tests/test_author_identity.py new file mode 100644 index 0000000..f3e5ad8 --- /dev/null +++ b/tests/test_author_identity.py @@ -0,0 +1,372 @@ +"""Unit tests for attribution policy parsing and model identity syntax.""" + +import contextlib +import importlib.util +import io +import json +import sys +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "author-identity.py" +SPEC = importlib.util.spec_from_file_location("author_identity", SCRIPT) +identity = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = identity +SPEC.loader.exec_module(identity) + +OWNER = "Martin Zeman " +ALIAS = "Claude " +OLD = ( + "Claude Fable 51m (claude-fable-51m) " +) +POLICY = f"""# Trusted policy fixture. +authors: + - {OWNER} + - {OLD} +trailers: + - {ALIAS} +model_domains: + - claude.noreply.nexus.local + - codex.noreply.nexus.local + - grok.noreply.nexus.local + - lumo.noreply.nexus.local + - kimi.noreply.nexus.local +""" + + +def model_identity( + model="gpt-6-astra", *, local=None, domain="codex.noreply.nexus.local", name="Codex" +): + return f"{name} ({model}) <{local or model}@{domain}>" + + +class IdentityTests(unittest.TestCase): + def setUp(self): + self.policy = identity.parse_policy(POLICY) + + def test_future_models_need_no_catalog_entry(self): + for model, harness in [ + ("gpt-6-astra", "codex"), + ("claude-fable-5.1", "claude"), + ("claude-fable-5.2", "claude"), + ("claude-fable-5-2", "claude"), + ("futuremodel-2030.12", "kimi"), + ]: + with self.subTest(model=model): + identity.validate_identity( + self.policy, + model_identity(model, domain=f"{harness}.noreply.nexus.local"), + ) + + def test_exact_human_and_legacy_authors_remain_valid(self): + for author in (OWNER, OLD): + identity.validate_identity(self.policy, author) + identity.validate_identity(self.policy, author, trailer=True) + + def test_trailer_alias_cannot_author(self): + identity.validate_identity(self.policy, ALIAS, trailer=True) + with self.assertRaises(identity.IdentityError): + identity.validate_identity(self.policy, ALIAS) + self.assertEqual(identity.identity_key(self.policy, ALIAS), ("exact", ALIAS)) + + def test_unlisted_human_fails(self): + with self.assertRaises(identity.IdentityError): + identity.validate_identity(self.policy, "Other Person ") + + def test_untrusted_or_spoofed_domains_fail(self): + for domain in ( + "other.noreply.nexus.local", + "codex.noreply.nexus.local.evil.test", + "codex.noreply.nexus.local.", + "CODEX.noreply.nexus.local", + "example.com", + ): + with self.subTest(domain=domain), self.assertRaises(identity.IdentityError): + identity.validate_identity(self.policy, model_identity(domain=domain)) + + def test_mismatched_model_ids_fail(self): + with self.assertRaises(identity.IdentityError): + identity.validate_identity(self.policy, model_identity(local="gpt-5.6-sol")) + + def test_bad_model_ids_fail(self): + for model in ( + "GPT-6", + "", + "model_1", + "model/1", + "mödél-1", + ".model", + "model.", + "model..1", + "model--1", + "model[2m]", + "model[1m][1m]", + ): + with self.subTest(model=model), self.assertRaises(identity.IdentityError): + identity.canonical_model_id(model) + + def test_malformed_names_and_addresses_fail(self): + for author in ( + "Codex ", + model_identity(name=""), + model_identity(name=" "), + " " + model_identity(), + model_identity() + " ", + model_identity().replace(" <", " <"), + ): + with self.subTest(author=author), self.assertRaises(identity.IdentityError): + identity.validate_identity(self.policy, author) + + def test_control_characters_fail(self): + for control in ("\n", "\r", "\t", "\x00", "\x1b", "\x7f", "\u202e"): + with ( + self.subTest(control=repr(control)), + self.assertRaises(identity.IdentityError), + ): + identity.validate_identity( + self.policy, model_identity(name="Co" + control + "dex") + ) + + def test_printable_unicode_display_name_passes(self): + identity.validate_identity(self.policy, model_identity(name="Vývojář")) + + def test_context_suffix_keys_match(self): + canonical = model_identity() + expanded = model_identity( + "gpt-6-astra[1m]", local="gpt-6-astra", name="Other display" + ) + identity.validate_identity(self.policy, expanded) + self.assertEqual( + identity.identity_key(self.policy, canonical), + identity.identity_key(self.policy, expanded), + ) + + def test_legacy_exact_author_key_is_canonical(self): + current = model_identity( + "claude-fable-5", + domain="claude.noreply.nexus.local", + name="Different display", + ) + self.assertEqual( + identity.identity_key(self.policy, OLD), + identity.identity_key(self.policy, current), + ) + self.assertEqual( + identity.canonical_model_id("claude-opus-51m"), "claude-opus-5" + ) + + def test_arbitrary_trailing_1m_is_preserved(self): + self.assertEqual(identity.canonical_model_id("future-51m"), "future-51m") + self.assertNotEqual( + identity.identity_key(self.policy, model_identity("future-51m")), + identity.identity_key(self.policy, model_identity("future-5")), + ) + + def test_model_keys_include_the_harness(self): + self.assertNotEqual( + identity.identity_key(self.policy, model_identity()), + identity.identity_key( + self.policy, model_identity(domain="claude.noreply.nexus.local") + ), + ) + + def test_resolve_uses_unique_listed_identity(self): + self.assertEqual( + identity.resolve_identity(self.policy, "claude-fable-5", "claude"), OLD + ) + + def test_resolve_unique_known_model_without_harness(self): + self.assertEqual(identity.resolve_identity(self.policy, "claude-fable-5"), OLD) + + def test_resolve_ambiguous_known_model_without_harness(self): + other = model_identity("claude-fable-5", domain="codex.noreply.nexus.local") + policy = identity.parse_policy( + POLICY.replace("trailers:", f" - {other}\ntrailers:") + ) + with self.assertRaises(identity.IdentityError): + identity.resolve_identity(policy, "claude-fable-5") + + def test_resolve_future_model_requires_harness(self): + with self.assertRaises(identity.IdentityError): + identity.resolve_identity(self.policy, "gpt-6-astra") + + def test_resolve_generates_future_model_identity(self): + self.assertEqual( + identity.resolve_identity(self.policy, "gpt-6-astra[1m]", "codex"), + model_identity(), + ) + + def test_resolve_rejects_unknown_harness_or_model(self): + for model, harness in ( + ("gpt-6-astra", "unknown"), + ("gpt-6-astra", "codex.evil"), + ("gpt-6-astra", "Codex"), + ("bad/model", "codex"), + ): + with ( + self.subTest(model=model, harness=harness), + self.assertRaises(identity.IdentityError), + ): + identity.resolve_identity(self.policy, model, harness) + + def test_resolve_rejects_ambiguous_listed_matches(self): + other = model_identity("claude-fable-5", domain="claude.noreply.nexus.local") + policy = identity.parse_policy( + POLICY.replace("trailers:", f" - {other}\ntrailers:") + ) + with self.assertRaises(identity.IdentityError): + identity.resolve_identity(policy, "claude-fable-5", "claude") + + def test_legacy_policy_infers_only_author_harness_domains(self): + policy = identity.parse_policy(f"authors:\n - {OLD}\n") + self.assertEqual( + identity.resolve_identity(policy, "claude-fable-5", "claude"), OLD + ) + with self.assertRaises(identity.IdentityError): + identity.validate_identity(policy, model_identity()) + future = model_identity("claude-fable-5.2", domain="claude.noreply.nexus.local") + identity.validate_identity(policy, future) + self.assertEqual(policy.model_domains, ("claude.noreply.nexus.local",)) + + def test_legacy_trailer_domain_does_not_grant_author_permissions(self): + policy = identity.parse_policy( + f"authors:\n - {OWNER}\ntrailers:\n - {OLD}\n" + ) + self.assertEqual(policy.model_domains, ()) + with self.assertRaises(identity.IdentityError): + identity.validate_identity( + policy, + model_identity("claude-fable-5.2", domain="claude.noreply.nexus.local"), + ) + + def test_explicit_empty_domains_disable_legacy_inference(self): + policy = identity.parse_policy(f"authors:\n - {OLD}\nmodel_domains: []\n") + identity.validate_identity(policy, OLD) + with self.assertRaises(identity.IdentityError): + identity.validate_identity( + policy, + model_identity("claude-fable-5.2", domain="claude.noreply.nexus.local"), + ) + + def test_explicit_domains_override_legacy_author_domains(self): + policy = identity.parse_policy( + f"authors:\n - {OLD}\nmodel_domains:\n - codex.noreply.nexus.local\n" + ) + identity.validate_identity(policy, model_identity()) + with self.assertRaises(identity.IdentityError): + identity.validate_identity( + policy, + model_identity("claude-fable-5.2", domain="claude.noreply.nexus.local"), + ) + + def test_malformed_policy_fails_closed(self): + for text in ( + "", + "authors:\n", + "authors: []\n", + f"trailers:\n - {ALIAS}\n", + POLICY + "authors:\n", + POLICY + "unknown:\n", + POLICY + f" - {OWNER}\n", + POLICY.replace(f" - {OWNER}", f" - {OWNER}\n - {OWNER}"), + POLICY.replace("authors:", "authors: []"), + POLICY.replace(f" - {OWNER}", f' - "{OWNER}"'), + POLICY.replace( + f" - {OWNER}", " - &owner Person " + ), + POLICY.replace(f" - {OWNER}", " - *owner"), + POLICY.replace(f" - {OWNER}", " - not-an-identity"), + POLICY.replace(" - claude.noreply", " - claude.noreply"), + POLICY.replace(f" - {ALIAS}", f" - {OWNER}"), + POLICY.replace("# Trusted policy fixture.", "# bad\x00comment"), + ): + with self.subTest(text=text), self.assertRaises(identity.PolicyError): + identity.parse_policy(text) + + def test_invalid_or_duplicate_domains_fail_closed(self): + for domain in ( + "example.com", + "*.noreply.nexus.local", + "codex.noreply.nexus.local.evil", + "Codex.noreply.nexus.local", + "a..b.noreply.nexus.local", + "codex.noreply.nexus.local", + ): + with self.subTest(domain=domain), self.assertRaises(identity.PolicyError): + identity.parse_policy(POLICY + f" - {domain}\n") + + def test_listed_internal_model_entries_require_consistency(self): + malformed = ( + model_identity(local="gpt-5.6-sol"), + "Codex ", + model_identity("GPT-6-astra"), + model_identity(domain="codex.NOREPLY.nexus.local"), + model_identity(domain="bad..harness.noreply.nexus.local"), + ) + for entry in malformed: + for existing in (OLD, ALIAS): + with ( + self.subTest(entry=entry, existing=existing), + self.assertRaises(identity.PolicyError), + ): + identity.parse_policy(POLICY.replace(existing, entry)) + + def test_external_human_parentheses_remain_exact(self): + human = "Martin Zeman (work) " + policy = identity.parse_policy(POLICY.replace(OWNER, human)) + identity.validate_identity(policy, human) + identity.validate_identity(policy, ALIAS, trailer=True) + self.assertEqual(identity.identity_key(policy, human), ("exact", human)) + + def test_empty_optional_lists_and_crlf_are_valid(self): + policy = identity.parse_policy( + f"authors:\r\n - {OWNER}\r\ntrailers: []\r\nmodel_domains: []\r\n" + ) + self.assertEqual(policy, identity.Policy((OWNER,))) + + def test_cli_exit_codes_and_stable_key(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "authors.yaml" + path.write_text(POLICY, encoding="utf-8") + + def invoke(command, *arguments): + output, errors = io.StringIO(), io.StringIO() + with ( + contextlib.redirect_stdout(output), + contextlib.redirect_stderr(errors), + ): + code = identity.main([command, "--policy", str(path), *arguments]) + return code, output.getvalue(), errors.getvalue() + + self.assertEqual(invoke("check-policy")[0], 0) + self.assertEqual(invoke("validate", "--identity", model_identity())[0], 0) + self.assertEqual(invoke("validate", "--identity", ALIAS)[0], 1) + self.assertEqual(invoke("validate", "--identity", ALIAS, "--trailer")[0], 0) + code, output, _ = invoke("key", "--identity", model_identity()) + self.assertEqual(code, 0) + self.assertEqual( + json.loads(output), + ["model", "codex.noreply.nexus.local", "gpt-6-astra"], + ) + self.assertEqual( + invoke("resolve", "--model", "gpt-6-astra", "--harness", "codex")[ + 1 + ].strip(), + model_identity(), + ) + path.write_text("authors: []\n", encoding="utf-8") + self.assertEqual(invoke("check-policy")[0], 2) + self.assertEqual(invoke("validate", "--identity", model_identity())[0], 2) + path.write_text( + POLICY.replace(OLD, model_identity(local="gpt-5.6-sol")), + encoding="utf-8", + ) + self.assertEqual(invoke("check-policy")[0], 2) + self.assertEqual(invoke("validate", "--identity", OWNER)[0], 2) + path.unlink() + self.assertEqual(invoke("check-policy")[0], 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_authorship_integration.py b/tests/test_authorship_integration.py new file mode 100644 index 0000000..f7e0ec2 --- /dev/null +++ b/tests/test_authorship_integration.py @@ -0,0 +1,389 @@ +"""Exercise attribution checks in isolated, local Git fixture repositories. + +Fixtures use Git plumbing and isolated configuration. They never use project +hooks, credentials, remote services, or the source repository's Git metadata. +""" + +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SCRIPTS = (ROOT / "scripts",) +OWNER = "Fixture Owner " +TOOL = "Fixture Tool " +LEGACY = "Claude Legacy (claude-opus-51m) " +POLICY = f"""authors: + - {OWNER} + - {LEGACY} +trailers: + - {TOOL} +model_domains: + - codex.noreply.nexus.local + - claude.noreply.nexus.local +""" +ZERO = "0" * 40 + + +def model_identity( + model="gpt-6-astra", *, harness="codex", display="Codex", local=None +): + return f"{display} ({model}) <{local or model}@{harness}.noreply.nexus.local>" + + +class SourceWiringTests(unittest.TestCase): + def test_ci_uses_the_exact_base_checkout(self): + workflow = (ROOT / ".github/workflows/attestations.yaml").read_text() + authorship = workflow.split(" spec:", 1)[0] + self.assertIn("ref: ${{ github.event.pull_request.base.sha }}", authorship) + self.assertIn('checked_out=$(git rev-parse HEAD)', authorship) + self.assertIn('[ "$checked_out" = "$BASE_SHA" ]', authorship) + self.assertNotIn("ref: ${{ github.event.pull_request.head.sha }}", authorship) + + def test_ci_uses_the_shared_checker_and_base_policy(self): + workflow = (ROOT / ".github/workflows/attestations.yaml").read_text() + authorship = workflow.split(" spec:", 1)[0] + self.assertIn('bash "$GITHUB_WORKSPACE/scripts/check-authorship"', authorship) + self.assertIn('--authors-file "$GITHUB_WORKSPACE/authors.yaml"', authorship) + self.assertIn('range_base=$(git merge-base "$BASE_SHA" "$HEAD_SHA")', authorship) + + def test_local_authorship_check_runs_at_pre_push(self): + config = (ROOT / ".pre-commit-config.yaml").read_text() + hook = config.split("- id: check-authorship", 1)[1].split("- id:", 1)[0] + self.assertIn("entry: bash scripts/check-authorship", hook) + self.assertIn("stages: [pre-push]", hook) + self.assertIn("pass_filenames: false", hook) + self.assertIn("always_run: true", hook) + + def test_attribution_sources_require_specification_coverage(self): + workflow = (ROOT / ".github/workflows/attestations.yaml").read_text() + pattern = re.search(r"protected='([^']+)'", workflow).group(1) + for path in ( + "authors.yaml", + "scripts/check-authorship", + "scripts/author-identity.py", + ): + with self.subTest(path=path): + self.assertIsNotNone(re.search(pattern, path)) + + def test_quality_runs_the_authorship_regressions(self): + workflow = (ROOT / ".github/workflows/quality.yaml").read_text() + self.assertIn( + "python3 -m unittest discover -s tests -p 'test_author*.py'", workflow + ) + + +class AuthorshipIntegrationTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="authorship-integration-") + self.addCleanup(self.temporary.cleanup) + self.directory = Path(self.temporary.name) + self.repository = self.directory / "repository" + self.repository.mkdir() + self.git_binary = shutil.which("git") + self.assertIsNotNone(self.git_binary, "Git is required for local fixture tests") + self.environment = { + "PATH": os.environ.get("PATH", os.defpath), + "LC_ALL": "C", + "TMPDIR": str(self.directory), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_SYSTEM": os.devnull, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_TERMINAL_PROMPT": "0", + "GIT_ALLOW_PROTOCOL": "file", + } + self.git("init", "--quiet", "--initial-branch=fixture") + self.base = self.commit(OWNER, "Fixture base", policy=POLICY) + self.git("update-ref", "refs/remotes/origin/main", self.base) + + def run_command(self, arguments, *, content=None, environment=None): + process_environment = self.environment.copy() + process_environment.update(environment or {}) + return subprocess.run( + arguments, + cwd=self.repository, + env=process_environment, + input=content, + text=True, + capture_output=True, + check=False, + timeout=20, + ) + + def git(self, *arguments, content=None, environment=None): + result = self.run_command( + [self.git_binary, *arguments], content=content, environment=environment + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return result.stdout.strip() + + def commit(self, author, message, *, policy=POLICY, parents=()): + files = {"fixture.txt": "Local attribution fixture.\n"} + if policy is not None: + files["authors.yaml"] = policy + (self.repository / "authors.yaml").write_text(policy, encoding="utf-8") + elif (self.repository / "authors.yaml").exists(): + (self.repository / "authors.yaml").unlink() + entries = [] + for name, text in sorted(files.items()): + blob = self.git("hash-object", "-w", "--stdin", content=text) + entries.append(f"100644 blob {blob}\t{name}\n") + tree = self.git("mktree", content="".join(entries)) + name, address = author.rsplit(" <", 1) + author_environment = { + "GIT_AUTHOR_NAME": name, + "GIT_AUTHOR_EMAIL": address[:-1], + "GIT_AUTHOR_DATE": "2000-01-01T00:00:00+00:00", + "GIT_COMMITTER_NAME": "Fixture Builder", + "GIT_COMMITTER_EMAIL": "builder@example.invalid", + "GIT_COMMITTER_DATE": "2000-01-01T00:00:00+00:00", + } + parent_arguments = [ + argument for parent in parents for argument in ("-p", parent) + ] + head = self.git( + "commit-tree", + tree, + *parent_arguments, + content=message + "\n", + environment=author_environment, + ) + self.git("update-ref", "refs/heads/fixture", head) + return head + + def new_head( + self, author, message="Fixture change", *, policy=POLICY, parents=None + ): + return self.commit( + author, + message, + policy=policy, + parents=(self.base,) if parents is None else parents, + ) + + def assert_checks( + self, head, *, passes, base=None, policy_file=None, contains=None + ): + for directory in SCRIPTS: + with self.subTest(script=directory): + arguments = [ + "bash", + str(directory / "check-authorship"), + "--from-ref", + self.base if base is None else base, + "--to-ref", + head, + ] + if policy_file is not None: + arguments.extend(("--authors-file", str(policy_file))) + result = self.run_command(arguments) + output = result.stdout + result.stderr + if passes: + self.assertEqual(result.returncode, 0, output) + else: + self.assertNotEqual(result.returncode, 0, output) + if contains is not None: + self.assertIn(contains, output) + + def test_future_matching_models_pass_without_catalog_entries(self): + for model, harness in ( + ("gpt-6-astra", "codex"), + ("future-model-2035.12", "codex"), + ("future-claude-2036.7", "claude"), + ("claude-fable-5.2", "claude"), + ("claude-fable-5-2", "claude"), + ): + with self.subTest(model=model, harness=harness): + head = self.new_head(model_identity(model, harness=harness)) + self.assert_checks(head, passes=True) + + def test_display_and_address_model_mismatch_fails(self): + head = self.new_head(model_identity(local="gpt-5.6-sol")) + self.assert_checks(head, passes=False, contains=head) + + def test_legacy_base_accepts_future_versions_of_its_author_harnesses(self): + legacy_policy = POLICY.split("model_domains:")[0] + self.base = self.commit(OWNER, "Legacy policy fixture", policy=legacy_policy) + self.git("update-ref", "refs/remotes/origin/main", self.base) + head = self.new_head(model_identity("claude-fable-5.2", harness="claude")) + self.assert_checks(head, passes=True) + head = self.new_head(model_identity()) + self.assert_checks(head, passes=False) + + def test_legacy_base_ignores_head_domain_registration(self): + legacy_policy = POLICY.split("model_domains:")[0] + self.base = self.commit(OWNER, "Legacy policy fixture", policy=legacy_policy) + self.git("update-ref", "refs/remotes/origin/main", self.base) + expanded = legacy_policy.replace( + "trailers:", f" - {model_identity()}\ntrailers:" + ) + head = self.new_head(model_identity(), policy=expanded) + self.assert_checks(head, passes=False) + + def test_explicit_empty_domain_list_blocks_future_model_versions(self): + policy = POLICY.split("model_domains:")[0] + "model_domains: []\n" + self.base = self.commit(OWNER, "Exact-only policy fixture", policy=policy) + self.git("update-ref", "refs/remotes/origin/main", self.base) + head = self.new_head(model_identity("claude-fable-5.2", harness="claude")) + self.assert_checks(head, passes=False) + + def test_head_policy_cannot_authorize_an_unknown_domain(self): + expanded = POLICY + " - unknown.noreply.nexus.local\n" + head = self.new_head(model_identity(harness="unknown"), policy=expanded) + self.assert_checks(head, passes=False, contains=head) + + def test_explicit_trusted_policy_can_authorize_an_additional_domain(self): + head = self.new_head(model_identity(harness="unknown")) + trusted_policy = self.directory / "trusted-authors.yaml" + trusted_policy.write_text( + POLICY + " - unknown.noreply.nexus.local\n", encoding="utf-8" + ) + self.assert_checks(head, passes=False) + self.assert_checks(head, passes=True, policy_file=trusted_policy) + + def test_head_policy_removal_does_not_replace_trusted_policy(self): + head = self.new_head(model_identity(), policy=None) + self.assert_checks(head, passes=True) + + def test_valid_empty_range_passes(self): + self.assert_checks(self.base, passes=True) + + def test_invalid_trusted_policy_fails_even_for_an_empty_range(self): + for policy in ( + "authors: []\n", + POLICY + "model_domains: []\n", + POLICY.replace("codex.noreply.nexus.local", "*.noreply.nexus.local"), + POLICY.replace(" Date: Wed, 9 Sep 2026 01:31:50 +0200 Subject: [PATCH 2/4] fix: validate outgoing authorship and exact model aliases --- .../openspec/specs/commit-attribution/spec.md | 26 ++++ scripts/author-identity.py | 24 +++- scripts/check-authorship | 28 +++-- tests/test_author_identity.py | 48 ++++++- tests/test_authorship_integration.py | 118 ++++++++++++++++++ 5 files changed, 230 insertions(+), 14 deletions(-) diff --git a/docs/openspec/specs/commit-attribution/spec.md b/docs/openspec/specs/commit-attribution/spec.md index 523dcdb..3df1e44 100644 --- a/docs/openspec/specs/commit-attribution/spec.md +++ b/docs/openspec/specs/commit-attribution/spec.md @@ -16,6 +16,10 @@ A model ID MUST contain lowercase ASCII alphanumeric segments separated by dots The domain MUST match an approved `.noreply.nexus.local` entry exactly. New model versions under approved domains MUST require no catalog update. Human identities and vendor aliases MUST remain exact policy entries. +Identity resolution MUST prefer an exact model ID within the selected harness before canonical aliases. +It MUST remove a trailing `[1m]` annotation before this comparison. +Matches across multiple harnesses MUST require an explicit harness. +Multiple exact matches within one harness MUST fail as ambiguous. #### Scenario: Future version @@ -27,6 +31,16 @@ Human identities and vendor aliases MUST remain exact policy entries. - **WHEN** the model IDs differ or the domain adds a suffix to an approved domain - **THEN** the check rejects the identity +#### Scenario: Current and legacy model IDs coexist + +- **WHEN** the policy lists both `claude-fable-5` and `claude-fable-51m` for the selected harness +- **THEN** each ID resolves to its exact author entry + +#### Scenario: Duplicate exact identity + +- **WHEN** two author entries have the same model ID and harness +- **THEN** identity resolution rejects the ambiguity + ### Requirement: Trusted Domain Policy The check MUST read `model_domains:` from trusted `authors.yaml`. @@ -56,6 +70,8 @@ CI MUST execute the checker and helper from the exact pull request base checkout CI MUST use the policy from that same checkout. CI MUST inspect every commit from the merge base to the pull request head, including merge commits. Local pre-push checks MUST use the same checker with `origin/main:authors.yaml`. +For an orphan branch, they MUST inspect every commit reachable from the supplied head. +Target selection MUST prefer `--to-ref`, `PRE_COMMIT_TO_REF`, `GITLEAKS_PUSH_TO_REF`, then `HEAD`. The check MUST fail when policy, commit references, or history reads fail. Head changes MUST NOT authorize their own identities or replace CI checker code. Authorship source and policy changes MUST receive the existing specification-presence check. @@ -70,6 +86,16 @@ Authorship source and policy changes MUST receive the existing specification-pre - **WHEN** a push contains an invalid author in any outgoing commit - **THEN** the pre-push check rejects the range and names the commit +#### Scenario: Outgoing orphan differs from the working copy + +- **WHEN** the hook supplies an orphan through `GITLEAKS_PUSH_TO_REF` while `HEAD` remains on the default branch +- **THEN** the check validates the complete outgoing history against trusted policy + +#### Scenario: Explicit target overrides the environment + +- **WHEN** the caller supplies `--to-ref` and an environment target +- **THEN** the check validates the explicit target + ### Requirement: Contributor Identity The check MUST accept exact `trailers:` entries only as contributors. diff --git a/scripts/author-identity.py b/scripts/author-identity.py index 385ce80..f13feb1 100755 --- a/scripts/author-identity.py +++ b/scripts/author-identity.py @@ -58,7 +58,7 @@ def _address(identity: str) -> tuple[str, str, str]: return match[1], match[2], match[3] -def _model(identity: str) -> tuple[str, str]: +def _raw_model(identity: str) -> tuple[str, str]: name, local, domain = _address(identity) match = re.fullmatch(r"(.+) \(([^()]*)\)", name) if not match or not match[1].strip() or match[1] != match[1].strip(): @@ -68,7 +68,12 @@ def _model(identity: str) -> tuple[str, str]: model = canonical_model_id(match[2]) if canonical_model_id(local) != model: raise IdentityError("display model ID and address model ID must match") - return domain, model + return domain, match[2].removesuffix("[1m]") + + +def _model(identity: str) -> tuple[str, str]: + domain, model = _raw_model(identity) + return domain, canonical_model_id(model) def _valid_domain(domain: str) -> bool: @@ -179,18 +184,29 @@ def identity_key(policy: Policy, identity: str) -> tuple[str, ...]: def resolve_identity(policy: Policy, model: str, harness: str = "") -> str: """Resolve an existing identity or format one for a trusted harness.""" + raw_model = model.removesuffix("[1m]") model = canonical_model_id(model) if harness and not HARNESS.fullmatch(harness): raise IdentityError("harness must be a lowercase ASCII slug") domain = harness + DOMAIN_SUFFIX matches = [] + exact_matches = [] + matched_domains = set() for identity in policy.authors: try: - listed_domain, listed_model = _model(identity) - if listed_model == model and (not harness or listed_domain == domain): + listed_domain, listed_raw = _raw_model(identity) + if canonical_model_id(listed_raw) == model and ( + not harness or listed_domain == domain + ): matches.append(identity) + matched_domains.add(listed_domain) + if listed_raw == raw_model: + exact_matches.append(identity) except IdentityError: continue + if not harness and len(matched_domains) > 1: + raise IdentityError("provide a harness when a model matches multiple harnesses") + matches = exact_matches or matches if len(matches) > 1: raise IdentityError("model and harness match multiple listed identities") if matches: diff --git a/scripts/check-authorship b/scripts/check-authorship index 7b543ab..339fadf 100755 --- a/scripts/check-authorship +++ b/scripts/check-authorship @@ -4,7 +4,7 @@ set -o pipefail from="${PRE_COMMIT_FROM_REF:-}" -to="${PRE_COMMIT_TO_REF:-HEAD}" +to="${PRE_COMMIT_TO_REF:-${GITLEAKS_PUSH_TO_REF:-HEAD}}" authors_file="" script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) || exit 1 helper="$script_dir/author-identity.py" @@ -53,16 +53,30 @@ to_commit=$(git rev-parse --verify "$to^{commit}" 2>/dev/null) \ # A new remote branch has a zero from-ref. case "$from" in '' | 0000000000000000000000000000000000000000) - from=$(git merge-base origin/main "$to_commit" 2>/dev/null) \ + trusted_base=$(git rev-parse --verify 'origin/main^{commit}' 2>/dev/null) \ || { echo "check-authorship: cannot resolve origin/main. Set PRE_COMMIT_FROM_REF."; exit 1; } + if from=$(git merge-base "$trusted_base" "$to_commit" 2>/dev/null); then + : + else + merge_status=$? + # An orphan branch requires a check of its complete reachable history. + [ "$merge_status" -eq 1 ] \ + || { echo "check-authorship: cannot read the merge base for $to_commit"; exit 1; } + from="" + fi ;; esac -from_commit=$(git rev-parse --verify "$from^{commit}" 2>/dev/null) \ - || { echo "check-authorship: cannot resolve base commit $from"; exit 1; } +if [ -n "$from" ]; then + from_commit=$(git rev-parse --verify "$from^{commit}" 2>/dev/null) \ + || { echo "check-authorship: cannot resolve base commit $from"; exit 1; } + revisions="$from_commit..$to_commit" +else + revisions="$to_commit" +fi # Capture each Git read before its loop so a failed read fails the check. -range=$(git log --format='%H' "$from_commit..$to_commit") \ - || { echo "check-authorship: cannot list commits in $from_commit..$to_commit"; exit 1; } +range=$(git log --format='%H' "$revisions") \ + || { echo "check-authorship: cannot list commits in $revisions"; exit 1; } failures=0 while IFS= read -r commit; do [ -n "$commit" ] || continue @@ -91,5 +105,5 @@ while IFS= read -r commit; do fi done <<< "$trailers" done <<< "$range" -[ "$failures" -ne 0 ] || echo "Every commit in $from_commit..$to_commit satisfies $authors_source." +[ "$failures" -ne 0 ] || echo "Every commit in $revisions satisfies $authors_source." exit "$failures" diff --git a/tests/test_author_identity.py b/tests/test_author_identity.py index f3e5ad8..b2e0516 100644 --- a/tests/test_author_identity.py +++ b/tests/test_author_identity.py @@ -179,6 +179,41 @@ def test_resolve_uses_unique_listed_identity(self): def test_resolve_unique_known_model_without_harness(self): self.assertEqual(identity.resolve_identity(self.policy, "claude-fable-5"), OLD) + def test_resolve_exact_raw_ids_before_legacy_aliases(self): + for family in ("fable", "opus"): + canonical = model_identity( + f"claude-{family}-5", domain="claude.noreply.nexus.local" + ) + legacy = model_identity( + f"claude-{family}-51m", domain="claude.noreply.nexus.local" + ) + policy = identity.parse_policy( + POLICY.replace(OLD, canonical + "\n - " + legacy) + ) + for model, expected in ( + (f"claude-{family}-5", canonical), + (f"claude-{family}-51m", legacy), + (f"claude-{family}-5[1m]", canonical), + (f"claude-{family}-51m[1m]", legacy), + ): + for harness in ("", "claude"): + with self.subTest(model=model, harness=harness): + self.assertEqual( + identity.resolve_identity(policy, model, harness), expected + ) + + def test_resolve_legacy_ids_can_use_a_unique_canonical_entry(self): + for family in ("fable", "opus"): + canonical = model_identity( + f"claude-{family}-5", domain="claude.noreply.nexus.local" + ) + policy = identity.parse_policy(POLICY.replace(OLD, canonical)) + with self.subTest(family=family): + self.assertEqual( + identity.resolve_identity(policy, f"claude-{family}-51m", "claude"), + canonical, + ) + def test_resolve_ambiguous_known_model_without_harness(self): other = model_identity("claude-fable-5", domain="codex.noreply.nexus.local") policy = identity.parse_policy( @@ -186,6 +221,12 @@ def test_resolve_ambiguous_known_model_without_harness(self): ) with self.assertRaises(identity.IdentityError): identity.resolve_identity(policy, "claude-fable-5") + self.assertEqual( + identity.resolve_identity(policy, "claude-fable-5", "codex"), other + ) + self.assertEqual( + identity.resolve_identity(policy, "claude-fable-5", "claude"), OLD + ) def test_resolve_future_model_requires_harness(self): with self.assertRaises(identity.IdentityError): @@ -211,12 +252,13 @@ def test_resolve_rejects_unknown_harness_or_model(self): identity.resolve_identity(self.policy, model, harness) def test_resolve_rejects_ambiguous_listed_matches(self): - other = model_identity("claude-fable-5", domain="claude.noreply.nexus.local") + other = model_identity("claude-fable-51m", domain="claude.noreply.nexus.local") policy = identity.parse_policy( POLICY.replace("trailers:", f" - {other}\ntrailers:") ) - with self.assertRaises(identity.IdentityError): - identity.resolve_identity(policy, "claude-fable-5", "claude") + for model in ("claude-fable-5", "claude-fable-51m"): + with self.subTest(model=model), self.assertRaises(identity.IdentityError): + identity.resolve_identity(policy, model, "claude") def test_legacy_policy_infers_only_author_harness_domains(self): policy = identity.parse_policy(f"authors:\n - {OLD}\n") diff --git a/tests/test_authorship_integration.py b/tests/test_authorship_integration.py index f7e0ec2..25cb65b 100644 --- a/tests/test_authorship_integration.py +++ b/tests/test_authorship_integration.py @@ -301,6 +301,124 @@ def test_prek_range_environment_is_honored(self): ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_outgoing_target_precedence(self): + bad = self.new_head(model_identity(harness="unknown")) + self.git("update-ref", "refs/heads/fixture", self.base) + for directory in SCRIPTS: + for arguments, environment, passes in ( + ([], {"GITLEAKS_PUSH_TO_REF": bad}, False), + ( + [], + {"GITLEAKS_PUSH_TO_REF": bad, "PRE_COMMIT_TO_REF": ""}, + False, + ), + ( + [], + {"GITLEAKS_PUSH_TO_REF": bad, "PRE_COMMIT_TO_REF": self.base}, + True, + ), + ( + ["--to-ref", bad], + { + "GITLEAKS_PUSH_TO_REF": self.base, + "PRE_COMMIT_TO_REF": self.base, + }, + False, + ), + ([], {"GITLEAKS_PUSH_TO_REF": "missing-ref"}, False), + ): + with self.subTest(script=directory, environment=environment): + result = self.run_command( + ["bash", str(directory / "check-authorship"), *arguments], + environment=environment, + ) + self.assertEqual( + result.returncode == 0, passes, result.stdout + result.stderr + ) + if not passes and "missing-ref" not in environment.values(): + self.assertIn(bad, result.stdout + result.stderr) + + def test_pre_push_checks_outgoing_orphan_history_while_head_stays_on_main(self): + binaries = self.directory / "fixture-binaries" + binaries.mkdir() + prek = binaries / "prek" + prek.write_text( + "#!/bin/sh\n" + 'test "$*" = "run --stage pre-push --all-files" || exit 90\n' + 'test -n "$GITLEAKS_PUSH_TO_REF" || exit 91\n' + 'exec bash "$FIXTURE_AUTHORSHIP_CHECK"\n', + encoding="utf-8", + ) + prek.chmod(0o755) + (self.repository / ".pre-commit-config.yaml").write_text( + "repos: []\n", encoding="utf-8" + ) + self.git("update-ref", "refs/heads/main", self.base) + self.git("symbolic-ref", "HEAD", "refs/heads/main") + for valid_root in (True, False): + root = self.new_head( + OWNER if valid_root else model_identity(harness="unknown"), + "Outgoing orphan root", + parents=(), + ) + outgoing = self.new_head( + model_identity(), "Valid outgoing tip", parents=(root,) + ) + for directory in SCRIPTS: + with self.subTest(script=directory, valid_root=valid_root): + result = self.run_command( + ["bash", str(directory.parent / ".githooks" / "pre-push")], + content=f"refs/heads/orphan {outgoing} refs/heads/orphan {ZERO}\n", + environment={ + "PATH": str(binaries) + os.pathsep + self.environment["PATH"], + "FIXTURE_AUTHORSHIP_CHECK": str(directory / "check-authorship"), + }, + ) + output = result.stdout + result.stderr + self.assertEqual(result.returncode == 0, valid_root, output) + if valid_root: + self.assertIn(outgoing, output) + else: + self.assertIn(root, output) + self.assertEqual(self.git("rev-parse", "HEAD"), self.base) + + def test_orphan_history_still_requires_a_readable_trusted_base(self): + outgoing = self.new_head(model_identity(), parents=()) + trusted_policy = self.directory / "trusted-authors.yaml" + trusted_policy.write_text(POLICY, encoding="utf-8") + self.git("update-ref", "-d", "refs/remotes/origin/main") + self.assert_checks( + outgoing, + base=ZERO, + passes=False, + policy_file=trusted_policy, + contains="origin/main", + ) + + def test_merge_base_read_errors_fail(self): + head = self.new_head(model_identity()) + binaries = self.directory / "fixture-binaries" + binaries.mkdir() + git = binaries / "git" + git.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "merge-base" ]; then exit 128; fi\n' + 'exec "$FIXTURE_REAL_GIT" "$@"\n', + encoding="utf-8", + ) + git.chmod(0o755) + for directory in SCRIPTS: + with self.subTest(script=directory): + result = self.run_command( + ["bash", str(directory / "check-authorship"), "--to-ref", head], + environment={ + "PATH": str(binaries) + os.pathsep + self.environment["PATH"], + "FIXTURE_REAL_GIT": self.git_binary, + }, + ) + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("cannot read the merge base", result.stdout + result.stderr) + def test_trailer_only_alias_passes_as_a_contributor(self): head = self.new_head( model_identity(), f"Fixture change\n\nCo-Authored-By: {TOOL}" From 6bd5b1355a4d926b407e80f4a6fb652a6d580c1d Mon Sep 17 00:00:00 2001 From: "Codex (gpt-6-astra)" Date: Wed, 9 Sep 2026 01:51:34 +0200 Subject: [PATCH 3/4] fix: release archive locks at guard exit --- .github/workflows/quality.yaml | 8 ++- src/spec/transaction/mod.rs | 40 +++++++++----- src/spec/transaction/tests.rs | 56 +++++++++++++++++++ tests/test_authorship_integration.py | 80 ++++++++++++++++++++++++++++ 4 files changed, 170 insertions(+), 14 deletions(-) diff --git a/.github/workflows/quality.yaml b/.github/workflows/quality.yaml index 87d819d..1eff50c 100644 --- a/.github/workflows/quality.yaml +++ b/.github/workflows/quality.yaml @@ -86,7 +86,11 @@ jobs: # Scan exactly the commits this event introduces. Without a usable # base, gitleaks scans the target history and other hooks inspect all files. - name: Pre-push-stage checks + env: + PR_HEAD: ${{ github.event.pull_request.head.sha }} + PUSH_HEAD: ${{ github.sha }} run: | + to="${PR_HEAD:-$PUSH_HEAD}" if [ -n "${{ github.event.pull_request.base.sha }}" ]; then from="${{ github.event.pull_request.base.sha }}" elif [ -n "${{ github.event.before }}" ] && ! printf '%s' "${{ github.event.before }}" | grep -q '^0*$'; then @@ -95,7 +99,7 @@ jobs: from="" fi if [ -n "$from" ] && git cat-file -e "$from" 2>/dev/null; then - prek run --stage pre-push --from-ref "$from" --to-ref "${{ github.sha }}" + prek run --stage pre-push --from-ref "$from" --to-ref "$to" else - GITLEAKS_PUSH_TO_REF="${{ github.sha }}" prek run --stage pre-push --all-files + GITLEAKS_PUSH_TO_REF="$to" prek run --stage pre-push --all-files fi diff --git a/src/spec/transaction/mod.rs b/src/spec/transaction/mod.rs index 51c7a78..7557b94 100644 --- a/src/spec/transaction/mod.rs +++ b/src/spec/transaction/mod.rs @@ -156,11 +156,28 @@ pub(crate) struct Transaction { root: PathBuf, state_directory: PathBuf, journal_path: PathBuf, - _lock: File, + _lock: LockGuard, io: I, recovery: Option, } +struct LockGuard(File); + +impl LockGuard { + fn acquire(file: File) -> Result { + file.try_lock()?; + Ok(Self(file)) + } +} + +impl Drop for LockGuard { + fn drop(&mut self) { + // A fork can retain another descriptor until exec. + // Release the shared lock when this guard leaves scope. + let _ = self.0.unlock(); + } +} + /// The failure-injection seam, and the deliberate exception to RUST-0008 /// (no traits for internal types): recovery is testable only if every /// phase can fail on demand. Production holds [`SystemIo`] alone; the @@ -230,7 +247,7 @@ impl Transaction { .truncate(false) .open(&lock_path) .map_err(|error| io_error("open", &lock_path, error))?; - lock.try_lock().map_err(|error| { + let lock = LockGuard::acquire(lock).map_err(|error| { let message = match error { fs::TryLockError::WouldBlock => format!( "another spec archive transaction holds {}; retry after it finishes", @@ -614,18 +631,17 @@ pub(super) fn health_findings( Err(error) if error.kind() == io::ErrorKind::NotFound => None, Err(error) => return Err(io_error("open", &lock_path, error)), }; - if let Some(lock) = &lock - && let Err(error) = lock.try_lock() - { - return match error { - fs::TryLockError::WouldBlock => Ok(vec![TransactionHealthFinding { + let lock = match lock.map(LockGuard::acquire).transpose() { + Ok(lock) => lock, + Err(fs::TryLockError::WouldBlock) => { + return Ok(vec![TransactionHealthFinding { severity: super::DiagnosticSeverity::Warning, path: LOCK_FILE.to_string(), message: "another process holds the spec archive lock".to_string(), - }]), - fs::TryLockError::Error(error) => Err(io_error("lock", &lock_path, error)), - }; - } + }]); + } + Err(fs::TryLockError::Error(error)) => return Err(io_error("lock", &lock_path, error)), + }; let state_directory = root.join(TRANSACTION_DIRECTORY); if !state_directory.exists() { @@ -655,7 +671,7 @@ fn incomplete_transaction_findings( root: PathBuf, state_directory: PathBuf, journal_path: PathBuf, - lock: File, + lock: LockGuard, ) -> Result, Error> { let content = fs::read_to_string(&journal_path) .map_err(|error| io_error("read", &journal_path, error))?; diff --git a/src/spec/transaction/tests.rs b/src/spec/transaction/tests.rs index 473ae74..c2d806a 100644 --- a/src/spec/transaction/tests.rs +++ b/src/spec/transaction/tests.rs @@ -293,6 +293,62 @@ fn lock_contention_preserves_the_permanent_lock_file() { assert!(fixture.spec_root.base().join(LOCK_FILE).is_file()); } +#[test] +fn transaction_drop_releases_lock_with_a_duplicated_descriptor() { + let fixture = transaction_fixture(); + let transaction = acquire(&fixture.spec_root).unwrap(); + let Transaction { _lock: lock, .. } = &transaction; + let inherited_descriptor = lock.0.try_clone().unwrap(); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + + drop(transaction); + + let recovered = acquire(&fixture.spec_root).unwrap(); + drop(inherited_descriptor); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + drop(recovered); +} + +#[test] +fn incomplete_health_releases_lock_on_error_before_transaction() { + let fixture = transaction_fixture(); + let file = File::create(fixture.spec_root.base().join(LOCK_FILE)).unwrap(); + let inherited_descriptor = file.try_clone().unwrap(); + let lock = LockGuard::acquire(file).unwrap(); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + let state_directory = fixture.spec_root.base().join(TRANSACTION_DIRECTORY); + + let result = incomplete_transaction_findings( + &fixture.spec_root, + fixture.spec_root.base().to_path_buf(), + state_directory.clone(), + state_directory.join(JOURNAL_FILE), + lock, + ); + + assert!(result.is_err()); + let recovered = acquire(&fixture.spec_root).unwrap(); + drop(inherited_descriptor); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + drop(recovered); +} + #[test] fn prepared_recovery_discards_staged_state() { let fixture = fail_at_phase(Phase::Prepared); diff --git a/tests/test_authorship_integration.py b/tests/test_authorship_integration.py index 25cb65b..2991ca4 100644 --- a/tests/test_authorship_integration.py +++ b/tests/test_authorship_integration.py @@ -10,6 +10,7 @@ import subprocess import sys import tempfile +import textwrap import unittest from pathlib import Path @@ -77,6 +78,12 @@ def test_quality_runs_the_authorship_regressions(self): "python3 -m unittest discover -s tests -p 'test_author*.py'", workflow ) + def test_quality_declares_both_event_targets(self): + workflow = (ROOT / ".github/workflows/quality.yaml").read_text() + step = workflow.split("- name: Pre-push-stage checks", 1)[1] + self.assertIn("PR_HEAD: ${{ github.event.pull_request.head.sha }}", step) + self.assertIn("PUSH_HEAD: ${{ github.sha }}", step) + class AuthorshipIntegrationTests(unittest.TestCase): def setUp(self): @@ -190,6 +197,79 @@ def assert_checks( if contains is not None: self.assertIn(contains, output) + def quality_push_check(self, head, *, pr_head="", pr_base=""): + workflow = (ROOT / ".github/workflows/quality.yaml").read_text() + step = workflow.split("- name: Pre-push-stage checks", 1)[1] + script = textwrap.dedent(step.split("run: |\n", 1)[1]) + values = { + "github.event.pull_request.base.sha": pr_base, + "github.event.pull_request.head.sha": pr_head, + "github.event.before": self.base, + "github.sha": head, + } + for expression, value in values.items(): + script = script.replace("${{ " + expression + " }}", value) + binaries = self.directory / "bin" + binaries.mkdir(exist_ok=True) + prek = binaries / "prek" + checker = str(ROOT / "scripts/check-authorship") + prek.write_text( + f"#!{sys.executable}\n" + "import os, sys\n" + "arguments = sys.argv[1:]\n" + "references = []\n" + "for flag in ('--from-ref', '--to-ref'):\n" + " if flag in arguments:\n" + " references.extend((flag, arguments[arguments.index(flag) + 1]))\n" + f"os.execvp('bash', ['bash', {checker!r}, *references])\n", + encoding="utf-8", + ) + prek.chmod(0o755) + return self.run_command( + ["bash", "-e", "-c", script], + environment={ + "PATH": str(binaries) + os.pathsep + self.environment["PATH"], + "PR_BASE": pr_base, + "PR_HEAD": pr_head, + "PUSH_BASE": self.base, + "PUSH_HEAD": head, + }, + ) + + def test_quality_checks_pr_head_without_synthetic_merge_author(self): + head = self.new_head(model_identity()) + advanced_base = self.commit(OWNER, "Base advance", parents=(self.base,)) + synthetic = self.commit( + "Unlisted Creator ", + "Synthetic merge", + parents=(advanced_base, head), + ) + result = self.quality_push_check(synthetic, pr_head=head, pr_base=advanced_base) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_quality_still_rejects_an_invalid_actual_pr_author(self): + head = self.new_head("Unlisted Author ") + synthetic = self.commit(OWNER, "Synthetic merge", parents=(self.base, head)) + result = self.quality_push_check(synthetic, pr_head=head, pr_base=self.base) + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(head, result.stdout + result.stderr) + + def test_quality_all_files_fallback_checks_the_actual_pr_head(self): + head = self.new_head(model_identity()) + synthetic = self.commit( + "Unlisted Creator ", + "Synthetic merge", + parents=(self.base, head), + ) + result = self.quality_push_check(synthetic, pr_head=head, pr_base="f" * 40) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_quality_push_event_checks_its_own_target(self): + head = self.new_head("Unlisted Author ") + result = self.quality_push_check(head) + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(head, result.stdout + result.stderr) + def test_future_matching_models_pass_without_catalog_entries(self): for model, harness in ( ("gpt-6-astra", "codex"), From 212ea8a06bb70f5ff683e2f5d8ce32f76d8fed9a Mon Sep 17 00:00:00 2001 From: "Codex (gpt-6-astra)" Date: Wed, 9 Sep 2026 11:24:36 +0200 Subject: [PATCH 4/4] fix: validate only the selected docs push --- .githooks/jj-push | 13 +- .githooks/jj-push-bookmark.py | 176 +++++++++++++++ .github/workflows/quality.yaml | 15 ++ tests/test_jj_push.py | 399 +++++++++++++++++++++++++++++++++ 4 files changed, 601 insertions(+), 2 deletions(-) create mode 100644 .githooks/jj-push-bookmark.py create mode 100644 tests/test_jj_push.py diff --git a/.githooks/jj-push b/.githooks/jj-push index baf7e0a..2731eac 100755 --- a/.githooks/jj-push +++ b/.githooks/jj-push @@ -1,7 +1,16 @@ #!/usr/bin/env bash set -euo pipefail -cd "$(jj workspace root 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || dirname "$0")" +workspace_root=$(jj workspace root) +cd "$workspace_root" + +for argument in "$@"; do + case "$argument" in + -b*|--bookmark|--bookmark=*) + exec python3 "$workspace_root/.githooks/jj-push-bookmark.py" "$@" + ;; + esac +done zero=0000000000000000000000000000000000000000 @@ -76,7 +85,7 @@ jj status >/dev/null { synthesize_ref_updates synthesize_argument_updates "$@" -} | sort -u | bash "$(git rev-parse --show-toplevel)/.githooks/pre-push" \ +} | sort -u | bash "$workspace_root/.githooks/pre-push" \ origin "$(git remote get-url origin 2>/dev/null || printf 'origin')" exec jj git push "$@" diff --git a/.githooks/jj-push-bookmark.py b/.githooks/jj-push-bookmark.py new file mode 100644 index 0000000..04b0fe6 --- /dev/null +++ b/.githooks/jj-push-bookmark.py @@ -0,0 +1,176 @@ +"""Validate an exact JJ bookmark in a disposable Git checkout before publication.""" + +import argparse +import json +import subprocess +import sys +import tempfile +from pathlib import Path + + +def run(*arguments, cwd=None, capture=True, content=None): + result = subprocess.run( + arguments, + cwd=cwd, + check=True, + text=True, + input=content, + stdout=subprocess.PIPE if capture else None, + ) + return result.stdout.strip() if capture else "" + + +def target(workspace, bookmark, remote=None, operation=None): + template = 'if(conflict, "CONFLICT", normal_target.commit_id()) ++ "\\n"' + if remote is None: + template = f"if(!remote, {template})" + else: + template = f"if(remote, {template})" + arguments = ["jj"] + if operation is not None: + arguments.extend(["--at-operation", operation]) + arguments.extend(["bookmark", "list", f"exact:{json.dumps(bookmark)}"]) + if remote is not None: + arguments.extend(["--remote", f"exact:{json.dumps(remote)}"]) + value = run(*arguments, "-T", template, cwd=workspace) + if value and (len(value) != 40 or any(c not in "0123456789abcdef" for c in value)): + raise ValueError(f"Cannot resolve one conflict-free target for {bookmark}.") + return value + + +def live_target(git_directory, remote, bookmark): + output = run( + "git", + f"--git-dir={git_directory}", + "ls-remote", + "--refs", + "--", + remote, + f"refs/heads/{bookmark}", + ) + entries = [ + line.split("\t") + for line in output.splitlines() + if line.endswith(f"\trefs/heads/{bookmark}") + ] + if len(entries) > 1: + raise ValueError(f"The remote returned multiple targets for {bookmark}.") + return entries[0][0] if entries else "" + + +def main(arguments): + parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False) + parser.add_argument("-b", "--bookmark", required=True, action="append") + parser.add_argument("--remote", default="origin") + parser.add_argument("--dry-run", action="store_true") + options = parser.parse_args(arguments) + # A literal name keeps validation and publication on the same selection. + if len(options.bookmark) != 1: + raise ValueError("Validate and push one literal bookmark at a time.") + bookmark = options.bookmark[0].removeprefix("exact:") + run("git", "check-ref-format", f"refs/heads/{bookmark}") + if options.remote.startswith("-"): + raise ValueError("Use a named Git remote.") + + workspace = Path(run("jj", "workspace", "root")) + git_directory = run("jj", "git", "root", cwd=workspace) + operation = run( + "jj", "op", "log", "--limit", "1", "--no-graph", "-T", "id", cwd=workspace + ) + head = target(workspace, bookmark, operation=operation) + if not head: + raise ValueError(f"The local bookmark {bookmark} does not exist.") + old = target(workspace, bookmark, options.remote, operation=operation) + if live_target(git_directory, options.remote, bookmark) != old: + raise ValueError( + "The remote bookmark changed. Fetch and reconcile before pushing." + ) + if old == head: + print(f"{bookmark} already matches {options.remote}.", flush=True) + return + + remote_url = run( + "git", f"--git-dir={git_directory}", "remote", "get-url", options.remote + ) + trusted_main = run( + "git", + f"--git-dir={git_directory}", + "rev-parse", + "--verify", + "refs/remotes/origin/main^{commit}", + ) + print(f"Validate {bookmark} at {head[:12]} in an isolated checkout.", flush=True) + # Git writes affect only this disposable, Git-only validation repository. + # Do not export Git repository variables into validators or nested tests. + with tempfile.TemporaryDirectory(prefix="jj-push-validation-") as directory: + snapshot = Path(directory) / "repo" + run("git", "init", "--quiet", str(snapshot)) + refs = [head, "+refs/remotes/origin/main:refs/remotes/origin/main"] + if old: + refs.append(old) + run("git", "fetch", "--quiet", "--no-tags", git_directory, *refs, cwd=snapshot) + run("git", "switch", "--quiet", "--detach", head, cwd=snapshot) + copied_main = run("git", "rev-parse", "refs/remotes/origin/main", cwd=snapshot) + if copied_main != trusted_main: + raise ValueError("The trusted base changed while preparing validation.") + hook = snapshot / ".githooks" / "pre-push" + if not hook.is_file(): + raise ValueError("The outgoing commit has no pre-push hook.") + reference = f"refs/heads/{bookmark}" + update = f"{reference} {head} {reference} {old or '0' * 40}\n" + run( + "bash", + str(hook), + options.remote, + remote_url, + cwd=snapshot, + capture=False, + content=update, + ) + changes = run( + "git", "status", "--porcelain", "--untracked-files=normal", cwd=snapshot + ) + if changes: + raise ValueError( + "Validation changed the checkout. Apply those fixes before pushing.\n" + + changes + ) + + if ( + target(workspace, bookmark) != head + or target(workspace, bookmark, options.remote) != old + ): + raise ValueError( + "The bookmark changed during validation. Run the checks again." + ) + if live_target(git_directory, options.remote, bookmark) != old: + raise ValueError( + "The remote bookmark changed during validation. Fetch and reconcile before pushing." + ) + # Bind publication to the validated remote and literal name. Keep signing intact. + push_arguments = [ + "--remote", + options.remote, + "--bookmark", + f"exact:{json.dumps(bookmark)}", + ] + if options.dry_run: + push_arguments.append("--dry-run") + run( + "jj", + "--at-operation", + operation, + "git", + "push", + *push_arguments, + cwd=workspace, + capture=False, + ) + + +if __name__ == "__main__": + try: + main(sys.argv[1:]) + except (OSError, ValueError, subprocess.CalledProcessError) as error: + print(f"jj push: {error}", file=sys.stderr) + sys.exit(1) diff --git a/.github/workflows/quality.yaml b/.github/workflows/quality.yaml index 1eff50c..73ea472 100644 --- a/.github/workflows/quality.yaml +++ b/.github/workflows/quality.yaml @@ -80,6 +80,21 @@ jobs: - name: Authorship regression tests run: python3 -m unittest discover -s tests -p 'test_author*.py' + - name: Install JJ for push gate tests + env: + JJ_VERSION: "0.45.1" + JJ_SHA256: "f35438350b5d61963aac5dd74ede510b31d6b9690769d1a6268cf058cc825f72" + run: | + scratch=$(mktemp -d) + curl -fsSL -o "$scratch/jj.tar.gz" "https://github.com/jj-vcs/jj/releases/download/v${JJ_VERSION}/jj-v${JJ_VERSION}-x86_64-unknown-linux-musl.tar.gz" + printf '%s %s\n' "$JJ_SHA256" "$scratch/jj.tar.gz" | sha256sum --check + tar -xzf "$scratch/jj.tar.gz" -C "$scratch" ./jj + sudo install "$scratch/jj" /usr/local/bin/jj + jj --version + + - name: Test JJ push gate + run: python3 -m unittest discover -s tests -p 'test_jj_push.py' -v + - name: Commit-stage checks uses: j178/prek-action@5337cb91e0fa35a7ff31b9ca345126d8bbbcdf16 # v2 diff --git a/tests/test_jj_push.py b/tests/test_jj_push.py new file mode 100644 index 0000000..648450f --- /dev/null +++ b/tests/test_jj_push.py @@ -0,0 +1,399 @@ +"""Exercise explicit-bookmark push gates with local, isolated JJ fixtures. + +The fixtures have a bare Git backend and a separate JJ workspace. The only +remote is a temporary local directory. Fixture hooks do not run project code. +""" + +import json +import os +import shlex +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +BOOKMARK = "codex/fixture-policy" +ZERO = "0" * 40 +HOOK = r""" +import json +import os +import subprocess +import sys +from pathlib import Path + +def git(*arguments): + return subprocess.check_output(["git", *arguments], text=True).strip() + +record = { + "cwd": str(Path.cwd()), + "head": git("rev-parse", "HEAD"), + "trusted_main": git("rev-parse", "refs/remotes/origin/main"), + "bare": git("rev-parse", "--is-bare-repository"), + "status": git("status", "--porcelain"), + "updates": sys.stdin.read().splitlines(), + "arguments": sys.argv[1:], + "files": git("ls-files").splitlines(), + "refs": git("for-each-ref", "--format=%(refname)", "refs/heads").splitlines(), +} +Path(os.environ["JJ_PUSH_TEST_RECORD"]).write_text(json.dumps(record)) +mode = os.environ.get("JJ_PUSH_TEST_MODE", "pass") +if mode == "fail": + sys.exit(23) +if mode == "dirty": + Path("payload.txt").write_text("Hook changed the target.\n") +if mode == "move": + subprocess.run( + [os.environ["JJ_PUSH_TEST_REAL_JJ"], "bookmark", "set", + os.environ["JJ_PUSH_TEST_BOOKMARK"], "-r", "main", "--allow-backwards"], + cwd=os.environ["JJ_PUSH_TEST_WORKSPACE"], check=True, + ) +if mode == "remote-move": + subprocess.run( + ["git", "--git-dir", os.environ["JJ_PUSH_TEST_REMOTE"], "update-ref", + "refs/heads/" + os.environ["JJ_PUSH_TEST_BOOKMARK"], record["trusted_main"]], + check=True, + ) +""" + + +class BookmarkPushTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="jj-push-integration-") + self.addCleanup(self.temporary.cleanup) + self.directory = Path(self.temporary.name).resolve() + self.repository = self.directory / "repository" + self.workspace = self.directory / "workspace" + self.remote = self.directory / "remote.git" + self.record = self.directory / "hook.json" + self.command_log = self.directory / "jj-commands.jsonl" + self.git_binary = shutil.which("git") + self.jj_binary = shutil.which("jj") + self.assertIsNotNone(self.git_binary, "Git is required for fixture tests") + self.assertIsNotNone(self.jj_binary, "JJ is required for fixture tests") + self.config = self.directory / "jj-config.toml" + self.config.write_text( + '[user]\nname = "Fixture Owner"\nemail = "owner@example.invalid"\n' + '[signing]\nbehavior = "drop"\n' + "[git]\nsign-on-push = false\ncolocate = false\n" + '[ui]\ncolor = "never"\npager = ":builtin"\n', + encoding="utf-8", + ) + self.environment = { + "PATH": os.environ.get("PATH", os.defpath), + "LC_ALL": "C", + "TMPDIR": str(self.directory), + "JJ_CONFIG": str(self.config), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_SYSTEM": os.devnull, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_TERMINAL_PROMPT": "0", + "GIT_ALLOW_PROTOCOL": "file", + "JJ_PUSH_TEST_RECORD": str(self.record), + "JJ_PUSH_TEST_REAL_JJ": self.jj_binary, + "JJ_PUSH_TEST_WORKSPACE": str(self.workspace), + "JJ_PUSH_TEST_REMOTE": str(self.remote), + "JJ_PUSH_TEST_BOOKMARK": BOOKMARK, + "JJ_PUSH_TEST_LOG": str(self.command_log), + } + self.checked([self.git_binary, "init", "--bare", "--quiet", str(self.remote)]) + self.jj("git", "init", "--no-colocate", str(self.repository)) + hooks = self.repository / ".githooks" + hooks.mkdir() + for name in ("jj-push", "jj-push-bookmark.py"): + source = ROOT / ".githooks" / name + self.assertTrue(source.is_file(), f"Missing implementation: {source}") + shutil.copy2(source, hooks / name) + (hooks / "pre-push").write_text( + "#!/usr/bin/env bash\nexec " + + shlex.quote(sys.executable) + + " -c " + + shlex.quote(HOOK) + + ' "$@"\n', + encoding="utf-8", + ) + (hooks / "pre-push").chmod(0o755) + (self.repository / "payload.txt").write_text("Base fixture.\n") + (self.repository / "authors.yaml").write_text("authors: []\n") + self.jj("describe", "-m", "Fixture base", cwd=self.repository) + self.jj("bookmark", "create", "main", "-r", "@", cwd=self.repository) + self.jj("git", "remote", "add", "origin", str(self.remote), cwd=self.repository) + self.jj("git", "push", "--bookmark", "main", cwd=self.repository) + self.base = self.jj( + "log", "--no-graph", "-r", "main", "-T", "commit_id", cwd=self.repository + ) + self.jj("workspace", "add", str(self.workspace), cwd=self.repository) + self.jj("new", "main", cwd=self.workspace) + (self.workspace / "payload.txt").write_text("Approved target.\n") + self.jj("describe", "-m", "Fixture target", cwd=self.workspace) + self.jj("bookmark", "create", BOOKMARK, "-r", "@", cwd=self.workspace) + self.target = self.jj( + "log", "--no-graph", "-r", BOOKMARK, "-T", "commit_id", cwd=self.workspace + ) + self.jj("new", cwd=self.workspace) + self.install_recording_jj() + + def command(self, arguments, *, cwd=None, environment=None): + command_environment = self.environment.copy() + command_environment.update(environment or {}) + return subprocess.run( + arguments, + cwd=cwd or self.directory, + env=command_environment, + text=True, + capture_output=True, + check=False, + timeout=30, + ) + + def checked(self, arguments, *, cwd=None, environment=None): + result = self.command(arguments, cwd=cwd, environment=environment) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return result.stdout.strip() + + def jj(self, *arguments, cwd=None): + return self.checked([self.jj_binary, *arguments], cwd=cwd) + + def install_recording_jj(self): + directory = self.directory / "bin" + directory.mkdir() + shim = directory / "jj" + shim.write_text( + f"#!{sys.executable}\n" + "import json, os, subprocess, sys\n" + 'with open(os.environ["JJ_PUSH_TEST_LOG"], "a") as log:\n' + ' log.write(json.dumps(sys.argv[1:]) + "\\n")\n' + 'real = os.environ["JJ_PUSH_TEST_REAL_JJ"]\n' + 'if os.environ.get("JJ_PUSH_TEST_FINAL_MOVE") and "push" in sys.argv[1:]:\n' + ' subprocess.run([real, "bookmark", "set", os.environ["JJ_PUSH_TEST_BOOKMARK"],\n' + ' "-r", "main", "--allow-backwards"],\n' + ' cwd=os.environ["JJ_PUSH_TEST_WORKSPACE"], check=True)\n' + "os.execv(real, [real, *sys.argv[1:]])\n", + encoding="utf-8", + ) + shim.chmod(0o755) + self.environment["PATH"] = ( + str(directory) + os.pathsep + self.environment["PATH"] + ) + + def push(self, *arguments, mode="pass"): + return self.command( + ["bash", str(self.workspace / ".githooks" / "jj-push"), *arguments], + cwd=self.workspace, + environment={"JJ_PUSH_TEST_MODE": mode}, + ) + + def remote_target(self, name=BOOKMARK, *, remote=None): + result = self.command( + [ + self.git_binary, + "--git-dir", + str(remote or self.remote), + "rev-parse", + "--verify", + f"refs/heads/{name}", + ] + ) + return result.stdout.strip() if result.returncode == 0 else None + + def assert_hook(self, *, previous, bookmark=BOOKMARK): + self.assertTrue(self.record.is_file(), "The pre-push hook did not run") + record = json.loads(self.record.read_text()) + self.assertEqual(record["head"], self.target) + self.assertEqual(record["trusted_main"], self.base) + self.assertEqual(record["bare"], "false") + self.assertEqual(record["status"], "") + self.assertNotEqual(record["cwd"], str(self.workspace)) + self.assertIn("payload.txt", record["files"]) + self.assertEqual( + record["updates"], + [f"refs/heads/{bookmark} {self.target} refs/heads/{bookmark} {previous}"], + ) + return record + + def test_new_bookmark_without_git_head_uses_exact_workspace_snapshot(self): + self.assertFalse((self.workspace / ".git").exists()) + backend = self.jj("git", "root", cwd=self.workspace) + result = self.command( + [ + self.git_binary, + "--git-dir", + backend, + "show-ref", + "--verify", + f"refs/heads/{BOOKMARK}", + ] + ) + self.assertNotEqual(result.returncode, 0) + result = self.push("--bookmark", BOOKMARK) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=ZERO) + self.assertEqual(self.remote_target(), self.target) + + def test_unrelated_bookmark_does_not_enter_update_range(self): + self.jj("bookmark", "create", "unrelated", "-r", "main", cwd=self.workspace) + result = self.push("-b", BOOKMARK) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=ZERO) + self.assertIsNone(self.remote_target("unrelated")) + + def test_existing_remote_target_sets_exact_previous_sha(self): + self.jj("git", "push", "--bookmark", BOOKMARK, cwd=self.workspace) + previous = self.target + (self.workspace / "payload.txt").write_text("Second approved target.\n") + self.jj("describe", "-m", "Fixture follow-up", cwd=self.workspace) + self.jj("bookmark", "set", BOOKMARK, "-r", "@", cwd=self.workspace) + self.target = self.jj( + "log", "--no-graph", "-r", BOOKMARK, "-T", "commit_id", cwd=self.workspace + ) + self.jj("new", cwd=self.workspace) + result = self.push("--bookmark", BOOKMARK) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=previous) + self.assertEqual(self.remote_target(), self.target) + + def test_checkpoint_and_synthetic_refs_stay_outside_validation(self): + backend = self.jj("git", "root", cwd=self.workspace) + unrelated = ( + "entire/checkpoints/v1", + "jj-push-check", + "unrelated", + ) + for name in unrelated: + self.checked( + [ + self.git_binary, + "--git-dir", + backend, + "update-ref", + f"refs/heads/{name}", + self.base, + ] + ) + result = self.push("--bookmark", BOOKMARK) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + record = self.assert_hook(previous=ZERO) + for name in unrelated: + self.assertNotIn(f"refs/heads/{name}", record["refs"]) + self.assertIsNone(self.remote_target(name)) + + def test_hook_failure_prevents_publication(self): + result = self.push("--bookmark", BOOKMARK, mode="fail") + self.assertNotEqual(result.returncode, 0) + self.assert_hook(previous=ZERO) + self.assertIsNone(self.remote_target()) + + def test_hook_modification_prevents_publication(self): + result = self.push("--bookmark", BOOKMARK, mode="dirty") + self.assertNotEqual(result.returncode, 0) + self.assert_hook(previous=ZERO) + self.assertIsNone(self.remote_target()) + + def test_bookmark_movement_during_hook_prevents_publication(self): + result = self.push("--bookmark", BOOKMARK, mode="move") + self.assertNotEqual(result.returncode, 0) + self.assert_hook(previous=ZERO) + self.assertIsNone(self.remote_target()) + + def test_bookmark_movement_at_publication_keeps_validated_target(self): + self.environment["JJ_PUSH_TEST_FINAL_MOVE"] = "1" + result = self.push("--bookmark", BOOKMARK) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=ZERO) + self.assertEqual(self.remote_target(), self.target) + + def test_remote_movement_during_hook_prevents_publication(self): + result = self.push("--bookmark", BOOKMARK, mode="remote-move") + self.assertNotEqual(result.returncode, 0) + self.assert_hook(previous=ZERO) + self.assertEqual(self.remote_target(), self.base) + + def test_remote_movement_before_hook_requires_reconciliation(self): + self.checked( + [ + self.git_binary, + "--git-dir", + str(self.remote), + "update-ref", + f"refs/heads/{BOOKMARK}", + self.base, + ] + ) + result = self.push("--bookmark", BOOKMARK) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.record.exists()) + self.assertEqual(self.remote_target(), self.base) + + def test_push_binds_resolved_selection_and_keeps_signing_configuration(self): + configuration = self.config.read_bytes() + arguments = ["--bookmark", BOOKMARK, "--dry-run"] + expected_arguments = [ + "--remote", + "origin", + "--bookmark", + f"exact:{json.dumps(BOOKMARK)}", + "--dry-run", + ] + result = self.push(*arguments) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + calls = [json.loads(line) for line in self.command_log.read_text().splitlines()] + self.assertEqual(calls[-1][0], "--at-operation") + self.assertEqual(calls[-1][2:], ["git", "push", *expected_arguments]) + self.assertEqual(self.config.read_bytes(), configuration) + self.assertEqual( + self.jj("config", "get", "git.sign-on-push", cwd=self.workspace), "false" + ) + self.assertIsNone(self.remote_target()) + + def test_brace_named_bookmark_is_published_as_one_literal(self): + literal = "codex/{fixture-a,fixture-b}" + self.jj( + "bookmark", + "create", + json.dumps(literal), + "-r", + BOOKMARK, + cwd=self.workspace, + ) + for name in ("codex/fixture-a", "codex/fixture-b"): + self.jj("bookmark", "create", name, "-r", "main", cwd=self.workspace) + result = self.push("--bookmark", literal) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=ZERO, bookmark=literal) + self.assertEqual(self.remote_target(literal), self.target) + self.assertIsNone(self.remote_target("codex/fixture-a")) + self.assertIsNone(self.remote_target("codex/fixture-b")) + + def test_git_push_configuration_cannot_change_validated_remote(self): + other_remote = self.directory / "other.git" + self.checked([self.git_binary, "init", "--bare", "--quiet", str(other_remote)]) + self.jj("git", "remote", "add", "other", str(other_remote), cwd=self.workspace) + self.config.write_text( + self.config.read_text().replace("[git]\n", '[git]\npush = "other"\n') + ) + self.assertEqual( + self.jj("config", "get", "git.push", cwd=self.workspace), "other" + ) + result = self.push("--bookmark", BOOKMARK) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=ZERO) + self.assertEqual(self.remote_target(), self.target) + self.assertIsNone(self.remote_target(remote=other_remote)) + + def test_mixed_selection_is_rejected_before_hook(self): + result = self.push("--bookmark", BOOKMARK, "--all") + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.record.exists()) + self.assertIsNone(self.remote_target()) + + def test_equals_bookmark_syntax_routes_through_the_gate(self): + result = self.push(f"--bookmark={BOOKMARK}") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_hook(previous=ZERO) + self.assertEqual(self.remote_target(), self.target) + + +if __name__ == "__main__": + unittest.main()