ollie/cmd/olliesrv/internal/agent/local_summary.go

78 lines
2.0 KiB
Go

package agent
import (
"fmt"
"regexp"
"strings"
)
const (
localSummaryMinReduction = 0.25
localSummaryKeepLines = 20
)
var localSummarySignalRE = regexp.MustCompile(`(?i)(exit code|error|failed|failure|panic|exception|fatal|warning|status|success|passed|FAIL|ERROR)`)
func localColdSummary(content string) (string, bool) {
content = strings.ReplaceAll(content, "\r\n", "\n")
content = strings.TrimSpace(content)
if content == "" {
return "Tool returned no output.", true
}
if looksStructured(content) {
return "", false
}
lines := strings.Split(content, "\n")
lines = collapseAdjacentLines(lines)
if len(lines) > localSummaryKeepLines*2 {
selected := make([]string, 0, localSummaryKeepLines*2+1)
selected = append(selected, lines[:localSummaryKeepLines]...)
omitted := len(lines) - localSummaryKeepLines*2
selected = append(selected, fmt.Sprintf("[omitted %d lines]", omitted))
selected = append(selected, lines[len(lines)-localSummaryKeepLines:]...)
for _, line := range lines[localSummaryKeepLines : len(lines)-localSummaryKeepLines] {
if localSummarySignalRE.MatchString(line) {
selected = append(selected, line)
}
}
lines = selected
}
candidate := strings.TrimSpace(strings.Join(lines, "\n"))
if candidate == content || len(candidate) > int(float64(len(content))*(1-localSummaryMinReduction)) {
return "", false
}
return candidate, true
}
func collapseAdjacentLines(lines []string) []string {
if len(lines) < 2 {
return lines
}
out := make([]string, 0, len(lines))
for i := 0; i < len(lines); {
j := i + 1
for j < len(lines) && lines[j] == lines[i] {
j++
}
out = append(out, lines[i])
if j-i > 1 {
out = append(out, fmt.Sprintf("[repeated %d times]", j-i))
}
i = j
}
return out
}
func looksStructured(content string) bool {
trimmed := strings.TrimSpace(content)
if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "---") {
return true
}
if strings.Contains(content, "```") || strings.Contains(content, "\n ") {
return true
}
return false
}