@triedotdev/mcp 1.0.137 → 1.0.138

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 (92) hide show
  1. package/README.md +6 -6
  2. package/dist/{autonomy-config-QA6ATWLJ.js → autonomy-config-TZ6HF4FA.js} +3 -3
  3. package/dist/{chat-store-HFOOWZYN.js → chat-store-OJLJCJFI.js} +3 -3
  4. package/dist/{chunk-DFPVUMVE.js → chunk-23RJT5WT.js} +5 -4
  5. package/dist/chunk-23RJT5WT.js.map +1 -0
  6. package/dist/{chunk-QNKBXOIQ.js → chunk-3MUCUZ46.js} +3 -5
  7. package/dist/chunk-3MUCUZ46.js.map +1 -0
  8. package/dist/{chunk-6VIMBFUZ.js → chunk-3RRXWX3V.js} +21 -17
  9. package/dist/chunk-3RRXWX3V.js.map +1 -0
  10. package/dist/{chunk-WHIQAGB7.js → chunk-4C67GV3O.js} +2 -2
  11. package/dist/{chunk-DPZLABUC.js → chunk-67GSG2ST.js} +13 -10
  12. package/dist/chunk-67GSG2ST.js.map +1 -0
  13. package/dist/{chunk-G74XEI7K.js → chunk-6LLH3TBZ.js} +13 -13
  14. package/dist/chunk-6LLH3TBZ.js.map +1 -0
  15. package/dist/{chunk-4JQ6W7LW.js → chunk-D3AS5LY7.js} +4 -7
  16. package/dist/chunk-D3AS5LY7.js.map +1 -0
  17. package/dist/{chunk-K6NTRSDF.js → chunk-EDDT4ZIH.js} +6 -6
  18. package/dist/chunk-EDDT4ZIH.js.map +1 -0
  19. package/dist/{chunk-Z4DN527J.js → chunk-FG467PDD.js} +156 -39
  20. package/dist/chunk-FG467PDD.js.map +1 -0
  21. package/dist/{chunk-A6PWS6ZV.js → chunk-FOCXXIXY.js} +15 -5
  22. package/dist/chunk-FOCXXIXY.js.map +1 -0
  23. package/dist/{chunk-HUR67JXG.js → chunk-GFFUDJMK.js} +31 -12
  24. package/dist/chunk-GFFUDJMK.js.map +1 -0
  25. package/dist/{chunk-ZEXMMTIQ.js → chunk-J5EMP4XW.js} +2 -2
  26. package/dist/{chunk-6EP2VTHC.js → chunk-LT6VUZG2.js} +7 -4
  27. package/dist/chunk-LT6VUZG2.js.map +1 -0
  28. package/dist/{chunk-55CBWOEZ.js → chunk-QSWUPSLK.js} +2 -2
  29. package/dist/{chunk-45Y5TLQZ.js → chunk-SH7H3WRU.js} +3 -6
  30. package/dist/chunk-SH7H3WRU.js.map +1 -0
  31. package/dist/{chunk-AXYNWBME.js → chunk-X3F5QDER.js} +1018 -327
  32. package/dist/chunk-X3F5QDER.js.map +1 -0
  33. package/dist/{chunk-O6OTJI3W.js → chunk-Y32FM3MR.js} +2 -2
  34. package/dist/{chunk-QM5VIDFN.js → chunk-YOKQ25IW.js} +44 -28
  35. package/dist/chunk-YOKQ25IW.js.map +1 -0
  36. package/dist/{chunk-R3WZI6QZ.js → chunk-Z2P4WST6.js} +2 -2
  37. package/dist/cli/create-agent.js +1 -1
  38. package/dist/cli/main.js +75 -52
  39. package/dist/cli/main.js.map +1 -1
  40. package/dist/cli/yolo-daemon.js +16 -16
  41. package/dist/{client-BZHI675W.js → client-JTU5TRLB.js} +3 -3
  42. package/dist/{codebase-index-CR6Q2HEI.js → codebase-index-FNJ4GCBE.js} +3 -3
  43. package/dist/{goal-manager-62IL6WGY.js → goal-manager-6BJQ36AH.js} +6 -6
  44. package/dist/{goal-validator-HPPBSDXD.js → goal-validator-GISXYANK.js} +5 -5
  45. package/dist/{graph-PAUZ5EMP.js → graph-X2FMRQLG.js} +3 -3
  46. package/dist/{hypothesis-W37VG6DA.js → hypothesis-K3KQJOXJ.js} +6 -6
  47. package/dist/{incident-index-ZCDSJ42L.js → incident-index-BWW2UEY7.js} +3 -3
  48. package/dist/index.js +101 -52
  49. package/dist/index.js.map +1 -1
  50. package/dist/{insight-store-U3NYTOJE.js → insight-store-A5XXMFD6.js} +3 -5
  51. package/dist/{issue-store-EZMBHOVN.js → issue-store-BO5OWLJW.js} +3 -3
  52. package/dist/{tiered-storage-QW2G7GSG.js → tiered-storage-VZL7KK64.js} +3 -3
  53. package/dist/trie-agent-XMSGMD7E.js +26 -0
  54. package/dist/ui/chat.html +260 -67
  55. package/dist/ui/goals.html +246 -3
  56. package/dist/ui/hypotheses.html +248 -5
  57. package/dist/ui/ledger.html +252 -9
  58. package/dist/ui/nudges.html +244 -1
  59. package/package.json +1 -1
  60. package/dist/chunk-45Y5TLQZ.js.map +0 -1
  61. package/dist/chunk-4JQ6W7LW.js.map +0 -1
  62. package/dist/chunk-6EP2VTHC.js.map +0 -1
  63. package/dist/chunk-6VIMBFUZ.js.map +0 -1
  64. package/dist/chunk-A6PWS6ZV.js.map +0 -1
  65. package/dist/chunk-AXYNWBME.js.map +0 -1
  66. package/dist/chunk-DFPVUMVE.js.map +0 -1
  67. package/dist/chunk-DPZLABUC.js.map +0 -1
  68. package/dist/chunk-G74XEI7K.js.map +0 -1
  69. package/dist/chunk-HUR67JXG.js.map +0 -1
  70. package/dist/chunk-K6NTRSDF.js.map +0 -1
  71. package/dist/chunk-QM5VIDFN.js.map +0 -1
  72. package/dist/chunk-QNKBXOIQ.js.map +0 -1
  73. package/dist/chunk-Z4DN527J.js.map +0 -1
  74. package/dist/guardian-agent-YKG5XURG.js +0 -30
  75. /package/dist/{autonomy-config-QA6ATWLJ.js.map → autonomy-config-TZ6HF4FA.js.map} +0 -0
  76. /package/dist/{chat-store-HFOOWZYN.js.map → chat-store-OJLJCJFI.js.map} +0 -0
  77. /package/dist/{chunk-WHIQAGB7.js.map → chunk-4C67GV3O.js.map} +0 -0
  78. /package/dist/{chunk-ZEXMMTIQ.js.map → chunk-J5EMP4XW.js.map} +0 -0
  79. /package/dist/{chunk-55CBWOEZ.js.map → chunk-QSWUPSLK.js.map} +0 -0
  80. /package/dist/{chunk-O6OTJI3W.js.map → chunk-Y32FM3MR.js.map} +0 -0
  81. /package/dist/{chunk-R3WZI6QZ.js.map → chunk-Z2P4WST6.js.map} +0 -0
  82. /package/dist/{client-BZHI675W.js.map → client-JTU5TRLB.js.map} +0 -0
  83. /package/dist/{codebase-index-CR6Q2HEI.js.map → codebase-index-FNJ4GCBE.js.map} +0 -0
  84. /package/dist/{goal-manager-62IL6WGY.js.map → goal-manager-6BJQ36AH.js.map} +0 -0
  85. /package/dist/{goal-validator-HPPBSDXD.js.map → goal-validator-GISXYANK.js.map} +0 -0
  86. /package/dist/{graph-PAUZ5EMP.js.map → graph-X2FMRQLG.js.map} +0 -0
  87. /package/dist/{guardian-agent-YKG5XURG.js.map → hypothesis-K3KQJOXJ.js.map} +0 -0
  88. /package/dist/{hypothesis-W37VG6DA.js.map → incident-index-BWW2UEY7.js.map} +0 -0
  89. /package/dist/{incident-index-ZCDSJ42L.js.map → insight-store-A5XXMFD6.js.map} +0 -0
  90. /package/dist/{insight-store-U3NYTOJE.js.map → issue-store-BO5OWLJW.js.map} +0 -0
  91. /package/dist/{issue-store-EZMBHOVN.js.map → tiered-storage-VZL7KK64.js.map} +0 -0
  92. /package/dist/{tiered-storage-QW2G7GSG.js.map → trie-agent-XMSGMD7E.js.map} +0 -0
package/README.md CHANGED
@@ -18,7 +18,7 @@ The agent learns from every incident, decision, and fix. When you ship, Trie rem
18
18
 
19
19
  ## Goal
20
20
 
21
- **Trie is your personal AI agent that maintains multiple codebases without losing context.**
21
+ **Trie is your personal AI agent that carries context across tools.**
22
22
 
23
23
  Every bug you fix teaches the agent a pattern that protects all your projects. Every incident you report becomes institutional knowledge that travels with your code. Every decision you make—and the tradeoffs you considered—gets extracted and stored automatically by the agent.
24
24
 
@@ -108,12 +108,12 @@ Trie remembers your decisions across tools, tracks the tradeoffs you've made, an
108
108
 
109
109
  ## How It Works
110
110
 
111
- ### The Guardian System
111
+ ### The Trie Agent
112
112
 
113
- Trie uses a "Guardian Agent" architecture:
113
+ Trie uses a proactive agent architecture:
114
114
 
115
115
  - Analyzes your code for potential issues based on your incident history.
116
- - Guardian decides what matters based on your history.
116
+ - The agent decides what matters based on your history.
117
117
  - Memory Tree stores incident patterns using a trie data structure for fast lookups.
118
118
  - Learning Loop improves predictions based on your feedback.
119
119
 
@@ -312,7 +312,7 @@ trie watch
312
312
  # Reattach with: tmux attach -t trie-watch
313
313
  ```
314
314
 
315
- This allows you to keep the guardian running while using other terminals. The interactive dashboard will be available when you reattach.
315
+ This allows you to keep the agent running while using other terminals. The interactive dashboard will be available when you reattach.
316
316
 
317
317
  ### JIT Defect Prediction ("Gotchas")
318
318
 
@@ -635,7 +635,7 @@ What happens at the 10,000 issue cap: Trie will deduplicate new repeats, compact
635
635
 
636
636
  **Hooks not working**: Reinstall with `trie init`. Make sure you have write permissions to .git/hooks/.
637
637
 
638
- **Goals showing but not detecting violations**: This happens when goals appear in the UI but aren't active in guardian state. The Goals view will show a yellow warning box. To fix:
638
+ **Goals showing but not detecting violations**: This happens when goals appear in the UI but aren't active in project state. The Goals view will show a yellow warning box. To fix:
639
639
  ```bash
640
640
  # Quick fix - activate a specific goal
641
641
  node fix-goals.js "NO EMOJIS"
@@ -10,8 +10,8 @@ import {
10
10
  shouldAutoFix,
11
11
  shouldBlockPush,
12
12
  trackIssueOccurrence
13
- } from "./chunk-ZEXMMTIQ.js";
14
- import "./chunk-45Y5TLQZ.js";
13
+ } from "./chunk-J5EMP4XW.js";
14
+ import "./chunk-SH7H3WRU.js";
15
15
  import "./chunk-APMV77PU.js";
16
16
  import "./chunk-DGUM43GV.js";
17
17
  export {
@@ -27,4 +27,4 @@ export {
27
27
  shouldBlockPush,
28
28
  trackIssueOccurrence
29
29
  };
30
- //# sourceMappingURL=autonomy-config-QA6ATWLJ.js.map
30
+ //# sourceMappingURL=autonomy-config-TZ6HF4FA.js.map
@@ -2,9 +2,9 @@ import {
2
2
  ChatStore,
3
3
  clearChatStores,
4
4
  getChatStore
5
- } from "./chunk-DFPVUMVE.js";
5
+ } from "./chunk-23RJT5WT.js";
6
6
  import "./chunk-43X6JBEM.js";
7
- import "./chunk-45Y5TLQZ.js";
7
+ import "./chunk-SH7H3WRU.js";
8
8
  import "./chunk-APMV77PU.js";
9
9
  import "./chunk-DGUM43GV.js";
10
10
  export {
@@ -12,4 +12,4 @@ export {
12
12
  clearChatStores,
13
13
  getChatStore
14
14
  };
15
- //# sourceMappingURL=chat-store-HFOOWZYN.js.map
15
+ //# sourceMappingURL=chat-store-OJLJCJFI.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-43X6JBEM.js";
4
4
  import {
5
5
  getTrieDirectory
6
- } from "./chunk-45Y5TLQZ.js";
6
+ } from "./chunk-SH7H3WRU.js";
7
7
 
8
8
  // src/cli/dashboard/chat-store.ts
9
9
  import { mkdir, readFile, unlink } from "fs/promises";
@@ -20,11 +20,12 @@ var ChatMessageSchema = z.object({
20
20
  input: z.record(z.any())
21
21
  })).optional(),
22
22
  pendingFix: z.object({
23
- id: z.string(),
23
+ id: z.string().optional(),
24
24
  file: z.string(),
25
25
  goal: z.string(),
26
26
  violation: z.string(),
27
- suggestedFix: z.string().optional()
27
+ suggestedFix: z.string().optional(),
28
+ directory: z.string().optional()
28
29
  }).optional()
29
30
  });
30
31
  var ChatSessionSchema = z.object({
@@ -344,4 +345,4 @@ export {
344
345
  getChatStore,
345
346
  clearChatStores
346
347
  };
347
- //# sourceMappingURL=chunk-DFPVUMVE.js.map
348
+ //# sourceMappingURL=chunk-23RJT5WT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/dashboard/chat-store.ts"],"sourcesContent":["/**\n * Chat Store - Persistent storage for chat history\n * \n * Features:\n * - Save and load chat sessions\n * - List all chat sessions\n * - Archive management (rename, delete, export)\n * - Atomic writes with backup rotation\n * - Zod validation for data integrity\n * \n * Persists to: .trie/memory/chats/\n */\n\nimport { mkdir, readFile, unlink } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getTrieDirectory } from '../../utils/workspace.js';\nimport { z } from 'zod';\nimport { atomicWriteJSON } from '../../utils/atomic-write.js';\nimport type { ChatMessage } from './types.js';\n\n// ============================================================================\n// Schemas\n// ============================================================================\n\nconst ChatMessageSchema = z.object({\n role: z.enum(['user', 'assistant']),\n content: z.string(),\n timestamp: z.number(),\n toolCalls: z.array(z.object({\n id: z.string(),\n name: z.string(),\n input: z.record(z.any()),\n })).optional(),\n pendingFix: z.object({\n id: z.string().optional(),\n file: z.string(),\n goal: z.string(),\n violation: z.string(),\n suggestedFix: z.string().optional(),\n directory: z.string().optional(),\n }).optional(),\n});\n\nconst ChatSessionSchema = z.object({\n id: z.string(),\n title: z.string(),\n messages: z.array(ChatMessageSchema),\n createdAt: z.number(),\n updatedAt: z.number(),\n archived: z.boolean(),\n});\n\nexport type ChatSession = z.infer<typeof ChatSessionSchema>;\n\nconst ChatStoreIndexSchema = z.object({\n version: z.literal(1),\n sessions: z.array(z.object({\n id: z.string(),\n title: z.string(),\n createdAt: z.number(),\n updatedAt: z.number(),\n archived: z.boolean(),\n messageCount: z.number(),\n })),\n lastUpdated: z.string(),\n});\n\ntype ChatStoreIndex = z.infer<typeof ChatStoreIndexSchema>;\n\n// ============================================================================\n// ChatStore Class\n// ============================================================================\n\nexport class ChatStore {\n private projectPath: string;\n private index: ChatStoreIndex | null = null;\n \n constructor(projectPath: string) {\n this.projectPath = projectPath;\n }\n \n /**\n * Get the chats directory path\n */\n private getChatsDir(): string {\n return join(getTrieDirectory(this.projectPath), 'memory', 'chats');\n }\n \n /**\n * Get the index file path\n */\n private getIndexPath(): string {\n return join(this.getChatsDir(), 'index.json');\n }\n \n /**\n * Get the path for a specific session file\n */\n private getSessionPath(sessionId: string): string {\n return join(this.getChatsDir(), `${sessionId}.json`);\n }\n \n /**\n * Load the index file\n */\n private async loadIndex(): Promise<ChatStoreIndex> {\n if (this.index) {\n return this.index;\n }\n \n const indexPath = this.getIndexPath();\n \n if (existsSync(indexPath)) {\n try {\n const content = await readFile(indexPath, 'utf-8');\n const parsed = JSON.parse(content);\n const result = ChatStoreIndexSchema.safeParse(parsed);\n \n if (result.success) {\n this.index = result.data;\n return this.index;\n }\n } catch (error) {\n console.error('Failed to load chat index:', error);\n }\n }\n \n // Create empty index\n this.index = {\n version: 1,\n sessions: [],\n lastUpdated: new Date().toISOString(),\n };\n \n return this.index;\n }\n \n /**\n * Save the index file\n */\n private async saveIndex(): Promise<void> {\n if (!this.index) return;\n \n const indexPath = this.getIndexPath();\n const chatsDir = this.getChatsDir();\n \n // Ensure directory exists\n await mkdir(chatsDir, { recursive: true });\n \n // Update timestamp\n this.index.lastUpdated = new Date().toISOString();\n \n // Atomic write\n await atomicWriteJSON(indexPath, this.index);\n }\n \n /**\n * Generate a unique session ID\n */\n private generateSessionId(): string {\n return `chat-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n }\n \n /**\n * Generate a default title from the first user message\n */\n private generateTitle(messages: ChatMessage[]): string {\n const firstUser = messages.find(m => m.role === 'user');\n if (firstUser) {\n const text = firstUser.content.trim();\n const maxLen = 50;\n if (text.length > maxLen) {\n return text.slice(0, maxLen) + '...';\n }\n return text;\n }\n return 'New Chat';\n }\n \n /**\n * Save a chat session\n */\n async saveSession(messages: ChatMessage[], sessionId?: string, title?: string): Promise<string> {\n await this.loadIndex();\n \n const id = sessionId || this.generateSessionId();\n const now = Date.now();\n \n // Load existing session if updating\n let createdAt = now;\n if (sessionId) {\n const existing = this.index!.sessions.find(s => s.id === sessionId);\n if (existing) {\n createdAt = existing.createdAt;\n }\n }\n \n const session: ChatSession = {\n id,\n title: title || this.generateTitle(messages),\n messages,\n createdAt,\n updatedAt: now,\n archived: false,\n };\n \n // Validate\n const result = ChatSessionSchema.safeParse(session);\n if (!result.success) {\n throw new Error(`Invalid chat session: ${result.error.message}`);\n }\n \n // Save session file\n const sessionPath = this.getSessionPath(id);\n await mkdir(this.getChatsDir(), { recursive: true });\n await atomicWriteJSON(sessionPath, session);\n \n // Update index\n const existingIndex = this.index!.sessions.findIndex(s => s.id === id);\n const indexEntry = {\n id,\n title: session.title,\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n archived: session.archived,\n messageCount: messages.length,\n };\n \n if (existingIndex >= 0) {\n this.index!.sessions[existingIndex] = indexEntry;\n } else {\n this.index!.sessions.unshift(indexEntry);\n }\n \n await this.saveIndex();\n \n return id;\n }\n \n /**\n * Load a chat session\n */\n async loadSession(sessionId: string): Promise<ChatSession | null> {\n const sessionPath = this.getSessionPath(sessionId);\n \n if (!existsSync(sessionPath)) {\n return null;\n }\n \n try {\n const content = await readFile(sessionPath, 'utf-8');\n const parsed = JSON.parse(content);\n const result = ChatSessionSchema.safeParse(parsed);\n \n if (result.success) {\n return result.data;\n }\n \n console.error('Invalid chat session:', result.error.message);\n return null;\n } catch (error) {\n console.error('Failed to load chat session:', error);\n return null;\n }\n }\n \n /**\n * List all chat sessions\n */\n async listSessions(includeArchived: boolean = false): Promise<ChatStoreIndex['sessions']> {\n await this.loadIndex();\n \n let sessions = this.index!.sessions;\n \n if (!includeArchived) {\n sessions = sessions.filter(s => !s.archived);\n }\n \n // Sort by most recent first\n return sessions.sort((a, b) => b.updatedAt - a.updatedAt);\n }\n \n /**\n * Delete a chat session\n */\n async deleteSession(sessionId: string): Promise<boolean> {\n await this.loadIndex();\n \n const sessionPath = this.getSessionPath(sessionId);\n \n if (!existsSync(sessionPath)) {\n return false;\n }\n \n try {\n await unlink(sessionPath);\n \n // Remove from index\n this.index!.sessions = this.index!.sessions.filter(s => s.id !== sessionId);\n await this.saveIndex();\n \n return true;\n } catch (error) {\n console.error('Failed to delete chat session:', error);\n return false;\n }\n }\n \n /**\n * Rename a chat session\n */\n async renameSession(sessionId: string, newTitle: string): Promise<boolean> {\n await this.loadIndex();\n \n const session = await this.loadSession(sessionId);\n if (!session) {\n return false;\n }\n \n session.title = newTitle;\n session.updatedAt = Date.now();\n \n // Save updated session\n const sessionPath = this.getSessionPath(sessionId);\n await atomicWriteJSON(sessionPath, session);\n \n // Update index\n const indexEntry = this.index!.sessions.find(s => s.id === sessionId);\n if (indexEntry) {\n indexEntry.title = newTitle;\n indexEntry.updatedAt = session.updatedAt;\n await this.saveIndex();\n }\n \n return true;\n }\n \n /**\n * Archive a chat session\n */\n async archiveSession(sessionId: string): Promise<boolean> {\n await this.loadIndex();\n \n const session = await this.loadSession(sessionId);\n if (!session) {\n return false;\n }\n \n session.archived = true;\n session.updatedAt = Date.now();\n \n // Save updated session\n const sessionPath = this.getSessionPath(sessionId);\n await atomicWriteJSON(sessionPath, session);\n \n // Update index\n const indexEntry = this.index!.sessions.find(s => s.id === sessionId);\n if (indexEntry) {\n indexEntry.archived = true;\n indexEntry.updatedAt = session.updatedAt;\n await this.saveIndex();\n }\n \n return true;\n }\n \n /**\n * Unarchive a chat session\n */\n async unarchiveSession(sessionId: string): Promise<boolean> {\n await this.loadIndex();\n \n const session = await this.loadSession(sessionId);\n if (!session) {\n return false;\n }\n \n session.archived = false;\n session.updatedAt = Date.now();\n \n // Save updated session\n const sessionPath = this.getSessionPath(sessionId);\n await atomicWriteJSON(sessionPath, session);\n \n // Update index\n const indexEntry = this.index!.sessions.find(s => s.id === sessionId);\n if (indexEntry) {\n indexEntry.archived = false;\n indexEntry.updatedAt = session.updatedAt;\n await this.saveIndex();\n }\n \n return true;\n }\n \n /**\n * Export a chat session as JSON\n */\n async exportSession(sessionId: string): Promise<string | null> {\n const session = await this.loadSession(sessionId);\n if (!session) {\n return null;\n }\n \n return JSON.stringify(session, null, 2);\n }\n \n /**\n * Get statistics about chat sessions\n */\n async getStats(): Promise<{\n total: number;\n active: number;\n archived: number;\n totalMessages: number;\n }> {\n await this.loadIndex();\n \n const total = this.index!.sessions.length;\n const archived = this.index!.sessions.filter(s => s.archived).length;\n const active = total - archived;\n const totalMessages = this.index!.sessions.reduce((sum, s) => sum + s.messageCount, 0);\n \n return { total, active, archived, totalMessages };\n }\n \n /**\n * Prune old sessions (older than N days)\n */\n async pruneOldSessions(daysToKeep: number = 90): Promise<number> {\n await this.loadIndex();\n \n const cutoff = Date.now() - (daysToKeep * 24 * 60 * 60 * 1000);\n const toDelete = this.index!.sessions.filter(s => s.updatedAt < cutoff);\n \n for (const session of toDelete) {\n await this.deleteSession(session.id);\n }\n \n return toDelete.length;\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst chatStores: Map<string, ChatStore> = new Map();\n\n/**\n * Get the ChatStore for a project (singleton per project)\n */\nexport function getChatStore(projectPath: string): ChatStore {\n let store = chatStores.get(projectPath);\n if (!store) {\n store = new ChatStore(projectPath);\n chatStores.set(projectPath, store);\n }\n return store;\n}\n\n/**\n * Clear all ChatStore instances (for testing)\n */\nexport function clearChatStores(): void {\n chatStores.clear();\n}\n"],"mappings":";;;;;;;;AAaA,SAAS,OAAO,UAAU,cAAc;AACxC,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAErB,SAAS,SAAS;AAQlB,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,MAAM,EAAE,KAAK,CAAC,QAAQ,WAAW,CAAC;AAAA,EAClC,SAAS,EAAE,OAAO;AAAA,EAClB,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,MAAM,EAAE,OAAO;AAAA,IAC1B,IAAI,EAAE,OAAO;AAAA,IACb,MAAM,EAAE,OAAO;AAAA,IACf,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,CAAC,CAAC,EAAE,SAAS;AAAA,EACb,YAAY,EAAE,OAAO;AAAA,IACnB,IAAI,EAAE,OAAO,EAAE,SAAS;AAAA,IACxB,MAAM,EAAE,OAAO;AAAA,IACf,MAAM,EAAE,OAAO;AAAA,IACf,WAAW,EAAE,OAAO;AAAA,IACpB,cAAc,EAAE,OAAO,EAAE,SAAS;AAAA,IAClC,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC,EAAE,SAAS;AACd,CAAC;AAED,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,IAAI,EAAE,OAAO;AAAA,EACb,OAAO,EAAE,OAAO;AAAA,EAChB,UAAU,EAAE,MAAM,iBAAiB;AAAA,EACnC,WAAW,EAAE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WAKH;AACD,UAAM,KAAK,UAAU;AAErB,UAAM,QAAQ,KAAK,MAAO,SAAS;AACnC,UAAM,WAAW,KAAK,MAAO,SAAS,OAAO,OAAK,EAAE,QAAQ,EAAE;AAC9D,UAAM,SAAS,QAAQ;AACvB,UAAM,gBAAgB,KAAK,MAAO,SAAS,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,cAAc,CAAC;AAErF,WAAO,EAAE,OAAO,QAAQ,UAAU,cAAc;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,iBAAiB,aAAqB,IAAqB;AAC/D,UAAM,KAAK,UAAU;AAErB,UAAM,SAAS,KAAK,IAAI,IAAK,aAAa,KAAK,KAAK,KAAK;AACzD,UAAM,WAAW,KAAK,MAAO,SAAS,OAAO,OAAK,EAAE,YAAY,MAAM;AAEtE,eAAW,WAAW,UAAU;AAC9B,YAAM,KAAK,cAAc,QAAQ,EAAE;AAAA,IACrC;AAEA,WAAO,SAAS;AAAA,EAClB;AACF;AAMA,IAAM,aAAqC,oBAAI,IAAI;AAK5C,SAAS,aAAa,aAAgC;AAC3D,MAAI,QAAQ,WAAW,IAAI,WAAW;AACtC,MAAI,CAAC,OAAO;AACV,YAAQ,IAAI,UAAU,WAAW;AACjC,eAAW,IAAI,aAAa,KAAK;AAAA,EACnC;AACA,SAAO;AACT;AAKO,SAAS,kBAAwB;AACtC,aAAW,MAAM;AACnB;","names":[]}
@@ -7,9 +7,9 @@ import {
7
7
  } from "./chunk-43X6JBEM.js";
8
8
  import {
9
9
  getTrieDirectory
10
- } from "./chunk-45Y5TLQZ.js";
10
+ } from "./chunk-SH7H3WRU.js";
11
11
 
12
- // src/guardian/insight-store.ts
12
+ // src/agent/insight-store.ts
13
13
  import { mkdir, readFile } from "fs/promises";
14
14
  import { existsSync } from "fs";
15
15
  import { join } from "path";
@@ -51,7 +51,6 @@ var InsightSchema = z.object({
51
51
  category: z.enum(["security", "quality", "performance", "pattern", "progress", "general"]),
52
52
  details: InsightDetailsSchema.optional()
53
53
  });
54
- var GuardianInsightSchema = InsightSchema;
55
54
  var InsightStoreDataSchema = z.object({
56
55
  version: z.literal(1),
57
56
  insights: z.array(InsightSchema),
@@ -433,10 +432,9 @@ function clearInsightStores() {
433
432
  export {
434
433
  InsightDetailsSchema,
435
434
  InsightSchema,
436
- GuardianInsightSchema,
437
435
  InsightStoreDataSchema,
438
436
  InsightStore,
439
437
  getInsightStore,
440
438
  clearInsightStores
441
439
  };
442
- //# sourceMappingURL=chunk-QNKBXOIQ.js.map
440
+ //# sourceMappingURL=chunk-3MUCUZ46.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/insight-store.ts"],"sourcesContent":["/**\n * Insight Store - Persistent storage for insights\n * \n * Persists to: .trie/memory/insights.json\n * \n * Features:\n * - Insight persistence across restarts\n * - Cooldown state persistence (prevents duplicate insights)\n * - Dismissed insight tracking\n * - Atomic writes with backup rotation\n * - Zod validation for data integrity\n */\n\nimport { mkdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getTrieDirectory } from '../utils/workspace.js';\nimport { z } from 'zod';\nimport { atomicWriteJSON } from '../utils/atomic-write.js';\nimport { BackupManager } from '../utils/backup-manager.js';\nimport { safeParseAndValidate } from '../memory/validation.js';\n\n// ============================================================================\n// Schemas\n// ============================================================================\n\n/**\n * Schema for insight details\n */\nexport const InsightDetailsSchema = z.object({\n affectedFiles: z.array(z.string()).optional(),\n issueBreakdown: z.record(z.string(), z.number()).optional(),\n examples: z.array(z.string()).optional(),\n trend: z.enum(['improving', 'stable', 'worsening']).optional(),\n comparison: z.string().optional(),\n resolvedCount: z.number().optional(),\n resolvedIssues: z.array(z.object({\n file: z.string(),\n line: z.number().optional(),\n issue: z.string(),\n agent: z.string(),\n resolvedAt: z.string().optional(),\n })).optional(),\n summary: z.string().optional(),\n // Hypothesis-related fields\n hypothesis: z.string().optional(),\n testCriteria: z.string().optional(),\n confidence: z.number().optional(),\n // Pattern-related fields\n patternsCount: z.number().optional(),\n topPattern: z.string().optional(),\n});\n\n/**\n * Schema for an insight\n */\nexport const InsightSchema = z.object({\n id: z.string(),\n type: z.enum(['observation', 'warning', 'suggestion', 'celebration', 'question']),\n message: z.string(),\n context: z.string().optional(),\n suggestedAction: z.string().optional(),\n actionCommand: z.string().optional(),\n relatedIssues: z.array(z.string()),\n priority: z.number().min(1).max(10),\n timestamp: z.number(),\n dismissed: z.boolean(),\n category: z.enum(['security', 'quality', 'performance', 'pattern', 'progress', 'general']),\n details: InsightDetailsSchema.optional(),\n});\n\nexport type Insight = z.infer<typeof InsightSchema>;\n\n/**\n * Schema for the entire insight store file\n */\nexport const InsightStoreDataSchema = z.object({\n version: z.literal(1),\n insights: z.array(InsightSchema),\n cooldowns: z.record(z.string(), z.number()), // insightKey -> timestamp\n dismissedIds: z.array(z.string()), // Track dismissed insight IDs permanently\n lastUpdated: z.string(),\n});\n\nexport type InsightStoreData = z.infer<typeof InsightStoreDataSchema>;\n\n// ============================================================================\n// InsightStore Class\n// ============================================================================\n\n/**\n * Persistent store for insights\n * \n * Usage:\n * ```typescript\n * const store = new InsightStore(projectPath);\n * await store.load();\n * \n * await store.addInsight(insight);\n * const active = store.getActiveInsights();\n * await store.dismissInsight(insightId);\n * ```\n */\nexport class InsightStore {\n private projectPath: string;\n private data: InsightStoreData;\n private loaded: boolean = false;\n private dirty: boolean = false;\n \n // Default cooldown periods (in ms)\n static readonly COOLDOWNS: Record<string, number> = {\n 'pre-push-warning': 60000, // 1 min between pre-push warnings\n 'security-warning': 30000, // 30s between security warnings\n 'new-issues': 30000, // 30s between new issue observations\n 'celebration': 60000, // 1 min between celebrations\n 'pattern-suggestion': 120000, // 2 min between pattern suggestions\n 'accessibility-visual-qa': 300000, // 5 min between visual QA suggestions\n 'goal-suggestion': 300000, // 5 min between goal suggestions\n 'risk-prediction': 180000, // 3 min between risk predictions\n 'hypothesis-update': 600000, // 10 min between hypothesis updates\n 'auto-escalation': 300000, // 5 min between auto-escalations\n };\n \n constructor(projectPath: string) {\n this.projectPath = projectPath;\n this.data = this.createEmptyData();\n }\n \n /**\n * Get the storage file path\n */\n private getStorePath(): string {\n return join(getTrieDirectory(this.projectPath), 'memory', 'insights.json');\n }\n \n /**\n * Create empty data structure\n */\n private createEmptyData(): InsightStoreData {\n return {\n version: 1,\n insights: [],\n cooldowns: {},\n dismissedIds: [],\n lastUpdated: new Date().toISOString(),\n };\n }\n \n /**\n * Load insights from disk\n * \n * If the file is corrupted, attempts recovery from backup.\n * Returns empty data if no valid file/backup exists.\n */\n async load(): Promise<InsightStoreData> {\n if (this.loaded) {\n return this.data;\n }\n \n const storePath = this.getStorePath();\n \n try {\n if (existsSync(storePath)) {\n const content = await readFile(storePath, 'utf-8');\n const result = safeParseAndValidate(content, InsightStoreDataSchema);\n \n if (result.success) {\n this.data = result.data;\n this.loaded = true;\n // Deduplicate any existing duplicate insights\n this.deduplicateInsights();\n return this.data;\n }\n \n // Validation failed - attempt recovery from backup\n console.error(` Insight store corrupted: ${result.error}`);\n const backupManager = new BackupManager(storePath);\n \n if (await backupManager.recoverFromBackup()) {\n console.error(' Recovered from backup');\n const recovered = await readFile(storePath, 'utf-8');\n const recoveredResult = safeParseAndValidate(recovered, InsightStoreDataSchema);\n if (recoveredResult.success) {\n this.data = recoveredResult.data;\n this.loaded = true;\n // Deduplicate any existing duplicate insights\n this.deduplicateInsights();\n return this.data;\n }\n }\n \n console.error(' No valid backup found, starting fresh');\n }\n } catch (error) {\n // File doesn't exist or recovery failed - start fresh\n console.error(` Could not load insight store: ${error}`);\n }\n \n this.data = this.createEmptyData();\n this.loaded = true;\n return this.data;\n }\n \n /**\n * Deduplicate existing insights on load\n * Keeps the most recent instance of each unique insight\n */\n private deduplicateInsights(): void {\n const seen = new Map<string, number>(); // contentKey -> index of first occurrence\n const toRemove: number[] = [];\n \n // Process from newest to oldest (insights are sorted by recency)\n for (let i = 0; i < this.data.insights.length; i++) {\n const insight = this.data.insights[i];\n if (!insight) continue;\n \n const contentKey = this.getContentKey(insight);\n \n if (seen.has(contentKey)) {\n // This is a duplicate - mark for removal\n toRemove.push(i);\n } else {\n seen.set(contentKey, i);\n }\n }\n \n // Remove duplicates (reverse order to preserve indices)\n if (toRemove.length > 0) {\n for (let i = toRemove.length - 1; i >= 0; i--) {\n const idx = toRemove[i];\n if (idx !== undefined) {\n this.data.insights.splice(idx, 1);\n }\n }\n this.dirty = true;\n }\n }\n \n /**\n * Save insights to disk\n * \n * Creates backup before writing, uses atomic write.\n */\n async save(): Promise<void> {\n if (!this.dirty && this.loaded) {\n return; // No changes to save\n }\n \n const storePath = this.getStorePath();\n const memoryDir = join(getTrieDirectory(this.projectPath), 'memory');\n \n // Ensure directory exists\n await mkdir(memoryDir, { recursive: true });\n \n // Create backup before writing\n const backupManager = new BackupManager(storePath);\n await backupManager.createBackup();\n \n // Update timestamp\n this.data.lastUpdated = new Date().toISOString();\n \n // Atomic write\n await atomicWriteJSON(storePath, this.data);\n \n this.dirty = false;\n }\n \n /**\n * Generate a content-based key for deduplication\n * Insights with the same content key are considered duplicates\n */\n private getContentKey(insight: Insight): string {\n // Normalize the message by removing specific numbers/counts that might vary slightly\n // e.g., \"Found 30 security issues\" and \"Found 31 security issues\" are the same insight\n const normalizedMessage = insight.message\n .replace(/\\d+/g, 'N') // Replace all numbers with N\n .toLowerCase()\n .trim();\n \n return `${insight.type}:${insight.category}:${normalizedMessage}`;\n }\n \n /**\n * Add an insight to the store\n * \n * Checks for duplicates using both insight ID and content similarity.\n * If a similar insight already exists (same type, category, and normalized message),\n * updates its timestamp instead of creating a duplicate.\n * Respects cooldowns to prevent insight spam.\n */\n async addInsight(insight: Insight): Promise<boolean> {\n await this.load();\n \n // Check if already exists by ID\n if (this.data.insights.some(i => i.id === insight.id)) {\n return false;\n }\n \n // Check if ID was previously dismissed (don't re-add)\n if (this.data.dismissedIds.includes(insight.id)) {\n return false;\n }\n \n // Check for content-based duplicates (same type, category, similar message)\n const contentKey = this.getContentKey(insight);\n const existingIndex = this.data.insights.findIndex(i => \n !i.dismissed && this.getContentKey(i) === contentKey\n );\n \n if (existingIndex >= 0) {\n // Update existing insight instead of adding duplicate\n const existing = this.data.insights[existingIndex];\n if (existing) {\n // Update with new data but keep the original ID\n existing.timestamp = insight.timestamp;\n existing.message = insight.message; // Update with current counts\n existing.details = insight.details; // Update details\n existing.relatedIssues = insight.relatedIssues;\n existing.suggestedAction = insight.suggestedAction;\n \n // Move to front of list\n this.data.insights.splice(existingIndex, 1);\n this.data.insights.unshift(existing);\n \n this.dirty = true;\n await this.save();\n }\n return false; // Return false to indicate no new insight was created\n }\n \n // Add to front of list\n this.data.insights.unshift(insight);\n \n // Keep only last 100 insights\n if (this.data.insights.length > 100) {\n this.data.insights = this.data.insights.slice(0, 100);\n }\n \n this.dirty = true;\n await this.save();\n \n return true;\n }\n \n /**\n * Check if a cooldown has expired for an insight type\n */\n canCreateInsight(insightKey: string): boolean {\n const lastTime = this.data.cooldowns[insightKey];\n const cooldown = InsightStore.COOLDOWNS[insightKey] || 30000;\n \n if (!lastTime) return true;\n return Date.now() - lastTime > cooldown;\n }\n \n /**\n * Mark that an insight type was created (set cooldown)\n */\n async markInsightCreated(insightKey: string): Promise<void> {\n await this.load();\n this.data.cooldowns[insightKey] = Date.now();\n this.dirty = true;\n await this.save();\n }\n \n /**\n * Get active (non-dismissed) insights\n * \n * Returns insights sorted by priority (highest first),\n * limited to the specified count.\n */\n getActiveInsights(limit: number = 5): Insight[] {\n return this.data.insights\n .filter(i => !i.dismissed)\n .sort((a, b) => b.priority - a.priority)\n .slice(0, limit);\n }\n \n /**\n * Get all insights (including dismissed)\n */\n getAllInsights(): Insight[] {\n return [...this.data.insights];\n }\n \n /**\n * Dismiss an insight by ID\n */\n async dismissInsight(insightId: string): Promise<boolean> {\n await this.load();\n \n const insight = this.data.insights.find(i => i.id === insightId);\n if (!insight) {\n return false;\n }\n \n insight.dismissed = true;\n \n // Track permanently dismissed IDs\n if (!this.data.dismissedIds.includes(insightId)) {\n this.data.dismissedIds.push(insightId);\n \n // Keep only last 500 dismissed IDs\n if (this.data.dismissedIds.length > 500) {\n this.data.dismissedIds = this.data.dismissedIds.slice(-500);\n }\n }\n \n this.dirty = true;\n await this.save();\n \n return true;\n }\n \n /**\n * Remove an insight entirely\n */\n async removeInsight(insightId: string): Promise<boolean> {\n await this.load();\n \n const index = this.data.insights.findIndex(i => i.id === insightId);\n if (index === -1) {\n return false;\n }\n \n this.data.insights.splice(index, 1);\n this.dirty = true;\n await this.save();\n \n return true;\n }\n \n /**\n * Clear all cooldowns\n */\n async clearCooldowns(): Promise<void> {\n await this.load();\n this.data.cooldowns = {};\n this.dirty = true;\n await this.save();\n }\n \n /**\n * Get insight by ID\n */\n getInsight(insightId: string): Insight | undefined {\n return this.data.insights.find(i => i.id === insightId);\n }\n \n /**\n * Update an existing insight\n */\n async updateInsight(insightId: string, updates: Partial<Insight>): Promise<boolean> {\n await this.load();\n \n const insight = this.data.insights.find(i => i.id === insightId);\n if (!insight) {\n return false;\n }\n \n Object.assign(insight, updates);\n this.dirty = true;\n await this.save();\n \n return true;\n }\n \n /**\n * Get insights by category\n */\n getInsightsByCategory(category: Insight['category']): Insight[] {\n return this.data.insights.filter(i => i.category === category && !i.dismissed);\n }\n \n /**\n * Get insights by type\n */\n getInsightsByType(type: Insight['type']): Insight[] {\n return this.data.insights.filter(i => i.type === type && !i.dismissed);\n }\n \n /**\n * Get insights from the last N hours\n */\n getRecentInsights(hours: number = 24): Insight[] {\n const cutoff = Date.now() - (hours * 60 * 60 * 1000);\n return this.data.insights.filter(i => i.timestamp >= cutoff);\n }\n \n /**\n * Get statistics about insights\n */\n getStats(): {\n total: number;\n active: number;\n dismissed: number;\n byCategory: Record<string, number>;\n byType: Record<string, number>;\n } {\n const stats = {\n total: this.data.insights.length,\n active: 0,\n dismissed: 0,\n byCategory: {} as Record<string, number>,\n byType: {} as Record<string, number>,\n };\n \n for (const insight of this.data.insights) {\n if (insight.dismissed) {\n stats.dismissed++;\n } else {\n stats.active++;\n }\n \n stats.byCategory[insight.category] = (stats.byCategory[insight.category] || 0) + 1;\n stats.byType[insight.type] = (stats.byType[insight.type] || 0) + 1;\n }\n \n return stats;\n }\n \n /**\n * Prune old insights (older than N days)\n */\n async pruneOldInsights(daysToKeep: number = 30): Promise<number> {\n await this.load();\n \n const cutoff = Date.now() - (daysToKeep * 24 * 60 * 60 * 1000);\n const originalCount = this.data.insights.length;\n \n this.data.insights = this.data.insights.filter(i => i.timestamp >= cutoff);\n \n const pruned = originalCount - this.data.insights.length;\n if (pruned > 0) {\n this.dirty = true;\n await this.save();\n }\n \n return pruned;\n }\n \n /**\n * Check if the store has been loaded\n */\n isLoaded(): boolean {\n return this.loaded;\n }\n \n /**\n * Force reload from disk\n */\n async reload(): Promise<InsightStoreData> {\n this.loaded = false;\n this.dirty = false;\n return this.load();\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst insightStores: Map<string, InsightStore> = new Map();\n\n/**\n * Get the InsightStore for a project (singleton per project)\n */\nexport function getInsightStore(projectPath: string): InsightStore {\n let store = insightStores.get(projectPath);\n if (!store) {\n store = new InsightStore(projectPath);\n insightStores.set(projectPath, store);\n }\n return store;\n}\n\n/**\n * Clear all InsightStore instances (for testing)\n */\nexport function clearInsightStores(): void {\n insightStores.clear();\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAS,OAAO,gBAAgB;AAChC,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAErB,SAAS,SAAS;AAYX,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC5C,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC1D,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACvC,OAAO,EAAE,KAAK,CAAC,aAAa,UAAU,WAAW,CA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A,EAKA,MAAM,iBAAiB,aAAqB,IAAqB;AAC/D,UAAM,KAAK,KAAK;AAEhB,UAAM,SAAS,KAAK,IAAI,IAAK,aAAa,KAAK,KAAK,KAAK;AACzD,UAAM,gBAAgB,KAAK,KAAK,SAAS;AAEzC,SAAK,KAAK,WAAW,KAAK,KAAK,SAAS,OAAO,OAAK,EAAE,aAAa,MAAM;AAEzE,UAAM,SAAS,gBAAgB,KAAK,KAAK,SAAS;AAClD,QAAI,SAAS,GAAG;AACd,WAAK,QAAQ;AACb,YAAM,KAAK,KAAK;AAAA,IAClB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,WAAoB;AAClB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,SAAoC;AACxC,SAAK,SAAS;AACd,SAAK,QAAQ;AACb,WAAO,KAAK,KAAK;AAAA,EACnB;AACF;AAMA,IAAM,gBAA2C,oBAAI,IAAI;AAKlD,SAAS,gBAAgB,aAAmC;AACjE,MAAI,QAAQ,cAAc,IAAI,WAAW;AACzC,MAAI,CAAC,OAAO;AACV,YAAQ,IAAI,aAAa,WAAW;AACpC,kBAAc,IAAI,aAAa,KAAK;AAAA,EACtC;AACA,SAAO;AACT;AAKO,SAAS,qBAA2B;AACzC,gBAAc,MAAM;AACtB;","names":[]}
@@ -6,20 +6,18 @@ import {
6
6
  } from "./chunk-43X6JBEM.js";
7
7
  import {
8
8
  getTrieDirectory
9
- } from "./chunk-45Y5TLQZ.js";
10
- import {
11
- __require
12
- } from "./chunk-DGUM43GV.js";
9
+ } from "./chunk-SH7H3WRU.js";
13
10
 
14
11
  // src/context/codebase-index.ts
15
12
  import { readFile, stat } from "fs/promises";
16
13
  import { createHash } from "crypto";
17
14
  import { join } from "path";
18
- import { existsSync } from "fs";
15
+ import { existsSync, readFileSync } from "fs";
19
16
  var CodebaseIndex = class {
20
17
  trie = new Trie();
21
18
  projectPath;
22
19
  indexPath;
20
+ lastUpdated = null;
23
21
  constructor(projectPath) {
24
22
  this.projectPath = projectPath;
25
23
  this.indexPath = join(getTrieDirectory(projectPath), "codebase-index.json");
@@ -31,10 +29,13 @@ var CodebaseIndex = class {
31
29
  load() {
32
30
  if (!existsSync(this.indexPath)) return;
33
31
  try {
34
- const raw = JSON.parse(__require("fs").readFileSync(this.indexPath, "utf-8"));
32
+ const raw = JSON.parse(readFileSync(this.indexPath, "utf-8"));
35
33
  if (raw.trie) {
36
34
  this.trie = Trie.fromJSON(raw.trie);
37
35
  }
36
+ if (raw.lastUpdated) {
37
+ this.lastUpdated = raw.lastUpdated;
38
+ }
38
39
  } catch (error) {
39
40
  console.error("Failed to load codebase index:", error);
40
41
  }
@@ -43,9 +44,10 @@ var CodebaseIndex = class {
43
44
  * Save index to disk
44
45
  */
45
46
  async save() {
47
+ this.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
46
48
  const data = {
47
49
  version: 1,
48
- lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
50
+ lastUpdated: this.lastUpdated,
49
51
  fileCount: this.trie.getWithPrefix("").length,
50
52
  trie: this.trie.toJSON()
51
53
  };
@@ -76,8 +78,8 @@ var CodebaseIndex = class {
76
78
  const existing = this.trie.search(filePath);
77
79
  if (existing.found && existing.value) {
78
80
  if (existing.value.hash === hash) {
79
- metadata.violations = existing.value.violations;
80
- metadata.lastScanned = existing.value.lastScanned;
81
+ if (existing.value.violations) metadata.violations = existing.value.violations;
82
+ if (existing.value.lastScanned != null) metadata.lastScanned = existing.value.lastScanned;
81
83
  }
82
84
  }
83
85
  this.trie.insert(filePath, metadata);
@@ -133,7 +135,7 @@ var CodebaseIndex = class {
133
135
  */
134
136
  getFilesByType(type) {
135
137
  const allFiles = this.trie.getWithPrefix("");
136
- return allFiles.map((m) => m.value).filter((v) => v !== null && v.type === type);
138
+ return allFiles.map((m) => m.value).filter((v) => v != null && v.type === type);
137
139
  }
138
140
  /**
139
141
  * Record goal violation scan result for a file
@@ -144,14 +146,15 @@ var CodebaseIndex = class {
144
146
  metadata.lastScanned = Date.now();
145
147
  if (!metadata.violations) metadata.violations = [];
146
148
  metadata.violations = metadata.violations.filter((v) => v.goalId !== goalId);
147
- metadata.violations.push({
149
+ const entry = {
148
150
  goalId,
149
151
  goalDescription,
150
152
  found,
151
- details,
152
- confidence,
153
153
  timestamp: Date.now()
154
- });
154
+ };
155
+ if (details !== void 0) entry.details = details;
156
+ if (confidence !== void 0) entry.confidence = confidence;
157
+ metadata.violations.push(entry);
155
158
  this.trie.insert(filePath, metadata);
156
159
  }
157
160
  /**
@@ -181,7 +184,8 @@ var CodebaseIndex = class {
181
184
  totalSize: allFiles.reduce((sum, f) => sum + f.size, 0),
182
185
  filesByType: {},
183
186
  scannedFiles: allFiles.filter((f) => f.lastScanned).length,
184
- filesWithViolations: allFiles.filter((f) => f.violations && f.violations.some((v) => v.found)).length
187
+ filesWithViolations: allFiles.filter((f) => f.violations && f.violations.some((v) => v.found)).length,
188
+ lastUpdated: this.lastUpdated
185
189
  };
186
190
  for (const file of allFiles) {
187
191
  stats.filesByType[file.type] = (stats.filesByType[file.type] || 0) + 1;
@@ -201,7 +205,7 @@ var CodebaseIndex = class {
201
205
  file.violations = file.violations.filter((v) => v.timestamp > cutoff);
202
206
  cleared += before - file.violations.length;
203
207
  if (file.violations.length === 0) {
204
- file.lastScanned = void 0;
208
+ delete file.lastScanned;
205
209
  }
206
210
  this.trie.insert(file.path, file);
207
211
  }
@@ -213,4 +217,4 @@ var CodebaseIndex = class {
213
217
  export {
214
218
  CodebaseIndex
215
219
  };
216
- //# sourceMappingURL=chunk-6VIMBFUZ.js.map
220
+ //# sourceMappingURL=chunk-3RRXWX3V.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/codebase-index.ts"],"sourcesContent":["/**\n * Codebase Index - Fast file indexing for goal violation detection\n * \n * Uses Trie structure for efficient file lookup and caching to avoid\n * re-scanning unchanged files.\n * \n * For large codebases, this dramatically improves goal check performance:\n * - Indexes file hashes to detect changes\n * - Caches AI analysis results\n * - Uses Trie for O(m) lookups where m = path length\n * - Stores file metadata (size, type, last modified, etc.)\n */\n\nimport { readFile, stat } from 'fs/promises';\nimport { createHash } from 'crypto';\nimport { join } from 'path';\nimport { existsSync, readFileSync } from 'fs';\nimport { Trie } from '../trie/trie.js';\nimport { getTrieDirectory } from '../utils/workspace.js';\nimport { atomicWriteJSON } from '../utils/atomic-write.js';\n\nexport interface FileMetadata {\n path: string;\n hash: string; // SHA-256 of content\n size: number;\n lastModified: number;\n type: string; // Extension\n lastScanned?: number; // Timestamp of last AI scan\n violations?: {\n goalId: string;\n goalDescription: string;\n found: boolean;\n details?: string;\n confidence?: number;\n timestamp: number;\n }[];\n}\n\nexport interface CodebaseIndexData {\n version: number;\n lastUpdated: string;\n fileCount: number;\n trie: any; // Serialized Trie\n}\n\nexport class CodebaseIndex {\n private trie: Trie<FileMetadata> = new Trie();\n private projectPath: string;\n private indexPath: string;\n private lastUpdated: string | null = null;\n\n constructor(projectPath: string) {\n this.projectPath = projectPath;\n this.indexPath = join(getTrieDirectory(projectPath), 'codebase-index.json');\n this.load();\n }\n\n /**\n * Load index from disk if it exists\n */\n private load(): void {\n if (!existsSync(this.indexPath)) return;\n\n try {\n const raw = JSON.parse(readFileSync(this.indexPath, 'utf-8'));\n if (raw.trie) {\n this.trie = Trie.fromJSON<FileMetadata>(raw.trie);\n }\n if (raw.lastUpdated) {\n this.lastUpdated = raw.lastUpdated;\n }\n } catch (error) {\n console.error('Failed to load codebase index:', error);\n }\n }\n\n /**\n * Save index to disk\n */\n async save(): Promise<void> {\n this.lastUpdated = new Date().toISOString();\n const data: CodebaseIndexData = {\n version: 1,\n lastUpdated: this.lastUpdated,\n fileCount: this.trie.getWithPrefix('').length,\n trie: this.trie.toJSON(),\n };\n\n await atomicWriteJSON(this.indexPath, data);\n }\n\n /**\n * Add or update a file in the index\n * Returns null if the file doesn't exist or can't be read\n */\n async indexFile(filePath: string): Promise<FileMetadata | null> {\n // Safety check: if filePath is already absolute and doesn't start with projectPath,\n // this is likely a bug (stale cache entry from different project)\n if (filePath.startsWith('/')) {\n // Already absolute - check if it's within our project\n if (!filePath.toLowerCase().startsWith(this.projectPath.toLowerCase())) {\n return null; // Wrong project, skip silently\n }\n // It's absolute but within our project - use as-is\n }\n \n // Build absolute path: if filePath is relative, join with projectPath\n // If filePath is absolute (and within project), use it directly\n const absolutePath = filePath.startsWith('/') ? filePath : join(this.projectPath, filePath);\n \n try {\n const content = await readFile(absolutePath, 'utf-8');\n const stats = await stat(absolutePath);\n const hash = createHash('sha256').update(content).digest('hex');\n\n const metadata: FileMetadata = {\n path: filePath,\n hash,\n size: stats.size,\n lastModified: stats.mtimeMs,\n type: filePath.split('.').pop() || '',\n };\n\n // Check if file exists in index\n const existing = this.trie.search(filePath);\n if (existing.found && existing.value) {\n // File exists - preserve violations if hash matches\n if (existing.value.hash === hash) {\n if (existing.value.violations) metadata.violations = existing.value.violations;\n if (existing.value.lastScanned != null) metadata.lastScanned = existing.value.lastScanned;\n }\n }\n\n this.trie.insert(filePath, metadata);\n return metadata;\n } catch (error) {\n // File doesn't exist, was deleted, or can't be read - return null\n return null;\n }\n }\n\n /**\n * Get file metadata from index\n */\n getFile(filePath: string): FileMetadata | null {\n const result = this.trie.search(filePath);\n return result.found && result.value ? result.value : null;\n }\n\n /**\n * Check if file has changed since last index\n */\n async hasChanged(filePath: string): Promise<boolean> {\n // Safety check for absolute paths from wrong project\n if (filePath.startsWith('/') && !filePath.toLowerCase().startsWith(this.projectPath.toLowerCase())) {\n return true; // Wrong project, treat as changed (will be skipped later)\n }\n \n const metadata = this.getFile(filePath);\n if (!metadata) return true; // Not indexed = changed\n\n // Build absolute path correctly\n const absolutePath = filePath.startsWith('/') ? filePath : join(this.projectPath, filePath);\n try {\n const stats = await stat(absolutePath);\n if (stats.mtimeMs !== metadata.lastModified) return true;\n\n // Double-check with hash for certainty\n const content = await readFile(absolutePath, 'utf-8');\n const hash = createHash('sha256').update(content).digest('hex');\n return hash !== metadata.hash;\n } catch {\n return true; // Error = assume changed\n }\n }\n\n /**\n * Get files in a directory\n */\n getDirectoryFiles(directoryPath: string): FileMetadata[] {\n const prefix = directoryPath.endsWith('/') ? directoryPath : `${directoryPath}/`;\n const matches = this.trie.getWithPrefix(prefix);\n return matches.map(m => m.value).filter((v): v is FileMetadata => v !== null);\n }\n\n /**\n * Get files that match a pattern (uses Trie prefix matching)\n */\n getFilesWithPrefix(prefix: string): FileMetadata[] {\n const matches = this.trie.getWithPrefix(prefix);\n return matches.map(m => m.value).filter((v): v is FileMetadata => v !== null);\n }\n\n /**\n * Get files by type (extension)\n */\n getFilesByType(type: string): FileMetadata[] {\n const allFiles = this.trie.getWithPrefix('');\n return allFiles\n .map(m => m.value)\n .filter((v): v is FileMetadata => v != null && v.type === type);\n }\n\n /**\n * Record goal violation scan result for a file\n */\n recordViolation(\n filePath: string,\n goalId: string,\n goalDescription: string,\n found: boolean,\n details?: string,\n confidence?: number\n ): void {\n const metadata = this.getFile(filePath);\n if (!metadata) return;\n\n metadata.lastScanned = Date.now();\n if (!metadata.violations) metadata.violations = [];\n\n // Remove existing violation for this goal\n metadata.violations = metadata.violations.filter(v => v.goalId !== goalId);\n\n // Add new violation result\n const entry: { goalId: string; goalDescription: string; found: boolean; timestamp: number; details?: string; confidence?: number } = {\n goalId,\n goalDescription,\n found,\n timestamp: Date.now(),\n };\n if (details !== undefined) entry.details = details;\n if (confidence !== undefined) entry.confidence = confidence;\n metadata.violations.push(entry);\n\n this.trie.insert(filePath, metadata);\n }\n\n /**\n * Get cached violation results for a file\n */\n getCachedViolations(filePath: string, goalId?: string): FileMetadata['violations'] {\n const metadata = this.getFile(filePath);\n if (!metadata || !metadata.violations) return undefined;\n\n if (goalId) {\n return metadata.violations.filter(v => v.goalId === goalId);\n }\n\n return metadata.violations;\n }\n\n /**\n * Check if the index is empty (needs initial indexing)\n */\n isEmpty(): boolean {\n return this.trie.getWithPrefix('').length === 0;\n }\n\n /**\n * Get statistics about the index\n */\n getStats(): {\n totalFiles: number;\n totalSize: number;\n filesByType: Record<string, number>;\n scannedFiles: number;\n filesWithViolations: number;\n lastUpdated: string | null;\n } {\n const allFiles = this.trie.getWithPrefix('').map(m => m.value).filter((v): v is FileMetadata => v !== null);\n\n const stats = {\n totalFiles: allFiles.length,\n totalSize: allFiles.reduce((sum, f) => sum + f.size, 0),\n filesByType: {} as Record<string, number>,\n scannedFiles: allFiles.filter(f => f.lastScanned).length,\n filesWithViolations: allFiles.filter(f => f.violations && f.violations.some(v => v.found)).length,\n lastUpdated: this.lastUpdated,\n };\n\n for (const file of allFiles) {\n stats.filesByType[file.type] = (stats.filesByType[file.type] || 0) + 1;\n }\n\n return stats;\n }\n\n /**\n * Clear stale cached results (older than maxAgeMs)\n */\n clearStaleCache(maxAgeMs: number = 7 * 24 * 60 * 60 * 1000): number {\n const allFiles = this.trie.getWithPrefix('').map(m => m.value).filter((v): v is FileMetadata => v !== null);\n const cutoff = Date.now() - maxAgeMs;\n let cleared = 0;\n\n for (const file of allFiles) {\n if (file.violations) {\n const before = file.violations.length;\n file.violations = file.violations.filter(v => v.timestamp > cutoff);\n cleared += before - file.violations.length;\n if (file.violations.length === 0) {\n delete file.lastScanned;\n }\n this.trie.insert(file.path, file);\n }\n }\n\n return cleared;\n }\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,UAAU,YAAY;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,YAAY,oBAAoB;AA6BlC,IAAM,gBAAN,MAAoB;AAAA,EACjB,OAA2B,IAAI,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA,cAA6B;AAAA,EAErC,YAAY,aAAqB;AAC/B,SAAK,cAAc;AACnB,SAAK,YAAY,KAAK,iBAAiB,WAAW,GAAG,qBAAqB;AAC1E,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,QAAI,CAAC,WAAW,KAAK,SAAS,EAA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ClC;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-6NLHFIYA.js";
4
4
  import {
5
5
  getTrieDirectory
6
- } from "./chunk-45Y5TLQZ.js";
6
+ } from "./chunk-SH7H3WRU.js";
7
7
 
8
8
  // src/context/incident-index.ts
9
9
  import path2 from "path";
@@ -170,4 +170,4 @@ var IncidentIndex = class _IncidentIndex {
170
170
  export {
171
171
  IncidentIndex
172
172
  };
173
- //# sourceMappingURL=chunk-WHIQAGB7.js.map
173
+ //# sourceMappingURL=chunk-4C67GV3O.js.map
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  getInsightStore
3
- } from "./chunk-QNKBXOIQ.js";
3
+ } from "./chunk-3MUCUZ46.js";
4
4
  import {
5
5
  getProjectState
6
- } from "./chunk-6EP2VTHC.js";
6
+ } from "./chunk-LT6VUZG2.js";
7
7
  import {
8
8
  searchIssues
9
- } from "./chunk-R3WZI6QZ.js";
9
+ } from "./chunk-Z2P4WST6.js";
10
10
 
11
- // src/guardian/hypothesis.ts
11
+ // src/agent/hypothesis.ts
12
12
  import { dirname } from "path";
13
13
  var HYPOTHESIS_TEMPLATES = [
14
14
  {
@@ -77,13 +77,14 @@ var HypothesisEngine = class {
77
77
  const hypothesis = {
78
78
  id: `hyp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
79
79
  statement,
80
- confidence: options?.initialConfidence ?? 0.5,
80
+ confidence: options?.initialConfidence ?? 0,
81
81
  status: "proposed",
82
82
  evidence: [],
83
83
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
84
84
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
85
85
  testCriteria: options?.testCriteria,
86
- category: options?.category ?? "general"
86
+ category: options?.category ?? "general",
87
+ autoGenerated: options?.autoGenerated ?? false
87
88
  };
88
89
  await this.projectState.addHypothesis(hypothesis);
89
90
  return hypothesis;
@@ -114,7 +115,8 @@ var HypothesisEngine = class {
114
115
  const hypothesis = await this.createHypothesis(template.statement, {
115
116
  category: template.category,
116
117
  testCriteria: template.testCriteria,
117
- initialConfidence: evidence[0].weight
118
+ initialConfidence: evidence[0].weight,
119
+ autoGenerated: true
118
120
  });
119
121
  for (const e of evidence) {
120
122
  await this.projectState.addEvidence(hypothesis.id, e);
@@ -133,7 +135,7 @@ var HypothesisEngine = class {
133
135
  * This enables fully agentic hypothesis creation based on actual codebase observations
134
136
  */
135
137
  async generateHypothesesWithAI(context) {
136
- const { isAIAvailable, runAIAnalysis } = await import("./client-BZHI675W.js");
138
+ const { isAIAvailable, runAIAnalysis } = await import("./client-JTU5TRLB.js");
137
139
  if (!isAIAvailable()) {
138
140
  return [];
139
141
  }
@@ -218,7 +220,8 @@ Return empty array [] if no novel hypotheses can be generated from the data.`;
218
220
  const hypothesis = await this.createHypothesis(aiHypo.statement, {
219
221
  category: aiHypo.category,
220
222
  testCriteria: aiHypo.testCriteria,
221
- initialConfidence: Math.max(0.3, Math.min(0.7, aiHypo.confidence))
223
+ initialConfidence: Math.max(0.3, Math.min(0.7, aiHypo.confidence)),
224
+ autoGenerated: true
222
225
  });
223
226
  await this.projectState.addEvidence(hypothesis.id, {
224
227
  type: "supporting",
@@ -718,4 +721,4 @@ export {
718
721
  clearHypothesisEngines,
719
722
  gatherEvidenceForHypothesis
720
723
  };
721
- //# sourceMappingURL=chunk-DPZLABUC.js.map
724
+ //# sourceMappingURL=chunk-67GSG2ST.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/hypothesis.ts"],"sourcesContent":["/**\n * Hypothesis System - Self-improving hypothesis generation and validation\n * \n * Features:\n * - Generate hypotheses from patterns\n * - Track evidence for/against hypotheses\n * - Auto-validate/invalidate based on evidence\n * - Adjust confidence over time\n * - Learn from hypothesis outcomes\n */\n\nimport type { Hypothesis } from './project-state.js';\nimport { getProjectState } from './project-state.js';\nimport { getInsightStore, type Insight } from './insight-store.js';\nimport { searchIssues } from '../memory/issue-store.js';\nimport { dirname } from 'path';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Hypothesis template for auto-generation\n */\nexport interface HypothesisTemplate {\n category: 'timing' | 'pattern' | 'team' | 'code' | 'general';\n statement: string;\n testCriteria: string;\n minConfidence: number;\n dataRequired: string[];\n}\n\n/**\n * Evidence for a hypothesis\n */\nexport interface HypothesisEvidence {\n type: 'supporting' | 'contradicting';\n description: string;\n weight: number; // 0-1\n timestamp: string;\n}\n\n/**\n * Hypothesis analysis result\n */\nexport interface HypothesisAnalysis {\n hypothesis: Hypothesis;\n recentEvidence: HypothesisEvidence[];\n confidenceChange: number;\n statusChange?: 'validated' | 'invalidated';\n actionRequired: boolean;\n}\n\n// ============================================================================\n// Hypothesis Templates\n// ============================================================================\n\nconst HYPOTHESIS_TEMPLATES: HypothesisTemplate[] = [\n {\n category: 'timing',\n statement: 'Issues spike after weekend deployments',\n testCriteria: 'Compare Monday issue counts to other days',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps', 'deployment_data'],\n },\n {\n category: 'timing',\n statement: 'Code quality declines on Fridays',\n testCriteria: 'Compare Friday issue introduction rate to weekly average',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps'],\n },\n {\n category: 'pattern',\n statement: 'Auth-related code has the highest incident rate',\n testCriteria: 'Compare auth/ issue count to other directories',\n minConfidence: 0.4,\n dataRequired: ['issue_files'],\n },\n {\n category: 'pattern',\n statement: 'Security issues cluster in specific directories',\n testCriteria: 'Check if security issues are concentrated (>50% in <3 dirs)',\n minConfidence: 0.4,\n dataRequired: ['issue_files', 'issue_agents'],\n },\n {\n category: 'code',\n statement: 'Files with multiple authors have more issues',\n testCriteria: 'Correlate file author count with issue count',\n minConfidence: 0.4,\n dataRequired: ['issue_files', 'git_blame'],\n },\n {\n category: 'code',\n statement: 'Recently modified files are more likely to have issues',\n testCriteria: 'Compare issue rate for recent vs old files',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps', 'file_modification_times'],\n },\n {\n category: 'pattern',\n statement: 'Critical issues often come in clusters',\n testCriteria: 'Check temporal clustering of critical issues',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps', 'issue_severities'],\n },\n];\n\n// ============================================================================\n// HypothesisEngine Class\n// ============================================================================\n\n/**\n * Engine for generating and validating hypotheses\n */\nexport class HypothesisEngine {\n private projectPath: string;\n private projectState;\n private insightStore;\n \n constructor(projectPath: string) {\n this.projectPath = projectPath;\n this.projectState = getProjectState(projectPath);\n this.insightStore = getInsightStore(projectPath);\n }\n \n /**\n * Create a new hypothesis\n */\n async createHypothesis(statement: string, options?: {\n category?: Hypothesis['category'];\n testCriteria?: string;\n initialConfidence?: number;\n autoGenerated?: boolean;\n }): Promise<Hypothesis> {\n const hypothesis: Hypothesis = {\n id: `hyp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n statement,\n confidence: options?.initialConfidence ?? 0,\n status: 'proposed',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria: options?.testCriteria,\n category: options?.category ?? 'general',\n autoGenerated: options?.autoGenerated ?? false,\n };\n \n await this.projectState.addHypothesis(hypothesis);\n \n return hypothesis;\n }\n \n /**\n * Auto-generate hypotheses based on detected patterns\n */\n async autoGenerateHypotheses(): Promise<Hypothesis[]> {\n const generated: Hypothesis[] = [];\n \n try {\n // Get existing hypotheses to avoid duplicates\n await this.projectState.load();\n const existing = this.projectState.getAllHypotheses();\n const existingStatements = new Set(existing.map(h => h.statement.toLowerCase()));\n \n // Get data for pattern detection\n const issues = await searchIssues('', {\n workDir: this.projectPath,\n limit: 500,\n includeResolved: true,\n });\n \n if (issues.length < 10) {\n return generated; // Not enough data\n }\n \n // Check each template for applicability\n for (const template of HYPOTHESIS_TEMPLATES) {\n // Skip if already have similar hypothesis\n if (existingStatements.has(template.statement.toLowerCase())) {\n continue;\n }\n \n // Check if we have enough evidence to propose this hypothesis\n const evidence = await this.gatherInitialEvidence(template, issues);\n \n if (evidence.length > 0 && evidence[0]!.weight >= template.minConfidence) {\n const hypothesis = await this.createHypothesis(template.statement, {\n category: template.category,\n testCriteria: template.testCriteria,\n initialConfidence: evidence[0]!.weight,\n autoGenerated: true,\n });\n \n // Add initial evidence\n for (const e of evidence) {\n await this.projectState.addEvidence(hypothesis.id, e);\n }\n \n generated.push(hypothesis);\n \n // Limit to 2 new hypotheses per run\n if (generated.length >= 2) break;\n }\n }\n \n } catch (error) {\n console.error('Failed to auto-generate hypotheses:', error);\n }\n \n return generated;\n }\n \n /**\n * Use Claude AI to generate novel hypotheses from observed patterns\n * This enables fully agentic hypothesis creation based on actual codebase observations\n */\n async generateHypothesesWithAI(context: {\n recentIssues?: any[];\n patterns?: string[];\n observations?: string[];\n }): Promise<Hypothesis[]> {\n const { isAIAvailable, runAIAnalysis } = await import('../ai/client.js');\n \n if (!isAIAvailable()) {\n return []; // Fall back to template-based generation\n }\n \n const generated: Hypothesis[] = [];\n \n try {\n // Get existing hypotheses to avoid duplicates\n await this.projectState.load();\n const existing = this.projectState.getAllHypotheses();\n const existingStatements = existing.map(h => h.statement);\n \n // Get recent issue data\n const issues = context.recentIssues || await searchIssues('', {\n workDir: this.projectPath,\n limit: 100,\n includeResolved: true,\n });\n \n if (issues.length < 5) {\n return generated; // Not enough data for AI\n }\n \n // Build context for Claude\n const issuesSummary = this.summarizeIssuesForAI(issues);\n const patternsSummary = context.patterns?.join('\\n') || 'No explicit patterns provided';\n const observationsSummary = context.observations?.join('\\n') || 'No explicit observations provided';\n \n const prompt = `You are an AI agent observing a codebase over time. Based on the patterns below, generate 1-3 testable hypotheses about this codebase's quality patterns.\n\n## Recent Issues Summary\n${issuesSummary}\n\n## Observed Patterns\n${patternsSummary}\n\n## Additional Observations\n${observationsSummary}\n\n## Existing Hypotheses (avoid duplicates)\n${existingStatements.length > 0 ? existingStatements.map(s => `- ${s}`).join('\\n') : 'None yet'}\n\nGenerate hypotheses that are:\n1. Specific and testable (can be validated with data)\n2. Actionable (if validated, can guide improvements)\n3. Novel (not duplicates of existing hypotheses)\n4. Based on real patterns in the data above\n\nReturn ONLY a JSON array of hypotheses. Each hypothesis must have:\n- \"statement\": Clear, concise hypothesis statement\n- \"category\": One of: \"timing\", \"pattern\", \"team\", \"code\", \"general\"\n- \"testCriteria\": How to test this hypothesis\n- \"confidence\": Initial confidence (0-1)\n- \"reasoning\": Why you think this hypothesis is worth testing\n\nExample format:\n[\n {\n \"statement\": \"Authentication code changes correlate with security issues\",\n \"category\": \"pattern\",\n \"testCriteria\": \"Track auth file changes and subsequent security issue rates\",\n \"confidence\": 0.6,\n \"reasoning\": \"65% of security issues occur in files modified in the past week\"\n }\n]\n\nReturn empty array [] if no novel hypotheses can be generated from the data.`;\n \n const result = await runAIAnalysis({\n systemPrompt: 'You are an expert code quality analyst who identifies patterns and generates testable hypotheses.',\n userPrompt: prompt,\n maxTokens: 1024,\n temperature: 0.7, // Higher temperature for creative hypothesis generation\n });\n \n if (!result.success || !result.content.trim()) {\n return generated;\n }\n \n // Parse AI response\n let aiHypotheses: Array<{\n statement: string;\n category: Hypothesis['category'];\n testCriteria: string;\n confidence: number;\n reasoning: string;\n }> = [];\n \n try {\n const cleaned = result.content.replace(/```json?\\n?|\\n?```/g, '').trim();\n aiHypotheses = JSON.parse(cleaned);\n if (!Array.isArray(aiHypotheses)) aiHypotheses = [];\n } catch {\n return generated; // AI response wasn't valid JSON\n }\n \n // Create hypotheses from AI suggestions\n for (const aiHypo of aiHypotheses.slice(0, 3)) {\n // Check for duplicates\n const isDuplicate = existingStatements.some(existing => \n existing.toLowerCase().includes(aiHypo.statement.toLowerCase().slice(0, 30))\n );\n \n if (isDuplicate) continue;\n \n const hypothesis = await this.createHypothesis(aiHypo.statement, {\n category: aiHypo.category,\n testCriteria: aiHypo.testCriteria,\n initialConfidence: Math.max(0.3, Math.min(0.7, aiHypo.confidence)),\n autoGenerated: true,\n });\n \n // Add AI reasoning as initial evidence\n await this.projectState.addEvidence(hypothesis.id, {\n type: 'supporting',\n description: `AI observed: ${aiHypo.reasoning}`,\n weight: aiHypo.confidence,\n });\n \n generated.push(hypothesis);\n }\n \n } catch (error) {\n console.error('Failed to generate hypotheses with AI:', error);\n }\n \n return generated;\n }\n \n /**\n * Summarize issues for AI context\n */\n private summarizeIssuesForAI(issues: Array<{ issue: any; score: number }>): string {\n const totalIssues = issues.length;\n \n // Severity breakdown\n const severityCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n severityCounts[issue.severity] = (severityCounts[issue.severity] || 0) + 1;\n }\n \n // Agent breakdown\n const agentCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n agentCounts[issue.agent] = (agentCounts[issue.agent] || 0) + 1;\n }\n \n // File/directory patterns\n const fileCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n fileCounts[dir] = (fileCounts[dir] || 0) + 1;\n }\n \n // Time patterns\n const dayOfWeekCounts: Record<number, number> = {};\n for (const { issue } of issues) {\n const date = new Date(issue.timestamp);\n const day = date.getDay();\n dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;\n }\n \n const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n const dayDistribution = Object.entries(dayOfWeekCounts)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([day, count]) => `${dayNames[Number(day)]}: ${count}`)\n .join(', ');\n \n const topDirs = Object.entries(fileCounts)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 5)\n .map(([dir, count]) => `${dir}: ${count}`)\n .join(', ');\n \n const topAgents = Object.entries(agentCounts)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 5)\n .map(([agent, count]) => `${agent}: ${count}`)\n .join(', ');\n \n return `Total Issues: ${totalIssues}\nSeverities: ${Object.entries(severityCounts).map(([s, c]) => `${s}=${c}`).join(', ')}\nTop Agents: ${topAgents}\nTop Directories: ${topDirs}\nDay Distribution: ${dayDistribution}`;\n }\n \n /**\n * Gather initial evidence for a hypothesis template\n */\n private async gatherInitialEvidence(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): Promise<HypothesisEvidence[]> {\n const evidence: HypothesisEvidence[] = [];\n \n switch (template.category) {\n case 'timing':\n evidence.push(...this.analyzeTimingPatterns(template, issues));\n break;\n case 'pattern':\n evidence.push(...this.analyzeLocationPatterns(template, issues));\n break;\n case 'code':\n evidence.push(...this.analyzeCodePatterns(template, issues));\n break;\n }\n \n return evidence;\n }\n \n /**\n * Analyze timing patterns in issues\n */\n private analyzeTimingPatterns(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n \n // Analyze day-of-week patterns\n const dayOfWeekCounts: Record<number, number> = {};\n for (const { issue } of issues) {\n const date = new Date(issue.timestamp);\n const day = date.getDay();\n dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;\n }\n \n // Check for Friday pattern\n if (template.statement.includes('Friday')) {\n const fridayCount = dayOfWeekCounts[5] || 0;\n const avgOtherDays = (Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0) - fridayCount) / 4;\n \n if (fridayCount > avgOtherDays * 1.5) {\n evidence.push({\n type: 'supporting',\n description: `Friday has ${((fridayCount / avgOtherDays - 1) * 100).toFixed(0)}% more issues than average`,\n weight: Math.min(0.8, 0.3 + (fridayCount / avgOtherDays - 1) * 0.2),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: 'Friday issue count is not significantly higher',\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n // Check for Monday/weekend pattern\n if (template.statement.includes('weekend') || template.statement.includes('Monday')) {\n const mondayCount = dayOfWeekCounts[1] || 0;\n const avgOtherDays = (Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0) - mondayCount) / 4;\n \n if (mondayCount > avgOtherDays * 1.5) {\n evidence.push({\n type: 'supporting',\n description: `Monday has ${((mondayCount / avgOtherDays - 1) * 100).toFixed(0)}% more issues than average`,\n weight: Math.min(0.8, 0.3 + (mondayCount / avgOtherDays - 1) * 0.2),\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n return evidence;\n }\n \n /**\n * Analyze location patterns in issues\n */\n private analyzeLocationPatterns(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n \n // Analyze directory distribution\n const dirCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n dirCounts[dir] = (dirCounts[dir] || 0) + 1;\n }\n \n const sortedDirs = Object.entries(dirCounts)\n .sort(([, a], [, b]) => b - a);\n \n // Check for auth pattern\n if (template.statement.includes('Auth')) {\n const authDirs = sortedDirs.filter(([dir]) => \n dir.toLowerCase().includes('auth') || \n dir.toLowerCase().includes('login') ||\n dir.toLowerCase().includes('session')\n );\n \n const authCount = authDirs.reduce((sum, [, count]) => sum + count, 0);\n const percentage = (authCount / issues.length) * 100;\n \n if (percentage >= 20) {\n evidence.push({\n type: 'supporting',\n description: `Auth-related code has ${percentage.toFixed(0)}% of issues`,\n weight: Math.min(0.85, 0.4 + percentage / 100),\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n // Check for clustering pattern\n if (template.statement.includes('cluster')) {\n const topThreeDirs = sortedDirs.slice(0, 3);\n const topThreeCount = topThreeDirs.reduce((sum, [, count]) => sum + count, 0);\n const percentage = (topThreeCount / issues.length) * 100;\n \n if (percentage >= 50) {\n evidence.push({\n type: 'supporting',\n description: `Top 3 directories have ${percentage.toFixed(0)}% of issues`,\n weight: Math.min(0.8, 0.3 + percentage / 100),\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n return evidence;\n }\n \n /**\n * Analyze code patterns\n */\n private analyzeCodePatterns(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n \n // Analyze temporal clustering (critical issues in bursts)\n if (template.statement.includes('cluster')) {\n const criticalIssues = issues.filter(r => r.issue.severity === 'critical');\n \n if (criticalIssues.length >= 3) {\n // Check if critical issues are clustered in time\n const timestamps = criticalIssues\n .map(r => new Date(r.issue.timestamp).getTime())\n .sort((a, b) => a - b);\n \n let clusteredCount = 0;\n for (let i = 1; i < timestamps.length; i++) {\n // If within 24 hours of previous\n if (timestamps[i]! - timestamps[i - 1]! < 24 * 60 * 60 * 1000) {\n clusteredCount++;\n }\n }\n \n const clusterRatio = clusteredCount / (timestamps.length - 1);\n \n if (clusterRatio >= 0.5) {\n evidence.push({\n type: 'supporting',\n description: `${(clusterRatio * 100).toFixed(0)}% of critical issues occur within 24h of another`,\n weight: Math.min(0.75, 0.3 + clusterRatio * 0.4),\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n \n return evidence;\n }\n \n /**\n * Update confidence scores based on new data\n */\n async updateConfidenceFromOutcomes(): Promise<HypothesisAnalysis[]> {\n const analyses: HypothesisAnalysis[] = [];\n \n try {\n await this.projectState.load();\n const activeHypotheses = this.projectState.getActiveHypotheses();\n \n for (const hypothesis of activeHypotheses) {\n const analysis = await this.analyzeHypothesis(hypothesis);\n analyses.push(analysis);\n \n // Create insight if hypothesis was validated or invalidated\n if (analysis.statusChange && this.insightStore.canCreateInsight('hypothesis-update')) {\n const insight = this.createHypothesisInsight(analysis);\n await this.insightStore.addInsight(insight);\n await this.insightStore.markInsightCreated('hypothesis-update');\n }\n }\n \n // Update hypothesis accuracy metric\n await this.projectState.updateHypothesisAccuracy();\n \n } catch (error) {\n console.error('Failed to update hypothesis confidence:', error);\n }\n \n return analyses;\n }\n \n /**\n * Analyze a single hypothesis\n */\n private async analyzeHypothesis(hypothesis: Hypothesis): Promise<HypothesisAnalysis> {\n // Get recent issues for new evidence\n const issues = await searchIssues('', {\n workDir: this.projectPath,\n limit: 100,\n includeResolved: false,\n });\n \n // Find the matching template\n const template = HYPOTHESIS_TEMPLATES.find(t => \n t.statement.toLowerCase() === hypothesis.statement.toLowerCase()\n );\n \n const recentEvidence: HypothesisEvidence[] = [];\n \n if (template) {\n recentEvidence.push(...await this.gatherInitialEvidence(template, issues));\n } else {\n // For user-created hypotheses, use semantic evidence gathering\n recentEvidence.push(...this.gatherSemanticEvidence(hypothesis, issues));\n }\n \n // Calculate confidence change\n const oldConfidence = hypothesis.confidence;\n let newConfidence = oldConfidence;\n \n for (const evidence of recentEvidence) {\n if (evidence.type === 'supporting') {\n newConfidence = Math.min(1, newConfidence + evidence.weight * 0.1);\n } else {\n newConfidence = Math.max(0, newConfidence - evidence.weight * 0.1);\n }\n }\n \n // Determine status change\n let statusChange: 'validated' | 'invalidated' | undefined;\n \n if (newConfidence >= 0.8 && hypothesis.evidence.length >= 3) {\n statusChange = 'validated';\n await this.projectState.updateHypothesis(hypothesis.id, {\n status: 'validated',\n confidence: newConfidence,\n validatedAt: new Date().toISOString(),\n });\n } else if (newConfidence <= 0.2 && hypothesis.evidence.length >= 3) {\n statusChange = 'invalidated';\n await this.projectState.updateHypothesis(hypothesis.id, {\n status: 'invalidated',\n confidence: newConfidence,\n });\n } else {\n // Just update confidence\n await this.projectState.updateHypothesis(hypothesis.id, {\n confidence: newConfidence,\n });\n }\n \n // Add new evidence\n for (const evidence of recentEvidence) {\n await this.projectState.addEvidence(hypothesis.id, evidence);\n }\n \n const analysis: HypothesisAnalysis = {\n hypothesis: { ...hypothesis, confidence: newConfidence },\n recentEvidence,\n confidenceChange: newConfidence - oldConfidence,\n actionRequired: statusChange !== undefined,\n };\n \n if (statusChange) {\n analysis.statusChange = statusChange;\n }\n \n return analysis;\n }\n \n /**\n * Gather evidence for user-created hypotheses using semantic matching\n * \n * This enables agentic tracking for natural language hypotheses like:\n * - \"Mondays have more bugs than Fridays\"\n * - \"Code reviews reduce bug rate\"\n * - \"Security issues cluster in auth code\"\n */\n private gatherSemanticEvidence(\n hypothesis: Hypothesis,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n const stmt = hypothesis.statement.toLowerCase();\n \n // Time-based hypotheses (days of week patterns)\n if (stmt.includes('monday') || stmt.includes('friday') || stmt.includes('weekend') ||\n stmt.includes('morning') || stmt.includes('afternoon')) {\n const dayNames = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\n const dayOfWeekCounts: Record<number, number> = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 };\n \n for (const { issue } of issues) {\n const date = new Date(issue.timestamp);\n const day = date.getDay();\n dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;\n }\n \n const totalIssues = Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0);\n const avgPerDay = totalIssues / 7;\n \n // Check each day mentioned\n for (let dayIdx = 0; dayIdx < 7; dayIdx++) {\n const dayName = dayNames[dayIdx]!;\n if (stmt.includes(dayName)) {\n const dayCount = dayOfWeekCounts[dayIdx] || 0;\n \n if (stmt.includes('more') || stmt.includes('higher') || stmt.includes('spike')) {\n // Testing if this day has MORE issues\n if (dayCount > avgPerDay * 1.3) {\n evidence.push({\n type: 'supporting',\n description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has ${dayCount} issues (${((dayCount/avgPerDay - 1) * 100).toFixed(0)}% above average)`,\n weight: Math.min(0.7, 0.3 + (dayCount / avgPerDay - 1) * 0.3),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has average or below average issue count`,\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n } else if (stmt.includes('fewer') || stmt.includes('less') || stmt.includes('reduce')) {\n // Testing if this day has FEWER issues\n if (dayCount < avgPerDay * 0.7) {\n evidence.push({\n type: 'supporting',\n description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has ${dayCount} issues (${((1 - dayCount/avgPerDay) * 100).toFixed(0)}% below average)`,\n weight: Math.min(0.7, 0.3 + (1 - dayCount / avgPerDay) * 0.3),\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n }\n }\n \n // Code review hypotheses\n if (stmt.includes('review') || stmt.includes('pr') || stmt.includes('pull request')) {\n // Look for patterns in reviewed vs unreviewed code (approximated by commit patterns)\n const recentIssues = issues.slice(0, 30); // Most recent\n const olderIssues = issues.slice(30); // Older\n \n if (recentIssues.length >= 10 && olderIssues.length >= 10) {\n const recentRate = recentIssues.length;\n const olderRate = olderIssues.length;\n \n if (stmt.includes('reduce') || stmt.includes('fewer') || stmt.includes('less')) {\n if (recentRate < olderRate) {\n evidence.push({\n type: 'supporting',\n description: `Recent period has ${((1 - recentRate/olderRate) * 100).toFixed(0)}% fewer issues`,\n weight: Math.min(0.6, 0.3 + (1 - recentRate/olderRate) * 0.3),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `Issue rate has not decreased recently`,\n weight: 0.2,\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n }\n \n // Directory/location clustering hypotheses\n if (stmt.includes('cluster') || stmt.includes('concentrate') || stmt.includes('auth') ||\n stmt.includes('specific') || stmt.includes('certain files')) {\n const dirCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n dirCounts[dir] = (dirCounts[dir] || 0) + 1;\n }\n \n const sortedDirs = Object.entries(dirCounts).sort(([, a], [, b]) => b - a);\n const topThreeCount = sortedDirs.slice(0, 3).reduce((sum, [, count]) => sum + count, 0);\n const totalCount = issues.length;\n const concentration = topThreeCount / totalCount;\n \n if (concentration >= 0.5) {\n evidence.push({\n type: 'supporting',\n description: `Top 3 directories have ${(concentration * 100).toFixed(0)}% of issues (concentrated)`,\n weight: Math.min(0.7, 0.3 + concentration * 0.4),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `Issues are distributed across many directories`,\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n // Severity trend hypotheses\n if (stmt.includes('critical') || stmt.includes('security') || stmt.includes('severity')) {\n const criticalCount = issues.filter(r => r.issue.severity === 'critical').length;\n const seriousCount = issues.filter(r => r.issue.severity === 'serious').length;\n const highSeverityRatio = (criticalCount + seriousCount) / issues.length;\n \n if (stmt.includes('increase') || stmt.includes('more') || stmt.includes('rise')) {\n if (highSeverityRatio > 0.3) {\n evidence.push({\n type: 'supporting',\n description: `${(highSeverityRatio * 100).toFixed(0)}% of issues are high severity`,\n weight: Math.min(0.7, 0.3 + highSeverityRatio),\n timestamp: new Date().toISOString(),\n });\n }\n } else if (stmt.includes('decrease') || stmt.includes('fewer') || stmt.includes('reduce')) {\n if (highSeverityRatio < 0.2) {\n evidence.push({\n type: 'supporting',\n description: `Only ${(highSeverityRatio * 100).toFixed(0)}% of issues are high severity`,\n weight: 0.5,\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n \n // Agent/skill specific hypotheses\n const agents = ['security', 'performance', 'accessibility', 'test', 'typecheck', 'bug-finding'];\n for (const agent of agents) {\n if (stmt.includes(agent) || stmt.includes(agent.replace('-', ' '))) {\n const agentIssues = issues.filter(r => r.issue.agent === agent);\n const agentRatio = agentIssues.length / issues.length;\n \n if (stmt.includes('most') || stmt.includes('majority') || stmt.includes('main')) {\n if (agentRatio > 0.4) {\n evidence.push({\n type: 'supporting',\n description: `${agent} accounts for ${(agentRatio * 100).toFixed(0)}% of issues`,\n weight: Math.min(0.7, 0.3 + agentRatio),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `${agent} only accounts for ${(agentRatio * 100).toFixed(0)}% of issues`,\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n }\n \n return evidence;\n }\n \n /**\n * Create an insight for hypothesis status change\n */\n private createHypothesisInsight(analysis: HypothesisAnalysis): Insight {\n const isValidated = analysis.statusChange === 'validated';\n \n return {\n id: `insight-hyp-${analysis.hypothesis.id}`,\n type: isValidated ? 'celebration' : 'observation',\n message: isValidated\n ? `Hypothesis confirmed: \"${analysis.hypothesis.statement}\"`\n : `Hypothesis disproven: \"${analysis.hypothesis.statement}\"`,\n context: `Confidence: ${(analysis.hypothesis.confidence * 100).toFixed(0)}%. ${analysis.recentEvidence.length} evidence points analyzed.`,\n relatedIssues: [],\n priority: 5,\n timestamp: Date.now(),\n dismissed: false,\n category: 'pattern',\n details: {\n examples: analysis.recentEvidence.map(e => `${e.type}: ${e.description}`),\n },\n };\n }\n \n /**\n * Get hypothesis by ID\n */\n async getHypothesis(hypothesisId: string): Promise<Hypothesis | undefined> {\n await this.projectState.load();\n return this.projectState.getHypothesis(hypothesisId);\n }\n \n /**\n * Get all hypotheses\n */\n async getAllHypotheses(): Promise<Hypothesis[]> {\n await this.projectState.load();\n return this.projectState.getAllHypotheses();\n }\n \n /**\n * Get validated hypotheses\n */\n async getValidatedHypotheses(): Promise<Hypothesis[]> {\n await this.projectState.load();\n return this.projectState.getValidatedHypotheses();\n }\n \n /**\n * Get hypothesis accuracy stats\n */\n getAccuracy(): number {\n const metrics = this.projectState.getMetrics();\n return metrics.hypothesisAccuracy;\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst hypothesisEngines: Map<string, HypothesisEngine> = new Map();\n\n/**\n * Get the HypothesisEngine for a project (singleton per project)\n */\nexport function getHypothesisEngine(projectPath: string): HypothesisEngine {\n let engine = hypothesisEngines.get(projectPath);\n if (!engine) {\n engine = new HypothesisEngine(projectPath);\n hypothesisEngines.set(projectPath, engine);\n }\n return engine;\n}\n\n/**\n * Clear all HypothesisEngine instances (for testing)\n */\nexport function clearHypothesisEngines(): void {\n hypothesisEngines.clear();\n}\n\n/**\n * Gather evidence for a specific hypothesis (manual check from UI)\n */\nexport async function gatherEvidenceForHypothesis(\n hypothesisId: string,\n projectPath: string\n): Promise<Array<{ supports: boolean; description: string; weight: number }>> {\n const engine = getHypothesisEngine(projectPath);\n const projectState = getProjectState(projectPath);\n await projectState.load();\n \n const hypothesis = projectState.getAllHypotheses().find(h => h.id === hypothesisId);\n if (!hypothesis) {\n throw new Error(`Hypothesis ${hypothesisId} not found`);\n }\n \n // Get the analysis - access private method via bracket notation\n const analysis = await (engine as any).analyzeHypothesis(hypothesis);\n \n // Convert evidence to simpler format\n return analysis.recentEvidence.map((e: HypothesisEvidence) => ({\n supports: e.type === 'supporting',\n description: e.description,\n weight: e.weight,\n }));\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAS,eAAe;AA0CxB,IAAM,uBAA6C;AAAA,EACjD;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,oBAAoB,iBAAiB;AAAA,EACtD;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,kBAAkB;AAAA,EACnC;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,aAAa;AAAA,EAC9B;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,eAAe,cAAc;AAAA,EAC9C;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,eAAe,WAAW;AAAA,EAC3C;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,oBAAoB,yBAAyB;AAAA,EAC9D;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,oBAAoB,kBAAkB;AAAA,EACvD;AACF;AASO,IAAM,mBAAN,MAAuB;AAAA,EACpB;AAAA,EACA;AAAA,EAC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