Skip to content
Draft
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
7 changes: 7 additions & 0 deletions .github/actionlint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,10 @@ paths:
# 1.7.11 has not learned the key yet. Keep this scoped to R2 Pages.
# https://github.blog/changelog/2026-05-07-github-actions-concurrency-groups-now-allow-larger-queues/
- 'unexpected key "queue" for "concurrency" section'

.github/workflows/translate-finalize-reusable.yml:
ignore:
- 'unexpected key "queue" for "concurrency" section'
.github/workflows/translate-locale-reusable.yml:
ignore:
- 'unexpected key "queue" for "concurrency" section'
190 changes: 164 additions & 26 deletions .github/scripts/i18n/commit_locale_artifact.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
#!/usr/bin/env python3
"""Commit and publish one applied locale artifact.
"""Commit and publish validated translation artifacts through a pull request.

Definition:
This script owns the per-locale commit/push control plane for full
This script owns the aggregate and per-locale publication control plane for full
translation recovery. It expects locale files to have already been applied
and validated, then commits only docs/<locale> and that locale's translation
memory. Canary commits are additionally restricted to the sampled page and
locale translation memory. It retries rebase/push conflicts while guarding
locale translation memory. It retries fetch/rebase conflicts while guarding
against source metadata moving after artifact application.

Parameters:
--locale: Locale directory to commit. Default: LOCALE environment variable.
--base-source-sha: Source SHA observed after artifact application. Default:
BASE_SOURCE_SHA environment variable.
--artifact-dir: Downloaded locale artifact directory. Default: ARTIFACT_DIR.
--attempts: Push/rebase retry count. Default: 5.
--attempts: Fetch/rebase retry count. Default: 5.

Outputs:
GITHUB_OUTPUT receives committed=true or committed=false. The script exits
zero when there is nothing to commit or when source metadata moved after
apply; it exits non-zero only when a commit should have landed but push/retry
failed.
GITHUB_OUTPUT receives committed=true only after the merged PR's translation
tree is verified, or committed=false when no change is published. Stale source
metadata is an explicit skip. Unconfirmed publication exits non-zero and
retains any candidate branch and PR for inspection.

Examples:
LOCALE=fr BASE_SOURCE_SHA=abc python .github/scripts/i18n/commit_locale_artifact.py
Expand All @@ -31,12 +31,17 @@
from __future__ import annotations

import argparse
import hashlib
import json
import os
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Callable

from publication_admission import attest_publication


def run(args: list[str], check: bool = True) -> subprocess.CompletedProcess[str]:
Expand Down Expand Up @@ -144,6 +149,142 @@ def enforce_canary_scope(locale: str, allowed: set[str]) -> None:
raise SystemExit(1)


BUILD_INPUTS = ["docs", "scripts", "package.json", "package-lock.json", ".openclaw-sync"]


def scope_tree(ref: str, paths: list[str]) -> str:
return git_stdout(["ls-tree", "-r", "-z", "--full-tree", ref, "--", *paths])


def publish_commit(paths: list[str], title: str, source_current: Callable[[], bool], attempts: int,
revalidate: bool = True) -> bool:
"""Publish a locally committed artifact, preserving its validation owner."""
validated_base = git_stdout(["rev-parse", "HEAD^"]).strip()
for attempt in range(1, attempts + 1):
if run(["git", "fetch", "origin", "main:refs/remotes/origin/main"], check=False).returncode:
time.sleep(attempt * 2)
continue
if not source_current():
return False
base = git_stdout(["rev-parse", "origin/main"]).strip()
if base != validated_base:
changed_inputs = run(["git", "diff", "--quiet", validated_base, base, "--", *BUILD_INPUTS], check=False).returncode
if changed_inputs and not revalidate:
raise SystemExit("Canary build inputs changed after validation; run a fresh finalizer.")
if run(["git", "rebase", "origin/main"], check=False).returncode:
run(["git", "rebase", "--abort"], check=False)
time.sleep(attempt * 2)
continue
if changed_inputs:
# Rebased docs and renderer inputs must pass the same full check.
changed_dependencies = run(["git", "diff", "--quiet", validated_base, base, "--", "package.json", "package-lock.json"], check=False).returncode
if changed_dependencies or not Path("node_modules").exists():
run(["npm", "ci"])
run(["npm", "run", "docs:check"])
validated_base = base
if not source_current():
return False
break
else:
raise SystemExit("Failed to rebase translation artifacts; run a fresh finalizer.")

expected = scope_tree("HEAD", paths)
scope_key = hashlib.sha256("\0".join(paths).encode()).hexdigest()[:16]
payload_key = hashlib.sha256(expected.encode()).hexdigest()
branch = f"automation/docs-i18n/{scope_key}-{payload_key}-{validated_base}"
repo = os.environ.get("GITHUB_REPOSITORY") or run(["gh", "repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]).stdout.strip()
candidate_url = f"https://github.com/{repo}/compare/main...{branch}?expand=1"
remote = run(["git", "ls-remote", "--exit-code", "--heads", "origin", f"refs/heads/{branch}"], check=False)
if remote.returncode == 0:
head = remote.stdout.split()[0]
git_stdout(["fetch", "origin", head])
if scope_tree(head, paths) != expected:
raise SystemExit(f"Retained translation candidate differs; inspect {candidate_url}")
elif remote.returncode == 2:
head = git_stdout(["rev-parse", "HEAD"]).strip()
else:
raise SystemExit(f"Cannot inspect translation candidate: {candidate_url}")
for path in git_stdout(["diff", "--no-renames", "--name-only", "-z", f"origin/main...{head}"]).split("\0"):
if not path:
continue
if not any(path == allowed or path.startswith(allowed.rstrip("/") + "/") for allowed in paths):
raise SystemExit(f"Translation candidate changes unowned path {path}; inspect {candidate_url}")
if git_stdout(["show", "-s", "--format=%P", head]).strip() != validated_base:
raise SystemExit(f"Translation candidate does not have one validated base parent: {candidate_url}")
if remote.returncode == 2:
git_stdout(["push", f"--force-with-lease=refs/heads/{branch}:", "origin", f"HEAD:refs/heads/{branch}"])

def find_pr() -> str:
return run(["gh", "pr", "list", "--base", "main", "--head", branch, "--state", "all",
"--json", "number,isCrossRepository,headRefOid", "--jq",
f'[.[] | select(.isCrossRepository == false and .headRefOid == "{head}")] | .[0].number // empty']).stdout.strip()

print(f"Translation candidate: {candidate_url}")
number = find_pr()
if not number:
with tempfile.NamedTemporaryFile(mode="w", suffix=".md") as body:
body.write(f"{title}\n\nValidated translation tree: {payload_key}\n")
body.flush()
run(["gh", "pr", "create", "--base", "main", "--head", branch, "--title", title, "--body-file", body.name], check=False)
number = find_pr()
if not number:
raise SystemExit(f"Translation PR creation unconfirmed; inspect {candidate_url}")
url = f"https://github.com/{repo}/pull/{number}"
print(f"Translation PR: {url}")
# A required status starts missing. Attest before waiting for merge readiness;
# server-side strict checks protect the gap after our final base read.
attest_publication(repo, number, head, validated_base)
requested = False
for _ in range(30):
record = json.loads(run(["gh", "pr", "view", number, "--json", "headRefOid,state,mergeStateStatus,mergeCommit"]).stdout)
if record["headRefOid"] != head:
raise SystemExit(f"Translation PR head changed: {url}")
if record["state"] == "MERGED":
merged = record["mergeCommit"]["oid"]
git_stdout(["fetch", "origin", "main", merged])
git_stdout(["merge-base", "--is-ancestor", merged, "origin/main"])
if git_stdout(["show", "-s", "--format=%P", merged]).strip() != validated_base:
raise SystemExit(f"Translation merge parent differs from validated base: {url}")
if scope_tree(merged, paths) != expected or scope_tree("origin/main", paths) != expected:
raise SystemExit(f"Merged translation tree differs from validated artifacts: {url}")
if not source_current():
return False
print(f"Verified translation PR {url} at {merged}")
write_output("commit_sha", merged)
return True
if record["state"] != "OPEN" or record["mergeStateStatus"] == "DIRTY":
raise SystemExit(f"Translation PR cannot merge; retained for inspection: {url}")
if record["mergeStateStatus"] == "CLEAN" and not requested:
git_stdout(["fetch", "origin", "main:refs/remotes/origin/main"])
if not source_current():
return False
# This is a freshness check, not an atomic base compare-and-swap.
if run(["git", "diff", "--quiet", validated_base, "origin/main", "--", *BUILD_INPUTS], check=False).returncode:
raise SystemExit(f"Build inputs changed after PR validation; retained for inspection: {url}")
requested = True
run(["gh", "pr", "merge", number, "--squash", "--match-head-commit", head], check=False)
time.sleep(10)
raise SystemExit(f"Translation PR not merged; retained for inspection: {url}")


def commit_aggregate(base_metadata_oid: str, attempts: int) -> bool:
def source_current() -> bool:
result = run(["git", "rev-parse", "--verify", "refs/remotes/origin/main:.openclaw-sync/source.json"], check=False)
if result.returncode or result.stdout.strip() != base_metadata_oid:
print("Source metadata moved or is unreadable; start a fresh aggregate finalizer.")
write_output("committed", "false")
return False
return True

git_stdout(["config", "user.name", "openclaw-docs-i18n[bot]"])
git_stdout(["config", "user.email", "openclaw-docs-i18n[bot]@users.noreply.github.com"])
git_stdout(["add", "docs"])
git_stdout(["commit", "-m", "chore(i18n): refresh translations"])
committed = publish_commit(["docs"], "chore(i18n): refresh translations", source_current, attempts)
write_output("committed", "true" if committed else "false")
return committed


def commit_locale(
locale: str,
base_source_sha: str,
Expand All @@ -168,36 +309,28 @@ def commit_locale(
git_stdout(["add", *locale_pathspecs(locale)])
git_stdout(["commit", "-m", f"chore(i18n): refresh {locale} translations"])

for attempt in range(1, attempts + 1):
if run(["git", "fetch", "origin", "main:refs/remotes/origin/main"], check=False).returncode == 0:
if not ensure_base_current(base_source_sha, locale):
return False
if run(["git", "rebase", "origin/main"], check=False).returncode == 0:
if not ensure_base_current(base_source_sha, locale):
return False
if run(["git", "push", "origin", "HEAD:main"], check=False).returncode == 0:
write_output("committed", "true")
return True
run(["git", "rebase", "--abort"], check=False)
print(f"{locale} translation push attempt {attempt} failed; retrying.")
time.sleep(attempt * 2)

raise SystemExit(f"Failed to push {locale} translations after retries.")
committed = publish_commit(locale_pathspecs(locale), f"chore(i18n): refresh {locale} translations",
lambda: ensure_base_current(base_source_sha, locale), attempts,
revalidate=artifact_role != "canary" or os.environ.get("CANARY_BOOTSTRAP") == "true")
write_output("committed", "true" if committed else "false")
return committed


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Commit and publish one applied locale artifact.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""Outputs:
Writes committed=true/false to GITHUB_OUTPUT and pushes docs/<locale> plus locale TM when changed.
Writes committed=true only after the validated translation PR is merged.

Examples:
LOCALE=fr BASE_SOURCE_SHA=abc python .github/scripts/i18n/commit_locale_artifact.py
python .github/scripts/i18n/commit_locale_artifact.py --locale zh-CN --base-source-sha abc --artifact-dir .openclaw-sync/i18n-artifacts/zh-cn-s0of1 --attempts 3
""",
)
parser.add_argument("--locale", default=os.environ.get("LOCALE", ""))
parser.add_argument("--aggregate", action="store_true")
parser.add_argument("--base-source-metadata-oid", default=os.environ.get("BASE_SOURCE_METADATA_OID", ""))
parser.add_argument("--base-source-sha", default=os.environ.get("BASE_SOURCE_SHA", ""))
parser.add_argument("--artifact-dir", default=os.environ.get("ARTIFACT_DIR", ""))
parser.add_argument("--attempts", default=5, type=int)
Expand All @@ -206,12 +339,17 @@ def parse_args() -> argparse.Namespace:

def main() -> None:
args = parse_args()
if args.attempts < 1:
raise SystemExit("attempts must be >= 1")
if args.aggregate:
if not args.base_source_metadata_oid:
raise SystemExit("missing base source metadata OID")
commit_aggregate(args.base_source_metadata_oid, args.attempts)
return
if not args.locale:
raise SystemExit("missing locale: pass --locale or set LOCALE")
if not args.base_source_sha:
raise SystemExit("missing base source sha: pass --base-source-sha or set BASE_SOURCE_SHA")
if args.attempts < 1:
raise SystemExit("attempts must be >= 1")
commit_locale(
args.locale,
args.base_source_sha,
Expand Down
92 changes: 92 additions & 0 deletions .github/scripts/i18n/publication_admission.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Post neutral PR admission; publishers retain payload and provenance policy."""
from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
from pathlib import Path

CONTEXT = "Publication merge admission"


def api(path: str, fields: dict[str, str] | None = None):
args = ["gh", "api", path]
if fields:
args.extend(["--method", "POST"])
for key, value in fields.items():
args.extend(["-f", f"{key}={value}"])
result = subprocess.run(args, text=True, capture_output=True, timeout=60)
if result.returncode:
raise SystemExit(result.stderr.strip() or f"GitHub request failed: {path}")
return json.loads(result.stdout)


def current_pull(repository: str, number: str, head: str) -> bool:
pull = api(f"repos/{repository}/pulls/{number}")
return (pull["state"] == "open" and pull["head"]["sha"] == head
and pull["base"]["ref"] == "main" and pull["base"]["repo"]["full_name"] == repository)


def require_strict_gate(repository: str) -> None:
rules = api(f"repos/{repository}/rules/branches/main?per_page=100")
if not isinstance(rules, list) or len(rules) >= 100:
raise SystemExit("Effective branch rules are incomplete; PR retained")
app_id = api("apps/github-actions")["id"]
if type(app_id) is not int:
raise SystemExit("GitHub Actions identity is unavailable")
strict = [rule for rule in rules if rule["type"] == "required_status_checks"
and rule.get("parameters", {}).get("strict_required_status_checks_policy") is True
and any(check["context"] == CONTEXT and check.get("integration_id") == app_id
for check in rule["parameters"].get("required_status_checks", []))]
non_ff = [rule for rule in rules if rule["type"] == "non_fast_forward"]
if not strict or not non_ff:
raise SystemExit(f"Required strict {CONTEXT} gate is not active; PR retained")
for rule_id in {rule.get("ruleset_id") for rule in strict + non_ff}:
if type(rule_id) is not int:
raise SystemExit("Effective rule has no source ruleset")
ruleset = api(f"repos/{repository}/rulesets/{rule_id}?includes_parents=true")
if ruleset.get("enforcement") != "active":
raise SystemExit("Publication ruleset is inactive")
# GitHub redacts bypass actors without ruleset-write access. Activation
# owns that proof; runtime rejects exposed bypass without admin credentials.
if "bypass_actors" in ruleset and ruleset["bypass_actors"] != []:
raise SystemExit("Publication ruleset permits bypass")
if ruleset.get("current_user_can_bypass", "never") != "never":
raise SystemExit("Current publisher can bypass the ruleset")


def post_admission(repository: str, head: str) -> None:
fields = {"context": CONTEXT, "state": "success", "description": "Current open pull request targeting main"}
if os.environ.get("GITHUB_RUN_ID"):
fields["target_url"] = (f"{os.environ.get('GITHUB_SERVER_URL', 'https://github.com')}/"
f"{repository}/actions/runs/{os.environ['GITHUB_RUN_ID']}")
api(f"repos/{repository}/statuses/{head}", fields)


def attest_publication(repository: str, number: str, head: str, base: str) -> None:
require_strict_gate(repository)
if (not current_pull(repository, number, head)
or api(f"repos/{repository}/git/ref/heads/main")["object"]["sha"] != base):
raise SystemExit("Publication PR or validated base changed; PR retained")
post_admission(repository, head)


def main() -> None:
argparse.ArgumentParser(description=__doc__, epilog="Examples: python publication_admission.py").parse_args()
repository = os.environ.get("GITHUB_REPOSITORY", "")
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
number, head = str(event["number"]), event["pull_request"]["head"]["sha"]
if (not re.fullmatch(r"[\w.-]+/[\w.-]+", repository) or not re.fullmatch(r"[1-9][0-9]*", number)
or not re.fullmatch(r"[a-f0-9]{40}", head)):
raise SystemExit("Invalid publication event identity")
if current_pull(repository, number, head):
post_admission(repository, head)
else:
print("Obsolete pull request event; no status written.")


if __name__ == "__main__":
main()
Loading
Loading