@massu/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +71 -0
  2. package/dist/hooks/cost-tracker.js +127 -11493
  3. package/dist/hooks/post-edit-context.js +125 -11491
  4. package/dist/hooks/post-tool-use.js +127 -11493
  5. package/dist/hooks/pre-compact.js +127 -11493
  6. package/dist/hooks/pre-delete-check.js +126 -11492
  7. package/dist/hooks/quality-event.js +127 -11493
  8. package/dist/hooks/session-end.js +127 -11493
  9. package/dist/hooks/session-start.js +127 -11493
  10. package/dist/hooks/user-prompt.js +127 -11493
  11. package/package.json +9 -8
  12. package/src/__tests__/adr-generator.test.ts +260 -0
  13. package/src/__tests__/analytics.test.ts +282 -0
  14. package/src/__tests__/audit-trail.test.ts +382 -0
  15. package/src/__tests__/backfill-sessions.test.ts +690 -0
  16. package/src/__tests__/cli.test.ts +290 -0
  17. package/src/__tests__/cloud-sync.test.ts +261 -0
  18. package/src/__tests__/config-sections.test.ts +359 -0
  19. package/src/__tests__/config.test.ts +732 -0
  20. package/src/__tests__/cost-tracker.test.ts +348 -0
  21. package/src/__tests__/db.test.ts +177 -0
  22. package/src/__tests__/dependency-scorer.test.ts +325 -0
  23. package/src/__tests__/docs-integration.test.ts +178 -0
  24. package/src/__tests__/docs-tools.test.ts +199 -0
  25. package/src/__tests__/domains.test.ts +236 -0
  26. package/src/__tests__/hooks.test.ts +221 -0
  27. package/src/__tests__/import-resolver.test.ts +95 -0
  28. package/src/__tests__/integration/path-traversal.test.ts +134 -0
  29. package/src/__tests__/integration/pricing-consistency.test.ts +88 -0
  30. package/src/__tests__/integration/tool-registration.test.ts +146 -0
  31. package/src/__tests__/memory-db.test.ts +404 -0
  32. package/src/__tests__/memory-enhancements.test.ts +316 -0
  33. package/src/__tests__/memory-tools.test.ts +199 -0
  34. package/src/__tests__/middleware-tree.test.ts +177 -0
  35. package/src/__tests__/observability-tools.test.ts +595 -0
  36. package/src/__tests__/observability.test.ts +437 -0
  37. package/src/__tests__/observation-extractor.test.ts +167 -0
  38. package/src/__tests__/page-deps.test.ts +60 -0
  39. package/src/__tests__/prompt-analyzer.test.ts +298 -0
  40. package/src/__tests__/regression-detector.test.ts +295 -0
  41. package/src/__tests__/rules.test.ts +87 -0
  42. package/src/__tests__/schema-mapper.test.ts +29 -0
  43. package/src/__tests__/security-scorer.test.ts +238 -0
  44. package/src/__tests__/security-utils.test.ts +175 -0
  45. package/src/__tests__/sentinel-db.test.ts +491 -0
  46. package/src/__tests__/sentinel-scanner.test.ts +750 -0
  47. package/src/__tests__/sentinel-tools.test.ts +324 -0
  48. package/src/__tests__/sentinel-types.test.ts +750 -0
  49. package/src/__tests__/server.test.ts +452 -0
  50. package/src/__tests__/session-archiver.test.ts +524 -0
  51. package/src/__tests__/session-state-generator.test.ts +900 -0
  52. package/src/__tests__/team-knowledge.test.ts +327 -0
  53. package/src/__tests__/tools.test.ts +340 -0
  54. package/src/__tests__/transcript-parser.test.ts +195 -0
  55. package/src/__tests__/trpc-index.test.ts +25 -0
  56. package/src/__tests__/validate-features-runner.test.ts +517 -0
  57. package/src/__tests__/validation-engine.test.ts +300 -0
  58. package/src/adr-generator.ts +285 -0
  59. package/src/analytics.ts +367 -0
  60. package/src/audit-trail.ts +443 -0
  61. package/src/backfill-sessions.ts +180 -0
  62. package/src/cli.ts +105 -0
  63. package/src/cloud-sync.ts +194 -0
  64. package/src/commands/doctor.ts +300 -0
  65. package/src/commands/init.ts +399 -0
  66. package/src/commands/install-hooks.ts +26 -0
  67. package/src/config.ts +357 -0
  68. package/src/core-tools.ts +685 -0
  69. package/src/cost-tracker.ts +350 -0
  70. package/src/db.ts +233 -0
  71. package/src/dependency-scorer.ts +330 -0
  72. package/src/docs-map.json +100 -0
  73. package/src/docs-tools.ts +514 -0
  74. package/src/domains.ts +181 -0
  75. package/src/hooks/cost-tracker.ts +66 -0
  76. package/src/hooks/intent-suggester.ts +131 -0
  77. package/src/hooks/post-edit-context.ts +91 -0
  78. package/src/hooks/post-tool-use.ts +175 -0
  79. package/src/hooks/pre-compact.ts +146 -0
  80. package/src/hooks/pre-delete-check.ts +153 -0
  81. package/src/hooks/quality-event.ts +127 -0
  82. package/src/hooks/security-gate.ts +121 -0
  83. package/src/hooks/session-end.ts +467 -0
  84. package/src/hooks/session-start.ts +210 -0
  85. package/src/hooks/user-prompt.ts +91 -0
  86. package/src/import-resolver.ts +224 -0
  87. package/src/memory-db.ts +48 -0
  88. package/src/memory-queries.ts +804 -0
  89. package/src/memory-schema.ts +546 -0
  90. package/src/memory-tools.ts +392 -0
  91. package/src/middleware-tree.ts +70 -0
  92. package/src/observability-tools.ts +332 -0
  93. package/src/observation-extractor.ts +411 -0
  94. package/src/page-deps.ts +283 -0
  95. package/src/prompt-analyzer.ts +325 -0
  96. package/src/regression-detector.ts +313 -0
  97. package/src/rules.ts +57 -0
  98. package/src/schema-mapper.ts +232 -0
  99. package/src/security-scorer.ts +398 -0
  100. package/src/security-utils.ts +133 -0
  101. package/src/sentinel-db.ts +623 -0
  102. package/src/sentinel-scanner.ts +405 -0
  103. package/src/sentinel-tools.ts +515 -0
  104. package/src/sentinel-types.ts +140 -0
  105. package/src/server.ts +190 -0
  106. package/src/session-archiver.ts +112 -0
  107. package/src/session-state-generator.ts +174 -0
  108. package/src/team-knowledge.ts +400 -0
  109. package/src/tool-helpers.ts +41 -0
  110. package/src/tools.ts +111 -0
  111. package/src/transcript-parser.ts +458 -0
  112. package/src/trpc-index.ts +214 -0
  113. package/src/validate-features-runner.ts +107 -0
  114. package/src/validation-engine.ts +351 -0
@@ -0,0 +1,300 @@
1
+ // Copyright (c) 2026 Massu. All rights reserved.
2
+ // Licensed under BSL 1.1 - see LICENSE file for details.
3
+
4
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
5
+ import Database from 'better-sqlite3';
6
+ import { mkdirSync, writeFileSync, rmSync } from 'fs';
7
+ import { join } from 'path';
8
+ import {
9
+ getValidationToolDefinitions,
10
+ isValidationTool,
11
+ validateFile,
12
+ storeValidationResult,
13
+ handleValidationToolCall,
14
+ type ValidationCheck,
15
+ } from '../validation-engine.ts';
16
+
17
+ function createTestDb(): Database.Database {
18
+ const db = new Database(':memory:');
19
+ db.pragma('journal_mode = WAL');
20
+
21
+ db.exec(`
22
+ CREATE TABLE sessions (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ session_id TEXT UNIQUE NOT NULL,
25
+ started_at TEXT NOT NULL,
26
+ started_at_epoch INTEGER NOT NULL
27
+ );
28
+
29
+ CREATE TABLE validation_results (
30
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
31
+ session_id TEXT,
32
+ file_path TEXT NOT NULL,
33
+ validation_type TEXT NOT NULL,
34
+ passed INTEGER NOT NULL DEFAULT 1,
35
+ details TEXT,
36
+ rules_violated TEXT,
37
+ created_at TEXT DEFAULT (datetime('now'))
38
+ );
39
+ `);
40
+
41
+ return db;
42
+ }
43
+
44
+ describe('validation-engine', () => {
45
+ let db: Database.Database;
46
+ let testDir: string;
47
+
48
+ beforeEach(() => {
49
+ db = createTestDb();
50
+ testDir = join('/tmp', 'massu-test-' + Math.random().toString(36).slice(2));
51
+ mkdirSync(testDir, { recursive: true });
52
+ });
53
+
54
+ afterEach(() => {
55
+ db.close();
56
+ try {
57
+ rmSync(testDir, { recursive: true, force: true });
58
+ } catch {
59
+ // Ignore cleanup errors
60
+ }
61
+ });
62
+
63
+ describe('getValidationToolDefinitions', () => {
64
+ it('should return tool definitions for validation tools', () => {
65
+ const defs = getValidationToolDefinitions();
66
+ expect(defs.length).toBe(2);
67
+
68
+ const names = defs.map(d => d.name);
69
+ expect(names.some(n => n.includes('validation_check'))).toBe(true);
70
+ expect(names.some(n => n.includes('validation_report'))).toBe(true);
71
+
72
+ for (const def of defs) {
73
+ expect(def.name).toBeTruthy();
74
+ expect(def.description).toBeTruthy();
75
+ expect(def.inputSchema).toBeTruthy();
76
+ expect(def.inputSchema.type).toBe('object');
77
+ }
78
+ });
79
+ });
80
+
81
+ describe('isValidationTool', () => {
82
+ it('should return true for validation tools', () => {
83
+ expect(isValidationTool('massu_validation_check')).toBe(true);
84
+ expect(isValidationTool('massu_validation_report')).toBe(true);
85
+ });
86
+
87
+ it('should return false for non-validation tools', () => {
88
+ expect(isValidationTool('massu_cost_session')).toBe(false);
89
+ expect(isValidationTool('massu_quality_score')).toBe(false);
90
+ expect(isValidationTool('random_tool')).toBe(false);
91
+ });
92
+
93
+ it('should handle base names without prefix', () => {
94
+ expect(isValidationTool('validation_check')).toBe(true);
95
+ expect(isValidationTool('validation_report')).toBe(true);
96
+ });
97
+ });
98
+
99
+ describe('validateFile', () => {
100
+ it('should return error check for non-existent file', () => {
101
+ const filePath = join(testDir, 'nonexistent.ts');
102
+ const checks = validateFile(filePath, testDir);
103
+
104
+ expect(checks.length).toBeGreaterThan(0);
105
+ const fileCheck = checks.find(c => c.name === 'file_exists');
106
+ expect(fileCheck).toBeDefined();
107
+ expect(fileCheck?.severity).toBe('error');
108
+ });
109
+
110
+ it('should block path traversal attempts', () => {
111
+ const filePath = '../../../etc/passwd';
112
+ const checks = validateFile(filePath, testDir);
113
+
114
+ expect(checks.length).toBeGreaterThan(0);
115
+ const pathCheck = checks.find(c => c.name === 'path_traversal');
116
+ expect(pathCheck).toBeDefined();
117
+ expect(pathCheck?.severity).toBe('critical');
118
+ });
119
+
120
+ it('should validate existing file', () => {
121
+ const filePath = join(testDir, 'test.ts');
122
+ writeFileSync(filePath, `
123
+ // Simple test file
124
+ export function hello() {
125
+ return "world";
126
+ }
127
+ `.trim());
128
+
129
+ const checks = validateFile(filePath, testDir);
130
+
131
+ // Should not have critical errors
132
+ const criticalErrors = checks.filter(c => c.severity === 'critical' || c.severity === 'error');
133
+ expect(criticalErrors.length).toBe(0);
134
+ });
135
+
136
+ it('should detect import hallucinations', () => {
137
+ const filePath = join(testDir, 'imports.ts');
138
+ writeFileSync(filePath, `
139
+ import { something } from './nonexistent.ts';
140
+ import { other } from '@/fake-module.ts';
141
+ `.trim());
142
+
143
+ const checks = validateFile(filePath, testDir);
144
+
145
+ const importErrors = checks.filter(c => c.name === 'import_hallucination');
146
+ expect(importErrors.length).toBeGreaterThan(0);
147
+ expect(importErrors[0].severity).toBe('error');
148
+ });
149
+ });
150
+
151
+ describe('storeValidationResult', () => {
152
+ it('should store validation result in database', () => {
153
+ const sessionId = 'test-session-1';
154
+ db.prepare('INSERT INTO sessions (session_id, started_at, started_at_epoch) VALUES (?, ?, ?)').run(
155
+ sessionId,
156
+ new Date().toISOString(),
157
+ Math.floor(Date.now() / 1000)
158
+ );
159
+
160
+ const checks: ValidationCheck[] = [
161
+ {
162
+ name: 'import_hallucination',
163
+ severity: 'error',
164
+ message: 'Import not found',
165
+ line: 1,
166
+ file: 'test.ts',
167
+ },
168
+ {
169
+ name: 'rule_compliance',
170
+ severity: 'warning',
171
+ message: 'Rule violation',
172
+ file: 'test.ts',
173
+ },
174
+ ];
175
+
176
+ storeValidationResult(db, 'test.ts', checks, sessionId);
177
+
178
+ const results = db.prepare('SELECT * FROM validation_results WHERE session_id = ?').all(sessionId) as Array<Record<string, unknown>>;
179
+ expect(results.length).toBe(1);
180
+ expect(results[0].file_path).toBe('test.ts');
181
+ expect(results[0].passed).toBe(0); // Has errors
182
+ expect(results[0].details).toBeTruthy();
183
+
184
+ const details = JSON.parse(results[0].details as string);
185
+ expect(details.length).toBe(2);
186
+ });
187
+
188
+ it('should mark as passed when no errors', () => {
189
+ const sessionId = 'test-session-2';
190
+ db.prepare('INSERT INTO sessions (session_id, started_at, started_at_epoch) VALUES (?, ?, ?)').run(
191
+ sessionId,
192
+ new Date().toISOString(),
193
+ Math.floor(Date.now() / 1000)
194
+ );
195
+
196
+ const checks: ValidationCheck[] = [
197
+ {
198
+ name: 'rule_applicable',
199
+ severity: 'info',
200
+ message: 'Rule applies',
201
+ file: 'test.ts',
202
+ },
203
+ ];
204
+
205
+ storeValidationResult(db, 'test.ts', checks, sessionId);
206
+
207
+ const results = db.prepare('SELECT * FROM validation_results WHERE session_id = ?').all(sessionId) as Array<Record<string, unknown>>;
208
+ expect(results.length).toBe(1);
209
+ expect(results[0].passed).toBe(1); // No errors
210
+ });
211
+
212
+ it('should record violated rules', () => {
213
+ const sessionId = 'test-session-3';
214
+ db.prepare('INSERT INTO sessions (session_id, started_at, started_at_epoch) VALUES (?, ?, ?)').run(
215
+ sessionId,
216
+ new Date().toISOString(),
217
+ Math.floor(Date.now() / 1000)
218
+ );
219
+
220
+ const checks: ValidationCheck[] = [
221
+ {
222
+ name: 'import_hallucination',
223
+ severity: 'error',
224
+ message: 'Import not found',
225
+ file: 'test.ts',
226
+ },
227
+ {
228
+ name: 'db_access_pattern',
229
+ severity: 'warning',
230
+ message: 'Wrong pattern',
231
+ file: 'test.ts',
232
+ },
233
+ ];
234
+
235
+ storeValidationResult(db, 'test.ts', checks, sessionId);
236
+
237
+ const results = db.prepare('SELECT * FROM validation_results WHERE session_id = ?').all(sessionId) as Array<Record<string, unknown>>;
238
+ expect(results[0].rules_violated).toBeTruthy();
239
+ expect((results[0].rules_violated as string).includes('import_hallucination')).toBe(true);
240
+ expect((results[0].rules_violated as string).includes('db_access_pattern')).toBe(true);
241
+ });
242
+ });
243
+
244
+ describe('handleValidationToolCall', () => {
245
+ it('should handle validation_check tool call for non-existent file', () => {
246
+ const filePath = join(testDir, 'nonexistent.ts');
247
+ const result = handleValidationToolCall('massu_validation_check', { file: filePath }, db);
248
+
249
+ expect(result.content).toBeDefined();
250
+ expect(result.content.length).toBeGreaterThan(0);
251
+ expect(result.content[0].type).toBe('text');
252
+ const text = result.content[0].text;
253
+ expect(text).toContain('Validation');
254
+ expect(text).toContain('Errors');
255
+ });
256
+
257
+ it('should return error for missing file parameter', () => {
258
+ const result = handleValidationToolCall('massu_validation_check', {}, db);
259
+
260
+ expect(result.content).toBeDefined();
261
+ expect(result.content[0].type).toBe('text');
262
+ expect(result.content[0].text).toContain('Usage');
263
+ });
264
+
265
+ it('should handle validation_report tool call', () => {
266
+ const sessionId = 'report-session';
267
+ db.prepare('INSERT INTO sessions (session_id, started_at, started_at_epoch) VALUES (?, ?, ?)').run(
268
+ sessionId,
269
+ new Date().toISOString(),
270
+ Math.floor(Date.now() / 1000)
271
+ );
272
+
273
+ const checks: ValidationCheck[] = [
274
+ {
275
+ name: 'test_error',
276
+ severity: 'error',
277
+ message: 'Test error',
278
+ file: 'test.ts',
279
+ },
280
+ ];
281
+
282
+ storeValidationResult(db, 'test.ts', checks, sessionId);
283
+
284
+ const result = handleValidationToolCall('massu_validation_report', { days: 7 }, db);
285
+
286
+ expect(result.content).toBeDefined();
287
+ expect(result.content[0].type).toBe('text');
288
+ const text = result.content[0].text;
289
+ expect(text).toContain('Validation Report');
290
+ });
291
+
292
+ it('should handle unknown tool name', () => {
293
+ const result = handleValidationToolCall('massu_unknown_validation_tool', {}, db);
294
+
295
+ expect(result.content).toBeDefined();
296
+ expect(result.content[0].type).toBe('text');
297
+ expect(result.content[0].text).toContain('Unknown validation tool');
298
+ });
299
+ });
300
+ });
@@ -0,0 +1,285 @@
1
+ // Copyright (c) 2026 Massu. All rights reserved.
2
+ // Licensed under BSL 1.1 - see LICENSE file for details.
3
+
4
+ import type Database from 'better-sqlite3';
5
+ import type { ToolDefinition, ToolResult } from './tool-helpers.ts';
6
+ import { p, text } from './tool-helpers.ts';
7
+ import { getConfig } from './config.ts';
8
+
9
+ // ============================================================
10
+ // ADR (Architecture Decision Record) Auto-Generation
11
+ // ============================================================
12
+
13
+ /** Default decision detection phrases. Configurable via governance.adr.detection_phrases */
14
+ const DEFAULT_DETECTION_PHRASES = ['chose', 'decided', 'switching to', 'moving from', 'going with'];
15
+
16
+ /**
17
+ * Get decision detection phrases from config or defaults.
18
+ */
19
+ function getDetectionPhrases(): string[] {
20
+ return getConfig().governance?.adr?.detection_phrases ?? DEFAULT_DETECTION_PHRASES;
21
+ }
22
+
23
+ /**
24
+ * Detect decision patterns in text.
25
+ */
26
+ export function detectDecisionPatterns(text: string): boolean {
27
+ const phrases = getDetectionPhrases();
28
+ const lower = text.toLowerCase();
29
+ return phrases.some(phrase => lower.includes(phrase));
30
+ }
31
+
32
+ /**
33
+ * Extract alternatives from a decision description.
34
+ */
35
+ export function extractAlternatives(description: string): string[] {
36
+ const alternatives: string[] = [];
37
+
38
+ // Pattern: "X over Y"
39
+ const overMatch = description.match(/(\w[\w\s-]+)\s+over\s+(\w[\w\s-]+)/i);
40
+ if (overMatch) {
41
+ alternatives.push(overMatch[1].trim());
42
+ alternatives.push(overMatch[2].trim());
43
+ }
44
+
45
+ // Pattern: "X instead of Y"
46
+ const insteadMatch = description.match(/(\w[\w\s-]+)\s+instead\s+of\s+(\w[\w\s-]+)/i);
47
+ if (insteadMatch) {
48
+ alternatives.push(insteadMatch[1].trim());
49
+ alternatives.push(insteadMatch[2].trim());
50
+ }
51
+
52
+ // Pattern: "switching from X to Y"
53
+ const switchMatch = description.match(/switching\s+from\s+(\w[\w\s-]+)\s+to\s+(\w[\w\s-]+)/i);
54
+ if (switchMatch) {
55
+ alternatives.push(switchMatch[2].trim()); // Chosen
56
+ alternatives.push(switchMatch[1].trim()); // Rejected
57
+ }
58
+
59
+ return [...new Set(alternatives)];
60
+ }
61
+
62
+ /**
63
+ * Store an architecture decision.
64
+ */
65
+ export function storeDecision(
66
+ db: Database.Database,
67
+ decision: {
68
+ title: string;
69
+ context: string;
70
+ decision: string;
71
+ alternatives: string[];
72
+ consequences: string;
73
+ sessionId?: string;
74
+ status?: string;
75
+ }
76
+ ): number {
77
+ const result = db.prepare(`
78
+ INSERT INTO architecture_decisions
79
+ (title, context, decision, alternatives, consequences, session_id, status)
80
+ VALUES (?, ?, ?, ?, ?, ?, ?)
81
+ `).run(
82
+ decision.title,
83
+ decision.context,
84
+ decision.decision,
85
+ JSON.stringify(decision.alternatives),
86
+ decision.consequences,
87
+ decision.sessionId ?? null,
88
+ decision.status ?? 'accepted'
89
+ );
90
+
91
+ return Number(result.lastInsertRowid);
92
+ }
93
+
94
+ // ============================================================
95
+ // MCP Tool Definitions & Handlers
96
+ // ============================================================
97
+
98
+ export function getAdrToolDefinitions(): ToolDefinition[] {
99
+ return [
100
+ {
101
+ name: p('adr_list'),
102
+ description: 'List all recorded architecture decisions. Filter by status or search text.',
103
+ inputSchema: {
104
+ type: 'object',
105
+ properties: {
106
+ status: { type: 'string', description: 'Filter by status: accepted, superseded, deprecated' },
107
+ search: { type: 'string', description: 'Search in title and context' },
108
+ },
109
+ required: [],
110
+ },
111
+ },
112
+ {
113
+ name: p('adr_detail'),
114
+ description: 'Get full details of a specific architecture decision by ID.',
115
+ inputSchema: {
116
+ type: 'object',
117
+ properties: {
118
+ id: { type: 'number', description: 'ADR ID' },
119
+ },
120
+ required: ['id'],
121
+ },
122
+ },
123
+ {
124
+ name: p('adr_create'),
125
+ description: 'Generate an ADR from a description. Extracts alternatives, context, and consequences.',
126
+ inputSchema: {
127
+ type: 'object',
128
+ properties: {
129
+ title: { type: 'string', description: 'Decision title' },
130
+ context: { type: 'string', description: 'Why was this decision needed?' },
131
+ decision: { type: 'string', description: 'What was decided?' },
132
+ consequences: { type: 'string', description: 'What are the consequences?' },
133
+ },
134
+ required: ['title', 'decision'],
135
+ },
136
+ },
137
+ ];
138
+ }
139
+
140
+ const ADR_BASE_NAMES = new Set(['adr_list', 'adr_detail', 'adr_create']);
141
+
142
+ export function isAdrTool(name: string): boolean {
143
+ const pfx = getConfig().toolPrefix + '_';
144
+ const baseName = name.startsWith(pfx) ? name.slice(pfx.length) : name;
145
+ return ADR_BASE_NAMES.has(baseName);
146
+ }
147
+
148
+ export function handleAdrToolCall(
149
+ name: string,
150
+ args: Record<string, unknown>,
151
+ memoryDb: Database.Database
152
+ ): ToolResult {
153
+ try {
154
+ const pfx = getConfig().toolPrefix + '_';
155
+ const baseName = name.startsWith(pfx) ? name.slice(pfx.length) : name;
156
+
157
+ switch (baseName) {
158
+ case 'adr_list':
159
+ return handleAdrList(args, memoryDb);
160
+ case 'adr_detail':
161
+ return handleAdrDetail(args, memoryDb);
162
+ case 'adr_create':
163
+ return handleAdrGenerate(args, memoryDb);
164
+ default:
165
+ return text(`Unknown ADR tool: ${name}`);
166
+ }
167
+ } catch (error) {
168
+ return text(`Error in ${name}: ${error instanceof Error ? error.message : String(error)}\n\nUsage: ${p('adr_list')} {}, ${p('adr_create')} { title: "...", decision: "..." }`);
169
+ }
170
+ }
171
+
172
+ function handleAdrList(args: Record<string, unknown>, db: Database.Database): ToolResult {
173
+ let sql = 'SELECT id, title, status, created_at FROM architecture_decisions WHERE 1=1';
174
+ const params: string[] = [];
175
+
176
+ if (args.status) {
177
+ sql += ' AND status = ?';
178
+ params.push(args.status as string);
179
+ }
180
+
181
+ if (args.search) {
182
+ sql += ' AND (title LIKE ? OR context LIKE ?)';
183
+ const searchTerm = `%${args.search}%`;
184
+ params.push(searchTerm, searchTerm);
185
+ }
186
+
187
+ sql += ' ORDER BY created_at DESC';
188
+
189
+ const decisions = db.prepare(sql).all(...params) as Array<Record<string, unknown>>;
190
+
191
+ if (decisions.length === 0) {
192
+ return text(`No architecture decisions found. Decisions are recorded when you use ${p('adr_create')} during design discussions. Try: ${p('adr_create')} { title: "Use Redis for caching", decision: "We chose Redis over Memcached" }`);
193
+ }
194
+
195
+ const lines = [
196
+ `## Architecture Decisions (${decisions.length})`,
197
+ '',
198
+ '| ID | Title | Status | Date |',
199
+ '|----|-------|--------|------|',
200
+ ];
201
+
202
+ for (const d of decisions) {
203
+ lines.push(`| ${d.id} | ${d.title} | ${d.status} | ${(d.created_at as string).slice(0, 10)} |`);
204
+ }
205
+
206
+ return text(lines.join('\n'));
207
+ }
208
+
209
+ function handleAdrDetail(args: Record<string, unknown>, db: Database.Database): ToolResult {
210
+ const id = args.id as number;
211
+ if (!id) return text(`Usage: ${p('adr_detail')} { id: 1 } - Get full details of an architecture decision.`);
212
+
213
+ const decision = db.prepare(
214
+ 'SELECT * FROM architecture_decisions WHERE id = ?'
215
+ ).get(id) as Record<string, unknown> | undefined;
216
+
217
+ if (!decision) {
218
+ return text(`ADR #${id} not found. Decisions are stored when created via ${p('adr_create')}. Try: ${p('adr_list')} {} to see all recorded decisions.`);
219
+ }
220
+
221
+ const alternatives = JSON.parse((decision.alternatives as string) || '[]') as string[];
222
+
223
+ const lines = [
224
+ `# ADR-${decision.id}: ${decision.title}`,
225
+ `Status: ${decision.status}`,
226
+ `Date: ${(decision.created_at as string).slice(0, 10)}`,
227
+ '',
228
+ '## Context',
229
+ decision.context as string || 'Not specified',
230
+ '',
231
+ '## Decision',
232
+ decision.decision as string,
233
+ '',
234
+ ];
235
+
236
+ if (alternatives.length > 0) {
237
+ lines.push('## Alternatives Considered');
238
+ for (const alt of alternatives) {
239
+ lines.push(`- ${alt}`);
240
+ }
241
+ lines.push('');
242
+ }
243
+
244
+ if (decision.consequences) {
245
+ lines.push('## Consequences');
246
+ lines.push(decision.consequences as string);
247
+ }
248
+
249
+ return text(lines.join('\n'));
250
+ }
251
+
252
+ function handleAdrGenerate(args: Record<string, unknown>, db: Database.Database): ToolResult {
253
+ const title = args.title as string;
254
+ const decisionText = args.decision as string;
255
+ if (!title || !decisionText) return text(`Usage: ${p('adr_create')} { title: "Use Redis for caching", decision: "We chose Redis over Memcached for caching", context: "...", consequences: "..." }`);
256
+
257
+ const context = (args.context as string) ?? '';
258
+ const consequences = (args.consequences as string) ?? '';
259
+
260
+ // Extract alternatives from the decision text
261
+ const alternatives = extractAlternatives(decisionText);
262
+
263
+ const id = storeDecision(db, {
264
+ title,
265
+ context,
266
+ decision: decisionText,
267
+ alternatives,
268
+ consequences,
269
+ });
270
+
271
+ const lines = [
272
+ `## ADR-${id} Created: ${title}`,
273
+ '',
274
+ `**Status**: accepted`,
275
+ `**Decision**: ${decisionText}`,
276
+ alternatives.length > 0 ? `**Alternatives**: ${alternatives.join(', ')}` : '',
277
+ context ? `**Context**: ${context}` : '',
278
+ consequences ? `**Consequences**: ${consequences}` : '',
279
+ '',
280
+ `View full details: ${p('adr_detail')} { id: ${id} }`,
281
+ ];
282
+
283
+ return text(lines.filter(Boolean).join('\n'));
284
+ }
285
+