ideal-agentic-workflow 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.claude-plugin/plugin.json +16 -0
  2. package/AGENTS.md +113 -0
  3. package/agents/_persona-creator.md +75 -0
  4. package/agents/fullstack/architecture-auditor.md +12 -0
  5. package/agents/fullstack/implementation-reviewer.md +4 -0
  6. package/agents/fullstack/performance-seo-auditor.md +12 -0
  7. package/agents/fullstack/plan-critic.md +4 -0
  8. package/agents/fullstack/security-auditor.md +12 -0
  9. package/agents/fullstack/security-code-reviewer.md +4 -0
  10. package/agents/fullstack/test-quality-auditor.md +12 -0
  11. package/agents/fullstack/uiux-cro-auditor.md +12 -0
  12. package/agents/minecraft/architecture-auditor.md +12 -0
  13. package/agents/minecraft/game-performance-auditor.md +12 -0
  14. package/agents/minecraft/implementation-reviewer.md +4 -0
  15. package/agents/minecraft/mapping-compliance-auditor.md +14 -0
  16. package/agents/minecraft/mod-compatibility-auditor.md +12 -0
  17. package/agents/minecraft/plan-critic.md +4 -0
  18. package/agents/minecraft/test-quality-auditor.md +13 -0
  19. package/package.json +12 -0
  20. package/resources/audit-template.md +27 -0
  21. package/resources/gemini-template.md +74 -0
  22. package/resources/plan-template.md +40 -0
  23. package/resources/review-template.md +23 -0
  24. package/resources/stacks/_stack-pack-creator.md +34 -0
  25. package/resources/stacks/database-mongo-redis.md +56 -0
  26. package/resources/stacks/database-postgres-prisma.md +55 -0
  27. package/resources/stacks/mc-fabric.md +60 -0
  28. package/resources/stacks/mc-neoforge.md +64 -0
  29. package/resources/stacks/web-backend-java-spring.md +58 -0
  30. package/resources/stacks/web-backend-python-ai.md +62 -0
  31. package/resources/stacks/web-backend-rust.md +57 -0
  32. package/resources/stacks/web-nextjs-turborepo.md +65 -0
  33. package/resources/submit-template.md +24 -0
  34. package/resources/task-template.md +8 -0
  35. package/skills/s1-orchestrator/SKILL.md +193 -0
  36. package/skills/s1-orchestrator/resources/duolithic-mode.md +114 -0
  37. package/skills/s1-orchestrator/resources/fast-mode.md +170 -0
  38. package/skills/s1-orchestrator/resources/session-init.md +65 -0
  39. package/skills/s1-orchestrator/resources/trivial-mode.md +113 -0
  40. package/skills/s10-git-commit/SKILL.md +37 -0
  41. package/skills/s10-git-commit/resources/breaking-change-guide.md +33 -0
  42. package/skills/s10-git-commit/resources/commit-examples.md +76 -0
  43. package/skills/s11-gemini-update/SKILL.md +36 -0
  44. package/skills/s11-gemini-update/resources/gemini-schema.md +35 -0
  45. package/skills/s11-gemini-update/resources/global-skill-suggester.md +29 -0
  46. package/skills/s2-codebase-audit/SKILL.md +116 -0
  47. package/skills/s2-codebase-audit/resources/audit-compiler.md +33 -0
  48. package/skills/s2-codebase-audit/resources/fullstack-persona-bank.md +33 -0
  49. package/skills/s2-codebase-audit/resources/minecraft-persona-bank.md +33 -0
  50. package/skills/s3-planning/SKILL.md +62 -0
  51. package/skills/s3-planning/resources/priority-rubric.md +54 -0
  52. package/skills/s4-plan-review/SKILL.md +75 -0
  53. package/skills/s4-plan-review/resources/plan-review-guide.md +51 -0
  54. package/skills/s6-coding/SKILL.md +48 -0
  55. package/skills/s6-coding/resources/anti-patterns.md +49 -0
  56. package/skills/s6-coding/resources/stack-detector.md +35 -0
  57. package/skills/s8-code-review/SKILL.md +55 -0
  58. package/skills/s8-code-review/resources/code-review-guide.md +42 -0
@@ -0,0 +1,56 @@
1
+ # Stack Pack: MongoDB + Redis
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for MongoDB and Redis (Upstash) applications. An auditor MUST verify that the infrastructure matches these requirements to ensure compatibility with modern driver features. Failing to meet these requirements can lead to connection issues in serverless environments.
5
+
6
+ | Technology | Minimum Version | Required Dependencies | Incompatible With |
7
+ |---|---|---|---|
8
+ | MongoDB | 6.0 | `mongodb` or `mongoose` driver | MongoDB < 5.0 |
9
+ | Redis (Upstash) | 6.2 | `ioredis` or `@upstash/redis` | Local-only Redis configs in serverless |
10
+ | Node.js | 18.17.0 | None | Node.js < 18 |
11
+
12
+ ## 2. Architecture Rules
13
+ These rules define the structural boundaries and hygiene of a NoSQL and Key-Value store architecture. The codebase MUST adhere strictly to these constraints to ensure data consistency and prevent memory exhaustion. Violating these rules commonly results in unstructured data blobs and out-of-memory errors in caching layers.
14
+
15
+ - **Schema Validation**: MongoDB collections MUST enforce schema validation either at the database level (using JSON Schema validation) or at the application layer (using Mongoose schemas or Pydantic/Zod). Arbitrary document structures without validation are prohibited.
16
+ - **Index Creation**: The application MUST NOT rely on automatic index creation in production. Indexes MUST be defined explicitly and created via a deployment script or migration tool, not during application startup.
17
+ - **Redis TTL Requirement**: Every key written to Redis (including Upstash) MUST have a Time-To-Live (TTL) configured. Keys MUST NOT be allowed to persist indefinitely unless they are part of a bounded, explicitly managed state machine.
18
+ - **Keyspace Namespacing**: Redis keys MUST be prefixed with a clear namespace to prevent keyspace collisions (e.g., `session:user_123`, `rate_limit:ip_456`).
19
+ - **Connection Management**: MongoDB connections MUST be cached across serverless invocations (e.g., storing the client in a global variable) to prevent connection exhaustion. Upstash Redis MUST use REST-based clients (`@upstash/redis`) in serverless environments rather than TCP connections.
20
+
21
+ ## 3. Common Anti-Patterns
22
+ The following anti-patterns highlight the most common architectural mistakes made in MongoDB and Redis applications. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent NoSQL injection vulnerabilities and out-of-memory incidents.
23
+
24
+ #### AP-MONGO-01: NoSQL Injection Vulnerability
25
+ **What it is**: Passing user input directly into MongoDB query objects without sanitization.
26
+ **Detection signal**: Querying the database with an object that directly spreads `req.body` or `req.query`, such as `db.users.find(req.query)`.
27
+ **Consequence**: Attackers can inject query operators like `$gt` or `$ne` in the payload (e.g., `?password[$ne]=`) to bypass authentication or extract sensitive data.
28
+ **Correct alternative**: Explicitly map and sanitize input fields: `db.users.find({ username: req.body.username })`.
29
+
30
+ #### AP-REDIS-01: Missing TTL on Cache Keys
31
+ **What it is**: Writing data to Redis without setting an expiration time (TTL).
32
+ **Detection signal**: Using `redis.set("key", "value")` without passing the `EX` or `PX` arguments.
33
+ **Consequence**: The Redis instance eventually runs out of memory, causing evictions of important data or crashing the cache entirely.
34
+ **Correct alternative**: Always specify a TTL: `redis.set("key", "value", "EX", 3600)`.
35
+
36
+ #### AP-MONGO-02: Unbounded Array Growth
37
+ **What it is**: Continuously pushing items into an array field within a single MongoDB document.
38
+ **Detection signal**: Frequent use of the `$push` operator without `$slice` or `$sort` to cap the array size.
39
+ **Consequence**: The document exceeds the 16MB BSON limit, causing the application to crash on updates, and degrades read performance.
40
+ **Correct alternative**: Move unbounded one-to-many relationships to a separate collection and reference the parent document ID.
41
+
42
+ ## 4. Audit Checklist
43
+ An auditor MUST verify the following items when reviewing a MongoDB and Redis codebase. Failure to check these items may result in critical security vulnerabilities, unbounded memory usage, and exhausted connection limits.
44
+ - [ ] All MongoDB queries strictly sanitize user input and map fields explicitly to prevent NoSQL injection.
45
+ - [ ] Unbounded array growth is prevented via separate collections or the `$slice` operator.
46
+ - [ ] Every Redis `set` operation includes a TTL parameter.
47
+ - [ ] Redis keys use a structured prefix naming convention (e.g., `entity:id`).
48
+ - [ ] Serverless environments use global connection caching for MongoDB.
49
+ - [ ] Serverless environments use HTTP/REST clients for Upstash Redis instead of TCP connections.
50
+
51
+ ## 5. Useful References
52
+ The following resources provide authoritative guidance on building secure and performant applications with MongoDB and Redis. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions regarding schema design, index management, or caching strategies. Utilizing these resources prevents the adoption of brittle NoSQL data models.
53
+ - [MongoDB Schema Design Anti-Patterns](https://www.mongodb.com/developer/products/mongodb/schema-design-anti-pattern-summary/): Explains common pitfalls like unbounded arrays and monolithic documents.
54
+ - [Upstash Redis Best Practices](https://docs.upstash.com/redis): Guide on utilizing Redis over REST APIs in serverless architectures.
55
+ - [Preventing NoSQL Injection](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection): Comprehensive OWASP documentation on sanitizing input before querying a NoSQL database.
56
+ - [Redis TTL Documentation](https://redis.io/commands/expire/): Information on key expiration and eviction policies.
@@ -0,0 +1,55 @@
1
+ # Stack Pack: PostgreSQL + Prisma
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for PostgreSQL and Prisma ORM. An auditor MUST verify that `package.json` files comply with these ranges to prevent runtime failures and schema sync issues. Ensuring these versions are met is critical for utilizing modern Prisma features like full-text search and JSONB filtering.
5
+
6
+ | Technology | Minimum Version | Required Dependencies | Incompatible With |
7
+ |---|---|---|---|
8
+ | PostgreSQL | 14.0 | None | Postgres < 14 |
9
+ | Prisma | 5.0.0 | `@prisma/client` | Prisma 4.x or earlier |
10
+ | Node.js | 18.17.0 | None | Node.js < 18 |
11
+
12
+ ## 2. Architecture Rules
13
+ These rules define the structural boundaries and data access patterns of a Prisma-backed application. The codebase MUST adhere strictly to these constraints to ensure data integrity, atomicity, and performance. Note: For Upstash Redis constraints (TTL, Keyspace Namespacing) that are often paired with Prisma, refer to the `database-mongo-redis.md` stack pack.
14
+
15
+ - **Prisma Migration Discipline**: The application MUST NOT alter existing migration files (`.sql` files in `prisma/migrations`) after they have been applied to the database. All schema changes MUST be made in `schema.prisma` and applied via a new migration using `prisma migrate dev`.
16
+ - **Index Placement Rules**: The `schema.prisma` file MUST declare indexes (`@@index`) for fields frequently used in `where`, `orderBy`, or `join` operations. When creating composite indexes, the fields MUST be ordered starting with the most selective field first.
17
+ - **Atomicity Requirement**: The application MUST use `prisma.$transaction` for any operation that involves multi-table writes or sequential operations that must succeed or fail together.
18
+ - **Connection Pool Limits**: When deploying to serverless environments, the application MUST use an external connection pooler (e.g., PgBouncer) or Prisma Accelerate. Directly connecting serverless functions to PostgreSQL without a pooler exhausts database connections and crashes the application.
19
+
20
+ ## 3. Common Anti-Patterns
21
+ The following anti-patterns highlight the most common architectural mistakes made in Prisma-backed applications. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent catastrophic database load and connection exhaustion.
22
+
23
+ #### AP-PRISMA-01: Prisma N+1 Query Problem
24
+ **What it is**: Fetching a list of records and iterating over them to query related records individually, causing an explosion of database queries.
25
+ **Detection signal**: A `prisma.model.findUnique()` or `findMany()` call located inside a `for` loop, `map()`, or `Promise.all()`.
26
+ **Consequence**: Extremely slow response times as $N$ queries are sent sequentially to the database, exhausting connection pools.
27
+ **Correct alternative**: Use Prisma's `include` or `select` parameters to fetch nested relations in a single query, or use `in` operator to fetch multiple records in one go.
28
+
29
+ #### AP-PRISMA-02: Over-fetching with `include`
30
+ **What it is**: Using `include` without limits to fetch deeply nested relational data when only a few fields are needed.
31
+ **Detection signal**: A `prisma.model.findMany({ include: { relations: true } })` call that returns massive payloads.
32
+ **Consequence**: Excessive memory consumption in the Node.js process and slow database deserialization times.
33
+ **Correct alternative**: Use `select` instead of `include` to specify the exact fields needed, or apply pagination (`take`, `skip`) to nested includes.
34
+
35
+ #### AP-PRISMA-03: Direct Mutation of Migration Files
36
+ **What it is**: Modifying a generated `migration.sql` file after it has already been committed and applied to staging or production.
37
+ **Detection signal**: A git diff showing changes to an older `.sql` file inside the `prisma/migrations/` directory.
38
+ **Consequence**: The migration history drifts between environments, causing `prisma migrate deploy` to fail with checksum errors.
39
+ **Correct alternative**: Make changes in `schema.prisma` and run `npx prisma migrate dev --name <description>` to generate a new migration.
40
+
41
+ ## 4. Audit Checklist
42
+ An auditor MUST verify the following items when reviewing a Prisma codebase. Failure to check these items may result in corrupted migration histories, connection pool exhaustion, or severe performance degradation.
43
+ - [ ] No `prisma.*` queries exist inside loops or `Promise.all()` maps.
44
+ - [ ] Multi-table writes are wrapped in a `prisma.$transaction` block.
45
+ - [ ] Foreign keys and heavily queried fields have `@@index` defined in `schema.prisma`.
46
+ - [ ] Old migration files have not been modified.
47
+ - [ ] Serverless deployments use PgBouncer or Prisma Accelerate for connection pooling.
48
+ - [ ] Queries use `select` to limit payload size instead of over-fetching with blind `include`.
49
+
50
+ ## 5. Useful References
51
+ The following resources provide authoritative guidance on optimizing database access with Prisma and PostgreSQL. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions regarding database transactions, connection pooling, or migration workflows. Ensuring the application adheres to these best practices is essential for database scalability.
52
+ - [Prisma Optimization and N+1](https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance): Guide on resolving N+1 queries and optimizing data fetching strategies.
53
+ - [Prisma Transactions](https://www.prisma.io/docs/concepts/components/prisma-client/transactions): Best practices for ensuring data atomicity with interactive and nested transactions.
54
+ - [Prisma Schema Reference](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference): Official reference for all valid schema.prisma properties, types, and attributes.
55
+ - [PostgreSQL Documentation on Indexes](https://www.postgresql.org/docs/current/indexes.html): Guide on B-Tree index structure and multi-column index optimization.
@@ -0,0 +1,60 @@
1
+ # Stack Pack: Minecraft Mod (Fabric)
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for Fabric mods. An auditor MUST verify that `gradle.properties` and `build.gradle` files comply with these strict matrices. Strict adherence to these versions ensures the mod compiles against the correct mappings and game APIs.
5
+ **Note**: The ecosystem splits severely between 1.21.x and 26.x.
6
+
7
+ | Target MC Version | Fabric Loom | Gradle | Java | Allowed Mappings |
8
+ |---|---|---|---|---|
9
+ | MC 1.21.8 – 1.21.11 | ≤ 1.16 | 8.x | 21 | Yarn OR Mojang |
10
+ | MC 26.x | ≥ 1.17 | ≥ 9.5.1 | 25 | Mojang ONLY |
11
+
12
+ **Additional 26.x Constraints**:
13
+ - MC 26.2+ requires the Blaze3D API. Raw OpenGL calls are prohibited due to the experimental Vulkan backend.
14
+ - Yarn mappings are officially unsupported for 26.x and MUST NOT be used.
15
+
16
+ ## 2. Architecture Rules
17
+ These rules define the structural boundaries of a Fabric mod. The codebase MUST adhere strictly to these constraints to ensure server/client stability and registry timing. Failing to respect these boundaries will cause dedicated servers to crash upon initialization.
18
+
19
+ - **Initializer Split Rules**: The mod MUST separate its entry points. `ModInitializer` is for common code (registries, common events). `ClientModInitializer` is exclusively for client-side code (rendering, screens, keybinds). `DedicatedServerModInitializer` is exclusively for server-side behavior.
20
+ - **Client Code Isolation**: Server and common code MUST NEVER reference client-only classes (e.g., `MinecraftClient`, `Screen`, rendering classes). The `@Environment(EnvType.CLIENT)` annotation MUST be respected, and violating this boundary will cause dedicated servers to crash on startup.
21
+ - **Registry Entry Timing**: All registry entries (Blocks, Items, Entities) MUST be registered synchronously within the `onInitialize()` method of the `ModInitializer`. Lazy registration or registering items during gameplay events is strictly prohibited.
22
+ - **Dependency Declarations**: The `fabric.mod.json` file MUST accurately declare dependencies in the `depends`, `recommends`, and `breaks` fields. This includes declaring a dependency on `fabric-api` if its modules are used.
23
+ - **Event Handler Patterns**: The application MUST use the Fabric API Event system (e.g., `ServerTickEvents.END_SERVER_TICK.register(...)`) for callbacks rather than resorting to mixins for standard hooks.
24
+
25
+ ## 3. Common Anti-Patterns
26
+ The following anti-patterns highlight the most common architectural mistakes made in Fabric mod development. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent mod incompatibility and dedicated server crashes.
27
+
28
+ #### AP-FABRIC-01: Client Code Bleed in Common Setup
29
+ **What it is**: Referencing client-only classes from within the main `ModInitializer` or common event handlers.
30
+ **Detection signal**: Importing `net.minecraft.client.MinecraftClient` or setting up a `KeyBinding` inside the class that implements `ModInitializer`.
31
+ **Consequence**: The mod works perfectly in the single-player development environment but crashes instantly with a `ClassNotFoundException` when deployed to a dedicated server.
32
+ **Correct alternative**: Move all client-side logic to a separate class that implements `ClientModInitializer`.
33
+
34
+ #### AP-FABRIC-02: Overwriting Core Methods via Mixin
35
+ **What it is**: Using the `@Overwrite` annotation in a Mixin to completely replace a vanilla method.
36
+ **Detection signal**: The presence of `@Overwrite` in any Mixin class.
37
+ **Consequence**: Absolute incompatibility with any other mod that attempts to modify the same method, breaking the mod ecosystem.
38
+ **Correct alternative**: Use `@Inject` (with `cancellable = true` if necessary), `@ModifyVariable`, or `@ModifyReturnValue` to alter behavior cooperatively.
39
+
40
+ #### AP-FABRIC-03: Raw OpenGL in 26.2+
41
+ **What it is**: Using raw `GL11` or `RenderSystem` calls that bypass the abstraction layer in modern Minecraft.
42
+ **Detection signal**: Direct calls to `GL11.glEnable()` or similar low-level GL commands.
43
+ **Consequence**: The mod will crash or render incorrectly when the Vulkan backend is enabled in MC 26.2+.
44
+ **Correct alternative**: Use the Blaze3D API and the `MatrixStack` / `VertexConsumer` systems provided by Minecraft.
45
+
46
+ ## 4. Audit Checklist
47
+ An auditor MUST verify the following items when reviewing a Fabric mod. Failure to check these items may result in catastrophic compatibility issues, unstable mixins, or a broken build process.
48
+ - [ ] Version constraints (Loom, Gradle, Java, Mappings) strictly match the target MC version.
49
+ - [ ] No client-only classes are referenced in `ModInitializer` or common code.
50
+ - [ ] All registries are initialized synchronously in `onInitialize()`.
51
+ - [ ] Mixins do not use the `@Overwrite` annotation.
52
+ - [ ] `fabric.mod.json` correctly declares all dependencies and incompatibilities.
53
+ - [ ] For MC 26.2+ targets, no raw OpenGL calls exist.
54
+
55
+ ## 5. Useful References
56
+ The following resources provide authoritative guidance on developing resilient Minecraft mods using the Fabric toolchain. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions regarding networking, mixins, or the registry system. Referencing these guides ensures the mod remains compatible with the wider ecosystem.
57
+ - [Fabric Wiki: Environment isolation](https://fabricmc.net/wiki/tutorial:side): Deep dive on the distinction between the logical and physical server/client.
58
+ - [Fabric Wiki: Mixin Introduction](https://fabricmc.net/wiki/tutorial:mixin): Guidelines for writing safe, compatible mixins.
59
+ - [Fabric Registry Guidelines](https://fabricmc.net/wiki/tutorial:registry): Details on how and when to register new items and blocks.
60
+ - [SpongePowered Mixin Documentation](https://github.com/SpongePowered/Mixin/wiki): The official, comprehensive reference for all mixin annotations.
@@ -0,0 +1,64 @@
1
+ # Stack Pack: Minecraft Mod (NeoForge)
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for NeoForge mods. An auditor MUST verify that `gradle.properties`, `build.gradle`, and `neoforge.mods.toml` files comply with these matrices. Correctly specifying version bounds prevents game crashes on launch and ensures compatibility with the latest API breaking changes.
5
+
6
+ | Target MC Version | NeoForge | Gradle | Java | Allowed Mappings |
7
+ |---|---|---|---|---|
8
+ | MC 1.21.8 – 1.21.11 | 21.x | 8.x | 21 | Mojang (Parchment optional) |
9
+ | MC 26.x | 26.x | ≥ 9.5.1 | 25 | Mojang ONLY (No obfuscation!) |
10
+
11
+ **Additional Requirements**:
12
+ - `neoforge.mods.toml` MUST declare dependency ranges accurately using syntax like `[21.0,22)` for MC 1.21.x targets.
13
+ - MC 26.x environments run natively without obfuscation. Deobfuscation assumptions in build scripts MUST be removed for 26.x.
14
+
15
+ ## 2. Architecture Rules
16
+ These rules define the structural boundaries of a NeoForge mod. The codebase MUST adhere strictly to these constraints to ensure compatibility, correct event bus targeting, and safe registration. Bypassing these abstractions leads to race conditions and broken registries.
17
+
18
+ - **@Mod Annotation**: The main class MUST be annotated with `@Mod("modid")`. The Mod ID must precisely match the ID declared in `neoforge.mods.toml` and MUST be entirely lowercase with no special characters.
19
+ - **Event Registration Distinction**: The `@EventBusSubscriber` annotation MUST be used on classes to automatically register static event handlers (`@SubscribeEvent`) without manual bus registration. However, if instance-level state is required, the class MUST NOT use `@EventBusSubscriber` and instead manually register the instance using `NeoForge.EVENT_BUS.register(this)` and use `@SubscribeEvent` on non-static methods.
20
+ - **DeferredRegister Mandate**: All registry objects (Blocks, Items, Entities, MenuTypes) MUST be registered using the `DeferredRegister` pattern. Direct registration during mod initialization is prohibited as it causes race conditions with NeoForge's internal registry phases.
21
+ - **Event Bus Targeting**: Modders MUST explicitly target the correct event bus. Lifecycle events (setup, registry) belong on the Mod bus (`@EventBusSubscriber(bus = Bus.MOD)`). Gameplay events (tick, interaction) belong on the Forge bus (`@EventBusSubscriber(bus = Bus.FORGE)`).
22
+ - **Client Code Isolation**: Server code MUST NEVER reference client-only classes. Client-specific event handlers MUST specify `value = Dist.CLIENT` in the `@EventBusSubscriber` annotation to ensure they are not loaded on dedicated servers.
23
+ - **Capability System**: The application MUST use the `ICapabilityProvider` registration patterns and NeoForge's attachment system to attach custom data to entities or chunks, rather than relying on mixins or hash maps.
24
+ - **Mixin Configuration**: Mixins are allowed but MUST be explicitly declared via the `@MixinConfig` property in the `neoforge.mods.toml` file.
25
+ - **No Fabric API**: The mod MUST NOT use Fabric API. If cross-loader support is required, the mod MUST use FFAPI or the Sinytra Connector pattern.
26
+
27
+ ## 3. Common Anti-Patterns
28
+ The following anti-patterns highlight the most common architectural mistakes made in NeoForge mod development. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent silent event failures and registry crashes.
29
+
30
+ #### AP-NEOFORGE-01: Incorrect Event Bus Target
31
+ **What it is**: Registering an event handler to the wrong bus, causing the event to never fire.
32
+ **Detection signal**: Annotating a `PlayerTickEvent` handler with `@EventBusSubscriber(bus = Bus.MOD)`.
33
+ **Consequence**: The event handler is completely ignored by the game engine, resulting in silent feature failure.
34
+ **Correct alternative**: Use `bus = Bus.FORGE` for runtime/gameplay events, and `bus = Bus.MOD` for initialization/registry events.
35
+
36
+ #### AP-NEOFORGE-02: Eager Registry Instantiation
37
+ **What it is**: Instantiating a Block or Item as a static final field outside of the `DeferredRegister` framework.
38
+ **Detection signal**: `public static final Block MY_BLOCK = new Block(...)` declared at the class level without a `DeferredRegister` wrapper.
39
+ **Consequence**: The item is instantiated before the game's registry is ready, leading to crashes or missing items in-game.
40
+ **Correct alternative**: Wrap the instantiation in a `DeferredRegister.create()` call and register it via `register(name, () -> new Block(...))`.
41
+
42
+ #### AP-NEOFORGE-03: Missing Mixin Declaration
43
+ **What it is**: Adding a Mixin to the project but failing to declare it in the mod's configuration file.
44
+ **Detection signal**: A `mixins.json` file exists and is populated, but `neoforge.mods.toml` lacks the necessary configuration linking to it.
45
+ **Consequence**: The mixins silently fail to apply at runtime.
46
+ **Correct alternative**: Add `[[mixins]]` and `config="modid.mixins.json"` to the `neoforge.mods.toml` file.
47
+
48
+ ## 4. Audit Checklist
49
+ An auditor MUST verify the following items when reviewing a NeoForge mod. Failure to check these items may result in catastrophic compatibility issues, registry deadlocks, or broken event loops.
50
+ - [ ] Version constraints (NeoForge, Gradle, Java) strictly match the target MC version.
51
+ - [ ] Dependency version ranges in `neoforge.mods.toml` are correctly formatted (e.g., `[21.0,22)`).
52
+ - [ ] All Blocks, Items, and Entities use the `DeferredRegister` pattern.
53
+ - [ ] Event handlers explicitly define the correct bus (`MOD` vs `FORGE`).
54
+ - [ ] Client-only event subscribers use `value = Dist.CLIENT`.
55
+ - [ ] Mixin configs are properly declared in `neoforge.mods.toml`.
56
+ - [ ] No Fabric API classes are imported.
57
+ - [ ] `@Mod` annotation exactly matches the ID in `neoforge.mods.toml`.
58
+
59
+ ## 5. Useful References
60
+ The following resources provide authoritative guidance on developing resilient Minecraft mods using the NeoForge toolchain. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions regarding event buses, data attachments, or registries. Referencing these guides ensures the mod correctly utilizes modern NeoForge capabilities.
61
+ - [NeoForge Documentation: Concepts](https://docs.neoforged.net/docs/concepts/): Fundamental concepts outlining the mod initialization lifecycle.
62
+ - [NeoForge DeferredRegister](https://docs.neoforged.net/docs/concepts/registries/): Standard patterns for declaring blocks, items, and block entities.
63
+ - [NeoForge Event System](https://docs.neoforged.net/docs/concepts/events/): Detailed documentation on the differences between the Mod bus and Forge bus.
64
+ - [SpongePowered Mixin Documentation](https://github.com/SpongePowered/Mixin/wiki): The official reference for mixin configurations and annotations.
@@ -0,0 +1,58 @@
1
+ # Stack Pack: Java Spring Boot Backend
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for Spring Boot and Java backend applications. An auditor MUST verify that `pom.xml` or `build.gradle` files comply with these ranges to prevent runtime failures and dependency conflicts. Enforcing these versions ensures the application benefits from modern Jakarta EE namespaces and security features.
5
+
6
+ | Technology | Minimum Version | Required Dependencies | Incompatible With |
7
+ |---|---|---|---|
8
+ | Java | 17 (21 recommended) | None | Java < 17 |
9
+ | Spring Boot | 3.0.0 | Jakarta EE 10+ | javax.* namespaces |
10
+ | Spring Security | 6.0.0 | Spring Boot 3+ | WebSecurityConfigurerAdapter (deprecated) |
11
+
12
+ ## 2. Architecture Rules
13
+ These rules define the structural boundaries of a Spring Boot backend. The codebase MUST adhere strictly to these constraints to ensure proper transaction management, security, and separation of concerns. Violations of these rules directly lead to security vulnerabilities and unstable transaction lifecycles.
14
+
15
+ - **Transactional Boundaries**: The `@Transactional` annotation MUST only be applied at the Service layer. It MUST NOT be applied at the Controller layer (which handles HTTP) or the Repository layer (which handles individual queries), ensuring transactions wrap entire business operations.
16
+ - **DTO ↔ Entity Mapping**: Entities MUST NOT leak into the Controller layer. The Service layer MUST map Entities to Data Transfer Objects (DTOs) before returning data to the Controller, preventing over-posting attacks and accidental data exposure.
17
+ - **Spring Security Filter Chain**: The `SecurityFilterChain` bean MUST be ordered correctly. Public endpoints MUST be explicitly permitted (`permitAll()`), and all other endpoints MUST require authentication (`anyRequest().authenticated()`).
18
+ - **Authorization Annotations**: Prefer `@PreAuthorize` over `@Secured` for method-level security, as `@PreAuthorize` supports Spring Expression Language (SpEL) for complex rules (e.g., `@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")`).
19
+ - **Exception Handling**: The application MUST use a `@ControllerAdvice` or `@RestControllerAdvice` class to handle exceptions globally. Controllers MUST NOT contain excessive `try-catch` blocks returning raw `ResponseEntity` objects.
20
+
21
+ ## 3. Common Anti-Patterns
22
+ The following anti-patterns highlight the most common architectural mistakes made in Spring Boot applications. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent database performance collapse and runtime null pointer exceptions.
23
+
24
+ #### AP-SPRING-01: JPA N+1 Query Problem
25
+ **What it is**: Fetching a list of entities and then lazily loading a related entity for each item in the list, resulting in $N+1$ database queries instead of 1.
26
+ **Detection signal**: A `@OneToMany` or `@ManyToMany` relationship without a `fetch = FetchType.LAZY` default, combined with accessing the collection in a loop, or omitting `@BatchSize` or `JOIN FETCH` in the JPQL query.
27
+ **Consequence**: Severe database performance degradation under load as one API call triggers hundreds of queries.
28
+ **Correct alternative**: Use `JOIN FETCH` in JPQL queries, configure `@BatchSize` on collections, or use EntityGraphs to fetch related data in a single query.
29
+
30
+ #### AP-SPRING-02: Returning Null from Repositories
31
+ **What it is**: A repository method or service returning a raw `null` value when an entity is not found, forcing the caller to perform null checks.
32
+ **Detection signal**: A method signature like `User findByEmail(String email)` returning `null` if the user does not exist.
33
+ **Consequence**: High risk of `NullPointerException` (NPE) in downstream logic if a null check is missed.
34
+ **Correct alternative**: Return `Optional<User>` from the repository and use functional methods like `.orElseThrow()` in the service layer.
35
+
36
+ #### AP-SPRING-03: Singleton Bean Scope Misuse
37
+ **What it is**: Injecting stateful, request-scoped data into a default Singleton-scoped Spring bean.
38
+ **Detection signal**: A `@Service` or `@Component` class containing mutable instance variables (e.g., `private User currentUser;`) that are modified during a request.
39
+ **Consequence**: Severe race conditions and cross-user data leakage, as the same bean instance is shared across all concurrent HTTP threads.
40
+ **Correct alternative**: Keep singleton beans stateless. If state is required, inject the state via method parameters or use `@RequestScope` for the bean.
41
+
42
+ ## 4. Audit Checklist
43
+ An auditor MUST verify the following items when reviewing a Spring Boot codebase. Failure to check these items may result in broken transaction boundaries, security vulnerabilities, or severe database performance degradation.
44
+ - [ ] `@Transactional` is used exclusively on Service layer classes or methods.
45
+ - [ ] Controllers accept and return DTOs, not database Entities.
46
+ - [ ] `SecurityFilterChain` explicitly configures `permitAll()` for public routes and requires authentication for everything else.
47
+ - [ ] `@PreAuthorize` is used for method-level security instead of `@Secured`.
48
+ - [ ] `@OneToMany` and `@ManyToMany` relationships are audited for N+1 vulnerabilities (using `JOIN FETCH` or `@BatchSize`).
49
+ - [ ] Repositories return `Optional<T>` for single-entity queries.
50
+ - [ ] Global exception handling is implemented via `@RestControllerAdvice`.
51
+ - [ ] Singleton beans (`@Service`, `@Component`) have no mutable instance variables.
52
+
53
+ ## 5. Useful References
54
+ The following resources provide authoritative guidance on building scalable and secure applications with Java and Spring Boot. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions, particularly involving JPA performance or Spring Security filter chains. Reviewing these links regularly ensures that the application remains aligned with modern Spring ecosystem practices.
55
+ - [Spring Boot Reference Documentation](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/): The primary source of truth for configuration and auto-configuration details.
56
+ - [Spring Security Architecture](https://spring.io/guides/topicals/spring-security-architecture): In-depth guide on the security filter chain and authentication providers.
57
+ - [Hibernate N+1 Problem](https://vladmihalcea.com/n-plus-1-query-problem/): Detailed explanation of how to detect and resolve N+1 queries using `JOIN FETCH` and `@BatchSize`.
58
+ - [Spring Data JPA Documentation](https://docs.spring.io/spring-data/jpa/reference/): Authoritative guide on repository patterns, projections, and entity lifecycle.
@@ -0,0 +1,62 @@
1
+ # Stack Pack: Python AI & RAG Backend
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for Python backend applications focused on AI and RAG (Retrieval-Augmented Generation). An auditor MUST verify that `requirements.txt` or `pyproject.toml` files comply with these dependencies to prevent runtime errors and integration failures. Pinning these framework versions is critical because AI libraries frequently introduce breaking changes without major version bumps.
5
+
6
+ | Technology | Minimum Version | Required Dependencies | Incompatible With |
7
+ |---|---|---|---|
8
+ | Python | 3.10 | None | Python < 3.10 |
9
+ | FastAPI | 0.100.0 | `pydantic >= 2.0`, `uvicorn` | Pydantic v1 |
10
+ | LangChain | Pinned exact | Dependent on specific integrations | Unpinned versions |
11
+ | LlamaIndex | Pinned exact | Dependent on specific integrations | Unpinned versions |
12
+
13
+ ## 2. Architecture Rules
14
+ These rules define the structural boundaries and hygiene of an AI-powered Python backend. The codebase MUST adhere strictly to these constraints to ensure API stability, correct embeddings, and reliable execution. Failure to follow these rules will result in blocked event loops, mismatched vector dimensions, and leaked API keys.
15
+
16
+ - **Dependency Pinning**: AI framework libraries (LangChain, LlamaIndex, OpenAI SDK) evolve rapidly with breaking changes. The application MUST pin these dependencies to exact versions (e.g., `langchain==0.1.0`) rather than using loose bounds (`>=`).
17
+ - **Environment Variable Management**: The application MUST NOT hardcode API keys or secrets in source code. The application MUST use `pydantic-settings` to load, validate, and type-check environment variables at startup.
18
+ - **Type Annotation Completeness**: All functions and methods MUST have complete type hints for arguments and return types. The use of a bare `Any` type in production code is prohibited unless dealing with strictly unstructured external JSON.
19
+ - **Pydantic v2 Constraints**: The application MUST use `model_validator` or `field_validator` for complex validation logic, utilizing Pydantic v2 paradigms.
20
+ - **RAG Pipeline Hygiene**:
21
+ - The embedding model version MUST be pinned (e.g., `text-embedding-3-small`), as changing the model breaks compatibility with existing vector stores.
22
+ - The chunking strategy (e.g., chunk size and overlap) MUST be documented in the code near the initialization of the text splitter.
23
+ - The application MUST enforce a maximum token budget per chunk to prevent exceeding the LLM's context window during retrieval.
24
+ - Vector store index consistency MUST be maintained: the dimension size of the embedding model MUST exactly match the index dimension in the vector database.
25
+
26
+ ## 3. Common Anti-Patterns
27
+ The following anti-patterns highlight the most common architectural mistakes made in Python AI applications. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent blocked web servers and corrupt vector databases.
28
+
29
+ #### AP-PYAI-01: Blocking the Async Event Loop
30
+ **What it is**: Executing synchronous, long-running CPU or I/O operations directly within an `async def` FastAPI route.
31
+ **Detection signal**: Use of `requests.get()`, `time.sleep()`, or synchronous database calls inside a route defined with `async def`.
32
+ **Consequence**: The ASGI server (e.g., Uvicorn) event loop is blocked, causing the server to hang and fail to process concurrent requests.
33
+ **Correct alternative**: Run blocking operations in a thread pool using `asyncio.get_running_loop().run_in_executor()`, or define the FastAPI route as a standard synchronous `def`.
34
+
35
+ #### AP-PYAI-02: Missing Embedding Dimension Checks
36
+ **What it is**: Initializing a vector database client without verifying that the configured embedding dimensions match the model being used.
37
+ **Detection signal**: A Pinecone or Qdrant index is initialized using a hardcoded dimension size that is completely detached from the embedding model's configuration.
38
+ **Consequence**: Upserting vectors will silently fail or crash at runtime because the vector size generated by the model (e.g., 1536) does not match the database index size (e.g., 384).
39
+ **Correct alternative**: Abstract the embedding configuration into a single source of truth that configures both the model and the index initialization.
40
+
41
+ #### AP-PYAI-03: Hardcoded API Keys
42
+ **What it is**: Instantiating AI clients with string literals containing actual API keys.
43
+ **Detection signal**: `client = OpenAI(api_key="sk-...")` found in source code.
44
+ **Consequence**: Critical security vulnerability if the code is committed to version control.
45
+ **Correct alternative**: Rely on environment variables and validate them at startup using a `pydantic_settings.BaseSettings` class.
46
+
47
+ ## 4. Audit Checklist
48
+ An auditor MUST verify the following items when reviewing a Python AI codebase. Failure to check these items may result in unresponsive endpoints, security vulnerabilities, or silent data corruption in vector stores.
49
+ - [ ] No synchronous blocking calls exist inside `async def` routes without thread pool execution.
50
+ - [ ] AI framework dependencies (LangChain, LlamaIndex) are pinned to exact versions.
51
+ - [ ] No API keys are hardcoded in the codebase.
52
+ - [ ] Environment variables are managed using `pydantic-settings`.
53
+ - [ ] Pydantic v2 `model_validator` and `field_validator` are used instead of legacy v1 validators.
54
+ - [ ] Embedding model versions are explicitly declared and pinned.
55
+ - [ ] All functions and methods contain complete type annotations without bare `Any`.
56
+
57
+ ## 5. Useful References
58
+ The following resources provide authoritative guidance on building robust and asynchronous AI applications in Python. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions regarding FastAPI event loops or Pydantic validation. Ensuring the application adheres to these best practices prevents subtle bugs in high-traffic endpoints.
59
+ - [FastAPI: Concurrency and async / await](https://fastapi.tiangolo.com/async/): Detailed explanation of when to use `def` vs `async def` for route handlers.
60
+ - [Pydantic V2 Migration Guide](https://docs.pydantic.dev/latest/migration/): Documentation on the syntax and performance improvements of Pydantic V2 over V1.
61
+ - [LangChain Documentation](https://python.langchain.com/docs/get_started/introduction): The official guide for LangChain concepts and integrations.
62
+ - [OpenAI API Reference](https://platform.openai.com/docs/api-reference): Official documentation for the OpenAI SDK, including error handling and retry mechanisms.
@@ -0,0 +1,57 @@
1
+ # Stack Pack: Rust Backend
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for Rust backend applications. An auditor MUST verify that `Cargo.toml` files comply with these versions to prevent compilation failures and dependency conflicts. Keeping the Rust toolchain updated is essential for benefiting from the latest safety features and borrow checker improvements.
5
+
6
+ | Technology | Minimum Version | Required Dependencies | Incompatible With |
7
+ |---|---|---|---|
8
+ | Rust (Edition) | 2021 | None | Pre-2018 editions |
9
+ | Tokio | 1.0.0 | `features = ["full"]` for servers | Sync-only runtimes |
10
+ | Axum (or Actix) | 0.7.0 | `tokio` | Synchronous blocking code |
11
+
12
+ ## 2. Architecture Rules
13
+ These rules define the structural boundaries and memory patterns of a Rust backend. The codebase MUST adhere strictly to these constraints to ensure memory safety, concurrency, and maximum performance. Violating these constraints often results in deadlocks, memory churn, or blocked executors.
14
+
15
+ - **Error Type Discipline**: The application MUST differentiate between library errors and application errors. Use the `thiserror` crate for defining domain/library-level error enums, and use the `anyhow` crate for application-level error handling (e.g., in `main()` or generic request handlers where the exact error type is opaque).
16
+ - **No Panics in Production**: The application MUST NOT use `.unwrap()` or `.expect()` in request handling paths or business logic. All `Result` and `Option` types MUST be propagated using the `?` operator or handled explicitly via `match`.
17
+ - **Concurrent State Management**: For shared mutable state, the application MUST prefer `DashMap` (from the `dashmap` crate) over `Arc<Mutex<HashMap>>` for high-concurrency maps, as `DashMap` shards the locks and prevents global bottlenecks. For simple values, `Arc<RwLock<T>>` is preferred over `Mutex` if reads vastly outnumber writes.
18
+ - **Connection Pool Sizing**: Database connections (e.g., using `sqlx`) MUST use a connection pool (like `PgPool`). The pool's `max_connections` MUST be explicitly configured based on the expected worker thread count and database limits.
19
+ - **WASM Compilation Constraints**: If the Rust application is intended to be compiled to WebAssembly (e.g., using `wasm-bindgen`), the codebase MUST NOT rely on standard library features that are unavailable in the `wasm32-unknown-unknown` target, such as `std::fs`, `std::thread`, or blocking network sockets. All async operations must be compatible with the WASM event loop.
20
+
21
+ ## 3. Common Anti-Patterns
22
+ The following anti-patterns highlight the most common architectural mistakes made in asynchronous Rust applications. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent thread starvation and memory leaks.
23
+
24
+ #### AP-RUST-01: Blocking the Async Runtime
25
+ **What it is**: Executing long-running, CPU-bound, or synchronous I/O operations directly inside an `async fn` running on the Tokio runtime.
26
+ **Detection signal**: Use of `std::fs`, `std::thread::sleep`, heavy cryptographic hashing, or synchronous database clients (like `diesel` without `async` features) inside an `async` function.
27
+ **Consequence**: The async executor thread is blocked, preventing other async tasks from running. Under load, this causes the entire web server to stall and drop requests.
28
+ **Correct alternative**: Wrap blocking operations in `tokio::task::spawn_blocking(move || { ... })`.
29
+
30
+ #### AP-RUST-02: Unnecessary Memory Allocations
31
+ **What it is**: Repeatedly allocating heap memory (e.g., cloning `String` or `Vec`) in hot request paths when a reference or a zero-copy type could be used.
32
+ **Detection signal**: Extensive use of `.clone()`, `.to_string()`, or passing large structs by value in request handlers instead of borrowing (`&T`).
33
+ **Consequence**: High memory churn and CPU overhead from the allocator, severely reducing the maximum requests-per-second (RPS) the server can handle.
34
+ **Correct alternative**: Pass by reference where possible, use `Arc<T>` for shared read-only data to make cloning cheap, and use `Cow<'a, str>` for copy-on-write strings.
35
+
36
+ #### AP-RUST-03: Blindly Using Mutexes
37
+ **What it is**: Wrapping large, frequently accessed data structures in `std::sync::Mutex` or `tokio::sync::Mutex` without analyzing the contention.
38
+ **Detection signal**: `Arc<Mutex<AppState>>` where `AppState` is read by every request but modified rarely.
39
+ **Consequence**: Lock contention becomes the primary performance bottleneck, essentially forcing concurrent requests to execute sequentially.
40
+ **Correct alternative**: Use `tokio::sync::RwLock` for read-heavy workloads, or channel-based actor models for complex state mutations.
41
+
42
+ ## 4. Audit Checklist
43
+ An auditor MUST verify the following items when reviewing a Rust backend codebase. Failure to check these items may result in thread starvation, panics at runtime, or severe performance bottlenecks under load.
44
+ - [ ] No `std::fs` or heavy CPU-bound tasks execute directly in an `async fn` without `spawn_blocking`.
45
+ - [ ] No `.unwrap()` or `.expect()` calls exist outside of tests or application startup code.
46
+ - [ ] `thiserror` is used for domain error enums, and `anyhow` is used for generic propagation.
47
+ - [ ] High-concurrency hash maps use `DashMap` rather than `Arc<Mutex<HashMap>>`.
48
+ - [ ] Database interactions use a properly configured connection pool.
49
+ - [ ] Large structs are passed by reference or wrapped in `Arc` rather than cloned in hot paths.
50
+ - [ ] Any WASM targets do not use `std::thread` or `std::fs` modules.
51
+
52
+ ## 5. Useful References
53
+ The following resources provide authoritative guidance on building highly concurrent, safe backend systems in Rust. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions regarding the Tokio runtime, error handling, or memory management. Staying updated with these resources is critical to avoiding subtle deadlocks and concurrency bugs.
54
+ - [Tokio: CPU-bound tasks and blocking code](https://tokio.rs/tokio/tutorial/spawning#cpu-bound-tasks-and-blocking-code): Explains how to properly bridge synchronous and asynchronous code.
55
+ - [Rust API Guidelines: Error Handling](https://rust-lang.github.io/api-guidelines/interoperability.html): Best practices for designing error enums and using the `?` operator.
56
+ - [Axum Documentation](https://docs.rs/axum/latest/axum/): Comprehensive guide to routing, middleware, and request extraction in the Axum framework.
57
+ - [Rust Atomics and Locks](https://marabos.nl/atomics/): In-depth exploration of concurrency primitives and lock contention mitigation in Rust.
@@ -0,0 +1,65 @@
1
+ # Stack Pack: Next.js + Turborepo
2
+
3
+ ## 1. Version Constraint Matrix
4
+ This section defines the supported versions and compatibility requirements for Next.js, React, and Turborepo. An auditor MUST verify that all `package.json` files within the monorepo strictly comply with these ranges to prevent build failures and hydration mismatches. Ensuring that all workspaces share the same React version is critical for monorepo stability.
5
+
6
+ | Technology | Minimum Version | Required Dependencies | Incompatible With |
7
+ |---|---|---|---|
8
+ | Next.js | 14.0.0 | React 18+, Node.js 18.17+ | React < 18 |
9
+ | Turborepo | 1.11.0 | `turbo.json` config | Workspaces without explicit boundaries |
10
+ | TypeScript | 5.0.0 | `@types/react`, `@types/node` | `strict: false` in `tsconfig.json` |
11
+
12
+ ## 2. Architecture Rules
13
+ These rules define the structural boundaries of a Next.js App Router application within a Turborepo monorepo. The codebase MUST adhere strictly to these constraints to ensure correct hydration, rendering, and package isolation. Adhering to these rules prevents silent failures during static site generation and edge deployments.
14
+
15
+ - **App Router Exclusivity**: The application MUST exclusively use the App Router (`app/` directory). The Pages Router (`pages/`) MUST NOT be used alongside the App Router to prevent duplicate rendering paths and context confusion.
16
+ - **Turborepo Boundaries**: Code inside the `packages/` directory MUST NOT import anything from the `apps/` directory. Packages are independent libraries; apps consume packages, never the reverse.
17
+ - **Server and Client Directives**: Server components MUST NOT import browser-only APIs (`window`) or React hooks (`useState`). Client components MUST include the `'use client'` directive at the top. The `'use server'` directive MUST only be used at the top of a file containing server actions or inside an async function intended to be a server action; it MUST NOT be used as a general marker for server-side components.
18
+ - **TypeScript Strictness**: All `tsconfig.json` files MUST have `"strict": true` enabled. Use of `any` types in production code is prohibited.
19
+ - **Image Optimization**: The application MUST use `next/image` (`<Image />`) for all static and external images. Raw HTML `<img>` tags MUST NOT be used unless explicitly required for SVG svgr rendering or external embeds where `next/image` is unsupported.
20
+
21
+ ## 3. Common Anti-Patterns
22
+ The following anti-patterns represent the most frequent sources of performance degradation and architectural debt in Next.js applications. Auditors MUST actively scan the codebase for these specific scenarios during the S2 and S8 phases to prevent them from reaching production.
23
+
24
+ #### AP-NEXT-01: Improper Mixing of Server and Client Code
25
+ **What it is**: Passing a Server Component as a direct import into a Client Component instead of passing it as a `children` prop.
26
+ **Detection signal**: A file with `'use client'` at the top imports a component that performs server-side data fetching or uses Node.js APIs (like `fs`).
27
+ **Consequence**: The server component is forced to render on the client, exposing server-side code to the browser and increasing bundle size, or causing a runtime crash.
28
+ **Correct alternative**: Pass the server component as a React child: `<ClientWrapper><ServerComponent /></ClientWrapper>`.
29
+
30
+ #### AP-NEXT-02: Dynamic Routes Without Static Params
31
+ **What it is**: Creating dynamic routes (e.g., `[id]/page.tsx`) in a statically exported or highly cached site without providing `generateStaticParams`.
32
+ **Detection signal**: A dynamic route file `app/[slug]/page.tsx` exists, but there is no exported `generateStaticParams` function in that file.
33
+ **Consequence**: Next.js must render these pages on-demand at runtime, causing slow TTFB (Time to First Byte) and missing out on edge CDN caching.
34
+ **Correct alternative**: Export an async `generateStaticParams` function that returns an array of route parameters.
35
+
36
+ #### AP-NEXT-03: Heavy Third-Party Imports
37
+ **What it is**: Importing large, monolithic libraries (like `lodash` or `moment`) entirely into client bundles instead of using lighter alternatives or modular imports.
38
+ **Detection signal**: `import _ from 'lodash'` instead of `import get from 'lodash/get'`, or importing `moment` instead of `date-fns`.
39
+ **Consequence**: The client bundle size swells unnecessarily, leading to slow page loads and poor Core Web Vitals.
40
+ **Correct alternative**: Use modular imports (`lodash/get`), switch to modern lighter libraries (`date-fns`), or rely on native JavaScript APIs.
41
+
42
+ #### AP-NEXT-04: Broad Middleware Matchers
43
+ **What it is**: Configuring the Next.js middleware `matcher` array too broadly (e.g., matching all routes) without excluding static files or images.
44
+ **Detection signal**: A `middleware.ts` file contains a `matcher` config like `matcher: ['/:path*']` without negative lookaheads for `_next/static`, `_next/image`, and `favicon.ico`.
45
+ **Consequence**: The middleware executes on every static asset request, heavily degrading performance and increasing server costs.
46
+ **Correct alternative**: Use negative lookaheads in the matcher regex: `matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']`.
47
+
48
+ ## 4. Audit Checklist
49
+ An auditor MUST verify the following items when reviewing a Next.js + Turborepo codebase. Failure to check these items may result in severe performance issues, architectural violations, or broken builds.
50
+ - [ ] No files exist in a `pages/` directory if `app/` is being used for routing.
51
+ - [ ] No `packages/` workspace imports anything from an `apps/` workspace.
52
+ - [ ] `'use client'` is only used at the leaves of the component tree, not at the root layout.
53
+ - [ ] `'use server'` is only used for server actions, not as a component marker.
54
+ - [ ] `generateStaticParams` is implemented for dynamic routes where applicable.
55
+ - [ ] Middleware `matcher` configuration explicitly excludes static assets.
56
+ - [ ] All images use `next/image` rather than `<img>`.
57
+ - [ ] `tsconfig.json` has `"strict": true`.
58
+
59
+ ## 5. Useful References
60
+ The following resources provide authoritative guidance on building scalable applications with Next.js and Turborepo. Agents and developers MUST consult these documents when encountering ambiguous architectural decisions or when configuring advanced build caching features. Keeping up to date with these official resources ensures that the codebase does not adopt deprecated patterns or community-driven workarounds that are no longer necessary.
61
+ - [Next.js App Router Documentation](https://nextjs.org/docs/app): The primary source of truth for App Router paradigms, routing, and data fetching.
62
+ - [Turborepo Documentation](https://turbo.build/repo/docs): Guidelines for monorepo boundary configuration, caching, and task orchestration.
63
+ - [Next.js Middleware Constraints](https://nextjs.org/docs/app/building-your-application/routing/middleware): Details on Edge Runtime limitations and matcher configurations.
64
+ - [React Server Components](https://react.dev/reference/rsc/server-components): Understanding the mental model of RSCs and the serialization boundaries between server and client.
65
+ - [Next.js Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations): Best practices for securing and executing mutations on the server.
@@ -0,0 +1,24 @@
1
+ # Submission for Review
2
+ ### Task: [Task Description]
3
+
4
+ ## Context
5
+
6
+ [Provide context about the changes being submitted. Why were they made? What do they affect?]
7
+
8
+ ## Git Diff / Plan Content
9
+
10
+ [Embed the raw Git diff or the content of the plan being submitted.]
11
+ ```diff
12
+ - Old code
13
+ + New code
14
+ ```
15
+ [The diff above represents the complete scope of changes for this task. The reviewer MUST check these lines for anti-patterns.]
16
+
17
+ ## Self-Review Checklist
18
+
19
+ [The submitting agent MUST complete this checklist before requesting review.]
20
+ [Every box MUST be checked; otherwise, the submission is invalid.]
21
+ - [ ] I have verified this change does not violate the architecture.
22
+ - [ ] I have run the test suite and all tests pass.
23
+ - [ ] I have checked for any banned anti-patterns.
24
+ - [ ] I have verified there are no TODO/FIXME or simulation/mock implementations in this code.
@@ -0,0 +1,8 @@
1
+ # Task Tracker
2
+
3
+ This file tracks the execution progress of the tasks defined in the implementation plan.
4
+ The agent MUST update this file incrementally as each step is completed.
5
+
6
+ - `[ ]` [Uncompleted task]
7
+ - `[/]` [In-progress task]
8
+ - `[x]` [Completed task]