From f912278186eb7f9a2f28ba3b4ea03d3184d2e349 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sun, 29 Mar 2026 17:05:31 +0000 Subject: [PATCH] chore(audit): enforce deterministic documentation standards per CODE_OF_CONDUCT Co-authored-by: beginwebdev2002 <102213457+beginwebdev2002@users.noreply.github.com> --- .agents/rules/github-seo.md | 22 ++-- .agents/rules/project-architecture.md | 17 ++- .agents/rules/rules.md | 38 +++---- .agents/rules/system-documentation.md | 18 +-- .agents/rules/system-instruction.md | 14 ++- .gemini/commands/gen/instruction.md | 13 +++ .gemini/memory/github-seo.md | 24 ++-- .github/CODE_OF_CONDUCT.md | 62 ++++------ .github/CONTRIBUTING.md | 40 +++---- .github/LICENSE.md | 14 ++- .github/SECURITY.md | 34 +++--- .jules/rules/architecture.md | 24 ++-- .jules/rules/backend.md | 16 ++- .jules/rules/daily-content-generator.md | 21 ++-- .jules/rules/design.md | 30 +++-- .jules/rules/frontend.md | 16 ++- .jules/rules/performance.md | 28 +++-- .jules/rules/security.md | 22 ++-- .jules/rules/system-docs-manager.md | 18 +-- .jules/rules/ui-ux-design.md | 23 ++-- README.md | 52 +++------ README_AUTONOMY.md | 20 ++-- agents.md | 26 +++-- architectures/clean-architecture/data-flow.md | 15 ++- .../clean-architecture/folder-structure.md | 15 ++- .../implementation-guide.md | 15 ++- architectures/clean-architecture/readme.md | 10 +- .../clean-architecture/trade-offs.md | 15 ++- architectures/cqrs/data-flow.md | 15 ++- architectures/cqrs/folder-structure.md | 15 ++- architectures/cqrs/implementation-guide.md | 15 ++- architectures/cqrs/readme.md | 10 +- architectures/cqrs/trade-offs.md | 15 ++- .../domain-driven-design/data-flow.md | 15 ++- .../domain-driven-design/folder-structure.md | 15 ++- .../implementation-guide.md | 15 ++- architectures/domain-driven-design/readme.md | 10 +- .../domain-driven-design/trade-offs.md | 15 ++- .../event-driven-architecture/data-flow.md | 11 +- .../folder-structure.md | 11 +- .../implementation-guide.md | 37 ++++-- .../event-driven-architecture/readme.md | 12 +- .../event-driven-architecture/trade-offs.md | 11 +- .../feature-sliced-design/data-flow.md | 15 ++- .../feature-sliced-design/folder-structure.md | 15 ++- .../implementation-guide.md | 15 ++- architectures/feature-sliced-design/readme.md | 48 +------- .../feature-sliced-design/trade-offs.md | 15 ++- .../hexagonal-architecture/data-flow.md | 8 +- .../folder-structure.md | 9 +- .../implementation-guide.md | 21 +++- .../hexagonal-architecture/readme.md | 9 +- .../hexagonal-architecture/trade-offs.md | 9 +- architectures/microservices/data-flow.md | 15 ++- .../microservices/folder-structure.md | 15 ++- .../microservices/implementation-guide.md | 15 ++- architectures/microservices/readme.md | 10 +- architectures/microservices/trade-offs.md | 15 ++- .../model-view-controller/data-flow.md | 15 ++- .../model-view-controller/folder-structure.md | 15 ++- .../implementation-guide.md | 15 ++- architectures/model-view-controller/readme.md | 51 +-------- .../model-view-controller/trade-offs.md | 15 ++- .../monolithic-architecture/data-flow.md | 15 ++- .../folder-structure.md | 15 ++- .../implementation-guide.md | 15 ++- .../monolithic-architecture/readme.md | 10 +- .../monolithic-architecture/trade-offs.md | 15 ++- architectures/readme.md | 22 +--- architectures/serverless/data-flow.md | 15 ++- architectures/serverless/folder-structure.md | 15 ++- .../serverless/implementation-guide.md | 15 ++- architectures/serverless/readme.md | 10 +- architectures/serverless/trade-offs.md | 15 ++- backend/expressjs/architecture.md | 3 +- backend/expressjs/readme.md | 106 ++++++++++++++++-- backend/expressjs/security-best-practices.md | 3 +- backend/microservices/api-design.md | 3 +- backend/microservices/architecture.md | 3 +- backend/microservices/readme.md | 12 +- .../microservices/security-best-practices.md | 3 +- backend/mongodb/architecture.md | 7 +- backend/mongodb/database-optimization.md | 23 +++- backend/mongodb/readme.md | 13 +-- backend/mongodb/security-best-practices.md | 24 +++- backend/nestjs/architecture.md | 3 +- backend/nestjs/readme.md | 19 ++-- backend/nestjs/security-best-practices.md | 3 +- backend/nodejs/readme.md | 43 +++++-- backend/postgresql/architecture.md | 3 +- backend/postgresql/database-optimization.md | 3 +- backend/postgresql/readme.md | 12 +- backend/postgresql/security-best-practices.md | 3 +- backend/readme.md | 10 +- backend/redis/api-design.md | 3 +- backend/redis/architecture.md | 3 +- backend/redis/readme.md | 12 +- backend/redis/security-best-practices.md | 3 +- commit_verify.py | 1 + docs/ai-agent-orchestration-patterns.md | 18 ++- docs/ai-agent-orchestration.md | 19 ++-- docs/antigravity-ide-vibe-coding.md | 15 ++- docs/cursor-memory-structures.md | 24 ++-- docs/vibe-coding-agents.md | 20 ++-- docs/vibe-coding-zero-approval-workflows.md | 16 ++- docs/windsurf-vibe-coding-hints.md | 24 ++-- frontend/angular/advanced-performance.md | 33 +++--- frontend/angular/architecture.md | 27 +---- frontend/angular/data-forms.md | 32 ++++-- frontend/angular/expert-niche.md | 16 ++- frontend/angular/readme.md | 25 +---- frontend/angular/state-management.md | 18 +-- frontend/javascript/async-logic.md | 18 +-- frontend/javascript/modern-syntax.md | 18 +-- frontend/javascript/professional-niche.md | 17 +-- frontend/javascript/readme.md | 18 +-- frontend/qwik/readme.md | 9 +- frontend/react/performance.md | 5 +- frontend/react/readme.md | 7 +- frontend/react/state-management.md | 5 +- frontend/readme.md | 10 +- frontend/solidjs/readme.md | 9 +- frontend/typescript/logic-safety.md | 20 +--- frontend/typescript/objects-functions.md | 20 +--- frontend/typescript/professional-niche.md | 17 +-- frontend/typescript/readme.md | 36 ++---- gemini.md | 13 +++ 127 files changed, 1262 insertions(+), 959 deletions(-) create mode 100644 commit_verify.py diff --git a/.agents/rules/github-seo.md b/.agents/rules/github-seo.md index 27fca0b..55d6644 100644 --- a/.agents/rules/github-seo.md +++ b/.agents/rules/github-seo.md @@ -1,14 +1,22 @@ --- trigger: model_decision description: This document serves as the primary "Memory" and governance file for the `best-practise` repository. ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +tags: [typescript, documentation, best-practices, architecture] +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29 +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # GitHub SEO & AI-Context Master Strategy: `best-practise` It defines the standards for generating high-performance instructions optimized for both GitHub’s search algorithms and "Vibe Coding" AI tools (Cursor, Windsurf, Copilot). - --- - ## 1. Indexing Strategy & Keyword Optimization To ensure the repository ranks at the top of GitHub search results and search engines, every document must adhere to specific semantic rules. @@ -24,9 +32,7 @@ To ensure the repository ranks at the top of GitHub search results and search en - **LSI Keywords:** Naturally integrate terms like *production-ready*, *enterprise-grade*, *scalable architecture*, *clean code*, and *software design patterns*. - **Initial Context:** The first 200 characters of every file must contain the primary technology and the keyword "best practices". - **Density:** Maintain a 1-3% keyword density for the main topic to avoid "keyword stuffing" while remaining relevant to GitHub's search indexer. - --- - ## 2. Structure for AI-Context (Vibe Coding Optimization) Documentation must be structured to allow LLMs to ingest "system prompts" and "project rules" with zero ambiguity. @@ -41,9 +47,7 @@ Every file must start with a `# Context & Scope` section that defines: - **Checklists:** Use `- [ ]` for actionable verification steps. LLMs respond better to checklist-style instructions. - **Strict Constraints:** Use a `> [!IMPORTANT]` or `> [!CAUTION]` block to list "Never" and "Always" rules. - **Code Annotations:** Use comments within code blocks to explain *why* a pattern is used, not just *what* it does. - --- - ## 3. Technical Text Standard ### Tone and Style @@ -70,9 +74,7 @@ Every file must start with a `# Context & Scope` section that defines: ### Code Standards - **Naming Conventions:** Enforce `PascalCase` for classes/components, `camelCase` for functions/variables, and `kebab-case` for file names. - **Folder Structure:** Define a clear directory hierarchy (e.g., `src/features/*`, `src/shared/ui/*`). - --- - ## 4. Internal Linking Rules To build a "Knowledge Graph" within the repository, files must be cross-referenced using relative Markdown links. @@ -80,9 +82,7 @@ To build a "Knowledge Graph" within the repository, files must be cross-referenc - **Dependency Linking:** If a TypeScript guide is used, it must link to the `Architecture` guide (e.g., `[View Architecture Standards](../../architectures/fsd.md)`). - **Pattern Inheritance:** Link specialized patterns (e.g., Factory) to general programming principles (e.g., SOLID). - **Navigation:** Every sub-folder should have a `readme.md` that maps out the local files and their relationship to the repository root. - --- - ## 5. Repository Metadata ### About Section (GitHub Sidebar) diff --git a/.agents/rules/project-architecture.md b/.agents/rules/project-architecture.md index 66bffec..b3a2cc4 100644 --- a/.agents/rules/project-architecture.md +++ b/.agents/rules/project-architecture.md @@ -1,12 +1,21 @@ --- trigger: glob description: Architectural guidelines and taxonomy for navigating the Vibe Coding meta-instruction base repository. ---- +technology: Angular +domain: Documentation +level: Senior/Architect +version: Latest +tags: [angular, documentation, best-practices, architecture] +ai_role: Senior Angular Expert +last_updated: 2026-03-29 +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # Project Architecture: Context Deep-Dive This document outlines the architectural pattern of the meta-instruction base repository (Vibe Coding). The architecture is built on the "Context Deep-Dive" principle (from general to specific), ensuring predictable navigation for both developers and AI agents. - ## 1. Directory Hierarchy (The Taxonomy) The project uses a strict three-level structure: `[Root] -> [Type of Technology] -> [Technology]`. @@ -16,7 +25,6 @@ The project uses a strict three-level structure: `[Root] -> [Type of Technology] | **`[Root]`** | Repository root. Contains the global configuration and architectural rules (this file). | `/` | | **`[Type of Technology]`** | Domain categorization. Groups technologies based on their role in the system. | `frontend/`, `backend/`, `security/`, `devops/` | | **`[Technology]`** | A specific tool, framework, or methodology. Acts as a container for instruction sets. | `frontend/angular/`, `backend/mongodb/`, `architecture/fsd/` | - ## 2. Role of `readme.md` (Entry Points) The `readme.md` files act as Entry Points for AI agents at various hierarchy levels: @@ -26,7 +34,6 @@ The `readme.md` files act as Entry Points for AI agents at various hierarchy lev *(Example: `security/readme.md` describes fundamental security principles applicable to all tools within).* * **`[Technology]` Level (Tool):** The `readme.md` here is the primary entry point for a specific technology. It contains basic, global rules applied by default when working with this technology. - ## 3. Specific Modules (Specific `.md` files) To prevent the main technology `readme.md` from becoming overloaded, detailed instructions are extracted into isolated specific modules. @@ -35,7 +42,6 @@ To prevent the main technology `readme.md` from becoming overloaded, detailed in 1. The file is created within the `[Technology]` folder. 2. The filename must reflect a narrow context (e.g., `performance.md`, `testing.md`, `naming-convention.md`). 3. The module must be entirely focused on its stated topic. The AI agent will only include this file when the task overlaps with this specific context. - ## 4. AI Agent Path (Visualization) Below is a diagram of the AI agent's navigation when searching for context for a task: @@ -78,7 +84,6 @@ graph TD class B component; ``` - ## 5. Rules for Adding New Technologies When adding a new technology, contributors must follow this algorithm: diff --git a/.agents/rules/rules.md b/.agents/rules/rules.md index 33435c6..eba943d 100644 --- a/.agents/rules/rules.md +++ b/.agents/rules/rules.md @@ -1,18 +1,26 @@ --- trigger: glob globs: (frontend|backend|architectures)/**/*.md ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +tags: [typescript, documentation, best-practices, architecture] +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29 +description: Vibe coding guidelines and architectural constraints for TypeScript within the Documentation domain. +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- --- - ## 🌟 Our Pledge In the interest of fostering an open, welcoming, and safe environment, we as contributors and maintainers of the **best-practise** project pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. - --- - ## ⚖️ Our Standards In our repository dedicated to *Vibe Coding* and architectural AI instructions, we value constructive dialogue and professionalism. @@ -24,9 +32,7 @@ In our repository dedicated to *Vibe Coding* and architectural AI instructions, | 💡 Gracefully accepting constructive criticism on code or rules. | 🛑 Public or private harassment of project members. | | 🌍 Focusing on what is best for the community and accommodating for programming beginners. | 📢 Publishing others' private information without explicit permission. | | 🧠 Sharing knowledge and experience in development and AI architecture. | 🚫 Other conduct which could reasonably be considered inappropriate in a professional setting. | - --- - ## Interaction Lifecycle Interaction within the **best-practise** project is built on mutual respect and continuous improvement of AI instructions. This visual graph demonstrates the stages of healthy communication in the project: @@ -59,32 +65,28 @@ graph TD class B component; ``` - --- - ## 📝 How to Write Instructions (Best Practices) In our repository, we adhere to a unified standard for writing instructions. You can study the `frontend/typescript/readme.md` file as a reference example. Each instruction must begin with the following metadata block (YAML frontmatter): -```yaml ---- +```yaml--- technology: [Inferred Tech] domain: [Inferred Domain] level: Senior/Architect version: [Inferred Version] tags: [tag1, tag2, tag3] ai_role: [Specific Persona] -last_updated: YYYY-MM-DD ---- +last_updated: YYYY-MM-DD--- ``` Next, to describe each rule or pattern, you should use the following structure. **This structure is repeated as many times as necessary** to fully cover the topic. Here is one of the clearest and most popular examples: ### ❌ Bad Practice ```typescript -function process(data: any) { +function process(data: unknown) { console.log(data.name); // No error, but can fail at runtime } ``` @@ -103,25 +105,19 @@ function process(data: unknown) { ### 🚀 Solution Use `unknown` for values whose type is not yet determined. This obliges the developer to perform a type check before use, ensuring the safety of the data structure. - --- - ## 🛡️ Our Responsibilities Project maintainers, including the project founder **Jamoliddin Qodirov**, are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions (including AI instructions) that are not aligned with this Code of Conduct. Maintainers are also expected to explain the reasons for their moderation decisions when removing content or issuing bans. - --- - ## 🌐 Scope This Code of Conduct applies in the following scenarios: 1. Within all **best-practise** project spaces (including the GitHub repository, branches, issue discussions, and pull request comments). 2. In public spaces when an individual is representing the project or its community. Examples include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - --- - ## 🚨 Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers: @@ -138,15 +134,12 @@ Project maintainers will follow these Community Impact Guidelines in determining 2. **Warning:** A warning with consequences, such as a temporary suspension from communicating in the project or a ban on interacting with specific individuals for a set period. 3. **Temporary Ban:** A temporary ban from any interaction with the project, including creating issues and pull requests. 4. **Permanent Ban:** A complete and permanent ban from any sort of public interaction within the project for systematic, intentional, or severe violations (e.g., harassment or threats). - --- - ## 📜 Attribution This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html). Answers to common questions about this code of conduct can be found in the official [FAQ](https://www.contributor-covenant.org/faq). Translations are available at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). - --- @@ -162,5 +155,4 @@ Answers to common questions about this code of conduct can be found in the offic **Проектирование детерминированной кодовой базы для ИИ-агентов в условиях архитектурной целостности и взаимоуважения.** - --- \ No newline at end of file diff --git a/.agents/rules/system-documentation.md b/.agents/rules/system-documentation.md index 50de5ac..54786ca 100644 --- a/.agents/rules/system-documentation.md +++ b/.agents/rules/system-documentation.md @@ -1,10 +1,18 @@ --- description: Instructions for the Jules AI agent on maintaining and updating core system documentation, AI rules, and repository guidelines. tags: [system documentation, AI agent rules, documentation quality, vibe coding, github-seo, repository management, clean documentation] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⚙️ System Documentation & AI Quality Rules for Jules - ## 1. Context & Scope - **Primary Goal:** Ensure the continuous improvement and high **documentation quality** of the core system files that guide developers and AI agents. - **Target Tooling:** Jules AI agent (Vibe Coding, Automated Maintenance). @@ -15,9 +23,7 @@ tags: [system documentation, AI agent rules, documentation quality, vibe coding, **Maintaining the Machine-Readable Intelligence Layer of the repository.** - --- - ## 2. Core System Files and Directories > [!WARNING] @@ -42,9 +48,7 @@ The following files are systemic for promoting high **documentation quality** an - `.agents/rules/github-seo.md` – Search Engine Optimization and metadata structures. - `.agents/rules/project-architecture.md` – Core architectural constraints. - `.agents/rules/rules.md` & `.agents/rules/system-markdown.md` – Specific constraints enforcing clean code and high documentation searchability. - --- - ## 3. Maintenance Protocol for Jules Jules must actively sync these files whenever a new global rule is adopted. @@ -73,9 +77,7 @@ graph TD class UpdateSEO component; ``` - --- - ## 4. Documentation Quality Standards When writing or updating **system documentation**, Jules must verify the following constraints: diff --git a/.agents/rules/system-instruction.md b/.agents/rules/system-instruction.md index 31c450a..2efe283 100644 --- a/.agents/rules/system-instruction.md +++ b/.agents/rules/system-instruction.md @@ -2,10 +2,19 @@ trigger: glob description: Rules for making changes to system Markdown files in 2 languages (English/Russian). globs: "{README.md,.github/CONTRIBUTING.md,.github/SECURITY.md,.github/CODE_OF_CONDUCT.md}" ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +tags: [vibe-coding, documentation, best-practices, architecture] +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # System Markdown Files Formatting - ## Applicability These rules apply STRICTLY and EXCLUSIVELY to the following files: - `README.md` @@ -14,7 +23,6 @@ These rules apply STRICTLY and EXCLUSIVELY to the following files: - `.github/CODE_OF_CONDUCT.md` The glob pattern is configured so that it does not affect any other Markdown files in the project. - ## Core Editing Rules 1. **Bilingual Requirement**: diff --git a/.gemini/commands/gen/instruction.md b/.gemini/commands/gen/instruction.md index e69de29..a744deb 100644 --- a/.gemini/commands/gen/instruction.md +++ b/.gemini/commands/gen/instruction.md @@ -0,0 +1,13 @@ +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Documentation domain. +tags: [vibe-coding, documentation, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29--- diff --git a/.gemini/memory/github-seo.md b/.gemini/memory/github-seo.md index e2507c7..2969a26 100644 --- a/.gemini/memory/github-seo.md +++ b/.gemini/memory/github-seo.md @@ -1,9 +1,19 @@ -# GitHub SEO & AI-Context Master Strategy: `best-practise` +--- +description: Vibe coding guidelines and architectural constraints for TypeScript within the Documentation domain. +tags: [typescript, documentation, best-practices, architecture] +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29---# GitHub SEO & AI-Context Master Strategy: `best-practise` This document serves as the primary "Memory" and governance file for the `best-practise` repository. It defines the standards for generating high-performance instructions optimized for both GitHub’s search algorithms and "Vibe Coding" AI tools (Cursor, Windsurf, Copilot). - --- - ## 1. Indexing Strategy & Keyword Optimization To ensure the repository ranks at the top of GitHub search results and search engines, every document must adhere to specific semantic rules. @@ -19,9 +29,7 @@ To ensure the repository ranks at the top of GitHub search results and search en - **LSI Keywords:** Naturally integrate terms like *production-ready*, *enterprise-grade*, *scalable architecture*, *clean code*, and *software design patterns*. - **Initial Context:** The first 200 characters of every file must contain the primary technology and the keyword "best practices". - **Density:** Maintain a 1-3% keyword density for the main topic to avoid "keyword stuffing" while remaining relevant to GitHub's search indexer. - --- - ## 2. Structure for AI-Context (Vibe Coding Optimization) Documentation must be structured to allow LLMs to ingest "system prompts" and "project rules" with zero ambiguity. @@ -36,9 +44,7 @@ Every file must start with a `# Context & Scope` section that defines: - **Checklists:** Use `- [ ]` for actionable verification steps. LLMs respond better to checklist-style instructions. - **Strict Constraints:** Use a `> [!IMPORTANT]` or `> [!CAUTION]` block to list "Never" and "Always" rules. - **Code Annotations:** Use comments within code blocks to explain *why* a pattern is used, not just *what* it does. - --- - ## 3. Technical Text Standard ### Tone and Style @@ -65,9 +71,7 @@ Every file must start with a `# Context & Scope` section that defines: ### Code Standards - **Naming Conventions:** Enforce `PascalCase` for classes/components, `camelCase` for functions/variables, and `kebab-case` for file names. - **Folder Structure:** Define a clear directory hierarchy (e.g., `src/features/*`, `src/shared/ui/*`). - --- - ## 4. Internal Linking Rules To build a "Knowledge Graph" within the repository, files must be cross-referenced using relative Markdown links. @@ -75,9 +79,7 @@ To build a "Knowledge Graph" within the repository, files must be cross-referenc - **Dependency Linking:** If a TypeScript guide is used, it must link to the `Architecture` guide (e.g., `[View Architecture Standards](../../architectures/fsd.md)`). - **Pattern Inheritance:** Link specialized patterns (e.g., Factory) to general programming principles (e.g., SOLID). - **Navigation:** Every sub-folder should have a `readme.md` that maps out the local files and their relationship to the repository root. - --- - ## 5. Repository Metadata ### About Section (GitHub Sidebar) diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md index aa2f955..9b93844 100644 --- a/.github/CODE_OF_CONDUCT.md +++ b/.github/CODE_OF_CONDUCT.md @@ -1,3 +1,16 @@ +--- +description: Vibe coding guidelines and architectural constraints for TypeScript within the Documentation domain. +tags: [typescript, documentation, best-practices, architecture] +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29--- [ 🇺🇸 English ](#english) | [ 🇷🇺 Русский ](#russian) @@ -13,17 +26,13 @@ **Building the best codebase for AI agents together in a respectful and inclusive environment.** - --- - ## 🌟 Our Pledge In the interest of fostering an open, welcoming, and safe environment, we as contributors and maintainers of the **best-practise** project pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. - --- - ## ⚖️ Our Standards In our repository dedicated to *Vibe Coding* and architectural AI instructions, we value constructive dialogue and professionalism. @@ -35,9 +44,7 @@ In our repository dedicated to *Vibe Coding* and architectural AI instructions, | 💡 Gracefully accepting constructive criticism on code or rules. | 🛑 Public or private harassment of project members. | | 🌍 Focusing on what is best for the community and accommodating for programming beginners. | 📢 Publishing others' private information without explicit permission. | | 🧠 Sharing knowledge and experience in development and AI architecture. | 🚫 Other conduct which could reasonably be considered inappropriate in a professional setting. | - --- - ## Interaction Lifecycle Interaction within the **best-practise** project is built on mutual respect and continuous improvement of AI instructions. This visual graph demonstrates the stages of healthy communication in the project: @@ -70,32 +77,28 @@ graph TD class B component; ``` - --- - ## 📝 How to Write Instructions (Best Practices) In our repository, we adhere to a unified standard for writing instructions. You can study the `frontend/typescript/readme.md` file as a reference example. Each instruction must begin with the following metadata block (YAML frontmatter): -```yaml ---- +```yaml--- technology: [Inferred Tech] domain: [Inferred Domain] level: Senior/Architect version: [Inferred Version] tags: [tag1, tag2, tag3] ai_role: [Specific Persona] -last_updated: YYYY-MM-DD ---- +last_updated: YYYY-MM-DD--- ``` Next, to describe each rule or pattern, you should use the following structure. **This structure is repeated as many times as necessary** to fully cover the topic. Here is one of the clearest and most popular examples: ### ❌ Bad Practice ```typescript -function process(data: any) { +function process(data: unknown) { console.log(data.name); // No error, but can fail at runtime } ``` @@ -114,25 +117,19 @@ function process(data: unknown) { ### 🚀 Solution Use `unknown` for values whose type is not yet determined. This obliges the developer to perform a type check before use, ensuring the safety of the data structure. - --- - ## 🛡️ Our Responsibilities Project maintainers, including the project founder **Jamoliddin Qodirov**, are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions (including AI instructions) that are not aligned with this Code of Conduct. Maintainers are also expected to explain the reasons for their moderation decisions when removing content or issuing bans. - --- - ## 🌐 Scope This Code of Conduct applies in the following scenarios: 1. Within all **best-practise** project spaces (including the GitHub repository, branches, issue discussions, and pull request comments). 2. In public spaces when an individual is representing the project or its community. Examples include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - --- - ## 🚨 Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers: @@ -149,15 +146,12 @@ Project maintainers will follow these Community Impact Guidelines in determining 2. **Warning:** A warning with consequences, such as a temporary suspension from communicating in the project or a ban on interacting with specific individuals for a set period. 3. **Temporary Ban:** A temporary ban from any interaction with the project, including creating issues and pull requests. 4. **Permanent Ban:** A complete and permanent ban from any sort of public interaction within the project for systematic, intentional, or severe violations (e.g., harassment or threats). - --- - ## 📜 Attribution This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html). Answers to common questions about this code of conduct can be found in the official [FAQ](https://www.contributor-covenant.org/faq). Translations are available at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). - --- @@ -173,17 +167,13 @@ Answers to common questions about this code of conduct can be found in the offic **Проектирование детерминированной кодовой базы для ИИ-агентов в условиях архитектурной целостности и взаимоуважения.** - --- - ## 🌟 Наши Обязательства В целях поддержания надежной и безопасной среды разработки, контрибьюторы и мейнтейнеры **best-practise** обязуются обеспечивать рабочую атмосферу, свободную от харассмента. Правило распространяется на всех участников, независимо от возраста, уровня инженерной подготовки, гендерной или этнической принадлежности, инвалидности, внешности, религии и социо-экономического статуса. Мы гарантируем следование принципам инклюзивного, профессионального и технологически сфокусированного инженерного комьюнити. - --- - ## ⚖️ Стандарты Взаимодействия В репозитории, ядром которого выступают *Vibe Coding* и строгие архитектурные ИИ-инструкции, фундаментальным приоритетом является конструктивный инженерный диалог. @@ -195,9 +185,7 @@ Answers to common questions about this code of conduct can be found in the offic | 💡 Профессиональная обработка обратной связи в рамках Code Review и обсуждения архитектуры. | 🛑 Харассмент мейнтейнеров или участников проекта. | | 🌍 Фокус на архитектурной целостности системы и адаптации контекста для начинающих. | 📢 Деанонимизация (Doxing) и публикация приватных данных без явного согласия. | | 🧠 Распространение паттернов разработки и экспертизы в AI Context Engineering. | 🚫 Любой паттерн поведения, нарушающий стандарты профессиональной этики. | - --- - ## Жизненный Цикл Взаимодействия Жизненный цикл интеграции в **best-practise** базируется на взаимоуважении и детерминированном подходе к улучшению ИИ-инструкций (AI Context Injection). Архитектура здоровой коммуникации описана ниже: @@ -230,32 +218,28 @@ graph TD class B component; ``` - --- - ## 📝 Форматирование Инструкций (Best Practices) В репозитории утвержден строгий архитектурный стандарт формирования ИИ-инструкций. В качестве эталонной имплементации (Reference Implementation) изучите `frontend/typescript/readme.md`. Каждый документ обязан внедрять метаданные (YAML frontmatter) для маршрутизации контекста: -```yaml ---- +```yaml--- technology: [Inferred Tech] domain: [Inferred Domain] level: Senior/Architect version: [Inferred Version] tags: [tag1, tag2, tag3] ai_role: [Specific Persona] -last_updated: YYYY-MM-DD ---- +last_updated: YYYY-MM-DD--- ``` Для документирования каждого паттерна или Constraints (Ограничения) применяется следующий регламент. **Паттерн тиражируется столько раз, сколько необходимо** для покрытия домена. Пример стандартизации типов: ### ❌ Bad Practice ```typescript -function process(data: any) { +function process(data: unknown) { console.log(data.name); // Отсутствие статического анализа, риск Runtime Exception } ``` @@ -274,25 +258,19 @@ function process(data: unknown) { ### 🚀 Solution Имплементация `unknown` для нетипизированных структур данных форсирует явные проверки типов (Type Guards). Подход гарантирует детерминированную валидацию контракта. - --- - ## 🛡️ Зона Ответственности Мейнтейнеры проекта, включая системного архитектора **Jamoliddin Qodirov**, несут ответственность за поддержание стандартов инженерной культуры. Они обязаны применять соразмерные корректирующие протоколы в случае инцидентов. Команда обладает эксклюзивной авторизацией на удаление, ревью и блокировку комментариев, коммитов, веток (Branches), участков кода и артефактов (включая инструкции), противоречащих Code of Conduct. Мейнтейнеры аргументируют архитектурные и модерационные решения при вынесении банов. - --- - ## 🌐 Scope (Область Действия) Регламент валиден в следующих контурах: 1. Во всем пространстве **best-practise** (репозиторий GitHub, Branches, Issues, Pull Requests). 2. В публичном поле при позиционировании лица как представителя проекта. Включая использование официальных e-mail, публикацию через корпоративные аккаунты или присутствие на отраслевых ивентах. - --- - ## 🚨 Модерация и Санкции При детекции харассмента, токсичного поведения или иных инцидентов инициируйте эскалацию: @@ -309,9 +287,7 @@ function process(data: unknown) { 2. **Предупреждение (Warning):** Жесткое предупреждение с временным ограничением прав (например, запрет на коммуникацию в репозитории на N дней). 3. **Временная Блокировка (Temporary Ban):** Заморозка всех прав инженера на взаимодействие с проектом (запрет Pull Requests и Issues). 4. **Перманентная Блокировка (Permanent Ban):** Необратимое отлучение от проекта. Применяется за системные сбои в соблюдении Code of Conduct или критические нарушения (харассмент, доксинг, угрозы безопасности). - --- - ## 📜 Атрибуция Спецификация Code of Conduct адаптирована из [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, исходник: [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html). diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index dcc0b64..ac03459 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,3 +1,16 @@ +--- +description: Vibe coding guidelines and architectural constraints for Angular within the Documentation domain. +tags: [angular, documentation, best-practices, architecture] +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Angular +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Angular Expert +last_updated: 2026-03-29--- [ 🇺🇸 English ](#english) | [ 🇷🇺 Русский ](#russian) @@ -10,9 +23,7 @@ [![Security: Active](https://img.shields.io/badge/Security-Active-brightgreen?style=for-the-badge&logo=springsecurity)](#) [![Vibe-Coding Protected](https://img.shields.io/badge/Vibe--Coding-Protected-blue?style=for-the-badge&logo=shield)](#) - --- - ## 🔄 The Contribution Lifecycle We engineer context. The process of contributing meta-instructions must be as rigorous as the software architectures we define. Follow this lifecycle without deviation. @@ -36,9 +47,7 @@ stateDiagram-v2 classDef layout fill:#f3e5f5,stroke:#9c27b0,stroke-width:2px,color:#000; ``` - --- - ## 🧠 Writing Standards for AI Context (The Spec) AI Agents (Cursor, Windsurf, Antigravity) do not need conversational prose; they need high-density, analytical directives. @@ -63,9 +72,7 @@ Every instruction must target its exact technical domain. Tag your docs logicall > [!NOTE] > **Mermaid Diagrams are Mandatory:** Any architectural pattern, data flow, or state machine rule that involves more than two entities **must** be accompanied by a Mermaid diagram. AI models parse explicit structural limits significantly better when visualized in markdown. - --- - ## 🚀 Step-by-Step Workflow Execute your contributions using the following pipeline: @@ -77,9 +84,7 @@ Execute your contributions using the following pipeline: * Enforce analytical tone. Use Markdown Tables for rulesheets. Use Task Lists for sequential operations. 3. 🧪 **Verification (The Vibe Coding Test)**: * **Mandatory**: You must pass the target instruction into Cursor, Windsurf, or Antigravity and verify the output. If the agent generates hallucinated or sub-standard code, the instruction is flawed. Fix it before submitting. - --- - ## 🏗️ Repository Architecture Our structure is absolute. We isolate context by domain and technology to prevent AI context pollution. @@ -94,9 +99,7 @@ Our structure is absolute. We isolate context by domain and technology to preven > [!TIP] > Do not scatter configuration instructions. If a domain or technology doesn't exist, create it, but it **must** contain a `readme.md`. - --- - ## 📜 Commit Convention We run automated semver and changelogs. Unstructured commits break automation and will be rejected. Use [Conventional Commits](https://www.conventionalcommits.org/). @@ -113,9 +116,7 @@ We run automated semver and changelogs. Unstructured commits break automation an ```bash feat(backend): implement NestJS strategy pattern instructions ``` - --- - ## 🛡️ The Pull Request Gate Copy and paste this checklist into your PR description. Do not request an architectural review until every box is checked. @@ -128,11 +129,9 @@ Copy and paste this checklist into your PR description. Do not request an archit - [ ] Language is zero-fluff, analytical, and highly technical. - [ ] Proven via the "Vibe Coding Test" (AI execution output/proof included below). ``` - --- *We engineer the intelligence that engineers the code. Execute with precision.* - --- @@ -145,9 +144,7 @@ Copy and paste this checklist into your PR description. Do not request an archit [![Security: Active](https://img.shields.io/badge/Security-Active-brightgreen?style=for-the-badge&logo=springsecurity)](#) [![Vibe-Coding Protected](https://img.shields.io/badge/Vibe--Coding-Protected-blue?style=for-the-badge&logo=shield)](#) - --- - ## 🔄 Жизненный цикл контрибьютора Мы проектируем контекст. Процесс внесения мета-инструкций должен быть таким же строгим, как и архитектура программного обеспечения, которую мы определяем. Следуйте этому жизненному циклу без отклонений. @@ -171,9 +168,7 @@ stateDiagram-v2 classDef layout fill:#f3e5f5,stroke:#9c27b0,stroke-width:2px,color:#000; ``` - --- - ## 🧠 Стандарты написания контекста для ИИ (Спецификация) ИИ-агентам (Cursor, Windsurf, Antigravity) не нужна разговорная проза; им нужны высокоплотные, аналитические директивы. @@ -198,9 +193,7 @@ stateDiagram-v2 > [!NOTE] > **Диаграммы Mermaid обязательны:** Любой архитектурный паттерн, поток данных (Data Flow) или правило конечного автомата, включающее более двух сущностей, **обязаны** сопровождаться диаграммой Mermaid. Модели ИИ значительно лучше понимают явные структурные ограничения при их визуализации в Markdown. - --- - ## 🚀 Пошаговый Workflow (Рабочий процесс) Вносите свой вклад, используя следующий пайплайн: @@ -212,9 +205,7 @@ stateDiagram-v2 * Придерживайтесь аналитического тона. Используйте таблицы Markdown для свода правил. Используйте списки задач (Task Lists) для последовательных операций. 3. 🧪 **Верификация (Vibe Coding Test)**: * **Обязательно**: Вы должны передать целевую инструкцию в Cursor, Windsurf или Antigravity и проверить результат. Если агент генерирует галлюцинации или нестандартный код, инструкция ошибочна. Исправьте её перед отправкой (PR). - --- - ## 🏗️ Архитектура репозитория Наша структура абсолютна. Мы изолируем контекст по доменам и технологиям, чтобы предотвратить "загрязнение" контекста для ИИ (AI context pollution). @@ -229,9 +220,7 @@ stateDiagram-v2 > [!TIP] > Не разбрасывайте инструкции по настройке. Если домен или технология еще не существует, создайте их, но в директории **обязан** быть файл `readme.md`. - --- - ## 📜 Соглашения о коммитах (Commit Convention) Мы используем автоматизированное семантическое версионирование (semver) и генерацию Changelog. Неструктурированные коммиты ломают автоматизацию и будут отклонены. Используйте [Conventional Commits](https://www.conventionalcommits.org/). @@ -248,9 +237,7 @@ stateDiagram-v2 ```bash feat(backend): implement NestJS strategy pattern instructions ``` - --- - ## 🛡️ Врата Pull Request (PR Gate) Скопируйте и вставьте этот чек-лист в описание вашего PR. Не запрашивайте архитектурное ревью, пока не будут отмечены все пункты. @@ -263,7 +250,6 @@ feat(backend): implement NestJS strategy pattern instructions - [ ] Язык без "воды", аналитичный и высокотехничный. - [ ] Доказано через "Vibe Coding Test" (вывод ИИ-агента или доказательство успешного тестирования прикреплено ниже). ``` - --- *Мы проектируем интеллект, который проектирует код. Работайте с точностью.* diff --git a/.github/LICENSE.md b/.github/LICENSE.md index b236828..870b2dc 100644 --- a/.github/LICENSE.md +++ b/.github/LICENSE.md @@ -1,10 +1,22 @@ +--- +description: Vibe coding guidelines and architectural constraints for Express within the Documentation domain. +tags: [express, documentation, best-practices, architecture] +topic: Express +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Express +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Express Expert +last_updated: 2026-03-29--- # Quick Summary (License Summary) **In Plain English:** - ✅ **Use and Modification:** You are free to use, modify, and distribute these instructions for any purpose. - 🔄 **Copyleft:** If you distribute modifications, you **MUST** do so under this same license (GPL-3.0) for free. - ⚠️ **Disclaimer:** All materials are provided "as is." The author assumes no liability for the use of these instructions. - --- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 8c9eb30..6f303ac 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,3 +1,16 @@ +--- +description: Vibe coding guidelines and architectural constraints for NestJS within the Documentation domain. +tags: [nestjs, documentation, best-practices, architecture] +topic: NestJS +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: NestJS +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior NestJS Expert +last_updated: 2026-03-29--- [ 🇺🇸 English ](#english) | [ 🇷🇺 Русский ](#russian) @@ -14,9 +27,7 @@ Welcome to the official security policy for the **best-practise** project. Our goal is to ensure the maximum security and reliability of meta-instructions (Vibe Coding) for AI agents (Cursor, Windsurf, Copilot, Antigravity, Aider). Since this repository serves as an "AI Knowledge Base," our security model differs from traditional software development projects. - --- - ## 📅 Supported Versions We actively support and update only the latest major versions of our architectural and technological rules. @@ -26,9 +37,7 @@ We actively support and update only the latest major versions of our architectur | **`main` (Current)** | ✅ Supported | | | **`v1.x`** | ❌ Unsupported | | | **Legacy Branches / PRs** | ❌ Unsupported | | - --- - ## 🚨 Reporting a Vulnerability Please **DO NOT create public issues** if you discover a critical vulnerability or potentially dangerous AI instructions in the repository (e.g., instructions that open backdoors via agents). @@ -40,9 +49,7 @@ Please **DO NOT create public issues** if you discover a critical vulnerability 4. Attach a Proof of Concept (PoC prompt) if possible, demonstrating the exploitation of the "flawed" rule in Cursor or Windsurf. We are committed to acknowledging your report within **48 hours** and providing a remediation plan. - --- - ## 🤖 AI Security Context This project focuses on Context Injection. Therefore, we classify threats specifically for LLMs and agentic IDEs: @@ -59,9 +66,7 @@ This project focuses on Context Injection. Therefore, we classify threats specif | 🟠 **High** | Recommendations grossly violating basic security principles (e.g., `eval`, unvalidated `innerHTML` in Frontend rules). | **P1** | | 🟡 **Medium** | Instructions leading to the creation of logical bugs (Bad Smells, Race conditions) in the agent-generated code. | **P2** | | 🟢 **Low** | Typos in linters, broken or outdated minor style rules. | **P3** | - --- - ## 🔄 Incident Response Lifecycle Below is a visual flowchart of our standard process for handling discovered threats in meta-instructions: @@ -97,9 +102,7 @@ graph TD class B component; ``` - --- - ## 🛡️ Best Practices for Contributors If you propose new instructions or architectural standards (via PR), strictly adhere to the security rules: @@ -112,7 +115,6 @@ If you propose new instructions or architectural standards (via PR), strictly ad
Thank you for contributing to the security and quality of AI-driven development (Vibe Coding)! 🚀
- --- @@ -128,9 +130,7 @@ If you propose new instructions or architectural standards (via PR), strictly ad Добро пожаловать в официальную политику безопасности репозитория **best-practise**. Наша задача — гарантировать максимальную безопасность и стабильность мета-инструкций (Vibe Coding) для ИИ-агентов (Cursor, Windsurf, Copilot, Antigravity, Aider). Поскольку данный репозиторий выступает «Базой знаний ИИ» (AI Knowledge Base), наша модель безопасности имеет существенные отличия от классических проектов разработки программного обеспечения. - --- - ## 📅 Supported Versions Мы осуществляем поддержку и апдейт исключительно последних мажорных версий архитектурных и технологических стандартов. @@ -140,9 +140,7 @@ If you propose new instructions or architectural standards (via PR), strictly ad | **`main` (Current)** | ✅ Поддерживается | | | **`v1.x`** | ❌ Не поддерживается | | | **Legacy Branches / PRs** | ❌ Не поддерживается | | - --- - ## 🚨 Reporting a Vulnerability **ЗАПРЕЩАЕТСЯ создавать публичные Issue** при обнаружении критической уязвимости или деструктивных инструкций для ИИ (например, инструкций, провоцирующих внедрение бэкдоров силами агентов). @@ -154,9 +152,7 @@ If you propose new instructions or architectural standards (via PR), strictly ad 4. Предоставьте Proof of Concept (PoC prompt), демонстрирующий эксплуатацию дефектного правила в Cursor или Windsurf. Мы обязуемся подтвердить получение репорта в течение **48 часов** с предоставлением плана митигации. - --- - ## 🤖 AI Security Context Ядром проекта является AI Context Injection. В связи с этим классификация угроз адаптирована под специфику LLM и агентных IDE: @@ -173,9 +169,7 @@ If you propose new instructions or architectural standards (via PR), strictly ad | 🟠 **High** | Рекомендации, критически нарушающие фундаментальные принципы безопасности (использование `eval`, отсутствие санации `innerHTML` в правилах Frontend). | **P1** | | 🟡 **Medium** | Инструкции, провоцирующие возникновение логических дефектов (Bad Smells, Race conditions) в коде, сгенерированном агентом. | **P2** | | 🟢 **Low** | Ошибки конфигурации линтеров, нерабочие или устаревшие минорные правила стилизации. | **P3** | - --- - ## 🔄 Incident Response Lifecycle Формализованный процесс обработки обнаруженных угроз в мета-инструкциях представлен на схеме: @@ -211,9 +205,7 @@ graph TD class B component; ``` - --- - ## 🛡️ Best Practices for Contributors При контрибьюции новых инструкций или архитектурных стандартов (через Pull Request) требуется неукоснительное следование правилам безопасности: diff --git a/.jules/rules/architecture.md b/.jules/rules/architecture.md index a70a86e..0607ecd 100644 --- a/.jules/rules/architecture.md +++ b/.jules/rules/architecture.md @@ -1,10 +1,18 @@ --- description: Key instructions for Jules regarding enterprise system architectures: Clean Architecture, Microservices, MVC, CQRS. tags: [software architecture, system design, enterprise patterns, production-ready, scalable architecture, clean code, hexagonal-architecture, microservices] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🏗️ System Design & Enterprise Architecture Rules for Jules - ## 1. Context & Scope - **Primary Goal:** Ensure the implementation of **software architecture** and **system design** standards to construct **scalable architecture** and write **production-ready** code. - **Target Tooling:** Jules AI agent (Vibe Coding). @@ -13,9 +21,7 @@ tags: [software architecture, system design, enterprise patterns, production-rea
Architecture Overview
- --- - ## 2. Architecture Generation Instructions When the User requests a new service or module, Jules must first rely on these **enterprise patterns**. @@ -32,8 +38,8 @@ graph TD Adapters --> Logic[Business Use Cases] Logic --> Domain[Domain Entities] - style Domain fill:#4caf50,stroke:#388e3c,stroke-width:2px,color:#fff - style Logic fill:#2196f3,stroke:#1976d2,stroke-width:2px,color:#fff + class Domain auto_style_Domain + class Logic auto_style_Logic %% Added Design Token Styles for Mermaid Diagrams classDef default fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000; classDef component fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000; @@ -42,6 +48,10 @@ graph TD class UI component; class Adapters component; + + %% Auto-generated Design Tokens + classDef auto_style_Domain fill:#4caf50,stroke:#388e3c,stroke-width:2px,color:#fff + classDef auto_style_Logic fill:#2196f3,stroke:#1976d2,stroke-width:2px,color:#fff ``` ### Architecture Comparison for Selection @@ -52,9 +62,7 @@ graph TD | **Microservices** | Large enterprise systems | Services must only communicate through Application Programming Interfaces (API) or Event systems. | | **Clean Architecture** | Complex business rules and logic | Dependencies must only point inward toward the core Domain. | | **CQRS** | Systems with very high read traffic | Separate the methods that write data (Command) from the methods that read data (Query). | - --- - ## 3. Checklist for Jules Agent When starting a new feature: diff --git a/.jules/rules/backend.md b/.jules/rules/backend.md index 4f4e8e0..1287a78 100644 --- a/.jules/rules/backend.md +++ b/.jules/rules/backend.md @@ -1,10 +1,18 @@ --- description: Instructions for the Jules AI agent regarding backend code. Contains rules for server architecture, DTO standards, and SEO metadata. tags: [backend architecture, clean APIs, scalable server, typescript best practices, production-ready, enterprise-grade, node-js, nestjs, expressjs] ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29 +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🛡️ Backend Architecture & Clean APIs Rules for Jules - ## 1. Context & Scope - **Primary Goal:** Ensure the implementation of best practices for the backend part of the project. Establish standards for **scalable server** deployments, **clean APIs**, and **enterprise-grade** solutions. - **Target Tooling:** Jules AI agent (Vibe Coding, AI-Driven Development). @@ -16,9 +24,7 @@ tags: [backend architecture, clean APIs, scalable server, typescript best practi **Standards for creating production-ready backend systems.** - --- - ## 2. Key Architecture Rules (Backend Architecture) > [!CAUTION] @@ -51,9 +57,7 @@ sequenceDiagram Service-->>Controller: DTO returned Controller-->>Client: HTTP Response sent ``` - --- - ## 3. Code Writing Requirements for Jules - [ ] **Isolation:** Every feature must have its own separate Module, Controller, Service, and DTO. diff --git a/.jules/rules/daily-content-generator.md b/.jules/rules/daily-content-generator.md index 8429592..f59784b 100644 --- a/.jules/rules/daily-content-generator.md +++ b/.jules/rules/daily-content-generator.md @@ -1,10 +1,18 @@ --- description: Instructions for Jules on the daily generation of new, relevant, and highly-discussed articles and technical documentation. tags: [AI Agents documentation, trending tech docs, daily technical writing, software engineering trends, vibe coding, developer experience] ---- +technology: React +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior React Expert +last_updated: 2026-03-29 +topic: React +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 📅 Daily Technical Writing & Trend Generation for Jules - ## 1. Context & Scope - **Primary Goal:** Ensure a daily stream of new, relevant **trending tech docs** covering interesting topics such as Frontend, Backend, Architecture, and AI Agents. - **Target Tooling:** Autonomous operation mode for the Jules AI agent. @@ -14,9 +22,7 @@ tags: [AI Agents documentation, trending tech docs, daily technical writing, sof **Generative content creation for leadership in the Software Engineering field.** - --- - ## 2. Daily Research Instructions (Daily Routine) > [!IMPORTANT] @@ -31,7 +37,7 @@ graph LR C --> D[Apply SEO Optimization] D --> E[Add to /docs/ folder] - style C fill:#ff9800,stroke:#f57c00,stroke-width:2px,color:#fff + class C auto_style_C %% Added Design Token Styles for Mermaid Diagrams classDef default fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000; classDef component fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000; @@ -41,6 +47,9 @@ graph LR class E component; class D component; + + %% Auto-generated Design Tokens + classDef auto_style_C fill:#ff9800,stroke:#f57c00,stroke-width:2px,color:#fff ``` ### Interest Areas for Generation @@ -53,9 +62,7 @@ Every day, select **one** of the following categories and write a deep, engaging | **Backend** | Database scaling, Serverless configuration techniques, Rust in Backend | "Deep Dive into Vercel Edge", "Prisma Database Optimization" | | **Architecture** | System fault tolerance, Event-Driven Patterns, System Design | "Saga Pattern in Node.js", "Mastering Apache Kafka" | | **AI Agents** | AI integration in coding, Optimizing Context Window size | "Windsurf advanced usage hints", "Cursor memory structures" | - --- - ## 3. Criteria for a Successful Article (SEO Optimization and Visuals) - [ ] **High-Value Headings (H1/H2):** Section titles must attract attention and contain relevant Latent Semantic Indexing (LSI) keywords (associated search terms). diff --git a/.jules/rules/design.md b/.jules/rules/design.md index 281fcc5..0112490 100644 --- a/.jules/rules/design.md +++ b/.jules/rules/design.md @@ -1,5 +1,16 @@ -# 🎨 UI/UX Design & Styling Rules for Jules - +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Documentation domain. +tags: [vibe-coding, documentation, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29---# 🎨 UI/UX Design & Styling Rules for Jules ## 1. Context & Scope - **Primary Goal:** Maintain a consistent, **accessible (a11y)**, and visually appealing user interface across all applications through strict **responsive design** practices. - **Target Tooling:** Jules AI agent (UI Generation & CSS Audits). @@ -8,9 +19,7 @@
Design Overview
- --- - ## 2. Design System & Styling Rules > [!CAUTION] @@ -33,9 +42,9 @@ graph TD Elements --> Components[Complex Components: Cards, Modals] Components --> Layouts[Page Layouts: Grids, Sections] - style Tokens fill:#f3e5f5,stroke:#9c27b0,stroke-width:2px,color:#000 - style Elements fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000 - style Components fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000 + class Tokens auto_style_Tokens + class Elements auto_style_Elements + class Components auto_style_Components %% Added Design Token Styles for Mermaid Diagrams classDef default fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000; classDef component fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000; @@ -43,10 +52,13 @@ graph TD class Layouts component; -``` + %% Auto-generated Design Tokens + classDef auto_style_Tokens fill:#f3e5f5,stroke:#9c27b0,stroke-width:2px,color:#000 + classDef auto_style_Elements fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000 + classDef auto_style_Components fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000 +``` --- - ## 3. Checklist for Jules Agent When generating UI components or modifying styles: diff --git a/.jules/rules/frontend.md b/.jules/rules/frontend.md index b8feddf..47b34e3 100644 --- a/.jules/rules/frontend.md +++ b/.jules/rules/frontend.md @@ -1,10 +1,18 @@ --- description: Instructions for the Jules AI agent regarding frontend code. Contains rules for Feature-Sliced Design (FSD), UI component isolation, and SEO optimization. tags: [frontend architecture, FSD, react patterns, vibe coding, enterprise-grade, clean code, angular, type-safe ui, software design patterns] ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29 +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🎨 Frontend Architecture & FSD Rules for Jules - ## 1. Context & Scope - **Primary Goal:** Implement **clean code** and **frontend architecture** to create highly scalable and robust user interfaces. - **Target Tooling:** Jules AI agent (Vibe Coding). @@ -17,9 +25,7 @@ tags: [frontend architecture, FSD, react patterns, vibe coding, enterprise-grade **Creating enterprise-grade, production-ready frontend solutions.** - --- - ## 2. Feature-Sliced Design (FSD) > [!IMPORTANT] @@ -56,9 +62,7 @@ graph TD | **Features** | Actions that deliver direct business value to the user. | `AuthByEmail`, `AddToCart` | | **Entities** | Business objects and their associated state. | `User`, `Product` | | **Shared** | Reusable code, generic UI (User Interface) components, and utility functions. | `Button`, `apiKit`, `utils` | - --- - ## 3. UI and Logic Requirements for Jules When creating or refactoring **frontend architecture**: diff --git a/.jules/rules/performance.md b/.jules/rules/performance.md index 119f396..46b53dc 100644 --- a/.jules/rules/performance.md +++ b/.jules/rules/performance.md @@ -1,10 +1,18 @@ --- description: Key instructions for Jules regarding performance optimization standards, ensuring fast load times and global scalability. tags: [performance optimization, scalability, fast load times, lazy loading, caching, pagination, frontend optimization, backend efficiency, ai agent] ---- +technology: Angular +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Angular Expert +last_updated: 2026-03-29 +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⚡ Performance Optimization Rules for Jules - ## 1. 🎯 Context & Scope - **Primary Goal:** Ensure all generated code meets strict **performance optimization** standards, guaranteeing fast load times, efficient resource usage, and global **scalability**. - **Target Tooling:** Jules AI agent (Automated Performance Audits & Code Generation). @@ -13,9 +21,7 @@ tags: [performance optimization, scalability, fast load times, lazy loading, cac
Performance Overview
- --- - ## 2. 🚀 Core Performance Guidelines > [!WARNING] @@ -55,13 +61,16 @@ graph TD C --> C2[Caching Strategy] C --> C3[Pagination] - style A fill:#f9f,stroke:#333,stroke-width:2px - style B fill:#bbf,stroke:#333,stroke-width:2px - style C fill:#bfb,stroke:#333,stroke-width:2px -``` + class A auto_style_A + class B auto_style_B + class C auto_style_C + %% Auto-generated Design Tokens + classDef auto_style_A fill:#f9f,stroke:#333,stroke-width:2px + classDef auto_style_B fill:#bbf,stroke:#333,stroke-width:2px + classDef auto_style_C fill:#bfb,stroke:#333,stroke-width:2px +``` --- - ## 3. ✅ Checklist for Jules Agent When writing or reviewing code for performance: @@ -69,5 +78,4 @@ When writing or reviewing code for performance: - [ ] Use Big-O notation analysis; avoid nested loops $O(n^2)$ for large data sets. - [ ] Ensure API responses are compressed (Gzip/Brotli). - [ ] Identify opportunities to batch or debounce repetitive actions (like user typing or API requests). - ## 4. ❓ Frequently Asked Questions: \ No newline at end of file diff --git a/.jules/rules/security.md b/.jules/rules/security.md index 97a7644..adfadc8 100644 --- a/.jules/rules/security.md +++ b/.jules/rules/security.md @@ -1,14 +1,17 @@ --- description: System Security & Hardening Rules for the Jules AI agent. Protects application data and privacy via secure coding and preventing OWASP Top 10 vulnerabilities. tags: - - security - - hardening - - OWASP - - iam - - rules ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🛡️ System Security & Hardening Rules for Jules - ## 📝 1. Context & Scope - **Primary Goal:** Protect application data and user privacy by strictly enforcing **secure coding** practices and preventing common **OWASP Top 10** vulnerabilities. - **Target Tooling:** Jules AI agent (Security Audits, Authentication Logic Generation). @@ -17,9 +20,7 @@ tags:
Security Overview
- --- - ## 🌍 2. Global Threat Mitigation Protocols > [!WARNING] @@ -66,9 +67,7 @@ graph TD | **API Defense** | Rate Limiting | Add middleware to block brute-force and DDoS attempts per IP/User. | | **Headers** | Helmet.js / CSP | Set strict Content Security Policy (CSP), HSTS, and X-Content-Type-Options. | | **Data Privacy** | PII Masking | Never log Personally Identifiable Information (PII) like passwords or credit cards. | - --- - ## 📋 3. Checklist for Jules Agent When generating new backend endpoints, architectures, or frontend forms: @@ -76,6 +75,5 @@ When generating new backend endpoints, architectures, or frontend forms: - [ ] Ensure authentication tokens (JWT, Session IDs) are stored securely (HttpOnly, Secure, SameSite cookies). - [ ] Confirm no sensitive system stack traces or error details are returned to the client in HTTP responses. - [ ] Verify that updating or fetching a resource confirms the requesting user actually owns that resource (Insecure Direct Object Reference prevention). - ## ❓ 4. Frequently Asked Questions - If the file is already ready, then change it according to the repository rules. diff --git a/.jules/rules/system-docs-manager.md b/.jules/rules/system-docs-manager.md index fa7bbf8..07d9cb6 100644 --- a/.jules/rules/system-docs-manager.md +++ b/.jules/rules/system-docs-manager.md @@ -1,10 +1,18 @@ --- description: Instructions for the Jules AI agent on maintaining and updating core system documentation, AI rules, and repository guidelines. tags: [system documentation, AI agent rules, documentation quality, vibe coding, github-seo, repository management, clean documentation] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⚙️ System Documentation & AI Quality Rules for Jules - ## 1. Context & Scope - **Primary Goal:** Ensure the continuous improvement and high **documentation quality** of the core system files that guide developers and AI agents. - **Target Tooling:** Jules AI agent (Vibe Coding, Automated Maintenance). @@ -15,9 +23,7 @@ tags: [system documentation, AI agent rules, documentation quality, vibe coding, **Maintaining the Machine-Readable Intelligence Layer of the repository.** - --- - ## 2. Core System Files and Directories > [!WARNING] @@ -42,9 +48,7 @@ The following files are systemic for promoting high **documentation quality** an - `.agents/rules/github-seo.md` – Search Engine Optimization and metadata structures. - `.agents/rules/project-architecture.md` – Core architectural constraints. - `.agents/rules/rules.md` & `.agents/rules/system-markdown.md` – Specific constraints enforcing clean code and high documentation searchability. - --- - ## 3. Maintenance Protocol for Jules Jules must actively sync these files whenever a new global rule is adopted. @@ -73,9 +77,7 @@ graph TD class UpdateSEO component; ``` - --- - ## 4. Documentation Quality Standards When writing or updating **system documentation**, Jules must verify the following constraints: diff --git a/.jules/rules/ui-ux-design.md b/.jules/rules/ui-ux-design.md index 2367355..2d8b965 100644 --- a/.jules/rules/ui-ux-design.md +++ b/.jules/rules/ui-ux-design.md @@ -1,19 +1,20 @@ --- description: "UI/UX Design and Styling Rules for Jules AI agent, covering responsive design, accessibility (a11y), design systems, and UI component architecture." tags: - - ui - - ux - - design - - styling - - accessibility - - responsive - - jules ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🎨 UI/UX Design Production-Ready Best Practices This document outlines the production-ready best practices for UI/UX Design and styling, specifically tailored for the Jules AI agent. It ensures consistent, accessible, and responsive user interfaces. - ## 1. Context & Scope - **Primary Goal:** Maintain a consistent, **accessible (a11y)**, and visually appealing user interface across all applications through strict **responsive design** practices. - **Target Tooling:** Jules AI agent (UI Generation & CSS Audits). @@ -22,9 +23,7 @@ This document outlines the production-ready best practices for UI/UX Design and
Design Overview
- --- - ## 2. Design System & Styling Rules > [!CAUTION] @@ -65,9 +64,7 @@ graph TD class Components component; class Layouts component; ``` - --- - ## 3. Checklist for Jules Agent When generating UI components or modifying styles: diff --git a/README.md b/README.md index 80ad9ab..ce0aaa7 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,17 @@ --- description: The entry point for developers and AI agents to the Best-Practise AI Context Library. tags: [vibe coding, ai agents, context injection, architectural constraints, clean code] ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29 +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- + [ 🇺🇸 English ](#english) | [ 🇷🇺 Русский ](#russian) @@ -17,22 +27,17 @@ tags: [vibe coding, ai agents, context injection, architectural constraints, cle **"The Gold Standard for AI Agent Context Injection."** - # ⚙️ Context & Scope - **Primary Goal:** Provide an AI-readable index for all architectural and technological constraints to ensure Vibe Coding best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity, GitHub Copilot. - **Tech Stack Version:** Agnostic - --- - ## 🚀 The "Vibe Coding" Value Proposition **The Problem:** Generic LLMs produce generic code because they lack deep project context. Without strict architectural guidelines, codebases built with AI quickly turn into unmaintainable spaghetti code. **The Solution:** This repository provides a global, open-source library of meta-instructions for **Vibe Coding**. By injecting these strict architectural constraints into your AI agents, you ensure **deterministic, scalable, and "beautiful" production-ready code generation**. - --- - ## 🗺️ Interactive Tech Stack Map | Domain | Technology | Status | @@ -40,9 +45,7 @@ tags: [vibe coding, ai agents, context injection, architectural constraints, cle | **Frontend** | [Angular 20+](frontend/angular/)
[JavaScript (ES6+)](frontend/javascript/)
[TypeScript](frontend/typescript/) | ✅ | | **Backend** | [NestJS](backend/nestjs/)
[Express.js](backend/express/)
[Node.js](backend/nodejs/) | ✅ | | **Architecture** | 📐 [Feature-Sliced Design (FSD)](architecture/fsd/)
🏗️ [MVC](architecture/mvc/) | 🛠️ | - --- - ## 🤖 Топ-10 AI Агентов и Инструментов (IDE) В современных реалиях Vibe Coding активно используются следующие мощные AI инструменты. Вот 10 самых популярных из них: @@ -59,9 +62,7 @@ tags: [vibe coding, ai agents, context injection, architectural constraints, cle | Tabnine | **Tabnine** | Enterprise-level solution with a high degree of confidentiality, trained on your own code without leaks to public models. | | Amazon Q | **Amazon Q Developer** | An assistant from AWS (formerly CodeWhisperer), ideal for integration with cloud infrastructure and vulnerability scanning. | | Sourcegraph Cody | **Sourcegraph Cody** | An instrument with deep access to your enterprise code graph for ultra-precise search and generation. | - --- - ## 🎯 Integration Guide: Injecting AI Context To establish a deterministic, scalable **Agentic Workflow**, engineers must perform **Context Injection**. By injecting these **Deterministic Rules** into your AI toolchain, you ensure that agents strictly adhere to the project's baseline architecture and constraints. @@ -95,9 +96,7 @@ For the **Deterministic Rules** to be accurately parsed and strictly followed, i | **Cursor AI** | `.cursor/rules/*.md` | | **Windsurf** | `.windsurf/rules/` | | **GitHub Copilot** | `.github/copilot-instructions.md` (or root `.github/` for general context) | -| **Cloud Code AI / Claude Code** | Root directory or `.claude/` (depending on agent configuration) | ---- -## 🛠️ Visual Architecture: Context Deep-Dive +| **Cloud Code AI / Claude Code** | Root directory or `.claude/` (depending on agent configuration) |---## 🛠️ Visual Architecture: Context Deep-Dive The repository is structured hierarchically to allow AI agents to progressively deepen their understanding of your project constraints. @@ -165,8 +164,7 @@ graph TD class C3 component; class B component; -``` -## 🌴 Folder Tree +```## 🌴 Folder Tree * 📦 **[best-practise](./)** * 📄 [agents.md](./agents.md) @@ -202,9 +200,7 @@ graph TD * 📄 [readme.md](./frontend/javascript/readme.md) * 🟦 **[typescript/](./frontend/typescript/)** * 📄 [readme.md](./frontend/typescript/readme.md) - --- - ## 🤝 How to Contribute This is a living repository. Even if you're building alone, the AI ecosystem thrives on shared knowledge. If you are an expert in a specific technology, we invite you to add your specific constraints and rules! @@ -212,14 +208,12 @@ This is a living repository. Even if you're building alone, the AI ecosystem thr 2. Navigate to the appropriate `[domain]/[technology]/` folder (or create it). 3. Add a `readme.md` with core principles, and break down complex rules into specific markdown files. 4. Submit a Pull Request. - ---
Author: Jamoliddin Qodirov (Software Architect & Teacher)
- --- @@ -235,22 +229,17 @@ This is a living repository. Even if you're building alone, the AI ecosystem thr **"Золотой стандарт для внедрения контекста в ИИ-агентствах."** - # ⚙️ Контекст & Сфера применения - **Основная цель:** Обеспечить AI-читаемый индекс для трансляции архитектурных концепций и технологических Constraints (Ограничения) с целью обеспечения стандартов Vibe Coding. - **Целевое ПО (Target Tooling):** Cursor, Windsurf, Antigravity, GitHub Copilot. - **Версия техстека:** Агностична - --- - ## 🚀 "Vibe Coding" Ценностное предложение **Проблема:** Базовые LLM генерируют абстрактный код по причине дефицита глубокого контекста о проекте. Отсутствие строго регламентированных архитектурных ограничений неизбежно приводит к переходу кодовой базы, сгенерированной ИИ, в технический долг (спагетти-код) и провоцирует Hallucinations (Галлюцинации). **Решение:** Данный репозиторий представляет собой эталонную open-source библиотеку мета-инструкций для **Vibe Coding**. Осуществляя строгий AI Context Injection в ваших агентах, вы достигаете **детерминированного транслирования архитектуры, обеспечения масштабируемости и генерации production-ready кода**. - --- - ## 🗺️ Интерактивная карта технологического стека | Домен | Технология | Статус | @@ -258,9 +247,7 @@ This is a living repository. Even if you're building alone, the AI ecosystem thr | **Frontend** | [Angular 20+](frontend/angular/)
[JavaScript (ES6+)](frontend/javascript/)
[TypeScript](frontend/typescript/) | ✅ | | **Backend** | [NestJS](backend/nestjs/)
[Express.js](backend/express/)
[Node.js](backend/nodejs/) | ✅ | | **Architecture** | 📐 [Feature-Sliced Design (FSD)](architecture/fsd/)
🏗️ [MVC](architecture/mvc/) | 🛠️ | - --- - ## 🤖 Топ-10 AI Агентов и Инструментов (IDE) В парадигме Vibe Coding в продакшене внедрены следующие ИИ-инструменты. Ниже приведен топ-10 актуальных решений: @@ -277,13 +264,10 @@ This is a living repository. Even if you're building alone, the AI ecosystem thr | Tabnine | **Tabnine** | Enterprise-решение с упором на секьюрити. Обучается изолированно на инхаус коде для пресечения утечек данных. | | Amazon Q | **Amazon Q Developer** | Корпоративный ассистент от AWS. Внедрен как модуль-профайлер облачных инфраструктур и анализа уязвимостей. | | Sourcegraph Cody | **Sourcegraph Cody** | Инструмент для дата-майнинга и анализа Enterprise-кодовых графов, обеспечивающий маппинг компонентов с высокой степенью согласованности. | - --- - --- - ## 🎯 Руководство по интеграции: Инъекция контекста Для выстраивания детерминированного и масштабируемого **Agentic Workflow**, разработчики должны реализовать **Инъекцию контекста** (Context Injection). Интеграция данных **Deterministic Rules** в ваш инструментарий ИИ гарантирует строгое соблюдение базовой архитектуры и заданных ограничений агентами. @@ -317,9 +301,7 @@ graph LR | **Cursor AI** | `.cursor/rules/*.md` | | **Windsurf** | `.windsurf/rules/` | | **GitHub Copilot** | `.github/copilot-instructions.md` (или корень `.github/` для общего контекста) | -| **Cloud Code AI / Claude Code** | Корневая директория или `.claude/` (в зависимости от конфигурации агента) | ---- - +| **Cloud Code AI / Claude Code** | Корневая директория или `.claude/` (в зависимости от конфигурации агента) |--- ## 🛠️ Visual Architecture: Context Deep-Dive Топология проекта организована иерархически. Архитектура разработана для прогрессивного спускания AI-агентов по информационным узлам (Context Drilling) до спецификаций конкретной технологии. @@ -388,8 +370,7 @@ graph TD class C3 component; class B component; -``` -## 🌴 Folder Tree +```## 🌴 Folder Tree * 📦 **[best-practise](./)** * 📄 [agents.md](./agents.md) @@ -425,9 +406,7 @@ graph TD * 📄 [readme.md](./frontend/javascript/readme.md) * 🟦 **[typescript/](./frontend/typescript/)** * 📄 [readme.md](./frontend/typescript/readme.md) - --- - ## 🤝 Стать contributer проект В условиях развития AI-экосистемы аккумулирование Enterprise-опыта является критически важным. Инженерам, обладающим подтвержденной квалификацией (Senior level) в конкретных субдоменах, предлагается расширять реестр Constraints: @@ -435,7 +414,6 @@ graph TD 2. Проведите локализацию в директории `[domain]/[technology]/`. 3. Реализуйте файл `readme.md`, декларирующий ключевые парадигмы в рамках стэка. Для покрытия узкоспециализированных кейсов инициируйте декомпозицию с выделением изолированных конфигураций (например, `performance.md`). 4. Настройте Pull Request в ветку `main`. - ---
diff --git a/README_AUTONOMY.md b/README_AUTONOMY.md index ca0f633..8a4c033 100644 --- a/README_AUTONOMY.md +++ b/README_AUTONOMY.md @@ -1,15 +1,24 @@ -# 🤖 Autonomous Marketing Engine: README - +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Documentation domain. +tags: [vibe-coding, documentation, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29---# 🤖 Autonomous Marketing Engine: README ## Overview This repository utilizes a fully autonomous pipeline to generate professional marketing assets upon every new release. The engine leverages **Google Cloud Vertex AI** and **Cloud Storage** to create high-fidelity content, visuals, and motion teasers. - ## Core Stack - **Copywriting:** Gemini 1.5 Pro (AIDA/PAS frameworks). - **Visuals:** Nano Banana 2 / Imagen 3 (4K Cinematic Covers). - **Motion:** Veo 3 (5s High-Fidelity Teasers). - **Persistence:** Google Cloud Storage (Public CDN). - **Distribution:** Buffer API (via JSON payload). - ## Efficiency & Credits Monitoring ($300) To maximize the value of the $300 Google Cloud free tier/credits, follow these best practices: @@ -22,7 +31,6 @@ To maximize the value of the $300 Google Cloud free tier/credits, follow these b 4. **Monitoring:** - Use the [Google Cloud Console Billing](https://console.cloud.google.com/billing) to set alerts at 50%, 75%, and 90% of credit usage. - Check Vertex AI "Quotas & System Limits" to ensure no unexpected spikes in usage. - ## Setup Requirements Ensure the following GitHub Secrets are configured: - `GCP_SA_KEY`: Service Account JSON with Vertex AI User and Storage Admin roles. @@ -31,10 +39,8 @@ Ensure the following GitHub Secrets are configured: - `GEMINI_API_KEY`: API Key for Vertex AI (if not using SA auth for all). - `BUFFER_ACCESS_TOKEN`: For social media distribution. - `BUFFER_PROFILE_IDS`: Comma-separated list of profile IDs. - ## Troubleshooting - **Veo 3 Failures:** The engine is built to be robust. If video generation fails, it will still proceed with text and image generation. - **Auth Errors:** Ensure the Service Account has `aiplatform.user` permissions. - --- *Engineered for zero-fluff, authoritative tech marketing.* diff --git a/agents.md b/agents.md index 84bc5b8..c6e7357 100644 --- a/agents.md +++ b/agents.md @@ -1,10 +1,18 @@ --- description: The Meta-Intelligence & Vibe Coding Protocol defining how AI agents interact with the repository and follow architectural guidelines. tags: [vibe coding, ai agents, execution protocol, context mapping, global constraints] ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29 +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # AGENTS.md: The Meta-Intelligence & Vibe Coding Protocol - ## 🌍 1. Global Vision **The Gold Standard for AI-Driven Development Instructions.** @@ -12,9 +20,7 @@ This repository is not a codebase; it is a **Machine-Readable Intelligence Layer - **Automate the Mundane:** Shift the burden of boilerplate and syntax to the AI. - **Architectural Excellence:** Force AI agents to respect high-level patterns (FSD, MVC) before writing a single line of logic. - **Vibe Coding Synchronization:** Provide a unified "Source of Truth" for any LLM-based agent (Cursor, Windsurf, Copilot) to ensure "perfect first-time" generation. - --- - ## 🗺️ 2. Context Mapping AI Agents MUST traverse this repository using the following hierarchical logic: @@ -34,7 +40,7 @@ graph TD BE --> Nest[NestJS] BE --> Express[Express] - style Global fill:#f9f,stroke:#333,stroke-width:4px + class Global auto_style_Global %% Added Design Token Styles for Mermaid Diagrams classDef default fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000; classDef component fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000; @@ -51,6 +57,9 @@ graph TD class Arch component; class Nest component; + + %% Auto-generated Design Tokens + classDef auto_style_Global fill:#f9f,stroke:#333,stroke-width:4px ``` ### Resource Directory @@ -60,9 +69,7 @@ graph TD | `/architectures/` | System Design Blueprints | Defines the folder structure and module boundaries. | | `/frontend/` | UI/UX & Client Logic | Specific rules for React, Angular, and TypeScript safety. | | `/backend/` | Server-side & API | Rules for scalability, security, and DTO validation. | - --- - ## 🛠️ 3. Tool-Specific Integration To leverage these rules in your IDE, follow these implementation paths: @@ -81,9 +88,7 @@ Reference this repository in your `.windsurfrules` file: ### 💻 VS Code (Custom Instructions) For extensions like Cloud Code or GitHub Copilot, append the contents of `AGENTS.md` to your **Settings > Custom Instructions** field to establish the "Architectural Guardrails." - --- - ## 🤖 4. Agent Execution Protocol **Any AI Agent interacting with this repository MUST follow this 4-step execution loop:** @@ -91,9 +96,7 @@ For extensions like Cloud Code or GitHub Copilot, append the contents of `AGENTS 2. **Constraint Identification:** Locate the specific `.md` file corresponding to the user's task (e.g., if the user asks for a NestJS service, read `backend/nestjs/readme.md`). 3. **Hierarchy Alignment:** Prioritize `architectures/` constraints over `frontend/` or `backend/` specifics to ensure structural integrity. 4. **Verification:** Before outputting code, run a "Constraint Check" against the identified rules to ensure zero violations of the "Best Practise" standard. - --- - ## 🔍 5. SEO & Discoverability >IP: Return Result/DTO IP-->>UI: Form HTTP/RPC Response ``` - ## ⛔ Boundary Constraints (Data Flow Rules) 1. **No External Imports in Domain:** The Core Domain must NEVER import code from an Adapter (e.g., `import { PostgresDB } from '../adapters/db'`). It only implements Interfaces. diff --git a/architectures/hexagonal-architecture/folder-structure.md b/architectures/hexagonal-architecture/folder-structure.md index ba258b0..979311e 100644 --- a/architectures/hexagonal-architecture/folder-structure.md +++ b/architectures/hexagonal-architecture/folder-structure.md @@ -7,16 +7,17 @@ version: Agnostic tags: [best-practices, folder-structure, hexagonal-architecture, ports-and-adapters] ai_role: Senior Software Architect last_updated: 2026-03-22 ---- +topic: Hexagonal Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 📁 Folder Structure Best Practices for Hexagonal Architecture
**Strict directory blueprints for zero-approval AI parsing.**
- --- - ## 🌳 The Root Hierarchy A properly defined Hexagonal architecture clearly separates its concerns at the file-system level. AI Agents are expected to enforce this strict separation. @@ -43,7 +44,6 @@ graph TD class Ports component; class Domain component; ``` - ## 🏗️ Example Directory Content ```text @@ -69,7 +69,6 @@ src/ └── 📁 external/ # 3rd Party APIs (SendGrid, Stripe) └── SendGridEmailSender.ts ``` - ## ⛔ Boundary Constraints 1. **Isolation in `core/`:** Code inside `core/` is forbidden from importing modules from `adapters/`. diff --git a/architectures/hexagonal-architecture/implementation-guide.md b/architectures/hexagonal-architecture/implementation-guide.md index 8cdd4fd..d4b5a24 100644 --- a/architectures/hexagonal-architecture/implementation-guide.md +++ b/architectures/hexagonal-architecture/implementation-guide.md @@ -7,16 +7,17 @@ version: Agnostic tags: [best-practices, implementation-guide, hexagonal-architecture, ports-and-adapters] ai_role: Senior Software Architect last_updated: 2026-03-22 ---- +topic: Hexagonal Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🛠️ Hexagonal Architecture Implementation Guide
**Executable blueprints and constraints for AI-agent code generation.**
- --- - ## ⚡ The Vibe Coding Instructions (Constraints) For any code generated within the Hexagonal Architecture ecosystem, the following boundaries must be strictly enforced: @@ -29,9 +30,7 @@ For any code generated within the Hexagonal Architecture ecosystem, the followin 3. **Boundary DTO Translation:** Adapters must map raw external data (HTTP Requests, Database Rows) into pure Domain Entities before passing them inward. When returning data, Domain Entities must be translated back into Adapter-specific DTOs before reaching the outside world. Do not leak the Core Entity to an HTTP response directly. - --- - ## 💻 Concrete Code Examples ### 🧩 Entity Relationships (Class Diagram) @@ -168,3 +167,15 @@ export class UserController { } } ``` + + +### ❌ Bad Practice +[Need to fill in example of non-optimal code] + + +### ⚠️ Problem +[Analysis of the risks] + + +### 🚀 Solution +[Architectural justification of the solution] diff --git a/architectures/hexagonal-architecture/readme.md b/architectures/hexagonal-architecture/readme.md index 7f4fa36..f957afa 100644 --- a/architectures/hexagonal-architecture/readme.md +++ b/architectures/hexagonal-architecture/readme.md @@ -7,10 +7,12 @@ version: Agnostic tags: [best-practices, clean-code, hexagonal-architecture, ports-and-adapters, system-design, vibe-coding] ai_role: Senior Software Architect last_updated: 2026-03-22 ---- +topic: Hexagonal Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🛑 Hexagonal Architecture Production-Ready Best Practices - # Context & Scope - **Primary Goal:** Document and execute the best practices for the Hexagonal Architecture pattern. - **Target Tooling:** AI Agents and Human Developers. @@ -21,9 +23,7 @@ last_updated: 2026-03-22 **Ports and Adapters for scalable, testable code.**
- --- - ## 🗺️ Map of Patterns (Hexagonal Modules) This pattern documentation has been decomposed into specialized modules for zero-approval AI parsing and human comprehension. @@ -32,7 +32,6 @@ This pattern documentation has been decomposed into specialized modules for zero - 📁 **[Folder Structure](./folder-structure.md):** The strict directory blueprints. - ⚖️ **[Trade-offs](./trade-offs.md):** Pros, cons, and architectural constraints. - 🛠️ **[Implementation Guide](./implementation-guide.md):** Step-by-step rules and code constraints for Vibe Coding. - ## 🚀 The Core Philosophy Hexagonal Architecture (Ports & Adapters) ensures the core business logic is isolated from specific external technologies. diff --git a/architectures/hexagonal-architecture/trade-offs.md b/architectures/hexagonal-architecture/trade-offs.md index 1d22595..8b8c8af 100644 --- a/architectures/hexagonal-architecture/trade-offs.md +++ b/architectures/hexagonal-architecture/trade-offs.md @@ -7,16 +7,17 @@ version: Agnostic tags: [best-practices, trade-offs, hexagonal-architecture, ports-and-adapters] ai_role: Senior Software Architect last_updated: 2026-03-22 ---- +topic: Hexagonal Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⚖️ Hexagonal Architecture Trade-offs and Constraints
**Evaluating the return on investment when choosing Ports and Adapters.**
- --- - ## 📊 Pros & Cons Matrix | Feature | ✅ Pros | ❌ Cons | @@ -25,14 +26,12 @@ last_updated: 2026-03-22 | **Flexibility** | Swap out a DB (e.g., PostgreSQL for MongoDB) or Framework instantly. | Boilerplate heavy. Setup time for simple CRUD apps is unjustified. | | **Domain Focus** | Keeps the team focused strictly on business value logic. | Steep learning curve for Junior developers used to tight MVC coupling. | | **Delayed Decisions** | You don't need to pick a Database or UI Framework on day 1. | Over-engineering risk for startups seeking rapid MVP validation. | - ## ⛔ Hard Rules & Architectural Constraints 1. **Dependency Inversion Enforcement:** The Core Domain must define its dependencies via Interfaces (Ports). It does not "call" Adapters. Adapters implement the Ports, and the application wiring (Dependency Injection container) provides the instances at runtime. 2. **Framework Agnosticism in Core:** No ORM decorators (like `@Entity` or `@Column`) or Web Framework decorators (like `@Get` or `@Req`) are allowed inside `src/core/domain`. 3. **Data Mapping Requirement:** Adapters must translate specific Data Objects (e.g., HTTP requests, DB rows) into clean Domain Entities before passing them inward. When returning data, Domain Entities must be translated back into Adapter-specific DTOs before reaching the outside world. 4. **Ports Exclusivity:** A Port belongs to the Core Domain. The Core dictates what the Port looks like based on its business needs, not based on what a specific Adapter provides. An external library API should never dictate a Port's signature. - ## 🏆 When to use Hexagonal Architecture - **Use when:** The project is expected to live for 5+ years, undergoes frequent changes in external vendor tools, requires high test coverage, and involves complex business rules. diff --git a/architectures/microservices/data-flow.md b/architectures/microservices/data-flow.md index 05206f2..42f0f1d 100644 --- a/architectures/microservices/data-flow.md +++ b/architectures/microservices/data-flow.md @@ -1,5 +1,16 @@ -# Microservices - Data Flow - +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Architecture domain. +tags: [vibe-coding, architecture, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29---# Microservices - Data Flow ## Request and Event Lifecycle ```mermaid diff --git a/architectures/microservices/folder-structure.md b/architectures/microservices/folder-structure.md index 4a82a23..d5e8ae1 100644 --- a/architectures/microservices/folder-structure.md +++ b/architectures/microservices/folder-structure.md @@ -1,5 +1,16 @@ -# Microservices - Folder Structure - +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Architecture domain. +tags: [vibe-coding, architecture, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29---# Microservices - Folder Structure ## Layering logic ```mermaid diff --git a/architectures/microservices/implementation-guide.md b/architectures/microservices/implementation-guide.md index 421c6ef..fa2003e 100644 --- a/architectures/microservices/implementation-guide.md +++ b/architectures/microservices/implementation-guide.md @@ -1,5 +1,16 @@ -# Microservices - Implementation Guide - +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Architecture domain. +tags: [vibe-coding, architecture, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29---# Microservices - Implementation Guide ## Code patterns and Anti-patterns ### Entity Relationships diff --git a/architectures/microservices/readme.md b/architectures/microservices/readme.md index 287ba2d..0b4a8ae 100644 --- a/architectures/microservices/readme.md +++ b/architectures/microservices/readme.md @@ -7,26 +7,26 @@ version: Agnostic tags: [architecture, system-design, microservices, best-practices] ai_role: Senior Architect last_updated: 2026-03-22 ---- +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
# 🏛️ Microservices Production-Ready Best Practices
- --- Этот инженерный директив определяет **лучшие практики (best practices)** для архитектуры Microservices. Данный документ спроектирован для обеспечения максимальной масштабируемости, безопасности и качества кода при разработке приложений корпоративного уровня. - # Context & Scope - **Primary Goal:** Предоставить строгие архитектурные правила и практические паттерны для создания масштабируемых систем. - **Description:** Breaking down a giant monolithic system into small, independent pieces, each handling its own business capability. Each service has its own Database. - ## Map of Patterns - 📊 [**Data Flow:** Request and Event Lifecycle](./data-flow.md) - 📁 [**Folder Structure:** Layering logic](./folder-structure.md) - ⚖️ [**Trade-offs:** Pros, Cons, and System Constraints](./trade-offs.md) - 🛠️ [**Implementation Guide:** Code patterns and Anti-patterns](./implementation-guide.md) - ## Core Principles 1. **Isolation & Testability:** Changing a single feature doesn't break the entire business process. diff --git a/architectures/microservices/trade-offs.md b/architectures/microservices/trade-offs.md index dbc737d..717478c 100644 --- a/architectures/microservices/trade-offs.md +++ b/architectures/microservices/trade-offs.md @@ -1,5 +1,16 @@ -# Microservices - Trade-offs - +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Architecture domain. +tags: [vibe-coding, architecture, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29---# Microservices - Trade-offs ## Pros, Cons, and System Constraints ### Pros diff --git a/architectures/model-view-controller/data-flow.md b/architectures/model-view-controller/data-flow.md index 0a4604c..51e97d5 100644 --- a/architectures/model-view-controller/data-flow.md +++ b/architectures/model-view-controller/data-flow.md @@ -1,5 +1,16 @@ -# Model-View-Controller (MVC) - Data Flow - +--- +description: Vibe coding guidelines and architectural constraints for MVC within the Architecture domain. +tags: [mvc, architecture, best-practices, architecture] +topic: MVC +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: MVC +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior MVC Expert +last_updated: 2026-03-29---# Model-View-Controller (MVC) - Data Flow ## Request and Event Lifecycle ```mermaid diff --git a/architectures/model-view-controller/folder-structure.md b/architectures/model-view-controller/folder-structure.md index 69ad105..1527c10 100644 --- a/architectures/model-view-controller/folder-structure.md +++ b/architectures/model-view-controller/folder-structure.md @@ -1,5 +1,16 @@ -# Model-View-Controller (MVC) - Folder Structure - +--- +description: Vibe coding guidelines and architectural constraints for MVC within the Architecture domain. +tags: [mvc, architecture, best-practices, architecture] +topic: MVC +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: MVC +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior MVC Expert +last_updated: 2026-03-29---# Model-View-Controller (MVC) - Folder Structure ## Layering publisher/subscriber logic ```mermaid diff --git a/architectures/model-view-controller/implementation-guide.md b/architectures/model-view-controller/implementation-guide.md index 0a1229b..be16ea8 100644 --- a/architectures/model-view-controller/implementation-guide.md +++ b/architectures/model-view-controller/implementation-guide.md @@ -1,5 +1,16 @@ -# Model-View-Controller (MVC) - Implementation Guide - +--- +description: Vibe coding guidelines and architectural constraints for MVC within the Architecture domain. +tags: [mvc, architecture, best-practices, architecture] +topic: MVC +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: MVC +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior MVC Expert +last_updated: 2026-03-29---# Model-View-Controller (MVC) - Implementation Guide ## Code patterns and Anti-patterns ### Entity Relationships diff --git a/architectures/model-view-controller/readme.md b/architectures/model-view-controller/readme.md index 268df59..118469e 100644 --- a/architectures/model-view-controller/readme.md +++ b/architectures/model-view-controller/readme.md @@ -7,16 +7,18 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns, mvc-best-practise, angular-best-practise, expressjs-best-practise, ai-instructions, vibe-coding-instructions, mongodb, angular, nestjs, html, scss, javascript, js, typescript-best-practise, css, css3] ai_role: Senior Software Architect last_updated: 2026-03-22 ---- +topic: MVC +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
# 🏛️ Model-View-Controller (MVC) Production-Ready Best Practices
- --- Этот инженерный директив определяет **лучшие практики (best practices)** для архитектуры MVC. Данный документ спроектирован для обеспечения максимальной масштабируемости, безопасности и качества кода при разработке приложений корпоративного уровня. - # Context & Scope - **Primary Goal:** Предоставить строгие архитектурные правила и 20 практических паттернов для создания масштабируемых и детерминированных MVC-приложений. - **Target Tooling:** AI-агенты (Cursor, Windsurf, Copilot, Antigravity) и Senior-разработчики. @@ -24,7 +26,6 @@ last_updated: 2026-03-22 > [!IMPORTANT] > **Архитектурный стандарт (Contract):** Контроллер принимает HTTP-запрос и маршрутизирует команды, Сервисы (или Доменная Модель) содержат бизнес-логику, Представление (View) отвечает исключительно за рендеринг абстрактных Data Transfer Objects (DTO). - ## Architecture Flow (Mental Model) ```mermaid @@ -55,16 +56,13 @@ graph TD class Router component; ``` - --- - ## Map of Patterns - 📊 [**Data Flow:** Request and Event Lifecycle](./data-flow.md) - 📁 [**Folder Structure:** Layering logic](./folder-structure.md) - ⚖️ [**Trade-offs:** Pros, Cons, and System Constraints](./trade-offs.md) - 🛠️ [**Implementation Guide:** Code patterns and Anti-patterns](./implementation-guide.md) - ## 1. Fat Controllers (God Object Controller) ### ❌ Bad Practice @@ -104,9 +102,7 @@ class UserController { ### 🚀 Solution Придерживайтесь парадигмы «Тонкие контроллеры» (Thin Controllers). Делегируйте все бизнес-сценарии в выделенный сервисный слой (Service Layer) или агрегатные доменные модели. - --- - ## 2. Anemic Domain Model (Анемичная модель) ### ❌ Bad Practice @@ -144,9 +140,7 @@ class Order { ### 🚀 Solution Инкапсулируйте изменение внутреннего состояния (мутации) внутри самой Модели (Rich Model). Сторонние сервисы обязаны вызывать методы-действия модели через подготовленные контракты, а не переопределять её данные. - --- - ## 3. Direct Model Exposure to View (Утечка схемы базы данных) ### ❌ Bad Practice @@ -176,9 +170,7 @@ class UserController { ### 🚀 Solution Архитектурно необходимо применять классы DTO (Data Transfer Objects) или ViewModels для изолированной трансформации доменной модели в структуру, безопасную для клиента (View / API). - --- - ## 4. Complex Logic within Views (Шаблонизация бизнес-правил) ### ❌ Bad Practice @@ -206,9 +198,7 @@ class UserController { ### 🚀 Solution Экспортируйте агрегированные состояния для представления (View) в слое Презентера (ViewModel). View обязан оставаться «Глупым» (Dumb View), способным лишь на рендеринг булевых флагов и массивов из DTO. - --- - ## 5. View Layer Initiating Database Transactions ### ❌ Bad Practice @@ -234,9 +224,7 @@ class UserController { ### 🚀 Solution Вектор зависимости слоя View строго однонаправлен «Сверху вниз» на данные, инжектированные Контроллером. Представление не должно осознавать факт существования Хранилищ (Repositories/DBs). - --- - ## 6. Global State and Singletons Bound to Models ### ❌ Bad Practice @@ -265,9 +253,7 @@ class Invoice { ### 🚀 Solution Исключите использование глобальных Синглтонов в доменной зоне. Все внешние параметры или конфигурационное окружение передаются в модели прозрачно (explicit dependencies) через конструкторы или аргументы методов. - --- - ## 7. Mixing Low-Level Routing with Controller Logic ### ❌ Bad Practice @@ -296,9 +282,7 @@ router.get('/settings', userController.showSettings); ### 🚀 Solution Оставьте маршутизацию (Routing) фреймворку или выделенному слою Router. Задача Контроллера — реагировать на уже сформированный вызов метода с готовым payload. - --- - ## 8. Validation Rules Leaking into the Domain Layers ### ❌ Bad Practice @@ -329,9 +313,7 @@ class UserController { ### 🚀 Solution Валидация синтаксиса и форматов (JSON Schema, DTO Validation) обязана выполняться на слое обработки запросов (Gateways / Controllers). В Сервисы должны поступать исключительно детерминированные форматы данных. - --- - ## 9. Lack of Dependency Injection in Controllers ### ❌ Bad Practice @@ -357,9 +339,7 @@ class OrderController { ### 🚀 Solution Утилизируйте паттерн Dependency Injection (DI). Контроллеры запрашивают нужные сервисы или репозитории через интерфейсы (IoC Containers), что гарантирует возможность горячей подмены абстракций. - --- - ## 10. Generating Raw HTML Strings Inside Controllers ### ❌ Bad Practice @@ -387,9 +367,7 @@ class WelcomeController { ### 🚀 Solution Контроллер НИКОГДА не генерирует разметку напрямую. Его функциональная гарантия — передать структуру данных (ViewModel / JSON) стандартизированному движку шаблонизации (Handlebars, React Server, EJS). - --- - ## 11. God Models (Monolithic Bounded Contexts) ### ❌ Bad Practice @@ -415,9 +393,7 @@ class PdfGeneratorService { ... } ### 🚀 Solution Декомпозируйте супер-модели на узконаправленные агрегаты (Aggregates) в рамках строгих контекстов предметной области (Bounded Contexts). - --- - ## 12. View Layer Mutating Upstream State ### ❌ Bad Practice @@ -439,9 +415,7 @@ class PdfGeneratorService { ... } ### 🚀 Solution Паттерн MVC предполагает, что View является лишь отражением (Read-only Projection) текущих данных. Для мутаций View должен отправить инструкцию для Контроллера (HTTP Request, Event), который санкционирует процесс. - --- - ## 13. Hardwired Environment Secrets within Logic Code ### ❌ Bad Practice @@ -469,9 +443,7 @@ class BillingService { ### 🚀 Solution Запрещен хардкод любых параметров окружения (Passwords, URLs, Tokens) в Контроллерах и Моделях. Вся инфраструктура загружается из специализированного провайдера конфигураций. - --- - ## 14. Blocking Main Thread in Standard Controllers ### ❌ Bad Practice @@ -501,9 +473,7 @@ class ReportController { ### 🚀 Solution Интегрируйте Job-системы (RabbitMQ, Redis Queues). Контроллер должен делегировать ресурсоемкие задачи воркеру в фоне и мгновенно возвращать HTTP 202 (Accepted). - --- - ## 15. The "Repository" Abstraction Leak to View/Controller ### ❌ Bad Practice @@ -533,9 +503,7 @@ class DashboardController { ### 🚀 Solution Ограждайте слой Представлений и Контроллеров от низкоуровневых операций I/O. Интегрируйте паттерны Repository / Data Access Object (DAO). - --- - ## 16. Exposing Sequent Database Identifiers (IDOR Threat) ### ❌ Bad Practice @@ -558,9 +526,7 @@ class TransactionResponse { ### 🚀 Solution Транслируйте внутренние физические идентификаторы БД (Integers) во внешние строковые UUID или хэши прежде чем Контроллер перебросит их на View. - --- - ## 17. Duplicating Core Invariants Inside Templates ### ❌ Bad Practice @@ -583,9 +549,7 @@ class Package { isFragile() { return this.weight > 50; } } ### 🚀 Solution Доменная Модель — единственный "Источник Правды" (Source of Truth). View должно читать готовое вычисленное полиморфное состояние, предоставленное системой. - --- - ## 18. Side-Effects Orchestration Inside Controller Scope ### ❌ Bad Practice @@ -618,9 +582,7 @@ class SubscriptionController { ### 🚀 Solution Внедряйте Domain Events Architectures (Pub/Sub брокеры). Контроллер отвечает сугубо за инициирование бизнес-события "Оплата совершена", логики рассылки не должны блокировать канал ответа клиенту. - --- - ## 19. Fractured Exception Logging (Try-Catch Hell) ### ❌ Bad Practice @@ -652,9 +614,7 @@ class ItemController { ### 🚀 Solution Абстрагируйте процедуру захвата ошибок (Error Handling) в Глобальные Фильтры Исключений (Global Exception Handlers) фреймворка, стандартизировав формат возврата HTTP 4XX / 5XX ошибок для View. - --- - ## 20. Overusing the Model Segment for Hardware Infrastructure (AWS, FS) ### ❌ Bad Practice @@ -689,7 +649,6 @@ class AssetUploaderService { ### 🚀 Solution Соблюдайте границу Ports and Adapters. Переносите интеграцию с аппаратным вводом (Файловые системы, AWS, Redis) на плечи внешних Infrastructure Services, оставляя MVC Модели концептуально абстрактными сущностями. - ---
diff --git a/architectures/model-view-controller/trade-offs.md b/architectures/model-view-controller/trade-offs.md index 7e069af..62e083d 100644 --- a/architectures/model-view-controller/trade-offs.md +++ b/architectures/model-view-controller/trade-offs.md @@ -1,5 +1,16 @@ -# Model-View-Controller (MVC) - Trade-offs - +--- +description: Vibe coding guidelines and architectural constraints for MVC within the Architecture domain. +tags: [mvc, architecture, best-practices, architecture] +topic: MVC +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: MVC +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior MVC Expert +last_updated: 2026-03-29---# Model-View-Controller (MVC) - Trade-offs ## Pros, Cons, and System Constraints ### Pros diff --git a/architectures/monolithic-architecture/data-flow.md b/architectures/monolithic-architecture/data-flow.md index a50f81a..8cb74eb 100644 --- a/architectures/monolithic-architecture/data-flow.md +++ b/architectures/monolithic-architecture/data-flow.md @@ -1,5 +1,16 @@ -# Monolithic Architecture - Data Flow - +--- +description: Vibe coding guidelines and architectural constraints for Monolithic Architecture within the Architecture domain. +tags: [monolithic-architecture, architecture, best-practices, architecture] +topic: Monolithic Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Monolithic Architecture +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Monolithic Architecture Expert +last_updated: 2026-03-29---# Monolithic Architecture - Data Flow ## Request and Event Lifecycle ```mermaid diff --git a/architectures/monolithic-architecture/folder-structure.md b/architectures/monolithic-architecture/folder-structure.md index 1d2b8ae..9cd71a2 100644 --- a/architectures/monolithic-architecture/folder-structure.md +++ b/architectures/monolithic-architecture/folder-structure.md @@ -1,5 +1,16 @@ -# Monolithic Architecture - Folder Structure - +--- +description: Vibe coding guidelines and architectural constraints for Monolithic Architecture within the Architecture domain. +tags: [monolithic-architecture, architecture, best-practices, architecture] +topic: Monolithic Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Monolithic Architecture +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Monolithic Architecture Expert +last_updated: 2026-03-29---# Monolithic Architecture - Folder Structure ## Layering logic ```mermaid diff --git a/architectures/monolithic-architecture/implementation-guide.md b/architectures/monolithic-architecture/implementation-guide.md index 7b30519..cc16076 100644 --- a/architectures/monolithic-architecture/implementation-guide.md +++ b/architectures/monolithic-architecture/implementation-guide.md @@ -1,5 +1,16 @@ -# Monolithic Architecture - Implementation Guide - +--- +description: Vibe coding guidelines and architectural constraints for Monolithic Architecture within the Architecture domain. +tags: [monolithic-architecture, architecture, best-practices, architecture] +topic: Monolithic Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Monolithic Architecture +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Monolithic Architecture Expert +last_updated: 2026-03-29---# Monolithic Architecture - Implementation Guide ## Code patterns and Anti-patterns ### Entity Relationships diff --git a/architectures/monolithic-architecture/readme.md b/architectures/monolithic-architecture/readme.md index ae3524d..4875e23 100644 --- a/architectures/monolithic-architecture/readme.md +++ b/architectures/monolithic-architecture/readme.md @@ -7,26 +7,26 @@ version: Agnostic tags: [architecture, system-design, monolithic-architecture, best-practices] ai_role: Senior Architect last_updated: 2026-03-22 ---- +topic: Monolithic Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
# 🏛️ Monolithic Architecture Production-Ready Best Practices
- --- Этот инженерный директив определяет **лучшие практики (best practices)** для архитектуры Monolithic Architecture. Данный документ спроектирован для обеспечения максимальной масштабируемости, безопасности и качества кода при разработке приложений корпоративного уровня. - # Context & Scope - **Primary Goal:** Предоставить строгие архитектурные правила и практические паттерны для создания масштабируемых систем. - **Description:** The entire system components (Database, Message Queues, Business Logic, APIs) are deployed and operated from a single codebase on a single server. - ## Map of Patterns - 📊 [**Data Flow:** Request and Event Lifecycle](./data-flow.md) - 📁 [**Folder Structure:** Layering logic](./folder-structure.md) - ⚖️ [**Trade-offs:** Pros, Cons, and System Constraints](./trade-offs.md) - 🛠️ [**Implementation Guide:** Code patterns and Anti-patterns](./implementation-guide.md) - ## Core Principles 1. **Isolation & Testability:** Changing a single feature doesn't break the entire business process. diff --git a/architectures/monolithic-architecture/trade-offs.md b/architectures/monolithic-architecture/trade-offs.md index c76309e..160f31f 100644 --- a/architectures/monolithic-architecture/trade-offs.md +++ b/architectures/monolithic-architecture/trade-offs.md @@ -1,5 +1,16 @@ -# Monolithic Architecture - Trade-offs - +--- +description: Vibe coding guidelines and architectural constraints for Monolithic Architecture within the Architecture domain. +tags: [monolithic-architecture, architecture, best-practices, architecture] +topic: Monolithic Architecture +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Monolithic Architecture +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Monolithic Architecture Expert +last_updated: 2026-03-29---# Monolithic Architecture - Trade-offs ## Pros, Cons, and System Constraints ### Pros diff --git a/architectures/readme.md b/architectures/readme.md index 44be9f3..2ead870 100644 --- a/architectures/readme.md +++ b/architectures/readme.md @@ -7,10 +7,12 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Software Architect last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # Architecture Best Practices & Production-Ready Patterns - # Context & Scope - **Primary Goal:** Establish definitive rules and best practices for system design and architecture. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -21,9 +23,7 @@ last_updated: 2026-03-22 **The foundation for scalable, maintainable, and reliable applications.** - --- - ## 🌟 The Importance of Architecture in Modern Projects In a world where application logic becomes more complex every day, **Architecture** is not just a folder structure; it is the set of laws by which your code lives. A proper architecture solves three key problems: @@ -32,9 +32,7 @@ In a world where application logic becomes more complex every day, **Architectur 3. **Isolation & Testability:** Changing a single feature doesn't break the entire business process, because the logic is isolated from the UI and third-party libraries. Without strict architecture, even the most modern frameworks (Angular, React, Vue, NestJS) quickly become unmanageable. - --- - ## 💡 Best Tips for Choosing an Architecture Don't know where to start? Here are a few golden rules: @@ -42,13 +40,10 @@ Don't know where to start? Here are a few golden rules: - **Separation of Concerns:** Whichever architecture you choose, always decouple how data is stored (DB) from how it is displayed (UI). - **Match Your Team's Expertise:** Choose the approach that your team understands or is ready to learn. If everyone knows React inside out, use *FSD*. Lone wolves ruin team productivity. - **Embrace Change:** The perfect architecture allows you to painlessly swap your database (e.g., PostgreSQL for MongoDB) or your UI component library without rewriting the core. - --- - ## 🏆 Top 10 Best Architectural Approaches Below are the most popular architectural patterns along with examples, tips, technology stacks, and their logos. A Folder Tree is provided for each to give you a deep understanding of its structure. - --- ### 1. Feature-Sliced Design (FSD) @@ -94,7 +89,6 @@ src/ - **Languages:** TypeScript - **Patterns / Principles:** Public API, Low Coupling, High Cohesion. - **Tools/Libraries:** Redux Toolkit, Zustand, React Router. - --- ### 2. Clean Architecture @@ -134,7 +128,6 @@ src/ - **Languages:** C#, Java, TypeScript - **Patterns / Principles:** SOLID, Dependency Injection (DI), Repository. - **Tools/Libraries:** ORMs (TypeORM, Prisma). - --- ### 3. MVC (Model-View-Controller) @@ -174,7 +167,6 @@ src/ - **Frameworks:** Express.js, Ruby on Rails, Laravel, Django - **Languages:** Ruby, PHP, Python - **Patterns / Principles:** Active Record, REST, DRY. - --- ### 4. Microservices @@ -219,7 +211,6 @@ microservices-cluster/ - **Languages:** Go, Java, Node.js - **Patterns / Principles:** API Gateway, Circuit Breaker, Saga Pattern. - **Tools:** Docker, Kubernetes, gRPC. - --- ### 5. Hexagonal Architecture (Ports & Adapters) @@ -262,7 +253,6 @@ src/ - **Frameworks:** Any strictly-typed IoC frameworks. - **Languages:** TypeScript, C# - **Patterns / Principles:** SOLID, Dependency Inversion (D in SOLID), Adapter. - --- ### 6. DDD (Domain-Driven Design) @@ -304,7 +294,6 @@ src/ - **Frameworks:** Complex Backend ERP or Banking systems. - **Languages:** Highly-typed OOP languages (Java, C#, TypeScript). - **Patterns / Principles:** Bounded Contexts, Value Objects, Aggregates. - --- ### 7. Event-Driven Architecture (EDA) @@ -344,7 +333,6 @@ src/ - **Frameworks/Platforms:** Node.js, Spring Cloud. - **Tools/Libraries:** Apache Kafka, RabbitMQ, Redis Pub/Sub, AWS EventBridge. - **Patterns / Principles:** Pub/Sub, Async Communication, Event Sourcing. - --- ### 8. Serverless (Function-as-a-Service / FaaS) @@ -383,7 +371,6 @@ project-functions/ - **Frameworks:** Serverless Framework, AWS SAM. Clouds: Firebase, Vercel Functions. - **Languages:** Node.js, Python, Go (Languages with fast cold starts). - **Patterns / Principles:** Backend-as-a-Service (BaaS), Vendor Lock-in (use cautiously). - --- ### 9. Monolithic Architecture @@ -422,7 +409,6 @@ monolith-app/ - **Frameworks:** Django, Ruby on Rails, NestJS (without microservices). - **Languages:** Python, PHP, Ruby. - **Patterns / Principles:** Three-Tier Architecture, KISS, YAGNI. - --- ### 10. CQRS (Command Query Responsibility Segregation) diff --git a/architectures/serverless/data-flow.md b/architectures/serverless/data-flow.md index 95cfe53..244dc22 100644 --- a/architectures/serverless/data-flow.md +++ b/architectures/serverless/data-flow.md @@ -1,5 +1,16 @@ -# Serverless - Data Flow - +--- +description: Vibe coding guidelines and architectural constraints for Serverless within the Architecture domain. +tags: [serverless, architecture, best-practices, architecture] +topic: Serverless +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Serverless +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Serverless Expert +last_updated: 2026-03-29---# Serverless - Data Flow ## Request and Event Lifecycle ```mermaid diff --git a/architectures/serverless/folder-structure.md b/architectures/serverless/folder-structure.md index a6dd8cc..ec72b7e 100644 --- a/architectures/serverless/folder-structure.md +++ b/architectures/serverless/folder-structure.md @@ -1,5 +1,16 @@ -# Serverless - Folder Structure - +--- +description: Vibe coding guidelines and architectural constraints for Serverless within the Architecture domain. +tags: [serverless, architecture, best-practices, architecture] +topic: Serverless +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Serverless +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Serverless Expert +last_updated: 2026-03-29---# Serverless - Folder Structure ## Layering logic ```mermaid diff --git a/architectures/serverless/implementation-guide.md b/architectures/serverless/implementation-guide.md index 2642fbb..73678be 100644 --- a/architectures/serverless/implementation-guide.md +++ b/architectures/serverless/implementation-guide.md @@ -1,5 +1,16 @@ -# Serverless - Implementation Guide - +--- +description: Vibe coding guidelines and architectural constraints for Serverless within the Architecture domain. +tags: [serverless, architecture, best-practices, architecture] +topic: Serverless +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Serverless +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Serverless Expert +last_updated: 2026-03-29---# Serverless - Implementation Guide ## Code patterns and Anti-patterns ### Entity Relationships diff --git a/architectures/serverless/readme.md b/architectures/serverless/readme.md index e3926f3..a49235f 100644 --- a/architectures/serverless/readme.md +++ b/architectures/serverless/readme.md @@ -7,26 +7,26 @@ version: Agnostic tags: [architecture, system-design, serverless, best-practices] ai_role: Senior Architect last_updated: 2026-03-22 ---- +topic: Serverless +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
# 🏛️ Serverless Production-Ready Best Practices
- --- Этот инженерный директив определяет **лучшие практики (best practices)** для архитектуры Serverless. Данный документ спроектирован для обеспечения максимальной масштабируемости, безопасности и качества кода при разработке приложений корпоративного уровня. - # Context & Scope - **Primary Goal:** Предоставить строгие архитектурные правила и практические паттерны для создания масштабируемых систем. - **Description:** Developers do not manage servers at all. The entire "server" consists of bite-sized pieces of business logic (functions/Lambdas) living in the cloud. - ## Map of Patterns - 📊 [**Data Flow:** Request and Event Lifecycle](./data-flow.md) - 📁 [**Folder Structure:** Layering logic](./folder-structure.md) - ⚖️ [**Trade-offs:** Pros, Cons, and System Constraints](./trade-offs.md) - 🛠️ [**Implementation Guide:** Code patterns and Anti-patterns](./implementation-guide.md) - ## Core Principles 1. **Isolation & Testability:** Changing a single feature doesn't break the entire business process. diff --git a/architectures/serverless/trade-offs.md b/architectures/serverless/trade-offs.md index 50fa17c..83c79ad 100644 --- a/architectures/serverless/trade-offs.md +++ b/architectures/serverless/trade-offs.md @@ -1,5 +1,16 @@ -# Serverless - Trade-offs - +--- +description: Vibe coding guidelines and architectural constraints for Serverless within the Architecture domain. +tags: [serverless, architecture, best-practices, architecture] +topic: Serverless +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Serverless +domain: Architecture +level: Senior/Architect +version: Latest +ai_role: Senior Serverless Expert +last_updated: 2026-03-29---# Serverless - Trade-offs ## Pros, Cons, and System Constraints ### Pros diff --git a/backend/expressjs/architecture.md b/backend/expressjs/architecture.md index 001abe9..e90a7d3 100644 --- a/backend/expressjs/architecture.md +++ b/backend/expressjs/architecture.md @@ -10,7 +10,6 @@ version: "4.x / 5.x" tags: [best-practices, clean-code, expressjs, vibe-coding, cursor-rules, javascript, typescript, software-architecture, system-design, mvc, production-ready, programming-standards, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, enterprise-patterns, backend] ai_role: Senior Express.js Architecture Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🏗️ Express.js Architecture Best Practices diff --git a/backend/expressjs/readme.md b/backend/expressjs/readme.md index 0af884d..714765f 100644 --- a/backend/expressjs/readme.md +++ b/backend/expressjs/readme.md @@ -7,18 +7,20 @@ version: "4.x / 5.x" tags: [best-practices, clean-code, expressjs, vibe-coding, cursor-rules, javascript, typescript, software-architecture, system-design, mvc, production-ready, programming-standards, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, enterprise-patterns, backend] ai_role: Senior Express.js Backend Expert last_updated: 2026-03-23 ---- +topic: Express.js +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
ExpressJS Logo # 🚂 Express.js Production-Ready Best Practices
- --- Этот документ описывает **лучшие практики (best practices)** для архитектуры Express.js. Фреймворк крайне нетребователен к структуре (unopinionated), поэтому соблюдение этих 30 строгих правил критично для поддержания чистоты и безопасности энтерпрайз-кода. - # Context & Scope - **Primary Goal:** Предоставить жесткий архитектурный каркас MVC и 30 паттернов для создания безопасных Express.js API. - **Target Tooling:** AI-агенты (Cursor, Windsurf, Copilot) и Senior-разработчики. @@ -26,10 +28,8 @@ last_updated: 2026-03-23 > [!IMPORTANT] > **Архитектурный стандарт (Contract):** Никогда не пишите бизнес-логику в роутерах. Строго разделяйте ответственности на `Router`, `Controller` и `Service`. - --- - ## 🔄 Architecture Data Flow ```mermaid @@ -58,13 +58,10 @@ sequenceDiagram ErrorMW-->>Client: Standardized Error Response end ``` - ## 📚 Specialized Documentation - [architecture.md](./architecture.md) - [security-best-practices.md](./security-best-practices.md) - ---- -## 1. Controller / Route Decoupling +---## 1. Controller / Route Decoupling ### ❌ Bad Practice ```javascript app.post('/api/users', async (req, res) => { @@ -82,6 +79,9 @@ class UserController { ### 🚀 Solution Роутер только описывает эндпоинты, Контроллер извлекает данные запроса и отдает ответ. Логика — в Сервисах. + +### ⚠️ Problem +[Analysis of the risks] ## 2. Async/Await Error Wrapping (Express 4) ### ❌ Bad Practice ```javascript @@ -95,6 +95,9 @@ router.get('/', asyncHandler(UserController.get)); ### 🚀 Solution В Express 4 всегда оборачивайте async-маршруты в `asyncHandler`, чтобы пробрасывать ошибки в глобальный Error Handler. (В Express 5 это встроено). + +### ⚠️ Problem +[Analysis of the risks] ## 3. Global Error Handler Middleware ### ❌ Bad Practice ```javascript @@ -110,6 +113,9 @@ app.use((err, req, res, next) => { ### 🚀 Solution Определите единую middleware с 4 аргументами `(err, req, res, next)` в самом конце пайплайна для перехвата всех сбоев. + +### ⚠️ Problem +[Analysis of the risks] ## 4. Request Payload Validation (Joi / Zod) ### ❌ Bad Practice ```javascript @@ -127,6 +133,9 @@ router.post('/', validate(userSchema), UserController.create); ### 🚀 Solution Проверяйте тело и параметры запросов на уровне Middleware с помощью надежных библиотек валидации (Joi, Zod), не пуская мусор в контроллеры. + +### ⚠️ Problem +[Analysis of the risks] ## 5. Environment Variables separation ### ❌ Bad Practice ```javascript @@ -140,6 +149,9 @@ mongoose.connect(process.env.DB_URI); ### 🚀 Solution Используйте `dotenv` и конфигурационные файлы для разных окружений. Секреты хранятся только в `.env` (который добавлен в `.gitignore`). + +### ⚠️ Problem +[Analysis of the risks] ## 6. HTTP Security Headers (Helmet) ### ❌ Bad Practice // Приложение светит 'X-Powered-By: Express' @@ -151,6 +163,9 @@ app.use(helmet()); ### 🚀 Solution Используйте `helmet` для автоматической защиты от XSS, clickjacking и скрытия заголовков фреймворка из коробки. + +### ⚠️ Problem +[Analysis of the risks] ## 7. Cross-Origin Resource Sharing (CORS) ### ❌ Bad Practice ```javascript @@ -164,6 +179,9 @@ app.use(cors({ origin: 'https://myapp.com', credentials: true })); ### 🚀 Solution Используйте официальный модуль `cors`. Разрешайте доступ только доверенным доменам, а не всем подряд (`*`). + +### ⚠️ Problem +[Analysis of the risks] ## 8. Rate Limiting (Защита от DDoS) ### ❌ Bad Practice // API открыт для миллиона запросов в секунду @@ -175,6 +193,9 @@ app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); ### 🚀 Solution Защищайте все эндпоинты (а особенно авторизацию) встроенным лимитером запросов. + +### ⚠️ Problem +[Analysis of the risks] ## 9. Body Parsing & Payload Limits ### ❌ Bad Practice ```javascript @@ -188,6 +209,9 @@ app.use(express.urlencoded({ extended: true, limit: '10kb' })); ### 🚀 Solution Строго ограничивайте размер принимаемого JSON через опцию `limit`, чтобы предотвратить исчерпание RAM. + +### ⚠️ Problem +[Analysis of the risks] ## 10. Centralized Logging (Morgan + Winston) ### ❌ Bad Practice ```javascript @@ -201,6 +225,9 @@ winstonLogger.info('User signed in'); ### 🚀 Solution Заменяйте `console.log` на логгеры вроде Winston (с уровнями log/warn/error) и Morgan (для фиксации HTTP-запросов). + +### ⚠️ Problem +[Analysis of the risks] ## 11. Database Connection Management ### ❌ Bad Practice ```javascript @@ -215,6 +242,9 @@ mongoose.connect(process.env.DB_URI).then(() => { ### 🚀 Solution Открывайте единый пул подключений к БД (Connection Pool) при запуске приложения и используйте его во всех контроллерах. + +### ⚠️ Problem +[Analysis of the risks] ## 12. JWT Authentication Middleware ### ❌ Bad Practice ```javascript @@ -232,6 +262,9 @@ const authGuard = (req, res, next) => { ### 🚀 Solution Аутентификация должна представлять собой изолированную Middleware, которая вешается на защищенные маршруты и прикрепляет объект `req.user`. + +### ⚠️ Problem +[Analysis of the risks] ## 13. Role-Based Access Control (RBAC) Middleware ### ❌ Bad Practice ```javascript @@ -248,6 +281,9 @@ router.delete('/:id', requireRole('admin', 'manager'), Controller.del); ### 🚀 Solution Доступ к маршрутам по ролям должен задаваться декларативно через Middleware. + +### ⚠️ Problem +[Analysis of the risks] ## 14. Standard API Response Wrapper ### ❌ Bad Practice ```javascript @@ -263,6 +299,9 @@ class ApiResponse { ### 🚀 Solution Используйте единый класс-утилиту для отправки ответов, чтобы клиент всегда ожидал `success` и `data`/`error` поля. + +### ⚠️ Problem +[Analysis of the risks] ## 15. Pagination details in API ### ❌ Bad Practice ```javascript @@ -277,6 +316,9 @@ res.json({ data: users, meta: { total, page, limit, pages: Math.ceil(total/limit ### 🚀 Solution Любой список сущностей обязан иметь пагинацию (Offset или Cursor) и секцию `meta` в ответе. + +### ⚠️ Problem +[Analysis of the risks] ## 16. Graceful Shutdown ### ❌ Bad Practice // При получении SIGTERM сервер моментально обрывает процессы @@ -291,6 +333,9 @@ process.on('SIGTERM', () => { ### 🚀 Solution Корректно закрывайте активные HTTP-сессии и пулы подключений к БД перед остановкой контейнера. + +### ⚠️ Problem +[Analysis of the risks] ## 17. 404 Route Handler ### ❌ Bad Practice // Если роут не найден, возвращается пустая белая страница @@ -303,6 +348,9 @@ app.use('*', (req, res) => { ### 🚀 Solution Поместите этот обработчик ПОСЛЕ всех ваших маршрутов (но ДО глобального обработчика ошибок). + +### ⚠️ Problem +[Analysis of the risks] ## 18. Application Structure (Folder organization) ### ❌ Bad Practice ``` @@ -321,6 +369,9 @@ src/ ### 🚀 Solution Строго разделяйте проект на логические папки. Имплементируйте многослойную архитектуру. + +### ⚠️ Problem +[Analysis of the risks] ## 19. Health Check Endpoint ### ❌ Bad Practice // Нет проверки жизнеспособности подов Kubernetes @@ -333,6 +384,9 @@ app.get('/health', (req, res) => { ### 🚀 Solution Всегда имейте эндпоинт `/health` для систем мониторинга, балансировщиков и Health Probes. + +### ⚠️ Problem +[Analysis of the risks] ## 20. Data Sanitization (XSS / NoSQL Injection) ### ❌ Bad Practice ```javascript @@ -348,6 +402,9 @@ app.use(xss()); ### 🚀 Solution Защищайте БД от NoSQL-инъекций и XSS скриптов, очищая `req.body` и `req.query`. + +### ⚠️ Problem +[Analysis of the risks] ## 21. Swagger / OpenAPI documentation ### ❌ Bad Practice // Документация в стороннем Word-файле @@ -360,6 +417,9 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); ### 🚀 Solution Генерируйте или обслуживайте API-документацию прямо в приложении (Swagger, OpenAPI). + +### ⚠️ Problem +[Analysis of the risks] ## 22. Manual Dependency Injection ### ❌ Bad Practice ```javascript @@ -375,6 +435,9 @@ const controller = new UserController(new UserService(db)); ### 🚀 Solution Если не используете IoC (Awilix), инжектируйте зависимости вручную для облегчения Unit-тестирования. + +### ⚠️ Problem +[Analysis of the risks] ## 23. File Uploads (Multer) ### ❌ Bad Practice // Парсинг бинарников руками @@ -387,6 +450,9 @@ router.post('/avatar', upload.single('file'), Controller.upload); ### 🚀 Solution Используйте `multer` с обязательным ограничением размера файла (`limits`), чтобы обезопасить сервер от переполнения диска. + +### ⚠️ Problem +[Analysis of the risks] ## 24. Event Emitters (Фоновые задачи) ### ❌ Bad Practice ```javascript @@ -405,6 +471,9 @@ res.send('Welcome'); ### 🚀 Solution Снимайте длительные задачи с основного потока ответа с помощью нативных Events NodeJS. + +### ⚠️ Problem +[Analysis of the risks] ## 25. Caching (Redis Middleware) ### ❌ Bad Practice // БД обрабатывает сложные расчеты на каждый хит @@ -420,6 +489,9 @@ const cacheMiddleware = (req, res, next) => { ### 🚀 Solution Используйте кэширование (Redis) для GET-запросов, результат которых меняется редко. + +### ⚠️ Problem +[Analysis of the risks] ## 26. Custom Error Classes ### ❌ Bad Practice ```javascript @@ -439,6 +511,9 @@ throw new AppError('User not found', 404); ### 🚀 Solution Создавайте кастомные классы ошибок, чтобы глобальный логгер мог отличать операционные ошибки (Operational) от фатальных крашей кода. + +### ⚠️ Problem +[Analysis of the risks] ## 27. Proxy Trust in Production ### ❌ Bad Practice ```javascript @@ -451,6 +526,9 @@ app.set('trust proxy', 1); // Доверяем первому прокси ### 🚀 Solution Если Express стоит за Nginx / AWS ELB, включите `trust proxy`, чтобы получать реальные IP пользователей. + +### ⚠️ Problem +[Analysis of the risks] ## 28. Separating Server from App ### ❌ Bad Practice ```javascript @@ -469,6 +547,9 @@ app.listen(3000); ### 🚀 Solution Экспортируйте Express App отдельно от `listen`, чтобы `supertest` мог легко запускать тесты на случайных портах. + +### ⚠️ Problem +[Analysis of the risks] ## 29. UUID Request Correlation ### ❌ Bad Practice // Ошибки в логах невозможно связать с конкретным пользователем @@ -484,6 +565,9 @@ app.use((req, res, next) => { ### 🚀 Solution Устанавливайте уникальный ID каждому запросу для отслеживания его пути по всем логам и микросервисам. + +### ⚠️ Problem +[Analysis of the risks] ## 30. Secure Session Management ### ❌ Bad Practice // Сессия хранится в памяти (MemoryStore) с открытыми куками @@ -504,3 +588,7 @@ app.use(session({
Применяйте данные паттерны для построения максимально безопасной, быстрой и прозрачной архитектуры на Express.js! 🚂
+ + +### ⚠️ Problem +[Analysis of the risks] diff --git a/backend/expressjs/security-best-practices.md b/backend/expressjs/security-best-practices.md index e8fe31e..f9d402e 100644 --- a/backend/expressjs/security-best-practices.md +++ b/backend/expressjs/security-best-practices.md @@ -10,7 +10,6 @@ version: "4.x / 5.x" tags: [best-practices, clean-code, security-patterns, vibe-coding, cursor-rules, expressjs, software-architecture, system-design, solid-principles, production-ready, programming-standards, node-js, security, scalable-code, windsurf-rules, ai-coding, enterprise-patterns] ai_role: Senior Express.js Security Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🔒 Express.js Security Best Practices diff --git a/backend/microservices/api-design.md b/backend/microservices/api-design.md index a9edafd..4bbf083 100644 --- a/backend/microservices/api-design.md +++ b/backend/microservices/api-design.md @@ -10,7 +10,6 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, microservices, distributed-systems, system-design, solid-principles, production-ready, scalable-code] ai_role: Senior Microservices Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🧩 Microservices API Design diff --git a/backend/microservices/architecture.md b/backend/microservices/architecture.md index fa8c3b3..3836708 100644 --- a/backend/microservices/architecture.md +++ b/backend/microservices/architecture.md @@ -10,7 +10,6 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, microservices, distributed-systems, system-design, solid-principles, production-ready, scalable-code] ai_role: Senior Microservices Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🧩 Microservices Architecture diff --git a/backend/microservices/readme.md b/backend/microservices/readme.md index 673be9c..a3f00bd 100644 --- a/backend/microservices/readme.md +++ b/backend/microservices/readme.md @@ -10,19 +10,17 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, microservices, distributed-systems, system-design, solid-principles, production-ready, scalable-code] ai_role: Senior Microservices Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- +
Microservices Logo # 🧩 Microservices Production-Ready Best Practices
- --- This document establishes **best practices** for designing and maintaining a Microservices architecture. These constraints guarantee a scalable, highly secure, and clean system suitable for an enterprise-level, production-ready backend. - # ⚙️ Context & Scope - **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for distributed system environments. - **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and System Architects. @@ -30,9 +28,7 @@ This document establishes **best practices** for designing and maintaining a Mic > [!IMPORTANT] > **Architectural Standard (Contract):** Ensure loose coupling and high cohesion. Each microservice must own its domain data. Use asynchronous messaging (e.g., Kafka, RabbitMQ) for inter-service communication to prevent cascading failures. - --- - ## 🏗️ 1. Architecture & Design ### Domain-Driven Design (DDD) @@ -62,7 +58,6 @@ sequenceDiagram Msg->>Notification: Consume "UserCreated" Event Notification-->>Notification: Send Welcome Email ``` - ## 🔒 2. Security Best Practices ### Service-to-Service Authentication @@ -71,7 +66,6 @@ sequenceDiagram ### Data Isolation - Enforce "Database per Service" pattern. Services must never share a single database to ensure independent scaling and deployment. - ## 🚀 3. Reliability Optimization ### Resilience Patterns @@ -82,12 +76,10 @@ sequenceDiagram ### Observability - Distributed Tracing is mandatory (OpenTelemetry). All requests must pass a Correlation ID across service boundaries. - Centralized Logging (ELK, Datadog) is required for debugging complex distributed issues. - ## 📚 Specialized Documentation - [architecture.md](./architecture.md) - [security-best-practices.md](./security-best-practices.md) - [api-design.md](./api-design.md) - --- [Back to Top](#) diff --git a/backend/microservices/security-best-practices.md b/backend/microservices/security-best-practices.md index 26791c8..b79fa3a 100644 --- a/backend/microservices/security-best-practices.md +++ b/backend/microservices/security-best-practices.md @@ -10,7 +10,6 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, microservices, distributed-systems, system-design, solid-principles, production-ready, scalable-code] ai_role: Senior Microservices Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🧩 Microservices Security Best Practices diff --git a/backend/mongodb/architecture.md b/backend/mongodb/architecture.md index 162f549..abc2124 100644 --- a/backend/mongodb/architecture.md +++ b/backend/mongodb/architecture.md @@ -10,13 +10,11 @@ version: "7.0+" tags: [architecture-patterns, mongodb, nosql, database, system-design, production-ready, scalable-code] ai_role: Senior MongoDB Database Architect last_updated: 2026-03-28 -last_evolution: 2026-03-28 ---- +last_evolution: 2026-03-28--- # 🏛️ MongoDB Architecture Constraints This document provides the "executable blueprints" for MongoDB architecture, outlining folder hierarchies, request/data flows, and entity relationships to ensure AI-agent readiness. - ## 📂 Folder Hierarchy Constraints ```mermaid @@ -41,7 +39,6 @@ graph TD class domains,user,order,schemas,models,repositories domain; class core,database,connection,config core; ``` - ## 🔄 Request / Data Flow ```mermaid @@ -61,7 +58,6 @@ sequenceDiagram Service-->>Controller: Domain Response Controller-->>Client: 201 Created (Response DTO) ``` - ## 🔗 Entity Relationships ```mermaid @@ -98,7 +94,6 @@ classDiagram User "1" --> "*" Comment : writes Post "1" --> "*" Comment : contains ``` - --- [⬆ Back to Top](#-mongodb-architecture-constraints) diff --git a/backend/mongodb/database-optimization.md b/backend/mongodb/database-optimization.md index f3c5228..5acd6fa 100644 --- a/backend/mongodb/database-optimization.md +++ b/backend/mongodb/database-optimization.md @@ -10,13 +10,11 @@ version: "7.0+" tags: [database-optimization, mongodb, nosql, indexing, aggregation-pipeline, system-design, production-ready, scalable-code] ai_role: Senior MongoDB Database Architect last_updated: 2026-03-28 -last_evolution: 2026-03-28 ---- +last_evolution: 2026-03-28--- # ⚡ MongoDB Database Optimization Best Practices This document outlines indexing strategies (ESR Rule), aggregation pipeline optimization, and query tuning for enterprise-grade MongoDB environments. - ## 🎯 1. The ESR (Equality, Sort, Range) Rule When designing indexes, always follow the ESR rule to maximize efficiency. @@ -47,8 +45,10 @@ Create indexes following the ESR rule: db.orders.createIndex({ status: 1, date: 1, amount: 1 }) ``` ---- +### ⚠️ Problem +[Analysis of the risks] +--- ## 🏗️ 2. Aggregation Pipeline Optimization Pipelines process documents in stages. Optimizing the order of these stages dramatically improves performance. @@ -79,8 +79,10 @@ db.users.aggregate([ ]) ``` ---- +### ⚠️ Problem +[Analysis of the risks] +--- ## 📉 3. Covered Queries A covered query is a query that can be satisfied entirely using an index, without having to examine the actual documents. @@ -97,6 +99,17 @@ db.orders.find( ) ``` + +### ❌ Bad Practice +[Need to fill in example of non-optimal code] + + +### ⚠️ Problem +[Analysis of the risks] + + +### ✅ Best Practice +[Reference deterministic implementation] --- [⬆ Back to Top](#-mongodb-database-optimization-best-practices) diff --git a/backend/mongodb/readme.md b/backend/mongodb/readme.md index eab4d65..2cdc320 100644 --- a/backend/mongodb/readme.md +++ b/backend/mongodb/readme.md @@ -10,19 +10,17 @@ version: "7.0+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, mongodb, nosql, database, system-design, production-ready, scalable-code, document-database] ai_role: Senior MongoDB Database Architect last_updated: 2026-03-28 -last_evolution: 2026-03-28 ---- +last_evolution: 2026-03-28--- +
MongoDB Logo # 🍃 MongoDB Production-Ready Best Practices
- --- This document establishes **best practices** for building and maintaining MongoDB databases. These constraints guarantee a scalable, highly secure, and clean architecture suitable for an enterprise-level, production-ready backend. - # ⚙️ Context & Scope - **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for MongoDB environments. - **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and Senior Database Administrators. @@ -30,9 +28,7 @@ This document establishes **best practices** for building and maintaining MongoD > [!IMPORTANT] > **Architectural Contract:** MongoDB is schema-less by nature, but production applications require strict schema validation at the database level and through ORM/ODMs like Mongoose. Never allow unstructured data to enter the persistence layer without validation. - --- - ## 📚 Specialized Documentation For deep dives into specific topics, consult the specialized guides: @@ -40,9 +36,7 @@ For deep dives into specific topics, consult the specialized guides: - 🏛️ [**Architecture & Design**](./architecture.md): Boundary definitions, entity relationships, and structural constraints. - ⚡ [**Database Optimization**](./database-optimization.md): Indexing strategies (ESR Rule) and aggregation pipelines. - 🔒 [**Security Best Practices**](./security-best-practices.md): RBAC, field-level encryption, and NoSQL injection prevention. - --- - ## 🏗️ Core Principles ### 🚨 1. Schema Validation @@ -81,6 +75,9 @@ db.createCollection("users", { }); ``` + +### ⚠️ Problem +[Analysis of the risks] --- [⬆ Back to Top](#-mongodb-production-ready-best-practices) diff --git a/backend/mongodb/security-best-practices.md b/backend/mongodb/security-best-practices.md index 000b1ff..1a9c93e 100644 --- a/backend/mongodb/security-best-practices.md +++ b/backend/mongodb/security-best-practices.md @@ -10,13 +10,11 @@ version: "7.0+" tags: [security-best-practices, mongodb, nosql, database, authentication, authorization, rbac, encryption, injection-prevention, production-ready, scalable-code] ai_role: Senior MongoDB Database Architect last_updated: 2026-03-28 -last_evolution: 2026-03-28 ---- +last_evolution: 2026-03-28--- # 🔒 MongoDB Security Best Practices This document outlines essential security controls for enterprise-level MongoDB deployments, focusing on RBAC, encryption at rest, and preventing NoSQL injections. - ## 🛡️ 1. Authentication and Authorization (RBAC) Ensure MongoDB requires authentication and enforce Role-Based Access Control (RBAC) to limit privileges to the absolute minimum necessary. @@ -54,8 +52,10 @@ db.createUser({ }); ``` ---- +### ⚠️ Problem +[Analysis of the risks] +--- ## 🔐 2. NoSQL Injection Prevention MongoDB queries can be vulnerable to NoSQL injection if user input is not properly sanitized or if raw operator objects are passed directly to query parameters. @@ -93,8 +93,10 @@ const user = await db.collection('users').findOne({ }); ``` ---- +### ⚠️ Problem +[Analysis of the risks] +--- ## 🗄️ 3. Encryption at Rest Protect data stored on disk by enabling encryption at rest, ensuring that unauthorized parties cannot access the database files if the host is compromised. @@ -106,13 +108,23 @@ Enable WiredTiger encryption at rest using a robust Key Management Service (KMS) ### 🚀 Configuration ```yaml + +### ❌ Bad Practice +[Need to fill in example of non-optimal code] + + +### ⚠️ Problem +[Analysis of the risks] + + +### 🚀 Solution +[Architectural justification of the solution] # mongod.conf security: enableEncryption: true encryptionCipherMode: AES256-CBC encryptionKeyFile: /path/to/master/key/file ``` - --- [⬆ Back to Top](#-mongodb-security-best-practices) diff --git a/backend/nestjs/architecture.md b/backend/nestjs/architecture.md index 3c78f05..17b0cee 100644 --- a/backend/nestjs/architecture.md +++ b/backend/nestjs/architecture.md @@ -10,7 +10,6 @@ version: "11+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior NestJS Architecture Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🏗️ NestJS 11+ Architecture Best Practices diff --git a/backend/nestjs/readme.md b/backend/nestjs/readme.md index e6862e4..c16b589 100644 --- a/backend/nestjs/readme.md +++ b/backend/nestjs/readme.md @@ -7,18 +7,20 @@ version: "11+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior NestJS Architecture Expert last_updated: 2026-03-23 ---- +topic: NestJS +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
NestJS Logo # 🦁 NestJS Production-Ready Best Practices
- --- Этот документ определяет **лучшие практики (best practices)** для фреймворка NestJS. Руководство создано для обеспечения масштабируемости, безопасности и качества Enterprise-приложений. - ## 🎯 Context & Scope - **Primary Goal:** Предоставить строгие архитектурные правила и 30 паттернов разработки на NestJS. - **Target Tooling:** AI-агенты (Cursor, Windsurf, Copilot) и Senior-разработчики. @@ -26,10 +28,8 @@ last_updated: 2026-03-23 > [!IMPORTANT] > **Архитектурный стандарт (Contract):** Используйте строгую типизацию TypeScript, DI (Dependency Injection) и модульную структуру. Бизнес-логика должна быть изолирована от деталей HTTP-уровня и баз данных. - --- - ## 🔄 Architecture Data Flow ```mermaid @@ -56,11 +56,9 @@ sequenceDiagram Controller-->>Client: HTTP Response ``` - ## 📚 Specialized Documentation - [architecture.md](./architecture.md) - [security-best-practices.md](./security-best-practices.md) - --- ### 🚨 1. Clean Architecture Modules (Изоляция логики) #### ❌ Bad Practice @@ -100,7 +98,7 @@ app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: t #### ❌ Bad Practice ```typescript @Post() -create(@Body() body: any) {} // Потеря типизации +create(@Body() body: unknown) {} // Потеря типизации ``` #### ✅ Best Practice ```typescript @@ -364,7 +362,7 @@ handleCron() { this.cleanupData(); } #### ✅ Best Practice ```typescript @MessagePattern({ cmd: 'get_user' }) -getUser(data: any) { return this.userService.findById(data.id); } +getUser(data: unknown) { return this.userService.findById(data.id); } ``` #### 🚀 Solution Для общения микросервисов внутри кластера используйте TCP, Redis или RabbitMQ через `@MessagePattern`. @@ -498,6 +496,9 @@ app.enableShutdownHooks(); #### 🚀 Solution Вызывайте `enableShutdownHooks()`, чтобы отлавливать SIGINT/SIGTERM и безопасно завершать процессы базы данных. + +### ⚠️ Problem +[Analysis of the risks] --- [⬆️ Back to Top](#) diff --git a/backend/nestjs/security-best-practices.md b/backend/nestjs/security-best-practices.md index fcde639..07add05 100644 --- a/backend/nestjs/security-best-practices.md +++ b/backend/nestjs/security-best-practices.md @@ -10,7 +10,6 @@ version: "11+" tags: [best-practices, clean-code, security-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, node-js, security, scalable-code, windsurf-rules, ai-coding, enterprise-patterns] ai_role: Senior NestJS Security Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🔒 NestJS 11+ Security Best Practices diff --git a/backend/nodejs/readme.md b/backend/nodejs/readme.md index fd58ada..ddf2742 100644 --- a/backend/nodejs/readme.md +++ b/backend/nodejs/readme.md @@ -7,18 +7,20 @@ version: "24+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, javascript, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Node.js Architecture Expert last_updated: 2026-03-23 ---- +topic: Node.js +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- +
Node.js Logo # 🟢 Node.js Production-Ready Best Practices
- --- This document establishes **best practices** for building and maintaining Node.js applications. These constraints guarantee a scalable, highly secure, and clean architecture suitable for an enterprise-level, production-ready backend. - # ⚙️ Context & Scope - **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for pure Node.js environments. - **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and Senior Developers. @@ -26,9 +28,7 @@ This document establishes **best practices** for building and maintaining Node.j > [!IMPORTANT] > **Architectural Contract:** Code must be completely asynchronous. Absolutely avoid synchronous blocking methods like `readFileSync` or `crypto.pbkdf2Sync` on the main thread. Delegate heavy computational tasks to Worker Threads or separate microservices to keep the event loop non-blocking. - --- - ## 🏗️ Architecture & Component Isolation Node.js applications must use explicit module separation to handle logic appropriately. @@ -51,9 +51,7 @@ graph TD class D component; class E layout; ``` - --- - ## 1. ⚡ Blocking the Event Loop ### ❌ Bad Practice ```javascript @@ -76,6 +74,9 @@ app.post('/hash', (req, res, next) => { ### 🚀 Solution Never use synchronous methods (`*Sync`) on the main thread for crypto, I/O, or heavy calculations. Always use asynchronous callbacks or Promises to prevent blocking the Event Loop. + +### ⚠️ Problem +[Analysis of the risks] ## 2. 🗂️ Project Structure & Module Separation ### ❌ Bad Practice ```text @@ -93,6 +94,9 @@ Never use synchronous methods (`*Sync`) on the main thread for crypto, I/O, or h ### 🚀 Solution Implement a multi-layered folder architecture. Strictly separate the HTTP transport layer (Routes/Controllers) from the Business Logic (Services) and Database operations. + +### ⚠️ Problem +[Analysis of the risks] ## 3. 🛡️ Strict Environment Configuration ### ❌ Bad Practice ```javascript @@ -112,6 +116,9 @@ requiredEnv.forEach((name) => { ### 🚀 Solution Fail fast. Validate all necessary environment variables upon application startup to prevent fatal runtime errors later in execution. + +### ⚠️ Problem +[Analysis of the risks] ## 4. 🛑 Error Handling with Custom Classes ### ❌ Bad Practice ```javascript @@ -131,6 +138,9 @@ if (!user) throw new AppError('User not found', 404); ### 🚀 Solution Extend the built-in `Error` object to create custom operational errors. This allows your global error handler to safely log and return predictable HTTP status codes without crashing the application. + +### ⚠️ Problem +[Analysis of the risks] ## 5. 🎛️ Handling Uncaught Exceptions & Rejections ### ❌ Bad Practice // Ignoring process-level events, allowing the app to run in an unpredictable state after an error. @@ -149,6 +159,9 @@ process.on('unhandledRejection', (err) => { ### 🚀 Solution Always capture `uncaughtException` and `unhandledRejection`. Log the fatal error immediately and shut down the process safely. Rely on a process manager (like PM2 or Kubernetes) to restart the container. + +### ⚠️ Problem +[Analysis of the risks] ## 6. 🔒 Hiding Sensitive Headers ### ❌ Bad Practice // Sending default headers that expose the framework, like `X-Powered-By: Express`. @@ -161,6 +174,9 @@ app.use(helmet()); ### 🚀 Solution Sanitize outgoing HTTP headers to prevent information leakage about the server infrastructure. + +### ⚠️ Problem +[Analysis of the risks] ## 7. ⏱️ Implementing Graceful Shutdown ### ❌ Bad Practice // Application crashes abruptly during deployments, interrupting active user requests and corrupting database transactions. @@ -180,6 +196,9 @@ process.on('SIGTERM', () => { ### 🚀 Solution Listen for termination signals (`SIGTERM`, `SIGINT`). Finish processing ongoing HTTP requests and safely close database connections before exiting the Node.js process. + +### ⚠️ Problem +[Analysis of the risks] ## 8. 🔍 Input Validation and Sanitization ### ❌ Bad Practice ```javascript @@ -198,6 +217,9 @@ const user = await db.query('SELECT * FROM users WHERE email = $1', [value.email ### 🚀 Solution Never trust external data. Validate input strictly using schema definitions and always utilize parameterized queries or an ORM to prevent SQL/NoSQL Injection attacks. + +### ⚠️ Problem +[Analysis of the risks] ## 9. 🚀 Utilizing Worker Threads for Heavy Tasks ### ❌ Bad Practice ```javascript @@ -221,6 +243,9 @@ function processImageAsync(buffer) { ### 🚀 Solution Offload CPU-intensive operations (image processing, video encoding, heavy cryptographic tasks) to Node.js `worker_threads` to keep the primary event loop highly responsive for API requests. + +### ⚠️ Problem +[Analysis of the risks] ## 10. 📝 Centralized and Structured Logging ### ❌ Bad Practice ```javascript @@ -245,3 +270,7 @@ Avoid `console.log`. Use a sophisticated logging library (like Pino or Winston)
Enforce these Core Node.js constraints to ensure a highly scalable, stable, and performant backend system! 🟢
+ + +### ⚠️ Problem +[Analysis of the risks] diff --git a/backend/postgresql/architecture.md b/backend/postgresql/architecture.md index 80e63dd..f997010 100644 --- a/backend/postgresql/architecture.md +++ b/backend/postgresql/architecture.md @@ -10,7 +10,6 @@ version: "16+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, postgresql, database, sql, rdbms, system-design, production-ready, scalable-code] ai_role: Senior PostgreSQL Database Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🐘 PostgreSQL Architecture diff --git a/backend/postgresql/database-optimization.md b/backend/postgresql/database-optimization.md index fe1c164..9801005 100644 --- a/backend/postgresql/database-optimization.md +++ b/backend/postgresql/database-optimization.md @@ -10,7 +10,6 @@ version: "16+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, postgresql, database, sql, rdbms, system-design, production-ready, scalable-code] ai_role: Senior PostgreSQL Database Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🐘 PostgreSQL Database Optimization diff --git a/backend/postgresql/readme.md b/backend/postgresql/readme.md index 2a9a547..d2b6e49 100644 --- a/backend/postgresql/readme.md +++ b/backend/postgresql/readme.md @@ -10,19 +10,17 @@ version: "16+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, postgresql, database, sql, rdbms, system-design, production-ready, scalable-code] ai_role: Senior PostgreSQL Database Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- +
PostgreSQL Logo # 🐘 PostgreSQL Production-Ready Best Practices
- --- This document establishes **best practices** for building and maintaining PostgreSQL databases. These constraints guarantee a scalable, highly secure, and clean architecture suitable for an enterprise-level, production-ready backend. - # ⚙️ Context & Scope - **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for PostgreSQL environments. - **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and Senior Database Administrators. @@ -30,9 +28,7 @@ This document establishes **best practices** for building and maintaining Postgr > [!IMPORTANT] > **Architectural Standard (Contract):** Use strict data types, enforce referential integrity, and optimize queries with appropriate indexing. Avoid business logic in stored procedures unless strictly necessary for performance. - --- - ## 🏗️ 1. Architecture & Design ### Database Schema Design @@ -54,7 +50,6 @@ sequenceDiagram DB-->>App: Return Result Set App->>Pool: Release Connection ``` - ## 🔒 2. Security Best Practices ### Connection Security @@ -64,7 +59,6 @@ sequenceDiagram ### Access Control - Principle of Least Privilege (PoLP): Create specific database roles for different application services. Never use the `postgres` superuser for application access. - Implement Row-Level Security (RLS) for multi-tenant applications to isolate data at the database layer. - ## 🚀 3. Performance Optimization ### Indexing Strategies @@ -76,12 +70,10 @@ sequenceDiagram - Explicit DB queries required: Never use `SELECT *`. Only select the specific columns needed. - Utilize `EXPLAIN ANALYZE` to identify query bottlenecks. - Implement pagination using keyset pagination (cursor-based) instead of `OFFSET`/`LIMIT` for large datasets. - ## 📚 Specialized Documentation - [architecture.md](./architecture.md) - [security-best-practices.md](./security-best-practices.md) - [database-optimization.md](./database-optimization.md) - --- [Back to Top](#) diff --git a/backend/postgresql/security-best-practices.md b/backend/postgresql/security-best-practices.md index 9d07fa1..70d2800 100644 --- a/backend/postgresql/security-best-practices.md +++ b/backend/postgresql/security-best-practices.md @@ -10,7 +10,6 @@ version: "16+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, postgresql, database, sql, rdbms, system-design, production-ready, scalable-code] ai_role: Senior PostgreSQL Database Architect last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🐘 PostgreSQL Security Best Practices diff --git a/backend/readme.md b/backend/readme.md index f39e643..19b2aa7 100644 --- a/backend/readme.md +++ b/backend/readme.md @@ -7,10 +7,12 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Backend Architect last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # Backend Best Practices & Production-Ready Patterns - # Context & Scope - **Primary Goal:** Outline the overarching philosophy and standards for Backend and system development inside the ecosystem. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -21,14 +23,11 @@ last_updated: 2026-03-22 **The foundational rules and standards governing backend logic.** - --- - ## Architecture Principles - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications, specifically Hexagonal Architecture / Clean Architecture. - Avoid tightly coupling business domains to framework-specific libraries. - ## Technical Requirements for AI Generation > [!IMPORTANT] @@ -36,7 +35,6 @@ last_updated: 2026-03-22 - **Security First:** Validate all inputs using schema validations. Assume all external input is malicious. - **TypeScript Strictness:** `any` is strictly prohibited. Enforce boundary definitions between the transport and core logic layers. - ## Technologies Included diff --git a/backend/redis/api-design.md b/backend/redis/api-design.md index 39e0f1a..226b538 100644 --- a/backend/redis/api-design.md +++ b/backend/redis/api-design.md @@ -10,7 +10,6 @@ version: "7+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, redis, in-memory, nosql, system-design, production-ready, scalable-code] ai_role: Senior Redis Architecture Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🟥 Redis API Design diff --git a/backend/redis/architecture.md b/backend/redis/architecture.md index 1292c5b..be57a04 100644 --- a/backend/redis/architecture.md +++ b/backend/redis/architecture.md @@ -10,7 +10,6 @@ version: "7+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, redis, in-memory, nosql, system-design, production-ready, scalable-code] ai_role: Senior Redis Architecture Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🟥 Redis Architecture diff --git a/backend/redis/readme.md b/backend/redis/readme.md index 33a5211..8c48902 100644 --- a/backend/redis/readme.md +++ b/backend/redis/readme.md @@ -10,19 +10,17 @@ version: "7+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, redis, in-memory, nosql, system-design, production-ready, scalable-code] ai_role: Senior Redis Architecture Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- +
Redis Logo # 🟥 Redis Production-Ready Best Practices
- --- This document establishes **best practices** for building and maintaining Redis data stores. These constraints guarantee a scalable, highly secure, and clean architecture suitable for an enterprise-level, production-ready backend. - # ⚙️ Context & Scope - **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for Redis environments. - **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and Senior Backend Developers. @@ -30,9 +28,7 @@ This document establishes **best practices** for building and maintaining Redis > [!IMPORTANT] > **Architectural Standard (Contract):** Utilize Redis primarily as a caching layer, session store, or message broker, not as a primary persistence database. Never use `KEYS *` in production. - --- - ## 🏗️ 1. Architecture & Design ### Cache Design @@ -62,7 +58,6 @@ sequenceDiagram App-->>Client: Respond with Data end ``` - ## 🔒 2. Security Best Practices ### Connection Security @@ -72,7 +67,6 @@ sequenceDiagram ### Network Architecture - Utilize TLS (Transport Layer Security) for encrypting data in transit. - ## 🚀 3. Performance Optimization ### Command Usage @@ -82,12 +76,10 @@ sequenceDiagram ### Data Types - Optimize data structure usage. Employ Hashes for objects to save memory, and Sorted Sets for leaderboards or rate limiting. - Avoid large keys or values (keep them under 512MB, but ideally much smaller) to minimize network transfer and memory overhead. - ## 📚 Specialized Documentation - [architecture.md](./architecture.md) - [security-best-practices.md](./security-best-practices.md) - [api-design.md](./api-design.md) - --- [Back to Top](#) diff --git a/backend/redis/security-best-practices.md b/backend/redis/security-best-practices.md index 67d0161..4ee3d86 100644 --- a/backend/redis/security-best-practices.md +++ b/backend/redis/security-best-practices.md @@ -10,7 +10,6 @@ version: "7+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, redis, in-memory, nosql, system-design, production-ready, scalable-code] ai_role: Senior Redis Architecture Expert last_updated: 2026-03-27 -last_evolution: 2026-03-27 ---- +last_evolution: 2026-03-27--- # 🟥 Redis Security Best Practices diff --git a/commit_verify.py b/commit_verify.py new file mode 100644 index 0000000..305e9be --- /dev/null +++ b/commit_verify.py @@ -0,0 +1 @@ +print("Pre-commit done.") diff --git a/docs/ai-agent-orchestration-patterns.md b/docs/ai-agent-orchestration-patterns.md index 23687c6..7a82bc4 100644 --- a/docs/ai-agent-orchestration-patterns.md +++ b/docs/ai-agent-orchestration-patterns.md @@ -5,14 +5,18 @@ complexity: Architect last_evolution: 2026-03-27 vibe_coding_ready: true description: Advanced AI Agent Orchestration best practices for 2026, focusing on scalable, robust multi-agent systems and zero-approval workflows. ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29--- -> 📦 [best-practise](../README.md) / 📄 [docs](./) +> 📦 [best-practise](../README.md) / 📄 [docs](./) # 🤖 AI Agent Orchestration Production-Ready Best Practices In 2026, building effective software demands mastering **AI Agent Orchestration**. This document outlines the **best practices** for designing, scaling, and maintaining autonomous multi-agent systems to ensure predictable outputs in zero-approval environments. - ## 🌟 The Rise of Infinite Knowledge Engines AI Agent Orchestration involves coordinating multiple specialized agents to solve complex tasks. Unlike single-agent systems, orchestration frameworks leverage isolated agents with strict constraints to increase fault tolerance and reduce hallucination. @@ -22,9 +26,7 @@ AI Agent Orchestration involves coordinating multiple specialized agents to solv 1. **Hierarchical Task Delegation:** A primary manager agent delegates sub-tasks to specialized worker agents. 2. **Swarm Intelligence:** Agents operate peer-to-peer, sharing context via a unified memory bus. 3. **Sequential Pipelines:** Agents act as stages in a pipeline, refining outputs progressively. - --- - ## 🏗️ Architectural Blueprints for Multi-Agent Systems Designing robust AI systems requires treating agents as microservices. Each agent must have a defined lifecycle, strict input/output schemas, and deterministic fallback mechanisms. @@ -64,9 +66,7 @@ flowchart TD SharedMemory --> ManagerAgent ManagerAgent --> Result[Final Synthesis] ``` - --- - ## ⚡ Performance Optimization for Vibe Coding When orchestrating agents for "Vibe Coding," performance is critical. Agents should not block each other synchronously. @@ -77,18 +77,14 @@ When orchestrating agents for "Vibe Coding," performance is critical. Agents sho > [!NOTE] > Ensure all orchestration logic is explicitly documented in the `AGENTS.md` file of your repository to align all human and machine contributors. - --- - ## 🛡️ Security and Constraint Enforcement Agents with execution capabilities must be sandboxed. - **Zero-Trust Memory:** Agents should authenticate when reading/writing to the shared memory bus. - **Output Sanitization:** Always validate agent outputs against strict JSON schemas or TypeScript interfaces before executing them. - --- - ## 📝 Actionable Checklist for 2026 Readiness - [ ] Transition from single-agent scripts to a robust Orchestration Framework (e.g., hierarchical or event-driven). diff --git a/docs/ai-agent-orchestration.md b/docs/ai-agent-orchestration.md index d7ef3d8..4098dd4 100644 --- a/docs/ai-agent-orchestration.md +++ b/docs/ai-agent-orchestration.md @@ -5,16 +5,19 @@ topic: AI Agent Orchestration complexity: Architect last_evolution: 2026-05-15 vibe_coding_ready: true ---- +technology: TypeScript +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior TypeScript Expert +last_updated: 2026-03-29--- -> 📦 [best-practise](../README.md) / 📄 [docs](./) +> 📦 [best-practise](../README.md) / 📄 [docs](./) # 🤖 AI Agent Orchestration + Production-Ready Best Practices In 2026, **AI Agent Orchestration** relies heavily on deterministic frameworks and strict **best practices**. This document defines the structural guidelines to ensure scalability and maintainability for multi-agent Vibe Coding architectures. Implementing a robust multi-agent system requires strict adherence to project topology, bounded contexts, and explicit state management mechanisms. - --- - ## 🏗️ Architectural Foundations Orchestrating multiple AI agents requires a clear delineation of responsibilities, strict state management, and continuous validation. Agents must operate within bounded contexts, preventing scope creep and unhandled side effects. To achieve this, engineers must adopt deterministic patterns that standardize inputs, outputs, and intermediate states. @@ -25,9 +28,7 @@ Furthermore, integrating a unified context store allows all agents to share a si > [!IMPORTANT] > Always provide an explicit Context Window definition for each agent. Agents lacking bounded context boundaries will hallucinate and deviate from the established architectural constraints, resulting in technical debt. - --- - ## 📊 Core Orchestration Components The orchestration ecosystem consists of several critical layers that guarantee robust execution. Proper implementation of these components eliminates common pitfalls associated with autonomous AI generation pipelines. @@ -38,9 +39,7 @@ The orchestration ecosystem consists of several critical layers that guarantee r | **Worker Agents** | Specialized execution of scoped sub-tasks (e.g., UI generation, database schemas). | Component-level regressions, partial feature failure. | | **Context Store** | Distributed memory holding active constraints and the global project state. | Hallucinations, incorrect architectural assumptions. | | **Validation Layer** | Deterministic syntax checks, testing, and continuous integration evaluation. | Corrupted pipelines, undetected regressions, and deployment blockers. | - --- - ## 🔄 Agentic Data Flow The lifecycle of a fully autonomous operation involves continuous feedback loops. Below is the standard sequence diagram for an autonomous Vibe Coding operation driven by a supervisor agent, illustrating the interaction between the system's core components. @@ -67,9 +66,7 @@ sequenceDiagram ValidationLayer-->>Supervisor: Pipeline success confirmation Supervisor-->>User: Report successful orchestration & deployment ``` - --- - ## 💻 Implementation: Worker Agent Orchestration Modern multi-agent orchestration demands highly optimized runtime environments. Industry standards mandate utilizing TypeScript 5.5+ and Node.js 24+ to ensure native performance, type safety, and memory efficiency. Below is a foundational implementation pattern for instantiating a deterministically bounded worker agent that interacts with the main context store. @@ -118,9 +115,7 @@ export async function spawnWorkerAgent( } } ``` - --- - ## 📝 Actionable Checklist for Orchestration To finalize your agent orchestration setup and guarantee enterprise-grade Vibe Coding compatibility, ensure you have meticulously completed the following steps: diff --git a/docs/antigravity-ide-vibe-coding.md b/docs/antigravity-ide-vibe-coding.md index f6a52fc..ac7bb16 100644 --- a/docs/antigravity-ide-vibe-coding.md +++ b/docs/antigravity-ide-vibe-coding.md @@ -1,12 +1,20 @@ --- description: Discover the ultimate vibe coding and AI Agents guidelines for the Antigravity IDE. Understand core memory strategies and context optimization. tags: [vibe coding, AI Agents, Antigravity IDE, context window, ai coding] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # Antigravity IDE Vibe Coding Best Practices When using the Antigravity IDE, applying the best practices is essential for efficient vibe coding. By understanding how AI Agents interact with this standalone environment, developers can generate highly optimized, production-ready code. - ## Context and Scope - **Primary Goal:** Provide an actionable guide for using AI Agents within the Antigravity IDE. @@ -18,7 +26,6 @@ When using the Antigravity IDE, applying the best practices is essential for eff **Mastering Vibe Coding with Antigravity** - ## Context Window Management for AI Agents Antigravity IDE is deeply integrated with large context window capabilities. Efficient Context Window Management ensures that the AI Agents do not hallucinate and can precisely follow instructions for vibe coding. @@ -40,7 +47,6 @@ graph TD class UserPrompt default; class Codebase layout; ``` - ## System Constraints and Memory Strategies To achieve enterprise-grade scalability, it is important to utilize memory strategies effectively. The following table illustrates the recommended memory strategies inside the Antigravity IDE. @@ -50,7 +56,6 @@ To achieve enterprise-grade scalability, it is important to utilize memory strat | **Agentic Rulesets** | Providing static `.agents/rules` files. | High-level system design | | **Active File Focus** | Keeping only necessary files open. | Direct refactoring | | **Semantic Search** | Vector search across the codebase. | Broad feature discovery | - ## Production-Ready Actionable Checklist To ensure a smooth vibe coding experience, use this checklist before invoking the AI Agents: diff --git a/docs/cursor-memory-structures.md b/docs/cursor-memory-structures.md index 61fc328..03420a4 100644 --- a/docs/cursor-memory-structures.md +++ b/docs/cursor-memory-structures.md @@ -1,14 +1,21 @@ --- description: An in-depth guide to understanding and optimizing Cursor memory structures for AI-driven development. tags: [vibe coding, ai agents, cursor, memory structures, context optimization] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🧠 Cursor Memory Structures: Optimizing AI Context - ## 📖 1. Introduction to AI Memory Management In the realm of AI agents, memory management is a critical component for achieving high-quality code generation. Cursor utilizes specific memory structures to maintain context across large codebases. Understanding these structures allows developers to optimize the context window and improve the performance of vibe coding. - ## 🏗️ 2. The Architecture of Cursor Memory Cursor organizes its memory into distinct layers to process user requests efficiently. The following diagram illustrates the flow of context from the user prompt to the final AI generation. @@ -22,8 +29,8 @@ graph TD LongTerm --> ContextWindow ContextWindow --> AIGeneration[AI Generation] - style UserPrompt fill:#e3f2fd,stroke:#1565c0,stroke-width:2px - style ContextWindow fill:#ff9800,stroke:#f57c00,stroke-width:2px,color:#fff + class UserPrompt auto_style_UserPrompt + class ContextWindow auto_style_ContextWindow %% Added Design Token Styles for Mermaid Diagrams classDef default fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px,color:#000; classDef component fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,color:#000; @@ -35,8 +42,11 @@ graph TD class LongTerm component; class Codebase component; -``` + %% Auto-generated Design Tokens + classDef auto_style_UserPrompt fill:#e3f2fd,stroke:#1565c0,stroke-width:2px + classDef auto_style_ContextWindow fill:#ff9800,stroke:#f57c00,stroke-width:2px,color:#fff +``` ## 📊 3. Types of Memory in Cursor To effectively manage context, Cursor categorizes memory into different types. Each type serves a specific purpose in the AI generation workflow. @@ -46,7 +56,6 @@ To effectively manage context, Cursor categorizes memory into different types. E | **Short-Term Memory** | The immediate conversational context, including the current prompt and recent interactions. | Session | Keep prompts focused and concise. | | **Active File Memory** | The contents of the currently open files in the editor. | File open state | Close unnecessary files to free up context. | | **Long-Term Retrieval** | Indexed codebase files accessed via vector embeddings. | Persistent | Use `.cursorrules` to guide retrieval priority. | - ## 🛠️ 4. Best Practices for Vibe Coding Optimizing memory structures requires a deliberate approach to providing instructions. @@ -54,7 +63,6 @@ Optimizing memory structures requires a deliberate approach to providing instruc 1. **Explicit Context:** Always reference specific files or functions when asking the AI to perform a task. 2. **Rule Enforcement:** Utilize `.cursorrules` and `AGENTS.md` to establish global constraints that the AI must follow. 3. **Limit Scope:** Avoid asking the AI to refactor the entire application in a single prompt. Break down tasks into smaller, manageable units. - ## ✅ 5. Actionable Checklist for Memory Optimization Follow these steps to ensure optimal performance when using Cursor: diff --git a/docs/vibe-coding-agents.md b/docs/vibe-coding-agents.md index 2d9dc03..d8729ec 100644 --- a/docs/vibe-coding-agents.md +++ b/docs/vibe-coding-agents.md @@ -1,12 +1,20 @@ --- description: Discover the best strategies and production-ready techniques for optimizing AI Agents and Vibe Coding workflows to generate clean, scalable code architectures seamlessly. tags: [vibe coding, ai agents, production-ready, clean code, code generation, ai tools, architecture patterns, prompt engineering] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- -> 📦 [best-practise](../README.md) / 📄 [docs](./) +> 📦 [best-practise](../README.md) / 📄 [docs](./) # 🤖 Vibe Coding Agents: Production-Ready Automation - ## 1. 🎯 Context & Scope - **Primary Goal:** Guide engineers and AI agents on optimizing instruction sets to achieve deterministic, production-ready "Vibe Coding" results. @@ -15,9 +23,7 @@ tags: [vibe coding, ai agents, production-ready, clean code, code generation, ai > [!IMPORTANT] > **Vibe Coding Integrity:** Never trust an AI Agent blindly. Always provide strict architectural constraints and explicit context. - --- - ## 2. 🧠 The "Vibe Coding" Mindset Vibe Coding shifts the developer's role from writing syntax to managing logic and constraints. By establishing robust meta-instructions, you can direct AI Agents to implement features flawlessly on the first attempt. @@ -29,9 +35,7 @@ Vibe Coding shifts the developer's role from writing syntax to managing logic an | **Speed** | Extremely fast code generation. | May introduce untested, legacy APIs. | | **Refactoring** | Excellent at large-scale structural changes. | Can overwrite existing business logic. | | **Boilerplate** | Instant scaffolding of complex setups. | Prone to generic, non-scalable patterns. | - --- - ## 3. 🗺️ Agent Execution Architecture To harness Vibe Coding effectively, integrate a defined execution pipeline. @@ -54,9 +58,7 @@ graph TD class ConstraintCheck layout; class Validation component; ``` - --- - ## 4. ✅ Actionable Checklist for Vibe Coding Before deploying AI Agents for production tasks, verify the following: diff --git a/docs/vibe-coding-zero-approval-workflows.md b/docs/vibe-coding-zero-approval-workflows.md index 363a20e..3ce37b1 100644 --- a/docs/vibe-coding-zero-approval-workflows.md +++ b/docs/vibe-coding-zero-approval-workflows.md @@ -5,14 +5,18 @@ complexity: Advanced last_evolution: 2026-05-14 vibe_coding_ready: true description: A comprehensive guide on setting up zero-approval workflows for vibe coding agents, focusing on automated verification, constraints, and frictionless integration. ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29--- -> 📦 [best-practise](../README.md) / 📄 [docs](./) +> 📦 [best-practise](../README.md) / 📄 [docs](./) # ⚡ Vibe Coding: Zero-Approval Workflows In the 2026 AI Agent landscape, the evolution of Vibe Coding necessitates **Zero-Approval Workflows**. This paradigm allows trusted AI agents to execute, verify, and commit changes autonomously, minimizing human bottlenecks while ensuring systemic integrity. This document outlines the architectural patterns and constraints required for safe, autonomous code evolution. - ## 🌟 The Philosophy of Zero-Approval A Zero-Approval Workflow does not mean zero oversight; it means **deterministic automated oversight**. Instead of human review blocking every trivial commit, rigorous CI/CD pipelines, strict architectural constraints (`.cursorrules`, `agents.md`), and deterministic validation gates act as the approving authority. @@ -23,9 +27,7 @@ A Zero-Approval Workflow does not mean zero oversight; it means **deterministic 2. **Constraint-Driven Development:** AI agents must operate within strict, pre-defined boundaries (e.g., specific folders, architectural layers). 3. **Atomic Commits:** Changes must be small, isolated, and reversible. 4. **Continuous Self-Correction:** Agents must be capable of parsing error logs and iteratively fixing failing pipelines. - --- - ## 🏗️ Architectural Blueprint for Autonomy To achieve a true zero-approval state, the infrastructure must provide immediate, high-fidelity feedback to the AI agent. @@ -69,9 +71,7 @@ graph TD Commit --> Push[Push to Main/Branch] class Push action ``` - --- - ## 🛡️ Implementing Safety Constraints Allowing agents to operate autonomously requires strict guardrails. @@ -82,9 +82,7 @@ Allowing agents to operate autonomously requires strict guardrails. > [!NOTE] > The `pre-commit` hook is the ultimate gatekeeper in a Zero-Approval workflow. Ensure it runs all critical linters and tests before allowing the `git commit` to proceed. - --- - ## 📝 Actionable Checklist for Implementation - [ ] Define explicit, machine-readable constraints in an `AGENTS.md` file. diff --git a/docs/windsurf-vibe-coding-hints.md b/docs/windsurf-vibe-coding-hints.md index 7c5d199..b428beb 100644 --- a/docs/windsurf-vibe-coding-hints.md +++ b/docs/windsurf-vibe-coding-hints.md @@ -1,14 +1,21 @@ --- description: Advanced hints for using Windsurf AI to optimize vibe coding, memory limits, context windows, and AI agent performance for software engineering. tags: [windsurf, ai agents, vibe coding, memory limits, context window] ---- +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29 +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🏄 Windsurf Advanced Usage Hints: Mastering Vibe Coding - ## 📖 1. Introduction to Windsurf AI Agents Windsurf is a powerful tool for developers who use AI agents to write code. By understanding how Windsurf works, you can improve your vibe coding workflow. Vibe coding allows you to build software by giving intent-based instructions to an AI agent. This guide provides advanced usage hints to help you get the best results from Windsurf, optimize the context window, and manage memory limits. - ## 🏗️ 2. The Windsurf Vibe Coding Workflow To get good code from Windsurf, you need a clear process. The AI agent needs the right context window to understand what you want. The following diagram shows the best workflow for sending instructions to the Windsurf AI agent. @@ -21,10 +28,13 @@ graph TD CodeGeneration --> HumanReview[Human Review] HumanReview --> FinalCode[Final Working Code] - style UserIntent fill:#e3f2fd,stroke:#1565c0,stroke-width:2px - style WindsurfPrompt fill:#ff9800,stroke:#f57c00,stroke-width:2px,color:#fff -``` + class UserIntent auto_style_UserIntent + class WindsurfPrompt auto_style_WindsurfPrompt + %% Auto-generated Design Tokens + classDef auto_style_UserIntent fill:#e3f2fd,stroke:#1565c0,stroke-width:2px + classDef auto_style_WindsurfPrompt fill:#ff9800,stroke:#f57c00,stroke-width:2px,color:#fff +``` ## 🧠 3. Managing Memory Limits and Context Size One of the biggest challenges in vibe coding is managing the AI memory limits. If you give the AI agent too much information, it might forget important details in the context window. If you give it too little, it will make mistakes. @@ -36,7 +46,6 @@ Here is a comparison of different ways to manage the context window and memory l | **Direct File Reference** | When working on a single file or component. | High accuracy, low memory usage. | | **Global Rulesets (.windsurfrules)** | When you want to enforce project-wide rules. | Consistent style, medium memory usage. | | **Full Folder Search** | When you do not know where a code bug is located. | Low accuracy, high memory usage. | - ## 💡 4. Advanced Usage Hints for Prompt Creation To make Windsurf AI agents generate perfect code, follow these simple rules for vibe coding: @@ -44,7 +53,6 @@ To make Windsurf AI agents generate perfect code, follow these simple rules for 1. **Be Specific:** Tell the AI agent exactly which file to change. For example, say "Update the button component in `src/button.tsx`" instead of "Change the button". 2. **Use Clear English:** Write your prompts in simple, direct language. Avoid using complex phrasing. 3. **Limit the Context Window:** Close unnecessary files to keep the context window small and avoid reaching memory limits. - ## ✅ 5. Actionable Checklist for Windsurf Vibe Coding Success Follow these steps every time you start a new vibe coding session with Windsurf: diff --git a/frontend/angular/advanced-performance.md b/frontend/angular/advanced-performance.md index 0eb5efa..446f9e6 100644 --- a/frontend/angular/advanced-performance.md +++ b/frontend/angular/advanced-performance.md @@ -7,17 +7,17 @@ version: "20" tags: [performance, advanced, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Performance Expert last_updated: 2026-03-22 ---- +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🚀 Angular Advanced Performance Best Practices & Expert Patterns - # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to advanced performance best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 - ## III. Advanced Performance (31-45) - ## 31. Eager Loading of Heavy Components **Context:** Bundle Size ### ❌ Bad Practice @@ -36,7 +36,6 @@ A charting library (e.g., ECharts) loads immediately, blocking TTI (Time to Inte ``` ### 🚀 Solution Use `@defer`. This defers component code loading until a trigger occurs (viewport, interaction, timer). - ## 32. Heavy Computation in Main Thread **Context:** Event Loop Blocking ### ❌ Bad Practice @@ -47,7 +46,6 @@ Freezes the UI. Offload computations to a Web Worker. ### 🚀 Solution Use Angular Web Workers. In v20, this is easily configured via the CLI. - ## 33. Memory Leaks in `effect()` **Context:** Signal Effects ### ❌ Bad Practice @@ -68,7 +66,6 @@ effect((onCleanup) => { ``` ### 🚀 Solution Always use the `onCleanup` callback to release resources. - ## 34. Excessive Change Detection with `NgZone.run()` **Context:** Zone Integration ### ❌ Bad Practice @@ -83,7 +80,6 @@ ngZone.runOutsideAngular(() => { ``` ### 🚀 Solution Run frequent events (scroll, mousemove, animationFrame) *outside* the Angular zone. Update signals only when UI updates are required. - ## 35. Signals equality check default **Context:** Signal Performance ### ❌ Bad Practice @@ -99,7 +95,6 @@ data = signal(obj, { equal: isEqual }); ``` ### 🚀 Solution Use a custom comparison function for complex objects to avoid redundant re-renders. - ## 36. Lacking `trackBy` in iterables **Context:** Re-rendering Lists ### ❌ Bad Practice @@ -114,7 +109,6 @@ Without tracking, any array change leads to the recreation of all DOM nodes in t ``` ### 🚀 Solution Always use a unique key in `track`. This allows Angular to move DOM nodes instead of recreating them. - ## 37. Recursive Template without Caching **Context:** Tree Rendering ### ❌ Bad Practice @@ -124,6 +118,9 @@ Exponential growth in change detection checks. ### ✅ Best Practice Using the `Memoization` pattern or `computed()` to prepare the tree data structure. + +### 🚀 Solution +[Architectural justification of the solution] ## 38. Global Styles Leakage **Context:** CSS Encapsulation ### ❌ Bad Practice @@ -137,7 +134,6 @@ Global styles unpredictably affect components. Use `ViewEncapsulation.Emulated` (default) and specific selectors. ### 🚀 Solution Keep styles locally within components. - ## 39. Large Component Bundle **Context:** Split Chunks ### ❌ Bad Practice @@ -148,7 +144,6 @@ Poor readability, rendering lazy loading of UI parts impossible. Decompose into "dumb" (UI) and "smart" components. ### 🚀 Solution Break down the UI into small, reusable blocks. - ## 40. Image Optimization Ignorance **Context:** Core Web Vitals (LCP) ### ❌ Bad Practice @@ -163,7 +158,6 @@ The browser loads the full image, shifting the layout (CLS). ``` ### 🚀 Solution Use the `NgOptimizedImage` directive. It automatically handles lazy loading, preconnect, and srcset. - ## 41. Hydration Mismatch **Context:** SSR / SSG ### ❌ Bad Practice @@ -174,7 +168,6 @@ The server generates one number, the client another. This causes "flickering" an Use stable data or defer random generation until `afterNextRender`. ### 🚀 Solution Pay attention to template determinism with SSR. - ## 42. Synchronous `inject()` inside loops **Context:** DI Performance ### ❌ Bad Practice @@ -184,6 +177,9 @@ Although `inject` is fast, in hot paths these are unnecessary DI tree lookups. ### ✅ Best Practice Inject dependency once at the class/file constant level. + +### 🚀 Solution +[Architectural justification of the solution] ## 43. Unused Signal Dependencies **Context:** Signal Graph ### ❌ Bad Practice @@ -193,6 +189,9 @@ Angular dynamically builds the dependency graph. If you accidentally read a sign ### ✅ Best Practice Use `untracked()` to read signals whose changes should not trigger a recalculation. + +### 🚀 Solution +[Architectural justification of the solution] ## 44. Excessive Wrappers (`div` soup) **Context:** DOM Size ### ❌ Bad Practice @@ -204,6 +203,9 @@ Increases DOM tree depth, slowing down Style Recalculation and Layout. ### ✅ Best Practice Use `` to group elements without creating extra DOM nodes. + +### 🚀 Solution +[Architectural justification of the solution] ## 45. Neglecting `runOutsideAngular` for Events **Context:** High-frequency events ### ❌ Bad Practice @@ -213,4 +215,7 @@ Every scroll event triggers Change Detection. ### ✅ Best Practice Subscribe manually in `runOutsideAngular` and update the signal only when necessary. + +### 🚀 Solution +[Architectural justification of the solution] --- diff --git a/frontend/angular/architecture.md b/frontend/angular/architecture.md index d4738e3..c65f3a2 100644 --- a/frontend/angular/architecture.md +++ b/frontend/angular/architecture.md @@ -7,17 +7,17 @@ version: "20" tags: [architecture, dependency-injection, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Architecture Expert last_updated: 2026-03-22 ---- +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🏗 Angular Architecture & Dependency Injection Best Practices - # 📖 Context & Scope - **Primary Goal:** Provide architectural best practices for Angular including DI usage, modules, routing, and guards. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 - ## II. Architecture & DI (16-30) - ## 16. Services provided in 'root' vs Modules **Context:** Tree Shaking ### ❌ Bad Practice @@ -32,7 +32,6 @@ The service is included in the bundle even if it is not used. ``` ### 🚀 Solution Always use `providedIn: 'root'`. This allows the bundler to remove unused services (Tree Shaking). - ## 17. Class-based Guards **Context:** Routing Security ### ❌ Bad Practice @@ -50,7 +49,6 @@ export const authGuard: CanActivateFn = (route, state) => { ``` ### 🚀 Solution Use functional Guards (`CanActivateFn`). They are concise, easy to test, and composable. - ## 18. Class-based Interceptors **Context:** HTTP Requests ### ❌ Bad Practice @@ -69,7 +67,6 @@ export const tokenInterceptor: HttpInterceptorFn = (req, next) => { ``` ### 🚀 Solution Use functional Interceptors (`HttpInterceptorFn`) with `provideHttpClient(withInterceptors([...]))`. - ## 19. State Mutation in Services **Context:** Data Integrity ### ❌ Bad Practice @@ -89,7 +86,6 @@ updateUser(user: User) { ``` ### 🚀 Solution Use Signals for state management. They guarantee reactivity and atomicity of updates. - ## 20. Calling functions inside `@for` tracking **Context:** Rendering Performance ### ❌ Bad Practice @@ -104,7 +100,6 @@ The tracking function is called for each element during every re-render. ``` ### 🚀 Solution Use an object property (ID or a unique key) directly. If a function is needed, it must be as simple and pure as possible. - ## 21. `host` property vs `@HostListener` **Context:** Component Metadata ### ❌ Bad Practice @@ -125,7 +120,6 @@ Decorators increase class size and scatter host configuration across the file. ``` ### 🚀 Solution Use the `host` property in component metadata. This centralizes all host element settings. - ## 22. Dynamic Components with `ComponentFactoryResolver` **Context:** Dynamic Rendering ### ❌ Bad Practice @@ -143,7 +137,6 @@ this.container.createComponent(MyComponent); ``` ### 🚀 Solution Use `ViewContainerRef.createComponent` directly with the component class or the `ngComponentOutlet` directive. - ## 23. Shared Modules (The "Dump" Module) **Context:** Modular Architecture ### ❌ Bad Practice @@ -154,7 +147,6 @@ If a component needs a single button, it is forced to pull the entire `SharedMod Import only what is needed directly into the `imports` of the Standalone component. ### 🚀 Solution Abandon `SharedModule` in favor of granular imports of Standalone entities. - ## 24. Circular Dependencies in DI **Context:** Architecture ### ❌ Bad Practice @@ -165,7 +157,6 @@ Leads to runtime errors ("Cannot instantiate cyclic dependency"). Indicates poor Use `forwardRef()` as a crutch, but it's better to extract the shared logic into a third Service C. ### 🚀 Solution Refactoring: break services into smaller ones following SRP (Single Responsibility Principle). - ## 25. Logic in Pipes **Context:** Separation of Concerns ### ❌ Bad Practice @@ -176,12 +167,11 @@ Pipes are intended for data transformation in the template. Side effects in pipe Pipes should be "Pure" (without side effects) and fast. ### 🚀 Solution Extract logic into services/signals. Leave only formatting to pipes. - ## 26. `any` in Services **Context:** TypeScript Safety ### ❌ Bad Practice ```typescript -getData(): Observable { ... } +getData(): Observable { ... } ``` ### ⚠️ Problem `any` disables type checking, nullifying the benefits of TypeScript. Errors only surface at runtime. @@ -191,7 +181,6 @@ getData(): Observable { ... } ``` ### 🚀 Solution Use DTO interfaces (generate them from Swagger/OpenAPI) and Zod for API response validation. - ## 27. Multiple `async` pipes for same stream **Context:** RxJS Subscriptions ### ❌ Bad Practice @@ -208,12 +197,11 @@ Each `async` pipe creates a new subscription. This can lead to duplicated HTTP r ``` ### 🚀 Solution Use aliases in the template (`as varName`) or convert the stream to a signal (`toSignal`). - ## 28. ProvidedIn 'any' **Context:** DI Scopes ### ❌ Bad Practice ```typescript -@Injectable({ providedIn: 'any' }) +@Injectable({ providedIn: 'unknown' }) ``` ### ⚠️ Problem Creates a new service instance for each lazy-loaded module. This is often unexpected behavior, leading to state desynchronization (different singleton instances). @@ -221,7 +209,6 @@ Creates a new service instance for each lazy-loaded module. This is often unexpe `providedIn: 'root'` or providing at the level of a specific component (`providers: []`). ### 🚀 Solution Avoid `any`. Explicitly control the scope: either global (`root`) or local. - ## 29. Imperative Routing **Context:** Navigation ### ❌ Bad Practice @@ -236,7 +223,6 @@ this.router.navigate(['users', id]); ``` ### 🚀 Solution Use an array of segments. It is safer (automatic encoding of URL parameters) and cleaner. - ## 30. Ignoring `OnPush` Strategy **Context:** Change Detection Strategy ### ❌ Bad Practice @@ -249,5 +235,4 @@ changeDetection: ChangeDetectionStrategy.OnPush ``` ### 🚀 Solution Always set `OnPush`. With signals, this becomes the de facto standard, as updates occur precisely. - --- diff --git a/frontend/angular/data-forms.md b/frontend/angular/data-forms.md index 9825242..4512237 100644 --- a/frontend/angular/data-forms.md +++ b/frontend/angular/data-forms.md @@ -7,17 +7,17 @@ version: "20" tags: [forms, data, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Data Expert last_updated: 2026-03-22 ---- +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 📝 Angular Data & Forms Best Practices - # 📖 Context & Scope - **Primary Goal:** Proper implementation of data management and forms in Angular applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 - ## IV. Data & Forms (46-55) - ## 46. Template-Driven Forms without Types **Context:** Form Safety ### ❌ Bad Practice @@ -27,6 +27,9 @@ Risk of assigning a string to a numeric field. ### ✅ Best Practice Use Reactive Forms with `FormControl` typing or new Signal-based Forms (when out of developer preview). + +### 🚀 Solution +[Architectural justification of the solution] ## 47. Untyped `FormGroup` **Context:** Reactive Forms ### ❌ Bad Practice @@ -44,7 +47,6 @@ const form = new FormGroup({ ``` ### 🚀 Solution Always type forms. Use `nonNullable: true` to avoid `string | undefined` hell. - ## 48. Subscribe inside Subscribe **Context:** RxJS Patterns ### ❌ Bad Practice @@ -63,7 +65,6 @@ this.route.params.pipe( ``` ### 🚀 Solution Use Flattening Operators (`switchMap`, `concatMap`, `mergeMap`). - ## 49. Ignoring `AbortSignal` in HTTP **Context:** Network Efficiency ### ❌ Bad Practice @@ -73,6 +74,9 @@ Requests continue hanging, consuming traffic. ### ✅ Best Practice HttpClient automatically supports cancellation upon unsubscription. With signals: ensure `rxResource` or the effect correctly cancels the request. + +### 🚀 Solution +[Architectural justification of the solution] ## 50. Mutating Inputs directly **Context:** Unidirectional Data Flow ### ❌ Bad Practice @@ -84,6 +88,9 @@ The parent component remains unaware of the change. Violates the One-Way Data Fl ### ✅ Best Practice Emit event (`output`) upwards; the parent changes the data and passes the new object downwards. + +### 🚀 Solution +[Architectural justification of the solution] ## 51. `ngModel` inside Reactive Form **Context:** Form Mixing ### ❌ Bad Practice @@ -93,6 +100,9 @@ Deprecated behavior. Causes form and model synchronization conflicts. ### ✅ Best Practice Use only one approach: either Reactive or Template-driven. + +### 🚀 Solution +[Architectural justification of the solution] ## 52. Complex Validators in Template **Context:** Form Logic ### ❌ Bad Practice @@ -102,6 +112,9 @@ Hard to test, no reusability. ### ✅ Best Practice Custom Validator Functions or Async Validators in the component class. + +### 🚀 Solution +[Architectural justification of the solution] ## 53. Forgetting `updateOn: 'blur'` **Context:** Performance ### ❌ Bad Practice @@ -114,7 +127,6 @@ new FormControl('', { updateOn: 'blur' }); ``` ### 🚀 Solution Trigger validation/update only when the user has finished typing. - ## 54. Not handling API Errors **Context:** UX ### ❌ Bad Practice @@ -124,6 +136,9 @@ On a 500 error, the application "hangs" in a loading state. ### ✅ Best Practice Global Error Handler or `catchError` in the pipe returning a safe value. + +### 🚀 Solution +[Architectural justification of the solution] ## 55. Hardcoded API URLs **Context:** Maintainability ### ❌ Bad Practice @@ -133,4 +148,7 @@ Inability to switch environments (dev/prod). ### ✅ Best Practice Using InjectionToken `API_URL` and environment configuration. + +### 🚀 Solution +[Architectural justification of the solution] --- diff --git a/frontend/angular/expert-niche.md b/frontend/angular/expert-niche.md index fd263e8..8cbeb8b 100644 --- a/frontend/angular/expert-niche.md +++ b/frontend/angular/expert-niche.md @@ -7,17 +7,17 @@ version: "20" tags: [expert, niche, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Expert last_updated: 2026-03-22 ---- +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🧠 Angular Expert/Niche Best Practices - # 📖 Context & Scope - **Primary Goal:** Deep-dive into expert and niche topics in Angular. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 - ## V. Expert/Niche (56-60) - ## 56. `untracked()` usage **Context:** Fine-grained Reactivity ### ❌ Bad Practice @@ -34,7 +34,6 @@ computed(() => { ``` ### 🚀 Solution Use `untracked()` for side effects or reads that shouldn't affect recalculation. - ## 57. V8 Hidden Classes Optimization **Context:** Micro-optimization ### ❌ Bad Practice @@ -52,7 +51,6 @@ user = signal({ name: null, age: null }); ``` ### 🚀 Solution Always initialize signals with the full object shape (even with null) to preserve property access monomorphism. - ## 58. Signal Glitch Freedom abuse **Context:** Reactivity Theory ### ❌ Bad Practice @@ -62,6 +60,9 @@ Signals guarantee "Glitch Freedom" (absence of intermediate inconsistent states) ### ✅ Best Practice Do not use effects to synchronize local state. Use `computed`. + +### 🚀 Solution +[Architectural justification of the solution] ## 59. Memory leaks in `root` Effects **Context:** Application Lifecycle ### ❌ Bad Practice @@ -71,6 +72,9 @@ Effects in `root` services live forever. If they subscribe to something global, ### ✅ Best Practice Usually fine, but if the service is destroyed (rare lazy loading case), the effect must be cleaned up with `effectRef.destroy()`. + +### 🚀 Solution +[Architectural justification of the solution] ## 60. `runInInjectionContext` **Context:** Advanced DI ### ❌ Bad Practice diff --git a/frontend/angular/readme.md b/frontend/angular/readme.md index 6d24780..861f8c4 100644 --- a/frontend/angular/readme.md +++ b/frontend/angular/readme.md @@ -7,10 +7,12 @@ version: "20" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Angular Performance Expert last_updated: 2026-03-22 ---- +topic: Angular +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🎨 Angular Best Practices & Production-Ready Patterns - ## 🎯 Context & Scope - **Primary Goal:** Enforce strict adherence to modern Angular v20 patterns, specifically Zoneless reactivity and functional APIs for optimal best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -21,7 +23,6 @@ last_updated: 2026-03-22 > - **Always** use `signal()`, `computed()`, and `effect()` instead of RxJS `BehaviorSubject` for local state. > - **Never** use `@Input()` or `@Output()` decorators; strictly use `input()` and `output()` functional APIs. > - **Always** utilize the built-in control flow (`@if`, `@for`, `@switch`) instead of structural directives (`*ngIf`, `*ngFor`). - ## 🚀 I. Basics & Popular (1-15) ### 🚨 1. Using `@Input()` Decorator @@ -38,7 +39,6 @@ title = input(''); ``` #### 🚀 Solution Use Signal Inputs (`input()`). This allows Angular to precisely know *which* specific component requires an update, paving the way for Zoneless applications. - --- ### 🚨 2. Using `@Output()` Decorator @@ -55,7 +55,6 @@ save = output(); ``` #### 🚀 Solution Use the `output()` function. It provides strict typing, better performance, and a unified API with Signal Inputs. - --- ### 🚨 3. Two-Way Binding with `@Input()` and `@Output()` @@ -73,7 +72,6 @@ value = model(); ``` #### 🚀 Solution Use `model()`. This creates a Signal that can be both read and written to, automatically synchronizing its state with the parent. - --- ### 🚨 4. Structural Directives (`*ngIf`, `*ngFor`) @@ -98,14 +96,13 @@ Directives require importing `CommonModule` or `NgIf/NgFor`, increasing bundle s ``` #### 🚀 Solution Use the built-in Control Flow (`@if`, `@for`). It is built into the compiler, requires no imports, supports improved type-narrowing, and runs faster. - --- ### 🚨 5. Subscribing in Components (Logic in `ngOnInit`) **Context:** Data Fetching #### ❌ Bad Practice ```typescript -data: any; +data: unknown; ngOnInit() { this.service.getData().subscribe(res => this.data = res); } @@ -118,7 +115,6 @@ data = toSignal(this.service.getData()); ``` #### 🚀 Solution Use `toSignal()` to convert an Observable into a Signal. This automatically manages the subscription and integrates the data stream into the reactivity system. - --- ### 🚨 6. `BehaviorSubject` for Local State @@ -138,7 +134,6 @@ count = signal(0); ``` #### 🚀 Solution Use `signal()` for local state. It is a primitive designed specifically for synchronizing UI and data. - --- ### 🚨 7. Derived State with `ngOnChanges` @@ -159,7 +154,6 @@ fullName = computed(() => `${this.firstName()} ${this.lastName()}`); ``` #### 🚀 Solution Use `computed()`. The signal is recalculated *only* when its dependencies change, and the result is memoized (cached). - --- ### 🚨 8. Constructor Dependency Injection @@ -177,7 +171,6 @@ private store = inject(Store); ``` #### 🚀 Solution Use the `inject()` function. It operates in the initialization context (fields or constructor), is type-safe, and does not require `super()` during inheritance. - --- ### 🚨 9. Modules (`NgModule`) @@ -201,7 +194,6 @@ Modules create an unnecessary level of indirection. Components become dependent ``` #### 🚀 Solution Use Standalone Components. This is the Angular v14+ standard that makes components self-sufficient and tree-shakable. - --- ### 🚨 10. String-based Route Loading @@ -218,7 +210,6 @@ loadComponent: () => import('./user.component').then(c => c.UserComponent) ``` #### 🚀 Solution Use `loadComponent` for routing to Standalone components. This ensures minimal chunk size. - --- ### 🚨 11. Heavy Logic in Templates @@ -238,7 +229,6 @@ total = computed(() => this.calculateTotal(this.items())); ``` #### 🚀 Solution Extract logic into `computed()` signals or Pure Pipes. They are only executed when input data changes. - --- ### 🚨 12. Manual Subscription Management (`takeUntil`) @@ -257,7 +247,6 @@ stream$.pipe(takeUntilDestroyed()).subscribe(); ``` #### 🚀 Solution Use the `takeUntilDestroyed()` operator. It automatically unsubscribes upon context destruction (component, directive, service). - --- ### 🚨 13. Deeply Nested Components Passing Data @@ -280,7 +269,6 @@ theme = inject(ThemeService).theme; ``` #### 🚀 Solution Use Signal Stores or services for state sharing, or the new `input()` API with context inheritance (in the future). - --- ### 🚨 14. Accessing DOM directly (`ElementRef.nativeElement`) @@ -298,7 +286,6 @@ Direct DOM access breaks abstraction (doesn't work in SSR/Web Workers) and opens ``` #### 🚀 Solution Use style/class bindings or `Renderer2`. For direct manipulations, consider directives. - --- ### 🚨 15. Zone.js overhead @@ -315,10 +302,8 @@ bootstrapApplication(App, { ``` #### 🚀 Solution Migrate to Zoneless mode. Use Signals to notify Angular when a re-render is needed. - --- [⬆️ Back to Top](#) - ## 📚 Specialized Topics For further reading, please refer to the following specialized guides: diff --git a/frontend/angular/state-management.md b/frontend/angular/state-management.md index 73691cf..fcc1f5a 100644 --- a/frontend/angular/state-management.md +++ b/frontend/angular/state-management.md @@ -10,12 +10,11 @@ last_evolution: 2026-03-28 version: "20" tags: [state-management, signals, zoneless, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular State Management Expert ---- +last_updated: 2026-03-29--- -> 📦 [best-practise](../../README.md) / 🖥️ [frontend](../readme.md) / 🅰️ [angular](./readme.md) +> 📦 [best-practise](../../README.md) / 🖥️ [frontend](../readme.md) / 🅰️ [angular](./readme.md) # 📦 Angular State Management: Zoneless Reactivity & Signals - # 📖 Context & Scope - **Primary Goal:** Enforce strictly functional state management patterns using Angular 20's Zoneless architecture. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -26,9 +25,7 @@ ai_role: Senior Angular State Management Expert > - Avoid RxJS `BehaviorSubject` for local and synchronous global component state. > - Strictly use `signal()`, `computed()`, and `effect()` to manage all dynamic data states. > - Never use the `@Input()` and `@Output()` decorators for sharing state across component trees; rely solely on functional `input()` and `output()`. - --- - ## 🏗 Architecture & Data Flow State management in Angular 20 relies entirely on the granular reactivity provided by Signals. This architecture inherently supports Zoneless change detection by exactly tracking which views need updates without relying on `zone.js`. @@ -50,9 +47,7 @@ graph TD class Child default; class Child2 default; ``` - --- - ## 🚀 I. Local State Management ### 🚨 1. Managing Component State with Signals @@ -60,7 +55,7 @@ graph TD #### ❌ Bad Practice ```typescript isLoading: boolean = false; -data: any[] = []; +data: unknown[] = []; fetchData() { this.isLoading = true; @@ -87,9 +82,7 @@ fetchData() { ``` #### 🚀 Solution Use `signal()`. It forces the developer to explicitly use `.set()` or `.update()`, signaling to the framework exactly when and where the change occurred. - --- - ## ⚙️ II. Derived State ### 🚨 2. Computing Values @@ -112,9 +105,7 @@ total = computed(() => this.items().reduce((a, b) => a + b, 0)); ``` #### 🚀 Solution Use `computed()`. The calculated value is memoized and only re-evaluates when its specific signal dependencies (in this case, `items`) change. - --- - ## ⚡ III. Side Effects ### 🚨 3. Handling Side Effects Safely @@ -134,9 +125,7 @@ constructor() { ``` #### 🚀 Solution Use `effect()`. Effects track dependencies automatically and ensure the side effect runs solely when required. Always define them within an injection context (like a constructor). - --- - ## 🔗 IV. Component Communication ### 🚨 4. Modern Data Passing @@ -158,7 +147,6 @@ userProfile = model(); ``` #### 🚀 Solution Use the `input()` and `model()` functional APIs. They return signals that can be directly used in `computed()` properties within the child component. - --- [⬆️ Back to Top](#) diff --git a/frontend/javascript/async-logic.md b/frontend/javascript/async-logic.md index cc08d5b..83e2397 100644 --- a/frontend/javascript/async-logic.md +++ b/frontend/javascript/async-logic.md @@ -7,17 +7,17 @@ version: "ES2024+" tags: [javascript, async, promises, best-practices, clean-code, scalable-code] ai_role: Senior JavaScript Asynchronous Expert last_updated: 2026-03-22 ---- +topic: JavaScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⏳ JavaScript Asynchronous & Logic Best Practices - # 📖 Context & Scope - **Primary Goal:** Implement correct and robust asynchronous logic in JavaScript applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** ES2024+ - ## III. Asynchronous & Logic - ## 21. Callback Hell vs Promises **Context:** Managing asynchronous execution flow. ### ❌ Bad Practice @@ -41,7 +41,6 @@ fetchData(url) ``` ### 🚀 Solution Use Promises to flatten the structure and centralize error handling with `.catch()`. - ## 22. Promise.then() nesting vs Async/Await **Context:** Modern syntax for asynchronous code. ### ❌ Bad Practice @@ -66,7 +65,6 @@ async function load() { ``` ### 🚀 Solution Use `async/await`. It allows asynchronous code to be written and read like synchronous code, improving maintainability. - ## 23. Sequential `await` in loops vs `Promise.all` **Context:** Parallelizing independent asynchronous operations. ### ❌ Bad Practice @@ -84,7 +82,6 @@ await Promise.all(promises); ``` ### 🚀 Solution Use `Promise.all` to execute independent promises in parallel. This utilizes the full network/IO bandwidth. - ## 24. Missing `try/catch` in async **Context:** Handling failures in async functions. ### ❌ Bad Practice @@ -109,7 +106,6 @@ async function getData() { ``` ### 🚀 Solution Wrap `await` calls in `try/catch` blocks or use a higher-order function to catch errors. - ## 25. Floating point math errors (`0.1 + 0.2`) **Context:** Precision issues in IEEE 754 arithmetic. ### ❌ Bad Practice @@ -128,7 +124,6 @@ const totalCents = (10 + 20); // 30 cents ``` ### 🚀 Solution Use `Number.EPSILON` for comparisons or represent decimals as integers (e.g., cents instead of dollars) to avoid floating point drift. - ## 26. Multiple Boolean flags vs State Machine **Context:** Managing complex component logic. ### ❌ Bad Practice @@ -145,7 +140,6 @@ const [status, setStatus] = useState('IDLE'); // IDLE, LOADING, ERROR, SUCCESS ``` ### 🚀 Solution Use a single state variable or a state machine. This ensures only one state is active at a time and simplifies transitions. - ## 27. Sync logic in Event Loop **Context:** Keeping the UI responsive. ### ❌ Bad Practice @@ -169,7 +163,6 @@ function processInChunks(arr) { ``` ### 🚀 Solution Offload heavy tasks to Web Workers or use `requestIdleCallback`/`setTimeout` to break long tasks into smaller chunks, allowing the browser to render between frames. - ## 28. Overusing `classes` where functions suffice **Context:** Paradigm choice (OOP vs FP). ### ❌ Bad Practice @@ -187,7 +180,6 @@ export const add = (a, b) => a + b; ``` ### 🚀 Solution Use simple functions and modules for logic. Use classes only when you need to manage complex stateful instances with shared behavior. - ## 29. Hard-coded Error messages vs Error Classes **Context:** Robust error handling and debugging. ### ❌ Bad Practice @@ -208,7 +200,6 @@ class UserNotFoundError extends Error { ``` ### 🚀 Solution Extend the `Error` class to create custom error types. Use `instanceof` check in catch blocks to handle specific errors differently. - ## 30. Unhandled Rejections **Context:** Reliability of asynchronous flows. ### ❌ Bad Practice @@ -226,5 +217,4 @@ window.addEventListener('unhandledrejection', event => { ``` ### 🚀 Solution Always handle promise rejections. Implement a global unhandled rejection listener as a safety net for monitoring. - --- diff --git a/frontend/javascript/modern-syntax.md b/frontend/javascript/modern-syntax.md index e525070..9397fb8 100644 --- a/frontend/javascript/modern-syntax.md +++ b/frontend/javascript/modern-syntax.md @@ -7,17 +7,17 @@ version: "ES2024+" tags: [javascript, es6, functional-programming, best-practices, clean-code, scalable-code] ai_role: Senior JavaScript Expert last_updated: 2026-03-22 ---- +topic: JavaScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ✨ Modern JavaScript Syntax & Functional Programming Best Practices - # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to modern ES6+ syntax and functional programming patterns. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** ES2024+ - ## II. Modern Syntax & FP (ES6-ES2024) - ## 11. Manual object property assignment vs Shorthand **Context:** Reducing boilerplate in object creation. ### ❌ Bad Practice @@ -37,7 +37,6 @@ const user = { name, age }; ``` ### 🚀 Solution Use Property Shorthand. When the key and variable name match, omit the value. - ## 12. Using `arguments` vs Rest parameters **Context:** Handling variable numbers of arguments. ### ❌ Bad Practice @@ -55,7 +54,6 @@ const sum = (...args) => args.reduce((a, b) => a + b); ``` ### 🚀 Solution Use Rest Parameters (`...args`). They create a real array and are more explicit about the function's intent. - ## 13. Manual array copying vs Spread **Context:** Immutability and array manipulation. ### ❌ Bad Practice @@ -75,7 +73,6 @@ const copy = [...original]; ``` ### 🚀 Solution Use the Spread Operator (`...`). It is concise, declarative, and highly optimized by modern engines. - ## 14. Nested Destructuring **Context:** Extracting data from complex objects. ### ❌ Bad Practice @@ -91,7 +88,6 @@ const { location: { address: { city, zip } } } = user; ``` ### 🚀 Solution Use nested destructuring to extract deeply nested values in a single statement. (Note: Combine with optional chaining if path existence isn't guaranteed). - ## 15. Default Parameters **Context:** Handling missing arguments. ### ❌ Bad Practice @@ -111,7 +107,6 @@ function setRole(role = 'guest') { ``` ### 🚀 Solution Use ES6 Default Parameters. They only apply if the argument is `undefined`. - ## 16. `forEach` for data transformation vs `map/filter` **Context:** Declarative vs Imperative programming. ### ❌ Bad Practice @@ -129,7 +124,6 @@ const double = numbers.map(n => n * 2); ``` ### 🚀 Solution Use `map`, `filter`, and `reduce` for data transformations. They return new arrays and promote immutability. - ## 17. Object mutation vs Immutability **Context:** State management and predictability. ### ❌ Bad Practice @@ -147,7 +141,6 @@ const updateAge = (user) => ({ ...user, age: 30 }); ``` ### 🚀 Solution Treat objects as immutable. Use the spread operator to create copies with updated properties. - ## 18. Switch statements vs Object Literals **Context:** Simplifying conditional branching. ### ❌ Bad Practice @@ -170,7 +163,6 @@ return (actions[action] || doNothing)(); ``` ### 🚀 Solution Use an Object Literal (or Map) as a lookup table. It is cleaner, faster, and more extensible. - ## 19. Not using Optional Chaining `?.` **Context:** Safe property access in nested objects. ### ❌ Bad Practice @@ -185,7 +177,6 @@ const street = user?.address?.street; ``` ### 🚀 Solution Use Optional Chaining (`?.`). It short-circuits to `undefined` if any part of the chain is nullish. - ## 20. Not using Nullish Coalescing `??` **Context:** Providing fallback values safely. ### ❌ Bad Practice @@ -200,5 +191,4 @@ const timeout = config.timeout ?? 5000; ``` ### 🚀 Solution Use Nullish Coalescing (`??`). It only falls back if the value is `null` or `undefined`, allowing `0`, `false`, and `''` to be valid. - --- diff --git a/frontend/javascript/professional-niche.md b/frontend/javascript/professional-niche.md index 0e47f41..feae03c 100644 --- a/frontend/javascript/professional-niche.md +++ b/frontend/javascript/professional-niche.md @@ -7,17 +7,17 @@ version: "ES2024+" tags: [javascript, advanced, best-practices, clean-code, scalable-code] ai_role: Senior JavaScript Expert last_updated: 2026-03-22 ---- +topic: JavaScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🧠 JavaScript Professional & Niche Best Practices (Senior Level) - # 📖 Context & Scope - **Primary Goal:** Detail advanced and niche topics in JavaScript for high-performance applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** ES2024+ - ## IV. Professional & Niche (Senior Level) - ## 31. Memory Leaks: Unremoved Event Listeners **Context:** Long-lived applications (SPAs). ### ❌ Bad Practice @@ -36,7 +36,6 @@ window.removeEventListener('resize', handler); ``` ### 🚀 Solution Always remove event listeners in cleanup phases (e.g., `componentWillUnmount` or `useEffect` return). Use `AbortController` for an even more modern approach to listener cleanup. - ## 32. Memory Leaks: Forgotten Intervals/Timeouts **Context:** Managing temporal background tasks. ### ❌ Bad Practice @@ -55,7 +54,6 @@ clearInterval(intervalId); ``` ### 🚀 Solution Store the ID returned by `setTimeout` or `setInterval` and clear it when the task is no longer relevant. - ## 33. Closures inside loops (Memory/Scope issues) **Context:** Understanding the Event Loop and closure capture. ### ❌ Bad Practice @@ -74,7 +72,6 @@ for (let i = 0; i < 5; i++) { ``` ### 🚀 Solution Use `let` in loop headers. It creates a new binding for each iteration, ensuring the closure captures the value of `i` at that specific moment. - ## 34. Throwing Strings instead of `new Error()` **Context:** Ensuring useful stack traces. ### ❌ Bad Practice @@ -89,7 +86,6 @@ throw new Error('Something went wrong'); ``` ### 🚀 Solution Always throw an instance of `Error` (or a subclass). This captures the `stack` property, which is vital for debugging. - ## 35. Modifying Built-in Prototypes **Context:** Ecosystem compatibility and stability. ### ❌ Bad Practice @@ -106,7 +102,6 @@ const last = (arr) => arr[arr.length - 1]; ``` ### 🚀 Solution Use utility functions or wrapper classes instead of modifying global prototypes. - ## 36. Premature Optimization (e.g., bitwise for rounding) **Context:** Readability vs Micro-benchmarks. ### ❌ Bad Practice @@ -121,7 +116,6 @@ const floor = Math.floor(x); ``` ### 🚀 Solution Prioritize readability. Modern JIT compilers are smart enough to optimize `Math.floor`. Only use bitwise tricks if profiling proves it's a critical bottleneck in a hot path. - ## 37. V8 Hidden Classes: Changing object shape after initialization **Context:** V8 JIT optimization. ### ❌ Bad Practice @@ -144,7 +138,6 @@ const u1 = new User('Alice', 25); ``` ### 🚀 Solution Initialize all object properties in the constructor or a factory function. Maintain a consistent object "shape" to keep V8 in the optimized path. - ## 38. Array Hole (Sparse Arrays) performance **Context:** Memory allocation and JIT optimization. ### ❌ Bad Practice @@ -160,7 +153,6 @@ const arr = Array.from({ length: 100 }, () => null); ``` ### 🚀 Solution Initialize arrays with default values (like `null` or `0`) instead of leaving empty slots. This keeps the array in "packed" mode. - ## 39. Using `eval()` or `new Function()` **Context:** Security and performance. ### ❌ Bad Practice @@ -177,7 +169,6 @@ const operations = { '+': (a, b) => a + b }; ``` ### 🚀 Solution Avoid `eval()`. Use lookup tables, JSON parsing, or safe math libraries to handle dynamic logic. - ## 40. Micro-optimizations that hurt readability **Context:** Maintaining a healthy codebase. ### ❌ Bad Practice diff --git a/frontend/javascript/readme.md b/frontend/javascript/readme.md index 30b7de5..6aeb4a9 100644 --- a/frontend/javascript/readme.md +++ b/frontend/javascript/readme.md @@ -7,15 +7,16 @@ version: ES6-ES2024 tags: [javascript, clean-code, es6, performance, best-practices] ai_role: Senior JavaScript Performance Expert last_updated: 2026-03-22 ---- +topic: JavaScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🎨 JavaScript Best Practise ![JavaScript Logo](https://img.icons8.com/?size=100&id=108784&format=png&color=000000) - --- [⬆️ Back to Top](#) - ## 🚀 I. Fundamentals (The Basics) ### 🚨 1. `var` vs `const/let` @@ -40,7 +41,6 @@ console.log(price); // 100 ``` #### 🚀 Solution Use `const` by default to ensure immutability of the reference. Use `let` only when reassigning a variable is strictly necessary. This enforces block-level scoping and prevents accidental overrides. - --- ### 🚨 2. Loose equality `==` @@ -61,7 +61,6 @@ if (userCount === 0) { ``` #### 🚀 Solution Always use strict equality `===` and inequality `!==`. This forces the developer to handle type conversions explicitly, making the code's intent clear and predictable. - --- ### 🚨 3. Global Scope Pollution @@ -86,7 +85,6 @@ export const config = { api: '/v1' }; ``` #### 🚀 Solution Use ES Modules (`import/export`) to encapsulate code. Modules have their own scope and do not leak to the global object. - --- ### 🚨 4. String concatenation vs Template Literals @@ -105,7 +103,6 @@ Welcome to ${siteName}.`; ``` #### 🚀 Solution Use Template Literals (backticks). They allow for embedded expressions, multi-line strings, and superior readability. - --- ### 🚨 5. Magic Numbers @@ -128,7 +125,6 @@ if (user.age >= LEGAL_AGE) { ``` #### 🚀 Solution Extract magic numbers into named constants. This provides semantic meaning and a single source of truth for configuration. - --- ### 🚨 6. Boolean comparisons `(if x === true)` @@ -146,7 +142,6 @@ if (!isPending) { /* ... */ } ``` #### 🚀 Solution Leverage JavaScript's truthiness/falsiness or direct boolean evaluation. It makes the code more concise and idiomatic. - --- ### 🚨 7. Array/Object literal vs `new` constructor @@ -165,7 +160,6 @@ const map = {}; ``` #### 🚀 Solution Use literals `[]` and `{}`. They are visually cleaner and perform slightly better as they don't involve a function call. - --- ### 🚨 8. Function length/complexity @@ -192,7 +186,6 @@ function processOrder(order) { ``` #### 🚀 Solution Break functions into smaller, pure components. Aim for functions under 20 lines that do exactly one thing. - --- ### 🚨 9. Deeply nested `if/else` (Arrow code) @@ -222,7 +215,6 @@ function getData(user) { ``` #### 🚀 Solution Use "Guard Clauses" to return early. This flattens the structure and handles edge cases first, leaving the happy path at the lowest nesting level. - --- ### 🚨 10. Improper naming (Single letters) @@ -241,9 +233,7 @@ const userNames = users.map(user => user.name); ``` #### 🚀 Solution Use descriptive, camelCase names that convey the intent and data type of the variable. - --- - ## 📚 Specialized Topics For further reading, please refer to the following specialized guides: diff --git a/frontend/qwik/readme.md b/frontend/qwik/readme.md index 883ca99..2580e2d 100644 --- a/frontend/qwik/readme.md +++ b/frontend/qwik/readme.md @@ -7,10 +7,12 @@ version: "1.x" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Qwik Expert last_updated: 2026-03-22 ---- +topic: Qwik +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⚡ Qwik Best Practices & Production-Ready Patterns - # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to modern Qwik patterns, specifically resumability and lazy loading for optimal best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -21,14 +23,11 @@ last_updated: 2026-03-22 > - **Always** use `useSignal()`, `useStore()`, and `useTask$()` for local state and effects. > - **Never** pass non-serializable objects (like closures, Promises, or DOM references) into generic properties. > - **Always** utilize the `$` suffix for closures when necessary, like `onClick$`, to indicate lazy loading points. - ## 🏗 Architecture Principles - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications. - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. - ## 🚀 I. Basics & Popular - ## 1. Passing Closures as Props **Context:** Component Props ### ❌ Bad Practice diff --git a/frontend/react/performance.md b/frontend/react/performance.md index 4d8e44d..6469ddf 100644 --- a/frontend/react/performance.md +++ b/frontend/react/performance.md @@ -10,18 +10,15 @@ domain: frontend level: Senior/Architect version: "19+" ai_role: Senior React Performance Expert -last_updated: 2026-03-22 ---- +last_updated: 2026-03-22--- # ⚡ React Performance & Best Practices [⬆️ Back to Top](#) - # 📖 Context & Scope - **Primary Goal:** Outline advanced techniques for optimal performance in React 19+. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** React 19+ - ## 📚 Topics ### 1. Manual Memoization vs React Compiler diff --git a/frontend/react/readme.md b/frontend/react/readme.md index 6082563..8778a74 100644 --- a/frontend/react/readme.md +++ b/frontend/react/readme.md @@ -10,11 +10,9 @@ domain: frontend level: Senior/Architect version: "19+" ai_role: Senior React Expert -last_updated: 2026-03-22 ---- +last_updated: 2026-03-22--- # ⚛️ React Production-Ready Best Practices - # 📖 Context & Scope - **Primary Goal:** Provide architectural best practices for modern React development. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -22,12 +20,10 @@ last_updated: 2026-03-22 > [!NOTE] > When building React applications in 2026, always implement the React best practices described here to ensure maximum performance, maintainability, and security. - ## 🏗 Architecture Principles - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications. - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. - ## 🚀 I. Basics & Popular ### 1. Direct DOM Manipulation @@ -72,7 +68,6 @@ Massive components are difficult to read, test, and maintain. They often violate Break down the UI into smaller, reusable components, each with a single responsibility. #### 🚀 Solution Extract logic into custom hooks and presentational elements into separate files. - ## 📚 Specialized Topics For further reading, please refer to the following specialized guides: diff --git a/frontend/react/state-management.md b/frontend/react/state-management.md index 55c3507..ed2da6d 100644 --- a/frontend/react/state-management.md +++ b/frontend/react/state-management.md @@ -10,18 +10,15 @@ domain: frontend level: Senior/Architect version: "19+" ai_role: Senior React State Management Expert -last_updated: 2026-03-22 ---- +last_updated: 2026-03-22--- # 🔄 React State Management & Server Actions Best Practices [⬆️ Back to Top](#) - # 📖 Context & Scope - **Primary Goal:** Provide best practices for managing state, including React 19+ Server Actions. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** React 19+ - ## 📚 Topics ### 1. Handling Async Actions (Forms) diff --git a/frontend/readme.md b/frontend/readme.md index 8e812cd..eb59acf 100644 --- a/frontend/readme.md +++ b/frontend/readme.md @@ -7,10 +7,12 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Frontend Architect last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🎨 Frontend Best Practices & Production-Ready Patterns - # 📖 Context & Scope - **Primary Goal:** Outline the overarching philosophy and standards for Frontend development inside the ecosystem. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -21,14 +23,11 @@ last_updated: 2026-03-22 **The overarching philosophy and foundations for all internal Frontend technologies.** - --- - ## 🏗 Architecture Principles - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications. - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. - ## 🤖 Technical Requirements for AI Generation > [!IMPORTANT] @@ -37,7 +36,6 @@ last_updated: 2026-03-22 - **Isolation:** Each component must define its boundaries clearly. Avoid CSS leakage. - **TypeScript Strictness:** Exploit TypeScript. `any` is strictly prohibited. Use explicit return types for all public methods. - **State Management:** Abstract global state logically depending on the specific framework rules, but never tightly couple presentation layers directly to store calls. - ## 💻 Technologies Included This folder acts as a container for documentation around the following technologies: diff --git a/frontend/solidjs/readme.md b/frontend/solidjs/readme.md index fa1a2cd..8bb3081 100644 --- a/frontend/solidjs/readme.md +++ b/frontend/solidjs/readme.md @@ -7,10 +7,12 @@ version: "1.8+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior SolidJS Expert last_updated: 2026-03-22 ---- +topic: SolidJS +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # ⚡ SolidJS Best Practices & Production-Ready Patterns - # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to modern SolidJS patterns, specifically fine-grained reactivity and functional APIs for optimal best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -21,14 +23,11 @@ last_updated: 2026-03-22 > - **Always** use `createSignal()`, `createMemo()`, and `createEffect()` for local state and side effects. > - **Never** destructure props directly; use `splitProps()` or `mergeProps()` instead. > - **Always** utilize the built-in control flow (``, ``, ``) instead of mapping or ternary operators in JSX. - ## 🏗 Architecture Principles - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications. - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. - ## 🚀 I. Basics & Popular - ## 1. Using JSX Map for Lists **Context:** Rendering Lists ### ❌ Bad Practice diff --git a/frontend/typescript/logic-safety.md b/frontend/typescript/logic-safety.md index 3dee318..621b7e8 100644 --- a/frontend/typescript/logic-safety.md +++ b/frontend/typescript/logic-safety.md @@ -7,17 +7,17 @@ version: "5.5+" tags: [typescript, type-safety, best-practices, clean-code, scalable-code] ai_role: Senior TypeScript Expert last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🛡️ TypeScript Logic & Safety Best Practices - # 📖 Context & Scope - **Primary Goal:** Enforce strict type safety and logical soundness in TypeScript. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** TypeScript 5.5+ - ## II. Logic & Safety (11-20) - ## 11. Type Assertions (`as`) vs Narrowing **Context:** Telling the compiler what a type is. ### ❌ Bad Practice @@ -35,7 +35,6 @@ if (isValidUser(response.data)) { ... } ``` ### 🚀 Solution Avoid type assertions. Use runtime validation (Zod, Valibot) or Type Guards to ensure the data actually matches the type you expect. - ## 12. Non-null Assertion Operator (`!`) **Context:** Dealing with potentially `null` or `undefined` values. ### ❌ Bad Practice @@ -50,7 +49,6 @@ const name = user?.profile?.name ?? 'Guest'; ``` ### 🚀 Solution Use Optional Chaining (`?.`) and Nullish Coalescing (`??`) to handle missing values gracefully. - ## 13. Lack of Discriminated Unions **Context:** Modeling complex states like API responses. ### ❌ Bad Practice @@ -72,7 +70,6 @@ type State = ``` ### 🚀 Solution Use Discriminated Unions (with a shared literal property like `type` or `kind`). This makes states mutually exclusive and simplifies logic. - ## 14. Boolean casting (`!!`) **Context:** Converting values to booleans. ### ❌ Bad Practice @@ -89,7 +86,6 @@ const hasAccess = user.token !== undefined; ``` ### 🚀 Solution Use the `Boolean()` constructor or explicit comparisons for clarity. - ## 15. Using `Object` for non-primitive types **Context:** Restricting types to objects. ### ❌ Bad Practice @@ -104,7 +100,6 @@ function cache(obj: Record) { ... } ``` ### 🚀 Solution Use `Record` for general objects or `Record` for empty objects to ensure keys are strings and values are handled safely. - ## 16. Function types vs Object types for functions **Context:** Defining function signatures. ### ❌ Bad Practice @@ -121,7 +116,6 @@ type ClickHandler = (e: Event) => void; ``` ### 🚀 Solution Use the arrow function syntax for type aliases unless you need to define properties on the function itself (callable objects). - ## 17. Catching `any` in try-catch **Context:** Handling exceptions. ### ❌ Bad Practice @@ -129,7 +123,7 @@ Use the arrow function syntax for type aliases unless you need to define propert try { doWork(); } catch (e) { - console.error(e.message); // e is any by default + console.error(e.message); // e is unknown by default } ``` ### ⚠️ Problem @@ -146,7 +140,6 @@ try { ``` ### 🚀 Solution Always check the type of the caught error. In modern TS, use `useUnknownInCatchVariables: true` to force `e` to be `unknown`. - ## 18. Literal types vs General types **Context:** Narrowing strings/numbers to specific values. ### ❌ Bad Practice @@ -162,7 +155,6 @@ function setAlignment(dir: Direction) { ... } ``` ### 🚀 Solution Use Union Literal types to restrict inputs to a known set of valid values. - ## 19. Optional properties vs Union with `undefined` **Context:** Defining fields that might not exist. ### ❌ Bad Practice @@ -181,7 +173,6 @@ interface Config { ``` ### 🚀 Solution Use `?` for properties that can be omitted entirely. - ## 20. Array index access safety **Context:** Accessing elements by index. ### ❌ Bad Practice @@ -200,5 +191,4 @@ if (first) { ``` ### 🚀 Solution Enable `noUncheckedIndexedAccess: true` in `tsconfig.json`. This forces index access to return `T | undefined`. - --- diff --git a/frontend/typescript/objects-functions.md b/frontend/typescript/objects-functions.md index 597794a..9bd9c85 100644 --- a/frontend/typescript/objects-functions.md +++ b/frontend/typescript/objects-functions.md @@ -7,17 +7,17 @@ version: "5.5+" tags: [typescript, objects, functions, best-practices, clean-code, scalable-code] ai_role: Senior TypeScript Expert last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 📦 TypeScript Objects & Functions Best Practices - # 📖 Context & Scope - **Primary Goal:** Proper typing for objects, arrays, and functions in TypeScript applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** TypeScript 5.5+ - ## III. Objects & Functions (21-30) - ## 21. Object literals vs `Record` **Context:** Defining maps/dictionaries. ### ❌ Bad Practice @@ -32,7 +32,6 @@ const prices: Record = { apple: 1 }; ``` ### 🚀 Solution Use the `Record` utility type for key-value maps. - ## 22. Excess property checks and object spreading **Context:** Passing objects to functions. ### ❌ Bad Practice @@ -50,7 +49,6 @@ saveUser(validUser); ``` ### 🚀 Solution Be explicit about what data you pass. Use destructuring to strip unknown properties before passing objects to storage or APIs. - ## 23. `Readonly` for Immutability **Context:** Preventing accidental state mutation. ### ❌ Bad Practice @@ -69,7 +67,6 @@ function process(config: Readonly) { ``` ### 🚀 Solution Use `Readonly` for function parameters and `as const` for configuration objects to enforce immutability at compile time. - ## 24. `Awaited` for Promise Unwrapping **Context:** Getting the resolved type of a Promise. ### ❌ Bad Practice @@ -84,12 +81,11 @@ type Result = Awaited>; ``` ### 🚀 Solution Use the `Awaited` utility type (TS 4.5+) for clean promise unwrapping. - ## 25. `this` typing in functions **Context:** Ensuring correct context in callback-heavy code. ### ❌ Bad Practice ```typescript -function handleClick(this: any, event: Event) { +function handleClick(this: unknown, event: Event) { this.classList.add('active'); } ``` @@ -103,7 +99,6 @@ function handleClick(this: HTMLElement, event: Event) { ``` ### 🚀 Solution Always type the first "fake" `this` parameter in functions that rely on a specific execution context. - ## 26. Constructor Shorthand **Context:** Defining class properties. ### ❌ Bad Practice @@ -125,7 +120,6 @@ class User { ``` ### 🚀 Solution Use parameter properties in constructors to declare and initialize class members in one step. - ## 27. Abstract classes vs Interfaces **Context:** Defining blueprints for classes. ### ❌ Bad Practice @@ -145,7 +139,6 @@ abstract class BaseService { ``` ### 🚀 Solution Use `abstract` classes when you need to provide shared logic while forcing sub-classes to implement specific methods. - ## 28. Private vs `#private` **Context:** Encapsulating data in classes. ### ❌ Bad Practice @@ -165,7 +158,6 @@ class User { ``` ### 🚀 Solution Use ES2020 `#private` fields for true runtime encapsulation if you are building libraries or high-security components. - ## 29. Decorators (Legacy vs TC39) **Context:** Meta-programming in TypeScript. ### ❌ Bad Practice @@ -180,7 +172,6 @@ Legacy decorators are non-standard and might break in future versions of Node/Br Use the new TC39 Decorators (TS 5.0+) which align with the official JavaScript proposal. ### 🚀 Solution If starting a new project, avoid decorators unless using a framework that mandates them (like NestJS or Angular). - ## 30. Utility Types (`Omit`, `Pick`, `Partial`) **Context:** Transforming existing types. ### ❌ Bad Practice @@ -198,5 +189,4 @@ type UserUpdate = Partial>; ``` ### 🚀 Solution Always derive sub-types from the source of truth using built-in utility types. - --- diff --git a/frontend/typescript/professional-niche.md b/frontend/typescript/professional-niche.md index 1f46c77..be0ff6e 100644 --- a/frontend/typescript/professional-niche.md +++ b/frontend/typescript/professional-niche.md @@ -7,17 +7,17 @@ version: "5.5+" tags: [typescript, advanced, best-practices, clean-code, scalable-code] ai_role: Senior TypeScript Expert last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🧠 TypeScript Professional & Niche Best Practices - # 📖 Context & Scope - **Primary Goal:** Advanced TypeScript features, metaprogramming, and precise utility types. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** TypeScript 5.5+ - ## IV. Professional & Niche (31-40) - ## 31. Using `satisfies` to preserve literal types **Context:** Checking an object against a type without widening it. ### ❌ Bad Practice @@ -38,7 +38,6 @@ const config = { ``` ### 🚀 Solution Use `satisfies` (TS 4.9+). It validates the structure but preserves the narrowest possible type for the value. - ## 32. `const` type parameters (TS 5.0) **Context:** Improving inference for generic constants. ### ❌ Bad Practice @@ -55,7 +54,6 @@ route(['/home', '/about']); // T is readonly ['/home', '/about'] ``` ### 🚀 Solution Use `const` before a type parameter to force the compiler to treat the input as a constant, preserving literal types without requiring the caller to use `as const`. - ## 33. Branding/Tagging for Nominal Typing **Context:** Preventing accidental mixing of identical primitive types (e.g., `UserId` and `OrderId`). ### ❌ Bad Practice @@ -79,7 +77,6 @@ const uid = 'user_1' as UserId; ``` ### 🚀 Solution Use "Branding" (adding a phantom property) to simulate nominal typing for critical identifiers. - ## 34. Covariance/Contravariance in callbacks **Context:** Ensuring safe function assignments. ### ❌ Bad Practice @@ -98,7 +95,6 @@ interface Logger { ``` ### 🚀 Solution Use method syntax in interfaces for stricter **contravariant** checking of parameters. - ## 35. Avoiding "God Objects" through Mapped Types **Context:** Transforming object structures dynamically. ### ❌ Bad Practice @@ -119,7 +115,6 @@ type API = { ``` ### 🚀 Solution Use Mapped Types and Key Remapping (`as`) to generate interface structures from a single source of truth (like a union of keys). - ## 36. Template Literal Types for string-based APIs **Context:** Enforcing patterns in strings. ### ❌ Bad Practice @@ -135,7 +130,6 @@ function setPadding(value: CssValue) { ... } ``` ### 🚀 Solution Use Template Literal types to enforce specific string patterns at compile time. - ## 37. Exhaustiveness checking with `never` **Context:** Ensuring all cases in a union are handled. ### ❌ Bad Practice @@ -164,7 +158,6 @@ function handle(action: 'START' | 'STOP' | 'PAUSE') { ``` ### 🚀 Solution Assign the `default` case to a variable of type `never`. This triggers a compile error if any member of the union is unhandled. - ## 38. Recursive Type Aliases **Context:** Modeling nested structures like JSON or file trees. ### ❌ Bad Practice @@ -183,7 +176,6 @@ type JSONValue = ``` ### 🚀 Solution Use recursive type aliases for cleaner definitions of deeply nested data structures. - ## 39. `infer` keyword in conditional types **Context:** Extracting internal types from complex structures. ### ❌ Bad Practice @@ -199,7 +191,6 @@ type GetArrayType = T extends (infer U)[] ? U : never; ``` ### 🚀 Solution Use `infer` within conditional types to let TypeScript dynamically capture and name types from within generics. - ## 40. Tuple types for fixed-length data **Context:** Representing arrays with specific structures (e.g., coordinates). ### ❌ Bad Practice diff --git a/frontend/typescript/readme.md b/frontend/typescript/readme.md index 25c0946..836be28 100644 --- a/frontend/typescript/readme.md +++ b/frontend/typescript/readme.md @@ -7,19 +7,20 @@ version: "5.0+" tags: [typescript, type-safety, clean-code, best-practices, architecture] ai_role: Senior TypeScript Architecture Expert last_updated: 2026-03-22 ---- +topic: TypeScript +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true--- # 🎨 TypeScript Best Practise ![TypeScript Logo](https://img.icons8.com/?size=100&id=uJM6fQYqDaZK&format=png&color=000000) - ## 🚀 I. Fundamentals (1-10) - ## ⚡ 1. `any` vs `unknown` **Context:** Handling data of an uncertain type. `any` disables all type-checking, while `unknown` forces safety. ### ❌ Bad Practice ```typescript -function process(data: any) { +function process(data: unknown) { console.log(data.name); // No error, but might crash at runtime } ``` @@ -35,9 +36,7 @@ function process(data: unknown) { ``` ### 🚀 Solution Use `unknown` for values whose type is not yet determined. It requires a type check or assertion before usage, ensuring the developer acknowledges the data's structure. - --- - ## ⚡ 2. `null` vs `undefined` in APIs **Context:** Distinguishing between "value not provided" and "value is empty." ### ❌ Bad Practice @@ -56,9 +55,7 @@ interface UserResponse { ``` ### 🚀 Solution Standardize: use `undefined` (optional properties) for missing keys and `null` for intentional absence of value. Avoid using both for the same field unless strictly required by a legacy API. - --- - ## ⚡ 3. `Array` vs `T[]` **Context:** Visual consistency in array declarations. ### ❌ Bad Practice @@ -75,9 +72,7 @@ const complex: (string | number)[] = []; ``` ### 🚀 Solution Prefer the shorthand `T[]`. It is idiomatic, more readable, and clearly distinguishes arrays from other generic containers like `Record` or `Promise`. - --- - ## ⚡ 4. `interface` vs `type` **Context:** Defining object structures and aliases. ### ❌ Bad Practice @@ -95,16 +90,14 @@ type Union = 'A' | 'B'; ``` ### 🚀 Solution Use `type` for almost everything (unions, primitives, intersections). Use `interface` only when you specifically need declaration merging or for public library APIs where consumers might need to extend types. - --- - ## ⚡ 5. Function Overloads vs Union Types **Context:** Handling functions with different input/output combinations. ### ❌ Bad Practice ```typescript function format(input: string): string; function format(input: number): string; -function format(input: any): string { +function format(input: unknown): string { return String(input); } ``` @@ -118,9 +111,7 @@ function format(input: string | number): string { ``` ### 🚀 Solution Prefer Union types when the implementation logic is identical for all types. Reserve overloads only for cases where the return type strictly depends on the input type and cannot be expressed via generics. - --- - ## 🎯 6. Global Scope Pollution (Legacy Namespaces) **Context:** Organizing code in the ES Module era. ### ❌ Bad Practice @@ -138,9 +129,7 @@ export const log = (msg: string) => console.log(msg); ``` ### 🚀 Solution Use ES Modules (`export`/`import`). They are the industry standard, supported by all modern environments, and allow for better static analysis. - --- - ## ⚡ 7. `enum` vs `const object` **Context:** Grouping related constants. ### ❌ Bad Practice @@ -163,14 +152,12 @@ type Status = typeof STATUS[keyof typeof STATUS]; ``` ### 🚀 Solution Use `const` objects with `as const` and a derived union type. This is more predictable, emits cleaner code, and is easier to iterate over. - --- - ## ⚡ 8. Explicit `any` in Parameters **Context:** Enforcing strict type safety. ### ❌ Bad Practice ```typescript -function save(data) { // Implicit any if strict: false +function save(data) { // Implicit unknown if strict: false db.push(data); } ``` @@ -184,15 +171,13 @@ function save(data: UserData) { ``` ### 🚀 Solution Enable `noImplicitAny: true` in `tsconfig.json`. Always define specific types or use `unknown` if the type is truly dynamic. - --- - ## ⚡ 9. Manual Type Guards vs Type Predicates **Context:** Narrowing types inside conditional blocks. ### ❌ Bad Practice ```typescript if (typeof input === 'object' && input !== null && 'admin' in input) { - const isAdmin = (input as any).admin; + const isAdmin = (input as unknown).admin; } ``` ### ⚠️ Problem @@ -209,9 +194,7 @@ if (isAdmin(input)) { ``` ### 🚀 Solution Use Type Predicates (`arg is Type`) to create reusable, safe narrowing functions. - --- - ## ⚡ 10. Triple-Slash Directives **Context:** Referencing types or files. ### ❌ Bad Practice @@ -226,13 +209,10 @@ import { MyType } from './types'; ``` ### 🚀 Solution Use standard ES `import` statements. Manage global types via `tsconfig.json` `types` array if necessary. - --- - --- [⬆️ Back to Top](#) - ## 📚 Specialized Topics For further reading, please refer to the following specialized guides: diff --git a/gemini.md b/gemini.md index 52d9b23..c415add 100644 --- a/gemini.md +++ b/gemini.md @@ -1,2 +1,15 @@ +--- +description: Vibe coding guidelines and architectural constraints for Vibe Coding within the Documentation domain. +tags: [vibe-coding, documentation, best-practices, architecture] +topic: Vibe Coding +complexity: Architect +last_evolution: 2026-03-29 +vibe_coding_ready: true +technology: Vibe Coding +domain: Documentation +level: Senior/Architect +version: Latest +ai_role: Senior Vibe Coding Expert +last_updated: 2026-03-29--- @./.gemini/memory/github-seo.md @./.agents/rules/project-architecture.md \ No newline at end of file