The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(schema): record how each event was collected and how sure we are of it
Claudee01548418283
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1b95d32c..d7f82dbd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -353,6 +353,7 @@ Use these npm trusted publisher values:- For macOS-only behavior, gate tests with `runtime.GOOS == "darwin"` or assert the non-Darwin contract explicitly.- Keep endpoint event schema fields stable: `vendor`, `product`, `schema_version`, required event fields, and Wazuh-compatible JSONL output are release contracts.- Preserve optional event fields for agent-native metadata (`session`, `trace`, `tool`, `file`, `command`, `mcp`, `approval`, `content`, `model`, `repository`, and `branch`) without changing existing required field semantics.+- Set the provenance markers on every new collection path. `harness.collection_method` (`hook`, `otlp`, `plugin`, `poll`) records the mechanism; `event.fidelity` (`observed`, `inferred`) records whether the source named the action or Beacon derived it. Both are defined in `pkg/asymptoteobserve/provenance.go` and are the only sanctioned way to express that difference — do not add per-runtime confidence fields, and do not leave a derived action unmarked. A new plugin-shaped runtime must be added to `CollectionMethodForPlatform`, whose default is `hook`. An action synthesized from an adjacent observation, such as an approval built from a pre-tool notification on a runtime with no approval hook, is `inferred`.- Keep `gen_ai.usage` as the single canonical token-usage representation: normalize all runtime token telemetry (span attributes, metric datapoints, legacy `llm.usage.*` aliases) into it, mirror OTel GenAI semconv JSON names exactly, and never add parallel or per-harness token fields. `gen_ai.usage.cost_usd` carries runtime-reported cost only; do not derive cost from local pricing tables.- When adding a new signal, include stable identifiers/counts/hashes alongside any retained raw content, and route raw fields through redaction, sanitization, truncation, and event-size controls.- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex e940bfce..44167be6 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -15,11 +15,29 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/cloudshuttle""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/git""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")var runInventoryHeartbeatCommand = exec.CommandContextfunc emitHookEvent(logger *logging.Logger, action, category, severity, message string, input map[string]interface{}, fields map[string]interface{}) {+ emitHookEventWithFidelity(logger, action, category, severity, message, asymptoteobserve.FidelityObserved, input, fields)+}++// emitInferredHookEvent is emitHookEvent for an action Beacon derived rather than read.+//+// The case that requires it: several runtimes expose a pre-tool notification but no approval hook,+// and Beacon has long turned the former into an approval.allowed event carrying+// approval.required=true. Nothing was gated -- a tool call was observed -- so recording that as a+// reported approval overstates what is known, and it is indistinguishable from Claude Code's+// PermissionRequest, which is a real operator decision. Marking it inferred leaves the action+// where downstream rules expect it while letting anything that counts approvals exclude the ones+// Beacon made up.+func emitInferredHookEvent(logger *logging.Logger, action, category, severity, message string, input map[string]interface{}, fields map[string]interface{}) {+ emitHookEventWithFidelity(logger, action, category, severity, message, asymptoteobserve.FidelityInferred, input, fields)+}++func emitHookEventWithFidelity(logger *logging.Logger, action, category, severity, message, fidelity string, input map[string]interface{}, fields map[string]interface{}) {if fields == nil {fields = map[string]interface{}{}}@@ -47,7 +65,7 @@ func emitHookEvent(logger *logging.Logger, action, category, severity, message sif branch := resolveBranch(input, cwd); branch != "" {fields["branch"] = branch}- if err := logger.EndpointEvent(action, category, severity, message, fields); err != nil {+ if err := logger.EndpointEventWithFidelity(action, category, severity, message, fidelity, fields); err != nil {logger.Error("Failed to write endpoint event", "error", err.Error(), "action", action)}}diff --git a/cli/beacon-hooks/cmd/permission_request.go b/cli/beacon-hooks/cmd/permission_request.goindex 53753193..22c22c5e 100644--- a/cli/beacon-hooks/cmd/permission_request.go+++ b/cli/beacon-hooks/cmd/permission_request.go@@ -4,6 +4,7 @@ import ("github.com/spf13/cobra""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract")@@ -40,7 +41,7 @@ func runPermissionRequest(cmd *cobra.Command, args []string) {}if isDevinLikePlatform(platformFlag) {- emitPreToolDecision(logger, input, sessionID, "approval.allowed", "approve", "Permission request approved")+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "approve", "Permission request approved", asymptoteobserve.FidelityObserved)outputJSON(devinApproveResponse)return}@@ -50,7 +51,7 @@ func runPermissionRequest(cmd *cobra.Command, args []string) {return}- emitPreToolDecision(logger, input, sessionID, "approval.requested", "requested", "Permission request observed")+ emitPreToolDecision(logger, input, sessionID, "approval.requested", "requested", "Permission request observed", asymptoteobserve.FidelityObserved)outputJSON(emptyResponse)}diff --git a/cli/beacon-hooks/cmd/policy.go b/cli/beacon-hooks/cmd/policy.goindex ae10a056..93396184 100644--- a/cli/beacon-hooks/cmd/policy.go+++ b/cli/beacon-hooks/cmd/policy.go@@ -109,7 +109,14 @@ func (c policyCandidate) event() asymptoteobserve.Event {"action": c.action,"category": c.category,},- "harness": map[string]interface{}{"name": platformFlag},+ "harness": map[string]interface{}{+ "name": platformFlag,+ // The contract promises the provider the same field names it would match in the+ // runtime JSONL, so the provenance marker belongs here too. No fidelity counterpart:+ // this event describes a tool call that has not happened yet, so there is no+ // observation for the action to be faithful to.+ "collection_method": asymptoteobserve.CollectionMethodForPlatform(platformFlag),+ },}for key, value := range c.fields {envelope[key] = valuediff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex 7e0442c4..38c745e4 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -11,6 +11,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract")@@ -52,7 +53,7 @@ func runPreTool(cmd *cobra.Command, args []string) {} else if platformFlag == "claude" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" {emitPreToolObserved(logger, input, sessionID)} else {- emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed")+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed", asymptoteobserve.FidelityInferred)}outputJSON(preToolResponse())}@@ -68,7 +69,7 @@ func emitCursorPreHook(logger *logging.Logger, input map[string]interface{}, ses"decision": "allow","reason": "Shell execution observed",}- emitHookEvent(logger, "approval.allowed", "approval", "info", "Shell execution observed", input, fields)+ emitInferredHookEvent(logger, "approval.allowed", "approval", "info", "Shell execution observed", input, fields)return truecase "beforeReadFile":fields := sessionFields(sessionID, input)@@ -82,12 +83,19 @@ func emitCursorPreHook(logger *logging.Logger, input map[string]interface{}, sesemitHookEvent(logger, "file.read", "file", "info", "File read observed", input, fields)return truedefault:- emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed")+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed", asymptoteobserve.FidelityInferred)return true}}-func emitPreToolDecision(logger *logging.Logger, input map[string]interface{}, sessionID, action, decision, reason string) {+// emitPreToolDecision writes an approval-category event for a tool call.+//+// fidelity is a required parameter rather than a constant inside because this one function serves+// both kinds of caller, and the difference between them is the whole point of the field. The+// permission-request hook reaches it when a runtime genuinely asked for a decision; the pre-tool+// hook reaches it on runtimes that expose no approval gate at all, where the approval block below+// describes what Beacon concluded from seeing a tool call rather than anything an operator did.+func emitPreToolDecision(logger *logging.Logger, input map[string]interface{}, sessionID, action, decision, reason, fidelity string) {toolName := getFirstStr(input, "tool_name", "toolName")toolInput := resolveToolInput(input)fields := sessionFields(sessionID, input)@@ -99,7 +107,7 @@ func emitPreToolDecision(logger *logging.Logger, input map[string]interface{}, s"decision": decision,"reason": reason,}- emitHookEvent(logger, action, "approval", "info", reason, input, fields)+ emitHookEventWithFidelity(logger, action, "approval", "info", reason, fidelity, input, fields)}func preToolResponse() map[string]interface{} {diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex 51602071..83503984 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -1049,3 +1049,111 @@ func endpointEvents(t *testing.T, path string) []map[string]interface{} {}return events}++// --- provenance: which approval events are real ---++func eventFidelity(t *testing.T, event map[string]interface{}) string {+ t.Helper()+ block, ok := event["event"].(map[string]interface{})+ if !ok {+ t.Fatalf("event has no event block: %#v", event)+ }+ fidelity, _ := block["fidelity"].(string)+ return fidelity+}++// Cursor exposes no approval hook. Beacon has always turned its pre-tool notification into an+// approval.allowed carrying approval.required=true, which is not an approval anybody granted --+// it is a tool call that was seen. The action is left alone here so existing rules keep matching;+// what changes is that the event now says it was Beacon's reading rather than Cursor's report.+func TestRunPreToolMarksSynthesizedCursorApprovalInferred(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "cursor"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPreTool, map[string]interface{}{+ "conversation_id": "conv-inferred",+ "hook_event_name": "preToolUse",+ "tool_name": "Write",+ })++ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action != "approval.allowed" {+ t.Fatalf("event.action = %q, want the unchanged approval.allowed", action)+ }+ if got := eventFidelity(t, event); got != "inferred" {+ t.Fatalf("event.fidelity = %q, want inferred for a synthesized approval", got)+ }+}++// beforeShellExecution is the same synthesis on a different Cursor hook: every shell command+// becomes an approval.allowed whether or not anything gated it.+func TestRunPreToolMarksCursorShellApprovalInferred(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "cursor"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPreTool, map[string]interface{}{+ "conversation_id": "conv-shell-inferred",+ "hook_event_name": "beforeShellExecution",+ "command": "npm test",+ })++ event := lastEndpointEvent(t, logPath)+ if got := eventFidelity(t, event); got != "inferred" {+ t.Fatalf("event.fidelity = %q, want inferred for a synthesized shell approval", got)+ }+}++// The counterpart, and the reason emitPreToolDecision takes fidelity as a parameter rather than+// hardcoding it: the permission-request hook fires because a runtime genuinely asked for a+// decision, so its approval events must stay observed. Marking this path inferred alongside the+// pre-tool one would delete the distinction the field exists to record.+func TestRunPermissionRequestKeepsRealApprovalObserved(t *testing.T) {+ for _, platform := range []string{"devin", "claude"} {+ t.Run(platform, func(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = platform+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPermissionRequest, map[string]interface{}{+ "session_id": "conv-permission",+ "tool_name": "Bash",+ })++ event := lastEndpointEvent(t, logPath)+ action, _ := event["event"].(map[string]interface{})["action"].(string)+ if !strings.HasPrefix(action, "approval.") {+ t.Fatalf("event.action = %q, want an approval event", action)+ }+ if got := eventFidelity(t, event); got != "observed" {+ t.Fatalf("event.fidelity = %q, want observed for a real permission request", got)+ }+ })+ }+}++// Ordinary telemetry is unaffected: a hook that fires for a named lifecycle event reports an+// action the runtime gave it, so nothing about this change should make normal events look+// uncertain.+func TestRunPostToolKeepsObservedFidelity(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "cursor"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "conversation_id": "conv-post",+ "hook_event_name": "afterShellExecution",+ "command": "go test ./...",+ "exit_code": float64(0),+ })++ event := lastEndpointEvent(t, logPath)+ if got := eventFidelity(t, event); got != "observed" {+ t.Fatalf("event.fidelity = %q, want observed for a reported hook event", got)+ }+}diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_test.goindex ab9c747b..9cd30574 100644--- a/cli/beacon-hooks/internal/logging/endpoint_event_test.go+++ b/cli/beacon-hooks/internal/logging/endpoint_event_test.go@@ -229,3 +229,141 @@ func TestEndpointEventSurfacesWriteFailure(t *testing.T) {t.Fatal("EndpointEvent returned nil, want write failure")}}++// --- provenance: harness.collection_method and event.fidelity ---++func decodeSingleEndpointEvent(t *testing.T, path string) map[string]interface{} {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read endpoint log: %v", err)+ }+ lines := strings.Split(strings.TrimSpace(string(data)), "\n")+ if len(lines) != 1 {+ t.Fatalf("endpoint log has %d lines, want 1", len(lines))+ }+ var event map[string]interface{}+ if err := json.Unmarshal([]byte(lines[0]), &event); err != nil {+ t.Fatalf("unmarshal endpoint event: %v", err)+ }+ return event+}++func nestedString(t *testing.T, event map[string]interface{}, block, key string) (string, bool) {+ t.Helper()+ inner, ok := event[block].(map[string]interface{})+ if !ok {+ t.Fatalf("event has no %q block: %#v", block, event)+ }+ value, present := inner[key]+ if !present {+ return "", false+ }+ text, ok := value.(string)+ if !ok {+ t.Fatalf("%s.%s = %#v, want a string", block, key, value)+ }+ return text, true+}++func TestEndpointEventRecordsHookCollectionMethod(t *testing.T) {+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("pre-tool", "cursor")+ if err := logger.EndpointEvent("file.modified", "file", "info", "File edit observed", nil); err != nil {+ t.Fatalf("EndpointEvent returned error: %v", err)+ }++ event := decodeSingleEndpointEvent(t, logPath)+ if method, ok := nestedString(t, event, "harness", "collection_method"); !ok || method != "hook" {+ t.Fatalf("harness.collection_method = %q (present=%v), want hook", method, ok)+ }+}++// One plugin platform, because the plugin case is the one a future integration gets wrong: the+// default is hook, so a plugin-shaped runtime that is not enumerated silently reports the wrong+// method.+func TestEndpointEventRecordsPluginCollectionMethod(t *testing.T) {+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("cline-event", "cline")+ if err := logger.EndpointEvent("prompt.submitted", "prompt", "info", "Prompt observed", nil); err != nil {+ t.Fatalf("EndpointEvent returned error: %v", err)+ }++ event := decodeSingleEndpointEvent(t, logPath)+ if method, ok := nestedString(t, event, "harness", "collection_method"); !ok || method != "plugin" {+ t.Fatalf("harness.collection_method = %q (present=%v), want plugin", method, ok)+ }+}++// This path builds raw maps rather than the shared Event struct, so it gets no `omitempty` for+// free. An empty string written into either field is worse than an absent one: a consumer would+// have to treat "" as a third case.+func TestEndpointEventOmitsProvenanceRatherThanWritingEmpty(t *testing.T) {+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("pre-tool", "")+ if err := logger.EndpointEventWithFidelity("tool.invoked", "tool", "info", "no platform", "", nil); err != nil {+ t.Fatalf("EndpointEventWithFidelity returned error: %v", err)+ }++ event := decodeSingleEndpointEvent(t, logPath)+ if _, present := nestedString(t, event, "harness", "collection_method"); present {+ t.Fatal("harness.collection_method written for an empty platform, want the key omitted")+ }+ if _, present := nestedString(t, event, "event", "fidelity"); present {+ t.Fatal("event.fidelity written when unset, want the key omitted")+ }+}++// EndpointEvent is the ordinary path and means "the runtime named this action", so it must not+// require every existing caller to opt in to being trusted.+func TestEndpointEventDefaultsToObservedFidelity(t *testing.T) {+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("post-tool", "claude")+ if err := logger.EndpointEvent("command.executed", "command", "info", "Command observed", nil); err != nil {+ t.Fatalf("EndpointEvent returned error: %v", err)+ }++ event := decodeSingleEndpointEvent(t, logPath)+ if fidelity, ok := nestedString(t, event, "event", "fidelity"); !ok || fidelity != "observed" {+ t.Fatalf("event.fidelity = %q (present=%v), want observed", fidelity, ok)+ }+}++func TestEndpointEventCarriesExplicitInferredFidelity(t *testing.T) {+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("pre-tool", "cursor")+ if err := logger.EndpointEventWithFidelity("approval.allowed", "approval", "info", "Pre-tool observed", "inferred", nil); err != nil {+ t.Fatalf("EndpointEventWithFidelity returned error: %v", err)+ }++ event := decodeSingleEndpointEvent(t, logPath)+ if fidelity, ok := nestedString(t, event, "event", "fidelity"); !ok || fidelity != "inferred" {+ t.Fatalf("event.fidelity = %q (present=%v), want inferred", fidelity, ok)+ }+}++// The size-limit fallback rewrites the event down to a key allowlist. Both provenance fields live+// inside blocks that survive wholesale, but a future edit to that list could drop them -- and+// losing the marker silently turns an inferred event into an unmarked one, which reads as trusted.+func TestMinimalEndpointEventKeepsProvenance(t *testing.T) {+ minimal := minimalEndpointEvent(map[string]interface{}{+ "event": map[string]interface{}{"action": "approval.allowed", "fidelity": "inferred"},+ "harness": map[string]interface{}{"name": "cursor", "collection_method": "hook"},+ })+ if fidelity, ok := nestedString(t, minimal, "event", "fidelity"); !ok || fidelity != "inferred" {+ t.Fatalf("compacted event.fidelity = %q (present=%v), want inferred", fidelity, ok)+ }+ if method, ok := nestedString(t, minimal, "harness", "collection_method"); !ok || method != "hook" {+ t.Fatalf("compacted harness.collection_method = %q (present=%v), want hook", method, ok)+ }+}diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex ff018796..cb1db2bb 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -95,7 +95,19 @@ func (l *Logger) write(entry map[string]interface{}) {}}+// EndpointEvent writes an event whose action the runtime named for us, which is the normal case+// on this path: a hook or plugin fires for a specific lifecycle event and the action follows from+// which one. Callers that instead derive an action from an adjacent observation must use+// EndpointEventWithFidelity and say so.func (l *Logger) EndpointEvent(action, category, severity, message string, fields map[string]interface{}) error {+ return l.EndpointEventWithFidelity(action, category, severity, message, asymptoteobserve.FidelityObserved, fields)+}++// EndpointEventWithFidelity is EndpointEvent with an explicit event.fidelity. It exists for the+// handful of hook paths that report an action the payload did not contain -- synthesizing an+// approval from a pre-tool notification, for instance -- so those events are distinguishable from+// the ones a runtime actually reported.+func (l *Logger) EndpointEventWithFidelity(action, category, severity, message, fidelity string, fields map[string]interface{}) error {path := endpointLogPath()if path == "" {return nil@@ -103,7 +115,7 @@ func (l *Logger) EndpointEvent(action, category, severity, message string, fieldif severity == "" {severity = "info"}- event := l.baseEndpointEvent(action, category, severity, message)+ event := l.baseEndpointEvent(action, category, severity, message, fidelity)for key, value := range fields {if value == nil {continue@@ -117,7 +129,7 @@ func (l *Logger) EndpointEvent(action, category, severity, message string, fieldreturn nil}-func (l *Logger) baseEndpointEvent(action, category, severity, message string) map[string]interface{} {+func (l *Logger) baseEndpointEvent(action, category, severity, message, fidelity string) map[string]interface{} {hostname, _ := os.Hostname()user := map[string]interface{}{"name": os.Getenv("USER"),@@ -125,30 +137,45 @@ func (l *Logger) baseEndpointEvent(action, category, severity, message string) mif uid := firstEnv("BEACON_CLOUD_USER_ID_HASH", "BEACON_CLOUD_USER_ID"); uid != "" {user["uid"] = uid}+ // Both blocks are assembled before the event literal so the provenance keys can be omitted+ // rather than written empty. This path builds raw maps instead of the shared Event struct, so+ // it does not get `omitempty` for free, and an empty "collection_method" on every event would+ // be both noise in the log and a value a consumer could mistake for a real one.+ eventBlock := map[string]interface{}{+ "kind": "agent_runtime",+ "action": action,+ "category": category,+ }+ if fidelity != "" {+ eventBlock["fidelity"] = fidelity+ }+ harnessBlock := map[string]interface{}{+ // Normalized rather than written raw. The OTLP path already reports the canonical name+ // for the same session, so emitting the raw --platform value here recorded one session+ // under two names -- splitting it for any query or SIEM detection that groups by+ // harness.name. The flag itself is unchanged, so existing installs are fixed without+ // having their settings.json rewritten.+ "name": asymptoteobserve.NormalizeHarnessName(l.platform),+ }+ // Derived from --platform rather than from the normalized name above, because the flag is what+ // records which integration shape is installed. The two differ for VS Code, whose hook and+ // OTLP telemetry share a harness name.+ if method := asymptoteobserve.CollectionMethodForPlatform(l.platform); method != "" {+ harnessBlock["collection_method"] = method+ }event := map[string]interface{}{"timestamp": time.Now().UTC().Format(time.RFC3339),"vendor": "beacon","product": "endpoint-agent","schema_version": "1.0",- "event": map[string]interface{}{- "kind": "agent_runtime",- "action": action,- "category": category,- },- "severity": severity,+ "event": eventBlock,+ "severity": severity,"endpoint": map[string]interface{}{"hostname": hostname,"os": runtime.GOOS,},- "user": user,- "harness": map[string]interface{}{- // Normalized rather than written raw. The OTLP path already reports the canonical name- // for the same session, so emitting the raw --platform value here recorded one session- // under two names -- splitting it for any query or SIEM detection that groups by- // harness.name. The flag itself is unchanged, so existing installs are fixed without- // having their settings.json rewritten.- "name": asymptoteobserve.NormalizeHarnessName(l.platform),- },+ "user": user,+ "harness": harnessBlock,"message": asymptoteobserve.CleanString(message, asymptoteobserve.DefaultStringLimit, true),}if origin := firstEnv("BEACON_ORIGIN"); origin != "" {diff --git a/cli/beacon/internal/devincloud/mapper.go b/cli/beacon/internal/devincloud/mapper.goindex 497490cc..6f0b00c3 100644--- a/cli/beacon/internal/devincloud/mapper.go+++ b/cli/beacon/internal/devincloud/mapper.go@@ -154,8 +154,11 @@ func baseEvent(s Session, action, category string, severity schema.Severity, tsUAction: action,Category: category,Severity: severity,- Harness: schema.HarnessInfo{Name: Harness},- Origin: schema.OriginCloud,+ // Poll, not hook: the Devin sessions API is read after the fact, so Beacon sees the+ // messages a run produced rather than observing the agent as it works. Recording that+ // here is what keeps a consumer from reading these events as endpoint-grade coverage.+ Harness: schema.HarnessInfo{Name: Harness, CollectionMethod: schema.CollectionMethodPoll},+ Origin: schema.OriginCloud,Run: &schema.RunInfo{Provider: Provider,RunID: s.SessionID,diff --git a/cli/beacon/internal/devincloud/mapper_test.go b/cli/beacon/internal/devincloud/mapper_test.goindex 8ca77ebf..80109fb2 100644--- a/cli/beacon/internal/devincloud/mapper_test.go+++ b/cli/beacon/internal/devincloud/mapper_test.go@@ -154,3 +154,24 @@ func TestObjectNameLayout(t *testing.T) {t.Fatalf("ObjectName empties = %q, want %q", got2, want2)}}++// Devin Cloud is the one collection path that is neither a hook nor an OTLP stream: Beacon polls+// the sessions API and maps whatever it returns after the run. Recording that on every event is+// what stops these from being read as endpoint-grade observation of the agent at work.+func TestMappedEventsRecordPollCollectionMethod(t *testing.T) {+ s := Session{SessionID: "sess-poll", Status: "finished", UserID: "user-1", CreatedAt: 1000, UpdatedAt: 1200}+ msgs := []Message{+ {EventID: "e1", Source: "user", Message: "do the thing", CreatedAt: 1000},+ {EventID: "e2", Source: "devin", Message: "done", CreatedAt: 1100},+ }++ mapped := MapSession(s, msgs)+ if len(mapped) == 0 {+ t.Fatal("MapSession produced no events")+ }+ for i, m := range mapped {+ if got := m.Event.Harness.CollectionMethod; got != "poll" {+ t.Fatalf("event %d (%s) collection_method = %q, want poll", i, m.Event.Event.Action, got)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/schema/event.go b/cli/beacon/internal/endpoint/schema/event.goindex 3f4217be..5dc10bf8 100644--- a/cli/beacon/internal/endpoint/schema/event.go+++ b/cli/beacon/internal/endpoint/schema/event.go@@ -20,6 +20,19 @@ const (type Origin = asymptoteobserve.Origin+// Provenance markers, re-exported so code in this module uses the same spellings as the hook+// adapter and the collector exporter rather than bare string literals. See+// pkg/asymptoteobserve/provenance.go for what each one means.+const (+ CollectionMethodHook = asymptoteobserve.CollectionMethodHook+ CollectionMethodOTLP = asymptoteobserve.CollectionMethodOTLP+ CollectionMethodPlugin = asymptoteobserve.CollectionMethodPlugin+ CollectionMethodPoll = asymptoteobserve.CollectionMethodPoll++ FidelityObserved = asymptoteobserve.FidelityObserved+ FidelityInferred = asymptoteobserve.FidelityInferred+)+const (OriginLocal = asymptoteobserve.OriginLocalOriginCloud = asymptoteobserve.OriginClouddiff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.goindex 1522b3d5..65a5d345 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go@@ -296,12 +296,16 @@ func (c Converter) EventFromLog(resourceAttrs map[string]interface{}, record ploattrs := MergeMaps(resourceAttrs, AttrsToMap(record.Attributes()))body := record.Body().AsString()ts := Timestamp(record.Timestamp().AsTime())+ // An action the record states outright is observed by definition; only the fallback has to+ // account for how it got there.action := FirstString(attrs, "beacon.event.action", "event.action", "gen_ai.agent.action", "ai.agent.action")+ fidelity := asymptoteobserve.FidelityObservedif action == "" {- action = InferAction(attrs, body)+ action, fidelity = InferActionWithFidelity(attrs, body)}message := FirstNonEmpty(body, FirstString(attrs, "message", "log.message", "event.name"))event := NewEvent(action, EventCategory(action, FirstString(attrs, "beacon.event.category", "event.category", "category")), Severity(record.SeverityText(), record.SeverityNumber().String()), HarnessName(attrs, message), ts)+ event.Event.Fidelity = fidelityevent.Message = messagec.PopulateCommon(&event, attrs)if !record.TraceID().IsEmpty() {@@ -322,11 +326,13 @@ func (c Converter) EventFromLog(resourceAttrs map[string]interface{}, record plofunc (c Converter) EventFromSpan(resourceAttrs map[string]interface{}, span ptrace.Span) Event {attrs := MergeMaps(resourceAttrs, AttrsToMap(span.Attributes()))action := FirstString(attrs, "beacon.event.action", "event.action", "gen_ai.agent.action", "ai.agent.action")+ fidelity := asymptoteobserve.FidelityObservedif action == "" {- action = InferAction(attrs, span.Name())+ action, fidelity = InferActionWithFidelity(attrs, span.Name())}message := FirstNonEmpty(FirstString(attrs, "message", "gen_ai.prompt", "gen_ai.response"), span.Name())event := NewEvent(action, EventCategory(action, FirstString(attrs, "beacon.event.category", "event.category", "tool")), SpanSeverity(span.Status().Code().String()), HarnessName(attrs, message, span.Name()), Timestamp(span.StartTimestamp().AsTime()))+ event.Event.Fidelity = fidelityevent.Message = messagec.PopulateCommon(&event, attrs)if !span.TraceID().IsEmpty() {@@ -363,7 +369,17 @@ func (c Converter) NormalizeCodexLogEvent(event *Event, attrs map[string]interfaif event == nil || event.Harness.Name != "codex_cli" {return}- switch CodexLogEventName(attrs) {+ name := CodexLogEventName(attrs)+ switch name {+ case CodexConversationStarts, CodexUserPrompt, CodexToolDecision, CodexToolResult:+ // Every arm below is selected by an exact match on Codex's own `event.name`, so whatever+ // InferAction guessed from the record body is superseded by something the source stated.+ // Without this upgrade Codex's best telemetry -- the events it names explicitly -- would+ // keep the fidelity of the guess that got overwritten. Names this switch does not know+ // fall through untouched and keep theirs, which is the correct answer for them.+ event.Event.Fidelity = asymptoteobserve.FidelityObserved+ }+ switch name {case CodexConversationStarts:event.Event.Action = "session.started"event.Event.Category = "session"@@ -443,24 +459,40 @@ func (c Converter) NormalizeClaudeLogEvent(event *Event, attrs map[string]interfpreserveAction := FirstString(attrs, "beacon.event.action", "event.action", "gen_ai.agent.action", "ai.agent.action") != ""preserveCategory := preserveAction || FirstString(attrs, "beacon.event.category", "event.category", "category") != ""+ originalFidelity := event.Event.Fidelity+eventName := ClaudeLogEventName(attrs, body)switch eventName {case ClaudeToolDecision:+ // A decision Claude Code reported, read out of its `decision` attribute.+ event.Event.Fidelity = asymptoteobserve.FidelityObservedNormalizeClaudeToolDecision(event, attrs)case ClaudeToolResult:+ event.Event.Fidelity = asymptoteobserve.FidelityObservedNormalizeClaudeToolResult(event, attrs)case "":returndefault:classification, ok := claudeLogEventClassifications[eventName]if !ok {+ // A `claude_code.*` event this build has never heard of. The name is real but its+ // meaning is not known here, and session.activity is a placeholder chosen so the+ // event is not dropped -- the one arm in this function that is a guess, and the+ // case that makes an unrecognized event distinguishable from a classified one+ // instead of both arriving as session.activity with nothing to tell them apart.classification = eventClassification{action: "session.activity", category: "session"}+ event.Event.Fidelity = asymptoteobserve.FidelityInferred+ } else {+ event.Event.Fidelity = asymptoteobserve.FidelityObserved}event.Event.Action = classification.actionevent.Event.Category = classification.category}if preserveAction {+ // The action came back from an explicit attribute, so its fidelity has to come back too;+ // otherwise the event would carry this function's verdict about an action it no longer has.event.Event.Action = originalAction+ event.Event.Fidelity = originalFidelity}if preserveCategory {event.Event.Category = originalCategory@@ -606,6 +638,9 @@ func (c Converter) EventFromMetric(resourceAttrs map[string]interface{}, metricaction = "metric.observed"}event := NewEvent(action, "metric", "info", HarnessName(attrs, metric.Name()), time.Now().UTC())+ // Observed on either path. A metric datapoint arriving is itself the fact being recorded, so+ // "metric.observed" restates the signal rather than guessing at what the agent did.+ event.Event.Fidelity = asymptoteobserve.FidelityObservedevent.Message = metric.Name()c.PopulateCommon(&event, attrs)event.Raw = c.RawPayload(attrs, map[string]interface{}{@@ -743,6 +778,9 @@ func (c Converter) usageEventFromDataPoint(resourceAttrs map[string]interface{},action = "cost.usage"}event := NewEvent(action, "metric", "info", HarnessName(attrs, metric.Name()), Timestamp(ts.AsTime()))+ // The metric name decides between the two actions, so this is a reading of a structured+ // identifier rather than of free text.+ event.Event.Fidelity = asymptoteobserve.FidelityObservedevent.Message = metric.Name()c.PopulateCommon(&event, attrs)// The datapoint value is the authoritative usage for this event. Drop any@@ -1631,7 +1669,36 @@ func NormalizeHarnessName(name string) string {return asymptoteobserve.NormalizeHarnessName(name)}+// InferAction derives an event action from OTLP attributes. It is retained for callers that only+// need the action; InferActionWithFidelity is the same logic and additionally reports how sure+// Beacon is of the answer.func InferAction(attrs map[string]interface{}, fallback string) string {+ action, _ := InferActionWithFidelity(attrs, fallback)+ return action+}++// InferActionWithFidelity derives an event action and classifies how it was derived.+//+// The classification rule is structural, not semantic: a branch keyed on an attribute whose value+// names the operation returns FidelityObserved, and a branch keyed on a substring of `text`+// returns FidelityInferred. `text` is the weak input -- it folds in `fallback`, which is the log+// record body or the span name, so free-form prose that happens to contain "file" or "exec"+// reaches those branches -- and the `default` arm below is the weakest of all, having matched+// nothing at all before landing on tool.invoked.+//+// Deliberately not a judgement about whether each mapping is semantically ideal. Some of the+// structured branches still take a step (`execute_hook` becoming approval.requested is a reading+// of what a hook execution means, not a restatement of it), and marking those inferred as well+// would make the field a running commentary on this function that no reviewer could check.+// "Did the source name the operation, or did Beacon pattern-match prose" is a question with one+// answer per branch, which is what makes it worth recording.+//+// The Gemini branches are the interesting case: GeminiToolAction and GeminiFileAction both key on+// structured attributes and would qualify as observed on their own, but they are *reached* by+// substring-matching an event name out of the same blob, so a body mentioning+// "gemini_cli.file_operation" arrives there too. Tightening the reach to an exact `event.name`+// comparison would promote them, and is a behavior change rather than a labeling one.+func InferActionWithFidelity(attrs map[string]interface{}, fallback string) (string, string) {tool := strings.ToLower(FirstString(attrs, "tool.name", "gen_ai.tool.name", "beacon.tool.name", "beacon.gen_ai.tool.name", "mcp.tool", "beacon.mcp.tool", "mcp.tool.name", "function_name", "tool_name"))operation := strings.ToLower(FirstString(attrs, "gen_ai.operation.name"))mcpMethod := strings.ToLower(FirstString(attrs, "mcp.method.name"))@@ -1644,41 +1711,43 @@ func InferAction(attrs map[string]interface{}, fallback string) string {mcpMethod,FirstString(attrs, "event.name", "codex.op", "rpc.method"),}, " "))+ observed := asymptoteobserve.FidelityObserved+ inferred := asymptoteobserve.FidelityInferredswitch {case harness == "copilot_cli" || harness == "vscode_copilot":- return CopilotAction(attrs, operation, text)+ return CopilotActionWithFidelity(attrs, operation, text)case mcpMethod == "tools/call":- return "mcp.tool_invoked"+ return "mcp.tool_invoked", observedcase mcpMethod == "resources/read" && IsFileURI(FirstString(attrs, "mcp.resource.uri")):- return "file.read"+ return "file.read", observedcase mcpServer != "" || FirstString(attrs, "mcp.tool", "beacon.mcp.tool", "mcp.tool.name") != "":- return "mcp.tool_invoked"+ return "mcp.tool_invoked", observedcase operation == "execute_tool":- return "tool.invoked"+ return "tool.invoked", observedcase (operation == "chat" || operation == "generate_content" || operation == "text_completion") && HasPromptLikeContent(attrs):- return "prompt.submitted"+ return "prompt.submitted", observedcase HasToolCall(attrs):- return "tool.invoked"+ return "tool.invoked", observedcase strings.Contains(text, "gemini_cli.user_prompt"):- return "prompt.submitted"+ return "prompt.submitted", inferredcase strings.Contains(text, "gemini_cli.tool_call"):- return GeminiToolAction(attrs)+ return GeminiToolAction(attrs), inferredcase strings.Contains(text, "gemini_cli.file_operation"):- return GeminiFileAction(attrs)+ return GeminiFileAction(attrs), inferredcase strings.Contains(text, "approval_mode_switch") || strings.Contains(text, "approval_mode_duration") || strings.Contains(text, "plan_execution"):- return "approval.requested"+ return "approval.requested", inferredcase strings.Contains(text, "prompt") || strings.Contains(text, "user_input"):- return "prompt.submitted"+ return "prompt.submitted", inferredcase strings.Contains(text, "mcp"):- return "mcp.tool_invoked"+ return "mcp.tool_invoked", inferredcase strings.Contains(text, "command") || strings.Contains(text, "shell") || strings.Contains(text, "exec"):- return "command.executed"+ return "command.executed", inferredcase strings.Contains(text, "file") || strings.Contains(text, "write") || strings.Contains(text, "edit"):- return "file.modified"+ return "file.modified", inferredcase strings.Contains(text, "approval"):- return "approval.requested"+ return "approval.requested", inferreddefault:- return "tool.invoked"+ return "tool.invoked", inferred}}@@ -1740,40 +1809,51 @@ func HasPromptLikeContent(attrs map[string]interface{}) bool {return len(LegacyMessages(attrs, "gen_ai.prompt.", "user")) > 0}+// CopilotAction is CopilotActionWithFidelity without the fidelity, kept for callers that only+// want the action.func CopilotAction(attrs map[string]interface{}, operation, text string) string {+ action, _ := CopilotActionWithFidelity(attrs, operation, text)+ return action+}++// CopilotActionWithFidelity classifies a Copilot event on the same structural rule as+// InferActionWithFidelity: exact `event.name` and `gen_ai.operation.name` comparisons are+// observed, the substring match and the catch-all are not.+func CopilotActionWithFidelity(attrs map[string]interface{}, operation, text string) (string, string) {+ observed := asymptoteobserve.FidelityObservedif eventName := FirstString(attrs, "event.name", "name"); eventName != "" {switch eventName {case "copilot_chat.session.start", "copilot_chat.cloud.session.invoke":- return "session.activity"+ return "session.activity", observedcase "copilot_chat.tool.call":if strings.EqualFold(FirstString(attrs, "success"), "false") || FirstString(attrs, "error.type") != "" {- return "tool.failed"+ return "tool.failed", observed}- return "tool.invoked"+ return "tool.invoked", observedcase "copilot_chat.edit.feedback", "copilot_chat.edit.hunk.action", "copilot_chat.inline.done":- return "file.modified"+ return "file.modified", observed}}switch {case operation == "invoke_agent" && FirstString(attrs, "copilot_chat.user_request") != "":- return "prompt.submitted"+ return "prompt.submitted", observedcase operation == "invoke_agent":- return "session.activity"+ return "session.activity", observedcase operation == "execute_hook":- return "approval.requested"+ return "approval.requested", observedcase operation == "chat":initiator := strings.ToLower(FirstString(attrs, "github.copilot.initiator"))turnID := FirstString(attrs, "github.copilot.turn_id")if initiator == "agent" || (turnID != "" && turnID != "0") {- return "session.activity"+ return "session.activity", observed}- return "prompt.submitted"+ return "prompt.submitted", observedcase operation == "execute_tool":- return "tool.invoked"+ return "tool.invoked", observedcase strings.Contains(text, "permission"):- return "approval.requested"+ return "approval.requested", asymptoteobserve.FidelityInferreddefault:- return "tool.invoked"+ return "tool.invoked", asymptoteobserve.FidelityInferred}}diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.goindex ec998d2f..18419355 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go@@ -12,6 +12,8 @@ import ("go.opentelemetry.io/collector/pdata/plog""go.opentelemetry.io/collector/pdata/pmetric""go.opentelemetry.io/collector/pdata/ptrace"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")// Guards against the exporter Event mirror struct drifting from the shared@@ -1259,3 +1261,189 @@ func TestClaudeShellToolsPopulateTheCommandDetectionSurface(t *testing.T) {})}}++// --- provenance: harness.collection_method and event.fidelity ---++// Everything this exporter emits arrived as OpenTelemetry, so the method is the same on all three+// signals. Asserting it per signal rather than once is what would catch a future construction path+// that bypasses NewEvent.+func TestCollectionMethodIsOTLPOnEverySignal(t *testing.T) {+ logs := plog.NewLogs()+ logRecord := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()+ logRecord.Body().SetStr("claude_code.assistant_response")+ logRecord.Attributes().PutStr("service.name", "claude-code")+ logRecord.Attributes().PutStr("event.name", "assistant_response")++ traces := ptrace.NewTraces()+ span := traces.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()+ span.SetName("chat gpt-4")+ span.Attributes().PutStr("gen_ai.operation.name", "execute_tool")++ converter := NewConverter(Options{})+ var events []Event+ events = append(events, converter.EventsFromLogs(logs)...)+ events = append(events, converter.EventsFromTraces(traces)...)+ if len(events) < 2 {+ t.Fatalf("events = %d, want at least one per signal", len(events))+ }+ for _, event := range events {+ if event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodOTLP {+ t.Fatalf("collection_method = %q for action %q, want otlp", event.Harness.CollectionMethod, event.Event.Action)+ }+ }+}++// The catch-all is the whole reason the field exists: a log record whose body matches nothing+// lands on tool.invoked, and until now nothing in the event said that the action was a fallback+// rather than a report.+func TestFidelityMarksCatchAllInferred(t *testing.T) {+ record := plog.NewLogRecord()+ record.Body().SetStr("something entirely unclassifiable")+ record.Attributes().PutStr("service.name", "some-runtime")++ event := NewConverter(Options{}).EventFromLog(nil, record)+ if event.Event.Action != "tool.invoked" {+ t.Fatalf("action = %q, want the tool.invoked catch-all", event.Event.Action)+ }+ if event.Event.Fidelity != asymptoteobserve.FidelityInferred {+ t.Fatalf("fidelity = %q, want inferred", event.Event.Fidelity)+ }+}++// A body containing "exec" becomes command.executed, which is the exact case that made the field+// necessary: rules/risky-command/ matches on command.executed, and prose is not a command.+func TestFidelityMarksKeywordMatchInferred(t *testing.T) {+ for body, wantAction := range map[string]string{+ "agent decided to exec something": "command.executed",+ "wrote the file to disk": "file.modified",+ "switching approval_mode_switch to on": "approval.requested",+ } {+ record := plog.NewLogRecord()+ record.Body().SetStr(body)+ record.Attributes().PutStr("service.name", "some-runtime")++ event := NewConverter(Options{}).EventFromLog(nil, record)+ if event.Event.Action != wantAction {+ t.Fatalf("body %q gave action %q, want %q", body, event.Event.Action, wantAction)+ }+ if event.Event.Fidelity != asymptoteobserve.FidelityInferred {+ t.Fatalf("body %q gave fidelity %q, want inferred", body, event.Event.Fidelity)+ }+ }+}++// A structured attribute that names the operation is a report, not a guess, and must not be+// tarred with the same marker as the keyword branches -- otherwise a consumer filtering out+// inferred events would throw away the good telemetry along with the bad.+func TestFidelityMarksStructuredAttributesObserved(t *testing.T) {+ for name, attrs := range map[string]map[string]string{+ "mcp tools/call": {"mcp.method.name": "tools/call"},+ "gen_ai execute_tool": {"gen_ai.operation.name": "execute_tool"},+ "gen_ai tool call id": {"gen_ai.tool.call.id": "call_123"},+ "explicit event action": {"beacon.event.action": "file.read"},+ } {+ t.Run(name, func(t *testing.T) {+ record := plog.NewLogRecord()+ record.Body().SetStr("prose that would otherwise be keyword-matched: exec file")+ record.Attributes().PutStr("service.name", "some-runtime")+ for key, value := range attrs {+ record.Attributes().PutStr(key, value)+ }+ event := NewConverter(Options{}).EventFromLog(nil, record)+ if event.Event.Fidelity != asymptoteobserve.FidelityObserved {+ t.Fatalf("fidelity = %q for %s, want observed", event.Event.Fidelity, name)+ }+ })+ }+}++// Codex names its events explicitly. Those names are resolved after construction, overwriting+// whatever the body was guessed to mean, so the fidelity has to be upgraded with the action --+// otherwise Codex's best telemetry would be labeled as a guess.+func TestFidelityUpgradedWhenCodexNormalizerResolvesAction(t *testing.T) {+ record := plog.NewLogRecord()+ // A body that on its own reaches the "prompt" keyword branch and would be marked inferred.+ record.Body().SetStr("codex prompt something")+ record.Attributes().PutStr("service.name", "codex")+ record.Attributes().PutStr("event.name", string(CodexUserPrompt))++ event := NewConverter(Options{}).EventFromLog(nil, record)+ if event.Event.Action != "prompt.submitted" {+ t.Fatalf("action = %q, want prompt.submitted", event.Event.Action)+ }+ if event.Event.Fidelity != asymptoteobserve.FidelityObserved {+ t.Fatalf("fidelity = %q, want observed after Codex normalization", event.Event.Fidelity)+ }+}++// A known claude_code.* name is a report; an unknown one falls back to session.activity, which is+// a placeholder. Both arrive as session.activity, so the fidelity is the only thing that tells a+// consumer which of the two it is holding.+func TestFidelitySeparatesKnownFromUnknownClaudeEvents(t *testing.T) {+ known := plog.NewLogRecord()+ known.Body().SetStr("claude_code.assistant_response")+ known.Attributes().PutStr("service.name", "claude-code")+ known.Attributes().PutStr("event.name", "assistant_response")++ unknown := plog.NewLogRecord()+ unknown.Body().SetStr("claude_code.future_lifecycle_event")+ unknown.Attributes().PutStr("service.name", "claude-code")+ unknown.Attributes().PutStr("event.name", "claude_code.future_lifecycle_event")++ converter := NewConverter(Options{})+ knownEvent := converter.EventFromLog(nil, known)+ unknownEvent := converter.EventFromLog(nil, unknown)++ if knownEvent.Event.Action != "session.activity" || unknownEvent.Event.Action != "session.activity" {+ t.Fatalf("actions = %q / %q, want both session.activity so fidelity is the only difference",+ knownEvent.Event.Action, unknownEvent.Event.Action)+ }+ if knownEvent.Event.Fidelity != asymptoteobserve.FidelityObserved {+ t.Fatalf("known event fidelity = %q, want observed", knownEvent.Event.Fidelity)+ }+ if unknownEvent.Event.Fidelity != asymptoteobserve.FidelityInferred {+ t.Fatalf("unknown event fidelity = %q, want inferred", unknownEvent.Event.Fidelity)+ }+}++// An explicit beacon.event.action wins over the Claude normalizer, and its fidelity has to travel+// with it. Marking this observed-by-attribute but then letting the normalizer's verdict stick+// would describe an action the event no longer carries.+func TestFidelityRestoredWithPreservedExplicitAction(t *testing.T) {+ record := plog.NewLogRecord()+ record.Body().SetStr("claude_code.future_lifecycle_event")+ record.Attributes().PutStr("service.name", "claude-code")+ record.Attributes().PutStr("event.name", "claude_code.future_lifecycle_event")+ record.Attributes().PutStr("beacon.event.action", "file.read")++ event := NewConverter(Options{}).EventFromLog(nil, record)+ if event.Event.Action != "file.read" {+ t.Fatalf("action = %q, want the explicit file.read", event.Event.Action)+ }+ if event.Event.Fidelity != asymptoteobserve.FidelityObserved {+ t.Fatalf("fidelity = %q, want observed for an explicitly stated action", event.Event.Fidelity)+ }+}++func TestCopilotFidelitySplitsNamedEventsFromFallback(t *testing.T) {+ named, namedFidelity := CopilotActionWithFidelity(map[string]interface{}{"event.name": "copilot_chat.tool.call"}, "", "")+ if named != "tool.invoked" || namedFidelity != asymptoteobserve.FidelityObserved {+ t.Fatalf("named copilot event = (%q, %q), want (tool.invoked, observed)", named, namedFidelity)+ }+ fallback, fallbackFidelity := CopilotActionWithFidelity(map[string]interface{}{}, "", "asking for permission")+ if fallback != "approval.requested" || fallbackFidelity != asymptoteobserve.FidelityInferred {+ t.Fatalf("keyword copilot event = (%q, %q), want (approval.requested, inferred)", fallback, fallbackFidelity)+ }+}++// InferAction is still exported and still returns just the action; the wrapper must not drift from+// the function it delegates to.+func TestInferActionMatchesWithFidelityVariant(t *testing.T) {+ for _, fallback := range []string{"", "unclassifiable", "wrote a file", "exec something", "claude_code.assistant_response"} {+ attrs := map[string]interface{}{"service.name": "some-runtime"}+ want, _ := InferActionWithFidelity(attrs, fallback)+ if got := InferAction(attrs, fallback); got != want {+ t.Fatalf("InferAction(%q) = %q, InferActionWithFidelity = %q", fallback, got, want)+ }+ }+}diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.goindex 2d5c7a02..f9438f33 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go@@ -117,7 +117,10 @@ func NewEvent(action, category, severity, harnessName string, ts time.Time) EvenAction: action,Category: category,Severity: asymptoteobserve.Severity(severity),- Harness: HarnessInfo{Name: harnessName},+ // Every event this exporter produces came off the runtime as OpenTelemetry, whatever+ // signal it arrived on, so the method is fixed here at the single construction point+ // rather than repeated at each of the log/span/metric call sites.+ Harness: HarnessInfo{Name: harnessName, CollectionMethod: asymptoteobserve.CollectionMethodOTLP},})return Event{ObservedAt: ts.UTC(),diff --git a/docs/telemetry-schema/event-schema.mdx b/docs/telemetry-schema/event-schema.mdxindex 007e72a3..28a0903e 100644--- a/docs/telemetry-schema/event-schema.mdx+++ b/docs/telemetry-schema/event-schema.mdx@@ -21,6 +21,53 @@ The schema gives every event a consistent backbone:| `run` and `session` | Connects activity to CI runs, cloud-agent jobs, local sessions, repositories, branches, and working directories || `tool`, `command`, `file`, `mcp`, `approval`, and `policy` | Captures the entities analysts and detections need to understand agent behavior || `content` | Records whether prompt or tool content was included, redacted, truncated, or omitted |+| `harness.collection_method` and `event.fidelity` | Record how Beacon obtained the event and how sure it is of the action |++## Provenance: how Beacon knows what it wrote++Normalizing many runtimes into one event shape has a cost: a field that reads the same for every+source hides how differently the sources behave. `event.action` is the field where that matters+most. A Claude Code `PermissionRequest` hook hands Beacon a typed payload naming the operation. A+Codex OTLP log record hands it a body string that Beacon classifies by pattern, with a fallback for+records that match nothing. Both produce an `event.action`, and without a marker a detection cannot+tell a report from a reading.++Two optional fields carry that context.++`harness.collection_method` describes the mechanism that carried the event off the runtime:++| Value | Meaning |+|-------|---------|+| `hook` | A runtime-native hook the vendor exposes, which executes `beacon-hooks` with a structured payload |+| `plugin` | A Beacon-managed plugin or extension file the runtime loads, which calls `beacon-hooks` from the runtime's own callbacks |+| `otlp` | OpenTelemetry logs, traces, or metrics the runtime exported to Beacon's local collector |+| `poll` | A periodic pull from a runtime's API, seen after the fact rather than as the agent works |++`event.fidelity` describes the specific action on the event:++| Value | Meaning |+|-------|---------|+| `observed` | The source named this action — a hook event name, a plugin event type, an explicit `event.action` attribute, or a structured attribute identifying the operation |+| `inferred` | Beacon derived the action: a pattern match over free text, a fallback for an unrecognized event, or an action synthesized from an adjacent observation |++The two are independent. One OTLP stream carries both kinds: a record that declares its+`event.name` is `observed`, while a record carrying only prose is `inferred`. Both are+`collection_method: otlp`.++Both fields are optional and omitted rather than written empty. Events Beacon emits about itself —+health heartbeats, self-update results — have no collecting harness and no source action to be+faithful to, so they carry neither.++Rules can match on both, so a detection that needs certainty can require it:++```+e.event.action == "approval.allowed" && e.event.fidelity == "observed"+```++Approvals are the clearest case for that. Several runtimes expose a pre-tool notification but no+approval hook, and Beacon turns the former into an `approval.allowed` event so approval-shaped+detections still have something to match. Those events are `inferred`: nothing was gated, a tool+call was seen. Anything counting real operator decisions should exclude them.## Required fields@@ -33,9 +80,11 @@ The schema gives every event a consistent backbone:| `event.kind` | Event family, currently `agent_runtime` || `event.action` | Normalized action such as `command.executed` or `tool.invoked` || `event.category` | Event category, provided by the runtime or inferred from `event.action` when possible |+| `event.fidelity` | Optional. `observed` or `inferred` — see [Provenance](#provenance-how-beacon-knows-what-it-wrote) || `severity` | `info`, `low`, `medium`, `high`, or `critical` || `endpoint` | Host and operating system context || `harness` | Runtime that produced the signal |+| `harness.collection_method` | Optional. `hook`, `plugin`, `otlp`, or `poll` — see [Provenance](#provenance-how-beacon-knows-what-it-wrote) |## How it extends OpenTelemetry@@ -51,6 +100,7 @@ The normalized schema is the contract between collection, detection, investigati- Write detections once against stable fields instead of per-runtime payloads.- Preserve source-specific OpenTelemetry and GenAI context without forcing downstream tools to parse raw traces.- Keep prompt, tool, command, file, approval, policy, and token-usage telemetry comparable across supported harnesses.+- Say how each event was collected and how sure Beacon is of its action, so a consumer can weigh a runtime-reported fact differently from a derived one.- Forward one predictable JSONL shape into customer-managed analytics, SIEM, object-storage, and review workflows.## Read nextdiff --git a/docs/telemetry-schema/normalization.mdx b/docs/telemetry-schema/normalization.mdxindex e08b1246..dc646c61 100644--- a/docs/telemetry-schema/normalization.mdx+++ b/docs/telemetry-schema/normalization.mdx@@ -164,6 +164,31 @@ When a runtime omits `event.category`, Beacon infers it from `event.action`:| `metric.*` | `metric` || `tool.*` | `tool` |+## Action inference and fidelity++Actions are resolved in order, and where the answer comes from is recorded on the event as+[`event.fidelity`](/telemetry-schema/event-schema#provenance-how-beacon-knows-what-it-wrote):++| Resolution step | Fidelity |+|-----------------|----------|+| An explicit `beacon.event.action`, `event.action`, `gen_ai.agent.action`, or `ai.agent.action` attribute | `observed` |+| A structured attribute naming the operation: `mcp.method.name`, `gen_ai.operation.name`, a `gen_ai.tool.call.*` value, a known Copilot `event.name` | `observed` |+| A known runtime event name resolved after conversion: a Codex `event.name`, a recognized `claude_code.*` event | `observed` |+| A pattern match over the log body, span name, or joined event text | `inferred` |+| An unrecognized `claude_code.*` event, which falls back to `session.activity` | `inferred` |+| Nothing matched, which falls back to `tool.invoked` | `inferred` |++The distinction is structural rather than semantic: it records whether the source named the+operation or Beacon pattern-matched prose, not whether a given mapping is ideal. An action resolved+from a runtime's own event name overrides an earlier pattern match, and the fidelity is raised with+it, so a runtime that names its events well is not penalized for also carrying a prose body.++Hook and plugin telemetry is `observed` by construction, because a hook fires for a named lifecycle+event. The exception is approval synthesis: on runtimes that expose a pre-tool notification but no+approval hook, Beacon emits an `approval.allowed` event carrying `approval.required` so+approval-shaped detections have something to match. Nothing was gated there, so those events are+`inferred`.+## Related<Columns cols={2}>diff --git a/pkg/asymptoteobserve/event.go b/pkg/asymptoteobserve/event.goindex a3934819..2ccea323 100644--- a/pkg/asymptoteobserve/event.go+++ b/pkg/asymptoteobserve/event.go@@ -52,6 +52,10 @@ type EventInfo struct {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 {@@ -70,6 +74,10 @@ type HarnessInfo struct {Version string `json:"version,omitempty"`ExecutablePath string `json:"executable_path,omitempty"`ConfigPath string `json:"config_path,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 {@@ -428,6 +436,10 @@ type NewEventOptions struct {Message stringOrigin OriginRun *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 {@@ -449,6 +461,7 @@ func NewEvent(opts NewEventOptions) Event {Kind: "agent_runtime",Action: opts.Action,Category: opts.Category,+ Fidelity: opts.Fidelity,},Severity: severity,Endpoint: EndpointInfo{@@ -496,6 +509,12 @@ func (e Event) Validate() error {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, or poll")+ }if e.Content != nil && e.Content.Retention != "" {switch e.Content.Retention {case ContentRetentionMetadata, ContentRetentionRedacted, ContentRetentionFull:diff --git a/pkg/asymptoteobserve/provenance.go b/pkg/asymptoteobserve/provenance.gonew file mode 100644index 00000000..81da922a--- /dev/null+++ b/pkg/asymptoteobserve/provenance.go@@ -0,0 +1,104 @@+package asymptoteobserve++import "strings"++// Provenance: how Beacon came to know a thing, recorded alongside the thing itself.+//+// Beacon collects from runtimes over four different mechanisms whose fidelity differs by roughly+// an order of magnitude. A Claude Code `PermissionRequest` hook hands Beacon a typed payload that+// names the operation. A Codex OTLP log record hands it a body string that Beacon has to classify+// by substring match, with a catch-all that lands on `tool.invoked` when nothing matches. Both+// produced an `event.action` in the same field, and until these two markers existed nothing in the+// event distinguished them -- so every rule in rules/, every SIEM query, and every dashboard+// treated a reported fact and a keyword guess as the same claim.+//+// Two independent axes, hence two fields rather than one:+//+// - harness.collection_method is about the pipe: which mechanism carried this event off the+// runtime. Stable for the lifetime of an install, useful for "what is my coverage" questions.+// - event.fidelity is about the specific claim: did the source name this action, or did Beacon+// derive it. Varies event to event within one collection method, because an OTLP stream+// carries both records that declare `event.name` and records that carry only prose.+//+// Neither field is required. An event Beacon emits about itself (a health heartbeat, a self-update+// result) has no collecting harness and no source action to be faithful to, and leaves both empty+// rather than asserting a method it did not use.+const (+ // CollectionMethodHook is a runtime-native hook: the runtime executes `beacon-hooks` and+ // hands it a structured payload for a named lifecycle event.+ CollectionMethodHook = "hook"+ // CollectionMethodOTLP is OpenTelemetry data the runtime exported to Beacon's local+ // collector, converted by the beaconjson exporter.+ CollectionMethodOTLP = "otlp"+ // CollectionMethodPlugin is a Beacon-managed plugin or extension file the runtime loads,+ // which calls `beacon-hooks` on the runtime's own event callbacks. Distinct from `hook`+ // because Beacon ships and versions the plugin source, so its coverage is Beacon's to fix+ // rather than the vendor's to expose.+ CollectionMethodPlugin = "plugin"+ // CollectionMethodPoll is a periodic pull from a runtime's API, where Beacon sees whatever+ // the API returns after the fact rather than observing the agent as it works.+ CollectionMethodPoll = "poll"+)++const (+ // FidelityObserved means the source named this action. The value came from a hook event+ // name, a plugin event type, an explicit `event.action` attribute, or a structured+ // attribute whose value identifies the operation (`mcp.method.name`, a known+ // `claude_code.*`/Codex `event.name`, a tool-call id). A consumer can treat the action as+ // a report.+ FidelityObserved = "observed"+ // FidelityInferred means Beacon derived this action rather than being told it: a substring+ // match over free text, a catch-all default, or an action synthesized from an adjacent+ // observation. The action is Beacon's best reading and may be wrong. A consumer that needs+ // certainty -- counting approvals, alerting on a specific action -- should exclude these.+ FidelityInferred = "inferred"+)++// ValidCollectionMethod reports whether value is one of the four defined methods. The empty+// string is not a method and is rejected here; callers that allow "unset" check for it first,+// which is what Validate does.+func ValidCollectionMethod(value string) bool {+ switch value {+ case CollectionMethodHook, CollectionMethodOTLP, CollectionMethodPlugin, CollectionMethodPoll:+ return true+ }+ return false+}++// ValidFidelity reports whether value is one of the two defined fidelities, on the same terms as+// ValidCollectionMethod.+func ValidFidelity(value string) bool {+ switch value {+ case FidelityObserved, FidelityInferred:+ return true+ }+ return false+}++// CollectionMethodForPlatform maps a `beacon-hooks --platform` value onto the mechanism that+// platform actually uses.+//+// It lives here, beside NormalizeHarnessName, for the same reason that function does: the hook+// adapter writes this field from its `--platform` flag and no other code path can see that flag,+// so a mapping kept anywhere else would be a second definition waiting to disagree. Keying on+// `--platform` rather than on the normalized harness name is deliberate -- the flag records which+// integration shape Beacon installed, which is exactly the question, while the harness name+// records which product it was, which is not. VS Code is the case that separates them: hook and+// OTLP telemetry for it normalize to the same `vscode_copilot` harness, but only one of the two+// arrives through a hook.+//+// Platforms that use a Beacon-managed plugin or extension file are enumerated rather than+// defaulted, because the default has to be something and `hook` is the safer wrong answer: a+// plugin platform reported as `hook` overstates vendor support, while a hook platform reported as+// `plugin` would send someone to fix Beacon's source for a payload the vendor never sent. New+// plugin-shaped integrations belong in the list; new hook-shaped ones need no change.+func CollectionMethodForPlatform(platform string) string {+ switch strings.ToLower(strings.TrimSpace(platform)) {+ case "":+ return ""+ case "opencode", "cline", "pi":+ return CollectionMethodPlugin+ default:+ return CollectionMethodHook+ }+}diff --git a/pkg/asymptoteobserve/provenance_test.go b/pkg/asymptoteobserve/provenance_test.gonew file mode 100644index 00000000..ccaefa71--- /dev/null+++ b/pkg/asymptoteobserve/provenance_test.go@@ -0,0 +1,155 @@+package asymptoteobserve++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestValidateFidelityValues(t *testing.T) {+ for _, fidelity := range []string{"", FidelityObserved, FidelityInferred} {+ t.Run("accepts_"+fidelity, func(t *testing.T) {+ event := NewEvent(NewEventOptions{+ Action: "tool.invoked",+ Harness: HarnessInfo{Name: "cursor"},+ Fidelity: fidelity,+ })+ if err := event.Validate(); err != nil {+ t.Fatalf("Validate rejected fidelity %q: %v", fidelity, err)+ }+ })+ }++ // "probably" is the shape of the mistake worth guarding: a third value invented at a call+ // site, which would leave consumers filtering on a vocabulary that no longer covers the log.+ event := NewEvent(NewEventOptions{Action: "tool.invoked", Harness: HarnessInfo{Name: "cursor"}, Fidelity: "probably"})+ if err := event.Validate(); err == nil || !strings.Contains(err.Error(), "event.fidelity must be observed or inferred") {+ t.Fatalf("Validate error = %v, want fidelity error", err)+ }+}++func TestValidateCollectionMethodValues(t *testing.T) {+ for _, method := range []string{"", CollectionMethodHook, CollectionMethodOTLP, CollectionMethodPlugin, CollectionMethodPoll} {+ t.Run("accepts_"+method, func(t *testing.T) {+ event := NewEvent(NewEventOptions{+ Action: "tool.invoked",+ Harness: HarnessInfo{Name: "cursor", CollectionMethod: method},+ })+ if err := event.Validate(); err != nil {+ t.Fatalf("Validate rejected collection_method %q: %v", method, err)+ }+ })+ }++ event := NewEvent(NewEventOptions{Action: "tool.invoked", Harness: HarnessInfo{Name: "cursor", CollectionMethod: "webhook"}})+ if err := event.Validate(); err == nil || !strings.Contains(err.Error(), "harness.collection_method must be hook, otlp, plugin, or poll") {+ t.Fatalf("Validate error = %v, want collection_method error", err)+ }+}++// Both fields are additive and optional, so an event from a producer that has never heard of them+// must serialize exactly as it did before. Asserting on absence rather than on a default value is+// the point: an empty string written into either field would be a value consumers have to handle.+func TestProvenanceFieldsOmittedWhenUnset(t *testing.T) {+ event := NewEvent(NewEventOptions{Action: "tool.invoked", Harness: HarnessInfo{Name: "cursor"}})+ data, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ for _, key := range []string{"fidelity", "collection_method"} {+ if strings.Contains(string(data), key) {+ t.Fatalf("unset provenance field %q serialized: %s", key, data)+ }+ }+}++func TestProvenanceFieldsSerializeUnderSchemaNames(t *testing.T) {+ event := NewEvent(NewEventOptions{+ Action: "command.executed",+ Harness: HarnessInfo{Name: "codex_cli", CollectionMethod: CollectionMethodOTLP},+ Fidelity: FidelityInferred,+ })+ data, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ var decoded struct {+ Event struct {+ Fidelity string `json:"fidelity"`+ } `json:"event"`+ Harness struct {+ CollectionMethod string `json:"collection_method"`+ } `json:"harness"`+ }+ if err := json.Unmarshal(data, &decoded); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if decoded.Event.Fidelity != FidelityInferred {+ t.Fatalf("event.fidelity = %q, want %q", decoded.Event.Fidelity, FidelityInferred)+ }+ if decoded.Harness.CollectionMethod != CollectionMethodOTLP {+ t.Fatalf("harness.collection_method = %q, want %q", decoded.Harness.CollectionMethod, CollectionMethodOTLP)+ }+}++func TestCollectionMethodForPlatform(t *testing.T) {+ for platform, want := range map[string]string{+ // Hook-shaped: the vendor exposes a hook configuration and Beacon registers in it.+ "cursor": CollectionMethodHook,+ "claude": CollectionMethodHook,+ "devin": CollectionMethodHook,+ "devin-cli": CollectionMethodHook,+ "devin-desktop": CollectionMethodHook,+ "grok": CollectionMethodHook,+ "antigravity": CollectionMethodHook,+ "hermes": CollectionMethodHook,+ "factory": CollectionMethodHook,+ "copilot": CollectionMethodHook,+ // vscode is the case that justifies keying on --platform rather than on the normalized+ // harness name: its hook and OTLP telemetry both normalize to vscode_copilot, so the+ // harness name cannot distinguish them and only the flag can.+ "vscode": CollectionMethodHook,+ // Plugin-shaped: Beacon ships and versions the file the runtime loads.+ "opencode": CollectionMethodPlugin,+ "cline": CollectionMethodPlugin,+ "pi": CollectionMethodPlugin,+ // Unset stays unset rather than defaulting to a method, so an event with no platform does+ // not claim one.+ "": "",+ } {+ if got := CollectionMethodForPlatform(platform); got != want {+ t.Fatalf("CollectionMethodForPlatform(%q) = %q, want %q", platform, got, want)+ }+ }+}++// Case and surrounding whitespace come from a hook command line written into a settings file, so+// they are worth normalizing rather than trusting.+func TestCollectionMethodForPlatformNormalizesInput(t *testing.T) {+ for _, platform := range []string{"Cline", " cline ", "CLINE"} {+ if got := CollectionMethodForPlatform(platform); got != CollectionMethodPlugin {+ t.Fatalf("CollectionMethodForPlatform(%q) = %q, want %q", platform, got, CollectionMethodPlugin)+ }+ }+}++// An unrecognized platform resolves to hook rather than to empty, mirroring how+// NormalizeHarnessName keeps an unknown runtime's own name instead of dropping it. A new+// hook-shaped integration then needs no change here; a new plugin-shaped one does.+func TestCollectionMethodForPlatformDefaultsToHook(t *testing.T) {+ if got := CollectionMethodForPlatform("some-future-runtime"); got != CollectionMethodHook {+ t.Fatalf("CollectionMethodForPlatform(unknown) = %q, want %q", got, CollectionMethodHook)+ }+}++func TestValidCollectionMethodAndFidelityRejectEmpty(t *testing.T) {+ // Validate() checks for empty separately before calling these, so the predicates themselves+ // treat "" as not-a-value. Pinning that keeps a future caller from using them as an+ // "is this allowed" check and accidentally permitting the empty string.+ if ValidCollectionMethod("") {+ t.Fatal("ValidCollectionMethod(\"\") = true, want false")+ }+ if ValidFidelity("") {+ t.Fatal("ValidFidelity(\"\") = true, want false")+ }+}diff --git a/spec/threat-rules/FIELDS.md b/spec/threat-rules/FIELDS.mdindex a424dd7e..93dd4932 100644--- a/spec/threat-rules/FIELDS.md+++ b/spec/threat-rules/FIELDS.md@@ -30,6 +30,7 @@ Regenerate with `beacon rules fields --markdown > spec/threat-rules/FIELDS.md`.| `e.error.type` | string || `e.event.action` | string || `e.event.category` | string |+| `e.event.fidelity` | string || `e.event.kind` | string || `e.field_truncated` | bool || `e.file.diff_bytes` | int |@@ -81,6 +82,7 @@ Regenerate with `beacon rules fields --markdown > spec/threat-rules/FIELDS.md`.| `e.gen_ai.usage.output_tokens` | int || `e.gen_ai.usage.reasoning.output_tokens` | int || `e.gen_ai.workflow.name` | string |+| `e.harness.collection_method` | string || `e.harness.config_path` | string || `e.harness.executable_path` | string || `e.harness.name` | string |