{"owner":"apache","repo":"cassandra","hasSkills":true,"totalSkillsCount":83,"totalTokensCount":52401,"categories":["anthropic-skill","root-instruction","claude-rule"],"hasMcp":false,"mcpConfig":null,"found":[".claude/skills/cassandra-injvm-dtest/SKILL.md",".claude/skills/deep-review/SKILL.md",".claude/skills/mega-review/SKILL.md",".claude/skills/heatmap/SKILL.md",".claude/skills/bug-archaeology/SKILL.md",".claude/skills/patch-explainer/SKILL.md",".claude/skills/write-reproducer/SKILL.md","AGENTS.md",".claude/skills/tla-plus/SKILL.md",".claude/skills/shallow-review/SKILL.md",".claude/skills/targeted-review/SKILL.md","CLAUDE.md","tools/cqlstress-counter-example.yaml","tools/cqlstress-example.yaml","tools/cqlstress-insanity-example.yaml","tools/cqlstress-lwt-example.yaml",".claude/skills/README.md",".claude/skills/install.sh",".claude/skills/heatmap/heatmap.py",".claude/skills/shallow-review/EVAL-PROMPT.md",".claude/skills/bug-archaeology/references/EVAL-PROMPT.md",".claude/skills/bug-archaeology/references/per-bug-format.md",".claude/skills/bug-archaeology/references/synthesis-format.md",".claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md",".claude/skills/cassandra-injvm-dtest/references/classloader_guide.md",".claude/skills/cassandra-injvm-dtest/references/cluster_utils.md",".claude/skills/patch-explainer/references/analysis_framework.md",".claude/skills/patch-explainer/references/ascii_patterns.md",".claude/skills/targeted-review/references/report-format.md",".claude/skills/targeted-review/references/subagent-prompt-template.md",".claude/skills/tla-plus/references/language.md",".claude/skills/tla-plus/references/pluscal.md",".claude/skills/tla-plus/scripts/check.sh",".claude/skills/tla-plus/scripts/parse.sh",".claude/skills/tla-plus/scripts/setup.sh",".claude/skills/tla-plus/scripts/tlc.sh",".claude/skills/tla-plus/scripts/translate.sh",".claude/skills/tla-plus/templates/basic.tla",".claude/skills/tla-plus/templates/distributed.tla",".claude/skills/tla-plus/templates/pluscal.tla",".claude/skills/write-reproducer/references/bug-taxonomy.md",".claude/skills/write-reproducer/references/concurrency.md",".claude/skills/write-reproducer/references/distributed-systems.md",".claude/skills/write-reproducer/references/failure-classification.md",".claude/skills/write-reproducer/references/fuzzing.md",".claude/skills/write-reproducer/references/minimality-lattice.md",".claude/skills/write-reproducer/references/minimization.md",".claude/skills/write-reproducer/references/output-contract.md",".claude/skills/write-reproducer/references/property-based-testing.md",".claude/skills/write-reproducer/references/shrinking-checklist.md",".claude/skills/write-reproducer/references/test-patterns.md",".claude/skills/write-reproducer/scripts/detect_context.sh",".claude/skills/write-reproducer/scripts/shrink_text.py",".claude/skills/write-reproducer/scripts/validate_repro.sh",".claude/skills/deep-review/references/deep/.gitkeep",".claude/skills/deep-review/references/deep/deep-absence-completeness.md",".claude/skills/deep-review/references/deep/deep-boundary.md",".claude/skills/deep-review/references/deep/deep-concurrency.md",".claude/skills/deep-review/references/deep/deep-cross-cutting.md",".claude/skills/deep-review/references/deep/deep-logic.md",".claude/skills/deep-review/references/deep/deep-resources.md",".claude/skills/targeted-review/references/categories/INDEX.md",".claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md",".claude/skills/targeted-review/references/categories/boundaries-and-numbers.md",".claude/skills/targeted-review/references/categories/concurrency-and-locking.md",".claude/skills/targeted-review/references/categories/conditions-and-predicates.md",".claude/skills/targeted-review/references/categories/io-and-crash-safety.md",".claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md",".claude/skills/targeted-review/references/categories/null-and-type-safety.md",".claude/skills/targeted-review/references/categories/refactor-aftermath.md",".claude/skills/targeted-review/references/categories/serialization-and-versioning.md",".claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md",".claude/skills/targeted-review/references/categories/validation-and-input-handling.md",".claude/skills/tla-plus/references/patterns/code-to-spec.md",".claude/skills/tla-plus/references/patterns/distributed-systems.md",".claude/skills/tla-plus/references/patterns/invariants.md",".claude/skills/tla-plus/references/patterns/protocols.md",".claude/skills/shallow-review/references/general/specialists/absence.md",".claude/skills/shallow-review/references/general/specialists/boundary.md",".claude/skills/shallow-review/references/general/specialists/completeness.md",".claude/skills/shallow-review/references/general/specialists/concurrency.md",".claude/skills/shallow-review/references/general/specialists/logic.md",".claude/skills/shallow-review/references/general/specialists/resources.md"],"skills":{".claude/skills/cassandra-injvm-dtest/SKILL.md":"---\nname: cassandra-injvm-dtest\nversion: \"1.0.0\"\ndescription: Comprehensive guide for writing Apache Cassandra in-JVM distributed tests (dtests). Use when creating tests that simulate multi-node Cassandra clusters within a single JVM for faster integration testing. Covers cluster creation (single-node, multi-node, multi-datacenter), configuration (all cassandra.yaml parameters, features, network topology), instance lifecycle (startup/shutdown/restart), query execution, message filtering for failure scenarios, running code on instances, ClusterUtils utilities, and debugging classloader-related issues (serialization failures, same-class-different-classloader problems).\n---\n\n# Apache Cassandra In-JVM DTest Writer\n\n## Overview\n\nWrite comprehensive distributed tests for Apache Cassandra using the in-JVM dtest framework. This framework enables multi-node cluster simulation within a single JVM using isolated classloaders, providing fast and reliable integration testing without actual network communication.\n\n## Core Concepts\n\n### Framework Architecture\n\nThe in-JVM dtest framework uses **classloader isolation** to run multiple Cassandra instances in one JVM:\n\n- **Shared ClassLoader**: Common classes (primitives, APIs, config objects, byte buffers)\n- **Per-Instance ClassLoader**: Isolated Cassandra internals (DatabaseDescriptor, singletons, all C* code)\n- **IsolatedExecutor**: Marshals serialized lambdas across classloader boundaries\n- **Message Interception**: Inter-node messaging hooked at MessagingService level (no actual networking)\n\n### Key Classes\n\n| Class | Purpose | Location |\n|-------|---------|----------|\n| `Cluster` | Main entry point for creating clusters | `org.apache.cassandra.distributed.Cluster` |\n| `AbstractCluster` | Core cluster management | `org.apache.cassandra.distributed.impl.AbstractCluster` |\n| `Instance` | Individual Cassandra node | `org.apache.cassandra.distributed.impl.Instance` |\n| `InstanceConfig` | Node configuration | `org.apache.cassandra.distributed.impl.InstanceConfig` |\n| `ClusterUtils` | Utility methods | `org.apache.cassandra.distributed.shared.ClusterUtils` |\n| `ICoordinator` | Query execution interface | API package |\n| `MessageFilters` | Message filtering/dropping | `org.apache.cassandra.distributed.impl.MessageFilters` |\n\n## Quick Start\n\n### Basic Cluster Setup\n\n```java\nimport org.apache.cassandra.distributed.Cluster;\nimport org.apache.cassandra.distributed.api.ConsistencyLevel;\n\n// Create and start a 3-node cluster\ntry (Cluster cluster = Cluster.build(3).start()) {\n    // Create keyspace\n    cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                        \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n    // Create table\n    cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n    // Execute query\n    cluster.coordinator(1).execute(\"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                                  ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n    // Read data\n    Object[][] rows = cluster.coordinator(1).execute(\n        \"SELECT * FROM test.users WHERE id = ?\",\n        ConsistencyLevel.QUORUM, 1);\n}\n```\n\n### Test Base Class Pattern\n\n```java\nimport org.apache.cassandra.distributed.test.TestBaseImpl;\n\npublic class MyDTest extends TestBaseImpl {\n    private static Cluster cluster;\n\n    @BeforeClass\n    public static void setupCluster() throws IOException {\n        cluster = init(Cluster.build(3).start(), 2); // RF=2\n    }\n\n    @AfterClass\n    public static void teardownCluster() {\n        if (cluster != null)\n            cluster.close();\n    }\n\n    @Test\n    public void testSomething() {\n        // Test implementation\n    }\n}\n```\n\n## Cluster Creation Patterns\n\n### Pattern 1: Simple Single-Node Cluster\n\n```java\nCluster cluster = Cluster.build(1).start();\n```\n\n### Pattern 2: Multi-Node Cluster with Configuration\n\n```java\nCluster cluster = Cluster.build(3)\n    .withConfig(config -> config\n        .set(\"num_tokens\", \"256\")\n        .set(\"concurrent_reads\", \"64\")\n        .set(\"concurrent_writes\", \"64\"))\n    .start();\n```\n\n### Pattern 3: Multi-Datacenter Cluster\n\n```java\nCluster cluster = builder()\n    .withRacks(2, 1, 3)  // 2 DCs, 1 rack per DC, 3 nodes per rack\n    .start();\n\n// Or with explicit DC/rack naming\nCluster cluster = builder()\n    .withDC(\"dc1\", 3)\n    .withDC(\"dc2\", 3)\n    .start();\n```\n\n### Pattern 4: Cluster with Features\n\n```java\nimport static org.apache.cassandra.distributed.api.Feature.*;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withConfig(config -> config\n        .with(GOSSIP)           // Enable gossip protocol\n        .with(NETWORK)          // Enable inter-node networking\n        .with(NATIVE_PROTOCOL)  // Enable CQL protocol\n        .with(JMX))             // Enable JMX\n    .start();\n```\n\n### Pattern 5: Custom Token Distribution\n\n```java\nimport org.apache.cassandra.distributed.api.TokenSupplier;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(3))\n    .start();\n```\n\n### Pattern 6: Dynamic Port Allocation\n\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Configuration\n\n### Available Configuration Parameters\n\nConfiguration is applied via `config.set(key, value)` or `config.with(Feature)`:\n\n#### Network Configuration\n```java\nconfig.set(\"broadcast_address\", \"127.0.0.1\")\n      .set(\"listen_address\", \"127.0.0.1\")\n      .set(\"rpc_address\", \"127.0.0.1\")\n      .set(\"storage_port\", \"7000\")\n      .set(\"native_transport_port\", \"9042\")\n      .set(\"jmx_port\", \"7199\");\n```\n\n#### Token Configuration\n```java\nconfig.set(\"num_tokens\", \"256\")\n      .set(\"initial_token\", \"0\");\n```\n\n#### Memory Configuration\n```java\nconfig.set(\"memtable_heap_space\", \"512MiB\")\n      .set(\"key_cache_size\", \"50MiB\")\n      .set(\"counter_cache_size\", \"50MiB\")\n      .set(\"row_cache_size\", \"0MiB\");\n```\n\n#### Compaction & Concurrency\n```java\nconfig.set(\"concurrent_compactors\", \"4\")\n      .set(\"concurrent_reads\", \"32\")\n      .set(\"concurrent_writes\", \"32\")\n      .set(\"concurrent_counter_writes\", \"32\");\n```\n\n#### Commitlog Configuration\n```java\nconfig.set(\"commitlog_sync\", \"periodic\")\n      .set(\"commitlog_sync_period_in_ms\", \"10000\")\n      .set(\"commitlog_segment_size\", \"32MiB\");\n```\n\n#### Authentication & Authorization\n```java\nconfig.set(\"authenticator\", \"PasswordAuthenticator\")\n      .set(\"authorizer\", \"CassandraAuthorizer\")\n      .set(\"role_manager\", \"CassandraRoleManager\");\n```\n\n#### Accord Configuration (CEP-15)\n```java\nconfig.set(\"accord.enabled\", \"true\")\n      .set(\"accord.journal_directory\", \"/path/to/journal\");\n```\n\n#### Data Directories\n```java\n// Data directories are arrays\nconfig.set(\"data_file_directories\", new String[]{\"/path/to/data\"})\n      .set(\"commitlog_directory\", \"/path/to/commitlog\")\n      .set(\"hints_directory\", \"/path/to/hints\")\n      .set(\"saved_caches_directory\", \"/path/to/saved_caches\");\n```\n\n## Instance Lifecycle Operations\n\n### Starting Instances\n\n```java\n// Start with default settings\ninstance.startup();\n\n// Start with system properties\nClusterUtils.start(instance, properties -> {\n    properties.set(RING_DELAY, \"5000\");\n    properties.set(BOOTSTRAP_SCHEMA_DELAY_MS, \"5000\");\n});\n```\n\n### Stopping Instances\n\n```java\n// Graceful shutdown (blocking)\nClusterUtils.stopUnchecked(instance);\n\n// Abrupt shutdown (simulates kill -9)\nClusterUtils.stopAbrupt(cluster, instance);\n\n// Stop all instances\nClusterUtils.stopAll(cluster);\n\n// Async shutdown\nFuture<?> shutdownFuture = instance.shutdown();\nshutdownFuture.get(); // wait for completion\n```\n\n### Restarting Instances\n\n```java\n// Simple restart\nClusterUtils.restartUnchecked(instance);\n\n// Restart with different configuration\ninstance.shutdown().get();\ninstance.config().set(\"concurrent_reads\", \"64\");\ninstance.startup();\n```\n\n### Adding Instances\n\n```java\n// Add instance with same config as existing nodes\nIInstance newInstance = ClusterUtils.addInstance(cluster);\n\n// Add instance with custom config\nIInstance newInstance = ClusterUtils.addInstance(cluster, config -> {\n    config.set(\"auto_bootstrap\", true);\n});\n\n// Add instance to specific DC/rack\nIInstance newInstance = ClusterUtils.addInstance(cluster, \"dc1\", \"rack1\", config -> {\n    config.set(\"num_tokens\", \"256\");\n});\n\n// Start the new instance\nnewInstance.startup();\n```\n\n### Replacing Instances\n\n```java\n// Replace a failed node\nIInstance replacement = ClusterUtils.replaceHostAndStart(cluster, failedInstance);\n\n// Replace with custom properties\nIInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    failedInstance,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n```\n\n## Running Code on Instances\n\n### Pattern 1: Run Without Return Value\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    StorageService.instance.forceKeyspaceFlush(\"system\");\n});\n```\n\n### Pattern 2: Get Return Value (Sync)\n\n```java\nString version = cluster.get(1).callOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\n```\n\n### Pattern 3: Get Return Value (Async)\n\n```java\nFuture<String> future = cluster.get(1).asyncCallOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\nString version = future.get();\n```\n\n### Pattern 4: Pass Parameters\n\n```java\n// Parameters must be serializable\nint result = cluster.get(1).callOnInstance(() -> {\n    // Access Cassandra internals here\n    return ClusterMetadata.current().directory.allAddresses().size();\n});\n```\n\n### Pattern 5: Instance-to-Instance Operations\n\n```java\n// Get node ID from one instance, use it on another\nint nodeId = ClusterUtils.getNodeId(cluster.get(1), cluster.get(2));\n\nNodeId id = new NodeId(nodeId);\ncluster.get(2).runOnInstance(() -> {\n    StorageService.instance.cancelInProgressSequences(id);\n});\n```\n\n## Query Execution\n\n### Basic Queries\n\n```java\n// Execute without results\ncluster.coordinator(1).execute(\n    \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n    ConsistencyLevel.QUORUM,\n    1, \"Alice\"\n);\n\n// Execute with results\nObject[][] rows = cluster.coordinator(1).execute(\n    \"SELECT * FROM test.users WHERE id = ?\",\n    ConsistencyLevel.QUORUM,\n    1\n);\n```\n\n### Using Query Results\n\n```java\nimport org.apache.cassandra.distributed.api.SimpleQueryResult;\n\nSimpleQueryResult result = cluster.coordinator(1).executeWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nwhile (result.hasNext()) {\n    Row row = result.next();\n    int id = row.getInteger(\"id\");\n    String name = row.getString(\"name\");\n    System.out.println(\"User: \" + id + \", \" + name);\n}\n```\n\n### Pagination\n\n```java\nSimpleQueryResult result = cluster.coordinator(1).executeWithPagingWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM,\n    100  // page size\n);\n```\n\n### Async Execution\n\n```java\nFuture<SimpleQueryResult> future = cluster.coordinator(1).asyncExecuteWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nSimpleQueryResult result = future.get();\n```\n\n### Query with Tracing\n\n```java\nimport java.util.UUID;\n\nUUID sessionId = UUID.randomUUID();\nSimpleQueryResult result = cluster.coordinator(1).executeWithTracingWithResult(\n    sessionId,\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\n// Query tracing info from system_traces\ncluster.coordinator(1).execute(\n    \"SELECT * FROM system_traces.sessions WHERE session_id = ?\",\n    ConsistencyLevel.ONE,\n    sessionId\n);\n```\n\n### Internal Queries (No Coordinator)\n\n```java\n// Execute directly on instance internals (bypasses coordinator)\nSimpleQueryResult result = instance.executeInternalWithResult(\n    \"SELECT * FROM system.peers WHERE peer=?\",\n    expectedPeer.config().broadcastAddress().getAddress()\n);\n```\n\n## Message Filtering for Failure Injection\n\n### Pattern 1: Drop Messages Between Nodes\n\n```java\n// Drop all mutation requests from node 1 to node 2\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop()\n    .on();\n\n// Verify timeout behavior\nassertThatThrownBy(() ->\n    cluster.coordinator(1).execute(\n        \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n        ConsistencyLevel.ALL, 1, \"Alice\"\n    )\n).isInstanceOf(WriteTimeoutException.class);\n\n// Reset filters\ncluster.filters().reset();\n```\n\n### Pattern 2: Drop All Verbs\n\n```java\ncluster.filters()\n    .allVerbs()\n    .from(1).to(2)\n    .drop()\n    .on();\n```\n\n### Pattern 3: Drop Outbound Messages\n\n```java\ncluster.filters()\n    .outbound()\n    .from(1)\n    .verbs(Verb.READ_REQ.id)\n    .drop()\n    .on();\n```\n\n### Pattern 4: Custom Message Matching\n\n```java\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .messagesMatching((from, to, message) -> {\n        // Custom logic to match specific messages\n        return message.verb() == Verb.MUTATION_REQ.id;\n    })\n    .drop()\n    .on();\n```\n\n### Pattern 5: Temporary Filter Control\n\n```java\nIMessageFilters.Filter filter = cluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop();\n\nfilter.on();  // Enable\n// ... perform operations ...\nfilter.off(); // Disable\n```\n\n## ClusterUtils Reference\n\nFor comprehensive utilities, see [references/cluster_utils.md](references/cluster_utils.md).\n\n### Most Commonly Used Methods\n\n#### Lifecycle Management\n```java\nClusterUtils.stopUnchecked(instance);\nClusterUtils.stopAbrupt(cluster, instance);\nClusterUtils.restartUnchecked(instance);\nClusterUtils.stopAll(cluster);\n```\n\n#### Instance Management\n```java\nClusterUtils.addInstance(cluster, config -> {...});\nClusterUtils.replaceHostAndStart(cluster, toReplace);\nClusterUtils.start(instance, properties -> {...});\n```\n\n#### Ring & Gossip\n```java\nClusterUtils.awaitRingJoin(cluster.get(1), newInstance);\nClusterUtils.awaitRingHealthy(cluster.get(1));\nClusterUtils.awaitGossipStatus(instance, target, \"NORMAL\");\nClusterUtils.assertInRing(instance, expectedInRing);\n```\n\n#### CMS & Metadata\n```java\nClusterUtils.waitForCMSToQuiesce(cluster);\nEpoch epoch = ClusterUtils.getCurrentEpoch(instance);\nClusterUtils.fetchLogFromCMS(instance, awaitedEpoch);\n```\n\n#### Directories & Files\n```java\nList<File> dirs = ClusterUtils.getDataDirectories(instance);\nFile commitlog = ClusterUtils.getCommitLogDirectory(instance);\nFile hints = ClusterUtils.getHintsDirectory(instance);\n```\n\n## Schema Management\n\n### Creating Keyspaces\n\n```java\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n// Multi-DC keyspace\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'NetworkTopologyStrategy', \" +\n                    \"'dc1': 2, 'dc2': 2}\");\n```\n\n### Creating Tables\n\n```java\ncluster.schemaChange(\"CREATE TABLE test.users (\" +\n                    \"id int PRIMARY KEY, \" +\n                    \"name text, \" +\n                    \"email text)\");\n\n// With clustering\ncluster.schemaChange(\"CREATE TABLE test.events (\" +\n                    \"user_id int, \" +\n                    \"event_time timestamp, \" +\n                    \"event_type text, \" +\n                    \"PRIMARY KEY (user_id, event_time)) \" +\n                    \"WITH CLUSTERING ORDER BY (event_time DESC)\");\n```\n\n### Waiting for Schema Agreement\n\n```java\n// Manual wait\ntry (Cluster.SchemaChangeMonitor monitor = cluster.new SchemaChangeMonitor()) {\n    monitor.startPolling();\n    cluster.schemaChange(\"CREATE TABLE ...\");\n    monitor.waitForCompletion();\n}\n\n// Using ClusterUtils\nClusterUtils.awaitGossipSchemaMatch(cluster);\n```\n\n## Monitoring & Observables\n\n### Log Watching\n\n```java\n// Mark position and wait for log message\nlong mark = instance.logs().mark();\n// ... perform operation ...\ninstance.logs().watchFor(mark, \"Bootstrap completed\");\n\n// Grep logs\nList<String> errors = instance.logs().grep(\"ERROR\").getResult();\n```\n\n### Nodetool Integration\n\n```java\nimport org.apache.cassandra.distributed.api.NodeToolResult;\n\nNodeToolResult result = instance.nodetoolResult(\"status\");\nresult.asserts().success();\nString output = result.getStdout();\n\n// Common nodetool commands\ninstance.nodetool(\"flush\");\ninstance.nodetool(\"repair\");\ninstance.nodetool(\"compact\");\ninstance.nodetool(\"decommission\");\n```\n\n### Ring Information\n\n```java\nimport org.apache.cassandra.distributed.shared.ClusterUtils.RingInstanceDetails;\n\nList<RingInstanceDetails> ring = ClusterUtils.ring(instance);\nfor (RingInstanceDetails details : ring) {\n    System.out.println(\"Address: \" + details.getAddress());\n    System.out.println(\"Status: \" + details.getStatus());   // Up/Down\n    System.out.println(\"State: \" + details.getState());     // Normal/Leaving/Joining\n    System.out.println(\"Token: \" + details.getToken());\n}\n```\n\n### Gossip Information\n\n```java\nMap<String, Map<String, String>> gossip = ClusterUtils.gossipInfo(instance);\nfor (Map.Entry<String, Map<String, String>> entry : gossip.entrySet()) {\n    String address = entry.getKey();\n    Map<String, String> state = entry.getValue();\n    System.out.println(address + \" -> \" + state.get(\"STATUS\"));\n}\n```\n\n## Classloader Issues & Debugging\n\n### Understanding Classloader Isolation\n\nThe in-JVM dtest framework uses multiple classloaders for isolation:\n- **Test ClassLoader**: Where your test code runs\n- **Shared ClassLoader**: Primitives, APIs, config objects\n- **Instance ClassLoaders**: Per-instance Cassandra code (isolated)\n\n### Common Classloader Issues\n\n#### Issue 1: Same Class, Different ClassLoaders\n\n**Symptom**: `ClassCastException` even though classes appear identical\n\n```java\n// WRONG - This will fail\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in test classloader\n    // Try to use token with instance internals -> ClassCastException\n});\n\n// CORRECT - Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in instance classloader\n    // Now token is in correct classloader\n});\n```\n\n#### Issue 2: Serialization Failures\n\n**Symptom**: `NotSerializableException` or `ClassNotFoundException`\n\n```java\n// WRONG - Non-serializable lambda capture\nString localVar = \"test\";\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar); // May fail if localVar isn't Serializable\n});\n\n// CORRECT - Only pass serializable primitives\nfinal String localVar = \"test\"; // String is Serializable\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar);\n});\n```\n\n**Lambdas are serialized** and transferred across classloaders. Only capture:\n- Primitives (int, long, String, etc.)\n- Serializable objects marked with `@Shared`\n- Nothing else from test classloader\n\n#### Issue 3: Static State Not Shared\n\n**Symptom**: Static fields don't reflect changes across instances\n\n```java\n// Each instance has its own DatabaseDescriptor, StorageService, etc.\n// Static state is NOT shared between instances\n\n// To coordinate across instances, use:\n// 1. CQL queries to share data\n// 2. Message passing\n// 3. Instance-specific operations\n```\n\n### Debugging Techniques\n\n#### Technique 1: Print Classloader Information\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(\"ClassLoader: \" +\n        Thread.currentThread().getContextClassLoader());\n    System.out.println(\"Token class loader: \" +\n        Token.class.getClassLoader());\n});\n```\n\n#### Technique 2: Transfer Objects Explicitly\n\n```java\nimport org.apache.cassandra.distributed.impl.IsolatedExecutor;\n\n// Transfer object to instance classloader\nSerializable transferred = instance.transfer(mySerializableObject);\n```\n\n#### Technique 3: Use @Shared and @Isolated Annotations\n\n```java\n// In your test code\nimport org.apache.cassandra.utils.Shared;\nimport org.apache.cassandra.utils.Isolated;\n\n@Shared  // Loaded in shared classloader\npublic class MySharedClass implements Serializable {\n    // Can be shared across boundaries\n}\n\n@Isolated  // Each instance gets own copy\npublic class MyIsolatedClass {\n    // Not shared\n}\n```\n\n#### Technique 4: Check Serialization\n\n```java\n// Verify object can be serialized\ntry {\n    ByteArrayOutputStream baos = new ByteArrayOutputStream();\n    ObjectOutputStream oos = new ObjectOutputStream(baos);\n    oos.writeObject(myObject);\n    oos.close();\n    System.out.println(\"Object is serializable\");\n} catch (NotSerializableException e) {\n    System.out.println(\"Object is NOT serializable: \" + e.getMessage());\n}\n```\n\n### Best Practices for Classloader Safety\n\n1. **Keep lambdas simple**: Minimize captured variables\n2. **Use primitives**: Pass int, String, long instead of complex objects\n3. **Create objects inside runOnInstance**: Don't create in test, pass to instance\n4. **Avoid static state**: Don't rely on static fields across instances\n5. **Use coordinator for data sharing**: Query data rather than passing objects\n\n## Advanced Patterns\n\n### Pattern: Pausing & Resuming CMS Operations\n\n```java\n// Pause before committing at specific epoch\nCallable<Epoch> pauseHandle = ClusterUtils.pauseBeforeCommit(\n    cmsInstance,\n    transformation -> transformation instanceof AddNode\n);\n\n// Wait for pause\nEpoch epoch = pauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseCommits(cmsInstance);\n```\n\n### Pattern: Pausing Enactment\n\n```java\n// Pause before enacting specific epoch\nCallable<Void> pauseHandle = ClusterUtils.pauseBeforeEnacting(instance, epoch);\n\n// Wait for pause\npauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseEnactment(instance);\n```\n\n### Pattern: Testing with Log Monitoring\n\n```java\nClusterUtils.runAndWaitForLogs(\n    () -> {\n        cluster.coordinator(1).execute(\"INSERT INTO test.users VALUES (1, 'Alice')\",\n                                      ConsistencyLevel.QUORUM);\n    },\n    \"Mutation applied\",\n    cluster.get(1), cluster.get(2), cluster.get(3)\n);\n```\n\n### Pattern: Custom Instance Initialization\n\n```java\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withInstanceInitializer((cl, i) -> {\n        // Custom initialization logic\n        System.out.println(\"Initializing instance \" + i);\n    })\n    .start();\n```\n\n### Pattern: Testing Node Replacement\n\n```java\n// Original node\nIInvokableInstance original = cluster.get(2);\n\n// Stop original\nClusterUtils.stopAbrupt(cluster, original);\n\n// Replace with new node\nIInvokableInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    original,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n\n// Verify replacement joined\nClusterUtils.awaitRingJoin(cluster.get(1), replacement);\n```\n\n### Pattern: Testing Decommission\n\n```java\nIInvokableInstance leaving = cluster.get(3);\n\nboolean success = ClusterUtils.decommission(leaving);\nAssert.assertTrue(\"Decommission failed\", success);\n\n// Verify node left\nClusterUtils.assertNotInRing(cluster.get(1), leaving);\n```\n\n### Pattern: Multi-DC Token Ranges\n\n```java\nList<ClusterUtils.Range> ranges = ClusterUtils.getPrimaryRanges(\n    cluster.get(1),\n    \"test\"  // keyspace\n);\n\nfor (ClusterUtils.Range range : ranges) {\n    System.out.println(\"Range: \" + range.left() + \" to \" + range.right());\n}\n```\n\n## Complete Test Examples\n\n### Example 1: Basic Read/Write Test\n\n```java\npublic class BasicReadWriteTest extends TestBaseImpl {\n    @Test\n    public void testReadWrite() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n            // Write\n            cluster.coordinator(1).execute(\n                \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n            // Read\n            Object[][] rows = cluster.coordinator(2).execute(\n                \"SELECT * FROM test.users WHERE id = ?\",\n                ConsistencyLevel.QUORUM, 1);\n\n            Assert.assertEquals(1, rows.length);\n            Assert.assertEquals(1, rows[0][0]);\n            Assert.assertEquals(\"Alice\", rows[0][1]);\n        }\n    }\n}\n```\n\n### Example 2: Testing Write Timeout with Message Filtering\n\n```java\npublic class WriteTimeoutTest extends TestBaseImpl {\n    @Test\n    public void testWriteTimeout() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 3}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY, v int)\");\n\n            // Drop mutations to node 2 and 3\n            cluster.filters().inbound()\n                .to(2, 3)\n                .verbs(Verb.MUTATION_REQ.id)\n                .drop()\n                .on();\n\n            // This should timeout (can't reach QUORUM)\n            try {\n                cluster.coordinator(1).execute(\n                    \"INSERT INTO test.data (k, v) VALUES (?, ?)\",\n                    ConsistencyLevel.QUORUM, 1, 100);\n                Assert.fail(\"Expected WriteTimeoutException\");\n            } catch (RuntimeException e) {\n                Assert.assertTrue(e.getCause() instanceof WriteTimeoutException);\n            }\n\n            cluster.filters().reset();\n        }\n    }\n}\n```\n\n### Example 3: Testing Node Addition\n\n```java\npublic class NodeAdditionTest extends TestBaseImpl {\n    @Test\n    public void testAddNode() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n            // Add and start new node\n            IInvokableInstance newNode = ClusterUtils.addInstance(cluster, config -> {\n                config.set(\"auto_bootstrap\", true);\n            });\n            newNode.startup();\n\n            // Wait for node to join\n            ClusterUtils.awaitRingJoin(cluster.get(1), newNode);\n\n            // Verify all nodes see the new node\n            ClusterUtils.assertInRing(cluster.get(1), newNode);\n            ClusterUtils.assertInRing(cluster.get(2), newNode);\n        }\n    }\n}\n```\n\n### Example 4: Running Code on Instance\n\n```java\npublic class InstanceCodeTest extends TestBaseImpl {\n    @Test\n    public void testRunOnInstance() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 1}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Insert data\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.ONE);\n\n            // Force flush on node 1\n            cluster.get(1).runOnInstance(() -> {\n                StorageService.instance.forceKeyspaceFlush(\"test\");\n            });\n\n            // Verify flush happened by checking for sstables\n            int sstableCount = cluster.get(1).callOnInstance(() -> {\n                ColumnFamilyStore cfs = Keyspace.open(\"test\")\n                                               .getColumnFamilyStore(\"data\");\n                return cfs.getLiveSSTables().size();\n            });\n\n            Assert.assertTrue(\"Expected at least one sstable\", sstableCount > 0);\n        }\n    }\n}\n```\n\n### Example 5: Multi-DC Test\n\n```java\npublic class MultiDCTest extends TestBaseImpl {\n    @Test\n    public void testMultiDC() throws IOException {\n        try (Cluster cluster = builder()\n                                  .withRacks(2, 1, 2)  // 2 DCs, 1 rack each, 2 nodes per rack\n                                  .start()) {\n\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'NetworkTopologyStrategy', \" +\n                                \"'datacenter1': 2, 'datacenter2': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Write from DC1\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.LOCAL_QUORUM);\n\n            // Read from DC2\n            Object[][] rows = cluster.coordinator(3).execute(\n                \"SELECT * FROM test.data WHERE k = 1\",\n                ConsistencyLevel.LOCAL_QUORUM);\n\n            Assert.assertEquals(1, rows.length);\n        }\n    }\n}\n```\n\n## Troubleshooting Guide\n\n### Problem: Tests are flaky or hang\n\n**Possible causes:**\n1. Schema not fully agreed before operations\n2. Insufficient timeout for async operations\n3. Message filters not properly reset\n\n**Solutions:**\n```java\n// Wait for schema agreement\nClusterUtils.awaitGossipSchemaMatch(cluster);\n\n// Use longer timeouts for operations\nfuture.get(30, TimeUnit.SECONDS);\n\n// Always reset filters in finally block\ntry {\n    cluster.filters().inbound().drop().on();\n    // test code\n} finally {\n    cluster.filters().reset();\n}\n```\n\n### Problem: ClassCastException with tokens or types\n\n**Cause:** Object created in wrong classloader\n\n**Solution:**\n```java\n// Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0);\n    // Use token here\n});\n```\n\n### Problem: NoClassDefFoundError or ClassNotFoundException\n\n**Cause:** Class not available in instance classloader\n\n**Solution:** Ensure class is in Cassandra dependencies or marked `@Shared`\n\n### Problem: Test times out waiting for ring/gossip\n\n**Cause:** Network features not enabled\n\n**Solution:**\n```java\nCluster cluster = builder()\n    .withConfig(c -> c.with(GOSSIP, NETWORK))\n    .start();\n```\n\n### Problem: Port conflicts\n\n**Cause:** Static port allocation\n\n**Solution:**\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Additional Resources\n\n- **ClusterUtils**: See [references/cluster_utils.md](references/cluster_utils.md) for exhaustive utility method documentation\n- **Advanced Patterns**: See [references/advanced_patterns.md](references/advanced_patterns.md) for CMS operations, Accord testing, and complex scenarios\n- **Classloader Deep Dive**: See [references/classloader_guide.md](references/classloader_guide.md) for detailed classloader mechanics and debugging\n",".claude/skills/deep-review/SKILL.md":"---\nname: deep-review\nversion: \"1.0.0\"\ndescription: >\n  Deep file-focused code review for correctness bugs. Unlike shallow-review which runs 6\n  specialists in parallel across the entire patch, deep-review focuses on user-specified\n  files with full pattern catalogs (500+ patterns), codebase investigation, and source-level\n  context gathering. Use when: the user specifies particular files for focused review, a\n  shallow review flagged areas that need deeper investigation, reviewing critical-path code\n  changes, examining complex serialization/lifecycle/state-machine changes. The user\n  instructs which files to focus on (typically a subset of files in the patch).\n---\n\n# Deep Code Review\n\nFocused, thorough review of user-specified files using the full 500+ pattern catalog.\nEach file is reviewed with context gathering (reading source, not just diff), codebase\nsearches, and cross-referencing against the complete pattern database.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n                    +--------v---------+\n                    | User selects     |\n                    | focus files      |\n                    +--------+---------+\n                             |\n              +--------------+--------------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 0: Context  |       | Phase 0: Context      |\n    | (read full files, |       | (read full files,     |\n    |  callers, types)  |       |  callers, types)      |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 1: Deep     |       | Phase 1: Deep         |\n    | specialist review |       | specialist review     |\n    | (full checklists) |       | (full checklists)     |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 2: Codebase |       | Phase 2: Codebase     |\n    | investigation     |       | investigation         |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n              +--------------+--------------+\n                             |\n                    +--------v---------+\n                    | Phase 3: Cross-  |\n                    | file symmetry &  |\n                    | merge findings   |\n                    +------------------+\n```\n\n## Quick Start\n\n1. **Receive patch** and user's file focus list\n2. **For each focus file**: run Phase 0 (context), Phase 1 (deep checklists), Phase 2 (search)\n3. **Cross-file symmetry** pass across all focus files\n4. **Merge & report** with confidence ranking\n\n---\n\n## Phase 0: Context Gathering (per focus file)\n\nBefore touching any checklist, deeply understand each focus file. This is the key difference\nfrom shallow review — you read the actual source, not just the diff.\n\n**Prompt template**:\n```\nRead the full source of the focus file: `{FILE_PATH}`\nRead the patch for context: `{PATCH_PATH}`\n\nFor this file, gather:\n1. CLASS HIERARCHY: What does it extend? What interfaces? Read the parent class/interface.\n2. SIBLING CLASSES: Are there parallel implementations? Read at least one sibling.\n3. CALLERS: Who calls the modified methods? How do they use return values? (grep + read)\n4. LIFECYCLE: When is this object created, used, destroyed?\n5. STATE MACHINE (if applicable): Map every state and every transition. What events are handled\n   in each state? What events are *not* handled (missing transitions)? What states are never\n   reached? Where is this state enum pattern-matched — are all states covered at every match site?\n6. INVARIANTS: Read Javadoc, assertions, and any test files for this class.\n7. SERIALIZATION: If it serializes — read serialize, deserialize, serializedSize together.\n\nOutput a structured context summary for use by the deep review phases.\n```\n\n---\n\n## Phase 1: Deep Specialist Review (per focus file)\n\nEach focus file is reviewed against the FULL domain checklists (not the trimmed shallow\nversions). The reviewer selects which domains apply based on Phase 0 context.\n\n### Domain Selection\n\nBased on Phase 0 context, load the relevant deep checklists:\n\n| File contains | Load checklist |\n|---|---|\n| Conditions, comparisons, control flow, types | `references/deep/deep-logic.md` |\n| Arithmetic, indices, ranges, ByteBuffer, I/O | `references/deep/deep-boundary.md` |\n| Shared state, locks, lifecycle, state machines | `references/deep/deep-concurrency.md` |\n| Serialization, resources, metrics, config | `references/deep/deep-resources.md` |\n| New classes, new fields, registrations | `references/deep/deep-absence-completeness.md` |\n| Refactoring, merges, shell scripts, parsing | `references/deep/deep-cross-cutting.md` |\n\nTypically 2-4 domains are relevant per file. Load all relevant ones.\n\n**Prompt template**:\n```\nYou are performing a DEEP REVIEW of: `{FILE_PATH}`\n\nCONTEXT (from Phase 0):\n{CONTEXT_SUMMARY}\n\nPATCH (the changes being reviewed):\nRead: `{PATCH_PATH}`\n\nCHECKLISTS (load each relevant one):\nRead: `{SKILL_DIR}/references/deep/deep-logic.md`\nRead: `{SKILL_DIR}/references/deep/deep-boundary.md`\n[... load relevant domains ...]\n\nFor EVERY checklist item that could apply to this file:\n1. Check whether the pattern exists in the code\n2. If the pattern matches: search the codebase for confirming/refuting evidence\n3. Rate confidence: High (confirmed by evidence), Medium (pattern matches but\n   uncertain), Low (possible but speculative)\n\nReport ALL findings. For each:\n- Pattern ID and name\n- Location (file:line)\n- Confidence (High/Medium/Low)\n- What's wrong (2-3 sentences with reasoning)\n- Evidence gathered (what you searched for, what you found/didn't find)\n- Suggested fix\n\nOr \"No finding in this domain for this file\" if nothing applies.\n```\n\n---\n\n## Phase 2: Codebase Investigation (per focus file)\n\nFor each finding from Phase 1, and for absence/completeness patterns, execute targeted\ncodebase searches.\n\n**Search patterns to execute:**\n\n### For new fields:\n```bash\ngrep -rn \"serialize\\|deserialize\\|serializedSize\\|equals\\|hashCode\\|toString\" {FILE_DIR}/\n```\n\n### For new registrations:\n```bash\ngrep -rn \"addListener\\|register\\|subscribe\\|addMetric\\|removeSensor\\|deregister\" {FILE_DIR}/\n```\n\n### For new enum constants:\n```bash\ngrep -rn \"switch.*{ENUM_TYPE}\\|case.*{CONSTANT}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For interface implementations:\n```bash\ngrep -rn \"implements {INTERFACE}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For method callers:\n```bash\ngrep -rn \"{METHOD_NAME}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For parallel paths:\n```bash\ngrep -rn \"class.*extends.*{PARENT_CLASS}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n**Prompt template**:\n```\nYou are investigating findings from the deep review of: `{FILE_PATH}`\n\nFINDINGS TO INVESTIGATE:\n{PHASE_1_FINDINGS}\n\nFor each finding:\n1. Execute the relevant codebase searches (grep, read files)\n2. Confirm or refute the finding based on evidence\n3. If confirmed: search for additional instances of the same pattern\n4. If refuted: explain why with evidence\n\nFor absence patterns:\n1. Build the search list from the diff events\n2. Execute each search\n3. If no match found: report as confirmed finding\n4. If match found: report as refuted (the symmetric code exists)\n\nReport updated findings with evidence.\n```\n\n---\n\n## Phase 3: Cross-File Symmetry & Merge\n\nAfter all focus files are reviewed:\n\n**Prompt template**:\n```\nReview findings across all focus files for cross-file patterns:\n\n1. CROSS-FILE SYMMETRY: For each change in file A, is there a structurally parallel\n   change needed in file B? Check:\n   - Serialization families (if serialize changed, did deserialize change?)\n   - Interface implementations (if one implementation changed, do siblings need it?)\n   - Version-gated paths (if one version branch changed, do others?)\n   - Test coverage (does the test file cover the changed behavior?)\n\n2. FINDING REINFORCEMENT: Do findings across files reinforce each other?\n   - Logic + Absence at same conceptual location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Pattern flagged in multiple files → likely systematic issue\n\n3. MERGE & DEDUP: Combine all findings, deduplicate, rank.\n\n4. THREE-POINT TEST each finding:\n   - The code construct actually exists (not inferred)\n   - The bug is possible given visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n```\n\n---\n\n## Report Format\n\n```\n## Deep Review: [target]\n\n### Focus Files\n- `path/to/File1.java` — [brief description of changes]\n- `path/to/File2.java` — [brief description of changes]\n\n### Context Summary\n[Key facts from Phase 0: class hierarchy, lifecycle, shared state, invariants]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Domain**: [Logic / Boundary / Concurrency / Resources / Absence / Completeness]\n- **Pattern**: [pattern name from checklist]\n- **What's wrong**: [2-3 sentences with reasoning]\n- **Evidence**: [what was searched, what was found]\n- **Suggested fix**: [specific change]\n\n#### Finding 2: ...\n\n### Domain Coverage (per file)\n| File | Logic | Boundary | Concurrency | Resources | Absence | Completeness |\n|---|---|---|---|---|---|---|\n| File1.java | 2 findings | - | 1 finding | - | checked | checked |\n| File2.java | - | 1 finding | - | 3 findings | checked | checked |\n\n### Cross-File Symmetry\n- [Any asymmetries found]\n- [Any reinforcing patterns]\n```\n\n---\n\n## Reference Files\n\n### Deep specialist checklists\n- `references/deep/deep-logic.md` — Full logic, types, constants, filtering patterns\n- `references/deep/deep-boundary.md` — Full boundary, overflow, null, I/O patterns\n- `references/deep/deep-concurrency.md` — Full concurrency, state, lifecycle patterns\n- `references/deep/deep-resources.md` — Full serialization, resource, crash-safety patterns\n- `references/deep/deep-absence-completeness.md` — Full absence + completeness with search methodology\n- `references/deep/deep-cross-cutting.md` — Refactoring, parsing, platform, dispatch patterns\n",".claude/skills/mega-review/SKILL.md":"---\nname: mega-review\nversion: \"1.0.0\"\ndescription: >\n  Multi-pass deep code review for large patches (1000+ LOC) that maximizes real bug detection.\n  Orchestrates targeted-review, shallow-review, and deep-review in parallel across all HIGH and\n  MEDIUM risk files and commits: understands the feature holistically, splits by file and commit,\n  runs deep review on every HIGH/MEDIUM file, targeted review across the same scope, and\n  per-commit shallow review, followed by cross-cut consistency checks. Use when: reviewing a\n  large patch (feature branch, multi-commit, or single large diff, 1000+ LOC), doing a thorough\n  pre-merge review, or when shallower reviews miss bugs due to patch size. Triggers on: \"review\n  this branch\", \"review these commits\", \"review this feature\", \"mega review\", \"thorough review\",\n  \"full review of X commits\", or when the user specifies a commit range or feature for review.\n---\n\n# Mega-Review: Multi-Pass Large Patch Review\n\nThis skill orchestrates `/targeted-review`, `/shallow-review`, and `/deep-review` with\ncross-cut consistency checks to maximize bug detection on large patches (1000+ LOC). The input\ncan be a commit range, a feature branch, or any large diff — it does not have to span multiple\ncommits.\n\n**You MUST invoke `/targeted-review`, `/shallow-review`, and `/deep-review` as part of this\nworkflow.** Those skills have specialist checklists, pattern catalogs, and structured review\nprocesses that this skill does not duplicate. This skill's job is to understand the change\nholistically, decompose it into reviewable chunks, and delegate the actual code review to the\nappropriate sub-skills at the right granularity.\n\n## Why This Exists\n\nA single pass of `/shallow-review` over 7000 LOC spreads attention too thin. Real bugs hide in:\n- **Offset arithmetic** that works for the simple case but breaks when offset params are added\n- **Variable lifecycle issues** where a loop modifies a variable but the final operation needs the original\n- **Cross-cut inconsistencies** where fixes or refactors in one subsystem introduce bugs in another\n- **Algorithmic boundary conditions** in new data structure code\n\nThe key insight: some bugs are findable by mechanical checking (every System.arraycopy, every\nvariable swap), while others require deep understanding. This skill does BOTH.\n\n## Architecture\n\n```\n+---------------------+\n| PHASE 1: Decompose  |\n|   & Classify        |    Produce decomposition map + coverage checklist.\n+----------+----------+\n           |\n    +-------+--------+----------+\n    |                |           |\n+---v----+   +-------v------+  +-v-----------+\n|PHASE 2 |   |   PHASE 3    |  |   PHASE 4   |\n|Deep    |   |  Targeted    |  |  Shallow    |\n|Review  |   |  Review      |  |  Review     |\n|(HIGH + |   | (HIGH +      |  | (HIGH +     |\n| MEDIUM |   |  MEDIUM      |  |  MEDIUM     |\n| files) |   |  files)      |  |  commits)   |\n+---+----+   +-------+------+  +-+-----------+\n    |                |            |\n    +----------------+------------+\n                     |\n          +----------v----------+\n          | PHASE 5: Cross-Cut  |    Cross-commit/cross-subsystem consistency, pattern\n          | Passes              |    amplification, and fix verification checks.\n          +----------+----------+    One subagent per pass type (5A / 5B / 5C).\n                     |\n          +----------v----------+\n          | PHASE 6: Merge &    |    Deduplicate, verify plausibility, rank.\n          | Validate            |    Combine findings from ALL phases.\n          +---------------------+\n```\n\n---\n\n## Chunking Strategy\n\nThis skill's core principle: **the orchestrator holds global state; subagents hold only their\nslice.** A large patch reviewed by a single agent suffers attention dilution — its context fills\nwith earlier files, earlier findings, and earlier grep output, and it starts missing things. The\nfix is to reset context at every subagent boundary.\n\n### Orchestrator responsibilities\n- Holds the full patch, decomposition map, and accumulated findings from all phases\n- Before spawning each subagent, assembles a **briefing packet**: the chunk + a tight 100–200\n  word context summary written by the orchestrator\n- After each subagent returns, integrates findings into the global picture\n\n### What each subagent receives\n- **Its chunk**: the diff for its commit / grep hits for its audit type / file diff for its deep pass\n- **Orchestrator context**: subsystem name, risk level, what the code is trying to do (one paragraph)\n- **Focused task**: exactly what to look for and why — not a generic \"find bugs\"\n- **Relevant prior findings only**: findings from earlier phases that touch THIS chunk's files,\n  not the full findings list from all files\n\n### What each subagent does\nEach subagent **invokes a review skill** on its chunk — it is not a generic agent. The skill\ndetermines the review depth and structure. The chunk is the scope; the briefing packet is the\ncontext. Subagents may read additional source files, grep for callers, or check sibling classes\nto inform the review, but must not receive the full patch as input — that defeats the purpose.\n\n### Chunk boundaries by phase\n\n| Phase | Chunk unit | Skill to invoke | What the subagent receives |\n|---|---|---|---|\n| 2 (Deep) | One HIGH or MEDIUM file | `/deep-review` | That file's diff + full current source |\n| 3 (Targeted) | All HIGH + MEDIUM files as a group | `/targeted-review` | Diff for those files + Phase 1 risk classification |\n| 4 (Shallow) | One HIGH or MEDIUM commit | `/shallow-review` | That commit's diff only |\n| 5 (Cross-cut) | One pass type (5A / 5B / 5C) | inline only — no sub-skill | Finding list relevant to that pass + grep targets |\n\n**Phases 2, 3, and 4 run in parallel** — launch all their subagents in a single message after Phase 1 completes. Do not wait for Phase 2 before starting Phase 3 or 4.\n\n---\n\n## PHASE 1: Decompose & Classify\n\n**This phase is done inline — no sub-skill invocation.** Its job is to produce a decomposition\nmap and coverage checklist fast, then immediately hand off to the parallel Phases 2/3/4.\nEvery minute spent in Phase 1 is a minute not spent finding bugs.\n\n**Determining the input scope** — two modes depending on what the user provided:\n\n*Mode A — git boundary given* (commit range, branch, or single SHA): proceed directly to\nStep 1a.\n\n*Mode B — no git boundary* (user describes a feature, subsystem, or set of files without\nspecifying a range):\n1. Discover candidate files via grep or directory inspection:\n   ```bash\n   grep -rl \"<keyword>\" src/ | grep '\\.java$' | sort > /tmp/file_list.txt\n   # or: find src/java/org/apache/cassandra/<package> -name '*.java' | sort\n   ```\n2. **Show the list to the user and ask for confirmation** before going further — file count,\n   file names, anything obviously missing or out of scope. Do not skip this step.\n3. Produce a working diff against a sensible base (usually `main`):\n   ```bash\n   git diff main -- $(cat /tmp/file_list.txt | tr '\\n' ' ') > /tmp/mega_review.diff\n   # For files with no git history (new/untracked), read them directly — there is no diff.\n   ```\n4. Use this confirmed file list as the direct seed for the coverage checklist in Step 1e —\n   paste the files into the `File` column verbatim.\n5. In Phase 4, there are no commit boundaries: chunk by **file** instead of by commit —\n   one `/shallow-review` invocation per file. Skip Step 1a and go straight to Step 1b.\n\n**Step 1a — Get commit shape:**\n```bash\ngit log --oneline --stat <base>..<head>\n# Or for a single commit: git show --stat <SHA>\n```\n\n**Step 1b — Skim diff stats (do NOT read file bodies):**\n```bash\ngit diff <base>..<head> --stat\n# What to note: file names, extension types, rough LOC changes, new vs modified files\n```\n\n**Step 1c — Classify each commit/subsystem** by risk:\n- **HIGH**: New algorithms, data structure rewrites, complex feature additions, new orchestration layers, state machine changes, bootstrap/recovery logic\n- **MEDIUM**: Feature additions with new control flow, non-trivial interface changes with multiple callers\n- **LOW**: Renames, moves, mechanical refactors, test-only or documentation changes\n\n**Step 1d — Classify each source file** by type:\n- **Algorithmic**: Array operations, tree traversals, binary search, merges, set operations\n- **State machine**: Bootstrap, recovery, catchup, topology, lifecycle management\n- **Wiring**: Delegation, API changes, parameter threading\n- **Concurrency**: Shared state, synchronization\n- **Documentation/Config**: Markdown, YAML, config files, skill definitions\n\n**Step 1e — Write `/tmp/mega_coverage.md`** (the coverage checklist). Every changed non-test\nfile gets one row; pre-assign reviewers now based on risk:\n\n```markdown\n| File | LOC changed | Risk | Type | Assigned reviewers | Min required | Covered? |\n|------|-------------|------|------|--------------------|--------------|----------|\n| src/Foo.java | 320 | HIGH | Algorithmic | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| src/Bar.java | 45 | MEDIUM | Wiring | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| docs/SKILL.md | 18 | LOW | Documentation | Phase 4 (sha: def456) | 1 | — |\n```\n\nAssignment rules:\n- **HIGH-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **MEDIUM-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **LOW-risk file** → Phase 4 (shallow) — min 1\n\n**Step 1f — IMMEDIATELY start Phases 2, 3, and 4.** Do not pause to write analysis. Do not\ninvoke patch-explainer or any other sub-skill. The coverage checklist IS the Phase 1 output.\nIn the same response, spawn all Phase 2/3/4 subagents — see \"Launching Phases 2/3/4\" below.\n\n---\n\n## PHASE 2: Deep Review — invoke `/deep-review`\n\nFor every HIGH- and MEDIUM-risk file, invoke `/deep-review` scoped to that file. Each file\ngets a **separate, fresh subagent** — they run in parallel and share no context with each other.\nThis phase runs **in parallel with Phases 3 and 4** — start it as soon as Phase 1 completes.\n\n**Per-file input packet** (what the orchestrator provides to each `/deep-review` invocation):\n- The diff for that file only: `git diff <base>..<head> -- <file>`\n- The file's full current source (deep-review reads this itself, but point it at the right file)\n- A 100–150 word orchestrator briefing:\n  - File classification (algorithmic / state machine / wiring / concurrency)\n  - What the file does in the context of the overall change (1–2 sentences from Phase 1)\n  - Risk level and why it was classified HIGH or MEDIUM\n\n---\n\n## PHASE 3: Targeted Review — invoke `/targeted-review`\n\nInvoke the `/targeted-review` skill scoped to **all HIGH- and MEDIUM-risk files** identified\nin Phase 1 — not the full patch. Targeted-review is designed for focused review: it picks only\nthe bug-pattern categories whose diff signals match, then spawns tight subagents per focus area.\nFeeding it the full patch dilutes that focus; feeding it the files that matter most lets it go\ndeep where it counts.\n\n**Selecting the scope**:\n- Include all files classified HIGH- or MEDIUM-risk in Phase 1\n- Include files touched in multiple commits (cross-commit modification from the decomposition map)\n- Exclude LOW-risk files, test-only files, and pure documentation/config changes\n\n**When invoking `/targeted-review`**:\n- Pass only the diff for the selected files (not the full patch)\n- Include the Phase 1 risk classification and file-type notes as context so targeted-review\n  subagents understand what to focus on\n\nThis phase runs **in parallel with Phases 2 and 4** — start it as soon as Phase 1 completes.\nCollect all findings and tag each with `Phase 3 (targeted-review)` and its subagent focus.\n\n---\n\n## PHASE 4: Per-Commit Shallow Reviews — invoke `/shallow-review`\n\nFor each HIGH- and MEDIUM-risk commit, invoke `/shallow-review` scoped to that commit's diff.\nEach invocation is a **fresh subagent** — it receives only that commit's diff, not the full\npatch or accumulated findings from other commits.\n\nThis phase runs **in parallel with Phases 2 and 3** — start it as soon as Phase 1 completes.\n\n**Step 4a**: Extract per-commit diff to its own file:\n```bash\ngit diff <SHA>~1..<SHA> > /tmp/patch_<SHA>.diff\n```\n\n**Step 4b**: Assemble a briefing packet for `/shallow-review` containing ONLY:\n- The commit's diff (`/tmp/patch_<SHA>.diff`)\n- A 100–150 word orchestrator briefing covering:\n  - What category the commit is (algorithmic, state machine, wiring, concurrency)\n  - What risk level (HIGH/MEDIUM) and why\n  - For \"Fix\" commits: \"This commit says 'Fix X' — verify the fix is correct, complete,\n    and does not introduce new bugs. Fix commits have a higher-than-average bug rate.\"\n\n**Step 4c**: Run all HIGH- and MEDIUM-risk commit reviews in a single parallel batch. Collect\nfindings and tag each with the commit SHA.\n\n---\n\n## PHASE 5: Cross-Cut Passes\n\n**Dispatch 5A, 5B, and 5C as parallel subagents.** Each receives a focused slice of findings\nand a targeted task — not the full findings dump from all prior phases. The orchestrator\npre-filters: each subagent receives only the findings relevant to its pass.\n\n### 5A: Pattern Amplification\n\nPatterns come entirely from **bugs actually found in Phases 2–4** — there is no pre-loaded catalog.\nIf Phases 2–4 found zero bugs, 5A is skipped.\n\n**Orchestrator's job** (done before spawning anything):\n1. Collect all findings from Phases 2–4\n2. For each distinct bug, characterize the structural pattern — not the specific instance, but\n   the general shape: e.g. \"method accepts a `start` offset parameter, but an internal\n   `arraycopy` call ignores it and uses hardcoded `0`\"\n3. Decide the search scope based on the pattern type:\n   - **Patch-only** — pattern is structural and specific to new code introduced in this PR\n     (new algorithm, new data structure, new method overload family). Unlikely to exist elsewhere.\n   - **Codebase-wide** — pattern is a convention violation or contract bug that could affect\n     any code following the same convention (serialization encoding, API return value contracts,\n     lifecycle protocols, error code handling). The same mistake recurs wherever the convention\n     is followed, including in code not touched by this PR.\n4. Grep at the chosen scope for locations that could match the pattern shape\n5. Spawn one subagent per pattern, passing it: the pattern description + the grep hits + the\n   scope used (so it knows whether to look beyond the patch if it finds new leads)\n\n**Each subagent's job**: verify whether each grep hit is actually the same bug — read the\nsurrounding source as needed. Report confirmed additional instances only.\n\nOne confirmed bug → one pattern → potentially many additional instances found. This is the\nhighest-yield step when Phases 2–4 produce findings.\n\n### 5B: Cross-Commit/Cross-Subsystem Consistency\n\n**Subagent input**: The decomposition map from Phase 1 (file list, method signatures changed,\nrename list) + the list of caller sites extracted by the orchestrator. Not the full patch.\n\n1. **Interface contracts**: For each changed method signature, verify ALL callers updated\n2. **Rename completeness**: `grep` for old names that should no longer appear\n3. **Assumption conflicts**: When one part of the patch assumes X and another assumes Y about the same state\n\n### 5C: Fix Verification\n\n**Subagent input**: One subagent per \"Fix\" commit. Each receives: that commit's diff only +\na one-paragraph description of the bug it claims to fix.\n\nFor each fix commit:\n1. Read the fix carefully\n2. Try to construct an input that would still trigger the original bug\n3. Try to construct an input that triggers a new bug introduced by the fix\n\n### 5D: Optional Additional Review Passes\n\nIf Phases 2–5C revealed areas not yet covered, run additional targeted passes:\n\n- If 5A found a pattern class in files not yet reviewed → `/deep-review` on those files with\n  the specific pattern as focus guidance\n- If 5B found cross-cut inconsistencies in files not yet reviewed → `/shallow-review` on the\n  combined diff of those files\n- If a fix commit (5C) looks suspicious → `/deep-review` on that file with guidance:\n  \"Verify this fix is correct and does not introduce new bugs.\"\n\n---\n\n## Coverage Gate — Verify Before Phase 6\n\nBefore merging findings, verify `/tmp/mega_coverage.md` is fully green.\n\n**Step 1 — Mark completions**: For each file row, confirm every assigned reviewer phase ran\nand reported (a \"no findings\" report counts). Update **Covered?**:\n- `✓` — all assigned reviewers completed\n- `GAP` — one or more assigned reviewers did not run\n\n**Step 2 — Fill gaps**: For every `GAP` row, launch additional review passes now:\n- File with 0 reviewers completed → `/shallow-review` on that file's diff\n- HIGH- or MEDIUM-risk file with only 1 of 2 reviewers completed → `/shallow-review` on that file's diff\n\nRun all gap-fill passes in a single parallel batch, then update the checklist.\n\n**Step 3 — Gate**: Do not proceed to Phase 6 until every row in `/tmp/mega_coverage.md`\nshows `✓`. If gaps remain after one gap-fill pass, repeat Step 2.\n\n**Step 4 — Include the final checklist** in the Phase 6 report under a \"Coverage\" section.\n\n---\n\n## PHASE 6: Merge & Validate Findings\n\n### Deduplication\nSame location + same root cause = one finding. Boost confidence when found by multiple phases.\n\n### Plausibility Validation\n\nEvery finding MUST pass ALL of:\n1. **The code exists**: Point to exact file:line in the current code\n2. **The bug is achievable**: Describe a concrete input that triggers it\n3. **The result is wrong**: Explain what the code produces vs what it should produce\n4. **Tests don't catch it**: Explain why (e.g., \"tests only call the simple overload without offsets\")\n\nDiscard findings that fail any of these.\n\n### Confidence Ranking\n- **High**: Found by Phase 2 (deep review), or found by 2+ phases independently\n- **Medium**: Single phase found it, plausible trigger exists but complex to verify\n- **Low**: Pattern match suggests possible bug but trigger is speculative\n\n---\n\n## Report Format\n\n```\n## Mega-Review: [commit range / feature name]\n\n### Summary\n- [N] commits/subsystems, [M] files, [L] LOC reviewed\n- [X] bugs found: [H] high-confidence, [M] medium, [L] low\n\n### Findings (ranked by confidence)\n\n#### [HIGH] Finding 1: [precise title]\n- **Location**: file:line\n- **Found by**: Phase [N] ([audit/review type])\n- **The bug**: [what the code does wrong, precisely]\n- **Trigger**: [specific input that causes it]\n- **Expected**: [what should happen]\n- **Actual**: [what happens instead]\n- **Why tests miss it**: [explanation]\n- **Fix**: [specific code change]\n\n[... more findings ...]\n\n### Phase Coverage\n| Phase | Scope | Findings |\n|---|---|---|\n| 1: Decompose & classify | git log + stat | (coverage map) |\n| 2: Deep review | [N] HIGH+MEDIUM files | [M] bugs |\n| 3: Targeted review | HIGH+MEDIUM files, [N] foci | [M] bugs |\n| 4: Shallow review | [N] HIGH+MEDIUM commits | [M] bugs |\n| 5A: Pattern amplification | [N] patterns | [M] additional bugs |\n| 5B: Cross-cut | [checks] | [M] bugs |\n```\n\n---\n\n## Anti-Patterns (What NOT to Report)\n\n- **Style/naming issues** — Not bugs.\n- **Performance concerns** — Not bugs (unless they cause incorrect results).\n- **\"Might be wrong\" without a trigger** — If you can't describe a concrete input that causes\n  incorrect output, it's not a finding.\n- **Documentation mismatches** — Only report if the mismatch causes callers to use the API wrong.\n",".claude/skills/heatmap/SKILL.md":"---\nname: heatmap\nversion: \"1.0.0\"\ndescription: Use git heatmap analysis to identify high-churn files and lines as candidates for thorough review or bug hunting. Works for PR reviews, security audits, bug hunts, or any code analysis task.\n---\n\n# Heatmap-Guided Review\n\nUse the bundled `heatmap.py` script to identify the hottest (most frequently and recently changed) code in a repository, then focus review effort on those areas. Hot code is statistically more likely to contain bugs: it changes often, accumulates complexity, and is where active development risk concentrates.\n\n## When to use\n\nInvoke this skill whenever you want to prioritize where to look in a codebase — during PR reviews, bug hunts, security audits, onboarding exploration, or any task where you need to decide which files and lines deserve the closest attention.\n\n## Prerequisites\n\n- Python 3 must be available.\n- The target must be a git repository.\n- The heatmap script is bundled with this skill at `~/.claude/skills/heatmap/heatmap.py`. All commands below use `HEATMAP` as a placeholder:\n  ```bash\n  HEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n  ```\n  If `heatmap` is available on PATH, you may use that instead.\n\n## Workflow\n\n### Step 1: Determine the repository path and scope\n\nFigure out the git repository root. If the user provided a repo path, use that. If working in a repo already, use the current directory. If reviewing a PR, determine which files were changed.\n\n```bash\nHEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n# Find the repo root\ngit -C <path> rev-parse --show-toplevel\n```\n\n### Step 2: Run repo-level heatmap\n\nGet the hottest files in the repository. Use `--json` for machine-readable output. Adjust `--top` based on context (20-50 for a broad scan, more for large repos).\n\n```bash\npython3 \"$HEATMAP\" repo --json --top 50 <repo_path>\n```\n\nThis returns JSON array of objects with: `path`, `heat`, `commits`, `last_modified_days`.\n\n### Step 3: Cross-reference with the task context\n\n**For PR reviews:** Intersect the heatmap results with the files changed in the PR. Files that are both changed in the PR AND high on the heatmap are the highest-priority review targets — they are already complex/volatile and the PR is adding more changes to them.\n\n```bash\n# Get PR changed files\ngit diff --name-only <base_branch>...HEAD\n```\n\n**For bug hunts:** The hottest files ARE the candidates — frequent recent changes correlate with bugs. Focus on the top 10-20.\n\n**For security audits:** Filter heatmap results to security-sensitive paths (auth, crypto, input parsing, network, serialization).\n\n**For general exploration:** Use the heatmap as a map of where active development is happening.\n\n### Step 4: Run line-level heatmap on top candidates\n\nFor each high-priority file (typically 3-8 files), run the line-level heatmap to find the hottest regions within those files.\n\n```bash\npython3 \"$HEATMAP\" file --json <file_path_relative_to_repo> <repo_path>\n```\n\nThis returns JSON array of objects with: `line`, `heat`, `content`.\n\n### Step 5: Identify hot zones\n\nFrom the line-level results, identify contiguous regions of high heat. These \"hot zones\" are where to focus review. Look for:\n\n- **Clusters of hot lines** — contiguous blocks of high-heat code indicate areas under active rework. These are prime bug candidates because:\n  - Multiple recent changes suggest the logic is not yet settled\n  - Each change is an opportunity for regression\n  - Complex interactions between recent changes may not be fully tested\n\n- **Hot lines surrounded by cold code** — surgical edits in otherwise stable code may indicate bug fixes, workarounds, or special-case handling that deserves scrutiny.\n\n- **Hot function/method boundaries** — if a method signature or its first few lines are hot, the contract may have changed recently, affecting all callers.\n\n### Step 6: Produce the review focus list\n\nOutput a ranked list of review targets, structured as:\n\n```\n## Heatmap Review Targets\n\n### Priority 1: <file_path> (heat: X, commits: Y)\n- **Hot zones**: lines A-B (description of what this code does)\n- **Why it matters**: <context — e.g., \"most changed file in repo AND modified in this PR\">\n- **What to look for**: <specific guidance based on the code — race conditions, edge cases, etc.>\n\n### Priority 2: ...\n```\n\n### Step 7: Deep review\n\nFor each priority target, read the hot zones and perform the actual review. The heatmap tells you WHERE to look; your expertise tells you WHAT to look for. Common patterns in hot code:\n\n- **State management bugs**: Hot code often manages complex state. Check for inconsistent updates, missing synchronization, or partial failures.\n- **Edge cases**: Frequent changes often mean edge cases keep being discovered. Look for more.\n- **Regression risk**: If code was recently fixed, check whether the fix is complete and doesn't break other paths.\n- **Missing tests**: Hot code that lacks test coverage is the highest-risk combination.\n\n## Output format\n\nAlways present findings as a prioritized list with:\n1. File path and heat metrics\n2. Specific line ranges to focus on\n3. What the hot code does (brief)\n4. What risks to look for (specific to the code, not generic)\n\n## Tips\n\n- Heat is relative — compare files against each other, not against an absolute threshold.\n- Files with high heat but few commits have large individual changes (risky). Files with high heat and many commits are under constant churn (also risky, differently).\n- `last_modified_days` close to 0 means very recent changes — highest chance of unfound bugs.\n- Use `--since` to adjust the time window. Default is 2 years. For recent bug hunts, try `--since \"6 months ago\"`.\n- The `--no-color` flag is useful when piping output, but prefer `--json` for programmatic use.\n",".claude/skills/bug-archaeology/SKILL.md":"---\nname: bug-archaeology\nversion: \"1.0.0\"\ndescription: >\n  Mine bug patterns from any git repository. Discovers bug-fix commits via git log\n  heuristics, analyzes each in parallel with subagents, writes individual analysis files,\n  and synthesizes a generalized PATTERNS.md with repo-specific details stripped.\n  Invoke explicitly with /bug-archaeology.\n---\n\n# Bug Archaeology\n\nSystematic extraction of reusable bug-detection heuristics from a repository's commit history.\n\n## Arguments\n\nAll optional. Parse from the user's invocation string.\n\n| Arg | Default | Description |\n|-----|---------|-------------|\n| `--range` | `HEAD~200..HEAD` | Git revision range |\n| `--path` | (all files) | Restrict to commits touching this path glob |\n| `--since` / `--until` | (none) | Date filter for `git log` |\n| `--limit` | 200 | Max bug-fix commits to analyze |\n| `--batch-size` | 10 | Commits per subagent |\n| `--output` | `./bug-archaeology/` | Output directory |\n\n## Workflow\n\nThree sequential phases. Each phase completes fully before the next starts.\n\n### Phase 1: Discovery\n\nFind bug-fix commits via git log heuristics.\n\n```bash\ngit log --no-merges --pretty=format:\"%H %s\" [--since=X] [--until=X] <range> [-- <path>] \\\n  | grep -iE '(fix|bug|patch|resolve|repair|correct|workaround|hotfix|regression|#[0-9]+|[A-Z]+-[0-9]+)'\n```\n\n**Filter out** commits whose message matches ONLY cosmetic keywords (`typo`, `whitespace`, `import`, `format`, `style`, `cleanup`, `rename`) with no bug keywords.\n\n**Truncate** to `--limit`.\n\n**Write** `QUEUE.txt` to the output directory:\n```\n0001 abc123def First line of commit message\n0002 def456abc Another commit message\n```\n\n**Resumption**: If `PROGRESS.md` exists, read it and exclude commits already marked `done` or `skipped`. Re-include `pending` and `error` entries.\n\n### Phase 2: Analysis (parallelized)\n\nSpawn subagents to analyze commits in batches. Each commit is independent.\n\n**Subagent prompt template** — adapt as needed:\n```\nRead the file at references/per-bug-format.md for the output format specification.\n\nAnalyze these commits from the repository at <REPO_PATH>:\n<list of \"NNNN hash message\" lines>\n\nFor each commit:\n1. Run: git show <hash>\n2. If the commit is cosmetic, test-only, refactor-only, or a merge with no\n   original changes — mark it as skipped with a one-word reason.\n3. Otherwise, write the analysis to <OUTPUT>/bug-<NNNN>-<slug>.md\n   following the format in per-bug-format.md exactly.\n\nReturn a status line per commit: NNNN <hash> done|skipped [reason-or-filename]\n```\n\n**Parallelism**: Launch up to 5 subagent batches concurrently. Wait for all to complete before the next wave.\n\n**Progress tracking**: After each wave, append results to `PROGRESS.md`:\n```markdown\n| # | Commit | Status | File / Reason |\n|---|--------|--------|---------------|\n| 0001 | abc123d | done | bug-0001-null-after-lookup.md |\n| 0002 | def456a | skipped | cosmetic |\n```\n\n**Errors**: Mark as `error` with a one-line reason. Don't retry — the user re-invokes with `--resume`.\n\n### Phase 3: Synthesis\n\nAfter all analysis is complete, produce `PATTERNS.md`. Read `references/synthesis-format.md` for the full specification.\n\n**Process**:\n1. Read all `bug-*.md` files in the output directory\n2. Parse the `Tags` section from each — extract `category` and `code-pattern`\n3. Group bugs by `code-pattern` tag\n4. For each group of 2+ bugs with the same code-pattern:\n   - Extract the shared Detection Rule (generalize if they differ across instances)\n   - Pick the most representative Example\n5. **Generalize** — strip repo-specific details:\n   - Replace specific class/method names with structural descriptions\n   - Remove ticket IDs, author names, project-specific subsystem labels\n   - Keep language-specific API names only if scope is that language or broader\n6. Group patterns by `category` and write `PATTERNS.md`\n7. Patterns with only 1 instance go in a \"Singletons\" section at the end\n\n## Reference Files\n\n| File | Loaded by | Purpose |\n|------|-----------|---------|\n| `references/per-bug-format.md` | Subagents (Phase 2) | Per-bug output template and field guidelines |\n| `references/synthesis-format.md` | Orchestrator (Phase 3) | PATTERNS.md structure and generalization rules |\n\n## Evaluating the Skill\n\nFull instructions are in `references/EVAL-PROMPT.md`. Summary:\n\n1. **Pick a bug** from the archaeology output and trace its introducing commit via `git blame`.\n2. **Extract the patch** with `git diff ${INTRO}~1 $INTRO`.\n3. **Choose a review skill** — the user must specify one:\n   - `/shallow-review` — quick 6-specialist parallel scan, any patch size\n   - `/deep-review` — focused on specific files, complex logic\n   - `/targeted-review` — findings-driven, medium-to-large patches\n   - `/mega-review` — large feature branches or 1000+ LOC diffs\n4. **Run the chosen skill** against the extracted patch.\n5. **Score** the output: Exact / Partial / Different bug / Miss.\n6. **Prod misses** — tell the skill what it missed and ask which checklist item would have caught it; use the answer to improve that skill's reference files.\n\nTarget: >90% hit rate (exact + partial), <5% miss rate across a batch of N bugs.\n",".claude/skills/patch-explainer/SKILL.md":"---\nname: patch-explainer\nversion: \"1.0.0\"\ndescription: Deep code analysis with ASCII visualizations showing structure, flow, and state transitions. Use when analyzing patches/diffs, explaining classes or subsystems, understanding code architecture, reviewing changes for inconsistencies, or when asked to visualize how code works. Provides before/after diagrams, data/control flow, concurrency analysis, assumptions, and failure modes. Triggers on explain this patch/code/class, how does X work, show me the flow, visualize this change, code review requests, or proactive analysis during PR reviews.\n---\n\n# Patch Explainer\n\nDeeply analyze and visualize code using ASCII diagrams to reveal structure, behavior, and interactions.\n\n## What This Skill Does\n\nProvides comprehensive code analysis with rich ASCII visualizations for:\n- **Patches/diffs**: Before/after states, what changed and why\n- **Classes**: Purpose, structure, state transitions, workflows\n- **Subsystems**: Component interactions, data flow, architecture\n- **Repositories**: Overall structure, key abstractions, major patterns\n- **Code reviews**: Finding inconsistencies, analyzing assumptions and failure modes\n\n## Analysis Approach\n\n### For Any Code (Patches, Classes, Subsystems, Repositories)\n\n1. **Identify the core purpose** - What does this code do and why does it exist?\n\n2. **Create ASCII visualizations** showing:\n   - Structure (components, layers, dependencies)\n   - Behavior (data flow, control flow, state transitions)\n   - Interactions (sequence diagrams, message passing, concurrency)\n   - For patches: before/after comparisons\n\n3. **Deep reasoning** about:\n   - **Assumptions**: What must be true for this to work correctly?\n   - **Failure modes**: What could go wrong at each step?\n   - **Concurrency**: If multiple threads/processes, show their interactions\n   - **Invariants**: What must always hold true?\n\n4. **Focus on the \"why\"**:\n   - Why does this code exist?\n   - Why was this approach chosen?\n   - For changes: Why this modification? What problem does it solve?\n\n### Visualization Strategy\n\nChoose diagram types based on what you're explaining:\n\n**State machines** - When code manages states/status:\n```\n[Initial] --event--> [Processing] --success--> [Complete]\n                          |\n                       failure\n                          |\n                          v\n                      [Failed]\n```\n\n**Data flow** - When showing information movement:\n```\nInput → [Transform A] → [Transform B] → Output\n```\n\n**Sequence diagrams** - When showing component interactions:\n```\nClient          Server          Database\n  |               |                 |\n  |--request----->|                 |\n  |               |----query------->|\n  |               |<---result-------|\n  |<--response----|                 |\n```\n\n**Component structure** - When showing architecture:\n```\n┌─────────────────────┐\n│   Application       │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Service Layer     │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Data Layer        │\n└─────────────────────┘\n```\n\n**Before/after** - When explaining changes:\n```\nBEFORE                  AFTER\n─────────────────────────────────\n[A] → [B] → [C]        [A] → [Cache?] ─Yes→ [C]\n                              |\n                              No\n                              v\n                            [B] → [C]\n```\n\n### Reference Materials\n\n**ASCII diagram templates**: See [ascii_patterns.md](references/ascii_patterns.md) for:\n- State machine patterns\n- Data flow diagrams\n- Sequence diagrams\n- Component/architecture diagrams\n- Before/after comparisons\n- Concurrency patterns\n- Control flow patterns\n- Dependency graphs\n\n**Analysis methodology**: See [analysis_framework.md](references/analysis_framework.md) for:\n- Structured analysis process for patches vs existing code\n- Concurrency analysis checklist\n- Assumption identification patterns\n- Failure mode identification\n- Analysis depth guidelines by scope (function → class → subsystem → repository)\n\n## Analysis Workflow\n\n### For Patches/Diffs\n\n1. Read the patch to understand what changed\n2. Identify the change type (bug fix, feature, refactor, optimization)\n3. Create before/after ASCII diagrams showing:\n   - Old behavior vs new behavior\n   - State transitions that changed\n   - Data flow modifications\n4. Explain what fundamentally changed:\n   - What problem did the old code have?\n   - How does the new code solve it?\n   - What assumptions changed?\n5. Analyze failure modes:\n   - What could go wrong with this change?\n   - Are there edge cases not handled?\n   - Concurrency implications?\n6. Focus on the \"why\": What problem does each modification solve?\n\n### For Classes\n\n1. Read the class to understand its purpose\n2. Create ASCII diagram showing:\n   - Class structure (key fields/methods)\n   - State machine if it manages state\n   - How it fits with related classes\n3. Explain key workflows (2-3 most important methods)\n4. Identify assumptions and invariants\n5. Analyze failure modes and edge cases\n6. Focus on the \"why\": Why does this class exist? What problem does it solve?\n\n### For Subsystems\n\n1. Identify the components in the subsystem\n2. Create ASCII diagram showing:\n   - Component relationships\n   - Key interfaces/boundaries\n   - Main data flows\n3. Trace 2-3 key workflows through the subsystem\n4. Explain how components interact\n5. Identify assumptions across component boundaries\n6. Focus on the \"why\": What is this subsystem's role in the larger system?\n\n### For Repositories\n\n1. Understand the high-level architecture\n2. Create ASCII diagram showing:\n   - Major modules/packages\n   - Layered architecture\n   - Key abstractions\n3. Identify core workflows\n4. Explain main patterns used throughout\n5. Highlight critical subsystems\n6. Focus on the \"why\": What problem does this codebase solve?\n\n## Concurrency Analysis\n\nWhen analyzing concurrent code, always show:\n\n**Thread interactions**:\n```\nThread A                State                Thread B\n   |                      |                      |\n   |--lock()------------>|                      |\n   |                     [LOCKED]               |\n   |--modify()---------->|                      |\n   |--unlock()---------->|                      |\n   |                     [UNLOCKED]             |\n   |                      |<---------lock()-----|\n   |                     [LOCKED]               |\n```\n\n**Race conditions**:\n```\nThread A            Thread B\n   |                   |\n   |--read(x=10)      |\n   |                   |--read(x=10)\n   |--x=x+1           |\n   |                   |--x=x+1\n   |--write(x=11)     |\n   |                   |--write(x=11)  ⚠ Lost update!\n\nResult: x=11 (expected: x=12)\n```\n\nCheck for:\n- Shared mutable state without synchronization\n- Lock ordering violations (potential deadlocks)\n- Race conditions in read-modify-write operations\n- Missing memory barriers\n\n## Output Structure\n\nStructure your analysis as:\n\n### 1. Executive Summary\nBrief overview (2-3 sentences) of what this code does and why it matters.\n\n### 2. Visual Overview\nHigh-level ASCII diagram showing the main structure or flow.\n\n### 3. Detailed Analysis\nOrganized by aspect:\n- **Purpose**: What it does and why it exists\n- **Structure**: Components and their relationships\n- **Key Workflows**: Step-by-step execution of main scenarios\n- **State Management**: States and transitions (if applicable)\n- **Assumptions**: What must be true for correctness\n- **Failure Modes**: What could go wrong\n- **Concurrency**: Thread safety analysis (if applicable)\n\n### 4. For Patches: Before/After\n- Before state (with diagram)\n- After state (with diagram)\n- Why this change was made\n- Critical modifications explained\n\n### 5. Key Insights\nBullet points highlighting:\n- Most important findings\n- Potential issues or risks\n- Recommendations (if applicable)\n\n## Prioritization\n\nFocus on high-impact elements:\n- **Critical paths**: Main workflows that matter most\n- **High-risk code**: Concurrency, error handling, resource management\n- **Complex logic**: Non-obvious algorithms or subtle interactions\n- **Key abstractions**: Core interfaces and contracts\n\nMinimize or skip:\n- Boilerplate code\n- Simple getters/setters\n- Standard patterns done correctly\n- Low-risk trivial changes\n\n## Example Scenarios\n\n**Scenario 1**: \"Explain this patch\"\n→ Show before/after diagrams, explain what changed and why, analyze assumptions and failure modes\n\n**Scenario 2**: \"How does SafeCommandStore work?\"\n→ Show class structure, explain the exclusive access pattern, trace key methods, analyze thread safety\n\n**Scenario 3**: \"Explain the coordination subsystem\"\n→ Show component diagram, trace PreAccept→Accept→Commit flow, explain message passing, show quorum tracking\n\n**Scenario 4**: \"What's the architecture of this codebase?\"\n→ Show high-level module structure, identify key abstractions, explain main patterns, highlight critical subsystems\n\n**Scenario 5**: During code review (proactive)\n→ Analyze changes for inconsistencies, check assumptions, identify potential race conditions, verify error handling\n",".claude/skills/write-reproducer/SKILL.md":"---\nname: write-reproducer\nversion: \"1.0.0\"\ndescription: \"Write minimal, reliable bug reproducers (repros) for any project. Use when: (1) a bug report or issue needs a test that reliably demonstrates the failure, (2) converting a described failure scenario into runnable code, (3) minimizing an existing complex test to its essential trigger conditions. Covers the full repro workflow: failure characterization, scope selection, writing the repro, verifying it fails for the right reason, and minimizing to the smallest possible trigger.\"\n---\n\n# Write Bug Reproducer\n\nYour goal is to turn a bug description into a minimal, self-contained, runnable reproduction that triggers a specific, machine-checkable failure criterion.\n\nA reproducer has three parts — keep them distinct in your head and in your code:\n\n- **Trigger**: the minimum input, state, schedule, or environment that causes the bug\n- **Harness**: how the trigger is executed (test runner, script, container, cluster test)\n- **Oracle**: the machine-checkable failure criterion (assertion, exit code, log pattern, invariant violation)\n\nFollow the five phases below in order. Do not skip ahead. Write the failure criterion before writing any repro code.\n\n## Phase 1: Understand and classify\n\nRestate the bug in one sentence: \"The bug is...\"\n\nClassify along three axes:\n\n- **Bug class**: crash, incorrect output, hang/deadlock, race condition, assertion/invariant violation, performance regression, resource leak, serialization bug, consistency anomaly. See `references/bug-taxonomy.md` for the full taxonomy when classification is unclear.\n- **Scope**: pure function, module, single process, multiple processes, cluster.\n- **Determinism**: deterministic, flaky (state what makes it flaky), requires rare schedule or timing.\n\nIf the user gave only symptoms with no code, list the 2-4 most likely causes before proceeding. Do not pick one yet — write hypotheses, not conclusions.\n\nIf the user included code or pointed at a codebase, read the suspect region and identify the likely code path before moving on.\n\n## Phase 2: Define the failure criterion\n\nThis is the most important phase. Before writing any repro code, write out the oracle in one of these machine-checkable forms:\n\n- **Assertion with concrete values**: `assert expected == actual` with both spelled out\n- **Exit code**: `expected: 0, actual: 139 (SIGSEGV)`\n- **Regex against stdout/stderr**: exact string fragment to match\n- **Log grep**: file and pattern\n- **Exception type and message fragment**: the specific error and location\n- **Linearizability/isolation check result**: checker verdict (e.g., linearizability violation, cycle detected)\n- **Invariant violation**: state the invariant in one line; state what breaks it\n\nRecord the failure criterion verbatim. It will be used in Phase 4 (to write the assertion) and Phase 5 (to prevent shrinking into a different bug).\n\nWithout an explicit oracle, shrinking can produce something that \"fails\" but not in the described way, and reviewers cannot tell whether the repro is successful.\n\n## Phase 3: Detect context and choose repro form\n\nInspect the working directory for build-system markers and prefer the project's existing test framework and conventions. Explore existing tests to understand helpers, fixtures, naming patterns, and how integration tests are structured.\n\nPick the lowest tier on the minimality lattice that can reliably exhibit the failure. See `references/minimality-lattice.md` for tier definitions and decision rules.\n\n- Tier 1: expression / REPL snippet\n- Tier 2: single-file snippet with `main`\n- Tier 3: single test in the project's existing framework\n- Tier 4: multi-file project fixture\n- Tier 5: containerized environment + test script\n- Tier 6: ephemeral cluster\n- Tier 7: deterministic simulation\n\nWrite one sentence naming the tier and why, based on what you found in the project.\n\nFor concurrency bugs: `references/concurrency.md`\nFor distributed-systems bugs: `references/distributed-systems.md`\nFor invariant bugs where a property test is the natural form: `references/property-based-testing.md`\nFor bugs found by fuzzing or where a fuzz harness is the natural repro: `references/fuzzing.md`\n\n## Phase 4: Draft the repro\n\n### Structure\n\nLabel the three parts in comments:\n\n```\n// TRIGGER: <what causes the bug>\n// HARNESS: <how we run it>\n// ORACLE:  <what we check>\n```\n\nUse the project's test framework and conventions. Match existing test style. Do not introduce a new framework unless the existing one cannot express the bug.\n\n### The pass-then-invert strategy\n\nFor subtle assertion bugs where the correct behavior is easy to state but the failing test is hard to get right, use **pass-then-invert**: first write a test that *passes* on the current buggy behavior (mirroring the observed wrong output in its assertions), then invert the assertions so they encode the *correct* expectation and therefore fail on the bug. This reduces hallucinated APIs and setup errors compared to writing a failing test directly.\n\nUse pass-then-invert when:\n- The bug produces a wrong value (not a crash or exception)\n- The correct expected value is known\n- Direct \"write a failing test\" attempts keep failing for setup reasons\n\nDo not use pass-then-invert when:\n- The bug is a crash, exception, or hang — just trigger it directly\n- The oracle is an absence check (no exception, no crash) — inversion doesn't apply\n\n### Verification before presenting\n\nThe repro must compile or parse cleanly. Resolve imports against the project's actual dependencies. Do not hallucinate APIs — if unsure of a method signature, read the library source or ask.\n\nIf execution is available, run the repro and confirm the failure criterion triggers. If not, trace through the code mentally and state your confidence level.\n\n### Generating multiple candidates\n\nWhen the bug is unclear or the first attempt fails, generate 2-5 candidate repro strategies:\n- Smallest direct unit test\n- Integration test if state/config matters\n- Standalone script if no test harness is obvious\n- Property-based test if the bug is about an invariant\n- Fuzz seed / deterministic scenario for correctness bugs\n\nExecute each candidate with a timeout. Classify each result using `references/failure-classification.md`. Refine until one produces an issue-relevant failure.\n\n### Documentation\n\nThe repro must include a comment or docstring stating:\n- Issue reference and one-line bug title\n- Expected (correct) behavior\n- Actual (buggy) behavior\n- Failure criterion (verbatim from Phase 2)\n\n## Phase 5: Shrink and validate\n\n### Validate first\n\nRun the repro (or trace through it mentally) and confirm:\n1. The failure criterion from Phase 2 triggers\n2. The failure is the *described* bug, not a test setup error\n3. The failure message matches what Phase 2 specified\n\nSee `references/failure-classification.md` for how to classify test results and distinguish issue-relevant failures from setup errors.\n\n### Then shrink\n\nUse the subtraction method from `references/minimization.md`. Work through dimensions in order (cheapest first):\n1. Reduce infrastructure scale (instances, partitions, replication)\n2. Reduce data volume (items, size, batches)\n3. Remove non-default configuration\n4. Remove setup steps\n5. Replace real sleeps with controlled time or polling\n6. Simplify trigger sequence\n\nSee `references/shrinking-checklist.md` for the guardrail checklist.\n\n### Over-minimization guardrail\n\nAfter each shrinking step, re-check that the failure is still *the same failure* — same assertion, same exception type, same message fragment from Phase 2. If the failure changed, revert that step. This prevents shrinking into a different bug.\n\n### For nondeterministic bugs\n\nWrap the trigger in an N-iteration harness with a retry budget. Report the observed failure rate (e.g., \"fails 23/1000 iterations\"). Do not use sleep-based synchronization — it makes tests flaky on different hardware. Prefer event-based scheduling, explicit synchronization primitives, or deterministic simulation.\n\nAlways print and record seeds for randomized tests so failing scenarios can be replayed.\n\n## Output\n\nAlways produce:\n\n1. **Repro file(s)** with `// TRIGGER`, `// HARNESS`, `// ORACLE` comments. Correct file placement matching the project's test layout.\n2. **Status**: one of `REPRODUCED` / `CANDIDATE` / `BLOCKED`. See `references/output-contract.md` for what each status means and requires.\n3. **Run command**: the exact command to execute the repro.\n4. **Failure summary**: \"This test should fail on the current code with: `<expected failure message>`\"\n5. **For flaky bugs**: failure rate and seed.\n6. **For blocked repros**: what's missing, what was attempted, next best direction.\n\n## Hard rules\n\n- **Write the failure criterion before the repro code.** Without an explicit oracle, you cannot distinguish a successful repro from a coincidental failure. This is the single most common failure mode.\n\n- **Do not hallucinate APIs.** If unsure whether a method, class, or flag exists, read the source or ask. Hallucinated APIs are the most frequent reason LLM-generated repros fail to compile.\n\n- **Assert expected behavior, not current broken behavior.** The oracle encodes what *should* happen. The test fails because reality doesn't match.\n\n- **Do not shrink past the bug.** After every shrinking step, re-verify the failure matches Phase 2. See `references/shrinking-checklist.md`.\n\n- **Flaky repros must declare their flakiness.** A repro that reproduces 23/1000 times must say so and wrap itself in a retry loop.\n\n- **Match the project's conventions.** Use the test framework, style, and helpers that already exist. Do not introduce a new framework unless the existing one cannot express the bug.\n\n- **Do not fix the bug.** Create tests/scripts/harnesses only. Do not edit production code unless explicitly asked.\n\n- **Do not use `:latest` image tags or unpinned dependency versions.** A repro is not reproducible if its dependencies drift.\n\n- **Do not confuse setup errors with reproduced bugs.** An error in test setup is not the same as the error caused by the bug. See `references/failure-classification.md`.\n\n## When to escalate to higher tiers\n\nEscalate to Tier 5+ (containerized, cluster, deterministic simulation) when:\n\n- The bug involves two or more processes (client + server, replica + leader)\n- The bug requires a specific network condition (partition, delay, drop)\n- The bug requires clock skew or node failure scenarios\n- The bug is about isolation, linearizability, or consensus\n- The user mentions Cassandra, Kafka, or any distributed system\n\nFor these cases read `references/distributed-systems.md` before drafting.\n\n## When to use a property-based test\n\nUse a property-based test when:\n\n- The bug is about an invariant (round-trip, idempotence, commutativity, ordering, bounded sums)\n- Shrinking comes for free in the property framework\n- You want the test to serve as a regression test with seed persistence\n\nSee `references/property-based-testing.md`.\n\n## When to use a fuzz harness\n\nUse a fuzz harness when:\n\n- The bug was originally found by fuzzing and a crashing input exists\n- The input is a byte stream or structured binary format\n- A single example fails but many nearby inputs are interesting for regression\n\nSee `references/fuzzing.md`.\n","AGENTS.md":"# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n",".claude/skills/tla-plus/SKILL.md":"---\nname: tla-plus\nversion: \"1.0.0\"\ndescription: Create, run, and verify TLA+ and PlusCal formal specifications. Use for modeling distributed systems, protocols, concurrent algorithms, state machines. Can compose specs from code, find divergences between spec and implementation, spot concurrency bugs and invariant violations. Use when asked to \"write a TLA+ spec\", \"model check\", \"verify protocol\", \"find race conditions\", or \"formal verification\".\n---\n\n# TLA+ Formal Specification Skill\n\nWrite non-trivial TLA+ specifications, run the TLC model checker, and bridge the gap between formal specs and implementation code.\n\n## Setup (Run Once)\n\n```bash\nbash SKILL_DIR/scripts/setup.sh\n```\n\nThis downloads `tla2tools.jar` (v1.8.0) and verifies Java 11+. The JAR is stored at `SKILL_DIR/lib/tla2tools.jar`.\n\n## Quick Reference\n\nLoad the right reference for your task:\n\n| Task | Reference |\n|------|-----------|\n| TLA+ syntax, operators, types | [references/language.md](references/language.md) |\n| PlusCal syntax, processes, labels | [references/pluscal.md](references/pluscal.md) |\n| Distributed systems patterns | [references/patterns/distributed-systems.md](references/patterns/distributed-systems.md) |\n| Protocol specifications | [references/patterns/protocols.md](references/patterns/protocols.md) |\n| Invariants, safety, liveness | [references/patterns/invariants.md](references/patterns/invariants.md) |\n| Code ↔ spec mapping, bug finding | [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md) |\n\n**Load references on-demand** — read the ones relevant to the current task before writing any spec.\n\n## Templates\n\nStart from a template when creating a new spec:\n\n| Template | Use For |\n|----------|---------|\n| [templates/basic.tla](templates/basic.tla) | Pure TLA+ state machine |\n| [templates/pluscal.tla](templates/pluscal.tla) | PlusCal algorithm with processes |\n| [templates/distributed.tla](templates/distributed.tla) | Distributed system with messages |\n\n## Running Specs\n\n### Full Check (Recommended)\n\nTranslates PlusCal (if present), parses, and model-checks in one step:\n\n```bash\nbash SKILL_DIR/scripts/check.sh spec.tla --config spec.cfg\n```\n\n### Individual Tools\n\n```bash\n# Parse only (syntax check)\nbash SKILL_DIR/scripts/parse.sh spec.tla\n\n# Translate PlusCal to TLA+\nbash SKILL_DIR/scripts/translate.sh spec.tla -nocfg\n\n# Model check with TLC\nbash SKILL_DIR/scripts/tlc.sh spec.tla --config spec.cfg --workers auto\nbash SKILL_DIR/scripts/tlc.sh spec.tla --no-deadlock    # suppress deadlock check\n```\n\n### Direct Java Invocation\n\n```bash\nJAR=\"SKILL_DIR/lib/tla2tools.jar\"\n\n# Parse\njava -cp \"$JAR\" tla2sany.SANY spec.tla\n\n# Translate PlusCal\njava -cp \"$JAR\" pcal.trans -nocfg spec.tla\n\n# Model check\njava -cp \"$JAR\" tlc2.TLC -workers auto -config spec.cfg spec.tla\n\n# REPL\njava -cp \"$JAR\" tlc2.REPL\n\n# Dump state graph (for visualization)\njava -cp \"$JAR\" tlc2.TLC -dump dot,actionlabels,colorize states.dot spec.tla\n```\n\n## Workflow: Writing a Spec\n\n### 1. Understand the System\n\nBefore writing any TLA+:\n- Identify the **concurrent agents** (processes, nodes, threads)\n- Identify **shared mutable state** (queues, databases, locks, counters)\n- Identify **the key safety property** (\"what must never happen?\")\n- Identify **the key liveness property** (\"what must eventually happen?\")\n\n### 2. Choose PlusCal vs Pure TLA+\n\n**Use PlusCal when:**\n- The system is naturally sequential/imperative\n- You're modeling code (threads, goroutines, async tasks)\n- You need `await`, `while`, `goto` semantics\n- The audience is programmers\n\n**Use Pure TLA+ when:**\n- You need fine-grained fairness control\n- The system is naturally a state machine\n- You need interruptible/restartable actions\n- You need refinement mappings\n- A single label would need to update a variable twice\n\n### 3. Start Small, Then Expand\n\n1. Write the **simplest possible spec** that captures the core behavior\n2. Add a **type invariant** immediately\n3. Run TLC with small constants (2-3 nodes, 2-3 messages)\n4. Add **safety invariants** one at a time, running after each\n5. Add **liveness properties** with fairness\n6. Increase constants to expand coverage\n\n### 4. Config File\n\nEvery spec needs a `.cfg` file. Create one alongside the `.tla`:\n\n```\nSPECIFICATION Spec\n\n\\* Properties to check\nINVARIANT TypeInvariant\nINVARIANT Safety\n\n\\* Uncomment for liveness (slower)\n\\* PROPERTY Liveness\n\n\\* Constants\nCONSTANT\n  NumNodes = 3\n  MaxMsgs = 5\n  NULL = NULL\n\n\\* Uncomment to bound state space\n\\* CONSTRAINT StateConstraint\n\n\\* Uncomment to ignore deadlocks\n\\* CHECK_DEADLOCK FALSE\n```\n\n## Workflow: Spec From Code\n\nWhen the user has existing code and wants a spec:\n\n1. **Read the code** — understand concurrency structure, shared state, synchronization\n2. **Read** [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md)\n3. **Map constructs** — threads→processes, locks→await, channels→queues\n4. **Abstract** — don't model every line, only concurrency-relevant operations\n5. **Write spec** — start with the concurrent skeleton, add detail iteratively\n6. **Run TLC** — find deadlocks, invariant violations, liveness failures\n7. **Report** — translate any TLC error traces back to code execution paths\n\n## Workflow: Finding Bugs\n\nWhen comparing a spec to code, or looking for bugs:\n\n1. **Read** [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md)\n2. **Write a spec** modeling the suspected buggy area\n3. **Run with small constants** — TLC is exhaustive, small state space is fine\n4. **Interpret error traces** — map TLA+ state sequences to code execution paths\n5. **Check atomicity** — does the code do atomically what the spec's label does?\n6. **Check completeness** — does the code handle all `either/or` branches?\n7. **Check ordering** — does the code enforce the same happens-before relations?\n\nIf TLC finds a violation:\n- The error trace is a **concrete counterexample** — a specific sequence of events\n- Map each state in the trace to concrete code state\n- The transition that causes the violation is the bug location\n\n## Interpreting TLC Output\n\n### Success\n```\nModel checking completed. No error has been found.\n  Estimates of the probability that TLC did not check all reachable states\n  because two distinct states had the same fingerprint:\n  calculated (optimistic):  val: 0\n```\n\n### Invariant Violation\n```\nError: Invariant SafetyInvariant is violated.\nThe following behavior constitutes a counter-example:\nState 1: <Initial predicate>\n  /\\ var1 = ...\nState 2: <Action line X>\n  /\\ var1 = ... (changed values in red)\n```\n\n### Deadlock\n```\nError: Deadlock reached.\n```\n→ No process can make progress. Check `await` conditions and process completion.\n\n### Liveness Violation\n```\nError: Temporal properties were violated.\n```\n→ Check fairness settings. Add `WF_vars` or `SF_vars`. Trace may include a \"stuttering\" suffix.\n\n## Key Principles\n\n1. **Type invariants first** — catch spec bugs before checking real properties\n2. **Small constants** — 3 nodes finds most bugs; 10 nodes takes 1000× longer\n3. **Safety before liveness** — invariants are faster to check\n4. **One property at a time** — add incrementally, run after each addition\n5. **Fairness is opt-in** — TLA+ assumes everything can crash by default\n6. **`=>` with `\\A`, `/\\` with `\\E`** — never use `=>` with `\\E`\n7. **Sequences are 1-indexed** — always\n8. **Every action must specify all variables** — use `UNCHANGED` for untouched ones\n",".claude/skills/shallow-review/SKILL.md":"---\nname: shallow-review\nversion: \"1.0.0\"\ndescription: >\n  Shallow (quick) ensemble bug-finding review using 6 specialist agents in parallel. Each\n  specialist reviews the same patch through a different lens: Logic & Types, Boundaries &\n  I/O, Concurrency & State, Resources & Serialization, Absence Analysis, and API\n  Completeness. Findings are merged and deduplicated. Best for: quick first-pass review of\n  patches, triage of diffs, broad surface-level bug scan. For deeper file-focused review\n  with full pattern catalogs and codebase investigation, use the deep-review skill instead.\n---\n\n# Ensemble Code Review\n\nSix specialist agents review the same patch in parallel. Each applies Phase 0 (understand\nthe change, form hypotheses) then a focused checklist. Their findings are merged and\ndeduplicated.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n    +-------+------+---------+---------+-----------+\n    |       |      |         |         |           |\n+---v--+ +--v--+ +-v-----+ +-v------+ +v-----+ +---v-------+\n|Logic | |Bound| |Concurr| |Resource| |Absenc| | Complete. |\n|&Type | | &I/O| |&State | |& Serde | |(2-ph)| | & Contr.  |\n+--+---+ +--+--+ +---+---+ +---+----+ +--+---+ +---+-------+\n   |        |        |         |          |        |\n   +--------+--------+---------+----------+--------+\n                               |\n                    +----------v----------+\n                    |  Pass 3: Symmetry   |\n                    |  (serial, optional) |\n                    +----------+----------+\n                               |\n                    +----------v----------+\n                    |   Merge & Dedup     |\n                    |   (main agent)      |\n                    +---------------------+\n```\n\n## Quick Start\n\n1. **Identify target** — patch, diff, file, or subsystem\n2. **Launch 6 specialists** in parallel (see prompts below)\n3. **Run Pass 3 Symmetry** check (serial, after specialists complete)\n4. **Merge** findings: deduplicate, rank by confidence\n5. **Report** in unified format\n\n## Phase 0: Understand Before Checking\n\nEvery specialist runs Phase 0 BEFORE touching the checklist:\n\n1. **Summarize** the patch in 2–3 sentences (feature, fix, refactor, move?)\n2. **Hypothesize** — list 3–5 things that could go wrong with this type of change\n3. **Note** code shapes that warrant deeper investigation\n\nThis switches the review from bottom-up (checklist→code) to top-down\n(code→hypotheses→verification). The checklist then verifies and extends the hypotheses.\n\n---\n\n## The Six Specialists\n\n### 1. Logic & Types (52% of bugs)\n\n**Priority**: wrong comparisons, missing returns, wrong constants, boolean polarity, sentinel ambiguity.\n\n**Reference**: `references/general/specialists/logic.md`\n\n**Prompt**:\n```\nYou are a LOGIC specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any suspicious code shapes (control flow, comparisons, constants, sentinels).\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/logic.md`\nApply questions that match your hypotheses and code shapes. Check all 30 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 2. Boundaries & I/O (17% of bugs)\n\n**Priority**: off-by-one, integer overflow, null/bounds checks, buffer sizing, I/O completeness.\n\n**Reference**: `references/general/specialists/boundary.md`\n\n**Prompt**:\n```\nYou are a BOUNDARY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any arithmetic, indexing, range, or I/O operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/boundary.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 3. Concurrency & State (16% of bugs)\n\n**Priority**: races, TOCTOU, live-view iteration, lock ordering, state cleanup.\n\n**Reference**: `references/general/specialists/concurrency.md`\n\n**Prompt**:\n```\nYou are a CONCURRENCY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any shared state, locks, collections, lifecycle operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/concurrency.md`\nApply questions that match your hypotheses and code shapes. Check all 24 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 4. Resources & Serialization (15% of bugs)\n\n**Priority**: resource leaks, serialization mismatches, wrong metric types, background tasks, wrapper bypass.\n\n**Reference**: `references/general/specialists/resources.md`\n\n**Prompt**:\n```\nYou are a RESOURCES specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any resource allocation, serialization methods, metrics, streams.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/resources.md`\nApply questions that match your hypotheses and code shapes. Check all 26 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 5. Absence Analysis (cross-cutting)\n\n**Priority**: find what SHOULD be present but ISN'T — missing guards, cleanup, handlers, registrations.\n\n**Reference**: `references/general/specialists/absence.md`\n\n**Prompt**:\n```\nYou are an ABSENCE specialist. Your job: find bugs that are purely absent — missing\nguards, cleanup, handlers, or conditions that leave no signal in the diff.\n\nPHASE 0 — Understand the patch first:\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that SHOULD be present but might be missing.\n\nPHASE 1 — Build the search list:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/absence.md`\nFor each event in the diff matching items (a)-(q), add to your search list.\n\nPHASE 2 — Execute searches and report:\nFor each item in your search list:\n  - Use Grep and Read tools to gather evidence from the codebase\n  - If match found (remove/deregister exists): discard\n  - If no match found: report as finding\n\nReport ALL findings above a noise floor. For each: what's missing, where it should\nbe, what evidence you searched for, Confidence (High/Medium/Low).\nOr \"No absence finding\" if nothing applies.\n```\n\n### 6. API Completeness & Contracts\n\n**Priority**: missing fields, missing overrides, registration symmetry, visibility, event coverage.\n\n**Reference**: `references/general/specialists/completeness.md`\n\n**Prompt**:\n```\nYou are an API COMPLETENESS specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could be incomplete about this change.\n3. Note any new classes, new fields, new registrations, visibility changes.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/completeness.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n---\n\n## Pass 3: Cross-Path Symmetry (serial, after specialists complete)\n\n**Prompt**:\n```\nYou are a SYMMETRY specialist. For each code path modified in this patch, identify\nwhether a structurally parallel path (same class, interface, event family, version range)\nwas NOT modified. For each asymmetry:\n- Where path A was changed\n- Where parallel path B exists\n- What was changed on A that is absent on B\n- Whether the asymmetry is intentional or suspicious\n\nRead the patch: `{PATCH_PATH}`\nSearch the codebase as needed using Grep and Read.\nReport all asymmetries, Confidence High/Medium/Low.\n```\n\n---\n\n## Merge & Dedup\n\nAfter all specialists report:\n\n1. **Collect** all findings from 6 specialists + symmetry\n2. **Deduplicate** — same code location + related reasons → combine\n3. **Rank** by confidence — findings confirmed by multiple specialists rank highest\n4. **Cross-check** reinforcement:\n   - Logic + Absence at same location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Any finding flagged by 3+ specialists → treat as confirmed\n5. **3-point test** each finding:\n   - The code construct actually exists in the diff (not inferred)\n   - The bug is possible given the visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n6. **Specialist Silence Rule**: If Absence or Completeness reports nothing on a >100-line\n   diff, note: \"Consider verifying Phase 2 searches executed for registration symmetry,\n   handler coverage, and field completeness.\"\n\n---\n\n## Report Format\n\n```\n## Review: [target]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Flagged by**: [specialists]\n- **What's wrong**: [1-2 sentences]\n\n### Specialist Coverage\n- Logic: [N findings / no finding]\n- Boundary: [N findings / no finding]\n- Concurrency: [N findings / no finding]\n- Resources: [N findings / no finding]\n- Absence: [N findings / no finding]\n- Completeness: [N findings / no finding]\n- Symmetry: [N asymmetries / none]\n```\n\n## Statistical Priors\n\n| Category | Share | Specialist |\n|---|---|---|\n| Logic error in condition | 26% | Logic |\n| Wrong constant / default | 15% | Logic |\n| Missing null / bounds check | 13% | Boundary |\n| Incorrect filtering / result | 11% | Logic |\n| Race condition | 9% | Concurrency |\n| Wrong serialization | 8% | Resources |\n| State not cleaned up | 7% | Concurrency |\n| Off-by-one | 4% | Boundary |\n| Resource leak | 3% | Resources |\n\n## Reference Files\n\n### Specialist checklists (trimmed, ensemble mode)\n- `references/general/specialists/logic.md` — 30 items, Logic specialist\n- `references/general/specialists/boundary.md` — 22 items, Boundary specialist\n- `references/general/specialists/concurrency.md` — 24 items, Concurrency specialist\n- `references/general/specialists/resources.md` — 26 items, Resources specialist\n- `references/general/specialists/absence.md` — Phase 1/2 search patterns, Absence specialist\n- `references/general/specialists/completeness.md` — 22 items, Completeness specialist\n",".claude/skills/targeted-review/SKILL.md":"---\nname: targeted-review\nversion: \"1.0.0\"\ndescription: >\n  Findings-driven targeted code review. Understands the patch via patch-explainer and\n  surrounding code via codebase-analysis, then consults a catalog of bug patterns\n  (~11 categories under references/categories/). Picks only categories whose diff-signals\n  match the patch and items whose \"look for\" hints match actual code shapes, groups them\n  by review focus (function/file/feature), and spawns parallel subagents — each with a\n  tight scope and selective checklist. Use for medium-to-large patches (50-1000 LOC) as\n  a focused alternative to whole-patch ensemble or whole-file deep review. Triggers on:\n  \"review this patch/diff/change\", \"find bugs in this change\", \"scoped review\", \"what\n  could go wrong here\", \"review using findings\", or proactive PR review.\n---\n\n# Targeted Review\n\nA meta-review skill. It does not encode bug patterns directly — it orchestrates other\nskills and a categorized findings catalog into a tight, evidence-driven review.\n\n## What it does\n\n```\n                +------------------+\n                |   Input patch    |\n                +--------+---------+\n                         |\n             +-----------+-----------+\n             |                       |\n   +---------v---------+   +---------v-----------+\n   | patch-explainer   |   | codebase-analysis   |\n   | (sub-skill)       |   | (sub-skill, scoped) |\n   | what changed,     |   | invariants, callers,|\n   | flow, assumptions |   | parallel paths      |\n   +---------+---------+   +---------+-----------+\n             |                       |\n             +-----------+-----------+\n                         |\n         +---------------v----------------+\n         | Pick categories + items        |\n         | × 3-5 independent iterations  |\n         | (each draw surfaces different  |\n         |  items from the same catalog)  |\n         +---------------+----------------+\n                         |\n                +--------v---------+\n                | Pool & prioritize|\n                | (items from 2+   |\n                |  iterations →    |\n                |  higher priority)|\n                +--------+---------+\n                         |\n                +--------v---------+\n                | Group items by   |\n                | review focus     |\n                | (file/func/feat) |\n                +--------+---------+\n                         |\n            +------------+------------+\n            |            |            |\n    +-------v---+  +-----v-----+  +---v-------+\n    | review    |  | review    |  | review    |\n    | subagent  |  | subagent  |  | subagent  |\n    | scope A   |  | scope B   |  | scope C   |\n    +-------+---+  +-----+-----+  +---+-------+\n            |            |            |\n            +------------+------------+\n                         |\n                +--------v---------+\n                | Merge & report   |\n                +------------------+\n```\n\n## When to use this skill\n\n- A patch or diff is on the table for review (single commit, multi-commit branch, or staged changes)\n- The user wants more focus than `shallow-review` provides (six fixed lenses on the whole patch) but doesn't want to commit to `deep-review`'s file-by-file deep pass\n- A `*-findings/` corpus exists or the categorized catalog under `references/categories/` is sufficient — the categories alone are usable; project corpora improve coverage\n- Medium-to-large patches where dispatching focused subagents avoids overwhelming a single reviewer\n\n## When NOT to use this skill\n\n- Trivial 1-3 line changes — direct review is faster\n- Pure refactors with no behavior change — `shallow-review` symmetry pass is enough\n- The user wants a single comprehensive write-up of one file — use `deep-review` instead\n\n---\n\n## Workflow\n\nYou will go through seven phases. Phases 1a and 1b run in parallel. Phases 2-6 are sequential.\n\n### Phase 1a: Understand the patch — call the patch-explainer skill\n\nInvoke the `patch-explainer` skill on the patch. Use the Skill tool. You want patch-explainer\nto produce its standard analysis (purpose, before/after diagrams, flow, assumptions,\nfailure modes).\n\nIf the patch is already provided as a file path, point patch-explainer at it. If you only\nhave a commit ref, ask for `git show <ref>` or read it from `git diff`. For multi-commit\nbranches, it is fine to feed the cumulative diff.\n\nCapture patch-explainer's full output. You will refer to it in Phases 3-5.\n\n### Phase 1b: Understand the surroundings — call the codebase-analysis skill\n\nIn parallel with 1a, invoke the `codebase-analysis` skill in **targeted mode** on the\naffected subsystem only — not the whole repo. Pass it:\n\n- The list of files touched by the patch\n- The subsystem name if obvious (e.g., \"the journal replay subsystem\")\n- A directive to focus on: invariants, lifecycle, parallel implementations, and recent\n  bug history in the affected area\n\nYou want codebase-analysis to produce a scoped `analysis/system-analysis.md` that gives\nyou the context the patch sits inside — what the surrounding code expects, where parallel\npaths exist, what historical bugs touched this area.\n\nIf invoking the full skill is too heavy for a small patch, instead spawn a research\nsubagent with this prompt: \"Read these files: {touched files}. Summarize: (a) the\ninvariants the surrounding code maintains, (b) any parallel implementations or sibling\nclasses, (c) callers of the modified methods, (d) any recent bug-fix commits in this\narea. Under 400 words.\" This is a lighter alternative that retains the spirit of\ncodebase-analysis. Prefer the full skill when the area is unfamiliar or large.\n\n### Phase 2: Pick categories — 3-5 independent iterations\n\nCategory selection and item picking are speculative: you're making probabilistic judgments\nabout which patterns might apply, and a single pass will reliably miss some. Run **3-5\nindependent iterations** of Phases 2+3, each starting from scratch with the same patch\nand context but without looking back at what prior iterations chose. Treat each iteration\nlike a fresh read — you are more likely to notice different things each time.\n\nFor each iteration, read `references/categories/INDEX.md` — it lists all 11 categories\nwith their descriptions and diff signals in one file (~200 lines). For each category, ask:\ndoes the patch contain ANY of the diff signals listed?\n- If yes → mark as **load**\n- If no → skip\n\nTypically 3-7 categories load per iteration. If you would load more than 8, re-examine.\nIf fewer than 2, the patch is probably too small for this skill.\n\n### Phase 3: Pick items within each loaded category (one pass per iteration)\n\nWithin each iteration, read the **full** content of each loaded category file. For each\nfinding (`### F-NN: title` + body + `**Look for:** {hint}`), ask:\n\n1. Does the \"Look for\" hint match a code shape that **actually appears in this patch**?\n2. Does the patch context (from patch-explainer + codebase-analysis) make this finding\n   **plausibly applicable** — not just a keyword match?\n\nIf yes to both → keep the item.\nIf no → drop.\n\nBe selective: a category typically has 25-40 findings; keep 3-12 per category per\niteration. Repeat for all iterations before moving to Phase 3b.\n\n### Phase 3b: Pool and prioritize across iterations\n\nAfter all iterations are complete, merge the item lists:\n\n- An item selected in **2 or more iterations** is a strong candidate — mark it **priority**.\n- An item selected in only one iteration is still in scope — mark it **speculative**.\n- Discard nothing yet; let the subagents decide.\n\nThe iteration count next to an item is a confidence signal for the subagents, not a\ngate. A speculative item can still turn into a real bug; a priority item can still be\na false alarm.\n\n### Phase 4: Group items by review focus\n\nNow you have a pooled list of selected items across categories and iterations. Group them\nby **review focus** — what part of the change a single reviewer should examine. A focus\nis one of:\n\n- A specific function or method (`MyClass.replay()`)\n- A specific file or small group (`FooSerializer.java` and its sibling `FooDeserializer.java`)\n- A feature, behavior, or concept (\"the new fsync coordination\", \"the version-gated dispatch path\")\n- A specific cross-cutting concern in the patch (\"any place we read the new `dirty` flag\")\n\nAim for 2-5 foci per patch. Each focus should have **5-15 checklist items** drawn from\nacross the categories — not too few (subagent has nothing to do) and not too many\n(subagent gets overwhelmed). Include each item's priority annotation (priority /\nspeculative) so the subagent knows where to focus first.\n\nIf multiple foci would receive the same checklist item, that's fine — the same pattern\ncan apply at multiple sites. Tag each item with the category it came from so the\nsubagent knows the rationale.\n\n### Phase 5: Spawn focused review subagents\n\nFor each focus, spawn one review subagent in parallel using the Agent tool. Use the\ntemplate in `references/subagent-prompt-template.md`. The subagent prompt must contain:\n\n- The patch (path, or pasted, or ref)\n- A 100-word summary of patch-explainer's findings (relevant slice only — not the full output)\n- A 100-word summary of codebase-analysis's findings (relevant slice only)\n- The focus statement (what part of the change to review)\n- The checklist items, each with: category, priority annotation, finding text, and\n  look-for hint\n- Instructions on how to gather evidence (read source, grep, check parallel paths) and\n  what confidence to assign\n\nEach subagent should produce: a list of findings, with location, confidence, and what\nevidence was checked.\n\nRun all subagents in a single tool call (parallel). They are independent.\n\n### Phase 6: Merge and report\n\nWhen all subagents return, merge findings:\n\n1. **Deduplicate** — same code location + similar reasoning → one finding, both subagents\n   credited\n2. **Rank** by confidence — High first, then Medium, then Low\n3. **Cross-reinforce** — if a finding was raised by multiple subagents, or if multiple\n   findings cluster on the same lifecycle/state, boost confidence\n4. **Three-point check** each surviving finding:\n   - The code construct actually exists in the diff (not inferred from absence alone)\n   - The bug is plausible given the visible context (not speculative)\n   - The finding is actionable (the reader can tell what to change)\n\nUse the format in `references/report-format.md`.\n\n---\n\n## Reference files\n\n| Reference | When to read |\n|---|---|\n| `references/subagent-prompt-template.md` | Phase 5, when spawning each review subagent |\n| `references/report-format.md` | Phase 6, when merging and presenting findings |\n| `references/categories/INDEX.md` | Phase 2 — single-file scan of all category descriptions + diff signals |\n| `references/categories/<name>.md` | Phase 3 — full body of each loaded category, picked from INDEX |\n\nThe categories in `references/categories/` are project-agnostic patterns mined from real\nbug fixes across distributed-systems projects (Cassandra, Kafka, Iceberg). They describe\ngeneralized code-level shapes, not project-specific issues.\n\n## How this differs from related skills\n\n| Skill | Scope | Pattern source | Subagent dispatch |\n|---|---|---|---|\n| `shallow-review` (cassandra-edge-case-explorer) | Whole patch | 6 fixed lenses (~100 items total) | One subagent per lens, fixed |\n| `deep-review` | User-named files | 444-pattern catalog | One subagent per file, full catalog |\n| `targeted-review` (this) | Whole patch, focus-decomposed | ~11 categories (300+ findings) — selectively loaded | One subagent per focus, selectively populated checklist |\n| `mega-review` | Large branches | Orchestrates the above | Multi-pass |\n\nUse `targeted-review` when:\n- The patch spans 50-1000 LOC\n- You want to spend tokens on **what matters for THIS patch**, not on a fixed catalog\n- You have a `*-findings/` corpus or are reviewing systems-level code that benefits from\n  the curated categories\n\n## Pitfalls and guardrails\n\n- **Don't skip Phase 1.** Calling patch-explainer and codebase-analysis is what lets you\n  pick categories and items intelligently. Without that grounding, you'll loose-match\n  on keywords and overwhelm subagents.\n- **Don't look at prior iterations while picking.** The whole value of multiple iterations\n  is independent draws. If you anchor on the first iteration's selections, you get one\n  draw repeated instead of several independent ones.\n- **Don't load every category \"just in case\".** The whole value is selection. If you\n  match more than 8 categories in an iteration, you've probably been too generous.\n- **Don't pass the full catalog to subagents.** Each subagent gets only the items\n  selected for its focus. Passing all items defeats the purpose.\n- **Don't substitute findings for understanding.** A finding that \"matches a code shape\"\n  is a hypothesis to verify — the subagent confirms or refutes by reading the code, not\n  by trusting the pattern. Mark uncertain findings as Low confidence.\n- **The checklist is the menu, not the order.** A subagent should also report bugs it\n  notices that aren't on the checklist — the checklist primes attention, it doesn't cap\n  it.\n","CLAUDE.md":"# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n","tools/cqlstress-counter-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-counter-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-counter-example.yaml)","tools/cqlstress-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-example.yaml)","tools/cqlstress-insanity-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-insanity-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-insanity-example.yaml)","tools/cqlstress-lwt-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-lwt-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-lwt-example.yaml)",".claude/skills/README.md":"# Skills Skill\n\nPath: `.claude/skills/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/README.md)",".claude/skills/install.sh":"# Claude Directive: install.sh\n\nPath: `.claude/skills/install.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/install.sh)",".claude/skills/heatmap/heatmap.py":"# Claude Directive: heatmap.py\n\nPath: `.claude/skills/heatmap/heatmap.py`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/heatmap/heatmap.py)",".claude/skills/shallow-review/EVAL-PROMPT.md":"# Shallow-review Skill\n\nPath: `.claude/skills/shallow-review/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/EVAL-PROMPT.md)",".claude/skills/bug-archaeology/references/EVAL-PROMPT.md":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/EVAL-PROMPT.md)",".claude/skills/bug-archaeology/references/per-bug-format.md":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/per-bug-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/per-bug-format.md)",".claude/skills/bug-archaeology/references/synthesis-format.md":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/synthesis-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/synthesis-format.md)",".claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md)",".claude/skills/cassandra-injvm-dtest/references/classloader_guide.md":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md)",".claude/skills/cassandra-injvm-dtest/references/cluster_utils.md":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md)",".claude/skills/patch-explainer/references/analysis_framework.md":"# References Skill\n\nPath: `.claude/skills/patch-explainer/references/analysis_framework.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/analysis_framework.md)",".claude/skills/patch-explainer/references/ascii_patterns.md":"# References Skill\n\nPath: `.claude/skills/patch-explainer/references/ascii_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/ascii_patterns.md)",".claude/skills/targeted-review/references/report-format.md":"# References Skill\n\nPath: `.claude/skills/targeted-review/references/report-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/report-format.md)",".claude/skills/targeted-review/references/subagent-prompt-template.md":"# References Skill\n\nPath: `.claude/skills/targeted-review/references/subagent-prompt-template.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/subagent-prompt-template.md)",".claude/skills/tla-plus/references/language.md":"# References Skill\n\nPath: `.claude/skills/tla-plus/references/language.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/language.md)",".claude/skills/tla-plus/references/pluscal.md":"# References Skill\n\nPath: `.claude/skills/tla-plus/references/pluscal.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/pluscal.md)",".claude/skills/tla-plus/scripts/check.sh":"# Claude Directive: check.sh\n\nPath: `.claude/skills/tla-plus/scripts/check.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/check.sh)",".claude/skills/tla-plus/scripts/parse.sh":"# Claude Directive: parse.sh\n\nPath: `.claude/skills/tla-plus/scripts/parse.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/parse.sh)",".claude/skills/tla-plus/scripts/setup.sh":"# Claude Directive: setup.sh\n\nPath: `.claude/skills/tla-plus/scripts/setup.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/setup.sh)",".claude/skills/tla-plus/scripts/tlc.sh":"# Claude Directive: tlc.sh\n\nPath: `.claude/skills/tla-plus/scripts/tlc.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/tlc.sh)",".claude/skills/tla-plus/scripts/translate.sh":"# Claude Directive: translate.sh\n\nPath: `.claude/skills/tla-plus/scripts/translate.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/translate.sh)",".claude/skills/tla-plus/templates/basic.tla":"# Claude Directive: basic.tla\n\nPath: `.claude/skills/tla-plus/templates/basic.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/basic.tla)",".claude/skills/tla-plus/templates/distributed.tla":"# Claude Directive: distributed.tla\n\nPath: `.claude/skills/tla-plus/templates/distributed.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/distributed.tla)",".claude/skills/tla-plus/templates/pluscal.tla":"# Claude Directive: pluscal.tla\n\nPath: `.claude/skills/tla-plus/templates/pluscal.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/pluscal.tla)",".claude/skills/write-reproducer/references/bug-taxonomy.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/bug-taxonomy.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/bug-taxonomy.md)",".claude/skills/write-reproducer/references/concurrency.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/concurrency.md)",".claude/skills/write-reproducer/references/distributed-systems.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/distributed-systems.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/distributed-systems.md)",".claude/skills/write-reproducer/references/failure-classification.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/failure-classification.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/failure-classification.md)",".claude/skills/write-reproducer/references/fuzzing.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/fuzzing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/fuzzing.md)",".claude/skills/write-reproducer/references/minimality-lattice.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/minimality-lattice.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimality-lattice.md)",".claude/skills/write-reproducer/references/minimization.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/minimization.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimization.md)",".claude/skills/write-reproducer/references/output-contract.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/output-contract.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/output-contract.md)",".claude/skills/write-reproducer/references/property-based-testing.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/property-based-testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/property-based-testing.md)",".claude/skills/write-reproducer/references/shrinking-checklist.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/shrinking-checklist.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/shrinking-checklist.md)",".claude/skills/write-reproducer/references/test-patterns.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/test-patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/test-patterns.md)",".claude/skills/write-reproducer/scripts/detect_context.sh":"# Claude Directive: detect_context.sh\n\nPath: `.claude/skills/write-reproducer/scripts/detect_context.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/detect_context.sh)",".claude/skills/write-reproducer/scripts/shrink_text.py":"# Claude Directive: shrink_text.py\n\nPath: `.claude/skills/write-reproducer/scripts/shrink_text.py`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/shrink_text.py)",".claude/skills/write-reproducer/scripts/validate_repro.sh":"# Claude Directive: validate_repro.sh\n\nPath: `.claude/skills/write-reproducer/scripts/validate_repro.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/validate_repro.sh)",".claude/skills/deep-review/references/deep/.gitkeep":"# Claude Directive: .gitkeep\n\nPath: `.claude/skills/deep-review/references/deep/.gitkeep`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/.gitkeep)",".claude/skills/deep-review/references/deep/deep-absence-completeness.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-absence-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-absence-completeness.md)",".claude/skills/deep-review/references/deep/deep-boundary.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-boundary.md)",".claude/skills/deep-review/references/deep/deep-concurrency.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-concurrency.md)",".claude/skills/deep-review/references/deep/deep-cross-cutting.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-cross-cutting.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-cross-cutting.md)",".claude/skills/deep-review/references/deep/deep-logic.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-logic.md)",".claude/skills/deep-review/references/deep/deep-resources.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-resources.md)",".claude/skills/targeted-review/references/categories/INDEX.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/INDEX.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/INDEX.md)",".claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md)",".claude/skills/targeted-review/references/categories/boundaries-and-numbers.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md)",".claude/skills/targeted-review/references/categories/concurrency-and-locking.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/concurrency-and-locking.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/concurrency-and-locking.md)",".claude/skills/targeted-review/references/categories/conditions-and-predicates.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/conditions-and-predicates.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/conditions-and-predicates.md)",".claude/skills/targeted-review/references/categories/io-and-crash-safety.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/io-and-crash-safety.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/io-and-crash-safety.md)",".claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md)",".claude/skills/targeted-review/references/categories/null-and-type-safety.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/null-and-type-safety.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/null-and-type-safety.md)",".claude/skills/targeted-review/references/categories/refactor-aftermath.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/refactor-aftermath.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/refactor-aftermath.md)",".claude/skills/targeted-review/references/categories/serialization-and-versioning.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/serialization-and-versioning.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/serialization-and-versioning.md)",".claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md)",".claude/skills/targeted-review/references/categories/validation-and-input-handling.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/validation-and-input-handling.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/validation-and-input-handling.md)",".claude/skills/tla-plus/references/patterns/code-to-spec.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/code-to-spec.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/code-to-spec.md)",".claude/skills/tla-plus/references/patterns/distributed-systems.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/distributed-systems.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/distributed-systems.md)",".claude/skills/tla-plus/references/patterns/invariants.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/invariants.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/invariants.md)",".claude/skills/tla-plus/references/patterns/protocols.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/protocols.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/protocols.md)",".claude/skills/shallow-review/references/general/specialists/absence.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/absence.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/absence.md)",".claude/skills/shallow-review/references/general/specialists/boundary.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/boundary.md)",".claude/skills/shallow-review/references/general/specialists/completeness.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/completeness.md)",".claude/skills/shallow-review/references/general/specialists/concurrency.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/concurrency.md)",".claude/skills/shallow-review/references/general/specialists/logic.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/logic.md)",".claude/skills/shallow-review/references/general/specialists/resources.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/resources.md)"},"files":{".claude/skills/cassandra-injvm-dtest/SKILL.md":"---\nname: cassandra-injvm-dtest\nversion: \"1.0.0\"\ndescription: Comprehensive guide for writing Apache Cassandra in-JVM distributed tests (dtests). Use when creating tests that simulate multi-node Cassandra clusters within a single JVM for faster integration testing. Covers cluster creation (single-node, multi-node, multi-datacenter), configuration (all cassandra.yaml parameters, features, network topology), instance lifecycle (startup/shutdown/restart), query execution, message filtering for failure scenarios, running code on instances, ClusterUtils utilities, and debugging classloader-related issues (serialization failures, same-class-different-classloader problems).\n---\n\n# Apache Cassandra In-JVM DTest Writer\n\n## Overview\n\nWrite comprehensive distributed tests for Apache Cassandra using the in-JVM dtest framework. This framework enables multi-node cluster simulation within a single JVM using isolated classloaders, providing fast and reliable integration testing without actual network communication.\n\n## Core Concepts\n\n### Framework Architecture\n\nThe in-JVM dtest framework uses **classloader isolation** to run multiple Cassandra instances in one JVM:\n\n- **Shared ClassLoader**: Common classes (primitives, APIs, config objects, byte buffers)\n- **Per-Instance ClassLoader**: Isolated Cassandra internals (DatabaseDescriptor, singletons, all C* code)\n- **IsolatedExecutor**: Marshals serialized lambdas across classloader boundaries\n- **Message Interception**: Inter-node messaging hooked at MessagingService level (no actual networking)\n\n### Key Classes\n\n| Class | Purpose | Location |\n|-------|---------|----------|\n| `Cluster` | Main entry point for creating clusters | `org.apache.cassandra.distributed.Cluster` |\n| `AbstractCluster` | Core cluster management | `org.apache.cassandra.distributed.impl.AbstractCluster` |\n| `Instance` | Individual Cassandra node | `org.apache.cassandra.distributed.impl.Instance` |\n| `InstanceConfig` | Node configuration | `org.apache.cassandra.distributed.impl.InstanceConfig` |\n| `ClusterUtils` | Utility methods | `org.apache.cassandra.distributed.shared.ClusterUtils` |\n| `ICoordinator` | Query execution interface | API package |\n| `MessageFilters` | Message filtering/dropping | `org.apache.cassandra.distributed.impl.MessageFilters` |\n\n## Quick Start\n\n### Basic Cluster Setup\n\n```java\nimport org.apache.cassandra.distributed.Cluster;\nimport org.apache.cassandra.distributed.api.ConsistencyLevel;\n\n// Create and start a 3-node cluster\ntry (Cluster cluster = Cluster.build(3).start()) {\n    // Create keyspace\n    cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                        \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n    // Create table\n    cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n    // Execute query\n    cluster.coordinator(1).execute(\"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                                  ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n    // Read data\n    Object[][] rows = cluster.coordinator(1).execute(\n        \"SELECT * FROM test.users WHERE id = ?\",\n        ConsistencyLevel.QUORUM, 1);\n}\n```\n\n### Test Base Class Pattern\n\n```java\nimport org.apache.cassandra.distributed.test.TestBaseImpl;\n\npublic class MyDTest extends TestBaseImpl {\n    private static Cluster cluster;\n\n    @BeforeClass\n    public static void setupCluster() throws IOException {\n        cluster = init(Cluster.build(3).start(), 2); // RF=2\n    }\n\n    @AfterClass\n    public static void teardownCluster() {\n        if (cluster != null)\n            cluster.close();\n    }\n\n    @Test\n    public void testSomething() {\n        // Test implementation\n    }\n}\n```\n\n## Cluster Creation Patterns\n\n### Pattern 1: Simple Single-Node Cluster\n\n```java\nCluster cluster = Cluster.build(1).start();\n```\n\n### Pattern 2: Multi-Node Cluster with Configuration\n\n```java\nCluster cluster = Cluster.build(3)\n    .withConfig(config -> config\n        .set(\"num_tokens\", \"256\")\n        .set(\"concurrent_reads\", \"64\")\n        .set(\"concurrent_writes\", \"64\"))\n    .start();\n```\n\n### Pattern 3: Multi-Datacenter Cluster\n\n```java\nCluster cluster = builder()\n    .withRacks(2, 1, 3)  // 2 DCs, 1 rack per DC, 3 nodes per rack\n    .start();\n\n// Or with explicit DC/rack naming\nCluster cluster = builder()\n    .withDC(\"dc1\", 3)\n    .withDC(\"dc2\", 3)\n    .start();\n```\n\n### Pattern 4: Cluster with Features\n\n```java\nimport static org.apache.cassandra.distributed.api.Feature.*;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withConfig(config -> config\n        .with(GOSSIP)           // Enable gossip protocol\n        .with(NETWORK)          // Enable inter-node networking\n        .with(NATIVE_PROTOCOL)  // Enable CQL protocol\n        .with(JMX))             // Enable JMX\n    .start();\n```\n\n### Pattern 5: Custom Token Distribution\n\n```java\nimport org.apache.cassandra.distributed.api.TokenSupplier;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(3))\n    .start();\n```\n\n### Pattern 6: Dynamic Port Allocation\n\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Configuration\n\n### Available Configuration Parameters\n\nConfiguration is applied via `config.set(key, value)` or `config.with(Feature)`:\n\n#### Network Configuration\n```java\nconfig.set(\"broadcast_address\", \"127.0.0.1\")\n      .set(\"listen_address\", \"127.0.0.1\")\n      .set(\"rpc_address\", \"127.0.0.1\")\n      .set(\"storage_port\", \"7000\")\n      .set(\"native_transport_port\", \"9042\")\n      .set(\"jmx_port\", \"7199\");\n```\n\n#### Token Configuration\n```java\nconfig.set(\"num_tokens\", \"256\")\n      .set(\"initial_token\", \"0\");\n```\n\n#### Memory Configuration\n```java\nconfig.set(\"memtable_heap_space\", \"512MiB\")\n      .set(\"key_cache_size\", \"50MiB\")\n      .set(\"counter_cache_size\", \"50MiB\")\n      .set(\"row_cache_size\", \"0MiB\");\n```\n\n#### Compaction & Concurrency\n```java\nconfig.set(\"concurrent_compactors\", \"4\")\n      .set(\"concurrent_reads\", \"32\")\n      .set(\"concurrent_writes\", \"32\")\n      .set(\"concurrent_counter_writes\", \"32\");\n```\n\n#### Commitlog Configuration\n```java\nconfig.set(\"commitlog_sync\", \"periodic\")\n      .set(\"commitlog_sync_period_in_ms\", \"10000\")\n      .set(\"commitlog_segment_size\", \"32MiB\");\n```\n\n#### Authentication & Authorization\n```java\nconfig.set(\"authenticator\", \"PasswordAuthenticator\")\n      .set(\"authorizer\", \"CassandraAuthorizer\")\n      .set(\"role_manager\", \"CassandraRoleManager\");\n```\n\n#### Accord Configuration (CEP-15)\n```java\nconfig.set(\"accord.enabled\", \"true\")\n      .set(\"accord.journal_directory\", \"/path/to/journal\");\n```\n\n#### Data Directories\n```java\n// Data directories are arrays\nconfig.set(\"data_file_directories\", new String[]{\"/path/to/data\"})\n      .set(\"commitlog_directory\", \"/path/to/commitlog\")\n      .set(\"hints_directory\", \"/path/to/hints\")\n      .set(\"saved_caches_directory\", \"/path/to/saved_caches\");\n```\n\n## Instance Lifecycle Operations\n\n### Starting Instances\n\n```java\n// Start with default settings\ninstance.startup();\n\n// Start with system properties\nClusterUtils.start(instance, properties -> {\n    properties.set(RING_DELAY, \"5000\");\n    properties.set(BOOTSTRAP_SCHEMA_DELAY_MS, \"5000\");\n});\n```\n\n### Stopping Instances\n\n```java\n// Graceful shutdown (blocking)\nClusterUtils.stopUnchecked(instance);\n\n// Abrupt shutdown (simulates kill -9)\nClusterUtils.stopAbrupt(cluster, instance);\n\n// Stop all instances\nClusterUtils.stopAll(cluster);\n\n// Async shutdown\nFuture<?> shutdownFuture = instance.shutdown();\nshutdownFuture.get(); // wait for completion\n```\n\n### Restarting Instances\n\n```java\n// Simple restart\nClusterUtils.restartUnchecked(instance);\n\n// Restart with different configuration\ninstance.shutdown().get();\ninstance.config().set(\"concurrent_reads\", \"64\");\ninstance.startup();\n```\n\n### Adding Instances\n\n```java\n// Add instance with same config as existing nodes\nIInstance newInstance = ClusterUtils.addInstance(cluster);\n\n// Add instance with custom config\nIInstance newInstance = ClusterUtils.addInstance(cluster, config -> {\n    config.set(\"auto_bootstrap\", true);\n});\n\n// Add instance to specific DC/rack\nIInstance newInstance = ClusterUtils.addInstance(cluster, \"dc1\", \"rack1\", config -> {\n    config.set(\"num_tokens\", \"256\");\n});\n\n// Start the new instance\nnewInstance.startup();\n```\n\n### Replacing Instances\n\n```java\n// Replace a failed node\nIInstance replacement = ClusterUtils.replaceHostAndStart(cluster, failedInstance);\n\n// Replace with custom properties\nIInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    failedInstance,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n```\n\n## Running Code on Instances\n\n### Pattern 1: Run Without Return Value\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    StorageService.instance.forceKeyspaceFlush(\"system\");\n});\n```\n\n### Pattern 2: Get Return Value (Sync)\n\n```java\nString version = cluster.get(1).callOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\n```\n\n### Pattern 3: Get Return Value (Async)\n\n```java\nFuture<String> future = cluster.get(1).asyncCallOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\nString version = future.get();\n```\n\n### Pattern 4: Pass Parameters\n\n```java\n// Parameters must be serializable\nint result = cluster.get(1).callOnInstance(() -> {\n    // Access Cassandra internals here\n    return ClusterMetadata.current().directory.allAddresses().size();\n});\n```\n\n### Pattern 5: Instance-to-Instance Operations\n\n```java\n// Get node ID from one instance, use it on another\nint nodeId = ClusterUtils.getNodeId(cluster.get(1), cluster.get(2));\n\nNodeId id = new NodeId(nodeId);\ncluster.get(2).runOnInstance(() -> {\n    StorageService.instance.cancelInProgressSequences(id);\n});\n```\n\n## Query Execution\n\n### Basic Queries\n\n```java\n// Execute without results\ncluster.coordinator(1).execute(\n    \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n    ConsistencyLevel.QUORUM,\n    1, \"Alice\"\n);\n\n// Execute with results\nObject[][] rows = cluster.coordinator(1).execute(\n    \"SELECT * FROM test.users WHERE id = ?\",\n    ConsistencyLevel.QUORUM,\n    1\n);\n```\n\n### Using Query Results\n\n```java\nimport org.apache.cassandra.distributed.api.SimpleQueryResult;\n\nSimpleQueryResult result = cluster.coordinator(1).executeWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nwhile (result.hasNext()) {\n    Row row = result.next();\n    int id = row.getInteger(\"id\");\n    String name = row.getString(\"name\");\n    System.out.println(\"User: \" + id + \", \" + name);\n}\n```\n\n### Pagination\n\n```java\nSimpleQueryResult result = cluster.coordinator(1).executeWithPagingWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM,\n    100  // page size\n);\n```\n\n### Async Execution\n\n```java\nFuture<SimpleQueryResult> future = cluster.coordinator(1).asyncExecuteWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nSimpleQueryResult result = future.get();\n```\n\n### Query with Tracing\n\n```java\nimport java.util.UUID;\n\nUUID sessionId = UUID.randomUUID();\nSimpleQueryResult result = cluster.coordinator(1).executeWithTracingWithResult(\n    sessionId,\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\n// Query tracing info from system_traces\ncluster.coordinator(1).execute(\n    \"SELECT * FROM system_traces.sessions WHERE session_id = ?\",\n    ConsistencyLevel.ONE,\n    sessionId\n);\n```\n\n### Internal Queries (No Coordinator)\n\n```java\n// Execute directly on instance internals (bypasses coordinator)\nSimpleQueryResult result = instance.executeInternalWithResult(\n    \"SELECT * FROM system.peers WHERE peer=?\",\n    expectedPeer.config().broadcastAddress().getAddress()\n);\n```\n\n## Message Filtering for Failure Injection\n\n### Pattern 1: Drop Messages Between Nodes\n\n```java\n// Drop all mutation requests from node 1 to node 2\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop()\n    .on();\n\n// Verify timeout behavior\nassertThatThrownBy(() ->\n    cluster.coordinator(1).execute(\n        \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n        ConsistencyLevel.ALL, 1, \"Alice\"\n    )\n).isInstanceOf(WriteTimeoutException.class);\n\n// Reset filters\ncluster.filters().reset();\n```\n\n### Pattern 2: Drop All Verbs\n\n```java\ncluster.filters()\n    .allVerbs()\n    .from(1).to(2)\n    .drop()\n    .on();\n```\n\n### Pattern 3: Drop Outbound Messages\n\n```java\ncluster.filters()\n    .outbound()\n    .from(1)\n    .verbs(Verb.READ_REQ.id)\n    .drop()\n    .on();\n```\n\n### Pattern 4: Custom Message Matching\n\n```java\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .messagesMatching((from, to, message) -> {\n        // Custom logic to match specific messages\n        return message.verb() == Verb.MUTATION_REQ.id;\n    })\n    .drop()\n    .on();\n```\n\n### Pattern 5: Temporary Filter Control\n\n```java\nIMessageFilters.Filter filter = cluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop();\n\nfilter.on();  // Enable\n// ... perform operations ...\nfilter.off(); // Disable\n```\n\n## ClusterUtils Reference\n\nFor comprehensive utilities, see [references/cluster_utils.md](references/cluster_utils.md).\n\n### Most Commonly Used Methods\n\n#### Lifecycle Management\n```java\nClusterUtils.stopUnchecked(instance);\nClusterUtils.stopAbrupt(cluster, instance);\nClusterUtils.restartUnchecked(instance);\nClusterUtils.stopAll(cluster);\n```\n\n#### Instance Management\n```java\nClusterUtils.addInstance(cluster, config -> {...});\nClusterUtils.replaceHostAndStart(cluster, toReplace);\nClusterUtils.start(instance, properties -> {...});\n```\n\n#### Ring & Gossip\n```java\nClusterUtils.awaitRingJoin(cluster.get(1), newInstance);\nClusterUtils.awaitRingHealthy(cluster.get(1));\nClusterUtils.awaitGossipStatus(instance, target, \"NORMAL\");\nClusterUtils.assertInRing(instance, expectedInRing);\n```\n\n#### CMS & Metadata\n```java\nClusterUtils.waitForCMSToQuiesce(cluster);\nEpoch epoch = ClusterUtils.getCurrentEpoch(instance);\nClusterUtils.fetchLogFromCMS(instance, awaitedEpoch);\n```\n\n#### Directories & Files\n```java\nList<File> dirs = ClusterUtils.getDataDirectories(instance);\nFile commitlog = ClusterUtils.getCommitLogDirectory(instance);\nFile hints = ClusterUtils.getHintsDirectory(instance);\n```\n\n## Schema Management\n\n### Creating Keyspaces\n\n```java\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n// Multi-DC keyspace\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'NetworkTopologyStrategy', \" +\n                    \"'dc1': 2, 'dc2': 2}\");\n```\n\n### Creating Tables\n\n```java\ncluster.schemaChange(\"CREATE TABLE test.users (\" +\n                    \"id int PRIMARY KEY, \" +\n                    \"name text, \" +\n                    \"email text)\");\n\n// With clustering\ncluster.schemaChange(\"CREATE TABLE test.events (\" +\n                    \"user_id int, \" +\n                    \"event_time timestamp, \" +\n                    \"event_type text, \" +\n                    \"PRIMARY KEY (user_id, event_time)) \" +\n                    \"WITH CLUSTERING ORDER BY (event_time DESC)\");\n```\n\n### Waiting for Schema Agreement\n\n```java\n// Manual wait\ntry (Cluster.SchemaChangeMonitor monitor = cluster.new SchemaChangeMonitor()) {\n    monitor.startPolling();\n    cluster.schemaChange(\"CREATE TABLE ...\");\n    monitor.waitForCompletion();\n}\n\n// Using ClusterUtils\nClusterUtils.awaitGossipSchemaMatch(cluster);\n```\n\n## Monitoring & Observables\n\n### Log Watching\n\n```java\n// Mark position and wait for log message\nlong mark = instance.logs().mark();\n// ... perform operation ...\ninstance.logs().watchFor(mark, \"Bootstrap completed\");\n\n// Grep logs\nList<String> errors = instance.logs().grep(\"ERROR\").getResult();\n```\n\n### Nodetool Integration\n\n```java\nimport org.apache.cassandra.distributed.api.NodeToolResult;\n\nNodeToolResult result = instance.nodetoolResult(\"status\");\nresult.asserts().success();\nString output = result.getStdout();\n\n// Common nodetool commands\ninstance.nodetool(\"flush\");\ninstance.nodetool(\"repair\");\ninstance.nodetool(\"compact\");\ninstance.nodetool(\"decommission\");\n```\n\n### Ring Information\n\n```java\nimport org.apache.cassandra.distributed.shared.ClusterUtils.RingInstanceDetails;\n\nList<RingInstanceDetails> ring = ClusterUtils.ring(instance);\nfor (RingInstanceDetails details : ring) {\n    System.out.println(\"Address: \" + details.getAddress());\n    System.out.println(\"Status: \" + details.getStatus());   // Up/Down\n    System.out.println(\"State: \" + details.getState());     // Normal/Leaving/Joining\n    System.out.println(\"Token: \" + details.getToken());\n}\n```\n\n### Gossip Information\n\n```java\nMap<String, Map<String, String>> gossip = ClusterUtils.gossipInfo(instance);\nfor (Map.Entry<String, Map<String, String>> entry : gossip.entrySet()) {\n    String address = entry.getKey();\n    Map<String, String> state = entry.getValue();\n    System.out.println(address + \" -> \" + state.get(\"STATUS\"));\n}\n```\n\n## Classloader Issues & Debugging\n\n### Understanding Classloader Isolation\n\nThe in-JVM dtest framework uses multiple classloaders for isolation:\n- **Test ClassLoader**: Where your test code runs\n- **Shared ClassLoader**: Primitives, APIs, config objects\n- **Instance ClassLoaders**: Per-instance Cassandra code (isolated)\n\n### Common Classloader Issues\n\n#### Issue 1: Same Class, Different ClassLoaders\n\n**Symptom**: `ClassCastException` even though classes appear identical\n\n```java\n// WRONG - This will fail\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in test classloader\n    // Try to use token with instance internals -> ClassCastException\n});\n\n// CORRECT - Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in instance classloader\n    // Now token is in correct classloader\n});\n```\n\n#### Issue 2: Serialization Failures\n\n**Symptom**: `NotSerializableException` or `ClassNotFoundException`\n\n```java\n// WRONG - Non-serializable lambda capture\nString localVar = \"test\";\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar); // May fail if localVar isn't Serializable\n});\n\n// CORRECT - Only pass serializable primitives\nfinal String localVar = \"test\"; // String is Serializable\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar);\n});\n```\n\n**Lambdas are serialized** and transferred across classloaders. Only capture:\n- Primitives (int, long, String, etc.)\n- Serializable objects marked with `@Shared`\n- Nothing else from test classloader\n\n#### Issue 3: Static State Not Shared\n\n**Symptom**: Static fields don't reflect changes across instances\n\n```java\n// Each instance has its own DatabaseDescriptor, StorageService, etc.\n// Static state is NOT shared between instances\n\n// To coordinate across instances, use:\n// 1. CQL queries to share data\n// 2. Message passing\n// 3. Instance-specific operations\n```\n\n### Debugging Techniques\n\n#### Technique 1: Print Classloader Information\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(\"ClassLoader: \" +\n        Thread.currentThread().getContextClassLoader());\n    System.out.println(\"Token class loader: \" +\n        Token.class.getClassLoader());\n});\n```\n\n#### Technique 2: Transfer Objects Explicitly\n\n```java\nimport org.apache.cassandra.distributed.impl.IsolatedExecutor;\n\n// Transfer object to instance classloader\nSerializable transferred = instance.transfer(mySerializableObject);\n```\n\n#### Technique 3: Use @Shared and @Isolated Annotations\n\n```java\n// In your test code\nimport org.apache.cassandra.utils.Shared;\nimport org.apache.cassandra.utils.Isolated;\n\n@Shared  // Loaded in shared classloader\npublic class MySharedClass implements Serializable {\n    // Can be shared across boundaries\n}\n\n@Isolated  // Each instance gets own copy\npublic class MyIsolatedClass {\n    // Not shared\n}\n```\n\n#### Technique 4: Check Serialization\n\n```java\n// Verify object can be serialized\ntry {\n    ByteArrayOutputStream baos = new ByteArrayOutputStream();\n    ObjectOutputStream oos = new ObjectOutputStream(baos);\n    oos.writeObject(myObject);\n    oos.close();\n    System.out.println(\"Object is serializable\");\n} catch (NotSerializableException e) {\n    System.out.println(\"Object is NOT serializable: \" + e.getMessage());\n}\n```\n\n### Best Practices for Classloader Safety\n\n1. **Keep lambdas simple**: Minimize captured variables\n2. **Use primitives**: Pass int, String, long instead of complex objects\n3. **Create objects inside runOnInstance**: Don't create in test, pass to instance\n4. **Avoid static state**: Don't rely on static fields across instances\n5. **Use coordinator for data sharing**: Query data rather than passing objects\n\n## Advanced Patterns\n\n### Pattern: Pausing & Resuming CMS Operations\n\n```java\n// Pause before committing at specific epoch\nCallable<Epoch> pauseHandle = ClusterUtils.pauseBeforeCommit(\n    cmsInstance,\n    transformation -> transformation instanceof AddNode\n);\n\n// Wait for pause\nEpoch epoch = pauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseCommits(cmsInstance);\n```\n\n### Pattern: Pausing Enactment\n\n```java\n// Pause before enacting specific epoch\nCallable<Void> pauseHandle = ClusterUtils.pauseBeforeEnacting(instance, epoch);\n\n// Wait for pause\npauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseEnactment(instance);\n```\n\n### Pattern: Testing with Log Monitoring\n\n```java\nClusterUtils.runAndWaitForLogs(\n    () -> {\n        cluster.coordinator(1).execute(\"INSERT INTO test.users VALUES (1, 'Alice')\",\n                                      ConsistencyLevel.QUORUM);\n    },\n    \"Mutation applied\",\n    cluster.get(1), cluster.get(2), cluster.get(3)\n);\n```\n\n### Pattern: Custom Instance Initialization\n\n```java\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withInstanceInitializer((cl, i) -> {\n        // Custom initialization logic\n        System.out.println(\"Initializing instance \" + i);\n    })\n    .start();\n```\n\n### Pattern: Testing Node Replacement\n\n```java\n// Original node\nIInvokableInstance original = cluster.get(2);\n\n// Stop original\nClusterUtils.stopAbrupt(cluster, original);\n\n// Replace with new node\nIInvokableInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    original,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n\n// Verify replacement joined\nClusterUtils.awaitRingJoin(cluster.get(1), replacement);\n```\n\n### Pattern: Testing Decommission\n\n```java\nIInvokableInstance leaving = cluster.get(3);\n\nboolean success = ClusterUtils.decommission(leaving);\nAssert.assertTrue(\"Decommission failed\", success);\n\n// Verify node left\nClusterUtils.assertNotInRing(cluster.get(1), leaving);\n```\n\n### Pattern: Multi-DC Token Ranges\n\n```java\nList<ClusterUtils.Range> ranges = ClusterUtils.getPrimaryRanges(\n    cluster.get(1),\n    \"test\"  // keyspace\n);\n\nfor (ClusterUtils.Range range : ranges) {\n    System.out.println(\"Range: \" + range.left() + \" to \" + range.right());\n}\n```\n\n## Complete Test Examples\n\n### Example 1: Basic Read/Write Test\n\n```java\npublic class BasicReadWriteTest extends TestBaseImpl {\n    @Test\n    public void testReadWrite() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n            // Write\n            cluster.coordinator(1).execute(\n                \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n            // Read\n            Object[][] rows = cluster.coordinator(2).execute(\n                \"SELECT * FROM test.users WHERE id = ?\",\n                ConsistencyLevel.QUORUM, 1);\n\n            Assert.assertEquals(1, rows.length);\n            Assert.assertEquals(1, rows[0][0]);\n            Assert.assertEquals(\"Alice\", rows[0][1]);\n        }\n    }\n}\n```\n\n### Example 2: Testing Write Timeout with Message Filtering\n\n```java\npublic class WriteTimeoutTest extends TestBaseImpl {\n    @Test\n    public void testWriteTimeout() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 3}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY, v int)\");\n\n            // Drop mutations to node 2 and 3\n            cluster.filters().inbound()\n                .to(2, 3)\n                .verbs(Verb.MUTATION_REQ.id)\n                .drop()\n                .on();\n\n            // This should timeout (can't reach QUORUM)\n            try {\n                cluster.coordinator(1).execute(\n                    \"INSERT INTO test.data (k, v) VALUES (?, ?)\",\n                    ConsistencyLevel.QUORUM, 1, 100);\n                Assert.fail(\"Expected WriteTimeoutException\");\n            } catch (RuntimeException e) {\n                Assert.assertTrue(e.getCause() instanceof WriteTimeoutException);\n            }\n\n            cluster.filters().reset();\n        }\n    }\n}\n```\n\n### Example 3: Testing Node Addition\n\n```java\npublic class NodeAdditionTest extends TestBaseImpl {\n    @Test\n    public void testAddNode() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n            // Add and start new node\n            IInvokableInstance newNode = ClusterUtils.addInstance(cluster, config -> {\n                config.set(\"auto_bootstrap\", true);\n            });\n            newNode.startup();\n\n            // Wait for node to join\n            ClusterUtils.awaitRingJoin(cluster.get(1), newNode);\n\n            // Verify all nodes see the new node\n            ClusterUtils.assertInRing(cluster.get(1), newNode);\n            ClusterUtils.assertInRing(cluster.get(2), newNode);\n        }\n    }\n}\n```\n\n### Example 4: Running Code on Instance\n\n```java\npublic class InstanceCodeTest extends TestBaseImpl {\n    @Test\n    public void testRunOnInstance() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 1}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Insert data\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.ONE);\n\n            // Force flush on node 1\n            cluster.get(1).runOnInstance(() -> {\n                StorageService.instance.forceKeyspaceFlush(\"test\");\n            });\n\n            // Verify flush happened by checking for sstables\n            int sstableCount = cluster.get(1).callOnInstance(() -> {\n                ColumnFamilyStore cfs = Keyspace.open(\"test\")\n                                               .getColumnFamilyStore(\"data\");\n                return cfs.getLiveSSTables().size();\n            });\n\n            Assert.assertTrue(\"Expected at least one sstable\", sstableCount > 0);\n        }\n    }\n}\n```\n\n### Example 5: Multi-DC Test\n\n```java\npublic class MultiDCTest extends TestBaseImpl {\n    @Test\n    public void testMultiDC() throws IOException {\n        try (Cluster cluster = builder()\n                                  .withRacks(2, 1, 2)  // 2 DCs, 1 rack each, 2 nodes per rack\n                                  .start()) {\n\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'NetworkTopologyStrategy', \" +\n                                \"'datacenter1': 2, 'datacenter2': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Write from DC1\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.LOCAL_QUORUM);\n\n            // Read from DC2\n            Object[][] rows = cluster.coordinator(3).execute(\n                \"SELECT * FROM test.data WHERE k = 1\",\n                ConsistencyLevel.LOCAL_QUORUM);\n\n            Assert.assertEquals(1, rows.length);\n        }\n    }\n}\n```\n\n## Troubleshooting Guide\n\n### Problem: Tests are flaky or hang\n\n**Possible causes:**\n1. Schema not fully agreed before operations\n2. Insufficient timeout for async operations\n3. Message filters not properly reset\n\n**Solutions:**\n```java\n// Wait for schema agreement\nClusterUtils.awaitGossipSchemaMatch(cluster);\n\n// Use longer timeouts for operations\nfuture.get(30, TimeUnit.SECONDS);\n\n// Always reset filters in finally block\ntry {\n    cluster.filters().inbound().drop().on();\n    // test code\n} finally {\n    cluster.filters().reset();\n}\n```\n\n### Problem: ClassCastException with tokens or types\n\n**Cause:** Object created in wrong classloader\n\n**Solution:**\n```java\n// Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0);\n    // Use token here\n});\n```\n\n### Problem: NoClassDefFoundError or ClassNotFoundException\n\n**Cause:** Class not available in instance classloader\n\n**Solution:** Ensure class is in Cassandra dependencies or marked `@Shared`\n\n### Problem: Test times out waiting for ring/gossip\n\n**Cause:** Network features not enabled\n\n**Solution:**\n```java\nCluster cluster = builder()\n    .withConfig(c -> c.with(GOSSIP, NETWORK))\n    .start();\n```\n\n### Problem: Port conflicts\n\n**Cause:** Static port allocation\n\n**Solution:**\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Additional Resources\n\n- **ClusterUtils**: See [references/cluster_utils.md](references/cluster_utils.md) for exhaustive utility method documentation\n- **Advanced Patterns**: See [references/advanced_patterns.md](references/advanced_patterns.md) for CMS operations, Accord testing, and complex scenarios\n- **Classloader Deep Dive**: See [references/classloader_guide.md](references/classloader_guide.md) for detailed classloader mechanics and debugging\n",".claude/skills/deep-review/SKILL.md":"---\nname: deep-review\nversion: \"1.0.0\"\ndescription: >\n  Deep file-focused code review for correctness bugs. Unlike shallow-review which runs 6\n  specialists in parallel across the entire patch, deep-review focuses on user-specified\n  files with full pattern catalogs (500+ patterns), codebase investigation, and source-level\n  context gathering. Use when: the user specifies particular files for focused review, a\n  shallow review flagged areas that need deeper investigation, reviewing critical-path code\n  changes, examining complex serialization/lifecycle/state-machine changes. The user\n  instructs which files to focus on (typically a subset of files in the patch).\n---\n\n# Deep Code Review\n\nFocused, thorough review of user-specified files using the full 500+ pattern catalog.\nEach file is reviewed with context gathering (reading source, not just diff), codebase\nsearches, and cross-referencing against the complete pattern database.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n                    +--------v---------+\n                    | User selects     |\n                    | focus files      |\n                    +--------+---------+\n                             |\n              +--------------+--------------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 0: Context  |       | Phase 0: Context      |\n    | (read full files, |       | (read full files,     |\n    |  callers, types)  |       |  callers, types)      |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 1: Deep     |       | Phase 1: Deep         |\n    | specialist review |       | specialist review     |\n    | (full checklists) |       | (full checklists)     |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 2: Codebase |       | Phase 2: Codebase     |\n    | investigation     |       | investigation         |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n              +--------------+--------------+\n                             |\n                    +--------v---------+\n                    | Phase 3: Cross-  |\n                    | file symmetry &  |\n                    | merge findings   |\n                    +------------------+\n```\n\n## Quick Start\n\n1. **Receive patch** and user's file focus list\n2. **For each focus file**: run Phase 0 (context), Phase 1 (deep checklists), Phase 2 (search)\n3. **Cross-file symmetry** pass across all focus files\n4. **Merge & report** with confidence ranking\n\n---\n\n## Phase 0: Context Gathering (per focus file)\n\nBefore touching any checklist, deeply understand each focus file. This is the key difference\nfrom shallow review — you read the actual source, not just the diff.\n\n**Prompt template**:\n```\nRead the full source of the focus file: `{FILE_PATH}`\nRead the patch for context: `{PATCH_PATH}`\n\nFor this file, gather:\n1. CLASS HIERARCHY: What does it extend? What interfaces? Read the parent class/interface.\n2. SIBLING CLASSES: Are there parallel implementations? Read at least one sibling.\n3. CALLERS: Who calls the modified methods? How do they use return values? (grep + read)\n4. LIFECYCLE: When is this object created, used, destroyed?\n5. STATE MACHINE (if applicable): Map every state and every transition. What events are handled\n   in each state? What events are *not* handled (missing transitions)? What states are never\n   reached? Where is this state enum pattern-matched — are all states covered at every match site?\n6. INVARIANTS: Read Javadoc, assertions, and any test files for this class.\n7. SERIALIZATION: If it serializes — read serialize, deserialize, serializedSize together.\n\nOutput a structured context summary for use by the deep review phases.\n```\n\n---\n\n## Phase 1: Deep Specialist Review (per focus file)\n\nEach focus file is reviewed against the FULL domain checklists (not the trimmed shallow\nversions). The reviewer selects which domains apply based on Phase 0 context.\n\n### Domain Selection\n\nBased on Phase 0 context, load the relevant deep checklists:\n\n| File contains | Load checklist |\n|---|---|\n| Conditions, comparisons, control flow, types | `references/deep/deep-logic.md` |\n| Arithmetic, indices, ranges, ByteBuffer, I/O | `references/deep/deep-boundary.md` |\n| Shared state, locks, lifecycle, state machines | `references/deep/deep-concurrency.md` |\n| Serialization, resources, metrics, config | `references/deep/deep-resources.md` |\n| New classes, new fields, registrations | `references/deep/deep-absence-completeness.md` |\n| Refactoring, merges, shell scripts, parsing | `references/deep/deep-cross-cutting.md` |\n\nTypically 2-4 domains are relevant per file. Load all relevant ones.\n\n**Prompt template**:\n```\nYou are performing a DEEP REVIEW of: `{FILE_PATH}`\n\nCONTEXT (from Phase 0):\n{CONTEXT_SUMMARY}\n\nPATCH (the changes being reviewed):\nRead: `{PATCH_PATH}`\n\nCHECKLISTS (load each relevant one):\nRead: `{SKILL_DIR}/references/deep/deep-logic.md`\nRead: `{SKILL_DIR}/references/deep/deep-boundary.md`\n[... load relevant domains ...]\n\nFor EVERY checklist item that could apply to this file:\n1. Check whether the pattern exists in the code\n2. If the pattern matches: search the codebase for confirming/refuting evidence\n3. Rate confidence: High (confirmed by evidence), Medium (pattern matches but\n   uncertain), Low (possible but speculative)\n\nReport ALL findings. For each:\n- Pattern ID and name\n- Location (file:line)\n- Confidence (High/Medium/Low)\n- What's wrong (2-3 sentences with reasoning)\n- Evidence gathered (what you searched for, what you found/didn't find)\n- Suggested fix\n\nOr \"No finding in this domain for this file\" if nothing applies.\n```\n\n---\n\n## Phase 2: Codebase Investigation (per focus file)\n\nFor each finding from Phase 1, and for absence/completeness patterns, execute targeted\ncodebase searches.\n\n**Search patterns to execute:**\n\n### For new fields:\n```bash\ngrep -rn \"serialize\\|deserialize\\|serializedSize\\|equals\\|hashCode\\|toString\" {FILE_DIR}/\n```\n\n### For new registrations:\n```bash\ngrep -rn \"addListener\\|register\\|subscribe\\|addMetric\\|removeSensor\\|deregister\" {FILE_DIR}/\n```\n\n### For new enum constants:\n```bash\ngrep -rn \"switch.*{ENUM_TYPE}\\|case.*{CONSTANT}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For interface implementations:\n```bash\ngrep -rn \"implements {INTERFACE}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For method callers:\n```bash\ngrep -rn \"{METHOD_NAME}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For parallel paths:\n```bash\ngrep -rn \"class.*extends.*{PARENT_CLASS}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n**Prompt template**:\n```\nYou are investigating findings from the deep review of: `{FILE_PATH}`\n\nFINDINGS TO INVESTIGATE:\n{PHASE_1_FINDINGS}\n\nFor each finding:\n1. Execute the relevant codebase searches (grep, read files)\n2. Confirm or refute the finding based on evidence\n3. If confirmed: search for additional instances of the same pattern\n4. If refuted: explain why with evidence\n\nFor absence patterns:\n1. Build the search list from the diff events\n2. Execute each search\n3. If no match found: report as confirmed finding\n4. If match found: report as refuted (the symmetric code exists)\n\nReport updated findings with evidence.\n```\n\n---\n\n## Phase 3: Cross-File Symmetry & Merge\n\nAfter all focus files are reviewed:\n\n**Prompt template**:\n```\nReview findings across all focus files for cross-file patterns:\n\n1. CROSS-FILE SYMMETRY: For each change in file A, is there a structurally parallel\n   change needed in file B? Check:\n   - Serialization families (if serialize changed, did deserialize change?)\n   - Interface implementations (if one implementation changed, do siblings need it?)\n   - Version-gated paths (if one version branch changed, do others?)\n   - Test coverage (does the test file cover the changed behavior?)\n\n2. FINDING REINFORCEMENT: Do findings across files reinforce each other?\n   - Logic + Absence at same conceptual location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Pattern flagged in multiple files → likely systematic issue\n\n3. MERGE & DEDUP: Combine all findings, deduplicate, rank.\n\n4. THREE-POINT TEST each finding:\n   - The code construct actually exists (not inferred)\n   - The bug is possible given visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n```\n\n---\n\n## Report Format\n\n```\n## Deep Review: [target]\n\n### Focus Files\n- `path/to/File1.java` — [brief description of changes]\n- `path/to/File2.java` — [brief description of changes]\n\n### Context Summary\n[Key facts from Phase 0: class hierarchy, lifecycle, shared state, invariants]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Domain**: [Logic / Boundary / Concurrency / Resources / Absence / Completeness]\n- **Pattern**: [pattern name from checklist]\n- **What's wrong**: [2-3 sentences with reasoning]\n- **Evidence**: [what was searched, what was found]\n- **Suggested fix**: [specific change]\n\n#### Finding 2: ...\n\n### Domain Coverage (per file)\n| File | Logic | Boundary | Concurrency | Resources | Absence | Completeness |\n|---|---|---|---|---|---|---|\n| File1.java | 2 findings | - | 1 finding | - | checked | checked |\n| File2.java | - | 1 finding | - | 3 findings | checked | checked |\n\n### Cross-File Symmetry\n- [Any asymmetries found]\n- [Any reinforcing patterns]\n```\n\n---\n\n## Reference Files\n\n### Deep specialist checklists\n- `references/deep/deep-logic.md` — Full logic, types, constants, filtering patterns\n- `references/deep/deep-boundary.md` — Full boundary, overflow, null, I/O patterns\n- `references/deep/deep-concurrency.md` — Full concurrency, state, lifecycle patterns\n- `references/deep/deep-resources.md` — Full serialization, resource, crash-safety patterns\n- `references/deep/deep-absence-completeness.md` — Full absence + completeness with search methodology\n- `references/deep/deep-cross-cutting.md` — Refactoring, parsing, platform, dispatch patterns\n",".claude/skills/mega-review/SKILL.md":"---\nname: mega-review\nversion: \"1.0.0\"\ndescription: >\n  Multi-pass deep code review for large patches (1000+ LOC) that maximizes real bug detection.\n  Orchestrates targeted-review, shallow-review, and deep-review in parallel across all HIGH and\n  MEDIUM risk files and commits: understands the feature holistically, splits by file and commit,\n  runs deep review on every HIGH/MEDIUM file, targeted review across the same scope, and\n  per-commit shallow review, followed by cross-cut consistency checks. Use when: reviewing a\n  large patch (feature branch, multi-commit, or single large diff, 1000+ LOC), doing a thorough\n  pre-merge review, or when shallower reviews miss bugs due to patch size. Triggers on: \"review\n  this branch\", \"review these commits\", \"review this feature\", \"mega review\", \"thorough review\",\n  \"full review of X commits\", or when the user specifies a commit range or feature for review.\n---\n\n# Mega-Review: Multi-Pass Large Patch Review\n\nThis skill orchestrates `/targeted-review`, `/shallow-review`, and `/deep-review` with\ncross-cut consistency checks to maximize bug detection on large patches (1000+ LOC). The input\ncan be a commit range, a feature branch, or any large diff — it does not have to span multiple\ncommits.\n\n**You MUST invoke `/targeted-review`, `/shallow-review`, and `/deep-review` as part of this\nworkflow.** Those skills have specialist checklists, pattern catalogs, and structured review\nprocesses that this skill does not duplicate. This skill's job is to understand the change\nholistically, decompose it into reviewable chunks, and delegate the actual code review to the\nappropriate sub-skills at the right granularity.\n\n## Why This Exists\n\nA single pass of `/shallow-review` over 7000 LOC spreads attention too thin. Real bugs hide in:\n- **Offset arithmetic** that works for the simple case but breaks when offset params are added\n- **Variable lifecycle issues** where a loop modifies a variable but the final operation needs the original\n- **Cross-cut inconsistencies** where fixes or refactors in one subsystem introduce bugs in another\n- **Algorithmic boundary conditions** in new data structure code\n\nThe key insight: some bugs are findable by mechanical checking (every System.arraycopy, every\nvariable swap), while others require deep understanding. This skill does BOTH.\n\n## Architecture\n\n```\n+---------------------+\n| PHASE 1: Decompose  |\n|   & Classify        |    Produce decomposition map + coverage checklist.\n+----------+----------+\n           |\n    +-------+--------+----------+\n    |                |           |\n+---v----+   +-------v------+  +-v-----------+\n|PHASE 2 |   |   PHASE 3    |  |   PHASE 4   |\n|Deep    |   |  Targeted    |  |  Shallow    |\n|Review  |   |  Review      |  |  Review     |\n|(HIGH + |   | (HIGH +      |  | (HIGH +     |\n| MEDIUM |   |  MEDIUM      |  |  MEDIUM     |\n| files) |   |  files)      |  |  commits)   |\n+---+----+   +-------+------+  +-+-----------+\n    |                |            |\n    +----------------+------------+\n                     |\n          +----------v----------+\n          | PHASE 5: Cross-Cut  |    Cross-commit/cross-subsystem consistency, pattern\n          | Passes              |    amplification, and fix verification checks.\n          +----------+----------+    One subagent per pass type (5A / 5B / 5C).\n                     |\n          +----------v----------+\n          | PHASE 6: Merge &    |    Deduplicate, verify plausibility, rank.\n          | Validate            |    Combine findings from ALL phases.\n          +---------------------+\n```\n\n---\n\n## Chunking Strategy\n\nThis skill's core principle: **the orchestrator holds global state; subagents hold only their\nslice.** A large patch reviewed by a single agent suffers attention dilution — its context fills\nwith earlier files, earlier findings, and earlier grep output, and it starts missing things. The\nfix is to reset context at every subagent boundary.\n\n### Orchestrator responsibilities\n- Holds the full patch, decomposition map, and accumulated findings from all phases\n- Before spawning each subagent, assembles a **briefing packet**: the chunk + a tight 100–200\n  word context summary written by the orchestrator\n- After each subagent returns, integrates findings into the global picture\n\n### What each subagent receives\n- **Its chunk**: the diff for its commit / grep hits for its audit type / file diff for its deep pass\n- **Orchestrator context**: subsystem name, risk level, what the code is trying to do (one paragraph)\n- **Focused task**: exactly what to look for and why — not a generic \"find bugs\"\n- **Relevant prior findings only**: findings from earlier phases that touch THIS chunk's files,\n  not the full findings list from all files\n\n### What each subagent does\nEach subagent **invokes a review skill** on its chunk — it is not a generic agent. The skill\ndetermines the review depth and structure. The chunk is the scope; the briefing packet is the\ncontext. Subagents may read additional source files, grep for callers, or check sibling classes\nto inform the review, but must not receive the full patch as input — that defeats the purpose.\n\n### Chunk boundaries by phase\n\n| Phase | Chunk unit | Skill to invoke | What the subagent receives |\n|---|---|---|---|\n| 2 (Deep) | One HIGH or MEDIUM file | `/deep-review` | That file's diff + full current source |\n| 3 (Targeted) | All HIGH + MEDIUM files as a group | `/targeted-review` | Diff for those files + Phase 1 risk classification |\n| 4 (Shallow) | One HIGH or MEDIUM commit | `/shallow-review` | That commit's diff only |\n| 5 (Cross-cut) | One pass type (5A / 5B / 5C) | inline only — no sub-skill | Finding list relevant to that pass + grep targets |\n\n**Phases 2, 3, and 4 run in parallel** — launch all their subagents in a single message after Phase 1 completes. Do not wait for Phase 2 before starting Phase 3 or 4.\n\n---\n\n## PHASE 1: Decompose & Classify\n\n**This phase is done inline — no sub-skill invocation.** Its job is to produce a decomposition\nmap and coverage checklist fast, then immediately hand off to the parallel Phases 2/3/4.\nEvery minute spent in Phase 1 is a minute not spent finding bugs.\n\n**Determining the input scope** — two modes depending on what the user provided:\n\n*Mode A — git boundary given* (commit range, branch, or single SHA): proceed directly to\nStep 1a.\n\n*Mode B — no git boundary* (user describes a feature, subsystem, or set of files without\nspecifying a range):\n1. Discover candidate files via grep or directory inspection:\n   ```bash\n   grep -rl \"<keyword>\" src/ | grep '\\.java$' | sort > /tmp/file_list.txt\n   # or: find src/java/org/apache/cassandra/<package> -name '*.java' | sort\n   ```\n2. **Show the list to the user and ask for confirmation** before going further — file count,\n   file names, anything obviously missing or out of scope. Do not skip this step.\n3. Produce a working diff against a sensible base (usually `main`):\n   ```bash\n   git diff main -- $(cat /tmp/file_list.txt | tr '\\n' ' ') > /tmp/mega_review.diff\n   # For files with no git history (new/untracked), read them directly — there is no diff.\n   ```\n4. Use this confirmed file list as the direct seed for the coverage checklist in Step 1e —\n   paste the files into the `File` column verbatim.\n5. In Phase 4, there are no commit boundaries: chunk by **file** instead of by commit —\n   one `/shallow-review` invocation per file. Skip Step 1a and go straight to Step 1b.\n\n**Step 1a — Get commit shape:**\n```bash\ngit log --oneline --stat <base>..<head>\n# Or for a single commit: git show --stat <SHA>\n```\n\n**Step 1b — Skim diff stats (do NOT read file bodies):**\n```bash\ngit diff <base>..<head> --stat\n# What to note: file names, extension types, rough LOC changes, new vs modified files\n```\n\n**Step 1c — Classify each commit/subsystem** by risk:\n- **HIGH**: New algorithms, data structure rewrites, complex feature additions, new orchestration layers, state machine changes, bootstrap/recovery logic\n- **MEDIUM**: Feature additions with new control flow, non-trivial interface changes with multiple callers\n- **LOW**: Renames, moves, mechanical refactors, test-only or documentation changes\n\n**Step 1d — Classify each source file** by type:\n- **Algorithmic**: Array operations, tree traversals, binary search, merges, set operations\n- **State machine**: Bootstrap, recovery, catchup, topology, lifecycle management\n- **Wiring**: Delegation, API changes, parameter threading\n- **Concurrency**: Shared state, synchronization\n- **Documentation/Config**: Markdown, YAML, config files, skill definitions\n\n**Step 1e — Write `/tmp/mega_coverage.md`** (the coverage checklist). Every changed non-test\nfile gets one row; pre-assign reviewers now based on risk:\n\n```markdown\n| File | LOC changed | Risk | Type | Assigned reviewers | Min required | Covered? |\n|------|-------------|------|------|--------------------|--------------|----------|\n| src/Foo.java | 320 | HIGH | Algorithmic | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| src/Bar.java | 45 | MEDIUM | Wiring | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| docs/SKILL.md | 18 | LOW | Documentation | Phase 4 (sha: def456) | 1 | — |\n```\n\nAssignment rules:\n- **HIGH-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **MEDIUM-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **LOW-risk file** → Phase 4 (shallow) — min 1\n\n**Step 1f — IMMEDIATELY start Phases 2, 3, and 4.** Do not pause to write analysis. Do not\ninvoke patch-explainer or any other sub-skill. The coverage checklist IS the Phase 1 output.\nIn the same response, spawn all Phase 2/3/4 subagents — see \"Launching Phases 2/3/4\" below.\n\n---\n\n## PHASE 2: Deep Review — invoke `/deep-review`\n\nFor every HIGH- and MEDIUM-risk file, invoke `/deep-review` scoped to that file. Each file\ngets a **separate, fresh subagent** — they run in parallel and share no context with each other.\nThis phase runs **in parallel with Phases 3 and 4** — start it as soon as Phase 1 completes.\n\n**Per-file input packet** (what the orchestrator provides to each `/deep-review` invocation):\n- The diff for that file only: `git diff <base>..<head> -- <file>`\n- The file's full current source (deep-review reads this itself, but point it at the right file)\n- A 100–150 word orchestrator briefing:\n  - File classification (algorithmic / state machine / wiring / concurrency)\n  - What the file does in the context of the overall change (1–2 sentences from Phase 1)\n  - Risk level and why it was classified HIGH or MEDIUM\n\n---\n\n## PHASE 3: Targeted Review — invoke `/targeted-review`\n\nInvoke the `/targeted-review` skill scoped to **all HIGH- and MEDIUM-risk files** identified\nin Phase 1 — not the full patch. Targeted-review is designed for focused review: it picks only\nthe bug-pattern categories whose diff signals match, then spawns tight subagents per focus area.\nFeeding it the full patch dilutes that focus; feeding it the files that matter most lets it go\ndeep where it counts.\n\n**Selecting the scope**:\n- Include all files classified HIGH- or MEDIUM-risk in Phase 1\n- Include files touched in multiple commits (cross-commit modification from the decomposition map)\n- Exclude LOW-risk files, test-only files, and pure documentation/config changes\n\n**When invoking `/targeted-review`**:\n- Pass only the diff for the selected files (not the full patch)\n- Include the Phase 1 risk classification and file-type notes as context so targeted-review\n  subagents understand what to focus on\n\nThis phase runs **in parallel with Phases 2 and 4** — start it as soon as Phase 1 completes.\nCollect all findings and tag each with `Phase 3 (targeted-review)` and its subagent focus.\n\n---\n\n## PHASE 4: Per-Commit Shallow Reviews — invoke `/shallow-review`\n\nFor each HIGH- and MEDIUM-risk commit, invoke `/shallow-review` scoped to that commit's diff.\nEach invocation is a **fresh subagent** — it receives only that commit's diff, not the full\npatch or accumulated findings from other commits.\n\nThis phase runs **in parallel with Phases 2 and 3** — start it as soon as Phase 1 completes.\n\n**Step 4a**: Extract per-commit diff to its own file:\n```bash\ngit diff <SHA>~1..<SHA> > /tmp/patch_<SHA>.diff\n```\n\n**Step 4b**: Assemble a briefing packet for `/shallow-review` containing ONLY:\n- The commit's diff (`/tmp/patch_<SHA>.diff`)\n- A 100–150 word orchestrator briefing covering:\n  - What category the commit is (algorithmic, state machine, wiring, concurrency)\n  - What risk level (HIGH/MEDIUM) and why\n  - For \"Fix\" commits: \"This commit says 'Fix X' — verify the fix is correct, complete,\n    and does not introduce new bugs. Fix commits have a higher-than-average bug rate.\"\n\n**Step 4c**: Run all HIGH- and MEDIUM-risk commit reviews in a single parallel batch. Collect\nfindings and tag each with the commit SHA.\n\n---\n\n## PHASE 5: Cross-Cut Passes\n\n**Dispatch 5A, 5B, and 5C as parallel subagents.** Each receives a focused slice of findings\nand a targeted task — not the full findings dump from all prior phases. The orchestrator\npre-filters: each subagent receives only the findings relevant to its pass.\n\n### 5A: Pattern Amplification\n\nPatterns come entirely from **bugs actually found in Phases 2–4** — there is no pre-loaded catalog.\nIf Phases 2–4 found zero bugs, 5A is skipped.\n\n**Orchestrator's job** (done before spawning anything):\n1. Collect all findings from Phases 2–4\n2. For each distinct bug, characterize the structural pattern — not the specific instance, but\n   the general shape: e.g. \"method accepts a `start` offset parameter, but an internal\n   `arraycopy` call ignores it and uses hardcoded `0`\"\n3. Decide the search scope based on the pattern type:\n   - **Patch-only** — pattern is structural and specific to new code introduced in this PR\n     (new algorithm, new data structure, new method overload family). Unlikely to exist elsewhere.\n   - **Codebase-wide** — pattern is a convention violation or contract bug that could affect\n     any code following the same convention (serialization encoding, API return value contracts,\n     lifecycle protocols, error code handling). The same mistake recurs wherever the convention\n     is followed, including in code not touched by this PR.\n4. Grep at the chosen scope for locations that could match the pattern shape\n5. Spawn one subagent per pattern, passing it: the pattern description + the grep hits + the\n   scope used (so it knows whether to look beyond the patch if it finds new leads)\n\n**Each subagent's job**: verify whether each grep hit is actually the same bug — read the\nsurrounding source as needed. Report confirmed additional instances only.\n\nOne confirmed bug → one pattern → potentially many additional instances found. This is the\nhighest-yield step when Phases 2–4 produce findings.\n\n### 5B: Cross-Commit/Cross-Subsystem Consistency\n\n**Subagent input**: The decomposition map from Phase 1 (file list, method signatures changed,\nrename list) + the list of caller sites extracted by the orchestrator. Not the full patch.\n\n1. **Interface contracts**: For each changed method signature, verify ALL callers updated\n2. **Rename completeness**: `grep` for old names that should no longer appear\n3. **Assumption conflicts**: When one part of the patch assumes X and another assumes Y about the same state\n\n### 5C: Fix Verification\n\n**Subagent input**: One subagent per \"Fix\" commit. Each receives: that commit's diff only +\na one-paragraph description of the bug it claims to fix.\n\nFor each fix commit:\n1. Read the fix carefully\n2. Try to construct an input that would still trigger the original bug\n3. Try to construct an input that triggers a new bug introduced by the fix\n\n### 5D: Optional Additional Review Passes\n\nIf Phases 2–5C revealed areas not yet covered, run additional targeted passes:\n\n- If 5A found a pattern class in files not yet reviewed → `/deep-review` on those files with\n  the specific pattern as focus guidance\n- If 5B found cross-cut inconsistencies in files not yet reviewed → `/shallow-review` on the\n  combined diff of those files\n- If a fix commit (5C) looks suspicious → `/deep-review` on that file with guidance:\n  \"Verify this fix is correct and does not introduce new bugs.\"\n\n---\n\n## Coverage Gate — Verify Before Phase 6\n\nBefore merging findings, verify `/tmp/mega_coverage.md` is fully green.\n\n**Step 1 — Mark completions**: For each file row, confirm every assigned reviewer phase ran\nand reported (a \"no findings\" report counts). Update **Covered?**:\n- `✓` — all assigned reviewers completed\n- `GAP` — one or more assigned reviewers did not run\n\n**Step 2 — Fill gaps**: For every `GAP` row, launch additional review passes now:\n- File with 0 reviewers completed → `/shallow-review` on that file's diff\n- HIGH- or MEDIUM-risk file with only 1 of 2 reviewers completed → `/shallow-review` on that file's diff\n\nRun all gap-fill passes in a single parallel batch, then update the checklist.\n\n**Step 3 — Gate**: Do not proceed to Phase 6 until every row in `/tmp/mega_coverage.md`\nshows `✓`. If gaps remain after one gap-fill pass, repeat Step 2.\n\n**Step 4 — Include the final checklist** in the Phase 6 report under a \"Coverage\" section.\n\n---\n\n## PHASE 6: Merge & Validate Findings\n\n### Deduplication\nSame location + same root cause = one finding. Boost confidence when found by multiple phases.\n\n### Plausibility Validation\n\nEvery finding MUST pass ALL of:\n1. **The code exists**: Point to exact file:line in the current code\n2. **The bug is achievable**: Describe a concrete input that triggers it\n3. **The result is wrong**: Explain what the code produces vs what it should produce\n4. **Tests don't catch it**: Explain why (e.g., \"tests only call the simple overload without offsets\")\n\nDiscard findings that fail any of these.\n\n### Confidence Ranking\n- **High**: Found by Phase 2 (deep review), or found by 2+ phases independently\n- **Medium**: Single phase found it, plausible trigger exists but complex to verify\n- **Low**: Pattern match suggests possible bug but trigger is speculative\n\n---\n\n## Report Format\n\n```\n## Mega-Review: [commit range / feature name]\n\n### Summary\n- [N] commits/subsystems, [M] files, [L] LOC reviewed\n- [X] bugs found: [H] high-confidence, [M] medium, [L] low\n\n### Findings (ranked by confidence)\n\n#### [HIGH] Finding 1: [precise title]\n- **Location**: file:line\n- **Found by**: Phase [N] ([audit/review type])\n- **The bug**: [what the code does wrong, precisely]\n- **Trigger**: [specific input that causes it]\n- **Expected**: [what should happen]\n- **Actual**: [what happens instead]\n- **Why tests miss it**: [explanation]\n- **Fix**: [specific code change]\n\n[... more findings ...]\n\n### Phase Coverage\n| Phase | Scope | Findings |\n|---|---|---|\n| 1: Decompose & classify | git log + stat | (coverage map) |\n| 2: Deep review | [N] HIGH+MEDIUM files | [M] bugs |\n| 3: Targeted review | HIGH+MEDIUM files, [N] foci | [M] bugs |\n| 4: Shallow review | [N] HIGH+MEDIUM commits | [M] bugs |\n| 5A: Pattern amplification | [N] patterns | [M] additional bugs |\n| 5B: Cross-cut | [checks] | [M] bugs |\n```\n\n---\n\n## Anti-Patterns (What NOT to Report)\n\n- **Style/naming issues** — Not bugs.\n- **Performance concerns** — Not bugs (unless they cause incorrect results).\n- **\"Might be wrong\" without a trigger** — If you can't describe a concrete input that causes\n  incorrect output, it's not a finding.\n- **Documentation mismatches** — Only report if the mismatch causes callers to use the API wrong.\n",".claude/skills/heatmap/SKILL.md":"---\nname: heatmap\nversion: \"1.0.0\"\ndescription: Use git heatmap analysis to identify high-churn files and lines as candidates for thorough review or bug hunting. Works for PR reviews, security audits, bug hunts, or any code analysis task.\n---\n\n# Heatmap-Guided Review\n\nUse the bundled `heatmap.py` script to identify the hottest (most frequently and recently changed) code in a repository, then focus review effort on those areas. Hot code is statistically more likely to contain bugs: it changes often, accumulates complexity, and is where active development risk concentrates.\n\n## When to use\n\nInvoke this skill whenever you want to prioritize where to look in a codebase — during PR reviews, bug hunts, security audits, onboarding exploration, or any task where you need to decide which files and lines deserve the closest attention.\n\n## Prerequisites\n\n- Python 3 must be available.\n- The target must be a git repository.\n- The heatmap script is bundled with this skill at `~/.claude/skills/heatmap/heatmap.py`. All commands below use `HEATMAP` as a placeholder:\n  ```bash\n  HEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n  ```\n  If `heatmap` is available on PATH, you may use that instead.\n\n## Workflow\n\n### Step 1: Determine the repository path and scope\n\nFigure out the git repository root. If the user provided a repo path, use that. If working in a repo already, use the current directory. If reviewing a PR, determine which files were changed.\n\n```bash\nHEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n# Find the repo root\ngit -C <path> rev-parse --show-toplevel\n```\n\n### Step 2: Run repo-level heatmap\n\nGet the hottest files in the repository. Use `--json` for machine-readable output. Adjust `--top` based on context (20-50 for a broad scan, more for large repos).\n\n```bash\npython3 \"$HEATMAP\" repo --json --top 50 <repo_path>\n```\n\nThis returns JSON array of objects with: `path`, `heat`, `commits`, `last_modified_days`.\n\n### Step 3: Cross-reference with the task context\n\n**For PR reviews:** Intersect the heatmap results with the files changed in the PR. Files that are both changed in the PR AND high on the heatmap are the highest-priority review targets — they are already complex/volatile and the PR is adding more changes to them.\n\n```bash\n# Get PR changed files\ngit diff --name-only <base_branch>...HEAD\n```\n\n**For bug hunts:** The hottest files ARE the candidates — frequent recent changes correlate with bugs. Focus on the top 10-20.\n\n**For security audits:** Filter heatmap results to security-sensitive paths (auth, crypto, input parsing, network, serialization).\n\n**For general exploration:** Use the heatmap as a map of where active development is happening.\n\n### Step 4: Run line-level heatmap on top candidates\n\nFor each high-priority file (typically 3-8 files), run the line-level heatmap to find the hottest regions within those files.\n\n```bash\npython3 \"$HEATMAP\" file --json <file_path_relative_to_repo> <repo_path>\n```\n\nThis returns JSON array of objects with: `line`, `heat`, `content`.\n\n### Step 5: Identify hot zones\n\nFrom the line-level results, identify contiguous regions of high heat. These \"hot zones\" are where to focus review. Look for:\n\n- **Clusters of hot lines** — contiguous blocks of high-heat code indicate areas under active rework. These are prime bug candidates because:\n  - Multiple recent changes suggest the logic is not yet settled\n  - Each change is an opportunity for regression\n  - Complex interactions between recent changes may not be fully tested\n\n- **Hot lines surrounded by cold code** — surgical edits in otherwise stable code may indicate bug fixes, workarounds, or special-case handling that deserves scrutiny.\n\n- **Hot function/method boundaries** — if a method signature or its first few lines are hot, the contract may have changed recently, affecting all callers.\n\n### Step 6: Produce the review focus list\n\nOutput a ranked list of review targets, structured as:\n\n```\n## Heatmap Review Targets\n\n### Priority 1: <file_path> (heat: X, commits: Y)\n- **Hot zones**: lines A-B (description of what this code does)\n- **Why it matters**: <context — e.g., \"most changed file in repo AND modified in this PR\">\n- **What to look for**: <specific guidance based on the code — race conditions, edge cases, etc.>\n\n### Priority 2: ...\n```\n\n### Step 7: Deep review\n\nFor each priority target, read the hot zones and perform the actual review. The heatmap tells you WHERE to look; your expertise tells you WHAT to look for. Common patterns in hot code:\n\n- **State management bugs**: Hot code often manages complex state. Check for inconsistent updates, missing synchronization, or partial failures.\n- **Edge cases**: Frequent changes often mean edge cases keep being discovered. Look for more.\n- **Regression risk**: If code was recently fixed, check whether the fix is complete and doesn't break other paths.\n- **Missing tests**: Hot code that lacks test coverage is the highest-risk combination.\n\n## Output format\n\nAlways present findings as a prioritized list with:\n1. File path and heat metrics\n2. Specific line ranges to focus on\n3. What the hot code does (brief)\n4. What risks to look for (specific to the code, not generic)\n\n## Tips\n\n- Heat is relative — compare files against each other, not against an absolute threshold.\n- Files with high heat but few commits have large individual changes (risky). Files with high heat and many commits are under constant churn (also risky, differently).\n- `last_modified_days` close to 0 means very recent changes — highest chance of unfound bugs.\n- Use `--since` to adjust the time window. Default is 2 years. For recent bug hunts, try `--since \"6 months ago\"`.\n- The `--no-color` flag is useful when piping output, but prefer `--json` for programmatic use.\n",".claude/skills/bug-archaeology/SKILL.md":"---\nname: bug-archaeology\nversion: \"1.0.0\"\ndescription: >\n  Mine bug patterns from any git repository. Discovers bug-fix commits via git log\n  heuristics, analyzes each in parallel with subagents, writes individual analysis files,\n  and synthesizes a generalized PATTERNS.md with repo-specific details stripped.\n  Invoke explicitly with /bug-archaeology.\n---\n\n# Bug Archaeology\n\nSystematic extraction of reusable bug-detection heuristics from a repository's commit history.\n\n## Arguments\n\nAll optional. Parse from the user's invocation string.\n\n| Arg | Default | Description |\n|-----|---------|-------------|\n| `--range` | `HEAD~200..HEAD` | Git revision range |\n| `--path` | (all files) | Restrict to commits touching this path glob |\n| `--since` / `--until` | (none) | Date filter for `git log` |\n| `--limit` | 200 | Max bug-fix commits to analyze |\n| `--batch-size` | 10 | Commits per subagent |\n| `--output` | `./bug-archaeology/` | Output directory |\n\n## Workflow\n\nThree sequential phases. Each phase completes fully before the next starts.\n\n### Phase 1: Discovery\n\nFind bug-fix commits via git log heuristics.\n\n```bash\ngit log --no-merges --pretty=format:\"%H %s\" [--since=X] [--until=X] <range> [-- <path>] \\\n  | grep -iE '(fix|bug|patch|resolve|repair|correct|workaround|hotfix|regression|#[0-9]+|[A-Z]+-[0-9]+)'\n```\n\n**Filter out** commits whose message matches ONLY cosmetic keywords (`typo`, `whitespace`, `import`, `format`, `style`, `cleanup`, `rename`) with no bug keywords.\n\n**Truncate** to `--limit`.\n\n**Write** `QUEUE.txt` to the output directory:\n```\n0001 abc123def First line of commit message\n0002 def456abc Another commit message\n```\n\n**Resumption**: If `PROGRESS.md` exists, read it and exclude commits already marked `done` or `skipped`. Re-include `pending` and `error` entries.\n\n### Phase 2: Analysis (parallelized)\n\nSpawn subagents to analyze commits in batches. Each commit is independent.\n\n**Subagent prompt template** — adapt as needed:\n```\nRead the file at references/per-bug-format.md for the output format specification.\n\nAnalyze these commits from the repository at <REPO_PATH>:\n<list of \"NNNN hash message\" lines>\n\nFor each commit:\n1. Run: git show <hash>\n2. If the commit is cosmetic, test-only, refactor-only, or a merge with no\n   original changes — mark it as skipped with a one-word reason.\n3. Otherwise, write the analysis to <OUTPUT>/bug-<NNNN>-<slug>.md\n   following the format in per-bug-format.md exactly.\n\nReturn a status line per commit: NNNN <hash> done|skipped [reason-or-filename]\n```\n\n**Parallelism**: Launch up to 5 subagent batches concurrently. Wait for all to complete before the next wave.\n\n**Progress tracking**: After each wave, append results to `PROGRESS.md`:\n```markdown\n| # | Commit | Status | File / Reason |\n|---|--------|--------|---------------|\n| 0001 | abc123d | done | bug-0001-null-after-lookup.md |\n| 0002 | def456a | skipped | cosmetic |\n```\n\n**Errors**: Mark as `error` with a one-line reason. Don't retry — the user re-invokes with `--resume`.\n\n### Phase 3: Synthesis\n\nAfter all analysis is complete, produce `PATTERNS.md`. Read `references/synthesis-format.md` for the full specification.\n\n**Process**:\n1. Read all `bug-*.md` files in the output directory\n2. Parse the `Tags` section from each — extract `category` and `code-pattern`\n3. Group bugs by `code-pattern` tag\n4. For each group of 2+ bugs with the same code-pattern:\n   - Extract the shared Detection Rule (generalize if they differ across instances)\n   - Pick the most representative Example\n5. **Generalize** — strip repo-specific details:\n   - Replace specific class/method names with structural descriptions\n   - Remove ticket IDs, author names, project-specific subsystem labels\n   - Keep language-specific API names only if scope is that language or broader\n6. Group patterns by `category` and write `PATTERNS.md`\n7. Patterns with only 1 instance go in a \"Singletons\" section at the end\n\n## Reference Files\n\n| File | Loaded by | Purpose |\n|------|-----------|---------|\n| `references/per-bug-format.md` | Subagents (Phase 2) | Per-bug output template and field guidelines |\n| `references/synthesis-format.md` | Orchestrator (Phase 3) | PATTERNS.md structure and generalization rules |\n\n## Evaluating the Skill\n\nFull instructions are in `references/EVAL-PROMPT.md`. Summary:\n\n1. **Pick a bug** from the archaeology output and trace its introducing commit via `git blame`.\n2. **Extract the patch** with `git diff ${INTRO}~1 $INTRO`.\n3. **Choose a review skill** — the user must specify one:\n   - `/shallow-review` — quick 6-specialist parallel scan, any patch size\n   - `/deep-review` — focused on specific files, complex logic\n   - `/targeted-review` — findings-driven, medium-to-large patches\n   - `/mega-review` — large feature branches or 1000+ LOC diffs\n4. **Run the chosen skill** against the extracted patch.\n5. **Score** the output: Exact / Partial / Different bug / Miss.\n6. **Prod misses** — tell the skill what it missed and ask which checklist item would have caught it; use the answer to improve that skill's reference files.\n\nTarget: >90% hit rate (exact + partial), <5% miss rate across a batch of N bugs.\n",".claude/skills/patch-explainer/SKILL.md":"---\nname: patch-explainer\nversion: \"1.0.0\"\ndescription: Deep code analysis with ASCII visualizations showing structure, flow, and state transitions. Use when analyzing patches/diffs, explaining classes or subsystems, understanding code architecture, reviewing changes for inconsistencies, or when asked to visualize how code works. Provides before/after diagrams, data/control flow, concurrency analysis, assumptions, and failure modes. Triggers on explain this patch/code/class, how does X work, show me the flow, visualize this change, code review requests, or proactive analysis during PR reviews.\n---\n\n# Patch Explainer\n\nDeeply analyze and visualize code using ASCII diagrams to reveal structure, behavior, and interactions.\n\n## What This Skill Does\n\nProvides comprehensive code analysis with rich ASCII visualizations for:\n- **Patches/diffs**: Before/after states, what changed and why\n- **Classes**: Purpose, structure, state transitions, workflows\n- **Subsystems**: Component interactions, data flow, architecture\n- **Repositories**: Overall structure, key abstractions, major patterns\n- **Code reviews**: Finding inconsistencies, analyzing assumptions and failure modes\n\n## Analysis Approach\n\n### For Any Code (Patches, Classes, Subsystems, Repositories)\n\n1. **Identify the core purpose** - What does this code do and why does it exist?\n\n2. **Create ASCII visualizations** showing:\n   - Structure (components, layers, dependencies)\n   - Behavior (data flow, control flow, state transitions)\n   - Interactions (sequence diagrams, message passing, concurrency)\n   - For patches: before/after comparisons\n\n3. **Deep reasoning** about:\n   - **Assumptions**: What must be true for this to work correctly?\n   - **Failure modes**: What could go wrong at each step?\n   - **Concurrency**: If multiple threads/processes, show their interactions\n   - **Invariants**: What must always hold true?\n\n4. **Focus on the \"why\"**:\n   - Why does this code exist?\n   - Why was this approach chosen?\n   - For changes: Why this modification? What problem does it solve?\n\n### Visualization Strategy\n\nChoose diagram types based on what you're explaining:\n\n**State machines** - When code manages states/status:\n```\n[Initial] --event--> [Processing] --success--> [Complete]\n                          |\n                       failure\n                          |\n                          v\n                      [Failed]\n```\n\n**Data flow** - When showing information movement:\n```\nInput → [Transform A] → [Transform B] → Output\n```\n\n**Sequence diagrams** - When showing component interactions:\n```\nClient          Server          Database\n  |               |                 |\n  |--request----->|                 |\n  |               |----query------->|\n  |               |<---result-------|\n  |<--response----|                 |\n```\n\n**Component structure** - When showing architecture:\n```\n┌─────────────────────┐\n│   Application       │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Service Layer     │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Data Layer        │\n└─────────────────────┘\n```\n\n**Before/after** - When explaining changes:\n```\nBEFORE                  AFTER\n─────────────────────────────────\n[A] → [B] → [C]        [A] → [Cache?] ─Yes→ [C]\n                              |\n                              No\n                              v\n                            [B] → [C]\n```\n\n### Reference Materials\n\n**ASCII diagram templates**: See [ascii_patterns.md](references/ascii_patterns.md) for:\n- State machine patterns\n- Data flow diagrams\n- Sequence diagrams\n- Component/architecture diagrams\n- Before/after comparisons\n- Concurrency patterns\n- Control flow patterns\n- Dependency graphs\n\n**Analysis methodology**: See [analysis_framework.md](references/analysis_framework.md) for:\n- Structured analysis process for patches vs existing code\n- Concurrency analysis checklist\n- Assumption identification patterns\n- Failure mode identification\n- Analysis depth guidelines by scope (function → class → subsystem → repository)\n\n## Analysis Workflow\n\n### For Patches/Diffs\n\n1. Read the patch to understand what changed\n2. Identify the change type (bug fix, feature, refactor, optimization)\n3. Create before/after ASCII diagrams showing:\n   - Old behavior vs new behavior\n   - State transitions that changed\n   - Data flow modifications\n4. Explain what fundamentally changed:\n   - What problem did the old code have?\n   - How does the new code solve it?\n   - What assumptions changed?\n5. Analyze failure modes:\n   - What could go wrong with this change?\n   - Are there edge cases not handled?\n   - Concurrency implications?\n6. Focus on the \"why\": What problem does each modification solve?\n\n### For Classes\n\n1. Read the class to understand its purpose\n2. Create ASCII diagram showing:\n   - Class structure (key fields/methods)\n   - State machine if it manages state\n   - How it fits with related classes\n3. Explain key workflows (2-3 most important methods)\n4. Identify assumptions and invariants\n5. Analyze failure modes and edge cases\n6. Focus on the \"why\": Why does this class exist? What problem does it solve?\n\n### For Subsystems\n\n1. Identify the components in the subsystem\n2. Create ASCII diagram showing:\n   - Component relationships\n   - Key interfaces/boundaries\n   - Main data flows\n3. Trace 2-3 key workflows through the subsystem\n4. Explain how components interact\n5. Identify assumptions across component boundaries\n6. Focus on the \"why\": What is this subsystem's role in the larger system?\n\n### For Repositories\n\n1. Understand the high-level architecture\n2. Create ASCII diagram showing:\n   - Major modules/packages\n   - Layered architecture\n   - Key abstractions\n3. Identify core workflows\n4. Explain main patterns used throughout\n5. Highlight critical subsystems\n6. Focus on the \"why\": What problem does this codebase solve?\n\n## Concurrency Analysis\n\nWhen analyzing concurrent code, always show:\n\n**Thread interactions**:\n```\nThread A                State                Thread B\n   |                      |                      |\n   |--lock()------------>|                      |\n   |                     [LOCKED]               |\n   |--modify()---------->|                      |\n   |--unlock()---------->|                      |\n   |                     [UNLOCKED]             |\n   |                      |<---------lock()-----|\n   |                     [LOCKED]               |\n```\n\n**Race conditions**:\n```\nThread A            Thread B\n   |                   |\n   |--read(x=10)      |\n   |                   |--read(x=10)\n   |--x=x+1           |\n   |                   |--x=x+1\n   |--write(x=11)     |\n   |                   |--write(x=11)  ⚠ Lost update!\n\nResult: x=11 (expected: x=12)\n```\n\nCheck for:\n- Shared mutable state without synchronization\n- Lock ordering violations (potential deadlocks)\n- Race conditions in read-modify-write operations\n- Missing memory barriers\n\n## Output Structure\n\nStructure your analysis as:\n\n### 1. Executive Summary\nBrief overview (2-3 sentences) of what this code does and why it matters.\n\n### 2. Visual Overview\nHigh-level ASCII diagram showing the main structure or flow.\n\n### 3. Detailed Analysis\nOrganized by aspect:\n- **Purpose**: What it does and why it exists\n- **Structure**: Components and their relationships\n- **Key Workflows**: Step-by-step execution of main scenarios\n- **State Management**: States and transitions (if applicable)\n- **Assumptions**: What must be true for correctness\n- **Failure Modes**: What could go wrong\n- **Concurrency**: Thread safety analysis (if applicable)\n\n### 4. For Patches: Before/After\n- Before state (with diagram)\n- After state (with diagram)\n- Why this change was made\n- Critical modifications explained\n\n### 5. Key Insights\nBullet points highlighting:\n- Most important findings\n- Potential issues or risks\n- Recommendations (if applicable)\n\n## Prioritization\n\nFocus on high-impact elements:\n- **Critical paths**: Main workflows that matter most\n- **High-risk code**: Concurrency, error handling, resource management\n- **Complex logic**: Non-obvious algorithms or subtle interactions\n- **Key abstractions**: Core interfaces and contracts\n\nMinimize or skip:\n- Boilerplate code\n- Simple getters/setters\n- Standard patterns done correctly\n- Low-risk trivial changes\n\n## Example Scenarios\n\n**Scenario 1**: \"Explain this patch\"\n→ Show before/after diagrams, explain what changed and why, analyze assumptions and failure modes\n\n**Scenario 2**: \"How does SafeCommandStore work?\"\n→ Show class structure, explain the exclusive access pattern, trace key methods, analyze thread safety\n\n**Scenario 3**: \"Explain the coordination subsystem\"\n→ Show component diagram, trace PreAccept→Accept→Commit flow, explain message passing, show quorum tracking\n\n**Scenario 4**: \"What's the architecture of this codebase?\"\n→ Show high-level module structure, identify key abstractions, explain main patterns, highlight critical subsystems\n\n**Scenario 5**: During code review (proactive)\n→ Analyze changes for inconsistencies, check assumptions, identify potential race conditions, verify error handling\n",".claude/skills/write-reproducer/SKILL.md":"---\nname: write-reproducer\nversion: \"1.0.0\"\ndescription: \"Write minimal, reliable bug reproducers (repros) for any project. Use when: (1) a bug report or issue needs a test that reliably demonstrates the failure, (2) converting a described failure scenario into runnable code, (3) minimizing an existing complex test to its essential trigger conditions. Covers the full repro workflow: failure characterization, scope selection, writing the repro, verifying it fails for the right reason, and minimizing to the smallest possible trigger.\"\n---\n\n# Write Bug Reproducer\n\nYour goal is to turn a bug description into a minimal, self-contained, runnable reproduction that triggers a specific, machine-checkable failure criterion.\n\nA reproducer has three parts — keep them distinct in your head and in your code:\n\n- **Trigger**: the minimum input, state, schedule, or environment that causes the bug\n- **Harness**: how the trigger is executed (test runner, script, container, cluster test)\n- **Oracle**: the machine-checkable failure criterion (assertion, exit code, log pattern, invariant violation)\n\nFollow the five phases below in order. Do not skip ahead. Write the failure criterion before writing any repro code.\n\n## Phase 1: Understand and classify\n\nRestate the bug in one sentence: \"The bug is...\"\n\nClassify along three axes:\n\n- **Bug class**: crash, incorrect output, hang/deadlock, race condition, assertion/invariant violation, performance regression, resource leak, serialization bug, consistency anomaly. See `references/bug-taxonomy.md` for the full taxonomy when classification is unclear.\n- **Scope**: pure function, module, single process, multiple processes, cluster.\n- **Determinism**: deterministic, flaky (state what makes it flaky), requires rare schedule or timing.\n\nIf the user gave only symptoms with no code, list the 2-4 most likely causes before proceeding. Do not pick one yet — write hypotheses, not conclusions.\n\nIf the user included code or pointed at a codebase, read the suspect region and identify the likely code path before moving on.\n\n## Phase 2: Define the failure criterion\n\nThis is the most important phase. Before writing any repro code, write out the oracle in one of these machine-checkable forms:\n\n- **Assertion with concrete values**: `assert expected == actual` with both spelled out\n- **Exit code**: `expected: 0, actual: 139 (SIGSEGV)`\n- **Regex against stdout/stderr**: exact string fragment to match\n- **Log grep**: file and pattern\n- **Exception type and message fragment**: the specific error and location\n- **Linearizability/isolation check result**: checker verdict (e.g., linearizability violation, cycle detected)\n- **Invariant violation**: state the invariant in one line; state what breaks it\n\nRecord the failure criterion verbatim. It will be used in Phase 4 (to write the assertion) and Phase 5 (to prevent shrinking into a different bug).\n\nWithout an explicit oracle, shrinking can produce something that \"fails\" but not in the described way, and reviewers cannot tell whether the repro is successful.\n\n## Phase 3: Detect context and choose repro form\n\nInspect the working directory for build-system markers and prefer the project's existing test framework and conventions. Explore existing tests to understand helpers, fixtures, naming patterns, and how integration tests are structured.\n\nPick the lowest tier on the minimality lattice that can reliably exhibit the failure. See `references/minimality-lattice.md` for tier definitions and decision rules.\n\n- Tier 1: expression / REPL snippet\n- Tier 2: single-file snippet with `main`\n- Tier 3: single test in the project's existing framework\n- Tier 4: multi-file project fixture\n- Tier 5: containerized environment + test script\n- Tier 6: ephemeral cluster\n- Tier 7: deterministic simulation\n\nWrite one sentence naming the tier and why, based on what you found in the project.\n\nFor concurrency bugs: `references/concurrency.md`\nFor distributed-systems bugs: `references/distributed-systems.md`\nFor invariant bugs where a property test is the natural form: `references/property-based-testing.md`\nFor bugs found by fuzzing or where a fuzz harness is the natural repro: `references/fuzzing.md`\n\n## Phase 4: Draft the repro\n\n### Structure\n\nLabel the three parts in comments:\n\n```\n// TRIGGER: <what causes the bug>\n// HARNESS: <how we run it>\n// ORACLE:  <what we check>\n```\n\nUse the project's test framework and conventions. Match existing test style. Do not introduce a new framework unless the existing one cannot express the bug.\n\n### The pass-then-invert strategy\n\nFor subtle assertion bugs where the correct behavior is easy to state but the failing test is hard to get right, use **pass-then-invert**: first write a test that *passes* on the current buggy behavior (mirroring the observed wrong output in its assertions), then invert the assertions so they encode the *correct* expectation and therefore fail on the bug. This reduces hallucinated APIs and setup errors compared to writing a failing test directly.\n\nUse pass-then-invert when:\n- The bug produces a wrong value (not a crash or exception)\n- The correct expected value is known\n- Direct \"write a failing test\" attempts keep failing for setup reasons\n\nDo not use pass-then-invert when:\n- The bug is a crash, exception, or hang — just trigger it directly\n- The oracle is an absence check (no exception, no crash) — inversion doesn't apply\n\n### Verification before presenting\n\nThe repro must compile or parse cleanly. Resolve imports against the project's actual dependencies. Do not hallucinate APIs — if unsure of a method signature, read the library source or ask.\n\nIf execution is available, run the repro and confirm the failure criterion triggers. If not, trace through the code mentally and state your confidence level.\n\n### Generating multiple candidates\n\nWhen the bug is unclear or the first attempt fails, generate 2-5 candidate repro strategies:\n- Smallest direct unit test\n- Integration test if state/config matters\n- Standalone script if no test harness is obvious\n- Property-based test if the bug is about an invariant\n- Fuzz seed / deterministic scenario for correctness bugs\n\nExecute each candidate with a timeout. Classify each result using `references/failure-classification.md`. Refine until one produces an issue-relevant failure.\n\n### Documentation\n\nThe repro must include a comment or docstring stating:\n- Issue reference and one-line bug title\n- Expected (correct) behavior\n- Actual (buggy) behavior\n- Failure criterion (verbatim from Phase 2)\n\n## Phase 5: Shrink and validate\n\n### Validate first\n\nRun the repro (or trace through it mentally) and confirm:\n1. The failure criterion from Phase 2 triggers\n2. The failure is the *described* bug, not a test setup error\n3. The failure message matches what Phase 2 specified\n\nSee `references/failure-classification.md` for how to classify test results and distinguish issue-relevant failures from setup errors.\n\n### Then shrink\n\nUse the subtraction method from `references/minimization.md`. Work through dimensions in order (cheapest first):\n1. Reduce infrastructure scale (instances, partitions, replication)\n2. Reduce data volume (items, size, batches)\n3. Remove non-default configuration\n4. Remove setup steps\n5. Replace real sleeps with controlled time or polling\n6. Simplify trigger sequence\n\nSee `references/shrinking-checklist.md` for the guardrail checklist.\n\n### Over-minimization guardrail\n\nAfter each shrinking step, re-check that the failure is still *the same failure* — same assertion, same exception type, same message fragment from Phase 2. If the failure changed, revert that step. This prevents shrinking into a different bug.\n\n### For nondeterministic bugs\n\nWrap the trigger in an N-iteration harness with a retry budget. Report the observed failure rate (e.g., \"fails 23/1000 iterations\"). Do not use sleep-based synchronization — it makes tests flaky on different hardware. Prefer event-based scheduling, explicit synchronization primitives, or deterministic simulation.\n\nAlways print and record seeds for randomized tests so failing scenarios can be replayed.\n\n## Output\n\nAlways produce:\n\n1. **Repro file(s)** with `// TRIGGER`, `// HARNESS`, `// ORACLE` comments. Correct file placement matching the project's test layout.\n2. **Status**: one of `REPRODUCED` / `CANDIDATE` / `BLOCKED`. See `references/output-contract.md` for what each status means and requires.\n3. **Run command**: the exact command to execute the repro.\n4. **Failure summary**: \"This test should fail on the current code with: `<expected failure message>`\"\n5. **For flaky bugs**: failure rate and seed.\n6. **For blocked repros**: what's missing, what was attempted, next best direction.\n\n## Hard rules\n\n- **Write the failure criterion before the repro code.** Without an explicit oracle, you cannot distinguish a successful repro from a coincidental failure. This is the single most common failure mode.\n\n- **Do not hallucinate APIs.** If unsure whether a method, class, or flag exists, read the source or ask. Hallucinated APIs are the most frequent reason LLM-generated repros fail to compile.\n\n- **Assert expected behavior, not current broken behavior.** The oracle encodes what *should* happen. The test fails because reality doesn't match.\n\n- **Do not shrink past the bug.** After every shrinking step, re-verify the failure matches Phase 2. See `references/shrinking-checklist.md`.\n\n- **Flaky repros must declare their flakiness.** A repro that reproduces 23/1000 times must say so and wrap itself in a retry loop.\n\n- **Match the project's conventions.** Use the test framework, style, and helpers that already exist. Do not introduce a new framework unless the existing one cannot express the bug.\n\n- **Do not fix the bug.** Create tests/scripts/harnesses only. Do not edit production code unless explicitly asked.\n\n- **Do not use `:latest` image tags or unpinned dependency versions.** A repro is not reproducible if its dependencies drift.\n\n- **Do not confuse setup errors with reproduced bugs.** An error in test setup is not the same as the error caused by the bug. See `references/failure-classification.md`.\n\n## When to escalate to higher tiers\n\nEscalate to Tier 5+ (containerized, cluster, deterministic simulation) when:\n\n- The bug involves two or more processes (client + server, replica + leader)\n- The bug requires a specific network condition (partition, delay, drop)\n- The bug requires clock skew or node failure scenarios\n- The bug is about isolation, linearizability, or consensus\n- The user mentions Cassandra, Kafka, or any distributed system\n\nFor these cases read `references/distributed-systems.md` before drafting.\n\n## When to use a property-based test\n\nUse a property-based test when:\n\n- The bug is about an invariant (round-trip, idempotence, commutativity, ordering, bounded sums)\n- Shrinking comes for free in the property framework\n- You want the test to serve as a regression test with seed persistence\n\nSee `references/property-based-testing.md`.\n\n## When to use a fuzz harness\n\nUse a fuzz harness when:\n\n- The bug was originally found by fuzzing and a crashing input exists\n- The input is a byte stream or structured binary format\n- A single example fails but many nearby inputs are interesting for regression\n\nSee `references/fuzzing.md`.\n","AGENTS.md":"# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n",".claude/skills/tla-plus/SKILL.md":"---\nname: tla-plus\nversion: \"1.0.0\"\ndescription: Create, run, and verify TLA+ and PlusCal formal specifications. Use for modeling distributed systems, protocols, concurrent algorithms, state machines. Can compose specs from code, find divergences between spec and implementation, spot concurrency bugs and invariant violations. Use when asked to \"write a TLA+ spec\", \"model check\", \"verify protocol\", \"find race conditions\", or \"formal verification\".\n---\n\n# TLA+ Formal Specification Skill\n\nWrite non-trivial TLA+ specifications, run the TLC model checker, and bridge the gap between formal specs and implementation code.\n\n## Setup (Run Once)\n\n```bash\nbash SKILL_DIR/scripts/setup.sh\n```\n\nThis downloads `tla2tools.jar` (v1.8.0) and verifies Java 11+. The JAR is stored at `SKILL_DIR/lib/tla2tools.jar`.\n\n## Quick Reference\n\nLoad the right reference for your task:\n\n| Task | Reference |\n|------|-----------|\n| TLA+ syntax, operators, types | [references/language.md](references/language.md) |\n| PlusCal syntax, processes, labels | [references/pluscal.md](references/pluscal.md) |\n| Distributed systems patterns | [references/patterns/distributed-systems.md](references/patterns/distributed-systems.md) |\n| Protocol specifications | [references/patterns/protocols.md](references/patterns/protocols.md) |\n| Invariants, safety, liveness | [references/patterns/invariants.md](references/patterns/invariants.md) |\n| Code ↔ spec mapping, bug finding | [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md) |\n\n**Load references on-demand** — read the ones relevant to the current task before writing any spec.\n\n## Templates\n\nStart from a template when creating a new spec:\n\n| Template | Use For |\n|----------|---------|\n| [templates/basic.tla](templates/basic.tla) | Pure TLA+ state machine |\n| [templates/pluscal.tla](templates/pluscal.tla) | PlusCal algorithm with processes |\n| [templates/distributed.tla](templates/distributed.tla) | Distributed system with messages |\n\n## Running Specs\n\n### Full Check (Recommended)\n\nTranslates PlusCal (if present), parses, and model-checks in one step:\n\n```bash\nbash SKILL_DIR/scripts/check.sh spec.tla --config spec.cfg\n```\n\n### Individual Tools\n\n```bash\n# Parse only (syntax check)\nbash SKILL_DIR/scripts/parse.sh spec.tla\n\n# Translate PlusCal to TLA+\nbash SKILL_DIR/scripts/translate.sh spec.tla -nocfg\n\n# Model check with TLC\nbash SKILL_DIR/scripts/tlc.sh spec.tla --config spec.cfg --workers auto\nbash SKILL_DIR/scripts/tlc.sh spec.tla --no-deadlock    # suppress deadlock check\n```\n\n### Direct Java Invocation\n\n```bash\nJAR=\"SKILL_DIR/lib/tla2tools.jar\"\n\n# Parse\njava -cp \"$JAR\" tla2sany.SANY spec.tla\n\n# Translate PlusCal\njava -cp \"$JAR\" pcal.trans -nocfg spec.tla\n\n# Model check\njava -cp \"$JAR\" tlc2.TLC -workers auto -config spec.cfg spec.tla\n\n# REPL\njava -cp \"$JAR\" tlc2.REPL\n\n# Dump state graph (for visualization)\njava -cp \"$JAR\" tlc2.TLC -dump dot,actionlabels,colorize states.dot spec.tla\n```\n\n## Workflow: Writing a Spec\n\n### 1. Understand the System\n\nBefore writing any TLA+:\n- Identify the **concurrent agents** (processes, nodes, threads)\n- Identify **shared mutable state** (queues, databases, locks, counters)\n- Identify **the key safety property** (\"what must never happen?\")\n- Identify **the key liveness property** (\"what must eventually happen?\")\n\n### 2. Choose PlusCal vs Pure TLA+\n\n**Use PlusCal when:**\n- The system is naturally sequential/imperative\n- You're modeling code (threads, goroutines, async tasks)\n- You need `await`, `while`, `goto` semantics\n- The audience is programmers\n\n**Use Pure TLA+ when:**\n- You need fine-grained fairness control\n- The system is naturally a state machine\n- You need interruptible/restartable actions\n- You need refinement mappings\n- A single label would need to update a variable twice\n\n### 3. Start Small, Then Expand\n\n1. Write the **simplest possible spec** that captures the core behavior\n2. Add a **type invariant** immediately\n3. Run TLC with small constants (2-3 nodes, 2-3 messages)\n4. Add **safety invariants** one at a time, running after each\n5. Add **liveness properties** with fairness\n6. Increase constants to expand coverage\n\n### 4. Config File\n\nEvery spec needs a `.cfg` file. Create one alongside the `.tla`:\n\n```\nSPECIFICATION Spec\n\n\\* Properties to check\nINVARIANT TypeInvariant\nINVARIANT Safety\n\n\\* Uncomment for liveness (slower)\n\\* PROPERTY Liveness\n\n\\* Constants\nCONSTANT\n  NumNodes = 3\n  MaxMsgs = 5\n  NULL = NULL\n\n\\* Uncomment to bound state space\n\\* CONSTRAINT StateConstraint\n\n\\* Uncomment to ignore deadlocks\n\\* CHECK_DEADLOCK FALSE\n```\n\n## Workflow: Spec From Code\n\nWhen the user has existing code and wants a spec:\n\n1. **Read the code** — understand concurrency structure, shared state, synchronization\n2. **Read** [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md)\n3. **Map constructs** — threads→processes, locks→await, channels→queues\n4. **Abstract** — don't model every line, only concurrency-relevant operations\n5. **Write spec** — start with the concurrent skeleton, add detail iteratively\n6. **Run TLC** — find deadlocks, invariant violations, liveness failures\n7. **Report** — translate any TLC error traces back to code execution paths\n\n## Workflow: Finding Bugs\n\nWhen comparing a spec to code, or looking for bugs:\n\n1. **Read** [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md)\n2. **Write a spec** modeling the suspected buggy area\n3. **Run with small constants** — TLC is exhaustive, small state space is fine\n4. **Interpret error traces** — map TLA+ state sequences to code execution paths\n5. **Check atomicity** — does the code do atomically what the spec's label does?\n6. **Check completeness** — does the code handle all `either/or` branches?\n7. **Check ordering** — does the code enforce the same happens-before relations?\n\nIf TLC finds a violation:\n- The error trace is a **concrete counterexample** — a specific sequence of events\n- Map each state in the trace to concrete code state\n- The transition that causes the violation is the bug location\n\n## Interpreting TLC Output\n\n### Success\n```\nModel checking completed. No error has been found.\n  Estimates of the probability that TLC did not check all reachable states\n  because two distinct states had the same fingerprint:\n  calculated (optimistic):  val: 0\n```\n\n### Invariant Violation\n```\nError: Invariant SafetyInvariant is violated.\nThe following behavior constitutes a counter-example:\nState 1: <Initial predicate>\n  /\\ var1 = ...\nState 2: <Action line X>\n  /\\ var1 = ... (changed values in red)\n```\n\n### Deadlock\n```\nError: Deadlock reached.\n```\n→ No process can make progress. Check `await` conditions and process completion.\n\n### Liveness Violation\n```\nError: Temporal properties were violated.\n```\n→ Check fairness settings. Add `WF_vars` or `SF_vars`. Trace may include a \"stuttering\" suffix.\n\n## Key Principles\n\n1. **Type invariants first** — catch spec bugs before checking real properties\n2. **Small constants** — 3 nodes finds most bugs; 10 nodes takes 1000× longer\n3. **Safety before liveness** — invariants are faster to check\n4. **One property at a time** — add incrementally, run after each addition\n5. **Fairness is opt-in** — TLA+ assumes everything can crash by default\n6. **`=>` with `\\A`, `/\\` with `\\E`** — never use `=>` with `\\E`\n7. **Sequences are 1-indexed** — always\n8. **Every action must specify all variables** — use `UNCHANGED` for untouched ones\n",".claude/skills/shallow-review/SKILL.md":"---\nname: shallow-review\nversion: \"1.0.0\"\ndescription: >\n  Shallow (quick) ensemble bug-finding review using 6 specialist agents in parallel. Each\n  specialist reviews the same patch through a different lens: Logic & Types, Boundaries &\n  I/O, Concurrency & State, Resources & Serialization, Absence Analysis, and API\n  Completeness. Findings are merged and deduplicated. Best for: quick first-pass review of\n  patches, triage of diffs, broad surface-level bug scan. For deeper file-focused review\n  with full pattern catalogs and codebase investigation, use the deep-review skill instead.\n---\n\n# Ensemble Code Review\n\nSix specialist agents review the same patch in parallel. Each applies Phase 0 (understand\nthe change, form hypotheses) then a focused checklist. Their findings are merged and\ndeduplicated.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n    +-------+------+---------+---------+-----------+\n    |       |      |         |         |           |\n+---v--+ +--v--+ +-v-----+ +-v------+ +v-----+ +---v-------+\n|Logic | |Bound| |Concurr| |Resource| |Absenc| | Complete. |\n|&Type | | &I/O| |&State | |& Serde | |(2-ph)| | & Contr.  |\n+--+---+ +--+--+ +---+---+ +---+----+ +--+---+ +---+-------+\n   |        |        |         |          |        |\n   +--------+--------+---------+----------+--------+\n                               |\n                    +----------v----------+\n                    |  Pass 3: Symmetry   |\n                    |  (serial, optional) |\n                    +----------+----------+\n                               |\n                    +----------v----------+\n                    |   Merge & Dedup     |\n                    |   (main agent)      |\n                    +---------------------+\n```\n\n## Quick Start\n\n1. **Identify target** — patch, diff, file, or subsystem\n2. **Launch 6 specialists** in parallel (see prompts below)\n3. **Run Pass 3 Symmetry** check (serial, after specialists complete)\n4. **Merge** findings: deduplicate, rank by confidence\n5. **Report** in unified format\n\n## Phase 0: Understand Before Checking\n\nEvery specialist runs Phase 0 BEFORE touching the checklist:\n\n1. **Summarize** the patch in 2–3 sentences (feature, fix, refactor, move?)\n2. **Hypothesize** — list 3–5 things that could go wrong with this type of change\n3. **Note** code shapes that warrant deeper investigation\n\nThis switches the review from bottom-up (checklist→code) to top-down\n(code→hypotheses→verification). The checklist then verifies and extends the hypotheses.\n\n---\n\n## The Six Specialists\n\n### 1. Logic & Types (52% of bugs)\n\n**Priority**: wrong comparisons, missing returns, wrong constants, boolean polarity, sentinel ambiguity.\n\n**Reference**: `references/general/specialists/logic.md`\n\n**Prompt**:\n```\nYou are a LOGIC specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any suspicious code shapes (control flow, comparisons, constants, sentinels).\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/logic.md`\nApply questions that match your hypotheses and code shapes. Check all 30 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 2. Boundaries & I/O (17% of bugs)\n\n**Priority**: off-by-one, integer overflow, null/bounds checks, buffer sizing, I/O completeness.\n\n**Reference**: `references/general/specialists/boundary.md`\n\n**Prompt**:\n```\nYou are a BOUNDARY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any arithmetic, indexing, range, or I/O operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/boundary.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 3. Concurrency & State (16% of bugs)\n\n**Priority**: races, TOCTOU, live-view iteration, lock ordering, state cleanup.\n\n**Reference**: `references/general/specialists/concurrency.md`\n\n**Prompt**:\n```\nYou are a CONCURRENCY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any shared state, locks, collections, lifecycle operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/concurrency.md`\nApply questions that match your hypotheses and code shapes. Check all 24 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 4. Resources & Serialization (15% of bugs)\n\n**Priority**: resource leaks, serialization mismatches, wrong metric types, background tasks, wrapper bypass.\n\n**Reference**: `references/general/specialists/resources.md`\n\n**Prompt**:\n```\nYou are a RESOURCES specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any resource allocation, serialization methods, metrics, streams.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/resources.md`\nApply questions that match your hypotheses and code shapes. Check all 26 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 5. Absence Analysis (cross-cutting)\n\n**Priority**: find what SHOULD be present but ISN'T — missing guards, cleanup, handlers, registrations.\n\n**Reference**: `references/general/specialists/absence.md`\n\n**Prompt**:\n```\nYou are an ABSENCE specialist. Your job: find bugs that are purely absent — missing\nguards, cleanup, handlers, or conditions that leave no signal in the diff.\n\nPHASE 0 — Understand the patch first:\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that SHOULD be present but might be missing.\n\nPHASE 1 — Build the search list:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/absence.md`\nFor each event in the diff matching items (a)-(q), add to your search list.\n\nPHASE 2 — Execute searches and report:\nFor each item in your search list:\n  - Use Grep and Read tools to gather evidence from the codebase\n  - If match found (remove/deregister exists): discard\n  - If no match found: report as finding\n\nReport ALL findings above a noise floor. For each: what's missing, where it should\nbe, what evidence you searched for, Confidence (High/Medium/Low).\nOr \"No absence finding\" if nothing applies.\n```\n\n### 6. API Completeness & Contracts\n\n**Priority**: missing fields, missing overrides, registration symmetry, visibility, event coverage.\n\n**Reference**: `references/general/specialists/completeness.md`\n\n**Prompt**:\n```\nYou are an API COMPLETENESS specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could be incomplete about this change.\n3. Note any new classes, new fields, new registrations, visibility changes.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/completeness.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n---\n\n## Pass 3: Cross-Path Symmetry (serial, after specialists complete)\n\n**Prompt**:\n```\nYou are a SYMMETRY specialist. For each code path modified in this patch, identify\nwhether a structurally parallel path (same class, interface, event family, version range)\nwas NOT modified. For each asymmetry:\n- Where path A was changed\n- Where parallel path B exists\n- What was changed on A that is absent on B\n- Whether the asymmetry is intentional or suspicious\n\nRead the patch: `{PATCH_PATH}`\nSearch the codebase as needed using Grep and Read.\nReport all asymmetries, Confidence High/Medium/Low.\n```\n\n---\n\n## Merge & Dedup\n\nAfter all specialists report:\n\n1. **Collect** all findings from 6 specialists + symmetry\n2. **Deduplicate** — same code location + related reasons → combine\n3. **Rank** by confidence — findings confirmed by multiple specialists rank highest\n4. **Cross-check** reinforcement:\n   - Logic + Absence at same location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Any finding flagged by 3+ specialists → treat as confirmed\n5. **3-point test** each finding:\n   - The code construct actually exists in the diff (not inferred)\n   - The bug is possible given the visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n6. **Specialist Silence Rule**: If Absence or Completeness reports nothing on a >100-line\n   diff, note: \"Consider verifying Phase 2 searches executed for registration symmetry,\n   handler coverage, and field completeness.\"\n\n---\n\n## Report Format\n\n```\n## Review: [target]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Flagged by**: [specialists]\n- **What's wrong**: [1-2 sentences]\n\n### Specialist Coverage\n- Logic: [N findings / no finding]\n- Boundary: [N findings / no finding]\n- Concurrency: [N findings / no finding]\n- Resources: [N findings / no finding]\n- Absence: [N findings / no finding]\n- Completeness: [N findings / no finding]\n- Symmetry: [N asymmetries / none]\n```\n\n## Statistical Priors\n\n| Category | Share | Specialist |\n|---|---|---|\n| Logic error in condition | 26% | Logic |\n| Wrong constant / default | 15% | Logic |\n| Missing null / bounds check | 13% | Boundary |\n| Incorrect filtering / result | 11% | Logic |\n| Race condition | 9% | Concurrency |\n| Wrong serialization | 8% | Resources |\n| State not cleaned up | 7% | Concurrency |\n| Off-by-one | 4% | Boundary |\n| Resource leak | 3% | Resources |\n\n## Reference Files\n\n### Specialist checklists (trimmed, ensemble mode)\n- `references/general/specialists/logic.md` — 30 items, Logic specialist\n- `references/general/specialists/boundary.md` — 22 items, Boundary specialist\n- `references/general/specialists/concurrency.md` — 24 items, Concurrency specialist\n- `references/general/specialists/resources.md` — 26 items, Resources specialist\n- `references/general/specialists/absence.md` — Phase 1/2 search patterns, Absence specialist\n- `references/general/specialists/completeness.md` — 22 items, Completeness specialist\n",".claude/skills/targeted-review/SKILL.md":"---\nname: targeted-review\nversion: \"1.0.0\"\ndescription: >\n  Findings-driven targeted code review. Understands the patch via patch-explainer and\n  surrounding code via codebase-analysis, then consults a catalog of bug patterns\n  (~11 categories under references/categories/). Picks only categories whose diff-signals\n  match the patch and items whose \"look for\" hints match actual code shapes, groups them\n  by review focus (function/file/feature), and spawns parallel subagents — each with a\n  tight scope and selective checklist. Use for medium-to-large patches (50-1000 LOC) as\n  a focused alternative to whole-patch ensemble or whole-file deep review. Triggers on:\n  \"review this patch/diff/change\", \"find bugs in this change\", \"scoped review\", \"what\n  could go wrong here\", \"review using findings\", or proactive PR review.\n---\n\n# Targeted Review\n\nA meta-review skill. It does not encode bug patterns directly — it orchestrates other\nskills and a categorized findings catalog into a tight, evidence-driven review.\n\n## What it does\n\n```\n                +------------------+\n                |   Input patch    |\n                +--------+---------+\n                         |\n             +-----------+-----------+\n             |                       |\n   +---------v---------+   +---------v-----------+\n   | patch-explainer   |   | codebase-analysis   |\n   | (sub-skill)       |   | (sub-skill, scoped) |\n   | what changed,     |   | invariants, callers,|\n   | flow, assumptions |   | parallel paths      |\n   +---------+---------+   +---------+-----------+\n             |                       |\n             +-----------+-----------+\n                         |\n         +---------------v----------------+\n         | Pick categories + items        |\n         | × 3-5 independent iterations  |\n         | (each draw surfaces different  |\n         |  items from the same catalog)  |\n         +---------------+----------------+\n                         |\n                +--------v---------+\n                | Pool & prioritize|\n                | (items from 2+   |\n                |  iterations →    |\n                |  higher priority)|\n                +--------+---------+\n                         |\n                +--------v---------+\n                | Group items by   |\n                | review focus     |\n                | (file/func/feat) |\n                +--------+---------+\n                         |\n            +------------+------------+\n            |            |            |\n    +-------v---+  +-----v-----+  +---v-------+\n    | review    |  | review    |  | review    |\n    | subagent  |  | subagent  |  | subagent  |\n    | scope A   |  | scope B   |  | scope C   |\n    +-------+---+  +-----+-----+  +---+-------+\n            |            |            |\n            +------------+------------+\n                         |\n                +--------v---------+\n                | Merge & report   |\n                +------------------+\n```\n\n## When to use this skill\n\n- A patch or diff is on the table for review (single commit, multi-commit branch, or staged changes)\n- The user wants more focus than `shallow-review` provides (six fixed lenses on the whole patch) but doesn't want to commit to `deep-review`'s file-by-file deep pass\n- A `*-findings/` corpus exists or the categorized catalog under `references/categories/` is sufficient — the categories alone are usable; project corpora improve coverage\n- Medium-to-large patches where dispatching focused subagents avoids overwhelming a single reviewer\n\n## When NOT to use this skill\n\n- Trivial 1-3 line changes — direct review is faster\n- Pure refactors with no behavior change — `shallow-review` symmetry pass is enough\n- The user wants a single comprehensive write-up of one file — use `deep-review` instead\n\n---\n\n## Workflow\n\nYou will go through seven phases. Phases 1a and 1b run in parallel. Phases 2-6 are sequential.\n\n### Phase 1a: Understand the patch — call the patch-explainer skill\n\nInvoke the `patch-explainer` skill on the patch. Use the Skill tool. You want patch-explainer\nto produce its standard analysis (purpose, before/after diagrams, flow, assumptions,\nfailure modes).\n\nIf the patch is already provided as a file path, point patch-explainer at it. If you only\nhave a commit ref, ask for `git show <ref>` or read it from `git diff`. For multi-commit\nbranches, it is fine to feed the cumulative diff.\n\nCapture patch-explainer's full output. You will refer to it in Phases 3-5.\n\n### Phase 1b: Understand the surroundings — call the codebase-analysis skill\n\nIn parallel with 1a, invoke the `codebase-analysis` skill in **targeted mode** on the\naffected subsystem only — not the whole repo. Pass it:\n\n- The list of files touched by the patch\n- The subsystem name if obvious (e.g., \"the journal replay subsystem\")\n- A directive to focus on: invariants, lifecycle, parallel implementations, and recent\n  bug history in the affected area\n\nYou want codebase-analysis to produce a scoped `analysis/system-analysis.md` that gives\nyou the context the patch sits inside — what the surrounding code expects, where parallel\npaths exist, what historical bugs touched this area.\n\nIf invoking the full skill is too heavy for a small patch, instead spawn a research\nsubagent with this prompt: \"Read these files: {touched files}. Summarize: (a) the\ninvariants the surrounding code maintains, (b) any parallel implementations or sibling\nclasses, (c) callers of the modified methods, (d) any recent bug-fix commits in this\narea. Under 400 words.\" This is a lighter alternative that retains the spirit of\ncodebase-analysis. Prefer the full skill when the area is unfamiliar or large.\n\n### Phase 2: Pick categories — 3-5 independent iterations\n\nCategory selection and item picking are speculative: you're making probabilistic judgments\nabout which patterns might apply, and a single pass will reliably miss some. Run **3-5\nindependent iterations** of Phases 2+3, each starting from scratch with the same patch\nand context but without looking back at what prior iterations chose. Treat each iteration\nlike a fresh read — you are more likely to notice different things each time.\n\nFor each iteration, read `references/categories/INDEX.md` — it lists all 11 categories\nwith their descriptions and diff signals in one file (~200 lines). For each category, ask:\ndoes the patch contain ANY of the diff signals listed?\n- If yes → mark as **load**\n- If no → skip\n\nTypically 3-7 categories load per iteration. If you would load more than 8, re-examine.\nIf fewer than 2, the patch is probably too small for this skill.\n\n### Phase 3: Pick items within each loaded category (one pass per iteration)\n\nWithin each iteration, read the **full** content of each loaded category file. For each\nfinding (`### F-NN: title` + body + `**Look for:** {hint}`), ask:\n\n1. Does the \"Look for\" hint match a code shape that **actually appears in this patch**?\n2. Does the patch context (from patch-explainer + codebase-analysis) make this finding\n   **plausibly applicable** — not just a keyword match?\n\nIf yes to both → keep the item.\nIf no → drop.\n\nBe selective: a category typically has 25-40 findings; keep 3-12 per category per\niteration. Repeat for all iterations before moving to Phase 3b.\n\n### Phase 3b: Pool and prioritize across iterations\n\nAfter all iterations are complete, merge the item lists:\n\n- An item selected in **2 or more iterations** is a strong candidate — mark it **priority**.\n- An item selected in only one iteration is still in scope — mark it **speculative**.\n- Discard nothing yet; let the subagents decide.\n\nThe iteration count next to an item is a confidence signal for the subagents, not a\ngate. A speculative item can still turn into a real bug; a priority item can still be\na false alarm.\n\n### Phase 4: Group items by review focus\n\nNow you have a pooled list of selected items across categories and iterations. Group them\nby **review focus** — what part of the change a single reviewer should examine. A focus\nis one of:\n\n- A specific function or method (`MyClass.replay()`)\n- A specific file or small group (`FooSerializer.java` and its sibling `FooDeserializer.java`)\n- A feature, behavior, or concept (\"the new fsync coordination\", \"the version-gated dispatch path\")\n- A specific cross-cutting concern in the patch (\"any place we read the new `dirty` flag\")\n\nAim for 2-5 foci per patch. Each focus should have **5-15 checklist items** drawn from\nacross the categories — not too few (subagent has nothing to do) and not too many\n(subagent gets overwhelmed). Include each item's priority annotation (priority /\nspeculative) so the subagent knows where to focus first.\n\nIf multiple foci would receive the same checklist item, that's fine — the same pattern\ncan apply at multiple sites. Tag each item with the category it came from so the\nsubagent knows the rationale.\n\n### Phase 5: Spawn focused review subagents\n\nFor each focus, spawn one review subagent in parallel using the Agent tool. Use the\ntemplate in `references/subagent-prompt-template.md`. The subagent prompt must contain:\n\n- The patch (path, or pasted, or ref)\n- A 100-word summary of patch-explainer's findings (relevant slice only — not the full output)\n- A 100-word summary of codebase-analysis's findings (relevant slice only)\n- The focus statement (what part of the change to review)\n- The checklist items, each with: category, priority annotation, finding text, and\n  look-for hint\n- Instructions on how to gather evidence (read source, grep, check parallel paths) and\n  what confidence to assign\n\nEach subagent should produce: a list of findings, with location, confidence, and what\nevidence was checked.\n\nRun all subagents in a single tool call (parallel). They are independent.\n\n### Phase 6: Merge and report\n\nWhen all subagents return, merge findings:\n\n1. **Deduplicate** — same code location + similar reasoning → one finding, both subagents\n   credited\n2. **Rank** by confidence — High first, then Medium, then Low\n3. **Cross-reinforce** — if a finding was raised by multiple subagents, or if multiple\n   findings cluster on the same lifecycle/state, boost confidence\n4. **Three-point check** each surviving finding:\n   - The code construct actually exists in the diff (not inferred from absence alone)\n   - The bug is plausible given the visible context (not speculative)\n   - The finding is actionable (the reader can tell what to change)\n\nUse the format in `references/report-format.md`.\n\n---\n\n## Reference files\n\n| Reference | When to read |\n|---|---|\n| `references/subagent-prompt-template.md` | Phase 5, when spawning each review subagent |\n| `references/report-format.md` | Phase 6, when merging and presenting findings |\n| `references/categories/INDEX.md` | Phase 2 — single-file scan of all category descriptions + diff signals |\n| `references/categories/<name>.md` | Phase 3 — full body of each loaded category, picked from INDEX |\n\nThe categories in `references/categories/` are project-agnostic patterns mined from real\nbug fixes across distributed-systems projects (Cassandra, Kafka, Iceberg). They describe\ngeneralized code-level shapes, not project-specific issues.\n\n## How this differs from related skills\n\n| Skill | Scope | Pattern source | Subagent dispatch |\n|---|---|---|---|\n| `shallow-review` (cassandra-edge-case-explorer) | Whole patch | 6 fixed lenses (~100 items total) | One subagent per lens, fixed |\n| `deep-review` | User-named files | 444-pattern catalog | One subagent per file, full catalog |\n| `targeted-review` (this) | Whole patch, focus-decomposed | ~11 categories (300+ findings) — selectively loaded | One subagent per focus, selectively populated checklist |\n| `mega-review` | Large branches | Orchestrates the above | Multi-pass |\n\nUse `targeted-review` when:\n- The patch spans 50-1000 LOC\n- You want to spend tokens on **what matters for THIS patch**, not on a fixed catalog\n- You have a `*-findings/` corpus or are reviewing systems-level code that benefits from\n  the curated categories\n\n## Pitfalls and guardrails\n\n- **Don't skip Phase 1.** Calling patch-explainer and codebase-analysis is what lets you\n  pick categories and items intelligently. Without that grounding, you'll loose-match\n  on keywords and overwhelm subagents.\n- **Don't look at prior iterations while picking.** The whole value of multiple iterations\n  is independent draws. If you anchor on the first iteration's selections, you get one\n  draw repeated instead of several independent ones.\n- **Don't load every category \"just in case\".** The whole value is selection. If you\n  match more than 8 categories in an iteration, you've probably been too generous.\n- **Don't pass the full catalog to subagents.** Each subagent gets only the items\n  selected for its focus. Passing all items defeats the purpose.\n- **Don't substitute findings for understanding.** A finding that \"matches a code shape\"\n  is a hypothesis to verify — the subagent confirms or refutes by reading the code, not\n  by trusting the pattern. Mark uncertain findings as Low confidence.\n- **The checklist is the menu, not the order.** A subagent should also report bugs it\n  notices that aren't on the checklist — the checklist primes attention, it doesn't cap\n  it.\n","CLAUDE.md":"# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n","tools/cqlstress-counter-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-counter-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-counter-example.yaml)","tools/cqlstress-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-example.yaml)","tools/cqlstress-insanity-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-insanity-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-insanity-example.yaml)","tools/cqlstress-lwt-example.yaml":"# Tools Skill\n\nPath: `tools/cqlstress-lwt-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-lwt-example.yaml)",".claude/skills/README.md":"# Skills Skill\n\nPath: `.claude/skills/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/README.md)",".claude/skills/install.sh":"# Claude Directive: install.sh\n\nPath: `.claude/skills/install.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/install.sh)",".claude/skills/heatmap/heatmap.py":"# Claude Directive: heatmap.py\n\nPath: `.claude/skills/heatmap/heatmap.py`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/heatmap/heatmap.py)",".claude/skills/shallow-review/EVAL-PROMPT.md":"# Shallow-review Skill\n\nPath: `.claude/skills/shallow-review/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/EVAL-PROMPT.md)",".claude/skills/bug-archaeology/references/EVAL-PROMPT.md":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/EVAL-PROMPT.md)",".claude/skills/bug-archaeology/references/per-bug-format.md":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/per-bug-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/per-bug-format.md)",".claude/skills/bug-archaeology/references/synthesis-format.md":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/synthesis-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/synthesis-format.md)",".claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md)",".claude/skills/cassandra-injvm-dtest/references/classloader_guide.md":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md)",".claude/skills/cassandra-injvm-dtest/references/cluster_utils.md":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md)",".claude/skills/patch-explainer/references/analysis_framework.md":"# References Skill\n\nPath: `.claude/skills/patch-explainer/references/analysis_framework.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/analysis_framework.md)",".claude/skills/patch-explainer/references/ascii_patterns.md":"# References Skill\n\nPath: `.claude/skills/patch-explainer/references/ascii_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/ascii_patterns.md)",".claude/skills/targeted-review/references/report-format.md":"# References Skill\n\nPath: `.claude/skills/targeted-review/references/report-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/report-format.md)",".claude/skills/targeted-review/references/subagent-prompt-template.md":"# References Skill\n\nPath: `.claude/skills/targeted-review/references/subagent-prompt-template.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/subagent-prompt-template.md)",".claude/skills/tla-plus/references/language.md":"# References Skill\n\nPath: `.claude/skills/tla-plus/references/language.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/language.md)",".claude/skills/tla-plus/references/pluscal.md":"# References Skill\n\nPath: `.claude/skills/tla-plus/references/pluscal.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/pluscal.md)",".claude/skills/tla-plus/scripts/check.sh":"# Claude Directive: check.sh\n\nPath: `.claude/skills/tla-plus/scripts/check.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/check.sh)",".claude/skills/tla-plus/scripts/parse.sh":"# Claude Directive: parse.sh\n\nPath: `.claude/skills/tla-plus/scripts/parse.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/parse.sh)",".claude/skills/tla-plus/scripts/setup.sh":"# Claude Directive: setup.sh\n\nPath: `.claude/skills/tla-plus/scripts/setup.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/setup.sh)",".claude/skills/tla-plus/scripts/tlc.sh":"# Claude Directive: tlc.sh\n\nPath: `.claude/skills/tla-plus/scripts/tlc.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/tlc.sh)",".claude/skills/tla-plus/scripts/translate.sh":"# Claude Directive: translate.sh\n\nPath: `.claude/skills/tla-plus/scripts/translate.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/translate.sh)",".claude/skills/tla-plus/templates/basic.tla":"# Claude Directive: basic.tla\n\nPath: `.claude/skills/tla-plus/templates/basic.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/basic.tla)",".claude/skills/tla-plus/templates/distributed.tla":"# Claude Directive: distributed.tla\n\nPath: `.claude/skills/tla-plus/templates/distributed.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/distributed.tla)",".claude/skills/tla-plus/templates/pluscal.tla":"# Claude Directive: pluscal.tla\n\nPath: `.claude/skills/tla-plus/templates/pluscal.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/pluscal.tla)",".claude/skills/write-reproducer/references/bug-taxonomy.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/bug-taxonomy.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/bug-taxonomy.md)",".claude/skills/write-reproducer/references/concurrency.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/concurrency.md)",".claude/skills/write-reproducer/references/distributed-systems.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/distributed-systems.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/distributed-systems.md)",".claude/skills/write-reproducer/references/failure-classification.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/failure-classification.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/failure-classification.md)",".claude/skills/write-reproducer/references/fuzzing.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/fuzzing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/fuzzing.md)",".claude/skills/write-reproducer/references/minimality-lattice.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/minimality-lattice.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimality-lattice.md)",".claude/skills/write-reproducer/references/minimization.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/minimization.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimization.md)",".claude/skills/write-reproducer/references/output-contract.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/output-contract.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/output-contract.md)",".claude/skills/write-reproducer/references/property-based-testing.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/property-based-testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/property-based-testing.md)",".claude/skills/write-reproducer/references/shrinking-checklist.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/shrinking-checklist.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/shrinking-checklist.md)",".claude/skills/write-reproducer/references/test-patterns.md":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/test-patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/test-patterns.md)",".claude/skills/write-reproducer/scripts/detect_context.sh":"# Claude Directive: detect_context.sh\n\nPath: `.claude/skills/write-reproducer/scripts/detect_context.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/detect_context.sh)",".claude/skills/write-reproducer/scripts/shrink_text.py":"# Claude Directive: shrink_text.py\n\nPath: `.claude/skills/write-reproducer/scripts/shrink_text.py`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/shrink_text.py)",".claude/skills/write-reproducer/scripts/validate_repro.sh":"# Claude Directive: validate_repro.sh\n\nPath: `.claude/skills/write-reproducer/scripts/validate_repro.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/validate_repro.sh)",".claude/skills/deep-review/references/deep/.gitkeep":"# Claude Directive: .gitkeep\n\nPath: `.claude/skills/deep-review/references/deep/.gitkeep`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/.gitkeep)",".claude/skills/deep-review/references/deep/deep-absence-completeness.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-absence-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-absence-completeness.md)",".claude/skills/deep-review/references/deep/deep-boundary.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-boundary.md)",".claude/skills/deep-review/references/deep/deep-concurrency.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-concurrency.md)",".claude/skills/deep-review/references/deep/deep-cross-cutting.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-cross-cutting.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-cross-cutting.md)",".claude/skills/deep-review/references/deep/deep-logic.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-logic.md)",".claude/skills/deep-review/references/deep/deep-resources.md":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-resources.md)",".claude/skills/targeted-review/references/categories/INDEX.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/INDEX.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/INDEX.md)",".claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md)",".claude/skills/targeted-review/references/categories/boundaries-and-numbers.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md)",".claude/skills/targeted-review/references/categories/concurrency-and-locking.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/concurrency-and-locking.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/concurrency-and-locking.md)",".claude/skills/targeted-review/references/categories/conditions-and-predicates.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/conditions-and-predicates.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/conditions-and-predicates.md)",".claude/skills/targeted-review/references/categories/io-and-crash-safety.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/io-and-crash-safety.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/io-and-crash-safety.md)",".claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md)",".claude/skills/targeted-review/references/categories/null-and-type-safety.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/null-and-type-safety.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/null-and-type-safety.md)",".claude/skills/targeted-review/references/categories/refactor-aftermath.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/refactor-aftermath.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/refactor-aftermath.md)",".claude/skills/targeted-review/references/categories/serialization-and-versioning.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/serialization-and-versioning.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/serialization-and-versioning.md)",".claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md)",".claude/skills/targeted-review/references/categories/validation-and-input-handling.md":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/validation-and-input-handling.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/validation-and-input-handling.md)",".claude/skills/tla-plus/references/patterns/code-to-spec.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/code-to-spec.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/code-to-spec.md)",".claude/skills/tla-plus/references/patterns/distributed-systems.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/distributed-systems.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/distributed-systems.md)",".claude/skills/tla-plus/references/patterns/invariants.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/invariants.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/invariants.md)",".claude/skills/tla-plus/references/patterns/protocols.md":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/protocols.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/protocols.md)",".claude/skills/shallow-review/references/general/specialists/absence.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/absence.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/absence.md)",".claude/skills/shallow-review/references/general/specialists/boundary.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/boundary.md)",".claude/skills/shallow-review/references/general/specialists/completeness.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/completeness.md)",".claude/skills/shallow-review/references/general/specialists/concurrency.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/concurrency.md)",".claude/skills/shallow-review/references/general/specialists/logic.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/logic.md)",".claude/skills/shallow-review/references/general/specialists/resources.md":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/resources.md)"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n","isInternal":false,"tokens":1077,"sizeBytes":4438},{"name":"EVAL-PROMPT.md","path":".claude/skills/bug-archaeology/references/EVAL-PROMPT.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/EVAL-PROMPT.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/EVAL-PROMPT.md)","tokens":300,"sizeBytes":228},{"name":"per-bug-format.md","path":".claude/skills/bug-archaeology/references/per-bug-format.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/per-bug-format.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/per-bug-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/per-bug-format.md)","tokens":300,"sizeBytes":234},{"name":"synthesis-format.md","path":".claude/skills/bug-archaeology/references/synthesis-format.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/synthesis-format.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/synthesis-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/synthesis-format.md)","tokens":300,"sizeBytes":238},{"name":"SKILL.md","path":".claude/skills/bug-archaeology/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/SKILL.md","title":"bug-archaeology","category":"anthropic-skill","format":"markdown","content":"---\nname: bug-archaeology\nversion: \"1.0.0\"\ndescription: >\n  Mine bug patterns from any git repository. Discovers bug-fix commits via git log\n  heuristics, analyzes each in parallel with subagents, writes individual analysis files,\n  and synthesizes a generalized PATTERNS.md with repo-specific details stripped.\n  Invoke explicitly with /bug-archaeology.\n---\n\n# Bug Archaeology\n\nSystematic extraction of reusable bug-detection heuristics from a repository's commit history.\n\n## Arguments\n\nAll optional. Parse from the user's invocation string.\n\n| Arg | Default | Description |\n|-----|---------|-------------|\n| `--range` | `HEAD~200..HEAD` | Git revision range |\n| `--path` | (all files) | Restrict to commits touching this path glob |\n| `--since` / `--until` | (none) | Date filter for `git log` |\n| `--limit` | 200 | Max bug-fix commits to analyze |\n| `--batch-size` | 10 | Commits per subagent |\n| `--output` | `./bug-archaeology/` | Output directory |\n\n## Workflow\n\nThree sequential phases. Each phase completes fully before the next starts.\n\n### Phase 1: Discovery\n\nFind bug-fix commits via git log heuristics.\n\n```bash\ngit log --no-merges --pretty=format:\"%H %s\" [--since=X] [--until=X] <range> [-- <path>] \\\n  | grep -iE '(fix|bug|patch|resolve|repair|correct|workaround|hotfix|regression|#[0-9]+|[A-Z]+-[0-9]+)'\n```\n\n**Filter out** commits whose message matches ONLY cosmetic keywords (`typo`, `whitespace`, `import`, `format`, `style`, `cleanup`, `rename`) with no bug keywords.\n\n**Truncate** to `--limit`.\n\n**Write** `QUEUE.txt` to the output directory:\n```\n0001 abc123def First line of commit message\n0002 def456abc Another commit message\n```\n\n**Resumption**: If `PROGRESS.md` exists, read it and exclude commits already marked `done` or `skipped`. Re-include `pending` and `error` entries.\n\n### Phase 2: Analysis (parallelized)\n\nSpawn subagents to analyze commits in batches. Each commit is independent.\n\n**Subagent prompt template** — adapt as needed:\n```\nRead the file at references/per-bug-format.md for the output format specification.\n\nAnalyze these commits from the repository at <REPO_PATH>:\n<list of \"NNNN hash message\" lines>\n\nFor each commit:\n1. Run: git show <hash>\n2. If the commit is cosmetic, test-only, refactor-only, or a merge with no\n   original changes — mark it as skipped with a one-word reason.\n3. Otherwise, write the analysis to <OUTPUT>/bug-<NNNN>-<slug>.md\n   following the format in per-bug-format.md exactly.\n\nReturn a status line per commit: NNNN <hash> done|skipped [reason-or-filename]\n```\n\n**Parallelism**: Launch up to 5 subagent batches concurrently. Wait for all to complete before the next wave.\n\n**Progress tracking**: After each wave, append results to `PROGRESS.md`:\n```markdown\n| # | Commit | Status | File / Reason |\n|---|--------|--------|---------------|\n| 0001 | abc123d | done | bug-0001-null-after-lookup.md |\n| 0002 | def456a | skipped | cosmetic |\n```\n\n**Errors**: Mark as `error` with a one-line reason. Don't retry — the user re-invokes with `--resume`.\n\n### Phase 3: Synthesis\n\nAfter all analysis is complete, produce `PATTERNS.md`. Read `references/synthesis-format.md` for the full specification.\n\n**Process**:\n1. Read all `bug-*.md` files in the output directory\n2. Parse the `Tags` section from each — extract `category` and `code-pattern`\n3. Group bugs by `code-pattern` tag\n4. For each group of 2+ bugs with the same code-pattern:\n   - Extract the shared Detection Rule (generalize if they differ across instances)\n   - Pick the most representative Example\n5. **Generalize** — strip repo-specific details:\n   - Replace specific class/method names with structural descriptions\n   - Remove ticket IDs, author names, project-specific subsystem labels\n   - Keep language-specific API names only if scope is that language or broader\n6. Group patterns by `category` and write `PATTERNS.md`\n7. Patterns with only 1 instance go in a \"Singletons\" section at the end\n\n## Reference Files\n\n| File | Loaded by | Purpose |\n|------|-----------|---------|\n| `references/per-bug-format.md` | Subagents (Phase 2) | Per-bug output template and field guidelines |\n| `references/synthesis-format.md` | Orchestrator (Phase 3) | PATTERNS.md structure and generalization rules |\n\n## Evaluating the Skill\n\nFull instructions are in `references/EVAL-PROMPT.md`. Summary:\n\n1. **Pick a bug** from the archaeology output and trace its introducing commit via `git blame`.\n2. **Extract the patch** with `git diff ${INTRO}~1 $INTRO`.\n3. **Choose a review skill** — the user must specify one:\n   - `/shallow-review` — quick 6-specialist parallel scan, any patch size\n   - `/deep-review` — focused on specific files, complex logic\n   - `/targeted-review` — findings-driven, medium-to-large patches\n   - `/mega-review` — large feature branches or 1000+ LOC diffs\n4. **Run the chosen skill** against the extracted patch.\n5. **Score** the output: Exact / Partial / Different bug / Miss.\n6. **Prod misses** — tell the skill what it missed and ask which checklist item would have caught it; use the answer to improve that skill's reference files.\n\nTarget: >90% hit rate (exact + partial), <5% miss rate across a batch of N bugs.\n","frontmatter":{"name":"bug-archaeology","version":"1.0.0","description":"Mine bug patterns from any git repository. Discovers bug-fix commits via git log heuristics, analyzes each in parallel with subagents, writes individual analysis files, and synthesizes a generalized PATTERNS.md with repo-specific details stripped. Invoke explicitly with /bug-archaeology.\n"},"isInternal":false,"tokens":1321,"sizeBytes":5180},{"name":"advanced_patterns.md","path":".claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md)","tokens":300,"sizeBytes":252},{"name":"classloader_guide.md","path":".claude/skills/cassandra-injvm-dtest/references/classloader_guide.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md)","tokens":300,"sizeBytes":252},{"name":"cluster_utils.md","path":".claude/skills/cassandra-injvm-dtest/references/cluster_utils.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md)","tokens":300,"sizeBytes":244},{"name":"SKILL.md","path":".claude/skills/cassandra-injvm-dtest/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/SKILL.md","title":"cassandra-injvm-dtest","category":"anthropic-skill","format":"markdown","content":"---\nname: cassandra-injvm-dtest\nversion: \"1.0.0\"\ndescription: Comprehensive guide for writing Apache Cassandra in-JVM distributed tests (dtests). Use when creating tests that simulate multi-node Cassandra clusters within a single JVM for faster integration testing. Covers cluster creation (single-node, multi-node, multi-datacenter), configuration (all cassandra.yaml parameters, features, network topology), instance lifecycle (startup/shutdown/restart), query execution, message filtering for failure scenarios, running code on instances, ClusterUtils utilities, and debugging classloader-related issues (serialization failures, same-class-different-classloader problems).\n---\n\n# Apache Cassandra In-JVM DTest Writer\n\n## Overview\n\nWrite comprehensive distributed tests for Apache Cassandra using the in-JVM dtest framework. This framework enables multi-node cluster simulation within a single JVM using isolated classloaders, providing fast and reliable integration testing without actual network communication.\n\n## Core Concepts\n\n### Framework Architecture\n\nThe in-JVM dtest framework uses **classloader isolation** to run multiple Cassandra instances in one JVM:\n\n- **Shared ClassLoader**: Common classes (primitives, APIs, config objects, byte buffers)\n- **Per-Instance ClassLoader**: Isolated Cassandra internals (DatabaseDescriptor, singletons, all C* code)\n- **IsolatedExecutor**: Marshals serialized lambdas across classloader boundaries\n- **Message Interception**: Inter-node messaging hooked at MessagingService level (no actual networking)\n\n### Key Classes\n\n| Class | Purpose | Location |\n|-------|---------|----------|\n| `Cluster` | Main entry point for creating clusters | `org.apache.cassandra.distributed.Cluster` |\n| `AbstractCluster` | Core cluster management | `org.apache.cassandra.distributed.impl.AbstractCluster` |\n| `Instance` | Individual Cassandra node | `org.apache.cassandra.distributed.impl.Instance` |\n| `InstanceConfig` | Node configuration | `org.apache.cassandra.distributed.impl.InstanceConfig` |\n| `ClusterUtils` | Utility methods | `org.apache.cassandra.distributed.shared.ClusterUtils` |\n| `ICoordinator` | Query execution interface | API package |\n| `MessageFilters` | Message filtering/dropping | `org.apache.cassandra.distributed.impl.MessageFilters` |\n\n## Quick Start\n\n### Basic Cluster Setup\n\n```java\nimport org.apache.cassandra.distributed.Cluster;\nimport org.apache.cassandra.distributed.api.ConsistencyLevel;\n\n// Create and start a 3-node cluster\ntry (Cluster cluster = Cluster.build(3).start()) {\n    // Create keyspace\n    cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                        \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n    // Create table\n    cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n    // Execute query\n    cluster.coordinator(1).execute(\"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                                  ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n    // Read data\n    Object[][] rows = cluster.coordinator(1).execute(\n        \"SELECT * FROM test.users WHERE id = ?\",\n        ConsistencyLevel.QUORUM, 1);\n}\n```\n\n### Test Base Class Pattern\n\n```java\nimport org.apache.cassandra.distributed.test.TestBaseImpl;\n\npublic class MyDTest extends TestBaseImpl {\n    private static Cluster cluster;\n\n    @BeforeClass\n    public static void setupCluster() throws IOException {\n        cluster = init(Cluster.build(3).start(), 2); // RF=2\n    }\n\n    @AfterClass\n    public static void teardownCluster() {\n        if (cluster != null)\n            cluster.close();\n    }\n\n    @Test\n    public void testSomething() {\n        // Test implementation\n    }\n}\n```\n\n## Cluster Creation Patterns\n\n### Pattern 1: Simple Single-Node Cluster\n\n```java\nCluster cluster = Cluster.build(1).start();\n```\n\n### Pattern 2: Multi-Node Cluster with Configuration\n\n```java\nCluster cluster = Cluster.build(3)\n    .withConfig(config -> config\n        .set(\"num_tokens\", \"256\")\n        .set(\"concurrent_reads\", \"64\")\n        .set(\"concurrent_writes\", \"64\"))\n    .start();\n```\n\n### Pattern 3: Multi-Datacenter Cluster\n\n```java\nCluster cluster = builder()\n    .withRacks(2, 1, 3)  // 2 DCs, 1 rack per DC, 3 nodes per rack\n    .start();\n\n// Or with explicit DC/rack naming\nCluster cluster = builder()\n    .withDC(\"dc1\", 3)\n    .withDC(\"dc2\", 3)\n    .start();\n```\n\n### Pattern 4: Cluster with Features\n\n```java\nimport static org.apache.cassandra.distributed.api.Feature.*;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withConfig(config -> config\n        .with(GOSSIP)           // Enable gossip protocol\n        .with(NETWORK)          // Enable inter-node networking\n        .with(NATIVE_PROTOCOL)  // Enable CQL protocol\n        .with(JMX))             // Enable JMX\n    .start();\n```\n\n### Pattern 5: Custom Token Distribution\n\n```java\nimport org.apache.cassandra.distributed.api.TokenSupplier;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(3))\n    .start();\n```\n\n### Pattern 6: Dynamic Port Allocation\n\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Configuration\n\n### Available Configuration Parameters\n\nConfiguration is applied via `config.set(key, value)` or `config.with(Feature)`:\n\n#### Network Configuration\n```java\nconfig.set(\"broadcast_address\", \"127.0.0.1\")\n      .set(\"listen_address\", \"127.0.0.1\")\n      .set(\"rpc_address\", \"127.0.0.1\")\n      .set(\"storage_port\", \"7000\")\n      .set(\"native_transport_port\", \"9042\")\n      .set(\"jmx_port\", \"7199\");\n```\n\n#### Token Configuration\n```java\nconfig.set(\"num_tokens\", \"256\")\n      .set(\"initial_token\", \"0\");\n```\n\n#### Memory Configuration\n```java\nconfig.set(\"memtable_heap_space\", \"512MiB\")\n      .set(\"key_cache_size\", \"50MiB\")\n      .set(\"counter_cache_size\", \"50MiB\")\n      .set(\"row_cache_size\", \"0MiB\");\n```\n\n#### Compaction & Concurrency\n```java\nconfig.set(\"concurrent_compactors\", \"4\")\n      .set(\"concurrent_reads\", \"32\")\n      .set(\"concurrent_writes\", \"32\")\n      .set(\"concurrent_counter_writes\", \"32\");\n```\n\n#### Commitlog Configuration\n```java\nconfig.set(\"commitlog_sync\", \"periodic\")\n      .set(\"commitlog_sync_period_in_ms\", \"10000\")\n      .set(\"commitlog_segment_size\", \"32MiB\");\n```\n\n#### Authentication & Authorization\n```java\nconfig.set(\"authenticator\", \"PasswordAuthenticator\")\n      .set(\"authorizer\", \"CassandraAuthorizer\")\n      .set(\"role_manager\", \"CassandraRoleManager\");\n```\n\n#### Accord Configuration (CEP-15)\n```java\nconfig.set(\"accord.enabled\", \"true\")\n      .set(\"accord.journal_directory\", \"/path/to/journal\");\n```\n\n#### Data Directories\n```java\n// Data directories are arrays\nconfig.set(\"data_file_directories\", new String[]{\"/path/to/data\"})\n      .set(\"commitlog_directory\", \"/path/to/commitlog\")\n      .set(\"hints_directory\", \"/path/to/hints\")\n      .set(\"saved_caches_directory\", \"/path/to/saved_caches\");\n```\n\n## Instance Lifecycle Operations\n\n### Starting Instances\n\n```java\n// Start with default settings\ninstance.startup();\n\n// Start with system properties\nClusterUtils.start(instance, properties -> {\n    properties.set(RING_DELAY, \"5000\");\n    properties.set(BOOTSTRAP_SCHEMA_DELAY_MS, \"5000\");\n});\n```\n\n### Stopping Instances\n\n```java\n// Graceful shutdown (blocking)\nClusterUtils.stopUnchecked(instance);\n\n// Abrupt shutdown (simulates kill -9)\nClusterUtils.stopAbrupt(cluster, instance);\n\n// Stop all instances\nClusterUtils.stopAll(cluster);\n\n// Async shutdown\nFuture<?> shutdownFuture = instance.shutdown();\nshutdownFuture.get(); // wait for completion\n```\n\n### Restarting Instances\n\n```java\n// Simple restart\nClusterUtils.restartUnchecked(instance);\n\n// Restart with different configuration\ninstance.shutdown().get();\ninstance.config().set(\"concurrent_reads\", \"64\");\ninstance.startup();\n```\n\n### Adding Instances\n\n```java\n// Add instance with same config as existing nodes\nIInstance newInstance = ClusterUtils.addInstance(cluster);\n\n// Add instance with custom config\nIInstance newInstance = ClusterUtils.addInstance(cluster, config -> {\n    config.set(\"auto_bootstrap\", true);\n});\n\n// Add instance to specific DC/rack\nIInstance newInstance = ClusterUtils.addInstance(cluster, \"dc1\", \"rack1\", config -> {\n    config.set(\"num_tokens\", \"256\");\n});\n\n// Start the new instance\nnewInstance.startup();\n```\n\n### Replacing Instances\n\n```java\n// Replace a failed node\nIInstance replacement = ClusterUtils.replaceHostAndStart(cluster, failedInstance);\n\n// Replace with custom properties\nIInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    failedInstance,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n```\n\n## Running Code on Instances\n\n### Pattern 1: Run Without Return Value\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    StorageService.instance.forceKeyspaceFlush(\"system\");\n});\n```\n\n### Pattern 2: Get Return Value (Sync)\n\n```java\nString version = cluster.get(1).callOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\n```\n\n### Pattern 3: Get Return Value (Async)\n\n```java\nFuture<String> future = cluster.get(1).asyncCallOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\nString version = future.get();\n```\n\n### Pattern 4: Pass Parameters\n\n```java\n// Parameters must be serializable\nint result = cluster.get(1).callOnInstance(() -> {\n    // Access Cassandra internals here\n    return ClusterMetadata.current().directory.allAddresses().size();\n});\n```\n\n### Pattern 5: Instance-to-Instance Operations\n\n```java\n// Get node ID from one instance, use it on another\nint nodeId = ClusterUtils.getNodeId(cluster.get(1), cluster.get(2));\n\nNodeId id = new NodeId(nodeId);\ncluster.get(2).runOnInstance(() -> {\n    StorageService.instance.cancelInProgressSequences(id);\n});\n```\n\n## Query Execution\n\n### Basic Queries\n\n```java\n// Execute without results\ncluster.coordinator(1).execute(\n    \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n    ConsistencyLevel.QUORUM,\n    1, \"Alice\"\n);\n\n// Execute with results\nObject[][] rows = cluster.coordinator(1).execute(\n    \"SELECT * FROM test.users WHERE id = ?\",\n    ConsistencyLevel.QUORUM,\n    1\n);\n```\n\n### Using Query Results\n\n```java\nimport org.apache.cassandra.distributed.api.SimpleQueryResult;\n\nSimpleQueryResult result = cluster.coordinator(1).executeWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nwhile (result.hasNext()) {\n    Row row = result.next();\n    int id = row.getInteger(\"id\");\n    String name = row.getString(\"name\");\n    System.out.println(\"User: \" + id + \", \" + name);\n}\n```\n\n### Pagination\n\n```java\nSimpleQueryResult result = cluster.coordinator(1).executeWithPagingWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM,\n    100  // page size\n);\n```\n\n### Async Execution\n\n```java\nFuture<SimpleQueryResult> future = cluster.coordinator(1).asyncExecuteWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nSimpleQueryResult result = future.get();\n```\n\n### Query with Tracing\n\n```java\nimport java.util.UUID;\n\nUUID sessionId = UUID.randomUUID();\nSimpleQueryResult result = cluster.coordinator(1).executeWithTracingWithResult(\n    sessionId,\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\n// Query tracing info from system_traces\ncluster.coordinator(1).execute(\n    \"SELECT * FROM system_traces.sessions WHERE session_id = ?\",\n    ConsistencyLevel.ONE,\n    sessionId\n);\n```\n\n### Internal Queries (No Coordinator)\n\n```java\n// Execute directly on instance internals (bypasses coordinator)\nSimpleQueryResult result = instance.executeInternalWithResult(\n    \"SELECT * FROM system.peers WHERE peer=?\",\n    expectedPeer.config().broadcastAddress().getAddress()\n);\n```\n\n## Message Filtering for Failure Injection\n\n### Pattern 1: Drop Messages Between Nodes\n\n```java\n// Drop all mutation requests from node 1 to node 2\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop()\n    .on();\n\n// Verify timeout behavior\nassertThatThrownBy(() ->\n    cluster.coordinator(1).execute(\n        \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n        ConsistencyLevel.ALL, 1, \"Alice\"\n    )\n).isInstanceOf(WriteTimeoutException.class);\n\n// Reset filters\ncluster.filters().reset();\n```\n\n### Pattern 2: Drop All Verbs\n\n```java\ncluster.filters()\n    .allVerbs()\n    .from(1).to(2)\n    .drop()\n    .on();\n```\n\n### Pattern 3: Drop Outbound Messages\n\n```java\ncluster.filters()\n    .outbound()\n    .from(1)\n    .verbs(Verb.READ_REQ.id)\n    .drop()\n    .on();\n```\n\n### Pattern 4: Custom Message Matching\n\n```java\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .messagesMatching((from, to, message) -> {\n        // Custom logic to match specific messages\n        return message.verb() == Verb.MUTATION_REQ.id;\n    })\n    .drop()\n    .on();\n```\n\n### Pattern 5: Temporary Filter Control\n\n```java\nIMessageFilters.Filter filter = cluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop();\n\nfilter.on();  // Enable\n// ... perform operations ...\nfilter.off(); // Disable\n```\n\n## ClusterUtils Reference\n\nFor comprehensive utilities, see [references/cluster_utils.md](references/cluster_utils.md).\n\n### Most Commonly Used Methods\n\n#### Lifecycle Management\n```java\nClusterUtils.stopUnchecked(instance);\nClusterUtils.stopAbrupt(cluster, instance);\nClusterUtils.restartUnchecked(instance);\nClusterUtils.stopAll(cluster);\n```\n\n#### Instance Management\n```java\nClusterUtils.addInstance(cluster, config -> {...});\nClusterUtils.replaceHostAndStart(cluster, toReplace);\nClusterUtils.start(instance, properties -> {...});\n```\n\n#### Ring & Gossip\n```java\nClusterUtils.awaitRingJoin(cluster.get(1), newInstance);\nClusterUtils.awaitRingHealthy(cluster.get(1));\nClusterUtils.awaitGossipStatus(instance, target, \"NORMAL\");\nClusterUtils.assertInRing(instance, expectedInRing);\n```\n\n#### CMS & Metadata\n```java\nClusterUtils.waitForCMSToQuiesce(cluster);\nEpoch epoch = ClusterUtils.getCurrentEpoch(instance);\nClusterUtils.fetchLogFromCMS(instance, awaitedEpoch);\n```\n\n#### Directories & Files\n```java\nList<File> dirs = ClusterUtils.getDataDirectories(instance);\nFile commitlog = ClusterUtils.getCommitLogDirectory(instance);\nFile hints = ClusterUtils.getHintsDirectory(instance);\n```\n\n## Schema Management\n\n### Creating Keyspaces\n\n```java\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n// Multi-DC keyspace\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'NetworkTopologyStrategy', \" +\n                    \"'dc1': 2, 'dc2': 2}\");\n```\n\n### Creating Tables\n\n```java\ncluster.schemaChange(\"CREATE TABLE test.users (\" +\n                    \"id int PRIMARY KEY, \" +\n                    \"name text, \" +\n                    \"email text)\");\n\n// With clustering\ncluster.schemaChange(\"CREATE TABLE test.events (\" +\n                    \"user_id int, \" +\n                    \"event_time timestamp, \" +\n                    \"event_type text, \" +\n                    \"PRIMARY KEY (user_id, event_time)) \" +\n                    \"WITH CLUSTERING ORDER BY (event_time DESC)\");\n```\n\n### Waiting for Schema Agreement\n\n```java\n// Manual wait\ntry (Cluster.SchemaChangeMonitor monitor = cluster.new SchemaChangeMonitor()) {\n    monitor.startPolling();\n    cluster.schemaChange(\"CREATE TABLE ...\");\n    monitor.waitForCompletion();\n}\n\n// Using ClusterUtils\nClusterUtils.awaitGossipSchemaMatch(cluster);\n```\n\n## Monitoring & Observables\n\n### Log Watching\n\n```java\n// Mark position and wait for log message\nlong mark = instance.logs().mark();\n// ... perform operation ...\ninstance.logs().watchFor(mark, \"Bootstrap completed\");\n\n// Grep logs\nList<String> errors = instance.logs().grep(\"ERROR\").getResult();\n```\n\n### Nodetool Integration\n\n```java\nimport org.apache.cassandra.distributed.api.NodeToolResult;\n\nNodeToolResult result = instance.nodetoolResult(\"status\");\nresult.asserts().success();\nString output = result.getStdout();\n\n// Common nodetool commands\ninstance.nodetool(\"flush\");\ninstance.nodetool(\"repair\");\ninstance.nodetool(\"compact\");\ninstance.nodetool(\"decommission\");\n```\n\n### Ring Information\n\n```java\nimport org.apache.cassandra.distributed.shared.ClusterUtils.RingInstanceDetails;\n\nList<RingInstanceDetails> ring = ClusterUtils.ring(instance);\nfor (RingInstanceDetails details : ring) {\n    System.out.println(\"Address: \" + details.getAddress());\n    System.out.println(\"Status: \" + details.getStatus());   // Up/Down\n    System.out.println(\"State: \" + details.getState());     // Normal/Leaving/Joining\n    System.out.println(\"Token: \" + details.getToken());\n}\n```\n\n### Gossip Information\n\n```java\nMap<String, Map<String, String>> gossip = ClusterUtils.gossipInfo(instance);\nfor (Map.Entry<String, Map<String, String>> entry : gossip.entrySet()) {\n    String address = entry.getKey();\n    Map<String, String> state = entry.getValue();\n    System.out.println(address + \" -> \" + state.get(\"STATUS\"));\n}\n```\n\n## Classloader Issues & Debugging\n\n### Understanding Classloader Isolation\n\nThe in-JVM dtest framework uses multiple classloaders for isolation:\n- **Test ClassLoader**: Where your test code runs\n- **Shared ClassLoader**: Primitives, APIs, config objects\n- **Instance ClassLoaders**: Per-instance Cassandra code (isolated)\n\n### Common Classloader Issues\n\n#### Issue 1: Same Class, Different ClassLoaders\n\n**Symptom**: `ClassCastException` even though classes appear identical\n\n```java\n// WRONG - This will fail\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in test classloader\n    // Try to use token with instance internals -> ClassCastException\n});\n\n// CORRECT - Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in instance classloader\n    // Now token is in correct classloader\n});\n```\n\n#### Issue 2: Serialization Failures\n\n**Symptom**: `NotSerializableException` or `ClassNotFoundException`\n\n```java\n// WRONG - Non-serializable lambda capture\nString localVar = \"test\";\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar); // May fail if localVar isn't Serializable\n});\n\n// CORRECT - Only pass serializable primitives\nfinal String localVar = \"test\"; // String is Serializable\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar);\n});\n```\n\n**Lambdas are serialized** and transferred across classloaders. Only capture:\n- Primitives (int, long, String, etc.)\n- Serializable objects marked with `@Shared`\n- Nothing else from test classloader\n\n#### Issue 3: Static State Not Shared\n\n**Symptom**: Static fields don't reflect changes across instances\n\n```java\n// Each instance has its own DatabaseDescriptor, StorageService, etc.\n// Static state is NOT shared between instances\n\n// To coordinate across instances, use:\n// 1. CQL queries to share data\n// 2. Message passing\n// 3. Instance-specific operations\n```\n\n### Debugging Techniques\n\n#### Technique 1: Print Classloader Information\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(\"ClassLoader: \" +\n        Thread.currentThread().getContextClassLoader());\n    System.out.println(\"Token class loader: \" +\n        Token.class.getClassLoader());\n});\n```\n\n#### Technique 2: Transfer Objects Explicitly\n\n```java\nimport org.apache.cassandra.distributed.impl.IsolatedExecutor;\n\n// Transfer object to instance classloader\nSerializable transferred = instance.transfer(mySerializableObject);\n```\n\n#### Technique 3: Use @Shared and @Isolated Annotations\n\n```java\n// In your test code\nimport org.apache.cassandra.utils.Shared;\nimport org.apache.cassandra.utils.Isolated;\n\n@Shared  // Loaded in shared classloader\npublic class MySharedClass implements Serializable {\n    // Can be shared across boundaries\n}\n\n@Isolated  // Each instance gets own copy\npublic class MyIsolatedClass {\n    // Not shared\n}\n```\n\n#### Technique 4: Check Serialization\n\n```java\n// Verify object can be serialized\ntry {\n    ByteArrayOutputStream baos = new ByteArrayOutputStream();\n    ObjectOutputStream oos = new ObjectOutputStream(baos);\n    oos.writeObject(myObject);\n    oos.close();\n    System.out.println(\"Object is serializable\");\n} catch (NotSerializableException e) {\n    System.out.println(\"Object is NOT serializable: \" + e.getMessage());\n}\n```\n\n### Best Practices for Classloader Safety\n\n1. **Keep lambdas simple**: Minimize captured variables\n2. **Use primitives**: Pass int, String, long instead of complex objects\n3. **Create objects inside runOnInstance**: Don't create in test, pass to instance\n4. **Avoid static state**: Don't rely on static fields across instances\n5. **Use coordinator for data sharing**: Query data rather than passing objects\n\n## Advanced Patterns\n\n### Pattern: Pausing & Resuming CMS Operations\n\n```java\n// Pause before committing at specific epoch\nCallable<Epoch> pauseHandle = ClusterUtils.pauseBeforeCommit(\n    cmsInstance,\n    transformation -> transformation instanceof AddNode\n);\n\n// Wait for pause\nEpoch epoch = pauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseCommits(cmsInstance);\n```\n\n### Pattern: Pausing Enactment\n\n```java\n// Pause before enacting specific epoch\nCallable<Void> pauseHandle = ClusterUtils.pauseBeforeEnacting(instance, epoch);\n\n// Wait for pause\npauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseEnactment(instance);\n```\n\n### Pattern: Testing with Log Monitoring\n\n```java\nClusterUtils.runAndWaitForLogs(\n    () -> {\n        cluster.coordinator(1).execute(\"INSERT INTO test.users VALUES (1, 'Alice')\",\n                                      ConsistencyLevel.QUORUM);\n    },\n    \"Mutation applied\",\n    cluster.get(1), cluster.get(2), cluster.get(3)\n);\n```\n\n### Pattern: Custom Instance Initialization\n\n```java\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withInstanceInitializer((cl, i) -> {\n        // Custom initialization logic\n        System.out.println(\"Initializing instance \" + i);\n    })\n    .start();\n```\n\n### Pattern: Testing Node Replacement\n\n```java\n// Original node\nIInvokableInstance original = cluster.get(2);\n\n// Stop original\nClusterUtils.stopAbrupt(cluster, original);\n\n// Replace with new node\nIInvokableInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    original,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n\n// Verify replacement joined\nClusterUtils.awaitRingJoin(cluster.get(1), replacement);\n```\n\n### Pattern: Testing Decommission\n\n```java\nIInvokableInstance leaving = cluster.get(3);\n\nboolean success = ClusterUtils.decommission(leaving);\nAssert.assertTrue(\"Decommission failed\", success);\n\n// Verify node left\nClusterUtils.assertNotInRing(cluster.get(1), leaving);\n```\n\n### Pattern: Multi-DC Token Ranges\n\n```java\nList<ClusterUtils.Range> ranges = ClusterUtils.getPrimaryRanges(\n    cluster.get(1),\n    \"test\"  // keyspace\n);\n\nfor (ClusterUtils.Range range : ranges) {\n    System.out.println(\"Range: \" + range.left() + \" to \" + range.right());\n}\n```\n\n## Complete Test Examples\n\n### Example 1: Basic Read/Write Test\n\n```java\npublic class BasicReadWriteTest extends TestBaseImpl {\n    @Test\n    public void testReadWrite() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n            // Write\n            cluster.coordinator(1).execute(\n                \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n            // Read\n            Object[][] rows = cluster.coordinator(2).execute(\n                \"SELECT * FROM test.users WHERE id = ?\",\n                ConsistencyLevel.QUORUM, 1);\n\n            Assert.assertEquals(1, rows.length);\n            Assert.assertEquals(1, rows[0][0]);\n            Assert.assertEquals(\"Alice\", rows[0][1]);\n        }\n    }\n}\n```\n\n### Example 2: Testing Write Timeout with Message Filtering\n\n```java\npublic class WriteTimeoutTest extends TestBaseImpl {\n    @Test\n    public void testWriteTimeout() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 3}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY, v int)\");\n\n            // Drop mutations to node 2 and 3\n            cluster.filters().inbound()\n                .to(2, 3)\n                .verbs(Verb.MUTATION_REQ.id)\n                .drop()\n                .on();\n\n            // This should timeout (can't reach QUORUM)\n            try {\n                cluster.coordinator(1).execute(\n                    \"INSERT INTO test.data (k, v) VALUES (?, ?)\",\n                    ConsistencyLevel.QUORUM, 1, 100);\n                Assert.fail(\"Expected WriteTimeoutException\");\n            } catch (RuntimeException e) {\n                Assert.assertTrue(e.getCause() instanceof WriteTimeoutException);\n            }\n\n            cluster.filters().reset();\n        }\n    }\n}\n```\n\n### Example 3: Testing Node Addition\n\n```java\npublic class NodeAdditionTest extends TestBaseImpl {\n    @Test\n    public void testAddNode() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n            // Add and start new node\n            IInvokableInstance newNode = ClusterUtils.addInstance(cluster, config -> {\n                config.set(\"auto_bootstrap\", true);\n            });\n            newNode.startup();\n\n            // Wait for node to join\n            ClusterUtils.awaitRingJoin(cluster.get(1), newNode);\n\n            // Verify all nodes see the new node\n            ClusterUtils.assertInRing(cluster.get(1), newNode);\n            ClusterUtils.assertInRing(cluster.get(2), newNode);\n        }\n    }\n}\n```\n\n### Example 4: Running Code on Instance\n\n```java\npublic class InstanceCodeTest extends TestBaseImpl {\n    @Test\n    public void testRunOnInstance() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 1}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Insert data\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.ONE);\n\n            // Force flush on node 1\n            cluster.get(1).runOnInstance(() -> {\n                StorageService.instance.forceKeyspaceFlush(\"test\");\n            });\n\n            // Verify flush happened by checking for sstables\n            int sstableCount = cluster.get(1).callOnInstance(() -> {\n                ColumnFamilyStore cfs = Keyspace.open(\"test\")\n                                               .getColumnFamilyStore(\"data\");\n                return cfs.getLiveSSTables().size();\n            });\n\n            Assert.assertTrue(\"Expected at least one sstable\", sstableCount > 0);\n        }\n    }\n}\n```\n\n### Example 5: Multi-DC Test\n\n```java\npublic class MultiDCTest extends TestBaseImpl {\n    @Test\n    public void testMultiDC() throws IOException {\n        try (Cluster cluster = builder()\n                                  .withRacks(2, 1, 2)  // 2 DCs, 1 rack each, 2 nodes per rack\n                                  .start()) {\n\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'NetworkTopologyStrategy', \" +\n                                \"'datacenter1': 2, 'datacenter2': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Write from DC1\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.LOCAL_QUORUM);\n\n            // Read from DC2\n            Object[][] rows = cluster.coordinator(3).execute(\n                \"SELECT * FROM test.data WHERE k = 1\",\n                ConsistencyLevel.LOCAL_QUORUM);\n\n            Assert.assertEquals(1, rows.length);\n        }\n    }\n}\n```\n\n## Troubleshooting Guide\n\n### Problem: Tests are flaky or hang\n\n**Possible causes:**\n1. Schema not fully agreed before operations\n2. Insufficient timeout for async operations\n3. Message filters not properly reset\n\n**Solutions:**\n```java\n// Wait for schema agreement\nClusterUtils.awaitGossipSchemaMatch(cluster);\n\n// Use longer timeouts for operations\nfuture.get(30, TimeUnit.SECONDS);\n\n// Always reset filters in finally block\ntry {\n    cluster.filters().inbound().drop().on();\n    // test code\n} finally {\n    cluster.filters().reset();\n}\n```\n\n### Problem: ClassCastException with tokens or types\n\n**Cause:** Object created in wrong classloader\n\n**Solution:**\n```java\n// Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0);\n    // Use token here\n});\n```\n\n### Problem: NoClassDefFoundError or ClassNotFoundException\n\n**Cause:** Class not available in instance classloader\n\n**Solution:** Ensure class is in Cassandra dependencies or marked `@Shared`\n\n### Problem: Test times out waiting for ring/gossip\n\n**Cause:** Network features not enabled\n\n**Solution:**\n```java\nCluster cluster = builder()\n    .withConfig(c -> c.with(GOSSIP, NETWORK))\n    .start();\n```\n\n### Problem: Port conflicts\n\n**Cause:** Static port allocation\n\n**Solution:**\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Additional Resources\n\n- **ClusterUtils**: See [references/cluster_utils.md](references/cluster_utils.md) for exhaustive utility method documentation\n- **Advanced Patterns**: See [references/advanced_patterns.md](references/advanced_patterns.md) for CMS operations, Accord testing, and complex scenarios\n- **Classloader Deep Dive**: See [references/classloader_guide.md](references/classloader_guide.md) for detailed classloader mechanics and debugging\n","frontmatter":{"name":"cassandra-injvm-dtest","version":"1.0.0","description":"Comprehensive guide for writing Apache Cassandra in-JVM distributed tests (dtests). Use when creating tests that simulate multi-node Cassandra clusters within a single JVM for faster integration testing. Covers cluster creation (single-node, multi-node, multi-datacenter), configuration (all cassandra.yaml parameters, features, network topology), instance lifecycle (startup/shutdown/restart), query execution, message filtering for failure scenarios, running code on instances, ClusterUtils utilities, and debugging classloader-related issues (serialization failures, same-class-different-classloader problems)."},"isInternal":false,"tokens":6931,"sizeBytes":30586},{"name":"deep-absence-completeness.md","path":".claude/skills/deep-review/references/deep/deep-absence-completeness.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-absence-completeness.md","title":"Deep Skill","category":"anthropic-skill","format":"markdown","content":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-absence-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-absence-completeness.md)","tokens":300,"sizeBytes":252},{"name":"deep-boundary.md","path":".claude/skills/deep-review/references/deep/deep-boundary.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-boundary.md","title":"Deep Skill","category":"anthropic-skill","format":"markdown","content":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-boundary.md)","tokens":300,"sizeBytes":228},{"name":"deep-concurrency.md","path":".claude/skills/deep-review/references/deep/deep-concurrency.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-concurrency.md","title":"Deep Skill","category":"anthropic-skill","format":"markdown","content":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-concurrency.md)","tokens":300,"sizeBytes":234},{"name":"deep-cross-cutting.md","path":".claude/skills/deep-review/references/deep/deep-cross-cutting.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-cross-cutting.md","title":"Deep Skill","category":"anthropic-skill","format":"markdown","content":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-cross-cutting.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-cross-cutting.md)","tokens":300,"sizeBytes":238},{"name":"deep-logic.md","path":".claude/skills/deep-review/references/deep/deep-logic.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-logic.md","title":"Deep Skill","category":"anthropic-skill","format":"markdown","content":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-logic.md)","tokens":300,"sizeBytes":222},{"name":"deep-resources.md","path":".claude/skills/deep-review/references/deep/deep-resources.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-resources.md","title":"Deep Skill","category":"anthropic-skill","format":"markdown","content":"# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-resources.md)","tokens":300,"sizeBytes":230},{"name":"SKILL.md","path":".claude/skills/deep-review/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/SKILL.md","title":"deep-review","category":"anthropic-skill","format":"markdown","content":"---\nname: deep-review\nversion: \"1.0.0\"\ndescription: >\n  Deep file-focused code review for correctness bugs. Unlike shallow-review which runs 6\n  specialists in parallel across the entire patch, deep-review focuses on user-specified\n  files with full pattern catalogs (500+ patterns), codebase investigation, and source-level\n  context gathering. Use when: the user specifies particular files for focused review, a\n  shallow review flagged areas that need deeper investigation, reviewing critical-path code\n  changes, examining complex serialization/lifecycle/state-machine changes. The user\n  instructs which files to focus on (typically a subset of files in the patch).\n---\n\n# Deep Code Review\n\nFocused, thorough review of user-specified files using the full 500+ pattern catalog.\nEach file is reviewed with context gathering (reading source, not just diff), codebase\nsearches, and cross-referencing against the complete pattern database.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n                    +--------v---------+\n                    | User selects     |\n                    | focus files      |\n                    +--------+---------+\n                             |\n              +--------------+--------------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 0: Context  |       | Phase 0: Context      |\n    | (read full files, |       | (read full files,     |\n    |  callers, types)  |       |  callers, types)      |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 1: Deep     |       | Phase 1: Deep         |\n    | specialist review |       | specialist review     |\n    | (full checklists) |       | (full checklists)     |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 2: Codebase |       | Phase 2: Codebase     |\n    | investigation     |       | investigation         |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n              +--------------+--------------+\n                             |\n                    +--------v---------+\n                    | Phase 3: Cross-  |\n                    | file symmetry &  |\n                    | merge findings   |\n                    +------------------+\n```\n\n## Quick Start\n\n1. **Receive patch** and user's file focus list\n2. **For each focus file**: run Phase 0 (context), Phase 1 (deep checklists), Phase 2 (search)\n3. **Cross-file symmetry** pass across all focus files\n4. **Merge & report** with confidence ranking\n\n---\n\n## Phase 0: Context Gathering (per focus file)\n\nBefore touching any checklist, deeply understand each focus file. This is the key difference\nfrom shallow review — you read the actual source, not just the diff.\n\n**Prompt template**:\n```\nRead the full source of the focus file: `{FILE_PATH}`\nRead the patch for context: `{PATCH_PATH}`\n\nFor this file, gather:\n1. CLASS HIERARCHY: What does it extend? What interfaces? Read the parent class/interface.\n2. SIBLING CLASSES: Are there parallel implementations? Read at least one sibling.\n3. CALLERS: Who calls the modified methods? How do they use return values? (grep + read)\n4. LIFECYCLE: When is this object created, used, destroyed?\n5. STATE MACHINE (if applicable): Map every state and every transition. What events are handled\n   in each state? What events are *not* handled (missing transitions)? What states are never\n   reached? Where is this state enum pattern-matched — are all states covered at every match site?\n6. INVARIANTS: Read Javadoc, assertions, and any test files for this class.\n7. SERIALIZATION: If it serializes — read serialize, deserialize, serializedSize together.\n\nOutput a structured context summary for use by the deep review phases.\n```\n\n---\n\n## Phase 1: Deep Specialist Review (per focus file)\n\nEach focus file is reviewed against the FULL domain checklists (not the trimmed shallow\nversions). The reviewer selects which domains apply based on Phase 0 context.\n\n### Domain Selection\n\nBased on Phase 0 context, load the relevant deep checklists:\n\n| File contains | Load checklist |\n|---|---|\n| Conditions, comparisons, control flow, types | `references/deep/deep-logic.md` |\n| Arithmetic, indices, ranges, ByteBuffer, I/O | `references/deep/deep-boundary.md` |\n| Shared state, locks, lifecycle, state machines | `references/deep/deep-concurrency.md` |\n| Serialization, resources, metrics, config | `references/deep/deep-resources.md` |\n| New classes, new fields, registrations | `references/deep/deep-absence-completeness.md` |\n| Refactoring, merges, shell scripts, parsing | `references/deep/deep-cross-cutting.md` |\n\nTypically 2-4 domains are relevant per file. Load all relevant ones.\n\n**Prompt template**:\n```\nYou are performing a DEEP REVIEW of: `{FILE_PATH}`\n\nCONTEXT (from Phase 0):\n{CONTEXT_SUMMARY}\n\nPATCH (the changes being reviewed):\nRead: `{PATCH_PATH}`\n\nCHECKLISTS (load each relevant one):\nRead: `{SKILL_DIR}/references/deep/deep-logic.md`\nRead: `{SKILL_DIR}/references/deep/deep-boundary.md`\n[... load relevant domains ...]\n\nFor EVERY checklist item that could apply to this file:\n1. Check whether the pattern exists in the code\n2. If the pattern matches: search the codebase for confirming/refuting evidence\n3. Rate confidence: High (confirmed by evidence), Medium (pattern matches but\n   uncertain), Low (possible but speculative)\n\nReport ALL findings. For each:\n- Pattern ID and name\n- Location (file:line)\n- Confidence (High/Medium/Low)\n- What's wrong (2-3 sentences with reasoning)\n- Evidence gathered (what you searched for, what you found/didn't find)\n- Suggested fix\n\nOr \"No finding in this domain for this file\" if nothing applies.\n```\n\n---\n\n## Phase 2: Codebase Investigation (per focus file)\n\nFor each finding from Phase 1, and for absence/completeness patterns, execute targeted\ncodebase searches.\n\n**Search patterns to execute:**\n\n### For new fields:\n```bash\ngrep -rn \"serialize\\|deserialize\\|serializedSize\\|equals\\|hashCode\\|toString\" {FILE_DIR}/\n```\n\n### For new registrations:\n```bash\ngrep -rn \"addListener\\|register\\|subscribe\\|addMetric\\|removeSensor\\|deregister\" {FILE_DIR}/\n```\n\n### For new enum constants:\n```bash\ngrep -rn \"switch.*{ENUM_TYPE}\\|case.*{CONSTANT}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For interface implementations:\n```bash\ngrep -rn \"implements {INTERFACE}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For method callers:\n```bash\ngrep -rn \"{METHOD_NAME}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For parallel paths:\n```bash\ngrep -rn \"class.*extends.*{PARENT_CLASS}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n**Prompt template**:\n```\nYou are investigating findings from the deep review of: `{FILE_PATH}`\n\nFINDINGS TO INVESTIGATE:\n{PHASE_1_FINDINGS}\n\nFor each finding:\n1. Execute the relevant codebase searches (grep, read files)\n2. Confirm or refute the finding based on evidence\n3. If confirmed: search for additional instances of the same pattern\n4. If refuted: explain why with evidence\n\nFor absence patterns:\n1. Build the search list from the diff events\n2. Execute each search\n3. If no match found: report as confirmed finding\n4. If match found: report as refuted (the symmetric code exists)\n\nReport updated findings with evidence.\n```\n\n---\n\n## Phase 3: Cross-File Symmetry & Merge\n\nAfter all focus files are reviewed:\n\n**Prompt template**:\n```\nReview findings across all focus files for cross-file patterns:\n\n1. CROSS-FILE SYMMETRY: For each change in file A, is there a structurally parallel\n   change needed in file B? Check:\n   - Serialization families (if serialize changed, did deserialize change?)\n   - Interface implementations (if one implementation changed, do siblings need it?)\n   - Version-gated paths (if one version branch changed, do others?)\n   - Test coverage (does the test file cover the changed behavior?)\n\n2. FINDING REINFORCEMENT: Do findings across files reinforce each other?\n   - Logic + Absence at same conceptual location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Pattern flagged in multiple files → likely systematic issue\n\n3. MERGE & DEDUP: Combine all findings, deduplicate, rank.\n\n4. THREE-POINT TEST each finding:\n   - The code construct actually exists (not inferred)\n   - The bug is possible given visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n```\n\n---\n\n## Report Format\n\n```\n## Deep Review: [target]\n\n### Focus Files\n- `path/to/File1.java` — [brief description of changes]\n- `path/to/File2.java` — [brief description of changes]\n\n### Context Summary\n[Key facts from Phase 0: class hierarchy, lifecycle, shared state, invariants]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Domain**: [Logic / Boundary / Concurrency / Resources / Absence / Completeness]\n- **Pattern**: [pattern name from checklist]\n- **What's wrong**: [2-3 sentences with reasoning]\n- **Evidence**: [what was searched, what was found]\n- **Suggested fix**: [specific change]\n\n#### Finding 2: ...\n\n### Domain Coverage (per file)\n| File | Logic | Boundary | Concurrency | Resources | Absence | Completeness |\n|---|---|---|---|---|---|---|\n| File1.java | 2 findings | - | 1 finding | - | checked | checked |\n| File2.java | - | 1 finding | - | 3 findings | checked | checked |\n\n### Cross-File Symmetry\n- [Any asymmetries found]\n- [Any reinforcing patterns]\n```\n\n---\n\n## Reference Files\n\n### Deep specialist checklists\n- `references/deep/deep-logic.md` — Full logic, types, constants, filtering patterns\n- `references/deep/deep-boundary.md` — Full boundary, overflow, null, I/O patterns\n- `references/deep/deep-concurrency.md` — Full concurrency, state, lifecycle patterns\n- `references/deep/deep-resources.md` — Full serialization, resource, crash-safety patterns\n- `references/deep/deep-absence-completeness.md` — Full absence + completeness with search methodology\n- `references/deep/deep-cross-cutting.md` — Refactoring, parsing, platform, dispatch patterns\n","frontmatter":{"name":"deep-review","version":"1.0.0","description":"Deep file-focused code review for correctness bugs. Unlike shallow-review which runs 6 specialists in parallel across the entire patch, deep-review focuses on user-specified files with full pattern catalogs (500+ patterns), codebase investigation, and source-level context gathering. Use when: the user specifies particular files for focused review, a shallow review flagged areas that need deeper investigation, reviewing critical-path code changes, examining complex serialization/lifecycle/state-machine changes. The user instructs which files to focus on (typically a subset of files in the patch).\n"},"isInternal":false,"tokens":2407,"sizeBytes":10396},{"name":"SKILL.md","path":".claude/skills/heatmap/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/heatmap/SKILL.md","title":"heatmap","category":"anthropic-skill","format":"markdown","content":"---\nname: heatmap\nversion: \"1.0.0\"\ndescription: Use git heatmap analysis to identify high-churn files and lines as candidates for thorough review or bug hunting. Works for PR reviews, security audits, bug hunts, or any code analysis task.\n---\n\n# Heatmap-Guided Review\n\nUse the bundled `heatmap.py` script to identify the hottest (most frequently and recently changed) code in a repository, then focus review effort on those areas. Hot code is statistically more likely to contain bugs: it changes often, accumulates complexity, and is where active development risk concentrates.\n\n## When to use\n\nInvoke this skill whenever you want to prioritize where to look in a codebase — during PR reviews, bug hunts, security audits, onboarding exploration, or any task where you need to decide which files and lines deserve the closest attention.\n\n## Prerequisites\n\n- Python 3 must be available.\n- The target must be a git repository.\n- The heatmap script is bundled with this skill at `~/.claude/skills/heatmap/heatmap.py`. All commands below use `HEATMAP` as a placeholder:\n  ```bash\n  HEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n  ```\n  If `heatmap` is available on PATH, you may use that instead.\n\n## Workflow\n\n### Step 1: Determine the repository path and scope\n\nFigure out the git repository root. If the user provided a repo path, use that. If working in a repo already, use the current directory. If reviewing a PR, determine which files were changed.\n\n```bash\nHEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n# Find the repo root\ngit -C <path> rev-parse --show-toplevel\n```\n\n### Step 2: Run repo-level heatmap\n\nGet the hottest files in the repository. Use `--json` for machine-readable output. Adjust `--top` based on context (20-50 for a broad scan, more for large repos).\n\n```bash\npython3 \"$HEATMAP\" repo --json --top 50 <repo_path>\n```\n\nThis returns JSON array of objects with: `path`, `heat`, `commits`, `last_modified_days`.\n\n### Step 3: Cross-reference with the task context\n\n**For PR reviews:** Intersect the heatmap results with the files changed in the PR. Files that are both changed in the PR AND high on the heatmap are the highest-priority review targets — they are already complex/volatile and the PR is adding more changes to them.\n\n```bash\n# Get PR changed files\ngit diff --name-only <base_branch>...HEAD\n```\n\n**For bug hunts:** The hottest files ARE the candidates — frequent recent changes correlate with bugs. Focus on the top 10-20.\n\n**For security audits:** Filter heatmap results to security-sensitive paths (auth, crypto, input parsing, network, serialization).\n\n**For general exploration:** Use the heatmap as a map of where active development is happening.\n\n### Step 4: Run line-level heatmap on top candidates\n\nFor each high-priority file (typically 3-8 files), run the line-level heatmap to find the hottest regions within those files.\n\n```bash\npython3 \"$HEATMAP\" file --json <file_path_relative_to_repo> <repo_path>\n```\n\nThis returns JSON array of objects with: `line`, `heat`, `content`.\n\n### Step 5: Identify hot zones\n\nFrom the line-level results, identify contiguous regions of high heat. These \"hot zones\" are where to focus review. Look for:\n\n- **Clusters of hot lines** — contiguous blocks of high-heat code indicate areas under active rework. These are prime bug candidates because:\n  - Multiple recent changes suggest the logic is not yet settled\n  - Each change is an opportunity for regression\n  - Complex interactions between recent changes may not be fully tested\n\n- **Hot lines surrounded by cold code** — surgical edits in otherwise stable code may indicate bug fixes, workarounds, or special-case handling that deserves scrutiny.\n\n- **Hot function/method boundaries** — if a method signature or its first few lines are hot, the contract may have changed recently, affecting all callers.\n\n### Step 6: Produce the review focus list\n\nOutput a ranked list of review targets, structured as:\n\n```\n## Heatmap Review Targets\n\n### Priority 1: <file_path> (heat: X, commits: Y)\n- **Hot zones**: lines A-B (description of what this code does)\n- **Why it matters**: <context — e.g., \"most changed file in repo AND modified in this PR\">\n- **What to look for**: <specific guidance based on the code — race conditions, edge cases, etc.>\n\n### Priority 2: ...\n```\n\n### Step 7: Deep review\n\nFor each priority target, read the hot zones and perform the actual review. The heatmap tells you WHERE to look; your expertise tells you WHAT to look for. Common patterns in hot code:\n\n- **State management bugs**: Hot code often manages complex state. Check for inconsistent updates, missing synchronization, or partial failures.\n- **Edge cases**: Frequent changes often mean edge cases keep being discovered. Look for more.\n- **Regression risk**: If code was recently fixed, check whether the fix is complete and doesn't break other paths.\n- **Missing tests**: Hot code that lacks test coverage is the highest-risk combination.\n\n## Output format\n\nAlways present findings as a prioritized list with:\n1. File path and heat metrics\n2. Specific line ranges to focus on\n3. What the hot code does (brief)\n4. What risks to look for (specific to the code, not generic)\n\n## Tips\n\n- Heat is relative — compare files against each other, not against an absolute threshold.\n- Files with high heat but few commits have large individual changes (risky). Files with high heat and many commits are under constant churn (also risky, differently).\n- `last_modified_days` close to 0 means very recent changes — highest chance of unfound bugs.\n- Use `--since` to adjust the time window. Default is 2 years. For recent bug hunts, try `--since \"6 months ago\"`.\n- The `--no-color` flag is useful when piping output, but prefer `--json` for programmatic use.\n","frontmatter":{"name":"heatmap","version":"1.0.0","description":"Use git heatmap analysis to identify high-churn files and lines as candidates for thorough review or bug hunting. Works for PR reviews, security audits, bug hunts, or any code analysis task."},"isInternal":false,"tokens":1312,"sizeBytes":5779},{"name":"SKILL.md","path":".claude/skills/mega-review/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/mega-review/SKILL.md","title":"mega-review","category":"anthropic-skill","format":"markdown","content":"---\nname: mega-review\nversion: \"1.0.0\"\ndescription: >\n  Multi-pass deep code review for large patches (1000+ LOC) that maximizes real bug detection.\n  Orchestrates targeted-review, shallow-review, and deep-review in parallel across all HIGH and\n  MEDIUM risk files and commits: understands the feature holistically, splits by file and commit,\n  runs deep review on every HIGH/MEDIUM file, targeted review across the same scope, and\n  per-commit shallow review, followed by cross-cut consistency checks. Use when: reviewing a\n  large patch (feature branch, multi-commit, or single large diff, 1000+ LOC), doing a thorough\n  pre-merge review, or when shallower reviews miss bugs due to patch size. Triggers on: \"review\n  this branch\", \"review these commits\", \"review this feature\", \"mega review\", \"thorough review\",\n  \"full review of X commits\", or when the user specifies a commit range or feature for review.\n---\n\n# Mega-Review: Multi-Pass Large Patch Review\n\nThis skill orchestrates `/targeted-review`, `/shallow-review`, and `/deep-review` with\ncross-cut consistency checks to maximize bug detection on large patches (1000+ LOC). The input\ncan be a commit range, a feature branch, or any large diff — it does not have to span multiple\ncommits.\n\n**You MUST invoke `/targeted-review`, `/shallow-review`, and `/deep-review` as part of this\nworkflow.** Those skills have specialist checklists, pattern catalogs, and structured review\nprocesses that this skill does not duplicate. This skill's job is to understand the change\nholistically, decompose it into reviewable chunks, and delegate the actual code review to the\nappropriate sub-skills at the right granularity.\n\n## Why This Exists\n\nA single pass of `/shallow-review` over 7000 LOC spreads attention too thin. Real bugs hide in:\n- **Offset arithmetic** that works for the simple case but breaks when offset params are added\n- **Variable lifecycle issues** where a loop modifies a variable but the final operation needs the original\n- **Cross-cut inconsistencies** where fixes or refactors in one subsystem introduce bugs in another\n- **Algorithmic boundary conditions** in new data structure code\n\nThe key insight: some bugs are findable by mechanical checking (every System.arraycopy, every\nvariable swap), while others require deep understanding. This skill does BOTH.\n\n## Architecture\n\n```\n+---------------------+\n| PHASE 1: Decompose  |\n|   & Classify        |    Produce decomposition map + coverage checklist.\n+----------+----------+\n           |\n    +-------+--------+----------+\n    |                |           |\n+---v----+   +-------v------+  +-v-----------+\n|PHASE 2 |   |   PHASE 3    |  |   PHASE 4   |\n|Deep    |   |  Targeted    |  |  Shallow    |\n|Review  |   |  Review      |  |  Review     |\n|(HIGH + |   | (HIGH +      |  | (HIGH +     |\n| MEDIUM |   |  MEDIUM      |  |  MEDIUM     |\n| files) |   |  files)      |  |  commits)   |\n+---+----+   +-------+------+  +-+-----------+\n    |                |            |\n    +----------------+------------+\n                     |\n          +----------v----------+\n          | PHASE 5: Cross-Cut  |    Cross-commit/cross-subsystem consistency, pattern\n          | Passes              |    amplification, and fix verification checks.\n          +----------+----------+    One subagent per pass type (5A / 5B / 5C).\n                     |\n          +----------v----------+\n          | PHASE 6: Merge &    |    Deduplicate, verify plausibility, rank.\n          | Validate            |    Combine findings from ALL phases.\n          +---------------------+\n```\n\n---\n\n## Chunking Strategy\n\nThis skill's core principle: **the orchestrator holds global state; subagents hold only their\nslice.** A large patch reviewed by a single agent suffers attention dilution — its context fills\nwith earlier files, earlier findings, and earlier grep output, and it starts missing things. The\nfix is to reset context at every subagent boundary.\n\n### Orchestrator responsibilities\n- Holds the full patch, decomposition map, and accumulated findings from all phases\n- Before spawning each subagent, assembles a **briefing packet**: the chunk + a tight 100–200\n  word context summary written by the orchestrator\n- After each subagent returns, integrates findings into the global picture\n\n### What each subagent receives\n- **Its chunk**: the diff for its commit / grep hits for its audit type / file diff for its deep pass\n- **Orchestrator context**: subsystem name, risk level, what the code is trying to do (one paragraph)\n- **Focused task**: exactly what to look for and why — not a generic \"find bugs\"\n- **Relevant prior findings only**: findings from earlier phases that touch THIS chunk's files,\n  not the full findings list from all files\n\n### What each subagent does\nEach subagent **invokes a review skill** on its chunk — it is not a generic agent. The skill\ndetermines the review depth and structure. The chunk is the scope; the briefing packet is the\ncontext. Subagents may read additional source files, grep for callers, or check sibling classes\nto inform the review, but must not receive the full patch as input — that defeats the purpose.\n\n### Chunk boundaries by phase\n\n| Phase | Chunk unit | Skill to invoke | What the subagent receives |\n|---|---|---|---|\n| 2 (Deep) | One HIGH or MEDIUM file | `/deep-review` | That file's diff + full current source |\n| 3 (Targeted) | All HIGH + MEDIUM files as a group | `/targeted-review` | Diff for those files + Phase 1 risk classification |\n| 4 (Shallow) | One HIGH or MEDIUM commit | `/shallow-review` | That commit's diff only |\n| 5 (Cross-cut) | One pass type (5A / 5B / 5C) | inline only — no sub-skill | Finding list relevant to that pass + grep targets |\n\n**Phases 2, 3, and 4 run in parallel** — launch all their subagents in a single message after Phase 1 completes. Do not wait for Phase 2 before starting Phase 3 or 4.\n\n---\n\n## PHASE 1: Decompose & Classify\n\n**This phase is done inline — no sub-skill invocation.** Its job is to produce a decomposition\nmap and coverage checklist fast, then immediately hand off to the parallel Phases 2/3/4.\nEvery minute spent in Phase 1 is a minute not spent finding bugs.\n\n**Determining the input scope** — two modes depending on what the user provided:\n\n*Mode A — git boundary given* (commit range, branch, or single SHA): proceed directly to\nStep 1a.\n\n*Mode B — no git boundary* (user describes a feature, subsystem, or set of files without\nspecifying a range):\n1. Discover candidate files via grep or directory inspection:\n   ```bash\n   grep -rl \"<keyword>\" src/ | grep '\\.java$' | sort > /tmp/file_list.txt\n   # or: find src/java/org/apache/cassandra/<package> -name '*.java' | sort\n   ```\n2. **Show the list to the user and ask for confirmation** before going further — file count,\n   file names, anything obviously missing or out of scope. Do not skip this step.\n3. Produce a working diff against a sensible base (usually `main`):\n   ```bash\n   git diff main -- $(cat /tmp/file_list.txt | tr '\\n' ' ') > /tmp/mega_review.diff\n   # For files with no git history (new/untracked), read them directly — there is no diff.\n   ```\n4. Use this confirmed file list as the direct seed for the coverage checklist in Step 1e —\n   paste the files into the `File` column verbatim.\n5. In Phase 4, there are no commit boundaries: chunk by **file** instead of by commit —\n   one `/shallow-review` invocation per file. Skip Step 1a and go straight to Step 1b.\n\n**Step 1a — Get commit shape:**\n```bash\ngit log --oneline --stat <base>..<head>\n# Or for a single commit: git show --stat <SHA>\n```\n\n**Step 1b — Skim diff stats (do NOT read file bodies):**\n```bash\ngit diff <base>..<head> --stat\n# What to note: file names, extension types, rough LOC changes, new vs modified files\n```\n\n**Step 1c — Classify each commit/subsystem** by risk:\n- **HIGH**: New algorithms, data structure rewrites, complex feature additions, new orchestration layers, state machine changes, bootstrap/recovery logic\n- **MEDIUM**: Feature additions with new control flow, non-trivial interface changes with multiple callers\n- **LOW**: Renames, moves, mechanical refactors, test-only or documentation changes\n\n**Step 1d — Classify each source file** by type:\n- **Algorithmic**: Array operations, tree traversals, binary search, merges, set operations\n- **State machine**: Bootstrap, recovery, catchup, topology, lifecycle management\n- **Wiring**: Delegation, API changes, parameter threading\n- **Concurrency**: Shared state, synchronization\n- **Documentation/Config**: Markdown, YAML, config files, skill definitions\n\n**Step 1e — Write `/tmp/mega_coverage.md`** (the coverage checklist). Every changed non-test\nfile gets one row; pre-assign reviewers now based on risk:\n\n```markdown\n| File | LOC changed | Risk | Type | Assigned reviewers | Min required | Covered? |\n|------|-------------|------|------|--------------------|--------------|----------|\n| src/Foo.java | 320 | HIGH | Algorithmic | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| src/Bar.java | 45 | MEDIUM | Wiring | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| docs/SKILL.md | 18 | LOW | Documentation | Phase 4 (sha: def456) | 1 | — |\n```\n\nAssignment rules:\n- **HIGH-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **MEDIUM-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **LOW-risk file** → Phase 4 (shallow) — min 1\n\n**Step 1f — IMMEDIATELY start Phases 2, 3, and 4.** Do not pause to write analysis. Do not\ninvoke patch-explainer or any other sub-skill. The coverage checklist IS the Phase 1 output.\nIn the same response, spawn all Phase 2/3/4 subagents — see \"Launching Phases 2/3/4\" below.\n\n---\n\n## PHASE 2: Deep Review — invoke `/deep-review`\n\nFor every HIGH- and MEDIUM-risk file, invoke `/deep-review` scoped to that file. Each file\ngets a **separate, fresh subagent** — they run in parallel and share no context with each other.\nThis phase runs **in parallel with Phases 3 and 4** — start it as soon as Phase 1 completes.\n\n**Per-file input packet** (what the orchestrator provides to each `/deep-review` invocation):\n- The diff for that file only: `git diff <base>..<head> -- <file>`\n- The file's full current source (deep-review reads this itself, but point it at the right file)\n- A 100–150 word orchestrator briefing:\n  - File classification (algorithmic / state machine / wiring / concurrency)\n  - What the file does in the context of the overall change (1–2 sentences from Phase 1)\n  - Risk level and why it was classified HIGH or MEDIUM\n\n---\n\n## PHASE 3: Targeted Review — invoke `/targeted-review`\n\nInvoke the `/targeted-review` skill scoped to **all HIGH- and MEDIUM-risk files** identified\nin Phase 1 — not the full patch. Targeted-review is designed for focused review: it picks only\nthe bug-pattern categories whose diff signals match, then spawns tight subagents per focus area.\nFeeding it the full patch dilutes that focus; feeding it the files that matter most lets it go\ndeep where it counts.\n\n**Selecting the scope**:\n- Include all files classified HIGH- or MEDIUM-risk in Phase 1\n- Include files touched in multiple commits (cross-commit modification from the decomposition map)\n- Exclude LOW-risk files, test-only files, and pure documentation/config changes\n\n**When invoking `/targeted-review`**:\n- Pass only the diff for the selected files (not the full patch)\n- Include the Phase 1 risk classification and file-type notes as context so targeted-review\n  subagents understand what to focus on\n\nThis phase runs **in parallel with Phases 2 and 4** — start it as soon as Phase 1 completes.\nCollect all findings and tag each with `Phase 3 (targeted-review)` and its subagent focus.\n\n---\n\n## PHASE 4: Per-Commit Shallow Reviews — invoke `/shallow-review`\n\nFor each HIGH- and MEDIUM-risk commit, invoke `/shallow-review` scoped to that commit's diff.\nEach invocation is a **fresh subagent** — it receives only that commit's diff, not the full\npatch or accumulated findings from other commits.\n\nThis phase runs **in parallel with Phases 2 and 3** — start it as soon as Phase 1 completes.\n\n**Step 4a**: Extract per-commit diff to its own file:\n```bash\ngit diff <SHA>~1..<SHA> > /tmp/patch_<SHA>.diff\n```\n\n**Step 4b**: Assemble a briefing packet for `/shallow-review` containing ONLY:\n- The commit's diff (`/tmp/patch_<SHA>.diff`)\n- A 100–150 word orchestrator briefing covering:\n  - What category the commit is (algorithmic, state machine, wiring, concurrency)\n  - What risk level (HIGH/MEDIUM) and why\n  - For \"Fix\" commits: \"This commit says 'Fix X' — verify the fix is correct, complete,\n    and does not introduce new bugs. Fix commits have a higher-than-average bug rate.\"\n\n**Step 4c**: Run all HIGH- and MEDIUM-risk commit reviews in a single parallel batch. Collect\nfindings and tag each with the commit SHA.\n\n---\n\n## PHASE 5: Cross-Cut Passes\n\n**Dispatch 5A, 5B, and 5C as parallel subagents.** Each receives a focused slice of findings\nand a targeted task — not the full findings dump from all prior phases. The orchestrator\npre-filters: each subagent receives only the findings relevant to its pass.\n\n### 5A: Pattern Amplification\n\nPatterns come entirely from **bugs actually found in Phases 2–4** — there is no pre-loaded catalog.\nIf Phases 2–4 found zero bugs, 5A is skipped.\n\n**Orchestrator's job** (done before spawning anything):\n1. Collect all findings from Phases 2–4\n2. For each distinct bug, characterize the structural pattern — not the specific instance, but\n   the general shape: e.g. \"method accepts a `start` offset parameter, but an internal\n   `arraycopy` call ignores it and uses hardcoded `0`\"\n3. Decide the search scope based on the pattern type:\n   - **Patch-only** — pattern is structural and specific to new code introduced in this PR\n     (new algorithm, new data structure, new method overload family). Unlikely to exist elsewhere.\n   - **Codebase-wide** — pattern is a convention violation or contract bug that could affect\n     any code following the same convention (serialization encoding, API return value contracts,\n     lifecycle protocols, error code handling). The same mistake recurs wherever the convention\n     is followed, including in code not touched by this PR.\n4. Grep at the chosen scope for locations that could match the pattern shape\n5. Spawn one subagent per pattern, passing it: the pattern description + the grep hits + the\n   scope used (so it knows whether to look beyond the patch if it finds new leads)\n\n**Each subagent's job**: verify whether each grep hit is actually the same bug — read the\nsurrounding source as needed. Report confirmed additional instances only.\n\nOne confirmed bug → one pattern → potentially many additional instances found. This is the\nhighest-yield step when Phases 2–4 produce findings.\n\n### 5B: Cross-Commit/Cross-Subsystem Consistency\n\n**Subagent input**: The decomposition map from Phase 1 (file list, method signatures changed,\nrename list) + the list of caller sites extracted by the orchestrator. Not the full patch.\n\n1. **Interface contracts**: For each changed method signature, verify ALL callers updated\n2. **Rename completeness**: `grep` for old names that should no longer appear\n3. **Assumption conflicts**: When one part of the patch assumes X and another assumes Y about the same state\n\n### 5C: Fix Verification\n\n**Subagent input**: One subagent per \"Fix\" commit. Each receives: that commit's diff only +\na one-paragraph description of the bug it claims to fix.\n\nFor each fix commit:\n1. Read the fix carefully\n2. Try to construct an input that would still trigger the original bug\n3. Try to construct an input that triggers a new bug introduced by the fix\n\n### 5D: Optional Additional Review Passes\n\nIf Phases 2–5C revealed areas not yet covered, run additional targeted passes:\n\n- If 5A found a pattern class in files not yet reviewed → `/deep-review` on those files with\n  the specific pattern as focus guidance\n- If 5B found cross-cut inconsistencies in files not yet reviewed → `/shallow-review` on the\n  combined diff of those files\n- If a fix commit (5C) looks suspicious → `/deep-review` on that file with guidance:\n  \"Verify this fix is correct and does not introduce new bugs.\"\n\n---\n\n## Coverage Gate — Verify Before Phase 6\n\nBefore merging findings, verify `/tmp/mega_coverage.md` is fully green.\n\n**Step 1 — Mark completions**: For each file row, confirm every assigned reviewer phase ran\nand reported (a \"no findings\" report counts). Update **Covered?**:\n- `✓` — all assigned reviewers completed\n- `GAP` — one or more assigned reviewers did not run\n\n**Step 2 — Fill gaps**: For every `GAP` row, launch additional review passes now:\n- File with 0 reviewers completed → `/shallow-review` on that file's diff\n- HIGH- or MEDIUM-risk file with only 1 of 2 reviewers completed → `/shallow-review` on that file's diff\n\nRun all gap-fill passes in a single parallel batch, then update the checklist.\n\n**Step 3 — Gate**: Do not proceed to Phase 6 until every row in `/tmp/mega_coverage.md`\nshows `✓`. If gaps remain after one gap-fill pass, repeat Step 2.\n\n**Step 4 — Include the final checklist** in the Phase 6 report under a \"Coverage\" section.\n\n---\n\n## PHASE 6: Merge & Validate Findings\n\n### Deduplication\nSame location + same root cause = one finding. Boost confidence when found by multiple phases.\n\n### Plausibility Validation\n\nEvery finding MUST pass ALL of:\n1. **The code exists**: Point to exact file:line in the current code\n2. **The bug is achievable**: Describe a concrete input that triggers it\n3. **The result is wrong**: Explain what the code produces vs what it should produce\n4. **Tests don't catch it**: Explain why (e.g., \"tests only call the simple overload without offsets\")\n\nDiscard findings that fail any of these.\n\n### Confidence Ranking\n- **High**: Found by Phase 2 (deep review), or found by 2+ phases independently\n- **Medium**: Single phase found it, plausible trigger exists but complex to verify\n- **Low**: Pattern match suggests possible bug but trigger is speculative\n\n---\n\n## Report Format\n\n```\n## Mega-Review: [commit range / feature name]\n\n### Summary\n- [N] commits/subsystems, [M] files, [L] LOC reviewed\n- [X] bugs found: [H] high-confidence, [M] medium, [L] low\n\n### Findings (ranked by confidence)\n\n#### [HIGH] Finding 1: [precise title]\n- **Location**: file:line\n- **Found by**: Phase [N] ([audit/review type])\n- **The bug**: [what the code does wrong, precisely]\n- **Trigger**: [specific input that causes it]\n- **Expected**: [what should happen]\n- **Actual**: [what happens instead]\n- **Why tests miss it**: [explanation]\n- **Fix**: [specific code change]\n\n[... more findings ...]\n\n### Phase Coverage\n| Phase | Scope | Findings |\n|---|---|---|\n| 1: Decompose & classify | git log + stat | (coverage map) |\n| 2: Deep review | [N] HIGH+MEDIUM files | [M] bugs |\n| 3: Targeted review | HIGH+MEDIUM files, [N] foci | [M] bugs |\n| 4: Shallow review | [N] HIGH+MEDIUM commits | [M] bugs |\n| 5A: Pattern amplification | [N] patterns | [M] additional bugs |\n| 5B: Cross-cut | [checks] | [M] bugs |\n```\n\n---\n\n## Anti-Patterns (What NOT to Report)\n\n- **Style/naming issues** — Not bugs.\n- **Performance concerns** — Not bugs (unless they cause incorrect results).\n- **\"Might be wrong\" without a trigger** — If you can't describe a concrete input that causes\n  incorrect output, it's not a finding.\n- **Documentation mismatches** — Only report if the mismatch causes callers to use the API wrong.\n","frontmatter":{"name":"mega-review","version":"1.0.0","description":"Multi-pass deep code review for large patches (1000+ LOC) that maximizes real bug detection. Orchestrates targeted-review, shallow-review, and deep-review in parallel across all HIGH and MEDIUM risk files and commits: understands the feature holistically, splits by file and commit, runs deep review on every HIGH/MEDIUM file, targeted review across the same scope, and per-commit shallow review, followed by cross-cut consistency checks. Use when: reviewing a large patch (feature branch, multi-commit, or single large diff, 1000+ LOC), doing a thorough pre-merge review, or when shallower reviews miss bugs due to patch size. Triggers on: \"review this branch\", \"review these commits\", \"review this feature\", \"mega review\", \"thorough review\", \"full review of X commits\", or when the user specifies a commit range or feature for review.\n"},"isInternal":false,"tokens":4824,"sizeBytes":19603},{"name":"analysis_framework.md","path":".claude/skills/patch-explainer/references/analysis_framework.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/analysis_framework.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/patch-explainer/references/analysis_framework.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/analysis_framework.md)","tokens":300,"sizeBytes":242},{"name":"ascii_patterns.md","path":".claude/skills/patch-explainer/references/ascii_patterns.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/ascii_patterns.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/patch-explainer/references/ascii_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/ascii_patterns.md)","tokens":300,"sizeBytes":234},{"name":"SKILL.md","path":".claude/skills/patch-explainer/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/SKILL.md","title":"patch-explainer","category":"anthropic-skill","format":"markdown","content":"---\nname: patch-explainer\nversion: \"1.0.0\"\ndescription: Deep code analysis with ASCII visualizations showing structure, flow, and state transitions. Use when analyzing patches/diffs, explaining classes or subsystems, understanding code architecture, reviewing changes for inconsistencies, or when asked to visualize how code works. Provides before/after diagrams, data/control flow, concurrency analysis, assumptions, and failure modes. Triggers on explain this patch/code/class, how does X work, show me the flow, visualize this change, code review requests, or proactive analysis during PR reviews.\n---\n\n# Patch Explainer\n\nDeeply analyze and visualize code using ASCII diagrams to reveal structure, behavior, and interactions.\n\n## What This Skill Does\n\nProvides comprehensive code analysis with rich ASCII visualizations for:\n- **Patches/diffs**: Before/after states, what changed and why\n- **Classes**: Purpose, structure, state transitions, workflows\n- **Subsystems**: Component interactions, data flow, architecture\n- **Repositories**: Overall structure, key abstractions, major patterns\n- **Code reviews**: Finding inconsistencies, analyzing assumptions and failure modes\n\n## Analysis Approach\n\n### For Any Code (Patches, Classes, Subsystems, Repositories)\n\n1. **Identify the core purpose** - What does this code do and why does it exist?\n\n2. **Create ASCII visualizations** showing:\n   - Structure (components, layers, dependencies)\n   - Behavior (data flow, control flow, state transitions)\n   - Interactions (sequence diagrams, message passing, concurrency)\n   - For patches: before/after comparisons\n\n3. **Deep reasoning** about:\n   - **Assumptions**: What must be true for this to work correctly?\n   - **Failure modes**: What could go wrong at each step?\n   - **Concurrency**: If multiple threads/processes, show their interactions\n   - **Invariants**: What must always hold true?\n\n4. **Focus on the \"why\"**:\n   - Why does this code exist?\n   - Why was this approach chosen?\n   - For changes: Why this modification? What problem does it solve?\n\n### Visualization Strategy\n\nChoose diagram types based on what you're explaining:\n\n**State machines** - When code manages states/status:\n```\n[Initial] --event--> [Processing] --success--> [Complete]\n                          |\n                       failure\n                          |\n                          v\n                      [Failed]\n```\n\n**Data flow** - When showing information movement:\n```\nInput → [Transform A] → [Transform B] → Output\n```\n\n**Sequence diagrams** - When showing component interactions:\n```\nClient          Server          Database\n  |               |                 |\n  |--request----->|                 |\n  |               |----query------->|\n  |               |<---result-------|\n  |<--response----|                 |\n```\n\n**Component structure** - When showing architecture:\n```\n┌─────────────────────┐\n│   Application       │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Service Layer     │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Data Layer        │\n└─────────────────────┘\n```\n\n**Before/after** - When explaining changes:\n```\nBEFORE                  AFTER\n─────────────────────────────────\n[A] → [B] → [C]        [A] → [Cache?] ─Yes→ [C]\n                              |\n                              No\n                              v\n                            [B] → [C]\n```\n\n### Reference Materials\n\n**ASCII diagram templates**: See [ascii_patterns.md](references/ascii_patterns.md) for:\n- State machine patterns\n- Data flow diagrams\n- Sequence diagrams\n- Component/architecture diagrams\n- Before/after comparisons\n- Concurrency patterns\n- Control flow patterns\n- Dependency graphs\n\n**Analysis methodology**: See [analysis_framework.md](references/analysis_framework.md) for:\n- Structured analysis process for patches vs existing code\n- Concurrency analysis checklist\n- Assumption identification patterns\n- Failure mode identification\n- Analysis depth guidelines by scope (function → class → subsystem → repository)\n\n## Analysis Workflow\n\n### For Patches/Diffs\n\n1. Read the patch to understand what changed\n2. Identify the change type (bug fix, feature, refactor, optimization)\n3. Create before/after ASCII diagrams showing:\n   - Old behavior vs new behavior\n   - State transitions that changed\n   - Data flow modifications\n4. Explain what fundamentally changed:\n   - What problem did the old code have?\n   - How does the new code solve it?\n   - What assumptions changed?\n5. Analyze failure modes:\n   - What could go wrong with this change?\n   - Are there edge cases not handled?\n   - Concurrency implications?\n6. Focus on the \"why\": What problem does each modification solve?\n\n### For Classes\n\n1. Read the class to understand its purpose\n2. Create ASCII diagram showing:\n   - Class structure (key fields/methods)\n   - State machine if it manages state\n   - How it fits with related classes\n3. Explain key workflows (2-3 most important methods)\n4. Identify assumptions and invariants\n5. Analyze failure modes and edge cases\n6. Focus on the \"why\": Why does this class exist? What problem does it solve?\n\n### For Subsystems\n\n1. Identify the components in the subsystem\n2. Create ASCII diagram showing:\n   - Component relationships\n   - Key interfaces/boundaries\n   - Main data flows\n3. Trace 2-3 key workflows through the subsystem\n4. Explain how components interact\n5. Identify assumptions across component boundaries\n6. Focus on the \"why\": What is this subsystem's role in the larger system?\n\n### For Repositories\n\n1. Understand the high-level architecture\n2. Create ASCII diagram showing:\n   - Major modules/packages\n   - Layered architecture\n   - Key abstractions\n3. Identify core workflows\n4. Explain main patterns used throughout\n5. Highlight critical subsystems\n6. Focus on the \"why\": What problem does this codebase solve?\n\n## Concurrency Analysis\n\nWhen analyzing concurrent code, always show:\n\n**Thread interactions**:\n```\nThread A                State                Thread B\n   |                      |                      |\n   |--lock()------------>|                      |\n   |                     [LOCKED]               |\n   |--modify()---------->|                      |\n   |--unlock()---------->|                      |\n   |                     [UNLOCKED]             |\n   |                      |<---------lock()-----|\n   |                     [LOCKED]               |\n```\n\n**Race conditions**:\n```\nThread A            Thread B\n   |                   |\n   |--read(x=10)      |\n   |                   |--read(x=10)\n   |--x=x+1           |\n   |                   |--x=x+1\n   |--write(x=11)     |\n   |                   |--write(x=11)  ⚠ Lost update!\n\nResult: x=11 (expected: x=12)\n```\n\nCheck for:\n- Shared mutable state without synchronization\n- Lock ordering violations (potential deadlocks)\n- Race conditions in read-modify-write operations\n- Missing memory barriers\n\n## Output Structure\n\nStructure your analysis as:\n\n### 1. Executive Summary\nBrief overview (2-3 sentences) of what this code does and why it matters.\n\n### 2. Visual Overview\nHigh-level ASCII diagram showing the main structure or flow.\n\n### 3. Detailed Analysis\nOrganized by aspect:\n- **Purpose**: What it does and why it exists\n- **Structure**: Components and their relationships\n- **Key Workflows**: Step-by-step execution of main scenarios\n- **State Management**: States and transitions (if applicable)\n- **Assumptions**: What must be true for correctness\n- **Failure Modes**: What could go wrong\n- **Concurrency**: Thread safety analysis (if applicable)\n\n### 4. For Patches: Before/After\n- Before state (with diagram)\n- After state (with diagram)\n- Why this change was made\n- Critical modifications explained\n\n### 5. Key Insights\nBullet points highlighting:\n- Most important findings\n- Potential issues or risks\n- Recommendations (if applicable)\n\n## Prioritization\n\nFocus on high-impact elements:\n- **Critical paths**: Main workflows that matter most\n- **High-risk code**: Concurrency, error handling, resource management\n- **Complex logic**: Non-obvious algorithms or subtle interactions\n- **Key abstractions**: Core interfaces and contracts\n\nMinimize or skip:\n- Boilerplate code\n- Simple getters/setters\n- Standard patterns done correctly\n- Low-risk trivial changes\n\n## Example Scenarios\n\n**Scenario 1**: \"Explain this patch\"\n→ Show before/after diagrams, explain what changed and why, analyze assumptions and failure modes\n\n**Scenario 2**: \"How does SafeCommandStore work?\"\n→ Show class structure, explain the exclusive access pattern, trace key methods, analyze thread safety\n\n**Scenario 3**: \"Explain the coordination subsystem\"\n→ Show component diagram, trace PreAccept→Accept→Commit flow, explain message passing, show quorum tracking\n\n**Scenario 4**: \"What's the architecture of this codebase?\"\n→ Show high-level module structure, identify key abstractions, explain main patterns, highlight critical subsystems\n\n**Scenario 5**: During code review (proactive)\n→ Analyze changes for inconsistencies, check assumptions, identify potential race conditions, verify error handling\n","frontmatter":{"name":"patch-explainer","version":"1.0.0","description":"Deep code analysis with ASCII visualizations showing structure, flow, and state transitions. Use when analyzing patches/diffs, explaining classes or subsystems, understanding code architecture, reviewing changes for inconsistencies, or when asked to visualize how code works. Provides before/after diagrams, data/control flow, concurrency analysis, assumptions, and failure modes. Triggers on explain this patch/code/class, how does X work, show me the flow, visualize this change, code review requests, or proactive analysis during PR reviews."},"isInternal":false,"tokens":1975,"sizeBytes":9506},{"name":"README.md","path":".claude/skills/README.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/README.md","title":"Skills Skill","category":"anthropic-skill","format":"markdown","content":"# Skills Skill\n\nPath: `.claude/skills/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/README.md)","tokens":300,"sizeBytes":160},{"name":"EVAL-PROMPT.md","path":".claude/skills/shallow-review/EVAL-PROMPT.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/EVAL-PROMPT.md","title":"Shallow-review Skill","category":"anthropic-skill","format":"markdown","content":"# Shallow-review Skill\n\nPath: `.claude/skills/shallow-review/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/EVAL-PROMPT.md)","tokens":300,"sizeBytes":208},{"name":"absence.md","path":".claude/skills/shallow-review/references/general/specialists/absence.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/absence.md","title":"Specialists Skill","category":"anthropic-skill","format":"markdown","content":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/absence.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/absence.md)","tokens":300,"sizeBytes":259},{"name":"boundary.md","path":".claude/skills/shallow-review/references/general/specialists/boundary.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/boundary.md","title":"Specialists Skill","category":"anthropic-skill","format":"markdown","content":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/boundary.md)","tokens":300,"sizeBytes":261},{"name":"completeness.md","path":".claude/skills/shallow-review/references/general/specialists/completeness.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/completeness.md","title":"Specialists Skill","category":"anthropic-skill","format":"markdown","content":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/completeness.md)","tokens":300,"sizeBytes":269},{"name":"concurrency.md","path":".claude/skills/shallow-review/references/general/specialists/concurrency.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/concurrency.md","title":"Specialists Skill","category":"anthropic-skill","format":"markdown","content":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/concurrency.md)","tokens":300,"sizeBytes":267},{"name":"logic.md","path":".claude/skills/shallow-review/references/general/specialists/logic.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/logic.md","title":"Specialists Skill","category":"anthropic-skill","format":"markdown","content":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/logic.md)","tokens":300,"sizeBytes":255},{"name":"resources.md","path":".claude/skills/shallow-review/references/general/specialists/resources.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/resources.md","title":"Specialists Skill","category":"anthropic-skill","format":"markdown","content":"# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/resources.md)","tokens":300,"sizeBytes":263},{"name":"SKILL.md","path":".claude/skills/shallow-review/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/SKILL.md","title":"shallow-review","category":"anthropic-skill","format":"markdown","content":"---\nname: shallow-review\nversion: \"1.0.0\"\ndescription: >\n  Shallow (quick) ensemble bug-finding review using 6 specialist agents in parallel. Each\n  specialist reviews the same patch through a different lens: Logic & Types, Boundaries &\n  I/O, Concurrency & State, Resources & Serialization, Absence Analysis, and API\n  Completeness. Findings are merged and deduplicated. Best for: quick first-pass review of\n  patches, triage of diffs, broad surface-level bug scan. For deeper file-focused review\n  with full pattern catalogs and codebase investigation, use the deep-review skill instead.\n---\n\n# Ensemble Code Review\n\nSix specialist agents review the same patch in parallel. Each applies Phase 0 (understand\nthe change, form hypotheses) then a focused checklist. Their findings are merged and\ndeduplicated.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n    +-------+------+---------+---------+-----------+\n    |       |      |         |         |           |\n+---v--+ +--v--+ +-v-----+ +-v------+ +v-----+ +---v-------+\n|Logic | |Bound| |Concurr| |Resource| |Absenc| | Complete. |\n|&Type | | &I/O| |&State | |& Serde | |(2-ph)| | & Contr.  |\n+--+---+ +--+--+ +---+---+ +---+----+ +--+---+ +---+-------+\n   |        |        |         |          |        |\n   +--------+--------+---------+----------+--------+\n                               |\n                    +----------v----------+\n                    |  Pass 3: Symmetry   |\n                    |  (serial, optional) |\n                    +----------+----------+\n                               |\n                    +----------v----------+\n                    |   Merge & Dedup     |\n                    |   (main agent)      |\n                    +---------------------+\n```\n\n## Quick Start\n\n1. **Identify target** — patch, diff, file, or subsystem\n2. **Launch 6 specialists** in parallel (see prompts below)\n3. **Run Pass 3 Symmetry** check (serial, after specialists complete)\n4. **Merge** findings: deduplicate, rank by confidence\n5. **Report** in unified format\n\n## Phase 0: Understand Before Checking\n\nEvery specialist runs Phase 0 BEFORE touching the checklist:\n\n1. **Summarize** the patch in 2–3 sentences (feature, fix, refactor, move?)\n2. **Hypothesize** — list 3–5 things that could go wrong with this type of change\n3. **Note** code shapes that warrant deeper investigation\n\nThis switches the review from bottom-up (checklist→code) to top-down\n(code→hypotheses→verification). The checklist then verifies and extends the hypotheses.\n\n---\n\n## The Six Specialists\n\n### 1. Logic & Types (52% of bugs)\n\n**Priority**: wrong comparisons, missing returns, wrong constants, boolean polarity, sentinel ambiguity.\n\n**Reference**: `references/general/specialists/logic.md`\n\n**Prompt**:\n```\nYou are a LOGIC specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any suspicious code shapes (control flow, comparisons, constants, sentinels).\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/logic.md`\nApply questions that match your hypotheses and code shapes. Check all 30 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 2. Boundaries & I/O (17% of bugs)\n\n**Priority**: off-by-one, integer overflow, null/bounds checks, buffer sizing, I/O completeness.\n\n**Reference**: `references/general/specialists/boundary.md`\n\n**Prompt**:\n```\nYou are a BOUNDARY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any arithmetic, indexing, range, or I/O operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/boundary.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 3. Concurrency & State (16% of bugs)\n\n**Priority**: races, TOCTOU, live-view iteration, lock ordering, state cleanup.\n\n**Reference**: `references/general/specialists/concurrency.md`\n\n**Prompt**:\n```\nYou are a CONCURRENCY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any shared state, locks, collections, lifecycle operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/concurrency.md`\nApply questions that match your hypotheses and code shapes. Check all 24 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 4. Resources & Serialization (15% of bugs)\n\n**Priority**: resource leaks, serialization mismatches, wrong metric types, background tasks, wrapper bypass.\n\n**Reference**: `references/general/specialists/resources.md`\n\n**Prompt**:\n```\nYou are a RESOURCES specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any resource allocation, serialization methods, metrics, streams.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/resources.md`\nApply questions that match your hypotheses and code shapes. Check all 26 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 5. Absence Analysis (cross-cutting)\n\n**Priority**: find what SHOULD be present but ISN'T — missing guards, cleanup, handlers, registrations.\n\n**Reference**: `references/general/specialists/absence.md`\n\n**Prompt**:\n```\nYou are an ABSENCE specialist. Your job: find bugs that are purely absent — missing\nguards, cleanup, handlers, or conditions that leave no signal in the diff.\n\nPHASE 0 — Understand the patch first:\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that SHOULD be present but might be missing.\n\nPHASE 1 — Build the search list:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/absence.md`\nFor each event in the diff matching items (a)-(q), add to your search list.\n\nPHASE 2 — Execute searches and report:\nFor each item in your search list:\n  - Use Grep and Read tools to gather evidence from the codebase\n  - If match found (remove/deregister exists): discard\n  - If no match found: report as finding\n\nReport ALL findings above a noise floor. For each: what's missing, where it should\nbe, what evidence you searched for, Confidence (High/Medium/Low).\nOr \"No absence finding\" if nothing applies.\n```\n\n### 6. API Completeness & Contracts\n\n**Priority**: missing fields, missing overrides, registration symmetry, visibility, event coverage.\n\n**Reference**: `references/general/specialists/completeness.md`\n\n**Prompt**:\n```\nYou are an API COMPLETENESS specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could be incomplete about this change.\n3. Note any new classes, new fields, new registrations, visibility changes.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/completeness.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n---\n\n## Pass 3: Cross-Path Symmetry (serial, after specialists complete)\n\n**Prompt**:\n```\nYou are a SYMMETRY specialist. For each code path modified in this patch, identify\nwhether a structurally parallel path (same class, interface, event family, version range)\nwas NOT modified. For each asymmetry:\n- Where path A was changed\n- Where parallel path B exists\n- What was changed on A that is absent on B\n- Whether the asymmetry is intentional or suspicious\n\nRead the patch: `{PATCH_PATH}`\nSearch the codebase as needed using Grep and Read.\nReport all asymmetries, Confidence High/Medium/Low.\n```\n\n---\n\n## Merge & Dedup\n\nAfter all specialists report:\n\n1. **Collect** all findings from 6 specialists + symmetry\n2. **Deduplicate** — same code location + related reasons → combine\n3. **Rank** by confidence — findings confirmed by multiple specialists rank highest\n4. **Cross-check** reinforcement:\n   - Logic + Absence at same location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Any finding flagged by 3+ specialists → treat as confirmed\n5. **3-point test** each finding:\n   - The code construct actually exists in the diff (not inferred)\n   - The bug is possible given the visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n6. **Specialist Silence Rule**: If Absence or Completeness reports nothing on a >100-line\n   diff, note: \"Consider verifying Phase 2 searches executed for registration symmetry,\n   handler coverage, and field completeness.\"\n\n---\n\n## Report Format\n\n```\n## Review: [target]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Flagged by**: [specialists]\n- **What's wrong**: [1-2 sentences]\n\n### Specialist Coverage\n- Logic: [N findings / no finding]\n- Boundary: [N findings / no finding]\n- Concurrency: [N findings / no finding]\n- Resources: [N findings / no finding]\n- Absence: [N findings / no finding]\n- Completeness: [N findings / no finding]\n- Symmetry: [N asymmetries / none]\n```\n\n## Statistical Priors\n\n| Category | Share | Specialist |\n|---|---|---|\n| Logic error in condition | 26% | Logic |\n| Wrong constant / default | 15% | Logic |\n| Missing null / bounds check | 13% | Boundary |\n| Incorrect filtering / result | 11% | Logic |\n| Race condition | 9% | Concurrency |\n| Wrong serialization | 8% | Resources |\n| State not cleaned up | 7% | Concurrency |\n| Off-by-one | 4% | Boundary |\n| Resource leak | 3% | Resources |\n\n## Reference Files\n\n### Specialist checklists (trimmed, ensemble mode)\n- `references/general/specialists/logic.md` — 30 items, Logic specialist\n- `references/general/specialists/boundary.md` — 22 items, Boundary specialist\n- `references/general/specialists/concurrency.md` — 24 items, Concurrency specialist\n- `references/general/specialists/resources.md` — 26 items, Resources specialist\n- `references/general/specialists/absence.md` — Phase 1/2 search patterns, Absence specialist\n- `references/general/specialists/completeness.md` — 22 items, Completeness specialist\n","frontmatter":{"name":"shallow-review","version":"1.0.0","description":"Shallow (quick) ensemble bug-finding review using 6 specialist agents in parallel. Each specialist reviews the same patch through a different lens: Logic & Types, Boundaries & I/O, Concurrency & State, Resources & Serialization, Absence Analysis, and API Completeness. Findings are merged and deduplicated. Best for: quick first-pass review of patches, triage of diffs, broad surface-level bug scan. For deeper file-focused review with full pattern catalogs and codebase investigation, use the deep-review skill instead.\n"},"isInternal":false,"tokens":2852,"sizeBytes":12054},{"name":"api-contracts-and-completeness.md","path":".claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/api-contracts-and-completeness.md)","tokens":300,"sizeBytes":288},{"name":"boundaries-and-numbers.md","path":".claude/skills/targeted-review/references/categories/boundaries-and-numbers.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/boundaries-and-numbers.md)","tokens":300,"sizeBytes":272},{"name":"concurrency-and-locking.md","path":".claude/skills/targeted-review/references/categories/concurrency-and-locking.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/concurrency-and-locking.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/concurrency-and-locking.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/concurrency-and-locking.md)","tokens":300,"sizeBytes":274},{"name":"conditions-and-predicates.md","path":".claude/skills/targeted-review/references/categories/conditions-and-predicates.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/conditions-and-predicates.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/conditions-and-predicates.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/conditions-and-predicates.md)","tokens":300,"sizeBytes":278},{"name":"INDEX.md","path":".claude/skills/targeted-review/references/categories/INDEX.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/INDEX.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/INDEX.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/INDEX.md)","tokens":300,"sizeBytes":238},{"name":"io-and-crash-safety.md","path":".claude/skills/targeted-review/references/categories/io-and-crash-safety.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/io-and-crash-safety.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/io-and-crash-safety.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/io-and-crash-safety.md)","tokens":300,"sizeBytes":266},{"name":"lifecycle-and-ordering.md","path":".claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/lifecycle-and-ordering.md)","tokens":300,"sizeBytes":272},{"name":"null-and-type-safety.md","path":".claude/skills/targeted-review/references/categories/null-and-type-safety.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/null-and-type-safety.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/null-and-type-safety.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/null-and-type-safety.md)","tokens":300,"sizeBytes":268},{"name":"refactor-aftermath.md","path":".claude/skills/targeted-review/references/categories/refactor-aftermath.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/refactor-aftermath.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/refactor-aftermath.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/refactor-aftermath.md)","tokens":300,"sizeBytes":264},{"name":"serialization-and-versioning.md","path":".claude/skills/targeted-review/references/categories/serialization-and-versioning.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/serialization-and-versioning.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/serialization-and-versioning.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/serialization-and-versioning.md)","tokens":300,"sizeBytes":284},{"name":"state-and-resource-cleanup.md","path":".claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/state-and-resource-cleanup.md)","tokens":300,"sizeBytes":280},{"name":"validation-and-input-handling.md","path":".claude/skills/targeted-review/references/categories/validation-and-input-handling.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/validation-and-input-handling.md","title":"Categories Skill","category":"anthropic-skill","format":"markdown","content":"# Categories Skill\n\nPath: `.claude/skills/targeted-review/references/categories/validation-and-input-handling.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/categories/validation-and-input-handling.md)","tokens":300,"sizeBytes":286},{"name":"report-format.md","path":".claude/skills/targeted-review/references/report-format.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/report-format.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/targeted-review/references/report-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/report-format.md)","tokens":300,"sizeBytes":232},{"name":"subagent-prompt-template.md","path":".claude/skills/targeted-review/references/subagent-prompt-template.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/subagent-prompt-template.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/targeted-review/references/subagent-prompt-template.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/references/subagent-prompt-template.md)","tokens":300,"sizeBytes":254},{"name":"SKILL.md","path":".claude/skills/targeted-review/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/targeted-review/SKILL.md","title":"targeted-review","category":"anthropic-skill","format":"markdown","content":"---\nname: targeted-review\nversion: \"1.0.0\"\ndescription: >\n  Findings-driven targeted code review. Understands the patch via patch-explainer and\n  surrounding code via codebase-analysis, then consults a catalog of bug patterns\n  (~11 categories under references/categories/). Picks only categories whose diff-signals\n  match the patch and items whose \"look for\" hints match actual code shapes, groups them\n  by review focus (function/file/feature), and spawns parallel subagents — each with a\n  tight scope and selective checklist. Use for medium-to-large patches (50-1000 LOC) as\n  a focused alternative to whole-patch ensemble or whole-file deep review. Triggers on:\n  \"review this patch/diff/change\", \"find bugs in this change\", \"scoped review\", \"what\n  could go wrong here\", \"review using findings\", or proactive PR review.\n---\n\n# Targeted Review\n\nA meta-review skill. It does not encode bug patterns directly — it orchestrates other\nskills and a categorized findings catalog into a tight, evidence-driven review.\n\n## What it does\n\n```\n                +------------------+\n                |   Input patch    |\n                +--------+---------+\n                         |\n             +-----------+-----------+\n             |                       |\n   +---------v---------+   +---------v-----------+\n   | patch-explainer   |   | codebase-analysis   |\n   | (sub-skill)       |   | (sub-skill, scoped) |\n   | what changed,     |   | invariants, callers,|\n   | flow, assumptions |   | parallel paths      |\n   +---------+---------+   +---------+-----------+\n             |                       |\n             +-----------+-----------+\n                         |\n         +---------------v----------------+\n         | Pick categories + items        |\n         | × 3-5 independent iterations  |\n         | (each draw surfaces different  |\n         |  items from the same catalog)  |\n         +---------------+----------------+\n                         |\n                +--------v---------+\n                | Pool & prioritize|\n                | (items from 2+   |\n                |  iterations →    |\n                |  higher priority)|\n                +--------+---------+\n                         |\n                +--------v---------+\n                | Group items by   |\n                | review focus     |\n                | (file/func/feat) |\n                +--------+---------+\n                         |\n            +------------+------------+\n            |            |            |\n    +-------v---+  +-----v-----+  +---v-------+\n    | review    |  | review    |  | review    |\n    | subagent  |  | subagent  |  | subagent  |\n    | scope A   |  | scope B   |  | scope C   |\n    +-------+---+  +-----+-----+  +---+-------+\n            |            |            |\n            +------------+------------+\n                         |\n                +--------v---------+\n                | Merge & report   |\n                +------------------+\n```\n\n## When to use this skill\n\n- A patch or diff is on the table for review (single commit, multi-commit branch, or staged changes)\n- The user wants more focus than `shallow-review` provides (six fixed lenses on the whole patch) but doesn't want to commit to `deep-review`'s file-by-file deep pass\n- A `*-findings/` corpus exists or the categorized catalog under `references/categories/` is sufficient — the categories alone are usable; project corpora improve coverage\n- Medium-to-large patches where dispatching focused subagents avoids overwhelming a single reviewer\n\n## When NOT to use this skill\n\n- Trivial 1-3 line changes — direct review is faster\n- Pure refactors with no behavior change — `shallow-review` symmetry pass is enough\n- The user wants a single comprehensive write-up of one file — use `deep-review` instead\n\n---\n\n## Workflow\n\nYou will go through seven phases. Phases 1a and 1b run in parallel. Phases 2-6 are sequential.\n\n### Phase 1a: Understand the patch — call the patch-explainer skill\n\nInvoke the `patch-explainer` skill on the patch. Use the Skill tool. You want patch-explainer\nto produce its standard analysis (purpose, before/after diagrams, flow, assumptions,\nfailure modes).\n\nIf the patch is already provided as a file path, point patch-explainer at it. If you only\nhave a commit ref, ask for `git show <ref>` or read it from `git diff`. For multi-commit\nbranches, it is fine to feed the cumulative diff.\n\nCapture patch-explainer's full output. You will refer to it in Phases 3-5.\n\n### Phase 1b: Understand the surroundings — call the codebase-analysis skill\n\nIn parallel with 1a, invoke the `codebase-analysis` skill in **targeted mode** on the\naffected subsystem only — not the whole repo. Pass it:\n\n- The list of files touched by the patch\n- The subsystem name if obvious (e.g., \"the journal replay subsystem\")\n- A directive to focus on: invariants, lifecycle, parallel implementations, and recent\n  bug history in the affected area\n\nYou want codebase-analysis to produce a scoped `analysis/system-analysis.md` that gives\nyou the context the patch sits inside — what the surrounding code expects, where parallel\npaths exist, what historical bugs touched this area.\n\nIf invoking the full skill is too heavy for a small patch, instead spawn a research\nsubagent with this prompt: \"Read these files: {touched files}. Summarize: (a) the\ninvariants the surrounding code maintains, (b) any parallel implementations or sibling\nclasses, (c) callers of the modified methods, (d) any recent bug-fix commits in this\narea. Under 400 words.\" This is a lighter alternative that retains the spirit of\ncodebase-analysis. Prefer the full skill when the area is unfamiliar or large.\n\n### Phase 2: Pick categories — 3-5 independent iterations\n\nCategory selection and item picking are speculative: you're making probabilistic judgments\nabout which patterns might apply, and a single pass will reliably miss some. Run **3-5\nindependent iterations** of Phases 2+3, each starting from scratch with the same patch\nand context but without looking back at what prior iterations chose. Treat each iteration\nlike a fresh read — you are more likely to notice different things each time.\n\nFor each iteration, read `references/categories/INDEX.md` — it lists all 11 categories\nwith their descriptions and diff signals in one file (~200 lines). For each category, ask:\ndoes the patch contain ANY of the diff signals listed?\n- If yes → mark as **load**\n- If no → skip\n\nTypically 3-7 categories load per iteration. If you would load more than 8, re-examine.\nIf fewer than 2, the patch is probably too small for this skill.\n\n### Phase 3: Pick items within each loaded category (one pass per iteration)\n\nWithin each iteration, read the **full** content of each loaded category file. For each\nfinding (`### F-NN: title` + body + `**Look for:** {hint}`), ask:\n\n1. Does the \"Look for\" hint match a code shape that **actually appears in this patch**?\n2. Does the patch context (from patch-explainer + codebase-analysis) make this finding\n   **plausibly applicable** — not just a keyword match?\n\nIf yes to both → keep the item.\nIf no → drop.\n\nBe selective: a category typically has 25-40 findings; keep 3-12 per category per\niteration. Repeat for all iterations before moving to Phase 3b.\n\n### Phase 3b: Pool and prioritize across iterations\n\nAfter all iterations are complete, merge the item lists:\n\n- An item selected in **2 or more iterations** is a strong candidate — mark it **priority**.\n- An item selected in only one iteration is still in scope — mark it **speculative**.\n- Discard nothing yet; let the subagents decide.\n\nThe iteration count next to an item is a confidence signal for the subagents, not a\ngate. A speculative item can still turn into a real bug; a priority item can still be\na false alarm.\n\n### Phase 4: Group items by review focus\n\nNow you have a pooled list of selected items across categories and iterations. Group them\nby **review focus** — what part of the change a single reviewer should examine. A focus\nis one of:\n\n- A specific function or method (`MyClass.replay()`)\n- A specific file or small group (`FooSerializer.java` and its sibling `FooDeserializer.java`)\n- A feature, behavior, or concept (\"the new fsync coordination\", \"the version-gated dispatch path\")\n- A specific cross-cutting concern in the patch (\"any place we read the new `dirty` flag\")\n\nAim for 2-5 foci per patch. Each focus should have **5-15 checklist items** drawn from\nacross the categories — not too few (subagent has nothing to do) and not too many\n(subagent gets overwhelmed). Include each item's priority annotation (priority /\nspeculative) so the subagent knows where to focus first.\n\nIf multiple foci would receive the same checklist item, that's fine — the same pattern\ncan apply at multiple sites. Tag each item with the category it came from so the\nsubagent knows the rationale.\n\n### Phase 5: Spawn focused review subagents\n\nFor each focus, spawn one review subagent in parallel using the Agent tool. Use the\ntemplate in `references/subagent-prompt-template.md`. The subagent prompt must contain:\n\n- The patch (path, or pasted, or ref)\n- A 100-word summary of patch-explainer's findings (relevant slice only — not the full output)\n- A 100-word summary of codebase-analysis's findings (relevant slice only)\n- The focus statement (what part of the change to review)\n- The checklist items, each with: category, priority annotation, finding text, and\n  look-for hint\n- Instructions on how to gather evidence (read source, grep, check parallel paths) and\n  what confidence to assign\n\nEach subagent should produce: a list of findings, with location, confidence, and what\nevidence was checked.\n\nRun all subagents in a single tool call (parallel). They are independent.\n\n### Phase 6: Merge and report\n\nWhen all subagents return, merge findings:\n\n1. **Deduplicate** — same code location + similar reasoning → one finding, both subagents\n   credited\n2. **Rank** by confidence — High first, then Medium, then Low\n3. **Cross-reinforce** — if a finding was raised by multiple subagents, or if multiple\n   findings cluster on the same lifecycle/state, boost confidence\n4. **Three-point check** each surviving finding:\n   - The code construct actually exists in the diff (not inferred from absence alone)\n   - The bug is plausible given the visible context (not speculative)\n   - The finding is actionable (the reader can tell what to change)\n\nUse the format in `references/report-format.md`.\n\n---\n\n## Reference files\n\n| Reference | When to read |\n|---|---|\n| `references/subagent-prompt-template.md` | Phase 5, when spawning each review subagent |\n| `references/report-format.md` | Phase 6, when merging and presenting findings |\n| `references/categories/INDEX.md` | Phase 2 — single-file scan of all category descriptions + diff signals |\n| `references/categories/<name>.md` | Phase 3 — full body of each loaded category, picked from INDEX |\n\nThe categories in `references/categories/` are project-agnostic patterns mined from real\nbug fixes across distributed-systems projects (Cassandra, Kafka, Iceberg). They describe\ngeneralized code-level shapes, not project-specific issues.\n\n## How this differs from related skills\n\n| Skill | Scope | Pattern source | Subagent dispatch |\n|---|---|---|---|\n| `shallow-review` (cassandra-edge-case-explorer) | Whole patch | 6 fixed lenses (~100 items total) | One subagent per lens, fixed |\n| `deep-review` | User-named files | 444-pattern catalog | One subagent per file, full catalog |\n| `targeted-review` (this) | Whole patch, focus-decomposed | ~11 categories (300+ findings) — selectively loaded | One subagent per focus, selectively populated checklist |\n| `mega-review` | Large branches | Orchestrates the above | Multi-pass |\n\nUse `targeted-review` when:\n- The patch spans 50-1000 LOC\n- You want to spend tokens on **what matters for THIS patch**, not on a fixed catalog\n- You have a `*-findings/` corpus or are reviewing systems-level code that benefits from\n  the curated categories\n\n## Pitfalls and guardrails\n\n- **Don't skip Phase 1.** Calling patch-explainer and codebase-analysis is what lets you\n  pick categories and items intelligently. Without that grounding, you'll loose-match\n  on keywords and overwhelm subagents.\n- **Don't look at prior iterations while picking.** The whole value of multiple iterations\n  is independent draws. If you anchor on the first iteration's selections, you get one\n  draw repeated instead of several independent ones.\n- **Don't load every category \"just in case\".** The whole value is selection. If you\n  match more than 8 categories in an iteration, you've probably been too generous.\n- **Don't pass the full catalog to subagents.** Each subagent gets only the items\n  selected for its focus. Passing all items defeats the purpose.\n- **Don't substitute findings for understanding.** A finding that \"matches a code shape\"\n  is a hypothesis to verify — the subagent confirms or refutes by reading the code, not\n  by trusting the pattern. Mark uncertain findings as Low confidence.\n- **The checklist is the menu, not the order.** A subagent should also report bugs it\n  notices that aren't on the checklist — the checklist primes attention, it doesn't cap\n  it.\n","frontmatter":{"name":"targeted-review","version":"1.0.0","description":"Findings-driven targeted code review. Understands the patch via patch-explainer and surrounding code via codebase-analysis, then consults a catalog of bug patterns (~11 categories under references/categories/). Picks only categories whose diff-signals match the patch and items whose \"look for\" hints match actual code shapes, groups them by review focus (function/file/feature), and spawns parallel subagents — each with a tight scope and selective checklist. Use for medium-to-large patches (50-1000 LOC) as a focused alternative to whole-patch ensemble or whole-file deep review. Triggers on: \"review this patch/diff/change\", \"find bugs in this change\", \"scoped review\", \"what could go wrong here\", \"review using findings\", or proactive PR review.\n"},"isInternal":false,"tokens":3002,"sizeBytes":13267},{"name":"language.md","path":".claude/skills/tla-plus/references/language.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/language.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/tla-plus/references/language.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/language.md)","tokens":300,"sizeBytes":208},{"name":"code-to-spec.md","path":".claude/skills/tla-plus/references/patterns/code-to-spec.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/code-to-spec.md","title":"Patterns Skill","category":"anthropic-skill","format":"markdown","content":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/code-to-spec.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/code-to-spec.md)","tokens":300,"sizeBytes":232},{"name":"distributed-systems.md","path":".claude/skills/tla-plus/references/patterns/distributed-systems.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/distributed-systems.md","title":"Patterns Skill","category":"anthropic-skill","format":"markdown","content":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/distributed-systems.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/distributed-systems.md)","tokens":300,"sizeBytes":246},{"name":"invariants.md","path":".claude/skills/tla-plus/references/patterns/invariants.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/invariants.md","title":"Patterns Skill","category":"anthropic-skill","format":"markdown","content":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/invariants.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/invariants.md)","tokens":300,"sizeBytes":228},{"name":"protocols.md","path":".claude/skills/tla-plus/references/patterns/protocols.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/protocols.md","title":"Patterns Skill","category":"anthropic-skill","format":"markdown","content":"# Patterns Skill\n\nPath: `.claude/skills/tla-plus/references/patterns/protocols.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/patterns/protocols.md)","tokens":300,"sizeBytes":226},{"name":"pluscal.md","path":".claude/skills/tla-plus/references/pluscal.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/pluscal.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/tla-plus/references/pluscal.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/references/pluscal.md)","tokens":300,"sizeBytes":206},{"name":"SKILL.md","path":".claude/skills/tla-plus/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/SKILL.md","title":"tla-plus","category":"anthropic-skill","format":"markdown","content":"---\nname: tla-plus\nversion: \"1.0.0\"\ndescription: Create, run, and verify TLA+ and PlusCal formal specifications. Use for modeling distributed systems, protocols, concurrent algorithms, state machines. Can compose specs from code, find divergences between spec and implementation, spot concurrency bugs and invariant violations. Use when asked to \"write a TLA+ spec\", \"model check\", \"verify protocol\", \"find race conditions\", or \"formal verification\".\n---\n\n# TLA+ Formal Specification Skill\n\nWrite non-trivial TLA+ specifications, run the TLC model checker, and bridge the gap between formal specs and implementation code.\n\n## Setup (Run Once)\n\n```bash\nbash SKILL_DIR/scripts/setup.sh\n```\n\nThis downloads `tla2tools.jar` (v1.8.0) and verifies Java 11+. The JAR is stored at `SKILL_DIR/lib/tla2tools.jar`.\n\n## Quick Reference\n\nLoad the right reference for your task:\n\n| Task | Reference |\n|------|-----------|\n| TLA+ syntax, operators, types | [references/language.md](references/language.md) |\n| PlusCal syntax, processes, labels | [references/pluscal.md](references/pluscal.md) |\n| Distributed systems patterns | [references/patterns/distributed-systems.md](references/patterns/distributed-systems.md) |\n| Protocol specifications | [references/patterns/protocols.md](references/patterns/protocols.md) |\n| Invariants, safety, liveness | [references/patterns/invariants.md](references/patterns/invariants.md) |\n| Code ↔ spec mapping, bug finding | [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md) |\n\n**Load references on-demand** — read the ones relevant to the current task before writing any spec.\n\n## Templates\n\nStart from a template when creating a new spec:\n\n| Template | Use For |\n|----------|---------|\n| [templates/basic.tla](templates/basic.tla) | Pure TLA+ state machine |\n| [templates/pluscal.tla](templates/pluscal.tla) | PlusCal algorithm with processes |\n| [templates/distributed.tla](templates/distributed.tla) | Distributed system with messages |\n\n## Running Specs\n\n### Full Check (Recommended)\n\nTranslates PlusCal (if present), parses, and model-checks in one step:\n\n```bash\nbash SKILL_DIR/scripts/check.sh spec.tla --config spec.cfg\n```\n\n### Individual Tools\n\n```bash\n# Parse only (syntax check)\nbash SKILL_DIR/scripts/parse.sh spec.tla\n\n# Translate PlusCal to TLA+\nbash SKILL_DIR/scripts/translate.sh spec.tla -nocfg\n\n# Model check with TLC\nbash SKILL_DIR/scripts/tlc.sh spec.tla --config spec.cfg --workers auto\nbash SKILL_DIR/scripts/tlc.sh spec.tla --no-deadlock    # suppress deadlock check\n```\n\n### Direct Java Invocation\n\n```bash\nJAR=\"SKILL_DIR/lib/tla2tools.jar\"\n\n# Parse\njava -cp \"$JAR\" tla2sany.SANY spec.tla\n\n# Translate PlusCal\njava -cp \"$JAR\" pcal.trans -nocfg spec.tla\n\n# Model check\njava -cp \"$JAR\" tlc2.TLC -workers auto -config spec.cfg spec.tla\n\n# REPL\njava -cp \"$JAR\" tlc2.REPL\n\n# Dump state graph (for visualization)\njava -cp \"$JAR\" tlc2.TLC -dump dot,actionlabels,colorize states.dot spec.tla\n```\n\n## Workflow: Writing a Spec\n\n### 1. Understand the System\n\nBefore writing any TLA+:\n- Identify the **concurrent agents** (processes, nodes, threads)\n- Identify **shared mutable state** (queues, databases, locks, counters)\n- Identify **the key safety property** (\"what must never happen?\")\n- Identify **the key liveness property** (\"what must eventually happen?\")\n\n### 2. Choose PlusCal vs Pure TLA+\n\n**Use PlusCal when:**\n- The system is naturally sequential/imperative\n- You're modeling code (threads, goroutines, async tasks)\n- You need `await`, `while`, `goto` semantics\n- The audience is programmers\n\n**Use Pure TLA+ when:**\n- You need fine-grained fairness control\n- The system is naturally a state machine\n- You need interruptible/restartable actions\n- You need refinement mappings\n- A single label would need to update a variable twice\n\n### 3. Start Small, Then Expand\n\n1. Write the **simplest possible spec** that captures the core behavior\n2. Add a **type invariant** immediately\n3. Run TLC with small constants (2-3 nodes, 2-3 messages)\n4. Add **safety invariants** one at a time, running after each\n5. Add **liveness properties** with fairness\n6. Increase constants to expand coverage\n\n### 4. Config File\n\nEvery spec needs a `.cfg` file. Create one alongside the `.tla`:\n\n```\nSPECIFICATION Spec\n\n\\* Properties to check\nINVARIANT TypeInvariant\nINVARIANT Safety\n\n\\* Uncomment for liveness (slower)\n\\* PROPERTY Liveness\n\n\\* Constants\nCONSTANT\n  NumNodes = 3\n  MaxMsgs = 5\n  NULL = NULL\n\n\\* Uncomment to bound state space\n\\* CONSTRAINT StateConstraint\n\n\\* Uncomment to ignore deadlocks\n\\* CHECK_DEADLOCK FALSE\n```\n\n## Workflow: Spec From Code\n\nWhen the user has existing code and wants a spec:\n\n1. **Read the code** — understand concurrency structure, shared state, synchronization\n2. **Read** [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md)\n3. **Map constructs** — threads→processes, locks→await, channels→queues\n4. **Abstract** — don't model every line, only concurrency-relevant operations\n5. **Write spec** — start with the concurrent skeleton, add detail iteratively\n6. **Run TLC** — find deadlocks, invariant violations, liveness failures\n7. **Report** — translate any TLC error traces back to code execution paths\n\n## Workflow: Finding Bugs\n\nWhen comparing a spec to code, or looking for bugs:\n\n1. **Read** [references/patterns/code-to-spec.md](references/patterns/code-to-spec.md)\n2. **Write a spec** modeling the suspected buggy area\n3. **Run with small constants** — TLC is exhaustive, small state space is fine\n4. **Interpret error traces** — map TLA+ state sequences to code execution paths\n5. **Check atomicity** — does the code do atomically what the spec's label does?\n6. **Check completeness** — does the code handle all `either/or` branches?\n7. **Check ordering** — does the code enforce the same happens-before relations?\n\nIf TLC finds a violation:\n- The error trace is a **concrete counterexample** — a specific sequence of events\n- Map each state in the trace to concrete code state\n- The transition that causes the violation is the bug location\n\n## Interpreting TLC Output\n\n### Success\n```\nModel checking completed. No error has been found.\n  Estimates of the probability that TLC did not check all reachable states\n  because two distinct states had the same fingerprint:\n  calculated (optimistic):  val: 0\n```\n\n### Invariant Violation\n```\nError: Invariant SafetyInvariant is violated.\nThe following behavior constitutes a counter-example:\nState 1: <Initial predicate>\n  /\\ var1 = ...\nState 2: <Action line X>\n  /\\ var1 = ... (changed values in red)\n```\n\n### Deadlock\n```\nError: Deadlock reached.\n```\n→ No process can make progress. Check `await` conditions and process completion.\n\n### Liveness Violation\n```\nError: Temporal properties were violated.\n```\n→ Check fairness settings. Add `WF_vars` or `SF_vars`. Trace may include a \"stuttering\" suffix.\n\n## Key Principles\n\n1. **Type invariants first** — catch spec bugs before checking real properties\n2. **Small constants** — 3 nodes finds most bugs; 10 nodes takes 1000× longer\n3. **Safety before liveness** — invariants are faster to check\n4. **One property at a time** — add incrementally, run after each addition\n5. **Fairness is opt-in** — TLA+ assumes everything can crash by default\n6. **`=>` with `\\A`, `/\\` with `\\E`** — never use `=>` with `\\E`\n7. **Sequences are 1-indexed** — always\n8. **Every action must specify all variables** — use `UNCHANGED` for untouched ones\n","frontmatter":{"name":"tla-plus","version":"1.0.0","description":"Create, run, and verify TLA+ and PlusCal formal specifications. Use for modeling distributed systems, protocols, concurrent algorithms, state machines. Can compose specs from code, find divergences between spec and implementation, spot concurrency bugs and invariant violations. Use when asked to \"write a TLA+ spec\", \"model check\", \"verify protocol\", \"find race conditions\", or \"formal verification\"."},"isInternal":false,"tokens":1881,"sizeBytes":7500},{"name":"bug-taxonomy.md","path":".claude/skills/write-reproducer/references/bug-taxonomy.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/bug-taxonomy.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/bug-taxonomy.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/bug-taxonomy.md)","tokens":300,"sizeBytes":232},{"name":"concurrency.md","path":".claude/skills/write-reproducer/references/concurrency.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/concurrency.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/concurrency.md)","tokens":300,"sizeBytes":230},{"name":"distributed-systems.md","path":".claude/skills/write-reproducer/references/distributed-systems.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/distributed-systems.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/distributed-systems.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/distributed-systems.md)","tokens":300,"sizeBytes":246},{"name":"failure-classification.md","path":".claude/skills/write-reproducer/references/failure-classification.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/failure-classification.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/failure-classification.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/failure-classification.md)","tokens":300,"sizeBytes":252},{"name":"fuzzing.md","path":".claude/skills/write-reproducer/references/fuzzing.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/fuzzing.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/fuzzing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/fuzzing.md)","tokens":300,"sizeBytes":222},{"name":"minimality-lattice.md","path":".claude/skills/write-reproducer/references/minimality-lattice.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimality-lattice.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/minimality-lattice.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimality-lattice.md)","tokens":300,"sizeBytes":244},{"name":"minimization.md","path":".claude/skills/write-reproducer/references/minimization.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimization.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/minimization.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/minimization.md)","tokens":300,"sizeBytes":232},{"name":"output-contract.md","path":".claude/skills/write-reproducer/references/output-contract.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/output-contract.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/output-contract.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/output-contract.md)","tokens":300,"sizeBytes":238},{"name":"property-based-testing.md","path":".claude/skills/write-reproducer/references/property-based-testing.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/property-based-testing.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/property-based-testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/property-based-testing.md)","tokens":300,"sizeBytes":252},{"name":"shrinking-checklist.md","path":".claude/skills/write-reproducer/references/shrinking-checklist.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/shrinking-checklist.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/shrinking-checklist.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/shrinking-checklist.md)","tokens":300,"sizeBytes":246},{"name":"test-patterns.md","path":".claude/skills/write-reproducer/references/test-patterns.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/test-patterns.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.claude/skills/write-reproducer/references/test-patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/references/test-patterns.md)","tokens":300,"sizeBytes":234},{"name":"SKILL.md","path":".claude/skills/write-reproducer/SKILL.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/SKILL.md","title":"write-reproducer","category":"anthropic-skill","format":"markdown","content":"---\nname: write-reproducer\nversion: \"1.0.0\"\ndescription: \"Write minimal, reliable bug reproducers (repros) for any project. Use when: (1) a bug report or issue needs a test that reliably demonstrates the failure, (2) converting a described failure scenario into runnable code, (3) minimizing an existing complex test to its essential trigger conditions. Covers the full repro workflow: failure characterization, scope selection, writing the repro, verifying it fails for the right reason, and minimizing to the smallest possible trigger.\"\n---\n\n# Write Bug Reproducer\n\nYour goal is to turn a bug description into a minimal, self-contained, runnable reproduction that triggers a specific, machine-checkable failure criterion.\n\nA reproducer has three parts — keep them distinct in your head and in your code:\n\n- **Trigger**: the minimum input, state, schedule, or environment that causes the bug\n- **Harness**: how the trigger is executed (test runner, script, container, cluster test)\n- **Oracle**: the machine-checkable failure criterion (assertion, exit code, log pattern, invariant violation)\n\nFollow the five phases below in order. Do not skip ahead. Write the failure criterion before writing any repro code.\n\n## Phase 1: Understand and classify\n\nRestate the bug in one sentence: \"The bug is...\"\n\nClassify along three axes:\n\n- **Bug class**: crash, incorrect output, hang/deadlock, race condition, assertion/invariant violation, performance regression, resource leak, serialization bug, consistency anomaly. See `references/bug-taxonomy.md` for the full taxonomy when classification is unclear.\n- **Scope**: pure function, module, single process, multiple processes, cluster.\n- **Determinism**: deterministic, flaky (state what makes it flaky), requires rare schedule or timing.\n\nIf the user gave only symptoms with no code, list the 2-4 most likely causes before proceeding. Do not pick one yet — write hypotheses, not conclusions.\n\nIf the user included code or pointed at a codebase, read the suspect region and identify the likely code path before moving on.\n\n## Phase 2: Define the failure criterion\n\nThis is the most important phase. Before writing any repro code, write out the oracle in one of these machine-checkable forms:\n\n- **Assertion with concrete values**: `assert expected == actual` with both spelled out\n- **Exit code**: `expected: 0, actual: 139 (SIGSEGV)`\n- **Regex against stdout/stderr**: exact string fragment to match\n- **Log grep**: file and pattern\n- **Exception type and message fragment**: the specific error and location\n- **Linearizability/isolation check result**: checker verdict (e.g., linearizability violation, cycle detected)\n- **Invariant violation**: state the invariant in one line; state what breaks it\n\nRecord the failure criterion verbatim. It will be used in Phase 4 (to write the assertion) and Phase 5 (to prevent shrinking into a different bug).\n\nWithout an explicit oracle, shrinking can produce something that \"fails\" but not in the described way, and reviewers cannot tell whether the repro is successful.\n\n## Phase 3: Detect context and choose repro form\n\nInspect the working directory for build-system markers and prefer the project's existing test framework and conventions. Explore existing tests to understand helpers, fixtures, naming patterns, and how integration tests are structured.\n\nPick the lowest tier on the minimality lattice that can reliably exhibit the failure. See `references/minimality-lattice.md` for tier definitions and decision rules.\n\n- Tier 1: expression / REPL snippet\n- Tier 2: single-file snippet with `main`\n- Tier 3: single test in the project's existing framework\n- Tier 4: multi-file project fixture\n- Tier 5: containerized environment + test script\n- Tier 6: ephemeral cluster\n- Tier 7: deterministic simulation\n\nWrite one sentence naming the tier and why, based on what you found in the project.\n\nFor concurrency bugs: `references/concurrency.md`\nFor distributed-systems bugs: `references/distributed-systems.md`\nFor invariant bugs where a property test is the natural form: `references/property-based-testing.md`\nFor bugs found by fuzzing or where a fuzz harness is the natural repro: `references/fuzzing.md`\n\n## Phase 4: Draft the repro\n\n### Structure\n\nLabel the three parts in comments:\n\n```\n// TRIGGER: <what causes the bug>\n// HARNESS: <how we run it>\n// ORACLE:  <what we check>\n```\n\nUse the project's test framework and conventions. Match existing test style. Do not introduce a new framework unless the existing one cannot express the bug.\n\n### The pass-then-invert strategy\n\nFor subtle assertion bugs where the correct behavior is easy to state but the failing test is hard to get right, use **pass-then-invert**: first write a test that *passes* on the current buggy behavior (mirroring the observed wrong output in its assertions), then invert the assertions so they encode the *correct* expectation and therefore fail on the bug. This reduces hallucinated APIs and setup errors compared to writing a failing test directly.\n\nUse pass-then-invert when:\n- The bug produces a wrong value (not a crash or exception)\n- The correct expected value is known\n- Direct \"write a failing test\" attempts keep failing for setup reasons\n\nDo not use pass-then-invert when:\n- The bug is a crash, exception, or hang — just trigger it directly\n- The oracle is an absence check (no exception, no crash) — inversion doesn't apply\n\n### Verification before presenting\n\nThe repro must compile or parse cleanly. Resolve imports against the project's actual dependencies. Do not hallucinate APIs — if unsure of a method signature, read the library source or ask.\n\nIf execution is available, run the repro and confirm the failure criterion triggers. If not, trace through the code mentally and state your confidence level.\n\n### Generating multiple candidates\n\nWhen the bug is unclear or the first attempt fails, generate 2-5 candidate repro strategies:\n- Smallest direct unit test\n- Integration test if state/config matters\n- Standalone script if no test harness is obvious\n- Property-based test if the bug is about an invariant\n- Fuzz seed / deterministic scenario for correctness bugs\n\nExecute each candidate with a timeout. Classify each result using `references/failure-classification.md`. Refine until one produces an issue-relevant failure.\n\n### Documentation\n\nThe repro must include a comment or docstring stating:\n- Issue reference and one-line bug title\n- Expected (correct) behavior\n- Actual (buggy) behavior\n- Failure criterion (verbatim from Phase 2)\n\n## Phase 5: Shrink and validate\n\n### Validate first\n\nRun the repro (or trace through it mentally) and confirm:\n1. The failure criterion from Phase 2 triggers\n2. The failure is the *described* bug, not a test setup error\n3. The failure message matches what Phase 2 specified\n\nSee `references/failure-classification.md` for how to classify test results and distinguish issue-relevant failures from setup errors.\n\n### Then shrink\n\nUse the subtraction method from `references/minimization.md`. Work through dimensions in order (cheapest first):\n1. Reduce infrastructure scale (instances, partitions, replication)\n2. Reduce data volume (items, size, batches)\n3. Remove non-default configuration\n4. Remove setup steps\n5. Replace real sleeps with controlled time or polling\n6. Simplify trigger sequence\n\nSee `references/shrinking-checklist.md` for the guardrail checklist.\n\n### Over-minimization guardrail\n\nAfter each shrinking step, re-check that the failure is still *the same failure* — same assertion, same exception type, same message fragment from Phase 2. If the failure changed, revert that step. This prevents shrinking into a different bug.\n\n### For nondeterministic bugs\n\nWrap the trigger in an N-iteration harness with a retry budget. Report the observed failure rate (e.g., \"fails 23/1000 iterations\"). Do not use sleep-based synchronization — it makes tests flaky on different hardware. Prefer event-based scheduling, explicit synchronization primitives, or deterministic simulation.\n\nAlways print and record seeds for randomized tests so failing scenarios can be replayed.\n\n## Output\n\nAlways produce:\n\n1. **Repro file(s)** with `// TRIGGER`, `// HARNESS`, `// ORACLE` comments. Correct file placement matching the project's test layout.\n2. **Status**: one of `REPRODUCED` / `CANDIDATE` / `BLOCKED`. See `references/output-contract.md` for what each status means and requires.\n3. **Run command**: the exact command to execute the repro.\n4. **Failure summary**: \"This test should fail on the current code with: `<expected failure message>`\"\n5. **For flaky bugs**: failure rate and seed.\n6. **For blocked repros**: what's missing, what was attempted, next best direction.\n\n## Hard rules\n\n- **Write the failure criterion before the repro code.** Without an explicit oracle, you cannot distinguish a successful repro from a coincidental failure. This is the single most common failure mode.\n\n- **Do not hallucinate APIs.** If unsure whether a method, class, or flag exists, read the source or ask. Hallucinated APIs are the most frequent reason LLM-generated repros fail to compile.\n\n- **Assert expected behavior, not current broken behavior.** The oracle encodes what *should* happen. The test fails because reality doesn't match.\n\n- **Do not shrink past the bug.** After every shrinking step, re-verify the failure matches Phase 2. See `references/shrinking-checklist.md`.\n\n- **Flaky repros must declare their flakiness.** A repro that reproduces 23/1000 times must say so and wrap itself in a retry loop.\n\n- **Match the project's conventions.** Use the test framework, style, and helpers that already exist. Do not introduce a new framework unless the existing one cannot express the bug.\n\n- **Do not fix the bug.** Create tests/scripts/harnesses only. Do not edit production code unless explicitly asked.\n\n- **Do not use `:latest` image tags or unpinned dependency versions.** A repro is not reproducible if its dependencies drift.\n\n- **Do not confuse setup errors with reproduced bugs.** An error in test setup is not the same as the error caused by the bug. See `references/failure-classification.md`.\n\n## When to escalate to higher tiers\n\nEscalate to Tier 5+ (containerized, cluster, deterministic simulation) when:\n\n- The bug involves two or more processes (client + server, replica + leader)\n- The bug requires a specific network condition (partition, delay, drop)\n- The bug requires clock skew or node failure scenarios\n- The bug is about isolation, linearizability, or consensus\n- The user mentions Cassandra, Kafka, or any distributed system\n\nFor these cases read `references/distributed-systems.md` before drafting.\n\n## When to use a property-based test\n\nUse a property-based test when:\n\n- The bug is about an invariant (round-trip, idempotence, commutativity, ordering, bounded sums)\n- Shrinking comes for free in the property framework\n- You want the test to serve as a regression test with seed persistence\n\nSee `references/property-based-testing.md`.\n\n## When to use a fuzz harness\n\nUse a fuzz harness when:\n\n- The bug was originally found by fuzzing and a crashing input exists\n- The input is a byte stream or structured binary format\n- A single example fails but many nearby inputs are interesting for regression\n\nSee `references/fuzzing.md`.\n","frontmatter":{"name":"write-reproducer","version":"1.0.0","description":"Write minimal, reliable bug reproducers (repros) for any project. Use when: (1) a bug report or issue needs a test that reliably demonstrates the failure, (2) converting a described failure scenario into runnable code, (3) minimizing an existing complex test to its essential trigger conditions. Covers the full repro workflow: failure characterization, scope selection, writing the repro, verifying it fails for the right reason, and minimizing to the smallest possible trigger."},"isInternal":false,"tokens":2442,"sizeBytes":11314},{"name":"cqlstress-counter-example.yaml","path":"tools/cqlstress-counter-example.yaml","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-counter-example.yaml","title":"Tools Skill","category":"anthropic-skill","format":"yaml","content":"# Tools Skill\n\nPath: `tools/cqlstress-counter-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-counter-example.yaml)","tokens":300,"sizeBytes":183},{"name":"cqlstress-example.yaml","path":"tools/cqlstress-example.yaml","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-example.yaml","title":"Tools Skill","category":"anthropic-skill","format":"yaml","content":"# Tools Skill\n\nPath: `tools/cqlstress-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-example.yaml)","tokens":300,"sizeBytes":167},{"name":"cqlstress-insanity-example.yaml","path":"tools/cqlstress-insanity-example.yaml","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-insanity-example.yaml","title":"Tools Skill","category":"anthropic-skill","format":"yaml","content":"# Tools Skill\n\nPath: `tools/cqlstress-insanity-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-insanity-example.yaml)","tokens":300,"sizeBytes":185},{"name":"cqlstress-lwt-example.yaml","path":"tools/cqlstress-lwt-example.yaml","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-lwt-example.yaml","title":"Tools Skill","category":"anthropic-skill","format":"yaml","content":"# Tools Skill\n\nPath: `tools/cqlstress-lwt-example.yaml`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/tools/cqlstress-lwt-example.yaml)","tokens":300,"sizeBytes":175},{"name":".gitkeep","path":".claude/skills/deep-review/references/deep/.gitkeep","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/.gitkeep","title":"Claude Directive: .gitkeep","category":"claude-rule","format":"markdown","content":"# Claude Directive: .gitkeep\n\nPath: `.claude/skills/deep-review/references/deep/.gitkeep`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/.gitkeep)","tokens":300,"sizeBytes":228},{"name":"heatmap.py","path":".claude/skills/heatmap/heatmap.py","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/heatmap/heatmap.py","title":"Claude Directive: heatmap.py","category":"claude-rule","format":"markdown","content":"# Claude Directive: heatmap.py\n\nPath: `.claude/skills/heatmap/heatmap.py`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/heatmap/heatmap.py)","tokens":300,"sizeBytes":194},{"name":"install.sh","path":".claude/skills/install.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/install.sh","title":"Claude Directive: install.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: install.sh\n\nPath: `.claude/skills/install.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/install.sh)","tokens":300,"sizeBytes":178},{"name":"check.sh","path":".claude/skills/tla-plus/scripts/check.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/check.sh","title":"Claude Directive: check.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: check.sh\n\nPath: `.claude/skills/tla-plus/scripts/check.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/check.sh)","tokens":300,"sizeBytes":206},{"name":"parse.sh","path":".claude/skills/tla-plus/scripts/parse.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/parse.sh","title":"Claude Directive: parse.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: parse.sh\n\nPath: `.claude/skills/tla-plus/scripts/parse.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/parse.sh)","tokens":300,"sizeBytes":206},{"name":"setup.sh","path":".claude/skills/tla-plus/scripts/setup.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/setup.sh","title":"Claude Directive: setup.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: setup.sh\n\nPath: `.claude/skills/tla-plus/scripts/setup.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/setup.sh)","tokens":300,"sizeBytes":206},{"name":"tlc.sh","path":".claude/skills/tla-plus/scripts/tlc.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/tlc.sh","title":"Claude Directive: tlc.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: tlc.sh\n\nPath: `.claude/skills/tla-plus/scripts/tlc.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/tlc.sh)","tokens":300,"sizeBytes":200},{"name":"translate.sh","path":".claude/skills/tla-plus/scripts/translate.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/translate.sh","title":"Claude Directive: translate.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: translate.sh\n\nPath: `.claude/skills/tla-plus/scripts/translate.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/scripts/translate.sh)","tokens":300,"sizeBytes":218},{"name":"basic.tla","path":".claude/skills/tla-plus/templates/basic.tla","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/basic.tla","title":"Claude Directive: basic.tla","category":"claude-rule","format":"markdown","content":"# Claude Directive: basic.tla\n\nPath: `.claude/skills/tla-plus/templates/basic.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/basic.tla)","tokens":300,"sizeBytes":213},{"name":"distributed.tla","path":".claude/skills/tla-plus/templates/distributed.tla","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/distributed.tla","title":"Claude Directive: distributed.tla","category":"claude-rule","format":"markdown","content":"# Claude Directive: distributed.tla\n\nPath: `.claude/skills/tla-plus/templates/distributed.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/distributed.tla)","tokens":300,"sizeBytes":231},{"name":"pluscal.tla","path":".claude/skills/tla-plus/templates/pluscal.tla","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/pluscal.tla","title":"Claude Directive: pluscal.tla","category":"claude-rule","format":"markdown","content":"# Claude Directive: pluscal.tla\n\nPath: `.claude/skills/tla-plus/templates/pluscal.tla`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/tla-plus/templates/pluscal.tla)","tokens":300,"sizeBytes":219},{"name":"detect_context.sh","path":".claude/skills/write-reproducer/scripts/detect_context.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/detect_context.sh","title":"Claude Directive: detect_context.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: detect_context.sh\n\nPath: `.claude/skills/write-reproducer/scripts/detect_context.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/detect_context.sh)","tokens":300,"sizeBytes":249},{"name":"shrink_text.py","path":".claude/skills/write-reproducer/scripts/shrink_text.py","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/shrink_text.py","title":"Claude Directive: shrink_text.py","category":"claude-rule","format":"markdown","content":"# Claude Directive: shrink_text.py\n\nPath: `.claude/skills/write-reproducer/scripts/shrink_text.py`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/shrink_text.py)","tokens":300,"sizeBytes":240},{"name":"validate_repro.sh","path":".claude/skills/write-reproducer/scripts/validate_repro.sh","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/validate_repro.sh","title":"Claude Directive: validate_repro.sh","category":"claude-rule","format":"markdown","content":"# Claude Directive: validate_repro.sh\n\nPath: `.claude/skills/write-reproducer/scripts/validate_repro.sh`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/write-reproducer/scripts/validate_repro.sh)","tokens":300,"sizeBytes":249},{"name":"CLAUDE.md","path":"CLAUDE.md","rawUrl":"https://raw.githubusercontent.com/apache/cassandra/HEAD/CLAUDE.md","title":"Claude Agent Guidelines & System Prompt","category":"claude-rule","format":"markdown","content":"# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n","isInternal":false,"tokens":1077,"sizeBytes":4438}],"systemPromptSnippet":"<yakaai_skills repo=\"apache/cassandra\">\n<!-- File: AGENTS.md (Tokens: ~1077 | Category: root-instruction) -->\n# Agent Instructions for Apache Cassandra\n\n> These instructions apply to all AI-assisted contributions to `apache/cassandra`.\n\n## Apache Cassandra\nApache Cassandra is a NoSQL distributed database. This is the official Git repository.\n\n## Environment\n\n- Java 11 (default), 17, 21.\n- Python 3 for `cqlsh` and dtests.\n- Apache Ant >= 1.10 for all builds. Do NOT attempt to use Maven, Gradle, or any other build tool. Cassandra uses Ant exclusively.\n- Do NOT attempt to install dependencies, every dependency requires OSS community approval first.\n\n## Build\n\nPrefer the `.build/*.sh` helper scripts over calling `ant` directly. See\n[.build/README.md](./.build/README.md) for the full set.\n\n```bash\n.build/build-jars.sh -s          # build the Cassandra JAR (runs `ant jar`)\n.build/build-jars.sh -s --clean  # clean first, then build\n```\n\nAll three scripts accept `-s`/`--summary`, which prints a summary of failures instead of the full ant output.  Omit it for the full output.  `--clean` applies to `.build/build-jars.sh` only.\n\n## Testing\n\n- Do NOT run the entire test suite. Run only the specific test(s) relevant to your change.\n- The project must be built first (e.g. `.build/build-jars.sh`).\n\n    ```bash\n    # Run a single test class: -a is the test type, -t is a class-name regexp\n    .build/run-tests.sh -s -a test -t StorageServiceServerTest\n    ```\n\n- `-a` is the test type (`test`, `jvm-dtest`, `long-test`, …; run `.build/run-tests.sh -h` for the full list).\n- `-t` matches the test class only, not individual methods.\n- `-s`/`--summary` prints a concise list of failed tests.  The full output is kept in `build/run-tests.log`.\n- When fixing a bug, first create a regression test that reproduces the failure, then implement the fix and verify.\n- Provide test(s) coverage for all new or modified code.\n\n## Linting and Code Checks\n\n```bash\n.build/check-code.sh -s    # runs `ant check` (rat-check + checkstyle + checkstyle-test, after a build)\n```\n\nThe `check` target depends on `_main-jar`, `build-test` and `gen-asciidoc`, so\n`.build/check-code.sh` builds the jar and the test classes itself.  Do not run\n`.build/build-jars.sh` before it.\n\nThe same dependencies make `check` slower than checkstyle alone: it also generates the\ndocumentation, and `rat-check` reads every file in the working directory.\n\n## Code Style\nCassandra enforces style via Checkstyle (run via `.build/check-code.sh`). The official style guide is at https://cassandra.apache.org/_/development/code_style.html. Always defer to it when in doubt.\n\nGeneral style conventions:\n- 4-space indentation, no tabs.\n- Match existing code style in the file you are editing.\n- All new files must include the Apache License 2.0 header.\n- Concise English documentation is required for complex classes and methods; trivial ones may not require them.\n- Shorten (make succinct) comments. Comments are not needed for what can easily be read from the code.\n\n# Docker mode\nIf commands fails due to host issues, and docker is available, use the `.build/docker/` command equivalents.\n\n## Git Workflow\n- Do NOT commit unless explicitly asked.\n- Commit messages format. For example:\n\n    ```\n    <One sentence description, usually Jira title or CHANGES.txt summary, no jira id>\n\n    <Optional lengthier description>\n  \n     patch by <Authors,>; reviewed by <Reviewers,> for CASSANDRA-#####\n\n    Assisted-by: AGENT_NAME:MODEL_VERSION\n    ```\n\n\n## Boundaries\n\n- 🚫 Never modify generated files in `src/gen-java/` — they are built from `src/antlr/` grammars.\n- 🚫 Never modify files in `lib/` — these are managed dependencies.\n- 🚫 Never commit secrets, credentials, or API keys.\n- 🚫 Never run the full test suite — it takes hours. Run targeted tests only.\n- 🚫 Never bypass Checkstyle violations without a suppression comment explaining why.\n- ⚠️ Ask before modifying the CQL grammar (`src/antlr/Cql.g`) — changes cascade widely.\n\n## Security\n\nSecurity model: [SECURITY.md](./SECURITY.md), which links to the project's\nsecurity model at\n[doc/modules/cassandra/pages/reference/security-model.adoc](./doc/modules/cassandra/pages/reference/security-model.adoc).\n\nAutomated agents (security scanners, code analyzers) that scan this\nrepository should consult that security model for the project's in-scope /\nout-of-scope declarations, trust boundaries, the security properties\nCassandra provides and disclaims, and how findings are triaged, before\nreporting issues.\n\n<!-- File: .claude/skills/bug-archaeology/references/EVAL-PROMPT.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/EVAL-PROMPT.md)\n\n<!-- File: .claude/skills/bug-archaeology/references/per-bug-format.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/per-bug-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/per-bug-format.md)\n\n<!-- File: .claude/skills/bug-archaeology/references/synthesis-format.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/bug-archaeology/references/synthesis-format.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/bug-archaeology/references/synthesis-format.md)\n\n<!-- File: .claude/skills/bug-archaeology/SKILL.md (Tokens: ~1321 | Category: anthropic-skill) -->\n---\nname: bug-archaeology\nversion: \"1.0.0\"\ndescription: >\n  Mine bug patterns from any git repository. Discovers bug-fix commits via git log\n  heuristics, analyzes each in parallel with subagents, writes individual analysis files,\n  and synthesizes a generalized PATTERNS.md with repo-specific details stripped.\n  Invoke explicitly with /bug-archaeology.\n---\n\n# Bug Archaeology\n\nSystematic extraction of reusable bug-detection heuristics from a repository's commit history.\n\n## Arguments\n\nAll optional. Parse from the user's invocation string.\n\n| Arg | Default | Description |\n|-----|---------|-------------|\n| `--range` | `HEAD~200..HEAD` | Git revision range |\n| `--path` | (all files) | Restrict to commits touching this path glob |\n| `--since` / `--until` | (none) | Date filter for `git log` |\n| `--limit` | 200 | Max bug-fix commits to analyze |\n| `--batch-size` | 10 | Commits per subagent |\n| `--output` | `./bug-archaeology/` | Output directory |\n\n## Workflow\n\nThree sequential phases. Each phase completes fully before the next starts.\n\n### Phase 1: Discovery\n\nFind bug-fix commits via git log heuristics.\n\n```bash\ngit log --no-merges --pretty=format:\"%H %s\" [--since=X] [--until=X] <range> [-- <path>] \\\n  | grep -iE '(fix|bug|patch|resolve|repair|correct|workaround|hotfix|regression|#[0-9]+|[A-Z]+-[0-9]+)'\n```\n\n**Filter out** commits whose message matches ONLY cosmetic keywords (`typo`, `whitespace`, `import`, `format`, `style`, `cleanup`, `rename`) with no bug keywords.\n\n**Truncate** to `--limit`.\n\n**Write** `QUEUE.txt` to the output directory:\n```\n0001 abc123def First line of commit message\n0002 def456abc Another commit message\n```\n\n**Resumption**: If `PROGRESS.md` exists, read it and exclude commits already marked `done` or `skipped`. Re-include `pending` and `error` entries.\n\n### Phase 2: Analysis (parallelized)\n\nSpawn subagents to analyze commits in batches. Each commit is independent.\n\n**Subagent prompt template** — adapt as needed:\n```\nRead the file at references/per-bug-format.md for the output format specification.\n\nAnalyze these commits from the repository at <REPO_PATH>:\n<list of \"NNNN hash message\" lines>\n\nFor each commit:\n1. Run: git show <hash>\n2. If the commit is cosmetic, test-only, refactor-only, or a merge with no\n   original changes — mark it as skipped with a one-word reason.\n3. Otherwise, write the analysis to <OUTPUT>/bug-<NNNN>-<slug>.md\n   following the format in per-bug-format.md exactly.\n\nReturn a status line per commit: NNNN <hash> done|skipped [reason-or-filename]\n```\n\n**Parallelism**: Launch up to 5 subagent batches concurrently. Wait for all to complete before the next wave.\n\n**Progress tracking**: After each wave, append results to `PROGRESS.md`:\n```markdown\n| # | Commit | Status | File / Reason |\n|---|--------|--------|---------------|\n| 0001 | abc123d | done | bug-0001-null-after-lookup.md |\n| 0002 | def456a | skipped | cosmetic |\n```\n\n**Errors**: Mark as `error` with a one-line reason. Don't retry — the user re-invokes with `--resume`.\n\n### Phase 3: Synthesis\n\nAfter all analysis is complete, produce `PATTERNS.md`. Read `references/synthesis-format.md` for the full specification.\n\n**Process**:\n1. Read all `bug-*.md` files in the output directory\n2. Parse the `Tags` section from each — extract `category` and `code-pattern`\n3. Group bugs by `code-pattern` tag\n4. For each group of 2+ bugs with the same code-pattern:\n   - Extract the shared Detection Rule (generalize if they differ across instances)\n   - Pick the most representative Example\n5. **Generalize** — strip repo-specific details:\n   - Replace specific class/method names with structural descriptions\n   - Remove ticket IDs, author names, project-specific subsystem labels\n   - Keep language-specific API names only if scope is that language or broader\n6. Group patterns by `category` and write `PATTERNS.md`\n7. Patterns with only 1 instance go in a \"Singletons\" section at the end\n\n## Reference Files\n\n| File | Loaded by | Purpose |\n|------|-----------|---------|\n| `references/per-bug-format.md` | Subagents (Phase 2) | Per-bug output template and field guidelines |\n| `references/synthesis-format.md` | Orchestrator (Phase 3) | PATTERNS.md structure and generalization rules |\n\n## Evaluating the Skill\n\nFull instructions are in `references/EVAL-PROMPT.md`. Summary:\n\n1. **Pick a bug** from the archaeology output and trace its introducing commit via `git blame`.\n2. **Extract the patch** with `git diff ${INTRO}~1 $INTRO`.\n3. **Choose a review skill** — the user must specify one:\n   - `/shallow-review` — quick 6-specialist parallel scan, any patch size\n   - `/deep-review` — focused on specific files, complex logic\n   - `/targeted-review` — findings-driven, medium-to-large patches\n   - `/mega-review` — large feature branches or 1000+ LOC diffs\n4. **Run the chosen skill** against the extracted patch.\n5. **Score** the output: Exact / Partial / Different bug / Miss.\n6. **Prod misses** — tell the skill what it missed and ask which checklist item would have caught it; use the answer to improve that skill's reference files.\n\nTarget: >90% hit rate (exact + partial), <5% miss rate across a batch of N bugs.\n\n<!-- File: .claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/advanced_patterns.md)\n\n<!-- File: .claude/skills/cassandra-injvm-dtest/references/classloader_guide.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/classloader_guide.md)\n\n<!-- File: .claude/skills/cassandra-injvm-dtest/references/cluster_utils.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/cassandra-injvm-dtest/references/cluster_utils.md)\n\n<!-- File: .claude/skills/cassandra-injvm-dtest/SKILL.md (Tokens: ~6931 | Category: anthropic-skill) -->\n---\nname: cassandra-injvm-dtest\nversion: \"1.0.0\"\ndescription: Comprehensive guide for writing Apache Cassandra in-JVM distributed tests (dtests). Use when creating tests that simulate multi-node Cassandra clusters within a single JVM for faster integration testing. Covers cluster creation (single-node, multi-node, multi-datacenter), configuration (all cassandra.yaml parameters, features, network topology), instance lifecycle (startup/shutdown/restart), query execution, message filtering for failure scenarios, running code on instances, ClusterUtils utilities, and debugging classloader-related issues (serialization failures, same-class-different-classloader problems).\n---\n\n# Apache Cassandra In-JVM DTest Writer\n\n## Overview\n\nWrite comprehensive distributed tests for Apache Cassandra using the in-JVM dtest framework. This framework enables multi-node cluster simulation within a single JVM using isolated classloaders, providing fast and reliable integration testing without actual network communication.\n\n## Core Concepts\n\n### Framework Architecture\n\nThe in-JVM dtest framework uses **classloader isolation** to run multiple Cassandra instances in one JVM:\n\n- **Shared ClassLoader**: Common classes (primitives, APIs, config objects, byte buffers)\n- **Per-Instance ClassLoader**: Isolated Cassandra internals (DatabaseDescriptor, singletons, all C* code)\n- **IsolatedExecutor**: Marshals serialized lambdas across classloader boundaries\n- **Message Interception**: Inter-node messaging hooked at MessagingService level (no actual networking)\n\n### Key Classes\n\n| Class | Purpose | Location |\n|-------|---------|----------|\n| `Cluster` | Main entry point for creating clusters | `org.apache.cassandra.distributed.Cluster` |\n| `AbstractCluster` | Core cluster management | `org.apache.cassandra.distributed.impl.AbstractCluster` |\n| `Instance` | Individual Cassandra node | `org.apache.cassandra.distributed.impl.Instance` |\n| `InstanceConfig` | Node configuration | `org.apache.cassandra.distributed.impl.InstanceConfig` |\n| `ClusterUtils` | Utility methods | `org.apache.cassandra.distributed.shared.ClusterUtils` |\n| `ICoordinator` | Query execution interface | API package |\n| `MessageFilters` | Message filtering/dropping | `org.apache.cassandra.distributed.impl.MessageFilters` |\n\n## Quick Start\n\n### Basic Cluster Setup\n\n```java\nimport org.apache.cassandra.distributed.Cluster;\nimport org.apache.cassandra.distributed.api.ConsistencyLevel;\n\n// Create and start a 3-node cluster\ntry (Cluster cluster = Cluster.build(3).start()) {\n    // Create keyspace\n    cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                        \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n    // Create table\n    cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n    // Execute query\n    cluster.coordinator(1).execute(\"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                                  ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n    // Read data\n    Object[][] rows = cluster.coordinator(1).execute(\n        \"SELECT * FROM test.users WHERE id = ?\",\n        ConsistencyLevel.QUORUM, 1);\n}\n```\n\n### Test Base Class Pattern\n\n```java\nimport org.apache.cassandra.distributed.test.TestBaseImpl;\n\npublic class MyDTest extends TestBaseImpl {\n    private static Cluster cluster;\n\n    @BeforeClass\n    public static void setupCluster() throws IOException {\n        cluster = init(Cluster.build(3).start(), 2); // RF=2\n    }\n\n    @AfterClass\n    public static void teardownCluster() {\n        if (cluster != null)\n            cluster.close();\n    }\n\n    @Test\n    public void testSomething() {\n        // Test implementation\n    }\n}\n```\n\n## Cluster Creation Patterns\n\n### Pattern 1: Simple Single-Node Cluster\n\n```java\nCluster cluster = Cluster.build(1).start();\n```\n\n### Pattern 2: Multi-Node Cluster with Configuration\n\n```java\nCluster cluster = Cluster.build(3)\n    .withConfig(config -> config\n        .set(\"num_tokens\", \"256\")\n        .set(\"concurrent_reads\", \"64\")\n        .set(\"concurrent_writes\", \"64\"))\n    .start();\n```\n\n### Pattern 3: Multi-Datacenter Cluster\n\n```java\nCluster cluster = builder()\n    .withRacks(2, 1, 3)  // 2 DCs, 1 rack per DC, 3 nodes per rack\n    .start();\n\n// Or with explicit DC/rack naming\nCluster cluster = builder()\n    .withDC(\"dc1\", 3)\n    .withDC(\"dc2\", 3)\n    .start();\n```\n\n### Pattern 4: Cluster with Features\n\n```java\nimport static org.apache.cassandra.distributed.api.Feature.*;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withConfig(config -> config\n        .with(GOSSIP)           // Enable gossip protocol\n        .with(NETWORK)          // Enable inter-node networking\n        .with(NATIVE_PROTOCOL)  // Enable CQL protocol\n        .with(JMX))             // Enable JMX\n    .start();\n```\n\n### Pattern 5: Custom Token Distribution\n\n```java\nimport org.apache.cassandra.distributed.api.TokenSupplier;\n\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withTokenSupplier(TokenSupplier.evenlyDistributedTokens(3))\n    .start();\n```\n\n### Pattern 6: Dynamic Port Allocation\n\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Configuration\n\n### Available Configuration Parameters\n\nConfiguration is applied via `config.set(key, value)` or `config.with(Feature)`:\n\n#### Network Configuration\n```java\nconfig.set(\"broadcast_address\", \"127.0.0.1\")\n      .set(\"listen_address\", \"127.0.0.1\")\n      .set(\"rpc_address\", \"127.0.0.1\")\n      .set(\"storage_port\", \"7000\")\n      .set(\"native_transport_port\", \"9042\")\n      .set(\"jmx_port\", \"7199\");\n```\n\n#### Token Configuration\n```java\nconfig.set(\"num_tokens\", \"256\")\n      .set(\"initial_token\", \"0\");\n```\n\n#### Memory Configuration\n```java\nconfig.set(\"memtable_heap_space\", \"512MiB\")\n      .set(\"key_cache_size\", \"50MiB\")\n      .set(\"counter_cache_size\", \"50MiB\")\n      .set(\"row_cache_size\", \"0MiB\");\n```\n\n#### Compaction & Concurrency\n```java\nconfig.set(\"concurrent_compactors\", \"4\")\n      .set(\"concurrent_reads\", \"32\")\n      .set(\"concurrent_writes\", \"32\")\n      .set(\"concurrent_counter_writes\", \"32\");\n```\n\n#### Commitlog Configuration\n```java\nconfig.set(\"commitlog_sync\", \"periodic\")\n      .set(\"commitlog_sync_period_in_ms\", \"10000\")\n      .set(\"commitlog_segment_size\", \"32MiB\");\n```\n\n#### Authentication & Authorization\n```java\nconfig.set(\"authenticator\", \"PasswordAuthenticator\")\n      .set(\"authorizer\", \"CassandraAuthorizer\")\n      .set(\"role_manager\", \"CassandraRoleManager\");\n```\n\n#### Accord Configuration (CEP-15)\n```java\nconfig.set(\"accord.enabled\", \"true\")\n      .set(\"accord.journal_directory\", \"/path/to/journal\");\n```\n\n#### Data Directories\n```java\n// Data directories are arrays\nconfig.set(\"data_file_directories\", new String[]{\"/path/to/data\"})\n      .set(\"commitlog_directory\", \"/path/to/commitlog\")\n      .set(\"hints_directory\", \"/path/to/hints\")\n      .set(\"saved_caches_directory\", \"/path/to/saved_caches\");\n```\n\n## Instance Lifecycle Operations\n\n### Starting Instances\n\n```java\n// Start with default settings\ninstance.startup();\n\n// Start with system properties\nClusterUtils.start(instance, properties -> {\n    properties.set(RING_DELAY, \"5000\");\n    properties.set(BOOTSTRAP_SCHEMA_DELAY_MS, \"5000\");\n});\n```\n\n### Stopping Instances\n\n```java\n// Graceful shutdown (blocking)\nClusterUtils.stopUnchecked(instance);\n\n// Abrupt shutdown (simulates kill -9)\nClusterUtils.stopAbrupt(cluster, instance);\n\n// Stop all instances\nClusterUtils.stopAll(cluster);\n\n// Async shutdown\nFuture<?> shutdownFuture = instance.shutdown();\nshutdownFuture.get(); // wait for completion\n```\n\n### Restarting Instances\n\n```java\n// Simple restart\nClusterUtils.restartUnchecked(instance);\n\n// Restart with different configuration\ninstance.shutdown().get();\ninstance.config().set(\"concurrent_reads\", \"64\");\ninstance.startup();\n```\n\n### Adding Instances\n\n```java\n// Add instance with same config as existing nodes\nIInstance newInstance = ClusterUtils.addInstance(cluster);\n\n// Add instance with custom config\nIInstance newInstance = ClusterUtils.addInstance(cluster, config -> {\n    config.set(\"auto_bootstrap\", true);\n});\n\n// Add instance to specific DC/rack\nIInstance newInstance = ClusterUtils.addInstance(cluster, \"dc1\", \"rack1\", config -> {\n    config.set(\"num_tokens\", \"256\");\n});\n\n// Start the new instance\nnewInstance.startup();\n```\n\n### Replacing Instances\n\n```java\n// Replace a failed node\nIInstance replacement = ClusterUtils.replaceHostAndStart(cluster, failedInstance);\n\n// Replace with custom properties\nIInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    failedInstance,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n```\n\n## Running Code on Instances\n\n### Pattern 1: Run Without Return Value\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    StorageService.instance.forceKeyspaceFlush(\"system\");\n});\n```\n\n### Pattern 2: Get Return Value (Sync)\n\n```java\nString version = cluster.get(1).callOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\n```\n\n### Pattern 3: Get Return Value (Async)\n\n```java\nFuture<String> future = cluster.get(1).asyncCallOnInstance(() -> {\n    return FBUtilities.getReleaseVersionString();\n});\nString version = future.get();\n```\n\n### Pattern 4: Pass Parameters\n\n```java\n// Parameters must be serializable\nint result = cluster.get(1).callOnInstance(() -> {\n    // Access Cassandra internals here\n    return ClusterMetadata.current().directory.allAddresses().size();\n});\n```\n\n### Pattern 5: Instance-to-Instance Operations\n\n```java\n// Get node ID from one instance, use it on another\nint nodeId = ClusterUtils.getNodeId(cluster.get(1), cluster.get(2));\n\nNodeId id = new NodeId(nodeId);\ncluster.get(2).runOnInstance(() -> {\n    StorageService.instance.cancelInProgressSequences(id);\n});\n```\n\n## Query Execution\n\n### Basic Queries\n\n```java\n// Execute without results\ncluster.coordinator(1).execute(\n    \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n    ConsistencyLevel.QUORUM,\n    1, \"Alice\"\n);\n\n// Execute with results\nObject[][] rows = cluster.coordinator(1).execute(\n    \"SELECT * FROM test.users WHERE id = ?\",\n    ConsistencyLevel.QUORUM,\n    1\n);\n```\n\n### Using Query Results\n\n```java\nimport org.apache.cassandra.distributed.api.SimpleQueryResult;\n\nSimpleQueryResult result = cluster.coordinator(1).executeWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nwhile (result.hasNext()) {\n    Row row = result.next();\n    int id = row.getInteger(\"id\");\n    String name = row.getString(\"name\");\n    System.out.println(\"User: \" + id + \", \" + name);\n}\n```\n\n### Pagination\n\n```java\nSimpleQueryResult result = cluster.coordinator(1).executeWithPagingWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM,\n    100  // page size\n);\n```\n\n### Async Execution\n\n```java\nFuture<SimpleQueryResult> future = cluster.coordinator(1).asyncExecuteWithResult(\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\nSimpleQueryResult result = future.get();\n```\n\n### Query with Tracing\n\n```java\nimport java.util.UUID;\n\nUUID sessionId = UUID.randomUUID();\nSimpleQueryResult result = cluster.coordinator(1).executeWithTracingWithResult(\n    sessionId,\n    \"SELECT * FROM test.users\",\n    ConsistencyLevel.QUORUM\n);\n\n// Query tracing info from system_traces\ncluster.coordinator(1).execute(\n    \"SELECT * FROM system_traces.sessions WHERE session_id = ?\",\n    ConsistencyLevel.ONE,\n    sessionId\n);\n```\n\n### Internal Queries (No Coordinator)\n\n```java\n// Execute directly on instance internals (bypasses coordinator)\nSimpleQueryResult result = instance.executeInternalWithResult(\n    \"SELECT * FROM system.peers WHERE peer=?\",\n    expectedPeer.config().broadcastAddress().getAddress()\n);\n```\n\n## Message Filtering for Failure Injection\n\n### Pattern 1: Drop Messages Between Nodes\n\n```java\n// Drop all mutation requests from node 1 to node 2\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop()\n    .on();\n\n// Verify timeout behavior\nassertThatThrownBy(() ->\n    cluster.coordinator(1).execute(\n        \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n        ConsistencyLevel.ALL, 1, \"Alice\"\n    )\n).isInstanceOf(WriteTimeoutException.class);\n\n// Reset filters\ncluster.filters().reset();\n```\n\n### Pattern 2: Drop All Verbs\n\n```java\ncluster.filters()\n    .allVerbs()\n    .from(1).to(2)\n    .drop()\n    .on();\n```\n\n### Pattern 3: Drop Outbound Messages\n\n```java\ncluster.filters()\n    .outbound()\n    .from(1)\n    .verbs(Verb.READ_REQ.id)\n    .drop()\n    .on();\n```\n\n### Pattern 4: Custom Message Matching\n\n```java\ncluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .messagesMatching((from, to, message) -> {\n        // Custom logic to match specific messages\n        return message.verb() == Verb.MUTATION_REQ.id;\n    })\n    .drop()\n    .on();\n```\n\n### Pattern 5: Temporary Filter Control\n\n```java\nIMessageFilters.Filter filter = cluster.filters()\n    .inbound()\n    .from(1).to(2)\n    .verbs(Verb.MUTATION_REQ.id)\n    .drop();\n\nfilter.on();  // Enable\n// ... perform operations ...\nfilter.off(); // Disable\n```\n\n## ClusterUtils Reference\n\nFor comprehensive utilities, see [references/cluster_utils.md](references/cluster_utils.md).\n\n### Most Commonly Used Methods\n\n#### Lifecycle Management\n```java\nClusterUtils.stopUnchecked(instance);\nClusterUtils.stopAbrupt(cluster, instance);\nClusterUtils.restartUnchecked(instance);\nClusterUtils.stopAll(cluster);\n```\n\n#### Instance Management\n```java\nClusterUtils.addInstance(cluster, config -> {...});\nClusterUtils.replaceHostAndStart(cluster, toReplace);\nClusterUtils.start(instance, properties -> {...});\n```\n\n#### Ring & Gossip\n```java\nClusterUtils.awaitRingJoin(cluster.get(1), newInstance);\nClusterUtils.awaitRingHealthy(cluster.get(1));\nClusterUtils.awaitGossipStatus(instance, target, \"NORMAL\");\nClusterUtils.assertInRing(instance, expectedInRing);\n```\n\n#### CMS & Metadata\n```java\nClusterUtils.waitForCMSToQuiesce(cluster);\nEpoch epoch = ClusterUtils.getCurrentEpoch(instance);\nClusterUtils.fetchLogFromCMS(instance, awaitedEpoch);\n```\n\n#### Directories & Files\n```java\nList<File> dirs = ClusterUtils.getDataDirectories(instance);\nFile commitlog = ClusterUtils.getCommitLogDirectory(instance);\nFile hints = ClusterUtils.getHintsDirectory(instance);\n```\n\n## Schema Management\n\n### Creating Keyspaces\n\n```java\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n// Multi-DC keyspace\ncluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                    \"{'class': 'NetworkTopologyStrategy', \" +\n                    \"'dc1': 2, 'dc2': 2}\");\n```\n\n### Creating Tables\n\n```java\ncluster.schemaChange(\"CREATE TABLE test.users (\" +\n                    \"id int PRIMARY KEY, \" +\n                    \"name text, \" +\n                    \"email text)\");\n\n// With clustering\ncluster.schemaChange(\"CREATE TABLE test.events (\" +\n                    \"user_id int, \" +\n                    \"event_time timestamp, \" +\n                    \"event_type text, \" +\n                    \"PRIMARY KEY (user_id, event_time)) \" +\n                    \"WITH CLUSTERING ORDER BY (event_time DESC)\");\n```\n\n### Waiting for Schema Agreement\n\n```java\n// Manual wait\ntry (Cluster.SchemaChangeMonitor monitor = cluster.new SchemaChangeMonitor()) {\n    monitor.startPolling();\n    cluster.schemaChange(\"CREATE TABLE ...\");\n    monitor.waitForCompletion();\n}\n\n// Using ClusterUtils\nClusterUtils.awaitGossipSchemaMatch(cluster);\n```\n\n## Monitoring & Observables\n\n### Log Watching\n\n```java\n// Mark position and wait for log message\nlong mark = instance.logs().mark();\n// ... perform operation ...\ninstance.logs().watchFor(mark, \"Bootstrap completed\");\n\n// Grep logs\nList<String> errors = instance.logs().grep(\"ERROR\").getResult();\n```\n\n### Nodetool Integration\n\n```java\nimport org.apache.cassandra.distributed.api.NodeToolResult;\n\nNodeToolResult result = instance.nodetoolResult(\"status\");\nresult.asserts().success();\nString output = result.getStdout();\n\n// Common nodetool commands\ninstance.nodetool(\"flush\");\ninstance.nodetool(\"repair\");\ninstance.nodetool(\"compact\");\ninstance.nodetool(\"decommission\");\n```\n\n### Ring Information\n\n```java\nimport org.apache.cassandra.distributed.shared.ClusterUtils.RingInstanceDetails;\n\nList<RingInstanceDetails> ring = ClusterUtils.ring(instance);\nfor (RingInstanceDetails details : ring) {\n    System.out.println(\"Address: \" + details.getAddress());\n    System.out.println(\"Status: \" + details.getStatus());   // Up/Down\n    System.out.println(\"State: \" + details.getState());     // Normal/Leaving/Joining\n    System.out.println(\"Token: \" + details.getToken());\n}\n```\n\n### Gossip Information\n\n```java\nMap<String, Map<String, String>> gossip = ClusterUtils.gossipInfo(instance);\nfor (Map.Entry<String, Map<String, String>> entry : gossip.entrySet()) {\n    String address = entry.getKey();\n    Map<String, String> state = entry.getValue();\n    System.out.println(address + \" -> \" + state.get(\"STATUS\"));\n}\n```\n\n## Classloader Issues & Debugging\n\n### Understanding Classloader Isolation\n\nThe in-JVM dtest framework uses multiple classloaders for isolation:\n- **Test ClassLoader**: Where your test code runs\n- **Shared ClassLoader**: Primitives, APIs, config objects\n- **Instance ClassLoaders**: Per-instance Cassandra code (isolated)\n\n### Common Classloader Issues\n\n#### Issue 1: Same Class, Different ClassLoaders\n\n**Symptom**: `ClassCastException` even though classes appear identical\n\n```java\n// WRONG - This will fail\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in test classloader\n    // Try to use token with instance internals -> ClassCastException\n});\n\n// CORRECT - Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0); // Loaded in instance classloader\n    // Now token is in correct classloader\n});\n```\n\n#### Issue 2: Serialization Failures\n\n**Symptom**: `NotSerializableException` or `ClassNotFoundException`\n\n```java\n// WRONG - Non-serializable lambda capture\nString localVar = \"test\";\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar); // May fail if localVar isn't Serializable\n});\n\n// CORRECT - Only pass serializable primitives\nfinal String localVar = \"test\"; // String is Serializable\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(localVar);\n});\n```\n\n**Lambdas are serialized** and transferred across classloaders. Only capture:\n- Primitives (int, long, String, etc.)\n- Serializable objects marked with `@Shared`\n- Nothing else from test classloader\n\n#### Issue 3: Static State Not Shared\n\n**Symptom**: Static fields don't reflect changes across instances\n\n```java\n// Each instance has its own DatabaseDescriptor, StorageService, etc.\n// Static state is NOT shared between instances\n\n// To coordinate across instances, use:\n// 1. CQL queries to share data\n// 2. Message passing\n// 3. Instance-specific operations\n```\n\n### Debugging Techniques\n\n#### Technique 1: Print Classloader Information\n\n```java\ncluster.get(1).runOnInstance(() -> {\n    System.out.println(\"ClassLoader: \" +\n        Thread.currentThread().getContextClassLoader());\n    System.out.println(\"Token class loader: \" +\n        Token.class.getClassLoader());\n});\n```\n\n#### Technique 2: Transfer Objects Explicitly\n\n```java\nimport org.apache.cassandra.distributed.impl.IsolatedExecutor;\n\n// Transfer object to instance classloader\nSerializable transferred = instance.transfer(mySerializableObject);\n```\n\n#### Technique 3: Use @Shared and @Isolated Annotations\n\n```java\n// In your test code\nimport org.apache.cassandra.utils.Shared;\nimport org.apache.cassandra.utils.Isolated;\n\n@Shared  // Loaded in shared classloader\npublic class MySharedClass implements Serializable {\n    // Can be shared across boundaries\n}\n\n@Isolated  // Each instance gets own copy\npublic class MyIsolatedClass {\n    // Not shared\n}\n```\n\n#### Technique 4: Check Serialization\n\n```java\n// Verify object can be serialized\ntry {\n    ByteArrayOutputStream baos = new ByteArrayOutputStream();\n    ObjectOutputStream oos = new ObjectOutputStream(baos);\n    oos.writeObject(myObject);\n    oos.close();\n    System.out.println(\"Object is serializable\");\n} catch (NotSerializableException e) {\n    System.out.println(\"Object is NOT serializable: \" + e.getMessage());\n}\n```\n\n### Best Practices for Classloader Safety\n\n1. **Keep lambdas simple**: Minimize captured variables\n2. **Use primitives**: Pass int, String, long instead of complex objects\n3. **Create objects inside runOnInstance**: Don't create in test, pass to instance\n4. **Avoid static state**: Don't rely on static fields across instances\n5. **Use coordinator for data sharing**: Query data rather than passing objects\n\n## Advanced Patterns\n\n### Pattern: Pausing & Resuming CMS Operations\n\n```java\n// Pause before committing at specific epoch\nCallable<Epoch> pauseHandle = ClusterUtils.pauseBeforeCommit(\n    cmsInstance,\n    transformation -> transformation instanceof AddNode\n);\n\n// Wait for pause\nEpoch epoch = pauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseCommits(cmsInstance);\n```\n\n### Pattern: Pausing Enactment\n\n```java\n// Pause before enacting specific epoch\nCallable<Void> pauseHandle = ClusterUtils.pauseBeforeEnacting(instance, epoch);\n\n// Wait for pause\npauseHandle.call();\n\n// Do something while paused\n// ...\n\n// Resume\nClusterUtils.unpauseEnactment(instance);\n```\n\n### Pattern: Testing with Log Monitoring\n\n```java\nClusterUtils.runAndWaitForLogs(\n    () -> {\n        cluster.coordinator(1).execute(\"INSERT INTO test.users VALUES (1, 'Alice')\",\n                                      ConsistencyLevel.QUORUM);\n    },\n    \"Mutation applied\",\n    cluster.get(1), cluster.get(2), cluster.get(3)\n);\n```\n\n### Pattern: Custom Instance Initialization\n\n```java\nCluster cluster = Cluster.build()\n    .withNodes(3)\n    .withInstanceInitializer((cl, i) -> {\n        // Custom initialization logic\n        System.out.println(\"Initializing instance \" + i);\n    })\n    .start();\n```\n\n### Pattern: Testing Node Replacement\n\n```java\n// Original node\nIInvokableInstance original = cluster.get(2);\n\n// Stop original\nClusterUtils.stopAbrupt(cluster, original);\n\n// Replace with new node\nIInvokableInstance replacement = ClusterUtils.replaceHostAndStart(\n    cluster,\n    original,\n    (inst, properties) -> {\n        properties.set(RING_DELAY, \"5000\");\n    }\n);\n\n// Verify replacement joined\nClusterUtils.awaitRingJoin(cluster.get(1), replacement);\n```\n\n### Pattern: Testing Decommission\n\n```java\nIInvokableInstance leaving = cluster.get(3);\n\nboolean success = ClusterUtils.decommission(leaving);\nAssert.assertTrue(\"Decommission failed\", success);\n\n// Verify node left\nClusterUtils.assertNotInRing(cluster.get(1), leaving);\n```\n\n### Pattern: Multi-DC Token Ranges\n\n```java\nList<ClusterUtils.Range> ranges = ClusterUtils.getPrimaryRanges(\n    cluster.get(1),\n    \"test\"  // keyspace\n);\n\nfor (ClusterUtils.Range range : ranges) {\n    System.out.println(\"Range: \" + range.left() + \" to \" + range.right());\n}\n```\n\n## Complete Test Examples\n\n### Example 1: Basic Read/Write Test\n\n```java\npublic class BasicReadWriteTest extends TestBaseImpl {\n    @Test\n    public void testReadWrite() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.users (id int PRIMARY KEY, name text)\");\n\n            // Write\n            cluster.coordinator(1).execute(\n                \"INSERT INTO test.users (id, name) VALUES (?, ?)\",\n                ConsistencyLevel.QUORUM, 1, \"Alice\");\n\n            // Read\n            Object[][] rows = cluster.coordinator(2).execute(\n                \"SELECT * FROM test.users WHERE id = ?\",\n                ConsistencyLevel.QUORUM, 1);\n\n            Assert.assertEquals(1, rows.length);\n            Assert.assertEquals(1, rows[0][0]);\n            Assert.assertEquals(\"Alice\", rows[0][1]);\n        }\n    }\n}\n```\n\n### Example 2: Testing Write Timeout with Message Filtering\n\n```java\npublic class WriteTimeoutTest extends TestBaseImpl {\n    @Test\n    public void testWriteTimeout() throws IOException {\n        try (Cluster cluster = Cluster.build(3).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 3}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY, v int)\");\n\n            // Drop mutations to node 2 and 3\n            cluster.filters().inbound()\n                .to(2, 3)\n                .verbs(Verb.MUTATION_REQ.id)\n                .drop()\n                .on();\n\n            // This should timeout (can't reach QUORUM)\n            try {\n                cluster.coordinator(1).execute(\n                    \"INSERT INTO test.data (k, v) VALUES (?, ?)\",\n                    ConsistencyLevel.QUORUM, 1, 100);\n                Assert.fail(\"Expected WriteTimeoutException\");\n            } catch (RuntimeException e) {\n                Assert.assertTrue(e.getCause() instanceof WriteTimeoutException);\n            }\n\n            cluster.filters().reset();\n        }\n    }\n}\n```\n\n### Example 3: Testing Node Addition\n\n```java\npublic class NodeAdditionTest extends TestBaseImpl {\n    @Test\n    public void testAddNode() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 2}\");\n\n            // Add and start new node\n            IInvokableInstance newNode = ClusterUtils.addInstance(cluster, config -> {\n                config.set(\"auto_bootstrap\", true);\n            });\n            newNode.startup();\n\n            // Wait for node to join\n            ClusterUtils.awaitRingJoin(cluster.get(1), newNode);\n\n            // Verify all nodes see the new node\n            ClusterUtils.assertInRing(cluster.get(1), newNode);\n            ClusterUtils.assertInRing(cluster.get(2), newNode);\n        }\n    }\n}\n```\n\n### Example 4: Running Code on Instance\n\n```java\npublic class InstanceCodeTest extends TestBaseImpl {\n    @Test\n    public void testRunOnInstance() throws IOException {\n        try (Cluster cluster = Cluster.build(2).start()) {\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'SimpleStrategy', 'replication_factor': 1}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Insert data\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.ONE);\n\n            // Force flush on node 1\n            cluster.get(1).runOnInstance(() -> {\n                StorageService.instance.forceKeyspaceFlush(\"test\");\n            });\n\n            // Verify flush happened by checking for sstables\n            int sstableCount = cluster.get(1).callOnInstance(() -> {\n                ColumnFamilyStore cfs = Keyspace.open(\"test\")\n                                               .getColumnFamilyStore(\"data\");\n                return cfs.getLiveSSTables().size();\n            });\n\n            Assert.assertTrue(\"Expected at least one sstable\", sstableCount > 0);\n        }\n    }\n}\n```\n\n### Example 5: Multi-DC Test\n\n```java\npublic class MultiDCTest extends TestBaseImpl {\n    @Test\n    public void testMultiDC() throws IOException {\n        try (Cluster cluster = builder()\n                                  .withRacks(2, 1, 2)  // 2 DCs, 1 rack each, 2 nodes per rack\n                                  .start()) {\n\n            cluster.schemaChange(\"CREATE KEYSPACE test WITH replication = \" +\n                                \"{'class': 'NetworkTopologyStrategy', \" +\n                                \"'datacenter1': 2, 'datacenter2': 2}\");\n            cluster.schemaChange(\"CREATE TABLE test.data (k int PRIMARY KEY)\");\n\n            // Write from DC1\n            cluster.coordinator(1).execute(\"INSERT INTO test.data (k) VALUES (1)\",\n                                          ConsistencyLevel.LOCAL_QUORUM);\n\n            // Read from DC2\n            Object[][] rows = cluster.coordinator(3).execute(\n                \"SELECT * FROM test.data WHERE k = 1\",\n                ConsistencyLevel.LOCAL_QUORUM);\n\n            Assert.assertEquals(1, rows.length);\n        }\n    }\n}\n```\n\n## Troubleshooting Guide\n\n### Problem: Tests are flaky or hang\n\n**Possible causes:**\n1. Schema not fully agreed before operations\n2. Insufficient timeout for async operations\n3. Message filters not properly reset\n\n**Solutions:**\n```java\n// Wait for schema agreement\nClusterUtils.awaitGossipSchemaMatch(cluster);\n\n// Use longer timeouts for operations\nfuture.get(30, TimeUnit.SECONDS);\n\n// Always reset filters in finally block\ntry {\n    cluster.filters().inbound().drop().on();\n    // test code\n} finally {\n    cluster.filters().reset();\n}\n```\n\n### Problem: ClassCastException with tokens or types\n\n**Cause:** Object created in wrong classloader\n\n**Solution:**\n```java\n// Create objects inside runOnInstance\ncluster.get(1).runOnInstance(() -> {\n    Token token = new Murmur3Partitioner.LongToken(0);\n    // Use token here\n});\n```\n\n### Problem: NoClassDefFoundError or ClassNotFoundException\n\n**Cause:** Class not available in instance classloader\n\n**Solution:** Ensure class is in Cassandra dependencies or marked `@Shared`\n\n### Problem: Test times out waiting for ring/gossip\n\n**Cause:** Network features not enabled\n\n**Solution:**\n```java\nCluster cluster = builder()\n    .withConfig(c -> c.with(GOSSIP, NETWORK))\n    .start();\n```\n\n### Problem: Port conflicts\n\n**Cause:** Static port allocation\n\n**Solution:**\n```java\nCluster cluster = Cluster.build(3)\n    .withDynamicPortAllocation(true)\n    .start();\n```\n\n## Additional Resources\n\n- **ClusterUtils**: See [references/cluster_utils.md](references/cluster_utils.md) for exhaustive utility method documentation\n- **Advanced Patterns**: See [references/advanced_patterns.md](references/advanced_patterns.md) for CMS operations, Accord testing, and complex scenarios\n- **Classloader Deep Dive**: See [references/classloader_guide.md](references/classloader_guide.md) for detailed classloader mechanics and debugging\n\n<!-- File: .claude/skills/deep-review/references/deep/deep-absence-completeness.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-absence-completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-absence-completeness.md)\n\n<!-- File: .claude/skills/deep-review/references/deep/deep-boundary.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-boundary.md)\n\n<!-- File: .claude/skills/deep-review/references/deep/deep-concurrency.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-concurrency.md)\n\n<!-- File: .claude/skills/deep-review/references/deep/deep-cross-cutting.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-cross-cutting.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-cross-cutting.md)\n\n<!-- File: .claude/skills/deep-review/references/deep/deep-logic.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-logic.md)\n\n<!-- File: .claude/skills/deep-review/references/deep/deep-resources.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Deep Skill\n\nPath: `.claude/skills/deep-review/references/deep/deep-resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/deep-review/references/deep/deep-resources.md)\n\n<!-- File: .claude/skills/deep-review/SKILL.md (Tokens: ~2407 | Category: anthropic-skill) -->\n---\nname: deep-review\nversion: \"1.0.0\"\ndescription: >\n  Deep file-focused code review for correctness bugs. Unlike shallow-review which runs 6\n  specialists in parallel across the entire patch, deep-review focuses on user-specified\n  files with full pattern catalogs (500+ patterns), codebase investigation, and source-level\n  context gathering. Use when: the user specifies particular files for focused review, a\n  shallow review flagged areas that need deeper investigation, reviewing critical-path code\n  changes, examining complex serialization/lifecycle/state-machine changes. The user\n  instructs which files to focus on (typically a subset of files in the patch).\n---\n\n# Deep Code Review\n\nFocused, thorough review of user-specified files using the full 500+ pattern catalog.\nEach file is reviewed with context gathering (reading source, not just diff), codebase\nsearches, and cross-referencing against the complete pattern database.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n                    +--------v---------+\n                    | User selects     |\n                    | focus files      |\n                    +--------+---------+\n                             |\n              +--------------+--------------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 0: Context  |       | Phase 0: Context      |\n    | (read full files, |       | (read full files,     |\n    |  callers, types)  |       |  callers, types)      |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 1: Deep     |       | Phase 1: Deep         |\n    | specialist review |       | specialist review     |\n    | (full checklists) |       | (full checklists)     |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n    +---------v---------+       +-----------v-----------+\n    | Phase 2: Codebase |       | Phase 2: Codebase     |\n    | investigation     |       | investigation         |\n    +---------+---------+       +-----------+-----------+\n              |                             |\n              +--------------+--------------+\n                             |\n                    +--------v---------+\n                    | Phase 3: Cross-  |\n                    | file symmetry &  |\n                    | merge findings   |\n                    +------------------+\n```\n\n## Quick Start\n\n1. **Receive patch** and user's file focus list\n2. **For each focus file**: run Phase 0 (context), Phase 1 (deep checklists), Phase 2 (search)\n3. **Cross-file symmetry** pass across all focus files\n4. **Merge & report** with confidence ranking\n\n---\n\n## Phase 0: Context Gathering (per focus file)\n\nBefore touching any checklist, deeply understand each focus file. This is the key difference\nfrom shallow review — you read the actual source, not just the diff.\n\n**Prompt template**:\n```\nRead the full source of the focus file: `{FILE_PATH}`\nRead the patch for context: `{PATCH_PATH}`\n\nFor this file, gather:\n1. CLASS HIERARCHY: What does it extend? What interfaces? Read the parent class/interface.\n2. SIBLING CLASSES: Are there parallel implementations? Read at least one sibling.\n3. CALLERS: Who calls the modified methods? How do they use return values? (grep + read)\n4. LIFECYCLE: When is this object created, used, destroyed?\n5. STATE MACHINE (if applicable): Map every state and every transition. What events are handled\n   in each state? What events are *not* handled (missing transitions)? What states are never\n   reached? Where is this state enum pattern-matched — are all states covered at every match site?\n6. INVARIANTS: Read Javadoc, assertions, and any test files for this class.\n7. SERIALIZATION: If it serializes — read serialize, deserialize, serializedSize together.\n\nOutput a structured context summary for use by the deep review phases.\n```\n\n---\n\n## Phase 1: Deep Specialist Review (per focus file)\n\nEach focus file is reviewed against the FULL domain checklists (not the trimmed shallow\nversions). The reviewer selects which domains apply based on Phase 0 context.\n\n### Domain Selection\n\nBased on Phase 0 context, load the relevant deep checklists:\n\n| File contains | Load checklist |\n|---|---|\n| Conditions, comparisons, control flow, types | `references/deep/deep-logic.md` |\n| Arithmetic, indices, ranges, ByteBuffer, I/O | `references/deep/deep-boundary.md` |\n| Shared state, locks, lifecycle, state machines | `references/deep/deep-concurrency.md` |\n| Serialization, resources, metrics, config | `references/deep/deep-resources.md` |\n| New classes, new fields, registrations | `references/deep/deep-absence-completeness.md` |\n| Refactoring, merges, shell scripts, parsing | `references/deep/deep-cross-cutting.md` |\n\nTypically 2-4 domains are relevant per file. Load all relevant ones.\n\n**Prompt template**:\n```\nYou are performing a DEEP REVIEW of: `{FILE_PATH}`\n\nCONTEXT (from Phase 0):\n{CONTEXT_SUMMARY}\n\nPATCH (the changes being reviewed):\nRead: `{PATCH_PATH}`\n\nCHECKLISTS (load each relevant one):\nRead: `{SKILL_DIR}/references/deep/deep-logic.md`\nRead: `{SKILL_DIR}/references/deep/deep-boundary.md`\n[... load relevant domains ...]\n\nFor EVERY checklist item that could apply to this file:\n1. Check whether the pattern exists in the code\n2. If the pattern matches: search the codebase for confirming/refuting evidence\n3. Rate confidence: High (confirmed by evidence), Medium (pattern matches but\n   uncertain), Low (possible but speculative)\n\nReport ALL findings. For each:\n- Pattern ID and name\n- Location (file:line)\n- Confidence (High/Medium/Low)\n- What's wrong (2-3 sentences with reasoning)\n- Evidence gathered (what you searched for, what you found/didn't find)\n- Suggested fix\n\nOr \"No finding in this domain for this file\" if nothing applies.\n```\n\n---\n\n## Phase 2: Codebase Investigation (per focus file)\n\nFor each finding from Phase 1, and for absence/completeness patterns, execute targeted\ncodebase searches.\n\n**Search patterns to execute:**\n\n### For new fields:\n```bash\ngrep -rn \"serialize\\|deserialize\\|serializedSize\\|equals\\|hashCode\\|toString\" {FILE_DIR}/\n```\n\n### For new registrations:\n```bash\ngrep -rn \"addListener\\|register\\|subscribe\\|addMetric\\|removeSensor\\|deregister\" {FILE_DIR}/\n```\n\n### For new enum constants:\n```bash\ngrep -rn \"switch.*{ENUM_TYPE}\\|case.*{CONSTANT}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For interface implementations:\n```bash\ngrep -rn \"implements {INTERFACE}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For method callers:\n```bash\ngrep -rn \"{METHOD_NAME}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n### For parallel paths:\n```bash\ngrep -rn \"class.*extends.*{PARENT_CLASS}\" --include=\"*.java\" {PROJECT_ROOT}/\n```\n\n**Prompt template**:\n```\nYou are investigating findings from the deep review of: `{FILE_PATH}`\n\nFINDINGS TO INVESTIGATE:\n{PHASE_1_FINDINGS}\n\nFor each finding:\n1. Execute the relevant codebase searches (grep, read files)\n2. Confirm or refute the finding based on evidence\n3. If confirmed: search for additional instances of the same pattern\n4. If refuted: explain why with evidence\n\nFor absence patterns:\n1. Build the search list from the diff events\n2. Execute each search\n3. If no match found: report as confirmed finding\n4. If match found: report as refuted (the symmetric code exists)\n\nReport updated findings with evidence.\n```\n\n---\n\n## Phase 3: Cross-File Symmetry & Merge\n\nAfter all focus files are reviewed:\n\n**Prompt template**:\n```\nReview findings across all focus files for cross-file patterns:\n\n1. CROSS-FILE SYMMETRY: For each change in file A, is there a structurally parallel\n   change needed in file B? Check:\n   - Serialization families (if serialize changed, did deserialize change?)\n   - Interface implementations (if one implementation changed, do siblings need it?)\n   - Version-gated paths (if one version branch changed, do others?)\n   - Test coverage (does the test file cover the changed behavior?)\n\n2. FINDING REINFORCEMENT: Do findings across files reinforce each other?\n   - Logic + Absence at same conceptual location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Pattern flagged in multiple files → likely systematic issue\n\n3. MERGE & DEDUP: Combine all findings, deduplicate, rank.\n\n4. THREE-POINT TEST each finding:\n   - The code construct actually exists (not inferred)\n   - The bug is possible given visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n```\n\n---\n\n## Report Format\n\n```\n## Deep Review: [target]\n\n### Focus Files\n- `path/to/File1.java` — [brief description of changes]\n- `path/to/File2.java` — [brief description of changes]\n\n### Context Summary\n[Key facts from Phase 0: class hierarchy, lifecycle, shared state, invariants]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Domain**: [Logic / Boundary / Concurrency / Resources / Absence / Completeness]\n- **Pattern**: [pattern name from checklist]\n- **What's wrong**: [2-3 sentences with reasoning]\n- **Evidence**: [what was searched, what was found]\n- **Suggested fix**: [specific change]\n\n#### Finding 2: ...\n\n### Domain Coverage (per file)\n| File | Logic | Boundary | Concurrency | Resources | Absence | Completeness |\n|---|---|---|---|---|---|---|\n| File1.java | 2 findings | - | 1 finding | - | checked | checked |\n| File2.java | - | 1 finding | - | 3 findings | checked | checked |\n\n### Cross-File Symmetry\n- [Any asymmetries found]\n- [Any reinforcing patterns]\n```\n\n---\n\n## Reference Files\n\n### Deep specialist checklists\n- `references/deep/deep-logic.md` — Full logic, types, constants, filtering patterns\n- `references/deep/deep-boundary.md` — Full boundary, overflow, null, I/O patterns\n- `references/deep/deep-concurrency.md` — Full concurrency, state, lifecycle patterns\n- `references/deep/deep-resources.md` — Full serialization, resource, crash-safety patterns\n- `references/deep/deep-absence-completeness.md` — Full absence + completeness with search methodology\n- `references/deep/deep-cross-cutting.md` — Refactoring, parsing, platform, dispatch patterns\n\n<!-- File: .claude/skills/heatmap/SKILL.md (Tokens: ~1312 | Category: anthropic-skill) -->\n---\nname: heatmap\nversion: \"1.0.0\"\ndescription: Use git heatmap analysis to identify high-churn files and lines as candidates for thorough review or bug hunting. Works for PR reviews, security audits, bug hunts, or any code analysis task.\n---\n\n# Heatmap-Guided Review\n\nUse the bundled `heatmap.py` script to identify the hottest (most frequently and recently changed) code in a repository, then focus review effort on those areas. Hot code is statistically more likely to contain bugs: it changes often, accumulates complexity, and is where active development risk concentrates.\n\n## When to use\n\nInvoke this skill whenever you want to prioritize where to look in a codebase — during PR reviews, bug hunts, security audits, onboarding exploration, or any task where you need to decide which files and lines deserve the closest attention.\n\n## Prerequisites\n\n- Python 3 must be available.\n- The target must be a git repository.\n- The heatmap script is bundled with this skill at `~/.claude/skills/heatmap/heatmap.py`. All commands below use `HEATMAP` as a placeholder:\n  ```bash\n  HEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n  ```\n  If `heatmap` is available on PATH, you may use that instead.\n\n## Workflow\n\n### Step 1: Determine the repository path and scope\n\nFigure out the git repository root. If the user provided a repo path, use that. If working in a repo already, use the current directory. If reviewing a PR, determine which files were changed.\n\n```bash\nHEATMAP=\"$HOME/.claude/skills/heatmap/heatmap.py\"\n# Find the repo root\ngit -C <path> rev-parse --show-toplevel\n```\n\n### Step 2: Run repo-level heatmap\n\nGet the hottest files in the repository. Use `--json` for machine-readable output. Adjust `--top` based on context (20-50 for a broad scan, more for large repos).\n\n```bash\npython3 \"$HEATMAP\" repo --json --top 50 <repo_path>\n```\n\nThis returns JSON array of objects with: `path`, `heat`, `commits`, `last_modified_days`.\n\n### Step 3: Cross-reference with the task context\n\n**For PR reviews:** Intersect the heatmap results with the files changed in the PR. Files that are both changed in the PR AND high on the heatmap are the highest-priority review targets — they are already complex/volatile and the PR is adding more changes to them.\n\n```bash\n# Get PR changed files\ngit diff --name-only <base_branch>...HEAD\n```\n\n**For bug hunts:** The hottest files ARE the candidates — frequent recent changes correlate with bugs. Focus on the top 10-20.\n\n**For security audits:** Filter heatmap results to security-sensitive paths (auth, crypto, input parsing, network, serialization).\n\n**For general exploration:** Use the heatmap as a map of where active development is happening.\n\n### Step 4: Run line-level heatmap on top candidates\n\nFor each high-priority file (typically 3-8 files), run the line-level heatmap to find the hottest regions within those files.\n\n```bash\npython3 \"$HEATMAP\" file --json <file_path_relative_to_repo> <repo_path>\n```\n\nThis returns JSON array of objects with: `line`, `heat`, `content`.\n\n### Step 5: Identify hot zones\n\nFrom the line-level results, identify contiguous regions of high heat. These \"hot zones\" are where to focus review. Look for:\n\n- **Clusters of hot lines** — contiguous blocks of high-heat code indicate areas under active rework. These are prime bug candidates because:\n  - Multiple recent changes suggest the logic is not yet settled\n  - Each change is an opportunity for regression\n  - Complex interactions between recent changes may not be fully tested\n\n- **Hot lines surrounded by cold code** — surgical edits in otherwise stable code may indicate bug fixes, workarounds, or special-case handling that deserves scrutiny.\n\n- **Hot function/method boundaries** — if a method signature or its first few lines are hot, the contract may have changed recently, affecting all callers.\n\n### Step 6: Produce the review focus list\n\nOutput a ranked list of review targets, structured as:\n\n```\n## Heatmap Review Targets\n\n### Priority 1: <file_path> (heat: X, commits: Y)\n- **Hot zones**: lines A-B (description of what this code does)\n- **Why it matters**: <context — e.g., \"most changed file in repo AND modified in this PR\">\n- **What to look for**: <specific guidance based on the code — race conditions, edge cases, etc.>\n\n### Priority 2: ...\n```\n\n### Step 7: Deep review\n\nFor each priority target, read the hot zones and perform the actual review. The heatmap tells you WHERE to look; your expertise tells you WHAT to look for. Common patterns in hot code:\n\n- **State management bugs**: Hot code often manages complex state. Check for inconsistent updates, missing synchronization, or partial failures.\n- **Edge cases**: Frequent changes often mean edge cases keep being discovered. Look for more.\n- **Regression risk**: If code was recently fixed, check whether the fix is complete and doesn't break other paths.\n- **Missing tests**: Hot code that lacks test coverage is the highest-risk combination.\n\n## Output format\n\nAlways present findings as a prioritized list with:\n1. File path and heat metrics\n2. Specific line ranges to focus on\n3. What the hot code does (brief)\n4. What risks to look for (specific to the code, not generic)\n\n## Tips\n\n- Heat is relative — compare files against each other, not against an absolute threshold.\n- Files with high heat but few commits have large individual changes (risky). Files with high heat and many commits are under constant churn (also risky, differently).\n- `last_modified_days` close to 0 means very recent changes — highest chance of unfound bugs.\n- Use `--since` to adjust the time window. Default is 2 years. For recent bug hunts, try `--since \"6 months ago\"`.\n- The `--no-color` flag is useful when piping output, but prefer `--json` for programmatic use.\n\n<!-- File: .claude/skills/mega-review/SKILL.md (Tokens: ~4824 | Category: anthropic-skill) -->\n---\nname: mega-review\nversion: \"1.0.0\"\ndescription: >\n  Multi-pass deep code review for large patches (1000+ LOC) that maximizes real bug detection.\n  Orchestrates targeted-review, shallow-review, and deep-review in parallel across all HIGH and\n  MEDIUM risk files and commits: understands the feature holistically, splits by file and commit,\n  runs deep review on every HIGH/MEDIUM file, targeted review across the same scope, and\n  per-commit shallow review, followed by cross-cut consistency checks. Use when: reviewing a\n  large patch (feature branch, multi-commit, or single large diff, 1000+ LOC), doing a thorough\n  pre-merge review, or when shallower reviews miss bugs due to patch size. Triggers on: \"review\n  this branch\", \"review these commits\", \"review this feature\", \"mega review\", \"thorough review\",\n  \"full review of X commits\", or when the user specifies a commit range or feature for review.\n---\n\n# Mega-Review: Multi-Pass Large Patch Review\n\nThis skill orchestrates `/targeted-review`, `/shallow-review`, and `/deep-review` with\ncross-cut consistency checks to maximize bug detection on large patches (1000+ LOC). The input\ncan be a commit range, a feature branch, or any large diff — it does not have to span multiple\ncommits.\n\n**You MUST invoke `/targeted-review`, `/shallow-review`, and `/deep-review` as part of this\nworkflow.** Those skills have specialist checklists, pattern catalogs, and structured review\nprocesses that this skill does not duplicate. This skill's job is to understand the change\nholistically, decompose it into reviewable chunks, and delegate the actual code review to the\nappropriate sub-skills at the right granularity.\n\n## Why This Exists\n\nA single pass of `/shallow-review` over 7000 LOC spreads attention too thin. Real bugs hide in:\n- **Offset arithmetic** that works for the simple case but breaks when offset params are added\n- **Variable lifecycle issues** where a loop modifies a variable but the final operation needs the original\n- **Cross-cut inconsistencies** where fixes or refactors in one subsystem introduce bugs in another\n- **Algorithmic boundary conditions** in new data structure code\n\nThe key insight: some bugs are findable by mechanical checking (every System.arraycopy, every\nvariable swap), while others require deep understanding. This skill does BOTH.\n\n## Architecture\n\n```\n+---------------------+\n| PHASE 1: Decompose  |\n|   & Classify        |    Produce decomposition map + coverage checklist.\n+----------+----------+\n           |\n    +-------+--------+----------+\n    |                |           |\n+---v----+   +-------v------+  +-v-----------+\n|PHASE 2 |   |   PHASE 3    |  |   PHASE 4   |\n|Deep    |   |  Targeted    |  |  Shallow    |\n|Review  |   |  Review      |  |  Review     |\n|(HIGH + |   | (HIGH +      |  | (HIGH +     |\n| MEDIUM |   |  MEDIUM      |  |  MEDIUM     |\n| files) |   |  files)      |  |  commits)   |\n+---+----+   +-------+------+  +-+-----------+\n    |                |            |\n    +----------------+------------+\n                     |\n          +----------v----------+\n          | PHASE 5: Cross-Cut  |    Cross-commit/cross-subsystem consistency, pattern\n          | Passes              |    amplification, and fix verification checks.\n          +----------+----------+    One subagent per pass type (5A / 5B / 5C).\n                     |\n          +----------v----------+\n          | PHASE 6: Merge &    |    Deduplicate, verify plausibility, rank.\n          | Validate            |    Combine findings from ALL phases.\n          +---------------------+\n```\n\n---\n\n## Chunking Strategy\n\nThis skill's core principle: **the orchestrator holds global state; subagents hold only their\nslice.** A large patch reviewed by a single agent suffers attention dilution — its context fills\nwith earlier files, earlier findings, and earlier grep output, and it starts missing things. The\nfix is to reset context at every subagent boundary.\n\n### Orchestrator responsibilities\n- Holds the full patch, decomposition map, and accumulated findings from all phases\n- Before spawning each subagent, assembles a **briefing packet**: the chunk + a tight 100–200\n  word context summary written by the orchestrator\n- After each subagent returns, integrates findings into the global picture\n\n### What each subagent receives\n- **Its chunk**: the diff for its commit / grep hits for its audit type / file diff for its deep pass\n- **Orchestrator context**: subsystem name, risk level, what the code is trying to do (one paragraph)\n- **Focused task**: exactly what to look for and why — not a generic \"find bugs\"\n- **Relevant prior findings only**: findings from earlier phases that touch THIS chunk's files,\n  not the full findings list from all files\n\n### What each subagent does\nEach subagent **invokes a review skill** on its chunk — it is not a generic agent. The skill\ndetermines the review depth and structure. The chunk is the scope; the briefing packet is the\ncontext. Subagents may read additional source files, grep for callers, or check sibling classes\nto inform the review, but must not receive the full patch as input — that defeats the purpose.\n\n### Chunk boundaries by phase\n\n| Phase | Chunk unit | Skill to invoke | What the subagent receives |\n|---|---|---|---|\n| 2 (Deep) | One HIGH or MEDIUM file | `/deep-review` | That file's diff + full current source |\n| 3 (Targeted) | All HIGH + MEDIUM files as a group | `/targeted-review` | Diff for those files + Phase 1 risk classification |\n| 4 (Shallow) | One HIGH or MEDIUM commit | `/shallow-review` | That commit's diff only |\n| 5 (Cross-cut) | One pass type (5A / 5B / 5C) | inline only — no sub-skill | Finding list relevant to that pass + grep targets |\n\n**Phases 2, 3, and 4 run in parallel** — launch all their subagents in a single message after Phase 1 completes. Do not wait for Phase 2 before starting Phase 3 or 4.\n\n---\n\n## PHASE 1: Decompose & Classify\n\n**This phase is done inline — no sub-skill invocation.** Its job is to produce a decomposition\nmap and coverage checklist fast, then immediately hand off to the parallel Phases 2/3/4.\nEvery minute spent in Phase 1 is a minute not spent finding bugs.\n\n**Determining the input scope** — two modes depending on what the user provided:\n\n*Mode A — git boundary given* (commit range, branch, or single SHA): proceed directly to\nStep 1a.\n\n*Mode B — no git boundary* (user describes a feature, subsystem, or set of files without\nspecifying a range):\n1. Discover candidate files via grep or directory inspection:\n   ```bash\n   grep -rl \"<keyword>\" src/ | grep '\\.java$' | sort > /tmp/file_list.txt\n   # or: find src/java/org/apache/cassandra/<package> -name '*.java' | sort\n   ```\n2. **Show the list to the user and ask for confirmation** before going further — file count,\n   file names, anything obviously missing or out of scope. Do not skip this step.\n3. Produce a working diff against a sensible base (usually `main`):\n   ```bash\n   git diff main -- $(cat /tmp/file_list.txt | tr '\\n' ' ') > /tmp/mega_review.diff\n   # For files with no git history (new/untracked), read them directly — there is no diff.\n   ```\n4. Use this confirmed file list as the direct seed for the coverage checklist in Step 1e —\n   paste the files into the `File` column verbatim.\n5. In Phase 4, there are no commit boundaries: chunk by **file** instead of by commit —\n   one `/shallow-review` invocation per file. Skip Step 1a and go straight to Step 1b.\n\n**Step 1a — Get commit shape:**\n```bash\ngit log --oneline --stat <base>..<head>\n# Or for a single commit: git show --stat <SHA>\n```\n\n**Step 1b — Skim diff stats (do NOT read file bodies):**\n```bash\ngit diff <base>..<head> --stat\n# What to note: file names, extension types, rough LOC changes, new vs modified files\n```\n\n**Step 1c — Classify each commit/subsystem** by risk:\n- **HIGH**: New algorithms, data structure rewrites, complex feature additions, new orchestration layers, state machine changes, bootstrap/recovery logic\n- **MEDIUM**: Feature additions with new control flow, non-trivial interface changes with multiple callers\n- **LOW**: Renames, moves, mechanical refactors, test-only or documentation changes\n\n**Step 1d — Classify each source file** by type:\n- **Algorithmic**: Array operations, tree traversals, binary search, merges, set operations\n- **State machine**: Bootstrap, recovery, catchup, topology, lifecycle management\n- **Wiring**: Delegation, API changes, parameter threading\n- **Concurrency**: Shared state, synchronization\n- **Documentation/Config**: Markdown, YAML, config files, skill definitions\n\n**Step 1e — Write `/tmp/mega_coverage.md`** (the coverage checklist). Every changed non-test\nfile gets one row; pre-assign reviewers now based on risk:\n\n```markdown\n| File | LOC changed | Risk | Type | Assigned reviewers | Min required | Covered? |\n|------|-------------|------|------|--------------------|--------------|----------|\n| src/Foo.java | 320 | HIGH | Algorithmic | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| src/Bar.java | 45 | MEDIUM | Wiring | Phase 2 (deep), Phase 3 (targeted) | 2 | — |\n| docs/SKILL.md | 18 | LOW | Documentation | Phase 4 (sha: def456) | 1 | — |\n```\n\nAssignment rules:\n- **HIGH-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **MEDIUM-risk file** → Phase 2 (deep) + Phase 3 (targeted) — min 2; also covered by Phase 4\n- **LOW-risk file** → Phase 4 (shallow) — min 1\n\n**Step 1f — IMMEDIATELY start Phases 2, 3, and 4.** Do not pause to write analysis. Do not\ninvoke patch-explainer or any other sub-skill. The coverage checklist IS the Phase 1 output.\nIn the same response, spawn all Phase 2/3/4 subagents — see \"Launching Phases 2/3/4\" below.\n\n---\n\n## PHASE 2: Deep Review — invoke `/deep-review`\n\nFor every HIGH- and MEDIUM-risk file, invoke `/deep-review` scoped to that file. Each file\ngets a **separate, fresh subagent** — they run in parallel and share no context with each other.\nThis phase runs **in parallel with Phases 3 and 4** — start it as soon as Phase 1 completes.\n\n**Per-file input packet** (what the orchestrator provides to each `/deep-review` invocation):\n- The diff for that file only: `git diff <base>..<head> -- <file>`\n- The file's full current source (deep-review reads this itself, but point it at the right file)\n- A 100–150 word orchestrator briefing:\n  - File classification (algorithmic / state machine / wiring / concurrency)\n  - What the file does in the context of the overall change (1–2 sentences from Phase 1)\n  - Risk level and why it was classified HIGH or MEDIUM\n\n---\n\n## PHASE 3: Targeted Review — invoke `/targeted-review`\n\nInvoke the `/targeted-review` skill scoped to **all HIGH- and MEDIUM-risk files** identified\nin Phase 1 — not the full patch. Targeted-review is designed for focused review: it picks only\nthe bug-pattern categories whose diff signals match, then spawns tight subagents per focus area.\nFeeding it the full patch dilutes that focus; feeding it the files that matter most lets it go\ndeep where it counts.\n\n**Selecting the scope**:\n- Include all files classified HIGH- or MEDIUM-risk in Phase 1\n- Include files touched in multiple commits (cross-commit modification from the decomposition map)\n- Exclude LOW-risk files, test-only files, and pure documentation/config changes\n\n**When invoking `/targeted-review`**:\n- Pass only the diff for the selected files (not the full patch)\n- Include the Phase 1 risk classification and file-type notes as context so targeted-review\n  subagents understand what to focus on\n\nThis phase runs **in parallel with Phases 2 and 4** — start it as soon as Phase 1 completes.\nCollect all findings and tag each with `Phase 3 (targeted-review)` and its subagent focus.\n\n---\n\n## PHASE 4: Per-Commit Shallow Reviews — invoke `/shallow-review`\n\nFor each HIGH- and MEDIUM-risk commit, invoke `/shallow-review` scoped to that commit's diff.\nEach invocation is a **fresh subagent** — it receives only that commit's diff, not the full\npatch or accumulated findings from other commits.\n\nThis phase runs **in parallel with Phases 2 and 3** — start it as soon as Phase 1 completes.\n\n**Step 4a**: Extract per-commit diff to its own file:\n```bash\ngit diff <SHA>~1..<SHA> > /tmp/patch_<SHA>.diff\n```\n\n**Step 4b**: Assemble a briefing packet for `/shallow-review` containing ONLY:\n- The commit's diff (`/tmp/patch_<SHA>.diff`)\n- A 100–150 word orchestrator briefing covering:\n  - What category the commit is (algorithmic, state machine, wiring, concurrency)\n  - What risk level (HIGH/MEDIUM) and why\n  - For \"Fix\" commits: \"This commit says 'Fix X' — verify the fix is correct, complete,\n    and does not introduce new bugs. Fix commits have a higher-than-average bug rate.\"\n\n**Step 4c**: Run all HIGH- and MEDIUM-risk commit reviews in a single parallel batch. Collect\nfindings and tag each with the commit SHA.\n\n---\n\n## PHASE 5: Cross-Cut Passes\n\n**Dispatch 5A, 5B, and 5C as parallel subagents.** Each receives a focused slice of findings\nand a targeted task — not the full findings dump from all prior phases. The orchestrator\npre-filters: each subagent receives only the findings relevant to its pass.\n\n### 5A: Pattern Amplification\n\nPatterns come entirely from **bugs actually found in Phases 2–4** — there is no pre-loaded catalog.\nIf Phases 2–4 found zero bugs, 5A is skipped.\n\n**Orchestrator's job** (done before spawning anything):\n1. Collect all findings from Phases 2–4\n2. For each distinct bug, characterize the structural pattern — not the specific instance, but\n   the general shape: e.g. \"method accepts a `start` offset parameter, but an internal\n   `arraycopy` call ignores it and uses hardcoded `0`\"\n3. Decide the search scope based on the pattern type:\n   - **Patch-only** — pattern is structural and specific to new code introduced in this PR\n     (new algorithm, new data structure, new method overload family). Unlikely to exist elsewhere.\n   - **Codebase-wide** — pattern is a convention violation or contract bug that could affect\n     any code following the same convention (serialization encoding, API return value contracts,\n     lifecycle protocols, error code handling). The same mistake recurs wherever the convention\n     is followed, including in code not touched by this PR.\n4. Grep at the chosen scope for locations that could match the pattern shape\n5. Spawn one subagent per pattern, passing it: the pattern description + the grep hits + the\n   scope used (so it knows whether to look beyond the patch if it finds new leads)\n\n**Each subagent's job**: verify whether each grep hit is actually the same bug — read the\nsurrounding source as needed. Report confirmed additional instances only.\n\nOne confirmed bug → one pattern → potentially many additional instances found. This is the\nhighest-yield step when Phases 2–4 produce findings.\n\n### 5B: Cross-Commit/Cross-Subsystem Consistency\n\n**Subagent input**: The decomposition map from Phase 1 (file list, method signatures changed,\nrename list) + the list of caller sites extracted by the orchestrator. Not the full patch.\n\n1. **Interface contracts**: For each changed method signature, verify ALL callers updated\n2. **Rename completeness**: `grep` for old names that should no longer appear\n3. **Assumption conflicts**: When one part of the patch assumes X and another assumes Y about the same state\n\n### 5C: Fix Verification\n\n**Subagent input**: One subagent per \"Fix\" commit. Each receives: that commit's diff only +\na one-paragraph description of the bug it claims to fix.\n\nFor each fix commit:\n1. Read the fix carefully\n2. Try to construct an input that would still trigger the original bug\n3. Try to construct an input that triggers a new bug introduced by the fix\n\n### 5D: Optional Additional Review Passes\n\nIf Phases 2–5C revealed areas not yet covered, run additional targeted passes:\n\n- If 5A found a pattern class in files not yet reviewed → `/deep-review` on those files with\n  the specific pattern as focus guidance\n- If 5B found cross-cut inconsistencies in files not yet reviewed → `/shallow-review` on the\n  combined diff of those files\n- If a fix commit (5C) looks suspicious → `/deep-review` on that file with guidance:\n  \"Verify this fix is correct and does not introduce new bugs.\"\n\n---\n\n## Coverage Gate — Verify Before Phase 6\n\nBefore merging findings, verify `/tmp/mega_coverage.md` is fully green.\n\n**Step 1 — Mark completions**: For each file row, confirm every assigned reviewer phase ran\nand reported (a \"no findings\" report counts). Update **Covered?**:\n- `✓` — all assigned reviewers completed\n- `GAP` — one or more assigned reviewers did not run\n\n**Step 2 — Fill gaps**: For every `GAP` row, launch additional review passes now:\n- File with 0 reviewers completed → `/shallow-review` on that file's diff\n- HIGH- or MEDIUM-risk file with only 1 of 2 reviewers completed → `/shallow-review` on that file's diff\n\nRun all gap-fill passes in a single parallel batch, then update the checklist.\n\n**Step 3 — Gate**: Do not proceed to Phase 6 until every row in `/tmp/mega_coverage.md`\nshows `✓`. If gaps remain after one gap-fill pass, repeat Step 2.\n\n**Step 4 — Include the final checklist** in the Phase 6 report under a \"Coverage\" section.\n\n---\n\n## PHASE 6: Merge & Validate Findings\n\n### Deduplication\nSame location + same root cause = one finding. Boost confidence when found by multiple phases.\n\n### Plausibility Validation\n\nEvery finding MUST pass ALL of:\n1. **The code exists**: Point to exact file:line in the current code\n2. **The bug is achievable**: Describe a concrete input that triggers it\n3. **The result is wrong**: Explain what the code produces vs what it should produce\n4. **Tests don't catch it**: Explain why (e.g., \"tests only call the simple overload without offsets\")\n\nDiscard findings that fail any of these.\n\n### Confidence Ranking\n- **High**: Found by Phase 2 (deep review), or found by 2+ phases independently\n- **Medium**: Single phase found it, plausible trigger exists but complex to verify\n- **Low**: Pattern match suggests possible bug but trigger is speculative\n\n---\n\n## Report Format\n\n```\n## Mega-Review: [commit range / feature name]\n\n### Summary\n- [N] commits/subsystems, [M] files, [L] LOC reviewed\n- [X] bugs found: [H] high-confidence, [M] medium, [L] low\n\n### Findings (ranked by confidence)\n\n#### [HIGH] Finding 1: [precise title]\n- **Location**: file:line\n- **Found by**: Phase [N] ([audit/review type])\n- **The bug**: [what the code does wrong, precisely]\n- **Trigger**: [specific input that causes it]\n- **Expected**: [what should happen]\n- **Actual**: [what happens instead]\n- **Why tests miss it**: [explanation]\n- **Fix**: [specific code change]\n\n[... more findings ...]\n\n### Phase Coverage\n| Phase | Scope | Findings |\n|---|---|---|\n| 1: Decompose & classify | git log + stat | (coverage map) |\n| 2: Deep review | [N] HIGH+MEDIUM files | [M] bugs |\n| 3: Targeted review | HIGH+MEDIUM files, [N] foci | [M] bugs |\n| 4: Shallow review | [N] HIGH+MEDIUM commits | [M] bugs |\n| 5A: Pattern amplification | [N] patterns | [M] additional bugs |\n| 5B: Cross-cut | [checks] | [M] bugs |\n```\n\n---\n\n## Anti-Patterns (What NOT to Report)\n\n- **Style/naming issues** — Not bugs.\n- **Performance concerns** — Not bugs (unless they cause incorrect results).\n- **\"Might be wrong\" without a trigger** — If you can't describe a concrete input that causes\n  incorrect output, it's not a finding.\n- **Documentation mismatches** — Only report if the mismatch causes callers to use the API wrong.\n\n<!-- File: .claude/skills/patch-explainer/references/analysis_framework.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/patch-explainer/references/analysis_framework.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/analysis_framework.md)\n\n<!-- File: .claude/skills/patch-explainer/references/ascii_patterns.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.claude/skills/patch-explainer/references/ascii_patterns.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/patch-explainer/references/ascii_patterns.md)\n\n<!-- File: .claude/skills/patch-explainer/SKILL.md (Tokens: ~1975 | Category: anthropic-skill) -->\n---\nname: patch-explainer\nversion: \"1.0.0\"\ndescription: Deep code analysis with ASCII visualizations showing structure, flow, and state transitions. Use when analyzing patches/diffs, explaining classes or subsystems, understanding code architecture, reviewing changes for inconsistencies, or when asked to visualize how code works. Provides before/after diagrams, data/control flow, concurrency analysis, assumptions, and failure modes. Triggers on explain this patch/code/class, how does X work, show me the flow, visualize this change, code review requests, or proactive analysis during PR reviews.\n---\n\n# Patch Explainer\n\nDeeply analyze and visualize code using ASCII diagrams to reveal structure, behavior, and interactions.\n\n## What This Skill Does\n\nProvides comprehensive code analysis with rich ASCII visualizations for:\n- **Patches/diffs**: Before/after states, what changed and why\n- **Classes**: Purpose, structure, state transitions, workflows\n- **Subsystems**: Component interactions, data flow, architecture\n- **Repositories**: Overall structure, key abstractions, major patterns\n- **Code reviews**: Finding inconsistencies, analyzing assumptions and failure modes\n\n## Analysis Approach\n\n### For Any Code (Patches, Classes, Subsystems, Repositories)\n\n1. **Identify the core purpose** - What does this code do and why does it exist?\n\n2. **Create ASCII visualizations** showing:\n   - Structure (components, layers, dependencies)\n   - Behavior (data flow, control flow, state transitions)\n   - Interactions (sequence diagrams, message passing, concurrency)\n   - For patches: before/after comparisons\n\n3. **Deep reasoning** about:\n   - **Assumptions**: What must be true for this to work correctly?\n   - **Failure modes**: What could go wrong at each step?\n   - **Concurrency**: If multiple threads/processes, show their interactions\n   - **Invariants**: What must always hold true?\n\n4. **Focus on the \"why\"**:\n   - Why does this code exist?\n   - Why was this approach chosen?\n   - For changes: Why this modification? What problem does it solve?\n\n### Visualization Strategy\n\nChoose diagram types based on what you're explaining:\n\n**State machines** - When code manages states/status:\n```\n[Initial] --event--> [Processing] --success--> [Complete]\n                          |\n                       failure\n                          |\n                          v\n                      [Failed]\n```\n\n**Data flow** - When showing information movement:\n```\nInput → [Transform A] → [Transform B] → Output\n```\n\n**Sequence diagrams** - When showing component interactions:\n```\nClient          Server          Database\n  |               |                 |\n  |--request----->|                 |\n  |               |----query------->|\n  |               |<---result-------|\n  |<--response----|                 |\n```\n\n**Component structure** - When showing architecture:\n```\n┌─────────────────────┐\n│   Application       │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Service Layer     │\n└──────────┬──────────┘\n           |\n┌──────────┴──────────┐\n│   Data Layer        │\n└─────────────────────┘\n```\n\n**Before/after** - When explaining changes:\n```\nBEFORE                  AFTER\n─────────────────────────────────\n[A] → [B] → [C]        [A] → [Cache?] ─Yes→ [C]\n                              |\n                              No\n                              v\n                            [B] → [C]\n```\n\n### Reference Materials\n\n**ASCII diagram templates**: See [ascii_patterns.md](references/ascii_patterns.md) for:\n- State machine patterns\n- Data flow diagrams\n- Sequence diagrams\n- Component/architecture diagrams\n- Before/after comparisons\n- Concurrency patterns\n- Control flow patterns\n- Dependency graphs\n\n**Analysis methodology**: See [analysis_framework.md](references/analysis_framework.md) for:\n- Structured analysis process for patches vs existing code\n- Concurrency analysis checklist\n- Assumption identification patterns\n- Failure mode identification\n- Analysis depth guidelines by scope (function → class → subsystem → repository)\n\n## Analysis Workflow\n\n### For Patches/Diffs\n\n1. Read the patch to understand what changed\n2. Identify the change type (bug fix, feature, refactor, optimization)\n3. Create before/after ASCII diagrams showing:\n   - Old behavior vs new behavior\n   - State transitions that changed\n   - Data flow modifications\n4. Explain what fundamentally changed:\n   - What problem did the old code have?\n   - How does the new code solve it?\n   - What assumptions changed?\n5. Analyze failure modes:\n   - What could go wrong with this change?\n   - Are there edge cases not handled?\n   - Concurrency implications?\n6. Focus on the \"why\": What problem does each modification solve?\n\n### For Classes\n\n1. Read the class to understand its purpose\n2. Create ASCII diagram showing:\n   - Class structure (key fields/methods)\n   - State machine if it manages state\n   - How it fits with related classes\n3. Explain key workflows (2-3 most important methods)\n4. Identify assumptions and invariants\n5. Analyze failure modes and edge cases\n6. Focus on the \"why\": Why does this class exist? What problem does it solve?\n\n### For Subsystems\n\n1. Identify the components in the subsystem\n2. Create ASCII diagram showing:\n   - Component relationships\n   - Key interfaces/boundaries\n   - Main data flows\n3. Trace 2-3 key workflows through the subsystem\n4. Explain how components interact\n5. Identify assumptions across component boundaries\n6. Focus on the \"why\": What is this subsystem's role in the larger system?\n\n### For Repositories\n\n1. Understand the high-level architecture\n2. Create ASCII diagram showing:\n   - Major modules/packages\n   - Layered architecture\n   - Key abstractions\n3. Identify core workflows\n4. Explain main patterns used throughout\n5. Highlight critical subsystems\n6. Focus on the \"why\": What problem does this codebase solve?\n\n## Concurrency Analysis\n\nWhen analyzing concurrent code, always show:\n\n**Thread interactions**:\n```\nThread A                State                Thread B\n   |                      |                      |\n   |--lock()------------>|                      |\n   |                     [LOCKED]               |\n   |--modify()---------->|                      |\n   |--unlock()---------->|                      |\n   |                     [UNLOCKED]             |\n   |                      |<---------lock()-----|\n   |                     [LOCKED]               |\n```\n\n**Race conditions**:\n```\nThread A            Thread B\n   |                   |\n   |--read(x=10)      |\n   |                   |--read(x=10)\n   |--x=x+1           |\n   |                   |--x=x+1\n   |--write(x=11)     |\n   |                   |--write(x=11)  ⚠ Lost update!\n\nResult: x=11 (expected: x=12)\n```\n\nCheck for:\n- Shared mutable state without synchronization\n- Lock ordering violations (potential deadlocks)\n- Race conditions in read-modify-write operations\n- Missing memory barriers\n\n## Output Structure\n\nStructure your analysis as:\n\n### 1. Executive Summary\nBrief overview (2-3 sentences) of what this code does and why it matters.\n\n### 2. Visual Overview\nHigh-level ASCII diagram showing the main structure or flow.\n\n### 3. Detailed Analysis\nOrganized by aspect:\n- **Purpose**: What it does and why it exists\n- **Structure**: Components and their relationships\n- **Key Workflows**: Step-by-step execution of main scenarios\n- **State Management**: States and transitions (if applicable)\n- **Assumptions**: What must be true for correctness\n- **Failure Modes**: What could go wrong\n- **Concurrency**: Thread safety analysis (if applicable)\n\n### 4. For Patches: Before/After\n- Before state (with diagram)\n- After state (with diagram)\n- Why this change was made\n- Critical modifications explained\n\n### 5. Key Insights\nBullet points highlighting:\n- Most important findings\n- Potential issues or risks\n- Recommendations (if applicable)\n\n## Prioritization\n\nFocus on high-impact elements:\n- **Critical paths**: Main workflows that matter most\n- **High-risk code**: Concurrency, error handling, resource management\n- **Complex logic**: Non-obvious algorithms or subtle interactions\n- **Key abstractions**: Core interfaces and contracts\n\nMinimize or skip:\n- Boilerplate code\n- Simple getters/setters\n- Standard patterns done correctly\n- Low-risk trivial changes\n\n## Example Scenarios\n\n**Scenario 1**: \"Explain this patch\"\n→ Show before/after diagrams, explain what changed and why, analyze assumptions and failure modes\n\n**Scenario 2**: \"How does SafeCommandStore work?\"\n→ Show class structure, explain the exclusive access pattern, trace key methods, analyze thread safety\n\n**Scenario 3**: \"Explain the coordination subsystem\"\n→ Show component diagram, trace PreAccept→Accept→Commit flow, explain message passing, show quorum tracking\n\n**Scenario 4**: \"What's the architecture of this codebase?\"\n→ Show high-level module structure, identify key abstractions, explain main patterns, highlight critical subsystems\n\n**Scenario 5**: During code review (proactive)\n→ Analyze changes for inconsistencies, check assumptions, identify potential race conditions, verify error handling\n\n<!-- File: .claude/skills/README.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Skills Skill\n\nPath: `.claude/skills/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/README.md)\n\n<!-- File: .claude/skills/shallow-review/EVAL-PROMPT.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Shallow-review Skill\n\nPath: `.claude/skills/shallow-review/EVAL-PROMPT.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/EVAL-PROMPT.md)\n\n<!-- File: .claude/skills/shallow-review/references/general/specialists/absence.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/absence.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/absence.md)\n\n<!-- File: .claude/skills/shallow-review/references/general/specialists/boundary.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/boundary.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/boundary.md)\n\n<!-- File: .claude/skills/shallow-review/references/general/specialists/completeness.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/completeness.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/completeness.md)\n\n<!-- File: .claude/skills/shallow-review/references/general/specialists/concurrency.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/concurrency.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/concurrency.md)\n\n<!-- File: .claude/skills/shallow-review/references/general/specialists/logic.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/logic.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/logic.md)\n\n<!-- File: .claude/skills/shallow-review/references/general/specialists/resources.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Specialists Skill\n\nPath: `.claude/skills/shallow-review/references/general/specialists/resources.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/apache/cassandra/HEAD/.claude/skills/shallow-review/references/general/specialists/resources.md)\n\n<!-- File: .claude/skills/shallow-review/SKILL.md (Tokens: ~2852 | Category: anthropic-skill) -->\n---\nname: shallow-review\nversion: \"1.0.0\"\ndescription: >\n  Shallow (quick) ensemble bug-finding review using 6 specialist agents in parallel. Each\n  specialist reviews the same patch through a different lens: Logic & Types, Boundaries &\n  I/O, Concurrency & State, Resources & Serialization, Absence Analysis, and API\n  Completeness. Findings are merged and deduplicated. Best for: quick first-pass review of\n  patches, triage of diffs, broad surface-level bug scan. For deeper file-focused review\n  with full pattern catalogs and codebase investigation, use the deep-review skill instead.\n---\n\n# Ensemble Code Review\n\nSix specialist agents review the same patch in parallel. Each applies Phase 0 (understand\nthe change, form hypotheses) then a focused checklist. Their findings are merged and\ndeduplicated.\n\n```\n                    +------------------+\n                    |   Input Patch    |\n                    +--------+---------+\n                             |\n    +-------+------+---------+---------+-----------+\n    |       |      |         |         |           |\n+---v--+ +--v--+ +-v-----+ +-v------+ +v-----+ +---v-------+\n|Logic | |Bound| |Concurr| |Resource| |Absenc| | Complete. |\n|&Type | | &I/O| |&State | |& Serde | |(2-ph)| | & Contr.  |\n+--+---+ +--+--+ +---+---+ +---+----+ +--+---+ +---+-------+\n   |        |        |         |          |        |\n   +--------+--------+---------+----------+--------+\n                               |\n                    +----------v----------+\n                    |  Pass 3: Symmetry   |\n                    |  (serial, optional) |\n                    +----------+----------+\n                               |\n                    +----------v----------+\n                    |   Merge & Dedup     |\n                    |   (main agent)      |\n                    +---------------------+\n```\n\n## Quick Start\n\n1. **Identify target** — patch, diff, file, or subsystem\n2. **Launch 6 specialists** in parallel (see prompts below)\n3. **Run Pass 3 Symmetry** check (serial, after specialists complete)\n4. **Merge** findings: deduplicate, rank by confidence\n5. **Report** in unified format\n\n## Phase 0: Understand Before Checking\n\nEvery specialist runs Phase 0 BEFORE touching the checklist:\n\n1. **Summarize** the patch in 2–3 sentences (feature, fix, refactor, move?)\n2. **Hypothesize** — list 3–5 things that could go wrong with this type of change\n3. **Note** code shapes that warrant deeper investigation\n\nThis switches the review from bottom-up (checklist→code) to top-down\n(code→hypotheses→verification). The checklist then verifies and extends the hypotheses.\n\n---\n\n## The Six Specialists\n\n### 1. Logic & Types (52% of bugs)\n\n**Priority**: wrong comparisons, missing returns, wrong constants, boolean polarity, sentinel ambiguity.\n\n**Reference**: `references/general/specialists/logic.md`\n\n**Prompt**:\n```\nYou are a LOGIC specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any suspicious code shapes (control flow, comparisons, constants, sentinels).\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/logic.md`\nApply questions that match your hypotheses and code shapes. Check all 30 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 2. Boundaries & I/O (17% of bugs)\n\n**Priority**: off-by-one, integer overflow, null/bounds checks, buffer sizing, I/O completeness.\n\n**Reference**: `references/general/specialists/boundary.md`\n\n**Prompt**:\n```\nYou are a BOUNDARY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any arithmetic, indexing, range, or I/O operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/boundary.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 3. Concurrency & State (16% of bugs)\n\n**Priority**: races, TOCTOU, live-view iteration, lock ordering, state cleanup.\n\n**Reference**: `references/general/specialists/concurrency.md`\n\n**Prompt**:\n```\nYou are a CONCURRENCY specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any shared state, locks, collections, lifecycle operations.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/concurrency.md`\nApply questions that match your hypotheses and code shapes. Check all 24 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 4. Resources & Serialization (15% of bugs)\n\n**Priority**: resource leaks, serialization mismatches, wrong metric types, background tasks, wrapper bypass.\n\n**Reference**: `references/general/specialists/resources.md`\n\n**Prompt**:\n```\nYou are a RESOURCES specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could go wrong with this type of change.\n3. Note any resource allocation, serialization methods, metrics, streams.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/resources.md`\nApply questions that match your hypotheses and code shapes. Check all 26 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n### 5. Absence Analysis (cross-cutting)\n\n**Priority**: find what SHOULD be present but ISN'T — missing guards, cleanup, handlers, registrations.\n\n**Reference**: `references/general/specialists/absence.md`\n\n**Prompt**:\n```\nYou are an ABSENCE specialist. Your job: find bugs that are purely absent — missing\nguards, cleanup, handlers, or conditions that leave no signal in the diff.\n\nPHASE 0 — Understand the patch first:\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that SHOULD be present but might be missing.\n\nPHASE 1 — Build the search list:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/absence.md`\nFor each event in the diff matching items (a)-(q), add to your search list.\n\nPHASE 2 — Execute searches and report:\nFor each item in your search list:\n  - Use Grep and Read tools to gather evidence from the codebase\n  - If match found (remove/deregister exists): discard\n  - If no match found: report as finding\n\nReport ALL findings above a noise floor. For each: what's missing, where it should\nbe, what evidence you searched for, Confidence (High/Medium/Low).\nOr \"No absence finding\" if nothing applies.\n```\n\n### 6. API Completeness & Contracts\n\n**Priority**: missing fields, missing overrides, registration symmetry, visibility, event coverage.\n\n**Reference**: `references/general/specialists/completeness.md`\n\n**Prompt**:\n```\nYou are an API COMPLETENESS specialist reviewing a patch for correctness bugs.\n\nPHASE 0 — Understand the patch first (before reading checklist):\nRead the patch: `{PATCH_PATH}`\n1. Summarize what this patch does in 2-3 sentences.\n2. List 3-5 things that could be incomplete about this change.\n3. Note any new classes, new fields, new registrations, visibility changes.\n\nPHASE 1 — Apply checklist:\nRead your checklist: `{SKILL_DIR}/references/general/specialists/completeness.md`\nApply questions that match your hypotheses and code shapes. Check all 22 items\nagainst the patch but spend the most effort where your hypotheses pointed.\n\nReport ALL findings above a noise floor. For each: Location, Confidence\n(High/Medium/Low), What's wrong (1-2 sentences).\nOr \"No finding in my domain\" if nothing applies.\n```\n\n---\n\n## Pass 3: Cross-Path Symmetry (serial, after specialists complete)\n\n**Prompt**:\n```\nYou are a SYMMETRY specialist. For each code path modified in this patch, identify\nwhether a structurally parallel path (same class, interface, event family, version range)\nwas NOT modified. For each asymmetry:\n- Where path A was changed\n- Where parallel path B exists\n- What was changed on A that is absent on B\n- Whether the asymmetry is intentional or suspicious\n\nRead the patch: `{PATCH_PATH}`\nSearch the codebase as needed using Grep and Read.\nReport all asymmetries, Confidence High/Medium/Low.\n```\n\n---\n\n## Merge & Dedup\n\nAfter all specialists report:\n\n1. **Collect** all findings from 6 specialists + symmetry\n2. **Deduplicate** — same code location + related reasons → combine\n3. **Rank** by confidence — findings confirmed by multiple specialists rank highest\n4. **Cross-check** reinforcement:\n   - Logic + Absence at same location → boost to High\n   - Concurrency + Resources on same lifecycle → boost to High\n   - Any finding flagged by 3+ specialists → treat as confirmed\n5. **3-point test** each finding:\n   - The code construct actually exists in the diff (not inferred)\n   - The bug is possible given the visible context (not speculative)\n   - The finding is actionable (what specifically should change)\n6. **Specialist Silence Rule**: If Absence or Completeness reports nothing on a >100-line\n   diff, note: \"Consider verifying Phase 2 searches executed for registration symmetry,\n   handler coverage, and field completeness.\"\n\n---\n\n## Report Format\n\n```\n## Review: [target]\n\n### Findings (ranked by confidence)\n\n#### Finding 1: [title]\n- **Location**: [file:line]\n- **Confidence**: High / Medium / Low\n- **Flagged by**: [specialists]\n- **What's wrong**: [1-2 sentences]\n\n### Specialist Coverage\n- Logic: [N findings / no finding]\n- Boundary: [N findings / no finding]\n- Concurrency: [N findings / no finding]\n- Resources: [N findings / no finding]\n- Absence: [N findings / no finding]\n- Completeness: [N findings / no finding]\n- Symmetry: [N asymmetries / none]\n```\n\n## Statistical Priors\n\n| Category | Share | Specialist |\n|---|---|---|\n| Logic error in condition | 26% | Logic |\n| Wrong constant / default | 15% | Logic |\n| Missing null / bounds check | 13% | Boundary |\n| Incorrect filtering / result | 11% | Logic |\n| Race condition | 9% | Concurrency |\n| Wrong serialization | 8% | Resources |\n| State not cleaned up | 7% | Concurrency |\n| Off-by-one | 4% | Boundary |\n| Resource leak | 3% | Resources |\n\n## Reference Files\n\n### Specialist checklists (trimmed, ensemble mode)\n- `references/general/specialists/logic.md` — 30 items, Logic specialist\n- `references/general/specialists/boundary.md` — 22 items, Boundary specialist\n- `references/general/specialists/concurrency.md` — 24 items, Concurrency specialist\n- `references/general/specialists/resources.md` — 26 items, Resources specialist\n- `references/general/specialists/absence.md` — Phase 1/2 search patterns, Absence specialist\n- `references/general/specialists/completeness.md` — 22 items, Completeness specialist\n\n<!-- ... +53 more modular skills available via /api/skills/apache/cassandra?path={path} -->\n</yakaai_skills>"}