From a8e4ca9e63d21d0a2107b8651444727a7cf5afd1 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:55:30 +0200 Subject: [PATCH 1/9] CI: one local pre-push gate that runs CI's own steps, enforced for agents Most failed PR runs were checks any machine can run (Vale/LanguageTool counts, inline guide snippets, comma-cut alt text, copyright headers, Playground snippets, Initializr rules). Agents ran hand-copied commands that judged differently from CI. - scripts/pre-push-gates.sh picks gates with CI's selector and runs the workflow steps themselves through scripts/ci/run-workflow-steps.py. - A clean pass records HEAD; .claude/settings.json wires scripts/ci/claude-pre-push-hook.py to block agent pushes of unrecorded commits (Java changes need --full). - check-workflows.yml runs --validate-steps so renaming a step the gate names fails the PR that renames it. - validate-guide-snippets.py honours CN1_MAVEN_REPO_LOCAL and CN1_GUIDE_SNIPPETS_NO_COMPILE. Co-Authored-By: Claude Opus 5.5 --- .claude/settings.json | 15 + .github/workflows/check-workflows.yml | 5 + .gitignore | 5 +- CLAUDE.md | 47 +++ scripts/ci/claude-pre-push-hook.py | 165 ++++++++++ scripts/ci/run-workflow-steps.py | 250 +++++++++++++++ .../validate-guide-snippets.py | 15 +- scripts/pre-push-gates.sh | 296 ++++++++++++++++++ 8 files changed, 793 insertions(+), 5 deletions(-) create mode 100644 .claude/settings.json create mode 100755 scripts/ci/claude-pre-push-hook.py create mode 100755 scripts/ci/run-workflow-steps.py create mode 100755 scripts/pre-push-gates.sh diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000000..927d2fc7d89 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/scripts/ci/claude-pre-push-hook.py\"" + } + ] + } + ] + } +} diff --git a/.github/workflows/check-workflows.yml b/.github/workflows/check-workflows.yml index 97edea55f40..8e15d50ffe8 100644 --- a/.github/workflows/check-workflows.yml +++ b/.github/workflows/check-workflows.yml @@ -51,6 +51,11 @@ jobs: # Those wrappers download from repo.codenameone.com, so a Maven or wrapper version # bump fails here, in one place, until the "Seed Maven distributions to R2" # workflow has copied it there -- not in every job that starts Maven. + # scripts/pre-push-gates.sh runs workflow steps BY NAME; a renamed step + # must fail here, in the PR that renames it, not in the next agent's push. + - name: Check the local pre-push gate names only steps that exist + run: bash scripts/pre-push-gates.sh --validate-steps + - name: Check R2 serves every Maven distribution the tree names run: bash maven/scripts/r2/seed-maven-distributions.sh --verify diff --git a/.gitignore b/.gitignore index 8abbb5941e2..1ecab09ff40 100644 --- a/.gitignore +++ b/.gitignore @@ -83,7 +83,9 @@ node_modules # bundled IDE configs versioned. !maven/cn1app-archetype/src/main/resources/archetype-resources/.idea !maven/cn1app-archetype/src/main/resources/archetype-resources/.idea/** -.claude/ +# Claude Code local state; the project hooks file is shared (pre-push gate). +**/.claude/* +!/.claude/settings.json target pom.xml.versionsBackup pom.xml.releaseBackup @@ -137,7 +139,6 @@ package-lock.json package.json !/scripts/package.json !/scripts/package-lock.json -.claude/ # Local screenshot/perf bench output /artifacts/ diff --git a/CLAUDE.md b/CLAUDE.md index c3ac7d2261c..5ffe6bad2b5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -106,6 +106,53 @@ To use locally-built version, edit the generated `pom.xml`: - **Main JAVA_HOME (for building the framework)**: Must be JDK 8 - **Runtime JDK for simulator / desktop run**: JDK 11 through 25 is supported. The Codename One Maven plugin checks this on entry to `cn1:run` and `cn1:debug` and aborts with a friendly error when an older JDK is in use. The build-time goals (`generate-desktop-app-wrapper`, `prepare-simulator-classpath`, the `executable-jar` profile) are not gated -- they still work on JDK 8 because they only generate icons / classpath metadata. +### Before every push: `scripts/pre-push-gates.sh` + +CI is the final gate, not the QA. Most failed runs on pull requests were checks +any machine can run: inline source blocks in the guide, image alt text cut short +by a comma, a Vale or LanguageTool finding, a Playground snippet that does not +compile (javadoc in `CodenameOne/src` counts), a near-miss class name, a +copyright header, a PMD finding, a build hint named in Initializr skill text, +launcher drift, an Initializr fixture rule. So before every push: + +1. **Commit.** CI judges commits, and the selector and header gate here read + `merge-base(origin/master)..HEAD`. `git fetch origin master` if it is old. +2. **`scripts/pre-push-gates.sh`**, every time, whatever the change. +3. **Add `--full`** when the branch changes Java (SpotBugs, PMD, Checkstyle, + build hint catalog, cast semantics), the website (Hugo build) or guide Java + snippets (compiled against the demos). +4. **Push only with no `FAILED` line.** `NOT RUN` lines are not passes; name + them when you report. + +The script copies no commands. CI's own selector +(`scripts/ci/select-ci-members.py`) picks the gates, and +`scripts/ci/run-workflow-steps.py` executes the **workflow steps themselves**: +`source-gates.yml` in full, and the `developer-guide-docs.yml`, `blog-prose.yml`, +`website-docs.yml` and `check-workflows.yml` steps. They run with a real +`GITHUB_ENV`, so the step that records a Vale count feeds the step that fails on +it, as it does on the runner. Hand-run copies are how local and CI drifted: plain +`vale` exits 0 on findings CI counts, a bare `check-copyright-headers.sh` sees +only the working tree, and the guide checks without the final "Fail build on +developer guide quality issues" step judge nothing. + +- **Agents cannot push without it.** A clean pass over a clean tree records + HEAD in `/cn1-pre-push-gates`, and the Claude Code hook in + `.claude/settings.json` (`scripts/ci/claude-pre-push-hook.py`) blocks a + `git push` of any commit not recorded there, or of a Java-changing commit + recorded without `--full`. Do not hand-write that file or route around the + hook; fix what the gate reports. Humans pushing from a terminal are not affected. +- **Fix a mismatch by naming a workflow step**, never by pasting a command into + the script. `check-workflows.yml` runs `scripts/pre-push-gates.sh + --validate-steps`, so renaming a step the script names fails that PR; update + the script's list in the same change. +- Gates that compile against Codename One (the Playground snippets, the guide + snippet compile) install the snapshots into this checkout's `maven/.m2-repo` + (`mvn install -Plocal-dev-javase` on JDK 17, never `~/.m2`). They run it + once, and again only when the branch touches what it installs. +- The script warns when local Vale or Hugo differs from the workflow's pin. +- CI alone runs the device and screenshot suites, the perf gates, the Xcode and + Android builds, the guide figure comparison and the Initializr's Windows leg. + ### Static Analysis Gates PR CI (`.github/workflows/pr.yml`, Java 8 leg) runs SpotBugs over diff --git a/scripts/ci/claude-pre-push-hook.py b/scripts/ci/claude-pre-push-hook.py new file mode 100755 index 00000000000..c286d5ce33f --- /dev/null +++ b/scripts/ci/claude-pre-push-hook.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. +"""Claude Code PreToolUse hook: no agent `git push` without a local gate pass. + +Wired in .claude/settings.json for the Bash tool. It reads the hook's JSON on +stdin, and when the command pushes from a Codename One checkout it requires +every commit being pushed to be recorded in /cn1-pre-push-gates, +which scripts/pre-push-gates.sh appends to after a clean pass over a clean +tree. A commit whose branch changes Java (CI's `pr` member) needs a --full pass. + +Exit 0 allows the call; exit 2 blocks it and the message on stderr is shown to +the agent. Anything this hook cannot understand is allowed, not blocked: it is +a guard against forgetting the gate, and a hook that wedges every push would be +switched off. A human pushing from a terminal is not affected. +""" +import json +import os +import re +import shlex +import subprocess +import sys + +STAMP = "cn1-pre-push-gates" +GATE = "scripts/pre-push-gates.sh" + + +def git(cwd, *args): + result = subprocess.run(("git", "-C", cwd) + args, capture_output=True, text=True) + return result.stdout.strip() if result.returncode == 0 else None + + +def segments(command): + """Split a shell command line into simple commands at ; && || | and newlines.""" + try: + lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|\n") + lexer.whitespace_split = True + lexer.commenters = "" + tokens = list(lexer) + except ValueError: + return None + current = [] + for token in tokens: + if token and set(token) <= set(";&|\n"): + if current: + yield current + current = [] + else: + current.append(token) + if current: + yield current + + +def pushes(command, cwd): + """Yield (directory, refs) for every `git push` in the command line.""" + split = segments(command) + if split is None: + return + for words in split: + while words and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[0]): + words = words[1:] # VAR=value prefixes + if words and words[0] in ("cd", "pushd") and len(words) > 1: + cwd = os.path.join(cwd, os.path.expanduser(words[1])) + continue + if not words or os.path.basename(words[0]) != "git": + continue + i, where = 1, cwd + while i < len(words) and words[i].startswith("-"): + if words[i] == "-C" and i + 1 < len(words): + where = os.path.join(where, os.path.expanduser(words[i + 1])) + i += 2 + elif words[i] in ("-c", "--git-dir", "--work-tree") and i + 1 < len(words): + i += 2 + else: + i += 1 + if i >= len(words) or words[i] != "push": + continue + args = words[i + 1:] + if any(a in ("--delete", "-d", "--dry-run", "-n", "--help", "-h") for a in args): + continue + if any(a in ("--all", "--mirror", "--branches") for a in args): + yield where, None # every branch: require all local branch tips + continue + positional = [a for a in args if not a.startswith("-")] + refspecs = positional[1:] # the first is the remote + yield where, refspecs or ["HEAD"] + + +def main(): + try: + data = json.load(sys.stdin) + except ValueError: + return 0 + if data.get("tool_name") != "Bash": + return 0 + command = (data.get("tool_input") or {}).get("command") or "" + if "push" not in command: + return 0 + problems = [] + for where, refs in pushes(command, data.get("cwd") or os.getcwd()): + top = git(where, "rev-parse", "--show-toplevel") + if not top or not os.path.exists(os.path.join(top, GATE)): + continue # not a Codename One checkout (or one from before the gate) + common = git(where, "rev-parse", "--path-format=absolute", "--git-common-dir") + recorded = {} + try: + with open(os.path.join(common, STAMP), encoding="utf-8") as handle: + for line in handle: + parts = line.split() + if len(parts) == 3: + prev = recorded.get(parts[0]) + # a full pass anywhere in the file outranks a quick one + if prev is None or parts[1] == "full": + recorded[parts[0]] = (parts[1], parts[2]) + except OSError: + pass + if refs is None: + refs = (git(where, "for-each-ref", "--format=%(refname)", "refs/heads") or "").split() + for ref in refs: + src = ref.lstrip("+").split(":", 1)[0] + if not src: + continue # `:branch` deletes + if src.startswith("refs/tags/") or git(where, "rev-parse", "-q", "--verify", "refs/tags/" + src): + continue # tags are cut from commits that were already gated + sha = git(where, "rev-parse", "-q", "--verify", src + "^{commit}") + if not sha: + continue # not a local revision; let git report it + entry = recorded.get(sha) + if entry is None and git(where, "merge-base", "--is-ancestor", sha, "origin/master") is not None: + continue # already on master: nothing of this branch's own to gate + if entry is None: + problems.append("%s (%s) has no passing %s run" % (src, sha[:10], GATE)) + elif entry[1] == "1" and entry[0] != "full": + problems.append("%s (%s) changes Java and passed without --full" % (src, sha[:10])) + if not problems: + return 0 + sys.stderr.write( + "Push blocked: CI is the final gate, not the QA.\n - " + "\n - ".join(problems) + + "\nCommit, then run `%s` (add --full when Java changed) until it reports no FAILED line;" + " a clean pass records HEAD and the push is allowed. See \"Before every push\" in CLAUDE.md.\n" + % GATE) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/ci/run-workflow-steps.py b/scripts/ci/run-workflow-steps.py new file mode 100755 index 00000000000..331bb3832a2 --- /dev/null +++ b/scripts/ci/run-workflow-steps.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. +"""Run the ``run:`` blocks of a GitHub workflow job on this machine. + +The local pre-push gate (scripts/pre-push-gates.sh) used to be a set of +hand-copied commands, and every copy drifted from the workflow it imitated: +Vale was run without the issue-count rule, the copyright check without a base, +the guide lint without the final step that turns findings into a failure. So +nothing is copied any more. This script reads the workflow YAML and executes +the job's own step scripts, in order, with the job's env, a real GITHUB_ENV +(so a step that records a status feeds the step that judges it, exactly as on +the runner), and GITHUB_OUTPUT / GITHUB_STEP_SUMMARY files. + +Steps are chosen BY NAME with --step. A name that no longer exists in the +workflow is an error, never a silent skip: renaming a CI step breaks the local +gate loudly instead of quietly dropping a check. ``uses:`` steps (setup +actions) are not run; the developer's machine supplies the tools, and +scripts/pre-push-gates.sh checks their versions against the workflow pins. + +``${{ ... }}`` expressions are resolved for the few contexts a local pull +request run has (github.event_name, base/head SHAs, runner.temp, matrix +values given with --matrix); anything else resolves to an empty string and is +reported, so a step that silently depends on one is visible. + + scripts/ci/run-workflow-steps.py .github/workflows/source-gates.yml \ + --job source-gates --all-run-steps --base origin/master + scripts/ci/run-workflow-steps.py .github/workflows/developer-guide-docs.yml \ + --job build --step "Run Asciidoctor lint" --step "Fail build on ..." +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from shutil import which as shutil_which + +try: + import yaml +except ImportError: # pragma: no cover + sys.exit("run-workflow-steps: PyYAML is required (pip install pyyaml)") + +EXPR = re.compile(r"\$\{\{\s*(.*?)\s*\}\}") + + +def git(*args): + return subprocess.check_output(("git",) + args, text=True).strip() + + +class Context: + def __init__(self, base, head, temp, matrix): + self.values = { + "github.event_name": "pull_request", + "github.event.pull_request.base.sha": base, + "github.event.pull_request.head.sha": head, + "github.event.before": "", + "github.sha": head, + "github.base_ref": "master", + "github.head_ref": git("rev-parse", "--abbrev-ref", "HEAD"), + "github.ref_name": git("rev-parse", "--abbrev-ref", "HEAD"), + "github.workspace": os.getcwd(), + "github.repository": "codenameone/CodenameOne", + "runner.temp": temp, + "runner.os": "macOS" if sys.platform == "darwin" else "Linux", + } + for key, value in matrix.items(): + self.values["matrix." + key] = value + self.unresolved = set() + + def resolve(self, text): + if not isinstance(text, str): + return "" if text is None else str(text) + + def sub(match): + expr = match.group(1) + if expr in self.values: + return self.values[expr] + # `a || b` picks the first resolvable operand, as Actions does. + for part in (p.strip() for p in expr.split("||")): + if part in self.values and self.values[part]: + return self.values[part] + if part.startswith("'") and part.endswith("'"): + return part[1:-1] + self.unresolved.add(expr) + return "" + + return EXPR.sub(sub, text) + + +def read_env_file(path, env): + """Apply a GITHUB_ENV file: KEY=VALUE lines and KEY<&2; exit 2 ;; + esac +done + +RUN="python3 scripts/ci/run-workflow-steps.py" +WF=.github/workflows +FAILED=() +SKIPPED=() +note() { printf '\n=== %s\n' "$*"; } +gate() { # gate