package ingest import ( "bufio" "crypto/sha256" "fmt" "os" "path/filepath" "regexp" "sort" "strings" "time" ) var _ Ingester = (*LogIngester)(nil) type LogIngester struct { Version string } func NewLogIngester() *LogIngester { return &LogIngester{Version: "log-parser/v2"} } func (l *LogIngester) SourceID() string { return "opencode-log" } var ( sessionIDRE = regexp.MustCompile(`session[=_ ]?([a-zA-Z0-9_-]+)`) modelRE = regexp.MustCompile(`model[=_ ]?([a-zA-Z0-9_.-]+)`) agentRE = regexp.MustCompile(`agent[=_ ]?([a-zA-Z0-9_.-]+)`) levelRE = regexp.MustCompile(`\blevel=([A-Za-z]+)`) ) // Log lines are structured as `timestamp=... level=... run=... message=...`. // Only real WARN/ERROR/FATAL lines are "errors"; the previous substring match // flagged INFO permission lines that merely contained the word "timeout". var seriousLevels = map[string]bool{"ERROR": true, "WARN": true, "FATAL": true} func (l *LogIngester) Ingest(path string) (*IngestResult, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("open log: %w", err) } defer f.Close() var ( sessionIDs []string models []string agents []string signatures []string totalLines int errCount int warnCount int ) scanner := bufio.NewScanner(f) scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) for scanner.Scan() { line := scanner.Text() totalLines++ if m := sessionIDRE.FindStringSubmatch(line); len(m) > 1 { sessionIDs = append(sessionIDs, m[1]) } if m := modelRE.FindStringSubmatch(line); len(m) > 1 { models = append(models, m[1]) } if m := agentRE.FindStringSubmatch(line); len(m) > 1 { agents = append(agents, m[1]) } m := levelRE.FindStringSubmatch(line) if len(m) < 2 { continue } level := strings.ToUpper(m[1]) if !seriousLevels[level] { continue } if level == "WARN" { warnCount++ } else { errCount++ } signatures = append(signatures, normalizeLogLine(line)) } base := filepath.Base(path) fp := Fingerprint([]byte("log:" + base)) createdAt := "" if fi, err := os.Stat(path); err == nil { createdAt = fi.ModTime().UTC().Format(time.RFC3339) } uniq := uniqueSorted(signatures) contentHash := hashSignatures(uniq, errCount, warnCount) summary := buildLogSummary(uniq, errCount, warnCount) confidence := 0.6 if errCount > 0 || warnCount > 0 { confidence = 0.8 } return &IngestResult{ Fingerprint: fp, SourceID: l.SourceID(), SourcePath: base, ContentType: ".log", Title: "Log " + base, Summary: summary, Content: strings.Join(uniq, "\n"), CreatedAt: createdAt, Confidence: confidence, IngesterVersion: l.Version, LineEnd: totalLines, ContentHash: contentHash, Provenance: map[string]any{ "session_ids": uniqueSlice(sessionIDs), "models": uniqueSlice(models), "agents": uniqueSlice(agents), "error_count": errCount, "warn_count": warnCount, "errors_sample": firstN(uniq, 5), "file_size": fmt.Sprintf("%d lines", totalLines), }, }, nil } // Normalization patterns strip values that change between identical log events // so the same error yields the same signature. var ( tsPrefixRE = regexp.MustCompile(`^timestamp=\S+\s*`) runRE = regexp.MustCompile(`run=[0-9a-fA-F]+`) sesRE = regexp.MustCompile(`ses_[A-Za-z0-9]+`) msgRE = regexp.MustCompile(`msg_[A-Za-z0-9]+`) hexRE = regexp.MustCompile(`\b[0-9a-fA-F]{6,}\b`) numRE = regexp.MustCompile(`[0-9]+`) ) func normalizeLogLine(line string) string { s := tsPrefixRE.ReplaceAllString(line, "") s = runRE.ReplaceAllString(s, "run=") s = sesRE.ReplaceAllString(s, "") s = msgRE.ReplaceAllString(s, "") s = hexRE.ReplaceAllString(s, "") s = numRE.ReplaceAllString(s, "") s = strings.Join(strings.Fields(s), " ") return truncate(s, 160) } // hashSignatures is the change signal: it depends only on the set of distinct // error signatures and the level counts — not on total line count or ordering. func hashSignatures(sigs []string, errCount, warnCount int) string { h := sha256.New() for _, s := range sigs { h.Write([]byte(s)) h.Write([]byte{'\n'}) } fmt.Fprintf(h, "E=%d W=%d", errCount, warnCount) return fmt.Sprintf("%x", h.Sum(nil)[:8]) } func buildLogSummary(sigs []string, errCount, warnCount int) string { if errCount == 0 && warnCount == 0 { return "no errors" } var b strings.Builder fmt.Fprintf(&b, "levels: E%d W%d", errCount, warnCount) if len(sigs) > 0 { b.WriteString(" | err: ") b.WriteString(strings.Join(firstN(sigs, 5), " ;; ")) } return b.String() } // uniqueSorted returns de-duplicated, lexicographically sorted signatures. func uniqueSorted(items []string) []string { seen := make(map[string]bool) var out []string for _, s := range items { if !seen[s] { seen[s] = true out = append(out, s) } } sort.Strings(out) return out } func firstN(items []string, n int) []string { if len(items) > n { return items[:n] } return items } func uniqueJoin(items []string, max int) string { uniq := uniqueSlice(items) if len(uniq) > max { uniq = uniq[:max] } return strings.Join(uniq, ", ") } func uniqueSlice(items []string) []string { seen := make(map[string]bool) var uniq []string for _, s := range items { if !seen[s] { seen[s] = true uniq = append(uniq, s) } } return uniq }