Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions .githooks/jj-push
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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 "$@"
176 changes: 176 additions & 0 deletions .githooks/jj-push-bookmark.py
Original file line number Diff line number Diff line change
@@ -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)
72 changes: 16 additions & 56 deletions .github/workflows/attestations.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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) <address>')"
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
Expand All @@ -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
Expand Down
26 changes: 24 additions & 2 deletions .github/workflows/quality.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,35 @@ 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: 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

# 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
Expand All @@ -92,7 +114,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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,6 @@ Cargo.lock

# SpecStory writes transcripts to the working layer, not the repository.
.specstory/

# Python test bytecode stays local.
__pycache__/
10 changes: 9 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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]
20 changes: 8 additions & 12 deletions authors.yaml
Original file line number Diff line number Diff line change
@@ -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 <N4M3Z@users.noreply.github.com>
- Claude (claude) <claude@claude.noreply.nexus.local>
Expand All @@ -27,3 +18,8 @@ trailers:
- Claude Opus 5 <noreply@anthropic.com>
- Claude Opus 4.8 <noreply@anthropic.com>
- Claude Sonnet 5 <noreply@anthropic.com>

model_domains:
- claude.noreply.nexus.local
- codex.noreply.nexus.local
- grok.noreply.nexus.local
Loading
Loading