project-brain 0.23.0 → 0.26.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 (61) hide show
  1. package/README.md +1 -1
  2. package/package.json +6 -6
  3. package/templates/project.claude.md +1 -1
  4. package/templates/skills/brain-audit/SKILL.md +38 -11
  5. package/templates/skills/brain-audit/references/abuse.md +36 -11
  6. package/templates/skills/brain-audit/references/accessibility.md +50 -22
  7. package/templates/skills/brain-audit/references/ai.md +39 -15
  8. package/templates/skills/brain-audit/references/analytics.md +34 -11
  9. package/templates/skills/brain-audit/references/api.md +38 -13
  10. package/templates/skills/brain-audit/references/backend.md +41 -9
  11. package/templates/skills/brain-audit/references/browser.md +146 -0
  12. package/templates/skills/brain-audit/references/complexity.md +22 -12
  13. package/templates/skills/brain-audit/references/concurrency.md +36 -18
  14. package/templates/skills/brain-audit/references/consistency.md +32 -9
  15. package/templates/skills/brain-audit/references/contract-drift.md +34 -16
  16. package/templates/skills/brain-audit/references/cost.md +45 -23
  17. package/templates/skills/brain-audit/references/cross-surface-parity.md +38 -11
  18. package/templates/skills/brain-audit/references/database.md +43 -17
  19. package/templates/skills/brain-audit/references/dependencies-licensing.md +27 -12
  20. package/templates/skills/brain-audit/references/design-system.md +40 -17
  21. package/templates/skills/brain-audit/references/devops.md +32 -17
  22. package/templates/skills/brain-audit/references/documentation.md +38 -16
  23. package/templates/skills/brain-audit/references/failure.md +40 -18
  24. package/templates/skills/brain-audit/references/feature-flags.md +31 -15
  25. package/templates/skills/brain-audit/references/flow-integrity.md +42 -10
  26. package/templates/skills/brain-audit/references/frontend.md +40 -12
  27. package/templates/skills/brain-audit/references/functional.md +31 -11
  28. package/templates/skills/brain-audit/references/future.md +28 -7
  29. package/templates/skills/brain-audit/references/goal.md +15 -6
  30. package/templates/skills/brain-audit/references/i18n.md +30 -8
  31. package/templates/skills/brain-audit/references/idempotency.md +46 -24
  32. package/templates/skills/brain-audit/references/infrastructure.md +43 -13
  33. package/templates/skills/brain-audit/references/mobile.md +37 -15
  34. package/templates/skills/brain-audit/references/multi-tenancy.md +41 -12
  35. package/templates/skills/brain-audit/references/numeric.md +33 -16
  36. package/templates/skills/brain-audit/references/observability.md +43 -19
  37. package/templates/skills/brain-audit/references/packaging.md +39 -13
  38. package/templates/skills/brain-audit/references/performance.md +43 -13
  39. package/templates/skills/brain-audit/references/privacy.md +38 -15
  40. package/templates/skills/brain-audit/references/product.md +29 -10
  41. package/templates/skills/brain-audit/references/prompt-spec-gap.md +34 -10
  42. package/templates/skills/brain-audit/references/reachability.md +38 -18
  43. package/templates/skills/brain-audit/references/repo-history.md +23 -16
  44. package/templates/skills/brain-audit/references/runtime.md +121 -0
  45. package/templates/skills/brain-audit/references/scalability.md +37 -10
  46. package/templates/skills/brain-audit/references/security.md +46 -22
  47. package/templates/skills/brain-audit/references/state-model.md +44 -15
  48. package/templates/skills/brain-audit/references/supply-chain.md +42 -13
  49. package/templates/skills/brain-audit/references/temporal.md +37 -14
  50. package/templates/skills/brain-audit/references/testing.md +39 -15
  51. package/templates/skills/brain-audit/references/tooling-baseline.md +34 -18
  52. package/templates/skills/brain-audit/references/type-safety.md +38 -19
  53. package/templates/skills/brain-audit/references/usability.md +78 -0
  54. package/templates/skills/brain-audit/references/versioning-compatibility.md +34 -12
  55. package/templates/skills/brain-audit/references/visual-design.md +38 -12
  56. package/templates/skills/brain-audit/references/web-metadata.md +47 -19
  57. package/templates/skills/brain-record/SKILL.md +297 -0
  58. package/templates/skills/brain-record/assets/build-video.sh +142 -0
  59. package/templates/skills/brain-record/assets/record.mjs +283 -0
  60. package/templates/skills/brain-record/references/pitfalls.md +233 -0
  61. package/templates/skills/brain-worktree/SKILL.md +103 -0
@@ -4,20 +4,23 @@ What is harder to change than it needs to be? Complexity is not line count — i
4
4
 
5
5
  Use `repo_map` to find the structurally central symbols, then `impact` on each. **A symbol with a large blast radius and high internal complexity is the riskiest code in the project**, and that combination is what this module is for.
6
6
 
7
- This module never computes a complexity score — no cyclomatic number, no cognitive-complexity number — because that requires running an analyser, and everything here is established by reading. If the project already has one committed (a linter's `complexity` rule, a SonarQube report, a CI badge), read it with the evidence in mind rather than at face value: cyclomatic complexity's correlation with real defects is weaker and more contested than it's often assumed to be — a formal critique (Shepperd, "A critique of cyclomatic complexity as a software metric") argues its predictive power may reduce mostly to code size — while a ceiling on the number (historically 10, sometimes relaxed to 15 with strong review and test discipline) remains a defensible *engineering* limit, which is a different and more modest claim than "this number predicts a bug." Cognitive Complexity (SonarSource, 2016) is the better-regarded metric specifically for *readability* — it was designed to fix cyclomatic complexity's blind spot for nesting and mixed boolean chains — but controlled studies still find it only a modest predictor of understandability, not of defects. Treat any such number, from this project or elsewhere, as a structural signal worth a closer read, never as proof on its own.
7
+ This module never computes a complexity score — no cyclomatic number, no cognitive-complexity number — because that requires running an analyser, and everything here is established by reading. If the project already has one committed (a linter's `complexity` rule, a SonarQube report, a CI badge), read it with the evidence in mind rather than at face value: cyclomatic complexity's correlation with real defects is weaker and more contested than it's often assumed to be — a formal critique (Shepperd, "A critique of cyclomatic complexity as a software metric") argues its predictive power may reduce mostly to code size — while a ceiling on the number (historically 10, sometimes relaxed to 15 with strong review and test discipline) remains a defensible *engineering* limit, which is a different and more modest claim than "this number predicts a bug." Cognitive Complexity (SonarSource, 2016–17) is the better-regarded metric specifically for *readability* — it was designed to fix cyclomatic complexity's blind spot for nesting and mixed boolean chains — but controlled studies still find it only a modest predictor of understandability, not of defects. Treat any such number, from this project or elsewhere, as a structural signal worth a closer read, never as proof on its own.
8
8
 
9
9
  ## Structural complexity
10
10
 
11
+ - [ ] If a linter rule, SonarQube profile, or CI check declares its own cyclomatic/cognitive complexity ceiling (`search_code` for a `complexity`/`cognitive-complexity` rule config, threshold, or `max-complexity` setting), `Read` which committed symbols exceed it. This is a narrower and stronger claim than "this number is high" — it is the project's own contributors having already agreed where the line is, and this symbol crossing it. NIST235 frames the 10/15 ceiling as exactly this kind of organizational decision requiring justification to exceed (quoted via Microsoft, official vendor documentation, current, https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-cyclomatic-complexity?view=visualstudio). Refuted if the rule is disabled, suppressed with an inline exception comment, or the ceiling was raised project-wide after this symbol was written — check for a suppression comment or a recent config change before flagging.
11
12
  - [ ] Functions doing more than one thing — the tell is the name: `and`, `or`, `handle`, `process`, `manage`, or a name that describes the caller rather than the operation. `search_code` for definitions matching those verbs, then read each to confirm it does more than its name admits.
12
- - [ ] Deep nesting — three levels of conditionals inside a loop is where off-by-one and missed-branch bugs live. Start from `repo_map`'s central symbols and read each; early returns and guard clauses usually collapse it.
13
+ - [ ] Deep nesting — three levels of conditionals inside a loop is where off-by-one and missed-branch bugs live. Start from `repo_map`'s central symbols and read each; early returns and guard clauses usually collapse it. Cognitive Complexity's own mechanism names this exactly: "each nesting level increases complexity" because "the deeper you go through nested layers, the harder it becomes to keep the context in mind" (SonarSource, official rule documentation, rule S3776, current, https://github.com/SonarSource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3776.html).
13
14
  - [ ] Long parameter lists, especially with several of the same type — `find_symbol` the signature. Every call site is a chance to swap two arguments silently, so cross-check with `find_callers` whether call sites actually differ only by argument order.
14
15
  - [ ] Boolean parameters that select behaviour — `search_code` for call sites with adjacent boolean literals (`, true, false)`, `, false, true)`). `render(true, false)` at the call site tells the reader nothing without opening the definition.
16
+ - [ ] A boolean, enum, or bitflag whose actual meaning at a given read site depends on which code version, environment, or execution path is live — not on anything the type system enforces. `find_callers` every read site of the flag and confirm they agree on what each value means; a comment or dead branch implying the value once meant something else, or two call sites making incompatible assumptions about it, is the exact defect class that turned a routine feature addition into a real production incident elsewhere: Knight Capital's flag word ran out of new bits, "so an engineer reused a bit from a deprecated flag: the power peg flag," and one still-live server silently reinterpreted it as the old, years-dormant meaning, costing $460M (Speculative Branches, public post-mortem analysis, 2012 incident, https://specbranch.com/posts/knight-capital/). Refuted if all read sites are proven to derive the flag's meaning from a shared, type-enforced source (an enum with no legacy aliasing, a single well-named boolean with one caller pattern) rather than from ambient context.
15
17
  - [ ] Functions whose control flow depends on the *caller's* state rather than their arguments — read the function body for a reference to module-level or global state, then `find_callers` to confirm different callers rely on different ambient state to get different behaviour.
16
18
 
17
19
  ## Coupling
18
20
 
19
- - [ ] `impact` on the central symbols: how much of the codebase must be re-verified to change one of them? A high number is not automatically wrong, but it must be intentional.
20
- - [ ] Modules that import from many others — `find_callees` at module granularity. A module with a long callee list is coupled to all of them at once.
21
+ - [ ] `impact` on the central symbols: how much of the codebase must be re-verified to change one of them? A high number is not automatically wrong, but it must be intentional. Across the empirical fault-proneness studies surveyed, "coupling, complexity and inheritance metrics are the most significant predictors of faults in software," with coupling the strongest of the three (survey of multiple empirical fault-proneness studies, arXiv preprint, 2025, https://arxiv.org/html/2504.08230v1).
22
+ - [ ] Modules that import from many others — `find_callees` at module granularity, and compare the callee count against its peer modules' median; a count several times its peers' median is coupled to all of them at once. Rule out: a module whose stated role is to aggregate or wire up others (a facade, an orchestrator, a DI container) is expected to import broadly — confirm the module isn't one of these before flagging.
23
+ - [ ] High fan-in as its own signal, not just fan-out: `find_callers` on `repo_map`'s central symbols and compare the caller count against its peers' median, the same way the fan-out check above compares `find_callees` counts. A symbol whose caller count is several times its peers' median, with no interface/contract layer justifying the concentration, means every one of those callers is coupled to this symbol's exact current behaviour — any change forces re-verifying all of them, not just review of one function. Coupling metrics (the OO analogue of fan-in) repeatedly correlate with fault-proneness across the studies surveyed above, though the survey itself caveats this doesn't generalize to every system (survey of multiple empirical fault-proneness studies, arXiv preprint, 2025, https://arxiv.org/html/2504.08230v1) — which is why this stays Medium rather than claiming the correlation directly for this codebase. Refuted if the symbol is a small, stable interface (an exported type, a constant, a pure utility with no internal state) where high fan-in is the intended and safe shape — confirm the symbol's own internal complexity before flagging the combination as risky.
21
24
  - [ ] Cyclic dependencies — `trace_path` from a module back to itself. A cycle means neither side can be understood alone.
22
25
  - [ ] Shared mutable state as a coupling mechanism — `search_code` for an exported `let` or a mutable singleton, then `find_callers` on it. Two unrelated modules both writing to it are coupled without an interface.
23
26
  - [ ] Reaching through an object to its internals (`a.b.c.d`) — `search_code` the deepest access chain seen while reading a central module. Each additional segment is one more assumption the caller makes about the callee's internal shape.
@@ -25,17 +28,17 @@ This module never computes a complexity score — no cyclomatic number, no cogni
25
28
  ## Duplication that matters
26
29
 
27
30
  - [ ] Duplicated *logic*, not duplicated *shape*. Two functions with the same structure and different meaning should stay separate; two encoding the same rule must not. Once `search_code` surfaces structurally similar functions (same branch count, same operation order), read both bodies side by side to tell which case you're in.
28
- - [ ] The same business rule expressed in more than one place — a validation, a threshold, a format. `search_code` the literal value (a magic number, a regex, a status string) across the repo; more than one hit outside a shared constant is the finding.
31
+ - [ ] The same business rule expressed in more than one place — a validation, a threshold, a format. `search_code` the literal value (a magic number, a regex, a status string) across the repo; more than one hit outside a shared constant is the finding. Rule out: two hits that coincidentally share the same literal for unrelated purposes (a retry count of 3 next to an unrelated array size of 3) are not the finding — confirm both hits encode the same rule, not merely the same numeric value, before flagging.
29
32
  - [ ] Magic values repeated across files — `search_code` the literal. One named constant, one place to change.
30
- - [ ] Premature deduplication is its own finding — `find_callers` on the shared abstraction. A count of one caller, plus three parameters that only exist to serve it, is complexity added for a reuse that never happened.
31
- - [ ] An abstraction serving two or more callers that has grown parameters or conditionals existing only to accommodate one caller's divergence — `find_callers` the shared function or component and read what each call site actually needs from it. When the callers no longer share the same *reason* to call it, even though the code path is still shared, this is the wrong abstraction (Sandi Metz, "The Wrong Abstraction," 2016): the fix is to inline it back into each caller and let the duplication return, not add another parameter to keep forcing them together. This is the same smell as the one-caller case above, one caller further along — and more damaging, because it's now a live complexity tax on real call sites instead of unused generality.
33
+ - [ ] Premature deduplication is its own finding — `find_callers` on the shared abstraction. A count of one caller, plus three parameters that only exist to serve it, is complexity added for a reuse that never happened. Google's own review guidance flags exactly this: solve "the problem they know needs to be solved now, not the problem that the developer speculates might need to be solved in the future" (Google, official engineering guide, current, https://google.github.io/eng-practices/review/reviewer/looking-for.html).
34
+ - [ ] An abstraction serving two or more callers that has grown parameters or conditionals existing only to accommodate one caller's divergence — `find_callers` the shared function or component and read what each call site actually needs from it. When the callers no longer share the same *reason* to call it, even though the code path is still shared, this is the wrong abstraction (Sandi Metz, "The Wrong Abstraction," 2016, https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction): the fix is to inline it back into each caller and let the duplication return, not add another parameter to keep forcing them together — "duplication is far cheaper than the wrong abstraction." This is the same smell as the one-caller case above, one caller further along — and more damaging, because it's now a live complexity tax on real call sites instead of unused generality.
32
35
 
33
36
  ## Cognitive load
34
37
 
35
- - [ ] Names that require reading the implementation to understand — predict the function's behaviour from its name alone, then read the body and check the prediction held. Cross-reference the naming-drift check in `functional.md`.
38
+ - [ ] Names that require reading the implementation to understand — predict the function's behaviour from its name alone, then `Read` the body and check the prediction held. Cross-reference the naming-drift check in `functional.md`.
36
39
  - [ ] Implicit ordering requirements — "call `init` before `run`" enforced only by convention — `find_callers` on the second call to check every call site actually calls the first one first, and whether anything enforces it structurally (a state check, a type that only exists post-init) rather than by convention alone.
37
- - [ ] Non-obvious code with no comment explaining *why* — read the functions `repo_map` and `impact` flag as central. Comments restating *what* the code does are noise; a missing *why* on a surprising line is a real gap.
38
- - [ ] Conditionals whose branches are hard to enumerate — `search_code` for nested ternaries (`? ... ? ... :`) and `switch` statements missing a `break` before the next `case`.
40
+ - [ ] Non-obvious code with no comment explaining *why* — `Read` the functions `repo_map` and `impact` flag as central. Comments restating *what* the code does are noise; the failure condition is a line that contradicts what the surrounding code implies, a workaround with no linked issue, or a magic exception to an otherwise-consistent pattern, with no comment explaining it — that missing *why* is a real gap.
41
+ - [ ] Conditionals whose branches are hard to enumerate — `search_code` for nested ternaries (`? ... ? ... :`) and `switch` statements missing a `break` before the next `case`. A nested ternary reads as one expression but branches like a `switch` — each additional `?:` is a decision point that raises cyclomatic complexity the same way a nested `if` does, and it does so without the visual indentation that would make the branching obvious on a skim — practitioner heuristic, no source found for the claim at the specific level of nested ternaries.
39
42
 
40
43
  ## Dead weight
41
44
 
@@ -44,19 +47,26 @@ Report these under `Reachability` rather than here, but look for them while read
44
47
  ## Out of static reach
45
48
 
46
49
  - Whether a high-blast-radius symbol is actually risky in practice, or merely central and rarely touched — call-graph centrality is not change frequency; cross-reference `repo-history.md` for that signal.
47
- - Whether coupling through shared state actually causes incorrect behaviour, which depends on execution order this module cannot observe.
50
+ - Whether coupling through shared state actually causes incorrect behaviour, which depends on execution order this module cannot observe — closed by `runtime.md`'s repeated and reordered test runs when execution is enabled, which can surface an order-dependent failure tied to this coupling, bounded by what those runs sample.
48
51
  - Whether a reader genuinely finds a given structure confusing — cognitive load is inferred from shape, not measured from a person.
49
- - Whether an implicit ordering requirement has ever actually been violated in production.
52
+ - Whether an implicit ordering requirement has ever actually been violated in production — closed by `runtime.md`'s repeated (`n/10`) and reordered test runs when execution is enabled, bounded by what those runs sample.
50
53
  - Whether the same rule reimplemented across services (a validation duplicated in a mobile client, say) is intentional platform divergence or drift — this module sees one repo at a time.
51
54
  - Whether a reported complexity score (cyclomatic, cognitive, or otherwise) has ever correlated with an actual defect in this codebase specifically — the general research correlating either metric with real-world bug density is weaker than commonly assumed, and settling it here would require the historical defect data this module doesn't have.
55
+ - Whether cutting this symbol's complexity would have prevented a past incident — that requires the incident record and a controlled comparison this module doesn't have.
56
+ - Whether the project's complexity tooling computes the number correctly — this module reads what it reports, it does not re-derive it.
57
+ - Whether this codebase's complexity has a measurable cost in onboarding time — that is an organizational metric, not a structural one.
52
58
 
53
59
  ## Severity guidance
54
60
 
55
61
  | Situation | Severity |
56
62
  |---|---|
57
63
  | High-blast-radius symbol that is also internally complex | High |
64
+ | Flag/enum whose meaning is inferred from ambient context, and read sites disagree on it | High |
65
+ | Committed symbol exceeds the project's own declared complexity ceiling | Medium |
66
+ | High fan-in on a central symbol, no interface/contract layer justifying the concentration | Medium |
58
67
  | The same business rule duplicated in more than one place | Medium |
59
68
  | Cyclic dependency between modules | Medium |
69
+ | Module importing far more than its peers, with no aggregator/facade role justifying it | Medium |
60
70
  | Implicit call-ordering requirement with no enforcement | Medium |
61
71
  | Deeply nested control flow on a correctness-critical path | Medium |
62
72
  | Shared abstraction kept alive with extra parameters for callers that no longer agree (the wrong abstraction) | Medium |
@@ -6,46 +6,58 @@ Concurrency defects are the ones that pass every test and fail in production, be
6
6
 
7
7
  ## Shared mutable state
8
8
 
9
- - [ ] Identify every piece of state reachable from more than one concurrent path. `find_callers` on each module-level mutable binding — more than one caller on different paths is a candidate.
10
- - [ ] Module-level `let`, mutable singletons, and caches populated lazily: `search_code` for a module-scope `let`/static field, or a lazy-init guard (`if (!cache) cache = …`). Lazy initialisation under concurrency initialises twice — the second caller reads a half-built value or triggers the expensive setup a second time.
11
- - [ ] Objects passed by reference to concurrent consumers and mutated by any of them: `find_callers` on the function that hands out the reference, then read each caller for an in-place mutation (`.push`, a property assignment) instead of a read-only use.
9
+ - [ ] Identify every piece of state reachable from more than one concurrent path. `find_callers` on each module-level mutable binding — more than one caller on different paths is a candidate. A shared resource with a timing window in which another concurrent sequence can modify it is the general race condition, not only an attacker-triggered one (MITRE, CWE-362, current, https://cwe.mitre.org/data/definitions/362.html).
10
+ - [ ] Module-level `let`, mutable singletons, and caches populated lazily: `search_code` for a module-scope `let`/static field, or a lazy-init guard (`if (!cache) cache = …`). Lazy initialisation under concurrency initialises twice — the second caller reads a half-built value or triggers the expensive setup a second time, because the reference-store and the field-initialising writes can be reordered with no further synchronisation (Pugh et al., Java Memory Model reference, University of Maryland, 2004, https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html). Rule out first: confirm the two call paths found via `find_callers` above can actually be in flight at the same time (same process, both reachable after startup) — mutually exclusive entry points (a CLI path vs. a server path) or a single-threaded startup phase are not racy even though two callers exist.
11
+ - [ ] Objects passed by reference to concurrent consumers and mutated by any of them: `find_callers` on the function that hands out the reference, then read each caller for an in-place mutation (`.push`, a property assignment) instead of a read-only use (MITRE, CWE-362, current, https://cwe.mitre.org/data/definitions/362.html).
12
12
 
13
13
  ## Read-modify-write
14
14
 
15
- - [ ] Every read-then-write sequence on shared state: `search_code` for `+= 1`/`++` on a stored field, `findOrCreate`, `getOrCreate`, or a `SELECT` immediately followed by an `INSERT`/`UPDATE` in the same function. Between the read and the write, another actor can change it. Look for: counters, "check then create", "find or insert", version bumps, balance updates.
16
- - [ ] The fix must be visible at the site found above: read it for an atomic operation, a compare-and-swap, a row lock, or a unique constraint. A comment saying it is safe is not a mechanism — if the site has none of these, it is the finding regardless of how it reads.
17
- - [ ] `check-then-act` on the filesystem: `search_code` for `existsSync(` followed by a nearby `writeFile`/`mkdirSync` — the check and the act are two operations, and anything can happen between them. Prefer atomic create or accept-and-handle-the-error.
15
+ - [ ] Every read-then-write sequence on **in-process** shared state: `search_code` for `+= 1`/`++` on a stored field, or a `findOrCreate`/`getOrCreate` pattern operating on an in-memory or cache store. Between the read and the write, another actor can change it — the interfering sequence can be trusted, internal code, not only an attacker (MITRE, CWE-362, current, https://cwe.mitre.org/data/definitions/362.html). Look for: counters, "check then create", "find or insert", version bumps, balance updates. Row-level read-modify-write against the database — a `SELECT` immediately followed by an `INSERT`/`UPDATE` on the same row — is `database.md`'s check (`search_code` for the same pattern against a table row); cross-reference it there instead of re-reporting here.
16
+ - [ ] The fix must be visible at the site found above: Read it for an atomic operation, a compare-and-swap, a unique constraint, or an advisory/distributed lock. A comment saying it is safe is not a mechanism — if the site has none of these, it is the finding regardless of how it reads (MITRE, CWE-367, current, https://cwe.mitre.org/data/definitions/367.html — mitigations named are eliminating the check, minimising the gap when atomicity is impossible, locking before checking, or re-verifying after use).
17
+ - [ ] `check-then-act` on the filesystem: `search_code` for `existsSync(` followed by a nearby `writeFile`/`mkdirSync` — the check and the act are two operations, and anything can happen between them (MITRE, CWE-367 (TOCTOU), current, https://cwe.mitre.org/data/definitions/367.html). Prefer atomic create or accept-and-handle-the-error.
18
18
 
19
19
  ## Ordering
20
20
 
21
- - [ ] `Promise.all` over operations with hidden interdependencies: `search_code` for `Promise.all(`, then read each operand for a dependency on another operand in the same array — they will interleave, not run in the order they are written.
22
- - [ ] Fire-and-forget calls whose effects a later step assumes: `search_code` for an async call with no `await` and no `.then`/`.catch`, then `find_callers` on the caller's caller to check whether a subsequent step relies on the fired-off work having finished.
21
+ - [ ] `Promise.all` over operations with hidden interdependencies: `search_code` for `Promise.all(`, then read each operand for a dependency on another operand in the same array — they will interleave, not run in the order they are written; the resolved array is ordered by array position, "regardless of completion order" (MDN Web Docs, current, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).
22
+ - [ ] Fire-and-forget calls whose effects a later step assumes: `search_code` for an async call with no `await` and no `.then`/`.catch`, then `find_callers` on the caller's caller to check whether a subsequent step relies on the fired-off work having finished. An unhandled rejection on that call is "emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop" (Node.js project, official API docs, current, https://nodejs.org/api/process.html#event-unhandledrejection).
23
+ - [ ] For each fire-and-forget call found above, `search_code` for a `.catch(` on that same call or a process-level `process.on('unhandledRejection', ...)` handler, and `Read` the project's declared Node engine version (`package.json` `engines.node` or an `.nvmrc`/Dockerfile base image tag). Recent Node defaults raise an unhandled rejection as an uncaught exception (Node.js project, official API docs, current, https://nodejs.org/api/process.html#event-unhandledrejection): a fire-and-forget call with neither a local `.catch` nor a global handler does not just lose its own effect on Node.js 15+, it can take the whole process down on the next tick it rejects on. Refuted if a global `unhandledRejection` handler exists and does not itself call `process.exit`/rethrow — the process survives, and the finding reduces to the "lost effect" case above.
23
24
  - [ ] Event handlers that can be re-entered before the previous invocation finishes: `search_code` for `.on(`/`addEventListener` registering an `async` callback, then read it for an in-flight guard (a boolean flag, a lock) before the next event can start processing.
24
- - [ ] A queue message or job whose visibility/lease timeout can expire mid-processing, letting a second worker pick it up while the first is still running: `search_code` for a heartbeat/lease-extension call (SQS's `ChangeMessageVisibility`, a job-lock renewal) inside a handler whose runtime can exceed the queue's timeout — SQS's own default visibility timeout is 30 seconds. Its absence on a handler with real duration is the finding: two workers now hold the same logical message concurrently, and whatever the handler writes is a read-modify-write race between them.
25
+ - [ ] A queue message or job whose visibility/lease timeout can expire mid-processing, letting a second worker pick it up while the first is still running: `search_code` for a heartbeat/lease-extension call (SQS's `ChangeMessageVisibility`, a job-lock renewal) inside a handler whose runtime can exceed the queue's timeout — SQS's own default visibility timeout is 30 seconds, but rule out a longer configured value first: `search_code` the IaC/deploy config for the queue resource's own `VisibilityTimeout` setting, since a project can override the default to something already generous enough that this handler never approaches it (AWS, SQS Developer Guide, current, https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html). Its absence on a handler with real duration exceeding the configured timeout is the finding: two workers now hold the same logical message concurrently, and whatever the handler writes is a read-modify-write race between them.
26
+ - [ ] Where a heartbeat/lease-renewal call was found (the check above), `Read` the handler for whether its total possible runtime is bounded (a fixed batch size, a hard iteration cap) rather than open-ended (unbounded pagination, an external call with no timeout of its own). A renewal call proves the handler survives past the *configured* timeout, not past the queue's own hard ceiling — extending the timeout does not reset SQS's 12-hour limit from first receipt (AWS, SQS Developer Guide, current, https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html). Refuted if the handler is chunked into multiple messages/steps by design (e.g. re-enqueues its own continuation) rather than processing one unbounded unit of work under one lease.
25
27
 
26
28
  ## Locks and resources
27
29
 
28
- - [ ] Locks are always released, including on the error path: `search_code` for the lock/mutex acquire call (`.lock(`, `acquireLock`, `withLock`), then read whether the matching release sits in a `finally` block. A lock held through a throw is a permanent deadlock.
29
- - [ ] Lock acquisition order is consistent everywhere: collect every acquire site found above and list the resources each one locks, in order — two sites taking A-then-B and B-then-A deadlock.
30
- - [ ] Locks have a timeout or a lease: `search_code` the lock library's usage for a `timeout`/`ttl`/`lease` argument at each acquire site. Its absence means a dead holder blocks forever.
31
- - [ ] Nothing does I/O while holding a lock longer than necessary: read the code between each acquire and its release for a network or database call inside the critical section.
30
+ - [ ] Locks are always released, including on the error path: `search_code` for the lock/mutex acquire call (`.lock(`, `acquireLock`, `withLock`), then Read whether the matching release sits in a `finally` block. A lock held through a throw is a permanent deadlock. This is the detailed elaboration of `backend.md`'s general acquired-resource-release check, scoped specifically to locks — cross-reference it rather than treating this as a separate finding.
31
+ - [ ] Lock acquisition order is consistent everywhere. Read every acquire site found above and list the resources each one locks, in order — two sites taking A-then-B and B-then-A deadlock, the same circular wait as the canonical two-thread, two-lock example (Oracle, Java Tutorials, current, https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html).
32
+ - [ ] Locks have a timeout or a lease: `search_code` the lock library's usage for a `timeout`/`ttl`/`lease` argument at each acquire site. Its absence means a dead holder blocks forever, and even a holder that merely pauses past its lease (e.g. a GC pause) can resume unaware the lease expired and act after a second client has already acquired the lock (Martin Kleppmann, 2016, https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html).
33
+ - [ ] Where a lock acquire site found above protects a write to a resource outside the process (a database row, an object store, a downstream API call), `search_code` the write call for a monotonically increasing token/version argument passed alongside it and `Read` the resource's own handler for a check that rejects a token lower than the last one it accepted. A lock with a timeout but no such fencing token at the point of use is not proven safe against a holder that resumes after its lease expired — it is a narrower, unproven case of the check above, since "a lease/timeout alone does not stop a paused holder from writing after expiry; only a fencing token enforced at the resource does" (Martin Kleppmann, 2016, https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html — Redlock in particular "does not have any facility for generating fencing tokens"). Refuted if the lock service itself guarantees the holder is fenced off before the lease expires (e.g. a consensus-backed lock that revokes the holder's session, not merely its own local timer) — cite the lock library's own documented guarantee before treating the timeout-only case as unsafe.
34
+ - [ ] Nothing does I/O while holding a lock longer than necessary: Read the code between each acquire and its release for a network or database call inside the critical section.
32
35
 
33
36
  ## Cancellation
34
37
 
35
- - [ ] Long operations are cancellable, and cancellation actually stops work: `search_code` for `AbortController`/`AbortSignal`/a cancellation-token parameter on functions identified as long-running via `find_callees` (a loop or a chain of awaits). Its absence on an operation with real duration is the finding.
36
- - [ ] Cancelled operations clean up: read the abort handler (`signal.addEventListener('abort', …)` or equivalent) for resource release or rollback — a cancellation that only stops listening, without releasing what it held, leaks.
38
+ - [ ] Long operations are cancellable, and cancellation actually stops work: `search_code` for `AbortController`/`AbortSignal`/a cancellation-token parameter on functions identified as long-running via `find_callees` (a loop or a chain of awaits). Its absence on an operation with real duration is the finding — `AbortController.abort()` is the documented mechanism to "abort an asynchronous operation before it has completed" (MDN Web Docs, current, https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
39
+ - [ ] Cancelled operations clean up: Read the abort handler (`signal.addEventListener('abort', …)` or equivalent) for resource release or rollback — a cancellation that only stops listening, without releasing what it held, leaks. The signal documents only that the operation is notified, not that any resource it held is released (MDN Web Docs, current, https://developer.mozilla.org/en-US/docs/Web/API/AbortController) — that remains the responsibility of the code consuming the signal.
37
40
  - [ ] A late result from a cancelled or superseded operation cannot overwrite a newer one: `search_code` for a stored "latest request id"/sequence number compared before a result is applied (`if (id !== latestId) return`). Its absence on a handler triggered by rapid repeated calls (search, autocomplete, a fast double-click) is the finding — the same defect as the unmounted-component write in `frontend.md`.
38
41
 
39
42
  ## Signals and shutdown
40
43
 
41
- - [ ] In-flight work completes or is safely abandoned on shutdown: `search_code` for `process.on('SIGTERM'`/`'SIGINT'`, then read whether the handler awaits outstanding work before exiting.
42
- - [ ] Shutdown is bounded: read the shutdown handler for a forced-exit timeout wrapping the drain. Its absence means a hang on drain never resolves — worse than a forced exit.
44
+ - [ ] In-flight work completes or is safely abandoned on shutdown: `search_code` for `process.on('SIGTERM'`/`'SIGINT'`, then read whether the handler awaits outstanding work before exiting — a pod's termination grace period defaults to 30 seconds before SIGKILL follows SIGTERM (Kubernetes project, official documentation, current, https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/).
45
+ - [ ] Shutdown is bounded: Read the shutdown handler for a forced-exit timeout wrapping the drain. Its absence means a hang on drain never resolves cleanly on its own terms — the orchestrator's grace period elapses and SIGKILL follows, killing the process mid-work instead of letting it exit on a bounded timeout of its own (Kubernetes project, official documentation, current, https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/).
43
46
  - [ ] Persistent handles are closed on every exit path: for each resource opened elsewhere (`find_symbol` the db pool, WAL, or file-lock construction), `search_code` the shutdown handler for a matching `.close()`/`.end()`/`.disconnect()` call.
44
47
 
45
48
  ## Reporting
46
49
 
47
50
  State each finding as an interleaving: "if A reaches line X while B is between lines Y and Z, then …". A concurrency finding without a concrete interleaving is unfalsifiable, and reviewers correctly dismiss it.
48
51
 
52
+ ## What browser observation closes
53
+
54
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number. Concurrency defects are mostly interleavings inside a single process or across backend workers, invisible to a browser walking one flow in one tab — the bundle reaches only the narrow slice that is user-triggerable through rapid repeated interaction in the UI itself.
55
+
56
+ | Artefact | Gap it closes | Observed instance earns |
57
+ |---|---|---|
58
+ | `network.jsonl` (two requests from one action), `screenshots/` + `final-state.md` | A rapid double-click/double-submit on the same control fires two requests and produces a duplicated side effect. Refuted if the screenshot taken immediately after the first click already shows the control in a disabled/pending visual state before the second click was issued — `steps.md` records one timestamp per step, not per click, so ordering is read from the step sequence and the screenshot, not from a per-click timestamp. | Medium |
59
+ | `network.jsonl` (request/response timestamps out of order), `steps.md`/`final-state.md` | A fast repeated interaction (retype in a search/filter box) renders a stale result after a fresher one. Refuted if the rendered content matches the latest input despite out-of-order network arrival — a sequence guard is working even though the bundle alone can't see it in source. | Medium |
60
+
49
61
  ## Out of static reach
50
62
 
51
63
  - Whether the interleaving described actually occurs under real load — thread/event-loop scheduling is not observable from source.
@@ -53,17 +65,23 @@ State each finding as an interleaving: "if A reaches line X while B is between l
53
65
  - Whether a race is merely possible or actually hit within any realistic time window.
54
66
  - Actual behaviour of the runtime's scheduler or garbage collector during the interleaving.
55
67
  - Whether a shutdown timeout value is long enough for real in-flight work to drain.
68
+ - Whether the machines involved in a lease-based lock have clocks close enough together for the lease window to mean what the code assumes — this module reads the timeout value, not the clock skew between the processes honoring it.
69
+ - Whether a resource guarded by a fencing token is only ever written through this codebase, or also reachable from a service or script this index does not cover — an unindexed writer bypasses the fencing check by definition.
70
+ - Whether this project's actual message broker redelivers on a timer the way the check's SQS-derived example assumes, or on a different trigger (consumer rebalance, explicit nack) — confirm the broker before applying the SQS-shaped fix.
56
71
 
57
72
  ## Severity guidance
58
73
 
59
74
  | Situation | Severity |
60
75
  |---|---|
61
- | Read-modify-write on shared state with no atomicity | High |
76
+ | Read-modify-write on in-process or cache state with no atomicity | High |
62
77
  | Lock not released on the error path | High |
63
78
  | Inconsistent lock ordering across paths | High |
64
79
  | Message/job redelivered on lease expiry while the original worker is still processing it | High |
80
+ | Distributed lock protecting a write with no fencing token at the resource | High |
81
+ | Fire-and-forget call with no local `.catch` or global handler on Node.js 15+ (unhandled rejection can crash the process) | High |
65
82
  | Late result overwriting a newer one | Medium |
66
83
  | Lazy initialisation racing to initialise twice | Medium |
67
84
  | Unawaited async call whose effect is later assumed | Medium |
68
85
  | Non-cancellable long operation | Medium |
86
+ | Heartbeat/lease renewal on a handler whose total runtime can exceed the queue's own hard ceiling | Medium |
69
87
  | Unbounded shutdown drain | Low |
@@ -6,11 +6,11 @@ The method here is comparison, not judgement. Find the dominant pattern with `se
6
6
 
7
7
  ## Naming
8
8
 
9
- - [ ] Casing conventions per kind of thing (files, functions, types, constants, config keys) — `search_code` a sample of declarations for each kind, tally the casing style, and treat whichever covers the large majority as the standard. List every declaration using the other style.
9
+ - [ ] Casing conventions per kind of thing (files, functions, types, constants, config keys) — `search_code` a sample of declarations for each kind, tally the casing style, and treat whichever covers the large majority as the standard. List every declaration using the other style. Naming-convention adoption *consistency* differs sharply by language community: camelCase/PascalCase dominate and Hungarian notation is declining, but how uniformly a codebase actually applies its own nominal convention varies by ecosystem (empirical study of 48 open-source Java/C/C++ projects, arXiv preprint, 2014, https://arxiv.org/abs/1401.5300); Google's own style guide prescribes a specific casing per kind of identifier in one table — modules/functions/variables `lower_with_under`, classes `CapWords`, constants `CAPS_WITH_UNDER` (Google, Google Python Style Guide, official vendor/OSS style guide, current, https://google.github.io/styleguide/pyguide.html) — the same "one rule per kind of thing" shape this check verifies.
10
10
  - [ ] The same concept has the same name everywhere — `search_code` each candidate synonym (`user` / `account` / `member` for one entity) and compare hit counts. The minority name is the deviation, not automatically wrong, but it is a second mental model for one thing.
11
11
  - [ ] Opposite operations use symmetric names — `search_code` one half of a known pair (`open`) and check whether its counterpart in the same module is `close` or something asymmetric like `dispose`.
12
12
  - [ ] Boolean names read as assertions — `search_code` boolean-typed declarations or props; count how many use an `is`/`has`/`can` prefix versus a bare noun, and list the noun-named minority.
13
- - [ ] Abbreviations are used consistently or not at all — `search_code` a common abbreviation (`cfg`, `ctx`, `mgr`, `req`/`res`) alongside its spelled-out form; whichever wins the majority is the convention.
13
+ - [ ] Abbreviations are used consistently or not at all — `search_code` a common abbreviation (`cfg`, `ctx`, `mgr`, `req`/`res`) alongside its spelled-out form; whichever wins the majority is the convention. Google's own guidance: "do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word" (Google, Google Python Style Guide, official vendor/OSS style guide, current, https://google.github.io/styleguide/pyguide.html).
14
14
 
15
15
  ## Structure
16
16
 
@@ -23,14 +23,16 @@ The method here is comparison, not judgement. Find the dominant pattern with `se
23
23
 
24
24
  - [ ] One way to do each recurring thing: error creation, logging, config reading, async style, validation — `search_code` each candidate (`new Error(`, a custom error factory, `console.log` vs. the logger import, `process.env.` vs. a config module) and tally which one the codebase actually uses.
25
25
  - [ ] Async style is uniform — `search_code` for `.then(`, `async function`/`await`, and callback-style signatures (`(err, data) =>`) doing comparable work. Mixed styles for the same kind of operation forces the reader to context-switch.
26
- - [ ] Error handling shape is uniform — `search_code` for `throw new` versus a return-result shape (`{ ok: false`, `Result<`, `[error, data]`). A codebase using both for the same kind of failure has two error-handling mental models live at once.
27
- - [ ] Data validation happens at consistent boundaries — `search_code` the validation library's call sites (`.parse(`, `.validate(`) and note whether they cluster at the route/entry layer or are scattered three layers deep in some services and not others.
28
- - [ ] Immutability conventions are consistent — `search_code` for mutating methods (`.push(`, `.splice(`, `+=` on a declared `const` object) against the dominant style found elsewhere. If most code avoids mutation, the places that mutate need a reason.
26
+ - [ ] Error handling shape is uniform — `search_code` for `throw new` versus a return-result shape (`{ ok: false`, `Result<`, `[error, data]`). A codebase using both for the same kind of failure has two error-handling mental models live at once. Microsoft's own REST API Guidelines mandate a single error shape precisely so callers "write one piece of code that handles errors consistently" instead of per-endpoint logic (Microsoft, Microsoft REST API Guidelines, official framework/vendor documentation, current, https://github.com/microsoft/api-guidelines/blob/master/Guidelines.md); inconsistent error text for the same failure class is not only a readability cost, it can leak information — "even when error messages don't provide a lot of detail, inconsistencies in such messages can still reveal important clues on how a site works," the canonical example being "file not found" versus "access denied" disclosing that a restricted file exists (OWASP Foundation, official OWASP Community Page, current, https://owasp.org/www-community/Improper_Error_Handling).
27
+ - [ ] For error-handling shape inconsistency found above, when the two shapes handle the *same class of caller-facing failure* (authentication, authorization, or resource-existence), name it to `security.md` in addition to `consistency.md`. Compare the actual response text/shape for each path with `search_code`, then `trace_path` (or `find_callers`) from a public entry point to confirm both differing paths are reachable through the same external interface before raising it as an information-disclosure finding rather than a private internal inconsistency — the "file not found" vs. "access denied" disclosure is the canonical instance of this exact defect class (OWASP Foundation, official OWASP Community Page, current, https://owasp.org/www-community/Improper_Error_Handling), and a single API is expected to have one error shape in the first place, which is what makes the divergence notable (Microsoft, Microsoft REST API Guidelines, official framework/vendor documentation, current, https://github.com/microsoft/api-guidelines/blob/master/Guidelines.md). Refuted if the two differing responses are not both reachable by an unauthenticated/unprivileged caller (e.g. one path is admin-only and already assumes trust) — the reachability trace is exactly what rules this out.
28
+ - [ ] Data validation happens at consistent boundaries — `search_code` the validation library's call sites (`.parse(`, `.validate(`) and note whether they cluster at the route/entry layer or are scattered three layers deep in some services and not others. Input validation "must be implemented on the server-side before any data is processed," and "as early as possible in the data flow" (OWASP Foundation, OWASP Cheat Sheet Series, official project documentation, current, https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html) — the consistent-boundary layer this check verifies is what "as early as possible" looks like in practice.
29
+ - [ ] Once the dominant validation-call-site layer is established (e.g. every route handler calls `.parse(`/`.validate(` before its body), run `find_callees` on each sibling entry point at that same layer. An entry point whose callee set contains no validation call, where every sibling at the same layer has one, is a traced absence — report it to `security.md` as an unvalidated boundary, since input validation "must be implemented on the server-side before any data is processed" (OWASP Foundation, OWASP Cheat Sheet Series, official project documentation, current, https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html), not merely to `consistency.md` at the module's default inconsistency severity. Refuted if the entry point's own body performs equivalent checks inline (manual type/shape guards) rather than calling the shared validator — read the body before concluding the boundary is genuinely unvalidated, since the deviation might be idiom drift (back to the plain consistency finding) rather than an actual missing check.
30
+ - [ ] Immutability conventions are consistent — `search_code` for mutating methods (`.push(`, `.splice(`, `+=` on a declared `const` object) against the dominant style found elsewhere. If most code avoids mutation, the places that mutate need a reason: check for an adjacent comment or rationale (a perf-critical hot path note, an explicit justification) at the mutating site before flagging it as an unexplained deviation.
29
31
 
30
32
  ## Interfaces
31
33
 
32
34
  - [ ] Functions with the same role have the same signature shape — `find_symbol` a handful of same-role functions (every repository `findBy*`, say) and diff their parameter shape: options object vs. positional, sync vs. async, same parameter order.
33
- - [ ] Return shapes are consistent for the same kind of operation — `find_symbol` the same set and compare return types; a mix of throwing and returning `null` for "not found" across otherwise-identical functions is the deviation. Cross-reference the output-correctness check in `functional.md`.
35
+ - [ ] Return shapes are consistent for the same kind of operation — `find_symbol` the same set and compare return types; a mix of throwing and returning `null` for "not found" across otherwise-identical functions is the deviation. The same expectation the module already applies to errors — "developers SHOULD be able to write one piece of code that handles [outcomes] consistently" (Microsoft, Microsoft REST API Guidelines, official framework/vendor documentation, current, https://github.com/microsoft/api-guidelines/blob/master/Guidelines.md) — applies equally to return shape. Cross-reference the output-correctness check in `functional.md`.
34
36
  - [ ] Null vs. undefined vs. empty-collection means the same thing throughout — `search_code` for `=== null`, `=== undefined`, and `.length === 0` used as "nothing here" checks across different modules; if all three appear for the same semantic case, the meaning has drifted.
35
37
  - [ ] Optional parameters appear in the same position and default the same way — `find_symbol` the same function set and compare where the optional parameter sits and what its default is.
36
38
 
@@ -38,13 +40,27 @@ The method here is comparison, not judgement. Find the dominant pattern with `se
38
40
 
39
41
  - [ ] Comment style and density are uniform — `search_code` the doc-comment marker (`/**`, `///`) and compare its count against the number of exported symbols from `find_symbol`. Partial coverage across an otherwise-documented module reads as intentional gaps, which is worse than no documentation at all.
40
42
  - [ ] The documentation format is one format — `search_code` for competing doc styles (JSDoc blocks vs. plain `//` prose vs. a separate doc generator's syntax) and confirm one wins.
41
- - [ ] Comments are current — for any comment making a factual claim about behaviour ("closes the connection", "always returns non-null"), read the code directly beneath it and confirm the claim still holds. A comment contradicting its code is `Medium` — readers trust comments, and this one lies. This is exactly how the "Close without binding" comment in this repo's own HTTP test came to mislead.
43
+ - [ ] Comments are current — for any comment making a factual claim about behaviour ("closes the connection", "always returns non-null"), Read the code directly beneath it and confirm the claim still holds. A comment contradicting its code is `Medium` — readers trust comments, and this one lies. This is exactly how the "Close without binding" comment in this repo's own HTTP test came to mislead. Comment-code inconsistency is measurably associated with what comes next: "inconsistent changes are around 1.5 times more likely to lead to a bug-introducing commit than consistent changes," with the effect largest immediately after the drift appears (empirical study using GPT-3.5 + odds-ratio analysis, arXiv preprint, 2024, https://arxiv.org/abs/2409.10781).
44
+ - [ ] For a comment flagged above that makes a safety claim about a value ("always returns non-null", "never throws", "closes the connection"), before capping the finding at the module's default `Medium`, run `find_callers` on the commented function; if a caller uses the return value without a null/error check (or without a corresponding cleanup call), the comment is not just stale — it is actively misleading a specific call site, and the finding is `High`, not `Medium`. This is exactly the situation the effect above is largest in: a caller written against the comment's now-false promise, right after the drift starts (empirical study using GPT-3.5 + odds-ratio analysis, arXiv preprint, 2024, https://arxiv.org/abs/2409.10781). Refuted if the caller does have an equivalent guard that is not textually a null-check (e.g. a truthy check, a default-coalescing operator, a try/catch two frames up) — read the caller fully, not just for the literal pattern, before raising.
42
45
 
43
46
  ## Tooling agreement
44
47
 
45
48
  - [ ] Formatter and linter config exist and the codebase actually conforms — read the lint config's enabled rules, then `search_code` for a pattern one of those rules should have caught (`console.log` if `no-console` is on, say). A hit means the config is decoration. (As of 2026 the common combinations are Ruff for Python — largely displacing the older flake8/pylint/isort stack — and ESLint+Prettier or the newer single-tool Biome for JS/TS; the check here is that one combination was picked and enforced, not which.)
46
- - [ ] Committed config does not contradict itself — read `.editorconfig`, the formatter config, and the linter config side by side for the same setting (indent size, quote style, line length) and diff the values.
47
- - [ ] Pre-commit or CI enforces what the config declares — `search_code` for a pre-commit hook (`.husky/`, `.pre-commit-config.yaml`) and a lint/format step in the CI workflow files. Treat the two differently: a pre-commit hook with no matching CI step is enforced only for a developer who has the hook installed and hasn't bypassed it (`--no-verify`, or a fresh clone before the install step ran) — nothing stops a violation from merging. CI absent is the real gap; pre-commit absent with a CI lint step present is slower feedback, not a missing gate. Neither present means the standard is optional, and optional standards decay.
49
+ - [ ] Committed config does not contradict itself — Read `.editorconfig`, the formatter config, and the linter config side by side for the same setting (indent size, quote style, line length) and diff the values.
50
+ - [ ] Pre-commit or CI enforcement of what the config declares — owned by `tooling-baseline.md` (`search_code` for a pre-commit hook and a matching lint/format step in the CI workflow, and confirm the CI step actually gates the merge rather than running only pre-commit); reuse its finding, do not re-report.
51
+
52
+ ## Documented vs accidental deviation
53
+
54
+ - [ ] Before reporting a naming, structural or idiom deviation as an unexplained inconsistency, `search_code` the deviating file for a `TODO`/`FIXME`/`HACK`/`XXX` comment naming that specific deviation. A marker turns the finding from "accidental drift" into "documented debt" — report both, but cap the documented case at `Low` regardless of what the table below would otherwise assign; documented is not the same as intentionally scoped or already scheduled to be fixed. Refuted if a `TODO` found in the file names something unrelated to the specific deviation (e.g. a `TODO` about a missing test, on a file that also happens to have inconsistent casing) — the marker must reference the same deviation, not merely be present in the file.
55
+
56
+ ## What browser observation closes
57
+
58
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number. Everything else in this module — casing, file organisation, idiom uniformity, interface signature shape, comment format, tooling config — is a property of the source tree itself, not of rendered runtime behaviour, so a browser session run against the built app cannot observe it. Only the subset that becomes user-facing text at render time (labels, error copy) crosses from source into something the bundle can corroborate.
59
+
60
+ | Artefact | Gap it closes | Observed instance earns |
61
+ |---|---|---|
62
+ | `screenshots/`, `steps.md`, `final-state.md` (rendered label text) | User-facing terminology drift for the same action across screens (e.g. one flow's button says "Delete", another's says "Remove" for the same operation) — only visible once labels are rendered, not from a static JSX string grep when text is interpolated/i18n-keyed. Refuted if the two actions are not actually the same operation (one is a soft-delete/archive, the other a hard delete) — read `steps.md`'s recorded outcome for each flow before treating the words as interchangeable. | Low |
63
+ | `network.jsonl` (response bodies), `console.jsonl`, `final-state.md` | Runtime error text shown to the user for the same failure class differs between two flows, corroborating the error-text-inconsistency check above — parallel to it, now at `observed` since the browser session itself proves both are reachable in one signed-in context, without needing the `trace_path` step — with what an actual response body/rendered error state contained rather than only the source string. Refuted the same way: the two flows are not reachable by the same caller privilege level. | High |
48
64
 
49
65
  ## Out of static reach
50
66
 
@@ -53,11 +69,17 @@ The method here is comparison, not judgement. Find the dominant pattern with `se
53
69
  - Comment accuracy for logic whose correctness cannot itself be verified by reading alone (cross-reference the tier ceiling on `inferred` findings).
54
70
  - Whether a linter rule that exists but isn't enforced in CI is disabled locally by individual developers, or genuinely never runs at all.
55
71
  - The historical intent behind a deviation — a file that breaks the pattern on purpose, with the reason recorded only in a closed PR discussion this audit cannot read.
72
+ - Whether this project's names agree with a sibling repository's names for the same concept — this audit indexes one repository.
73
+ - Whether an internal name matches how the business describes the same concept outside the codebase — this audit has no access to product or support documentation.
74
+ - Who or what introduced a given deviation, and whether it was a deliberate choice — cross-reference `repo-history.md` if that module ran.
56
75
 
57
76
  ## Severity guidance
58
77
 
59
78
  | Situation | Severity |
60
79
  |---|---|
80
+ | Comment that contradicts its code, and an unguarded caller relies on the false claim, traced via `find_callers` | High |
81
+ | Inconsistent error text/shape for the same failure class, reachable from the same external interface (traced) | High |
82
+ | Entry point missing the shared validation call every sibling at its layer has, traced via `find_callees` | High |
61
83
  | Comment that contradicts its code | Medium |
62
84
  | One concept under several names | Medium |
63
85
  | Mixed async styles for the same operation kind | Medium |
@@ -65,3 +87,4 @@ The method here is comparison, not judgement. Find the dominant pattern with `se
65
87
  | Two competing file-organisation principles | Low |
66
88
  | Formatter config that nothing enforces | Low |
67
89
  | Casing convention drift | Low |
90
+ | Deviation with a `TODO`/`FIXME`/`HACK` marker naming it (documented, not accidental) | Low |
@@ -9,52 +9,66 @@ A contract is a promise written in two or more places. This module checks whethe
9
9
  ## Schema vs. server
10
10
 
11
11
  - [ ] Every operation in the schema exists in the implementation. `search_code` the operation name, then `find_symbol` on the handler.
12
- - [ ] Every implemented operation appears in the schema — `search_code` the route-registration/resolver list for operation names, then `search_code` each name against the schema file. A name present only on the server side is an undocumented endpoint, drift plus a `Reachability` question.
13
- - [ ] Field-level agreement: names, types, nullability, required-ness, enum members — `find_symbol` the schema type and the implementation's corresponding type/model, and diff the field lists by hand. Nullability drift is the most commonly missed and the most likely to crash a consumer.
12
+ - [ ] Every implemented operation appears in the schema — `search_code` the route-registration/resolver list for operation names, then `search_code` each name against the schema file. A name present only on the server side is an undocumented endpoint, drift plus a `Reachability` question — OWASP's API9:2023 names this precisely: "running multiple versions of an API requires additional management resources... and expands the attack surface" (OWASP, API Security Top 10:2023, official project page, 2023, https://owasp.org/API-Security/editions/2023/en/0xa9-improper-inventory-management/).
13
+ - [ ] Field-level agreement: names, types, nullability, required-ness, enum members — `find_symbol` the schema type and the implementation's corresponding type/model, and diff the field lists by hand. Nullability drift is the most commonly missed and the most likely to crash a consumer — OpenAPI 3.1 replaced the custom 3.0.3 `nullable: true` extension with the standard JSON Schema union-type approach (`type: [X, "null"]`), two syntactically different, mutually non-interchangeable ways of expressing the same nullability (OpenAPI Initiative, official project blog, 2021, https://www.openapis.org/blog/2021/02/18/openapi-specification-3-1-released). The schema file's `openapi:` version and its nullability syntax must agree: a document declaring `openapi: 3.1.x` (or later) that still uses the 3.0-only `nullable: true` extension instead of a `type` array is internally inconsistent — a strict JSON-Schema-only validator or codegen tool will not honor `nullable`, silently treating the field as non-nullable. `search_code` for `nullable:` co-occurring with an `openapi: 3.1` or `3.2` declaration in the same file. Refuted if the toolchain generating or consuming this schema is OpenAPI-3.0-aware and translates `nullable` correctly regardless of the declared version string — check the codegen/validator config before flagging a live break.
14
14
  - [ ] Declared error responses match what the server actually returns, including status codes — `search_code` the status codes and error shapes thrown in the handler, then compare against the schema's documented responses for the same operation.
15
- - [ ] The schema is generated from the implementation or verified against it — `search_code` the manifest/CI config for a codegen or schema-validation step (`openapi-generator`, `graphql-codegen`, a schema-diff check). None found means a hand-maintained schema with no check, which will drift — that is not a prediction, it is a certainty.
16
- - [ ] For streaming operations (Server-Sent Events, JSON Lines, multipart/mixed — expressible in OpenAPI 3.2+ via `itemSchema`), the declared per-event shape matches what the handler actually emits. `search_code` the handler's stream-write calls and diff the emitted event shape against the schema's `itemSchema`. A schema still describing the operation as a single response body — the only option before 3.2 — while the implementation already streams typed events is drift the older schema shape cannot even express, not merely an outdated field.
15
+ - [ ] The schema is generated from the implementation or verified against it — `search_code` the manifest/CI config for a codegen or schema-validation step (`openapi-generator`, `graphql-codegen`, a schema-diff check). None found means a hand-maintained schema with no check — the absence of a check is itself the finding, not a guaranteed future outcome this static read cannot observe. Where more than one API version is live (`/v1/` and `/v2/` route groups, a version header dispatch, or a deprecated-but-still-mounted resolver): each version has its own schema artefact that has actually been checked for drift, not just the current one — `search_code` for version-prefixed route registrations, and for each version found, re-run this check against that version's own schema, not only the newest. An old, forgotten version diverging from what the current version enforces, discovered only because it was still reachable, is OWASP API9:2023's own Scenario #1 (OWASP, API Security Top 10:2023, official project page, 2023, https://owasp.org/API-Security/editions/2023/en/0xa9-improper-inventory-management/). Refuted if the old version is a thin compatibility shim that forwards to the current handler with no schema of its own, or it is already flagged and tracked as deprecated-with-a-sunset-date elsewhere in the audit (`versioning-compatibility.md`) — report once, not twice.
16
+ - [ ] For streaming operations (Server-Sent Events, JSON Lines, multipart/mixed — expressible in OpenAPI 3.2+ via `itemSchema`), the declared per-event shape matches what the handler actually emits. `search_code` the handler's stream-write calls and diff the emitted event shape against the schema's `itemSchema`. A schema still describing the operation as a single response body — the only option before 3.2 — while the implementation already streams typed events is drift the older schema shape cannot even express, not merely an outdated field (OpenAPI 3.2 adds `text/event-stream`, `application/jsonl`, `application/json-seq`, and `multipart/mixed` as sequential media types, with `itemSchema` defining "what a streamed event looks like over the wire" — OpenAPI Initiative, official project blog, 2025, https://www.openapis.org/blog/2025/09/23/announcing-openapi-v3-2).
17
17
 
18
18
  ## Schema vs. consumer
19
19
 
20
- - [ ] Generated clients are regenerated from the current schema, and the generated output is either committed or built in CI — `search_code` the CI config for the client-generation command and check whether the generated directory is `.gitignore`d (built fresh) or committed (needs a staleness check). A stale committed client is drift with a long fuse.
20
+ - [ ] Generated clients are regenerated from the current schema, and the generated output is either committed or built in CI — `search_code` the CI config for the client-generation command and check whether the generated directory is `.gitignore`d (built fresh) or committed (needs a staleness check). A stale committed client is drift with a long fuse. Cross-reference `type-safety.md`'s generated-types-regenerated-in-CI check; report once.
21
21
  - [ ] Hand-written consumer types match the schema. Cross-reference `api.md`: `find_callers` on the response type to see who destructures which fields, then diff those field names against the schema.
22
- - [ ] Consumers do not read fields the schema does not promise — `search_code` the destructuring/property-access sites on a response object and check each accessed field appears in the schema, including fields that happen to exist today but are undocumented.
23
- - [ ] Consumers tolerate fields being added — `search_code` for a strict/`.strict()` parsing mode or a validator configured to reject unknown keys on incoming responses. A client rejecting unknown fields makes every additive change breaking.
22
+ - [ ] Consumers do not read fields the schema does not promise — `search_code` the destructuring/property-access sites on a response object and check each accessed field appears in the schema, including fields that happen to exist today but are undocumented. This is `High` at `read`; `trace_path` (or `find_callers`) from the response-construction code confirming no path still emits the field promotes it to `traced`, and `Critical`.
23
+ - [ ] Consumers tolerate fields being added — `search_code` for a strict/`.strict()` parsing mode or a validator configured to reject unknown keys on incoming responses. A client rejecting unknown fields makes every additive change breaking — Stripe's own enumerated list of backward-compatible changes includes new response properties and reordered response properties, exactly what a strict/unknown-key-rejecting client breaks on (Stripe, official API reference docs, current, https://docs.stripe.com/upgrades).
24
24
 
25
25
  ## Versioning of the contract
26
26
 
27
- - [ ] Schema changes are classified as additive or breaking, and breaking ones are versioned — `search_code` for a schema version field or a CHANGELOG referencing the schema. Cross-reference `versioning-compatibility.md`.
28
- - [ ] These look additive and are not: narrowing a type, adding a required field, making an optional field required, removing an enum member, tightening a pattern — read the schema file's recent git history (`git log -p` on the schema path) and check each change against this list.
29
- - [ ] For protobuf: field numbers are never reused or renumbered, removed fields are reserved — read the `.proto` file, list every field number in the message, and confirm no gap in the sequence is unaccounted for by a `reserved` statement.
30
- - [ ] For GraphQL: removing a field or changing a type is breaking even when clients do not currently request it — read the schema file's git history for removed fields or changed types; someone's query will break even if none in this repo does.
27
+ - [ ] Schema changes are classified as additive or breaking, and breaking ones are versioned — `search_code` for a schema version field or a CHANGELOG referencing the schema. Cross-reference `versioning-compatibility.md`. Stripe's own backward-compatible list is explicit and enumerated (new resources, new optional request parameters, new response properties, reordered response properties, changed length/format of opaque strings, new event types) — anything outside that list is breaking by default (Stripe, official API reference docs, current, https://docs.stripe.com/upgrades).
28
+ - [ ] These look additive and are not: narrowing a type, adding a required field, making an optional field required, removing an enum member, tightening a pattern — Read the current schema file against its last published version (a committed previous copy, a changelog entry, or the version `repo-history.md` recovered from the commit log when that module ran — the history reading is that module's, not this one's) and check each change against this list. A field added without a default is on this list too: Avro's own schema-resolution rule signals an error "if the reader's record schema has a field with no default value, and writer's schema does not have a field with the same name" (Apache Avro, official specification v1.12.0, current, https://avro.apache.org/docs/1.12.0/specification/).
29
+ - [ ] For protobuf: field numbers are never reused or renumbered, removed fields are reserved — Read the `.proto` file, list every field number in the message, and confirm no gap in the sequence is unaccounted for by a `reserved` statement. Field numbers "cannot be changed once your message type is in use" and reusing one "makes decoding wire-format messages ambiguous," with named consequences including "leaked PII/SPII" and "data corruption" (Protocol Buffers / Google, official language guide, current, https://protobuf.dev/programming-guides/proto3/).
30
+ - [ ] For Avro (and any Avro-based event/message schema — Kafka topics, `.avsc` files): a field added to the **reader's** schema (an upgraded consumer's schema) has a `"default"` key, or that reader will error decoding data written under the older writer schema, which lacks the field — `search_code` the `.avsc`/schema-registry-managed schema for the added field and confirm a default is present; `find_symbol` the corresponding message/record type in the implementation to confirm the field is genuinely optional there too (Apache Avro, official specification v1.12.0, current, https://avro.apache.org/docs/1.12.0/specification/). Refuted if the schema registry (or equivalent) is configured to reject the incompatible change at publish time and did so — confirm via a CI log or registry response before flagging, not by assumption.
31
+ - [ ] For GraphQL: removing a field or changing a type is breaking even when clients do not currently request it — Read the schema file's git history for removed fields or changed types; someone's query will break even if none in this repo does. GitHub's own distinction separates "breaking changes" (e.g. removing a field) from "dangerous changes" — "changes that won't break existing queries but could affect the runtime behavior of clients," such as adding an enum value — with breaking changes given "at least three months" notice and landing only on quarterly boundaries (GitHub / Microsoft, official product docs, current, https://docs.github.com/en/graphql/overview/breaking-changes).
31
32
 
32
33
  ## Shared types across boundaries
33
34
 
34
35
  - [ ] Types shared between packages or services come from one source, not duplicated definitions kept in sync by hand — `search_code` the type name; if it is declared, not imported, in more than one package, that is a duplicate rather than a shared type.
35
36
  - [ ] Where duplication is unavoidable, a test asserts equivalence — `search_code` the test suite for an assertion comparing the two duplicated definitions field-by-field. Same anti-drift pattern as a manifest-parity test: the hand-maintained copy is fine, the unguarded hand-maintained copy is not.
36
- - [ ] Serialisation boundaries agree on representation — date encoding, number precision, null vs. absent, empty vs. missing — read the serializer on one side and the deserializer on the other for the same field and compare what each assumes.
37
- - [ ] Enum values agree on the wire, not only in name — `find_symbol` both enum definitions and diff their underlying string/numeric values, not just the member names.
37
+ - [ ] Serialisation boundaries agree on representation — date encoding, number precision, null vs. absent, empty vs. missing — Read the serializer on one side and the deserializer on the other for the same field and compare what each assumes.
38
+ - [ ] Enum values agree on the wire, not only in name — `find_symbol` both enum definitions and diff their underlying string/numeric values, not just the member names. For GraphQL and any open-style enum: an added enum member is schema-compatible but can still break a consumer that pattern-matches on the enum without a default/fallback arm — `search_code` the enum type's consumer sites for a `switch`/`match` with no `default`/wildcard case, and `find_callers` on the enum type to enumerate every such site. GitHub's own "dangerous change" category names exactly this growth-direction failure mode (GitHub / Microsoft, official product docs, current, https://docs.github.com/en/graphql/overview/breaking-changes), and Stripe prescribes the fix: a switch needs "a default branch... to gracefully handle values your integration doesn't yet recognize" (Stripe, official API reference docs, current, https://docs.stripe.com/upgrades). Refuted if the switch's language has a compiler-enforced exhaustiveness check that already fails the build on a new member — confirm the language/tooling before flagging.
38
39
 
39
40
  ## Fixtures and tests
40
41
 
41
42
  - [ ] Test fixtures are validated against the schema — `search_code` test setup for the fixture being passed through the schema's own parser/validator before use. A fixture that drifted from the contract makes the suite pass against a shape that no longer exists, and the tests then actively hide the drift.
42
- - [ ] Contract tests exist at the boundary, not only unit tests on each side — `search_code` for a contract-testing tool: a Pact consumer test producing a `*.pact.json`/`pacts/` artefact plus a provider-side verification step that replays it (from disk or a Pact Broker), a Spring Cloud Contract stub, or a shared fixture package consumed by both producer and consumer — versus tests that only exercise one side in isolation. Two sides each passing their own tests is exactly the state in which drift survives; a pact file with no matching provider-verification step in CI is half the mechanism, and behaves like having none.
43
+ - [ ] Contract tests exist at the boundary, not only unit tests on each side — `search_code` for a contract-testing tool: a Pact consumer test producing a `*.pact.json`/`pacts/` artefact plus a provider-side verification step that replays it (from disk or a Pact Broker), a Spring Cloud Contract stub, or a shared fixture package consumed by both producer and consumer — versus tests that only exercise one side in isolation. Two sides each passing their own tests is exactly the state in which drift survives; a pact file with no matching provider-verification step in CI is half the mechanism, and behaves like having none — "in provider verification, each request is sent to the provider, and the actual response it generates is compared with the minimal expected response described in the consumer test" (Pact Foundation, official docs, current, https://docs.pact.io/getting_started/how_pact_works), and testing against a double "always raises the question of whether the double is indeed an accurate representation of the external service" (Martin Fowler, canonical bliki, current, https://martinfowler.com/bliki/ContractTest.html).
43
44
  - [ ] Something in CI fails when the schema and the implementation disagree — `search_code` the CI workflow files for a schema-diff, contract-test, or codegen-verification step. If not, that missing check is the finding that generates all the others.
44
45
 
45
46
  ## Out of static reach
46
47
 
47
48
  - Whether a consumer outside this repo — a mobile app, a partner integration — reads a field this module cannot see.
48
- - Runtime behaviour when a field the schema promises is actually absent on the wire under a server-side conditional this audit didn't trace.
49
+ - Runtime behaviour when a field the schema promises is actually absent on the wire under a server-side conditional this audit didn't trace — closed by `runtime.md` when a declared contract-test command is run under execution.
49
50
  - Whether a client's "tolerant" handling of extra fields is truly forward-compatible, or merely untested against a field's removal.
50
51
  - The provider's actual current schema version, when the local copy is unpinned — this module reads what's committed, not what production serves.
51
52
  - The historical intent behind an intentionally undocumented endpoint (internal-only, deprecated-but-kept) versus true drift.
53
+ - Whether the schema registry this project publishes to is actually configured to reject an incompatible change, or would only log it — this module reads the schema, not the registry's live policy.
54
+ - Whether a consumer outside this repo breaks on a newly added enum member — this module can check its own repo's consumers but not anyone else's.
55
+
56
+ ## What browser observation closes
57
+
58
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number. Bounded: `network.jsonl` bodies are captured only for 4xx/5xx responses, so a 2xx body's real shape is never confirmed this way.
59
+
60
+ | Artefact | Gap it closes | Observed instance earns |
61
+ |---|---|---|
62
+ | `network.jsonl` | Real status code, headers, and error-body shape for an operation's declared schema, observed on a walked flow — 2xx bodies are not captured, so the success shape stays unconfirmed | Medium |
63
+ | `network.jsonl` request paths, `routes.md` when present | Operation live in real traffic but absent from the schema, extending the existing "Every implemented operation appears in the schema" check. Refuted if the hit path is a static asset, a third-party beacon, or a redirect target rather than an API operation — check the request's resource type and response `Content-Type` before flagging | High |
64
+ | `network.jsonl` (4xx/5xx bodies) | Declared error response shape/status code matches what a walked flow actually returns, extending the existing "Declared error responses match what the server actually returns" check. Refuted if the error was provoked by an input the schema never claimed to validate — there is no declared contract to have drifted from | High |
52
65
 
53
66
  ## Severity guidance
54
67
 
55
68
  | Situation | Severity |
56
69
  |---|---|
57
- | Consumer reads a field the server no longer returns | Critical |
70
+ | Consumer reads a field the server no longer returns (traced) | Critical |
71
+ | Consumer reads a field the schema does not promise (read) | High |
58
72
  | Nullability mismatch between schema and implementation | High |
59
73
  | Breaking schema change shipped as additive | High |
60
74
  | Protobuf field number reused or renumbered | High |
@@ -66,4 +80,8 @@ A contract is a promise written in two or more places. This module checks whethe
66
80
  | No CI check that schema and implementation agree | Medium |
67
81
  | Streaming event shape drifted from the declared `itemSchema` | Medium |
68
82
  | Pact file with no provider-side verification wired into CI | Medium |
83
+ | Avro field added to a consumer's (reader) schema with no default, breaking on decode against data written under the older writer schema | High |
84
+ | Enum member added with no default/fallback arm in a consumer's exhaustive switch | Medium |
85
+ | Parallel/legacy API version's own schema never checked for drift | Medium |
86
+ | OpenAPI schema declares 3.1+ but still uses legacy `nullable: true` instead of a type array | Medium |
69
87
  | Client rejecting unknown fields | Low |