project-brain 0.22.3 → 0.23.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 (52) hide show
  1. package/README.md +1 -1
  2. package/package.json +7 -7
  3. package/templates/skills/brain-audit/SKILL.md +174 -8
  4. package/templates/skills/brain-audit/references/abuse.md +34 -24
  5. package/templates/skills/brain-audit/references/accessibility.md +41 -21
  6. package/templates/skills/brain-audit/references/ai.md +28 -18
  7. package/templates/skills/brain-audit/references/analytics.md +73 -0
  8. package/templates/skills/brain-audit/references/api.md +27 -17
  9. package/templates/skills/brain-audit/references/backend.md +24 -16
  10. package/templates/skills/brain-audit/references/complexity.md +30 -17
  11. package/templates/skills/brain-audit/references/concurrency.md +28 -19
  12. package/templates/skills/brain-audit/references/consistency.md +32 -24
  13. package/templates/skills/brain-audit/references/contract-drift.md +30 -19
  14. package/templates/skills/brain-audit/references/cost.md +35 -24
  15. package/templates/skills/brain-audit/references/cross-surface-parity.md +70 -0
  16. package/templates/skills/brain-audit/references/database.md +42 -24
  17. package/templates/skills/brain-audit/references/dependencies-licensing.md +34 -23
  18. package/templates/skills/brain-audit/references/design-system.md +99 -0
  19. package/templates/skills/brain-audit/references/devops.md +38 -24
  20. package/templates/skills/brain-audit/references/documentation.md +35 -23
  21. package/templates/skills/brain-audit/references/failure.md +33 -21
  22. package/templates/skills/brain-audit/references/feature-flags.md +87 -0
  23. package/templates/skills/brain-audit/references/flow-integrity.md +58 -33
  24. package/templates/skills/brain-audit/references/frontend.md +36 -19
  25. package/templates/skills/brain-audit/references/functional.md +38 -17
  26. package/templates/skills/brain-audit/references/future.md +32 -12
  27. package/templates/skills/brain-audit/references/goal.md +19 -12
  28. package/templates/skills/brain-audit/references/i18n.md +37 -23
  29. package/templates/skills/brain-audit/references/idempotency.md +76 -0
  30. package/templates/skills/brain-audit/references/infrastructure.md +31 -22
  31. package/templates/skills/brain-audit/references/mobile.md +32 -23
  32. package/templates/skills/brain-audit/references/multi-tenancy.md +74 -0
  33. package/templates/skills/brain-audit/references/numeric.md +70 -0
  34. package/templates/skills/brain-audit/references/observability.md +36 -21
  35. package/templates/skills/brain-audit/references/packaging.md +27 -19
  36. package/templates/skills/brain-audit/references/performance.md +48 -21
  37. package/templates/skills/brain-audit/references/privacy.md +39 -25
  38. package/templates/skills/brain-audit/references/product.md +31 -12
  39. package/templates/skills/brain-audit/references/prompt-spec-gap.md +25 -18
  40. package/templates/skills/brain-audit/references/reachability.md +28 -20
  41. package/templates/skills/brain-audit/references/repo-history.md +65 -0
  42. package/templates/skills/brain-audit/references/scalability.md +35 -22
  43. package/templates/skills/brain-audit/references/security.md +50 -33
  44. package/templates/skills/brain-audit/references/state-model.md +73 -0
  45. package/templates/skills/brain-audit/references/supply-chain.md +64 -0
  46. package/templates/skills/brain-audit/references/temporal.md +66 -0
  47. package/templates/skills/brain-audit/references/testing.md +49 -24
  48. package/templates/skills/brain-audit/references/tooling-baseline.md +77 -0
  49. package/templates/skills/brain-audit/references/type-safety.md +68 -0
  50. package/templates/skills/brain-audit/references/versioning-compatibility.md +33 -22
  51. package/templates/skills/brain-audit/references/visual-design.md +89 -0
  52. package/templates/skills/brain-audit/references/web-metadata.md +72 -0
@@ -4,60 +4,76 @@ Gate: auth, external input, or a network boundary was detected.
4
4
 
5
5
  **Scope discipline.** This module finds and reports defects in the audited codebase. It does not write exploits, and it does not produce working attack payloads. A finding names the vulnerable line, the class of attack, and the fix.
6
6
 
7
+ **This is the module where an invented finding does the most damage.** A false Critical here does not sit quietly in a backlog — it sends someone onto an emergency rotation for nothing, and the second cost is worse than the first: it trains that team to discount the next alert this skill raises, including the real one. Every rule-out below is not optional colour, it is the difference between a finding and an incident. If a check cannot be traced to its origin, it is not reported at this severity — see the Evidence Contract in `SKILL.md`.
8
+
7
9
  Trace every input from where it enters to where it is used. `find_callees` from the entry point, or `trace_path` from the handler to the sink. An input that reaches a sink without passing validation is the finding.
8
10
 
9
11
  ## Injection sinks
10
12
 
11
- Enumerate the sinks, then check what reaches each one:
13
+ Enumerate the sinks, then check what reaches each one. For every hit, the rule-out is the same shape: `trace_path` (or `find_callers` walked backward one hop at a time) from the sink to the value's origin. A value that terminates at a literal, an internal config object, or a value already validated upstream is not a finding — an invented finding at Critical is a full incident response for nothing, so confirm the traced origin is unvalidated external input before reporting anything.
12
14
 
13
- - [ ] **Query** — any query built by concatenation or interpolation from external input. Parameterised or nothing. `Critical`.
14
- - [ ] **Shell** — `exec`, `spawn` with a shell, or a command string built from input. Prefer argument arrays with no shell.
15
- - [ ] **Filesystem** — a path built from input. Check for `..` traversal and absolute-path override; the fix is resolve-then-verify-inside-root, not string filtering.
16
- - [ ] **Code** — `eval`, `new Function`, dynamic `require`/`import` of an input-derived name, deserialisation of untrusted data.
17
- - [ ] **Template/markup** — unescaped interpolation into HTML, `innerHTML`, `dangerouslySetInnerHTML`.
18
- - [ ] **Model prompt** — untrusted text concatenated into instructions; see `abuse.md` and `ai.md`.
15
+ - [ ] **Query** — `search_code` for string concatenation or template interpolation feeding a query call (`+ req.`, `` `${...}` `` next to a query function, `.raw(`, `f"SELECT`). Trace the interpolated value back with `trace_path`; parameterised or nothing. CWE-89, #2 in the 2025 CWE Top 25. `Critical`.
16
+ - [ ] **Shell** — `search_code` for `exec(`, `spawn(` with `shell: true`, `os.system(`, `subprocess.` with `shell=True`, or backtick/string command construction. Trace the command string's origin; prefer argument arrays with no shell. CWE-78/CWE-77 (OS command injection, #9/#23 in the 2025 CWE Top 25).
17
+ - [ ] **Filesystem** — `search_code` for `path.join(`/`os.path.join(` fed by a request parameter, or raw string path building. Read the resolved-path handling for `..` traversal and absolute-path override; the fix is resolve-then-verify-inside-root, not string filtering. CWE-22 Path Traversal, #6 in the 2025 CWE Top 25.
18
+ - [ ] **Code** — `search_code` for `eval(`, `new Function(`, dynamic `require(`/`import(` of a computed name, `pickle.loads`, `yaml.load` without `SafeLoader`, or other deserialisation of untrusted data. Trace the argument to its source. CWE-94 Code Injection (#10) or CWE-502 Deserialization of Untrusted Data (#15) in the 2025 CWE Top 25 — cite whichever fits the sink.
19
+ - [ ] **Template/markup** — `search_code` for `innerHTML`, `dangerouslySetInnerHTML`, `v-html`, or a template engine's raw/unescaped filter. Trace the value; a hit rendering only static or already-sanitised content is not the finding.
20
+ - [ ] **Model prompt** — `search_code` for string concatenation into a prompt or messages array. Trace the concatenated text to confirm it is untrusted user content, not a fixed system instruction; see `abuse.md` and `ai.md`.
19
21
 
20
22
  ## AuthN
21
23
 
22
- - [ ] Credential comparison is constant-time. `search_code` for `===` against a token or secret.
23
- - [ ] Passwords are hashed with a slow, salted algorithm — never a plain digest, never encrypted, never stored raw.
24
- - [ ] Sessions and tokens expire, and expiry is checked with the correct comparison. An off-by-one on `<` vs `<=` at an expiry boundary is a real defect.
25
- - [ ] Tokens are validated for signature, issuer, audience, and expiry — not merely decoded.
26
- - [ ] Logout invalidates server-side, not only client-side.
24
+ ASVS 5.0 §V6 (Authentication) and §V7 (Session Management) cover this section.
25
+
26
+ - [ ] Credential comparison is constant-time. `search_code` for `===`, `==`, or `.equals(` comparing a token, secret, or hash — read the call site; a comparison against a non-secret value (a public id, a CSRF token already bound to session) does not qualify.
27
+ - [ ] Passwords are hashed with a slow, salted algorithm. `find_symbol`/`search_code` the registration or password-set handler and read what it calls before persisting — `bcrypt`/`argon2`/`scrypt` is correct, `md5`/`sha256`/plain storage is the finding.
28
+ - [ ] Sessions and tokens expire, and expiry is checked with the correct comparison. `find_symbol` the verify function and read the comparison operator literally — an off-by-one on `<` vs `<=` at the expiry boundary is a real defect, not a style nit.
29
+ - [ ] Tokens are validated for signature, issuer, audience, and expiry. Read the verify call's options argument directly — a call that only decodes (`jwt.decode` with verification disabled, or no `verify()` at all) is the finding regardless of what happens after.
30
+ - [ ] Logout invalidates server-side. `find_symbol` the logout handler, then `find_callees` — a handler that only clears a client-side cookie or local storage entry, with no server-side session/token revocation call, is the finding.
27
31
 
28
32
  ## AuthZ
29
33
 
30
- - [ ] Every protected operation checks authorisation, and the check is on the server. `find_callers` on the authorisation helper, then compare against the full list of protected handlers — the gap is the finding.
31
- - [ ] Authorisation is checked against the *resource*, not only the *route*. Being logged in is not permission to read record 42.
32
- - [ ] No object reference from the client is trusted as ownership proof.
33
- - [ ] Privilege escalation paths: can a user set their own role, quota, or flags through a mass-assigned update?
34
- - [ ] Default is deny. A new endpoint added tomorrow should be closed unless opened.
34
+ ASVS 5.0 §V8 (Authorization) covers this section. The specific defect below — a handler trusting a client-supplied resource id as ownership proof — is **Broken Object Level Authorization**, OWASP API Security Top 10:2023 API1 (BOLA), CWE-639 Authorization Bypass Through User-Controlled Key, #24 in the 2025 CWE Top 25.
35
+
36
+ - [ ] Every protected operation checks authorisation, and the check is on the server. `find_callers` on the authorisation helper, then compare against the full list of protected handlers from `get_architecture`/route discovery — the gap between the two lists is the finding. CWE-862 Missing Authorization, #4 in the 2025 CWE Top 25.
37
+ - [ ] Authorisation is checked against the *resource*, not only the *route*. `trace_path` from the handler to the query that loads the record and confirm the caller's identity is compared against an ownership or ACL field before the read/write executes — a handler that only checks "is authenticated" and then loads by the id in the URL is the finding (BOLA, see above).
38
+ - [ ] No object reference from the client is trusted as ownership proof — same trace as above; the id in the request is data, not a credential.
39
+ - [ ] A caught exception or an unmatched branch in an authorisation check does not fail open. Read the authorisation helper's error handling directly — a `try/catch` around the permission check that falls through to "allow" on any exception, or a `switch`/`if` chain with no explicit deny in the default branch, is the finding. This is OWASP Top 10:2025 A10 (Mishandling of Exceptional Conditions), new for the 2025 edition.
40
+ - [ ] Mass assignment: `search_code` for `...req.body` spread into an update call, or an ORM `.update(req.body)`/`.save(req.body)` with no field allowlist. A hit with an explicit `pick`/DTO/schema validation between the request and the update is not the finding. OWASP API Security Top 10:2023 API3 (Broken Object Property Level Authorization / BOPLA).
41
+ - [ ] Default is deny. Check the router/framework's default for an unmatched or newly added route — a default-allow framework configuration is itself a finding even with no missing check found yet.
35
42
 
36
43
  ## Secrets
37
44
 
38
- - [ ] No secret in source, config committed to the repo, test fixture, or log line. `search_code` for `secret`, `password`, `token`, `api_key`, `private_key`, `Bearer`.
39
- - [ ] No secret in an error message, stack trace, or debug output.
40
- - [ ] Secrets come from the environment or a secret manager, and absence fails loudly at startup.
41
- - [ ] Check git history if a secret is found in the working tree — removal from HEAD does not remove it from history. Report the need for rotation.
45
+ - [ ] `search_code` for `secret`, `password`, `token`, `api_key`, `private_key`, `Bearer` as literal string assignments. This is the highest false-positive check in the whole skill — read every hit before reporting. A hit assigning a hardcoded literal (`"sk-...")`, `"changeme"` used as a real default, a real-looking key in a fixture reused outside tests) is the finding; a hit reading from `process.env`, a config object backed by env, or a secret-manager client call is not.
46
+ - [ ] No secret in an error message, stack trace, or debug output — read the logging/error-serialisation call sites found under Information disclosure below for a secret-bearing field, don't infer it.
47
+ - [ ] Secrets come from the environment or a secret manager, and absence fails loudly at startup. `search_code` the config-loading module for a fallback default on a secret-shaped key — a silent fallback (`|| 'default-secret'`) is the finding, not the absence of one. Application/service secrets should also carry an expiry or rotation mechanism, not just a source — read the secret-manager client call for a TTL/rotation parameter; its total absence on a long-lived service credential is `read`-tier evidence for a finding (this does not apply to user passwords, where mandatory periodic rotation is now considered outdated guidance per current NIST practice — do not flag its absence).
48
+ - [ ] If a secret is found in the working tree, check git history — removal from `HEAD` does not remove it from history. **Rotation is required regardless of whether the check-in was reverted or the history was later rewritten** — per OWASP's Secrets Management Cheat Sheet, squashing/rewriting history addresses the commit trail, not the exposure: the secret was retrievable, so it is compromised, full stop. Proactive, exhaustive history scanning is owned by `repo-history.md`; this line stays reactive — do not expand history work here.
42
49
 
43
50
  ## Transport and headers
44
51
 
45
- - [ ] TLS enforced; no plaintext transport for credentials or user data. No disabled certificate verification — `search_code` for `rejectUnauthorized: false` and equivalents.
46
- - [ ] CORS is not permissive-with-credentials. A wildcard origin plus credentials is `High`.
47
- - [ ] Cookies are `HttpOnly`, `Secure`, and have an appropriate `SameSite`.
48
- - [ ] State-changing requests are protected against cross-site forgery where cookie auth is used.
52
+ - [ ] TLS enforced; no plaintext transport for credentials or user data. `search_code` for `rejectUnauthorized: false`, `NODE_TLS_REJECT_UNAUTHORIZED=0`, `verify=False` (requests/httpx), or `InsecureSkipVerify: true` (Go) — each disables certificate verification outright and needs no further rule-out.
53
+ - [ ] CORS is not permissive-with-credentials. `search_code` for the CORS configuration and read it as one object — a wildcard origin (`*`) and `credentials: true` must be set on the *same* middleware instance to qualify; a wildcard on a public, unauthenticated endpoint with `credentials: false` elsewhere is not the finding.
54
+ - [ ] Cookies are `HttpOnly`, `Secure`, and have an appropriate `SameSite`. `search_code` for the cookie-setting call (`res.cookie(`, `Set-Cookie`, `set_cookie(`) and read the options object directly rather than assuming defaults.
55
+ - [ ] State-changing requests are protected against cross-site forgery where cookie auth is used. First confirm the auth mechanism: `search_code` for how the session is authenticated — a pure Bearer-token API with no cookie in the auth path does not need CSRF protection, and flagging its absence there is the false positive. Where cookie auth is confirmed, `search_code` for CSRF middleware/token verification and check it is wired into the state-changing routes, not just imported.
49
56
 
50
57
  ## Information disclosure
51
58
 
52
- - [ ] No stack trace, internal path, dependency version, or query text reaches a client. Cross-reference `failure.md`.
53
- - [ ] Error messages do not distinguish "no such user" from "wrong password".
54
- - [ ] Directory listing, source maps, and debug endpoints are disabled in production.
55
- - [ ] Logs do not contain credentials, tokens, or personal data — cross-reference `privacy.md`.
59
+ - [ ] No stack trace, internal path, dependency version, or query text reaches a client. `search_code` the central error handler for `err.stack`, `err.message`, or a caught error object serialised directly into the response body. Cross-reference `failure.md`.
60
+ - [ ] Error messages do not distinguish "no such user" from "wrong password". Read the login and password-reset handlers directly and literally compare the status code and message text returned on each branch — they must be identical, not merely similar.
61
+ - [ ] Directory listing, source maps, and debug endpoints are disabled in production. `search_code` the production build/deploy config for `sourceMap: true`, `devtool:` set to a non-hidden value, or a static-file server with listing enabled.
62
+ - [ ] Logs do not contain credentials, tokens, or personal data. Read what is passed to the logger at the request-boundary middleware — a logged `req` or `req.headers` object without redaction is the finding; cross-reference `privacy.md`.
56
63
 
57
64
  ## Dependencies
58
65
 
59
- - [ ] Known-vulnerable dependencies. Report the advisory, not a guess. Cross-reference `dependencies-licensing.md`.
60
- - [ ] Lockfile present and committed, so builds are reproducible.
66
+ - [ ] Known-vulnerable dependencies: cross-reference `dependencies-licensing.md` rather than duplicating that inventory here. Do not maintain a CVE list in this module — it goes stale the day it's written; live vulnerability status is unverifiable from source and belongs in Out of static reach.
67
+ - [ ] Lockfile present and committed, so builds are reproducible — `get_architecture` reports the package manager and manifest directly.
68
+
69
+ ## Out of static reach
70
+
71
+ - Whether a flagged dependency vulnerability is actually exploitable in this codebase's usage of it — that needs the vulnerable code path exercised, not just present.
72
+ - Live CVE/advisory status for any dependency — the manifest is a point-in-time read; advisories are published continuously.
73
+ - Whether network-layer controls (WAF rules, firewall policy, a reverse proxy's own header stripping) already mitigate a code-level finding.
74
+ - Actual production TLS/certificate configuration, as opposed to what the code declares — the deployed reality can diverge from the repo.
75
+ - Whether a secret found in git history has actually been rotated — this module can only prove exposure, not remediation; the reactive line above stays here, proactive scanning is `repo-history.md`'s job.
76
+ - Whether a rate limit, lockout policy, or auth control holds up under real concurrent traffic — cross-reference `abuse.md` and `concurrency.md` for the structural checks; effectiveness under load is not something source can show.
61
77
 
62
78
  ## Severity guidance
63
79
 
@@ -65,10 +81,11 @@ Enumerate the sinks, then check what reaches each one:
65
81
  |---|---|
66
82
  | Injection sink reachable from unvalidated external input | Critical |
67
83
  | Missing authorisation on a protected operation | Critical |
68
- | Secret committed to the repository | Critical |
84
+ | Secret committed to the repository (regardless of later history rewrite) | Critical |
69
85
  | Password stored unhashed or reversibly | Critical |
86
+ | Authorisation check fails open on an unhandled exception | High |
70
87
  | Certificate verification disabled | High |
71
- | Authorisation checked on route but not on resource | High |
88
+ | Authorisation checked on route but not on resource (BOLA) | High |
72
89
  | Wildcard CORS with credentials | High |
73
90
  | Non-constant-time secret comparison | Medium |
74
91
  | Missing cookie security attributes | Medium |
@@ -0,0 +1,73 @@
1
+ # State Model
2
+
3
+ Does every declared state get reached, and does everything that reads it agree on what it means? Gate: enumerated states, a status column, or a state library was detected.
4
+
5
+ This module audits explicit state machines and status fields — the enum, the `status` column, the state chart — as data. It does **not** own how a flow gets wired to UI events or navigation; that is `flow-integrity.md`. It does **not** own where a React component's or a store's state lives, or whether it is over- or under-lifted; that is `frontend.md`. If a check here starts asking "who calls `setState`", it belongs in one of those two instead.
6
+
7
+ A formal state model — a statechart, in Harel's original sense, standardised by the W3C as SCXML (a Recommendation since September 2015) and popularised in the JS ecosystem by XState — gives a codebase something a flat enum plus `switch` cannot express on its own: hierarchical (nested) states for sub-states that only carry meaning inside a parent, orthogonal/parallel regions for independent facets of status varying at once without a combinatorial cross-product enum, and a transition table where an edge must exist for a move to be legal at all, rather than any state being reachable from any other just because a write path didn't check. Every check below is, in effect, asking whether the codebase's enum-plus-switch is honouring guarantees a real state machine would have enforced structurally.
8
+
9
+ ## Enumerate the state set
10
+
11
+ - [ ] Find every declaration of the state set: an enum, a union type, a database column's `CHECK` constraint or comment listing valid values, a state-machine library's chart definition (XState, a `transitions` table). `find_symbol` on the type/enum name to get the canonical list.
12
+ - [ ] Find every place that switches on it: `find_callers` on the enum/type, then read each `switch`/`match`/if-chain for completeness against the list above.
13
+ - [ ] Note the state set's shape once, in prose, so every later check has a fixed reference — this is the yardstick, same discipline as establishing the token vocabulary in `design-system.md`.
14
+
15
+ ## Declared but unreachable
16
+
17
+ - [ ] A state present in the enum that no code path ever assigns. `search_code` the state's literal value as an assignment target (`status = 'archived'`, `.setState(Status.Archived)`); if nothing assigns it, it is dead data, not dead code — cross-reference `reachability.md` for the mechanics but report the finding here since the enum is the artefact.
18
+ - [ ] A state assigned only in a test fixture or seed script, never by application logic — the same shape, one layer removed.
19
+
20
+ ## Assigned but unhandled
21
+
22
+ - [ ] The inverse and more dangerous gap: a state that gets assigned somewhere but that a `switch`/`match` elsewhere doesn't handle. Read each switch site found via `find_callers` above for a **missing `default`/`else` arm** — code that silently falls through and does nothing is worse than a crash, because nothing signals the gap ever fired.
23
+ - [ ] `search_code` for the exhaustiveness marker itself (`: never`, `assertNever(`, `@Exhaustive`, a sealed-class `when` in Kotlin). Its absence at a switch site is exactly what let the current gaps exist, and adding it is the fix that prevents the next one. Cross-reference `type-safety.md` if the exhaustiveness gap is hidden behind an `any`/suppressed cast.
24
+ - [ ] Among the switch sites read above, a `default`/`else` arm that maps every unrecognised state to some fallback value rather than erroring or logging — a milder form of the same gap: it hides a genuinely unhandled state behind output that looks intentional, so nobody notices the switch was incomplete.
25
+ - [ ] Every creation path (constructor, insert, factory function) assigns one of the declared states explicitly. `search_code` the record's construction sites; a field left `null`/undefined at insert time behaves as a phantom extra state that no switch was written to handle.
26
+
27
+ ## Transitions
28
+
29
+ - [ ] Every transition path is deliberate: `trace_path` (or a straightforward read of the transition table) from each state to the states it's allowed to reach. A transition with no guard — any state can jump to any other by just setting the field — is not a state machine, it's a label.
30
+ - [ ] Transitions that skip a declared intermediate state. If the model says `draft → review → published`, `search_code` every write site setting `published` directly (`status = 'published'`, `.setState(Status.Published)`) and check its originating state — confirm any direct `draft → published` write is intentional (an admin override) rather than a bypass nobody meant to allow.
31
+ - [ ] Terminal states with a way out that shouldn't exist — `search_code` for a write to the state field inside any code path reachable after a `cancelled`/`refunded`/terminal check, e.g. `if (status === 'cancelled') { ... status = ... }`.
32
+ - [ ] Non-terminal states with no path forward at all: cross-check the transition table built above — any state that appears as a **target** of some transition but never as a **source** of one. Records land there and stay forever. Rule out first: a manual/support-only transition that's real but undocumented in code (an admin panel, a direct DB fix) — state which you checked.
33
+
34
+ ## Duplicated state sets
35
+
36
+ - [ ] The same conceptual state set declared twice — a backend enum and a frontend union, a database `CHECK` constraint and a client-side type — and already out of sync. Diff the literal member lists; a backend value with no frontend counterpart renders as `undefined`/a blank label, not an error. **Cross-reference `cross-surface-parity.md`**, which owns diverged behavioural rules between surfaces; this module reports the divergence, that module tracks the general pattern.
37
+ - [ ] Where a shared type is meant to be the single source, `search_code` the second surface's directory for a local re-declaration of the same enum/union name rather than an import from the shared location — a local copy that happens to match today is the drift waiting to happen.
38
+
39
+ ## Persisted values the code no longer knows about
40
+
41
+ - [ ] Values existing in stored data (a `status` column, a serialized state field) that don't appear in the current enum at all — the fingerprint of a state renamed or removed without a data migration. `search_code` for the old name in migration history or a comment; if the current switch has no case for it, every row carrying that value falls through the unhandled-state gap above, silently, in production, for real records.
42
+ - [ ] `search_code` migration files for an `ALTER`/`CHECK`-constraint change to the state column with no accompanying `UPDATE` statement backfilling the old values to a valid new one.
43
+
44
+ ## Concurrency on transitions
45
+
46
+ - [ ] `search_code` each transition function found above for a read-then-write shape (fetch the record, check its current state, then write the new one) with no atomic guard — optimistic lock, unique constraint, or conditional `UPDATE ... WHERE status = ...`. Two concurrent requests (a double-submit, a webhook retry) racing this gap will both pass the check and both write. Cross-reference `concurrency.md`'s read-modify-write section; report the state-specific instance here.
47
+ - [ ] A self-transition (a record transitioning back into the state it's already in) unintentionally re-firing side effects — a confirmation email, a webhook, a billing event — that were meant to fire once on entry. `find_callees` on the transition handler to see what it triggers, then check whether it guards on "value actually changed" before triggering them.
48
+
49
+ ## Display and downstream consumers
50
+
51
+ - [ ] `search_code` the label/badge/translation lookup that renders the state to a user and diff its case list against the canonical enum from the first section. A state with no display case renders a blank, the raw enum key, or throws, depending on the language's default behaviour for an unmatched case.
52
+ - [ ] `search_code` filter and sort UI (a dashboard's status filter, a report's grouping control) for a hardcoded local list of state values, and diff it against the canonical enum — a state added later silently never appears as a filter option, and records in it become invisible to anyone filtering.
53
+
54
+ ## Out of static reach
55
+
56
+ - Whether an admin-only or support-tooling transition is intentional versus a bypass — usually needs a person to confirm.
57
+ - The actual frequency a given transition fires in production, which decides how urgent an unguarded race really is.
58
+ - Whether a "stuck" non-terminal state is a real dead end or one only reachable through an out-of-repo system (a support queue, a manual ops runbook).
59
+
60
+ ## Severity guidance
61
+
62
+ | Situation | Severity |
63
+ |---|---|
64
+ | Persisted value with no current code path that handles it | Critical |
65
+ | Assigned state with no handling branch (silent no-op) | High |
66
+ | Transition with no guard, reachable from any state | High |
67
+ | Non-terminal state with zero outgoing transitions | High |
68
+ | Same state set duplicated across surfaces and diverged | High |
69
+ | Transition skipping a declared intermediate state | Medium |
70
+ | Terminal state with an unintended exit path | Medium |
71
+ | Missing exhaustiveness check on a state switch | Medium |
72
+ | Declared state never assigned by any code path | Medium |
73
+ | Race on a transition with no atomic guard | Medium (High if it double-charges/double-ships) |
@@ -0,0 +1,64 @@
1
+ # Supply Chain
2
+
3
+ Can the artefact you ship be trusted, and can the build that produced it be reproduced? Gate: a lockfile or dependency manifest is present.
4
+
5
+ `dependencies-licensing.md` owns *which* dependencies exist — their weight, health, and licences. This module does not repeat that inventory; it owns a different question: how each dependency **arrives**, whether the version that lands on a machine is the version anyone reviewed, and whether the build pipeline itself is a trusted, reproducible thing. A project can have perfectly healthy, permissively-licensed dependencies and still be compromised at the point where they are fetched, installed, or published — that gap is this module's entire scope, and it is no longer a specialist corner: OWASP's Top 10:2025 ranks it **A03:2025 — Software Supply Chain Failures**, a top-three category, widened from 2021's narrower A06 "Vulnerable and Outdated Components" (which only covered *using* a component with a known vulnerability) to the whole chain of how a dependency arrives. That 2021→2025 widening is exactly the line this module draws against `dependencies-licensing.md`.
6
+
7
+ ## Install-time execution
8
+
9
+ - [ ] `search_code` the project's own manifest for `postinstall`, `preinstall`, and `prepare` scripts, and — for any package with native bindings — a `binding.gyp` file. Lifecycle scripts are not the only install-time execution vector: 2026 npm worm campaigns shipped a weaponised `binding.gyp` that triggers `node-gyp` to run attacker code during `install`, specifically because scanners that only watch the `scripts` field miss it.
10
+ - [ ] Whether the install pipeline disables or audits scripts from dependencies — `search_code` CI config and root config files for `--ignore-scripts` (npm/pnpm), `enable-scripts` (yarn), or `trustedDependencies` (bun). **Falsify before flagging as missing**: some package managers ship this off by default and rely on an allowlist file instead — confirm the allowlist exists rather than assuming no gate at all.
11
+ - [ ] If scripts are not disabled, whether any allowlist restricts which packages may run them — `search_code` for `trustedDependencies`, an `.npmrc` scripts setting, or the package manager's equivalent — rather than trusting the entire dependency tree by default.
12
+
13
+ ## Lockfile integrity
14
+
15
+ - [ ] Lockfile present and committed — `get_architecture` packageManager, then confirm the lockfile file itself is tracked (`search_code` or a direct path check), not merely present on disk and gitignored.
16
+ - [ ] Manifest ranges the lockfile actually satisfies. Read a sample of `dependencies` entries against their resolved lockfile versions — a range the lockfile does not satisfy means a fresh `install` on CI resolves something nobody tested locally. This is the single most common source of "works on my machine, breaks in CI."
17
+ - [ ] In a monorepo, every workspace has its dependencies covered by the root lockfile — `search_code` for a `workspaces` / `packages` field, then confirm no workspace manifest references a dependency absent from the lockfile.
18
+ - [ ] Integrity hashes present for every lockfile entry (`integrity`, `resolved` + checksum, or the package manager's equivalent). An entry with a version but no hash trusts the registry's word at every future install, not just this one.
19
+ - [ ] Only one package manager's lockfile is present. Two lockfiles from different tools (`package-lock.json` alongside `pnpm-lock.yaml`) means whichever one CI happens to read is the one actually enforced, and a developer using the other tool silently resolves a different tree.
20
+ - [ ] What "locked" means for this ecosystem, checked rather than assumed. `Cargo.lock`, `package-lock.json`/`pnpm-lock.yaml`/`bun.lock`, and `uv.lock` each pin the full resolved dependency graph with a per-entry hash — `go.sum` does not: it is an append-only checksum ledger for modules already downloaded, not a resolved-graph lock, so read it alongside `go.mod` under `-mod=readonly` rather than treating it as equivalent. A Python project's `requirements.txt` with exact `==` pins looks locked but carries no hash unless generated with `--require-hashes` (e.g. via `pip-compile --generate-hashes`) — `search_code` for the flag before assuming pinned means verified.
21
+
22
+ ## Provenance and pinning
23
+
24
+ - [ ] A minimum-release-age (cooldown) is configured so a freshly-published version cannot resolve immediately — `search_code` for npm's `min-release-age`, pnpm's `minimumReleaseAge` (paired with `trustPolicy: no-downgrade`, pnpm ≥10.21), or Bun's `install.minimumReleaseAge` in `bunfig.toml` (Bun ≥1.3). Most compromised releases are pulled within hours; its absence means every install races the takedown.
25
+ - [ ] Dependency sources beyond the default registry — `search_code` the lockfile for `git+`, `github:`, direct tarball URLs, or `file:`/`link:` local paths. Each is a supply-chain path the registry's own integrity checks do not cover.
26
+ - [ ] Any git-sourced dependency pinned to a branch or tag rather than a commit SHA — read the lockfile's `git+` entries for a `#<sha>` suffix versus a branch or tag name. A branch ref is mutable — the maintainer can push different code to it tomorrow and every future install silently picks it up.
27
+ - [ ] CI action versions pinned by a full 40-character commit SHA, not a moving tag — the only form GitHub treats as immutable (`uses: actions/checkout@11bd719… # v4.2.2` vs `@v4`) — `search_code` workflow files for `uses:` lines. GitHub's actions-policy can enforce this org-wide (SHA-pinning policy, GA since August 2025); a repo relying on that alone, rather than the pin itself, is still unproven from source.
28
+ - [ ] Container base images pinned by digest (`FROM image@sha256:…`) rather than a tag that can be repointed (`:latest`, `:20`) — `search_code` Dockerfiles for `FROM`.
29
+
30
+ ## Release and publish trust
31
+
32
+ - [ ] SBOM generation as part of the release process — `search_code` release workflows for an SBOM tool invocation (`cyclonedx`/`cdxgen` for CycloneDX (spec 1.7, Mar 2026 — the final release in the 1.x line, backward compatible with 1.4–1.6; 2.0 is expected later in 2026, so a reader re-checking this later should confirm 1.7 is still current), `syft` for SPDX (spec 3.0.1, current since the 3.0 line shipped Apr 2024; a 3.1 release candidate is underway), `npm sbom`, or equivalent) and confirm the output is actually published as a release artefact, not just generated and discarded.
33
+ - [ ] Provenance or attestation on published artefacts — `search_code` for `npm publish --provenance`, PyPI Trusted Publishing, a `cosign sign`/`cosign attest` step, or GitHub's `actions/attest-build-provenance` action. All four now produce a DSSE-wrapped in-toto statement verifiable with a single tool (cosign v3 reads npm provenance, GitHub Attestations, and Homebrew provenance alike) — confirm the step exists, not that anyone has ever run verification against it.
34
+ - [ ] Who can publish the artefact — `search_code` the publish workflow for the trigger condition (tag push, manual approval, protected branch) and whether the publishing token is scoped to this package alone or holds broader org access.
35
+ - [ ] Whether publishing requires a review gate — `search_code` the publish workflow for a required-approval step or a branch-protection prerequisite before the tag that triggers release — rather than firing on any push to a default branch.
36
+
37
+ ## Impersonation and unvetted origin
38
+
39
+ - [ ] Internal-looking package names resolved from a public registry rather than a private one — read the manifest for names that look like internal tooling (`@company/*`, `internal-*`) and confirm they resolve from a scoped/private registry, not the public one, where a typosquat could sit under the same unscoped name.
40
+ - [ ] Vendored or copied third-party code with no recorded origin — `search_code` for a directory of third-party-looking code with no corresponding manifest entry, no `LICENSE`, and no comment naming its source or version. This is the one class of risk no dependency tool will ever surface, because it was never declared a dependency at all.
41
+
42
+ ## Out of static reach
43
+
44
+ - Whether a registry package's published tarball actually matches its public source repository at that version — requires fetching and diffing both, not reading the manifest.
45
+ - Runtime behaviour of any postinstall script or `binding.gyp`-triggered native build — this module can enumerate that scripts (or build files) exist, not what they do without executing them.
46
+ - Whether `--ignore-scripts` (or its equivalent) is actually honoured at install time in CI, versus merely configured somewhere and silently overridden.
47
+ - Registry-level compromise of a dependency between the version pinned in the lockfile and what a fresh resolve would fetch today.
48
+ - Whether the SBOM checked into the release matches the artefact that was actually built and shipped, rather than one generated from a different commit.
49
+
50
+ ## Severity guidance
51
+
52
+ | Situation | Severity |
53
+ |---|---|
54
+ | Git dependency pinned to a mutable branch, not a commit | High |
55
+ | Postinstall scripts enabled with no allowlist across the full dependency tree | High |
56
+ | Lockfile absent, uncommitted, or not satisfying the manifest range | High |
57
+ | Publish token unscoped or publish requires no review gate | High |
58
+ | Internal-looking package name resolving from the public registry | High |
59
+ | CI action or base image pinned by moving tag, not digest/SHA | Medium |
60
+ | No SBOM or provenance attestation in the release process | Medium |
61
+ | Vendored code with no recorded origin or version | Medium |
62
+ | Lockfile entry missing an integrity hash | Medium |
63
+ | Monorepo workspace not covered by the root lockfile | Medium |
64
+ | No minimum-release-age / cooldown configured on the package manager | Medium |
@@ -0,0 +1,66 @@
1
+ # Temporal
2
+
3
+ Does the code agree with itself about what time it is? Gate: dates, schedules, expiry, or scheduling logic present.
4
+
5
+ `database.md` notes, in one line, whether timestamp columns are timezone-aware. `testing.md` notes, in one line, whether tests depend on wall-clock time. Neither goes further than that. This module owns everything else about temporal correctness: the instant-versus-civil-time distinction that causes most date bugs, DST arithmetic, serialisation at every boundary, and the clock as a dependency nobody injected. If a finding is about the *storage type* of a column, it belongs in `database.md`; if it is about *what the code does* with the value once read, it belongs here.
6
+
7
+ The instant/civil distinction this module probes for by hand is, as of ECMAScript 2026, a distinction the language itself now names: TC39's Temporal proposal reached Stage 4 in March 2026 and ships unflagged in Firefox 139+, Chrome/Edge 144+, and Node.js 26+ (not yet in Safari as of this writing) — `Temporal.Instant` for a fixed point in time, `Temporal.PlainDateTime`/`Temporal.PlainDate` for a genuinely civil value with no zone attached, and `Temporal.ZonedDateTime` for a value that carries both. A codebase still on a modern runtime but exclusively using legacy `Date` for a "deliver at 9am local" feature had, until recently, no first-party type to reach for instead — that gap is closing, and its presence is useful context, not itself a defect.
8
+
9
+ ## Storage and representation
10
+
11
+ - [ ] Every timestamp column's declared type: `search_code` the schema/migrations for date fields, then `find_symbol` the column type. `TIMESTAMP WITHOUT TIME ZONE` (or a driver default that behaves like it) storing a value the application treats as an instant is a defect — the offset is silently lost, and every read is a guess about what zone it was written in.
12
+ - [ ] The inverse: a genuinely civil datetime — "9am local, wherever local is" — stored in a timezone-aware column. This double-converts on every read, because the column assumes a single instant and civil time by definition is not one.
13
+ - [ ] Naive local time (`new Date()`, `datetime.now()`, `time.Now()` with no explicit zone) used at a boundary that is supposed to represent a fixed instant — a token expiry, an audit log entry, a scheduled-at field. Rule out first: a value that is genuinely display-only and never compared or persisted is not a defect.
14
+ - [ ] The instant/civil conflation itself: a "deliver at 9am" feature that stores a single UTC instant instead of a wall-clock time plus a zone. This is correct in the sender's zone and wrong in every other zone, and DST will additionally shift it twice a year.
15
+
16
+ ## DST and calendar arithmetic
17
+
18
+ - [ ] Any `addDays`/`addHours`-style call used to mean "the same wall-clock time tomorrow" rather than "24 hours from now" — `search_code` for day-arithmetic helpers and read what they add. Adding 24 hours across a DST transition lands one hour off the intended wall-clock time.
19
+ - [ ] Recurring schedules (`search_code` for cron-like fields, `RRULE`, or a "repeat every" config) evaluated in a fixed offset rather than a named zone. A schedule anchored to `UTC-5` drifts by an hour relative to local time twice a year; one anchored to `America/Bogota` does not, because Bogota has no DST — the distinction matters exactly where DST exists.
20
+ - [ ] Time ranges spanning a "spring forward" gap (a wall-clock hour that never occurs) or a "fall back" overlap (an hour that occurs twice). A range built from raw wall-clock start/end without zone-aware arithmetic can silently normalise a nonexistent time to something else, or double-count the ambiguous hour.
21
+ - [ ] Whether ambiguous/nonexistent-hour disambiguation is explicit at each construction site rather than left to whatever the library defaults to — `search_code` for tz-aware datetime construction (Python's `fold` attribute or `is_dst=`, JS's `Temporal.ZonedDateTime.from(..., { disambiguation })`) with no argument supplied. Defaults genuinely differ by library and this is a common false assumption: Python's `zoneinfo` (PEP 495) and `pytz` both silently pick a side (the earlier occurrence, or `is_dst=False`) with no error, while `pandas.Series.dt.tz_localize` raises by default (`ambiguous='raise'`, `nonexistent='raise'`) — a codebase mixing both in one pipeline can have one path fail loudly and the adjacent one fail silently on the same kind of input.
22
+ - [ ] Month-end and leap-year arithmetic: adding a month to 31 January, or a year to 29 February. `search_code` for manual `setMonth`/`setDate`/`setFullYear` chains rather than a date library's calendar-aware add.
23
+ - [ ] Week-numbering assumptions (ISO week vs. US week, week start on Sunday vs. Monday) applied inconsistently between a report and the UI that renders it.
24
+ - [ ] A container/base-image build (`Dockerfile`, base-image manifest) with no mechanism to keep its bundled tz database current — `search_code` the Dockerfile for a `tzdata` package install with no update step, or a base image pinned by digest with no rebuild trigger. The IANA tz database releases several times a year whenever a government changes DST/offset rules (real 2026 examples: Alberta moving to permanent UTC-6, Morocco moving to permanent UTC+0); an image built once and never rebuilt computes the *old* rule for that zone until it is, which reproduces as "the time is right most of the year, then off by an hour around the transition." This is a `read` finding on the Dockerfile itself, not a claim about the deployed environment's actual tzdata version — that stays under Out of static reach.
25
+
26
+ ## Serialisation and boundaries
27
+
28
+ - [ ] Every wire boundary — API response, queue payload, log line, cache key — for date fields: does serialisation preserve the offset (ISO 8601 with `Z`/offset, or an explicit epoch) or silently drop it (a bare `YYYY-MM-DD HH:mm:ss`)? `search_code` the serializer/formatter used at each boundary. A numeric offset alone (`-04:00`) doesn't say which named zone/DST rule produced it — RFC 9557's Internet Extended Date/Time Format (IXDTF, the format `Temporal.ZonedDateTime.toString()` emits) adds a bracketed zone-name suffix (`-04:00[America/New_York]`) precisely to keep that disambiguated across a wire boundary; its absence isn't a defect on its own, but a codebase reinventing the same suffix ad hoc is a signal to check the two ends actually agree on the convention.
29
+ - [ ] A queue payload or webhook body carrying a naive timestamp string with no documented zone contract between producer and consumer — `trace_path` from producer to consumer to confirm both sides agree, rather than assuming they do.
30
+ - [ ] Comparisons between values of different kinds — an instant compared to a civil datetime, or a stored UTC value compared to a freshly-constructed local `Date` without normalising both sides first.
31
+ - [ ] `now()` (or its language equivalent) called more than once within a single logical operation — `search_code` for repeated `Date.now()`/`time.Now()` calls inside one function or one request. Two calls milliseconds apart can straddle a rounding boundary and disagree, and a "created before it expired" check built from two separate `now()` reads is not atomic.
32
+
33
+ ## Clock as a dependency
34
+
35
+ - [ ] `Date.now()`, `new Date()`, or the platform equivalent called directly deep inside business logic rather than through an injected clock/`now` parameter. `find_callers` on the logic function — if none of its callers can supply a fixed time, the logic is untestable for anything time-dependent and every "what happens near midnight / near expiry" case is unverifiable without wall-clock waiting.
36
+ - [ ] Expiry and TTL arithmetic: off-by-one at the boundary (`<` vs `<=` against the expiry instant), and which clock performs the check — client-supplied time versus server time. A client clock that is wrong, or deliberately manipulated, must never be the authority for an expiry decision.
37
+ - [ ] Cron/schedule expressions read against their documented intent — `search_code` the expression and compare it to what the surrounding comment or config name claims it does. A drifted expression (`0 0 * * 1` labelled "daily") is a silent scope change.
38
+ - [ ] What happens to a missed scheduled run (process was down, deploy in progress): does the job catch up, skip, or run every missed occurrence at once on restart? `find_callees` from the scheduler entry point to see if a catch-up path exists at all.
39
+
40
+ ## Presentation
41
+
42
+ - [ ] User-facing date/time formatting rendered in the server's zone rather than the user's — `search_code` for a formatter call with no zone argument on a value ultimately shown to a user. Cross-reference `i18n.md` for locale-specific format conventions (12h/24h, date order); this module owns whether the *zone* is right, `i18n.md` owns whether the *format* is right.
43
+
44
+ ## Out of static reach
45
+
46
+ - Whether a DST transition actually reproduces the bug in the deployed environment's real timezone database version.
47
+ - Clock skew between distributed nodes at runtime.
48
+ - Whether a cron scheduler's actual trigger times match the expression under real load (delayed execution, overlapping runs).
49
+ - User-perceived correctness of "relative time" displays ("3 hours ago") as real time elapses.
50
+
51
+ ## Severity guidance
52
+
53
+ | Situation | Severity |
54
+ |---|---|
55
+ | Instant stored as naive local time at a security-relevant boundary (token/session expiry) | Critical |
56
+ | Expiry checked against client-supplied clock | High |
57
+ | Timestamp column type disagrees with what the application treats it as | High |
58
+ | Serialisation drops offset at a cross-service boundary | High |
59
+ | `addDays`-style arithmetic used across a DST boundary for wall-clock intent | Medium |
60
+ | Ambiguous/nonexistent-hour disambiguation left to an unstated library default | Medium |
61
+ | `now()` called multiple times in one operation with no single source of truth | Medium |
62
+ | Hardcoded clock access preventing time-dependent logic from being tested | Medium |
63
+ | Missed-schedule catch-up behaviour undefined | Medium |
64
+ | User-facing time rendered in server zone instead of user zone | Medium |
65
+ | Base image with no tzdata update mechanism | Low |
66
+ | Week-numbering or month-end drift between two surfaces | Low |
@@ -2,45 +2,68 @@
2
2
 
3
3
  Gate: test files are present **or conspicuously absent**. The absence case is the point — "this project has no tests" is a finding, not a reason to skip the module.
4
4
 
5
- Coverage percentage is not the question. The question is: **which defects would this suite have caught?** Take the findings from the other modules and ask, for each, why no test failed.
5
+ Coverage percentage is not the question, and that is not a stylistic preference — it is what the evidence shows. The largest study to date on real (not injected) defects — Zhang et al., "Code Coverage and Post-release Defects," *IEEE Transactions on Reliability*, 2017, 100 large open-source Java projects — found coverage has an **insignificant correlation** with post-release defect counts. Mutation testing correlates better with real fault detection, because it measures whether the suite would actually catch a change rather than whether a line merely executed, but computing a mutation score means running the suite against generated mutants — out of reach for this module. The question this module *can* answer by reading alone is: **which defects would this suite have caught?** Take the findings from the other modules and ask, for each, why no test failed.
6
+
7
+ There is no universal "correct" shape to check the suite against, either. The classic pyramid (many unit, fewer integration, few end-to-end) and Kent C. Dodds' "testing trophy" (weighted toward integration) are both defensible depending on where a project's defects actually originate — do not flag a project for favouring one over the other. What *is* a real finding is a mismatch between where tests concentrate and where risk concentrates: cross-reference `complexity.md`'s high-blast-radius symbols and `reachability.md`'s boundaries, then `search_code` those symbol names against the test suite. Heavy coverage on trivial code next to none on the central, high-blast-radius symbols is a gap regardless of which shape the suite otherwise resembles.
8
+
9
+ Everything below is established by reading test source and config — this module never runs the suite.
6
10
 
7
11
  ## Does the suite prove anything
8
12
 
9
- - [ ] For each confirmed finding elsewhere in this audit, identify the missing test. That list is the most valuable output of this module.
10
- - [ ] Tests assert behaviour, not implementation. A test that breaks on every refactor and passes through every real bug is negative value.
11
- - [ ] Tests would fail if the feature broke. Try it mentally on the most important test: mutate the logic and ask whether an assertion catches it.
12
- - [ ] No test asserts only that a function was called. Call-count assertions on a mock prove the test's own wiring.
13
- - [ ] Assertions are specific — `toEqual` on a shape rather than `toBeDefined`, expected values rather than `expect.anything()`.
13
+ - [ ] For each confirmed finding elsewhere in this audit, identify the missing test — `search_code` the file/function named in the finding against the test suite; no matching test file or describe block is the gap. That list is the most valuable output of this module.
14
+ - [ ] Tests assert behaviour, not implementation — read each test's assertions. A test that breaks on every refactor and passes through every real bug is negative value.
15
+ - [ ] Tests would fail if the feature broke — pick the most important test, read the implementation it covers, and mentally invert one condition. If no assertion in the test would catch the inversion, the test is not proving what it claims to.
16
+ - [ ] No test asserts only that a function was called — `search_code` for `toHaveBeenCalled()`/`toHaveBeenCalledWith()` with no accompanying assertion on a return value or side effect in the same test. Call-count assertions on a mock prove the test's own wiring, not the behaviour.
17
+ - [ ] Assertions are specific — `search_code` for `toBeDefined()`, `toBeTruthy()`, `expect.anything()`, `assert.ok(` used where a specific expected value would fit. These pass on almost anything.
18
+ - [ ] A test with many unlabelled assertions makes its own failure hard to diagnose — `search_code` test bodies for more than two or three bare assertion calls with no message argument and no single clear behaviour under test ("Assertion Roulette," a catalogued test smell). This is a maintainability finding, not a correctness one: the test still catches the bug, it just won't say which assertion caught it.
19
+
20
+ ## Test doubles
21
+
22
+ - [ ] Mocks target code the project owns, not a third-party SDK or framework class reached directly — `search_code` the test suite for a mock/stub/spy applied to an imported third-party package. A mock of a dependency you don't own encodes an assumption about that dependency's contract that nothing revalidates; the contract can drift after a version bump while the mock — and the test — keeps passing. ("Don't mock what you don't own" — Freeman & Pryce, *Growing Object-Oriented Software, Guided by Tests*; reinforced in Google's own testing guidance.)
23
+ - [ ] Where the codebase already wraps a third-party dependency in its own adapter, confirm tests mock the adapter and not the raw import — `search_code` for both the adapter's own test double and a direct mock of the underlying package inside the same test file. A test still reaching past the adapter defeats the reason the adapter exists.
14
24
 
15
25
  ## What is not covered
16
26
 
17
- - [ ] Error paths. Most suites test only the happy path; cross-reference `failure.md` and check each error branch has a test.
18
- - [ ] Boundaries: empty, one, many, maximum, negative, zero, unicode, very long.
19
- - [ ] Concurrency. Tests run operations one at a time, which is why the defects in `concurrency.md` survive green suites. Note explicitly which are untestable as written.
20
- - [ ] Idempotency and re-run paths.
21
- - [ ] Migration and upgrade paths — reading state written by the previous version.
22
- - [ ] The packaged artefact, as a consumer would use it. Cross-reference `packaging.md`: the suite runs from the repository where every file exists, which is exactly why it misses packaging bugs.
27
+ - [ ] Error paths — `search_code` each `throw`/rejected-promise site in the implementation, then `search_code` the test suite for a matching "throws"/"rejects" assertion. Most suites test only the happy path; cross-reference `failure.md`.
28
+ - [ ] Boundaries: empty, one, many, maximum, negative, zero, unicode, very long — `search_code` the test suite for these literal values (`''`, `0`, `-1`, `[]`) against the function under test. Their absence is the gap.
29
+ - [ ] Concurrency — `search_code` the test suite for `Promise.all`, parallel invocation, or a lock/mutex test. Tests run operations one at a time, which is why the defects in `concurrency.md` survive green suites. Note explicitly which are untestable as written.
30
+ - [ ] Idempotency and re-run paths — `search_code` for a test that invokes the same operation twice and asserts the second call's effect. Its absence next to an idempotency claim elsewhere in the code is the gap.
31
+ - [ ] Migration and upgrade paths — `search_code` test fixtures for one representing state written by a previous schema or version. Reading only current-shape fixtures means the suite never proves an upgrade path works.
32
+ - [ ] The packaged artefact, as a consumer would use it — `search_code` for a test that imports from the built output (`dist/`, the packed tarball) rather than source. The suite runs from the repository where every file exists, which is exactly why it misses packaging bugs. Cross-reference `packaging.md`.
23
33
 
24
34
  ## Test isolation
25
35
 
26
- - [ ] **No test writes outside its own temporary directory.** Check for writes derived from the home directory, a global config path, or a shared data directory. A test that pollutes the developer's real environment is `High` — and it is easy to introduce accidentally when production code resolves paths from `homedir()`.
27
- - [ ] Injection seams exist for anything that resolves a real path, spawns a process, or reaches the network — and the tests actually use them.
28
- - [ ] Tests do not depend on execution order or on each other's leftovers.
29
- - [ ] Each test cleans up on both the pass and the fail path.
30
- - [ ] Nothing hits a real paid or external endpoint. Cross-reference `cost.md`.
36
+ - [ ] **No test writes outside its own temporary directory.** `search_code` test files for `homedir()`, `os.homedir()`, a hardcoded absolute path, or a shared config/data directory. A write derived from any of these pollutes the developer's real environment and is `High` — and it is easy to introduce accidentally when production code resolves paths from `homedir()`.
37
+ - [ ] Injection seams exist for anything that resolves a real path, spawns a process, or reaches the network — `search_code` test files for direct `fs.`, `child_process.`, or `http.`/`fetch(` calls that bypass a mock or an injected client. A direct call means the seam either doesn't exist or isn't used.
38
+ - [ ] Tests do not depend on execution order or on each other's leftovers — `search_code` for module-level mutable state written in one test and read in another (a shared fixture reused without `beforeEach` resetting it).
39
+ - [ ] Each test cleans up on both the pass and the fail path — `search_code` for cleanup code placed inside the test body versus inside `afterEach`/`finally`. Cleanup only at the end of the body is skipped whenever an earlier assertion throws.
40
+ - [ ] Nothing hits a real paid or external endpoint — `search_code` for a live API base URL, an unmocked SDK client, or a real API key referenced inside a test file. Cross-reference `cost.md`.
31
41
 
32
42
  ## Determinism
33
43
 
34
- - [ ] No dependence on wall-clock time, current date, timezone, or locale without control.
35
- - [ ] No dependence on unseeded randomness.
36
- - [ ] No fixed sleeps standing in for synchronisation — that is a flake with a timer.
37
- - [ ] No dependence on a fixed port, or ports are allocated dynamically. Fixed ports collide under parallel runs and in CI.
38
- - [ ] **Known flaky tests are tracked, not tolerated.** A test that fails one run in ten is a real signal being discarded. Report each one with its observed failure rate.
44
+ Flaky-test root causes have a stable, well-studied taxonomy (Luo et al., FSE 2014, independently reconfirmed since) clustering into non-determinism (races, shared mutable state, unseeded randomness), environment dependence (CI runner, timezone, locale), and order dependence (a test's pass depends on what ran before it). Of these, only non-determinism and order dependence leave a trace readable without executing the suite repeatedly — environment dependence is out of static reach entirely. The checks below, plus the isolation checks above, are what that reading finds.
45
+
46
+ - [ ] No dependence on wall-clock time, current date, timezone, or locale without control — `search_code` for `new Date()`/`Date.now()` inside code the tests exercise, and check whether the suite injects or freezes the clock (fake timers, an injected clock parameter) rather than reading the real one.
47
+ - [ ] No dependence on unseeded randomness — `search_code` for `Math.random(` (or the language equivalent) in tested logic and confirm the test either seeds it or mocks the call.
48
+ - [ ] No fixed sleeps standing in for synchronisation — `search_code` test files for `sleep(`/`setTimeout(` used to wait for an async operation instead of awaiting it directly. That is a flake with a timer.
49
+ - [ ] No dependence on a fixed port, or ports are allocated dynamically — `search_code` test setup for a literal port number (`.listen(3000)`). Fixed ports collide under parallel runs and in CI.
50
+ - [ ] **Known flaky tests are tracked, not tolerated.** `search_code` for `test.skip`, `.only`, a retry/`flaky` annotation, or a comment naming a test as unreliable. A test that fails one run in ten is a real signal being discarded — report each one with its observed failure rate if the repo records it (a CI badge, a flake-tracking issue).
39
51
 
40
52
  ## Guard tests
41
53
 
42
- - [ ] Where the codebase depends on two things agreeing — a manifest and a directory, a schema and a model, a gate table and a file set — a test asserts the agreement. Hand-maintained lists are fine; unguarded hand-maintained lists are not.
43
- - [ ] **A guard nobody has watched fail is not a guard.** Verify each one by mutation: break the invariant deliberately, confirm the test fails, revert. Report guards that pass unconditionally.
54
+ - [ ] Where the codebase depends on two things agreeing — a manifest and a directory, a schema and a model, a gate table and a file set — a test asserts the agreement. `search_code` for both things being compared (the manifest read, the directory listing) inside the test suite. Hand-maintained lists are fine; unguarded hand-maintained lists are not.
55
+ - [ ] **A guard that cannot fail is not a guard.** Read the assertion itself rather than running it: an assertion comparing a value to itself (`expect(x).toEqual(x)`), one wrapped in a `try`/`catch` that swallows the failure, one behind a condition that is never true, or one that checks only that a function returned rather than what it returned — none of these can ever fail, regardless of what changes underneath them. Flag any guard test whose assertion has this shape.
56
+
57
+ ## Out of static reach
58
+
59
+ - Whether the suite actually passes right now — this module reads test source and config, it does not execute anything.
60
+ - Real flake rate — only observable from CI run history, which may live outside this repo's version control.
61
+ - Whether an order-dependency or shared-state pattern flagged above has ever actually produced a real race — confirming that requires executing under contention, not reading. Cross-reference `concurrency.md`.
62
+ - Environment-dependent flakiness (CI runner differences, resource limits, network latency) — invisible until the suite runs somewhere other than where it was written.
63
+ - Whether a mocked network or filesystem seam faithfully reproduces the real dependency's failure modes.
64
+ - Coverage percentage as measured by a coverage tool — this module infers gaps from what it reads, it does not instrument a run.
65
+ - Mutation score — the more strongly-correlated measure of test quality; this module can note the absence of a mutation-testing tool in the project config, but cannot compute or estimate the score itself.
66
+ - Whether a guard test that is structurally capable of failing has ever actually caught a real regression.
44
67
 
45
68
  ## Severity guidance
46
69
 
@@ -55,4 +78,6 @@ Coverage percentage is not the question. The question is: **which defects would
55
78
  | No test for any error path | Medium |
56
79
  | Fixed sleep standing in for synchronisation | Medium |
57
80
  | Fixed port causing collisions under parallel runs | Medium |
81
+ | Mock of a third-party dependency the project doesn't own, wrapped nowhere | Medium |
58
82
  | Tests asserting implementation rather than behaviour | Low |
83
+ | Assertion Roulette — many unlabelled assertions, unclear which failed | Low |
@@ -0,0 +1,77 @@
1
+ # Tooling Baseline
2
+
3
+ What does this project already check automatically, and does anyone actually look? Gate: a linter, formatter, type-checker, test-runner, or scanner configuration is present — or its absence is conspicuous enough to be the finding itself.
4
+
5
+ This audit otherwise reasons from source alone. Most projects already carry deterministic tooling that reasons about the same source more reliably — a rule a tool enforces cannot silently rot the way a convention this audit merely observes can. That configuration, and any output a tool has already produced, is evidence this audit would otherwise throw away, and it is stronger evidence than anything reasoned out fresh: SAST integrated with LLM review measurably beats either alone. This module owns the inventory-wide questions — what exists, what it actually enforces, what it has already produced — and does not duplicate work owned elsewhere: `type-safety.md` owns type-checker escape-hatch density specifically; `devops.md`'s Pipeline integrity section owns the mechanics of whether a CI step can fail the build; `consistency.md`'s Tooling agreement owns whether the *code* conforms to what one formatter/linter declares. This module owns the *inventory* across every tool category, the declared-vs-enforced gap as a structural question, and committed tool output as first-class evidence. A finding here that a project's own configured tool would already catch — but that is suppressed or never wired into CI — is `read`-tier under the Evidence Contract and unusually solid, because the "should this fail" question was answered by the tool's own author, not by this audit's judgement. The inverse also counts: a defect this audit reports elsewhere that the project's tooling *should* have caught, and did not, is itself a finding about the tooling, and belongs in this module, not buried in the module that found the defect.
6
+
7
+ ## Inventory
8
+
9
+ - [ ] Locate every tool config in the tree — `search_code` for `.eslintrc`/`eslint.config`, `.prettierrc`, `biome.json`, `.stylelintrc`, `ruff.toml`/`pyproject.toml`'s `[tool.ruff]`, `.flake8`, `mypy.ini`/`pyrightconfig.json`, `tsconfig.json`, `go.mod`/`.golangci.yml`, `.rubocop.yml`, `checkstyle.xml`, a test-runner config (`jest.config`, `vitest.config`, `pytest.ini`), a SAST/dependency-scanner config (`.semgrep.yml`, `.snyk`, `codeql.yml`, `trivy.yaml`, `.bandit`), `.pre-commit-config.yaml`, `.editorconfig`. Record what each declares — existence alone is not the finding, its content is.
10
+ - [ ] Where tooling exists for one category but is conspicuously silent on an adjacent one the project clearly needs — a Python API handling auth with no `bandit`/`semgrep` config beside its `ruff` config — note the asymmetry; a gap in an otherwise-tooled project says more than a gap in an untooled one.
11
+ - [ ] Version-pin the tools themselves — `search_code` the manifest/lockfile for each tool's declared version. An unpinned linter/formatter version means the ruleset it enforces can shift between a CI run and a fresh clone without anyone touching the config.
12
+
13
+ ## Declared versus enforced
14
+
15
+ The central check: a rule in a config nothing runs is a rule nobody obeys, and a scan that runs but does not gate the merge is theatre with a green checkmark.
16
+
17
+ - [ ] For every config found above, confirm a CI step actually invokes it — `search_code` the CI workflow files for the tool's run command (`eslint`, `ruff check`, `mypy`, `go vet`, `semgrep ci`). A config present with no matching CI invocation is enforced only on whichever machine happens to run it locally, if any does.
18
+ - [ ] Where CI does invoke it, confirm the step's failure fails the build. Cross-reference `devops.md`'s Pipeline integrity checks for the mechanics (`continue-on-error`, `|| true`, `--passWithNoTests`) — this module confirms the check exists and is wired in, `devops.md` owns whether it can actually fail; do not re-run that probe here.
19
+ - [ ] Where a pre-commit framework is configured, confirm the same hooks also run in CI, not only pre-commit — diff `.pre-commit-config.yaml`'s hook list against the CI workflow's step list. A hook that only pre-commit runs is bypassable with `--no-verify` or a clone that skipped `pre-commit install`.
20
+ - [ ] A scanner or checker that runs in CI but does not gate the merge — read the job's position in the workflow: a security-scan job with no branch-protection tie or `needs:` dependency feeding the merge check is informational only, and a red result there stops nothing.
21
+
22
+ ## Suppression inventory
23
+
24
+ The gap between what a tool would flag and what it actually flags. This owns the general shape; `type-safety.md` owns type-checker suppression density specifically — do not re-derive that count here.
25
+
26
+ - [ ] Root-level rule disables across every config found in Inventory — `search_code` each config for a rules-off block (`"off"`/`0` in an eslint config, a bare `ignore =` in ruff/flake8, `disable=` in `.rubocop.yml`) — each is a policy decision covering the whole tree; list what it would otherwise have caught.
27
+ - [ ] Per-file and per-line suppressions, tallied separately from root-level ones — `search_code` for inline disable comments (`eslint-disable-next-line`, `# noqa`, `# pragma: no cover`, `// nolint`) and group by file. A cluster in one file is a different finding than the same count spread thin.
28
+ - [ ] Ignore files and exclude globs wide enough to remove a whole directory — read `.eslintignore`/`ignorePatterns`, `.prettierignore`, and each scanner's `exclude`/`paths-ignore`. A glob matching `**/legacy/**` or a `generated/` directory that is in fact hand-edited silently drops it from every check that config runs, not just one.
29
+ - [ ] Confirm the type checker itself is inventoried and wired in per the checks above, but stop there — `any`/`@ts-ignore`/`# type: ignore` density, reason-carrying, and scope are `type-safety.md`'s probes, not this module's.
30
+
31
+ ## Committed tool output
32
+
33
+ - [ ] `search_code` for a committed SARIF file, coverage report (`coverage/`, `lcov.info`, `.coverage`), scanner baseline, or audit log checked into the repo. Where one exists, read it directly — it is `read`-tier evidence a deterministic tool produced, not evidence this audit reasoned out, and it is the strongest input available to the rest of the audit.
34
+ - [ ] Check its staleness before citing it — compare its embedded timestamp or generation commit against the current state of the files it describes. A report generated before the code it covers last changed is describing a version of the code that no longer exists.
35
+ - [ ] Where a coverage report is committed, read the numbers for the specific modules other findings in this audit touch, and cite them directly rather than estimating — this is measured, not inferred, even though `testing.md` owns the qualitative test-quality checks around it.
36
+ - [ ] A committed report showing zero findings from a scanner not wired into CI (per Declared versus enforced) is not evidence the code is clean — it is evidence of one run, possibly stale, that nothing repeats. State which is true before treating either as clean; a confident zero is exactly the "bug-free" framing that measurably suppresses detection elsewhere in this audit, and this module is where that framing enters.
37
+
38
+ ## Baseline files
39
+
40
+ - [ ] Locate a baseline/ignore-existing-violations file for any scanner or linter (`.rubocop_todo.yml`, a generated ESLint baseline, a SonarQube/Semgrep baseline snapshot, mypy's `--baseline` output) — `search_code` for the tool's baseline-generation flag or a file matching its documented baseline naming.
41
+ - [ ] Confirm the baseline only ever shrinks — check whether CI compares against it for new entries, or whether the baseline-regeneration command runs as part of the normal lint step, which re-freezes every current violation as newly accepted on every run. A baseline that regenerates itself is not a baseline, it is a ratchet permanently stuck at zero, and that is a finding, not neutral infrastructure.
42
+ - [ ] A baseline with no visible owner, date, or shrink target is itself the finding — nobody is accountable for burning it down, and the tool it fronts has quietly become decoration for the code frozen inside it.
43
+
44
+ ## Coverage of the tree
45
+
46
+ - [ ] For each config's `include`/`exclude`, confirm which top-level directories it actually reaches — read the scope against `list_modules` or the repo tree. Generated code, vendored dependencies, and test directories excluded on purpose are correct; the same exclusion silently covering a feature directory is not.
47
+ - [ ] Confirm test directories are excluded from *production-only rules*, not from the type checker outright — a config that drops `**/*.test.*` from type-checking entirely, rather than relaxing specific rules, lets test code drift from the types it exercises unnoticed. Cross-reference the test-time erosion check in `type-safety.md`.
48
+ - [ ] In a monorepo, confirm every package actually inherits the root config rather than shadowing it — `search_code` each package's own config for one that redefines rather than extends the root. A shadowed config is silent scope-narrowing nobody had to justify.
49
+
50
+ ## What absence means
51
+
52
+ - [ ] Where Inventory found no linter, no type checker, and no test runner at all for a language capable of having them, state it plainly: every defect this audit reports in that code was invisible to automation before this audit ran, and will be again the moment it ends. That is a scoping instruction for the rest of the module selection, not a caveat — `consistency.md` and `reachability.md` carry more weight here because nothing else is checking.
53
+ - [ ] Where tooling covers one language or surface in a polyglot repo but not another — TypeScript linted, a Python service beside it left bare — name the asymmetry directly; it usually tracks which surface a team actually owns.
54
+
55
+ ## Out of static reach
56
+
57
+ - Whether a suppression's stated reason is still true today, or a baseline entry's original cause has since been fixed elsewhere and only the freeze remains.
58
+ - Whether required CI checks are enforced by branch protection — a platform setting, not a file; cross-reference `devops.md`, which names this the same way.
59
+ - Real flake or noise rate of a configured scanner — only observable from run history this audit cannot read.
60
+ - Whether a tool absent from this repo runs upstream, in a monorepo sibling, or in an organisation-wide pipeline this audit cannot see.
61
+ - Whether a committed report's zero findings reflect a genuinely clean pass or a scanner misconfigured to match nothing.
62
+
63
+ ## Severity guidance
64
+
65
+ | Situation | Severity |
66
+ |---|---|
67
+ | Configured tool would catch a real defect but is suppressed or never wired into CI | High |
68
+ | No linter, type checker, or test runner at all for a language that supports them | High |
69
+ | Baseline file that regenerates itself, freezing violations permanently at zero | High |
70
+ | Committed scanner output cited as clean but stale against current code | Medium |
71
+ | Scanner runs in CI but does not gate the merge | Medium |
72
+ | Root-level suppression disabling a rule tree-wide with no stated reason | Medium |
73
+ | Exclude glob silently covering a live feature directory | Medium |
74
+ | Baseline file with no owner, date, or shrink target | Medium |
75
+ | Tooling asymmetry across languages/surfaces in one repo | Low |
76
+ | Unpinned tool version in manifest/lockfile | Low |
77
+ | Isolated, justified per-line suppression | Info |