go/internal/bugseti/stats.go

360 lines
8.2 KiB
Go
Raw Normal View History

feat: BugSETI app, WebSocket hub, browser automation, and MCP tools (#336) * feat: add security logging and fix framework regressions This commit implements comprehensive security event logging and resolves critical regressions in the core framework. Security Logging: - Enhanced `pkg/log` with a `Security` level and helper. - Added `log.Username()` to consistently identify the executing user. - Instrumented GitHub CLI auth, Agentic configuration, filesystem sandbox, MCP handlers, and MCP TCP transport with security logs. - Added `SecurityStyle` to the CLI for consistent visual representation of security events. UniFi Security (CodeQL): - Refactored `pkg/unifi` to remove hardcoded `InsecureSkipVerify`, resolving a high-severity alert. - Added a `--verify-tls` flag and configuration option to control TLS verification. - Updated command handlers to support the new verification parameter. Framework Fixes: - Restored original signatures for `MustServiceFor`, `Config()`, and `Display()` in `pkg/framework/core`, which had been corrupted during a merge. - Fixed `pkg/framework/framework.go` and `pkg/framework/core/runtime_pkg.go` to match the restored signatures. - These fixes resolve project-wide compilation errors caused by the signature mismatches. I encountered significant blockers due to a corrupted state of the `dev` branch after a merge, which introduced breaking changes in the core framework's DI system. I had to manually reconcile these signatures with the expected usage across the codebase to restore build stability. * feat(mcp): add RAG tools (query, ingest, collections) Add vector database tools to the MCP server for RAG operations: - rag_query: Search for relevant documentation using semantic similarity - rag_ingest: Ingest files or directories into the vector database - rag_collections: List available collections Uses existing internal/cmd/rag exports (QueryDocs, IngestDirectory, IngestFile) and pkg/rag for Qdrant client access. Default collection is "hostuk-docs" with topK=5 for queries. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(mcp): add metrics tools (record, query) Add MCP tools for recording and querying AI/security metrics events. The metrics_record tool writes events to daily JSONL files, and the metrics_query tool provides aggregated statistics by type, repo, and agent. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add 'core mcp serve' command Add CLI command to start the MCP server for AI tool integration. - Create internal/cmd/mcpcmd package with serve subcommand - Support --workspace flag for directory restriction - Handle SIGINT/SIGTERM for clean shutdown - Register in full.go build variant Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(ws): add WebSocket hub package for real-time streaming Add pkg/ws package implementing a hub pattern for WebSocket connections: - Hub manages client connections, broadcasts, and channel subscriptions - Client struct represents connected WebSocket clients - Message types: process_output, process_status, event, error, ping/pong - Channel-based subscription system (subscribe/unsubscribe) - SendProcessOutput and SendProcessStatus for process streaming integration - Full test coverage including concurrency tests Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(mcp): add process management and WebSocket MCP tools Add MCP tools for process management: - process_start: Start a new external process - process_stop: Gracefully stop a running process - process_kill: Force kill a process - process_list: List all managed processes - process_output: Get captured process output - process_input: Send input to process stdin Add MCP tools for WebSocket: - ws_start: Start WebSocket server for real-time streaming - ws_info: Get hub statistics (clients, channels) Update Service struct with optional process.Service and ws.Hub fields, new WithProcessService and WithWSHub options, getter methods, and Shutdown method for cleanup. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(webview): add browser automation package via Chrome DevTools Protocol Add pkg/webview package for browser automation: - webview.go: Main interface with Connect, Navigate, Click, Type, QuerySelector, Screenshot, Evaluate - cdp.go: Chrome DevTools Protocol WebSocket client implementation - actions.go: DOM action types (Click, Type, Hover, Scroll, etc.) and ActionSequence builder - console.go: Console message capture and filtering with ConsoleWatcher and ExceptionWatcher - angular.go: Angular-specific helpers for router navigation, component access, and Zone.js stability Add MCP tools for webview: - webview_connect/disconnect: Connection management - webview_navigate: Page navigation - webview_click/type/query/wait: DOM interaction - webview_console: Console output capture - webview_eval: JavaScript execution - webview_screenshot: Screenshot capture Add documentation: - docs/mcp/angular-testing.md: Guide for Angular application testing Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: document new packages and BugSETI application - Update CLAUDE.md with documentation for: - pkg/ws (WebSocket hub for real-time streaming) - pkg/webview (Browser automation via CDP) - pkg/mcp (MCP server tools: process, ws, webview) - BugSETI application overview - Add comprehensive README for BugSETI with: - Installation and configuration guide - Usage workflow documentation - Architecture overview - Contributing guidelines Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(bugseti): add BugSETI system tray app with auto-update BugSETI - Distributed Bug Fixing like SETI@home but for code Features: - System tray app with Wails v3 - GitHub issue fetching with label filters - Issue queue with priority management - AI context seeding via seed-agent-developer skill - Automated PR submission flow - Stats tracking and leaderboard - Cross-platform notifications - Self-updating with stable/beta/nightly channels Includes: - cmd/bugseti: Main application with Angular frontend - internal/bugseti: Core services (fetcher, queue, seeder, submit, config, stats, notify) - internal/bugseti/updater: Auto-update system (checker, downloader, installer) - .github/workflows/bugseti-release.yml: CI/CD for all platforms Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: resolve import cycle and code duplication - Remove pkg/log import from pkg/io/local to break import cycle (pkg/log/rotation.go imports pkg/io, creating circular dependency) - Use stderr logging for security events in sandbox escape detection - Remove unused sync/atomic import from core.go - Fix duplicate LogSecurity function declarations in cli/log.go - Update workspace/service.go Crypt() call to match interface Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: update tests for new function signatures and format code - Update core_test.go: Config(), Display() now panic instead of returning error - Update runtime_pkg_test.go: sr.Config() now panics instead of returning error - Update MustServiceFor tests to use assert.Panics - Format BugSETI, MCP tools, and webview packages with gofmt Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Snider <631881+Snider@users.noreply.github.com> Co-authored-by: Claude <developers@lethean.io> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 17:22:05 +00:00
// Package bugseti provides services for the BugSETI distributed bug fixing application.
package bugseti
import (
"encoding/json"
"log"
"os"
"path/filepath"
"sync"
"time"
)
// StatsService tracks user contribution statistics.
type StatsService struct {
config *ConfigService
stats *Stats
mu sync.RWMutex
}
// Stats contains all tracked statistics.
type Stats struct {
// Issue stats
IssuesAttempted int `json:"issuesAttempted"`
IssuesCompleted int `json:"issuesCompleted"`
IssuesSkipped int `json:"issuesSkipped"`
// PR stats
PRsSubmitted int `json:"prsSubmitted"`
PRsMerged int `json:"prsMerged"`
PRsRejected int `json:"prsRejected"`
// Repository stats
ReposContributed map[string]*RepoStats `json:"reposContributed"`
// Streaks
CurrentStreak int `json:"currentStreak"`
LongestStreak int `json:"longestStreak"`
LastActivity time.Time `json:"lastActivity"`
// Time tracking
TotalTimeSpent time.Duration `json:"totalTimeSpent"`
AverageTimePerPR time.Duration `json:"averageTimePerPR"`
// Activity history (last 30 days)
DailyActivity map[string]*DayStats `json:"dailyActivity"`
}
// RepoStats contains statistics for a single repository.
type RepoStats struct {
Name string `json:"name"`
IssuesFixed int `json:"issuesFixed"`
PRsSubmitted int `json:"prsSubmitted"`
PRsMerged int `json:"prsMerged"`
FirstContrib time.Time `json:"firstContrib"`
LastContrib time.Time `json:"lastContrib"`
}
// DayStats contains statistics for a single day.
type DayStats struct {
Date string `json:"date"`
IssuesWorked int `json:"issuesWorked"`
PRsSubmitted int `json:"prsSubmitted"`
TimeSpent int `json:"timeSpentMinutes"`
}
// NewStatsService creates a new StatsService.
func NewStatsService(config *ConfigService) *StatsService {
s := &StatsService{
config: config,
stats: &Stats{
ReposContributed: make(map[string]*RepoStats),
DailyActivity: make(map[string]*DayStats),
},
}
s.load()
return s
}
// ServiceName returns the service name for Wails.
func (s *StatsService) ServiceName() string {
return "StatsService"
}
// GetStats returns a copy of the current statistics.
func (s *StatsService) GetStats() Stats {
s.mu.RLock()
defer s.mu.RUnlock()
return *s.stats
}
// RecordIssueAttempted records that an issue was started.
func (s *StatsService) RecordIssueAttempted(repo string) {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.IssuesAttempted++
s.ensureRepo(repo)
s.updateStreak()
s.updateDailyActivity("issue")
s.save()
}
// RecordIssueCompleted records that an issue was completed.
func (s *StatsService) RecordIssueCompleted(repo string) {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.IssuesCompleted++
if rs, ok := s.stats.ReposContributed[repo]; ok {
rs.IssuesFixed++
rs.LastContrib = time.Now()
}
s.save()
}
// RecordIssueSkipped records that an issue was skipped.
func (s *StatsService) RecordIssueSkipped() {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.IssuesSkipped++
s.save()
}
// RecordPRSubmitted records that a PR was submitted.
func (s *StatsService) RecordPRSubmitted(repo string) {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.PRsSubmitted++
if rs, ok := s.stats.ReposContributed[repo]; ok {
rs.PRsSubmitted++
rs.LastContrib = time.Now()
}
s.updateDailyActivity("pr")
s.save()
}
// RecordPRMerged records that a PR was merged.
func (s *StatsService) RecordPRMerged(repo string) {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.PRsMerged++
if rs, ok := s.stats.ReposContributed[repo]; ok {
rs.PRsMerged++
}
s.save()
}
// RecordPRRejected records that a PR was rejected.
func (s *StatsService) RecordPRRejected() {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.PRsRejected++
s.save()
}
// RecordTimeSpent adds time spent on an issue.
func (s *StatsService) RecordTimeSpent(duration time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
s.stats.TotalTimeSpent += duration
// Recalculate average
if s.stats.PRsSubmitted > 0 {
s.stats.AverageTimePerPR = s.stats.TotalTimeSpent / time.Duration(s.stats.PRsSubmitted)
}
// Update daily activity
today := time.Now().Format("2006-01-02")
if day, ok := s.stats.DailyActivity[today]; ok {
day.TimeSpent += int(duration.Minutes())
}
s.save()
}
// GetRepoStats returns statistics for a specific repository.
func (s *StatsService) GetRepoStats(repo string) *RepoStats {
s.mu.RLock()
defer s.mu.RUnlock()
return s.stats.ReposContributed[repo]
}
// GetTopRepos returns the top N repositories by contributions.
func (s *StatsService) GetTopRepos(n int) []*RepoStats {
s.mu.RLock()
defer s.mu.RUnlock()
repos := make([]*RepoStats, 0, len(s.stats.ReposContributed))
for _, rs := range s.stats.ReposContributed {
repos = append(repos, rs)
}
// Sort by PRs merged (descending)
for i := 0; i < len(repos)-1; i++ {
for j := i + 1; j < len(repos); j++ {
if repos[j].PRsMerged > repos[i].PRsMerged {
repos[i], repos[j] = repos[j], repos[i]
}
}
}
if n > len(repos) {
n = len(repos)
}
return repos[:n]
}
// GetActivityHistory returns the activity for the last N days.
func (s *StatsService) GetActivityHistory(days int) []*DayStats {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]*DayStats, 0, days)
now := time.Now()
for i := 0; i < days; i++ {
date := now.AddDate(0, 0, -i).Format("2006-01-02")
if day, ok := s.stats.DailyActivity[date]; ok {
result = append(result, day)
} else {
result = append(result, &DayStats{Date: date})
}
}
return result
}
// ensureRepo creates a repo stats entry if it doesn't exist.
func (s *StatsService) ensureRepo(repo string) {
if _, ok := s.stats.ReposContributed[repo]; !ok {
s.stats.ReposContributed[repo] = &RepoStats{
Name: repo,
FirstContrib: time.Now(),
LastContrib: time.Now(),
}
}
}
// updateStreak updates the contribution streak.
func (s *StatsService) updateStreak() {
now := time.Now()
lastActivity := s.stats.LastActivity
if lastActivity.IsZero() {
s.stats.CurrentStreak = 1
} else {
daysSince := int(now.Sub(lastActivity).Hours() / 24)
if daysSince <= 1 {
// Same day or next day
if daysSince == 1 || now.Day() != lastActivity.Day() {
s.stats.CurrentStreak++
}
} else {
// Streak broken
s.stats.CurrentStreak = 1
}
}
if s.stats.CurrentStreak > s.stats.LongestStreak {
s.stats.LongestStreak = s.stats.CurrentStreak
}
s.stats.LastActivity = now
}
// updateDailyActivity updates today's activity.
func (s *StatsService) updateDailyActivity(activityType string) {
today := time.Now().Format("2006-01-02")
if _, ok := s.stats.DailyActivity[today]; !ok {
s.stats.DailyActivity[today] = &DayStats{Date: today}
}
day := s.stats.DailyActivity[today]
switch activityType {
case "issue":
day.IssuesWorked++
case "pr":
day.PRsSubmitted++
}
// Clean up old entries (keep last 90 days)
cutoff := time.Now().AddDate(0, 0, -90).Format("2006-01-02")
for date := range s.stats.DailyActivity {
if date < cutoff {
delete(s.stats.DailyActivity, date)
}
}
}
// save persists stats to disk.
func (s *StatsService) save() {
dataDir := s.config.GetDataDir()
if dataDir == "" {
return
}
path := filepath.Join(dataDir, "stats.json")
data, err := json.MarshalIndent(s.stats, "", " ")
if err != nil {
log.Printf("Failed to marshal stats: %v", err)
return
}
if err := os.WriteFile(path, data, 0644); err != nil {
log.Printf("Failed to save stats: %v", err)
}
}
// load restores stats from disk.
func (s *StatsService) load() {
dataDir := s.config.GetDataDir()
if dataDir == "" {
return
}
path := filepath.Join(dataDir, "stats.json")
data, err := os.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
log.Printf("Failed to read stats: %v", err)
}
return
}
var stats Stats
if err := json.Unmarshal(data, &stats); err != nil {
log.Printf("Failed to unmarshal stats: %v", err)
return
}
// Ensure maps are initialized
if stats.ReposContributed == nil {
stats.ReposContributed = make(map[string]*RepoStats)
}
if stats.DailyActivity == nil {
stats.DailyActivity = make(map[string]*DayStats)
}
s.stats = &stats
}
// Reset clears all statistics.
func (s *StatsService) Reset() error {
s.mu.Lock()
defer s.mu.Unlock()
s.stats = &Stats{
ReposContributed: make(map[string]*RepoStats),
DailyActivity: make(map[string]*DayStats),
}
s.save()
return nil
}