Skip to content

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

32.9 KB
Raw Blame
package asymptoteobserve

import (
	"errors"
	"os"
	"runtime"
	"time"
)

const (
	Vendor        = "beacon"
	Product       = "endpoint-agent"
	SchemaVersion = "1.0"
)

type Severity string

const (
	SeverityInfo     Severity = "info"
	SeverityLow      Severity = "low"
	SeverityMedium   Severity = "medium"
	SeverityHigh     Severity = "high"
	SeverityCritical Severity = "critical"
)

type Origin string

const (
	OriginLocal Origin = "local"
	OriginCloud Origin = "cloud"
	OriginCI    Origin = "ci"
)

const (
	AttributeOrigin        = "beacon.origin"
	AttributeRunProvider   = "beacon.run.provider"
	AttributeRunID         = "beacon.run.run_id"
	AttributeRunAttempt    = "beacon.run.run_attempt"
	AttributeRunWorkflow   = "beacon.run.workflow"
	AttributeRunJob        = "beacon.run.job"
	AttributeRunEventName  = "beacon.run.event_name"
	AttributeRunCommit     = "beacon.run.commit"
	AttributeRunRepository = "beacon.run.repository"
	AttributeRunBranch     = "beacon.run.branch"
	AttributeRunPR         = "beacon.run.pr"
	AttributeRunPRNumber   = "beacon.run.pr_number"
	AttributeRunActor      = "beacon.run.actor"
	AttributeRunEphemeral  = "beacon.run.ephemeral"
)

// EventInfo names what happened. ID is the event's stable identity: see
// EventIDForLine for how it is derived and what equality between two of them
// means.
type EventInfo struct {
	ID       string `json:"id,omitempty"`
	Kind     string `json:"kind"`
	Action   string `json:"action"`
	Category string `json:"category,omitempty"`
	// Fidelity records whether Action was reported by the source or derived by Beacon.
	// See FidelityObserved / FidelityInferred in provenance.go. Empty when the question does
	// not apply, as it does not for events Beacon emits about itself.
	Fidelity string `json:"fidelity,omitempty"`
}

type EndpointInfo struct {
	Hostname     string `json:"hostname,omitempty"`
	OS           string `json:"os"`
	AgentVersion string `json:"agent_version,omitempty"`
}

type UserInfo struct {
	Name string `json:"name,omitempty"`
	UID  string `json:"uid,omitempty"`
}

type HarnessInfo struct {
	Name           string `json:"name"`
	Version        string `json:"version,omitempty"`
	ExecutablePath string `json:"executable_path,omitempty"`
	ConfigPath     string `json:"config_path,omitempty"`
	// Profile names the runtime profile the event came from, for runtimes that keep separate
	// configuration and state per profile on one host.
	Profile string `json:"profile,omitempty"`
	// CollectionMethod records the mechanism that carried this event off the runtime.
	// See the CollectionMethod* constants in provenance.go. Empty for events Beacon emits
	// about itself, which no harness collected.
	CollectionMethod string `json:"collection_method,omitempty"`
}

type SessionInfo struct {
	ID               string `json:"id,omitempty"`
	WorkingDirectory string `json:"working_directory,omitempty"`
}

type TraceInfo struct {
	ID           string `json:"id,omitempty"`
	SpanID       string `json:"span_id,omitempty"`
	ParentSpanID string `json:"parent_span_id,omitempty"`
}

type ErrorInfo struct {
	Type string `json:"type,omitempty"`
}

type JSONRPCRequestInfo struct {
	ID string `json:"id,omitempty"`
}

type JSONRPCProtocolInfo struct {
	Version string `json:"version,omitempty"`
}

type JSONRPCInfo struct {
	Request  *JSONRPCRequestInfo  `json:"request,omitempty"`
	Protocol *JSONRPCProtocolInfo `json:"protocol,omitempty"`
}

type NetworkProtocolInfo struct {
	Name    string `json:"name,omitempty"`
	Version string `json:"version,omitempty"`
}

type NetworkInfo struct {
	Protocol  *NetworkProtocolInfo `json:"protocol,omitempty"`
	Transport string               `json:"transport,omitempty"`
}

type RPCResponseInfo struct {
	StatusCode string `json:"status_code,omitempty"`
}

type RPCInfo struct {
	Response *RPCResponseInfo `json:"response,omitempty"`
}

type RunInfo struct {
	Provider   string `json:"provider,omitempty"`
	RunID      string `json:"run_id,omitempty"`
	RunAttempt string `json:"run_attempt,omitempty"`
	Workflow   string `json:"workflow,omitempty"`
	Job        string `json:"job,omitempty"`
	EventName  string `json:"event_name,omitempty"`
	Commit     string `json:"commit,omitempty"`
	Repository string `json:"repository,omitempty"`
	Branch     string `json:"branch,omitempty"`
	// PR holds the raw pull-request ref (e.g. refs/pull/12/merge) and is only
	// populated on pull-request events; it is left empty for non-PR refs such
	// as push builds. PRNumber is the parsed pull-request number.
	PR        string `json:"pr,omitempty"`
	PRNumber  string `json:"pr_number,omitempty"`
	Actor     string `json:"actor,omitempty"`
	Ephemeral bool   `json:"ephemeral,omitempty"`
}

type ToolInfo struct {
	Name    string `json:"name,omitempty"`
	Command string `json:"command,omitempty"`
	Path    string `json:"path,omitempty"`
}

type FileInfo struct {
	Path      string `json:"path,omitempty"`
	Operation string `json:"operation,omitempty"`
	Language  string `json:"language,omitempty"`
	DiffHash  string `json:"diff_hash,omitempty"`
	DiffBytes int    `json:"diff_bytes,omitempty"`
	// Diff is the retained unified diff for the edit. DiffHash is the hash of the
	// whole diff after secret redaction and DiffBytes the original diff's size
	// (RetainedDiff), so both stay stable when the stored copy is truncated and
	// the hash never confirms a guess at a secret the stored diff no longer
	// shows; the accompanying Content marker says whether either happened.
	//
	// Declared here because the hook adapter has always written it. It assembles
	// events as maps, so `file.diff` reached the log while this struct -- what the
	// dashboard, `beacon scan` and the CEL rules engine read events through --
	// dropped it on parse. The diff was captured and unreadable at the same time,
	// and no rule could match on it because the field reference is generated from
	// this type.
	Diff string `json:"diff,omitempty"`
}

type CommandInfo struct {
	Command    string `json:"command,omitempty"`
	ExitCode   *int   `json:"exit_code,omitempty"`
	DurationMS int64  `json:"duration_ms,omitempty"`
	// Output is the retained combined output of the command, when the runtime
	// reports it. Same history as FileInfo.Diff: Cursor's afterShellExecution hook
	// has always written `command.output`, and this struct has always dropped it.
	Output string `json:"output,omitempty"`
	// ParsedCommands is Command read as a bash command line, for the threat-rules engine only:
	// the commands it runs, so a rule can tell `curl ... | sudo bash` from the same text inside
	// a quoted string or a here-document. It is never written or read; the engine fills it on
	// its own copy of each event, as it does GenAIToolCallInfo.ResultText. See
	// threatrules.ParsedCommands.
	ParsedCommands []ParsedCommand `json:"-" cel:"parsed_commands"`
}

// ParsedCommand is one command of a command line, as the threat-rules engine presents it to
// rules (e.command.parsed_commands). It is never serialized; the cel tags are the names a rule
// uses. threatrules.ParsedCommands says how each field is derived.
type ParsedCommand struct {
	// Name is the base name of the command after its wrappers (sudo, env, exec, ...): rm for
	// `sudo /bin/rm -rf x`. Empty when it is unknown.
	Name string `cel:"name"`
	// Argv are the command's words as the shell passes them, wrappers included; a word whose
	// value the parse cannot know (a parameter, substitution, glob or leading tilde) is "".
	Argv []string `cel:"argv"`
	// ArgvRaw are the same words as written, quotes and expansions included ($HOME, /*).
	ArgvRaw []string `cel:"argv_raw"`
	// Env are the NAME=value assignments before the command; an unknown value is "".
	Env map[string]string `cel:"env"`
	// FileEffects are the files the command evidently writes, and how.
	FileEffects []ParsedFileEffect `cel:"file_effects"`
	// Pipeline identifies the command's pipeline: the stages of one pipeline share it. Stage
	// is the 0-based position in it (curl ... | sh: sh is stage 1).
	Pipeline int `cel:"pipeline"`
	Stage    int `cel:"stage"`
	// Nested is true for a command inside a command or process substitution, or inside the
	// script a shell runs with -c.
	Nested bool `cel:"nested"`
}

// ParsedFileEffect is a file a parsed command evidently writes. Op is one of write, append,
// touch, truncate, edit, delete, move_from, move_to, link.
type ParsedFileEffect struct {
	Path string `cel:"path"`
	Op   string `cel:"op"`
}

type MCPMethodInfo struct {
	Name string `json:"name,omitempty"`
}

type MCPProtocolInfo struct {
	Version string `json:"version,omitempty"`
}

type MCPResourceInfo struct {
	URI string `json:"uri,omitempty"`
}

type MCPSessionInfo struct {
	ID string `json:"id,omitempty"`
}

type MCPInfo struct {
	Server   string           `json:"server,omitempty"`
	Tool     string           `json:"tool,omitempty"`
	Method   *MCPMethodInfo   `json:"method,omitempty"`
	Protocol *MCPProtocolInfo `json:"protocol,omitempty"`
	Resource *MCPResourceInfo `json:"resource,omitempty"`
	Session  *MCPSessionInfo  `json:"session,omitempty"`
}

type ApprovalInfo struct {
	Required bool   `json:"required,omitempty"`
	Decision string `json:"decision,omitempty"`
	Reason   string `json:"reason,omitempty"`
}

type PolicyInfo struct {
	ID          string `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	Decision    string `json:"decision,omitempty"`
	Enforcement string `json:"enforcement,omitempty"`
	Reason      string `json:"reason,omitempty"`
}

// PromptInfo describes the user prompt an event belongs to.
//
// Text is set only on the prompt itself. ID is set on every event the prompt led to, from the
// prompt through the agent's response until the next prompt, so one value selects a whole turn.
// It is the runtime's own identifier, normalized from its spelling by PromptIDKeys; a present
// prompt object therefore no longer means the event is a prompt -- Text, or the prompt category,
// says that.
type PromptInfo struct {
	ID   string `json:"id,omitempty"`
	Text string `json:"text,omitempty"`
}

// TurnInfo says how the agent's turn ended, as the runtime reported it on its turn-end hook.
//
// Status is the runtime's own word, kept verbatim: Cursor's stop hook sends completed, aborted or
// error. The block is set only when the runtime names a status. Beacon never fills in a default,
// because a turn recorded as completed when the runtime said nothing would read like one the
// runtime confirmed.
type TurnInfo struct {
	Status string `json:"status,omitempty"`
}

// SystemContextInfo says what a session.context event recorded when the runtime gave the model
// context of its own, outside the conversation: which kind it was, where Beacon read it, and for a
// skill index, which skills it listed. The text itself is in gen_ai.system_instructions. This block
// is metadata, so it stays on an event whose text is removed, as metadata-only forwarding does.
type SystemContextInfo struct {
	Kind   string         `json:"kind"`
	Source string         `json:"source,omitempty"`
	Skills []SkillRefInfo `json:"skills,omitempty"`
}

// SkillRefInfo names one skill. The fields are spelled and SkillNameHash is computed the way the
// configuration inventory records a skill it found on disk, so a skill the model was shown joins
// to the SKILL.md it came from.
type SkillRefInfo struct {
	SkillName     string `json:"skill_name,omitempty"`
	SkillNameHash string `json:"skill_name_hash,omitempty"`
}

// SystemContextInfo.Kind values.
const (
	// SystemContextSkillListing is a skill index: each skill's name and description, which the
	// runtime lists so the model can choose one. A skill's body is not part of it.
	SystemContextSkillListing = "skill_listing"
)

// SystemContextInfo.Source values: where the runtime exposed the context to Beacon. With
// harness.name they say exactly which reader produced an event.
const (
	SystemContextSourceSystemPrompt = "system_prompt"
	SystemContextSourceTranscript   = "transcript"
)

// ContentInfo marks how an event's retained raw content was handled. Hash is of
// the whole content after secret redaction and Bytes the original content's
// size, both before truncation, so events keep a stable identifier and size
// even when the stored text was cut down, and the hash confirms nothing
// redaction removed.
type ContentInfo struct {
	Retention string `json:"retention"`
	Included  bool   `json:"included"`
	Redacted  bool   `json:"redacted,omitempty"`
	Truncated bool   `json:"truncated,omitempty"`
	Hash      string `json:"hash,omitempty"`
	Bytes     int    `json:"bytes,omitempty"`
}

const (
	ContentRetentionMetadata = "metadata"
	ContentRetentionRedacted = "redacted"
	ContentRetentionFull     = "full"
)

type GenAIAgentInfo struct {
	Description string `json:"description,omitempty"`
	ID          string `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	Version     string `json:"version,omitempty"`
}

type GenAIConversationInfo struct {
	ID string `json:"id,omitempty"`
}

type GenAIDataSourceInfo struct {
	ID string `json:"id,omitempty"`
}

type GenAIEmbeddingsInfo struct {
	DimensionCount *int `json:"dimension_count,omitempty"`
}

type GenAIEvaluationScoreInfo struct {
	Label string   `json:"label,omitempty"`
	Value *float64 `json:"value,omitempty"`
}

type GenAIEvaluationInfo struct {
	Explanation string                    `json:"explanation,omitempty"`
	Name        string                    `json:"name,omitempty"`
	Score       *GenAIEvaluationScoreInfo `json:"score,omitempty"`
}

type GenAIInputInfo struct {
	Messages interface{} `json:"messages,omitempty"`
}

type GenAIOperationInfo struct {
	Name string `json:"name,omitempty"`
}

type GenAIOutputInfo struct {
	Messages interface{} `json:"messages,omitempty"`
	Type     string      `json:"type,omitempty"`
}

type GenAIPromptInfo struct {
	Name string `json:"name,omitempty"`
}

type GenAIProviderInfo struct {
	Name string `json:"name,omitempty"`
}

type GenAIRequestInfo struct {
	ChoiceCount      *int     `json:"choice_count,omitempty"`
	EncodingFormats  []string `json:"encoding_formats,omitempty"`
	FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
	MaxTokens        *int     `json:"max_tokens,omitempty"`
	Model            string   `json:"model,omitempty"`
	PresencePenalty  *float64 `json:"presence_penalty,omitempty"`
	Seed             *int     `json:"seed,omitempty"`
	StopSequences    []string `json:"stop_sequences,omitempty"`
	Stream           *bool    `json:"stream,omitempty"`
	Temperature      *float64 `json:"temperature,omitempty"`
	TopK             *float64 `json:"top_k,omitempty"`
	TopP             *float64 `json:"top_p,omitempty"`
}

type GenAIResponseInfo struct {
	FinishReasons    []string `json:"finish_reasons,omitempty"`
	ID               string   `json:"id,omitempty"`
	Model            string   `json:"model,omitempty"`
	TimeToFirstChunk *float64 `json:"time_to_first_chunk,omitempty"`
}

type GenAIRetrievalInfo struct {
	Documents interface{} `json:"documents,omitempty"`
	QueryText string      `json:"query_text,omitempty"`
}

type GenAITokenInfo struct {
	Type string `json:"type,omitempty"`
}

type GenAIToolCallInfo struct {
	Arguments interface{} `json:"arguments,omitempty"`
	ID        string      `json:"id,omitempty"`
	Result    interface{} `json:"result,omitempty"`
	// ResultText is Result as plain text, for the threat-rules engine only. Result is
	// interface{} (a runtime may report a string, an object or a list of content
	// blocks), and CEL cannot address an interface{} field, so without this no rule
	// could match on what a file read, a web fetch or an MCP tool returned.
	//
	// It is never written or read: `json:"-"` keeps it off the wire, so the JSONL
	// contract is unchanged and a log line cannot assert it. The engine fills it on
	// its own copy of each event, from the retained Result, just before evaluation.
	// See threatrules.ToolResultText for exactly which events get a value.
	ResultText string `json:"-" cel:"result_text"`
}

type GenAIToolInfo struct {
	Call        *GenAIToolCallInfo `json:"call,omitempty"`
	Definitions interface{}        `json:"definitions,omitempty"`
	Description string             `json:"description,omitempty"`
	Name        string             `json:"name,omitempty"`
	Type        string             `json:"type,omitempty"`
}

// GenAIUsageCacheCreationInfo is the prompt-cache write count.
//
// InputTokens is every token written to the cache. Ephemeral1hInputTokens is the subset of those
// written with a one-hour TTL, which Anthropic bills at twice the input rate against 1.25x for the
// default five-minute TTL. It is a breakdown, never a parallel count: like reasoning inside output,
// it is already inside InputTokens and must not be added to any total. The name mirrors Anthropic's
// own usage.cache_creation.ephemeral_1h_input_tokens. Only sources that report the split set it, so
// absent means "not reported", not "no one-hour writes". Build it with NewCacheCreationUsage so it
// cannot exceed InputTokens.
type GenAIUsageCacheCreationInfo struct {
	InputTokens            *int64 `json:"input_tokens,omitempty"`
	Ephemeral1hInputTokens *int64 `json:"ephemeral_1h_input_tokens,omitempty"`
}

// NewCacheCreationUsage builds a cache-creation block from a write count and, when the source
// reports it, the one-hour subset. The subset is clamped to [0, inputTokens]: a breakdown larger
// than the count it breaks down is a malformed record, not extra writes.
func NewCacheCreationUsage(inputTokens int64, ephemeral1h *int64) *GenAIUsageCacheCreationInfo {
	out := &GenAIUsageCacheCreationInfo{InputTokens: &inputTokens}
	if ephemeral1h != nil {
		v := clampCacheSubset(*ephemeral1h, inputTokens)
		out.Ephemeral1hInputTokens = &v
	}
	return out
}

// OneHourInputTokens is the one-hour subset clamped to the write count, and zero when the source
// did not report it. Readers use this rather than the raw field, so a log line written by
// something other than Beacon cannot claim more one-hour writes than writes.
func (c *GenAIUsageCacheCreationInfo) OneHourInputTokens() int64 {
	if c == nil || c.Ephemeral1hInputTokens == nil {
		return 0
	}
	var total int64
	if c.InputTokens != nil {
		total = *c.InputTokens
	}
	return clampCacheSubset(*c.Ephemeral1hInputTokens, total)
}

// Minus is what c adds over an already-counted snapshot prior of the same usage, for callers
// that difference repeated or cumulative records field by field. Both counts are differenced and
// floored at zero, and the one-hour subset stays clamped to the differenced write count, so a
// delta can never carry more one-hour writes than writes. A nil prior counts as nothing counted.
func (c *GenAIUsageCacheCreationInfo) Minus(prior *GenAIUsageCacheCreationInfo) *GenAIUsageCacheCreationInfo {
	if c == nil {
		return nil
	}
	if prior == nil {
		prior = &GenAIUsageCacheCreationInfo{}
	}
	sub := func(next, counted *int64) *int64 {
		if next == nil {
			return nil
		}
		v := *next
		if counted != nil {
			v -= *counted
		}
		if v < 0 {
			v = 0
		}
		return &v
	}
	out := &GenAIUsageCacheCreationInfo{InputTokens: sub(c.InputTokens, prior.InputTokens)}
	if oneHour := sub(c.Ephemeral1hInputTokens, prior.Ephemeral1hInputTokens); oneHour != nil {
		var total int64
		if out.InputTokens != nil {
			total = *out.InputTokens
		}
		v := clampCacheSubset(*oneHour, total)
		out.Ephemeral1hInputTokens = &v
	}
	return out
}

func clampCacheSubset(subset, total int64) int64 {
	switch {
	case subset < 0 || total < 0:
		return 0
	case subset > total:
		return total
	}
	return subset
}

type GenAIUsageCacheReadInfo struct {
	InputTokens *int64 `json:"input_tokens,omitempty"`
}

type GenAIUsageReasoningInfo struct {
	OutputTokens *int64 `json:"output_tokens,omitempty"`
}

// GenAIContextInfo records how full the model's context was, which is a level rather than an
// amount and therefore does not belong in GenAIUsageInfo.
//
// Everything in gen_ai.usage is additive: a report sums it across events to answer "what did this
// session spend". Context size is the opposite -- it is a measurement at one moment, and summing it
// answers nothing. Qwen Code is the case that forced the distinction: its Stop hook reports the
// prompt token count for the turn, which in a multi-turn session already contains every prior turn,
// so adding those up inflates a session's total by roughly the square of its length. The number is
// exact and useful; it just is not spend.
//
// Keeping it in its own block means a consumer cannot reach it by accident. A rule or dashboard
// that sums gen_ai.usage still gets only additive fields, and one that wants context utilization
// asks for it by name.
//
// UsedTokens is how much of the window the request occupied. LimitTokens is the window the runtime
// reported for that call, which is better than a local model table when present because it reflects
// the tier actually in force. Neither has an OpenTelemetry GenAI semconv equivalent.
type GenAIContextInfo struct {
	UsedTokens  *int64 `json:"used_tokens,omitempty"`
	LimitTokens *int64 `json:"limit_tokens,omitempty"`
}

// GenAIUsageInfo mirrors the OpenTelemetry GenAI semconv usage attribute
// names. Token counts are int64 to match OTLP integer values. CostUSD has no
// semconv equivalent; it carries runtime-reported USD cost only (for example
// Claude Code's cost metric) and is never derived from local pricing tables.
type GenAIUsageInfo struct {
	CacheCreation *GenAIUsageCacheCreationInfo `json:"cache_creation,omitempty"`
	CacheRead     *GenAIUsageCacheReadInfo     `json:"cache_read,omitempty"`
	CostUSD       *float64                     `json:"cost_usd,omitempty"`
	InputTokens   *int64                       `json:"input_tokens,omitempty"`
	OutputTokens  *int64                       `json:"output_tokens,omitempty"`
	Reasoning     *GenAIUsageReasoningInfo     `json:"reasoning,omitempty"`
}

type GenAIWorkflowInfo struct {
	Name string `json:"name,omitempty"`
}

type GenAIInfo struct {
	Agent              *GenAIAgentInfo        `json:"agent,omitempty"`
	Context            *GenAIContextInfo      `json:"context,omitempty"`
	Conversation       *GenAIConversationInfo `json:"conversation,omitempty"`
	DataSource         *GenAIDataSourceInfo   `json:"data_source,omitempty"`
	Embeddings         *GenAIEmbeddingsInfo   `json:"embeddings,omitempty"`
	Evaluation         *GenAIEvaluationInfo   `json:"evaluation,omitempty"`
	Input              *GenAIInputInfo        `json:"input,omitempty"`
	Operation          *GenAIOperationInfo    `json:"operation,omitempty"`
	Output             *GenAIOutputInfo       `json:"output,omitempty"`
	Prompt             *GenAIPromptInfo       `json:"prompt,omitempty"`
	Provider           *GenAIProviderInfo     `json:"provider,omitempty"`
	Request            *GenAIRequestInfo      `json:"request,omitempty"`
	Response           *GenAIResponseInfo     `json:"response,omitempty"`
	Retrieval          *GenAIRetrievalInfo    `json:"retrieval,omitempty"`
	SystemInstructions interface{}            `json:"system_instructions,omitempty"`
	// SystemInstructionsText is SystemInstructions as plain text, for the threat-rules
	// engine only, for the same reason as GenAIToolCallInfo.ResultText: CEL cannot address
	// the interface{} semconv value. It is never written or read; the engine fills it on its
	// own copy of each event. See threatrules.SystemInstructionsText.
	SystemInstructionsText string             `json:"-" cel:"system_instructions_text"`
	Token                  *GenAITokenInfo    `json:"token,omitempty"`
	Tool                   *GenAIToolInfo     `json:"tool,omitempty"`
	Usage                  *GenAIUsageInfo    `json:"usage,omitempty"`
	Workflow               *GenAIWorkflowInfo `json:"workflow,omitempty"`
}

type DestinationInfo struct {
	Type   string `json:"type,omitempty"`
	Mode   string `json:"mode,omitempty"`
	Status string `json:"status,omitempty"`
}

// UserAgentInfo identifies the user agent (for browser-sourced events, the browser)
// that produced an event, in the OpenTelemetry and ECS `user_agent.*` shape. Name is
// what the agent claims to be, e.g. "Microsoft Edge", "Brave", or "Chromium", and
// Version is its version as reported (the browser extension sends the major version).
// It is metadata rather than content, so it survives metadata-only retention.
type UserAgentInfo struct {
	Name    string `json:"name,omitempty"`
	Version string `json:"version,omitempty"`
}

// VCSInfo is version-control context in the OpenTelemetry VCS semantic convention shape
// (vcs.ref.head.revision, vcs.ref.head.name, vcs.ref.head.type, vcs.repository.url.full).
// Attribution is Beacon's own and has no semconv equivalent: on a session.commit_linked event it
// records how the commit was matched to the session. Hook is Beacon's own too: on a
// git.hook_budget_exceeded event it records a git hook run that ran out of time. Everything here is
// metadata -- identifiers, names and counts, never file contents or commit messages -- so it
// survives metadata-only retention.
type VCSInfo struct {
	Ref         *VCSRefInfo         `json:"ref,omitempty"`
	Repository  *VCSRepositoryInfo  `json:"repository,omitempty"`
	Attribution *VCSAttributionInfo `json:"attribution,omitempty"`
	Hook        *VCSHookInfo        `json:"hook,omitempty"`
}

type VCSRefInfo struct {
	Head *VCSRefHeadInfo `json:"head,omitempty"`
}

type VCSRefHeadInfo struct {
	// Revision is the commit id.
	Revision string `json:"revision,omitempty"`
	// Name is the branch the commit was made on; empty on a detached HEAD.
	Name string `json:"name,omitempty"`
	// Type is "branch" when Name is set.
	Type string `json:"type,omitempty"`
}

type VCSRepositoryInfo struct {
	URL *VCSRepositoryURLInfo `json:"url,omitempty"`
}

type VCSRepositoryURLInfo struct {
	// Full is the remote's URL with any credentials removed.
	Full string `json:"full,omitempty"`
}

// VCSAttributionInfo records how a commit was matched to a session. Method names the rule
// (file_overlap: the session wrote files the commit changes); ChangedFiles is how many files the
// commit changes and MatchedFiles how many of those the session wrote.
type VCSAttributionInfo struct {
	Method       string `json:"method,omitempty"`
	ChangedFiles int    `json:"changed_files,omitempty"`
	MatchedFiles int    `json:"matched_files,omitempty"`
}

// VCSHookInfo is one run of a Beacon git hook that ran past its time budget. Name is the hook
// (post-commit, post-rewrite, pre-push) and Phase the step it was in when its time ran out.
// ElapsedMS is the whole run, PhaseElapsedMS the part of it spent in Phase, and GitSpawns how many
// git processes the run started. CutShort is true when running out of time left the hook's work
// undone (for post-commit, a commit left unlinked or a link event unrecorded); false means the
// work finished, late.
type VCSHookInfo struct {
	Name           string `json:"name,omitempty"`
	Phase          string `json:"phase,omitempty"`
	BudgetMS       int64  `json:"budget_ms,omitempty"`
	ElapsedMS      int64  `json:"elapsed_ms,omitempty"`
	PhaseElapsedMS int64  `json:"phase_elapsed_ms,omitempty"`
	GitSpawns      int64  `json:"git_spawns,omitempty"`
	CutShort       bool   `json:"cut_short,omitempty"`
}

type HealthInfo struct {
	Component string `json:"component,omitempty"`
	Status    string `json:"status,omitempty"`
	Reason    string `json:"reason,omitempty"`
}

type ServerInfo struct {
	Address string `json:"address,omitempty"`
	Port    *int   `json:"port,omitempty"`
}

type Event struct {
	Timestamp string `json:"timestamp"`
	// Sequence is the emitting writer's monotonic emission counter for this event,
	// starting at 1; 0 means unsequenced. It breaks ties between events that share a
	// timestamp -- routine while stamping was second-resolution, and still possible
	// afterwards because one metric export flushes a batch of datapoints that all carry
	// the same collection instant.
	//
	// It orders one writer's stream, not the log as a whole: the hook adapter runs as a
	// fresh short-lived process per hook and the collector runs as one long-lived export
	// loop, so neither can see the other's counter. Timestamp is the cross-writer
	// ordering key and Sequence is the tiebreaker beneath it -- see
	// threatrules.SortEvents, which is how correlation gets its ordered input.
	Sequence      uint64                 `json:"sequence,omitempty"`
	Vendor        string                 `json:"vendor"`
	Product       string                 `json:"product"`
	SchemaVersion string                 `json:"schema_version"`
	Event         EventInfo              `json:"event"`
	Severity      Severity               `json:"severity"`
	Endpoint      EndpointInfo           `json:"endpoint"`
	User          UserInfo               `json:"user,omitempty"`
	Harness       HarnessInfo            `json:"harness"`
	Origin        Origin                 `json:"origin,omitempty"`
	Error         *ErrorInfo             `json:"error,omitempty"`
	Run           *RunInfo               `json:"run,omitempty"`
	Session       *SessionInfo           `json:"session,omitempty"`
	Handoff       *HandoffInfo           `json:"handoff,omitempty"`
	Share         *ShareInfo             `json:"share,omitempty"`
	Trace         *TraceInfo             `json:"trace,omitempty"`
	JSONRPC       *JSONRPCInfo           `json:"jsonrpc,omitempty"`
	Network       *NetworkInfo           `json:"network,omitempty"`
	RPC           *RPCInfo               `json:"rpc,omitempty"`
	Server        *ServerInfo            `json:"server,omitempty"`
	Tool          *ToolInfo              `json:"tool,omitempty"`
	File          *FileInfo              `json:"file,omitempty"`
	Command       *CommandInfo           `json:"command,omitempty"`
	MCP           *MCPInfo               `json:"mcp,omitempty"`
	Approval      *ApprovalInfo          `json:"approval,omitempty"`
	Policy        *PolicyInfo            `json:"policy,omitempty"`
	Prompt        *PromptInfo            `json:"prompt,omitempty"`
	Turn          *TurnInfo              `json:"turn,omitempty"`
	SystemContext *SystemContextInfo     `json:"system_context,omitempty"`
	Content       *ContentInfo           `json:"content,omitempty"`
	Destination   *DestinationInfo       `json:"destination,omitempty"`
	Health        *HealthInfo            `json:"health,omitempty"`
	UserAgent     *UserAgentInfo         `json:"user_agent,omitempty"`
	VCS           *VCSInfo               `json:"vcs,omitempty"`
	GenAI         *GenAIInfo             `json:"gen_ai,omitempty"`
	Model         string                 `json:"model,omitempty"`
	Repository    string                 `json:"repository,omitempty"`
	Branch        string                 `json:"branch,omitempty"`
	Message       string                 `json:"message,omitempty"`
	Raw           map[string]interface{} `json:"raw,omitempty"`
	Truncated     bool                   `json:"field_truncated,omitempty"`
}

type NewEventOptions struct {
	Action       string
	Category     string
	Severity     Severity
	Harness      HarnessInfo
	AgentVersion string
	Message      string
	Origin       Origin
	Run          *RunInfo
	// Fidelity is optional and defaults to empty rather than to FidelityObserved. A caller that
	// knows how it derived Action says so; one that has not been taught to think about it stays
	// silent instead of claiming the stronger of the two values by accident.
	Fidelity string
}

func NewEvent(opts NewEventOptions) Event {
	hostname, _ := os.Hostname()
	userName := os.Getenv("USER")
	if userName == "" {
		userName = os.Getenv("USERNAME")
	}
	severity := opts.Severity
	if severity == "" {
		severity = SeverityInfo
	}
	return Event{
		Timestamp:     FormatTimestamp(time.Now()),
		Vendor:        Vendor,
		Product:       Product,
		SchemaVersion: SchemaVersion,
		Event: EventInfo{
			Kind:     "agent_runtime",
			Action:   opts.Action,
			Category: opts.Category,
			Fidelity: opts.Fidelity,
		},
		Severity: severity,
		Endpoint: EndpointInfo{
			Hostname:     hostname,
			OS:           runtime.GOOS,
			AgentVersion: opts.AgentVersion,
		},
		User: UserInfo{
			Name: userName,
			UID:  os.Getenv("UID"),
		},
		Harness: opts.Harness,
		Origin:  opts.Origin,
		Run:     opts.Run,
		Message: opts.Message,
	}
}

func (e Event) Validate() error {
	if e.Vendor != Vendor {
		return errors.New("vendor must be beacon")
	}
	if e.Product != Product {
		return errors.New("product must be endpoint-agent")
	}
	if e.SchemaVersion == "" {
		return errors.New("schema_version is required")
	}
	if e.Event.Kind == "" || e.Event.Action == "" {
		return errors.New("event.kind and event.action are required")
	}
	if e.Severity == "" {
		return errors.New("severity is required")
	}
	if e.Endpoint.OS == "" {
		return errors.New("endpoint.os is required")
	}
	if e.Harness.Name == "" {
		return errors.New("harness.name is required")
	}
	if e.Origin != "" {
		switch e.Origin {
		case OriginLocal, OriginCloud, OriginCI:
		default:
			return errors.New("origin must be local, cloud, or ci")
		}
	}
	if e.Event.Fidelity != "" && !ValidFidelity(e.Event.Fidelity) {
		return errors.New("event.fidelity must be observed or inferred")
	}
	if e.Harness.CollectionMethod != "" && !ValidCollectionMethod(e.Harness.CollectionMethod) {
		return errors.New("harness.collection_method must be hook, otlp, plugin, poll, or gateway")
	}
	if e.Content != nil && e.Content.Retention != "" {
		switch e.Content.Retention {
		case ContentRetentionMetadata, ContentRetentionRedacted, ContentRetentionFull:
		default:
			return errors.New("content.retention must be metadata, redacted, or full")
		}
	}
	return nil
}