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
4 changes: 4 additions & 0 deletions .agents/skills/pr-writing/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ or say they are from an earlier commit.
different structure.
- **Write from the actual diff.** Re-check the title and description after the scope
changes. Describe crash or bug mechanisms only as far as the code and tests confirm.
- **Keep the description current as the branch evolves.** Whenever commits are added
to a branch with an open PR (review fixes, a rebase replay, a scope change),
re-verify the title and description against the new diff and update what no longer
holds — sections, accepted costs, measured numbers.
- **Professional typesetting and layout.** Structure the description for scanning:
short sections with meaningful headings, bullets for enumerations, tables for
comparisons, `code spans` for identifiers and commands, fenced blocks for code/logs.
Expand Down
88 changes: 74 additions & 14 deletions .claude/hooks/require-fresh-review.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#!/usr/bin/env python3
# Copyright 2026, Datadog, Inc.
"""Claude Code PreToolUse hook: block commands that mention `gh pr create|new|ready`
while the branch's review marker is stale, and `gh pr create` whose title and body
reference no ticket. A single plain `gh pr create|new|ready` call that certainly targets
while the branch's review marker is stale, `gh pr create` whose title and body
reference no ticket, and `gh pr ready` whose PR description was last edited before
the PR's head commit. A single plain `gh pr create|new|ready` call that certainly targets
another repository than this one is not gated. Pushes are gated by .githooks/pre-push."""

import json
import os
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
import re
import shlex
import subprocess
Expand All @@ -26,6 +28,9 @@
# What an exempted command must spell its target as: no host aliases or other forms.
OWNER_REPO = re.compile(r"[\w.-]+/[\w.-]+")
PR_URL = re.compile(r"https://github\.com/([\w.-]+/[\w.-]+)/pull/\d+/?")
# A committer date further ahead than this is a broken clock, not a push from the future:
# the description gate fails open because no description edit can ever postdate it.
COMMIT_DATE_SKEW = timedelta(minutes=5)
# Every character an exempted command may contain. Anything else (\r, \, expansions, operators)
# might split differently in bash than in shell_words, so it keeps the command gated.
PLAIN_COMMAND = re.compile(r"[A-Za-z0-9 ._:/=@'\",+-]+")
Expand Down Expand Up @@ -80,17 +85,17 @@ def repo_flag(tokens):


def ready_target(args, repo, cwd):
"""Check arguments for the PR `gh pr ready` targets, from GitHub so the commits the
PR holds are checked; [] means the current branch, None that it cannot be resolved."""
selector = [a for i, a in enumerate(args)
if not a.startswith("-") and (i == 0 or args[i - 1] not in ("-R", "--repo"))]
"""(PR number, node id, head oid, check arguments) for the PR the PR-ready subcommand
targets, from GitHub so the commits the PR holds are checked; ("", "", "", []) means
the current branch, None that it cannot be resolved."""
selector = pr_selector(args)
out = gh_query(["pr", "view", *selector[:1], *(["-R", repo] if repo else []), "--json",
"headRefName,headRefOid,baseRefName", "-q",
'.headRefName + " " + .headRefOid + " " + .baseRefName'], cwd)
if not out or len(out.split()) != 3:
return None if selector else []
head, oid, base = out.split()
return ["--branch", head, "--commit", oid, "--base", origin(base)]
"id,number,headRefName,headRefOid,baseRefName", "-q",
'"\\(.id) \\(.number) \\(.headRefName) \\(.headRefOid) \\(.baseRefName)"'], cwd)
if not out or len(out.split()) != 5:
return None if selector else ("", "", "", [])
pr_id, number, head, oid, base = out.split()
return number, pr_id, oid, ["--branch", head, "--commit", oid, "--base", origin(base)]


# `gh pr create` flags that take a value, plus the global -R; short form -> long form.
Expand Down Expand Up @@ -224,6 +229,52 @@ def foreign_target(command, top):
return target


def pr_selector(args):
"""The positional PR selectors of a `gh pr` subcommand: words no flag ate."""
return [a for i, a in enumerate(args)
if not a.startswith("-") and (i == 0 or args[i - 1] not in ("-R", "--repo"))]


def gh_time(text):
"""gh's ISO 8601 timestamp ("...Z") as an aware datetime, or None when unparseable
or missing a UTC designator (a naive value would crash the aware-vs-aware comparison)."""
try:
dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
except ValueError:
return None
return None if dt.tzinfo is None else dt


PR_TIMES_QUERY = ('query($i:ID!){node(id:$i){... on PullRequest{lastEditedAt createdAt'
' headRefOid commits(last:1){nodes{commit{committedDate}}}}}}')


def stale_description(pr_id, approved_oid, cwd):
"""True when the PR body was last edited before its head commit, so it may predate
the latest code. GitHub's updatedAt also moves on comments and on pushed commits, so
it cannot date the description: the body's own timestamps are compared (lastEditedAt,
createdAt fallback). The query pins the commit by the PR's own headRefOid: a value
differing from the marker-approved oid means the PR moved between the two gh calls,
and a committer date in the future cannot be dated reliably. None (fail open) when
gh fails, the PR has no commits, a timestamp is unparseable, or either check fires."""
out = gh_query(["api", "graphql", "-f", "query=" + PR_TIMES_QUERY,
"-f", "i=" + pr_id,
"--jq",
('(.data.node) as $p | '
+ '(($p.lastEditedAt // $p.createdAt) // "") + " "'
+ ' + ($p.headRefOid // "") + " "'
+ ' + ($p.commits.nodes[0].commit.committedDate // "")')], cwd)
parts = (out or "").split()
if len(parts) != 3 or parts[1] != approved_oid:
return None
times = [gh_time(part) for part in (parts[0], parts[2])]
if None in times:
return None
if times[1] > datetime.now(timezone.utc) + COMMIT_DATE_SKEW:
return None
return times[0] < times[1]


def network_root(name, top):
"""OWNER/REPO, lowercase, of the root of `name`'s fork network as GitHub resolves it
(the repository itself when it is not a fork); None when gh fails."""
Expand Down Expand Up @@ -333,9 +384,10 @@ def evaluate(source, cwd, sub, args, command, match_text):
"""Return None to allow, else the reason to block."""
if sub == "ready":
# The repo flag may sit before `pr` (`gh -R o/r pr ready`), so read it from the whole match.
extra = ready_target(args, repo_flag(words(match_text)), cwd)
if extra is None:
target = ready_target(args, repo_flag(words(match_text)), cwd)
if target is None:
return "cannot resolve the PR's head commit (gh failed); retry when gh works."
number, pr_id, approved_oid, extra = target
else:
if HEAD_FLAG.search(command):
return "--head names a branch other than the checkout's.\n" \
Expand All @@ -350,6 +402,14 @@ def evaluate(source, cwd, sub, args, command, match_text):
default = default_base(cwd)
if default:
res = run_check(source, cwd, ["--base", default])
if res.returncode == 0 and sub == "ready":
# The probe reuses the PR gh itself resolved (ready_target's node id and the oid
# the marker check approved), so no second URL/flag parse can disagree with it.
stale = stale_description(pr_id, approved_oid, cwd)
if stale:
return "the PR description was last edited before the PR's head commit and " \
"may not match the pushed code. Re-verify the title and description " \
"against the current diff, update or re-save it, then retry."
if res.returncode == 0:
return None
reason = res.stderr.decode(errors="replace").strip()
Expand Down
44 changes: 29 additions & 15 deletions .githooks/pre-push
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
# Copyright 2026, Datadog, Inc.
"""git pre-push hook: refuse to update a branch that has an open PR unless the
pushed commits match its review marker (utils/review-marker.py as of origin/main),
and refuse any branch push whose commit fails the copyright or CLAUDE.md check."""
and refuse any branch push whose commit fails the copyright or CLAUDE.md check.
A push to a branch with an open PR that passes those gates warns to re-verify the
PR description against the pushed commits."""

import subprocess
import sys
Expand Down Expand Up @@ -101,11 +103,12 @@ def main():
sys.stdin.read()
return 0 # the gate is not on the default branch yet
blocked = False
warnings = []
for line in sys.stdin:
parts = line.split()
if len(parts) != 4:
continue
local_ref, local_sha, remote_ref, _ = parts
local_ref, local_sha, remote_ref, remote_sha = parts
if set(local_sha) == {"0"} or not remote_ref.startswith(HEADS):
continue # deletions (all-zero id, SHA-1 or SHA-256) and tags are not gated
remote_branch = remote_ref[len(HEADS):]
Expand All @@ -118,19 +121,30 @@ def main():
res = subprocess.run([sys.executable, "-I", "-c", source, "check", "--branch", branch,
"--commit", local_sha], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# The local check runs first so a fresh marker costs no network call.
if res.returncode == 0 or not has_open_pr(remote_branch):
continue
reason = res.stderr.decode(errors="replace").strip()
if res.returncode == 1:
print("pre-push: %s has an open PR and %s.\nRun the pre-pr-review skill "
"(.agents/skills/pre-pr-review), then push again." % (remote_branch, reason),
file=sys.stderr)
else:
print("pre-push: cannot check the review marker of %s: %s\nFix that, or "
"after a manual review push with --no-verify." % (branch, reason),
file=sys.stderr)
blocked = True
# The open-PR probe runs even for a fresh marker: it also drives the description
# warning below. Fails open (no warning, no block) like every gh call here. A
# remote ref still at the all-zero id is being created by this push and cannot
# have an open PR.
open_pr = False if set(remote_sha) == {"0"} else has_open_pr(remote_branch)
if res.returncode != 0 and open_pr:
reason = res.stderr.decode(errors="replace").strip()
if res.returncode == 1:
print("pre-push: %s has an open PR and %s.\nRun the pre-pr-review skill "
"(.agents/skills/pre-pr-review), then push again." % (remote_branch, reason),
file=sys.stderr)
else:
print("pre-push: cannot check the review marker of %s: %s\nFix that, or "
"after a manual review push with --no-verify." % (branch, reason),
file=sys.stderr)
blocked = True
elif open_pr:
# Deferred: a warning on one ref is noise when another ref blocks the push
# and nothing lands; it prints only when the push goes through.
warnings.append("pre-push: %s has an open PR; re-verify its title and description "
"against the pushed commits (pr-writing skill)." % remote_branch)
if not blocked:
for warning in warnings:
print(warning, file=sys.stderr)
return 1 if blocked else 0


Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,8 @@ via `core.hooksPath`), and in Claude Code and Pi (`.pi/extensions/`) the
Before writing or editing a PR title or description, a PR comment or review reply, a
Jira comment or a commit message, load the `pr-writing` skill
([.agents/skills/pr-writing/SKILL.md](.agents/skills/pr-writing/SKILL.md)).
After pushing commits to a branch with an open PR, re-verify the PR description
against the new diff — the pre-push hook warns, the skill defines what to check.

## CI / Automation Script Changes

Expand Down
7 changes: 5 additions & 2 deletions utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ Standalone, stdlib-only checks over the git-tracked files. Each prints one `<pat
| `check-knowledgebase.py` | Every tracked `.knowledgebase/memories/` file carries cairn's required memory frontmatter. |
| `check-skills.py` | Every tracked `.agents/skills/` skill has loadable frontmatter, `.claude/skills` links to it, and `AGENTS.md` names only existing skills. |

`.githooks/pre-push` runs `check-copyright.py` and `check-claude-md.py` on every pushed branch commit, so a violation stops the push before CI sees it (see `review-marker.py` below for the trust model). Set `branch.<name>.gh-merge-base` for a branch stacked on another feature branch.
`.githooks/pre-push` runs `check-copyright.py` and `check-claude-md.py` on every pushed branch commit, so a violation stops the push before CI sees it (see `review-marker.py` below for the trust model). Set `branch.<name>.gh-merge-base` for a branch stacked on another feature branch. A push to a branch with an open PR that passes those gates warns to re-verify the PR description against the pushed commits; the warning never blocks.

**Usage:**
```bash
Expand Down Expand Up @@ -294,11 +294,14 @@ Records that the agentic pre-PR review covered a branch, and checks it. Used by
- `install-hook` writes a shim to `<git-common-dir>/hooks/pre-push` that runs `.githooks/pre-push` as of `refs/remotes/origin/main`, which loads `review-marker.py` from the same ref; the Claude Code hook loads it from there too. All run with `python3 -I`, so files in the checkout, which may be an untrusted branch (e.g. a fork PR), are not executed or imported. When that ref lacks the scripts (the gate is not merged yet, or there is no `origin` remote), both hooks allow everything. Out of scope: Claude Code runs `.claude/` hooks from the session's own checkout under its workspace-trust model. It never sets `core.hooksPath`, which would replace global hooks such as Datadog's secret scanner; those chain to `.git/hooks`.
- The same shim also runs `check-copyright.py` and `check-claude-md.py` from that ref (see Source quality checks).
- For `gh pr create`, the Claude Code hook also runs `.github/scripts/check_pr_ticket.py` from that ref on the PR title and body; a command it cannot judge passes, and the CI `PR ticket reference` workflow checks it.
- For `gh pr ready`, after the marker check passes the hook also blocks when the PR description was last edited before the PR's head commit. One GraphQL `node(id:)` query reuses the PR gh itself resolved and compares the body's `lastEditedAt` (`createdAt` fallback) with the head commit's date from `commits(last: 1)`, pinned by the query's own `headRefOid` matching the marker-approved commit: GitHub's `updatedAt` also moves on comments and pushed commits, `commits` returns only its first page, and a PR that moved between the two calls cannot be dated. A head commit dated in the future (a broken committer clock) fails open, since no description edit can postdate it. The probes fail open.
- Exit codes: 0 fresh, written or installed; 1 missing or stale; 2 usage or environment error (e.g. missing base ref, git older than 2.39).
- Known limits, all accepted:
- An edit moved between two places whose surrounding lines are identical keeps the same digest, because hunk positions are left out so that rebases stay fresh.
- A fresh marker skips the network, so `pre-push` does not notice an open PR retargeted to a base other than the marker's.
- The marker check itself always runs on every gated push and every gated ready command; a fresh marker only avoids the block. Neither hook notices an open PR retargeted to a base other than the marker's; `pre-push` probes gh for an open PR on every branch push that updates an existing remote ref, so a fresh marker does not skip the network entirely.
- A branch pushed under another name (`git push origin fix:topic`) is found by `pre-push` but not by `gh pr ready`, which blocks rather than allows.
- A rebase or `git push --force-with-lease` replay rewrites commit dates, so the head commit is newer than the description and `gh pr ready` blocks until the body is re-saved (re-saving the identical body moves `lastEditedAt` and clears it).
- The description gate dates the head commit by its committer timestamp, which is backdatable (`GIT_COMMITTER_DATE`) and old when an existing older commit is force-pushed as head; such a head passes the freshness gate even though the pushed code predates the description edit.

**Usage:**
```bash
Expand Down
Loading
Loading