@mrciphersmith/keryx 0.4.28 → 0.4.30

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 (132) hide show
  1. package/dist/cli.js +4916 -3655
  2. package/dist/core.js +91 -28
  3. package/dist/keryx-general-worker-entry.js +413 -240
  4. package/package.json +1 -1
  5. package/src/gdskills/bundled/install-manifest.json +3 -0
  6. package/src/gdskills/bundled/rules/core/api-contracts.mdc +21 -136
  7. package/src/gdskills/bundled/rules/core/async-patterns.mdc +18 -171
  8. package/src/gdskills/bundled/rules/core/clean-architecture.mdc +40 -150
  9. package/src/gdskills/bundled/rules/core/cli-interface-design.mdc +63 -194
  10. package/src/gdskills/bundled/rules/core/code-style-patterns.mdc +36 -48
  11. package/src/gdskills/bundled/rules/core/concurrency-patterns.mdc +32 -0
  12. package/src/gdskills/bundled/rules/core/database-patterns.mdc +26 -148
  13. package/src/gdskills/bundled/rules/core/error-handling.mdc +57 -109
  14. package/src/gdskills/bundled/rules/core/frontend-assistant.mdc +14 -29
  15. package/src/gdskills/bundled/rules/core/layout-rendering.mdc +51 -0
  16. package/src/gdskills/bundled/rules/core/mobx-store-template.mdc +69 -511
  17. package/src/gdskills/bundled/rules/core/nestjs-dto.mdc +18 -36
  18. package/src/gdskills/bundled/rules/core/playwright-testing.mdc +35 -308
  19. package/src/gdskills/bundled/rules/core/security-baseline.mdc +18 -140
  20. package/src/gdskills/bundled/rules/core/skill-authoring.mdc +190 -0
  21. package/src/gdskills/bundled/rules/core/skills-storage-workflow.mdc +5 -0
  22. package/src/gdskills/bundled/rules/core/solid-principles.mdc +70 -121
  23. package/src/gdskills/bundled/rules/core/storybook-guidelines.mdc +20 -22
  24. package/src/gdskills/bundled/rules/core/tdd-workflow.mdc +37 -74
  25. package/src/gdskills/bundled/rules/core/ui-anti-slop.mdc +48 -37
  26. package/src/gdskills/bundled/skills/orchestration/task-implementer/SKILL.md +2 -2
  27. package/src/gdskills/bundled/skills/quality/deprecation-path/SKILL.md +1 -1
  28. package/src/gdskills/bundled/skills/quality/tests-creator/SKILL.md +1 -1
  29. package/src/gdskills/bundled/skills/review/review-architecture/SKILL.md +25 -61
  30. package/src/gdskills/bundled/skills/review/review-backend/SKILL.md +15 -69
  31. package/src/gdskills/bundled/skills/review/review-clean-code/SKILL.md +84 -418
  32. package/src/gdskills/bundled/skills/review/review-core-boundaries/SKILL.md +2 -2
  33. package/src/gdskills/bundled/skills/review/review-degradation/SKILL.md +1 -1
  34. package/src/gdskills/bundled/skills/review/review-flow-graph/SKILL.md +1 -1
  35. package/src/gdskills/bundled/skills/review/review-frontend/SKILL.md +17 -311
  36. package/src/gdskills/bundled/skills/review/review-frontend-conventions/SKILL.md +8 -22
  37. package/src/gdskills/bundled/skills/review/review-highload/SKILL.md +84 -228
  38. package/src/gdskills/bundled/skills/review/review-layout/SKILL.md +22 -28
  39. package/src/gdskills/bundled/skills/review/review-logic/SKILL.md +9 -10
  40. package/src/gdskills/bundled/skills/review/review-performance/SKILL.md +16 -38
  41. package/src/gdskills/bundled/skills/review/review-premise/SKILL.md +1 -1
  42. package/src/gdskills/bundled/skills/review/review-regression/SKILL.md +1 -1
  43. package/src/gdskills/bundled/skills/review/review-security-code/SKILL.md +8 -8
  44. package/src/gdskills/bundled/skills/review/review-style/SKILL.md +49 -88
  45. package/src/gdskills/bundled/skills/review/review-testing-practices/SKILL.md +22 -40
  46. package/src/gdskills/bundled/skills/review/review-ui-ux/SKILL.md +42 -82
  47. package/src/gdskills/bundled/stacks/angular/rules/coding-style.mdc +15 -57
  48. package/src/gdskills/bundled/stacks/angular/rules/patterns.mdc +16 -60
  49. package/src/gdskills/bundled/stacks/angular/rules/security.mdc +11 -49
  50. package/src/gdskills/bundled/stacks/angular/rules/testing.mdc +13 -52
  51. package/src/gdskills/bundled/stacks/c-cpp/rules/coding-style.mdc +33 -57
  52. package/src/gdskills/bundled/stacks/c-cpp/rules/patterns.mdc +35 -62
  53. package/src/gdskills/bundled/stacks/c-cpp/rules/security.mdc +35 -62
  54. package/src/gdskills/bundled/stacks/c-cpp/rules/testing.mdc +34 -54
  55. package/src/gdskills/bundled/stacks/ci-github-gitlab/rules/patterns.mdc +27 -56
  56. package/src/gdskills/bundled/stacks/ci-github-gitlab/rules/security.mdc +51 -119
  57. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/coding-style.mdc +42 -74
  58. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/patterns.mdc +45 -83
  59. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/security.mdc +34 -59
  60. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/testing.mdc +33 -62
  61. package/src/gdskills/bundled/stacks/django/rules/coding-style.mdc +15 -56
  62. package/src/gdskills/bundled/stacks/django/rules/patterns.mdc +16 -68
  63. package/src/gdskills/bundled/stacks/django/rules/security.mdc +13 -71
  64. package/src/gdskills/bundled/stacks/django/rules/testing.mdc +16 -62
  65. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/coding-style.mdc +30 -53
  66. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/patterns.mdc +20 -56
  67. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/security.mdc +52 -122
  68. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/testing.mdc +23 -42
  69. package/src/gdskills/bundled/stacks/fastapi/rules/coding-style.mdc +13 -47
  70. package/src/gdskills/bundled/stacks/fastapi/rules/patterns.mdc +18 -81
  71. package/src/gdskills/bundled/stacks/fastapi/rules/security.mdc +13 -75
  72. package/src/gdskills/bundled/stacks/fastapi/rules/testing.mdc +14 -58
  73. package/src/gdskills/bundled/stacks/flutter-dart/rules/coding-style.mdc +36 -74
  74. package/src/gdskills/bundled/stacks/flutter-dart/rules/patterns.mdc +30 -66
  75. package/src/gdskills/bundled/stacks/flutter-dart/rules/security.mdc +33 -67
  76. package/src/gdskills/bundled/stacks/flutter-dart/rules/testing.mdc +41 -73
  77. package/src/gdskills/bundled/stacks/go/rules/coding-style.mdc +36 -57
  78. package/src/gdskills/bundled/stacks/go/rules/patterns.mdc +27 -42
  79. package/src/gdskills/bundled/stacks/go/rules/security.mdc +26 -43
  80. package/src/gdskills/bundled/stacks/go/rules/testing.mdc +23 -41
  81. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/coding-style.mdc +21 -40
  82. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/patterns.mdc +26 -43
  83. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/security.mdc +25 -37
  84. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/testing.mdc +34 -50
  85. package/src/gdskills/bundled/stacks/kotlin-android/rules/coding-style.mdc +28 -65
  86. package/src/gdskills/bundled/stacks/kotlin-android/rules/patterns.mdc +34 -78
  87. package/src/gdskills/bundled/stacks/kotlin-android/rules/security.mdc +35 -68
  88. package/src/gdskills/bundled/stacks/kotlin-android/rules/testing.mdc +34 -68
  89. package/src/gdskills/bundled/stacks/mobx/rules/coding-style.mdc +18 -64
  90. package/src/gdskills/bundled/stacks/mobx/rules/patterns.mdc +13 -66
  91. package/src/gdskills/bundled/stacks/mobx/rules/security.mdc +8 -35
  92. package/src/gdskills/bundled/stacks/mobx/rules/testing.mdc +10 -39
  93. package/src/gdskills/bundled/stacks/nestjs/rules/coding-style.mdc +32 -45
  94. package/src/gdskills/bundled/stacks/nestjs/rules/patterns.mdc +40 -60
  95. package/src/gdskills/bundled/stacks/nestjs/rules/security.mdc +30 -50
  96. package/src/gdskills/bundled/stacks/nestjs/rules/testing.mdc +27 -47
  97. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/coding-style.mdc +14 -48
  98. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/patterns.mdc +15 -67
  99. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/security.mdc +12 -50
  100. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/testing.mdc +11 -43
  101. package/src/gdskills/bundled/stacks/php-laravel/rules/coding-style.mdc +17 -58
  102. package/src/gdskills/bundled/stacks/php-laravel/rules/patterns.mdc +15 -56
  103. package/src/gdskills/bundled/stacks/php-laravel/rules/security.mdc +13 -50
  104. package/src/gdskills/bundled/stacks/php-laravel/rules/testing.mdc +14 -55
  105. package/src/gdskills/bundled/stacks/python/rules/coding-style.mdc +13 -41
  106. package/src/gdskills/bundled/stacks/python/rules/patterns.mdc +20 -61
  107. package/src/gdskills/bundled/stacks/python/rules/security.mdc +15 -57
  108. package/src/gdskills/bundled/stacks/python/rules/testing.mdc +16 -50
  109. package/src/gdskills/bundled/stacks/react/rules/coding-style.mdc +14 -40
  110. package/src/gdskills/bundled/stacks/react/rules/patterns.mdc +15 -55
  111. package/src/gdskills/bundled/stacks/react/rules/security.mdc +13 -49
  112. package/src/gdskills/bundled/stacks/react/rules/testing.mdc +10 -37
  113. package/src/gdskills/bundled/stacks/ruby-rails/rules/coding-style.mdc +15 -48
  114. package/src/gdskills/bundled/stacks/ruby-rails/rules/patterns.mdc +18 -67
  115. package/src/gdskills/bundled/stacks/ruby-rails/rules/security.mdc +11 -60
  116. package/src/gdskills/bundled/stacks/ruby-rails/rules/testing.mdc +14 -65
  117. package/src/gdskills/bundled/stacks/rust/rules/coding-style.mdc +39 -65
  118. package/src/gdskills/bundled/stacks/rust/rules/patterns.mdc +33 -60
  119. package/src/gdskills/bundled/stacks/rust/rules/security.mdc +35 -57
  120. package/src/gdskills/bundled/stacks/rust/rules/testing.mdc +29 -52
  121. package/src/gdskills/bundled/stacks/sql-db/rules/coding-style.mdc +12 -48
  122. package/src/gdskills/bundled/stacks/sql-db/rules/patterns.mdc +22 -113
  123. package/src/gdskills/bundled/stacks/sql-db/rules/security.mdc +11 -56
  124. package/src/gdskills/bundled/stacks/sql-db/rules/testing.mdc +14 -59
  125. package/src/gdskills/bundled/stacks/swift-ios/rules/coding-style.mdc +29 -65
  126. package/src/gdskills/bundled/stacks/swift-ios/rules/patterns.mdc +41 -88
  127. package/src/gdskills/bundled/stacks/swift-ios/rules/security.mdc +28 -53
  128. package/src/gdskills/bundled/stacks/swift-ios/rules/testing.mdc +32 -65
  129. package/src/gdskills/bundled/stacks/vue/rules/coding-style.mdc +17 -52
  130. package/src/gdskills/bundled/stacks/vue/rules/patterns.mdc +17 -63
  131. package/src/gdskills/bundled/stacks/vue/rules/security.mdc +11 -41
  132. package/src/gdskills/bundled/stacks/vue/rules/testing.mdc +16 -48
@@ -7,80 +7,55 @@ metadata:
7
7
 
8
8
  # C#/.NET security
9
9
 
10
- Narrows `core-common-rules`' stack-agnostic security rules to
11
- C#/.NET-specific, OWASP-relevant risks and the safe framework API to use
12
- instead. Applies only to `*.cs` files.
10
+ Narrows `core-common-rules`' stack-agnostic security rules to C#/.NET-specific
11
+ risks (OWASP) and the safe framework API. Applies only to `*.cs` files.
13
12
 
14
13
  ## SQL and data access
15
14
 
16
- - Use parameterized queries for any SQL built from user-influenced
17
- input: `SqlCommand.Parameters.Add(...)`/`AddWithValue(...)` with `@`
18
- placeholders, or an ORM's parameterized query API (EF Core LINQ,
19
- Dapper's parameter objects) — never `string.Format`/interpolation/
20
- concatenation to build `CommandText` with a value that came from a
21
- caller. `$"SELECT * FROM Users WHERE Name = '{name}'"` is a SQL
22
- injection sink even when it "looks like" it is just formatting.
23
- - An ORM's raw-SQL escape hatch (EF Core's `FromSqlRaw`, Dapper's raw
24
- string execution) carries the same rule: pass user-influenced values
25
- as parameters, never interpolated directly into the raw SQL string.
26
- Prefer `FromSqlInterpolated`, which parameterizes `$"..."`
27
- interpolation holes automatically, over `FromSqlRaw` when the query
28
- needs any caller-supplied value at all.
15
+ - Parameterized queries for SQL from user-influenced input
16
+ (`SqlCommand.Parameters.Add(...)`/`AddWithValue(...)` with `@`
17
+ placeholders, EF Core LINQ, Dapper parameter objects); never
18
+ `string.Format`/interpolation/concatenation into `CommandText`.
19
+ - An ORM's raw-SQL escape hatch (`FromSqlRaw`, Dapper raw string execution)
20
+ takes user-influenced values as parameters; prefer `FromSqlInterpolated`
21
+ over `FromSqlRaw` when the query needs any caller-supplied value.
29
22
 
30
23
  ## Deserialization of untrusted data
31
24
 
32
- - Never use `BinaryFormatter` to deserialize data from any source you do
33
- not fully trust (or at all, on a current .NET version) — it is banned
34
- by Microsoft for security reasons because a crafted payload can
35
- execute arbitrary code during deserialization, and it is obsolete/
36
- removed on modern .NET.
37
- - Deserialize untrusted JSON with `System.Text.Json` using an explicit,
38
- known target type — avoid `TypeNameHandling`-style polymorphic
39
- deserialization from an untrusted source (whether via
40
- `Newtonsoft.Json`'s `TypeNameHandling.Auto`/`All` or a custom
41
- `$type`-driven resolver), which lets the payload itself choose what
42
- type gets constructed.
43
- - Validate/allowlist any type passed to `XmlSerializer`/`DataContractSerializer`
44
- from untrusted input the same way; do not resolve a type name found
45
- inside the untrusted payload without an allowlist.
25
+ - Never `BinaryFormatter` on data not fully trusted (or at all on a current
26
+ .NET version).
27
+ - Untrusted JSON through `System.Text.Json` with an explicit, known target
28
+ type; no `TypeNameHandling.Auto`/`All` (`Newtonsoft.Json`) or custom
29
+ `$type`-driven resolver.
30
+ - Allowlist any type passed to `XmlSerializer`/`DataContractSerializer` from
31
+ untrusted input; do not resolve a type name from the payload.
46
32
 
47
33
  ## Secrets and configuration
48
34
 
49
- - Never hard-code a connection string, API key, or signing secret in
50
- source or commit it in `appsettings.json` — use User Secrets
51
- (`dotnet user-secrets`) for local development and environment
52
- variables, Azure Key Vault, or another secret store the project has
53
- already standardized on for anything beyond local dev.
54
- - A connection string or secret read from `IConfiguration` should come
55
- from an environment-specific provider (environment variables, a
56
- secret manager), not a value checked into `appsettings.json` or
57
- `appsettings.Development.json` that happens to work.
35
+ - No hard-coded connection string, API key, or signing secret in source or
36
+ `appsettings.json`; User Secrets (`dotnet user-secrets`) for local
37
+ development, environment variables, Azure Key Vault, or the project's
38
+ standard secret store beyond that.
39
+ - A connection string or secret read from `IConfiguration` comes from an
40
+ environment-specific provider, not a value in `appsettings.json` or
41
+ `appsettings.Development.json`.
58
42
 
59
43
  ## Path and file handling
60
44
 
61
- - Never build a filesystem path for an untrusted, caller-supplied
62
- filename/segment with plain string concatenation and open it directly
63
- — validate the resulting path stays under the intended root (e.g.
64
- resolve with `Path.GetFullPath` and confirm it starts with the root's
65
- full path, or use an allowlist of known filenames) before calling
66
- `File.Open`/`File.ReadAllText`/etc.; `Path.Combine` alone does not stop
67
- a `..`-containing segment from climbing outside the intended
68
- directory.
45
+ - For an untrusted filename/segment, validate the resulting path stays under
46
+ the intended root (`Path.GetFullPath` and a root-prefix check, or a
47
+ filename allowlist) before `File.Open`/`File.ReadAllText`; `Path.Combine`
48
+ alone does not stop `..`.
69
49
 
70
50
  ## Web and transport (ASP.NET Core)
71
51
 
72
- - Never render user-influenced content into an HTML response outside of
73
- Razor's default auto-encoding (`Html.Raw`/`@Html.Raw` on
74
- caller-supplied content is an XSS vector) — let the framework's
75
- default encoding do its job unless the content is provably
76
- pre-sanitized.
52
+ - No `Html.Raw`/`@Html.Raw` on caller-supplied content outside Razor's
53
+ default auto-encoding unless provably pre-sanitized.
77
54
  - Never disable TLS certificate validation
78
55
  (`ServerCertificateCustomValidationCallback` returning `true`
79
- unconditionally, or `HttpClientHandler.ServerCertificateCustomValidationCallback`
80
- bypassing validation) outside a short-lived local test, and never ship
81
- it that way.
82
- - Use the framework's built-in antiforgery support
83
- (`[ValidateAntiForgeryToken]`/`IAntiforgery`) for any state-changing
84
- endpoint reachable from a browser session, and rely on ASP.NET Core
56
+ unconditionally, including on `HttpClientHandler`) outside a short-lived
57
+ local test, never shipped.
58
+ - Built-in antiforgery (`[ValidateAntiForgeryToken]`/`IAntiforgery`) for any
59
+ state-changing endpoint reachable from a browser session; ASP.NET Core
85
60
  Identity/`PasswordHasher<TUser>` (or an equivalent vetted library) for
86
- password hashing — never a custom hash/roll-your-own scheme.
61
+ password hashing, never a custom scheme.
@@ -13,77 +13,48 @@ convention and disciplined mocking with Moq/NSubstitute. Applies only to
13
13
 
14
14
  ## Framework and layout
15
15
 
16
- - Match whichever test framework the project already uses (xUnit or
17
- NUnit are both common; do not introduce a second one into a project
18
- that has standardized on the other). xUnit: `[Fact]` for a single
19
- case, `[Theory]` + `[InlineData(...)]`/`[MemberData(...)]` for
20
- parameterized cases. NUnit: `[Test]` and `[TestCase(...)]` play the
21
- same roles.
22
- - Tests live in a mirrored `*.Tests`/`*.Test` project (the standard .NET
23
- convention: `Orders/` production code, `Orders.Tests/` its tests), not
24
- inside the production project itself.
25
- - Name a test method for behavior, not implementation:
26
- `MethodName_Scenario_ExpectedResult`
27
- (`Validate_MissingOrderId_ThrowsArgumentException`) reads as a
28
- specification; `Test1`/`ValidateTest` does not.
16
+ - Match the project's test framework (xUnit or NUnit); do not add a second.
17
+ xUnit: `[Fact]`, `[Theory]` + `[InlineData(...)]`/`[MemberData(...)]`.
18
+ NUnit: `[Test]`, `[TestCase(...)]`.
19
+ - Tests live in a mirrored `*.Tests`/`*.Test` project (`Orders/` and
20
+ `Orders.Tests/`), not inside the production project.
21
+ - Name a test `MethodName_Scenario_ExpectedResult`
22
+ (`Validate_MissingOrderId_ThrowsArgumentException`).
29
23
 
30
24
  ## Table-driven (`Theory`/`TestCase`) tests
31
25
 
32
- - Use `[Theory]` + `[InlineData(...)]` (xUnit) or `[TestCase(...)]`
33
- (NUnit) for a set of cases that exercise the same method with
34
- different inputs/expected outputs, instead of copy-pasting a near-
35
- identical `[Fact]`/`[Test]` per case — each data row becomes its own
36
- reported test result, so a failure names exactly which input failed.
37
- - Reach for `[MemberData(nameof(Cases))]`/a `TestCaseSource` when a case
38
- needs a non-primitive value (an object, a collection) that attribute
39
- arguments cannot express directly.
26
+ - `[Theory]` + `[InlineData(...)]` (xUnit) or `[TestCase(...)]` (NUnit) for
27
+ cases on the same method, not a copy-pasted `[Fact]`/`[Test]` per case.
28
+ - `[MemberData(nameof(Cases))]`/`TestCaseSource` for non-primitive case
29
+ values.
40
30
 
41
31
  ## Async tests
42
32
 
43
- - A test that exercises `async` production code is itself `async Task`
44
- (`public async Task Validate_ValidOrder_ReturnsSuccess()`), and awaits
45
- the call under test — never `async void` (the test runner cannot await
46
- it, and any assertion failure or exception inside it is lost instead
47
- of failing the test) and never a blocking `.Result`/`.Wait()` on the
48
- Task under test as a substitute for `await`.
33
+ - A test of `async` code is `async Task` and awaits the call under test;
34
+ never `async void`, never a blocking `.Result`/`.Wait()`.
49
35
 
50
36
  ## Mocking boundaries: mock the seam, not the internals
51
37
 
52
- - Mock/stub an **external dependency the unit under test talks to
53
- through an interface** — an `HttpClient`-backed API client behind an
54
- interface, a repository interface wrapping the database, a clock/time
55
- provider, a message publisher — using Moq (`Mock<IThing>`) or
56
- NSubstitute (`Substitute.For<IThing>()`).
57
- - Do **not** mock an internal collaborator that is itself part of what
58
- the test is supposed to verify — a private helper method, a concrete
59
- value object, a piece of the same class's own logic split into another
60
- method for readability. Mocking one layer too deep proves only that
61
- the mock returns what you told it to, not that the unit under test
62
- actually behaves correctly; it also makes the test brittle to harmless
63
- internal refactors that change nothing about observable behavior.
64
- - The question to ask before adding a mock: "does the real system cross
65
- a process/network/disk boundary here (HTTP, database, filesystem,
66
- clock, random), or am I mocking a class my own code owns and could
67
- just construct for real?" Only the former earns a mock.
68
- - Verify a mock's interaction (`mock.Verify(...)`/
69
- `receivedCall.Received()`) only for a call whose occurrence is itself
70
- part of the contract being tested (e.g. "an email is sent exactly
71
- once") — do not add interaction verification for calls that are
72
- incidental implementation detail, which locks the test to today's
73
- internal wiring.
38
+ - Mock/stub an external dependency the unit talks to through an interface
39
+ (an `HttpClient`-backed client, a repository interface, a clock, a message
40
+ publisher) with Moq (`Mock<IThing>`) or NSubstitute
41
+ (`Substitute.For<IThing>()`).
42
+ - Do not mock an internal collaborator that is part of what the test
43
+ verifies (a private helper, a concrete value object, the class's own logic
44
+ split into another method).
45
+ - Before adding a mock, check whether the real system crosses a
46
+ process/network/disk boundary there (HTTP, database, filesystem, clock,
47
+ random); only that earns a mock, not a class your own code owns.
48
+ - Verify a mock's interaction (`mock.Verify(...)`/`receivedCall.Received()`)
49
+ only for a call that is itself part of the contract ("an email is sent
50
+ exactly once"), not incidental implementation detail.
74
51
 
75
52
  ## Assertions and determinism
76
53
 
77
- - Use the project's already-adopted assertion style (xUnit's built-in
78
- `Assert`, or FluentAssertions if already a dependency) — do not
79
- introduce a second assertion library into a project that has
80
- standardized on one.
81
- - Never synchronize with `Thread.Sleep`/`Task.Delay` to wait for an
82
- async operation or background work to finish — await the actual
83
- `Task`, or use a real synchronization primitive
84
- (`TaskCompletionSource`, a cancellation-bounded wait) so the test is
85
- deterministic and not flaky under load.
86
- - Reset/dispose any shared test fixture (`IClassFixture<T>`, a
87
- `WebApplicationFactory<TEntryPoint>` for integration tests) between
88
- cases that mutate shared state, so one test's leftovers cannot change
89
- another's result depending on run order.
54
+ - The project's adopted assertion style (xUnit `Assert`, or FluentAssertions
55
+ if already a dependency); do not add a second library.
56
+ - Never `Thread.Sleep`/`Task.Delay` to wait for async work; await the
57
+ `Task`, or use `TaskCompletionSource` or a cancellation-bounded wait.
58
+ - Reset/dispose a shared fixture (`IClassFixture<T>`,
59
+ `WebApplicationFactory<TEntryPoint>`) between cases that mutate shared
60
+ state.
@@ -7,74 +7,33 @@ metadata:
7
7
 
8
8
  # Django coding style
9
9
 
10
- Narrows `python`'s coding style to Django-project conventions. Applies to
11
- `*.py` files inside a Django project; non-Django Python in the same
12
- repository (a standalone script, a shared library package with no Django
13
- import) still comes from `python`'s own coding-style rule, not this file.
10
+ Narrows `python`'s coding style to Django conventions. Applies to `*.py` files inside a Django project; non-Django Python in the same repository follows `python`'s coding-style rule.
14
11
 
15
12
  ## App and project layout
16
13
 
17
- - One Django "app" per cohesive domain concern (`billing/`, `accounts/`),
18
- each with its own `models.py`/`views.py`/`urls.py`/`migrations/` — do not
19
- grow a single app into an unrelated dumping ground once it outgrows one
20
- clear responsibility.
21
- - Name an app's `urls.py` route names with the app as a namespace prefix
22
- (`billing:invoice-detail`) and reverse them with `reverse()`/`{% url %}`,
23
- never a hand-built path string, so a route can move without breaking every
24
- caller.
25
- - Keep `settings.py` split by environment (`settings/base.py` +
26
- `dev.py`/`prod.py`, or `django-environ`/`django-configurations`) when the
27
- project already uses that layout; match the existing convention rather
28
- than introducing a second settings-splitting scheme.
14
+ - One Django app per cohesive domain concern, each with its own `models.py`/`views.py`/`urls.py`/`migrations/`.
15
+ - Prefix route names with the app namespace (`billing:invoice-detail`) and reverse them with `reverse()`/`{% url %}`, never a hand-built path string.
16
+ - Split `settings.py` by environment only when the project already does; match the existing scheme.
29
17
 
30
18
  ## Models
31
19
 
32
- - Give every model field an explicit `verbose_name`/`help_text` when the
33
- field name alone would not be self-explanatory to someone using the admin
34
- or a generated form.
35
- - Use `related_name` on a `ForeignKey`/`ManyToManyField`/`OneToOneField`
36
- whenever the default (`<model>_set`) would collide or read unclearly at
37
- the call site; pick a name that reads naturally from the related side
38
- (`author.books`, not `author.book_set`).
39
- - Put field-level defaults and choices near the field (`choices=Status.choices`
40
- with a `TextChoices`/`IntegerChoices` enum), not a bare tuple of literal
41
- strings repeated at each call site.
42
- - Override `save()`/add a `clean()` only for invariants that must hold for
43
- every write path (including the admin and shell); a validation rule that
44
- only applies to one form belongs on that `Form`, not the model.
20
+ - Give a model field an explicit `verbose_name`/`help_text` when the name alone is not self-explanatory in the admin or a generated form.
21
+ - Use `related_name` when the default `<model>_set` would collide or read unclearly; name it from the related side (`author.books`).
22
+ - Use `choices=Status.choices` with a `TextChoices`/`IntegerChoices` enum, not a bare tuple of literals repeated per call site.
23
+ - Override `save()`/add `clean()` only for invariants that hold for every write path; a rule for one form belongs on that `Form`.
45
24
 
46
25
  ## Views and URLs
47
26
 
48
- - Prefer a class-based view (`ListView`, `DetailView`, `CreateView`, or a
49
- DRF `APIView`/`ViewSet` when the project uses Django REST Framework) for
50
- the framework's standard CRUD shapes; reach for a function-based view when
51
- the logic does not map cleanly onto a generic view's hooks — current
52
- Django guidance treats CBVs and FBVs as equally supported, not one as
53
- deprecated.
54
- - Keep business logic out of the view body: a view coordinates
55
- request/response and delegates the actual work to a model method, a form's
56
- `clean`/`save`, or a service function — a view that inlines several
57
- unrelated queries and branches is a sign the logic belongs elsewhere.
58
- - Name URL patterns and match the project's existing `path()`/`re_path()`
59
- convention; prefer `path()` with converters (`<int:pk>`) over `re_path()`
60
- unless the match genuinely needs a regex.
27
+ - Prefer a class-based view (`ListView`, `DetailView`, `CreateView`, or a DRF `APIView`/`ViewSet`) for standard CRUD shapes; use a function-based view when the logic does not map onto a generic view's hooks. Neither is deprecated.
28
+ - Keep business logic out of the view body; delegate to a model method, a form's `clean`/`save`, or a service function.
29
+ - Prefer `path()` with converters (`<int:pk>`) over `re_path()` unless the match needs a regex; match the project's existing convention.
61
30
 
62
31
  ## Forms and serializers
63
32
 
64
- - Validate with a `Form`/`ModelForm` (or DRF `Serializer`/`ModelSerializer`)
65
- `clean_<field>`/`clean()`/`validate_<field>`/`validate()` method, not
66
- ad-hoc validation scattered in the view after the fact.
67
- - Use `ModelForm`/`ModelSerializer` with an explicit `fields = [...]` list
68
- (never `fields = "__all__"` on a form or serializer that accepts
69
- user-submitted data) so a new model field is not silently exposed for
70
- mass-assignment until it is deliberately added.
33
+ - Validate in a `Form`/`ModelForm` (or DRF `Serializer`/`ModelSerializer`) `clean_<field>`/`clean()`/`validate_<field>`/`validate()` method, not ad hoc in the view.
34
+ - Use an explicit `fields = [...]` list, never `fields = "__all__"`, on a form or serializer that accepts user-submitted data.
71
35
 
72
36
  ## Imports and structure
73
37
 
74
- - Follow `python`'s stdlib/third-party/local import grouping; within
75
- "third-party", Django's own imports (`django.db`, `django.http`, ...)
76
- commonly sort before other third-party packages alphabetically — match
77
- what the project's `ruff`/`isort` config already produces rather than
78
- hand-ordering.
79
- - Import from `django.conf.settings`, never re-read environment variables
80
- directly in application code that already has a settings value for it.
38
+ - Follow `python`'s import grouping; match the order the project's `ruff`/`isort` config produces rather than hand-ordering.
39
+ - Import from `django.conf.settings`; do not re-read environment variables in application code that has a settings value.
@@ -7,86 +7,34 @@ metadata:
7
7
 
8
8
  # Django patterns
9
9
 
10
- Narrows `python`'s design guidance to idiomatic Django (5.x) ORM, view, and
11
- migration patterns and the anti-patterns they replace. Applies to Django
12
- project files; a non-Django module in the same repo still follows `python`'s
13
- own `rules/patterns.mdc`.
10
+ Narrows `python`'s design guidance to idiomatic Django (5.x) ORM, view and migration patterns. Applies to Django project files; a non-Django module follows `python`'s `rules/patterns.mdc`.
14
11
 
15
12
  ## Query optimization (the N+1 problem)
16
13
 
17
- - When a view or serializer will access a related object for every row in a
18
- queryset (`obj.author.name` in a loop, or a DRF nested serializer field),
19
- add `select_related("author")` for a `ForeignKey`/`OneToOneField` and
20
- `prefetch_related("tags")` for a `ManyToManyField`/reverse `ForeignKey` —
21
- `select_related` joins in one query; `prefetch_related` issues one extra
22
- query per relation and joins in Python. Combine both when a
23
- `prefetch_related` path itself needs a `select_related` (`Prefetch("best_pizza__toppings")`
24
- after `select_related("best_pizza")`).
25
- - Use `only()`/`defer()` to trim columns from a wide model only when a
26
- profiled query shows the extra columns matter; reaching for it by default
27
- makes the queryset fragile to a later field access that silently triggers
28
- a new query.
29
- - Prefer `QuerySet.exists()` over `bool(qs)`/`len(qs) > 0` for an
30
- existence check, and `.count()` over `len(list(qs))`, so the database does
31
- the work instead of materializing every row into Python.
32
- - Use `bulk_create`/`bulk_update`/`update()` for a batch write instead of a
33
- Python loop calling `.save()` per instance — a per-instance loop is an N+1
34
- on the write side, and skips `bulk_create`'s single round trip (note it
35
- bypasses `save()`/signals unless explicitly configured to call them).
14
+ - When a view or serializer accesses a related object per row, add `select_related("author")` for a `ForeignKey`/`OneToOneField` and `prefetch_related("tags")` for a `ManyToManyField`/reverse `ForeignKey`; combine them with `Prefetch("best_pizza__toppings")` after `select_related("best_pizza")` when a prefetch path needs a join.
15
+ - Use `only()`/`defer()` only when a profiled query shows the extra columns matter.
16
+ - Prefer `QuerySet.exists()` over `bool(qs)`/`len(qs) > 0`, and `.count()` over `len(list(qs))`.
17
+ - Use `bulk_create`/`bulk_update`/`update()` for batch writes, not a per-instance `.save()` loop; `bulk_create` bypasses `save()`/signals.
36
18
 
37
19
  ## Migrations
38
20
 
39
- - Run `python manage.py makemigrations` to generate a migration from a model
40
- change; never hand-write a migration's `operations` list to match a model
41
- edit by guesswork — let Django diff the models, then review the generated
42
- file.
43
- - Give a migration that needs to transform existing row data a `RunPython`
44
- operation with both a forward and a reverse function (or
45
- `migrations.RunPython.noop` when reversal is genuinely not meaningful),
46
- not a schema-only migration that silently leaves old data inconsistent
47
- with a new constraint.
48
- - Keep a destructive migration (dropping a column/table another release
49
- still reads) behind a deploy sequence that ships the code change first,
50
- then the schema change, when the project deploys code and migrations
51
- separately — a same-release drop-and-read is a two-phase problem, not a
52
- one-step migration.
53
- - Never edit a migration file that has already been applied in another
54
- environment (shared branch, staging, production) to "fix" it in place;
55
- add a new migration instead — editing history desyncs any environment
56
- that already recorded the old migration as applied.
21
+ - Generate migrations with `python manage.py makemigrations`; never hand-write `operations` to match a model edit.
22
+ - A migration that transforms existing row data uses `RunPython` with a forward and a reverse function (or `migrations.RunPython.noop` when reversal is not meaningful).
23
+ - Ship the code change first, then the destructive schema change (dropping a column/table another release still reads), when code and migrations deploy separately.
24
+ - Never edit a migration already applied in another environment; add a new one.
57
25
 
58
26
  ## Models as the single source of truth
59
27
 
60
- - Put a field-level invariant (a `CheckConstraint`, a `unique_together`/
61
- `UniqueConstraint`, a `validators=[...]` list) on the model field or
62
- `Meta.constraints`, not only in a form's `clean()` — validation the
63
- database itself does not enforce can still be violated by a direct
64
- `.save()`, the admin, a shell, or another service writing to the same
65
- table.
66
- - Use a model `Manager`/`QuerySet` subclass to name a repeated filter
67
- (`Order.objects.pending()`) instead of repeating the same `.filter(...)`
68
- chain at every call site.
28
+ - Put a field-level invariant (`CheckConstraint`, `unique_together`/`UniqueConstraint`, `validators=[...]`) on the field or `Meta.constraints`, not only in a form's `clean()`.
29
+ - Name a repeated filter with a model `Manager`/`QuerySet` subclass (`Order.objects.pending()`).
69
30
 
70
31
  ## Views
71
32
 
72
- - A view that only reads and renders/serializes belongs on a generic
73
- class-based view (`ListView`/`DetailView`/DRF `ReadOnlyModelViewSet`); a
74
- view with custom branching logic per HTTP method is a legitimate reason to
75
- drop to a function-based view or override a specific CBV method
76
- (`get_queryset`, `form_valid`) rather than reimplementing the whole
77
- request/response cycle.
78
- - Return the framework's own response helpers (`HttpResponseRedirect`/
79
- `redirect()`, `JsonResponse`, DRF's `Response`) instead of building a raw
80
- `HttpResponse` with a hand-set `Content-Type` and manually serialized body.
33
+ - A read-and-render view belongs on a generic class-based view (`ListView`/`DetailView`/DRF `ReadOnlyModelViewSet`); for per-method branching, drop to a function-based view or override a specific CBV method (`get_queryset`, `form_valid`).
34
+ - Return the framework's response helpers (`redirect()`, `JsonResponse`, DRF `Response`), not a raw `HttpResponse` with a hand-set `Content-Type`.
81
35
 
82
36
  ## Anti-patterns to flag, not introduce
83
37
 
84
- - A `for` loop over a queryset that touches a related object per iteration
85
- with no `select_related`/`prefetch_related` upstream — this is Django's
86
- most common performance bug and is invisible in a small dev dataset.
87
- - `fields = "__all__"` on a `ModelForm`/`ModelSerializer` that accepts
88
- user input, silently exposing every future field for mass-assignment.
89
- - A signal handler (`post_save`, etc.) that performs a slow or
90
- externally-visible side effect (sending an email, calling a third-party
91
- API) synchronously inside the request/response cycle instead of queuing it
92
- through the project's async task runner (Celery or equivalent).
38
+ - A `for` loop over a queryset that touches a related object per iteration with no upstream `select_related`/`prefetch_related`.
39
+ - `fields = "__all__"` on a `ModelForm`/`ModelSerializer` that accepts user input.
40
+ - A signal handler (`post_save`, etc.) doing a slow or externally-visible side effect (email, third-party API) synchronously instead of queuing it through the project's task runner (Celery or equivalent).
@@ -7,86 +7,28 @@ metadata:
7
7
 
8
8
  # Django security
9
9
 
10
- Narrows `python`'s security guidance to Django's own injection-class sinks:
11
- views, forms/serializers, template-tag modules, and settings — the Python
12
- files where Django's built-in CSRF/XSS/SQL-injection protections are either
13
- relied on or bypassed (template-rendered `.html` files are not `.py`, so
14
- they are out of this rule's `paths:` scope by construction, even though the
15
- XSS guidance below still applies to what those views/templatetags render
16
- into them). Applies only to the listed `.py` files; a non-request-facing
17
- module (a standalone script, a batch job with no HTTP surface) still
18
- follows `python`'s own `rules/security.mdc`.
10
+ Narrows `python`'s security guidance to Django's injection-class sinks: views, forms/serializers, template-tag modules and settings. Applies only to the listed `.py` files; a non-request-facing module follows `python`'s `rules/security.mdc`.
19
11
 
20
12
  ## CSRF
21
13
 
22
- - Leave `django.middleware.csrf.CsrfViewMiddleware` enabled and let
23
- `{% csrf_token %}`/the framework's CSRF cookie handling do its job for
24
- every state-changing view (`POST`/`PUT`/`PATCH`/`DELETE`).
25
- - Never add `@csrf_exempt` to make a failing request succeed without first
26
- establishing that the endpoint has another, equivalent protection (a
27
- signed webhook signature, a non-browser API authenticated by token, never
28
- session/cookie auth) — CSRF exemption on a session-authenticated endpoint
29
- reopens the exact attack the middleware exists to block.
30
- - A DRF `APIView`/`ViewSet` using `SessionAuthentication` still needs CSRF
31
- protection on unsafe methods (DRF enforces this by default for session
32
- auth); do not disable it to work around a client that isn't sending the
33
- token — fix the client to send it.
14
+ - Leave `django.middleware.csrf.CsrfViewMiddleware` enabled for every state-changing view.
15
+ - Never add `@csrf_exempt` to make a request succeed unless the endpoint has an equivalent protection (a signed webhook signature, or a non-browser API authenticated by token, never session/cookie auth).
16
+ - A DRF view using `SessionAuthentication` keeps CSRF protection on unsafe methods; fix the client to send the token.
34
17
 
35
18
  ## Cross-site scripting (XSS)
36
19
 
37
- - Rely on Django's automatic template auto-escaping for any value that
38
- reaches an HTML template — do not disable it project-wide.
39
- - Never apply `mark_safe()`/the `|safe` template filter/`format_html()`'s
40
- raw-string argument to a value that traces back to user input (a form
41
- field, a query parameter, an uploaded file's name, anything stored from a
42
- prior user submission) — `mark_safe`/`|safe` tell Django to skip escaping
43
- entirely, and reintroduce stored or reflected XSS on exactly the value the
44
- auto-escaper was protecting. `mark_safe`/`|safe` are for markup the
45
- application itself constructs and fully controls (a trusted CMS field
46
- rendered through a sanitizer, static admin-authored HTML) — never for
47
- data supplied by a request.
48
- - Build dynamically-assembled HTML with `format_html()`/`format_html_join()`
49
- (which escape each interpolated argument) instead of string
50
- concatenation or an f-string passed to `mark_safe()`.
20
+ - Keep Django's template auto-escaping on; do not disable it project-wide.
21
+ - Never apply `mark_safe()`/`|safe`/`format_html()`'s raw-string argument to a value that traces back to user input; reserve them for markup the application constructs and fully controls (e.g. a trusted CMS field rendered through a sanitizer).
22
+ - Build dynamic HTML with `format_html()`/`format_html_join()`, not concatenation or an f-string passed to `mark_safe()`.
51
23
 
52
24
  ## SQL injection
53
25
 
54
- - Django's ORM parameterizes query values automatically
55
- (`.filter(name=user_input)`); this protection does not extend to
56
- `.raw()` or `.extra()` — pass user-derived values through the `params`
57
- argument (`Model.objects.raw("... WHERE id = %s", [id])`), never by
58
- interpolating them into the SQL string with an f-string/`%`/`.format()`.
59
- - Treat `.extra()` as legacy; prefer expressing the same query with the ORM
60
- (`annotate`, `F()`, `Q()`, `Func`) or a parameterized `.raw()` call — the
61
- Django security team explicitly does not treat unsanitized input reaching
62
- `.extra()`'s `select`/`where` clauses as a framework bug, because
63
- `.extra()` was never given the ORM's own escaping.
26
+ - Pass user-derived values to `.raw()` through `params` (`Model.objects.raw("... WHERE id = %s", [id])`), never via f-string/`%`/`.format()`.
27
+ - Treat `.extra()` as legacy; prefer `annotate`, `F()`, `Q()`, `Func` or a parameterized `.raw()` call.
64
28
 
65
29
  ## Settings and secrets
66
30
 
67
- - `SECRET_KEY` must be at least 50 characters, unique per environment, never
68
- the `django-insecure-` placeholder `startproject` generates, and never
69
- committed to source — read it from the environment/secret store.
70
- - `DEBUG` must be `False` in any settings module used in production;
71
- `DEBUG = True` leaks stack traces, local variable values, and settings
72
- contents to any visitor who triggers an unhandled exception.
73
- - `ALLOWED_HOSTS` must be a real, non-empty list of the application's actual
74
- hostnames in production, never `["*"]` — an empty or wildcard value
75
- defeats the Host-header validation Django's deploy checks exist to
76
- enforce.
77
- - Run `python manage.py check --deploy` before a production release; it
78
- flags exactly these three (and related HSTS/secure-cookie) settings
79
- automatically — don't hand-audit `settings.py` for them instead.
80
-
81
- ## Red flags
82
-
83
- - "I'll add `|safe` here, this content only ever comes from an admin form" —
84
- if that admin form field can ever hold end-user-influenced text (a
85
- support agent pasting a customer's message, a bio field editable by the
86
- account owner), the trust boundary already includes untrusted input.
87
- - "`.extra()` with an f-string is fine, this value is just an internal ID"
88
- — an "internal" ID that ever originates from a URL param, form field, or
89
- header is user-controlled regardless of how it's described; use `params`.
90
- - "`@csrf_exempt` unblocks this POST and the tests pass now" — passing
91
- tests after exempting CSRF proves the exemption works, not that it's
92
- safe; verify the endpoint has an equivalent protection first.
31
+ - `SECRET_KEY`: at least 50 characters, unique per environment, never the `django-insecure-` placeholder, never committed; read it from the environment/secret store.
32
+ - `DEBUG` is `False` in any settings module used in production.
33
+ - `ALLOWED_HOSTS` is a non-empty list of the real hostnames in production, never `["*"]`.
34
+ - Run `python manage.py check --deploy` before a production release.