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
@@ -2,47 +2,56 @@
2
2
 
3
3
  Native or cross-platform mobile concerns. Gate: a native mobile project was detected.
4
4
 
5
- Mobile amplifies every defect the other modules find: the network is unreliable, the process can die at any moment, and the user cannot read a stack trace. Audit accordingly.
5
+ Mobile amplifies every defect the other modules find: the network is unreliable, the process can die at any moment, and the user cannot read a stack trace. Audit accordingly. The auditor cannot run a device or emulator — every check below establishes what the source commits to, and what only a running device could confirm is listed under `Out of static reach`.
6
6
 
7
7
  ## Lifecycle
8
8
 
9
- - [ ] State survives backgrounding. Anything held only in memory is gone when the OS reclaims the process.
10
- - [ ] In-flight work is paused or cancelled on background, and resumed or abandoned deliberately on foreground.
11
- - [ ] Deep links and cold starts reach the same state as in-app navigation. A screen reachable only through a parent that initialises it will crash on deep link.
12
- - [ ] Rotation and configuration changes do not lose user input.
9
+ - [ ] State survives backgrounding. `search_code` for the lifecycle hook (`onPause`, `applicationDidEnterBackground`, an `AppState` listener) and confirm in-memory state it should persist is written to a durable store (disk, `SharedPreferences`/`UserDefaults`, a persisted store) inside that hook, not only held in a view model.
10
+ - [ ] In-flight work is paused or cancelled on background, and resumed or abandoned deliberately on foreground. `find_callees` on the background/foreground lifecycle hooks for a cancellation or resume call on the in-flight request or task object.
11
+ - [ ] Deep links and cold starts reach the same state as in-app navigation. `trace_path` from the deep-link handler to the target screen's initialisation — a screen reachable only through a parent route that sets state the deep link skips is the finding.
12
+ - [ ] Rotation and configuration changes do not lose user input. `search_code` for the rotation/configuration-change callback and confirm form or input state is restored from a saved-instance-state mechanism rather than reset to defaults.
13
13
 
14
14
  ## Network reality
15
15
 
16
- - [ ] Every request assumes it can fail, be slow, or arrive twice. Offline is a state, not an error.
17
- - [ ] Retries are bounded and backed off. An unbounded retry on a metered connection is a cost defect too — cross-reference `Cost`.
18
- - [ ] Large payloads are paginated or streamed. Mobile memory limits are lower than the developer's machine.
19
- - [ ] Uploads survive interruption, or explicitly restart.
16
+ - [ ] Every request assumes it can fail, be slow, or arrive twice. `find_callees` on each network call site for a catch/error branch — a call with no error handling treats failure as impossible.
17
+ - [ ] Retries are bounded and backed off. `search_code` the retry wrapper around a network call and confirm a max-attempt count and backoff exist. An unbounded retry on a metered connection is a cost defect too — cross-reference `Cost`.
18
+ - [ ] Large payloads are paginated or streamed. `search_code` for a list-fetching call with no page/cursor parameter, against an endpoint the `API` module's inventory shows supports one.
19
+ - [ ] Uploads survive interruption, or explicitly restart. `find_callees` on the upload call site for a resume/checkpoint mechanism; its absence means any interruption restarts from zero with no stated fallback.
20
20
 
21
21
  ## Permissions
22
22
 
23
- - [ ] Every permission requested is actually used. `search_code` the manifest/plist entries and confirm each has a call site — an unused permission is a store-review risk and a trust cost.
24
- - [ ] Denial is handled, including permanent denial, with a path forward rather than a dead end.
25
- - [ ] Permissions are requested at the moment of need with context, not all at launch.
23
+ - [ ] Every permission requested is actually used. `search_code` the manifest/plist for each declared permission, then `find_callers` on the corresponding platform API to confirm a call site exists — an unused permission is a store-review risk and a trust cost.
24
+ - [ ] Denial is handled, including permanent denial, with a path forward rather than a dead end. `find_callees` on the permission-request call site for a denial branch, and a further branch for the "don't ask again"/permanently-denied state.
25
+ - [ ] Permissions are requested at the moment of need with context, not all at launch. `find_callers` on the permission-request call to confirm it fires from the feature that needs it, not from app-startup code.
26
26
 
27
27
  ## Storage and secrets
28
28
 
29
- - [ ] Tokens and credentials use the platform keystore, never plain preferences or a local file. `search_code` for the preference API alongside token-like keys.
30
- - [ ] Cached user data is clearable, and logout actually clears it.
31
- - [ ] Local database migrations exist and are tested against the previous version's schema.
29
+ - [ ] Tokens and credentials use the platform keystore, never plain preferences or a local file. `search_code` for a token/credential-shaped variable name adjacent to a `SharedPreferences`/`UserDefaults`/plain-file write call, instead of `Keychain`/`Keystore`/`EncryptedSharedPreferences`.
30
+ - [ ] Cached user data is clearable, and logout actually clears it. `find_callees` on the logout handler for a call that clears the local cache/database; its absence means logged-out state still holds the previous user's data.
31
+ - [ ] Local database migrations exist and are tested against the previous version's schema. `search_code` the local-DB migration directory and confirm a version-bump path exists — cross-reference `database.md`'s migration checks for the fuller review.
32
32
 
33
33
  ## Platform integration
34
34
 
35
- - [ ] Both platforms are covered wherever the code branches on OS. A branch handling one platform and falling through on the other is a half-wired feature — cross-reference `flow-integrity.md`.
36
- - [ ] Minimum OS version claimed by the manifest matches the APIs actually used.
37
- - [ ] Safe areas, notches, and system bars are respected.
38
- - [ ] Back-navigation follows platform convention, including hardware back.
35
+ - [ ] Both platforms are covered wherever the code branches on OS. `search_code` for `Platform.OS`/`#if os(`/build-variant conditionals and confirm each branch has a corresponding implementation, not a fallthrough or a no-op on one side — cross-reference `flow-integrity.md`.
36
+ - [ ] Minimum OS version claimed by the manifest matches the APIs actually used. Read the manifest's `minSdkVersion`/`MinimumOSVersion`, then `search_code` for any API call whose documented minimum exceeds it.
37
+ - [ ] Safe areas, notches, and system bars are respected. `search_code` for `SafeAreaView`/`safeAreaInsets`/edge-to-edge handling on screens with content near the top or bottom edge; its absence on a full-bleed screen is the finding.
38
+ - [ ] Back-navigation follows platform convention, including hardware back. `search_code` for a hardware-back-button override (`onBackPressed`, `BackHandler`) and confirm it does not strand the user with a no-op and no exit path.
39
39
 
40
40
  ## Performance on real devices
41
41
 
42
- - [ ] No work on the main/UI thread that can block a frame — parsing, image decoding, disk, crypto.
43
- - [ ] Lists are recycled/virtualised, not fully materialised.
44
- - [ ] Images are downsampled to display size before decoding.
45
- - [ ] Battery and wake-lock usage is bounded; background jobs have a stated budget.
42
+ - [ ] No work on the main/UI thread that can block a frame — parsing, image decoding, disk, crypto. `search_code` for a synchronous file/crypto/decode call not wrapped in a background dispatch (a thread, `async`, a worker) inside a component's render/lifecycle method.
43
+ - [ ] Lists are recycled/virtualised, not fully materialised. `search_code` for a `map()` rendering a full dataset as a list of components, instead of `FlatList`/`RecyclerView`/`LazyColumn` or an equivalent virtualising list.
44
+ - [ ] Images are downsampled to display size before decoding. `search_code` for an image-loading call with no resize/target-size option, against a source image likely to exceed display resolution — a camera capture, a full-resolution upload.
45
+ - [ ] Battery and wake-lock usage is bounded; background jobs have a stated budget. `search_code` for a wake-lock acquire or a background-task scheduler registration and confirm a matching release call and a stated time/battery budget exist.
46
+
47
+ ## Out of static reach
48
+
49
+ - Actual behaviour under real network conditions — latency, packet loss, airplane mode toggled mid-request.
50
+ - Real memory pressure and whether the OS actually reclaims the process under it.
51
+ - Battery drain and wake-lock duration in practice, versus a stated budget in source.
52
+ - Rendering performance — dropped frames, jank — on real device hardware.
53
+ - App-store review outcomes for permission usage: this module confirms a permission has a call site, not that a reviewer accepts the justification.
54
+ - Platform-API behaviour across the OS version fragmentation the codebase does not branch on.
46
55
 
47
56
  ## Severity guidance
48
57
 
@@ -0,0 +1,74 @@
1
+ # Multi-tenancy
2
+
3
+ Is every data access scoped to the right tenant? Gate: tenant, organisation, or workspace scoping present.
4
+
5
+ `security.md` owns authorisation in general — can this user do this action. This module owns the narrower, more mechanical question underneath it for a multi-tenant system: even for an action a user is allowed to perform, does the query reach only their tenant's rows? Authorisation can be correct and tenant scoping can still be wrong, because they are enforced at different layers and a bypass of one does not imply a bypass of the other.
6
+
7
+ ## Inventory
8
+
9
+ - [ ] Which isolation model this system uses — silo (each tenant gets its own database/schema), pool (tenants share tables, scoped by a `tenant_id`-shaped column), or bridge (a mix by tier, e.g. pooled web tier over siloed storage). `get_architecture` plus a schema read: one database/schema per tenant is silo; shared tables with a tenant column are pool. This isn't a finding by itself, but it sets what the rest of this module should weight most: a pool-model system has zero isolation beyond correct scoping code, so every check below matters more there than in a silo-model system where a scoping bug is contained to one tenant's own database.
10
+ - [ ] Every table's tenant-scoping status — `search_code` the schema/migrations for a `tenant_id`/`org_id`/`workspace_id`-shaped column, and list which tables have one and which do not. For tables without one, confirm they are genuinely global (reference/lookup data, system config) rather than tenant data that was never scoped — a tenant-owned table with no tenant column cannot be scoped by any mechanism below, no matter how careful the query layer is.
11
+ - [ ] The parameter's shape is consistent — `search_code` for `tenant_id`, `org_id`, `organizationId`, `workspace_id`, and similar across modules; one identifier type and name used everywhere, not `tenant_id` in one module and `organizationId` in another with a translation layer that could drop it.
12
+ - [ ] Unique constraints scoped correctly — `find_symbol` each unique index on a tenant-owned table and check whether the tenant column is part of the key. A global unique constraint on `email` (rather than `(tenant_id, email)`) either blocks a legitimate second tenant from using an address already in use elsewhere, or — if enforced only in application code — is exactly the kind of check the constraint should be enforcing instead.
13
+
14
+ ## Query-level scoping
15
+
16
+ - [ ] Before flagging any individual query as unscoped, find the repository/ORM layer or query-builder base class first — `search_context` "how are queries scoped to a tenant" or `find_symbol` the base repository. A centralised default scope (an ORM global scope, a query-builder mixin applied everywhere) makes individual unscoped-looking call sites correct by construction; report the *mechanism*, not thirty false positives against it.
17
+ - [ ] Once the mechanism is found: does every path that constructs a query for a tenant-scoped table go through it? `find_callers` on the raw query/ORM-model access to catch call sites that bypass the repository layer entirely (direct model access, a raw query builder used inline).
18
+ - [ ] Raw SQL anywhere in the codebase — `search_code` for a raw query execution call — is exempt from any ORM-level default scope by definition, so each one needs its own explicit tenant filter, checked by hand.
19
+ - [ ] Joins and eager-loaded relations: a primary query correctly scoped to a tenant does not guarantee its joined tables are. `find_symbol` the join/relation definition and confirm the joined table's own tenant filter is applied, not just an implicit assumption that the join key already narrows it.
20
+ - [ ] The actual scoping mechanism identified above — request-scoped middleware context, a database row-level security policy, an ORM default scope — and specifically how the tenant identifier gets into it. `find_symbol` the middleware/context setter and read where its value comes from: a client-supplied header or body field (rather than the authenticated session/token) lets a caller assert any tenant they like. OWASP's Multi-Tenant Security Cheat Sheet states this plainly: bind tenant context to the authenticated session, never trust a client-supplied tenant id.
21
+ - [ ] Where row-level security (Postgres RLS or equivalent) is the mechanism: RLS has two silent bypasses that make an enabled policy do nothing. `search_code` migrations for `ENABLE ROW LEVEL SECURITY` and check whether the matching `ALTER TABLE ... FORCE ROW LEVEL SECURITY` is also present — without `FORCE`, the table's owner role bypasses every policy on it. Separately, read the application's DB connection configuration for which role it authenticates as — a connection using a superuser role, or any role granted `BYPASSRLS`, skips RLS entirely regardless of what the policies say. Either gap means the policies are dead code for the role that matters.
22
+
23
+ ## Paths with no request context
24
+
25
+ - [ ] Background jobs and scheduled work — `search_code` the job/worker entry points and check whether each one receives an explicit tenant identifier or iterates tenants explicitly, versus relying on the same request-scoped context used by the web layer, which does not exist in a job runner. This is where tenant scoping is most often silently absent, because the code was written and tested only against the request path.
26
+ - [ ] Admin endpoints and internal tooling — `find_symbol` the admin route handlers and read whether tenant selection is an explicit parameter the operator supplies, or inherited from the same scoping code path used for a limited tenant-user, which may not generalise the way an admin tool needs it to.
27
+ - [ ] Data exports, report generation, and migrations — `find_callees` from each to confirm tenant filtering happens explicitly rather than being assumed from context that will not be present when the script runs standalone.
28
+ - [ ] Webhook and queue-consumer handlers that carry a tenant identifier in the payload — `find_symbol` the handler and confirm it re-derives the tenant from an authenticated/signed source (the subscription record, the API key that registered the webhook) rather than trusting a tenant ID the payload itself supplies, which a forged or misrouted event could set to any value.
29
+
30
+ ## Identifiers
31
+
32
+ - [ ] Sequential or otherwise guessable IDs (auto-increment integers) used as externally-exposed resource identifiers — combined with any authorisation gap, this permits enumeration across tenants even where scoping is otherwise correct, because the ID itself leaks the existence and ordering of other tenants' records. Cross-reference `abuse.md` for the enumeration/rate-limiting angle; report the identifier choice here.
33
+
34
+ ## Caches
35
+
36
+ - [ ] Every cache key touching tenant data includes the tenant identifier — `search_code` the cache-set/cache-get call sites for tenant-scoped data and read the key construction. A cache key built from a resource ID alone, with no tenant component, serves tenant A's cached value to tenant B's identical-shaped request. This is the highest-severity finding this module can produce, because it requires no attacker action at all — it fires on ordinary traffic the moment two tenants share a cache-key collision.
37
+ - [ ] Where the key does include a tenant component, check whether the cached value itself also carries the tenant identifier and is verified on read. `find_symbol` the cache-read path and confirm it checks the stored `tenant_id` against the expected one, rather than trusting key construction alone — a key-only guard has no second check if the key is ever built wrong at one call site while correct everywhere else.
38
+
39
+ ## Files and cross-boundary data
40
+
41
+ - [ ] Uploaded files and object-storage paths — `search_code` the upload handler's storage-path/key construction and check whether the tenant identifier is part of the path/prefix itself, or only enforced by an application-level check that a misconfigured bucket policy or a directly-guessed URL bypasses.
42
+ - [ ] Logs and error reports carrying tenant data — `search_code` the logger calls near tenant-data handling for full record dumps (rather than IDs) that could surface one tenant's data in another's support ticket or a shared observability tool. Cross-reference `privacy.md` for the general PII-in-logs concern; report the cross-tenant leak angle here.
43
+
44
+ ## Cross-tenant features
45
+
46
+ - [ ] Sharing, transfer, or impersonation features (an admin "log in as" a tenant's user, moving a resource between tenants) — confirm each one is deliberately scoped and, ideally, audited (`search_code` for an audit-log write alongside the action), rather than being a side door that bypasses the scoping mechanism entirely because it was built as a special case.
47
+ - [ ] Test coverage for cross-tenant isolation — `search_code` the test suite for a case that asserts tenant A cannot read tenant B's data. Its absence is itself a finding: a scoping mechanism nobody has written a test to break is a mechanism nobody has verified.
48
+
49
+ ## Out of static reach
50
+
51
+ - Whether a row-level security policy actually evaluates as expected against live data at runtime — the migration declaring `ENABLE`/`FORCE ROW LEVEL SECURITY` and the connection role's privileges are readable from source (see Query-level scoping above); whether the policy predicate itself is logically correct against real rows is not.
52
+ - Real cache collision behaviour under production key distributions.
53
+ - Whether a background job's tenant loop actually covers every active tenant in practice.
54
+ - Storage bucket/IAM policy configuration outside the repository.
55
+
56
+ ## Severity guidance
57
+
58
+ | Situation | Severity |
59
+ |---|---|
60
+ | Cache key for tenant data with no tenant component | Critical |
61
+ | Raw SQL or bypassed repository layer with no tenant filter on a tenant-scoped table | Critical |
62
+ | Webhook/queue payload's self-declared tenant ID trusted without re-derivation | Critical |
63
+ | RLS enabled but not `FORCE`d, or app connects via a role with `BYPASSRLS`/superuser | Critical |
64
+ | Background job or scheduled work with no tenant scoping at all | High |
65
+ | Tenant identifier sourced from a client-supplied value instead of the authenticated session | High |
66
+ | Tenant-scoped table with no tenant column at all | High |
67
+ | Joined/eager-loaded relation missing its own tenant filter | High |
68
+ | Cross-tenant feature (impersonation, transfer) with no audit trail | Medium |
69
+ | Sequential/guessable IDs on tenant-scoped resources | Medium |
70
+ | Uploaded file path with no tenant component in storage | Medium |
71
+ | Tenant data appearing in full in logs or error reports | Medium |
72
+ | Unique constraint scoped globally instead of per-tenant | Medium |
73
+ | No test asserting cross-tenant isolation | Medium |
74
+ | Inconsistent tenant-parameter naming across modules | Low |
@@ -0,0 +1,70 @@
1
+ # Numeric & Money
2
+
3
+ Can the arithmetic be trusted? Gate: monetary, quantity, or unit-bearing fields present.
4
+
5
+ Nothing else in this skill covers this. `database.md` audits schema shape generally but not numeric-type correctness for money specifically; `cross-surface-parity.md` audits recomputation across surfaces but not the arithmetic itself. This module owns whether numbers that represent money, quantities, or physical units are the right type, stay the right type across every hop, and round the same way everywhere they round.
6
+
7
+ ## Money as floating point
8
+
9
+ - [ ] Every money-named field — `search_code` for `price`, `amount`, `total`, `balance`, `fee`, `cost`, `subtotal`, `tax` — and its declared type at each layer: schema column, ORM/model type, API DTO, frontend type. A `FLOAT`/`DOUBLE`/`number`/plain JSON numeric anywhere in that chain is the headline finding of this module: binary floating point cannot represent most decimal fractions exactly, and money arithmetic on it accumulates visible error.
10
+ - [ ] The chosen alternative — integer minor units (cents) or a fixed-point/decimal type — applied consistently along the whole chain, not just at the database. `find_callers` on the money field's accessor to confirm every call site treats it as the same representation; a `DECIMAL` column read into a JS `number` at the ORM boundary silently becomes floating point again.
11
+ - [ ] JSON serialisation of money at any wire boundary: a decimal type serialised as a JSON number (not a string) loses precision in any consumer using IEEE-754 doubles, even if the producer's own type was exact. `search_code` the response serializer for money fields.
12
+
13
+ ## Rounding
14
+
15
+ - [ ] Where rounding happens and whether the mode is explicit — `search_code` for `round(`, `toFixed(`, `Math.round`, or a currency-formatting call, and check whether banker's rounding (round-half-to-even — IEEE 754's default tie-break, and Python's `round()`/`decimal.ROUND_HALF_EVEN` default), round-half-up, or truncation is stated versus assumed as a language default. There is no single universal "financial code must use X" rule across standards — round-half-up is the conventional default most non-technical stakeholders assume, while round-half-to-even is required in specific standards-driven contexts precisely to avoid cumulative bias over volume — so the finding is disagreement or silence, not a specific mode being "wrong". Watch for the false assumption in the other direction too: JavaScript's `Math.round()` always rounds an exact half *up* (`Math.round(2.5) === 3`, `Math.round(-2.5) === -2`), which is round-half-up, not banker's rounding, despite running on IEEE 754 doubles underneath — a dev who assumes `Math.round` matches the float standard's own tie-break rule is wrong.
16
+ - [ ] The same amount rounded at two different points in the flow (once on calculation, again on display, again on persistence) — trace each rounding site with `find_callers`/`trace_path` from the source value and confirm they use the same mode and the same precision. Disagreement here is invisible in any single-path test and shows up only as "the total doesn't match the sum of the lines."
17
+ - [ ] Division and percentage arithmetic that discards the remainder — a discount, tax, or fee calculated as `amount * rate` with no compensating remainder handling, run against an amount where the result cannot be represented exactly (e.g. dividing by 3).
18
+ - [ ] Allocation/splitting logic (split a bill N ways, distribute a total across line items) — `find_symbol` the split function and confirm the parts are made to sum back to the original total (typically by assigning the remainder to the last share, a special case of the standard largest-remainder/Hamilton apportionment method — floor each share, then hand out the leftover units to the shares with the largest fractional remainder), not just independently rounded, which drifts the sum away from the total by a cent or more.
19
+
20
+ ## Currency and units
21
+
22
+ - [ ] A hardcoded `* 100` / `/ 100` conversion constant applied uniformly to every currency — `search_code` for the literal `100` beside a money field's read/write path. ISO 4217 defines a per-currency minor-unit exponent, and it is not always 2: JPY, KRW, VND, ISK and others use exponent 0 (no minor unit at all — the major unit *is* the smallest unit, so `×100` inflates the stored amount a hundredfold), while BHD, KWD, JOD, OMR, TND, IQD, and LYD use exponent 3 (1/1000ths, e.g. Bahraini fils), so a `/100` truncates and a `×100` under-converts by a factor of ten. A single hardcoded constant is provably wrong for both edges of that range the moment the codebase touches one of these currencies.
23
+ - [ ] Amount values carried without their currency attached — a function or column holding a bare number where the currency is assumed rather than stored alongside it. `search_code` for arithmetic between two amount variables and check whether their currencies were ever compared; adding `100` (USD) to `100` (EUR) is nonsense the type system will not catch if currency isn't part of the value.
24
+ - [ ] Exchange-rate application: the rate's own timestamp, and whether the code applying it uses the rate valid at the transaction time versus whatever the latest cached rate happens to be. Cross-reference `temporal.md` for whether that timestamp is stored as a proper instant.
25
+ - [ ] Any field carrying bytes, milliseconds, kilometres, kilograms, or another unit whose name does not say so (`size`, `duration`, `distance`, `weight`) — `search_code` the field name and read the nearest comment or usage to infer the intended unit, then check every consumer agrees.
26
+ - [ ] Unit conversions applied twice (a value already in minor units gets divided by 100 again) or never (a value assumed to be in one unit is used directly in a formula expecting another) — trace with `find_callees` from the conversion function to confirm it is called exactly once per value on its way to use.
27
+
28
+ ## Precision and comparison
29
+
30
+ - [ ] Integer overflow or precision loss at boundaries — a large integer ID or amount crossing a JSON boundary into a language whose numbers are IEEE-754 doubles (JavaScript, or any `JSON.parse` consumer) silently loses precision beyond `Number.MAX_SAFE_INTEGER` (2^53 − 1 = 9,007,199,254,740,991 — the limit of the double's 53 bits of integer precision, 52 stored mantissa bits plus one implicit leading bit). This is concretely reproducible, not theoretical: `JSON.parse("9007199254740993")` returns `9007199254740992`, silently, with no error. `search_code` for large numeric IDs (order numbers, ledger entries) serialised as JSON numbers rather than strings.
31
+ - [ ] Floating-point values compared for equality (`===`, `==`, `.equals()`) anywhere in the codebase — `search_code` for `===` or `==` beside a variable that is a computed float. This is a near-guaranteed false negative on values that are mathematically equal but bit-different due to accumulated rounding.
32
+ - [ ] Database numeric column precision/scale versus the application type's range — a `DECIMAL(10,2)` column paired with an application type that permits more precision, silently truncated on write with no error surfaced.
33
+ - [ ] Division by a value that can be zero (a rate, a count used as a denominator) — `search_code` the division site and check whether the denominator's zero case is validated before use or produces `NaN`/`Infinity`/a runtime exception that propagates into a stored or displayed value.
34
+ - [ ] `NaN` and `Infinity` reachability into a persisted or serialised value — a `NaN` written to a numeric column, or serialised into JSON (where it becomes `null` or invalid JSON depending on the serializer), silently corrupting the value with no error at the point of injection.
35
+
36
+ ## Sign and bounds
37
+
38
+ - [ ] Negative-amount validation on fields that should never go negative (a balance, a quantity) versus ones that legitimately can (a refund, an adjustment) — `find_symbol` the validation on the write path and confirm the sign constraint matches the field's real semantics rather than being uniformly absent or uniformly forbidding negatives.
39
+ - [ ] Quantity or amount fields with no upper-bound validation before an arithmetic operation that could overflow or produce an absurd result (a quantity field multiplied by a price with no sanity check) — reachable from user input, not just internal computation.
40
+
41
+ ## Recomputation
42
+
43
+ - [ ] Totals, subtotals, or derived amounts computed in more than one place (backend on save, frontend for display, a report job, a webhook payload) — `search_code` the computation formula in each location and diff them line by line. Cross-reference `cross-surface-parity.md`, which owns the general recomputation-drift pattern; report the numeric-specific instance here with the exact formula divergence.
44
+
45
+ ## Out of static reach
46
+
47
+ - Whether rounding differences are actually visible to a user at production data volumes.
48
+ - Real-world exchange rate feed staleness or provider outages.
49
+ - Cumulative floating-point drift over a live dataset's actual transaction history.
50
+ - Currency-conversion correctness against the specific jurisdiction's legally mandated rounding rules.
51
+
52
+ ## Severity guidance
53
+
54
+ | Situation | Severity |
55
+ |---|---|
56
+ | Money stored or transmitted as binary float anywhere in the chain | Critical |
57
+ | Split/allocation logic that does not sum back to the total | High |
58
+ | Arithmetic between two amounts whose currencies are never checked | High |
59
+ | Large ID or amount losing precision across a JSON boundary | High |
60
+ | Hardcoded ×100/÷100 conversion applied to a non-exponent-2 currency | High |
61
+ | Floating-point equality comparison on computed monetary values | Medium |
62
+ | Rounding mode unstated, or disagreeing between two computation sites | Medium |
63
+ | Unit-bearing field with no unit in its name and inconsistent consumers | Medium |
64
+ | Exchange rate applied without a timestamp tying it to the transaction | Medium |
65
+ | Totals recomputed independently in more than one surface | Medium |
66
+ | Division with an unvalidated zero-capable denominator | Medium |
67
+ | `NaN`/`Infinity` reachable into a persisted or serialised value | Medium |
68
+ | Sign constraint absent or wrong for the field's real semantics | Medium |
69
+ | No upper-bound validation before a user-input-driven multiplication | Low |
70
+ | DB column precision narrower than the application type | Low |
@@ -4,41 +4,54 @@ Could you tell this broke, and find out why? Gate: logging, metrics, or tracing
4
4
 
5
5
  The test is concrete: pick the three worst plausible failures for this system and ask, for each, what signal would exist. If the answer is "a user complains", that is the finding.
6
6
 
7
+ **This module fires on absence too, and absence is not an inconclusive probe.** A `search_code` for a logger, metrics client, or tracing SDK import that returns nothing is itself the evidence: the project has no observability, full stop. Report that once, at `High`, rather than working through every check below to individually confirm there is nothing to check.
8
+
7
9
  ## Coverage
8
10
 
9
- - [ ] Every error path produces a signal. Cross-reference the swallowed-error sweep in `failure.md` — an empty catch block is both a failure defect and an observability hole.
10
- - [ ] Every external call records outcome and duration. These are the failures you do not control and most need to see.
11
- - [ ] Background jobs, cron, and queue consumers report that they ran, what they processed, and what they skipped. Silent background work is invisible when it stops.
12
- - [ ] Startup logs the resolved configuration — with secrets redacted — so a misconfigured deploy is diagnosable from the first line.
11
+ - [ ] Every error path produces a signal: reuse the swallowed-error sites from `failure.md`'s `search_code` (empty catch blocks, `.catch(() => {})`) and check whether a log or metric call sits at each one. An empty catch block is both a failure defect and an observability hole.
12
+ - [ ] Every external call records outcome and duration: for each network/db/queue call site identified under `Performance`'s I/O checks, read whether it is wrapped with a timing measurement and a success/failure log or metric. These are the failures you do not control and most need to see.
13
+ - [ ] Background jobs, cron, and queue consumers report that they ran, what they processed, and what they skipped: reuse the consumer/scheduler entry points from `scalability.md`'s queue checks and read each for a start/end/summary log. Silent background work is invisible when it stops.
14
+ - [ ] Startup logs the resolved configuration: `search_code` the app's bootstrap/entry file for a log statement dumping resolved config, and confirm secret fields pass through a redaction/mask helper first. Without it, a misconfigured deploy is only diagnosable by reading the process environment directly.
13
15
 
14
16
  ## Log quality
15
17
 
16
- - [ ] Structured, not interpolated prose. `log("user " + id + " failed")` cannot be queried; a structured field can.
17
- - [ ] Levels are used meaningfully: `error` means someone should look, `warn` means it is degraded, `info` is the narrative. If everything is `info`, the levels are decoration.
18
- - [ ] Correlation identifier flows through a whole operation, including into background work. Without it, a multi-service failure cannot be reassembled.
19
- - [ ] No personal data, credentials, or tokens in logs — cross-reference `privacy.md` and `security.md`. This is where accidental egress usually happens.
20
- - [ ] Volume is bounded: nothing logs per item in a large loop, and no message repeats per retry without a limit.
21
- - [ ] Enough context to act — identifiers and inputs, not just "failed".
18
+ - [ ] Structured, not interpolated prose: `search_code` for string concatenation or template literals inside log call arguments (`log("user " + id + " failed")`) versus a structured call taking an object. Interpolated prose cannot be queried; a structured field can.
19
+ - [ ] Levels are used meaningfully: `search_code` the ratio of `.warn(`/`.error(` calls to `.info(`/`.debug(` calls across the codebase. A ratio near zero on a system with real failure paths means the levels are decoration — everything is `info`.
20
+ - [ ] Correlation identifier flows through a whole operation, including into background work: `find_callees` from a request entry point into any async/queued work it triggers, and check whether `trace_id`/`span_id` (or an equivalent request-id) is threaded through, not dropped at the async boundary. Where a tracing SDK is present, `search_code` whether the logger call sites actually route through its log bridge/appender — a logger constructed independently of it silently drops trace/span correlation even though tracing exists elsewhere in the same service. Without correlation, a multi-service failure cannot be reassembled.
21
+ - [ ] Attribute and field names follow a shared convention, not a per-call-site dialect: `search_code` a sample of span/log/metric attribute keys against OpenTelemetry semantic conventions (semconv v1.44.0) namespaces — `http.request.method`, `db.system`, `db.query.text`, and similar. A codebase emitting `httpMethod`/`db_type` alongside a library's own `db.system` shows the instrumentation was hand-rolled per call site instead of following a shared schema, which is exactly what breaks correlation once a second service or a vendor tool joins on the field. Note: `gen_ai.*` (LLM) attributes are still Development-status in semconv as of 2026 — do not flag an AI call site for not yet matching a stable convention that does not exist.
22
+ - [ ] No personal data, credentials, or tokens in logs: `search_code` log call arguments for field names matching PII or secrets (email, password, token, ssn, authorization). Cross-reference `privacy.md` and `security.md` — this is where accidental egress usually happens.
23
+ - [ ] Volume is bounded: reuse the loop-detection technique from `performance.md` — `search_code` for a log call inside a loop body or a retry block with no sampling or aggregation.
24
+ - [ ] Enough context to act: read a sample of the log call sites found above for the fields actually passed — a bare `"failed"` with no identifier or input value is not actionable.
22
25
 
23
26
  ## Metrics
24
27
 
25
- - [ ] The four that matter for any request-serving surface: rate, error rate, duration distribution, saturation. Averages hide the problem; percentiles do not.
26
- - [ ] Queue depth and consumer lag wherever there is a queue — cross-reference `scalability.md`.
27
- - [ ] Business-level counters for the operations that matter, not only technical ones. "Signups dropped to zero" is caught by a business metric, not by CPU.
28
- - [ ] Cardinality is bounded — no metric labelled with a user id or a raw path.
28
+ - [ ] The four that matter for any request-serving surface: `search_code` the metrics client import (statsd, Prometheus, OpenTelemetry metrics), then read which of rate, error rate, duration distribution, and saturation are actually emitted around the hot paths `repo_map` ranks highest. Averages hide the problem; percentiles do not.
29
+ - [ ] Queue depth and consumer lag wherever there is a queue: `search_code` near the queue-consumer code for a depth/lag metric. Cross-reference `scalability.md`.
30
+ - [ ] Business-level counters for the operations that matter, not only technical ones: `find_symbol` the handler for a core business event (signup, checkout, purchase) and check for an accompanying metric emission. "Signups dropped to zero" is caught by a business metric, not by CPU.
31
+ - [ ] Cardinality is bounded: read each metric-emission call site found above for a label built from a user id or a raw path — unbounded label values blow up the metrics backend's cardinality.
29
32
 
30
33
  ## Tracing
31
34
 
32
- - [ ] Spans cover the boundaries: inbound request, outbound calls, database, queue publish and consume.
33
- - [ ] Context propagates across process boundaries, including asynchronous ones.
34
- - [ ] Span attributes carry the identifiers needed to correlate with logs.
35
+ - [ ] Spans cover the boundaries: `search_code` the tracing SDK import and its span-creation calls, and check coverage of inbound request, outbound calls, database, and queue publish/consume.
36
+ - [ ] Context propagates across process boundaries, including asynchronous ones: `search_code` for a trace-context header (`traceparent`) or an explicit context-injection call at outbound HTTP and queue-publish sites.
37
+ - [ ] Span attributes carry the identifiers needed to correlate with logs: read a span-creation call for `setAttribute`/equivalent calls — a span with no identifiers cannot be joined back to the logs for the same operation.
38
+ - [ ] A sampling strategy is configured and stated, not silently defaulted: `search_code` the tracer/SDK init site for a sampler (`TraceIdRatioBased`, `ParentBased`, or a tail-sampling collector config). Most SDKs sample everything by default when unconfigured, which is a volume-and-cost problem before it is a correctness one — cross-reference `cost.md`. **Falsify before flagging**: a low-traffic internal service sampling everything is a reasonable choice, not a defect; anchor severity to traffic volume from `repo_map`/`find_callers`, not to the absence of a rate. If only head-based sampling is configured, that is not itself a finding — head sampling is the standard starting point — unless the project's own docs or alerting claim every error trace is captured, which head sampling alone cannot guarantee.
35
39
 
36
40
  ## Alerting
37
41
 
38
- - [ ] Something alerts on the failures that matter, and it alerts on symptoms users feel rather than on causes.
39
- - [ ] Every alert is actionable and has a stated response. An alert nobody acts on trains everyone to ignore alerts.
40
- - [ ] Absence is alertable: a job that stops running produces no error, so the check must be on the missing heartbeat.
41
- - [ ] Health checks distinguish liveness from readiness, and readiness reflects real dependency health.
42
+ - [ ] Something alerts on the failures that matter, and it alerts on symptoms users feel rather than on causes: `search_code` the IaC/monitoring config for an alert rule tied to error rate or latency (a Datadog monitor, a Prometheus alert rule, a CloudWatch alarm).
43
+ - [ ] Every alert is actionable and has a stated response: read each alert rule found above for a runbook link or description field. An alert nobody acts on trains everyone to ignore alerts.
44
+ - [ ] Absence is alertable: for each background job/cron confirmed under Coverage, `search_code` for a heartbeat or dead-man's-switch check (a scheduled ping to a monitoring endpoint). A job that stops running produces no error on its own, so the check must be on the missing heartbeat.
45
+ - [ ] Health checks distinguish liveness from readiness, and readiness reflects real dependency health: `find_symbol` the liveness and readiness endpoints and read whether the readiness one checks a real dependency (a db ping, a queue connection) versus returning `200` unconditionally.
46
+ - [ ] Where an SLO or error-budget policy exists in the repo, alerting is burn-rate based, not a single static threshold: `search_code` for an SLO/error-budget config (an OpenSLO/Sloth/Nobl9 file, or a comment-documented target) and, if one exists, read whether the paired alert rule uses a multi-window burn-rate pattern (a fast window and a slow window) rather than one threshold. A single-window burn alert either pages too often on noise or too late on a slow leak. Absence of an SLO file entirely is not itself a finding — most repos never encode one — say `not applicable` rather than manufacturing the check.
47
+
48
+ ## Out of static reach
49
+
50
+ - Whether an alert that fires actually reaches a human and gets acted on.
51
+ - Real log volume, and whether it exceeds retention or cost limits in practice.
52
+ - Whether anyone actually looks at the dashboards this module confirms exist.
53
+ - Actual on-call response time to a fired alert.
54
+ - Whether traces correlate correctly across async boundaries at runtime, versus merely having the propagation code in place.
42
55
 
43
56
  ## Severity guidance
44
57
 
@@ -53,3 +66,5 @@ The test is concrete: pick the three worst plausible failures for this system an
53
66
  | Unbounded metric cardinality | Medium |
54
67
  | Only averages, no percentiles | Low |
55
68
  | Every message logged at one level | Low |
69
+ | Ad hoc/non-semconv attribute naming across span, log, or metric fields | Low |
70
+ | SLO/burn-rate config present but alert is single-window, not multi-window | Low |
@@ -2,40 +2,48 @@
2
2
 
3
3
  Does what ships match what was built? Gate: a published package manifest or a release workflow was detected.
4
4
 
5
- **This module earns its place empirically.** In this very project, the author's skills were absent from `package.json`'s `"files"` array and shipped to nobody for two months. Every test passed. Nothing detected it, because tests run from the repository where the files exist on disk. That is the exact class of bug this module exists to catch.
5
+ **This module earns its place empirically.** In this very project, the author's skills were absent from `package.json`'s `"files"` array and shipped to nobody for two months. Every test passed. Nothing detected it, because tests run from the repository where the files exist on disk. That is the exact class of bug this module exists to catch — and unlike most modules in this skill, everything it checks is a manifest, a config file, or a build script, all readable in full.
6
6
 
7
7
  ## What is in the artefact
8
8
 
9
- - [ ] Enumerate the include list (`files`, `include`, `MANIFEST`, build output config) and compare it to what the code loads at runtime. **Anything read at runtime but absent from the include list ships to nobody.**
10
- - [ ] The inverse: files shipped that need not be — tests, fixtures, source maps in production, `.env` samples with real values, internal docs. Each is bloat, and some are leaks.
11
- - [ ] Entry points declared in the manifest exist in the built artefact at those exact paths.
12
- - [ ] Binaries and executables declared are present and executable.
9
+ - [ ] Enumerate the include list (`files` in `package.json`, `include`/`MANIFEST.in`, build output config) and compare it against what the code loads at runtime. `search_code` for `readFile`/`require(`/`import(` targeting a relative path, then confirm each target sits inside the include list. **Anything read at runtime but absent from the include list ships to nobody.**
10
+ - [ ] The inverse: files shipped that need not be — tests, fixtures, source maps in production, `.env` samples with real values, internal docs. Read the include list and `search_code` for `*.test.*`, `fixtures/`, `.map`, `.env.example` patterns it matches — each hit is bloat, and a `.env` sample with a real-looking value is a leak.
11
+ - [ ] Entry points declared in the manifest (`main`, `module`, `exports`, `bin`) exist in the built artefact at those exact paths. Read the manifest's entry fields, then confirm the build output config (`tsconfig`'s `outDir`, the bundler config) actually writes a file to each declared path.
12
+ - [ ] Binaries and executables declared are present and executable. Read the manifest's `bin` field, then confirm the target file exists and the build step does not skip generating it.
13
13
 
14
14
  ## Path assumptions
15
15
 
16
- - [ ] No runtime code resolves a path relative to the source tree. Templates, schemas, WASM, and assets read via a source-relative path work in development and fail in the published artefact.
17
- - [ ] Assets needed at runtime are embedded at build time or explicitly shipped and located by a mechanism that survives packaging.
18
- - [ ] Where the project ships a compiled/bundled binary, verify the embedding actually happened rather than trusting it. This is the single highest-value check in the module.
16
+ - [ ] No runtime code resolves a path relative to the source tree. `search_code` for `__dirname`, `import.meta.url`, or a relative `../` path adjacent to a `readFile`/asset-load call, then confirm the target stays inside the include list above rather than reaching into `src/` structure that packaging flattens or excludes.
17
+ - [ ] Assets needed at runtime are embedded at build time or explicitly shipped and located by a mechanism that survives packaging. `search_code` for a template/schema/WASM file loaded at runtime, then confirm the build config copies or embeds it — absence from both the include list and an embed step means it is missing the moment the source tree is gone.
18
+ - [ ] Where the project ships a compiled/bundled binary, verify the embedding actually happened rather than trusting it. Read the build script/bundler config for the embed step, then confirm the built output actually contains the asset — its declared size, or a reference to it in the bundle — rather than trusting the config exists. **This is the single highest-value check in the module.**
19
19
 
20
20
  ## Install-time verification
21
21
 
22
- - [ ] Something exercises the artefact as a consumer would — installed from a packed tarball, or run from a scratch directory outside the repository with no dependencies present.
23
- - [ ] That check runs in CI. A verification only ever run by hand will stop being run.
24
- - [ ] The check asserts the absence of file-not-found errors, not only a zero exit code — a swallowed load failure exits zero.
22
+ - [ ] Something exercises the artefact as a consumer would — installed from a packed tarball, or run from a scratch directory outside the repository with no dependencies present. `search_code` the CI workflow files and manifest scripts for a step that packs (`npm pack`, `pip build`) and installs into a scratch directory before running the entry point from there.
23
+ - [ ] That check runs in CI. Read the CI workflow file found above and confirm the pack-and-run step is a job triggered on push/PR, not only a local script nobody invokes. A verification only ever run by hand will stop being run.
24
+ - [ ] The check asserts the absence of file-not-found errors, not only a zero exit code. Read the CI step's assertion logic — a swallowed load failure inside a try/catch that still exits zero passes a check that proves nothing.
25
25
 
26
26
  ## Metadata
27
27
 
28
- - [ ] Version, license, repository, and description are present and accurate.
29
- - [ ] Declared runtime/engine requirements match what the code actually uses.
30
- - [ ] Dependencies are in the right section — nothing needed at runtime sits in dev dependencies. This fails only for consumers, never in the repository.
31
- - [ ] Peer dependencies and optional dependencies are declared deliberately.
28
+ - [ ] Version, license, repository, and description are present and accurate. Read the manifest's `version`, `license`, `repository`, `description` fields and confirm the license field matches the actual `LICENSE` file in the repository root.
29
+ - [ ] Declared runtime/engine requirements match what the code actually uses. Read the manifest's `engines`/`requires-python` field, then `search_code` for a language feature (optional chaining, a specific stdlib call) whose minimum version exceeds the declared floor.
30
+ - [ ] Dependencies are in the right section — nothing needed at runtime sits in dev dependencies. Read `dependencies` vs `devDependencies` in the manifest, then `search_code` each `devDependencies` entry's import inside runtime (non-test, non-build-script) source files. A hit there fails only for consumers, never in the repository, which is exactly why CI misses it.
31
+ - [ ] Peer dependencies and optional dependencies are declared deliberately. Read the manifest's `peerDependencies`/`optionalDependencies`, then `search_code` confirming each is imported conditionally rather than assumed always-present.
32
32
 
33
33
  ## Release process
34
34
 
35
- - [ ] Publishing is automated from a tagged commit, not run from a laptop.
36
- - [ ] The published version corresponds to a commit that exists and is tagged.
37
- - [ ] Nothing can publish from a dirty tree.
38
- - [ ] Multi-platform artefacts are built for every platform claimed as supported, not only the maintainer's.
35
+ - [ ] Publishing is automated from a tagged commit, not run from a laptop. `search_code` the CI workflow for a `publish`/`release` job triggered on a tag push, and confirm no local publish script exists that a developer would run with real credentials. This is also the precondition for `npm publish --provenance` or GitHub Attestations to mean anything — cross-reference `supply-chain.md`'s provenance check; a provenance step run from a laptop just moves trust from the registry to the laptop.
36
+ - [ ] The published version corresponds to a commit that exists and is tagged. Read the release workflow for a step that tags the commit before or as part of publish, rather than publishing from an arbitrary branch head.
37
+ - [ ] Nothing can publish from a dirty tree. Read the release workflow/publish script for a `git status --porcelain`/clean-tree check gating the publish step.
38
+ - [ ] Multi-platform artefacts are built for every platform claimed as supported, not only the maintainer's. Read the manifest's `os`/`cpu`/platform-support fields, then confirm the release workflow's build matrix covers each one.
39
+
40
+ ## Out of static reach
41
+
42
+ - Whether the packed tarball actually installs cleanly on every supported platform and language/runtime version — this module confirms CI runs the check, not that it passes on hardware nobody tested.
43
+ - Real download/install size as experienced by a consumer, versus the include list's apparent scope.
44
+ - Registry-side behaviour (npm, PyPI) — deprecation warnings, dist-tag correctness, unpublish windows.
45
+ - Whether a credential used for publishing is scoped correctly — that lives in the registry/CI secret store, not in source.
46
+ - Actual first-run behaviour of the installed artefact on a machine with none of the developer's global tooling present.
39
47
 
40
48
  ## Severity guidance
41
49
 
@@ -2,47 +2,69 @@
2
2
 
3
3
  Where does time and memory actually go? Gate: a hot path or a measurable workload was detected. This module was defined in the original audit design but no gate ever enabled it — it could never run. It runs now.
4
4
 
5
- **Measure or say you did not.** A performance finding with no number is a guess. If you cannot measure, state the complexity and the input size at which it matters, and mark the confidence accordingly.
5
+ A performance finding with no measurement behind it is `inferred` — a hypothesis about the shape of the code, not a measured fact — and per the Evidence Contract that caps it at `Medium`, no matter how bad it would be if true. It reaches `High` only when paired with `read` evidence that pins the input size, call frequency, or a config value proving no bound exists. It cannot reach `Critical` in this module: the auditor has no profiler, benchmark, or load test to run, so nothing here is ever `executed`.
6
6
 
7
7
  ## Find the hot paths first
8
8
 
9
9
  - [ ] `repo_map` ranks symbols by PageRank over the call graph — the top of that list is where a slowdown costs the most.
10
10
  - [ ] For each candidate, `find_callers` to learn how often it is reached, and `find_callees` to see what it drags in.
11
- - [ ] Anything called inside a loop, per request, or per item is a hot path regardless of how cheap it looks alone.
11
+ - [ ] Anything called inside a loop, per request, or per item is a hot path regardless of how cheap it looks alone — confirm the call site with `search_code` for the enclosing `for`/`while`/`.map`/`.forEach`.
12
+ - [ ] An unbounded loop or an O(n²) block earns no severity above `Low` on its own. It matters only on a path that is actually hot: anchor the claim to a `repo_map` rank and a `find_callers` count, not to how alarming the code reads.
12
13
 
13
14
  ## Algorithmic cost
14
15
 
15
- - [ ] Nested iteration over the same collection — O(n²) that is fine at 10 and fatal at 10,000. State the crossover.
16
- - [ ] Repeated linear scans where a map or set would be constant. `find_callees` for `includes`/`indexOf`/`find` inside a loop.
17
- - [ ] Sorting or grouping recomputed on every access instead of once.
18
- - [ ] Work repeated per item that could be hoisted out of the loop — regex compilation, config lookup, date parsing.
16
+ - [ ] Nested iteration over the same collection: `search_code` for a loop whose body contains a second loop over a variable bound in the outer one. O(n²) is fine at 10 and fatal at 10,000 — state the crossover, and rule out that the outer collection is bounded by construction (a fixed enum, a fixed page size) before flagging it.
17
+ - [ ] Repeated linear scans where a map or set would be constant: `find_callees` for `includes`/`indexOf`/`find` called inside a loop.
18
+ - [ ] Sorting or grouping recomputed on every access instead of once: `find_callers` on the sort/group function — a call count that tracks request volume, with nothing caching the result in between, is the finding.
19
+ - [ ] Work repeated per item that could be hoisted out of the loop: `search_code` for `new RegExp(`, a config-lookup call, or `new Date(`/`Date.parse(` sitting inside a loop body — each is cheap once and wasteful per item.
19
20
 
20
21
  ## I/O
21
22
 
22
- - [ ] Sequential awaits over independent operations. These should be concurrent; each one serialised costs its full latency.
23
- - [ ] A query, file read, or network call inside a loop. Cross-reference `Database`'s N+1 check.
24
- - [ ] Whole files or whole tables loaded to use part of them.
25
- - [ ] Missing pagination, streaming, or batching wherever the input can grow.
26
- - [ ] Synchronous filesystem or crypto calls on a request path.
23
+ - [ ] Sequential awaits over independent operations: read the function body for consecutive `await` calls not wrapped in `Promise.all`/`allSettled`. Rule out a genuine data dependency — the second call needs the first's result — before flagging; if it does, this is correct code, not a defect.
24
+ - [ ] A query, file read, or network call inside a loop: `find_callees` on the loop body for a query/fetch/`readFile` call. Cross-reference `Database`'s N+1 check.
25
+ - [ ] Whole files or whole tables loaded to use part of them: `search_code` for `SELECT *` with no `LIMIT`/`WHERE` narrowing the row count, or a full-file read immediately followed by an in-memory filter.
26
+ - [ ] Missing pagination, streaming, or batching wherever the input can grow: `search_code` a route handler's query call for the absence of `LIMIT`/`OFFSET`/a cursor parameter.
27
+ - [ ] Synchronous filesystem or crypto calls on a request path: `search_code` for `readFileSync`, `writeFileSync`, `execSync`, `*Sync(` inside a handler, then `find_callers` to confirm the handler is reached from a route rather than a CLI or build script — the same call is a non-issue in a one-shot script.
27
28
 
28
29
  ## Memory
29
30
 
30
- - [ ] Unbounded accumulation: a cache with no eviction, an array that only grows, a map keyed by user input.
31
- - [ ] Whole-result materialisation where a stream or iterator would do.
32
- - [ ] Retained references that outlive their use — closures capturing large objects, listeners never removed.
33
- - [ ] Large allocations in a loop that the allocator will churn on.
31
+ - [ ] Unbounded accumulation: `search_code` for a module-level `Map`/`Set`/array populated via `.push`/`.set` with no matching eviction, `maxSize`, or TTL nearby. Rule out that the key space is bounded by construction — a fixed set of feature flags is not user input.
32
+ - [ ] Whole-result materialisation where a stream or iterator would do: `search_code` for `.toArray()`/`.fetchAll()`/`readFileSync` used against a source with no declared size cap.
33
+ - [ ] Retained references that outlive their use: `search_code` for `addEventListener`/subscription calls with no paired `removeEventListener`/`unsubscribe`; `find_callers` on the owning object to check whether it is ever torn down.
34
+ - [ ] Large allocations in a loop that the allocator will churn on: `search_code` for `new Array(`, `Buffer.alloc(`, or an object/array literal constructed inside a loop body.
34
35
 
35
36
  ## Caching
36
37
 
37
- - [ ] Every cache has a stated key, a stated lifetime, and an invalidation path. A cache with no invalidation is a correctness bug wearing a performance costume.
38
- - [ ] Cache keys include everything the value depends on. A key missing a dimension serves the wrong answer.
39
- - [ ] Cached values that are cheap to compute — the cache costs more in complexity than it saves.
40
- - [ ] Nothing caches a mutable object by reference and lets a caller mutate it.
38
+ - [ ] Every cache has a stated key, a stated lifetime, and an invalidation path: `search_code` the cache import (`lru-cache`, `node-cache`, a hand-rolled `Map`), then read the set/get sites for a TTL and an explicit invalidation call. A cache with no invalidation is a correctness bug wearing a performance costume.
39
+ - [ ] Cache keys include everything the value depends on: `find_symbol` the cached function's signature, then read the key expression — a parameter missing from the key means two distinct inputs collide on one cache entry and one of them gets served the wrong answer.
40
+ - [ ] Cached values that are cheap to compute: read the wrapped function — a single arithmetic expression or constant lookup means the cache costs more in complexity than it saves.
41
+ - [ ] Nothing caches a mutable object by reference and lets a caller mutate it: `find_callers` on the cache getter, then check whether any caller mutates the returned object in place.
41
42
 
42
43
  ## Startup
43
44
 
44
- - [ ] Nothing expensive happens at import time. Top-level work runs even when the code path is never used.
45
- - [ ] Heavy dependencies are imported lazily at the point of need. Check for a dynamic import where a static one sits on a cold path.
45
+ - [ ] Nothing expensive happens at import time: `search_code` for a function call or `new Client(`/`.connect(` sitting at module scope rather than inside an exported function. `find_callers` on the module to rule out that it is only ever imported by the entry point itself, where the cost is paid once regardless of what runs.
46
+ - [ ] Heavy dependencies are imported lazily at the point of need: `search_code` a known heavy import (image processing, PDF, a large SDK) at the top of a file, then `find_callers` on that file's export to confirm the code path is rarely reached. A static top-level import on a cold path is the finding; a dynamic `import()` at the call site is the fix already in place.
47
+
48
+ ## Frontend rendering (Core Web Vitals)
49
+
50
+ Applies only when the project serves HTML to a browser — cross-reference the `Web Metadata` gate. Skip this section entirely, and say so, for a pure API/backend/CLI project. The current Core Web Vitals (Google, stable since March 2024) are LCP, INP, and CLS, each scored at the 75th percentile of real-user field data: LCP good ≤2.5s/poor >4.0s, INP good ≤200ms/poor >500ms, CLS good ≤0.1/poor >0.25. None of these are measurable statically — every check below is code shape, not a score.
51
+
52
+ - [ ] The LCP candidate is not blocked behind avoidable work: `search_code` for the hero image, video poster, or headline text that only renders after a client-side data fetch, with no SSR/prerender/static fallback ahead of it.
53
+ - [ ] The LCP candidate is sized and prioritised: `search_code` for that same element missing explicit `width`/`height` (or `aspect-ratio`), carrying `loading="lazy"` (which deprioritises exactly the element that must not be lazy), or lacking `fetchpriority="high"`/a preload hint.
54
+ - [ ] CLS-causing elements reserve their space: `search_code` for `<img>`/`<iframe>`/ad or embed slots with no `width`/`height`/`aspect-ratio`, and for content injected above existing content (a banner, a cookie notice, an async-loaded block) with no reserved slot.
55
+ - [ ] Web fonts do not cause layout shift on load: read the `@font-face`/font-loading config for `font-display` — its absence, or `font-display: block`, causes an invisible-text or swap-triggered reflow; `swap`/`optional` paired with a size-matched fallback is the fix already in place if present.
56
+ - [ ] INP-risking work runs inside interaction handlers: reuse this module's own hot-path technique — `search_code` a click/input/keydown/submit handler for synchronous work that belongs off the main thread (a large synchronous loop, parsing a large payload, unbatched layout reads/writes).
57
+ - [ ] The project actually measures these in the field, not only assumes them from code shape: `search_code` for the `web-vitals` library import (or an equivalent RUM SDK reporting `LCP`/`INP`/`CLS`) wired to somewhere the numbers leave the browser (an analytics event, a beacon endpoint). Its absence means every check above is `inferred` against code shape only, with no field measurement anywhere — say so under Coverage Gaps rather than treating the absence itself as a performance defect.
58
+ - [ ] The codebase is not still optimising for a retired metric: `search_code` for `FID`/`first-input` tracked or referenced with no accompanying `INP`. FID (First Input Delay) was retired as a Core Web Vital on 12 March 2024, replaced by INP — code or a dashboard still keyed on FID alone is measuring a metric Google no longer scores.
59
+
60
+ ## Out of static reach
61
+
62
+ - Actual LCP/INP/CLS percentile values from real users — nothing here runs Lighthouse or reads RUM data, only whether the code shape makes the thresholds reachable.
63
+ - Actual latency, throughput, or memory footprint under real traffic — nothing in this module is measured.
64
+ - The crossover input size at which an O(n²) block becomes user-visible, on the actual hardware and dataset.
65
+ - GC pause behaviour and allocator churn under sustained load.
66
+ - Whether a cache actually reduces latency in production, versus merely existing in the code.
67
+ - Cold-start time for serverless or lambda-style deployments.
46
68
 
47
69
  ## Severity guidance
48
70
 
@@ -55,4 +77,9 @@ Where does time and memory actually go? Gate: a hot path or a measurable workloa
55
77
  | O(n²) reachable at realistic input sizes | Medium |
56
78
  | Synchronous I/O on a request path | Medium |
57
79
  | Expensive work at import time | Medium |
80
+ | LCP candidate blocked behind a client-only fetch, no SSR/prerender fallback | Medium |
81
+ | CLS-causing element with no reserved space | Medium |
82
+ | Expensive synchronous work inside an interaction handler on a ranked hot path | Medium |
58
83
  | Repeated work hoistable out of a loop | Low |
84
+ | No field measurement (web-vitals/RUM) of Core Web Vitals at all | Low |
85
+ | Stale FID tracking with no INP replacement | Low |