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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
34 changes: 28 additions & 6 deletions .github/scripts/ai/update_versions_and_changelogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,11 @@ def get_last_release_tag():
print("[INFO] No release tags found - this is the first release")
return None

# Filter tags based on branch
if current_branch == "test":
filtered_tags = [t for t in all_tags if "-test" in t]
print("[INFO] Filtering for test branch tags (with -test suffix)")
elif current_branch == "main":
# test prepares main's next release, so both diff against main's last
# release. Old -test tags are leftovers and are ignored.
if current_branch in ("test", "main"):
filtered_tags = [t for t in all_tags if "-test" not in t]
print("[INFO] Filtering for main branch tags (without -test suffix)")
print("[INFO] Filtering for release tags (without -test suffix)")
else:
filtered_tags = all_tags
print(f"[INFO] Using all tags for branch: {current_branch}")
Expand All @@ -137,6 +135,24 @@ def get_last_release_tag():
return None


VERSION_STATE_PATHS = [VERSIONS_FILE, CHANGELOGS_FILE, ".version-history"]


def _current_branch():
return subprocess.check_output(["git", "branch", "--show-current"]).decode().strip()


def reset_version_state_to(tag):
"""Restore versions, changelogs and version history to their state at *tag*.

No-overlay restore: files absent at the tag are removed too. Raises on
failure - carrying on would bump already-bumped versions a second time."""
print(f"[INFO] Resetting version state to {tag} before recomputing")
subprocess.run(
["git", "restore", f"--source={tag}", "--", *VERSION_STATE_PATHS], check=True
)


def get_changed_files_with_renames(last_tag):
"""
Get changed files and detect renames.
Expand Down Expand Up @@ -1016,6 +1032,12 @@ def main():

last_tag = get_last_release_tag()

# test runs on every push but always diffs against the same release tag.
# Start each run from the published state at that tag, so pending entries
# are rebuilt from scratch: no double bumps, no stale entries after reverts.
if last_tag and not DRY_RUN and _current_branch() == "test":
reset_version_state_to(last_tag)

changed_files, renames = get_changed_files_with_renames(last_tag)

# Handle first release - only if no tags AND no existing version data
Expand Down
47 changes: 6 additions & 41 deletions .github/scripts/assemble_review_branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
covers deletions and case-renamed media. Don't swap it for
`git checkout <ref> -- <path>`: that only adds files and leaves stale ones behind.

Shared state files are merged per key, so unticked documents keep test's values.
The non-browsable map is merged per key, so unticked documents keep test's
values. Version state is never copied: test generates it.

CLI:
%(prog)s --date 2026-09-21 --all
Expand Down Expand Up @@ -66,11 +67,6 @@ def llm_cache_path(qmd: str) -> str:
return f"{LLM_CACHE_DIR}/{'__'.join(Path(qmd).parts)}.json"


def product_of(qmd: str) -> str:
"""Product directory owning *qmd* (`DOCS/<product>/...`)."""
return Path(qmd).parts[1]


def owned_paths(qmd: str, changed: list[str]) -> list[str]:
"""Paths in *changed* that belong to this document alone."""
stem = qmd[: -len(".qmd")]
Expand Down Expand Up @@ -132,29 +128,6 @@ def _json_at_ref(repo: str | Path, ref: str, path: str) -> dict:
return {}


def _merge_keyed_json(repo: Path, develop_ref: str, rel: str, keys: list[str]) -> bool:
"""Copy only *keys* from develop's copy of *rel* into the on-disk copy."""
develop_data = _json_at_ref(repo, develop_ref, rel)
target = load_json_or_empty(repo / rel, label=rel)
changed = False
for key in keys:
if key in develop_data:
if target.get(key) != develop_data[key]:
target[key] = develop_data[key]
changed = True
elif key in target:
del target[key]
changed = True
if not changed:
return False
path = repo / rel
path.parent.mkdir(parents=True, exist_ok=True)
# Same format as update_versions_and_changelogs.py (indent=2, sort_keys, no
# trailing newline), otherwise the PR diff gets end-of-file noise.
path.write_text(json.dumps(target, indent=2, sort_keys=True), encoding="utf-8")
return True


def _merge_non_browsable_map(repo: Path, develop_ref: str, selection: list[str]) -> bool:
"""Copy each selected document's secret-URL entry.

Expand Down Expand Up @@ -200,19 +173,11 @@ def _merge_non_browsable_map(repo: Path, develop_ref: str, selection: list[str])


def merge_shared_state(repo: Path, develop_ref: str, selection: list[str]) -> list[str]:
"""Merge each selected document's key into the shared state files."""
touched: list[str] = []
"""Merge each selected document's key into the shared state files.

if _merge_keyed_json(repo, develop_ref, f"{LLM_CACHE_DIR}/versions.json", selection):
touched.append(f"{LLM_CACHE_DIR}/versions.json")

by_product: dict[str, list[str]] = {}
for qmd in selection:
by_product.setdefault(product_of(qmd), []).append(qmd)
for product, qmds in by_product.items():
rel = f".version-history/{product}/versions.json"
if _merge_keyed_json(repo, develop_ref, rel, qmds):
touched.append(rel)
Version state (versions.json, change_logs.json, .version-history/) is not
merged: test generates it, so develop's copies are never promoted."""
touched: list[str] = []

if _merge_non_browsable_map(repo, develop_ref, selection):
touched.append(NON_BROWSABLE_MAP)
Expand Down
14 changes: 11 additions & 3 deletions .github/scripts/build_review_checklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,20 @@

# Per-document state: goes with its document, never with the pipeline block.
PER_DOC_STATE_EXACT = {
".llm_cache/versions.json",
".github/non_browsable_doc_map.json",
}
PER_DOC_STATE_PREFIXES = (
".version-history/",
".llm_cache/DOCS__",
)

# Version state is generated on test (and carried to main by the release
# merge). develop's copies are never promoted, per document or as pipeline.
VERSION_STATE_EXACT = {
".llm_cache/versions.json",
".llm_cache/change_logs.json",
}
VERSION_STATE_PREFIXES = (".version-history/",)


def is_pipeline_path(path: str) -> bool:
"""True if *path* belongs to the pipeline block.
Expand All @@ -44,7 +50,9 @@ def is_pipeline_path(path: str) -> bool:
"""
if path.startswith("DOCS/"):
return False
if path in PER_DOC_STATE_EXACT:
if path in PER_DOC_STATE_EXACT or path in VERSION_STATE_EXACT:
return False
if path.startswith(VERSION_STATE_PREFIXES):
return False
return not path.startswith(PER_DOC_STATE_PREFIXES)

Expand Down
88 changes: 88 additions & 0 deletions .github/scripts/check_independent_approval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Fail unless a promotion PR (into test or main) is approved by someone
other than the person who asked for it.

"Asked for" means either of these:
- triggered the open-* workflow that opened the PR. Promotion PRs are
authored by github-actions[bot], so GitHub's own "can't approve your own
PR" never applies. The workflow leaves REQUESTER_MARKER in a bot comment.
- clicked Ready for review. On a selective PR that click picks what lands.

A PR opened by a human counts its author as the requester.

Usage: check_independent_approval.py <pr-number> <head-sha> (needs GH_TOKEN)
"""
import json
import os
import re
import subprocess
import sys

BOT = "github-actions[bot]"
REQUESTER_MARKER = re.compile(r"<!-- promotion-requester: ([A-Za-z0-9-]+) -->")


def gh_items(path):
out = subprocess.check_output(
["gh", "api", "--paginate", path, "--jq", ".[]"], text=True
)
return [json.loads(line) for line in out.splitlines() if line.strip()]


def requesters(pr_author, comments, timeline):
"""Logins that may not approve. Empty set means the requester is unknown."""
who = set()
if pr_author != BOT:
who.add(pr_author)
for c in comments:
if c["user"]["login"] == BOT:
who.update(REQUESTER_MARKER.findall(c.get("body") or ""))
if not who:
return who # fail closed: don't count Ready clicks as the whole answer
for e in timeline:
if e.get("event") == "ready_for_review" and e.get("actor"):
who.add(e["actor"]["login"])
return who


def independent_approvers(reviews, excluded, head_sha):
"""Reviewers whose latest decisive review approves head_sha."""
latest = {}
for r in sorted(reviews, key=lambda r: r.get("submitted_at") or ""):
if r["state"] in ("APPROVED", "CHANGES_REQUESTED", "DISMISSED"):
latest[r["user"]["login"]] = r
return sorted(
login for login, r in latest.items()
if r["state"] == "APPROVED"
and r["commit_id"] == head_sha
and login not in excluded
and not login.endswith("[bot]")
)


def main(pr, head_sha):
repo = os.environ["GITHUB_REPOSITORY"]
pr_author = json.loads(subprocess.check_output(
["gh", "api", f"repos/{repo}/pulls/{pr}"], text=True))["user"]["login"]
excluded = requesters(
pr_author,
gh_items(f"repos/{repo}/issues/{pr}/comments"),
gh_items(f"repos/{repo}/issues/{pr}/timeline"),
)
if not excluded:
print("::error::No requester recorded on this PR (expected a "
f"'promotion-requester' comment from {BOT}). Refusing to pass.")
return 1
approvers = independent_approvers(
gh_items(f"repos/{repo}/pulls/{pr}/reviews"), excluded, head_sha)
print(f"Requested by: {', '.join(sorted(excluded))}")
if not approvers:
print("::error::Needs an approval of the current head from someone "
f"other than {', '.join(sorted(excluded))}.")
return 1
print(f"βœ… Independently approved by: {', '.join(approvers)}")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1], sys.argv[2]))
23 changes: 21 additions & 2 deletions .github/workflows/auto-merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ jobs:
- name: Checkout
uses: actions/checkout@v6

# Same script as the independent_approval required check. Run here too
# so a self-approval fails now instead of after the 30 min wait below.
- name: Reject approval by the requester
run: python3 .github/scripts/check_independent_approval.py "$PR" "$HEAD_SHA"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}

- name: Wait for all required status checks to pass
run: |
PR_NUMBER=${{ github.event.pull_request.number }}
Expand All @@ -50,9 +59,19 @@ jobs:
ELAPSED=0

while true; do
# Leave out auto-merge: this job's own run is always in progress,
# so counting it waited out the full timeout (PR #98).
# Each workflow run adds its own check run, so keep the newest per
# name. independent_approval: the run from before this approval may
# still be the newest and read failure; the one this review starts
# replaces it, so treat that failure as pending.
CHECKS=$(gh api \
"repos/${{ github.repository }}/commits/$HEAD_SHA/check-runs" \
--jq '[.check_runs[] | {name: .name, status: .status, conclusion: .conclusion}]')
"repos/${{ github.repository }}/commits/$HEAD_SHA/check-runs?per_page=100" \
--jq '[.check_runs[] | select(.name != "auto-merge")]
| group_by(.name) | map(max_by(.started_at))
| map(if .name == "independent_approval" and .conclusion == "failure"
then .status = "queued" else . end
| {name: .name, status: .status, conclusion: .conclusion})')

TOTAL=$(echo "$CHECKS" | jq 'length')
PENDING=$(echo "$CHECKS" | jq '[.[] | select(.status != "completed")] | length')
Expand Down
25 changes: 19 additions & 6 deletions .github/workflows/deploy-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ on:
- develop
- test
- main
workflow_dispatch: # manual trigger from Actions UI
# Not for people: auto-merge.yml dispatches test's deploy after a
# GITHUB_TOKEN merge (which fires no push). Manual clicks are skipped below.
workflow_dispatch:

# One run per branch - concurrent runs race on the cache commit-back and the
# gh-pages deploy. Queue, don't cancel (a half-written cache is worse).
Expand All @@ -17,6 +19,9 @@ concurrency:
jobs:
deploy_docs:
name: Build and Deploy Docs
# Only open-review-pr / open-release-pr are run by hand. A dispatch from
# the Actions tab is skipped; auto-merge's dispatch runs as the bot.
if: github.event_name != 'workflow_dispatch' || github.actor == 'github-actions[bot]'
runs-on: ubuntu-latest

# Force bash for every run step. Inside a container the default is sh.
Expand All @@ -35,8 +40,9 @@ jobs:
# github-actions[bot], but they can bypass deploy keys, so push as
# the key over SSH.
ssh-key: ${{ secrets.CI_DEPLOY_KEY }}
# develop/test only diff HEAD^..HEAD, so a shallow clone is enough
fetch-depth: ${{ (github.ref_name == 'main' || startsWith(github.ref, 'refs/heads/test-')) && '0' || '50' }}
# test diffs against main's last release tag (versions/changelogs),
# so it needs full history; develop only diffs HEAD^..HEAD.
fetch-depth: ${{ (github.ref_name == 'main' || github.ref_name == 'test' || startsWith(github.ref, 'refs/heads/test-')) && '0' || '50' }}
fetch-tags: true

- name: Mark repo as safe for Git
Expand Down Expand Up @@ -68,17 +74,24 @@ jobs:
fi

# Runs in the container - it carries google-genai + tiktoken.
# One writer per file, flowing one way (develop -> test -> main):
# develop: intros/keywords (.llm_cache/DOCS__*, carried to test per document)
# test: versions/changelogs/version-history, diffed against main's last
# release tag, carried to main by the release merge
# main: nothing - it publishes what test produced. build-docs.sh applies
# the cached intros and versions on every branch.
- name: Update intros, keywords, versions & changelogs
if: github.ref_name != 'main'
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
DRY_RUN: ${{ steps.test_mode.outputs.dry_run }}
run: |
DRY_RUN_FLAG=()
if [[ "$DRY_RUN" == "true" ]]; then DRY_RUN_FLAG=(--dry-run); fi
# --versions runs only on main (real releases) and test-* (dry-run tests).
# develop/test skip it: no version bumps there, and no tags to diff against.
if [[ "$GITHUB_REF_NAME" == "main" || "$GITHUB_REF" == refs/heads/test-* ]]; then
if [[ "$GITHUB_REF" == refs/heads/test-* ]]; then
python .github/scripts/ai/update_documentation.py --intros modified_docs_list.txt --versions "${DRY_RUN_FLAG[@]}"
elif [[ "$GITHUB_REF_NAME" == "test" ]]; then
python .github/scripts/ai/update_documentation.py --versions "${DRY_RUN_FLAG[@]}"
else
python .github/scripts/ai/update_documentation.py --intros modified_docs_list.txt "${DRY_RUN_FLAG[@]}"
fi
Expand Down
41 changes: 41 additions & 0 deletions .github/workflows/independent-approval.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Independent Approval

# Whoever asked for a promotion (ran Open Pre-Release Review PR / Open Release
# PR, or clicked Ready for review) can't be the one who approves it. The
# check fails until someone else approves the current head.
#
# Must be a required check on test and main (require-pr-release ruleset,
# context "independent_approval"). auto-merge.yml runs the same script, but a
# merge from the web UI skips that workflow, so only the ruleset enforces it.
#
# Limitation: pull_request runs the workflow from the PR head, so a promotion
# that changes this file or the script runs the changed version. Changes still
# reach develop only through a reviewed PR.

on:
pull_request:
types: [opened, reopened, synchronize, ready_for_review]
branches: [test, main]
pull_request_review:
types: [submitted, dismissed]

jobs:
independent_approval:
# pull_request_review has no branches filter.
if: github.event.pull_request.base.ref == 'test' || github.event.pull_request.base.ref == 'main'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
steps:
- uses: actions/checkout@v6
with:
sparse-checkout: .github/scripts

- name: Require approval from someone other than the requester
run: python3 .github/scripts/check_independent_approval.py "$PR" "$HEAD_SHA"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
Loading
Loading