@massu/core 1.10.7 → 1.12.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 (177) hide show
  1. package/CHANGELOG.md +1303 -0
  2. package/dist/adapter.js +6 -4
  3. package/dist/cli.js +559 -400
  4. package/dist/detect/adapters/.bundle-shasums.json +4 -7
  5. package/dist/detect/adapters/rails.js +6 -4
  6. package/dist/detect/adapters/spring.js +6 -4
  7. package/dist/detect/adapters/tree-sitter-loader.js +6 -4
  8. package/dist/hooks/auto-learning-pipeline.js +24 -1
  9. package/dist/hooks/classify-failure.js +32 -3
  10. package/dist/hooks/cost-tracker.js +24 -0
  11. package/dist/hooks/fix-detector.js +97 -1
  12. package/dist/hooks/incident-pipeline.js +30 -1
  13. package/dist/hooks/intent-suggester.js +6 -3
  14. package/dist/hooks/post-edit-context.js +24 -1
  15. package/dist/hooks/post-tool-use.js +66 -18
  16. package/dist/hooks/pre-compact.js +27 -2
  17. package/dist/hooks/pre-delete-check.js +48 -22
  18. package/dist/hooks/pre-tool-use-gate.js +962 -0
  19. package/dist/hooks/quality-event.js +24 -0
  20. package/dist/hooks/rule-enforcement-pipeline.js +24 -1
  21. package/dist/hooks/security-gate.js +29 -16
  22. package/dist/hooks/session-end.js +24 -0
  23. package/dist/hooks/session-start.js +8710 -8460
  24. package/dist/hooks/user-prompt.js +24 -0
  25. package/package.json +15 -18
  26. package/commands/README.md +0 -134
  27. package/src/adapter.ts +0 -121
  28. package/src/adr-generator.ts +0 -292
  29. package/src/analytics.ts +0 -373
  30. package/src/audit-trail.ts +0 -450
  31. package/src/backfill-sessions.ts +0 -182
  32. package/src/changelog-generator.ts +0 -178
  33. package/src/cli.ts +0 -246
  34. package/src/cloud-sync.ts +0 -234
  35. package/src/commands/adapters.ts +0 -824
  36. package/src/commands/changelog.ts +0 -165
  37. package/src/commands/config-check-drift.ts +0 -133
  38. package/src/commands/config-refresh.ts +0 -396
  39. package/src/commands/config-upgrade.ts +0 -127
  40. package/src/commands/doctor.ts +0 -485
  41. package/src/commands/hook-runner.ts +0 -145
  42. package/src/commands/init.ts +0 -1823
  43. package/src/commands/install-commands.ts +0 -692
  44. package/src/commands/install-hooks.ts +0 -27
  45. package/src/commands/permissions.ts +0 -150
  46. package/src/commands/refresh-log.ts +0 -37
  47. package/src/commands/show-template.ts +0 -65
  48. package/src/commands/template-engine.ts +0 -301
  49. package/src/commands/watch.ts +0 -430
  50. package/src/config.ts +0 -765
  51. package/src/cost-tracker.ts +0 -355
  52. package/src/db.ts +0 -370
  53. package/src/dependency-scorer.ts +0 -337
  54. package/src/detect/adapters/aspnet.ts +0 -4
  55. package/src/detect/adapters/discover.ts +0 -469
  56. package/src/detect/adapters/file-sampler.ts +0 -225
  57. package/src/detect/adapters/go-chi.ts +0 -4
  58. package/src/detect/adapters/index.ts +0 -51
  59. package/src/detect/adapters/nextjs-trpc.ts +0 -166
  60. package/src/detect/adapters/parse-guard.ts +0 -133
  61. package/src/detect/adapters/phoenix.ts +0 -4
  62. package/src/detect/adapters/python-django.ts +0 -208
  63. package/src/detect/adapters/python-fastapi.ts +0 -223
  64. package/src/detect/adapters/python-flask.ts +0 -235
  65. package/src/detect/adapters/query-helpers.ts +0 -170
  66. package/src/detect/adapters/rails.ts +0 -4
  67. package/src/detect/adapters/runner.ts +0 -284
  68. package/src/detect/adapters/spring.ts +0 -4
  69. package/src/detect/adapters/swift-swiftui.ts +0 -171
  70. package/src/detect/adapters/tree-sitter-loader.ts +0 -517
  71. package/src/detect/adapters/types.ts +0 -191
  72. package/src/detect/codebase-introspector.ts +0 -210
  73. package/src/detect/domain-inferrer.ts +0 -197
  74. package/src/detect/drift.ts +0 -199
  75. package/src/detect/framework-detector.ts +0 -307
  76. package/src/detect/index.ts +0 -209
  77. package/src/detect/manifest-registry.ts +0 -261
  78. package/src/detect/migrate.ts +0 -362
  79. package/src/detect/monorepo-detector.ts +0 -348
  80. package/src/detect/package-detector.ts +0 -828
  81. package/src/detect/passthrough.ts +0 -108
  82. package/src/detect/regex-fallback.ts +0 -449
  83. package/src/detect/source-dir-detector.ts +0 -297
  84. package/src/detect/vr-command-map.ts +0 -167
  85. package/src/docs-map.json +0 -100
  86. package/src/docs-tools.ts +0 -519
  87. package/src/domains.ts +0 -182
  88. package/src/hooks/auto-learning-pipeline.ts +0 -228
  89. package/src/hooks/classify-failure.ts +0 -259
  90. package/src/hooks/cost-tracker.ts +0 -66
  91. package/src/hooks/fix-detector.ts +0 -186
  92. package/src/hooks/incident-pipeline.ts +0 -190
  93. package/src/hooks/intent-suggester.ts +0 -131
  94. package/src/hooks/post-edit-context.ts +0 -91
  95. package/src/hooks/post-tool-use.ts +0 -413
  96. package/src/hooks/pre-compact.ts +0 -168
  97. package/src/hooks/pre-delete-check.ts +0 -243
  98. package/src/hooks/quality-event.ts +0 -127
  99. package/src/hooks/rule-enforcement-pipeline.ts +0 -159
  100. package/src/hooks/security-gate.ts +0 -153
  101. package/src/hooks/session-end.ts +0 -467
  102. package/src/hooks/session-start.ts +0 -436
  103. package/src/hooks/user-prompt.ts +0 -157
  104. package/src/import-resolver.ts +0 -226
  105. package/src/knowledge-db.ts +0 -176
  106. package/src/knowledge-indexer.ts +0 -708
  107. package/src/knowledge-tools.ts +0 -1414
  108. package/src/lib/fileLock.ts +0 -203
  109. package/src/lib/gitToplevel.ts +0 -22
  110. package/src/lib/hook-registry.ts +0 -43
  111. package/src/lib/installLock.ts +0 -66
  112. package/src/lib/memory-path.ts +0 -49
  113. package/src/lib/pidLiveness.ts +0 -67
  114. package/src/lib/settings-local.ts +0 -110
  115. package/src/lib/sql-table-names.ts +0 -71
  116. package/src/license.ts +0 -547
  117. package/src/lsp/auto-detect.ts +0 -98
  118. package/src/lsp/client.ts +0 -776
  119. package/src/lsp/enrich.ts +0 -127
  120. package/src/lsp/types.ts +0 -221
  121. package/src/memory-db.ts +0 -1614
  122. package/src/memory-file-ingest.ts +0 -128
  123. package/src/memory-tools.ts +0 -424
  124. package/src/middleware-tree.ts +0 -71
  125. package/src/observability-tools.ts +0 -343
  126. package/src/observation-extractor.ts +0 -418
  127. package/src/page-deps.ts +0 -285
  128. package/src/permissions.ts +0 -422
  129. package/src/prompt-analyzer.ts +0 -332
  130. package/src/python/coupling-detector.ts +0 -125
  131. package/src/python/domain-enforcer.ts +0 -84
  132. package/src/python/impact-analyzer.ts +0 -96
  133. package/src/python/import-parser.ts +0 -244
  134. package/src/python/import-resolver.ts +0 -136
  135. package/src/python/migration-indexer.ts +0 -116
  136. package/src/python/migration-parser.ts +0 -332
  137. package/src/python/model-indexer.ts +0 -71
  138. package/src/python/model-parser.ts +0 -279
  139. package/src/python/route-indexer.ts +0 -59
  140. package/src/python/route-parser.ts +0 -317
  141. package/src/python-tools.ts +0 -630
  142. package/src/regression-detector.ts +0 -319
  143. package/src/rules.ts +0 -57
  144. package/src/schema-mapper.ts +0 -232
  145. package/src/security/adapter-origin.ts +0 -130
  146. package/src/security/adapter-verifier.ts +0 -319
  147. package/src/security/atomic-write.ts +0 -164
  148. package/src/security/fetcher.ts +0 -200
  149. package/src/security/install-tracking.ts +0 -319
  150. package/src/security/license-pubkey.generated.ts +0 -30
  151. package/src/security/license-response-verifier.ts +0 -149
  152. package/src/security/local-fingerprint.ts +0 -225
  153. package/src/security/manifest-cache.ts +0 -333
  154. package/src/security/manifest-schema.ts +0 -129
  155. package/src/security/registry-pubkey.generated.ts +0 -35
  156. package/src/security/telemetry.ts +0 -320
  157. package/src/security-scorer.ts +0 -405
  158. package/src/security-utils.ts +0 -133
  159. package/src/sentinel-db.ts +0 -580
  160. package/src/sentinel-scanner.ts +0 -406
  161. package/src/sentinel-tools.ts +0 -513
  162. package/src/sentinel-types.ts +0 -140
  163. package/src/server-dispatch.ts +0 -225
  164. package/src/server.ts +0 -107
  165. package/src/session-archiver.ts +0 -111
  166. package/src/session-state-generator.ts +0 -174
  167. package/src/team-knowledge.ts +0 -407
  168. package/src/tool-db-needs.ts +0 -232
  169. package/src/tools.ts +0 -1205
  170. package/src/transcript-parser.ts +0 -458
  171. package/src/trpc-index.ts +0 -215
  172. package/src/validate-features-runner.ts +0 -107
  173. package/src/validation-engine.ts +0 -358
  174. package/src/watch/daemon.ts +0 -385
  175. package/src/watch/lockfile-detector.ts +0 -65
  176. package/src/watch/paths.ts +0 -279
  177. package/src/watch/state.ts +0 -178
package/src/tools.ts DELETED
@@ -1,1205 +0,0 @@
1
- // Copyright (c) 2026 Massu. All rights reserved.
2
- // Licensed under BSL 1.1 - see LICENSE file for details.
3
-
4
- import { readFileSync, existsSync } from 'fs';
5
- import { resolve, basename } from 'path';
6
- import { ensureWithinRoot } from './security-utils.ts';
7
- import type Database from 'better-sqlite3';
8
- import { matchRules } from './rules.ts';
9
- import { buildImportIndex } from './import-resolver.ts';
10
- import { buildTrpcIndex } from './trpc-index.ts';
11
- import { buildPageDeps, findAffectedPages } from './page-deps.ts';
12
- import { buildMiddlewareTree, isInMiddlewareTree, getMiddlewareTree } from './middleware-tree.ts';
13
- import { classifyFile, classifyRouter, findCrossDomainImports, getFilesInDomain } from './domains.ts';
14
- import { parsePrismaSchema, detectMismatches, findColumnUsageInRouters } from './schema-mapper.ts';
15
- import { isDataStale, updateBuildTimestamp, isPythonDataStale, updatePythonBuildTimestamp } from './db.ts';
16
- import { buildPythonImportIndex } from './python/import-resolver.ts';
17
- import { buildPythonRouteIndex } from './python/route-indexer.ts';
18
- import { buildPythonModelIndex } from './python/model-indexer.ts';
19
- import { buildPythonMigrationIndex } from './python/migration-indexer.ts';
20
- import { buildPythonCouplingIndex } from './python/coupling-detector.ts';
21
- import { getMemoryToolDefinitions, handleMemoryToolCall } from './memory-tools.ts';
22
- import { getMemoryDb } from './memory-db.ts';
23
- import { getDocsToolDefinitions, handleDocsToolCall } from './docs-tools.ts';
24
- import { getObservabilityToolDefinitions, handleObservabilityToolCall, isObservabilityTool } from './observability-tools.ts';
25
- import { getSentinelToolDefinitions, handleSentinelToolCall } from './sentinel-tools.ts';
26
- import { runFeatureScan } from './sentinel-scanner.ts';
27
- import { getAnalyticsToolDefinitions, isAnalyticsTool, handleAnalyticsToolCall } from './analytics.ts';
28
- import { getCostToolDefinitions, isCostTool, handleCostToolCall } from './cost-tracker.ts';
29
- import { getPromptToolDefinitions, isPromptTool, handlePromptToolCall } from './prompt-analyzer.ts';
30
- import { getAuditToolDefinitions, isAuditTool, handleAuditToolCall } from './audit-trail.ts';
31
- import { getValidationToolDefinitions, isValidationTool, handleValidationToolCall } from './validation-engine.ts';
32
- import { getAdrToolDefinitions, isAdrTool, handleAdrToolCall } from './adr-generator.ts';
33
- import { getSecurityToolDefinitions, isSecurityTool, handleSecurityToolCall } from './security-scorer.ts';
34
- import { getDependencyToolDefinitions, isDependencyTool, handleDependencyToolCall } from './dependency-scorer.ts';
35
- import { getTeamToolDefinitions, isTeamTool, handleTeamToolCall } from './team-knowledge.ts';
36
- import { getRegressionToolDefinitions, isRegressionTool, handleRegressionToolCall } from './regression-detector.ts';
37
- import { getKnowledgeToolDefinitions, isKnowledgeTool, handleKnowledgeToolCall } from './knowledge-tools.ts';
38
- import { getKnowledgeDb } from './knowledge-db.ts';
39
- import { getPythonToolDefinitions, isPythonTool, handlePythonToolCall } from './python-tools.ts';
40
- import { getConfig, getProjectRoot, getResolvedPaths } from './config.ts';
41
- import { getCurrentTier, getToolTier, isToolAllowed, annotateToolDefinitions, getLicenseToolDefinitions, isLicenseTool, handleLicenseToolCall, isCloudFeatureAvailable } from './license.ts';
42
- import { t } from './lib/sql-table-names.ts';
43
-
44
- export interface ToolDefinition {
45
- name: string;
46
- description: string;
47
- inputSchema: Record<string, unknown>;
48
- annotations?: Record<string, unknown>;
49
- }
50
-
51
- export interface ToolResult {
52
- content: { type: 'text'; text: string }[];
53
- }
54
-
55
- /** Get the configured tool prefix (e.g., 'massu' or 'myapp') */
56
- function prefix(): string {
57
- return getConfig().toolPrefix;
58
- }
59
-
60
- /** Prefix a tool name with the configured prefix */
61
- function p(name: string): string {
62
- return `${prefix()}_${name}`;
63
- }
64
-
65
- /**
66
- * Strip the configured prefix from a tool name to get the base name.
67
- * e.g., "massu_sync" -> "sync", "massu_memory_search" -> "memory_search"
68
- */
69
- function stripPrefix(name: string): string {
70
- const pfx = prefix() + '_';
71
- if (name.startsWith(pfx)) {
72
- return name.slice(pfx.length);
73
- }
74
- return name;
75
- }
76
-
77
- /**
78
- * Ensure indexes are built and up-to-date.
79
- *
80
- * Lazy initialization: only rebuilds if stale.
81
- *
82
- * **Codegraph-optional**: `codegraphDb` is now optional. When omitted, the
83
- * JS index section (imports, tRPC, pages, middleware — all derived from
84
- * CodeGraph AST data) is skipped. The Python index section (which only
85
- * reads Python source files via tree-sitter into Data DB) still runs.
86
- * This supports the lazy-per-tool-DB design from
87
- * `plan-1.6.2-server-lazy-db-deps`: Python tools and any tool that needs
88
- * fresh Python indexes can call `ensureIndexes(dataDb)` without requiring
89
- * a CodeGraph DB.
90
- */
91
- function ensureIndexes(dataDb: Database.Database, codegraphDb?: Database.Database, force: boolean = false): string {
92
- const results: string[] = [];
93
- const config = getConfig();
94
-
95
- // JS indexes — require CodeGraph DB. Skipped when codegraphDb is undefined
96
- // (e.g., a Python tool or memory tool triggered ensureIndexes for its
97
- // own Python-index needs without needing JS indexes).
98
- if (codegraphDb !== undefined && (force || isDataStale(dataDb, codegraphDb))) {
99
- const importCount = buildImportIndex(dataDb, codegraphDb);
100
- results.push(`Import edges: ${importCount}`);
101
-
102
- if (config.framework.router === 'trpc') {
103
- const trpcStats = buildTrpcIndex(dataDb);
104
- results.push(`tRPC procedures: ${trpcStats.totalProcedures} (${trpcStats.withCallers} with UI, ${trpcStats.withoutCallers} without)`);
105
- }
106
-
107
- const pageCount = buildPageDeps(dataDb, codegraphDb);
108
- results.push(`Page deps: ${pageCount} pages`);
109
-
110
- if (config.paths.middleware) {
111
- const middlewareCount = buildMiddlewareTree(dataDb);
112
- results.push(`Middleware tree: ${middlewareCount} files`);
113
- }
114
-
115
- updateBuildTimestamp(dataDb);
116
- }
117
-
118
- // Python indexes — independent of JS staleness
119
- if (config.python?.root) {
120
- const pythonRoot = config.python.root;
121
- const excludeDirs = config.python.exclude_dirs || ['__pycache__', '.venv', 'venv', '.mypy_cache', '.pytest_cache'];
122
-
123
- if (force || isPythonDataStale(dataDb, resolve(getProjectRoot(), pythonRoot))) {
124
- const pyImports = buildPythonImportIndex(dataDb, pythonRoot, excludeDirs);
125
- results.push(`Python imports: ${pyImports}`);
126
-
127
- const pyRoutes = buildPythonRouteIndex(dataDb, pythonRoot, excludeDirs);
128
- results.push(`Python routes: ${pyRoutes}`);
129
-
130
- const pyModels = buildPythonModelIndex(dataDb, pythonRoot, excludeDirs);
131
- results.push(`Python models: ${pyModels}`);
132
-
133
- if (config.python.alembic_dir) {
134
- const pyMigrations = buildPythonMigrationIndex(dataDb, config.python.alembic_dir);
135
- results.push(`Python migrations: ${pyMigrations}`);
136
- }
137
-
138
- const pyCoupling = buildPythonCouplingIndex(dataDb);
139
- results.push(`Python coupling: ${pyCoupling}`);
140
-
141
- updatePythonBuildTimestamp(dataDb);
142
- }
143
- }
144
-
145
- if (results.length === 0) return 'Indexes are up-to-date.';
146
- return `Indexes rebuilt:\n${results.join('\n')}`;
147
- }
148
-
149
- /**
150
- * Get all tool definitions for the MCP server.
151
- */
152
- export function getToolDefinitions(): ToolDefinition[] {
153
- const config = getConfig();
154
-
155
- return annotateToolDefinitions([
156
- // Memory tools
157
- ...getMemoryToolDefinitions(),
158
- // Observability tools
159
- ...getObservabilityToolDefinitions(),
160
- // Docs tools
161
- ...getDocsToolDefinitions(),
162
- // Sentinel tools (feature registry)
163
- ...getSentinelToolDefinitions(),
164
- // Analytics layer (quality trends, cost tracking, prompt analysis)
165
- ...getAnalyticsToolDefinitions(),
166
- ...getCostToolDefinitions(),
167
- ...getPromptToolDefinitions(),
168
- // Governance layer (audit trail, validation, ADR)
169
- ...getAuditToolDefinitions(),
170
- ...getValidationToolDefinitions(),
171
- ...getAdrToolDefinitions(),
172
- // Security layer (security scoring, dependency risk)
173
- ...getSecurityToolDefinitions(),
174
- ...getDependencyToolDefinitions(),
175
- // Enterprise layer (team knowledge, regression detection)
176
- // P-A-003: team tools are cloud-gated — only listed when cloud.enabled is true.
177
- ...(isCloudFeatureAvailable() ? getTeamToolDefinitions() : []),
178
- ...getRegressionToolDefinitions(),
179
- // Knowledge layer (indexed .claude/ knowledge — rules, patterns, incidents)
180
- ...getKnowledgeToolDefinitions(),
181
- // Python code intelligence tools
182
- ...getPythonToolDefinitions(),
183
- // License tools (always available)
184
- ...getLicenseToolDefinitions(),
185
- // Core tools
186
- {
187
- name: p('sync'),
188
- description: 'Force rebuild all indexes (import edges, tRPC mappings, page deps, middleware tree). Run this after significant code changes.',
189
- inputSchema: {
190
- type: 'object',
191
- properties: {},
192
- required: [],
193
- },
194
- },
195
- {
196
- name: p('context'),
197
- description: 'Get context for a file: applicable rules, pattern warnings, schema mismatch alerts, and whether the file is in the middleware import tree.',
198
- inputSchema: {
199
- type: 'object',
200
- properties: {
201
- file: { type: 'string', description: 'File path relative to project root' },
202
- },
203
- required: ['file'],
204
- },
205
- },
206
- ...(config.framework.router === 'trpc' ? [
207
- {
208
- name: p('trpc_map'),
209
- description: 'Map tRPC procedures to their UI call sites. Find which components call a router, which procedures have no UI callers, or list all procedures for a router.',
210
- inputSchema: {
211
- type: 'object',
212
- properties: {
213
- router: { type: 'string', description: 'Router name (e.g., "orders")' },
214
- procedure: { type: 'string', description: 'Procedure name to search across all routers' },
215
- uncoupled: { type: 'boolean', description: 'If true, show only procedures with ZERO UI callers' },
216
- },
217
- required: [],
218
- },
219
- },
220
- {
221
- name: p('coupling_check'),
222
- description: 'Automated coupling check. Finds all procedures with zero UI callers and components not rendered in any page.',
223
- inputSchema: {
224
- type: 'object',
225
- properties: {
226
- staged_files: {
227
- type: 'array',
228
- items: { type: 'string' },
229
- description: 'Optional: only check these specific files',
230
- },
231
- },
232
- required: [],
233
- },
234
- },
235
- ] : []),
236
- {
237
- name: p('impact'),
238
- description: 'Full impact analysis for a file: which pages are affected, which database tables are in the chain, middleware tree membership, domain crossings.',
239
- inputSchema: {
240
- type: 'object',
241
- properties: {
242
- file: { type: 'string', description: 'File path relative to project root' },
243
- },
244
- required: ['file'],
245
- },
246
- },
247
- ...(config.domains.length > 0 ? [{
248
- name: p('domains'),
249
- description: 'Domain boundary information. Classify a file into its domain, show cross-domain imports, or list all files in a domain.',
250
- inputSchema: {
251
- type: 'object',
252
- properties: {
253
- file: { type: 'string', description: 'File to classify into a domain' },
254
- crossings: { type: 'boolean', description: 'Show all cross-domain imports (violations highlighted)' },
255
- domain: { type: 'string', description: 'Domain name to list all files for' },
256
- },
257
- required: [],
258
- },
259
- }] : []),
260
- ...(config.framework.orm === 'prisma' ? [{
261
- name: p('schema'),
262
- description: 'Prisma schema cross-reference. Show columns for a table, detect mismatches between code and schema, or verify column references in a file.',
263
- inputSchema: {
264
- type: 'object',
265
- properties: {
266
- table: { type: 'string', description: 'Table/model name to inspect' },
267
- mismatches: { type: 'boolean', description: 'Show all detected column name mismatches' },
268
- verify: { type: 'string', description: 'File path to verify column references against schema' },
269
- },
270
- required: [],
271
- },
272
- }] : []),
273
- ]);
274
- }
275
-
276
- /**
277
- * Defensive assertion: a routing branch that consumes Data DB requires it
278
- * to have been resolved by the dispatcher. Should never fire — the manifest
279
- * declares which tools need Data DB and `server.ts:resolveDbsForTool`
280
- * resolves accordingly. A throw here indicates a manifest/code drift.
281
- */
282
- function assertDataDb(dataDb: Database.Database | undefined, toolName: string): Database.Database {
283
- if (!dataDb) {
284
- throw new Error(`Internal: tool "${toolName}" routed to a Data-DB branch but dispatcher did not resolve Data DB. Check TOOL_DB_NEEDS manifest entry includes 'data'.`);
285
- }
286
- return dataDb;
287
- }
288
-
289
- /**
290
- * Defensive assertion mirror of {@link assertDataDb} for CodeGraph DB.
291
- */
292
- function assertCodegraphDb(codegraphDb: Database.Database | undefined, toolName: string): Database.Database {
293
- if (!codegraphDb) {
294
- throw new Error(`Internal: tool "${toolName}" routed to a CodeGraph branch but dispatcher did not resolve CodeGraph DB. Check TOOL_DB_NEEDS manifest entry includes 'codegraph'.`);
295
- }
296
- return codegraphDb;
297
- }
298
-
299
- /**
300
- * Handle a tool call and return the result.
301
- *
302
- * **Pre-dispatch ordering invariant (P-A-002c, plan-1.6.2-server-lazy-db-deps)**:
303
- * 1. Tier gate (`isToolAllowed`) — checked BEFORE any DB access so
304
- * free-tier users cannot provoke DB errors on paid tools.
305
- * 2. Per-family routing (memory/observability/sentinel/knowledge/...) —
306
- * each family opens ONLY the DB connections its handler needs.
307
- * 3. Code-intel families (Python, core JS) invoke `ensureIndexes` at
308
- * the top of their branch with the DBs they have. ensureIndexes is
309
- * NEVER called unconditionally for memory/audit/knowledge/etc.
310
- *
311
- * **DB params**: `dataDb` and `codegraphDb` are OPTIONAL — the dispatcher
312
- * (`server.ts:resolveDbsForTool`) resolves them based on the tool's entry
313
- * in `TOOL_DB_NEEDS`. Memory/Knowledge DBs are opened per-call inside
314
- * their routing branches (existing pattern, unchanged).
315
- *
316
- * **Defensive checks**: branches that require a DB call `assertDataDb`
317
- * or `assertCodegraphDb` first. These should never fire — `TOOL_DB_NEEDS`
318
- * guarantees the dispatcher resolved the right DBs — but the runtime
319
- * check catches manifest/code drift loudly instead of silently passing
320
- * `undefined` into handlers.
321
- */
322
- export async function handleToolCall(
323
- name: string,
324
- args: Record<string, unknown>,
325
- dataDb?: Database.Database,
326
- codegraphDb?: Database.Database
327
- ): Promise<ToolResult> {
328
- // P3-017: Tier gate — check before any routing (ordering invariant step 1)
329
- const userTier = await getCurrentTier();
330
- const requiredTier = getToolTier(name);
331
- if (!isToolAllowed(name, userTier)) {
332
- return text(`This tool requires ${requiredTier} tier. Current tier: ${userTier}. Upgrade at https://massu.ai/pricing`);
333
- }
334
-
335
- const pfx = prefix();
336
-
337
- try {
338
- // Route memory tools to memory handler
339
- if (name.startsWith(pfx + '_memory_')) {
340
- const memDb = getMemoryDb();
341
- try {
342
- return handleMemoryToolCall(name, args, memDb);
343
- } finally {
344
- memDb.close();
345
- }
346
- }
347
-
348
- // Route observability tools to observability handler
349
- if (isObservabilityTool(name)) {
350
- const memDb = getMemoryDb();
351
- try {
352
- return handleObservabilityToolCall(name, args, memDb);
353
- } finally {
354
- memDb.close();
355
- }
356
- }
357
-
358
- // Route docs tools to docs handler
359
- if (name.startsWith(pfx + '_docs_')) {
360
- return handleDocsToolCall(name, args);
361
- }
362
-
363
- // Route sentinel tools to sentinel handler
364
- if (name.startsWith(pfx + '_sentinel_')) {
365
- return handleSentinelToolCall(name, args, assertDataDb(dataDb, name));
366
- }
367
-
368
- // Route analytics layer tools
369
- if (isAnalyticsTool(name)) {
370
- const memDb = getMemoryDb();
371
- try { return handleAnalyticsToolCall(name, args, memDb); }
372
- finally { memDb.close(); }
373
- }
374
- if (isCostTool(name)) {
375
- const memDb = getMemoryDb();
376
- try { return handleCostToolCall(name, args, memDb); }
377
- finally { memDb.close(); }
378
- }
379
- if (isPromptTool(name)) {
380
- const memDb = getMemoryDb();
381
- try { return handlePromptToolCall(name, args, memDb); }
382
- finally { memDb.close(); }
383
- }
384
-
385
- // Route governance layer tools
386
- if (isAuditTool(name)) {
387
- const memDb = getMemoryDb();
388
- try { return handleAuditToolCall(name, args, memDb); }
389
- finally { memDb.close(); }
390
- }
391
- if (isValidationTool(name)) {
392
- const memDb = getMemoryDb();
393
- try { return handleValidationToolCall(name, args, memDb); }
394
- finally { memDb.close(); }
395
- }
396
- if (isAdrTool(name)) {
397
- const memDb = getMemoryDb();
398
- try { return handleAdrToolCall(name, args, memDb); }
399
- finally { memDb.close(); }
400
- }
401
-
402
- // Route security layer tools
403
- if (isSecurityTool(name)) {
404
- const memDb = getMemoryDb();
405
- try { return handleSecurityToolCall(name, args, memDb); }
406
- finally { memDb.close(); }
407
- }
408
- if (isDependencyTool(name)) {
409
- const memDb = getMemoryDb();
410
- try { return handleDependencyToolCall(name, args, memDb); }
411
- finally { memDb.close(); }
412
- }
413
-
414
- // Route enterprise layer tools
415
- // P-A-003: team-tool dispatch gated on cloud availability; if a stale client
416
- // still has the tool name cached, fall through to the unknown-tool branch.
417
- if (isTeamTool(name) && isCloudFeatureAvailable()) {
418
- const memDb = getMemoryDb();
419
- try { return handleTeamToolCall(name, args, memDb); }
420
- finally { memDb.close(); }
421
- }
422
- if (isRegressionTool(name)) {
423
- const memDb = getMemoryDb();
424
- try { return handleRegressionToolCall(name, args, memDb); }
425
- finally { memDb.close(); }
426
- }
427
-
428
- // Route knowledge layer tools
429
- if (isKnowledgeTool(name)) {
430
- const knowledgeDb = getKnowledgeDb();
431
- try { return handleKnowledgeToolCall(name, args, knowledgeDb); }
432
- finally { knowledgeDb.close(); }
433
- }
434
-
435
- // Route Python tools (uses dataDb only; codegraphDb not required).
436
- // ensureIndexes runs WITHOUT codegraphDb — only the Python-index section
437
- // rebuilds (against dataDb). JS-index section is skipped (no codegraph).
438
- if (isPythonTool(name)) {
439
- const pyDataDb = assertDataDb(dataDb, name);
440
- ensureIndexes(pyDataDb);
441
- return handlePythonToolCall(name, args, pyDataDb);
442
- }
443
-
444
- // Route license tools
445
- if (isLicenseTool(name)) {
446
- const memDb = getMemoryDb();
447
- try { return await handleLicenseToolCall(name, args, memDb); }
448
- finally { memDb.close(); }
449
- }
450
-
451
- // Match core tools by base name. Each codegraph-dependent core tool
452
- // asserts both DBs and runs ensureIndexes (full JS + Python rebuild
453
- // when stale).
454
- const baseName = stripPrefix(name);
455
- switch (baseName) {
456
- case 'sync': {
457
- const d = assertDataDb(dataDb, name);
458
- const c = assertCodegraphDb(codegraphDb, name);
459
- return handleSync(d, c);
460
- }
461
- case 'context': {
462
- const d = assertDataDb(dataDb, name);
463
- const c = assertCodegraphDb(codegraphDb, name);
464
- ensureIndexes(d, c);
465
- return handleContext(args.file as string, d, c);
466
- }
467
- case 'trpc_map': {
468
- const d = assertDataDb(dataDb, name);
469
- // trpc_map needs the tRPC index in Data DB. The index is built by
470
- // ensureIndexes' JS section, which requires CodeGraph DB. If
471
- // codegraphDb is provided (manifest declares 'codegraph'), rebuild
472
- // the index; otherwise read whatever stale index exists.
473
- ensureIndexes(d, codegraphDb);
474
- return handleTrpcMap(args, d);
475
- }
476
- case 'coupling_check': {
477
- const d = assertDataDb(dataDb, name);
478
- const c = assertCodegraphDb(codegraphDb, name);
479
- ensureIndexes(d, c);
480
- return handleCouplingCheck(args, d, c);
481
- }
482
- case 'impact': {
483
- const d = assertDataDb(dataDb, name);
484
- const c = assertCodegraphDb(codegraphDb, name);
485
- ensureIndexes(d, c);
486
- return handleImpact(args.file as string, d, c);
487
- }
488
- case 'domains': {
489
- const d = assertDataDb(dataDb, name);
490
- const c = assertCodegraphDb(codegraphDb, name);
491
- ensureIndexes(d, c);
492
- return handleDomains(args, d, c);
493
- }
494
- case 'schema':
495
- // Filesystem-only; no DB access.
496
- return handleSchema(args);
497
- default:
498
- return text(`Unknown tool: ${name}`);
499
- }
500
- } catch (error) {
501
- const msg = error instanceof Error ? error.message : String(error);
502
- // Strip file paths and stack traces from error messages exposed to clients
503
- const safeMsg = msg.split('\n')[0].replace(/\/(Users|home|var|tmp)\/[^\s:]+/g, '<path>');
504
- return text(`Error in ${name}: ${safeMsg}`);
505
- }
506
- }
507
-
508
- function text(content: string): ToolResult {
509
- return { content: [{ type: 'text', text: content }] };
510
- }
511
-
512
- // === Tool Handlers ===
513
-
514
- function handleSync(dataDb: Database.Database, codegraphDb: Database.Database): ToolResult {
515
- const result = ensureIndexes(dataDb, codegraphDb, true);
516
-
517
- // Run feature auto-discovery after index rebuild
518
- try {
519
- const scanResult = runFeatureScan(dataDb);
520
- return text(`${result}\n\nFeature scan: ${scanResult.registered} features registered (${scanResult.fromProcedures} from procedures, ${scanResult.fromPages} from pages, ${scanResult.fromComponents} from components)`);
521
- } catch (error) {
522
- return text(`${result}\n\nFeature scan failed: ${error instanceof Error ? error.message : String(error)}`);
523
- }
524
- }
525
-
526
- function handleContext(file: string, dataDb: Database.Database, codegraphDb: Database.Database): ToolResult {
527
- const lines: string[] = [];
528
-
529
- // 1. CodeGraph context
530
- const nodes = codegraphDb.prepare(
531
- "SELECT name, kind, start_line, end_line FROM nodes WHERE file_path = ? ORDER BY start_line"
532
- ).all(file) as { name: string; kind: string; start_line: number; end_line: number }[];
533
-
534
- if (nodes.length > 0) {
535
- lines.push('## CodeGraph Nodes');
536
- for (const node of nodes.slice(0, 30)) {
537
- lines.push(`- ${node.kind}: ${node.name} (L${node.start_line}-${node.end_line})`);
538
- }
539
- if (nodes.length > 30) {
540
- lines.push(`... and ${nodes.length - 30} more`);
541
- }
542
- lines.push('');
543
- }
544
-
545
- // 2. Applicable rules
546
- const rules = matchRules(file);
547
- if (rules.length > 0) {
548
- lines.push('## Applicable Rules');
549
- for (const rule of rules) {
550
- const severity = rule.severity ? `[${rule.severity}]` : '';
551
- for (const r of rule.rules) {
552
- lines.push(`- ${severity} ${r}`);
553
- }
554
- if (rule.patternFile) {
555
- lines.push(` See: .claude/${rule.patternFile}`);
556
- }
557
- }
558
- lines.push('');
559
- }
560
-
561
- // 3. Middleware tree check
562
- if (isInMiddlewareTree(dataDb, file)) {
563
- lines.push('## WARNING: Middleware Import Tree');
564
- lines.push('This file is imported (directly or transitively) by the middleware entry point.');
565
- lines.push('NO Node.js dependencies allowed (pino, winston, fs, crypto, path, child_process).');
566
- lines.push('');
567
- }
568
-
569
- // 4. Domain classification
570
- const domain = classifyFile(file);
571
- lines.push(`## Domain: ${domain}`);
572
- lines.push('');
573
-
574
- // 5. Import edges
575
- const imports = dataDb.prepare(
576
- `SELECT target_file, imported_names FROM ${t('imports')} WHERE source_file = ? LIMIT 20`
577
- ).all(file) as { target_file: string; imported_names: string }[];
578
-
579
- if (imports.length > 0) {
580
- lines.push('## Imports (from this file)');
581
- for (const imp of imports) {
582
- const names = JSON.parse(imp.imported_names);
583
- lines.push(`- ${imp.target_file}${names.length > 0 ? ': ' + names.join(', ') : ''}`);
584
- }
585
- lines.push('');
586
- }
587
-
588
- // 6. Imported BY
589
- const importedBy = dataDb.prepare(
590
- `SELECT source_file FROM ${t('imports')} WHERE target_file = ? LIMIT 20`
591
- ).all(file) as { source_file: string }[];
592
-
593
- if (importedBy.length > 0) {
594
- lines.push('## Imported By');
595
- for (const imp of importedBy) {
596
- lines.push(`- ${imp.source_file}`);
597
- }
598
- lines.push('');
599
- }
600
-
601
- // 7. Knowledge context (relevant CRs, schema warnings, incidents, corrections)
602
- try {
603
- const knowledgeDb = getKnowledgeDb();
604
- try {
605
- const docCount = (knowledgeDb.prepare('SELECT COUNT(*) as cnt FROM knowledge_documents').get() as { cnt: number })?.cnt ?? 0;
606
- if (docCount > 0) {
607
- // Schema mismatch warnings: check if file references any known-mismatch tables
608
- const mismatches = knowledgeDb.prepare('SELECT table_name, wrong_column, correct_column FROM knowledge_schema_mismatches').all() as {
609
- table_name: string; wrong_column: string; correct_column: string;
610
- }[];
611
-
612
- if (mismatches.length > 0) {
613
- if (file.includes('router') || file.includes('server/api')) {
614
- lines.push('## Schema Mismatch Warnings');
615
- lines.push('Known column name traps (from CLAUDE.md):');
616
- for (const m of mismatches.slice(0, 5)) {
617
- lines.push(`- \`${m.table_name}.${m.wrong_column}\` → use \`${m.correct_column}\` instead`);
618
- }
619
- lines.push('');
620
- }
621
- }
622
-
623
- // Dynamic rule matching — combine file-type defaults with content-based FTS
624
- const fileType = file.includes('router') || file.includes('server/api') ? 'router'
625
- : file.includes('components') || file.includes('app/') ? 'component'
626
- : file.includes('middleware') ? 'middleware'
627
- : file.includes('migration') ? 'migration'
628
- : 'other';
629
-
630
- const domainDefaultCRs: Record<string, string[]> = {
631
- router: ['CR-2', 'CR-6'],
632
- component: ['CR-8', 'CR-12'],
633
- middleware: ['CR-16', 'CR-19'],
634
- migration: ['CR-2', 'CR-36'],
635
- };
636
-
637
- const defaultCRs = domainDefaultCRs[fileType] || [];
638
-
639
- // Extract keywords from file content for FTS matching
640
- let ftsRuleIds: string[] = [];
641
- try {
642
- const resolvedPaths = getResolvedPaths();
643
- const root = getProjectRoot();
644
- const absFilePath = ensureWithinRoot(resolve(resolvedPaths.srcDir, '..', file), root);
645
- if (existsSync(absFilePath)) {
646
- const fileContent = readFileSync(absFilePath, 'utf-8').slice(0, 3000);
647
- const keywords: string[] = [];
648
- if (fileContent.includes('ctx.db')) keywords.push('database', 'schema');
649
- if (fileContent.includes('BigInt') || fileContent.includes('Decimal')) keywords.push('BigInt', 'serialization');
650
- if (fileContent.includes('protectedProcedure') || fileContent.includes('publicProcedure')) keywords.push('procedure', 'mutation');
651
- if (fileContent.includes('Select') || fileContent.includes('value=')) keywords.push('Select', 'value');
652
- if (fileContent.includes('include:')) keywords.push('include', 'relation');
653
- if (fileContent.includes('migration') || fileContent.includes('ALTER TABLE')) keywords.push('migration', 'schema');
654
- if (fileContent.includes('RLS') || fileContent.includes('policy')) keywords.push('RLS', 'policy');
655
- if (fileContent.includes('onPointerDown') || fileContent.includes('onClick')) keywords.push('stylus', 'pointer');
656
-
657
- if (keywords.length > 0) {
658
- const ftsQuery = keywords.slice(0, 5).map(k => `"${k}"`).join(' OR ');
659
- try {
660
- const ftsResults = knowledgeDb.prepare(`
661
- SELECT DISTINCT kc.heading as rule_id
662
- FROM knowledge_fts kf
663
- JOIN knowledge_chunks kc ON kc.id = kf.rowid
664
- WHERE kf.content MATCH ? AND kc.chunk_type = 'rule'
665
- LIMIT 8
666
- `).all(ftsQuery) as { rule_id: string }[];
667
- ftsRuleIds = ftsResults.map(r => r.rule_id).filter(id => id.startsWith('CR-'));
668
- } catch { /* FTS syntax error — fall back to defaults */ }
669
- }
670
- }
671
- } catch { /* File read error — fall back to defaults */ }
672
-
673
- // Combine: defaults + FTS-discovered, deduplicated
674
- const relevantCRs = [...new Set([...defaultCRs, ...ftsRuleIds])].slice(0, 10);
675
-
676
- if (relevantCRs.length > 0) {
677
- const placeholders = relevantCRs.map(() => '?').join(',');
678
- const crRules = knowledgeDb.prepare(
679
- `SELECT rule_id, rule_text, vr_type FROM knowledge_rules WHERE rule_id IN (${placeholders})`
680
- ).all(...relevantCRs) as { rule_id: string; rule_text: string; vr_type: string }[];
681
-
682
- if (crRules.length > 0) {
683
- lines.push('## Relevant Canonical Rules');
684
- for (const cr of crRules) {
685
- lines.push(`- **${cr.rule_id}**: ${cr.rule_text} (${cr.vr_type})`);
686
- }
687
- lines.push('');
688
- }
689
- }
690
-
691
- // Relevant incidents based on file type
692
- const domainKeywords: Record<string, string[]> = {
693
- router: ['Schema', 'Migration', 'Database', 'API'],
694
- component: ['UI', 'Render', 'Component', 'UX'],
695
- middleware: ['Auth', 'Edge', 'Build'],
696
- migration: ['Schema', 'Migration', 'Database'],
697
- };
698
- const incidentKeywords = domainKeywords[fileType] || [];
699
- if (incidentKeywords.length > 0) {
700
- const kwPlaceholders = incidentKeywords.map(() => '?').join(' OR type LIKE ');
701
- const kwParams = incidentKeywords.map(k => `%${k}%`);
702
- const incidents = knowledgeDb.prepare(
703
- `SELECT incident_num, date, type, gap_found, prevention FROM knowledge_incidents WHERE type LIKE ${kwPlaceholders} ORDER BY incident_num DESC LIMIT 5`
704
- ).all(...kwParams) as { incident_num: number; date: string; type: string; gap_found: string; prevention: string }[];
705
-
706
- if (incidents.length > 0) {
707
- lines.push('## Related Incidents');
708
- for (const inc of incidents) {
709
- lines.push(`- **#${inc.incident_num}** (${inc.type}): ${inc.gap_found}`);
710
- }
711
- lines.push('');
712
- }
713
- }
714
-
715
- // Active corrections (behavioral learning)
716
- try {
717
- const corrections = knowledgeDb.prepare(`
718
- SELECT heading, content FROM knowledge_chunks
719
- WHERE metadata LIKE '%"is_correction":true%'
720
- ORDER BY CAST(json_extract(metadata, '$.date') AS TEXT) DESC
721
- LIMIT 3
722
- `).all() as { heading: string; content: string }[];
723
-
724
- if (corrections.length > 0) {
725
- lines.push('## Active Corrections');
726
- for (const c of corrections) {
727
- const ruleLine = c.content.split('\n').find(l => l.startsWith('Rule:')) || c.content.split('\n')[0];
728
- lines.push(`- ${c.heading}: ${ruleLine}`);
729
- }
730
- lines.push('');
731
- }
732
- } catch { /* corrections query failed — graceful degradation */ }
733
- }
734
- } finally {
735
- knowledgeDb.close();
736
- }
737
- } catch {
738
- // Knowledge DB not available — graceful degradation
739
- }
740
-
741
- // 8. Memory context — past bugs/fixes for this file
742
- let memDb: Database.Database | null = null;
743
- try {
744
- memDb = getMemoryDb();
745
- const fileObservations = memDb.prepare(`
746
- SELECT o.type, o.title, o.cr_rule, o.importance, o.created_at
747
- FROM observations o
748
- WHERE o.files_involved LIKE ?
749
- ORDER BY o.importance DESC, o.created_at_epoch DESC
750
- LIMIT 5
751
- `).all(`%${basename(file)}%`) as { type: string; title: string; cr_rule: string | null; importance: number; created_at: string }[];
752
-
753
- if (fileObservations.length > 0) {
754
- lines.push('## Past Observations (This File)');
755
- for (const obs of fileObservations) {
756
- const crTag = obs.cr_rule ? ` [${obs.cr_rule}]` : '';
757
- const impTag = obs.importance >= 4 ? ' **HIGH**' : '';
758
- lines.push(`- [${obs.type}] ${obs.title}${crTag}${impTag} (${obs.created_at})`);
759
- }
760
- lines.push('');
761
- }
762
-
763
- // Also check for failed attempts on this file
764
- const failures = memDb.prepare(`
765
- SELECT title, detail
766
- FROM observations
767
- WHERE type = 'failed_attempt' AND files_involved LIKE ?
768
- ORDER BY recurrence_count DESC
769
- LIMIT 3
770
- `).all(`%${basename(file)}%`) as { title: string; detail: string }[];
771
-
772
- if (failures.length > 0) {
773
- lines.push('## Failed Attempts (DO NOT RETRY)');
774
- for (const f of failures) {
775
- lines.push(`- ${f.title}`);
776
- }
777
- lines.push('');
778
- }
779
- } catch { /* Memory DB not available — graceful degradation */ }
780
- finally { memDb?.close(); }
781
-
782
- return text(lines.join('\n') || 'No context available for this file.');
783
- }
784
-
785
- function handleTrpcMap(args: Record<string, unknown>, dataDb: Database.Database): ToolResult {
786
- const lines: string[] = [];
787
-
788
- if (args.uncoupled) {
789
- const uncoupled = dataDb.prepare(
790
- `SELECT router_name, procedure_name, procedure_type, router_file FROM ${t('trpc_procedures')} WHERE has_ui_caller = 0 ORDER BY router_name, procedure_name`
791
- ).all() as { router_name: string; procedure_name: string; procedure_type: string; router_file: string }[];
792
-
793
- lines.push(`## Uncoupled Procedures (${uncoupled.length} total)`);
794
- lines.push('These procedures have ZERO UI callers.');
795
- lines.push('');
796
-
797
- let currentRouter = '';
798
- for (const proc of uncoupled) {
799
- if (proc.router_name !== currentRouter) {
800
- currentRouter = proc.router_name;
801
- lines.push(`### ${currentRouter} (${proc.router_file})`);
802
- }
803
- lines.push(`- ${proc.procedure_name} (${proc.procedure_type})`);
804
- }
805
- } else if (args.router) {
806
- const procs = dataDb.prepare(
807
- `SELECT id, procedure_name, procedure_type, has_ui_caller FROM ${t('trpc_procedures')} WHERE router_name = ? ORDER BY procedure_name`
808
- ).all(args.router as string) as { id: number; procedure_name: string; procedure_type: string; has_ui_caller: number }[];
809
-
810
- lines.push(`## Router: ${args.router} (${procs.length} procedures)`);
811
- lines.push('');
812
-
813
- for (const proc of procs) {
814
- const status = proc.has_ui_caller ? '' : ' [NO UI CALLERS]';
815
- lines.push(`### ${args.router}.${proc.procedure_name} (${proc.procedure_type})${status}`);
816
-
817
- const callSites = dataDb.prepare(
818
- `SELECT file, line, call_pattern FROM ${t('trpc_call_sites')} WHERE procedure_id = ?`
819
- ).all(proc.id) as { file: string; line: number; call_pattern: string }[];
820
-
821
- if (callSites.length > 0) {
822
- lines.push('UI Call Sites:');
823
- for (const site of callSites) {
824
- lines.push(` - ${site.file}:${site.line} -> ${site.call_pattern}`);
825
- }
826
- } else {
827
- lines.push('UI Call Sites: NONE');
828
- }
829
- lines.push('');
830
- }
831
- } else if (args.procedure) {
832
- const procs = dataDb.prepare(
833
- `SELECT id, router_name, router_file, procedure_type, has_ui_caller FROM ${t('trpc_procedures')} WHERE procedure_name = ? ORDER BY router_name`
834
- ).all(args.procedure as string) as { id: number; router_name: string; router_file: string; procedure_type: string; has_ui_caller: number }[];
835
-
836
- lines.push(`## Procedure "${args.procedure}" found in ${procs.length} routers`);
837
- lines.push('');
838
-
839
- for (const proc of procs) {
840
- lines.push(`### ${proc.router_name}.${args.procedure} (${proc.procedure_type})`);
841
- lines.push(`File: ${proc.router_file}`);
842
-
843
- const callSites = dataDb.prepare(
844
- `SELECT file, line, call_pattern FROM ${t('trpc_call_sites')} WHERE procedure_id = ?`
845
- ).all(proc.id) as { file: string; line: number; call_pattern: string }[];
846
-
847
- if (callSites.length > 0) {
848
- lines.push('UI Call Sites:');
849
- for (const site of callSites) {
850
- lines.push(` - ${site.file}:${site.line} -> ${site.call_pattern}`);
851
- }
852
- } else {
853
- lines.push('UI Call Sites: NONE');
854
- }
855
- lines.push('');
856
- }
857
- } else {
858
- const total = dataDb.prepare(`SELECT COUNT(*) as count FROM ${t('trpc_procedures')}`).get() as { count: number };
859
- const coupled = dataDb.prepare(`SELECT COUNT(*) as count FROM ${t('trpc_procedures')} WHERE has_ui_caller = 1`).get() as { count: number };
860
- const uncoupled = total.count - coupled.count;
861
-
862
- // P-H009 (plan-stage-c-high-batch): when the index is empty, return an
863
- // actionable remedy hint instead of bare "0" — previously fresh installs
864
- // saw "Total procedures: 0" and assumed the flagship tool was broken.
865
- if (total.count === 0) {
866
- lines.push('## tRPC Index Empty');
867
- lines.push('');
868
- lines.push('No tRPC procedures indexed yet. Either this repo has no tRPC');
869
- lines.push('routers, or the CodeGraph index has not been built. To rebuild:');
870
- lines.push('');
871
- lines.push(' npx massu sync');
872
- lines.push('');
873
- lines.push('If `massu sync` completes successfully but `trpc_map` still');
874
- lines.push('returns 0, the repo likely has no tRPC procedures (this is');
875
- lines.push('expected for non-tRPC stacks — try `schema` or `domains` tools).');
876
- } else {
877
- lines.push('## tRPC Procedure Summary');
878
- lines.push(`- Total procedures: ${total.count}`);
879
- lines.push(`- With UI callers: ${coupled.count}`);
880
- lines.push(`- Without UI callers: ${uncoupled}`);
881
- lines.push('');
882
- lines.push('Use { router: "name" } to see details for a specific router.');
883
- lines.push('Use { uncoupled: true } to see all procedures without UI callers.');
884
- }
885
- }
886
-
887
- return text(lines.join('\n'));
888
- }
889
-
890
- function handleCouplingCheck(args: Record<string, unknown>, dataDb: Database.Database, codegraphDb: Database.Database): ToolResult {
891
- const lines: string[] = [];
892
- const stagedFiles = args.staged_files as string[] | undefined;
893
-
894
- let uncoupledProcs;
895
- if (stagedFiles) {
896
- uncoupledProcs = dataDb.prepare(
897
- `SELECT router_name, procedure_name, procedure_type, router_file FROM ${t('trpc_procedures')} WHERE has_ui_caller = 0 AND router_file IN (${stagedFiles.map(() => '?').join(',')})`
898
- ).all(...stagedFiles) as { router_name: string; procedure_name: string; procedure_type: string; router_file: string }[];
899
- } else {
900
- uncoupledProcs = dataDb.prepare(
901
- `SELECT router_name, procedure_name, procedure_type, router_file FROM ${t('trpc_procedures')} WHERE has_ui_caller = 0`
902
- ).all() as { router_name: string; procedure_name: string; procedure_type: string; router_file: string }[];
903
- }
904
-
905
- lines.push('## Coupling Check Results');
906
- lines.push('');
907
-
908
- if (uncoupledProcs.length > 0) {
909
- lines.push(`### Uncoupled Procedures: ${uncoupledProcs.length}`);
910
- for (const proc of uncoupledProcs) {
911
- lines.push(`- ${proc.router_name}.${proc.procedure_name} (${proc.procedure_type}) in ${proc.router_file}`);
912
- }
913
- lines.push('');
914
- } else {
915
- lines.push('### Uncoupled Procedures: 0 (PASS)');
916
- lines.push('');
917
- }
918
-
919
- const allPages = codegraphDb.prepare(
920
- "SELECT path FROM files WHERE path LIKE 'src/app/%/page.tsx' OR path = 'src/app/page.tsx'"
921
- ).all() as { path: string }[];
922
-
923
- const pageImports = new Set<string>();
924
- for (const page of allPages) {
925
- const imports = dataDb.prepare(
926
- `SELECT target_file FROM ${t('imports')} WHERE source_file = ?`
927
- ).all(page.path) as { target_file: string }[];
928
- for (const imp of imports) {
929
- pageImports.add(imp.target_file);
930
- }
931
- }
932
-
933
- let componentFiles: { path: string }[];
934
- if (stagedFiles) {
935
- const placeholders = stagedFiles.map(() => '?').join(',');
936
- componentFiles = codegraphDb.prepare(
937
- `SELECT path FROM files WHERE path LIKE 'src/components/%' AND path IN (${placeholders})`
938
- ).all(...stagedFiles) as { path: string }[];
939
- } else {
940
- componentFiles = [];
941
- }
942
-
943
- const orphanComponents = componentFiles.filter(f => !pageImports.has(f.path));
944
- if (orphanComponents.length > 0) {
945
- lines.push(`### Orphan Components: ${orphanComponents.length}`);
946
- for (const comp of orphanComponents) {
947
- lines.push(`- ${comp.path} (not imported by any page.tsx)`);
948
- }
949
- lines.push('');
950
- }
951
-
952
- const totalIssues = uncoupledProcs.length + orphanComponents.length;
953
- lines.push(`### RESULT: ${totalIssues === 0 ? 'PASS' : `FAIL (${totalIssues} issues)`}`);
954
-
955
- return text(lines.join('\n'));
956
- }
957
-
958
- function handleImpact(file: string, dataDb: Database.Database, codegraphDb: Database.Database): ToolResult {
959
- const lines: string[] = [];
960
-
961
- lines.push(`## Impact Analysis: ${file}`);
962
- lines.push('');
963
-
964
- const affectedPages = findAffectedPages(dataDb, file);
965
-
966
- if (affectedPages.length > 0) {
967
- const portals = [...new Set(affectedPages.map(p => p.portal))];
968
- const allTables = [...new Set(affectedPages.flatMap(p => p.tables))];
969
- const allRouters = [...new Set(affectedPages.flatMap(p => p.routers))];
970
-
971
- lines.push(`### Pages Affected: ${affectedPages.length}`);
972
- for (const page of affectedPages) {
973
- lines.push(`- ${page.route} (${page.portal})`);
974
- }
975
- lines.push('');
976
-
977
- lines.push(`### Scopes Affected: ${portals.join(', ')}`);
978
- lines.push('');
979
-
980
- if (allRouters.length > 0) {
981
- lines.push(`### Routers Called (via hooks/components):`);
982
- for (const router of allRouters) {
983
- lines.push(`- ${router}`);
984
- }
985
- lines.push('');
986
- }
987
-
988
- if (allTables.length > 0) {
989
- lines.push(`### Database Tables:`);
990
- for (const table of allTables) {
991
- lines.push(`- ${table}`);
992
- }
993
- lines.push('');
994
- }
995
- } else {
996
- lines.push('No pages affected (file may not be in any page dependency chain).');
997
- lines.push('');
998
- }
999
-
1000
- const inMiddleware = isInMiddlewareTree(dataDb, file);
1001
- if (inMiddleware) {
1002
- lines.push('### WARNING: In Middleware Import Tree');
1003
- lines.push('Changes to this file affect Edge Runtime. No Node.js deps allowed.');
1004
- } else {
1005
- lines.push('### Middleware: NOT in middleware import tree (safe)');
1006
- }
1007
- lines.push('');
1008
-
1009
- const fileDomain = classifyFile(file);
1010
- lines.push(`### Domain: ${fileDomain}`);
1011
-
1012
- const imports = dataDb.prepare(
1013
- `SELECT target_file FROM ${t('imports')} WHERE source_file = ?`
1014
- ).all(file) as { target_file: string }[];
1015
-
1016
- const crossings: string[] = [];
1017
- for (const imp of imports) {
1018
- const targetDomain = classifyFile(imp.target_file);
1019
- if (targetDomain !== fileDomain && targetDomain !== 'Unknown') {
1020
- crossings.push(`${imp.target_file} (${targetDomain})`);
1021
- }
1022
- }
1023
-
1024
- if (crossings.length > 0) {
1025
- lines.push(`### Domain Crossings: ${crossings.length}`);
1026
- for (const crossing of crossings) {
1027
- lines.push(`- -> ${crossing}`);
1028
- }
1029
- }
1030
-
1031
- return text(lines.join('\n'));
1032
- }
1033
-
1034
- function handleDomains(args: Record<string, unknown>, dataDb: Database.Database, codegraphDb: Database.Database): ToolResult {
1035
- const lines: string[] = [];
1036
- const domains = getConfig().domains;
1037
-
1038
- if (args.file) {
1039
- const file = args.file as string;
1040
- const domain = classifyFile(file);
1041
- lines.push(`## ${file}`);
1042
- lines.push(`Domain: ${domain}`);
1043
-
1044
- const domainConfig = domains.find(d => d.name === domain);
1045
- if (domainConfig) {
1046
- lines.push(`Allowed imports from: ${domainConfig.allowedImportsFrom.join(', ') || 'any domain (system)'}`);
1047
- }
1048
- } else if (args.crossings) {
1049
- const crossings = findCrossDomainImports(dataDb);
1050
- const violations = crossings.filter(c => !c.allowed);
1051
- const allowed = crossings.filter(c => c.allowed);
1052
-
1053
- lines.push(`## Cross-Domain Import Analysis`);
1054
- lines.push(`Total crossings: ${crossings.length}`);
1055
- lines.push(`Violations: ${violations.length}`);
1056
- lines.push(`Allowed: ${allowed.length}`);
1057
- lines.push('');
1058
-
1059
- if (violations.length > 0) {
1060
- lines.push('### Violations (Disallowed Cross-Domain Imports)');
1061
- for (const v of violations.slice(0, 50)) {
1062
- lines.push(`- ${v.source} (${v.sourceDomain}) -> ${v.target} (${v.targetDomain})`);
1063
- }
1064
- if (violations.length > 50) {
1065
- lines.push(`... and ${violations.length - 50} more`);
1066
- }
1067
- }
1068
- } else if (args.domain) {
1069
- const domainName = args.domain as string;
1070
- const files = getFilesInDomain(dataDb, codegraphDb, domainName);
1071
- const config = domains.find(d => d.name === domainName);
1072
-
1073
- lines.push(`## Domain: ${domainName}`);
1074
- if (config) {
1075
- lines.push(`Allowed imports from: ${config.allowedImportsFrom.join(', ') || 'any domain (system)'}`);
1076
- }
1077
- lines.push('');
1078
-
1079
- lines.push(`### Routers (${files.routers.length})`);
1080
- for (const r of files.routers) lines.push(`- ${r}`);
1081
- lines.push('');
1082
-
1083
- lines.push(`### Pages (${files.pages.length})`);
1084
- for (const p of files.pages) lines.push(`- ${p}`);
1085
- lines.push('');
1086
-
1087
- lines.push(`### Components (${files.components.length})`);
1088
- for (const c of files.components.slice(0, 30)) lines.push(`- ${c}`);
1089
- if (files.components.length > 30) lines.push(`... and ${files.components.length - 30} more`);
1090
- } else {
1091
- lines.push('## Domain Summary');
1092
- for (const domain of domains) {
1093
- lines.push(`- **${domain.name}**: ${domain.routers.length} router patterns, imports from: ${domain.allowedImportsFrom.join(', ') || 'any'}`);
1094
- }
1095
- }
1096
-
1097
- return text(lines.join('\n'));
1098
- }
1099
-
1100
- function handleSchema(args: Record<string, unknown>): ToolResult {
1101
- const lines: string[] = [];
1102
- const models = parsePrismaSchema();
1103
-
1104
- if (args.mismatches) {
1105
- const mismatches = detectMismatches(models);
1106
-
1107
- lines.push(`## Schema Mismatches Detected: ${mismatches.length}`);
1108
- lines.push('');
1109
-
1110
- for (const m of mismatches) {
1111
- lines.push(`### ${m.table}.${m.codeColumn} [${m.severity}]`);
1112
- lines.push(`Code uses "${m.codeColumn}" but this column does NOT exist in the schema.`);
1113
- lines.push(`Files affected:`);
1114
- for (const f of m.files) {
1115
- lines.push(` - ${f}`);
1116
- }
1117
- lines.push('');
1118
- }
1119
-
1120
- if (mismatches.length === 0) {
1121
- lines.push('No known mismatches detected in code.');
1122
- }
1123
- } else if (args.table) {
1124
- const tableName = args.table as string;
1125
- const model = models.find(m => m.tableName === tableName || m.name === tableName);
1126
-
1127
- if (!model) {
1128
- return text(`Model/table "${tableName}" not found in Prisma schema.`);
1129
- }
1130
-
1131
- lines.push(`## ${model.name} (table: ${model.tableName})`);
1132
- lines.push('');
1133
- lines.push('### Fields');
1134
- for (const field of model.fields) {
1135
- const nullable = field.nullable ? '?' : '';
1136
- const relation = field.isRelation ? ' [RELATION]' : '';
1137
- lines.push(`- ${field.name}: ${field.type}${nullable}${relation}`);
1138
- }
1139
- lines.push('');
1140
-
1141
- const usage = findColumnUsageInRouters(model.tableName);
1142
- if (usage.size > 0) {
1143
- lines.push('### Column Usage in Routers');
1144
- for (const [col, usages] of usage) {
1145
- const validField = model.fields.find(f => f.name === col);
1146
- const status = validField ? '' : ' [NOT IN SCHEMA]';
1147
- lines.push(`- ${col}${status}: ${usages.length} references`);
1148
- }
1149
- }
1150
- } else if (args.verify) {
1151
- const file = args.verify as string;
1152
- lines.push(`## Schema Verification: ${file}`);
1153
- lines.push('Checking all column references against Prisma schema...');
1154
- lines.push('');
1155
-
1156
- const projectRoot = getProjectRoot();
1157
- const absPath = ensureWithinRoot(resolve(projectRoot, file), projectRoot);
1158
-
1159
- if (!existsSync(absPath)) {
1160
- return text(`File not found: ${file}`);
1161
- }
1162
-
1163
- const source = readFileSync(absPath, 'utf-8');
1164
-
1165
- // Use configurable db access pattern
1166
- const config = getConfig();
1167
- const dbPattern = config.dbAccessPattern ?? 'ctx.db.{table}';
1168
- const regexStr = dbPattern
1169
- .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1170
- .replace('\\{table\\}', '(\\w+)');
1171
- const tableRegex = new RegExp(regexStr + '\\.', 'g');
1172
- const tableRefs = new Set<string>();
1173
- let match;
1174
- while ((match = tableRegex.exec(source)) !== null) {
1175
- tableRefs.add(match[1]);
1176
- }
1177
-
1178
- for (const table of tableRefs) {
1179
- const model = models.find(m => m.tableName === table || m.name.toLowerCase() === table);
1180
- if (!model) {
1181
- lines.push(`### ${table}: MODEL NOT FOUND IN SCHEMA`);
1182
- continue;
1183
- }
1184
-
1185
- lines.push(`### ${table} (model: ${model.name})`);
1186
- const fieldNames = new Set(model.fields.map(f => f.name));
1187
- lines.push(`Schema has ${fieldNames.size} fields.`);
1188
- lines.push('');
1189
- }
1190
- } else {
1191
- lines.push(`## Prisma Schema Summary`);
1192
- lines.push(`Models: ${models.length}`);
1193
- lines.push('');
1194
-
1195
- const mismatches = detectMismatches(models);
1196
- if (mismatches.length > 0) {
1197
- lines.push(`### Active Mismatches: ${mismatches.length}`);
1198
- for (const m of mismatches) {
1199
- lines.push(`- ${m.table}.${m.codeColumn} [${m.severity}]`);
1200
- }
1201
- }
1202
- }
1203
-
1204
- return text(lines.join('\n'));
1205
- }