@triedotdev/mcp 1.0.113 → 1.0.114

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 (75) hide show
  1. package/dist/auto-fix-apply-PCAHWLXF.js +10 -0
  2. package/dist/autonomy-config-O4H3Z7YV.js +30 -0
  3. package/dist/chunk-2GIAROBF.js +173 -0
  4. package/dist/chunk-2GIAROBF.js.map +1 -0
  5. package/dist/{chunk-33WL3D7A.js → chunk-2SIFK7OW.js} +7 -419
  6. package/dist/chunk-2SIFK7OW.js.map +1 -0
  7. package/dist/chunk-43X6JBEM.js +36 -0
  8. package/dist/chunk-43X6JBEM.js.map +1 -0
  9. package/dist/{chunk-2764KZZQ.js → chunk-4SBZXIMG.js} +133 -595
  10. package/dist/chunk-4SBZXIMG.js.map +1 -0
  11. package/dist/chunk-55DOQNHJ.js +772 -0
  12. package/dist/chunk-55DOQNHJ.js.map +1 -0
  13. package/dist/chunk-6LXSA2OZ.js +425 -0
  14. package/dist/chunk-6LXSA2OZ.js.map +1 -0
  15. package/dist/{chunk-SDS3UVFY.js → chunk-AOFYU6T3.js} +113 -559
  16. package/dist/chunk-AOFYU6T3.js.map +1 -0
  17. package/dist/{chunk-6QR6QZIX.js → chunk-D3EXBJE2.js} +25 -658
  18. package/dist/chunk-D3EXBJE2.js.map +1 -0
  19. package/dist/chunk-DJ2YAGHK.js +50 -0
  20. package/dist/chunk-DJ2YAGHK.js.map +1 -0
  21. package/dist/chunk-DRDEEF6G.js +328 -0
  22. package/dist/chunk-DRDEEF6G.js.map +1 -0
  23. package/dist/chunk-DZREHOGW.js +706 -0
  24. package/dist/chunk-DZREHOGW.js.map +1 -0
  25. package/dist/chunk-KRH642MT.js +947 -0
  26. package/dist/chunk-KRH642MT.js.map +1 -0
  27. package/dist/{chunk-QYOACM2C.js → chunk-MVNJPJBK.js} +22 -252
  28. package/dist/chunk-MVNJPJBK.js.map +1 -0
  29. package/dist/chunk-NS2MSZMB.js +394 -0
  30. package/dist/chunk-NS2MSZMB.js.map +1 -0
  31. package/dist/chunk-SWSK7ANT.js +340 -0
  32. package/dist/chunk-SWSK7ANT.js.map +1 -0
  33. package/dist/chunk-VRLMTOB6.js +566 -0
  34. package/dist/chunk-VRLMTOB6.js.map +1 -0
  35. package/dist/chunk-YR4BMGYO.js +130 -0
  36. package/dist/chunk-YR4BMGYO.js.map +1 -0
  37. package/dist/chunk-ZV2K6M7T.js +74 -0
  38. package/dist/chunk-ZV2K6M7T.js.map +1 -0
  39. package/dist/cli/main.js +107 -375
  40. package/dist/cli/main.js.map +1 -1
  41. package/dist/cli/yolo-daemon.js +18 -8
  42. package/dist/cli/yolo-daemon.js.map +1 -1
  43. package/dist/client-7XZHCMD3.js +28 -0
  44. package/dist/client-7XZHCMD3.js.map +1 -0
  45. package/dist/{goal-manager-AP4LTE6U.js → goal-manager-LMS6ZJB7.js} +7 -3
  46. package/dist/goal-manager-LMS6ZJB7.js.map +1 -0
  47. package/dist/goal-validator-7UPLOVAZ.js +184 -0
  48. package/dist/goal-validator-7UPLOVAZ.js.map +1 -0
  49. package/dist/graph-U5JWSAB5.js +10 -0
  50. package/dist/graph-U5JWSAB5.js.map +1 -0
  51. package/dist/guardian-agent-EXP7APLC.js +25 -0
  52. package/dist/guardian-agent-EXP7APLC.js.map +1 -0
  53. package/dist/hypothesis-KGC3P54C.js +19 -0
  54. package/dist/hypothesis-KGC3P54C.js.map +1 -0
  55. package/dist/incident-index-PNIVT47T.js +11 -0
  56. package/dist/incident-index-PNIVT47T.js.map +1 -0
  57. package/dist/index.js +285 -16
  58. package/dist/index.js.map +1 -1
  59. package/dist/ledger-SR6OEBLO.js +15 -0
  60. package/dist/ledger-SR6OEBLO.js.map +1 -0
  61. package/dist/output-manager-BOTMXSND.js +13 -0
  62. package/dist/output-manager-BOTMXSND.js.map +1 -0
  63. package/dist/pattern-discovery-F7LU5K6E.js +8 -0
  64. package/dist/pattern-discovery-F7LU5K6E.js.map +1 -0
  65. package/package.json +1 -1
  66. package/dist/chunk-2764KZZQ.js.map +0 -1
  67. package/dist/chunk-33WL3D7A.js.map +0 -1
  68. package/dist/chunk-6JPPYG7F.js +0 -1813
  69. package/dist/chunk-6JPPYG7F.js.map +0 -1
  70. package/dist/chunk-6QR6QZIX.js.map +0 -1
  71. package/dist/chunk-QYOACM2C.js.map +0 -1
  72. package/dist/chunk-SDS3UVFY.js.map +0 -1
  73. package/dist/guardian-agent-XEYNG7RH.js +0 -18
  74. /package/dist/{goal-manager-AP4LTE6U.js.map → auto-fix-apply-PCAHWLXF.js.map} +0 -0
  75. /package/dist/{guardian-agent-XEYNG7RH.js.map → autonomy-config-O4H3Z7YV.js.map} +0 -0
@@ -0,0 +1,706 @@
1
+ import {
2
+ getInsightStore
3
+ } from "./chunk-6LXSA2OZ.js";
4
+ import {
5
+ searchIssues
6
+ } from "./chunk-55DOQNHJ.js";
7
+ import {
8
+ getGuardianState
9
+ } from "./chunk-KRH642MT.js";
10
+
11
+ // src/guardian/hypothesis.ts
12
+ import { dirname } from "path";
13
+ var HYPOTHESIS_TEMPLATES = [
14
+ {
15
+ category: "timing",
16
+ statement: "Issues spike after weekend deployments",
17
+ testCriteria: "Compare Monday issue counts to other days",
18
+ minConfidence: 0.3,
19
+ dataRequired: ["issue_timestamps", "deployment_data"]
20
+ },
21
+ {
22
+ category: "timing",
23
+ statement: "Code quality declines on Fridays",
24
+ testCriteria: "Compare Friday issue introduction rate to weekly average",
25
+ minConfidence: 0.3,
26
+ dataRequired: ["issue_timestamps"]
27
+ },
28
+ {
29
+ category: "pattern",
30
+ statement: "Auth-related code has the highest incident rate",
31
+ testCriteria: "Compare auth/ issue count to other directories",
32
+ minConfidence: 0.4,
33
+ dataRequired: ["issue_files"]
34
+ },
35
+ {
36
+ category: "pattern",
37
+ statement: "Security issues cluster in specific directories",
38
+ testCriteria: "Check if security issues are concentrated (>50% in <3 dirs)",
39
+ minConfidence: 0.4,
40
+ dataRequired: ["issue_files", "issue_agents"]
41
+ },
42
+ {
43
+ category: "code",
44
+ statement: "Files with multiple authors have more issues",
45
+ testCriteria: "Correlate file author count with issue count",
46
+ minConfidence: 0.4,
47
+ dataRequired: ["issue_files", "git_blame"]
48
+ },
49
+ {
50
+ category: "code",
51
+ statement: "Recently modified files are more likely to have issues",
52
+ testCriteria: "Compare issue rate for recent vs old files",
53
+ minConfidence: 0.3,
54
+ dataRequired: ["issue_timestamps", "file_modification_times"]
55
+ },
56
+ {
57
+ category: "pattern",
58
+ statement: "Critical issues often come in clusters",
59
+ testCriteria: "Check temporal clustering of critical issues",
60
+ minConfidence: 0.3,
61
+ dataRequired: ["issue_timestamps", "issue_severities"]
62
+ }
63
+ ];
64
+ var HypothesisEngine = class {
65
+ projectPath;
66
+ guardianState;
67
+ insightStore;
68
+ constructor(projectPath) {
69
+ this.projectPath = projectPath;
70
+ this.guardianState = getGuardianState(projectPath);
71
+ this.insightStore = getInsightStore(projectPath);
72
+ }
73
+ /**
74
+ * Create a new hypothesis
75
+ */
76
+ async createHypothesis(statement, options) {
77
+ const hypothesis = {
78
+ id: `hyp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
79
+ statement,
80
+ confidence: options?.initialConfidence ?? 0.5,
81
+ status: "proposed",
82
+ evidence: [],
83
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
84
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
85
+ testCriteria: options?.testCriteria,
86
+ category: options?.category ?? "general"
87
+ };
88
+ await this.guardianState.addHypothesis(hypothesis);
89
+ return hypothesis;
90
+ }
91
+ /**
92
+ * Auto-generate hypotheses based on detected patterns
93
+ */
94
+ async autoGenerateHypotheses() {
95
+ const generated = [];
96
+ try {
97
+ await this.guardianState.load();
98
+ const existing = this.guardianState.getAllHypotheses();
99
+ const existingStatements = new Set(existing.map((h) => h.statement.toLowerCase()));
100
+ const issues = await searchIssues("", {
101
+ workDir: this.projectPath,
102
+ limit: 500,
103
+ includeResolved: true
104
+ });
105
+ if (issues.length < 10) {
106
+ return generated;
107
+ }
108
+ for (const template of HYPOTHESIS_TEMPLATES) {
109
+ if (existingStatements.has(template.statement.toLowerCase())) {
110
+ continue;
111
+ }
112
+ const evidence = await this.gatherInitialEvidence(template, issues);
113
+ if (evidence.length > 0 && evidence[0].weight >= template.minConfidence) {
114
+ const hypothesis = await this.createHypothesis(template.statement, {
115
+ category: template.category,
116
+ testCriteria: template.testCriteria,
117
+ initialConfidence: evidence[0].weight
118
+ });
119
+ for (const e of evidence) {
120
+ await this.guardianState.addEvidence(hypothesis.id, e);
121
+ }
122
+ generated.push(hypothesis);
123
+ if (generated.length >= 2) break;
124
+ }
125
+ }
126
+ } catch (error) {
127
+ console.error("Failed to auto-generate hypotheses:", error);
128
+ }
129
+ return generated;
130
+ }
131
+ /**
132
+ * Use Claude AI to generate novel hypotheses from observed patterns
133
+ * This enables fully agentic hypothesis creation based on actual codebase observations
134
+ */
135
+ async generateHypothesesWithAI(context) {
136
+ const { isAIAvailable, runAIAnalysis } = await import("./client-7XZHCMD3.js");
137
+ if (!isAIAvailable()) {
138
+ return [];
139
+ }
140
+ const generated = [];
141
+ try {
142
+ await this.guardianState.load();
143
+ const existing = this.guardianState.getAllHypotheses();
144
+ const existingStatements = existing.map((h) => h.statement);
145
+ const issues = context.recentIssues || await searchIssues("", {
146
+ workDir: this.projectPath,
147
+ limit: 100,
148
+ includeResolved: true
149
+ });
150
+ if (issues.length < 5) {
151
+ return generated;
152
+ }
153
+ const issuesSummary = this.summarizeIssuesForAI(issues);
154
+ const patternsSummary = context.patterns?.join("\n") || "No explicit patterns provided";
155
+ const observationsSummary = context.observations?.join("\n") || "No explicit observations provided";
156
+ 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.
157
+
158
+ ## Recent Issues Summary
159
+ ${issuesSummary}
160
+
161
+ ## Observed Patterns
162
+ ${patternsSummary}
163
+
164
+ ## Additional Observations
165
+ ${observationsSummary}
166
+
167
+ ## Existing Hypotheses (avoid duplicates)
168
+ ${existingStatements.length > 0 ? existingStatements.map((s) => `- ${s}`).join("\n") : "None yet"}
169
+
170
+ Generate hypotheses that are:
171
+ 1. Specific and testable (can be validated with data)
172
+ 2. Actionable (if validated, can guide improvements)
173
+ 3. Novel (not duplicates of existing hypotheses)
174
+ 4. Based on real patterns in the data above
175
+
176
+ Return ONLY a JSON array of hypotheses. Each hypothesis must have:
177
+ - "statement": Clear, concise hypothesis statement
178
+ - "category": One of: "timing", "pattern", "team", "code", "general"
179
+ - "testCriteria": How to test this hypothesis
180
+ - "confidence": Initial confidence (0-1)
181
+ - "reasoning": Why you think this hypothesis is worth testing
182
+
183
+ Example format:
184
+ [
185
+ {
186
+ "statement": "Authentication code changes correlate with security issues",
187
+ "category": "pattern",
188
+ "testCriteria": "Track auth file changes and subsequent security issue rates",
189
+ "confidence": 0.6,
190
+ "reasoning": "65% of security issues occur in files modified in the past week"
191
+ }
192
+ ]
193
+
194
+ Return empty array [] if no novel hypotheses can be generated from the data.`;
195
+ const result = await runAIAnalysis({
196
+ systemPrompt: "You are an expert code quality analyst who identifies patterns and generates testable hypotheses.",
197
+ userPrompt: prompt,
198
+ maxTokens: 1024,
199
+ temperature: 0.7
200
+ // Higher temperature for creative hypothesis generation
201
+ });
202
+ if (!result.success || !result.content.trim()) {
203
+ return generated;
204
+ }
205
+ let aiHypotheses = [];
206
+ try {
207
+ const cleaned = result.content.replace(/```json?\n?|\n?```/g, "").trim();
208
+ aiHypotheses = JSON.parse(cleaned);
209
+ if (!Array.isArray(aiHypotheses)) aiHypotheses = [];
210
+ } catch {
211
+ return generated;
212
+ }
213
+ for (const aiHypo of aiHypotheses.slice(0, 3)) {
214
+ const isDuplicate = existingStatements.some(
215
+ (existing2) => existing2.toLowerCase().includes(aiHypo.statement.toLowerCase().slice(0, 30))
216
+ );
217
+ if (isDuplicate) continue;
218
+ const hypothesis = await this.createHypothesis(aiHypo.statement, {
219
+ category: aiHypo.category,
220
+ testCriteria: aiHypo.testCriteria,
221
+ initialConfidence: Math.max(0.3, Math.min(0.7, aiHypo.confidence))
222
+ });
223
+ await this.guardianState.addEvidence(hypothesis.id, {
224
+ type: "supporting",
225
+ description: `AI observed: ${aiHypo.reasoning}`,
226
+ weight: aiHypo.confidence,
227
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
228
+ });
229
+ generated.push(hypothesis);
230
+ }
231
+ } catch (error) {
232
+ console.error("Failed to generate hypotheses with AI:", error);
233
+ }
234
+ return generated;
235
+ }
236
+ /**
237
+ * Summarize issues for AI context
238
+ */
239
+ summarizeIssuesForAI(issues) {
240
+ const totalIssues = issues.length;
241
+ const severityCounts = {};
242
+ for (const { issue } of issues) {
243
+ severityCounts[issue.severity] = (severityCounts[issue.severity] || 0) + 1;
244
+ }
245
+ const agentCounts = {};
246
+ for (const { issue } of issues) {
247
+ agentCounts[issue.agent] = (agentCounts[issue.agent] || 0) + 1;
248
+ }
249
+ const fileCounts = {};
250
+ for (const { issue } of issues) {
251
+ const dir = dirname(issue.file);
252
+ fileCounts[dir] = (fileCounts[dir] || 0) + 1;
253
+ }
254
+ const dayOfWeekCounts = {};
255
+ for (const { issue } of issues) {
256
+ const date = new Date(issue.timestamp);
257
+ const day = date.getDay();
258
+ dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;
259
+ }
260
+ const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
261
+ const dayDistribution = Object.entries(dayOfWeekCounts).sort(([a], [b]) => Number(a) - Number(b)).map(([day, count]) => `${dayNames[Number(day)]}: ${count}`).join(", ");
262
+ const topDirs = Object.entries(fileCounts).sort(([, a], [, b]) => b - a).slice(0, 5).map(([dir, count]) => `${dir}: ${count}`).join(", ");
263
+ const topAgents = Object.entries(agentCounts).sort(([, a], [, b]) => b - a).slice(0, 5).map(([agent, count]) => `${agent}: ${count}`).join(", ");
264
+ return `Total Issues: ${totalIssues}
265
+ Severities: ${Object.entries(severityCounts).map(([s, c]) => `${s}=${c}`).join(", ")}
266
+ Top Agents: ${topAgents}
267
+ Top Directories: ${topDirs}
268
+ Day Distribution: ${dayDistribution}`;
269
+ }
270
+ /**
271
+ * Gather initial evidence for a hypothesis template
272
+ */
273
+ async gatherInitialEvidence(template, issues) {
274
+ const evidence = [];
275
+ switch (template.category) {
276
+ case "timing":
277
+ evidence.push(...this.analyzeTimingPatterns(template, issues));
278
+ break;
279
+ case "pattern":
280
+ evidence.push(...this.analyzeLocationPatterns(template, issues));
281
+ break;
282
+ case "code":
283
+ evidence.push(...this.analyzeCodePatterns(template, issues));
284
+ break;
285
+ }
286
+ return evidence;
287
+ }
288
+ /**
289
+ * Analyze timing patterns in issues
290
+ */
291
+ analyzeTimingPatterns(template, issues) {
292
+ const evidence = [];
293
+ const dayOfWeekCounts = {};
294
+ for (const { issue } of issues) {
295
+ const date = new Date(issue.timestamp);
296
+ const day = date.getDay();
297
+ dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;
298
+ }
299
+ if (template.statement.includes("Friday")) {
300
+ const fridayCount = dayOfWeekCounts[5] || 0;
301
+ const avgOtherDays = (Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0) - fridayCount) / 4;
302
+ if (fridayCount > avgOtherDays * 1.5) {
303
+ evidence.push({
304
+ type: "supporting",
305
+ description: `Friday has ${((fridayCount / avgOtherDays - 1) * 100).toFixed(0)}% more issues than average`,
306
+ weight: Math.min(0.8, 0.3 + (fridayCount / avgOtherDays - 1) * 0.2),
307
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
308
+ });
309
+ } else {
310
+ evidence.push({
311
+ type: "contradicting",
312
+ description: "Friday issue count is not significantly higher",
313
+ weight: 0.3,
314
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
315
+ });
316
+ }
317
+ }
318
+ if (template.statement.includes("weekend") || template.statement.includes("Monday")) {
319
+ const mondayCount = dayOfWeekCounts[1] || 0;
320
+ const avgOtherDays = (Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0) - mondayCount) / 4;
321
+ if (mondayCount > avgOtherDays * 1.5) {
322
+ evidence.push({
323
+ type: "supporting",
324
+ description: `Monday has ${((mondayCount / avgOtherDays - 1) * 100).toFixed(0)}% more issues than average`,
325
+ weight: Math.min(0.8, 0.3 + (mondayCount / avgOtherDays - 1) * 0.2),
326
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
327
+ });
328
+ }
329
+ }
330
+ return evidence;
331
+ }
332
+ /**
333
+ * Analyze location patterns in issues
334
+ */
335
+ analyzeLocationPatterns(template, issues) {
336
+ const evidence = [];
337
+ const dirCounts = {};
338
+ for (const { issue } of issues) {
339
+ const dir = dirname(issue.file);
340
+ dirCounts[dir] = (dirCounts[dir] || 0) + 1;
341
+ }
342
+ const sortedDirs = Object.entries(dirCounts).sort(([, a], [, b]) => b - a);
343
+ if (template.statement.includes("Auth")) {
344
+ const authDirs = sortedDirs.filter(
345
+ ([dir]) => dir.toLowerCase().includes("auth") || dir.toLowerCase().includes("login") || dir.toLowerCase().includes("session")
346
+ );
347
+ const authCount = authDirs.reduce((sum, [, count]) => sum + count, 0);
348
+ const percentage = authCount / issues.length * 100;
349
+ if (percentage >= 20) {
350
+ evidence.push({
351
+ type: "supporting",
352
+ description: `Auth-related code has ${percentage.toFixed(0)}% of issues`,
353
+ weight: Math.min(0.85, 0.4 + percentage / 100),
354
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
355
+ });
356
+ }
357
+ }
358
+ if (template.statement.includes("cluster")) {
359
+ const topThreeDirs = sortedDirs.slice(0, 3);
360
+ const topThreeCount = topThreeDirs.reduce((sum, [, count]) => sum + count, 0);
361
+ const percentage = topThreeCount / issues.length * 100;
362
+ if (percentage >= 50) {
363
+ evidence.push({
364
+ type: "supporting",
365
+ description: `Top 3 directories have ${percentage.toFixed(0)}% of issues`,
366
+ weight: Math.min(0.8, 0.3 + percentage / 100),
367
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
368
+ });
369
+ }
370
+ }
371
+ return evidence;
372
+ }
373
+ /**
374
+ * Analyze code patterns
375
+ */
376
+ analyzeCodePatterns(template, issues) {
377
+ const evidence = [];
378
+ if (template.statement.includes("cluster")) {
379
+ const criticalIssues = issues.filter((r) => r.issue.severity === "critical");
380
+ if (criticalIssues.length >= 3) {
381
+ const timestamps = criticalIssues.map((r) => new Date(r.issue.timestamp).getTime()).sort((a, b) => a - b);
382
+ let clusteredCount = 0;
383
+ for (let i = 1; i < timestamps.length; i++) {
384
+ if (timestamps[i] - timestamps[i - 1] < 24 * 60 * 60 * 1e3) {
385
+ clusteredCount++;
386
+ }
387
+ }
388
+ const clusterRatio = clusteredCount / (timestamps.length - 1);
389
+ if (clusterRatio >= 0.5) {
390
+ evidence.push({
391
+ type: "supporting",
392
+ description: `${(clusterRatio * 100).toFixed(0)}% of critical issues occur within 24h of another`,
393
+ weight: Math.min(0.75, 0.3 + clusterRatio * 0.4),
394
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
395
+ });
396
+ }
397
+ }
398
+ }
399
+ return evidence;
400
+ }
401
+ /**
402
+ * Update confidence scores based on new data
403
+ */
404
+ async updateConfidenceFromOutcomes() {
405
+ const analyses = [];
406
+ try {
407
+ await this.guardianState.load();
408
+ const activeHypotheses = this.guardianState.getActiveHypotheses();
409
+ for (const hypothesis of activeHypotheses) {
410
+ const analysis = await this.analyzeHypothesis(hypothesis);
411
+ analyses.push(analysis);
412
+ if (analysis.statusChange && this.insightStore.canCreateInsight("hypothesis-update")) {
413
+ const insight = this.createHypothesisInsight(analysis);
414
+ await this.insightStore.addInsight(insight);
415
+ await this.insightStore.markInsightCreated("hypothesis-update");
416
+ }
417
+ }
418
+ await this.guardianState.updateHypothesisAccuracy();
419
+ } catch (error) {
420
+ console.error("Failed to update hypothesis confidence:", error);
421
+ }
422
+ return analyses;
423
+ }
424
+ /**
425
+ * Analyze a single hypothesis
426
+ */
427
+ async analyzeHypothesis(hypothesis) {
428
+ const issues = await searchIssues("", {
429
+ workDir: this.projectPath,
430
+ limit: 100,
431
+ includeResolved: false
432
+ });
433
+ const template = HYPOTHESIS_TEMPLATES.find(
434
+ (t) => t.statement.toLowerCase() === hypothesis.statement.toLowerCase()
435
+ );
436
+ const recentEvidence = [];
437
+ if (template) {
438
+ recentEvidence.push(...await this.gatherInitialEvidence(template, issues));
439
+ } else {
440
+ recentEvidence.push(...this.gatherSemanticEvidence(hypothesis, issues));
441
+ }
442
+ const oldConfidence = hypothesis.confidence;
443
+ let newConfidence = oldConfidence;
444
+ for (const evidence of recentEvidence) {
445
+ if (evidence.type === "supporting") {
446
+ newConfidence = Math.min(1, newConfidence + evidence.weight * 0.1);
447
+ } else {
448
+ newConfidence = Math.max(0, newConfidence - evidence.weight * 0.1);
449
+ }
450
+ }
451
+ let statusChange;
452
+ if (newConfidence >= 0.8 && hypothesis.evidence.length >= 3) {
453
+ statusChange = "validated";
454
+ await this.guardianState.updateHypothesis(hypothesis.id, {
455
+ status: "validated",
456
+ confidence: newConfidence,
457
+ validatedAt: (/* @__PURE__ */ new Date()).toISOString()
458
+ });
459
+ } else if (newConfidence <= 0.2 && hypothesis.evidence.length >= 3) {
460
+ statusChange = "invalidated";
461
+ await this.guardianState.updateHypothesis(hypothesis.id, {
462
+ status: "invalidated",
463
+ confidence: newConfidence
464
+ });
465
+ } else {
466
+ await this.guardianState.updateHypothesis(hypothesis.id, {
467
+ confidence: newConfidence
468
+ });
469
+ }
470
+ for (const evidence of recentEvidence) {
471
+ await this.guardianState.addEvidence(hypothesis.id, evidence);
472
+ }
473
+ const analysis = {
474
+ hypothesis: { ...hypothesis, confidence: newConfidence },
475
+ recentEvidence,
476
+ confidenceChange: newConfidence - oldConfidence,
477
+ actionRequired: statusChange !== void 0
478
+ };
479
+ if (statusChange) {
480
+ analysis.statusChange = statusChange;
481
+ }
482
+ return analysis;
483
+ }
484
+ /**
485
+ * Gather evidence for user-created hypotheses using semantic matching
486
+ *
487
+ * This enables agentic tracking for natural language hypotheses like:
488
+ * - "Mondays have more bugs than Fridays"
489
+ * - "Code reviews reduce bug rate"
490
+ * - "Security issues cluster in auth code"
491
+ */
492
+ gatherSemanticEvidence(hypothesis, issues) {
493
+ const evidence = [];
494
+ const stmt = hypothesis.statement.toLowerCase();
495
+ if (stmt.includes("monday") || stmt.includes("friday") || stmt.includes("weekend") || stmt.includes("morning") || stmt.includes("afternoon")) {
496
+ const dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
497
+ const dayOfWeekCounts = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 };
498
+ for (const { issue } of issues) {
499
+ const date = new Date(issue.timestamp);
500
+ const day = date.getDay();
501
+ dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;
502
+ }
503
+ const totalIssues = Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0);
504
+ const avgPerDay = totalIssues / 7;
505
+ for (let dayIdx = 0; dayIdx < 7; dayIdx++) {
506
+ const dayName = dayNames[dayIdx];
507
+ if (stmt.includes(dayName)) {
508
+ const dayCount = dayOfWeekCounts[dayIdx] || 0;
509
+ if (stmt.includes("more") || stmt.includes("higher") || stmt.includes("spike")) {
510
+ if (dayCount > avgPerDay * 1.3) {
511
+ evidence.push({
512
+ type: "supporting",
513
+ description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has ${dayCount} issues (${((dayCount / avgPerDay - 1) * 100).toFixed(0)}% above average)`,
514
+ weight: Math.min(0.7, 0.3 + (dayCount / avgPerDay - 1) * 0.3),
515
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
516
+ });
517
+ } else {
518
+ evidence.push({
519
+ type: "contradicting",
520
+ description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has average or below average issue count`,
521
+ weight: 0.3,
522
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
523
+ });
524
+ }
525
+ } else if (stmt.includes("fewer") || stmt.includes("less") || stmt.includes("reduce")) {
526
+ if (dayCount < avgPerDay * 0.7) {
527
+ evidence.push({
528
+ type: "supporting",
529
+ description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has ${dayCount} issues (${((1 - dayCount / avgPerDay) * 100).toFixed(0)}% below average)`,
530
+ weight: Math.min(0.7, 0.3 + (1 - dayCount / avgPerDay) * 0.3),
531
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
532
+ });
533
+ }
534
+ }
535
+ }
536
+ }
537
+ }
538
+ if (stmt.includes("review") || stmt.includes("pr") || stmt.includes("pull request")) {
539
+ const recentIssues = issues.slice(0, 30);
540
+ const olderIssues = issues.slice(30);
541
+ if (recentIssues.length >= 10 && olderIssues.length >= 10) {
542
+ const recentRate = recentIssues.length;
543
+ const olderRate = olderIssues.length;
544
+ if (stmt.includes("reduce") || stmt.includes("fewer") || stmt.includes("less")) {
545
+ if (recentRate < olderRate) {
546
+ evidence.push({
547
+ type: "supporting",
548
+ description: `Recent period has ${((1 - recentRate / olderRate) * 100).toFixed(0)}% fewer issues`,
549
+ weight: Math.min(0.6, 0.3 + (1 - recentRate / olderRate) * 0.3),
550
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
551
+ });
552
+ } else {
553
+ evidence.push({
554
+ type: "contradicting",
555
+ description: `Issue rate has not decreased recently`,
556
+ weight: 0.2,
557
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
558
+ });
559
+ }
560
+ }
561
+ }
562
+ }
563
+ if (stmt.includes("cluster") || stmt.includes("concentrate") || stmt.includes("auth") || stmt.includes("specific") || stmt.includes("certain files")) {
564
+ const dirCounts = {};
565
+ for (const { issue } of issues) {
566
+ const dir = dirname(issue.file);
567
+ dirCounts[dir] = (dirCounts[dir] || 0) + 1;
568
+ }
569
+ const sortedDirs = Object.entries(dirCounts).sort(([, a], [, b]) => b - a);
570
+ const topThreeCount = sortedDirs.slice(0, 3).reduce((sum, [, count]) => sum + count, 0);
571
+ const totalCount = issues.length;
572
+ const concentration = topThreeCount / totalCount;
573
+ if (concentration >= 0.5) {
574
+ evidence.push({
575
+ type: "supporting",
576
+ description: `Top 3 directories have ${(concentration * 100).toFixed(0)}% of issues (concentrated)`,
577
+ weight: Math.min(0.7, 0.3 + concentration * 0.4),
578
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
579
+ });
580
+ } else {
581
+ evidence.push({
582
+ type: "contradicting",
583
+ description: `Issues are distributed across many directories`,
584
+ weight: 0.3,
585
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
586
+ });
587
+ }
588
+ }
589
+ if (stmt.includes("critical") || stmt.includes("security") || stmt.includes("severity")) {
590
+ const criticalCount = issues.filter((r) => r.issue.severity === "critical").length;
591
+ const seriousCount = issues.filter((r) => r.issue.severity === "serious").length;
592
+ const highSeverityRatio = (criticalCount + seriousCount) / issues.length;
593
+ if (stmt.includes("increase") || stmt.includes("more") || stmt.includes("rise")) {
594
+ if (highSeverityRatio > 0.3) {
595
+ evidence.push({
596
+ type: "supporting",
597
+ description: `${(highSeverityRatio * 100).toFixed(0)}% of issues are high severity`,
598
+ weight: Math.min(0.7, 0.3 + highSeverityRatio),
599
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
600
+ });
601
+ }
602
+ } else if (stmt.includes("decrease") || stmt.includes("fewer") || stmt.includes("reduce")) {
603
+ if (highSeverityRatio < 0.2) {
604
+ evidence.push({
605
+ type: "supporting",
606
+ description: `Only ${(highSeverityRatio * 100).toFixed(0)}% of issues are high severity`,
607
+ weight: 0.5,
608
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
609
+ });
610
+ }
611
+ }
612
+ }
613
+ const agents = ["security", "performance", "accessibility", "test", "typecheck", "bug-finding"];
614
+ for (const agent of agents) {
615
+ if (stmt.includes(agent) || stmt.includes(agent.replace("-", " "))) {
616
+ const agentIssues = issues.filter((r) => r.issue.agent === agent);
617
+ const agentRatio = agentIssues.length / issues.length;
618
+ if (stmt.includes("most") || stmt.includes("majority") || stmt.includes("main")) {
619
+ if (agentRatio > 0.4) {
620
+ evidence.push({
621
+ type: "supporting",
622
+ description: `${agent} accounts for ${(agentRatio * 100).toFixed(0)}% of issues`,
623
+ weight: Math.min(0.7, 0.3 + agentRatio),
624
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
625
+ });
626
+ } else {
627
+ evidence.push({
628
+ type: "contradicting",
629
+ description: `${agent} only accounts for ${(agentRatio * 100).toFixed(0)}% of issues`,
630
+ weight: 0.3,
631
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
632
+ });
633
+ }
634
+ }
635
+ }
636
+ }
637
+ return evidence;
638
+ }
639
+ /**
640
+ * Create an insight for hypothesis status change
641
+ */
642
+ createHypothesisInsight(analysis) {
643
+ const isValidated = analysis.statusChange === "validated";
644
+ return {
645
+ id: `insight-hyp-${analysis.hypothesis.id}`,
646
+ type: isValidated ? "celebration" : "observation",
647
+ message: isValidated ? `Hypothesis confirmed: "${analysis.hypothesis.statement}"` : `Hypothesis disproven: "${analysis.hypothesis.statement}"`,
648
+ context: `Confidence: ${(analysis.hypothesis.confidence * 100).toFixed(0)}%. ${analysis.recentEvidence.length} evidence points analyzed.`,
649
+ relatedIssues: [],
650
+ priority: 5,
651
+ timestamp: Date.now(),
652
+ dismissed: false,
653
+ category: "pattern",
654
+ details: {
655
+ examples: analysis.recentEvidence.map((e) => `${e.type}: ${e.description}`)
656
+ }
657
+ };
658
+ }
659
+ /**
660
+ * Get hypothesis by ID
661
+ */
662
+ async getHypothesis(hypothesisId) {
663
+ await this.guardianState.load();
664
+ return this.guardianState.getHypothesis(hypothesisId);
665
+ }
666
+ /**
667
+ * Get all hypotheses
668
+ */
669
+ async getAllHypotheses() {
670
+ await this.guardianState.load();
671
+ return this.guardianState.getAllHypotheses();
672
+ }
673
+ /**
674
+ * Get validated hypotheses
675
+ */
676
+ async getValidatedHypotheses() {
677
+ await this.guardianState.load();
678
+ return this.guardianState.getValidatedHypotheses();
679
+ }
680
+ /**
681
+ * Get hypothesis accuracy stats
682
+ */
683
+ getAccuracy() {
684
+ const metrics = this.guardianState.getMetrics();
685
+ return metrics.hypothesisAccuracy;
686
+ }
687
+ };
688
+ var hypothesisEngines = /* @__PURE__ */ new Map();
689
+ function getHypothesisEngine(projectPath) {
690
+ let engine = hypothesisEngines.get(projectPath);
691
+ if (!engine) {
692
+ engine = new HypothesisEngine(projectPath);
693
+ hypothesisEngines.set(projectPath, engine);
694
+ }
695
+ return engine;
696
+ }
697
+ function clearHypothesisEngines() {
698
+ hypothesisEngines.clear();
699
+ }
700
+
701
+ export {
702
+ HypothesisEngine,
703
+ getHypothesisEngine,
704
+ clearHypothesisEngines
705
+ };
706
+ //# sourceMappingURL=chunk-DZREHOGW.js.map