@triedotdev/mcp 1.0.136 → 1.0.137

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 (64) hide show
  1. package/dist/{chunk-DFHMB44X.js → chunk-4JQ6W7LW.js} +3 -4
  2. package/dist/chunk-4JQ6W7LW.js.map +1 -0
  3. package/dist/{chunk-WS6OA7H6.js → chunk-4MJ52WBH.js} +2 -3
  4. package/dist/chunk-4MJ52WBH.js.map +1 -0
  5. package/dist/{chunk-UHMMANC2.js → chunk-6EP2VTHC.js} +15 -15
  6. package/dist/chunk-6EP2VTHC.js.map +1 -0
  7. package/dist/{chunk-T4THB2OR.js → chunk-A6PWS6ZV.js} +38 -27
  8. package/dist/chunk-A6PWS6ZV.js.map +1 -0
  9. package/dist/{chunk-POHBQUG7.js → chunk-AXYNWBME.js} +272 -187
  10. package/dist/chunk-AXYNWBME.js.map +1 -0
  11. package/dist/{chunk-AJ34GCMD.js → chunk-DPZLABUC.js} +32 -32
  12. package/dist/chunk-DPZLABUC.js.map +1 -0
  13. package/dist/{chunk-UHX4462X.js → chunk-G74XEI7K.js} +13 -14
  14. package/dist/chunk-G74XEI7K.js.map +1 -0
  15. package/dist/{goal-validator-PDKYZSNP.js → chunk-HUR67JXG.js} +71 -33
  16. package/dist/chunk-HUR67JXG.js.map +1 -0
  17. package/dist/{chunk-6OUWNVLX.js → chunk-K6NTRSDF.js} +4 -4
  18. package/dist/{chunk-G5PRBQIQ.js → chunk-QM5VIDFN.js} +75 -71
  19. package/dist/chunk-QM5VIDFN.js.map +1 -0
  20. package/dist/{chunk-4YJ6KLGI.js → chunk-QNKBXOIQ.js} +7 -5
  21. package/dist/chunk-QNKBXOIQ.js.map +1 -0
  22. package/dist/{chunk-JAKMZI5S.js → chunk-R3WZI6QZ.js} +290 -179
  23. package/dist/chunk-R3WZI6QZ.js.map +1 -0
  24. package/dist/{chunk-VRLMTOB6.js → chunk-TIMIKBY2.js} +1 -1
  25. package/dist/chunk-TIMIKBY2.js.map +1 -0
  26. package/dist/cli/main.js +104 -100
  27. package/dist/cli/main.js.map +1 -1
  28. package/dist/cli/yolo-daemon.js +13 -13
  29. package/dist/cli/yolo-daemon.js.map +1 -1
  30. package/dist/{goal-manager-FAK7H4RR.js → goal-manager-62IL6WGY.js} +6 -7
  31. package/dist/goal-validator-HPPBSDXD.js +22 -0
  32. package/dist/guardian-agent-YKG5XURG.js +30 -0
  33. package/dist/{hypothesis-L5446W36.js → hypothesis-W37VG6DA.js} +6 -7
  34. package/dist/index.js +265 -259
  35. package/dist/index.js.map +1 -1
  36. package/dist/{insight-store-F5KDBY5Y.js → insight-store-U3NYTOJE.js} +5 -3
  37. package/dist/issue-store-EZMBHOVN.js +32 -0
  38. package/dist/{output-manager-BOTMXSND.js → output-manager-DZO5LGSG.js} +2 -2
  39. package/dist/output-manager-DZO5LGSG.js.map +1 -0
  40. package/dist/ui/chat.html +1 -1
  41. package/package.json +1 -1
  42. package/dist/chunk-4YJ6KLGI.js.map +0 -1
  43. package/dist/chunk-AJ34GCMD.js.map +0 -1
  44. package/dist/chunk-DFHMB44X.js.map +0 -1
  45. package/dist/chunk-G5PRBQIQ.js.map +0 -1
  46. package/dist/chunk-JAKMZI5S.js.map +0 -1
  47. package/dist/chunk-PEJEYWVR.js +0 -135
  48. package/dist/chunk-PEJEYWVR.js.map +0 -1
  49. package/dist/chunk-POHBQUG7.js.map +0 -1
  50. package/dist/chunk-T4THB2OR.js.map +0 -1
  51. package/dist/chunk-UHMMANC2.js.map +0 -1
  52. package/dist/chunk-UHX4462X.js.map +0 -1
  53. package/dist/chunk-VRLMTOB6.js.map +0 -1
  54. package/dist/chunk-WS6OA7H6.js.map +0 -1
  55. package/dist/goal-validator-PDKYZSNP.js.map +0 -1
  56. package/dist/guardian-agent-4RHGIXUD.js +0 -27
  57. package/dist/ledger-WKVJWHBX.js +0 -17
  58. /package/dist/{chunk-6OUWNVLX.js.map → chunk-K6NTRSDF.js.map} +0 -0
  59. /package/dist/{goal-manager-FAK7H4RR.js.map → goal-manager-62IL6WGY.js.map} +0 -0
  60. /package/dist/{guardian-agent-4RHGIXUD.js.map → goal-validator-HPPBSDXD.js.map} +0 -0
  61. /package/dist/{hypothesis-L5446W36.js.map → guardian-agent-YKG5XURG.js.map} +0 -0
  62. /package/dist/{insight-store-F5KDBY5Y.js.map → hypothesis-W37VG6DA.js.map} +0 -0
  63. /package/dist/{ledger-WKVJWHBX.js.map → insight-store-U3NYTOJE.js.map} +0 -0
  64. /package/dist/{output-manager-BOTMXSND.js.map → issue-store-EZMBHOVN.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  getInsightStore
3
- } from "./chunk-4YJ6KLGI.js";
3
+ } from "./chunk-QNKBXOIQ.js";
4
4
  import {
5
- searchIssues
6
- } from "./chunk-JAKMZI5S.js";
5
+ getProjectState
6
+ } from "./chunk-6EP2VTHC.js";
7
7
  import {
8
- getGuardianState
9
- } from "./chunk-UHMMANC2.js";
8
+ searchIssues
9
+ } from "./chunk-R3WZI6QZ.js";
10
10
 
11
11
  // src/guardian/hypothesis.ts
12
12
  import { dirname } from "path";
@@ -63,11 +63,11 @@ var HYPOTHESIS_TEMPLATES = [
63
63
  ];
64
64
  var HypothesisEngine = class {
65
65
  projectPath;
66
- guardianState;
66
+ projectState;
67
67
  insightStore;
68
68
  constructor(projectPath) {
69
69
  this.projectPath = projectPath;
70
- this.guardianState = getGuardianState(projectPath);
70
+ this.projectState = getProjectState(projectPath);
71
71
  this.insightStore = getInsightStore(projectPath);
72
72
  }
73
73
  /**
@@ -85,7 +85,7 @@ var HypothesisEngine = class {
85
85
  testCriteria: options?.testCriteria,
86
86
  category: options?.category ?? "general"
87
87
  };
88
- await this.guardianState.addHypothesis(hypothesis);
88
+ await this.projectState.addHypothesis(hypothesis);
89
89
  return hypothesis;
90
90
  }
91
91
  /**
@@ -94,8 +94,8 @@ var HypothesisEngine = class {
94
94
  async autoGenerateHypotheses() {
95
95
  const generated = [];
96
96
  try {
97
- await this.guardianState.load();
98
- const existing = this.guardianState.getAllHypotheses();
97
+ await this.projectState.load();
98
+ const existing = this.projectState.getAllHypotheses();
99
99
  const existingStatements = new Set(existing.map((h) => h.statement.toLowerCase()));
100
100
  const issues = await searchIssues("", {
101
101
  workDir: this.projectPath,
@@ -117,7 +117,7 @@ var HypothesisEngine = class {
117
117
  initialConfidence: evidence[0].weight
118
118
  });
119
119
  for (const e of evidence) {
120
- await this.guardianState.addEvidence(hypothesis.id, e);
120
+ await this.projectState.addEvidence(hypothesis.id, e);
121
121
  }
122
122
  generated.push(hypothesis);
123
123
  if (generated.length >= 2) break;
@@ -139,8 +139,8 @@ var HypothesisEngine = class {
139
139
  }
140
140
  const generated = [];
141
141
  try {
142
- await this.guardianState.load();
143
- const existing = this.guardianState.getAllHypotheses();
142
+ await this.projectState.load();
143
+ const existing = this.projectState.getAllHypotheses();
144
144
  const existingStatements = existing.map((h) => h.statement);
145
145
  const issues = context.recentIssues || await searchIssues("", {
146
146
  workDir: this.projectPath,
@@ -220,7 +220,7 @@ Return empty array [] if no novel hypotheses can be generated from the data.`;
220
220
  testCriteria: aiHypo.testCriteria,
221
221
  initialConfidence: Math.max(0.3, Math.min(0.7, aiHypo.confidence))
222
222
  });
223
- await this.guardianState.addEvidence(hypothesis.id, {
223
+ await this.projectState.addEvidence(hypothesis.id, {
224
224
  type: "supporting",
225
225
  description: `AI observed: ${aiHypo.reasoning}`,
226
226
  weight: aiHypo.confidence
@@ -403,8 +403,8 @@ Day Distribution: ${dayDistribution}`;
403
403
  async updateConfidenceFromOutcomes() {
404
404
  const analyses = [];
405
405
  try {
406
- await this.guardianState.load();
407
- const activeHypotheses = this.guardianState.getActiveHypotheses();
406
+ await this.projectState.load();
407
+ const activeHypotheses = this.projectState.getActiveHypotheses();
408
408
  for (const hypothesis of activeHypotheses) {
409
409
  const analysis = await this.analyzeHypothesis(hypothesis);
410
410
  analyses.push(analysis);
@@ -414,7 +414,7 @@ Day Distribution: ${dayDistribution}`;
414
414
  await this.insightStore.markInsightCreated("hypothesis-update");
415
415
  }
416
416
  }
417
- await this.guardianState.updateHypothesisAccuracy();
417
+ await this.projectState.updateHypothesisAccuracy();
418
418
  } catch (error) {
419
419
  console.error("Failed to update hypothesis confidence:", error);
420
420
  }
@@ -450,24 +450,24 @@ Day Distribution: ${dayDistribution}`;
450
450
  let statusChange;
451
451
  if (newConfidence >= 0.8 && hypothesis.evidence.length >= 3) {
452
452
  statusChange = "validated";
453
- await this.guardianState.updateHypothesis(hypothesis.id, {
453
+ await this.projectState.updateHypothesis(hypothesis.id, {
454
454
  status: "validated",
455
455
  confidence: newConfidence,
456
456
  validatedAt: (/* @__PURE__ */ new Date()).toISOString()
457
457
  });
458
458
  } else if (newConfidence <= 0.2 && hypothesis.evidence.length >= 3) {
459
459
  statusChange = "invalidated";
460
- await this.guardianState.updateHypothesis(hypothesis.id, {
460
+ await this.projectState.updateHypothesis(hypothesis.id, {
461
461
  status: "invalidated",
462
462
  confidence: newConfidence
463
463
  });
464
464
  } else {
465
- await this.guardianState.updateHypothesis(hypothesis.id, {
465
+ await this.projectState.updateHypothesis(hypothesis.id, {
466
466
  confidence: newConfidence
467
467
  });
468
468
  }
469
469
  for (const evidence of recentEvidence) {
470
- await this.guardianState.addEvidence(hypothesis.id, evidence);
470
+ await this.projectState.addEvidence(hypothesis.id, evidence);
471
471
  }
472
472
  const analysis = {
473
473
  hypothesis: { ...hypothesis, confidence: newConfidence },
@@ -659,28 +659,28 @@ Day Distribution: ${dayDistribution}`;
659
659
  * Get hypothesis by ID
660
660
  */
661
661
  async getHypothesis(hypothesisId) {
662
- await this.guardianState.load();
663
- return this.guardianState.getHypothesis(hypothesisId);
662
+ await this.projectState.load();
663
+ return this.projectState.getHypothesis(hypothesisId);
664
664
  }
665
665
  /**
666
666
  * Get all hypotheses
667
667
  */
668
668
  async getAllHypotheses() {
669
- await this.guardianState.load();
670
- return this.guardianState.getAllHypotheses();
669
+ await this.projectState.load();
670
+ return this.projectState.getAllHypotheses();
671
671
  }
672
672
  /**
673
673
  * Get validated hypotheses
674
674
  */
675
675
  async getValidatedHypotheses() {
676
- await this.guardianState.load();
677
- return this.guardianState.getValidatedHypotheses();
676
+ await this.projectState.load();
677
+ return this.projectState.getValidatedHypotheses();
678
678
  }
679
679
  /**
680
680
  * Get hypothesis accuracy stats
681
681
  */
682
682
  getAccuracy() {
683
- const metrics = this.guardianState.getMetrics();
683
+ const metrics = this.projectState.getMetrics();
684
684
  return metrics.hypothesisAccuracy;
685
685
  }
686
686
  };
@@ -698,9 +698,9 @@ function clearHypothesisEngines() {
698
698
  }
699
699
  async function gatherEvidenceForHypothesis(hypothesisId, projectPath) {
700
700
  const engine = getHypothesisEngine(projectPath);
701
- const guardianState = getGuardianState(projectPath);
702
- await guardianState.load();
703
- const hypothesis = guardianState.getAllHypotheses().find((h) => h.id === hypothesisId);
701
+ const projectState = getProjectState(projectPath);
702
+ await projectState.load();
703
+ const hypothesis = projectState.getAllHypotheses().find((h) => h.id === hypothesisId);
704
704
  if (!hypothesis) {
705
705
  throw new Error(`Hypothesis ${hypothesisId} not found`);
706
706
  }
@@ -718,4 +718,4 @@ export {
718
718
  clearHypothesisEngines,
719
719
  gatherEvidenceForHypothesis
720
720
  };
721
- //# sourceMappingURL=chunk-AJ34GCMD.js.map
721
+ //# sourceMappingURL=chunk-DPZLABUC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/guardian/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 './guardian-state.js';\nimport { getProjectState } from './guardian-state.js';\nimport { getInsightStore, type GuardianInsight } 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 }): 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.5,\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 };\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 });\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 });\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): GuardianInsight {\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,EACA;AAAA,EAER,YAAY,aAAqB;AAC/B,SAAK,cAAc;AACnB,SAAK,eAAe,gBAAgB,WAAW;AAC/C,SAAK,eAAe,g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;AACX,aAAS,IAAI,iBAAiB,WAAW;AACzC,sBAAkB,IAAI,aAAa,MAAM;AAAA,EAC3C;AACA,SAAO;AACT;AAKO,SAAS,yBAA+B;AAC7C,oBAAkB,MAAM;AAC1B;AAKA,eAAsB,4BACpB,cACA,aAC4E;AAC5E,QAAM,SAAS,oBAAoB,WAAW;AAC9C,QAAM,eAAe,gBAAgB,WAAW;AAChD,QAAM,aAAa,KAAK;AAExB,QAAM,aAAa,aAAa,iBAAiB,EAAE,KAAK,OAAK,EAAE,OAAO,YAAY;AAClF,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,cAAc,YAAY,YAAY;AAAA,EACxD;AAGA,QAAM,WAAW,MAAO,OAAe,kBAAkB,UAAU;AAGnE,SAAO,SAAS,eAAe,IAAI,CAAC,OAA2B;AAAA,IAC7D,UAAU,EAAE,SAAS;AAAA,IACrB,aAAa,EAAE;AAAA,IACf,QAAQ,EAAE;AAAA,EACZ,EAAE;AACJ;","names":["existing"]}
@@ -1,14 +1,6 @@
1
1
  import {
2
2
  tryGetClient
3
3
  } from "./chunk-O6OTJI3W.js";
4
- import {
5
- searchIssues
6
- } from "./chunk-JAKMZI5S.js";
7
- import {
8
- BackupManager,
9
- GlobalPatternsIndexSchema,
10
- safeParseAndValidate
11
- } from "./chunk-WS6OA7H6.js";
12
4
  import {
13
5
  scanForVulnerabilities
14
6
  } from "./chunk-F4NJ4CBP.js";
@@ -18,6 +10,14 @@ import {
18
10
  import {
19
11
  getStorage
20
12
  } from "./chunk-Z4DN527J.js";
13
+ import {
14
+ searchIssues
15
+ } from "./chunk-R3WZI6QZ.js";
16
+ import {
17
+ BackupManager,
18
+ GlobalPatternsIndexSchema,
19
+ safeParseAndValidate
20
+ } from "./chunk-4MJ52WBH.js";
21
21
  import {
22
22
  atomicWriteJSON
23
23
  } from "./chunk-43X6JBEM.js";
@@ -30,7 +30,7 @@ import { join } from "path";
30
30
  import { homedir } from "os";
31
31
  var GLOBAL_TRIE_DIR = join(homedir(), ".trie");
32
32
  var GLOBAL_MEMORY_DIR = join(GLOBAL_TRIE_DIR, "memory");
33
- async function recordToGlobalMemory(issues, projectName, projectPath, healthScore = 0) {
33
+ async function recordToGlobalMemory(issues, projectName, projectPath) {
34
34
  await mkdir(GLOBAL_MEMORY_DIR, { recursive: true });
35
35
  await mkdir(join(GLOBAL_MEMORY_DIR, "projects"), { recursive: true });
36
36
  const patterns = await loadGlobalPatterns();
@@ -64,7 +64,6 @@ async function recordToGlobalMemory(issues, projectName, projectPath, healthScor
64
64
  name: projectName,
65
65
  path: projectPath,
66
66
  lastScan: now,
67
- healthScore,
68
67
  totalIssues: issues.length,
69
68
  patterns: [...new Set(issues.map((i) => extractPatternId(i)))]
70
69
  };
@@ -164,11 +163,11 @@ async function updateGlobalMemoryMd() {
164
163
  lines.push(
165
164
  "## Tracked Projects",
166
165
  "",
167
- "| Project | Last Scan | Health | Issues |",
168
- "|---------|-----------|--------|--------|"
166
+ "| Project | Last Scan | Issues |",
167
+ "|---------|-----------|--------|"
169
168
  );
170
169
  for (const p of projects.slice(0, 20)) {
171
- lines.push(`| ${p.name} | ${p.lastScan.split("T")[0]} | ${p.healthScore}% | ${p.totalIssues} |`);
170
+ lines.push(`| ${p.name} | ${p.lastScan.split("T")[0]} | ${p.totalIssues} |`);
172
171
  }
173
172
  lines.push("", "---", "", "*This file is auto-generated by Trie. Do not edit manually.*");
174
173
  await mkdir(GLOBAL_MEMORY_DIR, { recursive: true });
@@ -467,4 +466,4 @@ export {
467
466
  searchGlobalPatterns,
468
467
  GotchaPredictor
469
468
  };
470
- //# sourceMappingURL=chunk-UHX4462X.js.map
469
+ //# sourceMappingURL=chunk-G74XEI7K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory/global-memory.ts","../src/guardian/gotcha-predictor.ts"],"sourcesContent":["/**\n * Cross-Project Memory\n * \n * Stores and retrieves patterns across all projects.\n * Location: ~/.trie/memory/\n * \n * Phase 1 Hardening:\n * - SHA256 hashing for pattern IDs\n * - Atomic writes to prevent corruption\n * - Rotational backups for recovery\n * - Zod validation for data integrity\n */\n\nimport { mkdir, writeFile, readFile, readdir } from 'fs/promises';\nimport { createHash } from 'crypto';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport type { Issue } from '../types/index.js';\nimport { atomicWriteJSON } from '../utils/atomic-write.js';\nimport { BackupManager } from '../utils/backup-manager.js';\nimport { GlobalPatternsIndexSchema, safeParseAndValidate } from './validation.js';\n\nconst GLOBAL_TRIE_DIR = join(homedir(), '.trie');\nconst GLOBAL_MEMORY_DIR = join(GLOBAL_TRIE_DIR, 'memory');\n\nexport interface GlobalPattern {\n id: string;\n pattern: string;\n description: string;\n severity: string;\n agent: string;\n occurrences: number;\n projects: string[];\n firstSeen: string;\n lastSeen: string;\n fixApplied?: {\n project: string;\n timestamp: string;\n fix: string;\n };\n}\n\nexport interface ProjectSummary {\n name: string;\n path: string;\n lastScan: string;\n totalIssues: number;\n patterns: string[];\n}\n\n/**\n * Record issues to global memory\n */\nexport async function recordToGlobalMemory(\n issues: Issue[],\n projectName: string,\n projectPath: string\n): Promise<void> {\n await mkdir(GLOBAL_MEMORY_DIR, { recursive: true });\n await mkdir(join(GLOBAL_MEMORY_DIR, 'projects'), { recursive: true });\n\n const patterns = await loadGlobalPatterns();\n const now = new Date().toISOString();\n\n for (const issue of issues) {\n const patternId = extractPatternId(issue);\n const existing = patterns.find(p => p.id === patternId);\n\n if (existing) {\n existing.occurrences++;\n existing.lastSeen = now;\n if (!existing.projects.includes(projectName)) {\n existing.projects.push(projectName);\n }\n } else {\n patterns.push({\n id: patternId,\n pattern: issue.issue.slice(0, 200),\n description: issue.fix.slice(0, 200),\n severity: issue.severity,\n agent: issue.agent,\n occurrences: 1,\n projects: [projectName],\n firstSeen: now,\n lastSeen: now,\n });\n }\n }\n\n await saveGlobalPatterns(patterns);\n\n const summaryPath = join(GLOBAL_MEMORY_DIR, 'projects', `${sanitizeName(projectName)}.json`);\n const summary: ProjectSummary = {\n name: projectName,\n path: projectPath,\n lastScan: now,\n totalIssues: issues.length,\n patterns: [...new Set(issues.map(i => extractPatternId(i)))],\n };\n \n // Use atomic write for project summary\n await atomicWriteJSON(summaryPath, summary);\n}\n\n/**\n * Find patterns that appear across multiple projects\n */\nexport async function findCrossProjectPatterns(\n minOccurrences: number = 2\n): Promise<GlobalPattern[]> {\n const patterns = await loadGlobalPatterns();\n return patterns\n .filter(p => p.projects.length >= minOccurrences)\n .sort((a, b) => b.occurrences - a.occurrences);\n}\n\n/**\n * Check if an issue has been fixed in another project\n */\nexport async function findFixFromOtherProjects(\n issue: Issue\n): Promise<GlobalPattern | null> {\n const patterns = await loadGlobalPatterns();\n const patternId = extractPatternId(issue);\n const pattern = patterns.find(p => p.id === patternId);\n\n if (pattern?.fixApplied) {\n return pattern;\n }\n\n return null;\n}\n\n/**\n * Record that a pattern was fixed\n */\nexport async function recordPatternFix(\n issue: Issue,\n projectName: string,\n fix: string\n): Promise<void> {\n const patterns = await loadGlobalPatterns();\n const patternId = extractPatternId(issue);\n const pattern = patterns.find(p => p.id === patternId);\n\n if (pattern && !pattern.fixApplied) {\n pattern.fixApplied = {\n project: projectName,\n timestamp: new Date().toISOString(),\n fix: fix.slice(0, 500),\n };\n await saveGlobalPatterns(patterns);\n }\n}\n\n/**\n * Get all tracked projects\n */\nexport async function listTrackedProjects(): Promise<ProjectSummary[]> {\n const projectsDir = join(GLOBAL_MEMORY_DIR, 'projects');\n \n try {\n if (!existsSync(projectsDir)) return [];\n \n const files = await readdir(projectsDir);\n const summaries: ProjectSummary[] = [];\n \n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n try {\n const content = await readFile(join(projectsDir, file), 'utf-8');\n summaries.push(JSON.parse(content));\n } catch {\n // Skip invalid files\n }\n }\n \n return summaries.sort((a, b) => \n new Date(b.lastScan).getTime() - new Date(a.lastScan).getTime()\n );\n } catch {\n return [];\n }\n}\n\n/**\n * Get global memory statistics\n */\nexport async function getGlobalMemoryStats(): Promise<{\n totalPatterns: number;\n crossProjectPatterns: number;\n trackedProjects: number;\n totalOccurrences: number;\n fixedPatterns: number;\n patternsByAgent: Record<string, number>;\n capacityInfo: {\n current: number;\n max: number;\n percentFull: number;\n isAtCap: boolean;\n };\n deduplicationStats: {\n uniquePatterns: number;\n averageOccurrences: number;\n };\n}> {\n const patterns = await loadGlobalPatterns();\n const projects = await listTrackedProjects();\n \n const MAX_PATTERNS = 500;\n \n // Count patterns by agent type\n const patternsByAgent: Record<string, number> = {};\n for (const pattern of patterns) {\n patternsByAgent[pattern.agent] = (patternsByAgent[pattern.agent] || 0) + 1;\n }\n \n const totalOccurrences = patterns.reduce((sum, p) => sum + p.occurrences, 0);\n const avgOccurrences = patterns.length > 0 ? totalOccurrences / patterns.length : 0;\n \n return {\n totalPatterns: patterns.length,\n crossProjectPatterns: patterns.filter(p => p.projects.length >= 2).length,\n trackedProjects: projects.length,\n totalOccurrences,\n fixedPatterns: patterns.filter(p => p.fixApplied).length,\n patternsByAgent,\n capacityInfo: {\n current: patterns.length,\n max: MAX_PATTERNS,\n percentFull: Math.round((patterns.length / MAX_PATTERNS) * 100),\n isAtCap: patterns.length >= MAX_PATTERNS,\n },\n deduplicationStats: {\n uniquePatterns: patterns.length,\n averageOccurrences: Math.round(avgOccurrences * 10) / 10,\n },\n };\n}\n\n/**\n * Update GLOBAL_MEMORY.md with current patterns\n */\nexport async function updateGlobalMemoryMd(): Promise<void> {\n const patterns = await loadGlobalPatterns();\n const crossProject = patterns.filter(p => p.projects.length >= 2);\n const projects = await listTrackedProjects();\n\n const lines: string[] = [\n '# Global Trie Memory',\n '',\n '> Auto-generated file tracking patterns across all your projects.',\n `> Last updated: ${new Date().toISOString()}`,\n '',\n '## Summary',\n '',\n `- **Projects tracked:** ${projects.length}`,\n `- **Total patterns:** ${patterns.length}`,\n `- **Cross-project patterns:** ${crossProject.length}`,\n '',\n '## Cross-Project Patterns',\n '',\n 'These issues appear in multiple projects:',\n '',\n ];\n \n for (const p of crossProject.slice(0, 20)) {\n lines.push(\n `### ${p.pattern.slice(0, 60)}${p.pattern.length > 60 ? '...' : ''}`,\n '',\n `- **Severity:** ${p.severity}`,\n `- **Agent:** ${p.agent}`,\n `- **Occurrences:** ${p.occurrences} across ${p.projects.length} projects`,\n `- **Projects:** ${p.projects.slice(0, 5).join(', ')}${p.projects.length > 5 ? '...' : ''}`,\n );\n if (p.fixApplied) {\n lines.push(`- **Fixed in:** ${p.fixApplied.project} on ${p.fixApplied.timestamp.split('T')[0]}`);\n } else {\n lines.push('- **Status:** Not fixed');\n }\n lines.push('');\n }\n\n lines.push(\n '## Tracked Projects',\n '',\n '| Project | Last Scan | Issues |',\n '|---------|-----------|--------|',\n );\n \n for (const p of projects.slice(0, 20)) {\n lines.push(`| ${p.name} | ${p.lastScan.split('T')[0]} | ${p.totalIssues} |`);\n }\n\n lines.push('', '---', '', '*This file is auto-generated by Trie. Do not edit manually.*');\n\n await mkdir(GLOBAL_MEMORY_DIR, { recursive: true });\n await writeFile(join(GLOBAL_MEMORY_DIR, 'GLOBAL_MEMORY.md'), lines.join('\\n'));\n}\n\n/**\n * Search global patterns\n */\nexport async function searchGlobalPatterns(\n query: string,\n options: {\n limit?: number;\n severity?: string[];\n agent?: string;\n } = {}\n): Promise<GlobalPattern[]> {\n const patterns = await loadGlobalPatterns();\n const limit = options.limit || 10;\n const queryTerms = query.toLowerCase().split(/\\s+/).filter(t => t.length > 2);\n \n const scored = patterns\n .filter(p => {\n if (options.severity && !options.severity.includes(p.severity)) return false;\n if (options.agent && p.agent !== options.agent) return false;\n return true;\n })\n .map(p => {\n const text = `${p.pattern} ${p.description} ${p.agent}`.toLowerCase();\n let score = 0;\n for (const term of queryTerms) {\n if (text.includes(term)) score++;\n }\n return { pattern: p, score };\n })\n .filter(s => s.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit);\n \n return scored.map(s => s.pattern);\n}\n\n// Private helpers\n\n/**\n * Load global patterns with validation and auto-recovery\n */\nasync function loadGlobalPatterns(): Promise<GlobalPattern[]> {\n const patternsPath = join(GLOBAL_MEMORY_DIR, 'global-patterns.json');\n \n try {\n if (existsSync(patternsPath)) {\n const content = await readFile(patternsPath, 'utf-8');\n const result = safeParseAndValidate(content, GlobalPatternsIndexSchema);\n \n if (result.success) {\n return result.data as GlobalPattern[];\n }\n \n // Validation failed - attempt recovery\n const backupManager = new BackupManager(patternsPath);\n if (await backupManager.recoverFromBackup()) {\n const recovered = await readFile(patternsPath, 'utf-8');\n const recoveredResult = safeParseAndValidate(recovered, GlobalPatternsIndexSchema);\n if (recoveredResult.success) {\n return recoveredResult.data as GlobalPattern[];\n }\n }\n }\n } catch {\n // File doesn't exist or recovery failed\n }\n \n return [];\n}\n\n/**\n * Save global patterns with backup and atomic write\n */\nasync function saveGlobalPatterns(patterns: GlobalPattern[]): Promise<void> {\n await mkdir(GLOBAL_MEMORY_DIR, { recursive: true });\n const patternsPath = join(GLOBAL_MEMORY_DIR, 'global-patterns.json');\n \n // Intelligent deduplication: merge patterns with same ID\n const patternMap = new Map<string, GlobalPattern>();\n for (const pattern of patterns) {\n const existing = patternMap.get(pattern.id);\n if (existing) {\n // Merge: update occurrences, projects, and timestamps\n existing.occurrences += pattern.occurrences;\n for (const proj of pattern.projects) {\n if (!existing.projects.includes(proj)) {\n existing.projects.push(proj);\n }\n }\n existing.lastSeen = pattern.lastSeen > existing.lastSeen ? pattern.lastSeen : existing.lastSeen;\n } else {\n patternMap.set(pattern.id, pattern);\n }\n }\n \n const deduplicated = Array.from(patternMap.values());\n \n // Intelligent pruning: prioritize recent, high-severity, cross-project patterns\n const pruned = intelligentPruneGlobalPatterns(deduplicated, 500);\n \n // Create backup before writing\n const backupManager = new BackupManager(patternsPath);\n await backupManager.createBackup();\n \n // Atomic write\n await atomicWriteJSON(patternsPath, pruned);\n}\n\n/**\n * Intelligently prune global patterns to target count\n * Prioritizes: cross-project, high severity, recent, fixed patterns\n */\nfunction intelligentPruneGlobalPatterns(patterns: GlobalPattern[], targetCount: number): GlobalPattern[] {\n if (patterns.length <= targetCount) {\n return patterns;\n }\n \n const severityWeight: Record<string, number> = {\n critical: 100,\n high: 50,\n moderate: 20,\n low: 10,\n info: 5,\n };\n \n const scored = patterns.map(pattern => {\n const ageInDays = (Date.now() - new Date(pattern.lastSeen).getTime()) / (1000 * 60 * 60 * 24);\n const recencyScore = Math.max(0, 100 - ageInDays * 2);\n const severityScore = severityWeight[pattern.severity] || 10;\n const crossProjectBonus = (pattern.projects.length - 1) * 30; // More projects = higher score\n const fixedBonus = pattern.fixApplied ? 20 : 0;\n const occurrenceScore = Math.min(pattern.occurrences * 2, 100);\n \n return {\n pattern,\n score: recencyScore + severityScore + crossProjectBonus + fixedBonus + occurrenceScore,\n };\n });\n \n return scored\n .sort((a, b) => b.score - a.score)\n .slice(0, targetCount)\n .map(s => s.pattern);\n}\n\n/**\n * Extract a pattern ID using SHA256 for proper deduplication\n * \n * Normalizes the issue text to group similar patterns:\n * - Lowercases\n * - Replaces code snippets with 'CODE'\n * - Replaces numbers with 'N'\n * - Removes quotes\n * \n * Uses SHA256 truncated to 12 chars for collision-free IDs.\n */\nfunction extractPatternId(issue: Issue): string {\n const normalized = issue.issue\n .toLowerCase()\n .replace(/`[^`]+`/g, 'CODE')\n .replace(/\\b\\d+\\b/g, 'N')\n .replace(/['\"]/g, '')\n .slice(0, 100);\n \n const hash = createHash('sha256')\n .update(normalized)\n .digest('hex')\n .slice(0, 12);\n \n return `${issue.agent}-${issue.severity}-${hash}`;\n}\n\nfunction sanitizeName(name: string): string {\n return name.replace(/[^a-zA-Z0-9-_]/g, '-').toLowerCase();\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { searchIssues } from '../memory/issue-store.js';\nimport { scanForVulnerabilities } from '../trie/vulnerability-signatures.js';\nimport { scanForVibeCodeIssues } from '../trie/vibe-code-signatures.js';\nimport type { LinearTicketNode, LinearTicketNodeData } from '../context/nodes.js';\nimport { tryGetClient } from '../ai/client.js';\nimport { getStorage } from '../storage/tiered-storage.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface GotchaPrediction {\n id: string;\n message: string;\n confidence: number;\n riskLevel: 'low' | 'medium' | 'high' | 'critical';\n precedentId?: string;\n recommendation: string;\n evidence: {\n pastIncidents: string[];\n matchingPatterns: string[];\n relatedTickets: string[];\n };\n}\n\nexport class GotchaPredictor {\n private readonly projectPath: string;\n private readonly graph: ContextGraph;\n\n constructor(projectPath: string, graph: ContextGraph) {\n this.projectPath = projectPath;\n this.graph = graph;\n }\n\n async predictGotchas(changedFiles: string[]): Promise<GotchaPrediction[]> {\n const gotchas: GotchaPrediction[] = [];\n\n // 1. Get active Linear tickets\n const tickets = (await this.graph.listNodes()).filter(n => n.type === 'linear-ticket') as LinearTicketNode[];\n \n for (const file of changedFiles) {\n const fileGotchas = await this.predictForFile(file, tickets);\n gotchas.push(...fileGotchas);\n }\n\n return gotchas;\n }\n\n private async predictForFile(filePath: string, tickets: LinearTicketNode[]): Promise<GotchaPrediction[]> {\n const gotchas: GotchaPrediction[] = [];\n const fullPath = path.resolve(this.projectPath, filePath);\n\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n\n // 1. Run deterministic scanners for signatures\n const vulnerabilities = await scanForVulnerabilities(content, filePath);\n const vibeIssues = await scanForVibeCodeIssues(content, filePath);\n\n const signatures = [\n ...vulnerabilities.map(v => v.category),\n ...vibeIssues.map(v => v.category)\n ];\n\n // === NEW: Query warm storage for relevant decisions and blockers ===\n const storage = getStorage(this.projectPath);\n await storage.initialize();\n\n // Infer tags from file path and signatures\n const tags = this.extractTagsFromFile(filePath, signatures);\n \n // Query relevant decisions for this file/area\n const relevantDecisions = await storage.queryDecisions({\n tags,\n limit: 10,\n });\n\n // Query active blockers for this area\n const activeBlockers = await storage.queryBlockers({\n tags,\n limit: 5,\n });\n\n // === NEW: Add gotchas from decision ledger ===\n for (const decision of relevantDecisions) {\n // Check if this file is in the decision's file list\n if (decision.files.some(f => f.includes(filePath) || filePath.includes(f))) {\n gotchas.push({\n id: `gotcha-decision-${decision.id}`,\n message: `Decision: ${decision.decision}`,\n confidence: 0.85,\n riskLevel: 'medium',\n precedentId: decision.id,\n recommendation: decision.reasoning || 'Review this decision before making changes',\n evidence: {\n pastIncidents: [],\n matchingPatterns: decision.tags,\n relatedTickets: []\n }\n });\n }\n }\n\n // === NEW: Add gotchas from active blockers ===\n for (const blocker of activeBlockers) {\n gotchas.push({\n id: `gotcha-blocker-${blocker.id}`,\n message: `⚠️ Active Blocker: ${blocker.blocker}`,\n confidence: 0.95,\n riskLevel: blocker.impact === 'critical' ? 'critical' : \n blocker.impact === 'high' ? 'high' : 'medium',\n recommendation: `This area is currently blocked. Consider resolving this before making changes.`,\n evidence: {\n pastIncidents: [],\n matchingPatterns: blocker.tags,\n relatedTickets: []\n }\n });\n }\n\n for (const ticket of tickets) {\n const ticketData = ticket.data as LinearTicketNodeData;\n \n // Correlation 1: Ticket Intent vs Deterministic Signatures\n const intentMatch = this.correlateIntentWithSignatures(ticketData, signatures);\n if (intentMatch) {\n gotchas.push(intentMatch);\n }\n\n // Correlation 2: Historical Precedents\n const historicalPrecedents = await this.findHistoricalPrecedents(filePath, ticketData);\n if (historicalPrecedents) {\n gotchas.push(historicalPrecedents);\n }\n }\n\n return gotchas;\n }\n\n /**\n * Extract tags from file path and signatures for storage queries\n */\n private extractTagsFromFile(filePath: string, signatures: string[]): string[] {\n const tags = new Set<string>();\n\n // Add tags from file path\n const normalized = filePath.toLowerCase();\n if (normalized.includes('/auth/')) tags.add('auth');\n if (normalized.includes('/payment/')) tags.add('payments');\n if (normalized.includes('/api/')) tags.add('api');\n if (normalized.includes('/frontend/') || normalized.includes('/ui/')) tags.add('ui');\n if (normalized.includes('/backend/')) tags.add('backend');\n if (normalized.includes('/database/') || normalized.includes('/models/')) tags.add('database');\n\n // Add tags from signatures\n signatures.forEach(sig => tags.add(sig.toLowerCase()));\n\n return Array.from(tags);\n }\n\n private correlateIntentWithSignatures(ticket: LinearTicketNodeData, signatures: string[]): GotchaPrediction | null {\n const relevantSignatures = signatures.filter(sig => \n ticket.intentVibe.some(vibe => this.vibeToSignatureMap(vibe).includes(sig))\n );\n\n if (relevantSignatures.length > 0) {\n return {\n id: `gotcha-intent-${ticket.ticketId}-${Date.now()}`,\n message: `[${ticket.ticketId}] Working on \"${ticket.title}\" (${ticket.intentVibe.join(', ')}) in a file with ${relevantSignatures.join(', ')} signatures.`,\n confidence: 0.8,\n riskLevel: 'high',\n recommendation: `Be careful with ${relevantSignatures[0]} patterns as they correlate with the intent of your ticket.`,\n evidence: {\n pastIncidents: [],\n matchingPatterns: relevantSignatures,\n relatedTickets: [ticket.ticketId]\n }\n };\n }\n\n return null;\n }\n\n private async findHistoricalPrecedents(filePath: string, ticket: LinearTicketNodeData): Promise<GotchaPrediction | null> {\n // Search for historical issues similar to this ticket's description\n const similarIssues = await searchIssues(ticket.description, {\n workDir: this.projectPath,\n limit: 3\n });\n\n const relevantIssues = similarIssues.filter(r => r.issue.file === filePath || r.issue.file.includes(path.basename(filePath)));\n\n const [firstMatch] = relevantIssues;\n if (firstMatch) {\n const issue = firstMatch.issue;\n return {\n id: `gotcha-precedent-${ticket.ticketId}-${Date.now()}`,\n message: `A similar task in the past caused an issue: \"${issue.issue}\"`,\n confidence: 0.9,\n riskLevel: 'critical',\n precedentId: issue.id,\n recommendation: `Last time we worked on something similar here, we had to fix: \"${issue.fix}\". Check this first.`,\n evidence: {\n pastIncidents: [issue.id],\n matchingPatterns: [],\n relatedTickets: [ticket.ticketId]\n }\n };\n }\n\n return null;\n }\n\n private vibeToSignatureMap(vibe: string): string[] {\n const map: Record<string, string[]> = {\n 'performance': ['giant-file', 'performance', 'react-antipattern'],\n 'security': ['injection', 'secrets', 'auth', 'xss', 'crypto'],\n 'auth': ['auth', 'secrets', 'config'],\n 'bug': ['no-error-handling', 'async', 'error-handling'],\n 'feature': ['mixing-concerns', 'hardcoded'],\n 'refactor': ['code-smell', 'giant-file', 'mixing-concerns']\n };\n return map[vibe] || [];\n }\n\n async synthesizeGotchaExplanation(gotcha: GotchaPrediction): Promise<string> {\n const client = tryGetClient();\n if (!client) return gotcha.message;\n\n const prompt = `\n You are a JIT Defect Predictor. You found a potential \"gotcha\" for a developer.\n \n Ticket context: ${gotcha.evidence.relatedTickets.join(', ')}\n Signatures detected: ${gotcha.evidence.matchingPatterns.join(', ')}\n Past incidents: ${gotcha.evidence.pastIncidents.join(', ')}\n \n Raw message: ${gotcha.message}\n Recommendation: ${gotcha.recommendation}\n \n Explain this gotcha in a concise, human-friendly way (max 2 sentences). \n Make it sound like a senior dev giving a helpful nudge.\n `;\n\n try {\n const response = await client.messages.create({\n model: 'claude-3-5-sonnet-20240620',\n max_tokens: 100,\n messages: [{ role: 'user', content: prompt }]\n });\n\n const text = response.content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map(block => block.text)\n .join('');\n \n return text.trim() || gotcha.message;\n } catch {\n return gotcha.message;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,OAAO,WAAW,UAAU,eAAe;AACpD,SAAS,kBAAkB;AAC3B,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,eAAe;AAMxB,IAAM,kBAAkB,KAAK,QAAQ,GAAG,OAAO;AAC/C,IAAM,oBAAoB,KAAK,iBAAiB,QAAQ;AA8BxD,eAAsB,qBACpB,QACA,aACA,aACe;AACf,QAAM,MAAM,mBAAmB,EAAE,WAAW,KAAK,CAAC;AAClD,QAAM,MAAM,KAAK,mBAAmB,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;AAEpE,QAAM,WAAW,MAAM,mBAAmB;AAC1C,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AAEnC,aAAW,SAAS,QAAQ;AAC1B,UAAM,YAAY,iBAAiB,KAAK;AACxC,UAAM,WAAW,SAAS,KAAK,OAAK,EAAE,OAAO,SAAS;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S,OAAO;AAAA,QAC5C,OAAO;AAAA,QACP,YAAY;AAAA,QACZ,UAAU,CAAC,EAAE,MAAM,QAAQ,SAAS,OAAO,CAAC;AAAA,MAC9C,CAAC;AAED,YAAM,OAAO,SAAS,QACnB,OAAO,CAAC,UAAmD,MAAM,SAAS,MAAM,EAChF,IAAI,WAAS,MAAM,IAAI,EACvB,KAAK,EAAE;AAEV,aAAO,KAAK,KAAK,KAAK,OAAO;AAAA,IAC/B,QAAQ;AACN,aAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;","names":[]}
@@ -1,24 +1,22 @@
1
1
  import {
2
- getGuardianState
3
- } from "./chunk-UHMMANC2.js";
4
- import "./chunk-WS6OA7H6.js";
5
- import "./chunk-43X6JBEM.js";
6
- import "./chunk-45Y5TLQZ.js";
7
- import "./chunk-APMV77PU.js";
8
- import "./chunk-DGUM43GV.js";
2
+ getProjectState
3
+ } from "./chunk-6EP2VTHC.js";
4
+ import {
5
+ searchIssues
6
+ } from "./chunk-R3WZI6QZ.js";
9
7
 
10
8
  // src/guardian/goal-validator.ts
11
9
  async function getActiveGoals(projectPath) {
12
- const guardianState = getGuardianState(projectPath);
13
- await guardianState.load();
14
- return guardianState.getAllGoals().filter((g) => g.status === "active");
10
+ const projectState = getProjectState(projectPath);
11
+ await projectState.load();
12
+ return projectState.getAllGoals().filter((g) => g.status === "active");
15
13
  }
16
14
  async function recordGoalViolationCaught(goal, file, projectPath) {
17
- const guardianState = getGuardianState(projectPath);
18
- await guardianState.load();
15
+ const projectState = getProjectState(projectPath);
16
+ await projectState.load();
19
17
  const metadata = goal.metadata || {};
20
18
  const caughtCount = (metadata.caughtCount || 0) + 1;
21
- await guardianState.updateGoal(goal.id, {
19
+ await projectState.updateGoal(goal.id, {
22
20
  metadata: {
23
21
  ...metadata,
24
22
  caughtCount,
@@ -28,31 +26,65 @@ async function recordGoalViolationCaught(goal, file, projectPath) {
28
26
  });
29
27
  }
30
28
  async function recordGoalViolationFixed(goal, file, projectPath) {
31
- const guardianState = getGuardianState(projectPath);
32
- await guardianState.load();
29
+ const projectState = getProjectState(projectPath);
30
+ await projectState.load();
33
31
  const metadata = goal.metadata || {};
34
- const caughtCount = (metadata.caughtCount || 0) + 1;
35
32
  const fixedCount = (metadata.fixedCount || 0) + 1;
36
- await guardianState.updateGoal(goal.id, {
33
+ await projectState.updateGoal(goal.id, {
37
34
  metadata: {
38
35
  ...metadata,
39
- caughtCount,
40
36
  fixedCount,
41
37
  lastFixed: (/* @__PURE__ */ new Date()).toISOString(),
42
38
  lastFixedFile: file
43
39
  }
44
40
  });
45
- if (goal.type === "reduction") {
46
- const newValue = Math.max(0, goal.currentValue - 1);
47
- await guardianState.updateGoal(goal.id, {
48
- currentValue: newValue
41
+ const { resolveGoalViolation } = await import("./issue-store-EZMBHOVN.js");
42
+ await resolveGoalViolation(file, goal.description, projectPath);
43
+ const { getGoalManager } = await import("./goal-manager-62IL6WGY.js");
44
+ const goalManager = getGoalManager(projectPath);
45
+ await goalManager.updateGoalProgress();
46
+ }
47
+ async function measureInitialGoalValue(description, projectPath) {
48
+ try {
49
+ const issues = await searchIssues("", {
50
+ workDir: projectPath,
51
+ limit: 1e3,
52
+ includeResolved: false
49
53
  });
50
- if (newValue <= goal.target) {
51
- await guardianState.updateGoal(goal.id, {
52
- status: "achieved",
53
- achievedAt: (/* @__PURE__ */ new Date()).toISOString()
54
- });
54
+ if (issues.length === 0) {
55
+ return 0;
56
+ }
57
+ const desc = description.toLowerCase();
58
+ const goalViolations = issues.filter(
59
+ (r) => r.issue.agent === "goal-violation" && r.issue.issue.toLowerCase().includes(desc.slice(0, 30))
60
+ );
61
+ if (goalViolations.length > 0) {
62
+ return goalViolations.length;
55
63
  }
64
+ if (desc.includes("security") || desc.includes("vulnerab")) {
65
+ return issues.filter(
66
+ (r) => r.issue.agent === "security" || r.issue.severity === "critical"
67
+ ).length;
68
+ }
69
+ if (desc.includes("type") || desc.includes("typescript") || desc.includes("any type")) {
70
+ return issues.filter(
71
+ (r) => r.issue.agent === "typecheck" || r.issue.issue.toLowerCase().includes("type")
72
+ ).length;
73
+ }
74
+ if (desc.includes("bug") || desc.includes("error")) {
75
+ return issues.filter(
76
+ (r) => r.issue.agent === "bug-finding" || r.issue.severity === "critical" || r.issue.severity === "serious"
77
+ ).length;
78
+ }
79
+ if (desc.includes("dead code") || desc.includes("unused")) {
80
+ return issues.filter((r) => {
81
+ const msg = r.issue.issue.toLowerCase();
82
+ return msg.includes("unused") || msg.includes("dead code") || msg.includes("never used");
83
+ }).length;
84
+ }
85
+ return 0;
86
+ } catch {
87
+ return 0;
56
88
  }
57
89
  }
58
90
  async function checkFilesForGoalViolations(goals, projectPath, filesToCheck, onProgress) {
@@ -243,13 +275,15 @@ ${filesBlock}`,
243
275
  const cleaned = result.content.replace(/```json?\n?|\n?```/g, "").trim();
244
276
  issues = JSON.parse(cleaned);
245
277
  if (!Array.isArray(issues)) issues = [];
246
- } catch {
278
+ } catch (err) {
279
+ console.debug("[Goal Check] Batch parse failed:", err);
247
280
  continue;
248
281
  }
249
282
  for (const issue of issues) {
250
283
  if (!issue.isGoalViolation || issue.confidence < 50) continue;
251
284
  if (issue.goalIndex == null || issue.goalIndex < 0 || issue.goalIndex >= goals.length) continue;
252
285
  const goal = goals[issue.goalIndex];
286
+ if (!goal) continue;
253
287
  const severity = issue.severity === "critical" ? "critical" : "warning";
254
288
  const message = `Goal "${goal.description}" violated in ${issue.file}: ${issue.description} [${issue.confidence}% confidence]`;
255
289
  allViolations.push({
@@ -269,8 +303,10 @@ ${filesBlock}`,
269
303
  await recordGoalViolationCaught(goal, issue.file, projectPath);
270
304
  }
271
305
  for (const file of validFiles) {
272
- for (const goal of goals) {
273
- const hasViolation = issues.some((i) => i.file === file.path && i.goalIndex === goals.indexOf(goal));
306
+ for (let goalIdx = 0; goalIdx < goals.length; goalIdx++) {
307
+ const goal = goals[goalIdx];
308
+ if (!goal) continue;
309
+ const hasViolation = issues.some((i) => i.file === file.path && i.goalIndex === goalIdx);
274
310
  if (!hasViolation) {
275
311
  codebaseIndex.recordViolation(
276
312
  file.path,
@@ -288,10 +324,12 @@ ${filesBlock}`,
288
324
  await codebaseIndex.save();
289
325
  return allViolations;
290
326
  }
327
+
291
328
  export {
292
- checkFilesForGoalViolations,
293
329
  getActiveGoals,
294
330
  recordGoalViolationCaught,
295
- recordGoalViolationFixed
331
+ recordGoalViolationFixed,
332
+ measureInitialGoalValue,
333
+ checkFilesForGoalViolations
296
334
  };
297
- //# sourceMappingURL=goal-validator-PDKYZSNP.js.map
335
+ //# sourceMappingURL=chunk-HUR67JXG.js.map