Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

31.4 KB
Raw Blame
package dashboard

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens"
	"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)

const (
	defaultEventLimit = 500
	maxEventLimit     = 2000
)

type EventRecord struct {
	ID         string          `json:"id"`
	Line       int             `json:"line"`
	Event      schema.Event    `json:"event"`
	Raw        json.RawMessage `json:"-"`
	Parsed     time.Time       `json:"parsed_timestamp,omitempty"`
	WazuhLevel int             `json:"wazuh_level,omitempty"`
}

type EventQuery struct {
	Limit           int
	NoLimit         bool
	Since           time.Time
	Until           time.Time
	Q               string
	Harness         string
	Model           string
	Action          string
	Severity        string
	Category        string
	Repository      string
	Session         string
	Trace           string
	File            string
	Command         string
	MCP             string
	Approval        string
	Decision        string
	Policy          string
	Review          string
	WazuhLevel      string
	SessionState    string
	sessionStateIDs map[string]bool
}

type EventResult struct {
	Events         []EventRecord     `json:"events"`
	TotalMatched   int               `json:"total_matched"`
	MalformedLines int               `json:"malformed_lines"`
	Limit          int               `json:"limit"`
	Query          string            `json:"query,omitempty"`
	Filters        map[string]string `json:"filters,omitempty"`
	Returned       int               `json:"returned"`
	Truncated      bool              `json:"truncated"`
}

func ReadEvents(path string, query EventQuery) (EventResult, error) {
	limit := normalizeLimit(query.Limit)
	query, err := resolveSessionState(path, query)
	if err != nil {
		return EventResult{}, err
	}
	result := EventResult{Limit: limit, Query: strings.TrimSpace(query.Q), Filters: activeFilters(query)}
	for _, source := range eventSources(path) {
		if err := readEventsFromSource(source, query, &result, limit); err != nil {
			return EventResult{}, err
		}
	}
	sort.SliceStable(result.Events, func(i, j int) bool {
		return recordBefore(result.Events[j], result.Events[i])
	})
	result.Returned = len(result.Events)
	result.Truncated = result.TotalMatched > len(result.Events)
	return result, nil
}

// resolveSessionState normalizes query's session-state filter and, when one is set, resolves the
// sessions in that state, which every reader must do before it matches a single event.
func resolveSessionState(path string, query EventQuery) (EventQuery, error) {
	query.SessionState = normalizeSessionState(query.SessionState)
	if query.SessionState != "" && query.sessionStateIDs == nil {
		ids, err := sessionIDsForState(path, query, query.SessionState)
		if err != nil {
			return query, err
		}
		query.sessionStateIDs = ids
	}
	return query, nil
}

// ReadEventsAppendOrder reads the full matching log (NoLimit) and returns the
// events in chronological (log append) order. Token aggregation needs append
// order because runtime timestamps are second-resolution, so a batch of
// cumulative datapoints from one export commonly shares a timestamp; the
// cumulative dedup then relies on append order to recover the emission sequence.
// Restore oldest-first emission order after the newest-first ReadEvents sort
// before aggregating cumulative counters.
func ReadEventsAppendOrder(path string, query EventQuery) ([]schema.Event, error) {
	query.NoLimit = true
	result, err := ReadEvents(path, query)
	if err != nil {
		return nil, err
	}
	SortRecordsAppendOrder(result.Events)
	events := make([]schema.Event, 0, len(result.Events))
	for _, record := range result.Events {
		events = append(events, record.Event)
	}
	return events, nil
}

// ReadTokenEventsAppendOrder returns query-matched events plus the session context
// the token report reads outside the query, in one pass over the log. Context is
// kept separate so token totals and TotalEvents still describe only the requested
// time/model/session slice while session-level facts can reach back past it:
//
//   - every session.context event, so user attribution reaches back to SessionStart;
//   - for each session and live collection method, the earliest event that arrived
//     over that method (tokens.LiveCaptureKey), so the live/poll cutover is where the
//     live channel started capturing the session rather than where the window starts
//     or where its first usage record landed.
func ReadTokenEventsAppendOrder(path string, query EventQuery) ([]schema.Event, []schema.Event, error) {
	query, err := resolveSessionState(path, query)
	if err != nil {
		return nil, nil, err
	}
	result, err := ReadEvents(path, EventQuery{NoLimit: true})
	if err != nil {
		return nil, nil, err
	}
	SortRecordsAppendOrder(result.Events)
	events := make([]schema.Event, 0, len(result.Events))
	contexts := make([]schema.Event, 0)
	type liveStart struct {
		ts    time.Time
		event schema.Event
	}
	liveStarts := map[string]liveStart{}
	var liveOrder []string
	for _, record := range result.Events {
		if record.Event.Event.Action == "session.context" {
			contexts = append(contexts, record.Event)
		} else if key, ts, ok := tokens.LiveCaptureKey(record.Event); ok {
			if current, seen := liveStarts[key]; !seen {
				liveStarts[key] = liveStart{ts: ts, event: record.Event}
				liveOrder = append(liveOrder, key)
			} else if ts.Before(current.ts) {
				liveStarts[key] = liveStart{ts: ts, event: record.Event}
			}
		}
		if matchesQuery(record, query) {
			events = append(events, record.Event)
		}
	}
	for _, key := range liveOrder {
		contexts = append(contexts, liveStarts[key].event)
	}
	return events, contexts, nil
}

// StreamEvents reads every event from the runtime log and its rotated archives in
// chronological (append) order and invokes fn for each, with no limit and no result
// buffering. Rule evaluation (beacon scan) needs the full, ordered stream — ReadEvents
// caps results and sorts newest-first, which is wrong for ordered correlation. Malformed
// lines are skipped; a missing active log is not an error. If fn returns an error,
// streaming stops and returns it.
func StreamEvents(path string, fn func(schema.Event) error) error {
	return streamEventRecords(path, func(record EventRecord) error {
		return fn(record.Event)
	})
}

// streamEventRecords retains source/line identity for readers that link raw events to projections.
func streamEventRecords(path string, fn func(EventRecord) error) error {
	sources := eventSources(path) // [active, archive1, archive2, ...] (archives ascending)
	// Chronological order is oldest first: highest archive index down to 1, then the
	// active log last. Within a file, lines are already in append order.
	ordered := make([]eventSource, 0, len(sources))
	for i := len(sources) - 1; i >= 1; i-- {
		ordered = append(ordered, sources[i])
	}
	ordered = append(ordered, sources[0])

	for _, source := range ordered {
		if err := streamRecordSource(source, fn); err != nil {
			return err
		}
	}
	return nil
}

func streamRecordSource(source eventSource, fn func(EventRecord) error) error {
	file, err := os.Open(source.path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
	lineNo := 0
	for scanner.Scan() {
		lineNo++
		line := bytes.TrimSpace(scanner.Bytes())
		if len(line) == 0 {
			continue
		}
		var event schema.Event
		if err := json.Unmarshal(line, &event); err != nil {
			continue // skip malformed
		}
		normalizeDashboardEvent(&event)
		if err := fn(EventRecord{ID: source.lineID(lineNo), Line: lineNo, Event: event}); err != nil {
			return err
		}
	}
	return scanner.Err()
}

type sessionStateStats struct {
	hasVisibleActivity bool
	prompt             string
	promptAt           time.Time
	harness            string
	harnessAt          time.Time
	repository         string
	repositoryAt       time.Time
	user               string
	userAt             time.Time
}

type sessionClassification struct {
	state           string
	recurrenceCount int
}

func sessionIDsForState(path string, query EventQuery, state string) (map[string]bool, error) {
	classifications, _, err := classifySessions(path, query, false)
	if err != nil {
		return nil, err
	}
	ids := map[string]bool{}
	for id, classification := range classifications {
		if classification.state == state {
			ids[id] = true
		}
	}
	return ids, nil
}

// classifySessions assigns one mutually exclusive category to every session active
// in the selected time window. Recurrence is computed over that complete set before
// any event or session result limit is applied.
//
// It also returns each shared session's sharing state, worked out from every event of the session
// whatever the filters are: a session.shared record outside the selected window or filters still
// marks the session shared, and activity outside them still makes the share stale.
//
// withSharing false skips the sharing work (sessionIDsForState needs only the states). With it,
// only sessions that have a session.shared record are buffered: a cheap first pass, which parses
// only the lines that mention session.shared, names them.
func classifySessions(path string, query EventQuery, withSharing bool) (map[string]sessionClassification, map[string]*SessionSharing, error) {
	// Session state is a property of the whole session, not the filtered slice.
	// Only the selected time window scopes recurrence. The owner is part of the
	// recurrence key; content, harness and individual-session filters must not
	// change a group's classification or count.
	stateQuery := EventQuery{
		Since: query.Since,
		Until: query.Until,
	}
	stats := map[string]*sessionStateStats{}
	sessionRecords := map[string][]EventRecord{}
	shared := map[string]bool{}
	if withSharing {
		var err error
		if shared, err = sharedSessionIDs(path); err != nil {
			return nil, nil, err
		}
	}
	for _, source := range eventSources(path) {
		if err := collectSessionStateStats(source, stateQuery, stats, sessionRecords, shared); err != nil {
			return nil, nil, err
		}
	}
	// Sharing state depends on the order of a session's events, so fold them in append order
	// (across rotated archives), as ReadSessionDetail and the trace history do.
	sharing := map[string]*SessionSharing{}
	for id := range shared {
		records := sessionRecords[id]
		SortRecordsAppendOrder(records)
		acc := &sessionAccumulator{record: SessionRecord{ID: id}}
		for _, record := range records {
			if acc.record.Harness == "" {
				acc.record.Harness = record.Event.Harness.Name
			}
			acc.noteSharing(record)
		}
		if acc.record.Sharing == nil {
			continue
		}
		acc.finish()
		sharing[id] = acc.record.Sharing
	}
	groupCounts := map[string]int{}
	groupKeys := map[string]string{}
	for id, stat := range stats {
		if stat.prompt == "" || !stat.hasVisibleActivity {
			continue
		}
		key := recurrenceGroupKey(stat)
		groupKeys[id] = key
		groupCounts[key]++
	}
	classifications := make(map[string]sessionClassification, len(stats))
	for id, stat := range stats {
		classification := sessionClassification{state: "captured"}
		if !stat.hasVisibleActivity {
			classification.state = "empty"
		} else if key := groupKeys[id]; key != "" && groupCounts[key] >= 2 {
			classification.state = "recurring"
			classification.recurrenceCount = groupCounts[key]
		}
		classifications[id] = classification
	}
	return classifications, sharing, nil
}

// sharingRecordBuffered is called once per record classifySessions buffers for the sharing state;
// tests replace it to count.
var sharingRecordBuffered = func() {}

var sessionSharedMarker = []byte(`"session.shared"`)

// sharedSessionIDs names the sessions that have a session.shared record. It parses only the lines
// that mention session.shared, so a log with no shares costs one read and no decoding.
func sharedSessionIDs(path string) (map[string]bool, error) {
	ids := map[string]bool{}
	for _, source := range eventSources(path) {
		file, err := os.Open(source.path)
		if err != nil {
			if os.IsNotExist(err) {
				continue
			}
			return nil, err
		}
		scanner := bufio.NewScanner(file)
		scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
		for scanner.Scan() {
			line := scanner.Bytes()
			if !bytes.Contains(line, sessionSharedMarker) {
				continue
			}
			var probe struct {
				Event struct {
					Action string `json:"action"`
				} `json:"event"`
				Session *struct {
					ID string `json:"id"`
				} `json:"session"`
			}
			if json.Unmarshal(line, &probe) == nil && probe.Event.Action == "session.shared" && probe.Session != nil && probe.Session.ID != "" {
				ids[probe.Session.ID] = true
			}
		}
		err = scanner.Err()
		file.Close()
		if err != nil {
			return nil, err
		}
	}
	return ids, nil
}

func collectSessionStateStats(source eventSource, query EventQuery, stats map[string]*sessionStateStats, sessionRecords map[string][]EventRecord, shared map[string]bool) error {
	file, err := os.Open(source.path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
	lineNo := 0
	for scanner.Scan() {
		lineNo++
		line := bytes.TrimSpace(scanner.Bytes())
		if len(line) == 0 {
			continue
		}
		var event schema.Event
		if err := json.Unmarshal(line, &event); err != nil {
			continue
		}
		normalizeDashboardEvent(&event)
		parsed, _ := asymptoteobserve.ParseTimestamp(event.Timestamp)
		record := EventRecord{
			ID:         source.lineID(lineNo),
			Line:       lineNo,
			Event:      event,
			Raw:        append(json.RawMessage(nil), line...),
			Parsed:     parsed,
			WazuhLevel: WazuhLevel(event.Event.Action),
		}
		if event.Session == nil || event.Session.ID == "" {
			continue
		}
		// A shared session's records, slimmed to what the sharing state reads, whatever the
		// filters. Sessions never shared are not buffered.
		if shared[event.Session.ID] {
			sessionRecords[event.Session.ID] = append(sessionRecords[event.Session.ID], shareRelevantRecord(record))
			sharingRecordBuffered()
		}
		if !matchesQuery(record, query) {
			continue
		}
		stat := stats[event.Session.ID]
		if stat == nil {
			stat = &sessionStateStats{}
			stats[event.Session.ID] = stat
		}
		if prompt := strings.TrimSpace(promptText(event)); prompt != "" && (stat.prompt == "" || eventComesBefore(parsed, stat.promptAt)) {
			stat.prompt = prompt
			stat.promptAt = parsed
		}
		if harness := strings.TrimSpace(event.Harness.Name); harness != "" && (stat.harness == "" || eventComesBefore(parsed, stat.harnessAt)) {
			stat.harness = harness
			stat.harnessAt = parsed
		}
		if repository := strings.TrimSpace(event.Repository); repository != "" && (stat.repository == "" || eventComesBefore(parsed, stat.repositoryAt)) {
			stat.repository = repository
			stat.repositoryAt = parsed
		}
		if user := normalizedSessionUser(event); user != "" && (stat.user == "" || eventComesBefore(parsed, stat.userAt)) {
			stat.user = user
			stat.userAt = parsed
		}
		if !isInternalSessionEvent(event) {
			stat.hasVisibleActivity = true
		}
	}
	return scanner.Err()
}

func eventComesBefore(candidate, current time.Time) bool {
	return !candidate.IsZero() && (current.IsZero() || candidate.Before(current))
}

func recurrenceGroupKey(stat *sessionStateStats) string {
	return strings.Join([]string{
		normalizeComparisonValue(stat.user),
		normalizeComparisonValue(stat.prompt),
		normalizeComparisonValue(asymptoteobserve.NormalizeHarnessName(stat.harness)),
		normalizeComparisonValue(stat.repository),
	}, "\x00")
}

func normalizeComparisonValue(value string) string {
	return strings.ToLower(strings.TrimSpace(value))
}

func normalizedSessionUser(event schema.Event) string {
	if uid := normalizeComparisonValue(event.User.UID); uid != "" {
		return "uid:" + uid
	}
	if name := normalizeComparisonValue(event.User.Name); name != "" {
		return "name:" + name
	}
	// Empty is the consistent identity for events without an owner in this local scope.
	return ""
}

func isPromptEvent(event schema.Event) bool {
	action := normalizedLifecycleValue(event.Event.Action)
	// Prompt text, not the prompt object: every event of a turn carries prompt.id, and a tool call
	// is not a prompt because it names the prompt it belongs to.
	return strings.EqualFold(event.Event.Category, "prompt") || strings.Contains(action, "prompt") || (event.Prompt != nil && event.Prompt.Text != "")
}

func isLifecycleSessionEvent(event schema.Event) bool {
	switch normalizedLifecycleValue(event.Event.Action) {
	case "session started", "agent session started", "session ended", "agent session ended":
		return true
	}
	switch normalizedLifecycleValue(event.Message) {
	case "session started", "agent session started", "session ended", "agent session ended":
		return true
	}
	return false
}

func isInternalSessionEvent(event schema.Event) bool {
	if isLifecycleSessionEvent(event) {
		return true
	}
	category := strings.ToLower(strings.TrimSpace(event.Event.Category))
	switch category {
	case "inventory", "validation", "metric":
		return true
	}
	action := strings.ToLower(strings.TrimSpace(event.Event.Action))
	for _, prefix := range []string{"inventory.", "validation.", "metric.", "endpoint.", "telemetry."} {
		if strings.HasPrefix(action, prefix) {
			return true
		}
	}
	return false
}

func normalizedLifecycleValue(value string) string {
	replacer := strings.NewReplacer(".", " ", "_", " ", "-", " ")
	return strings.Join(strings.Fields(strings.ToLower(replacer.Replace(strings.TrimSpace(value)))), " ")
}

func normalizeSessionState(value string) string {
	switch strings.ToLower(strings.TrimSpace(value)) {
	case "empty":
		return "empty"
	case "captured":
		return "captured"
	case "recurring":
		return "recurring"
	default:
		return ""
	}
}

func rawString(raw map[string]interface{}, key string) string {
	if raw == nil {
		return ""
	}
	value, ok := raw[key]
	if !ok {
		return ""
	}
	switch typed := value.(type) {
	case string:
		return typed
	default:
		return fmt.Sprint(typed)
	}
}

// SortRecordsAppendOrder orders records oldest-first: by timestamp, then by the
// emitting writer's sequence, then older archives before the live log, then by
// numeric line.
//
// Token aggregation needs this because a single metric export flushes a batch of
// cumulative datapoints that all carry that export's collection instant, so they
// tie on the timestamp however precise it is, and the cumulative dedup needs
// their emission order back. Sequence recovers it directly; the archive-and-line
// tiebreak below is the fallback for events written before sequence stamping,
// and is also used in reverse by the newest-first ReadEvents sort so limiting
// a result cannot discard newer events on lexicographic line-ID ties.
func SortRecordsAppendOrder(records []EventRecord) {
	sort.SliceStable(records, func(i, j int) bool {
		return recordBefore(records[i], records[j])
	})
}

func recordBefore(a, b EventRecord) bool {
	if !a.Parsed.Equal(b.Parsed) {
		return a.Parsed.Before(b.Parsed)
	}
	si, sj := a.Event.Sequence, b.Event.Sequence
	iHasSeq := si != 0
	jHasSeq := sj != 0
	if iHasSeq != jHasSeq {
		return !iHasSeq // unsequenced before sequenced
	}
	if iHasSeq && si != sj {
		return si < sj
	}
	ai, li, _ := parseRecordID(a.ID)
	aj, lj, _ := parseRecordID(b.ID)
	if ai != aj {
		// Higher archive index is an older rotation, so it comes first.
		return ai > aj
	}
	return li < lj
}

func readEventsFromSource(source eventSource, query EventQuery, result *EventResult, limit int) error {
	file, err := os.Open(source.path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)

	lineNo := 0
	for scanner.Scan() {
		lineNo++
		line := bytes.TrimSpace(scanner.Bytes())
		if len(line) == 0 {
			continue
		}
		var event schema.Event
		if err := json.Unmarshal(line, &event); err != nil {
			result.MalformedLines++
			continue
		}
		normalizeDashboardEvent(&event)
		parsed, _ := asymptoteobserve.ParseTimestamp(event.Timestamp)
		record := EventRecord{
			ID:         source.lineID(lineNo),
			Line:       lineNo,
			Event:      event,
			Raw:        append(json.RawMessage(nil), line...),
			Parsed:     parsed,
			WazuhLevel: WazuhLevel(event.Event.Action),
		}
		if !matchesQuery(record, query) {
			continue
		}
		result.TotalMatched++
		result.Events = append(result.Events, record)
		if !query.NoLimit {
			sort.SliceStable(result.Events, func(i, j int) bool {
				return recordBefore(result.Events[j], result.Events[i])
			})
			if len(result.Events) > limit {
				result.Events = result.Events[:limit]
			}
		}
	}
	if err := scanner.Err(); err != nil {
		return err
	}
	return nil
}

func FindEvent(path, id string) (EventRecord, bool, error) {
	archiveNum, lineNo, ok := parseRecordID(id)
	if !ok {
		return EventRecord{}, false, nil
	}
	source, found := findSource(eventSources(path), archiveNum)
	if !found {
		return EventRecord{}, false, nil
	}
	file, err := os.Open(source.path)
	if err != nil {
		if os.IsNotExist(err) {
			return EventRecord{}, false, nil
		}
		return EventRecord{}, false, err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
	currentLine := 0
	for scanner.Scan() {
		currentLine++
		if currentLine != lineNo {
			continue
		}
		line := bytes.TrimSpace(scanner.Bytes())
		if len(line) == 0 {
			return EventRecord{}, false, nil
		}
		var event schema.Event
		if err := json.Unmarshal(line, &event); err != nil {
			return EventRecord{}, false, nil
		}
		normalizeDashboardEvent(&event)
		parsed, _ := asymptoteobserve.ParseTimestamp(event.Timestamp)
		return EventRecord{
			ID:         source.lineID(lineNo),
			Line:       lineNo,
			Event:      event,
			Raw:        append(json.RawMessage(nil), line...),
			Parsed:     parsed,
			WazuhLevel: WazuhLevel(event.Event.Action),
		}, true, nil
	}
	if err := scanner.Err(); err != nil {
		return EventRecord{}, false, err
	}
	return EventRecord{}, false, nil
}

type eventSource struct {
	path    string
	archive int
}

func (s eventSource) lineID(line int) string {
	if s.archive == 0 {
		return fmt.Sprintf("line-%d", line)
	}
	return fmt.Sprintf("archive-%d-line-%d", s.archive, line)
}

func eventSources(path string) []eventSource {
	sources := []eventSource{{path: path}}
	dir := filepath.Dir(path)
	base := filepath.Base(path)
	entries, err := os.ReadDir(dir)
	if err != nil {
		return sources
	}
	prefix := base + "."
	var archives []eventSource
	for _, entry := range entries {
		name := entry.Name()
		suffix, ok := strings.CutPrefix(name, prefix)
		if !ok {
			continue
		}
		index, err := strconv.Atoi(suffix)
		if err != nil || index <= 0 {
			continue
		}
		archives = append(archives, eventSource{path: filepath.Join(dir, name), archive: index})
	}
	sort.Slice(archives, func(i, j int) bool {
		return archives[i].archive < archives[j].archive
	})
	return append(sources, archives...)
}

func findSource(sources []eventSource, archive int) (eventSource, bool) {
	for _, s := range sources {
		if s.archive == archive {
			return s, true
		}
	}
	return eventSource{}, false
}

func normalizeDashboardEvent(event *schema.Event) {
	asymptoteobserve.NormalizeTraceEvent(event)
}

func normalizeLimit(limit int) int {
	if limit <= 0 {
		return defaultEventLimit
	}
	if limit > maxEventLimit {
		return maxEventLimit
	}
	return limit
}

func matchesQuery(record EventRecord, query EventQuery) bool {
	event := record.Event
	if !query.Since.IsZero() {
		if record.Parsed.IsZero() || record.Parsed.Before(query.Since) {
			return false
		}
	}
	if !query.Until.IsZero() {
		if record.Parsed.IsZero() || record.Parsed.After(query.Until) {
			return false
		}
	}
	if query.Harness != "" && !strings.EqualFold(asymptoteobserve.NormalizeHarnessName(event.Harness.Name), asymptoteobserve.NormalizeHarnessName(query.Harness)) {
		return false
	}
	if query.Model != "" && !containsFold(event.Model, query.Model) {
		return false
	}
	if query.Action != "" && !strings.EqualFold(event.Event.Action, query.Action) {
		return false
	}
	if query.Severity != "" && !strings.EqualFold(string(event.Severity), query.Severity) {
		return false
	}
	if query.Category != "" && !strings.EqualFold(event.Event.Category, query.Category) {
		return false
	}
	if query.Repository != "" && !containsFold(event.Repository, query.Repository) {
		return false
	}
	if query.Session != "" {
		if event.Session == nil || !containsFold(event.Session.ID, query.Session) {
			return false
		}
	}
	if query.Trace != "" {
		if event.Trace == nil || (!containsFold(event.Trace.ID, query.Trace) && !containsFold(event.Trace.SpanID, query.Trace) && !containsFold(event.Trace.ParentSpanID, query.Trace)) {
			return false
		}
	}
	if query.File != "" {
		if event.File == nil || !containsFold(event.File.Path, query.File) {
			return false
		}
	}
	if query.Command != "" && !matchesCommand(event, query.Command) {
		return false
	}
	if query.MCP != "" {
		if event.MCP == nil || (!containsFold(event.MCP.Server, query.MCP) && !containsFold(event.MCP.Tool, query.MCP)) {
			return false
		}
	}
	if query.Approval != "" {
		if event.Approval == nil || (!containsFold(event.Approval.Decision, query.Approval) && !containsFold(event.Approval.Reason, query.Approval)) {
			return false
		}
	}
	if query.Decision != "" {
		if !matchesDecision(event, query.Decision) {
			return false
		}
	}
	if query.Policy != "" {
		if event.Policy == nil || (!containsFold(event.Policy.ID, query.Policy) && !containsFold(event.Policy.Name, query.Policy) && !containsFold(event.Policy.Decision, query.Policy) && !containsFold(event.Policy.Reason, query.Policy)) {
			return false
		}
	}
	if query.Review != "" && truthy(query.Review) && !isNeedsReview(record) {
		return false
	}
	if query.WazuhLevel != "" && !strings.EqualFold(strconv.Itoa(record.WazuhLevel), query.WazuhLevel) {
		return false
	}
	if query.SessionState != "" {
		if event.Session == nil || event.Session.ID == "" || !query.sessionStateIDs[event.Session.ID] {
			return false
		}
	}
	if query.Q != "" && !matchesFreeText(record, query.Q) {
		return false
	}
	return true
}

func containsFold(value, needle string) bool {
	return strings.Contains(strings.ToLower(value), strings.ToLower(strings.TrimSpace(needle)))
}

func matchesDecision(event schema.Event, decision string) bool {
	if event.Approval != nil && containsFold(event.Approval.Decision, decision) {
		return true
	}
	if event.Policy != nil && containsFold(event.Policy.Decision, decision) {
		return true
	}
	return false
}

func matchesCommand(event schema.Event, command string) bool {
	if event.Command != nil && containsFold(event.Command.Command, command) {
		return true
	}
	if event.Tool != nil && (containsFold(event.Tool.Name, command) || containsFold(event.Tool.Command, command)) {
		return true
	}
	return false
}

func matchesFreeText(record EventRecord, query string) bool {
	haystack := strings.ToLower(strings.Join(searchFields(record), "\x00"))
	for _, term := range strings.Fields(strings.ToLower(strings.TrimSpace(query))) {
		if !strings.Contains(haystack, term) {
			return false
		}
	}
	return true
}

func searchFields(record EventRecord) []string {
	event := record.Event
	fields := []string{
		record.ID,
		strconv.Itoa(record.Line),
		strconv.Itoa(record.WazuhLevel),
		event.Timestamp,
		event.Event.Kind,
		event.Event.Action,
		event.Event.Category,
		string(event.Severity),
		event.Endpoint.Hostname,
		event.Endpoint.OS,
		event.Endpoint.AgentVersion,
		event.User.Name,
		event.User.UID,
		event.Harness.Name,
		event.Harness.Version,
		event.Harness.ExecutablePath,
		event.Harness.ConfigPath,
		event.Harness.Profile,
		event.Model,
		event.Repository,
		event.Branch,
		event.Message,
	}
	if event.Session != nil {
		fields = append(fields, event.Session.ID, event.Session.WorkingDirectory)
	}
	if event.Trace != nil {
		fields = append(fields, event.Trace.ID, event.Trace.SpanID, event.Trace.ParentSpanID)
	}
	if event.Tool != nil {
		fields = append(fields, event.Tool.Name, event.Tool.Command, event.Tool.Path)
	}
	if event.File != nil {
		fields = append(fields, event.File.Path, event.File.Operation, event.File.Language, event.File.DiffHash, strconv.Itoa(event.File.DiffBytes))
	}
	if event.Command != nil {
		fields = append(fields, event.Command.Command, strconv.FormatInt(event.Command.DurationMS, 10))
		if event.Command.ExitCode != nil {
			fields = append(fields, strconv.Itoa(*event.Command.ExitCode))
		}
	}
	if event.MCP != nil {
		fields = append(fields, event.MCP.Server, event.MCP.Tool)
	}
	if event.Approval != nil {
		fields = append(fields, event.Approval.Decision, event.Approval.Reason)
	}
	if event.Policy != nil {
		fields = append(fields, event.Policy.ID, event.Policy.Name, event.Policy.Decision, event.Policy.Enforcement, event.Policy.Reason)
	}
	if event.Prompt != nil {
		fields = append(fields, event.Prompt.Text)
	}
	if event.Content != nil {
		fields = append(fields, event.Content.Retention)
		if event.Content.Included {
			fields = append(fields, "content included")
		}
		if event.Content.Redacted {
			fields = append(fields, "redacted")
		}
		if event.Content.Truncated {
			fields = append(fields, "truncated")
		}
	}
	if event.Destination != nil {
		fields = append(fields, event.Destination.Type, event.Destination.Mode, event.Destination.Status)
	}
	if event.Health != nil {
		fields = append(fields, event.Health.Component, event.Health.Status, event.Health.Reason)
	}
	if event.Truncated {
		fields = append(fields, "truncated")
	}
	return fields
}

func activeFilters(query EventQuery) map[string]string {
	filters := map[string]string{}
	add := func(key, value string) {
		value = strings.TrimSpace(value)
		if value != "" {
			filters[key] = value
		}
	}
	add("harness", query.Harness)
	add("model", query.Model)
	add("action", query.Action)
	add("severity", query.Severity)
	add("category", query.Category)
	add("repository", query.Repository)
	add("session", query.Session)
	add("trace", query.Trace)
	add("file", query.File)
	add("command", query.Command)
	add("mcp", query.MCP)
	add("approval", query.Approval)
	add("decision", query.Decision)
	add("policy", query.Policy)
	add("review", query.Review)
	add("wazuh_level", query.WazuhLevel)
	add("session_state", query.SessionState)
	if !query.Since.IsZero() {
		filters["since"] = query.Since.Format(time.RFC3339)
	}
	if !query.Until.IsZero() {
		filters["until"] = query.Until.Format(time.RFC3339)
	}
	if len(filters) == 0 {
		return nil
	}
	return filters
}

func truthy(value string) bool {
	switch strings.ToLower(strings.TrimSpace(value)) {
	case "1", "true", "yes", "review", "needs_review":
		return true
	default:
		return false
	}
}

func parseRecordID(id string) (int, int, bool) {
	if archiveID, rest, ok := strings.Cut(strings.TrimPrefix(id, "archive-"), "-line-"); ok && strings.HasPrefix(id, "archive-") {
		archive, err := strconv.Atoi(archiveID)
		if err != nil || archive <= 0 {
			return 0, 0, false
		}
		lineNo, err := strconv.Atoi(rest)
		if err != nil || lineNo <= 0 {
			return 0, 0, false
		}
		return archive, lineNo, true
	}
	line, ok := strings.CutPrefix(id, "line-")
	if !ok {
		return 0, 0, false
	}
	lineNo, err := strconv.Atoi(line)
	if err != nil || lineNo <= 0 {
		return 0, 0, false
	}
	return 0, lineNo, true
}

func WazuhLevel(action string) int {
	switch action {
	case "endpoint.tamper_detected", "endpoint.health_failed":
		return 12
	case "approval.denied", "policy.blocked":
		return 10
	case "tool.failed":
		return 9
	case "command.executed", "mcp.tool_invoked":
		return 7
	case "telemetry.disabled", "telemetry.misconfigured", "prompt.submitted", "tool.invoked", "tool.completed", "file.read", "file.modified":
		return 5
	case "":
		return 0
	default:
		return 3
	}
}