project-brain 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +100 -6
  2. package/package.json +7 -6
  3. package/templates/project.claude.md +1 -1
  4. package/templates/skills/brain-audit/SKILL.md +134 -0
  5. package/templates/skills/brain-audit/references/abuse.md +59 -0
  6. package/templates/skills/brain-audit/references/accessibility.md +55 -0
  7. package/templates/skills/brain-audit/references/ai.md +51 -0
  8. package/templates/skills/brain-audit/references/api.md +47 -0
  9. package/templates/skills/brain-audit/references/backend.md +48 -0
  10. package/templates/skills/brain-audit/references/complexity.md +52 -0
  11. package/templates/skills/brain-audit/references/concurrency.md +60 -0
  12. package/templates/skills/brain-audit/references/consistency.md +59 -0
  13. package/templates/skills/brain-audit/references/contract-drift.md +58 -0
  14. package/templates/skills/brain-audit/references/cost.md +60 -0
  15. package/templates/skills/brain-audit/references/database.md +59 -0
  16. package/templates/skills/brain-audit/references/dependencies-licensing.md +59 -0
  17. package/templates/skills/brain-audit/references/devops.md +61 -0
  18. package/templates/skills/brain-audit/references/documentation.md +56 -0
  19. package/templates/skills/brain-audit/references/failure.md +58 -0
  20. package/templates/skills/brain-audit/references/flow-integrity.md +61 -0
  21. package/templates/skills/brain-audit/references/frontend.md +51 -0
  22. package/templates/skills/brain-audit/references/functional.md +39 -0
  23. package/templates/skills/brain-audit/references/future.md +31 -0
  24. package/templates/skills/brain-audit/references/goal.md +38 -0
  25. package/templates/skills/brain-audit/references/i18n.md +61 -0
  26. package/templates/skills/brain-audit/references/infrastructure.md +62 -0
  27. package/templates/skills/brain-audit/references/mobile.md +58 -0
  28. package/templates/skills/brain-audit/references/observability.md +55 -0
  29. package/templates/skills/brain-audit/references/packaging.md +52 -0
  30. package/templates/skills/brain-audit/references/performance.md +58 -0
  31. package/templates/skills/brain-audit/references/privacy.md +63 -0
  32. package/templates/skills/brain-audit/references/product.md +34 -0
  33. package/templates/skills/brain-audit/references/prompt-spec-gap.md +41 -0
  34. package/templates/skills/brain-audit/references/reachability.md +58 -0
  35. package/templates/skills/brain-audit/references/scalability.md +55 -0
  36. package/templates/skills/brain-audit/references/security.md +75 -0
  37. package/templates/skills/brain-audit/references/testing.md +58 -0
  38. package/templates/skills/brain-audit/references/versioning-compatibility.md +59 -0
  39. package/templates/skills/brain-okf/SKILL.md +157 -0
package/README.md CHANGED
@@ -7,17 +7,25 @@ project-brain indexes your project files into a local LanceDB vector store using
7
7
  ## Quick Start
8
8
 
9
9
  ```bash
10
- # 1. Install globally
11
- bun install -g project-brain
10
+ # 1. Install globally — pick one
11
+ curl -fsSL https://raw.githubusercontent.com/jcsoftdev/project-brain/main/scripts/install.sh | sh
12
+ bun install -g project-brain # or npm / pnpm / yarn
13
+ brew install jcsoftdev/tap/project-brain
12
14
 
13
15
  # 2. One-time: register in your AI tools (Claude, Codex, Cursor, Gemini, Windsurf, Zed, VS Code)
16
+ # Also installs the brain-audit and brain-okf host skills. --no-skills to opt out.
14
17
  project-brain setup
15
18
 
16
19
  # 3. Per-project: initialize, index, and install git hook
17
20
  cd my-project
18
21
  project-brain init
22
+
23
+ # 4. Optional, per-project: start a knowledge bundle for the *why*
24
+ project-brain okf init
19
25
  ```
20
26
 
27
+ The `curl` line needs no package manager at all — the binary ships self-contained. See [Install](#install) for every channel and the platforms each covers.
28
+
21
29
  After `init`, the following run **automatically** without any extra steps:
22
30
 
23
31
  | Trigger | What happens |
@@ -28,7 +36,7 @@ After `init`, the following run **automatically** without any extra steps:
28
36
 
29
37
  ## Prerequisites
30
38
 
31
- - **Nothing extra to run it.** The registry install ships a self-contained, prebuilt binary per platform (the runtime is bundled in) — you do **not** need Bun or Node installed to use project-brain.
39
+ - **Nothing extra to run it.** Every channel ships the same self-contained, prebuilt binary per platform, with the runtime, WASM grammars and templates bundled in — you do **not** need Bun or Node installed to use project-brain. The `curl` installer does not even need one to *install* it.
32
40
  - **Bun** ≥ 1.3.14 — only needed to build/run **from source** ([install](https://bun.sh)).
33
41
  - **Ollama** (optional, only for semantic search) — download from [ollama.com](https://ollama.com). `project-brain init` **auto-pulls** the default embedding model `qwen3-embedding:0.6b` (1024-dim, fast, code-capable). To pre-pull it: `ollama pull qwen3-embedding:0.6b`. If it can't be pulled, project-brain falls back to `nomic-embed-text`. The structural tools work with **no** Ollama at all.
34
42
 
@@ -42,15 +50,44 @@ bun install -g project-brain
42
50
  npm install -g project-brain
43
51
  ```
44
52
 
45
- ### Standalone binary (no runtime required)
53
+ ### No package manager
54
+
55
+ The published binary is a `bun build --compile` artifact with the runtime, WASM grammars and templates embedded, so it needs no Node, no Bun, and nothing else at runtime.
56
+
57
+ ```bash
58
+ curl -fsSL https://raw.githubusercontent.com/jcsoftdev/project-brain/main/scripts/install.sh | sh
59
+ ```
60
+
61
+ Installs to `~/.local/bin` (override with `BRAIN_INSTALL_DIR`). Pin a version with `BRAIN_VERSION=v0.16.0`. To update, re-run it.
62
+
63
+ Apple Silicon, Linux x64 and Linux arm64 have published binaries. **Intel macOS does not** — the script says so instead of handing you an arm64 binary; use a registry install there.
64
+
65
+ ### Homebrew / Scoop
66
+
67
+ Each release attaches a generated `project-brain.rb` and `project-brain.json`, checksummed against the real assets. Once a tap and bucket exist:
68
+
69
+ ```bash
70
+ brew install jcsoftdev/tap/project-brain # macOS (Apple Silicon), Linux
71
+ scoop install project-brain # Windows
72
+ ```
73
+
74
+ Whichever channel you use, `project-brain update` reads the binary's own path to work out how it was installed and prints the right command — `brew upgrade`, `scoop update`, or the package manager's. For a channel it cannot drive it says so rather than guessing, because a guessed `npm install -g` would leave a second copy shadowing the first.
75
+
76
+ ### Build it yourself
46
77
 
47
78
  ```bash
48
79
  git clone https://github.com/jcsoftdev/project-brain
49
80
  cd project-brain
50
- bun build ./src/cli.ts --compile --outfile project-brain
81
+ bun build ./src/cli.ts ./src/parser/worker.ts --compile --outfile project-brain
51
82
  ./project-brain --help
52
83
  ```
53
84
 
85
+ `worker.ts` is a required second entrypoint — without it the parser's worker pool cannot resolve its own imports inside the compiled binary and silently extracts zero symbols.
86
+
87
+ ### Keeping the host skills current
88
+
89
+ Skills live in your assistant's global skills directory, not in the package, so upgrading the binary does not move them. project-brain compares the installed skill content against what the running binary carries and refreshes any directory it originally created — whichever way you upgraded. It never creates one (that is `setup`'s job) and never touches a directory it cannot prove it wrote. Opt out with `BRAIN_NO_SKILL_REFRESH=1`.
90
+
54
91
  ## Usage modes
55
92
 
56
93
  project-brain runs in two modes — CLI and inside AI tools. Both call the same underlying commands.
@@ -71,7 +108,22 @@ Once `project-brain setup` has registered the MCP server in your AI tool, you ca
71
108
  | `/brain-reindex` | `project-brain reindex` | Drop and rebuild full index |
72
109
  | `/brain-health` | `project-brain health` | Diagnose Ollama, index staleness, git hook |
73
110
 
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.
111
+ 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.
112
+
113
+ ### Host skills setup installs
114
+
115
+ | Skill | Equivalent CLI | What it does |
116
+ |---|---|---|
117
+ | `/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 |
118
+ | `/brain-okf` | *(none — host skill)* | Write an OKF concept: the reasoning behind code, anchored to a verified symbol and checkable by `okf audit` |
119
+
120
+ Unlike the `/brain-*` commands above, these have no CLI equivalent. They are **host skills**: the 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 `brain-audit` answer "is this export dead?" with `find_callers` instead of guessing from a grep, and what lets `brain-okf` verify an anchor with `find_symbol` before writing it.
121
+
122
+ `project-brain setup` installs them into each registered tool's global skills directory (`~/.claude/skills/`, `~/.codex/skills/`, or the shared `~/.agents/skills/`). Opt out with `project-brain setup --no-skills` (`--no-brain-audit` still works as an alias).
123
+
124
+ **Both are offered, not scheduled.** Nothing invokes them for you and nothing fires on commit — you decide when. `brain-audit` runs discovery, proposes an audit module set, 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. `brain-okf` proposes the type, title, and anchor and waits before creating a file, because whether an insight deserves a permanent home is your call, not the assistant's.
125
+
126
+ Setup never overwrites a skill directory it did not create. Ownership is proven per directory, so your own hand-written `brain-okf/` is left untouched — and reported — while `brain-audit/` upgrades beside it.
75
127
 
76
128
  ## MCP Tools
77
129
 
@@ -120,6 +172,8 @@ The CLI commands exit 0 for any executed query — including legitimate empty re
120
172
  | `get_architecture` | One-call project summary: detected tech stack, indexed modules, chunk count, and symbol count. |
121
173
  | `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
174
 
175
+ 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).
176
+
123
177
  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
178
 
125
179
  ## Recipes — get the most out of it
@@ -218,6 +272,46 @@ project-brain map --budget 2000 --focus createServer,runSync
218
272
  project-brain code "chargeCard" --limit 5
219
273
  ```
220
274
 
275
+ ### `okf` — knowledge bundles (the *why*, not the *what*)
276
+
277
+ 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.
278
+
279
+ ```bash
280
+ project-brain okf init [dir] # scaffold an empty bundle. Never overwrites.
281
+ project-brain okf validate [dir] # conformance (SPEC §11). Offline.
282
+ project-brain okf sync [dir] # index the concepts so search returns them
283
+ project-brain okf audit [dir] # cross-check the bundle against the code graph
284
+ project-brain okf audit --symbol <name> # which concepts to re-read after <name> changes
285
+ ```
286
+
287
+ `init` writes `index.md` and `log.md` and stops — **no seeded concepts**, because a bundle shipped with examples makes the first `audit` report coverage gaps across the whole repo. Type directories appear when the first concept needs them.
288
+
289
+ It also re-renders `CLAUDE.md`. `project-brain init` runs before any bundle exists, so the knowledge-bundle section is omitted then; `okf init` adds it once there is something to point at. That section asks the assistant to **decide, at the end of a task, whether anything belongs in the bundle** — and says plainly that most tasks produce nothing. A checkpoint that feels obliged to produce a file is a concept mill, and noise in a knowledge bundle is worse than gaps. Projects with no bundle never see the instruction.
290
+
291
+ `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.
292
+
293
+ A concept anchors code through `resource` (and `sources[]`), resolved from the bundle root:
294
+
295
+ ```yaml
296
+ ---
297
+ type: Gotcha
298
+ title: Language.load ignores Bun's /$bunfs virtual filesystem
299
+ resource: ../src/parser/wasm.ts#loadGrammar # or ../src/parser/wasm.ts#L14-L24
300
+ generated: { by: "human:you", at: 2026-07-30T00:00:00-05:00 }
301
+ ---
302
+ ```
303
+
304
+ `audit` reports four things no single graph can answer:
305
+
306
+ | Finding | Meaning |
307
+ |---|---|
308
+ | **Broken anchor** | The cited file or symbol is gone — the explanation points at nothing. |
309
+ | **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. |
310
+ | **Coverage gap** | Highest-PageRank symbols no concept explains — a documentation backlog in priority order. Test helpers excluded. |
311
+ | **Link suggestion** | Two concepts whose code calls across them, but whose prose never does. |
312
+
313
+ 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.
314
+
221
315
  ### `update`
222
316
 
223
317
  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.17.0",
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.17.0",
53
+ "project-brain-linux-x64": "0.17.0",
54
+ "project-brain-linux-arm64": "0.17.0",
55
+ "project-brain-windows-x64": "0.17.0",
56
+ "project-brain-windows-arm64": "0.17.0"
56
57
  },
57
58
  "devDependencies": {
58
59
  "@types/bun": "latest",
@@ -14,4 +14,4 @@ When answering questions about this codebase, run `search_context` first to find
14
14
 
15
15
  - **Project ID**: {{projectId}}
16
16
  - **Stack**: {{stack}}
17
- {{modules}}
17
+ {{modules}}{{okf}}
@@ -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 |