Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ This skill uses OpenRewrite to perform Abstract Syntax Tree (AST) based refactor

Because OpenRewrite's YAML recipes do not natively support simple variable or field renaming, a custom script is provided:
```bash
python3 .gemini/skills/java-ast-refactoring/scripts/safe_rename.py <filepath> <old_name> <new_name>
python3 .agents/skills/java-ast-refactoring/scripts/safe_rename.py <filepath> <old_name> <new_name>
```
**CRITICAL:** Running this python script is a LAST RESORT. It is a regex-based token replacement that ignores strings and comments, but it lacks true AST understanding. ALWAYS prefer using OpenRewrite recipes (`rewrite.yml`) for structural changes like renaming classes, methods, or moving targets, as OpenRewrite correctly handles imports, types, and cross-file references safely.

## Usage

1. Start from a clean working tree (`git status`) so the refactoring diff is isolated and easy to revert.
2. Create a `rewrite.yml` recipe file in the workspace root. Refer to `.gemini/skills/java-ast-refactoring/references/rewrite_recipes.md` for syntax. The recipe's first `name:` line is the recipe that gets activated.
2. Create a `rewrite.yml` recipe file in the workspace root. Refer to `.agents/skills/java-ast-refactoring/references/rewrite_recipes.md` for syntax. The recipe's first `name:` line is the recipe that gets activated.
3. Execute the script from the repository root:
```bash
./.gemini/skills/java-ast-refactoring/scripts/run_rewrite.sh rewrite.yml
./.agents/skills/java-ast-refactoring/scripts/run_rewrite.sh rewrite.yml
```
A recipe stored elsewhere is copied to `./rewrite.yml` for the run and removed afterwards; a recipe already at `./rewrite.yml` is used in place and left untouched. Delete your own `./rewrite.yml` before committing.
4. The script will safely apply the AST transformations and then automatically run `./gradlew spotlessApply` and `./gradlew javaIncrementalFormatApply` on the modified files to automatically fix any Checkstyle line-length and import ordering issues caused by longer/shorter identifiers.
Expand All @@ -35,7 +35,7 @@ python3 .gemini/skills/java-ast-refactoring/scripts/safe_rename.py <filepath> <o
```
3. Run the tests covering the touched code, e.g. `./gradlew :core:standardTest -x :console-webapp:buildConsoleWebapp`.
4. Confirm `git status` shows no stray files (`rewrite.yml`, `rewrite-init.gradle`, or a modified `console-webapp/package-lock.json`).
5. Commit, then run the `pr-polisher` skill (`python3 .gemini/skills/pr-polisher/scripts/check_diff.py`) to catch leftover fully qualified names, unused imports, and other anti-patterns.
5. Commit, then run the `pr-polisher` skill (`python3 .agents/skills/pr-polisher/scripts/check_diff.py`) to catch leftover fully qualified names, unused imports, and other anti-patterns.

## Error Recovery

Expand All @@ -48,4 +48,3 @@ python3 .gemini/skills/java-ast-refactoring/scripts/safe_rename.py <filepath> <o

## Known Limitations & Troubleshooting
* **Static Imports Dropped on Class Rename:** When using `ChangeType` to rename a class, OpenRewrite may sometimes drop static imports for fields/constants belonging to the old class instead of updating them to the new class. If compilation fails due to "cannot find symbol" for a constant after a class rename, manually restore the static import (e.g., `import static com.new.ClassName.CONSTANT;`).
* **Continuous Improvement:** If any new issues or edge cases are found while running the refactoring (e.g., build failures, formatting issues, or missed transformations), you **MUST** proactively ask the user if you should permanently update this skill file (`SKILL.md`) and its accompanying scripts (`scripts/run_rewrite.sh`, `scripts/safe_rename.py`) to fix the issue for future use. Do not wait for the user to prompt you to fix the infrastructure.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
---
name: pr-polisher
description: Automated pre-flight checklist to polish PRs. Use this before declaring a task or PR complete to automatically verify license headers, commit hygiene, formatting, and codebase mandates. Don't use for: non-Git or Piper changelists.
description: >-
Automated pre-flight checklist to polish PRs. Use this before declaring a task
or PR complete to automatically verify license headers, commit hygiene,
formatting, and codebase mandates. Don't use for non-Git changelists.
---

# PR Polisher
Expand All @@ -12,20 +15,13 @@ You, the AI agent, are known to forget to run this skill. To prevent this, you a
**ANY TIME you create a commit, amend a commit, or complete a user's request that modifies the repository state, your VERY LAST action before generating a text response to the user MUST be to run this workflow.**
Do not ask for permission. Do not wait for the user to remind you. Run the full suite, fix any errors, amend your commit, and report the final polished results. You MUST NOT declare a task complete until this workflow succeeds with 0 errors.

## Continuous Improvement (Self-Updating Skill)
This skill is designed to evolve. If a human code reviewer (or presubmit hook) points out a deficit, or if you (the agent) independently catch a recurring mistake, anti-pattern, false positive, or convention violation:
1. **You MUST proactively propose a fix to the user.** Do not wait for the user to instruct you to update the skill. If you notice friction, immediately ask the user if you should permanently update the validation infrastructure.
2. **Determine how to enforce the check.** Consider if the check is suitable for automation in the Python script. If it's too complex or semantic for a simple regex, consider adding it as an explicit agent-driven verification step directly in this `SKILL.md` file.
3. Update `.gemini/skills/pr-polisher/scripts/check_diff.py` to add a new automated check, OR modify this `SKILL.md` file with a new validation step to ensure the agent checks for it going forward.
4. Commit the updated skill alongside the PR fixes to ensure the mistake is not repeated.

## Workflow Execution Steps

1. **Sync, Rebase, and Run the Automated Analysis Script**
First, fetch the latest `upstream/master` (`git fetch upstream master`) and rebase onto it (`git rebase upstream/master`) whenever creating or updating a PR branch—including in-flight code reviews—so the PR merges cleanly onto `master`. Then execute the packaged Python diff-checker script from the repository root. This script automatically checks commit messages, working tree status, `package-lock.json` modifications, copyright years on new files, missing tests across all tested modules, the 2-PR database schema split (Flyway scripts must not ship with Java or `db-schema.sql.generated` changes), Valkey Protostuff-cached entity field edits, GKE `requests.memory` sizing against `-XX:MaxRAMPercentage`, single-read `ServletInputStream` dual-injection hazards, state-machine anti-patterns (`TimedTransitionProperty.fromValueMap`, ordinal `Enum.compareTo`, Angular `setTimeout`/`GlobalLoaderService`/multi-boolean state flags), internal-only links or paths leaking into this public repository, whether the branch is rebased onto `upstream/master` and `FETCH_HEAD` freshness, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching).

```bash
python3 .gemini/skills/pr-polisher/scripts/check_diff.py
python3 .agents/skills/pr-polisher/scripts/check_diff.py
```

2. **Run Formatting Validation**
Expand Down Expand Up @@ -90,4 +86,4 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p
git add -u
git commit --amend # Or git commit --amend --no-edit if only files changed
```
**CRITICAL:** You must loop back to Step 1 and run `python3 .gemini/skills/pr-polisher/scripts/check_diff.py` again. Continue this loop of checking and amending until the script definitively returns `0 ERRORS`, the build/presubmits pass, and the working directory is perfectly clean. Do not assume your fixes worked without re-running the check.
**CRITICAL:** You must loop back to Step 1 and run `python3 .agents/skills/pr-polisher/scripts/check_diff.py` again. Continue this loop of checking and amending until the script definitively returns `0 ERRORS`, the build/presubmits pass, and the working directory is perfectly clean. Do not assume your fixes worked without re-running the check.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
errors_found = 0
warnings_found = 0

SCRIPT_PATH = ".gemini/skills/pr-polisher/scripts/check_diff.py"
SCRIPT_PATH = ".agents/skills/pr-polisher/scripts/check_diff.py"

# Modules whose src/main Java changes should be accompanied by test changes.
TESTED_MODULES = (
Expand Down Expand Up @@ -123,9 +123,6 @@ def log_success(msg):
def run_cmd(cmd):
return subprocess.check_output(cmd, shell=True, text=True).strip()

def get_diff_files():
return [f for f in run_cmd("git diff HEAD^ --name-only").split('\n') if f]

def ref_exists(ref):
return subprocess.run(
["git", "rev-parse", "--verify", "--quiet", ref],
Expand All @@ -134,21 +131,56 @@ def ref_exists(ref):
check=False,
).returncode == 0

def merge_base(ref):
"""Returns merge-base of HEAD and ref, or None if missing/unrelated/shallow."""
if not ref_exists(ref):
return None
try:
return run_cmd(f"git merge-base HEAD {ref}")
except subprocess.CalledProcessError:
return None

def get_diff_base():
"""Returns the read-only merge-base against the freshest master ref."""
upstream_base = merge_base("refs/remotes/upstream/master")
origin_base = merge_base("refs/remotes/origin/master")

if upstream_base and origin_base:
is_upstream_ancestor = subprocess.run(
["git", "merge-base", "--is-ancestor", upstream_base, origin_base],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
).returncode == 0
base = origin_base if is_upstream_ancestor else upstream_base
else:
base = upstream_base or origin_base or merge_base("refs/heads/master")

if base:
head = run_cmd("git rev-parse HEAD")
if base != head:
return base
if ref_exists("HEAD^"):
return "HEAD^"
return "HEAD"

def get_diff_files():
return [f for f in run_cmd(f"git diff {get_diff_base()} --name-only").split('\n') if f]

def check_single_commit():
print("--- Checking Commit Count ---")
try:
base_refs = ["^master"]
upstream_ref = "refs/remotes/upstream/master"
if (
subprocess.run(
["git", "rev-parse", "--verify", upstream_ref],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
).returncode
== 0
):
base_refs.append("^upstream/master")
base_refs = [
f"^{ref}"
for ref in (
"refs/heads/master",
"refs/remotes/upstream/master",
"refs/remotes/origin/master",
)
if ref_exists(ref)
]
if not base_refs:
return
refs_arg = " ".join(base_refs)
count = int(run_cmd(f"git rev-list --count HEAD {refs_arg}"))
if count > 1:
Expand Down Expand Up @@ -195,7 +227,7 @@ def check_workspace_clean():

def check_package_lock():
print("\n--- Checking package-lock.json ---")
diff_files = run_cmd("git diff HEAD^ --name-only").split('\n')
diff_files = get_diff_files()
if "console-webapp/package-lock.json" in diff_files:
if "console-webapp/package.json" in diff_files or "dependencies.gradle" in diff_files:
log_warning("console-webapp/package-lock.json is modified in the diff. This is expected since dependencies were updated.")
Expand All @@ -207,7 +239,7 @@ def check_package_lock():
def check_license_headers():
print("\n--- Checking License Headers on New Files ---")
current_year = str(datetime.datetime.now().year)
added_files = run_cmd("git diff HEAD^ --name-status --diff-filter=A").split('\n')
added_files = run_cmd(f"git diff {get_diff_base()} --name-status --diff-filter=A").split('\n')

java_header = f"// Copyright {current_year} The Nomulus Authors. All Rights Reserved."
script_header = f"# Copyright {current_year} The Nomulus Authors. All Rights Reserved."
Expand Down Expand Up @@ -308,13 +340,6 @@ def check_upstream_freshness():
def check_formatting():
print("\n--- Checking Project Formatting ---")
try:
# Keep local origin/master tracking ref in sync with upstream/master so
# google-java-format-git-diff.sh only checks the current branch's diff.
try:
run_cmd("git rev-parse --verify refs/remotes/upstream/master")
run_cmd("git update-ref refs/remotes/origin/master refs/remotes/upstream/master")
except Exception as e:
log_warning(f"Failed to fast-forward origin/master to upstream/master: {e}")
run_cmd("./gradlew spotlessCheck javaIncrementalFormatCheck")
log_success("All formatting checks (spotless and javaIncrementalFormat) passed.")
except Exception as e:
Expand All @@ -325,7 +350,7 @@ def check_formatting():

def check_diff_anti_patterns():
print("\n--- Checking Code Anti-Patterns in Diff ---")
diff = run_cmd("git diff HEAD^ -U0")
diff = run_cmd(f"git diff {get_diff_base()} -U0")
current_file = ""

# Regex Patterns
Expand Down Expand Up @@ -428,7 +453,7 @@ def check_diff_anti_patterns():

# System clocks
if now_pattern.search(code_line):
log_error(f"[{current_file}] Found un-injected clock (Instant.now / System.currentTimeMillis). Inject Clock instead.")
log_error(f"[{current_file}] Found un-injected clock (Instant.now / System.currentTimeMillis). Inject Clock (or use a fixed Instant.parse(...) constant in tests) instead.")

# Catch generic
if catch_generic_pattern.search(code_line):
Expand Down Expand Up @@ -473,7 +498,7 @@ def check_diff_anti_patterns():

# Instant toString
if instant_tostring_pattern.search(code_line):
log_error(f"[{current_file}] Found potential Instant.toString(). Use DateTimeUtils.formatInstant(...) to preserve .000Z precision.")
log_error(f"[{current_file}] Found potential Instant.toString(). Statically import formatInstant(...) from DateTimeUtils to preserve .000Z precision.")

# DAO transactions
if current_file.lower().endswith('dao.java') and dao_transact_pattern.search(code_line):
Expand Down Expand Up @@ -515,7 +540,7 @@ def check_diff_anti_patterns():

def check_internal_link_leaks():
print("\n--- Checking for Internal Link and Path Leaks ---")
diff = run_cmd("git diff HEAD^ -U0")
diff = run_cmd(f"git diff {get_diff_base()} -U0")
current_file = ""
leaks_found = False

Expand Down Expand Up @@ -551,7 +576,7 @@ def is_jpa_entity(path):

def check_protostuff_cached_entities():
print("\n--- Checking Protostuff-Cached Entities (Valkey Compatibility) ---")
diff = run_cmd("git diff HEAD^ -U0")
diff = run_cmd(f"git diff {get_diff_base()} -U0")
current_file = ""
flagged_files = set()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
# limitations under the License.

import os
import subprocess
import sys
import tempfile
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import check_diff
Expand Down Expand Up @@ -200,6 +202,38 @@ def test_check_gke_memory_requests_checks_manifests_when_start_sh_changes(self):
finally:
check_diff.warnings_found = prev_warnings

def test_get_diff_base_handles_shallow_or_unrelated_remote_refs(self):
def fake_run_cmd(cmd):
if cmd == "git merge-base HEAD refs/remotes/upstream/master":
raise subprocess.CalledProcessError(1, cmd)
if cmd == "git merge-base HEAD refs/remotes/origin/master":
return "abc123"
if cmd == "git rev-parse HEAD":
return "def456"
raise AssertionError(f"Unexpected cmd: {cmd}")

with (
mock.patch.object(check_diff, "ref_exists", return_value=True),
mock.patch.object(check_diff, "run_cmd", side_effect=fake_run_cmd),
):
self.assertEqual(check_diff.get_diff_base(), "abc123")

def test_get_diff_base_falls_back_to_local_master_when_remotes_fail(self):
def fake_run_cmd(cmd):
if "refs/remotes/" in cmd:
raise subprocess.CalledProcessError(1, cmd)
if cmd == "git merge-base HEAD refs/heads/master":
return "local123"
if cmd == "git rev-parse HEAD":
return "head456"
raise AssertionError(f"Unexpected cmd: {cmd}")

with (
mock.patch.object(check_diff, "ref_exists", return_value=True),
mock.patch.object(check_diff, "run_cmd", side_effect=fake_run_cmd),
):
self.assertEqual(check_diff.get_diff_base(), "local123")


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