project-brain 0.24.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/package.json +6 -6
  3. package/templates/project.claude.md +1 -1
  4. package/templates/skills/brain-audit/SKILL.md +17 -7
  5. package/templates/skills/brain-audit/references/abuse.md +36 -11
  6. package/templates/skills/brain-audit/references/accessibility.md +50 -22
  7. package/templates/skills/brain-audit/references/ai.md +39 -15
  8. package/templates/skills/brain-audit/references/analytics.md +34 -11
  9. package/templates/skills/brain-audit/references/api.md +38 -13
  10. package/templates/skills/brain-audit/references/backend.md +41 -9
  11. package/templates/skills/brain-audit/references/browser.md +146 -0
  12. package/templates/skills/brain-audit/references/complexity.md +22 -12
  13. package/templates/skills/brain-audit/references/concurrency.md +36 -18
  14. package/templates/skills/brain-audit/references/consistency.md +32 -9
  15. package/templates/skills/brain-audit/references/contract-drift.md +34 -16
  16. package/templates/skills/brain-audit/references/cost.md +45 -23
  17. package/templates/skills/brain-audit/references/cross-surface-parity.md +38 -11
  18. package/templates/skills/brain-audit/references/database.md +43 -17
  19. package/templates/skills/brain-audit/references/dependencies-licensing.md +27 -12
  20. package/templates/skills/brain-audit/references/design-system.md +40 -17
  21. package/templates/skills/brain-audit/references/devops.md +32 -17
  22. package/templates/skills/brain-audit/references/documentation.md +38 -16
  23. package/templates/skills/brain-audit/references/failure.md +40 -18
  24. package/templates/skills/brain-audit/references/feature-flags.md +31 -15
  25. package/templates/skills/brain-audit/references/flow-integrity.md +42 -10
  26. package/templates/skills/brain-audit/references/frontend.md +40 -12
  27. package/templates/skills/brain-audit/references/functional.md +31 -11
  28. package/templates/skills/brain-audit/references/future.md +28 -7
  29. package/templates/skills/brain-audit/references/goal.md +15 -6
  30. package/templates/skills/brain-audit/references/i18n.md +30 -8
  31. package/templates/skills/brain-audit/references/idempotency.md +46 -24
  32. package/templates/skills/brain-audit/references/infrastructure.md +43 -13
  33. package/templates/skills/brain-audit/references/mobile.md +37 -15
  34. package/templates/skills/brain-audit/references/multi-tenancy.md +41 -12
  35. package/templates/skills/brain-audit/references/numeric.md +33 -16
  36. package/templates/skills/brain-audit/references/observability.md +43 -19
  37. package/templates/skills/brain-audit/references/packaging.md +39 -13
  38. package/templates/skills/brain-audit/references/performance.md +43 -13
  39. package/templates/skills/brain-audit/references/privacy.md +38 -15
  40. package/templates/skills/brain-audit/references/product.md +29 -10
  41. package/templates/skills/brain-audit/references/prompt-spec-gap.md +34 -10
  42. package/templates/skills/brain-audit/references/reachability.md +38 -18
  43. package/templates/skills/brain-audit/references/repo-history.md +23 -16
  44. package/templates/skills/brain-audit/references/runtime.md +48 -10
  45. package/templates/skills/brain-audit/references/scalability.md +37 -10
  46. package/templates/skills/brain-audit/references/security.md +46 -22
  47. package/templates/skills/brain-audit/references/state-model.md +44 -15
  48. package/templates/skills/brain-audit/references/supply-chain.md +42 -13
  49. package/templates/skills/brain-audit/references/temporal.md +37 -14
  50. package/templates/skills/brain-audit/references/testing.md +38 -14
  51. package/templates/skills/brain-audit/references/tooling-baseline.md +34 -18
  52. package/templates/skills/brain-audit/references/type-safety.md +38 -19
  53. package/templates/skills/brain-audit/references/usability.md +78 -0
  54. package/templates/skills/brain-audit/references/versioning-compatibility.md +34 -12
  55. package/templates/skills/brain-audit/references/visual-design.md +38 -12
  56. package/templates/skills/brain-audit/references/web-metadata.md +47 -19
  57. package/templates/skills/brain-record/SKILL.md +297 -0
  58. package/templates/skills/brain-record/assets/build-video.sh +142 -0
  59. package/templates/skills/brain-record/assets/record.mjs +283 -0
  60. package/templates/skills/brain-record/references/pitfalls.md +233 -0
  61. package/templates/skills/brain-worktree/SKILL.md +103 -0
@@ -6,42 +6,46 @@ Mobile amplifies every defect the other modules find: the network is unreliable,
6
6
 
7
7
  ## Lifecycle
8
8
 
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.
9
+ - [ ] State survives backgrounding. `search_code` for the lifecycle hook (`onPause`, `applicationDidEnterBackground`, an `AppState` listener) and confirm state bound to a form field or a multi-step flow's progress — specifically, not any other in-memory value such as scroll position or an open toast — is written to a durable store (disk, `SharedPreferences`/`UserDefaults`, a persisted store) inside that hook, not only held in a view model (Android Developers, Google, current, https://developer.android.com/topic/libraries/architecture/saving-states — `ViewModel` alone "is destroyed during a system-initiated process death"; a user "expects your app's UI state to remain the same" after switching away and back).
10
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
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.
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. Exclude screens locked to a single orientation (`android:screenOrientation="portrait"` or equivalent), where rotation cannot occur at all (Android Developers, Google, current, https://developer.android.com/guide/topics/resources/runtime-changes — a configuration change destroys and recreates the Activity, clearing any state kept as fields on it; the docs cite a form left half-filled as the concrete bad outcome).
13
13
 
14
14
  ## Network reality
15
15
 
16
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`.
17
+ - [ ] Retries are bounded and backed off — owned by `failure.md` (`search_code` the retry wrapper around a network call and confirm a max-attempt count and backoff exist); reuse its finding, do not re-report. This module's own angle is the metered-connection cost consequence: an unbounded retry on a metered connection is a cost defect too — cross-reference `Cost`.
18
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
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 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.
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 (Apple, App Store Review Guidelines §5.1.1, current, https://developer.apple.com/app-store/review/guidelines/ — "apps should only request access to data relevant to the core functionality of the app"). Read each permission's usage-description string (`NSCameraUsageDescription` and siblings in Info.plist, the runtime permission-rationale copy shown before an Android request) and confirm it names the concrete feature and reason, not a generic restatement of the permission's own name (e.g. "Camera access" for `NSCameraUsageDescription`) — a boilerplate string is a store-rejection risk independent of whether the permission itself is used. Refuted when a short string already names the specific feature (e.g. "Used to scan receipts for expense reports" is specific despite being brief); quote the full string before judging it generic (Apple, App Store Review Guidelines §5.1.1, current, https://developer.apple.com/app-store/review/guidelines/ — purpose strings must "clearly and completely describe your use of the data").
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 (Android Developers, Google, current, https://developer.android.com/training/permissions/requesting — after a user denies a permission more than once, the system stops showing the dialog again (`USER_FIXED`); the docs instruct apps to "gracefully degrade" and name the specific unavailable feature rather than block the whole UI).
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 (Android Developers, Google, current, https://developer.android.com/training/permissions/requesting — "ask for a permission in context, when the user starts to interact with the feature that requires it").
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 a token/credential-shaped variable name adjacent to a `SharedPreferences`/`UserDefaults`/plain-file write call, instead of `Keychain`/`Keystore`/`EncryptedSharedPreferences`.
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`; that is `High` at `read`. `trace_path` from the auth client/handler that produces the token to the plain-storage write call promotes the finding to `traced`, and `Critical`, by proving the value is genuinely a live credential rather than a similarly-named field (Android Developers, Google, current, https://developer.android.com/privacy-and-security/keystore — Keystore keeps key material out of the app process: "if the app's process is compromised, the attacker might be able to use the app's keys but can't extract their key material"). `find_callers` on the Keystore/Keychain key used for a payment, account-deletion, or credential-export operation and confirm the call site requires a fresh biometric or device-credential prompt (`BiometricPrompt`, `LAContext`) immediately before use, not only that the key lives in the platform keystore — a keystore-backed key usable without re-authentication is protected from extraction but not from a device left unlocked. Refuted when the operation already sits behind a very recent full authentication (e.g. inside a session that itself required biometric unlock seconds earlier) — trace the session's auth freshness before flagging a missing second prompt as redundant (Android Developers, Google, current, https://developer.android.com/privacy-and-security/keystore — Keystore lets an app require user authentication as an authorized-use condition on a key, a control plain `SharedPreferences`/file storage has no equivalent for).
30
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
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
+ ## OTA and release channel
34
+
35
+ - [ ] `search_code`/`Read` the OTA-update configuration (`app.json`/`eas.json` `runtimeVersion`, an equivalent CodePush deployment key) and confirm JS bundles are pinned to a runtime version the installed native binary declares — an OTA channel with no runtime-version policy can ship JS that expects a native module or permission the shipped binary does not have. Refuted when the app has no native-code dependency that could drift from JS (rare, but possible for a nearly-pure-JS app), or the OTA tooling itself enforces compatibility (some CodePush setups reject an incompatible bundle at the server) — check the enforcement point before flagging (Expo/650 Industries, EAS Update docs, current, https://docs.expo.dev/eas-update/introduction/ — native code, native dependencies, permissions, and SDK-version changes are explicitly excluded from OTA and require a new binary; nothing in the docs describes automatic protection against shipping JS a given binary can't run).
36
+
33
37
  ## Platform integration
34
38
 
35
39
  - [ ] 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
40
  - [ ] 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.
41
+ - [ ] 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 (Android Developers, Google, current, https://developer.android.com/develop/ui/views/layout/edge-to-edge — targeting SDK 35 on Android 15+ makes edge-to-edge mandatory; without handling `WindowInsets`, "portions of your app may be obscured").
38
42
  - [ ] 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
43
 
40
44
  ## Performance on real devices
41
45
 
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.
46
+ - [ ] 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 (Android Developers, Google, current, https://developer.android.com/topic/performance/vitals/anr — disk I/O, network calls, and long calculations on the main thread are named causes of an ANR; input dispatch un-acknowledged within 5 seconds triggers one). `search_code` for a large payload or heavy synchronous computation crossing the legacy bridge (a `NativeModules` call carrying more than a small JSON payload, or a JS-side loop over thousands of items) in a React Native app not yet on the New Architecture (no Fabric/TurboModules); this is the React Native-specific instance of the same defect — the bottleneck is bridge serialization, not the OS main thread, so it survives even when a `search_code` sweep for native disk/crypto calls comes back clean. Refuted when the app has adopted the New Architecture (JSI/Fabric/TurboModules) app-wide, in which case this serialization cost does not apply — confirm via the project's `newArchEnabled`/architecture flag before flagging (React Native core team/Meta, current, https://reactnative.dev/docs/the-new-architecture/why — the legacy bridge is asynchronous and pays a serialization cost on every JS↔native call; JSI replaces it with a direct C++ object reference, removing that cost).
47
+ - [ ] 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 (React Native core team/Meta, current, https://reactnative.dev/docs/optimizing-flatlist-configuration — full-list mounting is the failure mode virtualization knobs exist to avoid; rendering can fall behind and produce visible "blank areas"). Where a virtualising list is already in use (the check above passed), `search_code` for a large or unbounded dataset rendered through it with no `getItemLayout`/item-size hint and a default or oversized `windowSize` — the presence of a virtualising list component does not by itself prevent the blank-area-on-fast-scroll failure mode; a misconfigured one still drops frames. Refuted when the list's typical dataset is small enough (bounded by the API's own page size, confirmed via `find_callees` to the fetch call) that virtualization configuration is moot regardless of the props used (React Native core team/Meta, current, https://reactnative.dev/docs/optimizing-flatlist-configuration — `windowSize` and `removeClippedSubviews` are named as the specific levers against dropped frames and blank areas; `removeClippedSubviews` "reduces time spent on the main thread, and thus reduces the risk of dropped frames").
48
+ - [ ] 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 (Android Developers, Google, current, https://developer.android.com/topic/performance/graphics/load-bitmap — decoding a camera photo at full resolution "takes up precious memory and incurs additional performance overhead" and can throw `OutOfMemoryError`; a 2048×1536 image at `inSampleSize=4` uses 0.75 MB instead of 12 MB).
45
49
  - [ ] 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
50
 
47
51
  ## Out of static reach
@@ -50,18 +54,36 @@ Mobile amplifies every defect the other modules find: the network is unreliable,
50
54
  - Real memory pressure and whether the OS actually reclaims the process under it.
51
55
  - Battery drain and wake-lock duration in practice, versus a stated budget in source.
52
56
  - 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.
57
+ - App-store review outcomes for permission usage: this module confirms a permission has a call site, not that a reviewer accepts the justification, nor — for a purpose string specifically — that App Review accepts it as clear and complete rather than merely non-generic.
54
58
  - Platform-API behaviour across the OS version fragmentation the codebase does not branch on.
59
+ - Whether flagged main-thread or bridge work actually drops frames or triggers an ANR on a real device — this module confirms a code path capable of blocking, not measured frame timing.
60
+ - Whether a bad OTA update is caught and rolled back before reaching most users — this module confirms a runtime-version pin exists, not that a rollout/rollback policy operates.
61
+ - Whether a pinned certificate is current and rotates before expiry — this module can find a pinning library import, not validate the pinned certificate data itself.
62
+ - Whether certificate/TLS pinning is required or expected on the auth/payment client(s): OWASP MASVS names MASVS-NETWORK as a control category (OWASP MAS project, OWASP MASVS, current, https://mas.owasp.org/MASVS/), but its normative pinning-control text was not independently fetchable in this research pass — a coverage gap, not a scored check, until that control text is cited directly.
63
+
64
+ ## What browser observation closes
65
+
66
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number. `browser.md`'s tools drive a Chromium-family browser against a URL — a native mobile app has no URL to navigate to and no DOM to read, so its lifecycle hooks, permission dialogs, Keystore/Keychain calls, deep-link handling, background execution, and main-thread work stay entirely in `Out of static reach` regardless of whether browser observation runs. The two rows below apply only when the same product also ships (or is) a web/PWA surface, and even then they substitute for exactly one module heading's concerns (Platform integration's safe-area/touch-target angle).
67
+
68
+ | Artefact | Gap it closes | Observed instance earns |
69
+ |---|---|---|
70
+ | `screenshots/` at a mobile emulation preset + `a11y-snapshot.md` bounding boxes on the interactive element, where the tool exposes them (`playwright`'s `browser_snapshot`; not producible from `claude-in-chrome`'s `read_page`) | Touch targets meet the platform minimum (44×44pt iOS / 48×48dp Android), for a PWA or responsive web build only. A decorative or non-interactive element measured undersized is not a touch-target defect; only elements with a click/tap handler or link role count. Not producible when the bundle carries no bounding boxes for the tool that filled the walker role — report under Coverage Gaps instead. | Low |
71
+ | `screenshots/` + `scrollWidth`/`clientWidth` evaluate result, reusing `browser.md`'s own reflow candidate verbatim | Reflow / horizontal overflow at a 320px-wide emulated viewport, for a PWA or responsive web build only. Refuted if the overflowing region is one of WCAG 1.4.10's exempted two-dimensional cases | Medium |
55
72
 
56
73
  ## Severity guidance
57
74
 
58
75
  | Situation | Severity |
59
76
  |---|---|
60
- | Credential in plain local storage | Critical |
77
+ | Credential in plain local storage, confirmed via `trace_path` from the auth response (traced) | Critical |
78
+ | Credential-shaped value in plain local storage, established only by reading the storage call | High |
61
79
  | Crash on deep link or cold start | High |
62
- | State lost on backgrounding | High |
63
- | Unbounded retry loop | High |
80
+ | Form or multi-step-flow state lost on backgrounding | High |
64
81
  | Permission requested but never used | Medium |
65
82
  | Permanent-denial path dead-ends | Medium |
66
83
  | Blocking work on the UI thread | Medium |
67
84
  | Platform branch with an unhandled side | Medium |
85
+ | Boilerplate usage-description string, store-rejection risk | Medium |
86
+ | OTA channel with no runtime-version pin against the native binary | High |
87
+ | Keystore-backed key for a high-value operation usable with no fresh re-authentication | Medium |
88
+ | JS-thread blocking work crossing the legacy React Native bridge | Medium |
89
+ | Virtualising list present but misconfigured for its dataset size | Low |
@@ -6,10 +6,10 @@ Is every data access scoped to the right tenant? Gate: tenant, organisation, or
6
6
 
7
7
  ## Inventory
8
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.
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. AWS's SaaS Architecture Fundamentals whitepaper: "tenant isolation is separate from general security mechanisms... a user could be authenticated and authorized, and still access the resources of another tenant" — pooled resources need "more fine-grained policies to control access" than dedicated-stack isolation does.
10
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
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.
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. Rule out a deliberately tenant-agnostic identity table (a user account that can belong to more than one tenant) before flagging.
13
13
 
14
14
  ## Query-level scoping
15
15
 
@@ -17,24 +17,34 @@ Is every data access scoped to the right tenant? Gate: tenant, organisation, or
17
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
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
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.
20
+ - [ ] Endpoints or resolvers accepting an array of resource IDs (bulk fetch, bulk delete, batch export) — `search_code` for handler signatures taking an ID list, then `find_callees` to confirm the query built from that list carries the same tenant filter as the single-ID path (a `WHERE id IN (...) AND tenant_id = ?`), rather than a query scoped only by the ID list with tenant checked once outside the loop or not at all. A batch query that carries the tenant filter across the whole `IN (...)` set in one statement is correct scoping, not the finding, even though it looks unlike the single-ID pattern. OWASP API1:2023 BOLA requires checking permissions "in every function that uses an input from the client to access a record" — a batch/array endpoint is that function.
21
+ - [ ] 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. Where tenant context comes from a JWT or session claim, `search_code` the verification step and `find_callers` to confirm every tenant-scoped route calls it before the tenant-context setter runs, then `Read` the verification body itself to confirm it checks the claim against tenant membership for the resource being acted on, not merely that the token carries a validly signed claim — a shared signing key or verification path could accept a token minted for tenant A on a request addressed to tenant B. Structural coverage alone only proves the check runs everywhere, not that it does the right comparison, so a mixed check like this caps at the tier of its weaker half (`read`, not `traced`), per the Evidence Contract.
22
+ - [ ] 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 (PostgreSQL's own Row Security Policies documentation: "table owners normally bypass row security as well"). 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 ("superusers and roles with the BYPASSRLS attribute always bypass the row security system"). Either gap means the policies are dead code for the role that matters.
23
+
24
+ ## Tenant resolution
25
+
26
+ - [ ] Where tenant resolution derives from the request's Host header, `X-Forwarded-Host`, or a subdomain (the common per-tenant-subdomain SaaS pattern) — `search_code` the tenant-resolution middleware/function for where it reads that value, and confirm it is looked up against a registered tenant/domain table (a miss rejects) rather than trusted directly as the tenant identifier or interpolated into a generated link. A resolved value looked up against a tenant table where a miss is rejected (404/no match) rather than accepted as-is is not this finding — a lookup miss is a different failure mode than trusting the header value directly. PortSwigger's Host header attacks documentation: servers that derive routing or absolute-URL generation from the client-controllable Host header (or `X-Forwarded-Host`) enable password-reset poisoning, web-cache poisoning, virtual-host brute-forcing, routing-based SSRF, and authentication bypass — a per-tenant-subdomain architecture is the multi-tenant instance of this trust pattern.
27
+
28
+ ## Non-relational and search stores
29
+
30
+ - [ ] Stores queried outside the SQL/ORM layer entirely — a full-text search index, a vector database, an in-memory store queried via its own client library — `search_code` the query-construction call sites against each and confirm the tenant filter is part of that store's own query (a `term`/`filter` clause, a metadata predicate, or a separate index/collection per tenant), not assumed from the request-scoped context that only the SQL layer's central mechanism (found above) actually enforces. A store siloed per tenant at the index/collection-naming level (one index/collection per tenant) needs no query-level filter clause — confirm the naming convention before flagging a missing filter. AWS's SaaS tenant-isolation guidance generalises past SQL tables to any pooled resource; OWASP API1:2023 BOLA's "every function that uses input from the client to access a record" applies equally to a search/vector query function.
22
31
 
23
32
  ## Paths with no request context
24
33
 
25
34
  - [ ] 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
35
  - [ ] 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
36
  - [ ] 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.
37
+ - [ ] 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. This is `High` at `read`; `trace_path` from the webhook/queue handler to the query function that consumes the tenant value, then `Read` the handler to confirm the payload's tenant field is what the traced path carries, promotes it to `traced`, and `Critical`. CWE-639 Authorization Bypass Through User-Controlled Key names exactly this failure mode; OWASP's Multi-Tenant Security Cheat Sheet: "treat client-supplied tenant identifiers as selectors only."
29
38
 
30
39
  ## Identifiers
31
40
 
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.
41
+ - [ ] Sequential or otherwise guessable IDs (auto-increment integers) used as externally-exposed resource identifiers — `search_code` the API response shapes and URL path parameters for a numeric, sequential ID field. 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. OWASP API1:2023 BOLA recommends "random and unpredictable values as GUIDs" instead; CWE-639 names sequential/guessable identifiers explicitly as the multi-tenant/horizontal-authorization failure mode.
42
+ - [ ] Whether a request for another tenant's real resource ID returns a distinguishable response (a 403/"forbidden" body) from the one used for a genuinely absent ID (404) in the same tenant-scoped query/repository layer — `search_code` the not-found and forbidden branches. A response an attacker can tell apart confirms the ID exists under a different tenant even when no data is returned. A shared error-handling layer that normalizes both branches to an identical response before they leave the service is not the finding — check that layer, not just the repository's own branch. Cross-reference `abuse.md` for the enumeration/rate-limiting half; report the response-shape choice here, same split as the check above. The existence signal is a lesser instance of the same user-controlled-key leak CWE-639 describes, on the same object-identifier attack surface as BOLA.
33
43
 
34
44
  ## Caches
35
45
 
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.
46
+ - [ ] 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. PortSwigger's web cache deception documentation: a cache key that diverges from how the origin interprets the URL "lets a cache store and later replay one user's private, dynamic response to a different requester using the same key"; CWE-524 Use of Cache Containing Sensitive Information covers the same defect generally.
47
+ - [ ] 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. CWE-524: mitigations include verifying and protecting information stored in a shared cache, not trusting the key alone.
38
48
 
39
49
  ## Files and cross-boundary data
40
50
 
@@ -48,19 +58,33 @@ Is every data access scoped to the right tenant? Gate: tenant, organisation, or
48
58
 
49
59
  ## Out of static reach
50
60
 
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.
61
+ - 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 — closed by `runtime.md` when execution is enabled (running this module's own declared cross-tenant-isolation test).
52
62
  - Real cache collision behaviour under production key distributions.
53
63
  - Whether a background job's tenant loop actually covers every active tenant in practice.
54
64
  - Storage bucket/IAM policy configuration outside the repository.
65
+ - Whether the reverse proxy or load balancer in front of this service already whitelists the Host header before the application ever sees it — this module reads application code, not infrastructure configuration.
66
+ - Whether tenant JWT signing keys are actually isolated per tenant in the secrets manager, versus one shared key read from the same config value this module can see — key material itself is out of static reach.
67
+ - Whether the batch tenant filter still applies under an adversarial or malformed ID-list payload — that is a `runtime.md`/fuzzing question, not a static read.
68
+ - Whether a search/vector store's underlying index or shard actually enforces the isolation its application-level query implies — cluster configuration is out of static reach.
69
+
70
+ ## What browser observation closes
71
+
72
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number. Both rows need two authenticated tenant sessions the user provided credentials for, walked against the same endpoints; `network.jsonl` captures response bodies only on 4xx/5xx, so a 200 carrying the wrong tenant's data is **not** visible here — only status, size, headers and timing are diffed.
73
+
74
+ | Artefact | Gap it closes | Observed instance earns |
75
+ |---|---|---|
76
+ | `network.jsonl` | Whether a tenant-scoped endpoint answers a second tenant's session with the first tenant's status, size or cache headers — a 200 with identical size where a 403/404 or a different payload size was expected, or a shared `ETag`/`Cache-Control` across tenants | High |
77
+ | `network.jsonl` | Whether a cached response actually crosses tenants on the flows walked — same `ETag`, same `Age`/`X-Cache` hit, same size for two tenant sessions requesting tenant-scoped data | High |
78
+ | `network.jsonl` (status **and** body, captured on 4xx/5xx) | Cross-tenant existence via a distinguishable error response — two authenticated tenant sessions, one requesting the other's real resource ID, compared against that same session requesting a genuinely absent ID, capped at or below the static `read`-tier finding since this only confirms the response is distinguishable, not that data was returned | Low |
55
79
 
56
80
  ## Severity guidance
57
81
 
58
82
  | Situation | Severity |
59
83
  |---|---|
60
- | Cache key for tenant data with no tenant component | Critical |
61
84
  | 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 |
85
+ | Webhook/queue payload's self-declared tenant ID trusted without re-derivation (traced) | Critical |
86
+ | Cache key for tenant data with no tenant component | High |
87
+ | RLS enabled but not `FORCE`d, or app connects via a role with `BYPASSRLS`/superuser | High |
64
88
  | Background job or scheduled work with no tenant scoping at all | High |
65
89
  | Tenant identifier sourced from a client-supplied value instead of the authenticated session | High |
66
90
  | Tenant-scoped table with no tenant column at all | High |
@@ -72,3 +96,8 @@ Is every data access scoped to the right tenant? Gate: tenant, organisation, or
72
96
  | Unique constraint scoped globally instead of per-tenant | Medium |
73
97
  | No test asserting cross-tenant isolation | Medium |
74
98
  | Inconsistent tenant-parameter naming across modules | Low |
99
+ | Batch/bulk endpoint's query traced (`find_callees`) to skip the per-record tenant filter | High |
100
+ | Tenant resolved from Host header/subdomain with no registered-tenant-table lookup | High |
101
+ | JWT/session claim accepted with no tenant-membership check beyond signature validity | High |
102
+ | Non-relational/search store queried with no tenant filter and no per-tenant index/collection | High |
103
+ | Cross-tenant existence disclosed via a distinguishable error response (403 vs. 404) | Low |
@@ -6,41 +6,53 @@ Nothing else in this skill covers this. `database.md` audits schema shape genera
6
6
 
7
7
  ## Money as floating point
8
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.
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 (David Goldberg, "What Every Computer Scientist Should Know About Floating-Point Arithmetic," ACM Computing Surveys vol. 23, 1991, https://docs.oracle.com/cd/E19059-01/fortec6u2/806-7996/806-7996.pdf). This is not a theoretical risk: CWE-1339 names the Sleipner A offshore platform collapse — a ~$700M loss from a 50% buoyancy-calculation underestimation caused by numerical precision error between finite-element modules (MITRE, CWE-1339, official weakness catalogue entry, current, https://cwe.mitre.org/data/definitions/1339.html) — as a demonstrative example of exactly this class of defect. This is `High` at `read`; `find_callers` on the float-typed field's accessor, showing arithmetic actually consumes it, promotes this to `traced`, and `Critical`.
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. Stripe's own API represents all amounts as integers in the currency's minor unit for exactly this reason (Stripe, official API/product documentation, current, https://docs.stripe.com/currencies.md).
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 (David Goldberg, "What Every Computer Scientist Should Know About Floating-Point Arithmetic," ACM Computing Surveys vol. 23, 1991, https://docs.oracle.com/cd/E19059-01/fortec6u2/806-7996/806-7996.pdf). `search_code` the response serializer for money fields.
12
12
 
13
13
  ## Rounding
14
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.
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: "both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`" (Python Software Foundation, official language documentation, current, https://docs.python.org/3/library/functions.html#round)), 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 toward +∞ (`Math.round(2.5) === 3`, `Math.round(-2.5) === -2`, and even `Math.round(-5.5) === -5`) (MDN Web Docs, official language reference, current, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round), 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. Vancouver Stock Exchange's index computation is the canonical real-world example of what unexamined rounding-mode choice costs: recalculated via `floor()` (truncation, not rounding) roughly 3000 times a day, it drifted from 1000 to 524.811 over ~22 months before a weekend correction restored it to 1098.892 — roughly half its true value lost purely to truncation bias, compounded (Wikipedia, "Vancouver Stock Exchange," public post-mortem account, current, https://en.wikipedia.org/wiki/Vancouver_Stock_Exchange).
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." Rule out a display-only rounding that never feeds back into a stored or summed value — the finding is disagreement between two values that must reconcile, not any rounding difference.
17
+ - [ ] Division and percentage arithmetic that discards the remainder — `search_code` for 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 ranking shares by their fractional remainder and handing the leftover units to the largest ones first (the standard largest-remainder/Hamilton apportionment method: floor each share, then rank by fractional remainder and allocate leftover units to the largest remainders in order) (Wikipedia, "Largest remainder method," public reference, current, https://en.wikipedia.org/wiki/Largest_remainder_method) — dumping the remainder on the last share by position, rather than by remainder size, is a common shortcut but is not the same algorithm, and only coincidentally sums correctly. Not just independently rounded, which drifts the sum away from the total by a cent or more.
19
19
 
20
20
  ## Currency and units
21
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.
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 (Wikipedia, reproducing the ISO 4217 maintenance-agency currency/minor-unit table, current, https://en.wikipedia.org/wiki/ISO_4217), and it is not always 2: JPY, KRW, VND and others use exponent 0 outright (no minor unit at all — the major unit *is* the smallest unit, so `×100` inflates the stored amount a hundredfold); ISK and UGX are zero-decimal by ISO 4217 today but are still conventionally encoded as two-decimal-with-`00` by major payment APIs for backward compatibility — check what the integrated processor actually expects, not only the raw ISO exponent (Stripe, official API/product documentation, current, https://docs.stripe.com/currencies.md). 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
+ - [ ] A currency exponent table or switch statement that assumes one minor-unit rule per currency code everywhere it is used — `search_code` for the currency-exponent config and confirm currencies that transitioned exponent or that vendors special-case operationally are handled per operation, not assumed to follow one flat rule derived from the currency code alone. Stripe documents exactly this: ISK and UGX legally transitioned to zero-decimal but are still required encoded as two-decimal for backward compatibility, and HUF and TWD are two-decimal for charges but must be zero-decimal-and-divisible-by-100 for payouts — the same currency has two different minor-unit rules depending on which operation touches it (Stripe, official API/product documentation, current, https://docs.stripe.com/currencies.md). Refuted if the codebase never touches ISK, UGX, HUF, or TWD, or its currency-exponent table already encodes the operation-specific exception explicitly — confirmed by reading the table's own comments/tests rather than assuming absence of a bug.
24
+ - [ ] 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 — "money isn't actually a first class data type in any mainstream programming language," and a dedicated Money type exists precisely to prevent this (Martin Fowler, martinfowler.com, Patterns of Enterprise Application Architecture catalogue page, current, https://martinfowler.com/eaaCatalog/money.html).
25
+ - [ ] Exchange-rate application — `find_symbol` the rate-application function and `Read` whether it uses the rate valid at the transaction time versus whatever the latest cached rate happens to be, and whether the rate itself carries its own timestamp. Cross-reference `temporal.md` for whether that timestamp is stored as a proper instant.
25
26
  - [ ] 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
27
  - [ ] 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
 
28
29
  ## Precision and comparison
29
30
 
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.
31
+ - [ ] 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; beyond that, integers alias, so `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` evaluates `true`) (MDN Web Docs, official language reference, current, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). 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.
32
+ - [ ] Floating-point values compared for equality (`===`, `==`, `.equals()`) anywhere in the codebase — `search_code` for `===` or `==` beside a variable that is a computed float. Direct equality/inequality tests on floats "do not account for the possibility of loss of precision" from rounding error, so two mathematically equivalent calculations can produce differently-bit-represented results and an equality test yields an unexpected outcome (MITRE, CWE-1077, official weakness catalogue entry, current, https://cwe.mitre.org/data/definitions/1077.html). This is a near-guaranteed false negative on values that are mathematically equal but bit-different due to accumulated rounding. Rule out comparison against an exact, non-computed constant (`0`, a fixed sentinel) — the risk is two independently rounded results, not a comparison to a literal.
33
+ - [ ] Database numeric column precision/scale versus the application type's range — `find_symbol` the column definition and compare it against the application type's range: a `DECIMAL(10,2)` column paired with an application type that permits more precision is silently truncated on write with no error surfaced.
33
34
  - [ ] 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
+ - [ ] `NaN` and `Infinity` reachability into a persisted or serialised value — `trace_path` from the enclosing function of a division/parsing site that can produce `NaN`/`Infinity` to the serialiser/persist function: a `NaN` written to a numeric column, or serialised into JSON (where it becomes `null` or invalid JSON depending on the serializer), silently corrupts the value with no error at the point of injection. Small precision variations in financial calculations are exactly the class CWE-1339 flags as exploitable when a security decision or calculation depends on them (MITRE, CWE-1339, official weakness catalogue entry, current, https://cwe.mitre.org/data/definitions/1339.html) — this module stops at proving the value is reachable and wrong; `security.md` owns whether a specific reachable `NaN` is itself exploitable.
35
36
 
36
37
  ## Sign and bounds
37
38
 
38
39
  - [ ] 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
+ - [ ] 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) — `find_symbol` the validation on the write path and `trace_path` from the user-input entry point to the arithmetic operation to confirm it is reachable from user input, not just internal computation.
40
41
 
41
42
  ## Recomputation
42
43
 
43
44
  - [ ] 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.
45
+ - [ ] Where a total is recomputed in more than one place and the formulas match line-for-line, additionally `find_symbol` each site's declared numeric type — a formula identical in both places still diverges at scale if one path runs on a binary float/double and the other on a fixed-point/`Decimal` type, the same class of defect CWE-1339 names in the Sleipner A platform collapse: two independently developed calculation modules disagreeing by precision, not formula (MITRE, CWE-1339, official weakness catalogue entry, current, https://cwe.mitre.org/data/definitions/1339.html). Refuted if both sites round or serialise to the same fixed precision before the values are ever compared, stored, or summed, so the underlying type difference cannot surface as a visible discrepancy — confirmed by reading the shared downstream formatting/persistence call.
46
+
47
+ ## What browser observation closes
48
+
49
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number.
50
+
51
+ | Artefact | Gap it closes | Observed instance earns |
52
+ |---|---|---|
53
+ | `read_page` output or `final-state.md`, arithmetic on the extracted rendered numbers | Displayed total does not equal the sum of displayed line items on a confirmed flow. Refuted if the subtotal is explicitly labeled as excluding a downstream charge (tax, shipping) shown separately — check the UI label before flagging. | High |
54
+ | `network.jsonl` (raw JSON amount + currency) cross-referenced against `screenshots/`/`read_page` output (displayed value) | Rendered/formatted amount does not match the raw `amount` value in the API response for the same field. Refuted if the UI applies a disclosed FX conversion (a rate or "converted from" label is visible) — not a bug, an intentional display conversion. | High |
55
+ | `network.jsonl` (currency field) + `screenshots/` (rendered symbol) | Currency symbol/code rendered in the UI does not match the `currency` field on the same amount in the API response. Refuted if the UI is showing settlement currency while the API returns presentment currency (or vice versa) — a legitimate distinction Stripe's own docs draw (Stripe, official API/product documentation, current, https://docs.stripe.com/currencies.md) — confirm which the UI claims to show before flagging. | Medium |
44
56
 
45
57
  ## Out of static reach
46
58
 
@@ -48,16 +60,21 @@ Nothing else in this skill covers this. `database.md` audits schema shape genera
48
60
  - Real-world exchange rate feed staleness or provider outages.
49
61
  - Cumulative floating-point drift over a live dataset's actual transaction history.
50
62
  - Currency-conversion correctness against the specific jurisdiction's legally mandated rounding rules.
63
+ - Whether a locale's decimal/thousands-separator convention is parsed and formatted consistently across every input and display surface — this module found no source meeting its bar to ground the check, so it is not raised here.
64
+ - Whether an out-of-range write to a fixed-precision column silently truncates or raises an error — this depends on the database server's own configured strictness, not on anything the repository's source declares.
65
+ - Whether a numeric-precision defect this module traces into persistence is itself security-exploitable — `security.md` owns that determination; this module stops at proving the value is reachable and wrong.
51
66
 
52
67
  ## Severity guidance
53
68
 
54
69
  | Situation | Severity |
55
70
  |---|---|
56
- | Money stored or transmitted as binary float anywhere in the chain | Critical |
71
+ | Money stored or transmitted as binary float anywhere in the chain (traced) | Critical |
57
72
  | Split/allocation logic that does not sum back to the total | High |
58
73
  | Arithmetic between two amounts whose currencies are never checked | High |
59
74
  | Large ID or amount losing precision across a JSON boundary | High |
60
75
  | Hardcoded ×100/÷100 conversion applied to a non-exponent-2 currency | High |
76
+ | Currency-exponent rule applied uniformly by currency code when the vendor requires an operation-specific exception | High |
77
+ | Recomputation sites with matching formulas but diverging numeric types (float vs. fixed-point) | High |
61
78
  | Floating-point equality comparison on computed monetary values | Medium |
62
79
  | Rounding mode unstated, or disagreeing between two computation sites | Medium |
63
80
  | Unit-bearing field with no unit in its name and inconsistent consumers | Medium |
@@ -9,41 +9,46 @@ The test is concrete: pick the three worst plausible failures for this system an
9
9
  ## Coverage
10
10
 
11
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.
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. This is the golden-signals discipline applied at call-site granularity: latency and error rate are two of the four signals Google's SRE book says to focus on if only four are measured (Google SRE team, official Google SRE Book, current, https://sre.google/sre-book/monitoring-distributed-systems/).
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. The redaction requirement follows OWASP's own list of data that "should usually not be recorded directly in the logs": passwords, tokens, session identifiers, PII, secrets (OWASP, official OWASP Cheat Sheet Series, current, https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html).
15
15
 
16
16
  ## Log quality
17
17
 
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`.
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. Interpolating untrusted input into a log string is also an injection surface: OWASP recommends sanitizing log arguments against CR/LF and delimiter characters (CWE-117 log injection) (OWASP, official OWASP Cheat Sheet Series, current, https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html).
19
+ - [ ] `search_code` for log calls whose arguments directly interpolate a request header, query parameter, or other user-controlled string with no encoding/stripping of CR/LF or log-delimiter characters applied first. An attacker-controlled newline in a log argument can forge additional log lines or corrupt structured-log parsing — OWASP's own guidance is to "perform sanitization on all event data to prevent log injection attacks e.g. carriage return (CR), line feed (LF) and delimiter characters" (CWE-117) (OWASP, official OWASP Cheat Sheet Series, current, https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html). Refuted if the logging library itself always JSON-encodes/escapes field values at the call boundary (true of most structured loggers) — read the library's own serialization path once per project before flagging every call site individually.
20
+ - [ ] 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`. Rule out a system where `failure.md`'s error-path inventory is itself short — a low ratio against few real failure paths is accurate, not decorative.
20
21
  - [ ] 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.
22
+ - [ ] 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. (OpenTelemetry project, official spec/docs, current v1.44.0 fetched Sep 2026, https://opentelemetry.io/docs/specs/semconv/ — confirms both the attribute-naming convention and the `gen_ai.*` Development-status exemption.)
23
+ - [ ] 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. `observability.md` owns the log-quality/structure angle; `privacy.md` owns the compliance/inventory angle — report a given hit once. A hit that is both takes this module's `High`, not `privacy.md`'s lower severity for the same file:line. (OWASP, official OWASP Cheat Sheet Series, current, https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html — the exact "should usually not be recorded" list this check applies.)
23
24
  - [ ] 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.
25
+ - [ ] 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. OWASP's own guidance is that each log entry should capture "when, where, who and what" (OWASP, official OWASP Cheat Sheet Series, current, https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html).
25
26
 
26
27
  ## Metrics
27
28
 
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
+ - [ ] 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. These are Google SRE's own four golden signals — latency, traffic, errors, saturation — "if you can only measure four metrics of your user-facing system, focus on these four" (Google SRE team, official Google SRE Book, current, https://sre.google/sre-book/monitoring-distributed-systems/).
29
30
  - [ ] 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
31
  - [ ] 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.
32
+ - [ ] 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. Prometheus's own instrumentation guidance: "every unique combination of key-value label pairs represents a new time series," and explicitly warns against labels on "user IDs, email addresses, or other unbounded sets of values" (Prometheus project, official docs, current, https://prometheus.io/docs/practices/naming/).
33
+ - [ ] `search_code` metric-emission call sites (already located above) for a label value built by interpolating the raw request path or URL (e.g. `req.path`, `request.url`) rather than a route template (`/users/:id`). This is the same unbounded-cardinality defect as a `user_id` label even when no field is literally named `user_id` — every distinct numeric ID in the path mints a new time series, and Prometheus's own guidance defines the problem by cardinality, not by field name (Prometheus project, official docs, current, https://prometheus.io/docs/practices/naming/). Refuted if the framework's router/metrics middleware already normalizes the path to its route template before the label is set (common in off-the-shelf HTTP metrics middleware) — read the middleware's own labeling code once before flagging every route.
32
34
 
33
35
  ## Tracing
34
36
 
35
37
  - [ ] 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.
38
+ - [ ] 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. (W3C, official normative specification, current, https://www.w3.org/TR/trace-context/ — the `traceparent` header is the standard mechanism for exactly this, format `version-trace_id-parent_id-trace_flags`.)
39
+ - [ ] 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. `service.name` "MUST be provided by the SDK," and resource attributes are meant to identify a service "anywhere else... in a consistent manner" — on spans, logs, and metrics alike (OpenTelemetry project, official spec, current, https://opentelemetry.io/docs/specs/semconv/resource/).
40
+ - [ ] `search_code` for the OTel Resource/SDK initialization (or vendor-SDK equivalent) and confirm `service.name` (and, where the project deploys to more than one environment, `deployment.environment`) is set — not left at a generated default — and that the same resource attaches to the logger and the metrics exporter, not only the tracer. A resource attribute set only on the tracer means logs and metrics from the same process cannot be joined to the same service identity during an incident. Resource attributes are "recommended to be used anywhere else where there is a need to describe a resource in a consistent manner" — spans, logs, and metrics alike (OpenTelemetry project, official spec, current, https://opentelemetry.io/docs/specs/semconv/resource/). Refuted if a single-service repo with one deployment target has no cross-service correlation to lose — downgrade to Info and say so rather than flagging a default `service.name`.
41
+ - [ ] 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. Head-based sampling (decide at trace start) is the standard starting point; tail-based sampling is required to guarantee capture of error/latency-outlier traces (OpenTelemetry project, official docs, current, https://opentelemetry.io/docs/concepts/sampling/).
39
42
 
40
43
  ## Alerting
41
44
 
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.
45
+ - [ ] 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). Golden signals are, by construction, user-facing symptoms (latency, traffic, errors, saturation), not internal causes (Google SRE team, official Google SRE Book, current, https://sre.google/sre-book/monitoring-distributed-systems/).
46
+ - [ ] 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.
47
+ - [ ] 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. Where no in-repo heartbeat exists, mark `undetermined` rather than a finding if the job runs on a managed scheduler that may provide its own out-of-repo alerting — say so explicitly rather than assuming none exists.
48
+ - [ ] 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. Kubernetes' own guidance: liveness must not depend on downstream services, or an outage there triggers a restart storm — "the liveness probe passes when the app itself is healthy, but the readiness probe additionally checks that each required back-end service is available" (Kubernetes project, official docs, current, https://kubernetes.io/docs/concepts/workloads/pods/probes/).
49
+ - [ ] `find_symbol` the liveness endpoint/handler and `find_callees` from it — a liveness check that calls out to a database, queue, or downstream service (rather than only checking the process's own ability to make progress) is a defect independent of whether readiness does the same check correctly: an outage in that dependency will fail liveness on every replica simultaneously and trigger a synchronized restart storm instead of the intended traffic drain. Kubernetes' own docs warn that "incorrect implementation of liveness probes can lead to cascading failures" under load (Kubernetes project, official docs, current, https://kubernetes.io/docs/concepts/workloads/pods/probes/). Refuted if the "dependency" call inside the liveness handler is a local in-process check (e.g. an in-memory cache, a goroutine heartbeat) rather than a network call to an external service — `find_callees` distinguishes a local function from a client/driver call before this is flagged.
50
+ - [ ] 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. Google's own SRE Workbook: a single-window burn-rate alert has "low recall" and the fix is a paired fast+slow window, short window ≈ 1/12 the long window (Google SRE team, official Google SRE Workbook, current, https://sre.google/workbook/alerting-on-slos/).
51
+ - [ ] Where a burn-rate alert exists (per the check above), `Read` its short and long window durations and confirm the short window is roughly 1/12 the long window (the documented starting ratio: 14.4x over 1h+5m, 6x over 6h+30m, 1x over 3d+6h for a 99.9% SLO — Google SRE team, official Google SRE Workbook, current, https://sre.google/workbook/alerting-on-slos/), rather than two arbitrarily chosen windows that happen to both be present. A long-only or short-only window pair defeats the precision/recall tradeoff the two-window design exists to solve. Refuted if the project's own SLO/traffic profile documents a different ratio deliberately (e.g. a very low-traffic service widening the short window for statistical significance) — treat a stated rationale as satisfying the check even off the 1/12 default.
47
52
 
48
53
  ## Out of static reach
49
54
 
@@ -51,7 +56,21 @@ The test is concrete: pick the three worst plausible failures for this system an
51
56
  - Real log volume, and whether it exceeds retention or cost limits in practice.
52
57
  - Whether anyone actually looks at the dashboards this module confirms exist.
53
58
  - 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.
59
+ - Whether traces correlate correctly across async boundaries at runtime, versus merely having the propagation code in place — whether the resulting spans correlate correctly server-side stays out of reach regardless.
60
+ - What the application's sampler is configured to emit, not what a downstream collector or vendor pipeline actually retains — those live outside this repository.
61
+ - Cardinality as authored in one process, not cardinality at the replica count actually deployed — that number lives in the deployment platform, not the repo.
62
+ - Whether high-cardinality fields are emitted, not whether the backend in use can group by them ad hoc — that is a tool capability, not a code property.
63
+ - That the readiness probe queries a real dependency, not that its timeout is tuned correctly for production latency — that needs load data this module does not have.
64
+
65
+ ## What browser observation closes
66
+
67
+ Applies only when `browser.md` ran; findings here are `observed` and cite the bundle path with a line or step number.
68
+
69
+ | Artefact | Gap it closes | Observed instance earns |
70
+ |---|---|---|
71
+ | `network.jsonl` | Trace-context header (`traceparent`/`x-request-id`) actually present per request, with a measurer | High |
72
+ | `console.jsonl` (uncaught error/exception entry, with timestamp) cross-referenced against `network.jsonl` in the same time window for a POST to a known error-tracking host (Sentry/Bugsnag/Rollbar/a custom `/api/errors`-style endpoint) or no such request at all | An uncaught client-side error is never forwarded to an error-tracking endpoint. Refuted if the error is on an explicit ignore-list in a global handler for a known-benign browser quirk (e.g. `ResizeObserver loop limit exceeded`) — confirm the ignore-list via `search_code` before flagging. | Medium |
73
+ | `console.jsonl` shows zero uncaught errors AND `network.jsonl` shows zero requests to any known error-tracking host across the whole walk, corroborated by a `search_code` miss for an error-tracking SDK import | No error-tracking client is active in this session at all — this module's own "absence is itself the evidence" opening rule, promoted from `inferred` to `observed` for the walked flows. Refuted if the SDK is loaded dynamically or conditionally (an async script tag injected at runtime, a feature-flag-gated bundle) rather than statically imported — `search_code`'s static miss does not prove absence there; check the app's script-loading logic and any CSP `script-src` allowlist for a dynamically injected error-tracking host before concluding no client is active. | High |
55
74
 
56
75
  ## Severity guidance
57
76
 
@@ -64,7 +83,12 @@ The test is concrete: pick the three worst plausible failures for this system an
64
83
  | No correlation identifier across an operation | Medium |
65
84
  | Unbounded log volume inside a loop or retry | Medium |
66
85
  | Unbounded metric cardinality | Medium |
86
+ | Liveness probe calls out to a downstream dependency instead of only checking the process's own health | High |
67
87
  | Only averages, no percentiles | Low |
68
88
  | Every message logged at one level | Low |
69
89
  | Ad hoc/non-semconv attribute naming across span, log, or metric fields | Low |
70
90
  | SLO/burn-rate config present but alert is single-window, not multi-window | Low |
91
+ | Resource attribute (`service.name`) set only on the tracer, not shared with the logger and metrics exporter | Medium |
92
+ | Log call interpolates user-controlled input with no CR/LF or delimiter sanitization | Medium |
93
+ | Metric label built from a raw interpolated path/URL instead of a route template | Medium |
94
+ | Burn-rate alert present but short/long window ratio far from the documented 1/12 starting point | Low |