From 7912b4520f4f534eebb66bf40e2a484223861345 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Tue, 24 Nov 2026 15:33:10 -0500 Subject: [PATCH] Migrate skills to .agents and trim GEMINI.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI coding agents and reviewers working across fork-based workflows currently hit four recurring sources of friction: repository skills sit in a legacy directory that standard Git workspaces do not auto-discover, local diff and formatting checks overwrite remote tracking refs or diff against stale fork bases, redundant checklists and contradictory rules bloat always-on context toward per-file truncation limits, and commit messages often bury why a change matters beneath low-level file mechanics. Consolidating and trimming the repository engineering guide, relocating skills to the standard discovery directory, making fork-point detection strictly read-only, and requiring plain-English motivation at the top of every commit eliminate these failure modes. As a result, agents discover repository skills automatically without mutating developer Git remotes, always-on instructions stay comfortably below truncation caps, and reviewers can grasp the purpose and value of every pull request on first read. 1. **`GEMINI.md` (`20,649 B` -> `18,118 B`, down from `28,125 B` pre-#3284):** - Keeps the guide comfortably below the `24,000 B` per-file truncation cap while preserving all invariants added in #3284, #3301, and #3312 (including `Sync & Rebase onto upstream/master`). - Updates `Commit Message Style` so commit and PR bodies open with 2–4 plain-English sentences stating why the change is being made, what problem, waste, or risk exists today, and what concrete outcome improves—before naming classes, flags, or implementation mechanics ("what"/"how"). - Replaces the rigid push ban with a default push gate (halt at local commit unless overridden by a user-level rule or an explicit directive to open/update a PR; use `--force-with-lease` on amended branches; never chain remote transfers with `git commit`). - Resolves internal contradictions: recommends a fixed static `Instant.parse(...)` constant in `reTransact` test helpers (instead of `clock.now()`) and statically imported `formatInstant(...)` from `DateTimeUtils`. - Preserves both Reviewable footer formats (the HTML-comment Reviewable block and `This change is https://reviewable.io/reviews/...`), deduplicates the pre-commit `pr-polisher` checklist into a concise pointer to `.agents/skills/pr-polisher/SKILL.md`, and keeps a single concise `Continuous Improvement` bullet under `Common Pitfalls & Efficiency`. 2. **Migrate repo skills from `.gemini/skills/` to `.agents/skills/`:** - Moves `pr-polisher` (including `check_diff_test.py` from #3311) and `java-ast-refactoring` into `.agents/skills/` so agents automatically discover them in Git workspaces, updating all path references (including `SCRIPT_PATH` in `check_diff.py`). - Removes duplicated `Continuous Improvement` sections from both `SKILL.md` files (previously instructing agents to commit skill edits inside unrelated PRs), keeping the single concise `Continuous Improvement` bullet in `GEMINI.md`, and fixes YAML 1.2 frontmatter quoting in `.agents/skills/pr-polisher/SKILL.md` (removing internal VCS wording). 3. **Read-only merge-base & `pr-polisher` fixes:** - Removes the `git update-ref` mutation of `refs/remotes/origin/master` from `.agents/skills/pr-polisher/scripts/check_diff.py` and replaces hardcoded `HEAD^` diffs (including `check_protostuff_cached_entities()`) with a read-only `get_diff_base()` helper selecting the fresher merge-base across `upstream/master` and `origin/master` (gracefully catching `CalledProcessError` on shallow or unrelated remote refs and falling back to `refs/heads/master`, covered in `check_diff_test.py`). - Updates `java-format/google-java-format-git-diff.sh` (`findForkPoint()`) to pick the fresher merge-base across fully qualified `refs/remotes/upstream/master` and `refs/remotes/origin/master` read-only (falling back cleanly on shallow/unrelated refs via `|| true` and propagating errors via `forkPoint=$(findForkPoint) || exit 1`). - Fixes the self-contradictory `DateTimeUtils.formatInstant(...)` message in `check_diff.py` to recommend statically importing `formatInstant(...)`, and aligns the `Instant.now()` message with `GEMINI.md`. Verification: - `python3 .agents/skills/pr-polisher/scripts/check_diff_test.py -v`: `11/11` passed. - `python3 .agents/skills/pr-polisher/scripts/check_diff.py`: `0` errors, `0` warnings (`spotlessCheck` and `javaIncrementalFormatCheck` passed). - `./gradlew --no-daemon runPresubmits`: `BUILD SUCCESSFUL`. - Verified strict YAML frontmatter parsing on all `.agents/skills/*/SKILL.md` files, `bash -n java-format/google-java-format-git-diff.sh`, and zero remaining `.gemini/skills` references across the repository. BUG=http://b/588443833 Signed-off-by: Ben McIlwain --- .../skills/java-ast-refactoring/SKILL.md | 9 +- .../references/rewrite_recipes.md | 0 .../scripts/run_rewrite.sh | 0 .../scripts/safe_rename.py | 0 .../skills/pr-polisher/SKILL.md | 16 ++-- .../skills/pr-polisher/scripts/check_diff.py | 85 ++++++++++++------- .../pr-polisher/scripts/check_diff_test.py | 34 ++++++++ GEMINI.md | 71 ++++++---------- java-format/google-java-format-git-diff.sh | 34 ++++++-- 9 files changed, 156 insertions(+), 93 deletions(-) rename {.gemini => .agents}/skills/java-ast-refactoring/SKILL.md (86%) rename {.gemini => .agents}/skills/java-ast-refactoring/references/rewrite_recipes.md (100%) rename {.gemini => .agents}/skills/java-ast-refactoring/scripts/run_rewrite.sh (100%) rename {.gemini => .agents}/skills/java-ast-refactoring/scripts/safe_rename.py (100%) rename {.gemini => .agents}/skills/pr-polisher/SKILL.md (85%) rename {.gemini => .agents}/skills/pr-polisher/scripts/check_diff.py (94%) rename {.gemini => .agents}/skills/pr-polisher/scripts/check_diff_test.py (82%) diff --git a/.gemini/skills/java-ast-refactoring/SKILL.md b/.agents/skills/java-ast-refactoring/SKILL.md similarity index 86% rename from .gemini/skills/java-ast-refactoring/SKILL.md rename to .agents/skills/java-ast-refactoring/SKILL.md index 0a3fbf24e05..d6e9361b34d 100644 --- a/.gemini/skills/java-ast-refactoring/SKILL.md +++ b/.agents/skills/java-ast-refactoring/SKILL.md @@ -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 +python3 .agents/skills/java-ast-refactoring/scripts/safe_rename.py ``` **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. @@ -35,7 +35,7 @@ python3 .gemini/skills/java-ast-refactoring/scripts/safe_rename.py - + 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 @@ -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** @@ -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. diff --git a/.gemini/skills/pr-polisher/scripts/check_diff.py b/.agents/skills/pr-polisher/scripts/check_diff.py similarity index 94% rename from .gemini/skills/pr-polisher/scripts/check_diff.py rename to .agents/skills/pr-polisher/scripts/check_diff.py index 01465c567ff..264784c8aa6 100644 --- a/.gemini/skills/pr-polisher/scripts/check_diff.py +++ b/.agents/skills/pr-polisher/scripts/check_diff.py @@ -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 = ( @@ -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], @@ -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: @@ -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.") @@ -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." @@ -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: @@ -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 @@ -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): @@ -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): @@ -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 @@ -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() diff --git a/.gemini/skills/pr-polisher/scripts/check_diff_test.py b/.agents/skills/pr-polisher/scripts/check_diff_test.py similarity index 82% rename from .gemini/skills/pr-polisher/scripts/check_diff_test.py rename to .agents/skills/pr-polisher/scripts/check_diff_test.py index 342f683e2ce..b923154c4f1 100644 --- a/.gemini/skills/pr-polisher/scripts/check_diff_test.py +++ b/.agents/skills/pr-polisher/scripts/check_diff_test.py @@ -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 @@ -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() diff --git a/GEMINI.md b/GEMINI.md index a3a6f14ab40..bf2d7d9a706 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -1,13 +1,12 @@ # Nomulus Engineering Guide for Gemini -This document captures the mandates, architectural patterns, and project conventions needed to produce high-quality, idiomatic Nomulus code on the first iteration. When modifying this file, review the whole document to avoid duplicate instructions and keep it coherent. +Core mandates, architectural patterns, and conventions for Nomulus. Review the whole file when editing to keep it coherent and non-redundant. -## 🏛 Architecture Overview - -- **Transaction Management:** The codebase uses a custom wrapper around JPA. Always use `tm()` (from `TransactionManagerFactory`) to interact with the database. -- **Dependency Injection:** Dagger 2 is used extensively. "cannot find symbol" errors for classes starting with `Dagger...` mean annotation processing failed; fix compilation in core models first to restore generated code. -- **Value Types:** AutoValue and `ImmutableObject` patterns are dominant. Most models follow a `Buildable` pattern with a nested `Builder`. -- **Temporal Logic:** The project uses `java.time` for all temporal representations. Core boundaries: `DateTimeUtils.START_INSTANT` (Unix Epoch) and `DateTimeUtils.END_INSTANT` (`Long.MAX_VALUE / 1000`). +## Architecture Overview +- **Transaction Management:** Custom JPA wrapper; always use `tm()` (from `TransactionManagerFactory`). +- **Dependency Injection:** Dagger 2. `"cannot find symbol"` for `Dagger...` means annotation processing failed; fix core model compilation first (or `git checkout` a corrupted builder/component and re-apply surgically). +- **Value Types:** AutoValue and `ImmutableObject` (`Buildable` + nested `Builder`). +- **Temporal Logic:** `java.time` with `DateTimeUtils.START_INSTANT` (Unix Epoch) and `DateTimeUtils.END_INSTANT` (`Long.MAX_VALUE / 1000`). ## Core Mandates @@ -25,7 +24,7 @@ This document captures the mandates, architectural patterns, and project convent - **Test Timestamps:** Prefer fixed constants (e.g., `Instant.parse("2024-03-27T10:15:30.105Z")`) over capturing `clock.now()` to avoid flakiness. - **Beam Pipelines:** `Clock` is serializable; pass it through the `DoFn` constructor or Dagger provider methods in the pipeline module. - **Command-Line Tools:** Use a package-private `@Inject Clock clock;` field in `Command` implementations and set `command.clock = fakeClock;` in the test's `@BeforeEach` (base classes like `EppToolCommandTestCase` do this for generic command types). -- **Serialization Precision (`.000Z`):** Format `Instant`s with `DateTimeUtils.formatInstant(...)`, never `Instant.toString()` (which drops `.000Z` for whole seconds). Keep this in mind when editing `.xml`/`.yaml` test data. +- **Serialization Precision (`.000Z`):** Format `Instant`s with statically imported `formatInstant(...)` from `DateTimeUtils`, never `Instant.toString()` (which drops `.000Z` for whole seconds). Keep this in mind when editing `.xml`/`.yaml` test data. ### 3. Dependency Injection (Dagger) - **Concrete Types:** Dagger `inject` methods must use explicit concrete types; generic `inject(Command)` methods do not work. @@ -34,7 +33,7 @@ This document captures the mandates, architectural patterns, and project convent ### 4. Database Consistency - **Top-Level Transactions:** Define `tm().transact(...)` at the highest level of the call chain (Action, Command, or Flow) so all work is atomic and covered by retries. - **DAO Methods:** Never open transactions inside low-level DAO methods; use `tm().assertInTransaction()`. -- **`reTransact`:** Use `tm().reTransact(...)` for utility methods or Caffeine cache loaders reachable from both transactional and non-transactional paths (it joins an existing transaction or starts a new one). Test helpers may use `tm().reTransact(tm()::getTxTime)`, but NEVER `tm().transact(() -> tm().reTransact(...))`; when exact DB time is not needed, use `clock.now()`. In production code, wrap the *caller* in a transaction instead of adding `reTransact()` around `getTxTime()`. +- **`reTransact`:** Use `tm().reTransact(...)` for utility methods or Caffeine cache loaders reachable from both transactional and non-transactional paths (it joins an existing transaction or starts a new one). Test helpers may use `tm().reTransact(tm()::getTxTime)`, but NEVER `tm().transact(() -> tm().reTransact(...))`; when exact DB time is not needed, use a fixed static `Instant.parse(...)` constant. In production code, wrap the *caller* in a transaction instead of adding `reTransact()` around `getTxTime()`. - **`tm()` vs. `replicaTm()`:** Transaction state lives in a static `ThreadLocal` shared by every `JpaTransactionManagerImpl`, so a `replicaTm()` call inside a `tm()` transaction (or vice versa) is a nested transaction on the *outer* database. Finish one before starting the other. - **2-PR Schema Split:** Read `db/README.md` before any schema change. Never combine Flyway scripts (`db/src/main/resources/sql/flyway/V*.sql`) with Java ORM changes in one PR, because servers mid-rollout fail on unmigrated columns: 1. **PR #1 (Schema Only):** the Flyway script, `flyway.txt` (`:db:generateFlywayIndex`), `nomulus.golden.sql` (`:nom:generate_golden_file`), and ER diagrams. **Zero `.java` or `db-schema.sql.generated` changes.** @@ -78,10 +77,9 @@ This document captures the mandates, architectural patterns, and project convent - **SQL Integration:** Whenever a schema, Flyway script, or JPA entity changes, also run `./gradlew :db:test` and `./gradlew :core:sqlIntegrationTest`. ## Build Strategy -- **Compile Before Testing:** Run `./gradlew build -x test` (or `./gradlew :core:build -x test -x :console-webapp:buildConsoleWebapp` for backend-only changes) before unit tests; tests will not run if any part of `core` fails to compile. -- **Skip the Console Build:** Always pass `-x :console-webapp:buildConsoleWebapp` for backend-only tasks. Otherwise `:core:processResources` triggers `npmInstallDeps`, which dirties `console-webapp/package-lock.json` and can fail on host Node.js version mismatches. -- **Package Lock:** Revert `console-webapp/package-lock.json` (`git checkout console-webapp/package-lock.json`) before committing unless you intentionally changed NPM dependencies. -- **Formatting Failures:** Never declare success if `spotlessCheck`, `javaIncrementalFormatCheck`, or tests fail. Run `./gradlew spotlessApply` and re-run the build. +- **Compile Before Testing:** Run `./gradlew :core:build -x test -x :console-webapp:buildConsoleWebapp` for backend-only changes (pass `-x :console-webapp:buildConsoleWebapp` so `:core:processResources` does not trigger `npmInstallDeps`, dirtying `console-webapp/package-lock.json` or failing on host Node.js version mismatches). Run `./gradlew build -x test` when `console-webapp/` is modified. +- **Package Lock:** Revert `console-webapp/package-lock.json` (`git checkout console-webapp/package-lock.json`) before committing unless NPM dependencies intentionally changed. +- **Formatting Failures:** Never declare success if `spotlessCheck`, `javaIncrementalFormatCheck`, or tests fail. Run `./gradlew spotlessApply javaIncrementalFormatApply` and re-verify. ## Project Dependencies - **Common Module:** Modules using `Clock` or other core utilities (e.g., `load-testing`) need `implementation project(':common')` in their `build.gradle`. @@ -96,34 +94,21 @@ This document captures the mandates, architectural patterns, and project convent ## Source Control and Pull Requests - **Public Repository:** Never commit internal-only links, hostnames, file paths, or shortlinks. Bug-tracker references such as `b/123` are fine. -- **One Commit Per PR:** Create a commit for the branch's work, then amend follow-up changes into it (`git commit --amend --no-edit`) so the PR stays a single, clean commit. -- **Sync & Rebase onto `upstream/master`:** Whenever creating a PR or amending/pushing changes (including in-flight code review fixes), fetch the latest `upstream/master` (`git fetch upstream master`) and run `git rebase upstream/master` before testing and pushing. Keeping branches rebased onto `master` prevents merge conflicts and merge-queue failures, which outweighs minor review-diff turnover. Do not spontaneously rebase untouched, already-approved PRs unless GitHub blocks merging. -- **Commit Message Style:** Subject at most 50 characters, capitalized, no trailing punctuation. The body must summarize the "what" and "why" of the entire diff, including operational justification and CLI usage examples where relevant. -- **Completion Verification:** After every commit or amend, run `git status` and confirm `nothing to commit, working tree clean`. If changes remain, stage and amend, then re-check. Only then may you declare the task complete. -- **Diff Review:** Review `git diff HEAD^` before finalizing. Revert formatting-only changes in files without functional updates. -- **No Unsolicited Pushes:** NEVER run `git push` (or any remote transfer) without explicit, unambiguous authorization from the user in the immediate turn. When finished, state that the work is committed locally and ready for review. -- **Zero-Bundling Rule:** Run every remote transfer command as its own standalone command, never chained with `&&`, `||`, or `;` alongside local staging or commit commands. -- **Two-Step Handover:** Halt at the local commit. Report the commit SHA, `git status`, and diff verification, then ask: *"Local commit `[SHA]` is verified. Do you authorize running `git push origin [branch]` (or `--force-with-lease` when force-pushing an amended branch) to update the remote repository?"* +- **Sync & Rebase onto `upstream/master`:** Fetch the latest `upstream/master` (`git fetch upstream master`) before branching and run `git rebase upstream/master` whenever creating a PR or amending/pushing changes (including in-flight code review fixes) so branches merge cleanly. Do not spontaneously rebase untouched, already-approved PRs unless GitHub blocks merging. +- **One Commit Per PR:** Create one commit for the branch's work and amend follow-up fixes (`git commit --amend --no-edit`). +- **Commit Message Style:** Subject at most 50 characters, capitalized, no trailing punctuation. Open the body with 2–4 plain-English sentences stating **why** the change is being made, what problem, waste, or risk exists today, and **what concrete outcome improves**—before naming classes, flags, or implementation mechanics ("what"/"how"), including operational justification and CLI usage examples where relevant. +- **Completion Verification:** After every commit or amend, run `git status` and confirm `nothing to commit, working tree clean` before declaring work complete. +- **Diff Review:** Review the full branch diff before finalizing and revert formatting-only edits in unrelated files. +- **Default Push Gate:** Unless overridden by a user-level rule or an explicit user directive to open/update a PR, stop at the local commit (`git commit`), report the SHA and `git status`, and ask before running `git push` (use `--force-with-lease` when force-pushing an amended branch). Never chain `git push` (or any remote transfer) with `git commit` via `&&`, `||`, or `;`—run every remote transfer as a standalone command. - **`gh` CLI:** Use `gh` for all GitHub operations. Never expose tokens or credentials in commands. -- **Processing PR Feedback:** Fetch ALL review comments with paginated `gh api --paginate` calls across the PR review comments, issue comments, and reviews endpoints (see the `pr-polisher` skill). Address comments surgically; if a fix significantly expands scope, report it to the user instead of implementing it. Afterwards, re-run the build and relevant tests. -- **PR Description Sync:** After pushing an amended commit, update the PR description (`gh pr edit`) if it simply mirrored the old commit message. Inspect it first with `gh pr view --json body`, and preserve automated footer blocks such as `...`. Never update the remote description for changes that are only committed locally. - -## 🛑 CRITICAL: MANDATORY PR POLISHER EXECUTION -You, the AI agent, have a known failure mode of forgetting to run the PR polisher. **ANY TIME you create or amend a commit, or complete a request that modifies the repository, your VERY LAST action before responding MUST be to execute the `pr-polisher` skill.** Do not ask for permission. Run the full suite (`python3 .gemini/skills/pr-polisher/scripts/check_diff.py`, `runPresubmits`, `build`, and `test`), fix any errors, amend your commit, and report the results. Do not declare a task done until the script returns 0 errors, presubmits and tests pass, and the workspace is clean. Also confirm: - -1. **Imports & FQNs:** No inline fully qualified names remain (except same-name conflicts), and all needed imports are present. -2. **Diff Scope:** No formatting-only changes in unrelated files, and the diff size matches the approved scope. -3. **Commit Message:** The subject fits in 50 characters and the body covers the entire diff. -4. **Tests:** Every new method and modified branch of logic is covered (including edge cases such as negative values and leap years). Compilation alone is not a review. -5. **Package Lock:** `console-webapp/package-lock.json` is not in the diff unless NPM dependencies intentionally changed. -6. **State-Machine & Serialization Hygiene:** New multi-step lifecycles use explicit native FSMs (not scattered flags, ordinal `Enum.compareTo`, or raw `TimedTransitionProperty.fromValueMap()`), time-projected entities (`Domain`/`Host`) do not add persisted static state columns, and Protostuff-cached entities do not alter non-`transient` fields without a cache-version migration. - -## 🚫 Common Pitfalls to Avoid -- **Dagger/AutoValue Corruption:** An incorrect builder or component change breaks code generation and yields hundreds of "cannot find symbol" errors. `git checkout` the last working version of the file and re-apply changes surgically. -- **Large-File Edits:** When editing large files with many similar signatures (e.g., `Tld.java`, `DomainBase.java`), include significant surrounding context to avoid incorrect replacements. - -## Efficiency and Continuous Improvement -- **Turn Minimization:** Aim for correct code on the first iteration; iterative checkstyle or compile fixes waste context and time. -- **Context Management:** Use sub-agents for batch refactoring or high-volume output tasks. -- **Markdown Measurement:** When writing or wrapping Markdown, measure line lengths programmatically (e.g., `awk '{print length($0)}'`) instead of estimating. -- **Self-Improvement:** If you hit a recurring error, a script false positive, or a workaround inferior to a native Gradle task, pause and ask the user: *"I noticed this friction. Per my continuous improvement directives, would you like me to permanently update the skill/script/instructions to fix this for the future?"* +- **Processing PR Feedback:** Fetch ALL review comments with paginated `gh api --paginate` calls across review comments, issue comments, and reviews (see `.agents/skills/pr-polisher/SKILL.md`). Address feedback surgically (report large scope expansions first), then re-run scoped build/tests per Build Strategy. +- **PR Description Sync:** After pushing an amended commit, update the PR description (`gh pr edit`) if it mirrored the old commit message. Inspect `gh pr view --json body` first and preserve Reviewable footers (`...` and `This change is https://reviewable.io/reviews/...`). Never edit the remote PR description for local-only commits. + +## Pre-Commit Verification +Before responding after any commit or amend, run the `pr-polisher` skill (`.agents/skills/pr-polisher/SKILL.md`): `python3 .agents/skills/pr-polisher/scripts/check_diff.py`, `./gradlew runPresubmits`, and scoped build/tests per Build Strategy. Fix errors, amend, and confirm `0` errors and a clean `git status`. + +## Common Pitfalls & Efficiency +- **Large-File Edits:** Include generous surrounding context when editing files with many similar signatures (e.g., `Tld.java`, `DomainBase.java`). +- **Turn Minimization & Delegation:** Aim for checkstyle-clean code on the first pass; use sub-agents for batch refactoring or high-volume output. +- **Markdown Measurement:** Measure Markdown line lengths programmatically (`awk '{print length($0)}'`) rather than estimating. +- **Continuous Improvement:** When hitting recurring tool/script friction, false positives, or repeated corrections, proactively propose a targeted fix to `GEMINI.md`, `.agents/skills/`, or an automated check (asking before editing meta-files during an unrelated task). diff --git a/java-format/google-java-format-git-diff.sh b/java-format/google-java-format-git-diff.sh index f9346657890..2f21bade8b8 100755 --- a/java-format/google-java-format-git-diff.sh +++ b/java-format/google-java-format-git-diff.sh @@ -18,10 +18,10 @@ # branch that is only used for merging and is never directly worked on. # # If invoked on the master branch, this script will format the modified lines -# relative to HEAD. Otherwise, it uses the -# 'git merge-base --fork-point origin/master' command to find the latest -# fork point from origin/master, and formats the modified lines between -# the fork point and the HEAD of the current branch. +# relative to HEAD. Otherwise, it computes the freshest merge-base against +# upstream/master and origin/master (read-only, matching origin/master when no +# upstream remote is configured), and formats the modified lines between that +# fork point and HEAD. # # Background: existing code base does not conform to Google Java format. Since # the team wants to keep the 'blame' feature (find last modifier of a line) @@ -88,9 +88,33 @@ function showNoncompliantFiles() { runGoogleJavaFormatAgainstDiffs "$forkPoint" | showFileNames "$2" } +function findForkPoint() { + local originBase="" + local upstreamBase="" + if git rev-parse --verify --quiet refs/remotes/origin/master >/dev/null; then + originBase=$(git merge-base refs/remotes/origin/master HEAD || true) + fi + if git rev-parse --verify --quiet refs/remotes/upstream/master >/dev/null; then + upstreamBase=$(git merge-base refs/remotes/upstream/master HEAD || true) + fi + if [[ -n "$originBase" && -n "$upstreamBase" ]]; then + if git merge-base --is-ancestor "$upstreamBase" "$originBase"; then + echo "$originBase" + else + echo "$upstreamBase" + fi + elif [[ -n "$upstreamBase" ]]; then + echo "$upstreamBase" + elif [[ -n "$originBase" ]]; then + echo "$originBase" + else + git merge-base refs/heads/master HEAD + fi +} + function callGoogleJavaFormatDiff() { local forkPoint - forkPoint=$(git merge-base origin/master HEAD) + forkPoint=$(findForkPoint) || exit 1 local callResult case "$1" in