diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 795a64957e..7ec29852c8 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -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' diff --git a/.github/scripts/i18n/commit_locale_artifact.py b/.github/scripts/i18n/commit_locale_artifact.py index 3f6e2ebfe2..8985273938 100644 --- a/.github/scripts/i18n/commit_locale_artifact.py +++ b/.github/scripts/i18n/commit_locale_artifact.py @@ -1,12 +1,12 @@ #!/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/ 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: @@ -14,13 +14,13 @@ --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 @@ -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]: @@ -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, @@ -168,21 +309,11 @@ 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: @@ -190,7 +321,7 @@ def parse_args() -> argparse.Namespace: description="Commit and publish one applied locale artifact.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Outputs: - Writes committed=true/false to GITHUB_OUTPUT and pushes docs/ 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 @@ -198,6 +329,8 @@ def parse_args() -> argparse.Namespace: """, ) 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) @@ -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, diff --git a/.github/scripts/i18n/publication_admission.py b/.github/scripts/i18n/publication_admission.py new file mode 100644 index 0000000000..ff69e1cfc1 --- /dev/null +++ b/.github/scripts/i18n/publication_admission.py @@ -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() diff --git a/.github/scripts/i18n/tests/fixtures/gh-publish.py b/.github/scripts/i18n/tests/fixtures/gh-publish.py new file mode 100644 index 0000000000..c36025f4a7 --- /dev/null +++ b/.github/scripts/i18n/tests/fixtures/gh-publish.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""GitHub boundary fixture; branch creation and squash merges use real Git.""" +import json +import os +from pathlib import Path +import subprocess +import sys + +root = Path(os.environ["PR_FIXTURE_ROOT"]) +mode = os.environ.get("PR_FIXTURE_MODE", "merge") +record = root / "pr.json" + + +def git(cwd, *args): + return subprocess.check_output(["git", *args], cwd=cwd, text=True, stderr=subprocess.PIPE).strip() + + +def save(state): + record.write_text(json.dumps(state)) + + +operation = sys.argv[1:3] +if sys.argv[1] == "api": + path = sys.argv[2] + remote = Path(git(Path.cwd(), "remote", "get-url", "origin")) + if path == "apps/github-actions": + response = {"id": 15368} + elif "/rules/branches/main" in path: + response = [] if mode == "missing-gate" else [ + {"type": "non_fast_forward", "ruleset_id": 1}, + {"type": "required_status_checks", "ruleset_id": 1, "parameters": { + "strict_required_status_checks_policy": True, + "required_status_checks": [{"context": "Publication merge admission", "integration_id": 15368}]}}] + elif "/rulesets/1?" in path: + response = {"enforcement": "active"} + if mode == "bypass-gate": + response["bypass_actors"] = [{"actor_id": 1}] + elif "/pulls/" in path: + state = json.loads(record.read_text()) + response = {"state": state["state"].lower(), + "head": {"sha": "0" * 40 if mode == "moved-head" else state["headRefOid"]}, + "base": {"ref": "main", "repo": {"full_name": "example/docs"}}} + elif path.endswith("/git/ref/heads/main"): + response = {"object": {"sha": git(remote, "rev-parse", "main")}} + elif "/statuses/" in path: + response = dict(arg.split("=", 1) for arg in sys.argv[3:] if "=" in arg) + response["sha"] = path.rsplit("/", 1)[1] + (root / "status.json").write_text(json.dumps(response)) + else: + raise AssertionError(path) + print(json.dumps(response)) +elif operation == ["pr", "list"]: + branch = sys.argv[sys.argv.index("--head") + 1] + state = json.loads(record.read_text()) if record.exists() else None + remote = git(Path.cwd(), "ls-remote", "origin", f"refs/heads/{branch}") + print("1" if state and state["branch"] == branch and remote and state["headRefOid"] == remote.split()[0] else "") +elif operation == ["pr", "create"]: + if mode == "create-failed": + sys.exit(1) + branch = sys.argv[sys.argv.index("--head") + 1] + remote = git(Path.cwd(), "ls-remote", "origin", f"refs/heads/{branch}").split()[0] + save({"branch": branch, "headRefOid": remote, "state": "OPEN", "mergeStateStatus": "CLEAN", "mergeCommit": None}) + if mode == "uncertain-create": + sys.exit(1) + print("https://github.com/example/docs/pull/1") +elif operation == ["pr", "view"]: + state = json.loads(record.read_text()) + if not (root / "status.json").exists(): + state["mergeStateStatus"] = "BLOCKED" + if mode == "pending": + state["mergeStateStatus"] = "BLOCKED" + if mode == "moved-head": + state["headRefOid"] = "0" * 40 + print(json.dumps(state)) +elif operation == ["pr", "merge"]: + state = json.loads(record.read_text()) + assert "--squash" in sys.argv and "--admin" not in sys.argv + assert sys.argv[sys.argv.index("--match-head-commit") + 1] == state["headRefOid"] + if mode == "merge-failed": + sys.exit(1) + merger = root / "merger" + git(root, "clone", git(Path.cwd(), "remote", "get-url", "origin"), str(merger)) + git(merger, "config", "commit.gpgsign", "false") + git(merger, "config", "user.name", "Fixture") + git(merger, "config", "user.email", "fixture@example.invalid") + git(merger, "checkout", "-B", "main", "origin/main") + if mode == "merge-base-race": + (merger / "docs/fr/concurrent.md").write_text("concurrent\n") + git(merger, "add", ".") + git(merger, "commit", "-m", "Concurrent change after final client read") + git(merger, "push", "origin", "HEAD:main") + status = json.loads((root / "status.json").read_text()) + assert status["sha"] == state["headRefOid"] and status["context"] == "Publication merge admission" + assert status["state"] == "success" + # Model strict required-check admission, not a client-side base CAS. + if git(merger, "show", "-s", "--format=%P", state["headRefOid"]) != git(merger, "rev-parse", "HEAD"): + sys.exit(1) + git(merger, "merge", "--squash", state["headRefOid"]) + if mode == "wrong-tree": + (merger / "docs/fr/extra.md").write_text("unexpected\n") + git(merger, "add", "docs/fr/extra.md") + git(merger, "commit", "-m", "Squashed translation PR") + merged = git(merger, "rev-parse", "HEAD") + assert merged != state["headRefOid"] + git(merger, "push", "origin", "HEAD:main") + state.update(state="MERGED", mergeCommit={"oid": merged}) + save(state) + if mode == "uncertain-merge": + sys.exit(1) +else: + raise AssertionError(sys.argv) diff --git a/.github/scripts/i18n/tests/test_i18n_scripts.py b/.github/scripts/i18n/tests/test_i18n_scripts.py index a5869d832b..72b9fbfb79 100644 --- a/.github/scripts/i18n/tests/test_i18n_scripts.py +++ b/.github/scripts/i18n/tests/test_i18n_scripts.py @@ -50,6 +50,7 @@ def load_module(name: str): plan_incremental = load_module("plan_incremental") provider_preflight = load_module("provider_preflight") summarize_full = load_module("summarize_full") +publication_admission = load_module("publication_admission") commit_locale_artifact = load_module("commit_locale_artifact") dispatch_r2_pages = load_module("dispatch_r2_pages") @@ -90,15 +91,171 @@ def init_repo(repo: Path) -> None: run_git(repo, "config", "commit.gpgsign", "false") +@contextmanager +def github_pr_fixture(mode: str = "merge"): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + binary = root / "bin" + binary.mkdir() + shutil.copyfile(FIXTURES / "gh-publish.py", binary / "gh") + (binary / "gh").chmod(0o755) + (binary / "python").symlink_to(sys.executable) + (binary / "npm").write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$PR_FIXTURE_ROOT/npm.log"\n[ "$PR_FIXTURE_MODE" != validation-failed ]\n') + (binary / "npm").chmod(0o755) + with env({"PATH": f"{binary}{os.pathsep}{os.environ['PATH']}", + "PR_FIXTURE_ROOT": str(root), "PR_FIXTURE_MODE": mode, + "GITHUB_REPOSITORY": "example/docs"}): + yield root + + class I18NScriptTests(unittest.TestCase): + def test_publication_caller_ceilings_preserve_read_only_translation(self) -> None: + calls = 0 + for name in ("translate-all.yml", "translate-incremental.yml", "translate-retirements.yml"): + workflow = (REPO_ROOT / ".github/workflows" / name).read_text() + for block in re.findall(r"(?ms)^ [a-zA-Z0-9_-]+:\n.*?(?=^ [a-zA-Z0-9_-]+:\n|\Z)", workflow): + if re.search(r"uses: \./\.github/workflows/translate-(?:locale|finalize)-reusable.yml", block): + calls += 1 + for permission in ("actions: write", "contents: write", "pull-requests: write", "statuses: write"): + self.assertIn(permission, block) + self.assertEqual(11, calls) + reusable = (REPO_ROOT / ".github/workflows/translate-locale-reusable.yml").read_text() + worker = re.search(r"(?ms)^ translate:\n.*?(?=^ [a-zA-Z0-9_-]+:\n|\Z)", reusable).group(0) + self.assertIn(" permissions:\n contents: read\n", worker) + self.assertNotIn("pull-requests: write", worker) + self.assertNotIn("statuses: write", worker) + + def test_publication_admission_contract(self) -> None: + repository, head = "example/docs", "a" * 40 + for state, ref, target, candidate, writes in [ + ("open", "main", repository, head, 1), + ("closed", "main", repository, head, 0), + ("open", "other", repository, head, 0), + ("open", "main", "other/docs", head, 0), + ("open", "main", repository, "b" * 40, 0), + ]: + with self.subTest(state=state, ref=ref, target=target, candidate=candidate), tempfile.TemporaryDirectory() as tmp: + event = Path(tmp) / "event.json" + event.write_text(json.dumps({"number": 1, "pull_request": {"head": {"sha": head}}})) + posted = [] + def api(path, fields=None): + if fields: + posted.append((path, fields)) + return {} + self.assertEqual(f"repos/{repository}/pulls/1", path) + return {"state": state, "head": {"sha": candidate}, "base": {"ref": ref, "repo": {"full_name": target}}} + with patch.object(publication_admission, "api", side_effect=api), patch.object(sys, "argv", ["publication_admission.py"]), env({"GITHUB_REPOSITORY": repository, "GITHUB_EVENT_PATH": str(event)}): + publication_admission.main() + self.assertEqual(writes, len(posted)) + if writes: + self.assertEqual(f"repos/{repository}/statuses/{head}", posted[0][0]) + self.assertEqual("Publication merge admission", posted[0][1]["context"]) + self.assertEqual("success", posted[0][1]["state"]) + workflow = (REPO_ROOT / ".github/workflows/publication-admission.yml").read_text() + self.assertIn("ref: ${{ github.workflow_sha }}", workflow) + self.assertNotIn("pull_request.head", workflow) + + def test_publication_requires_effective_strict_app_bound_gate(self) -> None: + for case in ("valid", "redacted", "missing", "non-strict", "wrong-app", "no-nonff", "inactive", "bypass", "malformed-bypass", "current-bypass"): + with self.subTest(case=case): + rules = [ + {"type": "non_fast_forward", "ruleset_id": 1}, + {"type": "required_status_checks", "ruleset_id": 1, "parameters": { + "strict_required_status_checks_policy": case != "non-strict", + "required_status_checks": [{"context": publication_admission.CONTEXT, "integration_id": 42 if case == "wrong-app" else 15368}]}} + ] + if case == "missing": rules = [] + if case == "no-nonff": rules = rules[1:] + ruleset = {"enforcement": "disabled" if case == "inactive" else "active"} + if case != "redacted": ruleset["bypass_actors"] = [] + if case == "bypass": ruleset["bypass_actors"] = [{}] + if case == "malformed-bypass": ruleset["bypass_actors"] = None + if case == "current-bypass": ruleset["current_user_can_bypass"] = "always" + values = {"repos/example/docs/rules/branches/main?per_page=100": rules, + "apps/github-actions": {"id": 15368}, + "repos/example/docs/rulesets/1?includes_parents=true": ruleset} + with patch.object(publication_admission, "api", side_effect=lambda path: values[path]): + if case in ("valid", "redacted"): + publication_admission.require_strict_gate("example/docs") + else: + with self.assertRaises(SystemExit): + publication_admission.require_strict_gate("example/docs") + + def test_translation_pr_publication_receipts(self) -> None: + for owner in ("aggregate", "locale"): + for scenario in ("merge", "uncertain-create", "uncertain-merge", "create-failed", "merge-failed", + "pending", "moved-head", "wrong-tree", "source-moved", "revalidate", "validation-failed", + "missing-gate", "bypass-gate", "merge-base-race"): + with self.subTest(owner=owner, scenario=scenario), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + repo, origin, other = (root / name for name in ("repo", "origin.git", "other")) + repo.mkdir() + init_repo(repo) + (repo / "docs/fr").mkdir(parents=True) + (repo / "docs/.i18n").mkdir() + (repo / ".openclaw-sync").mkdir() + (repo / ".openclaw-sync/source.json").write_text(json.dumps({"repository": "openclaw/openclaw", "sha": "source-a"})) + (repo / "docs/fr/index.md").write_text("before\n") + (repo / "docs/.i18n/fr.tm.jsonl").write_text("{}\n") + run_git(repo, "add", ".") + run_git(repo, "commit", "-m", "initial") + run_git(root, "init", "--bare", "-b", "main", str(origin)) + run_git(repo, "remote", "add", "origin", str(origin)) + run_git(repo, "push", "origin", "main") + baseline = run_git(repo, "rev-parse", "HEAD").strip() + metadata = run_git(repo, "rev-parse", "HEAD:.openclaw-sync/source.json").strip() + (repo / "docs/fr/index.md").write_text("translated\n") + if scenario in ("source-moved", "revalidate", "validation-failed"): + run_git(root, "clone", str(origin), str(other)) + run_git(other, "config", "user.name", "Test") + run_git(other, "config", "user.email", "test@example.invalid") + run_git(other, "config", "commit.gpgsign", "false") + target = ".openclaw-sync/source.json" if scenario == "source-moved" else "package.json" + (other / target).write_text(json.dumps({"sha": "source-b"}) if scenario == "source-moved" else '{"private":true}\n') + run_git(other, "add", ".") + run_git(other, "commit", "-m", "concurrent inputs") + run_git(other, "push", "origin", "main") + before = run_git(origin, "rev-parse", "main").strip() + output = root / "output" + accepted = scenario in ("merge", "uncertain-create", "uncertain-merge", "revalidate") + with chdir(repo), github_pr_fixture(scenario) as fixture, env({"GITHUB_OUTPUT": str(output)}), patch.object(commit_locale_artifact.time, "sleep"): + def publish(): + if owner == "aggregate": + return commit_locale_artifact.commit_aggregate(metadata, 1) + return commit_locale_artifact.commit_locale("fr", "source-a", 1) + if accepted or scenario == "source-moved": + self.assertEqual(accepted, publish()) + else: + with self.assertRaises(SystemExit): + publish() + result = output.read_text() if output.exists() else "" + self.assertEqual(accepted, "committed=true" in result) + if accepted: + self.assertEqual("translated\n", run_git(origin, "show", "main:docs/fr/index.md")) + receipt = json.loads((fixture / "pr.json").read_text()) + self.assertEqual("MERGED", receipt["state"]) + self.assertNotEqual(receipt["headRefOid"], receipt["mergeCommit"]["oid"]) + self.assertEqual(receipt["mergeCommit"]["oid"], run_git(origin, "rev-parse", "main").strip()) + if scenario == "revalidate": + self.assertEqual(["ci", "run docs:check"], (fixture / "npm.log").read_text().splitlines()) + elif scenario == "merge-base-race": + self.assertEqual("before\n", run_git(origin, "show", "main:docs/fr/index.md")) + self.assertEqual("concurrent\n", run_git(origin, "show", "main:docs/fr/concurrent.md")) + self.assertEqual("OPEN", json.loads((fixture / "pr.json").read_text())["state"]) + elif scenario != "wrong-tree": + self.assertEqual(before, run_git(origin, "rev-parse", "main").strip()) + if scenario in ("source-moved", "revalidate", "validation-failed"): + self.assertNotEqual(baseline, before) + def test_translate_workflows_call_existing_scripts_without_inline_python_or_node_heredocs(self) -> None: workflows = sorted((REPO_ROOT / ".github/workflows").glob("translate-*.yml")) + workflows.append(REPO_ROOT / ".github/workflows/publication-admission.yml") self.assertTrue(workflows) called_scripts: set[Path] = set() heredoc_pattern = re.compile(r"(?:python|node)\s+-\s+<<['\"]?(?:PY|NODE)['\"]?") script_call_pattern = re.compile( - r"python\s+(?:" + r"python(?:3)?\s+(?:" r"(?P\.github/scripts/i18n/[A-Za-z0-9_./-]+\.py)" r"|\"\$\{I18N_SCRIPT_DIR\}/(?P[A-Za-z0-9_-]+\.py)\"" r")(?=\s|$)" @@ -341,8 +498,9 @@ def test_full_workflow_gates_batches_after_canary(self) -> None: self.assertIn('python "${I18N_SCRIPT_DIR}/dispatch_r2_pages.py" "${args[@]}"', reusable) commit_locale_block = re.search(r"(?ms)^ commit-locale:.*?(?=^ [a-zA-Z0-9_-]+:|\Z)", reusable) self.assertIsNotNone(commit_locale_block) - self.assertNotIn("concurrency:", commit_locale_block.group(0)) - self.assertIn("It retries rebase/push conflicts", commit_locale_artifact.__doc__ or "") + self.assertIn("group: docs-i18n-finalize", commit_locale_block.group(0)) + self.assertIn("queue: max", commit_locale_block.group(0)) + self.assertIn("It retries fetch/rebase conflicts", commit_locale_artifact.__doc__ or "") self.assertIn("--artifact-scope page", reusable) self.assertIn('--ref "${{ github.ref_name }}"', reusable) self.assertIn('--locale "${{ inputs.locale }}"', reusable) @@ -359,7 +517,7 @@ def test_full_workflow_gates_batches_after_canary(self) -> None: self.assertIn("ref: ${{ github.workflow_sha }}", finalize_reusable) self.assertIn("EXPECTED_LOCALES: ${{ inputs.expected_locales }}", finalize_reusable) self.assertIn("id: aggregate_commit", finalize_reusable) - self.assertIn('echo "committed=true" >> "$GITHUB_OUTPUT"', finalize_reusable) + self.assertIn('python "${I18N_SCRIPT_DIR}/commit_locale_artifact.py" --aggregate', finalize_reusable) self.assertIn("Fail uncommitted aggregate translation refresh", finalize_reusable) self.assertIn("steps.aggregate_commit.outputs.committed != 'true'", finalize_reusable) self.assertIn("steps.aggregate_commit.outputs.committed == 'true'", finalize_reusable) @@ -3046,7 +3204,7 @@ def test_canary_commit_new_locale_without_tm_does_not_add_missing_tm_path(self) (artifact / "changed-files.txt").write_text("docs/hi/index.md\n", encoding="utf-8") (artifact / "deleted-files.txt").write_text("", encoding="utf-8") - with chdir(repo): + with chdir(repo), github_pr_fixture(), patch.object(commit_locale_artifact.time, "sleep"): committed = commit_locale_artifact.commit_locale( "hi", "source-a", @@ -4223,7 +4381,7 @@ def test_finalizer_commit_rechecks_metadata_after_aggregate_validation(self) -> values = {f"steps.apply.outputs.{key}": value for key, value in applied.items()} self._retirement_step(repo, root, values, "Commit aggregate translation refresh", workflow_name=workflow) published = case in {"unchanged", "unrelated_main"} - self.assertEqual("true" if published else None, values.get("steps.aggregate_commit.outputs.committed")) + self.assertEqual("true" if published else "false", values.get("steps.aggregate_commit.outputs.committed")) paths = run_git(origin, "ls-tree", "-r", "--name-only", "main").splitlines() self.assertEqual(not published, "docs/fr/clawhub/retired.md" in paths) if published: @@ -4537,6 +4695,7 @@ def _retirement_fixture(self, root: Path): return repo, runner, values, seed, origin def _retirement_step(self, repo: Path, runner: Path, values: dict[str, str], name: str, *, succeeds: bool = True, workflow_name: str = "translate-retirements.yml"): + values.setdefault("github.token", "fixture-token") workflow = REPO_ROOT / ".github/workflows" / workflow_name blocks = [block for block in re.split(r"(?m)^ - name: ", workflow.read_text())[1:] if " run: |\n" in block] shells = runner / "shells" @@ -4551,7 +4710,14 @@ def _retirement_step(self, repo: Path, runner: Path, values: dict[str, str], nam output.write_text("") github_env.write_text("") process_env = {**os.environ, **values, **step_env, "GITHUB_WORKSPACE": str(repo), "GITHUB_OUTPUT": str(output), "GITHUB_ENV": str(github_env), "GITHUB_STEP_SUMMARY": str(runner / "summary")} - result = subprocess.run(["bash", str(extracted[index])], cwd=repo, env=process_env, text=True, capture_output=True, timeout=60) + if name == "Commit aggregate translation refresh": + # This focused step runs after the workflow's script-staging step. + process_env.setdefault("I18N_SCRIPT_DIR", str(SCRIPT_DIR)) + with github_pr_fixture(): + process_env.update({key: os.environ[key] for key in ("PATH", "PR_FIXTURE_ROOT", "PR_FIXTURE_MODE", "GITHUB_REPOSITORY")}) + result = subprocess.run(["bash", str(extracted[index])], cwd=repo, env=process_env, text=True, capture_output=True, timeout=60) + else: + result = subprocess.run(["bash", str(extracted[index])], cwd=repo, env=process_env, text=True, capture_output=True, timeout=60) if succeeds: self.assertEqual(0, result.returncode, f"{name}: {result.stdout}\n{result.stderr}") else: diff --git a/.github/workflows/publication-admission.yml b/.github/workflows/publication-admission.yml new file mode 100644 index 0000000000..c0089d2ddc --- /dev/null +++ b/.github/workflows/publication-admission.yml @@ -0,0 +1,27 @@ +name: Publication admission validator + +on: + pull_request_target: + branches: [main] + types: [opened, synchronize, reopened, edited, ready_for_review] + +permissions: + contents: read + pull-requests: read + statuses: write + +jobs: + inspect-publication-metadata: + name: Inspect publication metadata + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check out trusted admission code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.workflow_sha }} + persist-credentials: false + - name: Admit current pull request metadata + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/i18n/publication_admission.py diff --git a/.github/workflows/translate-all.yml b/.github/workflows/translate-all.yml index 8666c3c90c..172f8f8ce0 100644 --- a/.github/workflows/translate-all.yml +++ b/.github/workflows/translate-all.yml @@ -261,6 +261,11 @@ jobs: python .github/scripts/i18n/provider_preflight.py translate-canary: + permissions: + actions: write + contents: write + pull-requests: write + statuses: write name: Canary ${{ needs.prepare.outputs.canary_locale }} needs: - prepare @@ -301,6 +306,11 @@ jobs: fail-fast: false max-parallel: 3 matrix: ${{ fromJSON(needs.prepare.outputs.batch_1) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -330,6 +340,11 @@ jobs: fail-fast: false max-parallel: 3 matrix: ${{ fromJSON(needs.prepare.outputs.batch_2) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -359,6 +374,11 @@ jobs: fail-fast: false max-parallel: 3 matrix: ${{ fromJSON(needs.prepare.outputs.batch_3) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -388,6 +408,11 @@ jobs: fail-fast: false max-parallel: 3 matrix: ${{ fromJSON(needs.prepare.outputs.batch_4) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -417,6 +442,11 @@ jobs: fail-fast: false max-parallel: 3 matrix: ${{ fromJSON(needs.prepare.outputs.batch_5) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -446,6 +476,11 @@ jobs: fail-fast: false max-parallel: 3 matrix: ${{ fromJSON(needs.prepare.outputs.batch_6) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -465,6 +500,11 @@ jobs: secrets: inherit finalize: + permissions: + actions: write + contents: write + pull-requests: write + statuses: write name: Commit aggregate translation refresh needs: - prepare diff --git a/.github/workflows/translate-finalize-reusable.yml b/.github/workflows/translate-finalize-reusable.yml index 38196c93ff..30192709ab 100644 --- a/.github/workflows/translate-finalize-reusable.yml +++ b/.github/workflows/translate-finalize-reusable.yml @@ -29,6 +29,8 @@ on: permissions: actions: write contents: write + pull-requests: write + statuses: write jobs: finalize: @@ -38,6 +40,7 @@ jobs: concurrency: group: docs-i18n-finalize cancel-in-progress: false + queue: max steps: # The artifact commit targets latest main, while the workflow control # scripts stay pinned to the workflow ref under test. @@ -142,42 +145,11 @@ jobs: id: aggregate_commit if: steps.apply.outputs.changed_count != '0' env: + GH_TOKEN: ${{ github.token }} BASE_SOURCE_METADATA_OID: ${{ steps.apply.outputs.base_source_metadata_oid }} run: | set -euo pipefail - - ensure_base_current() { - if ! current_source_metadata_oid="$(git rev-parse --verify refs/remotes/origin/main:.openclaw-sync/source.json 2>/dev/null)" \ - || ! git cat-file blob "${current_source_metadata_oid}" >/dev/null 2>&1 \ - || [ "${current_source_metadata_oid}" != "${BASE_SOURCE_METADATA_OID}" ]; then - echo "Source metadata moved or is unreadable; skipping aggregate translation commit. Start a fresh finalizer attempt." - exit 0 - fi - } - - git config user.name "openclaw-docs-i18n[bot]" - git config user.email "openclaw-docs-i18n[bot]@users.noreply.github.com" - git add docs - git commit -m "chore(i18n): refresh translations" - - for attempt in 1 2 3 4 5; do - if git fetch origin main:refs/remotes/origin/main; then - ensure_base_current - if git rebase origin/main; then - ensure_base_current - if git push origin HEAD:main; then - echo "committed=true" >> "$GITHUB_OUTPUT" - exit 0 - fi - fi - git rebase --abort >/dev/null 2>&1 || true - fi - echo "Aggregate translation push attempt ${attempt} failed; retrying." - sleep $((attempt * 2)) - done - - echo "Failed to push aggregate translations after retries." - exit 1 + python "${I18N_SCRIPT_DIR}/commit_locale_artifact.py" --aggregate - name: Fail uncommitted aggregate translation refresh if: steps.apply.outputs.changed_count != '0' && steps.aggregate_commit.outputs.committed != 'true' diff --git a/.github/workflows/translate-incremental.yml b/.github/workflows/translate-incremental.yml index 95d6492569..b1a2b5da4d 100644 --- a/.github/workflows/translate-incremental.yml +++ b/.github/workflows/translate-incremental.yml @@ -134,6 +134,11 @@ jobs: fail-fast: false max-parallel: 12 matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + permissions: + actions: write + contents: write + pull-requests: write + statuses: write uses: ./.github/workflows/translate-locale-reusable.yml with: locale: ${{ matrix.locale }} @@ -174,6 +179,11 @@ jobs: python .github/scripts/i18n/provider_preflight.py finalize: + permissions: + actions: write + contents: write + pull-requests: write + statuses: write name: Commit successful locale artifacts needs: - prepare diff --git a/.github/workflows/translate-locale-reusable.yml b/.github/workflows/translate-locale-reusable.yml index 32b531597d..4ee10f3882 100644 --- a/.github/workflows/translate-locale-reusable.yml +++ b/.github/workflows/translate-locale-reusable.yml @@ -82,6 +82,8 @@ jobs: timeout-minutes: 360 outputs: canary_bootstrap: ${{ steps.pending.outputs.canary_bootstrap }} + # Callers reserve write scopes for the conditional finalizer. Translation + # itself keeps a read-only token, including when publication is disabled. permissions: contents: read concurrency: @@ -410,6 +412,12 @@ jobs: permissions: actions: write contents: write + pull-requests: write + statuses: write + concurrency: + group: docs-i18n-finalize + cancel-in-progress: false + queue: max steps: # Finalizers apply artifacts to latest main, but deploy/commit control # logic must come from this workflow ref so branch canaries test the fix. @@ -483,6 +491,8 @@ jobs: id: locale_commit if: inputs.commit_locale && steps.apply.outputs.changed_count != '0' env: + GH_TOKEN: ${{ github.token }} + CANARY_BOOTSTRAP: ${{ needs.translate.outputs.canary_bootstrap }} ARTIFACT_ROLE: ${{ inputs.artifact_role }} BASE_SOURCE_SHA: ${{ steps.apply.outputs.base_source_sha }} LOCALE: ${{ inputs.locale }} diff --git a/.github/workflows/translate-retirements.yml b/.github/workflows/translate-retirements.yml index 29efdcc140..3081f990d9 100644 --- a/.github/workflows/translate-retirements.yml +++ b/.github/workflows/translate-retirements.yml @@ -162,6 +162,11 @@ jobs: retention-days: 7 finalize: + permissions: + actions: write + contents: write + pull-requests: write + statuses: write name: Validate and publish aggregate retirements needs: produce uses: ./.github/workflows/translate-finalize-reusable.yml diff --git a/.github/workflows/translate-shell-check-reusable.yml b/.github/workflows/translate-shell-check-reusable.yml index e5de2ab4f7..be29629acd 100644 --- a/.github/workflows/translate-shell-check-reusable.yml +++ b/.github/workflows/translate-shell-check-reusable.yml @@ -5,6 +5,7 @@ on: paths: - ".github/scripts/i18n/**" - ".github/workflows/translate-*.yml" + - ".github/workflows/publication-admission.yml" - ".openclaw-sync/**" - "package.json" - "package-lock.json" diff --git a/AGENTS.md b/AGENTS.md index 3ad787cf56..4d45123ccb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ Website UI, translations, and publishing for `docs.openclaw.ai`. English content - `translate-incremental.yml` runs normal debounced docs changes. - `translate-all.yml` reconciles missing or changed translations weekly or by manual dispatch. Matching-page retranslation requires explicit `force_retranslate` recovery. - Translation pending logic compares source file SHA-256 with each page's `x-i18n.source_hash`. -- Locale workers upload artifacts; the shared finalizer pushes one aggregate i18n commit. +- Locale workers upload artifacts; the shared finalizer publishes one validated aggregate i18n PR. - If translated MDX fails, the repair step may touch only `docs//**` and `docs/.i18n/.tm.jsonl`. ## Autoreview priority diff --git a/CHANGELOG.md b/CHANGELOG.md index 28fa151542..c252fe894e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Publish aggregate and recovery translations through pull requests, verify the merged translation tree before deployment, and queue finalizers without replacing pending locale jobs. Require administrator-configured strict merge admission before automatic publication. + - Abort stalled publish probes and R2 credential calls after 30 seconds, and keep the community invitation inside narrow WebKit viewports. Thanks @SebTardif! (#318) - Refresh Lucide, Playwright, Slugify, and pinned translation actions within the two-day dependency cooldown while preserving published anchors. Thanks @dependabot! diff --git a/docs/.i18n/translation-workflow.md b/docs/.i18n/translation-workflow.md index 050bcd561f..6838931953 100644 --- a/docs/.i18n/translation-workflow.md +++ b/docs/.i18n/translation-workflow.md @@ -21,7 +21,7 @@ Internal note for the docs publish pipeline. This file is under `docs/.i18n`, wh 6. If a newer docs sync arrived during cooldown, the coordinator uses the newer source state. 7. Per-locale translation jobs run in parallel with `fail-fast: false`. 8. Each locale job uploads an artifact for the requested source SHA. -9. The finalizer downloads available artifacts, ignores stale or failed payloads, and pushes one aggregate i18n commit. +9. The finalizer downloads available artifacts, ignores stale or failed payloads, and publishes one aggregate i18n PR. 10. After the aggregate commit lands, the finalizer dispatches the Pages deploy once. 11. The Pages workflow dispatches live smoke after deployment. @@ -73,7 +73,14 @@ The source repo release workflow dispatches one `translate-all-release` event. T ## Aggregate commit -The finalizer owns the only locale push in the normal path. +The finalizer publishes locale changes through a pull request. Aggregate and +locale recovery finalizers share the same queued publication group. Up to 100 +pending jobs can wait without replacing an earlier pending finalizer. + +Both paths retain their source freshness checks and validate changed build +inputs again after rebasing. Each candidate has an immutable branch derived from +its scope, validated tree, and base commit. An unmerged or closed candidate stays +available for inspection; later runs never overwrite its branch. Commit message: @@ -81,7 +88,11 @@ Commit message: chore(i18n): refresh translations ``` -The commit may contain a partial locale set. The job summary lists applied locales, locales with no changes, missing or failed locales, stale artifacts, and invalid artifacts. +The commit may contain a partial locale set. Publication succeeds only after a +normal squash merge of the exact candidate head and verification of its owned +translation tree at the merge commit and current `main`. A pending PR is not a +published translation. The job summary lists applied locales, locales with no +changes, missing or failed locales, stale artifacts, and invalid artifacts. ## Weekly reconciliation @@ -102,8 +113,27 @@ The weekly run is the repair mechanism for LLM flakiness, partial failures, and English deploys from source sync commits. -Translations deploy after the aggregate i18n commit. The finalizer dispatches GitHub Pages once because GitHub suppresses normal push-triggered workflow runs from `GITHUB_TOKEN` commits. The Pages workflow dispatches live smoke after deployment so the smoke test checks the deployed site instead of racing the deploy. +Translations deploy through R2 Pages after the finalizer verifies the merged +translation tree. The finalizer dispatches the existing deploy workflow because +`GITHUB_TOKEN` publication does not trigger normal push workflows. Failed or +unconfirmed merges leave `committed` false and prevent the dependent deploy. A hot docs day should produce many fast English deploys, but only a small number of locale deploys. -The aggregate i18n commit limits publish work to one update. Avoid restoring per-locale pushes to `main`. +The aggregate i18n commit limits normal publish work to one update. Recovery +locale commits use the same PR and merge-verification path. + +Both publication owners require the strict `Publication merge admission` check +bound to GitHub Actions and the non-fast-forward rule before normal merging. +An administrator must activate the rules and verify empty bypass lists. Runtime +rejects exposed bypasses; GitHub can redact those lists from the workflow token, +so omitted fields do not prove the administrator-owned condition. + +The trusted `publication-admission.yml` workflow posts neutral admission only for +a current open PR targeting this repository's main branch at the event head. +Obsolete events write no status. It never executes candidate code or validates +translation payloads. Aggregate and locale publishers own source freshness, +validation, scope, single-parent candidate checks, and actual merged-tree receipts. +They post the same admission status after their checks, so token-created PRs do +not depend on another workflow event. Missing effective policy retains the PR +without merging or dispatching its dependent R2 deployment.