From c66643aaaa916afd5b8d023c9f6ef1bc1c1133d1 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Fri, 4 Dec 2026 22:21:09 -0500 Subject: [PATCH] Tighten agent docs, review skill, and guardrails After migrating repository skills to `.agents/skills/` (#3295), adding scoped `AGENTS.md` guides (#3311), and adding the on-demand `pr-review` skill (#3313), a full audit of all agent instructions and skill scripts uncovered remaining duplication, always-on context bloat, mis-routed/stale rules, and four concrete guardrail bugs: `check_diff.py` silently missed Valkey Protostuff fields on `@MappedSuperclass` parents and inline-annotated fields, `core/AGENTS.md` scoped the Netty `retainedDuplicate()` rule away from `proxy/` (its primary caller), `run_rewrite.sh` silently exited `0` on Gradle failure without cleanup traps, and `check_diff_test.py` never ran in presubmits or CI. Centralizing review rules into `pr-review`, moving `core/`-only rules out of root `GEMINI.md`, correcting stale Gradle/Spotless instructions, and fixing the guardrail scripts close these blind spots while cutting always-on `GEMINI.md` by 22%. Specifically, this change: - **Centralizes PR review rules in `.agents/skills/pr-review/SKILL.md`:** - `GEMINI.md` (`18,118 B` -> `14,071 B`): replaces duplicated `Processing PR Feedback` and `PR Description Sync` bullets with a 1-line pointer to `.agents/skills/pr-review/SKILL.md`. - `.agents/skills/pr-polisher/SKILL.md`: removes Step 9 (paginated PR review comment fetch), renumbers Step 10 -> 9, and adds `pr-review` negative routing to frontmatter `description`. - `console-webapp/AGENTS.md`: removes `## Review Calibration`, moving `Shared State` and `Build & Screenshots` into `pr-review` while keeping `Nested @if` as an Angular template authoring rule. - `core/AGENTS.md`: trims the review-only parenthetical from `JPQL Timestamp Ordering`. - `.agents/skills/pr-review/SKILL.md`: adds `### Nomulus Review Calibration` under `Conducting PR Reviews`. - **Re-scopes always-on rules and fixes stale build/formatting docs:** - Moves `Netty Retry Buffers` (`ByteBufHolder.retainedDuplicate()`) out of `core/AGENTS.md` into `GEMINI.md`'s Netty lifecycle bullet so `proxy/`, `networking/`, `prober/`, and `core/` all load it; removes the verbatim duplicated `console-webapp` sentence from `GEMINI.md`. - Moves `core/`-only idioms (CLI/Beam/`TestRegistryToolComponent`, model layering, `@GetterDelegate` sets, partial JSON updates, JAXB optional attributes, allocation tokens, Console actions, CSV output, time-projected entities, Valkey Protostuff compatibility, and async pipeline boundaries) from `GEMINI.md` into `core/AGENTS.md`, fixes exact `monthly_logs.sql` / `monthly_logs_test.sql` paths, and condenses `2-PR Schema Split` in `GEMINI.md`. - Corrects `spotlessApply` (`*.gradle` only) vs. `javaIncrementalFormatApply` (Java formatting & import order) and `checkstyleMain`/`checkstyleTest`, and replaces backend compile commands that triggered Docker `:core:buildToolImage` or `console-webapp` `npmInstallDeps` across `GEMINI.md`, `pr-polisher`, and `java-ast-refactoring`. - **Hardens guardrail scripts and wires unit tests into presubmits:** - `.agents/skills/pr-polisher/scripts/check_diff.py` (+ `SKILL.md` & `check_diff_test.py`): adds the 4 missing Protostuff `@MappedSuperclass` parents (`UpdateAutoTimestampEntity`, `GracePeriodBase`, `DomainDsDataBase`, `BaseTransferObject`), strips leading inline `@Annotation(...)` tokens instead of skipping annotated field lines, skips Java comment lines in anti-pattern checks (while still catching `/* package */`), fixes `fqn_pattern` capturing so full FQNs print, scopes `check_commit_message()` `[OK]` to local errors, and expands internal-leak checks to cover `//depot/configs` and `cl/` (`15/15` unit tests). - `config/presubmits.py`: adds `verify_agent_scripts()` so `check_diff_test.py` runs automatically on `./gradlew runPresubmits` and CI. - `.agents/skills/java-ast-refactoring/scripts/run_rewrite.sh`: adds `set -euo pipefail`, an `EXIT` cleanup trap for temporary files, and portable top-level `^name:` YAML extraction via `awk`. Verification: - `python3 .agents/skills/pr-polisher/scripts/check_diff_test.py -v`: `15/15` passed. - `python3 .agents/skills/pr-polisher/scripts/check_diff.py`: `0` errors, `0` warnings (`spotlessCheck` and `javaIncrementalFormatCheck` passed). - `./gradlew --no-daemon runPresubmits`: `BUILD SUCCESSFUL` (includes running `check_diff_test.py` via `verify_agent_scripts()`). - Strict `PyYAML` parse OK on all `.agents/skills/*/SKILL.md` files, `bash -n` on `run_rewrite.sh`, and `0` lines > 80 chars in `core/AGENTS.md` and `console-webapp/AGENTS.md`. BUG=http://b/593117423 Signed-off-by: Ben McIlwain --- .agents/skills/java-ast-refactoring/SKILL.md | 23 ++-- .../scripts/run_rewrite.sh | 42 ++++--- .agents/skills/pr-polisher/SKILL.md | 41 +++---- .../skills/pr-polisher/scripts/check_diff.py | 106 +++++++++++++----- .../pr-polisher/scripts/check_diff_test.py | 75 +++++++++++++ .agents/skills/pr-review/SKILL.md | 16 +++ GEMINI.md | 30 ++--- config/presubmits.py | 10 ++ console-webapp/AGENTS.md | 10 +- core/AGENTS.md | 92 ++++++++++++--- 10 files changed, 325 insertions(+), 120 deletions(-) diff --git a/.agents/skills/java-ast-refactoring/SKILL.md b/.agents/skills/java-ast-refactoring/SKILL.md index d6e9361b34d..b5f5d643fb3 100644 --- a/.agents/skills/java-ast-refactoring/SKILL.md +++ b/.agents/skills/java-ast-refactoring/SKILL.md @@ -1,6 +1,14 @@ --- 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. Don't use for: formatting-only fixes (use spotlessApply / javaIncrementalFormatApply), non-Java files, or single-line edits that a direct file edit handles safely." +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 javaIncrementalFormatApply + for Java or spotlessApply for Gradle), non-Java files, or single-line edits + that a direct file edit handles safely. --- # AST-Aware Java Refactoring @@ -24,26 +32,27 @@ python3 .agents/skills/java-ast-refactoring/scripts/safe_rename.py :compileJava ::compileTestJava for other modified modules (e.g., :proxy, :networking, :util) ``` -3. Run the tests covering the touched code, e.g. `./gradlew :core:standardTest -x :console-webapp:buildConsoleWebapp`. +3. Run the tests covering the touched code, e.g. `./gradlew :core:standardTest` (or `::test`). 4. Confirm `git status` shows no stray files (`rewrite.yml`, `rewrite-init.gradle`, or a modified `console-webapp/package-lock.json`). 5. Commit, then run the `pr-polisher` skill (`python3 .agents/skills/pr-polisher/scripts/check_diff.py`) to catch leftover fully qualified names, unused imports, and other anti-patterns. ## Error Recovery -* **Recipe not activated / "Could not extract 'name:'":** Ensure the recipe has a top-level `name:` line and `type: specs.openrewrite.org/v1beta/recipe`. +* **Recipe not activated / "Could not extract top-level 'name:'":** Ensure the recipe has a top-level `name:` line and `type: specs.openrewrite.org/v1beta/recipe`. * **No changes made:** The `methodPattern` or type name likely does not match. Use fully qualified types, `..` for any parameters, and verify against the method patterns section of `references/rewrite_recipes.md`. * **Gradle or plugin resolution failure:** Re-run with `--stacktrace`. The init script pins the OpenRewrite plugin version; if it is incompatible with the current Gradle version, update the version in `scripts/run_rewrite.sh`. * **Formatter failures after the run:** Re-run `./gradlew spotlessApply javaIncrementalFormatApply`, then repeat the compile step. -* **Interrupted run:** Remove leftover `rewrite-init.gradle` (and `./rewrite.yml` if it was a temporary copy), then restart. +* **Hard-killed run (`SIGKILL`):** The script removes `rewrite-init.gradle` (and temporary `./rewrite.yml`) automatically via an `EXIT` trap; only if forcefully killed, remove leftover temporary files before restarting. * **Bad transformation:** Discard it with `git checkout -- ` (or `git stash`), refine the recipe, and re-run rather than hand-patching the output. ## Known Limitations & Troubleshooting diff --git a/.agents/skills/java-ast-refactoring/scripts/run_rewrite.sh b/.agents/skills/java-ast-refactoring/scripts/run_rewrite.sh index 3042c3d98d0..9a466af33b9 100755 --- a/.agents/skills/java-ast-refactoring/scripts/run_rewrite.sh +++ b/.agents/skills/java-ast-refactoring/scripts/run_rewrite.sh @@ -14,27 +14,48 @@ # limitations under the License. # Wrapper script to dynamically execute OpenRewrite without modifying build.gradle +set -euo pipefail -if [ -z "$1" ]; then +if [ $# -lt 1 ] || [ -z "$1" ]; then echo "Usage: $0 " exit 1 fi -RECIPE_FILE=$(realpath "$1") +RECIPE_FILE=$(python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1") if [ ! -f "$RECIPE_FILE" ]; then echo "Error: Recipe file $RECIPE_FILE not found." exit 1 fi -# Extract the name of the recipe from the YAML to activate it -RECIPE_NAME=$(grep -oP '(?<=name: ).*' "$RECIPE_FILE" | head -n 1) +# Extract the top-level recipe name from the YAML to activate it (portable awk). +RECIPE_NAME=$(awk ' + /^name:[[:space:]]*/ { + sub(/^name:[[:space:]]*/, "") + sub(/[[:space:]]*(#.*)?$/, "") + gsub(/^["'\'']|["'\'']$/, "") + print + exit + } +' "$RECIPE_FILE") if [ -z "$RECIPE_NAME" ]; then - echo "Error: Could not extract 'name:' from $RECIPE_FILE" + echo "Error: Could not extract top-level 'name:' from $RECIPE_FILE" exit 1 fi INIT_SCRIPT="rewrite-init.gradle" +CREATED_INIT=false +COPIED_RECIPE=false + +cleanup() { + if [[ "$CREATED_INIT" == true ]]; then + rm -f "$INIT_SCRIPT" + fi + if [[ "$COPIED_RECIPE" == true ]]; then + rm -f ./rewrite.yml + fi +} +trap cleanup EXIT cat << EOF > "$INIT_SCRIPT" initscript { @@ -65,12 +86,13 @@ allprojects { apply plugin: org.openrewrite.gradle.RewritePlugin } EOF +CREATED_INIT=true # 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 +ROOT_RECIPE=$(python3 -c 'import os; print(os.path.realpath("rewrite.yml"))') +if [[ "$RECIPE_FILE" != "$ROOT_RECIPE" ]]; then cp "$RECIPE_FILE" ./rewrite.yml COPIED_RECIPE=true fi @@ -80,9 +102,3 @@ echo "Executing OpenRewrite recipe: $RECIPE_NAME" echo "Running code formatters to fix Checkstyle line-length and import ordering..." ./gradlew spotlessApply javaIncrementalFormatApply - -# Clean up temporary files -rm "$INIT_SCRIPT" -if [[ "$COPIED_RECIPE" == true ]]; then - rm ./rewrite.yml -fi diff --git a/.agents/skills/pr-polisher/SKILL.md b/.agents/skills/pr-polisher/SKILL.md index bd5e6e11e6a..82f075e485c 100644 --- a/.agents/skills/pr-polisher/SKILL.md +++ b/.agents/skills/pr-polisher/SKILL.md @@ -1,9 +1,11 @@ --- name: pr-polisher description: >- - Automated pre-flight checklist to polish PRs. Use this before declaring a task - or PR complete to automatically verify license headers, commit hygiene, - formatting, and codebase mandates. Don't use for non-Git changelists. + Automated pre-flight checklist to polish local PR commits. Use this before + declaring a task or commit complete to verify license headers, commit + hygiene, formatting, tests, and codebase mandates. Don't use for reading or + responding to GitHub/Reviewable PR reviews (use pr-review) or non-Git + changelists. --- # PR Polisher @@ -24,24 +26,22 @@ Do not ask for permission. Do not wait for the user to remind you. Run the full python3 .agents/skills/pr-polisher/scripts/check_diff.py ``` -2. **Run Formatting Validation** - Always run the project's formatting tools to ensure checkstyle and Google Java Format passes. +2. **Apply Formatting Fixes If Step 1 Reports Errors** + Step 1 (`check_diff.py`) already runs `./gradlew spotlessCheck javaIncrementalFormatCheck` (`spotless` checks `**/*.gradle`; `javaIncrementalFormat` runs Google Java Format and import sorting on changed Java lines). If it fails, apply fixes and re-run Checkstyle: ```bash - ./gradlew spotlessCheck javaIncrementalFormatCheck - # OR if formatting is needed: ./gradlew spotlessApply javaIncrementalFormatApply ``` -3. **Run Presubmits and Compilation** - Ensure that the project builds correctly and all presubmit checks pass. Use scoped builds and pass `-x :console-webapp:buildConsoleWebapp` when only modifying backend Java code to save time, avoid modifying `console-webapp/package-lock.json`, and prevent Angular CLI Node.js version mismatch failures. +3. **Run Presubmits, Compilation, Checkstyle, and Tests** + Ensure presubmits, compilation, Checkstyle (`checkstyleMain`/`checkstyleTest`), and tests pass. Use scoped compile targets for backend-only changes to avoid Docker image builds (`:core:buildToolImage`) and unnecessary `console-webapp` `npmInstallDeps` runs (which can dirty `console-webapp/package-lock.json` or fail on host Node.js mismatches): ```bash - # Run presubmits + # Run presubmits (also executes check_diff_test.py and release script tests) ./gradlew runPresubmits - # Verify compilation (use a scoped build if you only modified one module, e.g., :core) - ./gradlew :core:build -x test -x :console-webapp:buildConsoleWebapp - # Run standard test suite if modifying core - ./gradlew :core:standardTest -x :console-webapp:buildConsoleWebapp + # Verify backend compilation & Checkstyle (add ::compileJava for sibling modules) + ./gradlew :core:compileJava :core:compileTestJava :core:checkstyleMain :core:checkstyleTest + # Run standard test suite if modifying core (add -x :console-webapp:buildConsoleWebapp if running :core:test) + ./gradlew :core:standardTest ``` 4. **Verify PR Scope and Extraneous Files (Line-by-Line Inspection)** @@ -68,19 +68,10 @@ Do not ask for permission. Do not wait for the user to remind you. Run the full 8. **Verify State-Machine and Serialization Hygiene** If the diff adds or modifies lifecycle fields (`Status`/`State`/`Stage` enums, nullable timestamps, `TimedTransitionProperty`, Netty handlers, cron/Cloud Tasks pipelines, or Angular view/edit/loading booleans): * Confirm multi-step states and transitions are explicit and centralized (Java 25 `sealed` projections + transitioners, `ImmutableMultimap` transition maps, or Angular Signal discriminated unions via `@switch`) rather than scattered `if` guards, ordinal `Enum.compareTo`, or orthogonal booleans. - * Confirm no redundant persisted static `state` column is added to wall-clock time-projected entities (`Domain`, `Host`), and no non-`transient` field is added, removed, reordered, or retyped on Protostuff-cached entities (`EppResource`, `DomainBase`, `Domain`, `DomainTransferData`, `GracePeriod`, `DomainDsData`, `HostBase`, `Host`) without a coordinated `@Tag` or cache key-prefix migration. + * Confirm no redundant persisted static `state` column is added to wall-clock time-projected entities (`Domain`, `Host`), and no non-`transient` field is added, removed, reordered, or retyped on Protostuff-cached entities (`UpdateAutoTimestampEntity`, `EppResource`, `DomainBase`, `Domain`, `BaseTransferObject`, `DomainTransferData`, `GracePeriodBase`, `GracePeriod`, `DomainDsDataBase`, `DomainDsData`, `HostBase`, `Host`) without a coordinated `@Tag` or cache key-prefix migration. * Confirm async pipelines have explicit failure states, return retryable HTTP codes (`503`, not `204`) when Cloud Tasks must retry, and keep external HTTP/email side effects outside DB transactions. -9. **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. - -10. **Address Errors, Amend, and Re-Run (Iterative Checking)** +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 diff --git a/.agents/skills/pr-polisher/scripts/check_diff.py b/.agents/skills/pr-polisher/scripts/check_diff.py index 264784c8aa6..c14aed99c0d 100644 --- a/.agents/skills/pr-polisher/scripts/check_diff.py +++ b/.agents/skills/pr-polisher/scripts/check_diff.py @@ -43,12 +43,16 @@ # layouts breaks N/N+1 rolling upgrades unless @Tag or cache key prefixes migrate first. PROTOSTUFF_CACHED_FILES = frozenset(( "core/src/main/java/google/registry/model/EppResource.java", + "core/src/main/java/google/registry/model/UpdateAutoTimestampEntity.java", "core/src/main/java/google/registry/model/domain/Domain.java", "core/src/main/java/google/registry/model/domain/DomainBase.java", "core/src/main/java/google/registry/model/domain/GracePeriod.java", + "core/src/main/java/google/registry/model/domain/GracePeriodBase.java", "core/src/main/java/google/registry/model/domain/secdns/DomainDsData.java", + "core/src/main/java/google/registry/model/domain/secdns/DomainDsDataBase.java", "core/src/main/java/google/registry/model/host/Host.java", "core/src/main/java/google/registry/model/host/HostBase.java", + "core/src/main/java/google/registry/model/transfer/BaseTransferObject.java", "core/src/main/java/google/registry/model/transfer/DomainTransferData.java", )) PROTOSTUFF_FIELD_PATTERN = re.compile( @@ -100,8 +104,9 @@ 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'//depot/(?:google3|configs)'), "internal depot path"), (re.compile(r'(?:\bhttps?://|(? 0: + ch = rest[i] + if ch == '"': + i += 1 + while i < n and rest[i] != '"': + if rest[i] == '\\': + i += 1 + i += 1 + elif ch == '(': + depth += 1 + elif ch == ')': + depth -= 1 + i += 1 + while i < n and rest[i] in ' \t': + i += 1 + return prefix + rest[i:] + +def find_protostuff_field_changes(diff): current_file = "" - flagged_files = set() + flagged_files = [] + seen = set() for line in diff.split('\n'): if line.startswith('+++ '): current_file = line[6:] if line.startswith('+++ b/') else "" continue - if current_file not in PROTOSTUFF_CACHED_FILES or current_file in flagged_files: + if current_file not in PROTOSTUFF_CACHED_FILES or current_file in seen: continue if (line.startswith('+') and not line.startswith('+++')) or ( line.startswith('-') and not line.startswith('---') @@ -593,18 +636,29 @@ def check_protostuff_cached_entities(): stripped = code_line.strip() if (not stripped or stripped.startswith('//') or stripped.startswith('*') - or stripped.startswith('/*') - or stripped.startswith('@')): + or stripped.startswith('/*')): + continue + normalized = strip_leading_java_annotations(code_line) + if not normalized.strip(): continue - if (not PROTOSTUFF_SKIP_MODIFIER_PATTERN.search(code_line) - and PROTOSTUFF_FIELD_PATTERN.match(code_line) - and '(' not in code_line.split('=')[0]): - flagged_files.add(current_file) - log_warning( - f"[{current_file}] Modified a potential non-transient field on a Valkey" - " Protostuff-cached entity (no @Tag annotations). Adding, removing, reordering," - " or retyping fields breaks N/N+1 rolling upgrades in SimplifiedJedisClient;" - " never persist static state columns on time-projected Domain/Host entities.") + if (not PROTOSTUFF_SKIP_MODIFIER_PATTERN.search(normalized) + and PROTOSTUFF_FIELD_PATTERN.match(normalized) + and '(' not in normalized.split('=')[0]): + seen.add(current_file) + flagged_files.append(current_file) + return flagged_files + +def check_protostuff_cached_entities(): + print("\n--- Checking Protostuff-Cached Entities (Valkey Compatibility) ---") + diff = run_cmd(f"git diff {get_diff_base()} -U0") + flagged_files = find_protostuff_field_changes(diff) + + for current_file in flagged_files: + log_warning( + f"[{current_file}] Modified a potential non-transient field on a Valkey" + " Protostuff-cached entity (no @Tag annotations). Adding, removing, reordering," + " or retyping fields breaks N/N+1 rolling upgrades in SimplifiedJedisClient;" + " never persist static state columns on time-projected Domain/Host entities.") if not flagged_files: log_success("No non-transient field changes detected on Protostuff-cached entities.") diff --git a/.agents/skills/pr-polisher/scripts/check_diff_test.py b/.agents/skills/pr-polisher/scripts/check_diff_test.py index b923154c4f1..5c4e2312e18 100644 --- a/.agents/skills/pr-polisher/scripts/check_diff_test.py +++ b/.agents/skills/pr-polisher/scripts/check_diff_test.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import io import os import subprocess import sys @@ -234,6 +235,80 @@ def fake_run_cmd(cmd): ): self.assertEqual(check_diff.get_diff_base(), "local123") + def test_find_protostuff_field_changes_catches_inline_annotations_and_superclasses(self): + diff = ( + "+++ b/core/src/main/java/google/registry/model/domain/DomainBase.java\n" + "+ @Expose @Transient Set newField;\n" + "+++ b/core/src/main/java/google/registry/model/domain/GracePeriodBase.java\n" + "+ @Column(name = \"extra\") String extraColumn;\n" + "+++ b/core/src/main/java/google/registry/model/EppResource.java\n" + "+ @Expose\n" + "+ private transient int cachedOnly;\n" + "+ private static final int CONSTANT = 1;\n" + "+ @Override public String toString() {\n" + ) + self.assertEqual( + check_diff.find_protostuff_field_changes(diff), + [ + "core/src/main/java/google/registry/model/domain/DomainBase.java", + "core/src/main/java/google/registry/model/domain/GracePeriodBase.java", + ], + ) + + def test_check_diff_anti_patterns_skips_java_comments_keeps_package_and_prints_full_fqn(self): + diff = ( + "+++ b/core/src/main/java/google/registry/example/Foo.java\n" + "+ // Avoid Instant.now() and ZoneId.of(\"UTC\") here.\n" + "+ /* Javadoc: never call instant.toString() */\n" + "+ /* package */ void helper() {}\n" + "+ java.time.temporal.ChronoUnit unit;\n" + ) + prev_errors = check_diff.errors_found + prev_warnings = check_diff.warnings_found + buf = io.StringIO() + try: + with mock.patch("sys.stdout", buf): + check_diff.check_diff_anti_patterns(diff) + self.assertEqual(check_diff.errors_found, prev_errors + 1) + self.assertEqual(check_diff.warnings_found, prev_warnings + 1) + output = buf.getvalue() + self.assertIn("/* package */", output) + self.assertIn("java.time.temporal.ChronoUnit", output) + self.assertNotIn("un-injected clock", output) + self.assertNotIn("Instant.toString()", output) + finally: + check_diff.errors_found = prev_errors + check_diff.warnings_found = prev_warnings + + def test_check_commit_message_reports_ok_even_with_prior_errors(self): + prev_errors = check_diff.errors_found + buf = io.StringIO() + try: + check_diff.errors_found = 1 + with ( + mock.patch.object( + check_diff, + "run_cmd", + return_value="Valid short subject\n\nBody explaining why.", + ), + mock.patch("sys.stdout", buf), + ): + check_diff.check_commit_message() + self.assertIn("Commit message format looks good.", buf.getvalue()) + self.assertEqual(check_diff.errors_found, 1) + finally: + check_diff.errors_found = prev_errors + + def test_internal_leak_patterns_catch_configs_and_cl_and_allow_bug_refs(self): + def matches_any(text): + return any(p.search(text) for p, _ in check_diff.INTERNAL_LEAK_PATTERNS) + + self.assertTrue(matches_any("//depot/" + "configs/users/foo/bar")) + self.assertTrue(matches_any("See " + "cl/" + "123456789 for details")) + self.assertTrue(matches_any("http://" + "cl/" + "987654321")) + self.assertFalse(matches_any("BUG=http://b/593117423")) + self.assertFalse(matches_any("https://example.com/" + "cl/" + "not-digits")) + if __name__ == "__main__": unittest.main() diff --git a/.agents/skills/pr-review/SKILL.md b/.agents/skills/pr-review/SKILL.md index 0e8ef34beca..0219a53b20e 100644 --- a/.agents/skills/pr-review/SKILL.md +++ b/.agents/skills/pr-review/SKILL.md @@ -225,6 +225,22 @@ Reviewable infers blocking vs. non-blocking state from how a comment opens: genuine blockers. For security or logic fixes, explicitly require covering unit tests before approval. +### Nomulus Review Calibration + +Avoid noisy or false-positive review findings on known Nomulus patterns: + +- **Shared Angular State:** Verify DOM, tab, or route mutual exclusivity before + flagging shared state (e.g., `isLoading`) across views or tabs. +- **Nested Angular `@if`:** Do not ask authors to flatten nested + `@if (!cond) { @if (...) { ... } }` into `@if (cond) { } @else if (...)` with + a dummy empty block. +- **Console Build & Screenshots:** Do not suggest over-engineered Gradle checks + (`JsonSlurper` `angular.json` parsing, `Copy`-to-`Sync` rewrites), and do not + block on `ConsoleScreenshotTest` golden updates that CI catches cleanly. +- **JPQL Timestamp Ordering:** Do not request a trailing `domainName ASC` + tie-breaker when a JPQL query orders by `creationTime`, `deletionTime`, or + `modificationTime`. + ### Submit a Single Batched Review Post all inline comments and the summary atomically via the Reviews API (choose diff --git a/GEMINI.md b/GEMINI.md index bf2d7d9a706..67ee8af3387 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -15,29 +15,24 @@ Core mandates, architectural patterns, and conventions for Nomulus. Review the w - **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. +- **Formatting Tools:** Never hand-roll scripts or regexes to fix formatting. Run `./gradlew spotlessApply` (`*.gradle` files) and `./gradlew javaIncrementalFormatApply` (Java formatting and import sorting on changed lines; or `google-java-format --replace `). Checkstyle runs via `checkstyleMain`/`checkstyleTest`. - **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 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. -- **Test Components:** Use `TestRegistryToolComponent` for command-line tool tests to bridge `main` and `nonprod/test` source sets. ### 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 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.** - 2. **PR #2 (ORM):** after PR #1 is deployed to production: entity/flow changes, tests, and the regenerated `db-schema.sql.generated` (`generateSqlSchema`). +- **2-PR Schema Split:** Read `db/README.md` before any schema change. Never mix Flyway scripts (`db/src/main/resources/sql/flyway/V*.sql`) with Java ORM or `db-schema.sql.generated` changes in one PR; ship schema-only first (`flyway.txt`, `nomulus.golden.sql`, ER diagrams), then ORM/entity changes after prod deploy. ### 5. Java, Guava, and Nomulus Idioms - **Compiler Warnings are Errors (`-Werror`):** `@SuppressWarnings` is not repeatable; merge suppressions: `@SuppressWarnings({"unchecked", "MustBeClosedChecker"})`. @@ -49,22 +44,12 @@ Core mandates, architectural patterns, and conventions for Nomulus. Review the w - **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. ### 6. Explicit State Machines and Lifecycle Design - **Model Multi-Step Lifecycles Explicitly:** Whenever an entity, protocol handler, async pipeline, or UI flow has 3+ states or coupled lifecycle fields (status sets + nullable timestamps, Netty connection phases, multi-step cron/Beam/GCS stages, or Angular view/edit/async states), model states and legal transitions explicitly using native language constructs—Java 25 `sealed interface` + `record` + exhaustive `switch`, Guava `ImmutableMultimap`/`ImmutableTable` transition maps, or Angular Signal discriminated unions rendered via `@switch`. Do not add third-party FSM frameworks, scatter state across orthogonal booleans or nullable timestamp constellations, or gate stage transitions with ordinal `Enum.compareTo`. -- **Time-Projected Entities (Wall-Clock Caveat):** Core EPP resources (`Domain`, `Host`) and `TimedTransitionProperty` schedules (`Tld`, `AllocationToken`, `FeatureFlag`) advance state purely as wall-clock time passes (`cloneProjectedAtTime(now)` or `clock.now()`) with no code executing at transition boundaries. Never persist a redundant static `state` column on time-projected entities like `Domain` or `Host` (it drifts immediately as time advances). Instead, derive a total `sealed` state projection from `(entity, now)`, centralize mutations through one transitioner, and enforce `TimedTransitionProperty` transition graphs at build and YAML-deserialization time—never call raw `TimedTransitionProperty.fromValueMap(...)` for stateful enums (`TldState`, `TokenStatus`). -- **Valkey / Redis Protostuff Compatibility (`SimplifiedJedisClient`):** `Domain`, `Host`, and embedded transfer/grace-period/DS types serialize to shared Valkey via Protostuff `RuntimeSchema` without `@Tag` annotations. Never add, remove, reorder, or retype non-`transient` fields on `EppResource`, `DomainBase`, `Domain`, `DomainTransferData`, `GracePeriod`, `DomainDsData`, `HostBase`, or `Host` without first coordinating a `@Tag` or cache key-prefix migration across rolling upgrades. -- **Async Pipelines and Side-Effect Boundaries:** Do not coordinate multi-step cron, Cloud Tasks, Dataflow, or GCS workflows solely through `Cursor` rows, GCS prefix scans, and Cloud Tasks retry counts. Persist explicit durable job/stage rows with a terminal failure state, return HTTP `503` (never `204`) when a Cloud Task must retry, and keep external HTTP, email, and task-enqueue side effects outside SERIALIZABLE database transactions. -- **Netty and Console UI Lifecycles:** Model Netty connection, relay, and quota phases with explicit state types, bundle rotated TLS key/certificate/`SslContext` atomically under one supplier (never split expiration timers), and cover stateful handlers in full-pipeline `LocalChannel` tests. In `console-webapp/` (zoneless `OnPush`), represent async/form/modal states with signal-backed discriminated unions, cancel/timeout in-flight requests via RxJS (`timeout()`, `switchMap`, `takeUntilDestroyed`), and avoid plain mutable state fields or detached global timers. +- **Netty Lifecycles & Retry Buffers:** Model Netty connection, relay, and quota phases with explicit state types, bundle rotated TLS key/certificate/`SslContext` atomically under one supplier (never split expiration timers), call `ByteBufHolder.retainedDuplicate()` (never `retain()`) before retryable outbound Netty writes so retries do not share a mutated `readerIndex`, and cover stateful handlers in full-pipeline `LocalChannel` tests. (See `core/AGENTS.md` for EPP entity, Valkey Protostuff, and async pipeline lifecycle rules, and `console-webapp/AGENTS.md` for Angular Signal/RxJS rules.) ## 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). @@ -73,13 +58,13 @@ Core mandates, architectural patterns, and conventions for Nomulus. Review the w - **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. +- **Gradle Test Tasks:** In `core`, run `./gradlew :core:standardTest` first (faster than `:core:test`, which adds `fragileTest` and `:console-webapp:buildConsoleWebapp`); pass `-x :console-webapp:buildConsoleWebapp` when running `:core:test` or `:core:fragileTest` on backend-only changes. - **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 :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. +- **Compile Before Testing:** For backend-only changes, run `./gradlew :core:compileJava :core:compileTestJava :core:checkstyleMain :core:checkstyleTest` (and `::compileJava ::compileTestJava` for touched sibling modules like `:proxy`, `:networking`, `:prober`, `:jetty`, `:util`). Avoid bare `:core:build` or root `build` for backend-only edits because `:core:build` triggers Docker `:core:buildToolImage` and root `build` triggers `console-webapp` `npmInstallDeps` (which can dirty `console-webapp/package-lock.json` or fail 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. +- **Formatting Failures:** Never declare success if `spotlessCheck`, `javaIncrementalFormatCheck`, `checkstyleMain`/`checkstyleTest`, 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`. @@ -101,8 +86,7 @@ Core mandates, architectural patterns, and conventions for Nomulus. Review the w - **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 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. +- **PR Reviews & Feedback:** Use the `pr-review` skill (`.agents/skills/pr-review/SKILL.md`) when reading or responding to GitHub/Reviewable comments, syncing PR descriptions, or conducting code reviews. ## 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`. diff --git a/config/presubmits.py b/config/presubmits.py index f069f1693b4..82a9bb1a661 100644 --- a/config/presubmits.py +++ b/config/presubmits.py @@ -307,6 +307,15 @@ def verify_release_scripts(): return result.returncode != 0 +def verify_agent_scripts(): + """Runs unit tests for repository agent skill scripts.""" + result = subprocess.run( + [sys.executable, '.agents/skills/pr-polisher/scripts/check_diff_test.py'], + check=False, + ) + return result.returncode != 0 + + def get_files(): for root, dirnames, filenames in os.walk("."): for filename in filenames: @@ -330,6 +339,7 @@ def get_files(): # when we put it here it fails fast before all of the tests are run. failed |= verify_flyway_index() failed |= verify_release_scripts() + failed |= verify_agent_scripts() if failed: sys.exit(1) diff --git a/console-webapp/AGENTS.md b/console-webapp/AGENTS.md index a97041ae75f..ae37d75d1ee 100644 --- a/console-webapp/AGENTS.md +++ b/console-webapp/AGENTS.md @@ -3,7 +3,7 @@ Scoped Angular/RxJS/Vitest rules for `console-webapp/`. Root `GEMINI.md` still applies. -## Angular Signals, RxJS, and `GlobalLoader` +## Angular Templates, Signals, RxJS, and `GlobalLoader` - **Prefer Signal Unions Over `GlobalLoaderService`:** Under zoneless `OnPush`, model async/form/modal state with Signal discriminated unions @@ -27,13 +27,5 @@ applies. on list reloads and yields `undefined` when unmatched). Cancel in-flight requests on registrar switch via `onCleanup(() => sub.unsubscribe())` or `switchMap` so stale responses cannot act on the wrong registrar. - -## Review Calibration - -- **Shared State:** Verify DOM, tab, or route mutual exclusivity before - flagging shared state (e.g., `isLoading`) across views or tabs. - **Nested `@if`:** Never flatten nested `@if (!cond) { @if (...) { ... } }` into `@if (cond) { } @else if (...)` with a dummy empty block. -- **Build & Screenshots:** Avoid over-engineered Gradle checks (`JsonSlurper` - `angular.json` parsing, `Copy`-to-`Sync` rewrites) and do not block on - `ConsoleScreenshotTest` golden updates that CI catches cleanly. diff --git a/core/AGENTS.md b/core/AGENTS.md index 0598e1da8a9..bf6d87331d9 100644 --- a/core/AGENTS.md +++ b/core/AGENTS.md @@ -1,9 +1,17 @@ # Core Backend Agent Guidelines -Scoped Java/CLI/Console rules for `core/`. Root `GEMINI.md` still applies. +Scoped Java/CLI/Console/Model rules for `core/`. Root `GEMINI.md` still +applies. -## CLI Tools and `FeatureFlag` +## CLI Tools, Beam, and `FeatureFlag` +- **Command-Line Tools:** Use a package-private `@Inject Clock clock;` field + in `Command` implementations, set `command.clock = fakeClock;` in test + `@BeforeEach` (base classes like `EppToolCommandTestCase` do this for + generic command types), and use `TestRegistryToolComponent` for CLI tests + bridging `main` and `nonprod/test` source sets. +- **Beam Pipelines:** `Clock` is serializable; pass it through the `DoFn` + constructor or Dagger provider methods in the pipeline module. - **No Pre-Auth DB Queries During Parsing:** Never query Cloud SQL or `FeatureFlag` inside JCommander converters or validators before the CLI's access-justified (`-r`) database connection initializes. @@ -16,15 +24,20 @@ Scoped Java/CLI/Console rules for `core/`. Root `GEMINI.md` still applies. - **In-Tx Ownership and Console EPP:** Load resources and verify registrar ownership inside the mutating `tm().transact(...)` (never pre-load outside), using `isSuperuser = false` for missing/deleted resources and - Console `DELETE`. Reject `null` list entries upfront (HTTP `400`), - deduplicate inputs before DB writes and `toImmutableMap`, and pass + Console `DELETE`. Derive EPP superuser execution from the action type after + the permission check—never from `user.getUserRoles().isAdmin()`. Pass `@Config("registryAdminClientId")`—not sponsoring `registrarId`—to `StatelessRequestSessionMetadata` for superuser Console EPP - (`SUSPEND`/`UNSUSPEND`). -- **Gson Guards and Real Stream Tests:** Check `isJsonObject()`, - `isJsonArray()`, and `isJsonPrimitive() && getAsJsonPrimitive().isString()` - before `gson.fromJson` (Gson coerces numbers like `1.2e3` into strings), - and catch `JsonSyntaxException` to return HTTP `400`. Wire real request + (`SUSPEND`/`UNSUSPEND`), and prefix `ConsoleUpdateHistory` descriptions + with the registrar ID plus `ConsoleUpdateHistory.DESCRIPTION_SEPARATOR`. +- **Partial JSON Updates and Gson Guards:** For Gson-deserialized partial + updates, an omitted field is `null` and must preserve the stored value, + while an explicit `[]` clears it. Check `isJsonObject()`, `isJsonArray()`, + and `isJsonPrimitive() && getAsJsonPrimitive().isString()` before + `gson.fromJson` (Gson coerces numbers like `1.2e3` into strings), catch + `JsonSyntaxException` to return HTTP `400`, reject `null` list entries + upfront (HTTP `400`), trim/validate formats and size limits, and + deduplicate inputs before DB writes and `toImmutableMap`. Wire real request reads in console action tests via `ConsoleActionBaseTestCase.createServletInputStream(...)` and `RequestModule`. @@ -32,15 +45,60 @@ Scoped Java/CLI/Console rules for `core/`. Root `GEMINI.md` still applies. accepts non-zero trailing bits; verify `decoded.length == 32` and `base64().omitPadding().encode(decoded).equals(input)`. -## JPQL, Logging, and Netty Retries +## Models, JAXB, and Lifecycle Invariants + +- **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. +- **JAXB Optional Attributes:** Leave optional XML attributes with defaults + (e.g., fee `standard`/`refundable`, driven by `FeeType`) as `Boolean` + fields set to `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. +- **Time-Projected Entities (Wall-Clock Caveat):** Core EPP resources + (`Domain`, `Host`) and `TimedTransitionProperty` schedules (`Tld`, + `AllocationToken`, `FeatureFlag`) advance state as wall-clock time passes + (`cloneProjectedAtTime(now)` or `clock.now()`) with no code executing at + transition boundaries. Never persist a redundant static `state` column on + `Domain` or `Host`. Derive a total `sealed` state projection from + `(entity, now)`, centralize mutations through one transitioner, and enforce + `TimedTransitionProperty` transition graphs at build and + YAML-deserialization time—never call raw + `TimedTransitionProperty.fromValueMap(...)` for stateful enums (`TldState`, + `TokenStatus`). +- **Valkey / Redis Protostuff Compatibility (`SimplifiedJedisClient`):** + `Domain`, `Host`, and embedded transfer/grace-period/DS types serialize to + shared Valkey via Protostuff `RuntimeSchema` without `@Tag` annotations. + Never add, remove, reorder, or retype non-`transient` fields on + `UpdateAutoTimestampEntity`, `EppResource`, `DomainBase`, `Domain`, + `BaseTransferObject`, `DomainTransferData`, `GracePeriodBase`, + `GracePeriod`, `DomainDsDataBase`, `DomainDsData`, `HostBase`, or `Host` + without first coordinating a `@Tag` or cache key-prefix migration across + rolling upgrades. +- **Async Pipelines and Side-Effect Boundaries:** Do not coordinate + multi-step cron, Cloud Tasks, Dataflow, or GCS workflows solely through + `Cursor` rows, GCS prefix scans, and Cloud Tasks retry counts. Persist + explicit durable job/stage rows with a terminal failure state, return HTTP + `503` (never `204`) when a Cloud Task must retry, and keep external HTTP, + email, and task-enqueue side effects outside SERIALIZABLE DB transactions. + +## JPQL, CSV, and Logging - **JPQL Timestamp Ordering:** Do not append a trailing `domainName ASC` tie-breaker when ordering JPQL queries by `creationTime`, `deletionTime`, - or `modificationTime` (nor request one in reviews or tests). + or `modificationTime`. +- **CSV Output:** Build formats with + `CSVFormat.DEFAULT.builder().setRecordSeparator('\n').get()` (`build()` is + deprecated and the default separator is `\r\n`). - **Log Injection and `monthly_logs.sql`:** Sanitize `\r`/`\n` to `_` on - untrusted HTTP paths before logging, and update - `reporting/icann/sql/monthly_logs.sql` (and `monthly_logs_test.sql`) in - lockstep when demoting request logs it filters on. -- **Netty Retry Buffers:** Call `ByteBufHolder.retainedDuplicate()` (never - `retain()`) before retryable outbound Netty writes so retries do not share - a mutated `readerIndex`. + untrusted HTTP paths before logging, and update both + `src/main/resources/google/registry/reporting/icann/sql/monthly_logs.sql` + and + `src/test/resources/google/registry/reporting/icann/monthly_logs_test.sql` + in lockstep when demoting request logs it filters on.