okstra 0.231.0 → 0.232.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 (143) hide show
  1. package/README.md +15 -3
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/memory/memory.mjs +9 -55
  5. package/dist/commands/memory/memory.mjs.map +1 -1
  6. package/dist/lib/memory-auto-register.d.mts +1 -0
  7. package/dist/lib/memory-auto-register.mjs +113 -0
  8. package/dist/lib/memory-auto-register.mjs.map +1 -0
  9. package/dist/lib/memory-entry-contract.d.mts +12 -0
  10. package/dist/lib/memory-entry-contract.mjs +46 -0
  11. package/dist/lib/memory-entry-contract.mjs.map +1 -0
  12. package/dist/lib/python-helper.d.mts +1 -1
  13. package/dist/lib/python-helper.mjs +3 -2
  14. package/dist/lib/python-helper.mjs.map +1 -1
  15. package/dist/lib/record-secrets.d.mts +1 -0
  16. package/dist/lib/record-secrets.mjs +28 -0
  17. package/dist/lib/record-secrets.mjs.map +1 -0
  18. package/dist/lib/types.d.mts +2 -1
  19. package/docs/architecture/storage-model.md +129 -2
  20. package/docs/architecture.md +11 -2
  21. package/docs/cli.md +234 -0
  22. package/docs/project-structure-overview.md +2 -1
  23. package/package.json +1 -1
  24. package/runtime/BUILD.json +2 -2
  25. package/runtime/agents/common.json +8 -8
  26. package/runtime/agents/roles/verifier.json +2 -4
  27. package/runtime/bin/okstra-provider-exec.py +10 -4
  28. package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
  29. package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
  30. package/runtime/prompts/coding-preflight/clean-code.md +85 -281
  31. package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
  32. package/runtime/prompts/coding-preflight/languages/java.md +3 -5
  33. package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
  34. package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
  35. package/runtime/prompts/coding-preflight/languages/python.md +2 -7
  36. package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
  37. package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
  38. package/runtime/prompts/coding-preflight/overview.md +25 -38
  39. package/runtime/prompts/coding-preflight/review-rules.json +30 -0
  40. package/runtime/prompts/duties/code-reviewer.json +15 -18
  41. package/runtime/prompts/duties/implementation-verifier.json +1 -0
  42. package/runtime/prompts/lead/convergence.md +3 -3
  43. package/runtime/prompts/lead/okstra-lead-contract.md +2 -2
  44. package/runtime/prompts/lead/report-writer.md +1 -1
  45. package/runtime/prompts/lead/team-contract.md +1 -1
  46. package/runtime/prompts/profiles/_clarification-recommendation.md +3 -2
  47. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  48. package/runtime/python/okstra_ctl/agent/invocation.py +121 -36
  49. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +6 -0
  50. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +30 -4
  51. package/runtime/python/okstra_ctl/agent/standalone.py +3 -0
  52. package/runtime/python/okstra_ctl/analysis_packet.py +2 -19
  53. package/runtime/python/okstra_ctl/approval_decisions.py +16 -0
  54. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  55. package/runtime/python/okstra_ctl/business_flow/invocation.py +35 -3
  56. package/runtime/python/okstra_ctl/code_review_census.py +71 -7
  57. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  58. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  59. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  60. package/runtime/python/okstra_ctl/code_review_scope.py +36 -9
  61. package/runtime/python/okstra_ctl/code_review_target.py +85 -11
  62. package/runtime/python/okstra_ctl/consumers.py +12 -9
  63. package/runtime/python/okstra_ctl/convergence.py +112 -20
  64. package/runtime/python/okstra_ctl/convergence_engine.py +1 -0
  65. package/runtime/python/okstra_ctl/convergence_provenance.py +27 -11
  66. package/runtime/python/okstra_ctl/correction_round.py +6 -1
  67. package/runtime/python/okstra_ctl/design_review.py +207 -0
  68. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  69. package/runtime/python/okstra_ctl/dispatch_checkpoints.py +28 -5
  70. package/runtime/python/okstra_ctl/dispatch_core.py +3 -11
  71. package/runtime/python/okstra_ctl/doctor.py +8 -25
  72. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  73. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  74. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  75. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  76. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  77. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  78. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  79. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  80. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  81. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  82. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  83. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +261 -0
  84. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  85. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  86. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  87. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  88. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  89. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  90. package/runtime/python/okstra_ctl/json_boundary.py +21 -2
  91. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  92. package/runtime/python/okstra_ctl/manager_cli.py +26 -0
  93. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  94. package/runtime/python/okstra_ctl/manager_sync.py +3 -22
  95. package/runtime/python/okstra_ctl/model_io/renderers.py +13 -2
  96. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  97. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  98. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +12 -2
  99. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +19 -6
  100. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +5 -3
  101. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +39 -11
  102. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  103. package/runtime/python/okstra_ctl/phases/implementation/spec.md +26 -1
  104. package/runtime/python/okstra_ctl/phases/implementation/validation.py +86 -2
  105. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +4 -0
  106. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  107. package/runtime/python/okstra_ctl/report_assembly.py +15 -0
  108. package/runtime/python/okstra_ctl/report_narrative.py +3 -0
  109. package/runtime/python/okstra_ctl/report_prose_keys.py +7 -0
  110. package/runtime/python/okstra_ctl/report_synthesis_packet.py +19 -2
  111. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  112. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  113. package/runtime/python/okstra_ctl/run.py +24 -1
  114. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  115. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  116. package/runtime/python/okstra_ctl/team.py +3 -1
  117. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  118. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  119. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  120. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  121. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  122. package/runtime/python/okstra_ctl/worker_dispatch.py +3 -1
  123. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  124. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  125. package/runtime/python/okstra_ctl/wrapper_status.py +16 -0
  126. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  127. package/runtime/python/okstra_project/__init__.py +2 -0
  128. package/runtime/python/okstra_project/dirs.py +18 -0
  129. package/runtime/python/okstra_project/state.py +25 -20
  130. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  131. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  132. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  133. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  134. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  135. package/runtime/schemas/record-secret-patterns.json +41 -0
  136. package/runtime/skills/okstra-code-review/SKILL.md +71 -123
  137. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  138. package/runtime/skills/okstra-code-review/references/review-calibration.md +34 -54
  139. package/runtime/skills/okstra-manager/SKILL.md +7 -0
  140. package/runtime/skills/okstra-memory/SKILL.md +7 -0
  141. package/runtime/templates/implementation-worker-preamble.md +4 -9
  142. package/runtime/templates/worker-prompt-preamble.md +4 -12
  143. package/runtime/validators/validate-run.py +17 -8
@@ -1,47 +1,33 @@
1
1
  # Clean Code Principles (language-agnostic)
2
2
 
3
- Apply these on every change. They override personal taste. They do **not** override project-local rules.
3
+ Apply these on every change using the policy precedence in `overview.md`: explicit repository instructions and declared architecture, this common resource pack, then surrounding code conventions. Personal preference and existing violations do not waive an applicable rule.
4
4
 
5
- ## DRY — Don't Repeat Yourself
6
-
7
- A second copy of the same logic is a signal to extract. Two callers of the same algorithm should call the same function.
5
+ ## Five simultaneous quality outcomes
8
6
 
9
- Bad:
10
- ```javascript
11
- let total = 0;
12
- for (let i = 0; i < prices.length; i++) total += prices[i];
13
- // later, elsewhere:
14
- let t = 0;
15
- for (let i = 0; i < prices.length; i++) t += prices[i];
16
- ```
7
+ Correctness, coding principles, performance, safety and security are separate acceptance conditions. Satisfying one does not waive another. Identify the applicable expectations from the approved acceptance conditions, project policy, callers and dependency contracts; retain them in the existing plan, validation commands and test evidence rather than creating another checklist artifact.
17
8
 
18
- Good:
19
- ```javascript
20
- const sum = (arr) => arr.reduce((acc, x) => acc + x, 0);
21
- ```
9
+ - **Correctness:** establish reachable inputs and states, the expected result and side effects, and the observable result that would distinguish a defect. Exercise relevant success, boundary and failure outcomes.
10
+ - **Coding principles:** apply the documented responsibility, reuse, dependency-direction, naming and language rules to the design before writing it, then to the actual diff. Correct outputs and passing tests do not excuse an applicable rule violation.
11
+ - **Performance:** identify the affected workload and any declared latency, throughput, memory, allocation or concurrency limits. Compare appropriate evidence with those limits and the relevant baseline. Reuse existing measurements and resource-bound tests; do not invent a universal benchmark for every helper. If a necessary bound or measurement is unavailable, report that part as unverified instead of claiming a performance guarantee.
12
+ - **Safety:** preserve the intended state and primary failure through partial success, cleanup failure, retries, cancellation and concurrent work. Trace which writes remain, whether replay duplicates an effect, and whether abandoned work can continue changing state.
13
+ - **Security:** follow untrusted input to its operations and outputs. Check operation-specific access, input and resource bounds, injection sinks and disclosure of secrets or personal data against the project's policy.
22
14
 
23
- Caveat: extract when two current callers implement the same capability and would change together. Similar syntax alone does not establish a shared capability; keep independent decisions separate. Do not add an abstraction for a hypothetical second caller. A literal copy of an existing capability — test helpers included — reuses or moves the existing implementation.
15
+ Select the existing shared-catalog criteria that own these checks: correctness and error semantics under G1/G2, coding principles under S/M/G5, performance under G4, state safety under T1 with G1/G2, and security under G3. These are inspection dimensions, not five new verdict rows or five additional reviewers. Cite a reason when a dimension does not apply; a missing required input is not evidence of inapplicability.
24
16
 
25
- Two more forms of duplication that hide from symbol-level grep:
17
+ The author and assigned reviewers judge these outcomes from source and execution evidence. The grouped-verdict parser checks accounting and source anchors, not semantic truth; required command execution retains its existing evidence checks. Preserve failed, waived and unverified checks in the existing result fields. Do not claim all five outcomes verified from a complete table or a green test command alone.
26
18
 
27
- - **Scattered domain literals** — the same enum value / predicate repeated across queries or filters *may* be one business decision duplicated. The test: would the sites change together when the rule changes? If yes, consolidate to a named constant or builder at a single reference point; if they merely share a value, leave them apart — coupling incidental duplication is worse than repetition.
28
- - **Documented forks** — two deliberate variants of one capability kept as parallel implementations "because the delta is commented". If the delta is genuinely parametric (a few orthogonal options), collapse into one implementation with explicit option parameters; if not, split into two distinctly named capabilities. The commented fork itself is never the end state.
19
+ ## DRY — Don't Repeat Yourself
29
20
 
30
- ## KISS — Keep It Simple
21
+ Reuse or move an existing capability, including test helpers, rather than copying it. Extract shared logic when current callers implement the same capability and would change together; similar syntax or a hypothetical second caller is insufficient.
31
22
 
32
- The simplest solution that meets the requirement wins. Cleverness has a maintenance cost.
23
+ - Search touched domain enum values and predicates across queries, filters and branches, not only their identifiers. Consolidate a shared business decision into one named constant or query builder in the domain layer; leave independent decisions separate even when their literal values match.
24
+ - Read deliberate variants together. Consolidate genuinely parametric differences with explicit options when that simplifies the implementation. Otherwise retain distinctly named capabilities; a comment documenting the divergence does not justify duplicate implementations of one capability.
33
25
 
34
- Bad:
35
- ```javascript
36
- const canSubmit = isReady ? true : false;
37
- ```
26
+ ## KISS — Keep It Simple
38
27
 
39
- Good:
40
- ```javascript
41
- const canSubmit = isReady;
42
- ```
28
+ Choose the simplest direct solution meeting current requirements under `overview.md` precedence. Reuse-driven abstraction needs current callers; a local helper may name a cohesive step or separate abstraction levels with one caller.
43
29
 
44
- Here `isReady` is already a boolean, so both versions preserve the same value. Do not replace explicit null, undefined, or empty-string checks with a truthiness check unless rejecting `0`, `false`, and `NaN` is also intended.
30
+ Simplification preserves semantics: replace explicit null, undefined or empty-string checks with truthiness only when rejecting `0`, `false` and `NaN` is also intended.
45
31
 
46
32
  ## SOLID
47
33
 
@@ -51,320 +37,193 @@ Here `isReady` is already a boolean, so both versions preserve the same value. D
51
37
  - **I**nterface Segregation — many small interfaces beat one fat one.
52
38
  - **D**ependency Inversion — depend on abstractions, not concrete implementations.
53
39
 
54
- Bad (SRP):
55
- ```python
56
- class User:
57
- def save(self): ...
58
- def send_email(self, msg): ...
59
- ```
60
-
61
- Good (SRP):
62
- ```python
63
- class UserRepository:
64
- def save(self, user): ...
65
-
66
- class EmailService:
67
- def send(self, user, msg): ...
68
- ```
69
-
70
40
  ## YAGNI — You Aren't Gonna Need It
71
41
 
72
- Implement what is required **now**. Do not add knobs, options, hooks, or layers for a hypothetical future caller.
73
-
74
- Bad:
75
- ```javascript
76
- function calculator(a, b, op) {
77
- switch (op) {
78
- case 'add': return a + b;
79
- case 'multiply': return a * b; // not asked for
80
- case 'divide': return a / b; // not asked for
81
- }
82
- }
83
- ```
84
-
85
- Good:
86
- ```javascript
87
- const add = (a, b) => a + b;
88
- ```
42
+ Add no speculative parameters, configuration, hooks, layers or pre-1.0 compatibility shims. Every new identifier serves a current internal use, established external contract, runtime entry point or explicit user requirement; cite that evidence rather than a hypothetical future consumer.
89
43
 
90
44
  ## Meaningful naming
91
45
 
92
- Names reveal intent. `d` and `crtUsrAcct()` are bugs; `elapsedTimeInDays` and `createUserAccount()` are documentation.
93
-
94
46
  ### Names must be truthful
95
47
 
96
- The name must describe what the function actually does. Misleading names break reader expectations and survive renames.
97
-
98
- Flag and rename:
48
+ Names describe intent and actual behavior across branches:
99
49
 
100
- - `get*` / `fetch*` / `find*` that also perform caller-visible state changes their read-oriented names do not disclose. Documented lookup failures and diagnostic logging do not by themselves make a read name misleading.
101
- - `is*` / `has*` / `can*` that use an exception for an ordinary negative answer instead of returning `false`. An operational failure may still propagate under a documented failure contract.
102
- - `find*` that *creates* the entity when missing → `findOrCreate*` or `ensure*`.
103
- - Names that describe the implementation, not the intent: `loopOverUsers` → `notifyActiveUsers`, `runQuery` → `listOverdueInvoices`.
104
- - Names that say the opposite of what they do under some branch: `enableFoo` that disables when a flag is off, with no hint in the name.
50
+ - `get*` / `fetch*` / `find*` disclose caller-visible mutation or creation. Documented lookup failures and diagnostic logging alone do not invalidate a read name.
51
+ - `is*` / `has*` / `can*` return `false` for ordinary negative answers; operational failures may propagate under a documented contract.
52
+ - Name the operation's purpose rather than its loop or query mechanics, and disclose opposite actions under conditional branches.
105
53
 
106
54
  ### Names must stand alone
107
55
 
108
- The test: if the name appeared in a stacktrace, an autocomplete list, or a grep result, would the reader know what it does without opening the file? If not, add specificity.
109
-
110
- - Names missing the noun: `createPending()` → `createPendingInstallation()`. The verb is fine; the object is missing.
111
- - Generic verbs with no information: `handle`, `process`, `execute`, `doStuff`, `manage`. If the function deletes-then-inserts, name it `replace`, not `update`.
112
- - Constants that will collide with siblings later: `BUCKET` → `FONTS_BUCKET`, `TIMEOUT` → `HTTP_READ_TIMEOUT_MS`, `URL` → `AUTH_SERVICE_URL`.
113
- - Repository / port methods named after the rule they enforce, not the data they fetch: `findValid*` / `findActive*` / `findEligible*` — the adjective encodes a business rule the caller can't inspect from the name. Prefer `findDesktopLibrariesForUser(userId)` + a domain predicate applied by the caller.
114
- - Near-twin siblings a caller can't tell apart from the names alone (`parseRows` vs `parseRowsFromItems`): if a comment must explain which to pick, rename — encode the distinguishing fact (e.g., input shape: `parseRowsFromFlatItems`). Matching the existing sibling's style does not excuse the ambiguity.
56
+ Public methods, exports and port names identify their operation, object and distinguishing facts without file context. Compare exported siblings: if callers need a comment to choose one, encode the distinction in the name. Constants include their domain and units where needed; private helpers in tight scopes get more slack.
115
57
 
116
- This rule applies most strongly to **names crossing module boundaries**: public methods, exported constants, port methods. Private helpers in a tight local scope get more slack.
58
+ Business-oriented repository or port names are valid when their contract defines the term and governing policy or specification. Inspect policy ownership; an adjective alone neither proves a violation nor requires an unfiltered fetch.
117
59
 
118
60
  ### One identifier, one meaning per file
119
61
 
120
- A name that means two things in one file makes every reader re-derive which one they are looking at. The common shape: a new parameter holding a key takes the name a sibling signature already gives to the whole entity.
121
-
122
- Bad:
123
- ```ts
124
- findFullAccount(account: string) // a primary key
125
- update(idAccount: string, account: AccountRow) // the row — same word, four lines away
126
- ```
127
-
128
- Good: `findFullAccount(idAccount: string)` — the key takes the name the file already uses for keys.
129
-
130
- The test: grep the identifier across the file. If two occurrences carry different types or different roles, rename the newer one to the distinguishing fact and follow whatever name the file already uses for that role.
62
+ Search the identifier across the file. If occurrences carry different types or roles, rename the newer one to distinguish them and follow existing names for that role; do not use the entity's name for its key.
131
63
 
132
64
  ## Functions do one thing
133
65
 
134
- A name containing "and" or a body requiring scrolling is a reason to inspect responsibilities, not proof that a split is needed. Split when the body mixes independent responsibilities or levels of abstraction; apply the 50-line cap below separately.
135
-
136
- A short orchestrator may call several already-named steps at the same abstraction level:
137
- ```javascript
138
- function handleData() {
139
- fetchData();
140
- processData();
141
- displayData();
142
- }
143
- ```
144
-
145
- The body above does not need further splitting: each step is already a separate function. The generic name `handleData` is a naming issue; choose a name for the overall operation based on the caller's purpose.
66
+ Judge cohesion, complexity and abstraction levels. Split mixed responsibilities or levels when extraction improves the flow. A name containing "and" or a scrolling body prompts inspection, not automatic splitting. An orchestrator may call several named steps at one abstraction level; name their overall purpose.
146
67
 
147
68
  ### Plain-English summary test
148
69
 
149
- For every function you add or meaningfully modify, ask:
150
-
151
- > Can I summarize what this function does, line by line, as a short English sentence per line — and does the resulting summary read as prose?
152
-
153
- If the answer is "no, I'd have to group several lines together and invent a name for the group", **that grouping should already exist in the code as a named helper or named intermediate value**. The fact that you had to invent the name is the signal to extract. A local readability helper can have one caller; the second-caller requirement applies to reuse-driven abstraction layers.
70
+ For each added or meaningfully modified function, check whether short English sentences describing each line form readable prose. If that requires grouping lines under an invented name, represent the group as a named helper or intermediate value. A local readability helper may have one caller; the second-caller requirement concerns reuse-driven layers.
154
71
 
155
72
  ### Inspect for readability problems
156
73
 
157
- - Three nested control-flow blocks — inspect whether early returns or named predicates improve readability. Four or more require refactoring under "Limit nesting depth" below.
158
- - Mixed levels of abstraction — a high-level orchestrator suddenly doing string parsing, date arithmetic, or SQL assembly inline.
159
- - A reader has to track 5+ anonymous temporary values to understand the return.
160
- - A long `.map().filter().reduce()` chain where each stage does non-obvious work and no stage has a name.
161
- - Boolean expressions long enough that intent is buried — `if (a && b && !c && (d || e.f > 0) && ...)` without a named predicate.
162
- - A function that orchestrates 4+ distinct logical phases inline (*fetch → resolve → branch → persist → publish*), each more than a line or two. Even without deep nesting, that's enough work to warrant named sub-methods.
163
- - A chain of `if (x === SomeEnum.A) return …` over the values of one enum — that's a hand-rolled switch. Use a real `switch (x)` so the cases line up and exhaustiveness is visible; it also drops the trailing fall-through `return` that an if-chain needs.
164
- - A dense data literal — an object/struct/`{...}` carrying several inline ternaries or conditional spreads (`...(cond ? { x } : {})`) — assembled inline in a method that also does other work. Extract a named builder (`buildX(...)`) so the method reads as "compute X → assign X", and each conditional field gets a place to be understood.
165
-
166
- ### 50-line cap
74
+ - Apply "Limit nesting depth" below; inspect mixed abstraction levels, 5+ anonymous temporaries, unnamed non-obvious transformation stages and boolean expressions with buried intent.
75
+ - Name the steps of 4+ distinct inline phases, each longer than a line or two.
76
+ - Use a `switch` for branches over one enum so cases and exhaustiveness are visible.
77
+ - Extract a named builder when dense conditional fields are assembled inside a method doing other work.
167
78
 
168
- A single function/method body must stay within **50 lines**, counting only effective code (exclude blank lines, comments, and pure data declarations such as large enums, lookup tables, or constant maps).
79
+ ### Function size review signal
169
80
 
170
- Crossing the cap is an extraction signal, not a style nit. Before declaring a function complete, count effective body lines; if over 50, split, or surface the violation and confirm with the user before continuing.
81
+ Review newly added or substantially edited functions beyond 50 effective body lines, excluding blanks, comments and pure data declarations. Record why a longer function remains cohesive or identify its concrete problem and improved shape. Length alone is not a violation, an automatic gate or grounds for a user exception; split only when it improves understanding or maintenance. Explicit repository limits follow `overview.md` precedence.
171
82
 
172
83
  ### What's fine
173
84
 
174
- - Functions that read as a straight sequence of clear, already-named steps (each line is an English sentence).
175
- - Short functions (< ~10 lines) with a clear purpose and readable flow. Shortness does not exempt a function from the nesting-depth rule or other applicable checks.
176
- - Idiomatic framework patterns used clearly (a 30-line controller method obviously doing its job).
177
- - Guard clauses at the top — they *help* readability, they don't count against you.
85
+ Straight sequences of named steps, clear idiomatic framework patterns and guard clauses are acceptable. Short functions still follow nesting and other applicable rules.
178
86
 
179
87
  ## Mutation and state boundaries
180
88
 
181
- These defects survive a green suite because the test reads the same object the code mutated. State the fact you actually verified, at the moment you verified it.
182
-
183
89
  ### Decide on the direct fact, not a proxy
184
90
 
185
- A status field, a flag, or a "was processed" marker is evidence *about* a decision, not the decision itself. When the decision turns on identity or a destination — did this row move, did ownership change, is this the same target — compare the source and destination identifiers directly. If the direct fact is unavailable, do not perform the change; surface it.
186
-
187
- The test: construct the opposite case and ask whether your condition still reads true. `status === 'DONE'` holds both for "already moved here" and "moved somewhere else"; `row.parentId === target.parentId` does not.
91
+ For identity, ownership or destination decisions, compare the source and destination identifiers rather than status or processed flags. Check that the opposite case does not satisfy the condition. If the direct fact is unavailable, surface it without performing the change.
188
92
 
189
93
  ### Capture before-state before the mutating boundary
190
94
 
191
- When a value describes the state *before* processing, read it before anything that can mutate the object — a strategy call, a repository write, a reload, any `await` that hands the object to other code. Read every before-value feeding the same diagnostic in **one snapshot, at one moment**.
192
-
193
- Never re-read a before-field off the original object after that boundary, and never reconstruct it from the post-state. Pass before-state and result-state as two explicit values.
95
+ Capture all before-values for a diagnostic in one snapshot before any call, write, reload or handoff that can mutate the object. Pass before-state and result-state separately; never re-read or reconstruct before-state after that boundary.
194
96
 
195
97
  ### Update only the fields this work owns
196
98
 
197
- Creating a new row and updating an existing one are not the same write authority. When reusing an existing row, update only the fields the current operation owns, and express them as an allowlist. Provenance, ownership, and externally-managed values are not overwritten without an explicit requirement saying so. Keep the create-vs-reuse answer available at the later write step — that is what tells the two authorities apart.
198
-
199
- The test: for every field this change writes, grep the other sites that write the same field in the same flow — a later pass of the same loop, a final persist, a sibling handler — and put them in order. If a later write clears what an earlier one recorded, the clear needs a condition, not a default.
99
+ Keep create-versus-reuse information through the final write. For an existing row, allowlist only fields this operation owns; overwriting provenance, ownership or externally managed values requires an explicit requirement. Search and order all writes to each changed field in the flow. A later clear of an earlier value needs a condition, not a default.
200
100
 
201
101
  ### Zero affected rows is a question, not an answer
202
102
 
203
- A conditional write that changed no rows has not told you whether it succeeded. Re-read the current state and separate the three cases: already in the desired state, changed to a different conflicting state, target deleted. Each gets its own success/failure handling and its own message — collapsing conflict and deletion into one error hides the case the caller must act on.
103
+ After a conditional write affects zero rows, re-read state to distinguish already-desired state, conflict and deletion. Handle and report each case separately rather than inferring success or a cause from the row count.
204
104
 
205
105
  ### Priority between competing inputs is policy, not an if-chain
206
106
 
207
- Which of several inputs wins is a business rule. It does not belong in a service's early return or inline condition, where the next caller re-derives it differently. The service collects inputs; a named domain function decides. The function's name alone should tell you the policy.
107
+ A service collects inputs; a named domain function decides which wins. Its name identifies the priority policy instead of hiding it in service control flow.
208
108
 
209
109
  ### An error message states only what you observed
210
110
 
211
- Do not assert a cause the code never checked — "target not found" after a write that only reported zero rows is a guess. Failures with different remedies (deleted, state mismatch, concurrent change) get different messages, each covered by a test on that path.
111
+ Report only observed facts. Failures with different remedies, including deletion, state mismatch and concurrent change, get distinct messages and tests on their paths.
212
112
 
213
113
  ## Wrapping a third-party call
214
114
 
215
115
  ### The wrapper must add something the library does not already do
216
116
 
217
- Before writing recovery, retry, or fallback code around a library call, read that library's own handling of the same case in its installed source. A `catch` that repeats what the library already did — same read, same transaction, same conditions — recovers nothing; it only replaces a typed error with a weaker one.
218
-
219
- The test: name the condition under which your branch runs and the library's does not. If you cannot name it from the library's source, the branch is dead. Delete it, or make it do something the library provably does not — a locking read where the library read without a lock, a different isolation level, a retry the library never attempts.
117
+ Before adding recovery, retry or fallback, read the installed library's handling of that case. Identify the condition or behavior your branch adds beyond the library's handling; delete or change a branch that only repeats it.
220
118
 
221
119
  ### A comment may not name a condition the code does not run under
222
120
 
223
- Recovery documented as "under REPEATABLE READ this re-read succeeds" is false when every caller opens READ COMMITTED. Cite the call site that establishes the condition, or drop the claim — an unverifiable comment outlives the code it excuses.
121
+ Cite the call site establishing any condition a recovery comment relies on; remove claims that no caller establishes.
224
122
 
225
123
  ### Rethrowing keeps the original error
226
124
 
227
- Replacing a typed library error with a bare one throws away what the caller needs in order to act: which constraint fired, the driver's message, the original stack. Keep the original as the cause (`new Error(msg, { cause: err })`, `raise X from err`) and keep the type when a caller branches on it.
125
+ When replacing an error, retain the original as its cause, including its diagnostic details and stack. Preserve its type when callers branch on it.
228
126
 
229
127
  ## Testing discipline
230
128
 
231
- These principles apply to every test file regardless of language or framework. The mechanical detection patterns (which mock library, which spy API) are in each `languages/*.md` Tests section.
232
-
233
- Follow the testing-waiver policy in `overview.md` "Tests planned". An explicit waiver applies only to the named behavior or check, including its branch-test, branch-deletion, or resource-bound requirement. Record that scope as unverified. All checks outside the waiver and the quality rules for tests that are written or edited still apply.
129
+ Apply these rules to every test file; language-specific detection patterns are in `languages/*.md`. New behavior without a test is incomplete unless the user explicitly waives it for this change and project rules permit it. Record the exact waived behavior or check as unverified, including its branch-test, branch-deletion or resource-bound requirement. A waiver neither weakens existing tests nor establishes coverage; all other checks and quality rules for written or edited tests still apply.
234
130
 
235
131
  ### Reuse tests before adding coverage
236
132
 
237
- Before changing a function, search by its name, behavior, callers, and assertions and read the matching test bodies. Strengthen an existing behavior test in place. If it already verifies the changed contract, run and retain it. Add a test only when no existing test covers that behavior; prefer the nearest existing test file and justify a new file by a distinct ownership or boundary.
133
+ Before function edits or new test plans, search names, behavior, callers and assertions, then read candidate bodies. Strengthen an existing behavior test, or run and retain it if it already covers the changed contract. Add only for an uncovered behavior, preferably in an existing file; a new file needs distinct ownership or a boundary reason.
238
134
 
239
- Keep cases that separate changed outcomes or meaningful failures. A function extraction, renamed helper, or additional syntactic branch does not by itself justify another test. Do not create parallel tests for the same input and outcome or generate every model, provider, and task-type combination. One behavior has one primary test owner; an integration case needs a separate wiring risk.
135
+ Record the changed function, search terms, existing test locations and grounds for retaining, extending, adding or retiring coverage. Use `extend <path:line>`, `new (nothing covers <behavior>)` or `retire <path:line> (behavior moved to <where>)`. New tests without survey evidence are unfinished. Retire a test in the same commit only when its behavior is gone or a replacement asserts it more strongly through the same seam; otherwise retain it.
240
136
 
241
- The review evidence names the changed function, the existing test that was retained or strengthened, or the uncovered behavior that required a new test. Branch-deletion checks below apply to this coverage; they do not require a separate test function for every branch. Completion self-check and code review assess this evidence.
137
+ Keep distinct outcomes and meaningful failures, not parallel cases or cases per helper, branch, model, provider or task-type combination. Each behavior has one primary test owner; integration cases need separate wiring risks. Branch-deletion checks reuse this coverage. Completion self-check and code review assess the mapping.
242
138
 
243
139
  ### No self-mocking
244
140
 
245
- A unit test for class `Foo` must **not** stub, spy on, or replace methods on the instance of `Foo` being tested. Mocking injected collaborators (other services, repositories, adapters, ports, the clock) is fine and expected.
246
-
247
- Why it matters: when you mock a method on the subject under test (SUT), the test no longer verifies that method's behavior — it verifies that *some* version of the class (the one you wired up) calls the mocked method. If someone deletes the real implementation, the test still passes. The test has become a proof of its own shape.
248
-
249
- Bad (pseudo, language-agnostic):
250
- ```
251
- sut = new Foo(deps)
252
- mock(sut.calculateTotal).returns(100) // mocking the SUT's own method
253
- result = sut.checkout()
254
- assert result.total == 100 // proves wiring, not logic
255
- ```
256
-
257
- Good:
258
- ```
259
- sut = new Foo(deps) // real Foo, real calculateTotal
260
- mock(deps.payment.charge).returns(ok) // mock the collaborator at the boundary
261
- result = sut.checkout()
262
- assert result.total == expectedTotal // proves the logic
263
- ```
141
+ Exercise the real subject under test (SUT); do not stub, spy on or replace its methods. Mocking injected collaborators, including repositories, ports and clocks, is allowed.
264
142
 
265
143
  ### Behavioral, not implementation tests
266
144
 
267
- Assertions should be about **outcomes** — return values, thrown errors, persisted state, published events, calls made to genuine external boundaries. They should **not** be about *how* the work was done internally — which private helper was called, in what order.
268
-
269
- Smells:
270
-
271
- - `expect(spy).toHaveBeenCalledWith(...)` as the *only* or *primary* assertion, when the spy is on an internal helper or a pure collaborator with no side effects.
272
- - Tests that would break if you renamed a private method without changing behavior.
273
- - Assertions on private methods reached via reflection, cast-to-any, or bracket access — the issue is *reaching into privates*, not the language escape hatch itself.
274
- - A test file where most assertions are on spies rather than on results.
145
+ Assert return values, errors, persisted state, events or genuine external boundary calls, including mail, payment and repository writes. Do not make internal-helper or pure-collaborator calls the primary proof, assert private helpers through reflection or casts, or couple tests to private names or internal call order. A suite dominated by spy assertions merits inspection of whether those spies represent outcome boundaries.
275
146
 
276
- Legitimately behavioral (these are fine):
277
-
278
- - `expect(mailerSpy).toHaveBeenCalledWith(...)` — sending mail *is* the behavior.
279
- - `expect(paymentGateway.charge).toHaveBeenCalledWith(...)` — charging a card *is* the behavior.
280
- - `expect(orderRepo.save).toHaveBeenCalledWith(...)` in an application-service test — producing the right save call *is* the point of the service.
281
-
282
- The judgment call: is the mocked thing an **outcome boundary** (port, external service, side-effecting adapter) or an **internal helper**? Asserting on boundaries is behavioral; asserting on helpers is implementation-coupled.
147
+ Do not inspect mock-call arguments by positional indexing; use intent-revealing assertions. Follow the language pack's stated exception for unavoidable access.
283
148
 
284
149
  ### Assert the last write, not the first
285
150
 
286
- When one run writes the same record more than once — an update followed by a final persist, two passes of the same loop over sibling rows — asserting the earlier call proves nothing about what the record ends up holding. The later write can drop the very field the test asserted and the test stays green, so the suite certifies a broken end state.
287
-
288
- The test: list every write in this flow that touches the field you assert, and confirm the one you assert is the last. If it is not, assert the last one too.
151
+ List all writes to the asserted field in the flow. Assert the last write as well as any relevant earlier write; an intermediate assertion alone does not establish final state.
289
152
 
290
153
  ### An effect under its own mock is not evidence
291
154
 
292
- When a mock replaces the code path that would produce an effect, a test above that mock has not verified the effect — it verified that the mock was reachable. Claim coverage for an effect only where the real path runs; the presence of a mock in the harness is not proof that the branch behind it works.
155
+ Claim an effect's coverage only where its real producing path runs. Reaching a mock that replaces that path does not verify the effect behind it.
293
156
 
294
157
  ### Every branch you add gets a test that dies with it
295
158
 
296
- A new `catch`, guard, early return, or `else` is a behavior claim. Coverage for it means one test that FAILS when the branch body is deleted — not a happy-path test that merely reaches the same method.
297
-
298
- The test: delete the branch body and run the suite. Green means the branch is untested, and an untested recovery path is indistinguishable from one that cannot fire at all.
299
-
300
- This binds hardest on error-recovery code, where the happy path is what the library already does and the branch is the only behavior your code adds.
159
+ For every unwaived new `catch`, guard, early return or `else`, delete its body and run the suite to confirm a test fails. Merely reaching the method is insufficient, especially when recovery is the only behavior added beyond a library's happy path. This does not require a separate test function per branch.
301
160
 
302
161
  ### Shared fixtures keep the ordinary default
303
162
 
304
- A shared fixture's defaults describe the normal path. Do not flip a default to exercise one exception — every existing caller silently changes meaning. Pass the exceptional condition explicitly in the test that needs it (`makeFamily({ familyEnabled: false })`), and search all call sites before changing any default.
305
-
306
- The test: does the no-argument fixture call still describe the ordinary case?
163
+ Keep shared fixture defaults on the ordinary path. Pass exceptional conditions explicitly in their tests, and search all call sites before changing a default.
307
164
 
308
165
  ### Test data must actually separate the paths
309
166
 
310
- Two scenarios whose setup values and assertions are identical are one test with two names. Give source and destination, existing and incoming, success and conflict deliberately different values. The check: state each test's distinguishing input in one sentence, then delete that difference — if the test still passes, it never tested the path. A wrong implementation must not pass because the defaults happened to agree.
167
+ Use distinguishing inputs for source/destination, existing/incoming and success/conflict paths; identical setup and outcome do not justify separate cases. State each test's distinguishing input, then remove that difference to check whether the assertion detects it; defaults must not let an incorrect implementation pass.
311
168
 
312
169
  ### A test title names the unit and the one condition it isolates
313
170
 
314
- A test title is a name, so the truthful and stand-alone rules above apply to it. From a failure line alone the reader must know which unit ran and which single condition was under test.
315
-
316
- - Name the unit when the file covers more than one. `'returns the primary-key lookup result'` fits every by-key read in the class; `'findFullAccount returns …'`, or a `describe('findFullAccount', …)` wrapper, fits one.
317
- - Credit only the condition the case actually isolates. A parameterised case that trips two guards at once must not name one of them in the title — split it into one case per guard.
318
-
319
- The test: delete from the setup the input the title credits. If the case still passes, the title describes a guard the test never reached — retitle it, or fix the setup so it does.
171
+ The failure line identifies the unit and isolated condition, using a grouping name where appropriate. If a parameterized case trips two guards, separate them before naming one. Remove the input credited by the title: if the test still passes, correct the setup or title to match the path actually verified.
320
172
 
321
173
  ### Test tooling you add is used in the same change
322
174
 
323
- A new mock, state setter, or repository branch that no test calls is unfinished work, not coverage. Grep every new test identifier for a use site before claiming done, and check that a repository mock does not only ever return success.
175
+ Search every new mock, state setter, helper or repository branch for a test use in the same change. Unused tooling is unfinished; check that repository mocks do not only return success.
324
176
 
325
177
  ### Resource bounds need their own regression test
326
178
 
327
- A change to memory use, concurrency, batching, or stream handling is not covered by a functional test that passes on a small input. Add a test that pins the bound the change claims to hold — peak size, concurrent count, chunk count.
179
+ Changes to memory use, concurrency, batching or streaming need a regression test pinning the claimed bound, such as peak size, concurrent count or chunk count. Small-input functional success alone is insufficient.
328
180
 
329
181
  ## Trace what this change can do wrong
330
182
 
331
- The rules above name defect shapes. A defect with no name on this list is still a defect, and the ones that reach production usually have no name — they are ordinary code that produces a wrong result for one input nobody walked.
183
+ For every changed source file, trace changed paths to their outcomes, including failures beyond those listed in the plan:
184
+
185
+ - **error** — each new call's failures and what the caller can distinguish.
186
+ - **partial** — writes left behind and what a retry sees.
187
+ - **concurrent** — competing writes or work continuing after a deadline.
188
+ - **selection** — whose evidence survives when several candidates fail.
332
189
 
333
- For every source file this change touches, follow the paths the change creates or alters to their end, and state where a wrong result comes out:
190
+ Inside a cleaning `try` / `catch` / `finally`, register cleanup targets before throwing reads, writes or calls, including work that cleanup must await. Compare throwing-call and cleanup-registration order with the base when moving code; changed order is a behavior change. Name failures test fakes cannot produce as unverified, not clean.
334
191
 
335
- - **error** — what the caller sees when each new call fails, and whether that is distinguishable from the other failures it must be told apart from.
336
- - **partial** — the change succeeded halfway; what is left written, and what the next run sees.
337
- - **concurrent** — something else is still writing, or the deadline fired and the work did not stop.
338
- - **selection** — when several candidates fail, which one's evidence survives.
192
+ Use "Finding evidence and grading" below. Unreachable-state guards and extra tests of already-covered behavior are optional unless another applicable rule is violated. Small, cheap-to-fix failures remain findings.
339
193
 
340
- The failures the plan names are where the trace starts, not where it stops. Two orderings produce most error-path defects:
194
+ ## Finding evidence and grading
341
195
 
342
- - **cleanup registered after a call that can throw** — inside a `try` whose `catch` / `finally` cleans up, the object to clean up must be registered before any call that can throw: a property write, a read, a call that starts other work whose completion the cleanup must wait for. Registered after it, the failure leaves the object behind or lets the cleanup run before that work settles.
343
- - **order changed by a move** — when the change moves or restructures existing code, compare the order of throwing calls and cleanup registration with the base version; a refactor that swaps them is a behaviour change.
196
+ Implementation, independent verification and review use `review-rules.json` for rule IDs and blocking severity/timing. Referenced rules define applicability; `overview.md` defines precedence.
344
197
 
345
- A failure the test fakes cannot produce is not covered by a passing test. Name it as unverified rather than calling the path clean.
198
+ - An `execution-error` establishes a reachable input/state, expected behavior and actual wrong result.
199
+ - A `design-violation` establishes the applicable rule, violating source and concrete maintenance or design consequence; no runtime failure is required. A preferred alternative alone is insufficient.
200
+ - `must-fix` means a defect or a violation with substantial consequences; `should-fix` is a clear violation without immediate breakage; `nit` is a small, demonstrable improvement. Confidence is not severity; missing inspection is incomplete coverage.
201
+ - `now` is introduced or changed by this change. `park` needs a cited scope or accepted-risk basis, not cost, passing tests or a restrictive plan. Reclassifying explicitly accepted product behavior requires new evidence.
202
+ - Unresolved blocking `now` findings prevent acceptance: executors fix them, verifiers return `FAIL`, and reviewers preserve them for settlement. Record `nit` and justified `park` findings without blocking. Semantic grading remains worker judgment.
346
203
 
347
- **An execution-error finding names the input or state that produces the wrong result.** *"If the archive yields no entries, line 42 reports success and stores an empty result"* is an execution-error finding. A design-violation finding instead identifies the applicable rule, the violating code, and its concrete design or maintenance consequence; it does not require a runtime failure. An alternative implementation or preferred name alone establishes neither kind. Guards for states no caller can reach and extra tests for already-covered behavior are optional improvements unless a separate applicable rule violation is demonstrated. A real failure that is small and cheap to fix is still a finding.
204
+ M1 covers truthful, specific, standalone names; M2 covers cohesion, complexity, abstraction levels, nesting and plain-English flow. Size prompts inspection, not a finding by itself. Clear violations are normally `should-fix` / `now` even when execution is correct. Cite the construct and consequence; do not demand unrelated legacy cleanup.
205
+
206
+ `file_size_cap.py` measures physical size; reviewers judge responsibility. An oversized legacy file need not be cleaned wholesale, but adding unrelated responsibility still violates S3 or M2. Small wiring edits may remain with a cited rationale. Restrictive plan placement does not waive these rules: return a plan conflict with a conforming location and preserved acceptance behavior, and obtain plan repair before writing outside authorized scope.
348
207
 
349
208
  ## Untrusted input and security
350
209
 
351
- Input from outside the process — request bodies, query strings, headers, uploaded files, queue messages, webhook payloads — is controlled by whoever sends it, authenticated or not. These checks apply to every changed file that reads such input or acts on its behalf. **A finding names the input and what it does:** *"a body of 100k fonts with distinct keys runs the O(n²) uniqueness check before the size limit rejects it"* is a finding; "could be more secure" is not.
210
+ Treat outside-process input as sender-controlled, authenticated or not. Apply these checks to every changed file reading or acting on it. Findings name the input and its effect; generic hardening preferences are insufficient.
352
211
 
353
212
  ### Bound the work before the expensive check
354
213
 
355
- A size or count limit protects nothing if a costlier check still runs on the oversized input. Many validators run every rule on a field rather than stopping at the first failure — class-validator under a `ValidationPipe` without `stopAtFirstError`, for one — so `@ArrayMaxSize(50)` failing does not stop `@ArrayUnique`, whose comparison is O(n²). Any work that grows faster than the input — pairwise uniqueness, nested scans, a backtracking regex, recursion or expansion driven by the input — runs only after a bound has rejected oversized input, inside the same check (`if (items.length > MAX) return false;` then a `Set`), or the framework is configured to stop at the first failure. The body-size limit is not that bound: it caps bytes, not the element count the costly step loops over. Pin it with a test that sends an input well past the limit and asserts the rejection returns quickly (see "Resource bounds need their own regression test").
214
+ Reject oversized input before work that grows faster than input size, including nested scans, backtracking regexes and input-driven expansion. Verify actual execution order: a failed size rule may not stop other validators. Guard inside the costly check or configure first-failure stopping. Byte limits do not replace element-count bounds. Test prompt rejection well beyond the limit and the claimed resource bound, as required by "Resource bounds need their own regression test".
356
215
 
357
216
  ### Input never builds code
358
217
 
359
- Input that reaches SQL, a shell command, a file path, a URL fetched server-side, a template, or a regular expression goes through a parameter, an allowlist, or an escaping API for that sink — never string concatenation or interpolation. A path from input is resolved and checked to stay under its root; a server-side fetch target is checked against an allowlist of hosts.
218
+ Pass input to SQL, shells, paths, server-side fetches, templates and regexes through sink-specific parameters, allowlists or escaping, never direct concatenation or interpolation. Resolve input paths and verify confinement to their root; allowlist fetch hosts.
360
219
 
361
220
  ### Every new entry point checks the caller's access rights
362
221
 
363
- A new route, handler, resolver, or job that reads or writes per-user data establishes the caller or execution identity through the project's authentication mechanism and checks permission for the requested operation before returning or changing the resource. Apply the project's access policy: ownership, shared access, tenant membership, or an authorized administrative role may establish permission. An id the caller can choose is not proof of access. An explicitly public operation follows the project's public-access policy rather than requiring a user identity.
222
+ Before returning or changing per-user data, new routes, handlers, resolvers and jobs establish identity through project authentication and check operation-specific permissions. Ownership, shared access, tenant membership or authorized administration may grant access; an input-chosen ID does not. Explicitly public operations follow the project's public-access policy.
364
223
 
365
224
  ### Protect secrets and limit personal-data disclosure
366
225
 
367
- Keep real secrets, tokens, and credentials out of source and fixtures meant for production. Logs and error messages do not expose secrets, full tokens, passwords, or personal data through echoed request bodies or upstream errors passed through verbatim. A response may return personal data only when the operation's access policy authorizes the recipient and the fields are needed for its documented purpose. Credentials or tokens are returned only by operations explicitly designed to issue them to an authorized recipient; unrelated responses do not echo them.
226
+ Keep real secrets, tokens and credentials out of source and production fixtures. Logs and errors do not disclose secrets or personal data, including through echoed requests or upstream errors. Personal-data responses require an authorized recipient and fields needed for the documented purpose. Return credentials only from operations designed to issue them to authorized recipients.
368
227
 
369
228
  ### No execution of input
370
229
 
@@ -374,71 +233,16 @@ No `eval`, `Function(...)`, dynamic `import()` of an input-chosen path, or deser
374
233
 
375
234
  Replace hardcoded values with named constants.
376
235
 
377
- Bad: `if (age > 18)`
378
- Good: `const LEGAL_AGE = 18; if (age > LEGAL_AGE)`
379
-
380
236
  ## Limit nesting depth
381
237
 
382
238
  Count nested control-flow blocks within each function; the function, class, and module bodies do not count. At three levels, inspect readability rather than requiring a split solely for the count. At four or more, flatten with early returns or extract a named step before completion. Short functions follow the same threshold. Enforcement is the preflight self-check and code review.
383
239
 
384
- Bad:
385
- ```javascript
386
- function process(user) {
387
- if (user) {
388
- if (user.isActive) {
389
- if (user.hasPermission) {
390
- // ...
391
- }
392
- }
393
- }
394
- }
395
- ```
396
-
397
- Good:
398
- ```javascript
399
- function process(user) {
400
- if (!user) return;
401
- if (!user.isActive) return;
402
- if (!user.hasPermission) return;
403
- // ...
404
- }
405
- ```
406
-
407
240
  ## Comments explain *why*, not *what*
408
241
 
409
- The code already says **what**. Comments record the hidden constraint, the bug being worked around, the surprising tradeoff. Never narrate the next line.
410
-
411
- Interface documentation may describe caller-visible contracts that the signature cannot express: error versus ordinary negative results, missing-input behavior, side effects, or security constraints. This is not redundant narration of an implementation. Verify the documented behavior against implementations, callers, and relevant tests; do not infer it from the documentation alone. When the contract requires non-obvious work, explain its reason if that reason is established by evidence.
412
-
413
- Bad:
414
- ```javascript
415
- // increment i
416
- i++;
417
- ```
418
-
419
- Good:
420
- ```javascript
421
- // User may be soft-deleted; invalidate cache so stale reads vanish.
422
- cache.invalidate(user.id);
423
- ```
424
-
425
- **A comment is not a change log.** Never record change history in code — ticket IDs (`FU-003`, `DEV-9185`), verification logs (`verified parity-neutral on the real DB`), `retained from …`, or the reason something *changed*. That belongs to git blame, the commit message, and the PR; the code reader six months later does not have those tickets open. A comment earns its place only by stating a constraint or invariant that is **still true and load-bearing for someone reading the code cold, with zero knowledge of the diff that introduced it**. If it stops making sense once that diff is forgotten, delete it.
426
-
427
- Bad (change-log noise — delete):
428
- ```javascript
429
- // FU-003 read-path deltas — verified parity-neutral against the publish grid
430
- // on the real DB (DEV-9185 Stage 1). Retained as read-side display alignment.
431
- applyYearlyMultiplier(rows);
432
- ```
433
-
434
- Good (constraint a cold reader needs):
435
- ```javascript
436
- // Publish callers omit both fields, so the 0 multiplier is intentional here.
437
- applyYearlyMultiplier(rows);
438
- ```
242
+ Default to no implementation comment. Explain only constraints, workarounds or tradeoffs a future reader needs; do not narrate executable code.
439
243
 
440
- Default to writing **no comment**. Only add one when removing it would confuse a future reader.
244
+ Interface documentation may state caller-visible failure, missing-input, side-effect and security contracts that names and types cannot express. Verify them against implementations, callers and tests; explain non-obvious required work only from established evidence.
441
245
 
442
- ## Boy Scout Rule
246
+ Keep change history, ticket IDs and verification logs in commits or PRs, not code comments. A retained comment states a current constraint or invariant that remains useful without the introducing diff.
443
247
 
444
- Leave the file cleaner than you found it. Fix one small inconsistency on the way through, do not embark on a separate refactor.
248
+ Remove dead or commented-out code; version control preserves its history.