claude-brain 0.5.1 → 0.9.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 (43) hide show
  1. package/VERSION +1 -1
  2. package/assets/CLAUDE-unified.md +11 -0
  3. package/package.json +5 -1
  4. package/packs/backend/node.json +173 -0
  5. package/packs/core/javascript.json +176 -0
  6. package/packs/core/typescript.json +222 -0
  7. package/packs/frontend/react.json +254 -0
  8. package/packs/meta/testing.json +172 -0
  9. package/src/cli/bin.ts +14 -0
  10. package/src/cli/commands/hooks.ts +214 -0
  11. package/src/cli/commands/pack.ts +197 -0
  12. package/src/cli/commands/serve.ts +34 -0
  13. package/src/config/defaults.ts +1 -1
  14. package/src/config/schema.ts +85 -2
  15. package/src/hooks/brain-hook.ts +110 -0
  16. package/src/hooks/capture.ts +161 -0
  17. package/src/hooks/deduplicator.ts +72 -0
  18. package/src/hooks/index.ts +19 -0
  19. package/src/hooks/installer.ts +181 -0
  20. package/src/hooks/passive-classifier.ts +366 -0
  21. package/src/hooks/queue.ts +122 -0
  22. package/src/hooks/session-tracker.ts +199 -0
  23. package/src/hooks/types.ts +47 -0
  24. package/src/memory/chroma/store.ts +2 -1
  25. package/src/memory/index.ts +1 -0
  26. package/src/memory/store.ts +1 -0
  27. package/src/packs/index.ts +9 -0
  28. package/src/packs/loader.ts +134 -0
  29. package/src/packs/manager.ts +204 -0
  30. package/src/packs/ranker.ts +78 -0
  31. package/src/packs/types.ts +81 -0
  32. package/src/routing/entity-extractor.ts +410 -0
  33. package/src/routing/intent-classifier.ts +229 -0
  34. package/src/routing/response-filter.ts +221 -0
  35. package/src/routing/router.ts +671 -0
  36. package/src/server/handlers/call-tool.ts +7 -0
  37. package/src/server/handlers/list-tools.ts +22 -5
  38. package/src/server/handlers/tools/brain.ts +85 -0
  39. package/src/server/handlers/tools/init-project.ts +47 -0
  40. package/src/server/handlers/tools/schemas.ts +12 -0
  41. package/src/server/http-api.ts +188 -0
  42. package/src/tools/registry.ts +9 -0
  43. package/src/tools/schemas.ts +33 -1
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.5.1
1
+ 0.9.0
@@ -0,0 +1,11 @@
1
+ # Claude Brain
2
+
3
+ Call `brain()` with what you are doing. The server handles the rest.
4
+
5
+ Examples:
6
+ - brain("starting work on the auth system")
7
+ - brain("decided to use JWT because sessions don't scale")
8
+ - brain("finished the login page, next is the dashboard")
9
+ - brain("what auth patterns have we used?")
10
+ - brain("the bug was a race condition, fixed by adding a mutex")
11
+ - brain("React vs Vue for the new project?")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-brain",
3
- "version": "0.5.1",
3
+ "version": "0.9.0",
4
4
  "description": "Local development assistant bridging Obsidian vaults with Claude Code via MCP",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -9,6 +9,7 @@
9
9
  },
10
10
  "files": [
11
11
  "src/**/*.ts",
12
+ "packs/",
12
13
  "assets/",
13
14
  "package.json",
14
15
  "tsconfig.json",
@@ -44,6 +45,9 @@
44
45
  ],
45
46
  "author": "",
46
47
  "license": "MIT",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
47
51
  "devDependencies": {
48
52
  "@types/bun": "latest",
49
53
  "@types/node": "^20",
@@ -0,0 +1,173 @@
1
+ {
2
+ "id": "backend/node",
3
+ "name": "Node.js Backend Patterns",
4
+ "version": "1.0.0",
5
+ "stack": ["node", "express", "fastify", "hono", "nestjs", "elysia", "bun"],
6
+ "description": "Error handling, streams, worker threads, security, graceful shutdown, and server patterns",
7
+ "author": "claude-brain",
8
+ "entries": [
9
+ {
10
+ "type": "best-practice",
11
+ "category": "Error Handling",
12
+ "title": "Centralize error handling middleware",
13
+ "content": "Use a centralized error handling middleware/handler instead of try/catch in every route. Map error types to HTTP status codes. Log the full error server-side but return safe messages to clients.",
14
+ "confidence": 0.95,
15
+ "tags": ["node", "error-handling", "middleware"]
16
+ },
17
+ {
18
+ "type": "common-issue",
19
+ "category": "Error Handling",
20
+ "title": "Handle unhandled rejections and exceptions",
21
+ "content": "Always register handlers for 'uncaughtException' and 'unhandledRejection' process events. Log the error and perform graceful shutdown. These are last-resort safety nets.",
22
+ "confidence": 0.95,
23
+ "tags": ["node", "error-handling", "process"],
24
+ "example": "process.on('unhandledRejection', (reason) => { logger.fatal({ reason }, 'Unhandled rejection'); shutdown(); })"
25
+ },
26
+ {
27
+ "type": "pattern",
28
+ "category": "Graceful Shutdown",
29
+ "title": "Implement graceful shutdown",
30
+ "content": "Handle SIGTERM and SIGINT signals to gracefully shut down. Stop accepting new connections, finish in-flight requests, close database connections, then exit. This prevents data corruption during deployments.",
31
+ "confidence": 0.95,
32
+ "tags": ["node", "shutdown", "deployment"],
33
+ "example": "process.on('SIGTERM', async () => { await server.close(); await db.close(); process.exit(0); })"
34
+ },
35
+ {
36
+ "type": "best-practice",
37
+ "category": "Security",
38
+ "title": "Validate all input at system boundaries",
39
+ "content": "Validate and sanitize all external input (request body, query params, headers) at the API boundary using a schema validation library (Zod, Joi, AJV). Never trust client data.",
40
+ "confidence": 0.95,
41
+ "tags": ["node", "security", "validation"]
42
+ },
43
+ {
44
+ "type": "anti-pattern",
45
+ "category": "Security",
46
+ "title": "Never expose internal errors to clients",
47
+ "content": "Don't send stack traces, database errors, or internal paths to API clients. Map all errors to safe, generic messages with appropriate HTTP status codes. Log the full error server-side only.",
48
+ "confidence": 0.95,
49
+ "tags": ["node", "security", "error-handling"]
50
+ },
51
+ {
52
+ "type": "best-practice",
53
+ "category": "Security",
54
+ "title": "Use parameterized queries for databases",
55
+ "content": "Always use parameterized queries or an ORM for database operations. Never concatenate user input into SQL strings. This prevents SQL injection, the most critical web vulnerability.",
56
+ "confidence": 0.95,
57
+ "tags": ["node", "security", "sql-injection", "database"]
58
+ },
59
+ {
60
+ "type": "pattern",
61
+ "category": "Architecture",
62
+ "title": "Separate route handlers from business logic",
63
+ "content": "Keep route handlers thin — they should parse input, call service functions, and format responses. Business logic belongs in service modules that are independently testable and reusable.",
64
+ "confidence": 0.9,
65
+ "tags": ["node", "architecture", "separation-of-concerns"]
66
+ },
67
+ {
68
+ "type": "best-practice",
69
+ "category": "Logging",
70
+ "title": "Use structured logging with levels",
71
+ "content": "Use a structured logger (pino, winston) that outputs JSON. Include request IDs, timestamps, and context. Use log levels (debug, info, warn, error, fatal) consistently.",
72
+ "confidence": 0.9,
73
+ "tags": ["node", "logging", "observability"]
74
+ },
75
+ {
76
+ "type": "common-issue",
77
+ "category": "Performance",
78
+ "title": "Don't block the event loop",
79
+ "content": "Avoid synchronous operations (readFileSync, crypto, JSON.parse on large data) in request handlers. Use async alternatives, worker threads, or break work into chunks with setImmediate.",
80
+ "confidence": 0.95,
81
+ "tags": ["node", "performance", "event-loop"]
82
+ },
83
+ {
84
+ "type": "pattern",
85
+ "category": "Streams",
86
+ "title": "Use streams for large data processing",
87
+ "content": "Process large files, HTTP bodies, and datasets with streams instead of loading everything into memory. Pipe readable to writable streams. Use pipeline() for proper error handling.",
88
+ "confidence": 0.9,
89
+ "tags": ["node", "streams", "performance"],
90
+ "example": "import { pipeline } from 'stream/promises';\nawait pipeline(readStream, transform, writeStream);"
91
+ },
92
+ {
93
+ "type": "best-practice",
94
+ "category": "Configuration",
95
+ "title": "Use environment variables for configuration",
96
+ "content": "Load configuration from environment variables, not hardcoded values. Use a library (dotenv, env-schema) to validate env vars at startup. Fail fast if required configuration is missing.",
97
+ "confidence": 0.9,
98
+ "tags": ["node", "configuration", "environment"]
99
+ },
100
+ {
101
+ "type": "anti-pattern",
102
+ "category": "Security",
103
+ "title": "Never store secrets in code or git",
104
+ "content": "Don't commit API keys, database passwords, or tokens to version control. Use environment variables, secret management services (Vault, AWS Secrets Manager), or .env files in .gitignore.",
105
+ "confidence": 0.95,
106
+ "tags": ["node", "security", "secrets"]
107
+ },
108
+ {
109
+ "type": "best-practice",
110
+ "category": "API Design",
111
+ "title": "Use proper HTTP status codes",
112
+ "content": "Return semantically correct HTTP status codes: 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 409 (Conflict), 500 (Server Error).",
113
+ "confidence": 0.9,
114
+ "tags": ["node", "api", "http", "rest"]
115
+ },
116
+ {
117
+ "type": "pattern",
118
+ "category": "Middleware",
119
+ "title": "Use middleware for cross-cutting concerns",
120
+ "content": "Implement authentication, rate limiting, request logging, CORS, and compression as middleware. This keeps route handlers focused on business logic and makes concerns reusable.",
121
+ "confidence": 0.9,
122
+ "tags": ["node", "middleware", "architecture"]
123
+ },
124
+ {
125
+ "type": "common-issue",
126
+ "category": "Performance",
127
+ "title": "Implement connection pooling for databases",
128
+ "content": "Always use connection pooling for database connections. Creating a new connection per request is slow and exhausts database limits. Most ORMs and drivers support pooling out of the box.",
129
+ "confidence": 0.9,
130
+ "tags": ["node", "database", "performance", "connection-pooling"]
131
+ },
132
+ {
133
+ "type": "best-practice",
134
+ "category": "Security",
135
+ "title": "Set appropriate security headers",
136
+ "content": "Use helmet or set security headers manually: Content-Security-Policy, X-Content-Type-Options, Strict-Transport-Security, X-Frame-Options. These prevent common web attacks.",
137
+ "confidence": 0.9,
138
+ "tags": ["node", "security", "headers"]
139
+ },
140
+ {
141
+ "type": "pattern",
142
+ "category": "Testing",
143
+ "title": "Use dependency injection for testability",
144
+ "content": "Pass dependencies (database, logger, external services) as constructor/function parameters instead of importing singletons. This enables easy mocking in tests and flexible composition.",
145
+ "confidence": 0.85,
146
+ "tags": ["node", "testing", "dependency-injection"]
147
+ },
148
+ {
149
+ "type": "anti-pattern",
150
+ "category": "Error Handling",
151
+ "title": "Avoid empty catch blocks",
152
+ "content": "Never swallow errors silently with empty catch blocks. At minimum, log the error. Silently ignoring errors makes debugging impossible and can mask serious issues.",
153
+ "confidence": 0.95,
154
+ "tags": ["node", "error-handling"]
155
+ },
156
+ {
157
+ "type": "best-practice",
158
+ "category": "API Design",
159
+ "title": "Implement request rate limiting",
160
+ "content": "Add rate limiting to protect against abuse and DDoS. Use token bucket or sliding window algorithms. Apply stricter limits to authentication endpoints. Return 429 Too Many Requests.",
161
+ "confidence": 0.9,
162
+ "tags": ["node", "security", "rate-limiting", "api"]
163
+ },
164
+ {
165
+ "type": "common-issue",
166
+ "category": "Memory",
167
+ "title": "Watch for memory leaks in long-running processes",
168
+ "content": "Node.js servers can leak memory through event listeners, caches without size limits, closures holding references, and global arrays. Monitor heap usage and use WeakMap/WeakRef where appropriate.",
169
+ "confidence": 0.85,
170
+ "tags": ["node", "memory", "performance", "debugging"]
171
+ }
172
+ ]
173
+ }
@@ -0,0 +1,176 @@
1
+ {
2
+ "id": "core/javascript",
3
+ "name": "JavaScript Fundamentals",
4
+ "version": "1.0.0",
5
+ "stack": ["javascript"],
6
+ "description": "Closures, event loop, async patterns, modern ES features, and coercion pitfalls",
7
+ "author": "claude-brain",
8
+ "entries": [
9
+ {
10
+ "type": "best-practice",
11
+ "category": "Async Patterns",
12
+ "title": "Use async/await over raw promises",
13
+ "content": "Prefer async/await over .then() chains for readability and debuggability. Async/await produces clearer stack traces and is easier to reason about for error handling with try/catch.",
14
+ "confidence": 0.95,
15
+ "tags": ["javascript", "async", "promises"]
16
+ },
17
+ {
18
+ "type": "common-issue",
19
+ "category": "Async Patterns",
20
+ "title": "Avoid unhandled promise rejections",
21
+ "content": "Always handle promise rejections with try/catch in async functions or .catch() on promises. Unhandled rejections can crash Node.js processes and cause silent failures in browsers.",
22
+ "confidence": 0.95,
23
+ "tags": ["javascript", "async", "error-handling"]
24
+ },
25
+ {
26
+ "type": "anti-pattern",
27
+ "category": "Async Patterns",
28
+ "title": "Avoid sequential awaits for independent operations",
29
+ "content": "Don't await independent async operations sequentially. Use Promise.all() or Promise.allSettled() to run them concurrently. Sequential awaits waste time waiting for operations that could run in parallel.",
30
+ "confidence": 0.9,
31
+ "tags": ["javascript", "async", "performance"],
32
+ "example": "const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()])"
33
+ },
34
+ {
35
+ "type": "best-practice",
36
+ "category": "Modern ES",
37
+ "title": "Use destructuring for cleaner code",
38
+ "content": "Use destructuring assignment for objects and arrays to extract values concisely. This reduces intermediate variables and makes function parameter expectations clearer.",
39
+ "confidence": 0.9,
40
+ "tags": ["javascript", "es6", "destructuring"],
41
+ "example": "const { name, age } = user; const [first, ...rest] = items;"
42
+ },
43
+ {
44
+ "type": "best-practice",
45
+ "category": "Modern ES",
46
+ "title": "Prefer const, use let sparingly, avoid var",
47
+ "content": "Use `const` by default for all bindings. Only use `let` when reassignment is necessary. Never use `var` — it has function scoping and hoisting that causes bugs.",
48
+ "confidence": 0.95,
49
+ "tags": ["javascript", "variables", "scoping"]
50
+ },
51
+ {
52
+ "type": "common-issue",
53
+ "category": "Closures",
54
+ "title": "Understand closure variable capture",
55
+ "content": "Closures capture variables by reference, not by value. In loops, use `let` (block-scoped) instead of `var` to ensure each iteration gets its own copy. Arrow functions in loops with `var` all share the same variable.",
56
+ "confidence": 0.9,
57
+ "tags": ["javascript", "closures", "scoping"]
58
+ },
59
+ {
60
+ "type": "common-issue",
61
+ "category": "Event Loop",
62
+ "title": "Understand microtask vs macrotask ordering",
63
+ "content": "Promise callbacks (microtasks) run before setTimeout/setInterval callbacks (macrotasks). This matters for operation ordering. process.nextTick runs before all other microtasks in Node.js.",
64
+ "confidence": 0.85,
65
+ "tags": ["javascript", "event-loop", "async"]
66
+ },
67
+ {
68
+ "type": "anti-pattern",
69
+ "category": "Coercion",
70
+ "title": "Avoid loose equality (==)",
71
+ "content": "Always use strict equality (===) to avoid JavaScript's type coercion rules. Loose equality has unintuitive results like `'' == 0` being true and `null == undefined` being true.",
72
+ "confidence": 0.95,
73
+ "tags": ["javascript", "equality", "coercion"]
74
+ },
75
+ {
76
+ "type": "best-practice",
77
+ "category": "Modern ES",
78
+ "title": "Use optional chaining and nullish coalescing",
79
+ "content": "Use `?.` for safe property access on potentially null/undefined values. Use `??` for default values (only triggers on null/undefined, unlike `||` which triggers on falsy values).",
80
+ "confidence": 0.9,
81
+ "tags": ["javascript", "null-safety", "es2020"],
82
+ "example": "const name = user?.profile?.name ?? 'Anonymous'"
83
+ },
84
+ {
85
+ "type": "pattern",
86
+ "category": "Error Handling",
87
+ "title": "Create custom error classes for domain errors",
88
+ "content": "Extend the Error class for domain-specific errors. Include error codes, HTTP status codes, or other structured data to enable programmatic error handling.",
89
+ "confidence": 0.85,
90
+ "tags": ["javascript", "error-handling"],
91
+ "example": "class NotFoundError extends Error { constructor(resource) { super(`${resource} not found`); this.name = 'NotFoundError'; this.status = 404; } }"
92
+ },
93
+ {
94
+ "type": "best-practice",
95
+ "category": "Modern ES",
96
+ "title": "Use spread operator for immutable updates",
97
+ "content": "Use the spread operator to create shallow copies when updating objects or arrays. This supports immutable patterns without external libraries.",
98
+ "confidence": 0.9,
99
+ "tags": ["javascript", "immutability", "spread"],
100
+ "example": "const updated = { ...user, name: 'New Name' }"
101
+ },
102
+ {
103
+ "type": "common-issue",
104
+ "category": "Modern ES",
105
+ "title": "Understand shallow vs deep copy",
106
+ "content": "Spread and Object.assign only create shallow copies. Nested objects are still references. Use structuredClone() for deep copies, or libraries like immer for complex immutable updates.",
107
+ "confidence": 0.9,
108
+ "tags": ["javascript", "immutability", "deep-copy"]
109
+ },
110
+ {
111
+ "type": "anti-pattern",
112
+ "category": "Functions",
113
+ "title": "Avoid modifying function arguments",
114
+ "content": "Don't mutate objects or arrays passed as function arguments. This causes action-at-a-distance bugs. Return new values instead of modifying inputs.",
115
+ "confidence": 0.85,
116
+ "tags": ["javascript", "functions", "immutability"]
117
+ },
118
+ {
119
+ "type": "best-practice",
120
+ "category": "Modules",
121
+ "title": "Use ES modules (import/export)",
122
+ "content": "Prefer ES modules over CommonJS require(). ESM enables static analysis, tree-shaking, and top-level await. Most modern tools and runtimes support ESM natively.",
123
+ "confidence": 0.9,
124
+ "tags": ["javascript", "modules", "esm"]
125
+ },
126
+ {
127
+ "type": "pattern",
128
+ "category": "Arrays",
129
+ "title": "Use array methods for data transformations",
130
+ "content": "Prefer map, filter, reduce, find, and some over imperative loops for data transformations. They're more declarative, composable, and less error-prone.",
131
+ "confidence": 0.85,
132
+ "tags": ["javascript", "arrays", "functional"]
133
+ },
134
+ {
135
+ "type": "common-issue",
136
+ "category": "Coercion",
137
+ "title": "Be cautious with truthy/falsy checks",
138
+ "content": "JavaScript has six falsy values: false, 0, '', null, undefined, NaN. Be explicit when checking for null/undefined vs falsy. `if (value)` will miss 0 and empty string.",
139
+ "confidence": 0.9,
140
+ "tags": ["javascript", "coercion", "truthiness"]
141
+ },
142
+ {
143
+ "type": "best-practice",
144
+ "category": "Modern ES",
145
+ "title": "Use Map and Set for appropriate data structures",
146
+ "content": "Use Map instead of plain objects when keys are dynamic or non-string. Use Set for unique collections. Both have better performance characteristics and cleaner APIs than object-based alternatives.",
147
+ "confidence": 0.85,
148
+ "tags": ["javascript", "data-structures", "es6"]
149
+ },
150
+ {
151
+ "type": "anti-pattern",
152
+ "category": "Async Patterns",
153
+ "title": "Avoid mixing callbacks and promises",
154
+ "content": "Don't mix callback-style and promise-style async code. Use util.promisify() or write promise wrappers to convert callback APIs. Mixing styles leads to unhandled errors and confusing control flow.",
155
+ "confidence": 0.9,
156
+ "tags": ["javascript", "async", "callbacks"]
157
+ },
158
+ {
159
+ "type": "pattern",
160
+ "category": "Performance",
161
+ "title": "Use AbortController for cancellable operations",
162
+ "content": "Use AbortController with AbortSignal for cancellable fetch requests, event listeners, and async operations. This prevents memory leaks from abandoned operations.",
163
+ "confidence": 0.85,
164
+ "tags": ["javascript", "performance", "abort"],
165
+ "example": "const controller = new AbortController(); fetch(url, { signal: controller.signal })"
166
+ },
167
+ {
168
+ "type": "best-practice",
169
+ "category": "Modern ES",
170
+ "title": "Use Object.hasOwn over hasOwnProperty",
171
+ "content": "Use `Object.hasOwn(obj, prop)` instead of `obj.hasOwnProperty(prop)`. It works on objects created with Object.create(null) and is more readable.",
172
+ "confidence": 0.8,
173
+ "tags": ["javascript", "es2022", "objects"]
174
+ }
175
+ ]
176
+ }
@@ -0,0 +1,222 @@
1
+ {
2
+ "id": "core/typescript",
3
+ "name": "TypeScript Essentials",
4
+ "version": "1.0.0",
5
+ "stack": ["typescript"],
6
+ "description": "Type narrowing, strict mode patterns, generics, enums vs unions, and module best practices",
7
+ "author": "claude-brain",
8
+ "entries": [
9
+ {
10
+ "type": "best-practice",
11
+ "category": "Type Safety",
12
+ "title": "Prefer unknown over any",
13
+ "content": "Use `unknown` instead of `any` for values of uncertain type. Unlike `any`, `unknown` requires type narrowing before use, catching errors at compile time rather than runtime.",
14
+ "confidence": 0.95,
15
+ "tags": ["typescript", "type-safety", "strict-mode"]
16
+ },
17
+ {
18
+ "type": "best-practice",
19
+ "category": "Type Safety",
20
+ "title": "Use discriminated unions for state modeling",
21
+ "content": "Model mutually exclusive states with discriminated unions using a literal type discriminant. This ensures exhaustive checking and prevents impossible states.",
22
+ "confidence": 0.95,
23
+ "tags": ["typescript", "unions", "state-management"],
24
+ "example": "type Result<T> = { status: 'success'; data: T } | { status: 'error'; error: Error }"
25
+ },
26
+ {
27
+ "type": "anti-pattern",
28
+ "category": "Type Safety",
29
+ "title": "Avoid type assertions as default escape hatch",
30
+ "content": "Avoid `as` type assertions to silence type errors. They bypass the type checker entirely. Instead, use type guards, narrowing, or fix the underlying type mismatch.",
31
+ "confidence": 0.9,
32
+ "tags": ["typescript", "type-safety", "anti-pattern"]
33
+ },
34
+ {
35
+ "type": "best-practice",
36
+ "category": "Type Narrowing",
37
+ "title": "Use in operator for interface discrimination",
38
+ "content": "The `in` operator narrows types by checking for property existence. Combined with discriminated unions, it provides type-safe branching without runtime overhead.",
39
+ "confidence": 0.85,
40
+ "tags": ["typescript", "narrowing"],
41
+ "example": "if ('error' in result) { /* result is ErrorResult */ }"
42
+ },
43
+ {
44
+ "type": "best-practice",
45
+ "category": "Type Narrowing",
46
+ "title": "Use satisfies for type checking without widening",
47
+ "content": "The `satisfies` operator validates that an expression matches a type without changing the inferred type. Use it to catch errors while preserving literal types.",
48
+ "confidence": 0.9,
49
+ "tags": ["typescript", "satisfies", "type-inference"],
50
+ "example": "const routes = { home: '/', about: '/about' } satisfies Record<string, string>"
51
+ },
52
+ {
53
+ "type": "pattern",
54
+ "category": "Generics",
55
+ "title": "Constrain generics with extends",
56
+ "content": "Always constrain generic type parameters with `extends` when the function relies on specific properties. This provides better error messages and prevents misuse.",
57
+ "confidence": 0.9,
58
+ "tags": ["typescript", "generics"],
59
+ "example": "function getProperty<T extends object, K extends keyof T>(obj: T, key: K): T[K]"
60
+ },
61
+ {
62
+ "type": "anti-pattern",
63
+ "category": "Generics",
64
+ "title": "Avoid unnecessary generics",
65
+ "content": "Don't add generic type parameters that are only used once or don't provide additional type safety. A generic that appears in only the return type without constraining input is usually unnecessary.",
66
+ "confidence": 0.85,
67
+ "tags": ["typescript", "generics", "simplicity"]
68
+ },
69
+ {
70
+ "type": "best-practice",
71
+ "category": "Enums vs Unions",
72
+ "title": "Prefer const objects or union types over enums",
73
+ "content": "TypeScript enums generate runtime code and have surprising behaviors (numeric enums allow any number). Prefer `as const` objects with derived union types for better tree-shaking and type inference.",
74
+ "confidence": 0.9,
75
+ "tags": ["typescript", "enums", "unions"],
76
+ "example": "const Status = { Active: 'active', Inactive: 'inactive' } as const;\ntype Status = typeof Status[keyof typeof Status];"
77
+ },
78
+ {
79
+ "type": "common-issue",
80
+ "category": "Strict Mode",
81
+ "title": "Enable strict mode in tsconfig.json",
82
+ "content": "Always enable `strict: true` in tsconfig.json. This enables strictNullChecks, noImplicitAny, strictFunctionTypes, and other checks that catch the majority of type-related bugs.",
83
+ "confidence": 0.95,
84
+ "tags": ["typescript", "strict-mode", "configuration"]
85
+ },
86
+ {
87
+ "type": "common-issue",
88
+ "category": "Strict Mode",
89
+ "title": "Handle null and undefined explicitly",
90
+ "content": "With strictNullChecks enabled, use optional chaining (?.), nullish coalescing (??), and explicit null checks. Never use non-null assertions (!) unless you can prove the value exists.",
91
+ "confidence": 0.9,
92
+ "tags": ["typescript", "null-safety", "strict-mode"]
93
+ },
94
+ {
95
+ "type": "pattern",
96
+ "category": "Utility Types",
97
+ "title": "Use built-in utility types effectively",
98
+ "content": "TypeScript provides Partial, Required, Pick, Omit, Record, ReturnType, Parameters, and more. Use these instead of manually redefining type transformations.",
99
+ "confidence": 0.9,
100
+ "tags": ["typescript", "utility-types"]
101
+ },
102
+ {
103
+ "type": "best-practice",
104
+ "category": "Modules",
105
+ "title": "Use type-only imports for types",
106
+ "content": "Use `import type { ... }` for type-only imports. This ensures the import is erased at compile time, reducing bundle size and preventing circular dependency issues.",
107
+ "confidence": 0.9,
108
+ "tags": ["typescript", "modules", "imports"],
109
+ "example": "import type { Config } from './config'"
110
+ },
111
+ {
112
+ "type": "anti-pattern",
113
+ "category": "Type Safety",
114
+ "title": "Avoid using Function type",
115
+ "content": "The `Function` type accepts any function regardless of parameters or return type. Use specific function signatures like `(x: number) => string` or `(...args: unknown[]) => unknown`.",
116
+ "confidence": 0.9,
117
+ "tags": ["typescript", "type-safety"]
118
+ },
119
+ {
120
+ "type": "pattern",
121
+ "category": "Error Handling",
122
+ "title": "Type-safe error handling with instanceof narrowing",
123
+ "content": "In catch blocks, the error is `unknown`. Use `instanceof Error` to narrow it before accessing `.message` or `.stack`. Create custom error classes for domain-specific errors.",
124
+ "confidence": 0.9,
125
+ "tags": ["typescript", "error-handling"],
126
+ "example": "catch (error) { if (error instanceof Error) { log(error.message) } }"
127
+ },
128
+ {
129
+ "type": "best-practice",
130
+ "category": "Type Safety",
131
+ "title": "Use readonly for immutable data",
132
+ "content": "Mark arrays as `readonly T[]` and objects as `Readonly<T>` when mutation is not intended. This prevents accidental modification and communicates intent clearly.",
133
+ "confidence": 0.85,
134
+ "tags": ["typescript", "immutability", "readonly"]
135
+ },
136
+ {
137
+ "type": "pattern",
138
+ "category": "Type Guards",
139
+ "title": "Create custom type guard functions",
140
+ "content": "Use `is` return type annotations to create reusable type guards. These narrow types in conditional branches and can be tested independently.",
141
+ "confidence": 0.85,
142
+ "tags": ["typescript", "type-guards", "narrowing"],
143
+ "example": "function isString(value: unknown): value is string { return typeof value === 'string' }"
144
+ },
145
+ {
146
+ "type": "common-issue",
147
+ "category": "Async",
148
+ "title": "Always type async function return values",
149
+ "content": "Async functions always return a Promise. Explicitly typing the return as `Promise<T>` prevents accidentally returning the wrong type and makes the API contract clear.",
150
+ "confidence": 0.85,
151
+ "tags": ["typescript", "async", "promises"]
152
+ },
153
+ {
154
+ "type": "anti-pattern",
155
+ "category": "Type Safety",
156
+ "title": "Avoid excessive type casting chains",
157
+ "content": "If you need `value as unknown as TargetType`, the type system is telling you something is wrong. Fix the underlying type issue instead of casting through unknown.",
158
+ "confidence": 0.9,
159
+ "tags": ["typescript", "type-safety", "anti-pattern"]
160
+ },
161
+ {
162
+ "type": "best-practice",
163
+ "category": "Configuration",
164
+ "title": "Use path aliases in tsconfig",
165
+ "content": "Configure path aliases in tsconfig.json compilerOptions.paths (e.g., `@/` mapping to `src/`) to avoid deep relative imports and make refactoring easier.",
166
+ "confidence": 0.85,
167
+ "tags": ["typescript", "configuration", "imports"],
168
+ "example": "\"paths\": { \"@/*\": [\"src/*\"] }"
169
+ },
170
+ {
171
+ "type": "pattern",
172
+ "category": "Inference",
173
+ "title": "Leverage type inference where possible",
174
+ "content": "Don't annotate types that TypeScript can infer. Over-annotating adds noise without safety. Annotate function parameters, return types of exported functions, and complex objects.",
175
+ "confidence": 0.85,
176
+ "tags": ["typescript", "inference", "readability"]
177
+ },
178
+ {
179
+ "type": "best-practice",
180
+ "category": "Zod Integration",
181
+ "title": "Use Zod for runtime validation with type inference",
182
+ "content": "Zod schemas provide both runtime validation and compile-time types via `z.infer<typeof schema>`. Define the schema once and derive the type, keeping them in sync.",
183
+ "confidence": 0.85,
184
+ "tags": ["typescript", "zod", "validation"],
185
+ "example": "const UserSchema = z.object({ name: z.string() });\ntype User = z.infer<typeof UserSchema>;"
186
+ },
187
+ {
188
+ "type": "common-issue",
189
+ "category": "Modules",
190
+ "title": "Understand ESM vs CJS module resolution",
191
+ "content": "TypeScript's module resolution depends on moduleResolution setting. Use 'bundler' or 'nodenext' for modern projects. With ESM, imports require file extensions in output.",
192
+ "confidence": 0.8,
193
+ "tags": ["typescript", "modules", "esm", "commonjs"]
194
+ },
195
+ {
196
+ "type": "pattern",
197
+ "category": "Type Safety",
198
+ "title": "Use template literal types for string patterns",
199
+ "content": "Template literal types can enforce string patterns at the type level, like route paths, event names, or ID formats.",
200
+ "confidence": 0.8,
201
+ "tags": ["typescript", "template-literals"],
202
+ "example": "type EventName = `on${Capitalize<string>}`"
203
+ },
204
+ {
205
+ "type": "anti-pattern",
206
+ "category": "Type Safety",
207
+ "title": "Avoid using object type",
208
+ "content": "The `object` type is too broad — it matches arrays, functions, dates, and any non-primitive. Use `Record<string, unknown>` for key-value objects or define a specific interface.",
209
+ "confidence": 0.85,
210
+ "tags": ["typescript", "type-safety"]
211
+ },
212
+ {
213
+ "type": "best-practice",
214
+ "category": "Error Handling",
215
+ "title": "Use Result types for expected failures",
216
+ "content": "For operations that can fail expectedly (validation, parsing), return a discriminated union Result type instead of throwing. Reserve exceptions for unexpected failures.",
217
+ "confidence": 0.85,
218
+ "tags": ["typescript", "error-handling", "result-type"],
219
+ "example": "type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E }"
220
+ }
221
+ ]
222
+ }