project-brain 0.15.0 → 0.16.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 (37) hide show
  1. package/README.md +52 -1
  2. package/package.json +7 -6
  3. package/templates/skills/brain-audit/SKILL.md +134 -0
  4. package/templates/skills/brain-audit/references/abuse.md +59 -0
  5. package/templates/skills/brain-audit/references/accessibility.md +55 -0
  6. package/templates/skills/brain-audit/references/ai.md +51 -0
  7. package/templates/skills/brain-audit/references/api.md +47 -0
  8. package/templates/skills/brain-audit/references/backend.md +48 -0
  9. package/templates/skills/brain-audit/references/complexity.md +52 -0
  10. package/templates/skills/brain-audit/references/concurrency.md +60 -0
  11. package/templates/skills/brain-audit/references/consistency.md +59 -0
  12. package/templates/skills/brain-audit/references/contract-drift.md +58 -0
  13. package/templates/skills/brain-audit/references/cost.md +60 -0
  14. package/templates/skills/brain-audit/references/database.md +59 -0
  15. package/templates/skills/brain-audit/references/dependencies-licensing.md +59 -0
  16. package/templates/skills/brain-audit/references/devops.md +61 -0
  17. package/templates/skills/brain-audit/references/documentation.md +56 -0
  18. package/templates/skills/brain-audit/references/failure.md +58 -0
  19. package/templates/skills/brain-audit/references/flow-integrity.md +61 -0
  20. package/templates/skills/brain-audit/references/frontend.md +51 -0
  21. package/templates/skills/brain-audit/references/functional.md +39 -0
  22. package/templates/skills/brain-audit/references/future.md +31 -0
  23. package/templates/skills/brain-audit/references/goal.md +38 -0
  24. package/templates/skills/brain-audit/references/i18n.md +61 -0
  25. package/templates/skills/brain-audit/references/infrastructure.md +62 -0
  26. package/templates/skills/brain-audit/references/mobile.md +58 -0
  27. package/templates/skills/brain-audit/references/observability.md +55 -0
  28. package/templates/skills/brain-audit/references/packaging.md +52 -0
  29. package/templates/skills/brain-audit/references/performance.md +58 -0
  30. package/templates/skills/brain-audit/references/privacy.md +63 -0
  31. package/templates/skills/brain-audit/references/product.md +34 -0
  32. package/templates/skills/brain-audit/references/prompt-spec-gap.md +41 -0
  33. package/templates/skills/brain-audit/references/reachability.md +58 -0
  34. package/templates/skills/brain-audit/references/scalability.md +55 -0
  35. package/templates/skills/brain-audit/references/security.md +75 -0
  36. package/templates/skills/brain-audit/references/testing.md +58 -0
  37. package/templates/skills/brain-audit/references/versioning-compatibility.md +59 -0
package/README.md CHANGED
@@ -71,7 +71,21 @@ Once `project-brain setup` has registered the MCP server in your AI tool, you ca
71
71
  | `/brain-reindex` | `project-brain reindex` | Drop and rebuild full index |
72
72
  | `/brain-health` | `project-brain health` | Diagnose Ollama, index staleness, git hook |
73
73
 
74
- The slash commands are Claude Code skills installed globally at `~/.claude/skills/brain-*/SKILL.md`. They work in any session regardless of the current project.
74
+ These five are thin wrappers over the CLI. **project-brain does not install them** — write them yourself as skills in your assistant's global skills directory if you want the shortcuts, or just run the CLI.
75
+
76
+ ### `/brain-audit` — the one skill setup does install
77
+
78
+ | Skill | Equivalent CLI | What it does |
79
+ |---|---|---|
80
+ | `/brain-audit` | *(none — host skill)* | Whole-project audit: dead code, orphan UI, broken flows, coverage gaps, plus findings by severity across security, performance and architecture |
81
+
82
+ Unlike the `/brain-*` commands above, `brain-audit` has no CLI equivalent. It is a host skill: its logic lives in `SKILL.md` and runs inside the assistant, which calls project-brain's MCP tools to do the work. That is what lets it answer "is this export dead?" with `find_callers` instead of guessing from a grep.
83
+
84
+ `project-brain setup` installs it into each registered tool's global skills directory (`~/.claude/skills/`, `~/.codex/skills/`, or the shared `~/.agents/skills/`). Opt out with `project-brain setup --no-brain-audit`.
85
+
86
+ It runs discovery first, proposes an audit module set from what it found, and **waits for you to confirm** before loading anything — 34 modules exist, and loading all of them every time is what makes an audit expensive.
87
+
88
+ Setup never overwrites a `brain-audit/` directory it did not create. If you have your own skill by that name, setup leaves it untouched and tells you.
75
89
 
76
90
  ## MCP Tools
77
91
 
@@ -120,6 +134,8 @@ The CLI commands exit 0 for any executed query — including legitimate empty re
120
134
  | `get_architecture` | One-call project summary: detected tech stack, indexed modules, chunk count, and symbol count. |
121
135
  | `sync_project` | Re-index changed files now (incremental, hash-gated). Streams progress via MCP notifications when the client supplies a `progressToken`. Use when results look stale. |
122
136
 
137
+ Curated knowledge (the *why* behind the code) lives in an OKF bundle rather than in these tools — see [`okf`](#okf--knowledge-bundles-the-why-not-the-what).
138
+
123
139
  Routing: exact symbol → `find_symbol`; who-calls → `find_callers`; what-it-calls → `find_callees`; "what breaks if I change X" → `impact`; "how does A end up calling B" → `trace_path`; fuzzy/conceptual → `search_context` then `expand_context`; exact string/identifier you can type verbatim → `search_code`. The canonical tool list lives in `src/constants.ts` (`TOOL_CATALOG`) and is rendered into both the MCP server instructions and the per-project `CLAUDE.md`.
124
140
 
125
141
  ## Recipes — get the most out of it
@@ -218,6 +234,41 @@ project-brain map --budget 2000 --focus createServer,runSync
218
234
  project-brain code "chargeCard" --limit 5
219
235
  ```
220
236
 
237
+ ### `okf` — knowledge bundles (the *why*, not the *what*)
238
+
239
+ The index answers "what does this code do". It cannot answer "why is it like this", because that never existed in the AST. An **[Open Knowledge Format](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md) v0.2 bundle** — a committed directory of Markdown files with YAML frontmatter — holds that half, and `okf` keeps the two halves honest about each other.
240
+
241
+ ```bash
242
+ project-brain okf validate [dir] # conformance (SPEC §11). Offline.
243
+ project-brain okf sync [dir] # index the concepts so search returns them
244
+ project-brain okf audit [dir] # cross-check the bundle against the code graph
245
+ project-brain okf audit --symbol <name> # which concepts to re-read after <name> changes
246
+ ```
247
+
248
+ `dir` defaults to `./okf`. Because the bundle is tracked in git, a plain `project-brain sync` also keeps it fresh — bundle files are routed through the curated projection instead of being chunked as raw markdown, so `search_context` returns the reasoning next to the code it explains.
249
+
250
+ A concept anchors code through `resource` (and `sources[]`), resolved from the bundle root:
251
+
252
+ ```yaml
253
+ ---
254
+ type: Gotcha
255
+ title: Language.load ignores Bun's /$bunfs virtual filesystem
256
+ resource: ../src/parser/wasm.ts#loadGrammar # or ../src/parser/wasm.ts#L14-L24
257
+ generated: { by: "human:you", at: 2026-07-30T00:00:00-05:00 }
258
+ ---
259
+ ```
260
+
261
+ `audit` reports four things no single graph can answer:
262
+
263
+ | Finding | Meaning |
264
+ |---|---|
265
+ | **Broken anchor** | The cited file or symbol is gone — the explanation points at nothing. |
266
+ | **Stale concept** | The cited code changed after the knowledge was last confirmed. Uses git commit dates (not mtimes, which every clone resets) against the later of the declared attestation and the concept file's own commit date. |
267
+ | **Coverage gap** | Highest-PageRank symbols no concept explains — a documentation backlog in priority order. Test helpers excluded. |
268
+ | **Link suggestion** | Two concepts whose code calls across them, but whose prose never does. |
269
+
270
+ Broken anchors and stale concepts exit 1, so `audit` works as a CI gate. Coverage gaps and link suggestions are backlog and never fail the run. Clear a stale finding by re-reading the concept and adding a `verified` entry — the file changes, so its commit date moves and the finding clears.
271
+
221
272
  ### `update`
222
273
 
223
274
  Update project-brain to the latest published version, using whichever install manager (bun, pnpm, yarn, or npm) it was originally installed with.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "project-brain",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "type": "module",
5
5
  "description": "Local-first MCP server that gives AI tools semantic memory of your codebase.",
6
6
  "author": "jcsoftdev",
@@ -45,14 +45,15 @@
45
45
  "ollama": "^0.6.3",
46
46
  "unpdf": "^1.4.0",
47
47
  "web-tree-sitter": "^0.25.10",
48
+ "yaml": "^2.9.0",
48
49
  "zod": "^4.4.3"
49
50
  },
50
51
  "optionalDependencies": {
51
- "project-brain-darwin-arm64": "0.15.0",
52
- "project-brain-linux-x64": "0.15.0",
53
- "project-brain-linux-arm64": "0.15.0",
54
- "project-brain-windows-x64": "0.15.0",
55
- "project-brain-windows-arm64": "0.15.0"
52
+ "project-brain-darwin-arm64": "0.16.1",
53
+ "project-brain-linux-x64": "0.16.1",
54
+ "project-brain-linux-arm64": "0.16.1",
55
+ "project-brain-windows-x64": "0.16.1",
56
+ "project-brain-windows-arm64": "0.16.1"
56
57
  },
57
58
  "devDependencies": {
58
59
  "@types/bun": "latest",
@@ -0,0 +1,134 @@
1
+ ---
2
+ name: brain-audit
3
+ description: "Trigger: audit this project, comprehensive audit, full codebase audit, find dead code, unused features, orphan buttons, broken flows, security/performance/architecture audit. Discovers architecture via project-brain, proposes an audit module set, runs only what the user confirms, and reports findings by severity."
4
+ license: Apache-2.0
5
+ metadata:
6
+ author: jcsoftdev
7
+ version: "2.0"
8
+ generator: project-brain
9
+ ---
10
+
11
+ <!--
12
+ `generator: project-brain` is an ownership marker, not decoration.
13
+ `project-brain setup` overwrites this directory only when it finds that line;
14
+ without it, setup treats the directory as hand-written and leaves it alone.
15
+ Strip it and you pin this copy forever — no upgrade will ever reach it.
16
+ -->
17
+
18
+
19
+ ## Activation Contract
20
+
21
+ Apply when asked for a whole-project audit — not a single diff or PR review. Works on any project type: never assume frontend/backend/mobile/CLI before discovery confirms it.
22
+
23
+ Do not apply when: the ask is scoped to one diff, PR, or file; or the project is not project-brain-indexed (`check_health` fails) — fall back to manual discovery and say so explicitly in the output.
24
+
25
+ ## Hard Rules
26
+
27
+ - Discovery first, audit second. No module runs before discovery completes.
28
+ - **No module runs before the user confirms the module set.** Present the proposal, wait, then load references. Never load all modules by default.
29
+ - Route discovery through project-brain, not raw Read/grep sweeps:
30
+
31
+ | Need | Tool |
32
+ |------|------|
33
+ | Stack / module overview | `get_architecture` |
34
+ | Where to start reading | `repo_map` |
35
+ | "How does X work" (no exact name) | `search_context` → `expand_context(chunk_id)` |
36
+ | Exact symbol / file / config | `find_symbol` or `search_code` |
37
+ | Is this symbol dead? | `find_callers` (empty ⇒ no in-repo caller) |
38
+ | What does this depend on? | `find_callees` |
39
+ | Blast radius | `impact` |
40
+ | Does A reach B? | `trace_path` |
41
+ | Results look empty or stale | `check_health`, then `sync_project` |
42
+
43
+ - `find_callers` returning empty means no **in-repo** caller. Before reporting dead code, rule out: public API surface, dynamic dispatch, reflection, string-keyed registries, framework-convention entry points. State which you ruled out.
44
+ - Every finding requires: Title, Category, Severity, Confidence (0-100%), Evidence (`file:line`), Business impact, Technical impact, Recommendation, Priority. Thin evidence ⇒ state the confidence and why. Never invent a finding.
45
+ - Severity vocabulary is exactly: Critical | High | Medium | Low | Info.
46
+
47
+ ## Decision Gates
48
+
49
+ Gates propose; they do not decide. Render each module as `suggested` or `not applicable (reason)`, then ask.
50
+
51
+ The `Reference` column is the exact filename under `references/` — load that file and nothing else.
52
+
53
+ | Gate signal | Module | Reference |
54
+ |---|---|---|
55
+ | Always proposed (no detection needed) | Functional | `functional.md` |
56
+ | | Product | `product.md` |
57
+ | | Goal | `goal.md` |
58
+ | | Future | `future.md` |
59
+ | | Reachability | `reachability.md` |
60
+ | | Flow Integrity | `flow-integrity.md` |
61
+ | | Complexity | `complexity.md` |
62
+ | | Consistency | `consistency.md` |
63
+ | | Documentation | `documentation.md` |
64
+ | | Prompt/Spec Gap | `prompt-spec-gap.md` |
65
+ | Server framework or API routes present | Backend | `backend.md` |
66
+ | | API | `api.md` |
67
+ | UI framework present | Frontend | `frontend.md` |
68
+ | | Accessibility | `accessibility.md` |
69
+ | Native mobile project | Mobile | `mobile.md` |
70
+ | Schema, migrations, or ORM present | Database | `database.md` |
71
+ | LLM / AI SDK calls present | AI | `ai.md` |
72
+ | Hot path or measurable workload | Performance | `performance.md` |
73
+ | Queue, worker, or background jobs | Scalability | `scalability.md` |
74
+ | | Concurrency | `concurrency.md` |
75
+ | Auth, external input, or network boundary | Failure | `failure.md` |
76
+ | | Security | `security.md` |
77
+ | | Abuse | `abuse.md` |
78
+ | PII or user data persisted | Privacy | `privacy.md` |
79
+ | CI/CD, Dockerfile, or IaC present | DevOps | `devops.md` |
80
+ | | Infrastructure | `infrastructure.md` |
81
+ | Logging / metrics / tracing present **or conspicuously absent** | Observability | `observability.md` |
82
+ | Published package manifest or release workflow | Packaging | `packaging.md` |
83
+ | | Versioning & Compatibility | `versioning-compatibility.md` |
84
+ | Lockfile or dependency manifest present | Dependencies & Licensing | `dependencies-licensing.md` |
85
+ | LLM / AI SDK calls, or metered cloud usage | Cost | `cost.md` |
86
+ | Test files present **or conspicuously absent** | Testing | `testing.md` |
87
+ | Locale files or translation keys present | i18n | `i18n.md` |
88
+ | OpenAPI, GraphQL, protobuf, or shared types | Contract Drift | `contract-drift.md` |
89
+
90
+ The absence gates (`Observability`, `Testing`) fire in both directions on purpose: "this project has no tests at all" is a finding, not a reason to skip the module.
91
+
92
+ ### Establishing each signal
93
+
94
+ `get_architecture` covers only the manifest-derived signals. Everything else needs a probe, so run these rather than improvising — an improvised gate is a different answer on every run.
95
+
96
+ | Signal | How to establish it |
97
+ |---|---|
98
+ | Server framework / API routes | `get_architecture` frameworks; else `search_code` the route-registration call |
99
+ | UI framework | `get_architecture` frameworks |
100
+ | Native mobile project | `search_code` for `AndroidManifest.xml`, `Info.plist`, `pubspec.yaml`, `*.xcodeproj` |
101
+ | Schema / migrations / ORM | `search_code` for a migrations directory, `schema.sql`, or an ORM dependency |
102
+ | LLM / AI SDK calls | `search_code` the provider SDK import |
103
+ | Metered cloud usage | cloud SDK imports in the dependency manifest |
104
+ | Queue / worker / background jobs | `search_code` the queue or scheduler dependency, or a worker entry point |
105
+ | Auth, external input, network boundary | any one of: a route table, auth middleware, an outbound HTTP client |
106
+ | CI/CD, Dockerfile, IaC | `search_code` for workflow files, `Dockerfile`, `*.tf`, `*.yaml` in a deploy path |
107
+ | Logging / metrics / tracing | `search_code` the logger or metrics import — **absence fires the gate too** |
108
+ | Test files | `search_code` the test-runner config or `*.test.*` — **absence fires the gate too** |
109
+ | Published package manifest / release workflow | manifest from `get_architecture`, plus a release workflow file |
110
+ | Lockfile / dependency manifest | `get_architecture` packageManager and manifest |
111
+ | PII or user data persisted | schema and model field names — email, phone, address, name, date of birth, government id — plus any free-text column |
112
+ | Locale files / translation keys | `search_code` for a locales directory or the translation function |
113
+ | OpenAPI / GraphQL / protobuf / shared types | `search_code` for `openapi`, `.graphql`, `.proto`, or a shared-types package |
114
+ | Hot path or measurable workload | `repo_map`'s top-ranked symbols, plus any loop over unbounded input |
115
+
116
+ **A signal you cannot establish is `undetermined`, never `not applicable`.** Say which probe was inconclusive and let the user decide. Reporting an unestablished signal as not-applicable silently drops a module they may have needed, and they have no way to know it happened.
117
+
118
+ ## Execution Steps
119
+
120
+ 1. Discovery — stack, architecture, feature map, via the routing table.
121
+ 2. Apply gates → proposed module set with per-module rationale.
122
+ 3. **Present the proposal and wait for confirmation.** Report the token implication of the chosen set.
123
+ 4. For each confirmed module, read only its `references/<module>.md`, then verify against real code — project-brain first, `Read` only to confirm lines it points at.
124
+ 5. Collect findings using the schema above.
125
+
126
+ ## Output Contract
127
+
128
+ In this order: Executive Summary, Project Discovery, Architecture Summary, Feature Map, Modules Run (and why each was skipped), Findings by Severity, Wiring & Reachability Report, Coverage Gaps, Technical Debt, Security Risks, Missing Features, Architectural Risks, Recommendations, Quick Wins, Long-term Improvements.
129
+
130
+ Never invent issues — every finding is backed by repo evidence.
131
+
132
+ ## References
133
+
134
+ One file per module under `references/`. Load only confirmed modules.
@@ -0,0 +1,59 @@
1
+ # Abuse
2
+
3
+ Gate: auth, external input, or a network boundary was detected.
4
+
5
+ `Security` asks whether an attacker can break in. This module asks what a *legitimate* user can do that the system did not intend — no exploit needed, just using the product harder than expected. These findings are usually cheaper to fix and more often hit in practice.
6
+
7
+ ## Resource abuse
8
+
9
+ - [ ] Every endpoint that costs money or time has a rate limit. Absent limits on expensive operations is `High` — cross-reference `cost.md` where the operation bills per call.
10
+ - [ ] Rate limits are keyed on something the user cannot trivially rotate. Per-IP alone is weak; per-account is better.
11
+ - [ ] Request and payload size are bounded before parsing, not after.
12
+ - [ ] Uploads are bounded in size, count, and total per account, and the type is verified from content rather than from the filename.
13
+ - [ ] Anything that fans out — a single request causing N downstream calls — has a bound on N.
14
+ - [ ] Expensive queries reachable by an unauthenticated caller.
15
+
16
+ ## Input as a weapon
17
+
18
+ - [ ] Regexes applied to user input cannot backtrack catastrophically. Nested quantifiers over user-controlled length is a one-request denial of service.
19
+ - [ ] Recursive processing of user input (nested JSON, deeply nested structures, zip, XML) has a depth limit.
20
+ - [ ] Decompression has an output-size limit, not only an input-size limit.
21
+ - [ ] Pagination and limit parameters are clamped. `?limit=1000000` should not be honoured.
22
+ - [ ] Numeric input is range-checked; negative and zero are handled where they change behaviour.
23
+
24
+ ## Enumeration
25
+
26
+ - [ ] Identifiers are not sequential where enumerating them leaks the corpus size or lets a user walk other records.
27
+ - [ ] Existence is not disclosed by differential responses — status code, message, or timing between "not found" and "not permitted".
28
+ - [ ] Bulk lookup endpoints are limited per call and per window.
29
+ - [ ] Public search cannot be used to enumerate private records by narrowing.
30
+
31
+ ## Business-logic abuse
32
+
33
+ - [ ] Operations that grant value are idempotent or bounded — one coupon per account, one trial per user, one vote per poll. Cross-reference `concurrency.md`: the classic double-redeem is a read-modify-write race.
34
+ - [ ] Quotas and counters cannot be reset by the user (re-registering, changing an email, deleting and recreating).
35
+ - [ ] Ordering assumptions cannot be violated — can a user reach step 3 without steps 1 and 2? `trace_path` from each entry point to the privileged step.
36
+ - [ ] Money, credits, and quantities reject negative values everywhere, including refunds and adjustments.
37
+ - [ ] State transitions are validated against the current state, not merely applied.
38
+
39
+ ## Content abuse
40
+
41
+ - [ ] User-generated content is escaped at render, and stored content cannot break out at any consumer — including emails, exports, and logs.
42
+ - [ ] CSV/spreadsheet exports neutralise formula-leading characters.
43
+ - [ ] Filenames from users are sanitised before being used on disk or in a header.
44
+ - [ ] User-supplied URLs fetched by the server are validated against internal addresses.
45
+
46
+ ## Severity guidance
47
+
48
+ | Situation | Severity |
49
+ |---|---|
50
+ | Server fetches a user-supplied URL with no internal-address filter | Critical |
51
+ | No rate limit on an expensive or billed operation | High |
52
+ | Catastrophic backtracking reachable from user input | High |
53
+ | Unbounded request, payload, or decompression size | High |
54
+ | Value-granting operation that can be double-redeemed | High |
55
+ | Quota resettable by the user | Medium |
56
+ | Sequential identifiers enabling enumeration | Medium |
57
+ | Existence disclosed by differential response | Medium |
58
+ | Unclamped pagination limit | Medium |
59
+ | Export not neutralising formula characters | Low |
@@ -0,0 +1,55 @@
1
+ # Accessibility
2
+
3
+ Can everyone use it? Gate: a UI framework was detected. This module was documented in the original audit design but no gate ever enabled it — it could never run. It runs now.
4
+
5
+ Accessibility findings are unusually verifiable from source: most of them are the presence or absence of a specific attribute, and `search_code` finds them exactly.
6
+
7
+ ## Semantics
8
+
9
+ - [ ] Interactive things are interactive elements. `search_code` for `onClick` on `div` and `span` — each is a control keyboard and screen-reader users cannot reach.
10
+ - [ ] Headings form a real outline: one `h1`, no skipped levels, order reflects structure rather than font size.
11
+ - [ ] Landmarks exist — `main`, `nav`, `header`, `footer` — so a screen-reader user can skip to content.
12
+ - [ ] Lists are lists, tables are tables with headers, and neither is a stack of divs.
13
+
14
+ ## Keyboard
15
+
16
+ - [ ] Every action reachable by mouse is reachable by keyboard. Walk the flows from `flow-integrity.md` using Tab and Enter only.
17
+ - [ ] Focus is visible. `search_code` for `outline: none` and `outline: 0` — each needs a replacement indicator.
18
+ - [ ] Focus order follows visual order. Positive `tabindex` values are a red flag; `search_code` for `tabindex="1"` and above.
19
+ - [ ] Modals trap focus while open and restore it to the trigger on close.
20
+ - [ ] Nothing is a keyboard trap — every focusable region can be left with the keyboard.
21
+
22
+ ## Names and roles
23
+
24
+ - [ ] Every image has `alt`, and decorative images have `alt=""` rather than a filename.
25
+ - [ ] Icon-only buttons have an accessible name — `aria-label` or visually-hidden text. These are the single most common miss.
26
+ - [ ] Form inputs have associated `label` elements, not just placeholders. A placeholder disappears on input and is not a label.
27
+ - [ ] Required, invalid, and error states are conveyed programmatically (`aria-required`, `aria-invalid`, `aria-describedby`), not only by colour or position.
28
+ - [ ] `aria-*` attributes are valid for their element's role and are not contradicting native semantics.
29
+
30
+ ## Perception
31
+
32
+ - [ ] Colour is never the only carrier of meaning — error states, status badges, chart series.
33
+ - [ ] Text contrast meets 4.5:1 (3:1 for large text). Extract the colour pairs from the theme and compute; do not eyeball it.
34
+ - [ ] Content reflows at 320px width and at 200% zoom without loss.
35
+ - [ ] Motion respects `prefers-reduced-motion`. `search_code` for it — absence alongside animation is a finding.
36
+
37
+ ## Dynamic content
38
+
39
+ - [ ] Async status changes are announced — live regions for loading, success, and error, matching the triad in `flow-integrity.md`.
40
+ - [ ] Client-side route changes move focus and update the document title.
41
+ - [ ] Auto-dismissing messages last long enough to be read, or are dismissible.
42
+
43
+ ## Severity guidance
44
+
45
+ | Situation | Severity |
46
+ |---|---|
47
+ | Action reachable only by mouse | High |
48
+ | Icon-only control with no accessible name | High |
49
+ | Form input with no label | High |
50
+ | Focus outline removed with no replacement | Medium |
51
+ | Colour as the sole carrier of meaning | Medium |
52
+ | Contrast below 4.5:1 on body text | Medium |
53
+ | Missing `alt` on a meaningful image | Medium |
54
+ | Heading levels skipped | Low |
55
+ | No `prefers-reduced-motion` handling | Low |
@@ -0,0 +1,51 @@
1
+ # AI
2
+
3
+ LLM and AI SDK integration. Gate: calls to an AI/LLM SDK were detected.
4
+
5
+ Two modules pair with this one: `Cost` (the same gate fires it) and `Privacy` (what leaves the process in a prompt). Audit them together or cross-reference explicitly.
6
+
7
+ ## Prompt construction
8
+
9
+ - [ ] Prompts live in one place, not scattered as inline string literals across call sites. `search_code` a distinctive prompt phrase to find the duplicates.
10
+ - [ ] User input is clearly delimited from instructions. Concatenating untrusted text directly into an instruction block is prompt injection — cross-reference `Abuse`.
11
+ - [ ] Input length is bounded before it reaches the model. Unbounded user text is both an injection surface and an unbounded bill.
12
+ - [ ] Prompts are versioned or at least dated. An undated prompt cannot be correlated with a behaviour change.
13
+
14
+ ## Model contract
15
+
16
+ - [ ] The model identifier is configurable, not hardcoded at each call site. `search_code` the model name string — more than one occurrence means a future migration touches N places.
17
+ - [ ] The code states which capabilities it depends on (tool use, structured output, context window). A silent downgrade to a weaker model then fails mysteriously.
18
+ - [ ] Token limits are respected explicitly: input is truncated or chunked with a stated strategy, not left to fail at the API boundary.
19
+ - [ ] Temperature and sampling are set deliberately where determinism matters.
20
+
21
+ ## Output handling
22
+
23
+ - [ ] **Model output is untrusted input.** It is validated against a schema before use, never `eval`'d, never interpolated into a query, a shell command, or a filesystem path. A model-generated path reaching `readFile` is `Critical`.
24
+ - [ ] Structured output is parsed defensively — malformed JSON is an expected case, not an exception.
25
+ - [ ] There is a defined behaviour for a refusal, an empty response, and a truncated response.
26
+ - [ ] Hallucination-sensitive outputs (file paths, symbol names, citations) are verified against reality before being acted on or shown.
27
+
28
+ ## Failure and degradation
29
+
30
+ - [ ] Every model call has a timeout and a bounded retry with backoff.
31
+ - [ ] Rate limits and quota errors are distinguished from real failures and handled differently.
32
+ - [ ] There is a degraded path when the provider is unavailable — a cheaper model, a cached answer, or an honest error. Silent failure is the worst option.
33
+ - [ ] Streaming responses handle mid-stream disconnection without leaving partial state committed.
34
+
35
+ ## Evaluation
36
+
37
+ - [ ] Some check exists that the AI feature still works — golden tests, snapshot comparisons, or a manual procedure that is written down. A prompt with no evaluation regresses invisibly on the next model update.
38
+ - [ ] Non-determinism is handled in tests: either a fake client (assert the request, not the response) or tolerance-based assertions. A test asserting exact model prose is a flake generator.
39
+
40
+ ## Severity guidance
41
+
42
+ | Situation | Severity |
43
+ |---|---|
44
+ | Model output reaching `eval`, a shell, a query, or a path | Critical |
45
+ | User input concatenated into an instruction block unbounded | High |
46
+ | No timeout on a model call | High |
47
+ | No validation of structured output before use | High |
48
+ | No degraded path when the provider is down | Medium |
49
+ | Model identifier hardcoded at multiple call sites | Medium |
50
+ | No evaluation of the AI feature at all | Medium |
51
+ | Prompts duplicated as inline literals | Low |
@@ -0,0 +1,47 @@
1
+ # API
2
+
3
+ The contract as seen from outside. Gate: a server framework or API routes were detected. Distinct from `Backend` — that module audits how the server works, this one audits what it promises.
4
+
5
+ ## Surface inventory
6
+
7
+ - [ ] Enumerate every externally reachable endpoint, tool, or exported entry point. `search_code` the route-registration call, then `find_callers` on each handler.
8
+ - [ ] Each one is documented, or deliberately internal. An undocumented public endpoint is either an accident or a private API someone will depend on anyway.
9
+ - [ ] No endpoint exists that the docs do not mention and no client calls — that belongs to `Reachability`, cross-reference it.
10
+
11
+ ## Contract shape
12
+
13
+ - [ ] Naming and pluralisation are consistent across the surface. `/users/:id` next to `/getAccount` is two conventions.
14
+ - [ ] Status codes are used for their meaning: not 200-with-error-body, not 500 for validation failure.
15
+ - [ ] Error responses share one shape, and it includes something machine-readable — a code, not only prose.
16
+ - [ ] Pagination exists wherever a collection can grow, and it is the same mechanism everywhere.
17
+ - [ ] Field names and types are stable across endpoints. The same concept should not be `userId` here and `user_id` there.
18
+
19
+ ## Input contract
20
+
21
+ - [ ] Every parameter's type, required-ness, and bounds are declared, and the declaration is what actually validates. A schema that documents but does not enforce is worse than none.
22
+ - [ ] Unknown fields are rejected or ignored deliberately, not silently accepted and dropped.
23
+ - [ ] Defaults are documented, and the documented default matches the code.
24
+
25
+ ## Compatibility
26
+
27
+ - [ ] Breaking changes are versioned or gated. Compare the current shape against any published schema, generated client, or `openapi`/`graphql` artefact — that comparison belongs to `Contract Drift` if that gate is on.
28
+ - [ ] Optional fields are genuinely optional in every consumer. `find_callers` on the response type to see who destructures what.
29
+ - [ ] Removed or renamed fields have a deprecation path.
30
+
31
+ ## Discoverability
32
+
33
+ - [ ] A caller can find the full surface without reading the source. If not, that is the finding.
34
+ - [ ] Examples in the docs are executable and current. Test one against the real signature.
35
+ - [ ] Auth requirements are stated per endpoint, not only globally.
36
+
37
+ ## Severity guidance
38
+
39
+ | Situation | Severity |
40
+ |---|---|
41
+ | Declared schema does not actually enforce input | High |
42
+ | Breaking change shipped with no version or gate | High |
43
+ | Undocumented endpoint reachable externally | Medium |
44
+ | Collection endpoint with no pagination | Medium |
45
+ | Inconsistent error shape across the surface | Medium |
46
+ | Naming convention drift | Low |
47
+ | Docs example that no longer matches the signature | Low |
@@ -0,0 +1,48 @@
1
+ # Backend
2
+
3
+ Server-side correctness and structure. Gate: a server framework or API routes were detected.
4
+
5
+ Orient with `repo_map` first — the highest-ranked symbols in a backend are usually the request pipeline. Then `find_callees` on each handler to see what it actually reaches.
6
+
7
+ ## Request lifecycle
8
+
9
+ - [ ] Every handler validates its input before using it. Trace from the route to the first use of a request field.
10
+ - [ ] Auth runs before business logic, not inside it. A handler that checks permissions halfway through has already done work it may not be allowed to do.
11
+ - [ ] One place owns request→response shape. Handlers that each hand-roll their own error envelope will drift.
12
+ - [ ] Long operations do not block the request. If they do, state the observed or estimated duration.
13
+
14
+ ## Layering
15
+
16
+ - [ ] Handlers do not contain business logic, and business logic does not know about HTTP. Check with `find_callees`: a domain function reaching a request/response type is a layering violation.
17
+ - [ ] Data access is isolated from business rules. A service building SQL inline couples two layers that change for different reasons.
18
+ - [ ] No circular dependencies between modules. `trace_path` from a module back to itself.
19
+
20
+ ## Transactions and consistency
21
+
22
+ - [ ] Multi-step writes are transactional, or the partial-failure state is explicitly acceptable and documented.
23
+ - [ ] Nothing writes to two systems (DB + queue, DB + external API) without an outbox, retry, or documented tolerance for divergence.
24
+ - [ ] Read-modify-write sequences are safe against concurrent execution — see the `Concurrency` module if that gate is also on.
25
+
26
+ ## Configuration and secrets
27
+
28
+ - [ ] No secret is hardcoded. `search_code` for likely literals: `secret`, `token`, `password`, `api_key`, `Bearer`.
29
+ - [ ] Every config value has a validated shape and a stated default, or fails loudly at startup rather than at first use.
30
+ - [ ] Environment variables read in code are declared somewhere — cross-check with `Reachability`'s used-but-never-declared sweep.
31
+
32
+ ## Resource handling
33
+
34
+ - [ ] Every acquired resource is released on both the success and the error path — connections, file handles, locks, DB transactions.
35
+ - [ ] Connection pools are bounded and the bound is reachable from config.
36
+ - [ ] Timeouts exist on every outbound call. A missing timeout is a `High` — it converts a slow dependency into a hung server.
37
+
38
+ ## Severity guidance
39
+
40
+ | Situation | Severity |
41
+ |---|---|
42
+ | Unvalidated input reaching a query or filesystem path | Critical |
43
+ | Missing timeout on an outbound call | High |
44
+ | Auth check after side effects | High |
45
+ | Multi-system write with no reconciliation | High |
46
+ | Resource leaked on the error path | Medium |
47
+ | Business logic in a handler | Medium |
48
+ | Inconsistent error envelope across handlers | Low |
@@ -0,0 +1,52 @@
1
+ # Complexity
2
+
3
+ What is harder to change than it needs to be? Complexity is not line count — it is the number of things you must hold in your head to make a correct edit.
4
+
5
+ Use `repo_map` to find the structurally central symbols, then `impact` on each. **A symbol with a large blast radius and high internal complexity is the riskiest code in the project**, and that combination is what this module is for.
6
+
7
+ ## Structural complexity
8
+
9
+ - [ ] Functions doing more than one thing. The tell is the name: `and`, `or`, `handle`, `process`, `manage`, or a name that describes the caller rather than the operation.
10
+ - [ ] Deep nesting. Three levels of conditionals inside a loop is where off-by-one and missed-branch bugs live. Early returns and guard clauses usually collapse it.
11
+ - [ ] Long parameter lists, especially with several of the same type — every call site is a chance to swap two arguments silently.
12
+ - [ ] Boolean parameters that select behaviour. `render(true, false)` at the call site tells the reader nothing.
13
+ - [ ] Functions whose control flow depends on the *caller's* state rather than their arguments.
14
+
15
+ ## Coupling
16
+
17
+ - [ ] `impact` on the central symbols: how much of the codebase must be re-verified to change one of them? A high number is not automatically wrong, but it must be intentional.
18
+ - [ ] Modules that import from many others. `find_callees` at module granularity.
19
+ - [ ] Cyclic dependencies. `trace_path` from a module back to itself — a cycle means neither side can be understood alone.
20
+ - [ ] Shared mutable state as a coupling mechanism. Two modules communicating through a global are coupled without an interface.
21
+ - [ ] Reaching through an object to its internals (`a.b.c.d`) — that chain is four assumptions.
22
+
23
+ ## Duplication that matters
24
+
25
+ - [ ] Duplicated *logic*, not duplicated *shape*. Two functions with the same structure and different meaning should stay separate; two encoding the same rule must not.
26
+ - [ ] The same business rule expressed in more than one place — a validation, a threshold, a format. `search_code` the literal value.
27
+ - [ ] Magic values repeated across files. One named constant, one place to change.
28
+ - [ ] Premature deduplication is its own finding: an abstraction with one caller and three parameters that only exist to serve it.
29
+
30
+ ## Cognitive load
31
+
32
+ - [ ] Names that require reading the implementation to understand. Cross-reference the naming-drift check in `functional.md`.
33
+ - [ ] Implicit ordering requirements — "call `init` before `run`" enforced only by convention. Make it structural or check it.
34
+ - [ ] Non-obvious code with no comment explaining *why*. Comments restating *what* the code does are noise; a missing *why* on a surprising line is a real gap.
35
+ - [ ] Conditionals whose branches are hard to enumerate: nested ternaries, flag combinations, `switch` with fallthrough.
36
+
37
+ ## Dead weight
38
+
39
+ Report these under `Reachability` rather than here, but look for them while reading: unused parameters, options nothing sets, defensive checks for states that cannot occur, and abstraction layers that only forward.
40
+
41
+ ## Severity guidance
42
+
43
+ | Situation | Severity |
44
+ |---|---|
45
+ | High-blast-radius symbol that is also internally complex | High |
46
+ | The same business rule duplicated in more than one place | Medium |
47
+ | Cyclic dependency between modules | Medium |
48
+ | Implicit call-ordering requirement with no enforcement | Medium |
49
+ | Deeply nested control flow on a correctness-critical path | Medium |
50
+ | Boolean parameter selecting behaviour | Low |
51
+ | Surprising line with no explanatory comment | Low |
52
+ | Abstraction with one caller | Low |
@@ -0,0 +1,60 @@
1
+ # Concurrency
2
+
3
+ What happens when two of these run at once? Gate: a queue, worker, or background jobs were detected.
4
+
5
+ Concurrency defects are the ones that pass every test and fail in production, because tests run one thing at a time. Read for the interleaving, not the happy path.
6
+
7
+ ## Shared mutable state
8
+
9
+ - [ ] Identify every piece of state reachable from more than one concurrent path. `find_callers` on each module-level mutable binding — more than one caller on different paths is a candidate.
10
+ - [ ] Module-level `let`, mutable singletons, and caches populated lazily. Lazy initialisation under concurrency initialises twice.
11
+ - [ ] Objects passed by reference to concurrent consumers and mutated by any of them.
12
+
13
+ ## Read-modify-write
14
+
15
+ - [ ] Every read-then-write sequence on shared state. Between the read and the write, another actor can change it. Look for: counters, "check then create", "find or insert", version bumps, balance updates.
16
+ - [ ] The fix must be visible: an atomic operation, a compare-and-swap, a row lock, a unique constraint, or an explicit lock. A comment saying it is safe is not a mechanism.
17
+ - [ ] `check-then-act` on the filesystem — `existsSync` then `writeFile` is a race. Prefer atomic create or accept-and-handle-the-error.
18
+
19
+ ## Ordering
20
+
21
+ - [ ] Nothing depends on the completion order of concurrent operations unless it is enforced.
22
+ - [ ] `Promise.all` over operations with hidden interdependencies — they will interleave.
23
+ - [ ] Fire-and-forget calls whose effects a later step assumes. `search_code` for unawaited async calls.
24
+ - [ ] Event handlers that can be re-entered before the previous invocation finishes.
25
+
26
+ ## Locks and resources
27
+
28
+ - [ ] Locks are always released, including on the error path. A lock held through a throw is a permanent deadlock.
29
+ - [ ] Lock acquisition order is consistent everywhere; two paths taking A-then-B and B-then-A deadlock.
30
+ - [ ] Locks have a timeout or a lease, so a dead holder does not block forever.
31
+ - [ ] Nothing does I/O while holding a lock longer than necessary.
32
+
33
+ ## Cancellation
34
+
35
+ - [ ] Long operations are cancellable, and cancellation actually stops work rather than only ignoring the result.
36
+ - [ ] Cancelled operations clean up — release resources, roll back partial state.
37
+ - [ ] A late result from a cancelled or superseded operation cannot overwrite a newer one. This is the same defect as the unmounted-component write in `frontend.md`.
38
+
39
+ ## Signals and shutdown
40
+
41
+ - [ ] In-flight work completes or is safely abandoned on shutdown; nothing is left half-written.
42
+ - [ ] Shutdown is bounded — a hang on drain is worse than a forced exit.
43
+ - [ ] Persistent handles (database, WAL, file locks) are closed on every exit path.
44
+
45
+ ## Reporting
46
+
47
+ State each finding as an interleaving: "if A reaches line X while B is between lines Y and Z, then …". A concurrency finding without a concrete interleaving is unfalsifiable, and reviewers correctly dismiss it.
48
+
49
+ ## Severity guidance
50
+
51
+ | Situation | Severity |
52
+ |---|---|
53
+ | Read-modify-write on shared state with no atomicity | High |
54
+ | Lock not released on the error path | High |
55
+ | Inconsistent lock ordering across paths | High |
56
+ | Late result overwriting a newer one | Medium |
57
+ | Lazy initialisation racing to initialise twice | Medium |
58
+ | Unawaited async call whose effect is later assumed | Medium |
59
+ | Non-cancellable long operation | Medium |
60
+ | Unbounded shutdown drain | Low |