diff --git a/.gemini/skills/java-ast-refactoring/SKILL.md b/.gemini/skills/java-ast-refactoring/SKILL.md index ba4d7d554c3..0a3fbf24e05 100644 --- a/.gemini/skills/java-ast-refactoring/SKILL.md +++ b/.gemini/skills/java-ast-refactoring/SKILL.md @@ -1,6 +1,6 @@ --- name: java-ast-refactoring -description: "AST-aware Java refactoring using OpenRewrite. Use when asked to structurally refactor Java code, change class names, change method signatures/overloads, replace builder patterns, modify annotations, or perform cross-file structural replacements. Note: Renaming fields or local variables/parameters is not supported natively via simple YAML recipes in the standard openrewrite modules." +description: "AST-aware Java refactoring using OpenRewrite. Use when asked to structurally refactor Java code, change class names, change method signatures/overloads, replace builder patterns, modify annotations, or perform cross-file structural replacements. Note: Renaming fields or local variables/parameters is not supported natively via simple YAML recipes in the standard openrewrite modules. Don't use for: formatting-only fixes (use spotlessApply / javaIncrementalFormatApply), non-Java files, or single-line edits that a direct file edit handles safely." --- # AST-Aware Java Refactoring @@ -17,13 +17,34 @@ python3 .gemini/skills/java-ast-refactoring/scripts/safe_rename.py ` (or `git stash`), refine the recipe, and re-run rather than hand-patching the output. ## 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;`). diff --git a/.gemini/skills/java-ast-refactoring/references/rewrite_recipes.md b/.gemini/skills/java-ast-refactoring/references/rewrite_recipes.md index b18349c758b..976399e11e8 100644 --- a/.gemini/skills/java-ast-refactoring/references/rewrite_recipes.md +++ b/.gemini/skills/java-ast-refactoring/references/rewrite_recipes.md @@ -60,11 +60,15 @@ Updates the class name and automatically updates all imports across the codebase ``` ### 7. Change Method Arguments -Reorders or removes arguments based on a target signature. `newArgumentTemplate` uses 0-based indexing. +Removes or reorders arguments at every call site matching `methodPattern`. `argumentIndex` is 0-based. `oldParameterNames` lists the current parameter names in declaration order and `newParameterNames` lists them in the desired order. These recipes rewrite invocations only; update the method declaration itself separately. ```yaml - - org.openrewrite.java.ChangeMethodAccessLevel: - methodPattern: com.google.common.collect.ImmutableList of(..) - newAccessLevel: protected + - org.openrewrite.java.DeleteMethodArgument: + methodPattern: google.registry.util.Foo bar(java.lang.String, int) + argumentIndex: 1 + - org.openrewrite.java.ReorderMethodArguments: + methodPattern: google.registry.util.Foo baz(java.lang.String, int) + oldParameterNames: [name, count] + newParameterNames: [count, name] ``` ### 8. Add Import diff --git a/.gemini/skills/java-ast-refactoring/scripts/run_rewrite.sh b/.gemini/skills/java-ast-refactoring/scripts/run_rewrite.sh index 236626aa9b1..3042c3d98d0 100755 --- a/.gemini/skills/java-ast-refactoring/scripts/run_rewrite.sh +++ b/.gemini/skills/java-ast-refactoring/scripts/run_rewrite.sh @@ -66,8 +66,14 @@ allprojects { } EOF -# Copy the recipe file to the workspace root temporarily so OpenRewrite finds it -cp "$RECIPE_FILE" ./rewrite.yml +# OpenRewrite reads ./rewrite.yml from the workspace root. Copy the recipe there +# temporarily unless it already is that file (copying a file onto itself fails, +# and deleting it afterwards would destroy the user's recipe). +COPIED_RECIPE=false +if [[ "$RECIPE_FILE" != "$(realpath -m ./rewrite.yml)" ]]; then + cp "$RECIPE_FILE" ./rewrite.yml + COPIED_RECIPE=true +fi echo "Executing OpenRewrite recipe: $RECIPE_NAME" ./gradlew --init-script "$INIT_SCRIPT" rewriteRun --no-parallel --no-configuration-cache @@ -77,4 +83,6 @@ echo "Running code formatters to fix Checkstyle line-length and import ordering. # Clean up temporary files rm "$INIT_SCRIPT" -rm ./rewrite.yml +if [[ "$COPIED_RECIPE" == true ]]; then + rm ./rewrite.yml +fi diff --git a/.gemini/skills/pr-polisher/SKILL.md b/.gemini/skills/pr-polisher/SKILL.md index 0e541b054a1..1ff637c9244 100644 --- a/.gemini/skills/pr-polisher/SKILL.md +++ b/.gemini/skills/pr-polisher/SKILL.md @@ -1,6 +1,6 @@ --- 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. +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. --- # PR Polisher @@ -22,10 +22,10 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p ## Workflow Execution Steps 1. **Run the Automated Analysis Script** - Execute the packaged Python diff-checker script. This script automatically checks commit messages, working tree status, `package-lock.json` modifications, copyright years on new files, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching). + 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), internal-only links or paths leaking into this public repository, local `upstream/master` freshness, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching). ```bash - python3 ./pr-polisher/scripts/check_diff.py + python3 .gemini/skills/pr-polisher/scripts/check_diff.py ``` 2. **Run Formatting Validation** @@ -61,11 +61,27 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p Re-read your commit message (`git log -1 --pretty=format:%B`). Compare it directly against the actual diff (`git diff HEAD^`) to verify that it completely and accurately describes ONLY the changes present in the commit. * If the scope of the PR changed during prompting, you MUST update the commit message to reflect the final state of the code. * Ensure that the primary purpose of the PR is mentioned first, and that no irrelevant or outdated changes from previous attempts are listed. + * **Commit-message / PR-body parity:** The commit body and the GitHub PR description must BOTH contain the operational justification (why the change is needed) and, for new or changed commands, concrete CLI usage examples. Never leave this context in only one of the two. -7. **Address Errors, Amend, and Re-Run (Iterative Checking)** +7. **Verify `@Action` Reachability** + If the diff adds or modifies a class annotated with `@Action`, confirm it is actually reachable in production: + * It is wired into `core/src/main/java/google/registry/module/RequestComponent.java`. + * Its path appears in `core/src/test/resources/google/registry/module/routing.txt` (update this golden file using the instructions printed by a failing `RequestComponentTest`). + * Scheduled actions have a matching entry in the relevant `core/src/main/java/google/registry/config/files/tasks/cloud-scheduler-tasks-*.xml` files. + +8. **Read ALL Existing PR Review Comments (Paginated)** + When an open PR exists, never rely on a single unpaginated `gh api` or `gh pr view` call, which silently truncates and hides inline comments. Fetch all three endpoints with pagination: + ```bash + gh api --paginate repos/google/nomulus/pulls//comments --jq '.[] | {path, line, user: .user.login, body}' + gh api --paginate repos/google/nomulus/issues//comments --jq '.[] | {user: .user.login, body}' + gh api --paginate repos/google/nomulus/pulls//reviews --jq '.[] | {user: .user.login, state, body}' + ``` + Confirm every comment is addressed (or explicitly replied to) before declaring the PR polished. + +9. **Address Errors, Amend, and Re-Run (Iterative Checking)** If any script throws an error, if scope was reduced, if the commit message was inaccurate, or if formatting changes were applied, you must stage those fixes and amend your commit: ```bash 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 ./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. \ No newline at end of file + **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. \ No newline at end of file diff --git a/.gemini/skills/pr-polisher/scripts/check_diff.py b/.gemini/skills/pr-polisher/scripts/check_diff.py index 96cca49aea2..84896a43a76 100644 --- a/.gemini/skills/pr-polisher/scripts/check_diff.py +++ b/.gemini/skills/pr-polisher/scripts/check_diff.py @@ -18,6 +18,7 @@ import sys import datetime import os +import time # Color codes RED = "\033[91m" @@ -28,6 +29,27 @@ errors_found = 0 warnings_found = 0 +SCRIPT_PATH = ".gemini/skills/pr-polisher/scripts/check_diff.py" + +# Modules whose src/main Java changes should be accompanied by test changes. +TESTED_MODULES = ( + "common", "core", "db", "networking", "prober", "proxy", "release", "util") + +FLYWAY_SCRIPT_PATTERN = re.compile(r'^db/src/main/resources/sql/flyway/V[^/]*\.sql$') +JPA_ENTITY_PATTERN = re.compile(r'^\s*@(Entity|Embeddable|MappedSuperclass)\b', re.MULTILINE) + +# Internal-only references that must never land in this public repository. +# Buganizer references (b/123, http://b/123) are allowed and do not match. +INTERNAL_LEAK_PATTERNS = ( + (re.compile(r'corp\.google\.com'), "internal corp hostname"), + (re.compile(r'/google/src/'), "internal source path"), + (re.compile(r'//depot/google3'), "internal depot path"), + (re.compile(r'(?:\bhttps?://|(? UPSTREAM_MAX_AGE_HOURS: + log_warning( + f"Local upstream/master tip is {age_hours:.0f}h old. Run 'git fetch upstream master'" + " and rebase so the diff is not computed against a stale base.") + else: + log_success("Local upstream/master is fresh.") + def check_formatting(): print("\n--- Checking Project Formatting ---") try: @@ -309,19 +357,71 @@ def check_diff_anti_patterns(): if 'src/test/' in current_file and clock_now_pattern.search(code_line): log_warning(f"[{current_file}] Prefer using a fixed, static constant Instant over capturing clock.now() in tests to prevent flakiness.") +def check_internal_link_leaks(): + print("\n--- Checking for Internal Link and Path Leaks ---") + diff = run_cmd("git diff HEAD^ -U0") + current_file = "" + leaks_found = False + + for line in diff.split('\n'): + if line.startswith('+++ '): + current_file = line[6:] if line.startswith('+++ b/') else "" + continue + if not line.startswith('+') or not current_file: + continue + code_line = line[1:] + # Skip this script's own pattern definitions. + if current_file == SCRIPT_PATH and 're.compile(' in code_line: + continue + for pattern, description in INTERNAL_LEAK_PATTERNS: + if pattern.search(code_line): + leaks_found = True + log_error( + f"[{current_file}] Found {description} in an added line. This repository" + f" is public; remove internal references: {code_line.strip()}") + + if not leaks_found: + log_success("No internal links or paths found in added lines.") + +def is_jpa_entity(path): + if not path.endswith('.java') or '/src/main/' not in path: + return False + try: + with open(path, 'r') as file: + return bool(JPA_ENTITY_PATTERN.search(file.read())) + except FileNotFoundError: + # Deleted files cannot be inspected. + return False + +def check_db_schema_split(): + print("\n--- Checking Database Schema Changes ---") + diff_files = get_diff_files() + flyway_files = [f for f in diff_files if FLYWAY_SCRIPT_PATTERN.match(f)] + orm_files = [ + f for f in diff_files if f.endswith('.java') or f.endswith('db-schema.sql.generated')] + entity_files = [f for f in diff_files if is_jpa_entity(f)] + + if flyway_files and orm_files: + log_error( + "Flyway scripts and Java/db-schema.sql.generated changes must be split into two" + " PRs (schema first, then ORM after deployment). See db/README.md." + f" Flyway: {flyway_files}; Java/generated: {orm_files}") + if flyway_files or entity_files: + log_warning( + "Flyway scripts or JPA entities changed. Run './gradlew :db:test' and" + " './gradlew :core:sqlIntegrationTest' in addition to the standard tests.") + else: + log_success("No database schema or JPA entity changes found.") + def check_missing_tests(): print("\n--- Checking for Missing Tests ---") - diff_files = run_cmd("git diff HEAD^ --name-only").split('\n') - main_files_modified = False - test_files_modified = False - - for f in diff_files: - if f.startswith('core/src/main/') or f.startswith('util/src/main/'): - if f.endswith('.java'): - main_files_modified = True - if f.startswith('core/src/test/') or f.startswith('util/src/test/'): - if f.endswith('Test.java'): - test_files_modified = True + diff_files = get_diff_files() + main_prefixes = tuple(f"{m}/src/main/" for m in TESTED_MODULES) + test_prefixes = tuple(f"{m}/src/test/" for m in TESTED_MODULES) + main_files_modified = any( + f.startswith(main_prefixes) and f.endswith('.java') for f in diff_files) + test_files_modified = any( + f.startswith(test_prefixes) and f.endswith('Test.java') for f in diff_files) if main_files_modified and not test_files_modified: log_warning("Production code (.java files in src/main/) was modified, but no corresponding tests (.java files in src/test/) were added or updated. You MUST proactively write tests for any new logic or bug fixes.") @@ -337,10 +437,13 @@ def main(): check_commit_message() check_license_headers() check_missing_tests() + check_db_schema_split() + check_upstream_freshness() check_formatting() check_package_lock() check_workspace_clean() check_diff_anti_patterns() + check_internal_link_leaks() print("\n========================================") if errors_found == 0 and warnings_found == 0: diff --git a/GEMINI.md b/GEMINI.md index 5d82f91a166..4c0a3b243a0 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -1,189 +1,120 @@ -# Engineering Standards for Gemini CLI +# Nomulus Engineering Guide for Gemini -This document outlines foundational mandates, architectural patterns, and project-specific conventions to ensure high-quality, idiomatic, and consistent code from the first iteration. When modifying this file, always review the full document to prevent the introduction of duplicate instructions and ensure the content remains coherent and logically organized. +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. + +## 🏛 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`). ## Core Mandates -### 1. Rigorous Import Management -- **Addition:** When adding new symbols, ensure the corresponding import is added. -- **Removal:** When removing the last usage of a class or symbol from a file (e.g., removing a `@Inject Clock clock;` field), **immediately remove the associated import**. Do not wait for a build failure to identify unused imports. -- **No Redundant Qualifications:** NEVER use fully qualified class names (e.g., `java.time.temporal.ChronoUnit.DAYS`) in code when an import can be used instead. Always prefer adding an import and using the simple name. -- **Static Imports for Utilities:** Always statically import methods from utility classes like `DateTimeUtils` or `CacheUtils`. (e.g., use `toInstant(...)` instead of `DateTimeUtils.toInstant(...)`). -- **Checkstyle:** Proactively fix common checkstyle errors (line length > 100, formatting, unused imports) during the initial code write. Do not wait for CI/build failures to address these, as iterative fixes are inefficient. -- **Verification**: Before finalizing any change, scan the imports section for redundancy. -- **License Headers**: When creating new files, ensure the license header uses the current year (e.g., 2026). Existing files should retain their original year. - -## 2. Time and Precision Handling - -- **UTC Timezones:** Do not use `ZoneId.of("UTC")`. Use a statically imported `UTC` from `ZoneOffset` instead (`import static java.time.ZoneOffset.UTC;`). -- **Clock Injection:** - - Avoid direct calls to `Instant.now()`, `OffsetDateTime.now()`, or `System.currentTimeMillis()`. - - Inject `google.registry.util.Clock` (production) or `google.registry.testing.FakeClock` (tests). - - Use `clock.nowDate()` to get a `LocalDate` in UTC, or `clock.nowDateTime()` to get an `OffsetDateTime` in UTC. - - When defining timestamps for tests, prefer using a fixed, static constant (e.g., `Instant.parse("2024-03-27T10:15:30.105Z")`) over capturing `clock.now()` to prevent flaky tests caused by the passage of real time. -- **Beam Pipelines:** - - Ensure `Clock` is serializable (it is by default in this project) when used in Beam `DoFn`s. - - Pass the `Clock` through the constructor or via Dagger provider methods in the pipeline module. -- **Command-Line Tools:** - - Use `@Inject Clock clock;` in `Command` implementations. - - The `clock` field should be **package-private** (no access modifier) to allow manual initialization in corresponding test classes. - - In test classes (e.g., `UpdateDomainCommandTest`), manually set `command.clock = fakeClock;` in the `@BeforeEach` method. - - Base test classes like `EppToolCommandTestCase` should handle this assignment for their generic command types where applicable. +### 1. Imports and Formatting +- **Addition / Removal:** Add the import for every new symbol. When removing the last usage of a symbol (e.g., an `@Inject Clock clock;` field), **immediately remove its import**. +- **No Redundant Qualifications:** NEVER use fully qualified class names (e.g., `java.time.temporal.ChronoUnit.DAYS`) when an import can be used. *Exception:* if the file already imports a class with the same simple name (e.g., `java.util.Date` and `java.sql.Date`), one must remain fully qualified. +- **Static Imports for Utilities:** Statically import methods from utility classes like `DateTimeUtils` or `CacheUtils` (e.g., `toInstant(...)`, not `DateTimeUtils.toInstant(...)`). +- **Checkstyle:** Proactively avoid common checkstyle errors (line length > 100, formatting, unused imports) when first writing code. +- **Formatting Tools:** Never hand-roll scripts or regexes to fix formatting. Run `./gradlew spotlessApply` (imports) and `./gradlew javaIncrementalFormatApply` (or `google-java-format --replace `) for Java formatting. +- **License Headers:** New files use the current year (e.g., 2026). Existing files retain their original year. + +### 2. Time and Precision +- **UTC:** Never use `ZoneId.of("UTC")`; use statically imported `ZoneOffset.UTC`. +- **Clock Injection:** Avoid `Instant.now()`, `OffsetDateTime.now()`, and `System.currentTimeMillis()`. Inject `google.registry.util.Clock` (production) or `google.registry.testing.FakeClock` (tests). Use `clock.nowDate()` for a UTC `LocalDate` and `clock.nowDateTime()` for a UTC `OffsetDateTime`. +- **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. ### 3. Dependency Injection (Dagger) -- **Concrete Types:** Dagger `inject` methods must use explicit concrete types. Generic `inject(Command)` methods will not work. -- **Test Components:** Use `TestRegistryToolComponent` for command-line tool tests to bridge the gap between `main` and `nonprod/test` source sets. +- **Concrete Types:** Dagger `inject` methods must use explicit concrete types; generic `inject(Command)` methods do not work. +- **Test Components:** Use `TestRegistryToolComponent` for command-line tool tests to bridge `main` and `nonprod/test` source sets. ### 4. Database Consistency -- **Transaction Management:** - - **Top-Level:** Define database transactions (`tm().transact(...)`) at the highest possible level in the call chain (e.g., in an Action, a Command, or a Flow). This ensures all operations are atomic and handled by the retry logic. - - **DAO Methods:** Avoid declaring transactions inside low-level DAO methods. Use `tm().assertInTransaction()` to ensure that these methods are only called within a valid transactional context. - - **Utility/Cache Methods:** Use `tm().reTransact(...)` for utility methods or Caffeine cache loaders that might be invoked from both transactional and non-transactional paths. - - `reTransact` will join an existing transaction if one is present (acting as a no-op) or start a new one if not. - - This is particularly useful for in-memory caches where the loader must be able to fetch data regardless of whether the caller is currently in a transaction. - - **Test Helpers & Timestamps:** If a static test helper method (like in `DatabaseHelper`) needs the database transaction time but might be called from outside a transaction, using `tm().reTransact(tm()::getTxTime)` is acceptable. However, NEVER wrap it redundantly like `tm().transact(() -> tm().reTransact(tm()::getTxTime))`. If you are just setting an arbitrary timestamp in a test where the exact DB transaction time isn't strictly required, prefer `Instant.now()` or `clock.now()` to avoid creating unnecessary database transactions. - - **Production Code:** In production code, if a flow fails because it is calling `getTxTime()` outside of a transaction, you must wrap the *caller* in a transaction instead of adding an unnecessary `reTransact()` around `getTxTime()`. - - **Transactional Time:** Ensure code that relies on `tm().getTransactionTime()` (or `tm().getTxTime()`) is executed within a transaction context. -- **Database Schema Migrations & 2-PR Split Mandate:** - - **Mandatory Consultation of `db/README.md`:** Before planning, drafting, or executing any database schema modifications (e.g., adding/altering columns, creating Flyway `.sql` migration scripts, or modifying JPA entity `@Column` mappings), you **MUST read and strictly adhere to `db/README.md`**. - - **Strict 2-PR Deployment Split:** Never propose or submit combining Flyway SQL scripts (`db/src/main/resources/sql/flyway/V*.sql`) and Java ORM changes (`.java` entity files + `db-schema.sql.generated`) into a single PR for submission to `master`. Because live servers during a rolling deployment will fail if Java code attempts to access unmigrated database columns/constraints, all schema additions must be split into two sequential PRs per `db/README.md`: - 1. **PR #1 (Database Schema Only):** Contains *only* the new Flyway `.sql` script, the `flyway.txt` index update (`:db:generateFlywayIndex`), the `nomulus.golden.sql` dump (`:nom:generate_golden_file`), and ER diagrams (`er_diagram/`). Must contain **zero `.java` files or `db-schema.sql.generated` changes**. - 2. **PR #2 (Java ORM, EPP Flows & Generated Schema Map):** Submitted *only after* PR #1 is deployed to production. Contains all `.java` entity/flow modifications, tests, and the regenerated `db-schema.sql.generated` (`generateSqlSchema`). - -### 5. Testing Best Practices -- **Mandatory Proactive Testing:** You MUST automatically write and update tests alongside your code changes WITHOUT waiting for the user to prompt you. If you add a new feature, fix a bug, or change core logic, you are explicitly required to identify the corresponding `*Test.java` file and implement comprehensive test coverage for your changes. -- **FakeClock and Sleeper:** Use `FakeClock` and `Sleeper` for any logic involving timeouts, delays, or expiration. -- **Empirical Reproduction:** Before fixing a bug, always create a test case that reproduces the failure. -- **Base Classes:** Leverage `CommandTestCase`, `EppToolCommandTestCase`, etc., to reduce boilerplate and ensure consistent setup (e.g., clock initialization). -- **Gradle Test Patterns:** When running tests to investigate fixes in the "core" directory, try to first use the "standardTest" Gradle task (e.g., `./gradlew :core:standardTest -x :console-webapp:buildConsoleWebapp`). It is faster than the "test" task, which includes the "fragileTest" task. Only run the full "test" task after "standardTest" succeeds. Always pass `-x :console-webapp:buildConsoleWebapp` on backend-only `:core` test and build tasks so `:core:processResources` does not trigger `:console-webapp:npmInstallDeps` and `:console-webapp:buildConsoleWebapp` (which dirties `console-webapp/package-lock.json` and can fail on host Node.js version mismatches). -- **Mandatory SQL Integration Verification:** Whenever you modify any database schema, Flyway script (`.sql`), or JPA entity class, you MUST explicitly run both `./gradlew :db:test` and `./gradlew :core:sqlIntegrationTest` **in addition to** the standard test suites (`./gradlew standardTest` or `./gradlew test`) before finalizing the task or declaring completion. Do not rely solely on `standardTest` when database schemas or ORM mappings are touched; all three test suites (`standardTest`, `:db:test`, and `:core:sqlIntegrationTest`) are mandatory. - -### 6. Project Dependencies -- **Common Module:** When using `Clock` or other core utilities in a new or separate module (like `load-testing`), ensure `implementation project(':common')` is added to the module's `build.gradle`. -- **Updating Dependencies:** When updating third-party dependencies, you MUST follow this exact, non-negotiable sequence. NEVER run the update script without first verifying the lockfiles locally. +- **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()`. +- **`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.** + 2. **PR #2 (ORM):** after PR #1 is deployed to production: entity/flow changes, tests, and the regenerated `db-schema.sql.generated` (`generateSqlSchema`). + +### 5. Java, Guava, and Nomulus Idioms +- **Compiler Warnings are Errors (`-Werror`):** `@SuppressWarnings` is not repeatable; merge suppressions: `@SuppressWarnings({"unchecked", "MustBeClosedChecker"})`. +- **Immutable Types:** Declare fields, variables, and return types as Guava immutable types (`ImmutableList`, `ImmutableMap`) and collect with `toImmutableList()` / `toImmutableMap()` rather than accumulating into `ArrayList` / `HashMap`. +- **Null Safety:** Prefer `Optional` for possibly-absent values; otherwise annotate with `javax.annotation.Nullable` (never another `Nullable`). +- **Fail Fast:** Validate inputs at the highest level (`Preconditions.checkArgument`) instead of passing invalid state deeper. +- **Exceptions:** Catch specific exceptions, never generic `Exception`/`Throwable` when a narrower type is expected. Never log and re-throw. In batch jobs, catch per item/chunk so one failure does not abort the batch. +- **Constructors:** No heavy logic, I/O, or external calls in constructors; use factory methods or startup routines. +- **Magic Numbers:** Document hardcoded limits with an inline comment explaining the rationale. +- **No Unnecessary Casts:** e.g., avoid `(Instant) fakeClock.now()` if it compiles without the cast. +- **Visibility:** Never write `/* package */`; leave the modifier blank for package-private. +- **Model Layering:** Do not add new `google.registry.model` -> `google.registry.flows` dependencies. Put shared helpers in `google.registry.util` (e.g., `DomainNameUtils`). +- **Nullable `ImmutableObject` Sets:** Back nullable `Set` fields with a getter returning `ImmutableSortedSet` (e.g., `nullToEmptyImmutableSortedCopy`) and annotate the field with `@GetterDelegate` so `toString`, diffs, and `ModelUtils.getFieldValues()` use the getter. +- **Partial JSON Updates:** With Gson-deserialized partial updates, an omitted field is `null` and must preserve the stored value, while an explicit `[]` clears it. Validate list contents fail-closed (trim entries, reject `null` elements, enforce formats and size limits). +- **JAXB Optional Attributes:** Optional XML attributes with a default (e.g., fee `standard` / `refundable`, driven by `FeeType`) are `Boolean` fields left `null` when equal to the default so JAXB omits them. +- **Allocation Tokens:** Check single-use semantics with `tokenType.isOneTimeUse()`, not comparisons against specific `TokenType` values. +- **Console Actions:** Derive EPP superuser execution from the action type after the permission check, never from `user.getUserRoles().isAdmin()`. Prefix `ConsoleUpdateHistory` descriptions with the registrar ID and `ConsoleUpdateHistory.DESCRIPTION_SEPARATOR` so registrar history queries find them. +- **CSV Output:** Build formats with `CSVFormat.DEFAULT.builder().setRecordSeparator('\n').get()` (`build()` is deprecated and the default separator is `\r\n`). +- **Kubernetes JVM Flags:** When changing `JDK_JAVA_OPTIONS`, update every container in every manifest under `jetty/kubernetes/` and `proxy/kubernetes/` (some deployments have multiple containers) so all pods and rollbacks stay in parity. +- **Node Version:** Keep the `node` block in the root `build.gradle` and the Node install in `release/builder/build.sh` on the same version. + +## Testing +- **Mandatory Proactive Testing:** Write and update tests alongside every code change without being asked. New features, bug fixes, and logic changes require coverage in the corresponding `*Test.java` (including edge cases). +- **Empirical Reproduction:** Before fixing a bug, write a test that reproduces it. +- **FakeClock and Sleeper:** Use them for any timeout, delay, or expiration logic; never `Thread.sleep()`. +- **Base Classes:** Leverage `CommandTestCase`, `EppToolCommandTestCase`, etc., for consistent setup. +- **Truth:** Prefer `.hasValue(...)` over `.isEqualTo(Optional.of(...))`. +- **JVM Reuse:** `:core:standardTest` reuses JVMs across test classes, so static state and `System.setProperty` values leak between tests. Give static singletons a `resetForTesting()` hook, publish shared state through a single `volatile` field, and validate inputs before mutating global properties. +- **Gradle Test Tasks:** In `core`, run `./gradlew :core:standardTest -x :console-webapp:buildConsoleWebapp` first (faster than `test`, which adds `fragileTest`); run the full `test` task only after it passes. +- **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. + +## Project Dependencies +- **Common Module:** Modules using `Clock` or other core utilities (e.g., `load-testing`) need `implementation project(':common')` in their `build.gradle`. +- **Updating Dependencies:** Follow this sequence exactly: 1. Modify `dependencies.gradle`. - 2. Run `./gradlew dependencies --write-locks --update-locks '*:*'` to regenerate all Gradle lockfiles locally to resolve new versions. - 3. Run `./gradlew clean build` to exhaustively compile and run all tests against the new transitive dependency tree. If there are compilation or test errors due to breaking API changes or output formatting changes in the new dependency version, your primary goal is to **fix our codebase** to be compliant with the new dependency version. Only revert the dependency bump or cap the version if the required code changes are prohibitively complex or outside the scope of the current task. - 4. Only once the build passes and `git status` shows modified lockfiles, commit the `dependencies.gradle` and lockfile changes. - 5. ONLY after the local changes are committed and verified, execute the internal script `/google/src/head/depot/google3/domain/registry/tools/update_dependency.sh`. This ensures you don't corrupt the upstream remote artifact cache with broken or missing lockfiles. - 6. **Crucial Final Verification:** The `update_dependency.sh` script runs its own internal Blaze resolution and often modifies or drops additional `buildscript-gradle.lockfile` files. After the script finishes successfully, run `git status`. If there are any untracked or modified `*.lockfile` files, stage them and run `git commit --amend --no-edit` to ensure your commit perfectly reflects the final state deployed to the SSO repository. - -### 7. Search and Discovery -- **No CodeSearch:** This project is hosted on GitHub, not Google3. Do NOT use `mcp_Coding_search_for_files_codesearch` or other internal Google3 search tools. -- **Local Grep:** Use local shell commands like `git grep` or `grep` via `run_shell_command` to search the codebase. - -### 8. Git Operation Boundaries & Remote Push Prohibition -- **Zero-Bundling Rule for Remote Transfers:** NEVER bundle remote transfer commands (`git push`, `repo upload`, `g4 upload`, `g4 mail`, `hg push`, `jj git push`) inside compound bash pipelines (`&&`, `||`, `;`) with local staging or commit commands (e.g., `git commit --amend && git push ...`). Every remote transfer command MUST be executed as a standalone, single-command `run_command` invocation. -- **Mandatory Two-Step Handover Protocol:** When working on pull requests, changelists, or branches, strictly halt right at the local repository boundary (`git commit` / `g4 change`). Report the local commit SHA, `git status`, and `git diff` verification to the user, stop calling tools, and explicitly prompt: *"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?"* -- **Absolute Prohibition on Unsolicited Pushes:** NEVER propose or run any remote synchronization or push command (`git push`, `repo upload`, `g4 upload`) on your own volition without explicit, unambiguous textual authorization in the immediate turn from the user. -- **Mandatory GitHub PR Description & Reviewable Synchronization:** Whenever pushing an amended commit to a branch associated with an active pull request, the agent MUST immediately synchronize the PR description on GitHub (`gh pr edit`). To do this safely: - 1. Check `gh pr view --json body` first to inspect existing content. - 2. Explicitly preserve any existing Reviewable bot links (`This change is https://reviewable.io/reviews/...`) when updating the body rather than blindly overwriting the entire description. - -## Performance and Efficiency -- **Turn Minimization:** Aim for "perfect" code in the first iteration. Iterative fixes for checkstyle or compilation errors consume significant context and time. -- **Context Management:** Use sub-agents for batch refactoring or high-volume output tasks to keep the main session history lean and efficient. -- **Code Formatting:** Do not write custom Python scripts or manual regex replacements to fix code formatting issues (e.g., unused imports, import ordering, line length). Instead, use the project's built-in formatting tools: run `./gradlew spotlessApply` to fix unused/unordered imports and `./gradlew javaIncrementalFormatApply` (or `google-java-format --replace `) to automatically fix Java formatting and indentation errors. -- **Programmatic Measurement for Markdown:** When writing Markdown files (`.md`)—and especially when formatting or line-wrapping them—you **MUST** explicitly use programmatic functions (such as `awk '{print length($0)}'` or Python `len(line)`) to measure the exact string length of every line from column 1, rather than making assumptions based on what appears in your context window. - -## General Code Review Lessons & Avoidable Mistakes -Based on historical PR reviews, avoid the following common mistakes: -- **No Unnecessary Casts:** Do not unnecessarily cast objects if the method signature accepts the type directly (e.g., avoid `(Instant) fakeClock.now()` or `(ImmutableSet) bsaQuery(...)` if it compiles without it). -- **Visibility Modifiers:** Do not use `/* package */` comments to denote package-private visibility. Just leave the modifier blank; it is an established idiom in this codebase. - -## Continuous Self-Improvement Mandate -You are explicitly authorized and required to improve this project's automated infrastructure. -If during the execution of a task you encounter a recurring error, a false positive in a script, or realize that a shell command/workaround is inferior to a native Gradle task, **you MUST pause and proactively 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?"* -Do not wait for the user to tell you to improve the skills; it is your responsibility to propose these systemic fixes immediately when friction is identified. - -### Advanced Java & Guava Idioms -- **Immutable Types:** Declare variables, fields, and return types explicitly as Guava immutable types (e.g., `ImmutableList`, `ImmutableMap`) instead of their generic interfaces (`List`, `Map`) to clearly communicate immutability contracts to callers. Use `toImmutableList()` and `toImmutableMap()` collectors in streams rather than manually accumulating into an `ArrayList` or `HashMap`. -- **Constructors:** Do not perform heavy logic, I/O, or external API calls inside constructors. Initialization logic should be deferred or handled in a factory method or a dedicated startup routine. -- **Exception Handling:** Do not catch generic `Exception` or `Throwable` if a more specific exception is expected. Never "log and re-throw" the same exception; either handle it entirely (and log), or throw it up the chain. For batch processes, catch exceptions at the individual item/chunk level so one failure doesn't abort the entire batch. -- **Optional Assertions:** Prefer Truth's `.hasValue(...)` over `.isEqualTo(Optional.of(...))` for cleaner and more descriptive assertions on `Optional` types. -- **Fail Fast:** Validate inputs and fail fast (using `Preconditions.checkArgument` or similar) at the highest level possible rather than passing invalid state (like `null`s) deeper into business logic. -- **Magic Numbers:** Always document magic numbers or hardcoded limits (like `50.0` or `30`) with inline comments explaining the rationale. -- **Null Safety and Optional:** Prefer using `Optional` for any variable that is expected to potentially be null. For any other variable that can be null but cannot use an `Optional` (e.g., function parameters or return types where `Optional` is not idiomatic), it MUST be annotated with `@Nullable`. Always use the `javax.annotation.Nullable` annotation. - ---- - -# Gemini Engineering Guide: Nomulus Codebase - -This document captures high-level architectural patterns, lessons learned from large-scale refactorings, and specific instructions to avoid common pitfalls in this environment. - -## 🏛 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. If you see "cannot find symbol" errors for classes starting with `Dagger...`, the project is in a state where 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). - -## Source Control -- **No Unprompted Pushing:** You MUST NEVER push your changes to a remote repository (e.g., `git push origin ...`) unless the user VERY EXPLICITLY instructs you to do so. If you have finished a task, simply state that it is committed locally and ready for review. Do not assume pushing is desired. -- **Committing:** Always create a new commit on the branch if one hasn't been created yet for the branch's specific work. Only perform amending (`git commit --amend --no-edit`) for subsequent changes once the initial commit has been successfully created. -- **One Commit Per PR:** All changes for a single PR must be squashed into a single commit before merging. -- **Default to Amend:** Once an initial commit is created for a PR, all subsequent functional changes should be amended into that same commit by default (`git commit --amend --no-edit`). This ensures the PR remains a single, clean unit of work throughout the development lifecycle. -- **Commit Message Style:** Follow standard Git commit best practices. The subject line (first line) MUST be a maximum of 50 characters, concise, capitalized, and **must not end with punctuation** (e.g., a period). The body MUST explicitly encapsulate and summarize all changes made across the entire diff, detailing the "what" and "why" comprehensively. -- **Strict Completion Verification:** You MUST NEVER declare a task, commit, or amendment as complete until you have explicitly verified that the workspace is clean. You MUST follow this exact sequence of actions across multiple conversational turns if necessary: - 1. Execute the `git commit` or `git commit --amend` command. - 2. Wait for the tool to return successfully. - 3. Execute `git status`. - 4. Wait for the tool to return and explicitly verify the output contains `nothing to commit, working tree clean` (or similar indication that no unstaged changes remain). If changes remain, stage them and amend the commit, then repeat this verification loop. - 5. **Only after** step 4 has successfully returned a clean working directory may you generate a text response to the user declaring that the task is complete. -- **Diff Review:** Before finalizing a task, review the full diff (e.g., `git diff HEAD^`) to ensure all changes are functional and relevant. Identify and revert any formatting-only changes in files that do not contain functional updates to keep the commit focused. + 2. Run `./gradlew dependencies --write-locks --update-locks '*:*'` to regenerate all Gradle lockfiles. + 3. Run `./gradlew clean build` against the new dependency tree. If APIs or output formats changed, **fix our codebase** to comply; only revert or cap the version if the required changes are prohibitively complex or out of scope. + 4. Commit `dependencies.gradle` and every modified lockfile. Run `git status` and confirm no modified or untracked `*.lockfile` (including `buildscript-gradle.lockfile`) remains. + +## Search and Discovery +- This project is hosted on GitHub. Search it with local tools such as `git grep` or `grep`, not monorepo code search tools. + +## 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. +- **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?"* +- **`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 after making changes because you focus too narrowly on the immediate task. To prevent this, you are bound by the following absolute rule: - -**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 execute the `pr-polisher` skill.** -Do not ask for permission. Do not wait for the user to remind you. 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 final polished results in your response. - -You MUST NOT declare a task done until this automated script returns 0 errors, the presubmits and tests pass, and the workspace is fully clean. - -1. **Imports & FQNs:** Did I leave any fully-qualified class names or static variables inline? Did I add the necessary imports for them? *Crucial Exception:* If the file already imports a class with the identical name (e.g., it uses both `java.util.Date` and `java.sql.Date`), one MUST remain fully qualified to avoid a compilation conflict. -2. **Diff Scope:** Are there any formatting-only changes in files that I did not functionally modify? If so, revert them. Does the total line count of the diff align with the approved scope (e.g., ~1,000 lines for migrations)? -3. **Commit Message:** Does the commit message title fit within 50 characters? Does the body encapsulate the entirety of the changes across the diff cleanly and professionally? -4. **Missing Tests & Coverage:** *Perform a structured check for any new methods or modified behavior.* Did I add a new utility method (like `plusMonths(Instant, int)`) or change core logic? If so, I MUST open the corresponding test file and write tests to cover the new functionality (including edge cases, negative values, and leap years) before considering the task complete. A code review is not thorough if it only checks for compilation. I must actively ensure every new branch of logic has a test. -5. **Package Lock:** Did I include `console-webapp/package-lock.json` in my diff? If so, I MUST revert it (`git checkout console-webapp/package-lock.json`) unless I explicitly intended to modify NPM dependencies. This file is often modified by the build process and should not be committed accidentally. +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: -Only after actively executing the `pr-polisher` skill and confirming these checks against your diff are you permitted to finalize the task. - -## Refactoring & Migration Guardrails - - -### 1. Compiler Warnings are Errors (`-Werror`) -This project treats Error Prone warnings as errors. -- **Repeatable Annotations**: `@SuppressWarnings` is **NOT** repeatable in this environment. If a method or class already has a suppression (e.g., `@SuppressWarnings("unchecked")`), you must merge them: - - ❌ `@SuppressWarnings("unchecked") @SuppressWarnings("MustBeClosedChecker")` - - ✅ `@SuppressWarnings({"unchecked", "MustBeClosedChecker"})` - -### 2. Build Strategy -- **Validation**: Always run `./gradlew build -x test` (or `./gradlew :core:build -x test -x :console-webapp:buildConsoleWebapp` for backend-only changes) before attempting to run unit tests. Unit tests will not run if there are compilation errors in any part of the `core` module. Before finalizing a PR or declaring a task done, you MUST verify your changes. **Prefer scoped builds** with `-x :console-webapp:buildConsoleWebapp` (e.g., `./gradlew :core:build -x :console-webapp:buildConsoleWebapp`) if you are only modifying backend Java code. Even scoped `:core` tasks trigger the frontend `console-webapp` build via `:core:processResources` unless `-x :console-webapp:buildConsoleWebapp` is passed, which unnecessarily runs `npmInstallDeps` (modifying `console-webapp/package-lock.json`) and can fail on host Node.js version mismatches. If you must run a global build, you must revert `console-webapp/package-lock.json` afterwards. Do not declare success if formatting checks (e.g., `spotlessCheck` or `javaIncrementalFormatCheck`) or tests fail. If formatting fails, run `./gradlew spotlessApply` and then re-run your build command to verify everything passes. +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. ## 🚫 Common Pitfalls to Avoid - -- **Serialization Precision (`.000Z`):** When asserting against or generating XML/YAML files, remember that millisecond precision (`.000Z`) is required. Always use `DateTimeUtils.formatInstant(...)` to format `Instant` objects (it preserves the `.000Z` suffix) instead of `Instant.toString()` (which drops it for exact seconds). We have added custom Jackson `InstantKeySerializer`s for this purpose, but you must keep this precision in mind when manually updating `.xml` or `.yaml` test data. -- Dagger/AutoValue corruption: If you modify a builder or a component incorrectly, Dagger will fail to generate code, leading to hundreds of "cannot find symbol" errors. If this happens, `git checkout` the last working state of the specific file and re-apply changes more surgically. -- **`replace` tool context**: When using `replace` on large files (like `Tld.java` or `DomainBase.java`), provide significant surrounding context. These files have many similar method signatures (getters/setters) that can lead to incorrect replacements. - ---- - -## GitHub and Pull Request Protocol - -This protocol defines the standard for interacting with GitHub repositories and processing Pull Request (PR) feedback. - -### 1. Interaction via `gh` CLI -- **Primary Tool:** ALWAYS use the `gh` CLI for all GitHub-related operations (listing PRs, viewing PR content, checking status, adding comments). -- **Credential Safety:** Never expose tokens or credentials in shell commands. - -### 2. Processing PR Feedback -- **Systematic Review:** When asked to address PR comments, first fetch all comments using `gh pr view --json reviews,comments`. -- **Minimal Scope Expansion:** Address comments surgically. If a fix requires changes beyond a few lines or expands the PR's original scope significantly, DO NOT implement it without explicit user approval. Instead, report the issue to the user. -- **Verification:** After addressing feedback, run the full build (`./gradlew build`) and relevant tests to ensure no regressions were introduced. - -### 3. PR Lifecycle Management -- **One Commit Per PR:** Ensure all changes are squashed into a single, clean commit. Use `git commit --amend --no-edit` for follow-up fixes. -- **Clean Workspace:** Always run `git status` and verify the repository state before declaring a task complete. -- **Package Lock:** The Gradle build automatically modifies `console-webapp/package-lock.json` via the `npmInstallDeps` task. ALWAYS revert this file (`git checkout console-webapp/package-lock.json`) before staging changes or finalizing a commit unless you explicitly modified NPM dependencies. -- **PR Description Synchronization:** Whenever you amend or update a commit's description, you **MUST** check whether the corresponding GitHub PR description (if one exists) matches the previous commit description. If the PR description was not manually customized (i.e., it simply reflects the older commit description), you must automatically update it via `gh pr edit` to keep it in sync with your newly updated commit description—**strictly after the updated commit has been pushed to the remote GitHub PR branch**. Do not update the remote PR description when changes are only committed locally. **CRITICAL:** When updating the PR description, you must strictly preserve any automated review links or footer blocks (such as Reviewable link blocks: `...`) at the bottom of the description. +- **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?"*