@softspark/ai-toolkit 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/AGENTS.md +5 -29
  2. package/CHANGELOG.md +39 -0
  3. package/README.md +170 -27
  4. package/app/.claude-plugin/plugin.json +2 -2
  5. package/app/ARCHITECTURE.md +35 -19
  6. package/app/agents/ai-engineer.md +47 -5
  7. package/app/agents/fact-checker.md +1 -1
  8. package/app/agents/llm-ops-engineer.md +2 -2
  9. package/app/agents/{mcp-server-architect.md → mcp-specialist.md} +124 -18
  10. package/app/agents/mcp-testing-engineer.md +2 -2
  11. package/app/agents/nlp-engineer.md +1 -1
  12. package/app/agents/orchestrator.md +3 -4
  13. package/app/agents/project-planner.md +1 -1
  14. package/app/agents/technical-researcher.md +71 -21
  15. package/app/hooks/commit-quality.sh +53 -0
  16. package/app/hooks/governance-capture.sh +77 -0
  17. package/app/hooks/guard-config.sh +46 -0
  18. package/app/hooks/mcp-health.sh +53 -0
  19. package/app/hooks/pre-compact-save.sh +34 -0
  20. package/app/hooks/session-context.sh +60 -0
  21. package/app/hooks.json +60 -0
  22. package/app/mcp-templates/README.md +105 -0
  23. package/app/mcp-templates/brave-search.json +13 -0
  24. package/app/mcp-templates/cloudflare.json +14 -0
  25. package/app/mcp-templates/context7.json +10 -0
  26. package/app/mcp-templates/custom-template.json +13 -0
  27. package/app/mcp-templates/datadog.json +15 -0
  28. package/app/mcp-templates/docker.json +10 -0
  29. package/app/mcp-templates/fetch.json +10 -0
  30. package/app/mcp-templates/filesystem.json +10 -0
  31. package/app/mcp-templates/git.json +10 -0
  32. package/app/mcp-templates/github.json +13 -0
  33. package/app/mcp-templates/google-drive.json +15 -0
  34. package/app/mcp-templates/google-maps.json +13 -0
  35. package/app/mcp-templates/grafana.json +14 -0
  36. package/app/mcp-templates/linear.json +13 -0
  37. package/app/mcp-templates/memory.json +10 -0
  38. package/app/mcp-templates/notion.json +13 -0
  39. package/app/mcp-templates/postgres.json +10 -0
  40. package/app/mcp-templates/puppeteer.json +10 -0
  41. package/app/mcp-templates/redis.json +13 -0
  42. package/app/mcp-templates/sentry.json +14 -0
  43. package/app/mcp-templates/sequential-thinking.json +10 -0
  44. package/app/mcp-templates/slack.json +14 -0
  45. package/app/mcp-templates/sqlite.json +10 -0
  46. package/app/mcp-templates/supabase.json +14 -0
  47. package/app/mcp-templates/vercel.json +13 -0
  48. package/app/plugins/research-pack/README.md +1 -1
  49. package/app/plugins/research-pack/plugin.json +1 -1
  50. package/app/rules/claude-toolkit-rules.md +1 -1
  51. package/app/rules/common/coding-style.md +52 -0
  52. package/app/rules/common/git-workflow.md +45 -0
  53. package/app/rules/common/performance.md +49 -0
  54. package/app/rules/common/security.md +59 -0
  55. package/app/rules/common/testing.md +53 -0
  56. package/app/rules/cpp/coding-style.md +55 -0
  57. package/app/rules/cpp/frameworks.md +55 -0
  58. package/app/rules/cpp/patterns.md +57 -0
  59. package/app/rules/cpp/security.md +61 -0
  60. package/app/rules/cpp/testing.md +58 -0
  61. package/app/rules/csharp/coding-style.md +54 -0
  62. package/app/rules/csharp/frameworks.md +60 -0
  63. package/app/rules/csharp/patterns.md +61 -0
  64. package/app/rules/csharp/security.md +60 -0
  65. package/app/rules/csharp/testing.md +58 -0
  66. package/app/rules/dart/coding-style.md +61 -0
  67. package/app/rules/dart/frameworks.md +59 -0
  68. package/app/rules/dart/patterns.md +62 -0
  69. package/app/rules/dart/security.md +60 -0
  70. package/app/rules/dart/testing.md +60 -0
  71. package/app/rules/golang/coding-style.md +50 -0
  72. package/app/rules/golang/frameworks.md +56 -0
  73. package/app/rules/golang/patterns.md +52 -0
  74. package/app/rules/golang/security.md +61 -0
  75. package/app/rules/golang/testing.md +54 -0
  76. package/app/rules/java/coding-style.md +56 -0
  77. package/app/rules/java/frameworks.md +54 -0
  78. package/app/rules/java/patterns.md +59 -0
  79. package/app/rules/java/security.md +60 -0
  80. package/app/rules/java/testing.md +55 -0
  81. package/app/rules/kotlin/coding-style.md +56 -0
  82. package/app/rules/kotlin/frameworks.md +54 -0
  83. package/app/rules/kotlin/patterns.md +54 -0
  84. package/app/rules/kotlin/security.md +62 -0
  85. package/app/rules/kotlin/testing.md +56 -0
  86. package/app/rules/php/coding-style.md +53 -0
  87. package/app/rules/php/frameworks.md +57 -0
  88. package/app/rules/php/patterns.md +63 -0
  89. package/app/rules/php/security.md +61 -0
  90. package/app/rules/php/testing.md +60 -0
  91. package/app/rules/python/coding-style.md +52 -0
  92. package/app/rules/python/frameworks.md +53 -0
  93. package/app/rules/python/patterns.md +53 -0
  94. package/app/rules/python/security.md +58 -0
  95. package/app/rules/python/testing.md +52 -0
  96. package/app/rules/ruby/coding-style.md +56 -0
  97. package/app/rules/ruby/frameworks.md +56 -0
  98. package/app/rules/ruby/patterns.md +61 -0
  99. package/app/rules/ruby/security.md +61 -0
  100. package/app/rules/ruby/testing.md +63 -0
  101. package/app/rules/rust/coding-style.md +52 -0
  102. package/app/rules/rust/frameworks.md +59 -0
  103. package/app/rules/rust/patterns.md +58 -0
  104. package/app/rules/rust/security.md +64 -0
  105. package/app/rules/rust/testing.md +54 -0
  106. package/app/rules/swift/coding-style.md +55 -0
  107. package/app/rules/swift/frameworks.md +63 -0
  108. package/app/rules/swift/patterns.md +63 -0
  109. package/app/rules/swift/security.md +63 -0
  110. package/app/rules/swift/testing.md +60 -0
  111. package/app/rules/typescript/coding-style.md +51 -0
  112. package/app/rules/typescript/frameworks.md +51 -0
  113. package/app/rules/typescript/patterns.md +51 -0
  114. package/app/rules/typescript/security.md +55 -0
  115. package/app/rules/typescript/testing.md +52 -0
  116. package/app/skills/app-builder/SKILL.md +1 -1
  117. package/app/skills/brand-voice/SKILL.md +92 -0
  118. package/app/skills/council/SKILL.md +133 -0
  119. package/app/skills/introspect/SKILL.md +125 -0
  120. package/bin/ai-toolkit.js +103 -2
  121. package/kb/reference/agents-catalog.md +10 -13
  122. package/kb/reference/architecture-overview.md +29 -6
  123. package/kb/reference/commands-catalog.md +4 -4
  124. package/kb/reference/competitive-features-implementation.md +677 -0
  125. package/kb/reference/extension-api.md +175 -0
  126. package/kb/reference/hooks-catalog.md +90 -14
  127. package/kb/reference/language-rules.md +167 -0
  128. package/kb/reference/manifest-install.md +165 -0
  129. package/kb/reference/mcp-templates.md +110 -0
  130. package/kb/reference/skills-catalog.md +9 -6
  131. package/llms-full.txt +1511 -59
  132. package/llms.txt +8 -3
  133. package/package.json +2 -2
  134. package/scripts/inject_hook_cli.py +330 -0
  135. package/scripts/install.py +241 -7
  136. package/scripts/install_steps/ai_tools.py +63 -1
  137. package/scripts/install_steps/detect_language.py +50 -0
  138. package/scripts/install_steps/install_state.py +117 -0
  139. package/scripts/mcp_manager.py +206 -0
  140. package/app/agents/mcp-expert.md +0 -228
  141. package/app/agents/rag-engineer.md +0 -201
  142. package/app/agents/research-synthesizer.md +0 -138
@@ -0,0 +1,62 @@
1
+ ---
2
+ language: kotlin
3
+ category: security
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # Kotlin Security
8
+
9
+ ## Input Validation
10
+ - Validate all inputs at API boundaries using Bean Validation or manual checks.
11
+ - Use `require()` for argument validation: `require(age > 0) { "Age must be positive" }`.
12
+ - Use data class `init` blocks for domain validation on construction.
13
+ - Never trust client-provided IDs. Verify resource ownership server-side.
14
+ - Sanitize strings before using in HTML, SQL, or shell commands.
15
+
16
+ ## Null Safety as Security
17
+ - Kotlin's null safety prevents null pointer exceptions. Do not circumvent with `!!`.
18
+ - Use `?.` and `?:` chains for safe fallback values at boundaries.
19
+ - Treat Java interop as untrusted: platform types can still be null.
20
+ - Use `@Nullable` / `@NotNull` annotations on Java code consumed by Kotlin.
21
+
22
+ ## SQL Injection
23
+ - Use Exposed DSL or JPA with parameterized queries. Never concatenate input.
24
+ - Use `PreparedStatement` if writing raw JDBC.
25
+ - Use `CriteriaBuilder` or Exposed conditions for dynamic query construction.
26
+ - Audit `@Query(nativeQuery = true)` for parameter interpolation risks.
27
+
28
+ ## Serialization
29
+ - Use `kotlinx.serialization` with `@Serializable` for compile-time safety.
30
+ - Use `Json { ignoreUnknownKeys = true }` but validate after deserialization.
31
+ - Never use Java `ObjectInputStream` for deserialization (RCE risk).
32
+ - Restrict polymorphic deserialization to known sealed class subtypes.
33
+
34
+ ## Authentication
35
+ - Use Spring Security or Ktor Authentication plugin. Do not roll your own.
36
+ - Hash passwords with BCrypt or Argon2. Never store plaintext.
37
+ - Use short-lived JWTs (15 min) with refresh token rotation.
38
+ - Validate JWT signature, issuer, audience, and expiration on every request.
39
+
40
+ ## Coroutine Security
41
+ - Use `withTimeout()` to prevent unbounded coroutine execution (DoS vector).
42
+ - Use `Mutex` for critical sections. Do not use `synchronized` in suspend functions.
43
+ - Propagate security context through `CoroutineContext` elements.
44
+ - Cancel coroutine scopes on authentication failure or session expiry.
45
+
46
+ ## Secrets Management
47
+ - Use environment variables or Vault for secrets. Never hardcode.
48
+ - Use `@ConfigurationProperties` with injected secrets, not string literals.
49
+ - Never log request headers containing Authorization tokens.
50
+ - Use separate configuration profiles for dev/staging/prod secrets.
51
+
52
+ ## Dependencies
53
+ - Use Dependabot or Renovate for automated dependency updates.
54
+ - Run OWASP Dependency-Check or Gradle `dependencyCheckAnalyze`.
55
+ - Audit transitive dependencies with `gradle dependencies`.
56
+ - Pin dependency versions. Avoid dynamic versions like `1.+`.
57
+
58
+ ## Logging
59
+ - Use parameterized logging: `logger.info("User {} logged in", userId)`.
60
+ - Never log passwords, tokens, or PII.
61
+ - Sanitize user input before logging to prevent log injection.
62
+ - Use structured logging (JSON) for machine-parseable audit trails.
@@ -0,0 +1,56 @@
1
+ ---
2
+ language: kotlin
3
+ category: testing
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # Kotlin Testing
8
+
9
+ ## Framework
10
+ - Use JUnit 5 as the test runner.
11
+ - Use Kotest for Kotlin-idiomatic BDD-style testing (alternative).
12
+ - Use MockK for mocking (Kotlin-native, supports coroutines).
13
+ - Use Testcontainers for integration tests with external services.
14
+
15
+ ## File Naming
16
+ - Test files: `FooTest.kt` in `src/test/kotlin/` mirroring source package.
17
+ - Integration tests: `FooIT.kt` or use `@Tag("integration")`.
18
+ - Use `@Nested` inner classes to group related test cases.
19
+
20
+ ## Structure
21
+ - Use `@DisplayName` for human-readable test names.
22
+ - Use backtick function names for readable test names: `` `returns 404 when user not found` ``.
23
+ - Use `@BeforeEach` for per-test setup. Avoid shared mutable state.
24
+ - Use `@ParameterizedTest` with `@MethodSource` for table-driven tests.
25
+
26
+ ## MockK
27
+ - Use `mockk<UserRepository>()` to create mocks.
28
+ - Use `every { mock.find(any()) } returns user` for stubbing.
29
+ - Use `coEvery { ... }` and `coVerify { ... }` for coroutine mocking.
30
+ - Use `spyk()` for partial mocks on real objects.
31
+ - Use `slot<T>()` and `captured` to inspect arguments.
32
+ - Clear mocks in `@AfterEach` to prevent state leakage.
33
+
34
+ ## Coroutine Testing
35
+ - Use `runTest { }` from `kotlinx-coroutines-test` for coroutine tests.
36
+ - Use `TestDispatcher` to control coroutine execution timing.
37
+ - Use `advanceUntilIdle()` to complete all pending coroutines.
38
+ - Use `turbine` library for testing `Flow` emissions.
39
+
40
+ ## Assertions
41
+ - Use AssertJ or Kotest assertions for fluent, readable checks.
42
+ - Use `shouldBe`, `shouldThrow`, `shouldContain` (Kotest matchers).
43
+ - Use `assertSoftly { }` to collect multiple assertion failures.
44
+ - Use `assertThrows<FooException> { ... }` for exception testing.
45
+
46
+ ## Test Data
47
+ - Use factory functions for test data: `fun aUser(name: String = "Ada") = User(...)`.
48
+ - Use default parameters for minimal test data setup.
49
+ - Use `copy()` on data classes for variations of base test objects.
50
+ - Use `faker` library for realistic test data generation.
51
+
52
+ ## Spring Integration
53
+ - Use `@SpringBootTest` with `@AutoConfigureMockMvc` for API tests.
54
+ - Use `@WebMvcTest` for controller-only tests (faster).
55
+ - Use `@MockkBean` instead of `@MockBean` for MockK integration.
56
+ - Use `@Transactional` on test classes for automatic rollback.
@@ -0,0 +1,53 @@
1
+ ---
2
+ language: php
3
+ category: coding-style
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # PHP Coding Style
8
+
9
+ ## Standards
10
+ - Follow PSR-12 extended coding style.
11
+ - Use `declare(strict_types=1)` at the top of every file.
12
+ - Use PHP 8.1+ features: enums, fibers, readonly properties, intersection types.
13
+ - Use PHP CS Fixer or Pint for automated formatting.
14
+
15
+ ## Naming
16
+ - PascalCase: classes, interfaces, traits, enums.
17
+ - camelCase: methods, functions, variables.
18
+ - UPPER_SNAKE: class constants (`public const MAX_RETRIES = 3`).
19
+ - snake_case: not used for methods. PSR convention is camelCase.
20
+ - Suffix interfaces with `Interface` or prefix with contract name (project convention).
21
+
22
+ ## Type System
23
+ - Use typed properties: `private readonly string $name;`.
24
+ - Use union types: `string|int`. Use intersection types: `Countable&Iterator`.
25
+ - Use `enum` (PHP 8.1) for fixed sets of values. Use backed enums for persistence.
26
+ - Use `readonly` classes (PHP 8.2) for immutable DTOs.
27
+ - Use constructor promotion: `public function __construct(private string $name)`.
28
+ - Use `never` return type for functions that throw or exit.
29
+
30
+ ## Functions
31
+ - Use typed parameters and return types on all functions/methods.
32
+ - Use named arguments for readability: `new User(name: 'Ada', age: 36)`.
33
+ - Use null-safe operator: `$user?->address?->city`.
34
+ - Use match expression over switch for value mapping.
35
+ - Use first-class callable syntax: `array_map($this->transform(...), $items)`.
36
+
37
+ ## Imports and Namespaces
38
+ - Use PSR-4 autoloading via Composer.
39
+ - Group `use` statements: classes, functions, constants.
40
+ - Never use `require`/`include` for class loading. Use Composer autoloader.
41
+ - Use one class per file. File name matches class name.
42
+
43
+ ## Error Handling
44
+ - Use exceptions for error conditions. Never return error codes.
45
+ - Create domain exception hierarchies extending `RuntimeException` or `LogicException`.
46
+ - Use `match` with `throw` for exhaustive error mapping.
47
+ - Log exceptions with context using PSR-3 logger.
48
+
49
+ ## Configuration
50
+ - Use PHPStan at level 8+ for static analysis.
51
+ - Use Rector for automated code upgrades and refactoring.
52
+ - Use `.php-cs-fixer.dist.php` for formatting rules.
53
+ - Run `composer analyse` (PHPStan) and `composer format` (Pint) in CI.
@@ -0,0 +1,57 @@
1
+ ---
2
+ language: php
3
+ category: frameworks
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # PHP Frameworks
8
+
9
+ ## Laravel
10
+ - Use route model binding: `Route::get('/users/{user}', ...)`.
11
+ - Use Form Requests for validation: `class StoreUserRequest extends FormRequest`.
12
+ - Use Eloquent scopes for reusable query constraints: `scopeActive()`.
13
+ - Use API Resources for response transformation: `UserResource::collection($users)`.
14
+ - Use `config()` helper for configuration. Never access `env()` outside config files.
15
+ - Use middleware groups for auth, throttling, and CORS.
16
+
17
+ ## Eloquent ORM
18
+ - Use relationships: `hasMany`, `belongsTo`, `belongsToMany`, `morphMany`.
19
+ - Use eager loading: `User::with('posts.comments')->get()` to prevent N+1.
20
+ - Use `$fillable` or `$guarded` on models. Prefer `$fillable` (explicit whitelist).
21
+ - Use model events or observers for lifecycle hooks.
22
+ - Use `upsert()` for bulk insert-or-update operations.
23
+ - Use `cursor()` for memory-efficient iteration over large result sets.
24
+
25
+ ## Symfony
26
+ - Use attributes for route definitions: `#[Route('/api/users', methods: ['GET'])]`.
27
+ - Use autowiring for dependency injection. Register services in `services.yaml`.
28
+ - Use Symfony Forms for complex validation and data mapping.
29
+ - Use Messenger component for async message handling (commands, events).
30
+ - Use Doctrine ORM with repository pattern and query builders.
31
+
32
+ ## Doctrine ORM
33
+ - Use entity classes with annotations or attributes for mapping.
34
+ - Use repositories for data access: `$em->getRepository(User::class)`.
35
+ - Use DQL for type-safe queries. Use QueryBuilder for dynamic queries.
36
+ - Use migrations: `bin/console doctrine:migrations:diff` and `migrate`.
37
+ - Use lifecycle callbacks (`@PrePersist`, `@PostUpdate`) for entity events.
38
+
39
+ ## API Platform
40
+ - Use API Platform for rapid REST/GraphQL API generation from entities.
41
+ - Use `#[ApiResource]` attribute for automatic CRUD endpoint generation.
42
+ - Use custom state providers and processors for business logic.
43
+ - Use serialization groups for controlling response shape.
44
+ - Use filters for query parameter support: pagination, search, ordering.
45
+
46
+ ## Livewire (Laravel)
47
+ - Use Livewire components for reactive UI without JavaScript.
48
+ - Use `wire:model` for two-way data binding on form inputs.
49
+ - Use `$rules` property for inline validation on component properties.
50
+ - Use component actions for server-side event handling.
51
+ - Use `wire:loading` for loading state indicators.
52
+
53
+ ## Queues and Workers
54
+ - Use Laravel Horizon for Redis queue monitoring and management.
55
+ - Use Symfony Messenger with transports (Redis, AMQP, Doctrine).
56
+ - Use dead letter queues for failed job inspection and replay.
57
+ - Use rate limiting on queue workers to prevent downstream overload.
@@ -0,0 +1,63 @@
1
+ ---
2
+ language: php
3
+ category: patterns
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # PHP Patterns
8
+
9
+ ## Error Handling
10
+ - Use custom exception hierarchies: `class DomainException extends RuntimeException`.
11
+ - Add context to exceptions: `throw new UserNotFoundException(userId: $id)`.
12
+ - Use `match` with `default => throw` for exhaustive error mapping.
13
+ - Use `set_exception_handler()` for global uncaught exception handling.
14
+ - Log exceptions with PSR-3 logger and structured context.
15
+
16
+ ## Enums and Value Objects
17
+ - Use backed enums for database-persisted values: `enum Status: string`.
18
+ - Use `from()` for strict conversion, `tryFrom()` for nullable safe conversion.
19
+ - Implement methods on enums for behavior: `public function label(): string`.
20
+ - Use readonly classes for value objects: `readonly class Money { ... }`.
21
+ - Use constructor promotion for concise value object definitions.
22
+
23
+ ## Repository Pattern
24
+ - Abstract data access behind repository interfaces.
25
+ - Repositories return domain entities, not Eloquent models or arrays.
26
+ - Use constructor injection for repository dependencies.
27
+ - Use specifications or criteria objects for complex query building.
28
+ - Keep repository methods focused: one query per method.
29
+
30
+ ## Service Layer
31
+ - Use service classes for business logic. Keep controllers thin.
32
+ - Use action classes (single-method services) for discrete operations.
33
+ - Use DTOs for data transfer between layers. Never pass request objects to services.
34
+ - Use command/query separation: commands mutate, queries read.
35
+ - Inject dependencies via constructor. Never use `app()` helper in services.
36
+
37
+ ## Collections and Iterators
38
+ - Use Laravel Collections or standalone `illuminate/collections` for data manipulation.
39
+ - Chain `map()`, `filter()`, `reduce()` for declarative data transformation.
40
+ - Use `LazyCollection` for memory-efficient processing of large datasets.
41
+ - Use generators (`yield`) for lazy iteration over large result sets.
42
+ - Prefer `collect()` pipeline over nested loops.
43
+
44
+ ## Async Patterns
45
+ - Use Laravel Queues for background job processing.
46
+ - Use `dispatch()` for fire-and-forget. Use `Bus::chain()` for sequential jobs.
47
+ - Use `ShouldQueue` interface on jobs, listeners, and mailables.
48
+ - Set `$tries`, `$timeout`, `$backoff` on job classes.
49
+ - Use `batch()` for parallel job execution with completion callback.
50
+
51
+ ## Event-Driven
52
+ - Use events and listeners for decoupled side effects.
53
+ - Use domain events for cross-boundary communication.
54
+ - Use `ShouldQueue` on listeners for async event handling.
55
+ - Use event subscribers for grouping related listeners.
56
+ - Keep event payloads minimal: IDs and timestamps, not full objects.
57
+
58
+ ## Anti-Patterns
59
+ - Fat controllers: move logic to services/actions.
60
+ - God models: split into focused models with traits or separate classes.
61
+ - Using `DB::raw()` without parameterization: SQL injection risk.
62
+ - Static method calls for testable dependencies: use DI instead.
63
+ - Returning mixed types: use typed returns or Result objects.
@@ -0,0 +1,61 @@
1
+ ---
2
+ language: php
3
+ category: security
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # PHP Security
8
+
9
+ ## SQL Injection
10
+ - Use PDO prepared statements with bound parameters for all queries.
11
+ - Use Eloquent/Doctrine ORM for type-safe query building.
12
+ - Never concatenate user input into SQL strings. Never use `DB::raw($input)`.
13
+ - Use `whereIn()` with arrays, not string interpolation for IN clauses.
14
+ - Audit raw queries: `DB::select(DB::raw(...))` must use `?` placeholders.
15
+
16
+ ## XSS Prevention
17
+ - Blade templates auto-escape with `{{ }}`. Never use `{!! !!}` with user data.
18
+ - Use `htmlspecialchars()` with `ENT_QUOTES` when outputting outside Blade.
19
+ - Set `Content-Security-Policy` headers to restrict inline scripts.
20
+ - Sanitize rich-text input with HTMLPurifier before storage.
21
+ - Use `strip_tags()` only as a secondary measure, not primary defense.
22
+
23
+ ## CSRF Protection
24
+ - Use `@csrf` directive in all Blade forms.
25
+ - Use `VerifyCsrfToken` middleware (enabled by default in Laravel).
26
+ - Use `X-CSRF-TOKEN` header for AJAX requests from SPA frontends.
27
+ - Exclude only webhook endpoints from CSRF verification (with careful validation).
28
+
29
+ ## Authentication
30
+ - Use `password_hash()` with `PASSWORD_ARGON2ID` or `PASSWORD_BCRYPT`.
31
+ - Use Laravel Sanctum for SPA/mobile API authentication.
32
+ - Use Laravel Passport for full OAuth2 server implementation.
33
+ - Implement rate limiting on login endpoints: `ThrottleRequests` middleware.
34
+ - Use multi-factor authentication for admin accounts.
35
+
36
+ ## Authorization
37
+ - Use Laravel Gates and Policies for authorization logic.
38
+ - Use `$this->authorize('update', $post)` in controllers.
39
+ - Check resource ownership in policies, not just role membership.
40
+ - Default deny: use `Gate::before()` for super-admin bypass, nothing else.
41
+ - Use middleware `can:permission` for route-level authorization.
42
+
43
+ ## File Upload
44
+ - Validate file MIME type server-side. Do not trust `Content-Type` header.
45
+ - Store uploads outside the web root. Use `storage/` with `Storage::disk()`.
46
+ - Generate random filenames. Never use original user-provided filenames.
47
+ - Set maximum file size limits in validation and PHP `upload_max_filesize`.
48
+ - Scan uploaded files for malware in production environments.
49
+
50
+ ## Mass Assignment
51
+ - Use `$fillable` on Eloquent models. Never use `$guarded = []`.
52
+ - Use Form Requests to whitelist fields before model assignment.
53
+ - Use DTOs for data transfer. Never pass `$request->all()` to `create()`.
54
+ - Audit `forceFill()` and `forceCreate()` usage (bypasses guarding).
55
+
56
+ ## Secrets and Configuration
57
+ - Use `.env` files for local secrets. Use Vault or SSM for production.
58
+ - Never commit `.env` to version control. Commit `.env.example` as template.
59
+ - Use `config()` helper, never `env()` outside of config files (caching issue).
60
+ - Never log request content containing passwords or tokens.
61
+ - Use `APP_DEBUG=false` in production. Debug mode leaks sensitive data.
@@ -0,0 +1,60 @@
1
+ ---
2
+ language: php
3
+ category: testing
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # PHP Testing
8
+
9
+ ## Framework
10
+ - Use PHPUnit 10+ as the primary test framework.
11
+ - Use Pest PHP for expressive, minimal-boilerplate testing (built on PHPUnit).
12
+ - Use Mockery for flexible mocking. Use PHPUnit built-in mocks for simple cases.
13
+ - Use Testcontainers (via Docker) for integration tests with databases.
14
+
15
+ ## File Naming
16
+ - Test files: `FooTest.php` in `tests/` mirroring `src/` namespace structure.
17
+ - Unit tests: `tests/Unit/`. Integration tests: `tests/Integration/` or `tests/Feature/`.
18
+ - PHPUnit config: `phpunit.xml.dist` at project root.
19
+ - Use `@group` annotations for test categorization.
20
+
21
+ ## Structure (PHPUnit)
22
+ - Use `#[Test]` attribute (PHP 8) or `test` prefix for test methods.
23
+ - Use `setUp()` / `tearDown()` for per-test initialization and cleanup.
24
+ - Use `#[DataProvider('dataMethodName')]` for parameterized tests.
25
+ - Name tests: `testMethodName_Scenario_ExpectedResult` or descriptive snake_case.
26
+
27
+ ## Structure (Pest)
28
+ - Use `test('description', function () { ... })` for test cases.
29
+ - Use `it('should do something', ...)` for BDD-style descriptions.
30
+ - Use `beforeEach()` / `afterEach()` for setup and teardown.
31
+ - Use `dataset()` for shared test data across multiple tests.
32
+ - Use `->with([...])` for inline parameterized tests.
33
+
34
+ ## Assertions
35
+ - Use `$this->assertSame()` for strict equality (type + value).
36
+ - Use `$this->assertInstanceOf(Foo::class, $result)` for type checks.
37
+ - Use `$this->expectException(FooException::class)` before the throwing call.
38
+ - Use `$this->assertCount()`, `$this->assertContains()` for collections.
39
+ - Pest: use `expect($value)->toBe()`, `->toBeInstanceOf()`, `->toThrow()`.
40
+
41
+ ## Mocking (Mockery)
42
+ - Create mocks: `$mock = Mockery::mock(UserRepository::class)`.
43
+ - Stub: `$mock->shouldReceive('find')->with(1)->andReturn($user)`.
44
+ - Verify: `$mock->shouldHaveReceived('save')->once()`.
45
+ - Use `Mockery::close()` in `tearDown()` or `afterEach()`.
46
+ - Use `spy()` to verify interactions without stubbing.
47
+
48
+ ## Laravel Testing
49
+ - Use `RefreshDatabase` trait for database test isolation.
50
+ - Use `$this->actingAs($user)` for authenticated request testing.
51
+ - Use `$this->getJson('/api/users')->assertOk()->assertJsonCount(3)`.
52
+ - Use factories: `User::factory()->create()` for test data.
53
+ - Use `Bus::fake()`, `Event::fake()`, `Mail::fake()` for side-effect assertion.
54
+
55
+ ## Best Practices
56
+ - Test behavior, not implementation. Do not test private methods.
57
+ - Use in-memory SQLite for fast database tests when schema is compatible.
58
+ - Run `php artisan test --parallel` for faster Laravel test execution.
59
+ - Use `--coverage-html` for visual coverage reports.
60
+ - Keep tests fast: mock external HTTP calls with `Http::fake()`.
@@ -0,0 +1,52 @@
1
+ ---
2
+ language: python
3
+ category: coding-style
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # Python Coding Style
8
+
9
+ ## Type Hints
10
+ - Type all public function signatures (parameters + return).
11
+ - Use `str | None` (PEP 604) over `Optional[str]` on Python 3.10+.
12
+ - Use `from __future__ import annotations` for forward references.
13
+ - Use `TypeAlias` or `type` (3.12+) for complex type aliases.
14
+ - Use `Protocol` for structural subtyping instead of ABCs where possible.
15
+
16
+ ## Naming
17
+ - snake_case: variables, functions, methods, modules.
18
+ - PascalCase: classes, type aliases, Protocols.
19
+ - UPPER_SNAKE: module-level constants.
20
+ - Prefix private: `_internal_helper`. No double underscore unless name mangling needed.
21
+ - Prefix unused: `_` for intentionally unused variables.
22
+
23
+ ## Functions
24
+ - Prefer keyword arguments for functions with >2 params.
25
+ - Use `*` to force keyword-only: `def fetch(*, limit: int, offset: int)`.
26
+ - Return early to reduce nesting. Avoid deep if/else chains.
27
+ - Use `@staticmethod` only for pure utility. Prefer module-level functions.
28
+
29
+ ## Imports
30
+ - Group: stdlib, third-party, local. Separated by blank lines.
31
+ - Use absolute imports. Relative imports only within packages.
32
+ - Never `from module import *`. Be explicit.
33
+ - Use `if TYPE_CHECKING:` for import-only-for-types to avoid circular imports.
34
+
35
+ ## Data Structures
36
+ - Use `dataclasses` for plain data containers.
37
+ - Use Pydantic `BaseModel` for validated data / API schemas.
38
+ - Use `NamedTuple` for lightweight immutable records.
39
+ - Use `Enum` for fixed sets of values. Prefer `StrEnum` on 3.11+.
40
+ - Prefer `dict` / `list` literals over `dict()` / `list()` constructors.
41
+
42
+ ## Modern Python
43
+ - Use f-strings for formatting. Never `.format()` or `%` for new code.
44
+ - Use `pathlib.Path` over `os.path` for file operations.
45
+ - Use `contextlib.suppress(KeyError)` over bare try/except for simple cases.
46
+ - Use walrus operator `:=` when it genuinely improves readability.
47
+ - Use `match/case` (3.10+) for complex conditionals on structured data.
48
+
49
+ ## Tooling
50
+ - Formatter: `ruff format` or `black`. No manual formatting.
51
+ - Linter: `ruff check`. Fix all errors before committing.
52
+ - Type checker: `mypy --strict` or `pyright` in CI.
@@ -0,0 +1,53 @@
1
+ ---
2
+ language: python
3
+ category: frameworks
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # Python Frameworks
8
+
9
+ ## FastAPI
10
+ - Use Pydantic v2 models for request/response schemas.
11
+ - Use dependency injection (`Depends()`) for shared logic (auth, DB sessions).
12
+ - Use `APIRouter` to organize routes by domain.
13
+ - Return Pydantic models directly -- FastAPI handles serialization.
14
+ - Use `BackgroundTasks` for non-critical async work (emails, logging).
15
+ - Use `lifespan` context manager for startup/shutdown (not `on_event`).
16
+
17
+ ## Django
18
+ - Use class-based views for CRUD, function-based for custom logic.
19
+ - Use `select_related` and `prefetch_related` to prevent N+1 queries.
20
+ - Use Django REST Framework serializers for API validation.
21
+ - Use Django ORM migrations. Never modify database schema manually.
22
+ - Use `transaction.atomic()` for multi-model operations.
23
+ - Use signals sparingly: prefer explicit service calls.
24
+
25
+ ## SQLAlchemy 2.0
26
+ - Use the 2.0-style with `select()` statements, not legacy `query()`.
27
+ - Use `Mapped[type]` annotations for typed column definitions.
28
+ - Use `sessionmaker` with `expire_on_commit=False` for API responses.
29
+ - Use `async_sessionmaker` with `asyncpg` for async applications.
30
+ - Always use `session.begin()` context manager for transaction scope.
31
+
32
+ ## Pydantic v2
33
+ - Use `model_validator(mode="before")` for cross-field validation.
34
+ - Use `field_validator` for single-field validation.
35
+ - Use `model_config = ConfigDict(strict=True)` for strict type coercion.
36
+ - Use `Annotated[str, Field(min_length=1)]` for reusable constrained types.
37
+ - Use `model_dump(exclude_unset=True)` for PATCH operations.
38
+
39
+ ## CLI (click / typer)
40
+ - Use Typer for new CLI tools (type-hint-driven, less boilerplate).
41
+ - Use `click.group()` for multi-command CLIs.
42
+ - Use `rich` for formatted terminal output (tables, progress bars).
43
+
44
+ ## Task Queues
45
+ - Use Celery with Redis/RabbitMQ for background job processing.
46
+ - Use `arq` for lightweight async job queues.
47
+ - Always set task timeouts. Never let tasks run indefinitely.
48
+ - Use idempotent tasks: safe to retry on failure.
49
+
50
+ ## Package Management
51
+ - Use `uv` for fast dependency resolution and virtual environments.
52
+ - Use `pyproject.toml` for all project configuration (no setup.py/setup.cfg).
53
+ - Pin dependencies with lockfile (`uv.lock`, `poetry.lock`).
@@ -0,0 +1,53 @@
1
+ ---
2
+ language: python
3
+ category: patterns
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # Python Patterns
8
+
9
+ ## Error Handling
10
+ - Catch specific exceptions, never bare `except:` or `except Exception`.
11
+ - Use custom exception hierarchies: `class AppError(Exception)` as base.
12
+ - Add context when re-raising: `raise AppError("context") from original`.
13
+ - Use `contextlib.suppress()` for expected, ignorable exceptions.
14
+ - Log exceptions with `logger.exception("msg")` to include traceback.
15
+
16
+ ## Context Managers
17
+ - Use `with` for any resource that needs cleanup (files, connections, locks).
18
+ - Create custom context managers with `@contextmanager` decorator.
19
+ - Use `contextlib.AsyncExitStack` for dynamic async resource management.
20
+ - Use `atexit.register()` for process-level cleanup only.
21
+
22
+ ## Async
23
+ - Use `asyncio` for I/O-bound concurrency. Use `multiprocessing` for CPU-bound.
24
+ - Use `asyncio.gather()` for concurrent independent operations.
25
+ - Use `asyncio.TaskGroup` (3.11+) for structured concurrency.
26
+ - Never mix `asyncio.run()` inside already-running event loops.
27
+ - Use `async for` and `async with` for streaming and resource patterns.
28
+
29
+ ## Dataclass Patterns
30
+ - Use `frozen=True` for immutable value objects.
31
+ - Use `field(default_factory=list)` for mutable defaults, never `field(default=[])`.
32
+ - Use `__post_init__` for validation, not complex logic.
33
+ - Use `slots=True` (3.10+) for memory efficiency in high-volume objects.
34
+
35
+ ## Functional Patterns
36
+ - Use `functools.lru_cache` for pure function memoization.
37
+ - Use `itertools` for efficient iteration (chain, islice, groupby).
38
+ - Use generators (`yield`) for lazy sequences and large data processing.
39
+ - Prefer comprehensions over `map/filter` with lambdas.
40
+ - Use `functools.partial` to create specialized versions of functions.
41
+
42
+ ## Dependency Injection
43
+ - Use constructor injection: pass dependencies as `__init__` params.
44
+ - Use `Protocol` classes to define dependency interfaces.
45
+ - Use factory functions to wire dependencies at application startup.
46
+ - Avoid global state and singletons. Use module-level instances if needed.
47
+
48
+ ## Anti-Patterns
49
+ - Mutable default arguments: use `None` and create inside function.
50
+ - Catching `Exception` broadly: masks bugs and interrupts.
51
+ - Using `type()` for type checking: use `isinstance()`.
52
+ - Nested try/except: flatten with early returns or separate functions.
53
+ - Using `global` keyword: pass state through parameters or classes.
@@ -0,0 +1,58 @@
1
+ ---
2
+ language: python
3
+ category: security
4
+ version: "1.0.0"
5
+ ---
6
+
7
+ # Python Security
8
+
9
+ ## Input Validation
10
+ - Validate all input with Pydantic models at API boundaries.
11
+ - Use `constr`, `conint`, `conlist` for constrained types.
12
+ - Never use `eval()`, `exec()`, or `compile()` with user input.
13
+ - Never use `pickle.loads()` on untrusted data (arbitrary code execution).
14
+
15
+ ## SQL Injection
16
+ - Use ORM query builders (SQLAlchemy, Django ORM) for all queries.
17
+ - For raw SQL, always use parameterized queries: `cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))`.
18
+ - Never use f-strings or `.format()` to build SQL queries.
19
+ - Use `text()` with `:param` syntax in SQLAlchemy raw queries.
20
+
21
+ ## SSTI (Server-Side Template Injection)
22
+ - Use Jinja2 with autoescaping enabled: `Environment(autoescape=True)`.
23
+ - Never render user input as a template string.
24
+ - Use `markupsafe.Markup` only for trusted HTML content.
25
+
26
+ ## Command Injection
27
+ - Never use `os.system()` or `subprocess.run(shell=True)` with user input.
28
+ - Use `subprocess.run()` with list arguments: `subprocess.run(["ls", "-la", path])`.
29
+ - Use `shlex.quote()` if shell=True is absolutely necessary.
30
+
31
+ ## Path Traversal
32
+ - Use `pathlib.Path.resolve()` and verify the result is within allowed directory.
33
+ - Never concatenate user input into file paths without validation.
34
+ - Use `os.path.commonpath()` to verify path containment.
35
+
36
+ ## Secrets
37
+ - Use `secrets` module for tokens: `secrets.token_urlsafe(32)`.
38
+ - Use `hashlib.scrypt` or `bcrypt` for password hashing.
39
+ - Use `hmac.compare_digest()` for constant-time secret comparison.
40
+ - Load secrets from environment: `os.environ["SECRET_KEY"]`, never hardcode.
41
+
42
+ ## Dependencies
43
+ - Run `pip-audit` or `safety check` in CI.
44
+ - Use `uv` or `pip-compile` for reproducible dependency resolution.
45
+ - Avoid installing packages with native extensions from untrusted sources.
46
+ - Pin all dependency versions. Review dependency updates carefully.
47
+
48
+ ## Deserialization
49
+ - Never deserialize untrusted data with `pickle`, `yaml.load()`, or `marshal`.
50
+ - Use `yaml.safe_load()` instead of `yaml.load()`.
51
+ - Use `json.loads()` for untrusted data (safe by default).
52
+ - Validate deserialized data with Pydantic before use.
53
+
54
+ ## Django-Specific
55
+ - Set `DEBUG = False` in production. Never expose debug pages.
56
+ - Use `django.utils.html.escape()` for manual HTML escaping.
57
+ - Use `CSRF_COOKIE_HTTPONLY = True` and `SESSION_COOKIE_SECURE = True`.
58
+ - Keep `SECRET_KEY` unique per environment and out of version control.