Skip to content

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

add collector exporter

Justin D'Souza0e94e742ee55
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.go
new file mode 100644
index 00000000..d12582ee
--- /dev/null
+++ b/cli/beacon-hooks/cmd/endpoint_events.go
@@ -0,0 +1,147 @@
+package cmd
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
+)
+
+func emitHookEvent(logger *logging.Logger, action, category, severity, message string, input map[string]interface{}, fields map[string]interface{}) {
+ if fields == nil {
+ fields = map[string]interface{}{}
+ }
+ if model := getFirstStr(input, "model"); model != "" {
+ fields["model"] = model
+ }
+ if cwd := resolveCwd(input, platformFlag); cwd != "" {
+ fields["session"] = mergeNested(fields["session"], map[string]interface{}{"working_directory": cwd})
+ fields["repository"] = cwd
+ }
+ if branch := getFirstStr(input, "branch", "git_branch"); branch != "" {
+ fields["branch"] = branch
+ }
+ logger.EndpointEvent(action, category, severity, message, fields)
+}
+
+func sessionFields(sessionID string, input map[string]interface{}) map[string]interface{} {
+ fields := map[string]interface{}{}
+ session := map[string]interface{}{}
+ if sessionID != "" {
+ session["id"] = sessionID
+ }
+ if cwd := resolveCwd(input, platformFlag); cwd != "" {
+ session["working_directory"] = cwd
+ fields["repository"] = cwd
+ }
+ if len(session) > 0 {
+ fields["session"] = session
+ }
+ return fields
+}
+
+func toolFields(toolName string, toolInput map[string]interface{}) map[string]interface{} {
+ fields := map[string]interface{}{}
+ if toolName != "" {
+ fields["tool"] = map[string]interface{}{"name": toolName}
+ }
+ if command := firstToolString(toolInput, "command", "cmd", "shell_command"); command != "" {
+ fields["command"] = map[string]interface{}{"command": command}
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "command": command})
+ }
+ if path := firstToolString(toolInput, "file_path", "filePath", "path"); path != "" {
+ fields["file"] = map[string]interface{}{
+ "path": path,
+ "operation": fileOperation(toolName),
+ "language": strings.TrimPrefix(filepath.Ext(path), "."),
+ }
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"path": path})
+ }
+ if server := firstToolString(toolInput, "server", "server_name", "mcp_server"); server != "" || strings.Contains(strings.ToLower(toolName), "mcp") {
+ fields["mcp"] = map[string]interface{}{
+ "server": server,
+ "tool": firstToolString(toolInput, "tool", "tool_name", "name"),
+ }
+ }
+ return fields
+}
+
+func diffFields(filePath, diffStr string) map[string]interface{} {
+ if filePath == "" {
+ return nil
+ }
+ file := map[string]interface{}{
+ "path": filePath,
+ "operation": "modify",
+ "language": strings.TrimPrefix(filepath.Ext(filePath), "."),
+ }
+ if diffStr != "" {
+ sum := sha256.Sum256([]byte(diffStr))
+ file["diff_hash"] = hex.EncodeToString(sum[:])
+ file["diff_bytes"] = len(diffStr)
+ if config.ContentRetentionMode() != config.ContentRetentionMetadata {
+ file["diff"] = diffStr
+ }
+ }
+ return map[string]interface{}{"file": file}
+}
+
+func mergeNested(existing interface{}, values map[string]interface{}) map[string]interface{} {
+ out := map[string]interface{}{}
+ if current, ok := existing.(map[string]interface{}); ok {
+ for key, value := range current {
+ out[key] = value
+ }
+ }
+ for key, value := range values {
+ if value != "" && value != nil {
+ out[key] = value
+ }
+ }
+ return out
+}
+
+func firstToolString(input map[string]interface{}, keys ...string) string {
+ for _, key := range keys {
+ if value, ok := input[key]; ok {
+ if str := strings.TrimSpace(fmt.Sprint(value)); str != "" && str != "<nil>" {
+ return str
+ }
+ }
+ }
+ return ""
+}
+
+func fileOperation(toolName string) string {
+ lower := strings.ToLower(toolName)
+ switch {
+ case strings.Contains(lower, "read"):
+ return "read"
+ case strings.Contains(lower, "write") || strings.Contains(lower, "create"):
+ return "create"
+ case strings.Contains(lower, "edit") || strings.Contains(lower, "patch"):
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+func actionForTool(hookEvent, toolName string) string {
+ lower := strings.ToLower(toolName)
+ switch {
+ case strings.Contains(lower, "mcp"):
+ return "mcp.tool_invoked"
+ case strings.Contains(lower, "shell") || strings.Contains(lower, "terminal") || strings.Contains(lower, "command"):
+ return "command.executed"
+ case strings.Contains(lower, "read"):
+ return "file.read"
+ case isFileEditTool(platformFlag, toolName) || hookEvent == "afterFileEdit":
+ return "file.modified"
+ default:
+ return "tool.invoked"
+ }
+}
diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.go
index a6808a14..15311555 100644
--- a/cli/beacon-hooks/cmd/post_tool.go
+++ b/cli/beacon-hooks/cmd/post_tool.go
@@ -3,22 +3,19 @@ package cmd
import (
"encoding/json"
"strings"
- "time"
"github.com/spf13/cobra"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
- "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/depscan"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
- "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
)
var postToolCmd = &cobra.Command{
Use: "post-tool",
- Short: "Record file-edit telemetry and dependency scan findings",
+ Short: "Record file-edit telemetry",
Long: `PostToolUse hook - triggered after Write, Edit, or MultiEdit operations.
-The public Beacon build records local metadata and dependency scan findings only.`,
+The public Beacon build records local metadata only.`,
Run: runPostTool,
}
@@ -52,8 +49,7 @@ func runPostTool(cmd *cobra.Command, args []string) {
var params *evaluationParams
- // Check if dep-scan is enabled before parsing, so parsers can allow dep files through
- depScanEnabled := config.IsDepScanEnabled()
+ emitPostToolObserved(logger, input)
if platformFlag == "cursor" {
// Cursor fires two hook types through post-tool:
@@ -62,20 +58,13 @@ func runPostTool(cmd *cobra.Command, args []string) {
// We use hook_event_name (present in all Cursor hook inputs) to distinguish them.
hookEvent, _ := input["hook_event_name"].(string)
if hookEvent != "afterFileEdit" {
- // postToolUse — used for dep scan only (result stored in state, delivered via stop hook)
- params = parseCursorPostToolInput(input, logger, depScanEnabled)
- if params != nil && depscan.IsDependencyFile(params.filePath) && depScanEnabled {
- runDepScan(params, logger)
- return
- }
outputJSON(emptyResponse)
return
}
- // afterFileEdit — used for async evaluation only (no output supported).
- // Dep scan is handled by postToolUse above, so don't allow dep files through here.
- params = parseCursorInput(input, logger, false)
+ // afterFileEdit — records file-edit metadata only (no output supported).
+ params = parseCursorInput(input, logger)
} else {
- params = parseClaudeCopilotInput(input, logger, depScanEnabled)
+ params = parseClaudeCopilotInput(input, logger)
}
if params == nil {
@@ -83,25 +72,19 @@ func runPostTool(cmd *cobra.Command, args []string) {
return
}
- // Dep scan: if this is a dependency file and dep-scan is enabled, check for CVEs.
- if depscan.IsDependencyFile(params.filePath) && depScanEnabled {
- runDepScan(params, logger)
- return
- }
-
recordLocalEdit(params, logger)
outputJSON(emptyResponse)
}
// parseCursorInput extracts evaluation params from Cursor's afterFileEdit format.
-func parseCursorInput(input map[string]interface{}, logger *logging.Logger, depScanEnabled bool) *evaluationParams {
+func parseCursorInput(input map[string]interface{}, logger *logging.Logger) *evaluationParams {
sessionID := resolveSessionID(input, "cursor")
filePath, _ := input["file_path"].(string)
if sessionID == "" || filePath == "" {
return nil
}
- if !config.IsScannableFile(filePath) && !(depScanEnabled && depscan.IsDependencyFile(filePath)) {
+ if !config.IsScannableFile(filePath) {
logger.Debug("Skipping non-scannable file: " + filePath)
return nil
}
@@ -130,7 +113,7 @@ func parseCursorInput(input map[string]interface{}, logger *logging.Logger, depS
}
// parseClaudeCopilotInput extracts evaluation params from Claude/Copilot PostToolUse format.
-func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logger, depScanEnabled bool) *evaluationParams {
+func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logger) *evaluationParams {
var sessionID, toolName string
var toolInput, toolResponse map[string]interface{}
@@ -159,7 +142,7 @@ func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logge
return nil
}
- if !config.IsScannableFile(filePath) && !(depScanEnabled && depscan.IsDependencyFile(filePath)) {
+ if !config.IsScannableFile(filePath) {
logger.Debug("Skipping non-scannable file: " + filePath)
return nil
}
@@ -184,6 +167,13 @@ func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logge
// recordLocalEdit logs file-edit metadata without sending code or diffs to a hosted service.
func recordLocalEdit(params *evaluationParams, logger *logging.Logger) {
logger.Info("File edit observed", "file_path", params.filePath, "tool_name", params.toolName)
+ fields := map[string]interface{}{}
+ for key, value := range diffFields(params.filePath, params.diffStr) {
+ fields[key] = value
+ }
+ fields["tool"] = map[string]interface{}{"name": params.toolName, "path": params.filePath}
+ fields["session"] = map[string]interface{}{"id": params.sessionID}
+ logger.EndpointEvent("file.modified", "file", "info", "File edit observed", fields)
}
// resolveToolInput extracts tool input from Copilot's various formats.
@@ -219,112 +209,38 @@ func resolveToolResponse(input map[string]interface{}) map[string]interface{} {
return nil
}
-// runDepScan handles the dep-scan path: parse diff for packages, query OSV, return CVE report.
-func runDepScan(params *evaluationParams, logger *logging.Logger) {
- start := time.Now()
-
- logger.Debug("Dep file detected", "file_path", params.filePath)
-
- packages := depscan.ParseDiffForPackages(params.diffStr, params.filePath)
- if len(packages) == 0 {
- logger.Debug("No packages found in diff", "file_path", params.filePath)
- outputJSON(emptyResponse)
- return
+func emitPostToolObserved(logger *logging.Logger, input map[string]interface{}) {
+ toolName := getFirstStr(input, "tool_name", "toolName")
+ hookEvent := getFirstStr(input, "hook_event_name")
+ toolInput := resolveToolInput(input)
+ if toolInput == nil {
+ if nested, ok := input["tool_input"].(map[string]interface{}); ok {
+ toolInput = nested
+ }
}
-
- pkgNames := make([]string, len(packages))
- for i, p := range packages {
- pkgNames[i] = p.Name + "@" + p.Version
+ sessionID := resolveSessionID(input, platformFlag)
+ fields := sessionFields(sessionID, input)
+ for key, value := range toolFields(toolName, toolInput) {
+ fields[key] = value
}
- logger.Info("Packages parsed from diff", "file_path", params.filePath, "package_count", len(packages), "packages", strings.Join(pkgNames, ", "))
-
- // Query OSV.dev for vulnerabilities
- findings := depscan.QueryPackages(packages, logger)
-
- elapsed := time.Since(start)
-
- if len(findings) == 0 {
- logger.Info("No vulnerabilities found", "package_count", len(packages), "duration_ms", elapsed.Milliseconds())
- outputJSON(emptyResponse)
+ if hookEvent == "postToolUseFailure" {
+ emitHookEvent(logger, "tool.failed", "tool", "high", "Tool execution failed", input, fields)
return
}
-
- // Deduplicate and format
- deduplicated := depscan.DeduplicateFindings(packages, findings)
- report := depscan.FormatCVEReport(deduplicated)
-
- totalCVEs := 0
- for _, f := range deduplicated {
- totalCVEs += len(f.CVEs)
+ action := actionForTool(hookEvent, toolName)
+ category := "tool"
+ if strings.HasPrefix(action, "file.") {
+ category = "file"
+ } else if strings.HasPrefix(action, "command.") {
+ category = "command"
+ } else if strings.HasPrefix(action, "mcp.") {
+ category = "mcp"
}
-
- logger.Info("Vulnerabilities found",
- "total_vulns", totalCVEs,
- "affected_packages", len(deduplicated),
- "duration_ms", elapsed.Milliseconds())
-
- // Return platform-appropriate response
- if platformFlag == "cursor" {
- // Cursor's postToolUse additional_context is unreliable — store report
- // in session state for delivery via the stop hook's followup_message.
- st := state.NewSessionState(params.sessionID, platformFlag)
- st.SetDepScanReport(report)
- logger.Info("CVE report stored for stop hook", "platform", "cursor", "affected_packages", len(deduplicated), "cve_count", totalCVEs, "duration_ms", elapsed.Milliseconds())
- outputJSON(emptyResponse)
- } else {
- logger.Info("CVE report injected", "platform", platformFlag, "affected_packages", len(deduplicated), "cve_count", totalCVEs, "duration_ms", elapsed.Milliseconds())
- outputJSON(map[string]interface{}{
- "decision": "block",
- "reason": report,
- "hookSpecificOutput": map[string]interface{}{
- "hookEventName": "PostToolUse",
- "additionalContext": report,
- },
- })
- }
-}
-
-// parseCursorPostToolInput extracts evaluation params from Cursor's postToolUse format.
-// Cursor postToolUse has: conversation_id, tool_name, tool_input (map), tool_output (JSON string),
-// workspace_roots (array), model, generation_id.
-func parseCursorPostToolInput(input map[string]interface{}, logger *logging.Logger, depScanEnabled bool) *evaluationParams {
- sessionID := getFirstStr(input, "conversation_id")
- toolName := getFirstStr(input, "tool_name")
- toolInput, _ := input["tool_input"].(map[string]interface{})
-
- if !isFileEditTool(platformFlag, toolName) {
- return nil
- }
-
- filePath := diff.GetStringFromMaps("file_path", toolInput)
- if filePath == "" {
- return nil
- }
-
- if sessionID == "" || toolName == "" {
- return nil
- }
-
- if !config.IsScannableFile(filePath) && !(depScanEnabled && depscan.IsDependencyFile(filePath)) {
- return nil
- }
-
- // Build diff from content (Write/Create tool)
- content := diff.GetStringFromMaps("content", toolInput)
- if content == "" {
- return nil
- }
- diffStr := diff.FromToolResponse(toolName, toolInput, nil)
- if diffStr == "" {
- return nil
- }
-
- return &evaluationParams{
- sessionID: sessionID,
- toolName: toolName,
- filePath: filePath,
- diffStr: diffStr,
+ message := "Tool execution observed"
+ if action == "command.executed" {
+ message = "Shell command executed"
}
+ emitHookEvent(logger, action, category, "info", message, input, fields)
}
// isFileEditTool returns true if the tool name represents a file edit operation.
diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.go
index 67e22507..220d9323 100644
--- a/cli/beacon-hooks/cmd/pre_tool.go
+++ b/cli/beacon-hooks/cmd/pre_tool.go
@@ -46,12 +46,14 @@ func runPreTool(cmd *cobra.Command, args []string) {
// Short-circuit: SbD disabled → no-op
if !config.IsSecureByDesignEnabled(platformFlag) {
logger.Debug("Secure by design is disabled, allowing")
+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Secure by Design disabled")
outputJSON(allowResponse)
return
}
if sessionID == "" {
logger.Debug("No session ID, allowing")
+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "No session ID")
outputJSON(allowResponse)
return
}
@@ -66,6 +68,7 @@ func runPreTool(cmd *cobra.Command, args []string) {
// No policies cached → no-op
if policies == "" {
logger.Debug("No policies cached, allowing")
+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "No cached policies")
outputJSON(allowResponse)
return
}
@@ -75,6 +78,7 @@ func runPreTool(cmd *cobra.Command, args []string) {
logger.Debug("Generation ID mismatch, allowing Write (stale state)",
"input_generation_id", inputGenerationID,
"stored_generation_id", storedGenerationID)
+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Generation ID mismatch")
outputJSON(allowResponse)
return
}
@@ -83,6 +87,7 @@ func runPreTool(cmd *cobra.Command, args []string) {
if injected {
logger.Debug("Policy already injected, allowing Write",
"generation_id", storedGenerationID)
+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Policy already injected")
outputJSON(allowResponse)
return
}
@@ -97,6 +102,7 @@ func runPreTool(cmd *cobra.Command, args []string) {
"generation_id", storedGenerationID,
"policy_length", len(policies),
"duration_ms", elapsed.Milliseconds())
+ emitPreToolDecision(logger, input, sessionID, "approval.denied", "deny", "Policy context injection")
outputJSON(map[string]interface{}{
"permission": "deny",
@@ -104,3 +110,18 @@ func runPreTool(cmd *cobra.Command, args []string) {
"agent_message": message,
})
}
+
+func emitPreToolDecision(logger *logging.Logger, input map[string]interface{}, sessionID, action, decision, reason string) {
+ toolName := getFirstStr(input, "tool_name", "toolName")
+ toolInput := resolveToolInput(input)
+ fields := sessionFields(sessionID, input)
+ for key, value := range toolFields(toolName, toolInput) {
+ fields[key] = value
+ }
+ fields["approval"] = map[string]interface{}{
+ "required": true,
+ "decision": decision,
+ "reason": reason,
+ }
+ emitHookEvent(logger, action, "approval", "info", reason, input, fields)
+}
diff --git a/cli/beacon-hooks/cmd/prompt_submit.go b/cli/beacon-hooks/cmd/prompt_submit.go
index 5e2e02b1..d1e17369 100644
--- a/cli/beacon-hooks/cmd/prompt_submit.go
+++ b/cli/beacon-hooks/cmd/prompt_submit.go
@@ -48,6 +48,13 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {
} else {
logger.Debug("Prompt submit observed")
}
+ fields := sessionFields(sessionID, input)
+ if config.ContentRetentionMode() != config.ContentRetentionMetadata {
+ if prompt := getFirstStr(input, "prompt", "user_prompt", "text"); prompt != "" {
+ fields["raw"] = map[string]interface{}{"prompt": prompt}
+ }
+ }
+ emitHookEvent(logger, "prompt.submitted", "prompt", "info", "Prompt submitted to agent", input, fields)
outputJSON(noopResponse)
}
diff --git a/cli/beacon-hooks/cmd/session_end.go b/cli/beacon-hooks/cmd/session_end.go
index c34e3d0b..5dfb7e40 100644
--- a/cli/beacon-hooks/cmd/session_end.go
+++ b/cli/beacon-hooks/cmd/session_end.go
@@ -35,6 +35,7 @@ func runSessionEnd(cmd *cobra.Command, args []string) {
if sessionID != "" {
logger := logging.NewSessionLogger("session-end", platformFlag, sessionID)
logger.Info("Session ended", "session_id", sessionID, "platform", platformFlag)
+ emitHookEvent(logger, "session.ended", "session", "info", "Agent session ended", input, sessionFields(sessionID, input))
logFile := config.GetSessionLogFile(platformFlag, sessionID)
if err := os.Remove(logFile); err != nil && !os.IsNotExist(err) {
diff --git a/cli/beacon-hooks/cmd/session_start.go b/cli/beacon-hooks/cmd/session_start.go
index fcfea133..46ace003 100644
--- a/cli/beacon-hooks/cmd/session_start.go
+++ b/cli/beacon-hooks/cmd/session_start.go
@@ -56,5 +56,6 @@ func runSessionStart(cmd *cobra.Command, args []string) {
}
logger.Info("Session initialized", "session_id", sessionID, "platform", platformFlag)
+ emitHookEvent(logger, "session.started", "session", "info", "Agent session started", input, sessionFields(sessionID, input))
outputJSON(emptyResponse)
}
diff --git a/cli/beacon-hooks/cmd/stop.go b/cli/beacon-hooks/cmd/stop.go
index 9b0ef5a0..60d243ea 100644
--- a/cli/beacon-hooks/cmd/stop.go
+++ b/cli/beacon-hooks/cmd/stop.go
@@ -17,9 +17,9 @@ import (
var stopCmd = &cobra.Command{
Use: "stop",
- Short: "Deliver local dependency scan findings",
+ Short: "Record agent response completion",
Long: `Stop hook - triggered when the coding agent finishes responding.
-The public Beacon build does not poll hosted evaluations; it only delivers local dependency scan findings.`,
+The public Beacon build does not poll hosted evaluations.`,
Run: runStop,
}
@@ -53,7 +53,6 @@ func runStop(cmd *cobra.Command, args []string) {
config.RotateLogIfNeededForPlatform(platformFlag)
st := state.NewSessionState(sessionID, platformFlag)
- depScanReport := st.GetAndClearDepScanReport()
// The public Beacon build is local-only. Clear any pending remote evaluations
// left over from older hook versions instead of polling a hosted service.
@@ -63,20 +62,10 @@ func runStop(cmd *cobra.Command, args []string) {
logger.Warn("Cleared stale remote evaluations in local-only build", "count", len(pendingEvals))
}
- if depScanReport == "" {
- elapsed := time.Since(start)
- logger.Info("stop completed", "duration_ms", elapsed.Milliseconds())
- outputJSONAndExit(emptyResponse)
- return
- }
-
elapsed := time.Since(start)
- logger.Info("Delivering dep scan report via stop hook", "duration_ms", elapsed.Milliseconds())
- if platformFlag == "cursor" {
- outputJSONAndExit(map[string]interface{}{"followup_message": depScanReport})
- } else {
- outputJSONAndExit(map[string]interface{}{"decision": "block", "reason": depScanReport})
- }
+ logger.Info("stop completed", "duration_ms", elapsed.Milliseconds())
+ emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, sessionFields(sessionID, input))
+ outputJSONAndExit(emptyResponse)
}
// platformToTranscriptName maps the platform flag to the transcript platform identifier.
diff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.go
index 8e507251..3493a9c1 100644
--- a/cli/beacon-hooks/internal/config/config.go
+++ b/cli/beacon-hooks/internal/config/config.go
@@ -21,6 +21,14 @@ const (
LogMaxSizeBytes = 10 * 1024 * 1024 // 10 MB
)
+type ContentRetention string
+
+const (
+ ContentRetentionMetadata ContentRetention = "metadata"
+ ContentRetentionRedacted ContentRetention = "redacted"
+ ContentRetentionFull ContentRetention = "full"
+)
+
// Scannable extensions
var scannableExtensions = map[string]bool{
// JavaScript/TypeScript
@@ -125,11 +133,11 @@ func EnsureStateDir(platform string) error {
return os.MkdirAll(GetStateDir(platform), 0755)
}
-// IsDepScanEnabled checks if dependency scanning is enabled.
-// Reads from the global config at ~/.beacon/config.json (not per-platform).
-func IsDepScanEnabled() bool {
- globalPath := filepath.Join(BeaconDir, "config.json")
- data, err := os.ReadFile(globalPath)
+// IsSecureByDesignEnabled checks if Secure by Design is enabled for the given platform.
+// Reads from platform-specific config at ~/.beacon/{platform}/config.json.
+func IsSecureByDesignEnabled(platform string) bool {
+ platformPath := filepath.Join(GetStateDir(platform), "config.json")
+ data, err := os.ReadFile(platformPath)
if err != nil {
return false
}
@@ -137,22 +145,27 @@ func IsDepScanEnabled() bool {
if err := json.Unmarshal(data, &cfg); err != nil {
return false
}
- enabled, ok := cfg["dep_scan"].(bool)
+ enabled, ok := cfg["secure_by_design"].(bool)
return ok && enabled
}
-// IsSecureByDesignEnabled checks if Secure by Design is enabled for the given platform.
-// Reads from platform-specific config at ~/.beacon/{platform}/config.json.
-func IsSecureByDesignEnabled(platform string) bool {
- platformPath := filepath.Join(GetStateDir(platform), "config.json")
- data, err := os.ReadFile(platformPath)
+func ContentRetentionMode() ContentRetention {
+ endpointPath := filepath.Join(BeaconDir, "endpoint", "config.json")
+ data, err := os.ReadFile(endpointPath)
if err != nil {
- return false
+ return ContentRetentionMetadata
}
var cfg map[string]interface{}
if err := json.Unmarshal(data, &cfg); err != nil {
- return false
+ return ContentRetentionMetadata
+ }
+ mode, _ := cfg["content_retention"].(string)
+ switch ContentRetention(mode) {
+ case ContentRetentionRedacted:
+ return ContentRetentionRedacted
+ case ContentRetentionFull:
+ return ContentRetentionFull
+ default:
+ return ContentRetentionMetadata
}
- enabled, ok := cfg["secure_by_design"].(bool)
- return ok && enabled
}
diff --git a/cli/beacon-hooks/internal/depscan/depscan.go b/cli/beacon-hooks/internal/depscan/depscan.go
deleted file mode 100644
index 2304fa38..00000000
--- a/cli/beacon-hooks/internal/depscan/depscan.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package depscan
-
-import (
- "path/filepath"
- "strings"
-)
-
-// DetectedPackage represents a package found in a dependency file diff.
-type DetectedPackage struct {
- Name string
- Version string
- Ecosystem string
- FilePath string
-}
-
-// dependencyFileInfo maps filename patterns to their ecosystem.
-type dependencyFileInfo struct {
- ecosystem string
-}
-
-// knownDepFiles maps exact filenames to ecosystem info.
-var knownDepFiles = map[string]dependencyFileInfo{
- "requirements.txt": {ecosystem: "PyPI"},
- "setup.py": {ecosystem: "PyPI"},
- "Pipfile": {ecosystem: "PyPI"},
- "pyproject.toml": {ecosystem: "PyPI"},
- "package.json": {ecosystem: "npm"},
-}
-
-// IsDependencyFile checks if a file path is a known dependency file.
-func IsDependencyFile(filePath string) bool {
- base := filepath.Base(filePath)
-
- // Exact match
- if _, ok := knownDepFiles[base]; ok {
- return true
- }
-
- // requirements-*.txt pattern
- if strings.HasPrefix(base, "requirements-") && strings.HasSuffix(base, ".txt") {
- return true
- }
-
- // requirements/*.txt pattern (file inside a requirements directory)
- dir := filepath.Base(filepath.Dir(filePath))
- if dir == "requirements" && strings.HasSuffix(base, ".txt") {
- return true
- }
-
- return false
-}
-
-// getEcosystem returns the ecosystem for a dependency file path.
-func getEcosystem(filePath string) string {
- base := filepath.Base(filePath)
-
- if info, ok := knownDepFiles[base]; ok {
- return info.ecosystem
- }
-
- // requirements-*.txt or requirements/*.txt
- if strings.HasSuffix(base, ".txt") {
- if strings.HasPrefix(base, "requirements-") {
- return "PyPI"
- }
- dir := filepath.Base(filepath.Dir(filePath))
- if dir == "requirements" {
- return "PyPI"
- }
- }
-
- return ""
-}
-
-// ParseDiffForPackages extracts added packages from a unified diff string for the given file.
-func ParseDiffForPackages(diffStr, filePath string) []DetectedPackage {
- ecosystem := getEcosystem(filePath)
- if ecosystem == "" {
- return nil
- }
-
- // Extract added lines from the diff (lines starting with "+", excluding "+++")
- addedLines := extractAddedLines(diffStr)
- if len(addedLines) == 0 {
- return nil
- }
-
- var packages []DetectedPackage
- base := filepath.Base(filePath)
-
- switch {
- case ecosystem == "PyPI" && (base == "requirements.txt" ||
- strings.HasPrefix(base, "requirements-") ||
- filepath.Base(filepath.Dir(filePath)) == "requirements"):
- packages = ParseRequirementsTxt(addedLines)
- case ecosystem == "PyPI" && base == "pyproject.toml":
- packages = ParsePyprojectToml(addedLines)
- case ecosystem == "PyPI" && base == "setup.py":
- packages = ParsePyprojectToml(addedLines) // setup.py uses quoted format like pyproject.toml
- case ecosystem == "PyPI" && base == "Pipfile":
- packages = ParseRequirementsTxt(addedLines)
- case ecosystem == "npm" && base == "package.json":
- packages = ParsePackageJSON(addedLines)
- }
-
- // Set ecosystem and file path on all packages
- for i := range packages {
- packages[i].Ecosystem = ecosystem
- packages[i].FilePath = filePath
- }
-
- return packages
-}
-
-// extractAddedLines returns lines that were added in a unified diff (start with "+", excluding "+++").
-func extractAddedLines(diffStr string) []string {
- var added []string
- for _, line := range strings.Split(diffStr, "\n") {
- if strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++") {
- // Remove the leading "+"
- added = append(added, line[1:])
- }
- }
- return added
-}
diff --git a/cli/beacon-hooks/internal/depscan/depscan_test.go b/cli/beacon-hooks/internal/depscan/depscan_test.go
deleted file mode 100644
index 77117d6f..00000000
--- a/cli/beacon-hooks/internal/depscan/depscan_test.go
+++ /dev/null
@@ -1,253 +0,0 @@
-package depscan
-
-import (
- "testing"
-)
-
-func TestIsDependencyFile(t *testing.T) {
- tests := []struct {
- path string
- want bool
- }{
- {"requirements.txt", true},
- {"./requirements.txt", true},
- {"/app/requirements.txt", true},
- {"requirements-dev.txt", true},
- {"requirements-test.txt", true},
- {"requirements/base.txt", true},
- {"pyproject.toml", true},
- {"setup.py", true},
- {"Pipfile", true},
- {"package.json", true},
- {"/app/package.json", true},
-
- // Not dependency files
- {"app.py", false},
- {"main.go", false},
- {"index.js", false},
- {"README.txt", false},
- {"requirements.md", false},
- {"config.json", false},
- {"package-lock.json", false},
- }
-
- for _, tt := range tests {
- t.Run(tt.path, func(t *testing.T) {
- got := IsDependencyFile(tt.path)
- if got != tt.want {
- t.Errorf("IsDependencyFile(%q) = %v, want %v", tt.path, got, tt.want)
- }
- })
- }
-}
-
-func TestParseDiffForPackages_RequirementsTxt(t *testing.T) {
- diff := `--- a/requirements.txt
-+++ b/requirements.txt
-@@ -0,0 +1,4 @@
-+flask==2.3.2
-+jinja2==3.1.4
-+requests>=2.31.0
-+# this is a comment`
-
- packages := ParseDiffForPackages(diff, "requirements.txt")
-
- if len(packages) != 3 {
- t.Fatalf("expected 3 packages, got %d", len(packages))
- }
-
- expected := []struct {
- name, version, ecosystem string
- }{
- {"flask", "2.3.2", "PyPI"},
- {"jinja2", "3.1.4", "PyPI"},
- {"requests", "2.31.0", "PyPI"},
- }
-
- for i, exp := range expected {
- if packages[i].Name != exp.name {
- t.Errorf("package %d: name = %q, want %q", i, packages[i].Name, exp.name)
- }
- if packages[i].Version != exp.version {
- t.Errorf("package %d: version = %q, want %q", i, packages[i].Version, exp.version)
- }
- if packages[i].Ecosystem != exp.ecosystem {
- t.Errorf("package %d: ecosystem = %q, want %q", i, packages[i].Ecosystem, exp.ecosystem)
- }
- }
-}
-
-func TestParseDiffForPackages_PackageJSON(t *testing.T) {
- diff := `--- a/package.json
-+++ b/package.json
-@@ -5,0 +6,3 @@
-+ "express": "4.18.2",
-+ "lodash": "^4.17.21",
-+ "react": "~18.2.0"`
-
- packages := ParseDiffForPackages(diff, "package.json")
-
- if len(packages) != 3 {
- t.Fatalf("expected 3 packages, got %d", len(packages))
- }
-
- expected := []struct {
- name, version string
- }{
- {"express", "4.18.2"},
- {"lodash", "4.17.21"},
- {"react", "18.2.0"},
- }
-
- for i, exp := range expected {
- if packages[i].Name != exp.name {
- t.Errorf("package %d: name = %q, want %q", i, packages[i].Name, exp.name)
- }
- if packages[i].Version != exp.version {
- t.Errorf("package %d: version = %q, want %q", i, packages[i].Version, exp.version)
- }
- if packages[i].Ecosystem != "npm" {
- t.Errorf("package %d: ecosystem = %q, want npm", i, packages[i].Ecosystem)
- }
- }
-}
-
-func TestParseDiffForPackages_PyprojectToml(t *testing.T) {
- diff := `--- a/pyproject.toml
-+++ b/pyproject.toml
-@@ -10,0 +11,3 @@
-+ "django>=4.2.0",
-+ "celery==5.3.1",`
-
- packages := ParseDiffForPackages(diff, "pyproject.toml")
-
- if len(packages) != 2 {
- t.Fatalf("expected 2 packages, got %d", len(packages))
- }
-
- if packages[0].Name != "django" || packages[0].Version != "4.2.0" {
- t.Errorf("package 0: got %s@%s, want [email protected]", packages[0].Name, packages[0].Version)
- }
- if packages[1].Name != "celery" || packages[1].Version != "5.3.1" {
- t.Errorf("package 1: got %s@%s, want [email protected]", packages[1].Name, packages[1].Version)
- }
-}
-
-func TestParseDiffForPackages_NonDepFile(t *testing.T) {
- diff := `--- a/app.py
-+++ b/app.py
-@@ -0,0 +1 @@
-+import flask`
-
- packages := ParseDiffForPackages(diff, "app.py")
- if len(packages) != 0 {
- t.Errorf("expected 0 packages for non-dep file, got %d", len(packages))
- }
-}
-
-func TestParseDiffForPackages_NoAddedLines(t *testing.T) {
- diff := `--- a/requirements.txt
-+++ b/requirements.txt
-@@ -1 +1 @@
--flask==2.3.1`
-
- packages := ParseDiffForPackages(diff, "requirements.txt")
- if len(packages) != 0 {
- t.Errorf("expected 0 packages when no added lines, got %d", len(packages))
- }
-}
-
-func TestParseDiffForPackages_RequirementsDevTxt(t *testing.T) {
- diff := `--- a/requirements-dev.txt
-+++ b/requirements-dev.txt
-@@ -0,0 +1,2 @@
-+pytest==7.4.0
-+black==23.7.0`
-
- packages := ParseDiffForPackages(diff, "requirements-dev.txt")
-
- if len(packages) != 2 {
- t.Fatalf("expected 2 packages, got %d", len(packages))
- }
- if packages[0].Ecosystem != "PyPI" {
- t.Errorf("ecosystem = %q, want PyPI", packages[0].Ecosystem)
- }
-}
-
-func TestParseDiffForPackages_RequirementsSubdir(t *testing.T) {
- diff := `--- a/requirements/base.txt
-+++ b/requirements/base.txt
-@@ -0,0 +1 @@
-+django==5.1.7`
-
- packages := ParseDiffForPackages(diff, "requirements/base.txt")
-
- if len(packages) != 1 {
- t.Fatalf("expected 1 package, got %d", len(packages))
- }
- if packages[0].Name != "django" {
- t.Errorf("name = %q, want django", packages[0].Name)
- }
- if packages[0].Ecosystem != "PyPI" {
- t.Errorf("ecosystem = %q, want PyPI", packages[0].Ecosystem)
- }
-}
-
-func TestParseDiffForPackages_SetupPy(t *testing.T) {
- diff := `--- a/setup.py
-+++ b/setup.py
-@@ -10,0 +11,2 @@
-+ "flask==2.3.0",
-+ "requests>=2.31.0",`
-
- packages := ParseDiffForPackages(diff, "setup.py")
-
- if len(packages) != 2 {
- t.Fatalf("expected 2 packages, got %d", len(packages))
- }
-}
-
-func TestGetEcosystem(t *testing.T) {
- tests := []struct {
- path string
- want string
- }{
- {"requirements.txt", "PyPI"},
- {"requirements-dev.txt", "PyPI"},
- {"requirements/base.txt", "PyPI"},
- {"pyproject.toml", "PyPI"},
- {"setup.py", "PyPI"},
- {"Pipfile", "PyPI"},
- {"package.json", "npm"},
- {"app.py", ""},
- {"unknown.txt", ""},
- }
-
- for _, tt := range tests {
- got := getEcosystem(tt.path)
- if got != tt.want {
- t.Errorf("getEcosystem(%q) = %q, want %q", tt.path, got, tt.want)
- }
- }
-}
-
-func TestExtractAddedLines(t *testing.T) {
- diff := `--- a/file
-+++ b/file
-@@ -1,2 +1,3 @@
- unchanged
--removed
-+added1
-+added2`
-
- lines := extractAddedLines(diff)
- if len(lines) != 2 {
- t.Fatalf("expected 2 added lines, got %d", len(lines))
- }
- if lines[0] != "added1" {
- t.Errorf("line 0 = %q, want %q", lines[0], "added1")
- }
- if lines[1] != "added2" {
- t.Errorf("line 1 = %q, want %q", lines[1], "added2")
- }
-}
diff --git a/cli/beacon-hooks/internal/depscan/format.go b/cli/beacon-hooks/internal/depscan/format.go
deleted file mode 100644
index 43a62d23..00000000
--- a/cli/beacon-hooks/internal/depscan/format.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package depscan
-
-import (
- "fmt"
- "strings"
-)
-
-// PackageFinding represents a deduplicated set of vulnerabilities for one package.
-type PackageFinding struct {
- Pkg DetectedPackage
- CVEs []string
- Severity string
- Summary string
- FixVersion string
-}
-
-// severityRank maps severity strings to numeric ranks for comparison.
-var severityRank = map[string]int{
- "LOW": 1,
- "MODERATE": 2,
- "HIGH": 3,
- "CRITICAL": 4,
-}
-
-// DeduplicateFindings groups vulnerabilities by package key and picks the highest
-// severity, highest fix version, and collects all CVE IDs.
-func DeduplicateFindings(pkgs []DetectedPackage, findings map[string][]OSVVulnerability) []PackageFinding {
- // Build a map from package key to the DetectedPackage
- pkgMap := make(map[string]DetectedPackage)
- for _, p := range pkgs {
- pkgMap[p.Name+"@"+p.Version] = p
- }
-
- var result []PackageFinding
-
- for key, vulns := range findings {
- pkg := pkgMap[key]
- finding := PackageFinding{Pkg: pkg}
-
- var bestRank int
- var bestFixVersion string
-
- for _, v := range vulns {
- // Collect CVE aliases
- for _, alias := range v.Aliases {
- if strings.HasPrefix(alias, "CVE-") {
- finding.CVEs = append(finding.CVEs, alias)
- }
- }
-
- // If no CVE alias, use the OSV ID
- if len(v.Aliases) == 0 || !hasCVE(v.Aliases) {
- finding.CVEs = append(finding.CVEs, v.ID)
- }
-
- // Track highest severity
- sev := strings.ToUpper(v.Severity)
- rank := severityRank[sev]
- if rank > bestRank {
- bestRank = rank
- finding.Severity = sev
- finding.Summary = v.Summary
- }
-
- // Track highest fix version
- if v.FixedVersion != "" && compareVersions(v.FixedVersion, bestFixVersion) > 0 {
- bestFixVersion = v.FixedVersion
- }
- }
-
- if finding.Severity == "" {
- finding.Severity = "UNKNOWN"
- if len(vulns) > 0 {
- finding.Summary = vulns[0].Summary
- }
- }
-
- finding.FixVersion = bestFixVersion
-
- // Deduplicate CVE IDs
- finding.CVEs = uniqueStrings(finding.CVEs)
-
- result = append(result, finding)
- }
-
- return result
-}
-
-// FormatCVEReport generates a markdown report for injection into the agent's context.
-func FormatCVEReport(findings []PackageFinding) string {
- if len(findings) == 0 {
- return ""
- }
-
- var sb strings.Builder
- sb.WriteString("## Vulnerable Dependencies Detected\n\n")
- sb.WriteString("The following dependencies have known security vulnerabilities:\n\n")
-
- for i, f := range findings {
- sb.WriteString(fmt.Sprintf("### %d. [%s] %s %s\n", i+1, f.Severity, f.Pkg.Name, f.Pkg.Version))
- sb.WriteString(fmt.Sprintf("**File:** `%s`\n", f.Pkg.FilePath))
- sb.WriteString(fmt.Sprintf("**CVEs:** %s\n\n", strings.Join(f.CVEs, ", ")))
- sb.WriteString(fmt.Sprintf("**Vulnerability:** %s\n\n", f.Summary))
-
- if f.FixVersion != "" {
- sb.WriteString(fmt.Sprintf("**Fix:** Upgrade to %s >= %s\n", f.Pkg.Name, f.FixVersion))
- }
-
- if i < len(findings)-1 {
- sb.WriteString("\n---\n\n")
- }
- }
-
- sb.WriteString("\n\n---\n\nPlease update these dependencies to non-vulnerable versions before completing the task.")
-
- return sb.String()
-}
-
-// hasCVE checks if any alias starts with "CVE-".
-func hasCVE(aliases []string) bool {
- for _, a := range aliases {
- if strings.HasPrefix(a, "CVE-") {
- return true
- }
- }
- return false
-}
-
-// uniqueStrings deduplicates a string slice preserving order.
-func uniqueStrings(ss []string) []string {
- seen := make(map[string]bool, len(ss))
- var result []string
- for _, s := range ss {
- if !seen[s] {
- seen[s] = true
- result = append(result, s)
- }
- }
- return result
-}
-
-// compareVersions does a simple string-based version comparison.
-// Returns >0 if a > b, <0 if a < b, 0 if equal.
-// Uses lexicographic comparison of dot-separated segments.
-func compareVersions(a, b string) int {
- if b == "" {
- return 1
- }
- if a == "" {
- return -1
- }
-
- partsA := strings.Split(a, ".")
- partsB := strings.Split(b, ".")
-
- maxLen := len(partsA)
- if len(partsB) > maxLen {
- maxLen = len(partsB)
- }
-
- for i := 0; i < maxLen; i++ {
- var pA, pB string
- if i < len(partsA) {
- pA = partsA[i]
- }
- if i < len(partsB) {
- pB = partsB[i]
- }
-
- // Try numeric comparison
- nA := parseNum(pA)
- nB := parseNum(pB)
- if nA != nB {
- return nA - nB
- }
- }
- return 0
-}
-
-// parseNum parses a numeric string; returns 0 for non-numeric.
-func parseNum(s string) int {
- n := 0
- for _, c := range s {
- if c >= '0' && c <= '9' {
- n = n*10 + int(c-'0')
- } else {
- break
- }
- }
- return n
-}
diff --git a/cli/beacon-hooks/internal/depscan/format_test.go b/cli/beacon-hooks/internal/depscan/format_test.go
deleted file mode 100644
index 22c084e6..00000000
--- a/cli/beacon-hooks/internal/depscan/format_test.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package depscan
-
-import (
- "strings"
- "testing"
-)
-
-func TestDeduplicateFindings(t *testing.T) {
- pkgs := []DetectedPackage{
- {Name: "jinja2", Version: "3.1.4", Ecosystem: "PyPI", FilePath: "requirements.txt"},
- }
-
- findings := map[string][]OSVVulnerability{
- {
- ID: "GHSA-abc",
- Summary: "Sandbox escape",
- Aliases: []string{"CVE-2025-27516"},
- Severity: "MODERATE",
- FixedVersion: "3.1.5",
- },
- {
- ID: "GHSA-xyz",
- Summary: "Critical issue",
- Aliases: []string{"CVE-2024-56326"},
- Severity: "HIGH",
- FixedVersion: "3.1.6",
- },
- },
- }
-
- result := DeduplicateFindings(pkgs, findings)
-
- if len(result) != 1 {
- t.Fatalf("expected 1 finding, got %d", len(result))
- }
-
- f := result[0]
- if f.Severity != "HIGH" {
- t.Errorf("severity = %q, want HIGH", f.Severity)
- }
- if f.FixVersion != "3.1.6" {
- t.Errorf("fix version = %q, want 3.1.6", f.FixVersion)
- }
- if len(f.CVEs) != 2 {
- t.Errorf("expected 2 CVEs, got %d", len(f.CVEs))
- }
- if f.Summary != "Critical issue" {
- t.Errorf("summary = %q, want %q", f.Summary, "Critical issue")
- }
-}
-
-func TestFormatCVEReport(t *testing.T) {
- findings := []PackageFinding{
- {
- Pkg: DetectedPackage{Name: "jinja2", Version: "3.1.4", FilePath: "requirements.txt"},
- CVEs: []string{"CVE-2025-27516", "CVE-2024-56326"},
- Severity: "HIGH",
- Summary: "Sandbox breakout",
- FixVersion: "3.1.6",
- },
- }
-
- report := FormatCVEReport(findings)
-
- if !strings.Contains(report, "Vulnerable Dependencies Detected") {
- t.Error("report missing header")
- }
- if !strings.Contains(report, "[HIGH] jinja2 3.1.4") {
- t.Error("report missing severity/package info")
- }
- if !strings.Contains(report, "CVE-2025-27516") {
- t.Error("report missing CVE ID")
- }
- if !strings.Contains(report, "jinja2 >= 3.1.6") {
- t.Error("report missing fix version")
- }
- if !strings.Contains(report, "Sandbox breakout") {
- t.Error("report missing summary")
- }
- if !strings.Contains(report, "Please update these dependencies") {
- t.Error("report missing footer")
- }
-}
-
-func TestFormatCVEReport_Empty(t *testing.T) {
- report := FormatCVEReport(nil)
- if report != "" {
- t.Errorf("expected empty report, got %q", report)
- }
-}
-
-func TestDeduplicateFindings_NoSeverity(t *testing.T) {
- pkgs := []DetectedPackage{
- {Name: "unknown-pkg", Version: "1.0.0", Ecosystem: "PyPI", FilePath: "requirements.txt"},
- }
-
- findings := map[string][]OSVVulnerability{
- {ID: "GHSA-xyz", Summary: "Some vuln", Severity: "", FixedVersion: "1.0.1"},
- },
- }
-
- result := DeduplicateFindings(pkgs, findings)
-
- if len(result) != 1 {
- t.Fatalf("expected 1 finding, got %d", len(result))
- }
- if result[0].Severity != "UNKNOWN" {
- t.Errorf("severity = %q, want UNKNOWN", result[0].Severity)
- }
-}
-
-func TestDeduplicateFindings_NoCVEAlias(t *testing.T) {
- pkgs := []DetectedPackage{
- {Name: "pkg", Version: "1.0.0", Ecosystem: "PyPI", FilePath: "requirements.txt"},
- }
-
- findings := map[string][]OSVVulnerability{
- {ID: "GHSA-only-id", Summary: "No CVE alias", Severity: "HIGH", Aliases: []string{}},
- },
- }
-
- result := DeduplicateFindings(pkgs, findings)
-
- if len(result) != 1 {
- t.Fatalf("expected 1 finding, got %d", len(result))
- }
- // Should fall back to OSV ID when no CVE alias exists
- if len(result[0].CVEs) != 1 || result[0].CVEs[0] != "GHSA-only-id" {
- t.Errorf("CVEs = %v, want [GHSA-only-id]", result[0].CVEs)
- }
-}
-
-func TestFormatCVEReport_NoFixVersion(t *testing.T) {
- findings := []PackageFinding{
- {
- Pkg: DetectedPackage{Name: "pkg", Version: "1.0.0", FilePath: "requirements.txt"},
- CVEs: []string{"CVE-2025-99999"},
- Severity: "HIGH",
- Summary: "A vulnerability",
- },
- }
-
- report := FormatCVEReport(findings)
-
- if strings.Contains(report, "**Fix:**") {
- t.Error("report should not contain Fix section when no fix version")
- }
- if !strings.Contains(report, "CVE-2025-99999") {
- t.Error("report missing CVE ID")
- }
-}
-
-func TestFormatCVEReport_MultipleFindings(t *testing.T) {
- findings := []PackageFinding{
- {
- Pkg: DetectedPackage{Name: "pkg1", Version: "1.0.0", FilePath: "requirements.txt"},
- CVEs: []string{"CVE-2025-00001"},
- Severity: "HIGH",
- Summary: "First vuln",
- FixVersion: "1.0.1",
- },
- {
- Pkg: DetectedPackage{Name: "pkg2", Version: "2.0.0", FilePath: "requirements.txt"},
- CVEs: []string{"CVE-2025-00002"},
- Severity: "CRITICAL",
- Summary: "Second vuln",
- FixVersion: "2.0.1",
- },
- }
-
- report := FormatCVEReport(findings)
-
- if !strings.Contains(report, "### 1.") || !strings.Contains(report, "### 2.") {
- t.Error("report should have numbered findings")
- }
- if !strings.Contains(report, "---") {
- t.Error("report should have separator between findings")
- }
-}
-
-func TestCompareVersions(t *testing.T) {
- tests := []struct {
- a, b string
- want int // >0, 0, or <0
- }{
- {"3.1.6", "3.1.5", 1},
- {"3.1.5", "3.1.6", -1},
- {"3.1.6", "3.1.6", 0},
- {"4.0.0", "3.9.9", 1},
- {"3.1.6", "", 1},
- {"", "3.1.6", -1},
- }
-
- for _, tt := range tests {
- result := compareVersions(tt.a, tt.b)
- if (tt.want > 0 && result <= 0) || (tt.want < 0 && result >= 0) || (tt.want == 0 && result != 0) {
- t.Errorf("compareVersions(%q, %q) = %d, want sign %d", tt.a, tt.b, result, tt.want)
- }
- }
-}
diff --git a/cli/beacon-hooks/internal/depscan/npm.go b/cli/beacon-hooks/internal/depscan/npm.go
deleted file mode 100644
index 8a879813..00000000
--- a/cli/beacon-hooks/internal/depscan/npm.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package depscan
-
-import (
- "regexp"
- "strings"
-)
-
-// npmDepPattern matches package.json dependency entries like:
-//
-// "express": "4.18.2"
-// "lodash": "^4.17.21"
-// "react": "~18.2.0"
-//
-// Captures: package name, optional prefix (^, ~), version
-var npmDepPattern = regexp.MustCompile(`"([a-zA-Z0-9@/._-]+)"\s*:\s*"([~^]?)(\d+\.\d+\.\d+[a-zA-Z0-9._-]*)"`)
-
-// ParsePackageJSON parses added lines from package.json for dependency entries.
-func ParsePackageJSON(addedLines []string) []DetectedPackage {
- var packages []DetectedPackage
- for _, line := range addedLines {
- line = strings.TrimSpace(line)
-
- matches := npmDepPattern.FindStringSubmatch(line)
- if matches == nil {
- continue
- }
-
- name := matches[1]
- version := matches[3] // exact version without ^ or ~
-
- packages = append(packages, DetectedPackage{
- Name: name,
- Version: version,
- })
- }
- return packages
-}
diff --git a/cli/beacon-hooks/internal/depscan/npm_test.go b/cli/beacon-hooks/internal/depscan/npm_test.go
deleted file mode 100644
index 46099f51..00000000
--- a/cli/beacon-hooks/internal/depscan/npm_test.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package depscan
-
-import (
- "testing"
-)
-
-func TestParsePackageJSON(t *testing.T) {
- lines := []string{
- ` "express": "4.18.2",`,
- ` "lodash": "^4.17.21",`,
- ` "react": "~18.2.0",`,
- ` "@types/node": "20.10.0",`,
- ` "name": "my-app",`,
- }
-
- packages := ParsePackageJSON(lines)
-
- expected := []struct {
- name, version string
- }{
- {"express", "4.18.2"},
- {"lodash", "4.17.21"},
- {"react", "18.2.0"},
- {"@types/node", "20.10.0"},
- }
-
- if len(packages) != len(expected) {
- t.Fatalf("expected %d packages, got %d: %+v", len(expected), len(packages), packages)
- }
-
- for i, exp := range expected {
- if packages[i].Name != exp.name {
- t.Errorf("package %d: name = %q, want %q", i, packages[i].Name, exp.name)
- }
- if packages[i].Version != exp.version {
- t.Errorf("package %d: version = %q, want %q", i, packages[i].Version, exp.version)
- }
- }
-}
-
-func TestParsePackageJSON_NonDepLines(t *testing.T) {
- lines := []string{
- ` "name": "my-app",`,
- ` "version": "1.0.0",`,
- ` "scripts": {`,
- ` "start": "node index.js"`,
- }
-
- packages := ParsePackageJSON(lines)
-
- // "name" and "version" at the top level shouldn't match because their values
- // are not semver-like versions (my-app is not X.Y.Z with digits)
- // Actually "version": "1.0.0" would match. That's acceptable since it's still
- // a valid version pattern.
- // The important thing is "name": "my-app" doesn't match.
- for _, p := range packages {
- if p.Name == "name" {
- t.Error("should not match 'name' field as a dependency")
- }
- if p.Name == "scripts" || p.Name == "start" {
- t.Errorf("should not match %q as a dependency", p.Name)
- }
- }
-}
diff --git a/cli/beacon-hooks/internal/depscan/osv.go b/cli/beacon-hooks/internal/depscan/osv.go
deleted file mode 100644
index 91398ae8..00000000
--- a/cli/beacon-hooks/internal/depscan/osv.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package depscan
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "strings"
- "sync"
- "time"
-
- "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
-)
-
-const (
- osvAPIURL = "https://api.osv.dev/v1/query"
- osvQueryTimeout = 10 * time.Second
-)
-
-// OSVVulnerability represents a vulnerability from OSV.dev.
-type OSVVulnerability struct {
- ID string
- Summary string
- Aliases []string
- Severity string
- FixedVersion string
-}
-
-// osvQueryRequest is the request body for OSV.dev /v1/query.
-type osvQueryRequest struct {
- Version string `json:"version"`
- Package osvPackage `json:"package"`
-}
-
-type osvPackage struct {
- Name string `json:"name"`
- Ecosystem string `json:"ecosystem"`
-}
-
-// osvQueryResponse is the response from OSV.dev /v1/query.
-type osvQueryResponse struct {
- Vulns []osvVuln `json:"vulns"`
-}
-
-type osvVuln struct {
- ID string `json:"id"`
- Summary string `json:"summary"`
- Aliases []string `json:"aliases"`
- DatabaseSpecific *osvDatabaseSpecific `json:"database_specific"`
- Affected []osvAffected `json:"affected"`
-}
-
-type osvDatabaseSpecific struct {
- Severity string `json:"severity"`
-}
-
-type osvAffected struct {
- Ranges []osvRange `json:"ranges"`
-}
-
-type osvRange struct {
- Events []osvEvent `json:"events"`
-}
-
-type osvEvent struct {
- Introduced string `json:"introduced,omitempty"`
- Fixed string `json:"fixed,omitempty"`
-}
-
-// QueryPackage queries OSV.dev for vulnerabilities affecting a single package.
-func QueryPackage(ctx context.Context, pkg DetectedPackage) ([]OSVVulnerability, error) {
- reqBody := osvQueryRequest{
- Version: pkg.Version,
- Package: osvPackage{
- Name: pkg.Name,
- Ecosystem: pkg.Ecosystem,
- },
- }
-
- data, err := json.Marshal(reqBody)
- if err != nil {
- return nil, fmt.Errorf("marshal request: %w", err)
- }
-
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, osvAPIURL, bytes.NewReader(data))
- if err != nil {
- return nil, fmt.Errorf("create request: %w", err)
- }
- req.Header.Set("Content-Type", "application/json")
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("query osv.dev: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("osv.dev returned status %d", resp.StatusCode)
- }
-
- var osvResp osvQueryResponse
- if err := json.NewDecoder(resp.Body).Decode(&osvResp); err != nil {
- return nil, fmt.Errorf("decode response: %w", err)
- }
-
- var vulns []OSVVulnerability
- for _, v := range osvResp.Vulns {
- vuln := convertVuln(v)
- // Only report HIGH and CRITICAL severity vulnerabilities
- sev := strings.ToUpper(vuln.Severity)
- if sev != "HIGH" && sev != "CRITICAL" {
- continue
- }
- vulns = append(vulns, vuln)
- }
- return vulns, nil
-}
-
-// QueryPackages queries OSV.dev for all packages in parallel with a shared timeout.
-func QueryPackages(pkgs []DetectedPackage, logger *logging.Logger) map[string][]OSVVulnerability {
- ctx, cancel := context.WithTimeout(context.Background(), osvQueryTimeout)
- defer cancel()
-
- logger.Info("OSV query started", "package_count", len(pkgs))
-
- type result struct {
- key string
- vulns []OSVVulnerability
- err error
- pkg DetectedPackage
- }
-
- results := make(chan result, len(pkgs))
- var wg sync.WaitGroup
-
- for _, pkg := range pkgs {
- wg.Add(1)
- go func(p DetectedPackage) {
- defer wg.Done()
- vulns, err := QueryPackage(ctx, p)
- results <- result{
- key: p.Name + "@" + p.Version,
- vulns: vulns,
- err: err,
- pkg: p,
- }
- }(pkg)
- }
-
- go func() {
- wg.Wait()
- close(results)
- }()
-
- findings := make(map[string][]OSVVulnerability)
- for r := range results {
- if r.err != nil {
- if ctx.Err() != nil {
- logger.Warn("OSV query timeout", "package", r.pkg.Name, "version", r.pkg.Version)
- } else {
- logger.Warn("OSV query failed", "package", r.pkg.Name, "version", r.pkg.Version, "error", r.err.Error())
- }
- continue
- }
- logger.Debug("OSV query per-package result", "package", r.pkg.Name, "version", r.pkg.Version, "vuln_count", len(r.vulns))
- if len(r.vulns) > 0 {
- findings[r.key] = r.vulns
- }
- }
-
- return findings
-}
-
-// convertVuln converts an OSV API vulnerability to our internal representation.
-func convertVuln(v osvVuln) OSVVulnerability {
- vuln := OSVVulnerability{
- ID: v.ID,
- Summary: v.Summary,
- Aliases: v.Aliases,
- }
-
- // Extract severity from database_specific (e.g. GHSA advisories)
- if v.DatabaseSpecific != nil && v.DatabaseSpecific.Severity != "" {
- vuln.Severity = v.DatabaseSpecific.Severity
- }
-
- // Extract highest fixed version from affected ranges
- for _, affected := range v.Affected {
- for _, r := range affected.Ranges {
- for _, event := range r.Events {
- if event.Fixed != "" && compareVersions(event.Fixed, vuln.FixedVersion) > 0 {
- vuln.FixedVersion = event.Fixed
- }
- }
- }
- }
-
- return vuln
-}
diff --git a/cli/beacon-hooks/internal/depscan/osv_test.go b/cli/beacon-hooks/internal/depscan/osv_test.go
deleted file mode 100644
index 798d8587..00000000
--- a/cli/beacon-hooks/internal/depscan/osv_test.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package depscan
-
-import (
- "strings"
- "testing"
-)
-
-func TestConvertVuln(t *testing.T) {
- v := osvVuln{
- ID: "GHSA-abc-123",
- Summary: "Test vulnerability",
- Aliases: []string{"CVE-2025-12345"},
- DatabaseSpecific: &osvDatabaseSpecific{
- Severity: "HIGH",
- },
- Affected: []osvAffected{
- {
- Ranges: []osvRange{
- {
- Events: []osvEvent{
- {Introduced: "0"},
- {Fixed: "3.1.6"},
- },
- },
- },
- },
- },
- }
-
- result := convertVuln(v)
-
- if result.ID != "GHSA-abc-123" {
- t.Errorf("ID = %q, want GHSA-abc-123", result.ID)
- }
- if result.Summary != "Test vulnerability" {
- t.Errorf("Summary = %q, want 'Test vulnerability'", result.Summary)
- }
- if result.Severity != "HIGH" {
- t.Errorf("Severity = %q, want HIGH", result.Severity)
- }
- if result.FixedVersion != "3.1.6" {
- t.Errorf("FixedVersion = %q, want 3.1.6", result.FixedVersion)
- }
- if len(result.Aliases) != 1 || result.Aliases[0] != "CVE-2025-12345" {
- t.Errorf("Aliases = %v, want [CVE-2025-12345]", result.Aliases)
- }
-}
-
-func TestConvertVuln_NoSeverity(t *testing.T) {
- v := osvVuln{
- ID: "GHSA-xyz",
- Summary: "No severity info",
- }
-
- result := convertVuln(v)
-
- if result.Severity != "" {
- t.Errorf("Severity = %q, want empty", result.Severity)
- }
- if result.FixedVersion != "" {
- t.Errorf("FixedVersion = %q, want empty", result.FixedVersion)
- }
-}
-
-func TestConvertVuln_NilDatabaseSpecific(t *testing.T) {
- v := osvVuln{
- ID: "GHSA-nil",
- DatabaseSpecific: nil,
- }
-
- result := convertVuln(v)
-
- if result.Severity != "" {
- t.Errorf("Severity = %q, want empty", result.Severity)
- }
-}
-
-func TestConvertVuln_MultipleFixedVersions(t *testing.T) {
- // When there are multiple fixed versions, the last one wins
- v := osvVuln{
- ID: "GHSA-multi",
- Affected: []osvAffected{
- {
- Ranges: []osvRange{
- {
- Events: []osvEvent{
- {Introduced: "0"},
- {Fixed: "3.1.5"},
- },
- },
- {
- Events: []osvEvent{
- {Introduced: "4.0.0"},
- {Fixed: "4.0.2"},
- },
- },
- },
- },
- },
- }
-
- result := convertVuln(v)
-
- if result.FixedVersion != "4.0.2" {
- t.Errorf("FixedVersion = %q, want 4.0.2", result.FixedVersion)
- }
-}
-
-func TestSeverityFilter(t *testing.T) {
- // Simulate what QueryPackage does after converting vulns
- vulns := []osvVuln{
- {ID: "v1", Summary: "Critical", DatabaseSpecific: &osvDatabaseSpecific{Severity: "CRITICAL"}},
- {ID: "v2", Summary: "High", DatabaseSpecific: &osvDatabaseSpecific{Severity: "HIGH"}},
- {ID: "v3", Summary: "Moderate", DatabaseSpecific: &osvDatabaseSpecific{Severity: "MODERATE"}},
- {ID: "v4", Summary: "Low", DatabaseSpecific: &osvDatabaseSpecific{Severity: "LOW"}},
- {ID: "v5", Summary: "No severity", DatabaseSpecific: nil},
- {ID: "v6", Summary: "Empty severity", DatabaseSpecific: &osvDatabaseSpecific{Severity: ""}},
- }
-
- var filtered []OSVVulnerability
- for _, v := range vulns {
- vuln := convertVuln(v)
- sev := strings.ToUpper(vuln.Severity)
- if sev != "HIGH" && sev != "CRITICAL" {
- continue
- }
- filtered = append(filtered, vuln)
- }
-
- if len(filtered) != 2 {
- t.Fatalf("expected 2 filtered vulns, got %d", len(filtered))
- }
- if filtered[0].ID != "v1" {
- t.Errorf("filtered[0].ID = %q, want v1", filtered[0].ID)
- }
- if filtered[1].ID != "v2" {
- t.Errorf("filtered[1].ID = %q, want v2", filtered[1].ID)
- }
-}
diff --git a/cli/beacon-hooks/internal/depscan/pypi.go b/cli/beacon-hooks/internal/depscan/pypi.go
deleted file mode 100644
index 02442ca2..00000000
--- a/cli/beacon-hooks/internal/depscan/pypi.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package depscan
-
-import (
- "regexp"
- "strings"
-)
-
-// requirementPattern matches pip requirement specifiers like:
-//
-// pkg==1.2.3, pkg>=1.2.3, pkg~=1.2.3, pkg<=1.2.3
-var requirementPattern = regexp.MustCompile(`^\s*([a-zA-Z0-9][a-zA-Z0-9._-]*)\s*(?:==|>=|~=|<=)\s*([0-9][0-9a-zA-Z.*-]*)\s*(?:[;#].*)?$`)
-
-// ParseRequirementsTxt parses added lines from requirements.txt, setup.py, or Pipfile
-// for package==version patterns.
-func ParseRequirementsTxt(addedLines []string) []DetectedPackage {
- var packages []DetectedPackage
- for _, line := range addedLines {
- line = strings.TrimSpace(line)
-
- // Strip inline comments before processing
- if idx := strings.Index(line, "#"); idx >= 0 {
- line = strings.TrimSpace(line[:idx])
- }
-
- // Skip empty lines and options (like -r, --index-url)
- if line == "" || strings.HasPrefix(line, "-") {
- continue
- }
-
- // For Pipfile lines like: pkg = "==1.2.3"
- if strings.Contains(line, `= "`) {
- line = parsePipfileLine(line)
- if line == "" {
- continue
- }
- }
-
- matches := requirementPattern.FindStringSubmatch(line)
- if matches == nil {
- continue
- }
-
- packages = append(packages, DetectedPackage{
- Name: normalizePackageName(matches[1]),
- Version: matches[2],
- })
- }
- return packages
-}
-
-// pyprojectDepPattern matches dependency entries in pyproject.toml like:
-//
-// "jinja2>=3.1.4", "requests==2.31.0",
-var pyprojectDepPattern = regexp.MustCompile(`"([a-zA-Z0-9][a-zA-Z0-9._-]*)\s*(?:==|>=|~=|<=)\s*([0-9][0-9a-zA-Z.*-]*)"`)
-
-// ParsePyprojectToml parses added lines from pyproject.toml for dependency entries.
-func ParsePyprojectToml(addedLines []string) []DetectedPackage {
- var packages []DetectedPackage
- for _, line := range addedLines {
- matches := pyprojectDepPattern.FindAllStringSubmatch(line, -1)
- for _, match := range matches {
- packages = append(packages, DetectedPackage{
- Name: normalizePackageName(match[1]),
- Version: match[2],
- })
- }
- }
- return packages
-}
-
-// normalizePackageName normalizes a Python package name (PEP 503).
-// Replaces hyphens and dots with underscores and lowercases.
-func normalizePackageName(name string) string {
- name = strings.ToLower(name)
- name = strings.ReplaceAll(name, "-", "_")
- name = strings.ReplaceAll(name, ".", "_")
- return name
-}
-
-// parsePipfileLine converts a Pipfile line like `pkg = "==1.2.3"` to `pkg==1.2.3`.
-func parsePipfileLine(line string) string {
- parts := strings.SplitN(line, "=", 2)
- if len(parts) != 2 {
- return ""
- }
- pkg := strings.TrimSpace(parts[0])
- version := strings.TrimSpace(parts[1])
- // Remove surrounding quotes
- version = strings.Trim(version, `"'`)
- if version == "*" || version == "" {
- return ""
- }
- return pkg + version
-}
diff --git a/cli/beacon-hooks/internal/depscan/pypi_test.go b/cli/beacon-hooks/internal/depscan/pypi_test.go
deleted file mode 100644
index c51c6b94..00000000
--- a/cli/beacon-hooks/internal/depscan/pypi_test.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package depscan
-
-import (
- "testing"
-)
-
-func TestParseRequirementsTxt(t *testing.T) {
- lines := []string{
- "flask==2.3.2",
- "jinja2==3.1.4",
- "requests>=2.31.0",
- "Django~=4.2.0",
- "# comment line",
- "",
- "-r base.txt",
- " gunicorn==21.2.0 # with comment",
- "numpy<=1.26.0 ; python_version >= '3.9'",
- }
-
- packages := ParseRequirementsTxt(lines)
-
- expected := []struct {
- name, version string
- }{
- {"flask", "2.3.2"},
- {"jinja2", "3.1.4"},
- {"requests", "2.31.0"},
- {"django", "4.2.0"},
- {"gunicorn", "21.2.0"},
- {"numpy", "1.26.0"},
- }
-
- if len(packages) != len(expected) {
- t.Fatalf("expected %d packages, got %d: %+v", len(expected), len(packages), packages)
- }
-
- for i, exp := range expected {
- if packages[i].Name != exp.name {
- t.Errorf("package %d: name = %q, want %q", i, packages[i].Name, exp.name)
- }
- if packages[i].Version != exp.version {
- t.Errorf("package %d: version = %q, want %q", i, packages[i].Version, exp.version)
- }
- }
-}
-
-func TestParseRequirementsTxt_PipfileFormat(t *testing.T) {
- lines := []string{
- `flask = "==2.3.2"`,
- `requests = "*"`,
- }
-
- packages := ParseRequirementsTxt(lines)
-
- if len(packages) != 1 {
- t.Fatalf("expected 1 package, got %d", len(packages))
- }
- if packages[0].Name != "flask" || packages[0].Version != "2.3.2" {
- t.Errorf("got %s@%s, want [email protected]", packages[0].Name, packages[0].Version)
- }
-}
-
-func TestParsePyprojectToml(t *testing.T) {
- lines := []string{
- ` "django>=4.2.0",`,
- ` "celery==5.3.1",`,
- ` "redis>=4.0.0",`,
- `[tool.ruff]`,
- `line-length = 88`,
- }
-
- packages := ParsePyprojectToml(lines)
-
- if len(packages) != 3 {
- t.Fatalf("expected 3 packages, got %d", len(packages))
- }
-
- expected := []struct {
- name, version string
- }{
- {"django", "4.2.0"},
- {"celery", "5.3.1"},
- {"redis", "4.0.0"},
- }
-
- for i, exp := range expected {
- if packages[i].Name != exp.name {
- t.Errorf("package %d: name = %q, want %q", i, packages[i].Name, exp.name)
- }
- if packages[i].Version != exp.version {
- t.Errorf("package %d: version = %q, want %q", i, packages[i].Version, exp.version)
- }
- }
-}
-
-func TestNormalizePackageName(t *testing.T) {
- tests := []struct {
- input, want string
- }{
- {"Flask", "flask"},
- {"Jinja2", "jinja2"},
- {"my-package", "my_package"},
- {"some.pkg", "some_pkg"},
- {"My-Cool.Package", "my_cool_package"},
- }
-
- for _, tt := range tests {
- got := normalizePackageName(tt.input)
- if got != tt.want {
- t.Errorf("normalizePackageName(%q) = %q, want %q", tt.input, got, tt.want)
- }
- }
-}
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 78edc9b7..3bf85004 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -157,6 +157,97 @@ func (l *Logger) writeEndpointEvent(entry map[string]interface{}) {
_, _ = f.Write(append(data, '\n'))
}
+func (l *Logger) EndpointEvent(action, category, severity, message string, fields map[string]interface{}) {
+ path := endpointLogPath()
+ if path == "" {
+ return
+ }
+ if severity == "" {
+ severity = "info"
+ }
+ event := l.baseEndpointEvent(action, category, severity, message)
+ for key, value := range fields {
+ if value == nil {
+ continue
+ }
+ event[key] = value
+ }
+ retention := string(config.ContentRetentionMode())
+ if retention == "" {
+ retention = "metadata"
+ }
+ event["content"] = map[string]interface{}{
+ "retention": retention,
+ "included": retention != "metadata",
+ "redacted": retention == "redacted",
+ }
+ if raw, ok := event["raw"].(map[string]interface{}); ok {
+ event["raw"] = retentionAwareRaw(raw, retention)
+ }
+ writeEndpointJSON(path, event)
+}
+
+func (l *Logger) baseEndpointEvent(action, category, severity, message string) map[string]interface{} {
+ hostname, _ := os.Hostname()
+ 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,
+ "endpoint": map[string]interface{}{
+ "hostname": hostname,
+ "os": runtime.GOOS,
+ },
+ "user": map[string]interface{}{
+ "name": os.Getenv("USER"),
+ },
+ "harness": map[string]interface{}{
+ "name": l.platform,
+ },
+ "message": redactEndpointString(truncateEndpoint(message, 4096)),
+ }
+ if l.sessionID != "" {
+ event["session"] = map[string]interface{}{"id": l.sessionID}
+ }
+ return event
+}
+
+func writeEndpointJSON(path string, event map[string]interface{}) {
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return
+ }
+ data, err := json.Marshal(sanitizeEndpointMap(event))
+ if err != nil {
+ return
+ }
+ if len(data) > 64*1024 {
+ event["field_truncated"] = true
+ event["raw"] = nil
+ event["message"] = truncateEndpoint(fmt.Sprint(event["message"]), 1024)
+ data, err = json.Marshal(sanitizeEndpointMap(event))
+ if err != nil {
+ return
+ }
+ }
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ return
+ }
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
+ _ = f.Close()
+ return
+ }
+ defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+ defer f.Close()
+ _, _ = f.Write(append(data, '\n'))
+}
+
func endpointAction(hookName string, entry map[string]interface{}) (action, severity string) {
message := strings.ToLower(fmt.Sprint(entry["message"]))
switch hookName {
@@ -211,6 +302,47 @@ func redactEndpointString(value string) string {
return value
}
+func retentionAwareRaw(raw map[string]interface{}, retention string) map[string]interface{} {
+ if retention != "metadata" {
+ return raw
+ }
+ return map[string]interface{}{"field_count": len(raw)}
+}
+
+func sanitizeEndpointMap(input map[string]interface{}) map[string]interface{} {
+ out := make(map[string]interface{}, len(input))
+ for key, value := range input {
+ switch typed := value.(type) {
+ case string:
+ out[key] = redactEndpointString(truncateEndpoint(typed, 4096))
+ case map[string]interface{}:
+ out[key] = sanitizeEndpointMap(typed)
+ case []interface{}:
+ out[key] = sanitizeEndpointSlice(typed)
+ default:
+ out[key] = typed
+ }
+ }
+ return out
+}
+
+func sanitizeEndpointSlice(input []interface{}) []interface{} {
+ out := make([]interface{}, len(input))
+ for i, value := range input {
+ switch typed := value.(type) {
+ case string:
+ out[i] = redactEndpointString(truncateEndpoint(typed, 4096))
+ case map[string]interface{}:
+ out[i] = sanitizeEndpointMap(typed)
+ case []interface{}:
+ out[i] = sanitizeEndpointSlice(typed)
+ default:
+ out[i] = typed
+ }
+ }
+ return out
+}
+
func truncateEndpoint(value string, limit int) string {
if len(value) <= limit {
return value
diff --git a/cli/beacon-hooks/internal/state/state.go b/cli/beacon-hooks/internal/state/state.go
index b1cb8057..6b623553 100644
--- a/cli/beacon-hooks/internal/state/state.go
+++ b/cli/beacon-hooks/internal/state/state.go
@@ -34,9 +34,6 @@ type SessionData struct {
SbdPolicies string `json:"sbd_policies,omitempty"`
SbdGenerationID string `json:"sbd_generation_id,omitempty"`
SbdInjected bool `json:"sbd_injected,omitempty"`
-
- // Dep scan: CVE report pending delivery via stop hook
- DepScanReport string `json:"dep_scan_report,omitempty"`
}
// SessionState manages session state
@@ -248,38 +245,6 @@ func (s *SessionState) MarkSbdInjected() {
s.saveStateFile(state)
}
-// SetDepScanReport appends a CVE report for delivery via the stop hook.
-// Multiple reports (from editing multiple dep files in one turn) are joined.
-func (s *SessionState) SetDepScanReport(report string) {
- stateMutex.Lock()
- defer stateMutex.Unlock()
-
- state := s.loadStateFile()
- s.ensureSession(state)
- existing := state[s.sessionID].DepScanReport
- if existing != "" {
- state[s.sessionID].DepScanReport = existing + "\n\n" + report
- } else {
- state[s.sessionID].DepScanReport = report
- }
- s.saveStateFile(state)
-}
-
-// GetAndClearDepScanReport retrieves and clears any pending dep scan report.
-func (s *SessionState) GetAndClearDepScanReport() string {
- stateMutex.Lock()
- defer stateMutex.Unlock()
-
- state := s.loadStateFile()
- s.ensureSession(state)
- report := state[s.sessionID].DepScanReport
- if report != "" {
- state[s.sessionID].DepScanReport = ""
- s.saveStateFile(state)
- }
- return report
-}
-
// CleanupStaleForPlatform removes stale evaluations for the given platform
func CleanupStaleForPlatform(platform string) int {
stateMutex.Lock()
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index b85e1454..c36d96f4 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -20,19 +20,20 @@ import (
)
var endpointOpts struct {
- userMode bool
- logPath string
- harnesses string
- outputDir string
- jsonOutput bool
- grpcPort int
- httpPort int
- collectorPath string
- keepLogs bool
- keepConfig bool
- noStart bool
- coworkHeaders string
- hookLevel string
+ userMode bool
+ logPath string
+ harnesses string
+ outputDir string
+ jsonOutput bool
+ grpcPort int
+ httpPort int
+ collectorPath string
+ keepLogs bool
+ keepConfig bool
+ noStart bool
+ coworkHeaders string
+ hookLevel string
+ contentRetention string
}
var endpointCmd = &cobra.Command{
@@ -231,10 +232,12 @@ func init() {
endpointInstallCmd.Flags().IntVar(&endpointOpts.httpPort, "otlp-http-port", endpointconfig.DefaultHTTPPort, "Local OTLP HTTP port")
endpointInstallCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to an otelcol or otelcol-contrib binary")
endpointInstallCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the launchd service")
+ endpointInstallCmd.Flags().StringVar(&endpointOpts.contentRetention, "content-retention", "metadata", "Content retention mode: metadata, redacted, or full")
endpointRepairCmd.Flags().StringVar(&endpointOpts.harnesses, "harness", "claude,codex", "Comma-separated harnesses to configure")
endpointRepairCmd.Flags().IntVar(&endpointOpts.grpcPort, "otlp-grpc-port", endpointconfig.DefaultGRPCPort, "Local OTLP gRPC port")
endpointRepairCmd.Flags().IntVar(&endpointOpts.httpPort, "otlp-http-port", endpointconfig.DefaultHTTPPort, "Local OTLP HTTP port")
endpointRepairCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to a beacon-otelcol binary")
+ endpointRepairCmd.Flags().StringVar(&endpointOpts.contentRetention, "content-retention", "metadata", "Content retention mode: metadata, redacted, or full")
endpointDiscoverCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print discovery as JSON")
endpointStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")
@@ -338,13 +341,14 @@ func runEndpointWazuhValidate(cmd *cobra.Command, args []string) error {
func runEndpointInstall(cmd *cobra.Command, args []string) error {
result, err := lifecycle.Install(lifecycle.InstallOptions{
- UserMode: endpointOpts.userMode,
- LogPath: endpointOpts.logPath,
- Harnesses: splitCSV(endpointOpts.harnesses),
- GRPCPort: endpointOpts.grpcPort,
- HTTPPort: endpointOpts.httpPort,
- CollectorPath: endpointOpts.collectorPath,
- StartService: !endpointOpts.noStart,
+ UserMode: endpointOpts.userMode,
+ LogPath: endpointOpts.logPath,
+ Harnesses: splitCSV(endpointOpts.harnesses),
+ GRPCPort: endpointOpts.grpcPort,
+ HTTPPort: endpointOpts.httpPort,
+ CollectorPath: endpointOpts.collectorPath,
+ StartService: !endpointOpts.noStart,
+ ContentRetention: endpointconfig.ContentRetention(endpointOpts.contentRetention),
})
if err != nil {
return err
@@ -454,13 +458,14 @@ func runEndpointUninstall(cmd *cobra.Command, args []string) error {
func runEndpointRepair(cmd *cobra.Command, args []string) error {
result, err := lifecycle.Repair(lifecycle.InstallOptions{
- UserMode: endpointOpts.userMode,
- LogPath: endpointOpts.logPath,
- Harnesses: splitCSV(endpointOpts.harnesses),
- GRPCPort: endpointOpts.grpcPort,
- HTTPPort: endpointOpts.httpPort,
- CollectorPath: endpointOpts.collectorPath,
- StartService: !endpointOpts.noStart,
+ UserMode: endpointOpts.userMode,
+ LogPath: endpointOpts.logPath,
+ Harnesses: splitCSV(endpointOpts.harnesses),
+ GRPCPort: endpointOpts.grpcPort,
+ HTTPPort: endpointOpts.httpPort,
+ CollectorPath: endpointOpts.collectorPath,
+ StartService: !endpointOpts.noStart,
+ ContentRetention: endpointconfig.ContentRetention(endpointOpts.contentRetention),
})
if err != nil {
return err
diff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.go
index e8a061ad..f326def8 100644
--- a/cli/beacon/internal/endpoint/collector/collector.go
+++ b/cli/beacon/internal/endpoint/collector/collector.go
@@ -68,6 +68,7 @@ exporters:
max_event_bytes: 65536
rotate_bytes: 10485760
redact_secrets: true
+ content_retention: %q
extensions:
health_check:
@@ -88,7 +89,7 @@ service:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [beaconjson]
-`, cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, cfg.LogPath)
+`, cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, cfg.LogPath, cfg.ContentRetention)
}
func CheckStatus(cfg endpointconfig.Config) Status {
diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.go
index 6d65555f..eb2f8f59 100644
--- a/cli/beacon/internal/endpoint/config/config.go
+++ b/cli/beacon/internal/endpoint/config/config.go
@@ -2,6 +2,7 @@ package config
import (
"encoding/json"
+ "fmt"
"os"
"path/filepath"
)
@@ -13,12 +14,21 @@ const (
DefaultHTTPPort = 4318
)
+type ContentRetention string
+
+const (
+ ContentRetentionMetadata ContentRetention = "metadata"
+ ContentRetentionRedacted ContentRetention = "redacted"
+ ContentRetentionFull ContentRetention = "full"
+)
+
type Config struct {
- UserMode bool `json:"user_mode"`
- LogPath string `json:"log_path"`
- Collector Collector `json:"collector"`
- Harnesses []string `json:"harnesses"`
- EventCategories []string `json:"event_categories,omitempty"`
+ UserMode bool `json:"user_mode"`
+ LogPath string `json:"log_path"`
+ Collector Collector `json:"collector"`
+ Harnesses []string `json:"harnesses"`
+ EventCategories []string `json:"event_categories,omitempty"`
+ ContentRetention ContentRetention `json:"content_retention"`
}
type Collector struct {
@@ -32,9 +42,10 @@ type Collector struct {
func Default(userMode bool, logPath string) Config {
base := BaseDir(userMode)
return Config{
- UserMode: userMode,
- LogPath: logPath,
- Harnesses: []string{"claude", "codex"},
+ UserMode: userMode,
+ LogPath: logPath,
+ Harnesses: []string{"claude", "codex"},
+ ContentRetention: ContentRetentionMetadata,
Collector: Collector{
ConfigPath: filepath.Join(base, "otelcol.yaml"),
GRPCPort: DefaultGRPCPort,
@@ -76,10 +87,22 @@ func Load(userMode bool) (Config, error) {
if err := json.Unmarshal(data, &cfg); err != nil {
return Config{}, err
}
+ if cfg.ContentRetention == "" {
+ cfg.ContentRetention = ContentRetentionMetadata
+ }
+ if err := ValidateContentRetention(cfg.ContentRetention); err != nil {
+ return Config{}, err
+ }
return cfg, nil
}
func Save(cfg Config) (string, error) {
+ if cfg.ContentRetention == "" {
+ cfg.ContentRetention = ContentRetentionMetadata
+ }
+ if err := ValidateContentRetention(cfg.ContentRetention); err != nil {
+ return "", err
+ }
path := ConfigPath(cfg.UserMode)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return "", err
@@ -90,3 +113,12 @@ func Save(cfg Config) (string, error) {
}
return path, os.WriteFile(path, data, 0644)
}
+
+func ValidateContentRetention(mode ContentRetention) error {
+ switch mode {
+ case "", ContentRetentionMetadata, ContentRetentionRedacted, ContentRetentionFull:
+ return nil
+ default:
+ return fmt.Errorf("content retention must be metadata, redacted, or full")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/config/config_test.go b/cli/beacon/internal/endpoint/config/config_test.go
index bd8c4a6f..a8123768 100644
--- a/cli/beacon/internal/endpoint/config/config_test.go
+++ b/cli/beacon/internal/endpoint/config/config_test.go
@@ -27,6 +27,9 @@ func TestDefaultUserConfigUsesHomeScopedPaths(t *testing.T) {
if len(cfg.Harnesses) != 2 || cfg.Harnesses[0] != "claude" || cfg.Harnesses[1] != "codex" {
t.Fatalf("unexpected default harnesses: %#v", cfg.Harnesses)
}
+ if cfg.ContentRetention != ContentRetentionMetadata {
+ t.Fatalf("ContentRetention = %q, want %q", cfg.ContentRetention, ContentRetentionMetadata)
+ }
}
func TestSaveLoadRoundTrip(t *testing.T) {
@@ -37,6 +40,7 @@ func TestSaveLoadRoundTrip(t *testing.T) {
cfg := Default(true, logPath)
cfg.Collector.BinaryPath = filepath.Join(home, "bin", "otelcol")
cfg.EventCategories = []string{"tool", "session"}
+ cfg.ContentRetention = ContentRetentionRedacted
path, err := Save(cfg)
if err != nil {
@@ -59,6 +63,9 @@ func TestSaveLoadRoundTrip(t *testing.T) {
if len(loaded.EventCategories) != 2 || loaded.EventCategories[1] != "session" {
t.Fatalf("EventCategories did not round-trip: %#v", loaded.EventCategories)
}
+ if loaded.ContentRetention != ContentRetentionRedacted {
+ t.Fatalf("ContentRetention = %q, want %q", loaded.ContentRetention, ContentRetentionRedacted)
+ }
}
func TestLoadRejectsCorruptJSON(t *testing.T) {
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index aed041c4..c8782c5c 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -19,13 +19,14 @@ import (
)
type InstallOptions struct {
- UserMode bool
- LogPath string
- Harnesses []string
- GRPCPort int
- HTTPPort int
- CollectorPath string
- StartService bool
+ UserMode bool
+ LogPath string
+ Harnesses []string
+ GRPCPort int
+ HTTPPort int
+ CollectorPath string
+ StartService bool
+ ContentRetention endpointconfig.ContentRetention
}
type UninstallOptions struct {
@@ -202,6 +203,9 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {
cfg.Collector.HTTPPort = opts.HTTPPort
}
cfg.Collector.BinaryPath = opts.CollectorPath
+ if opts.ContentRetention != "" {
+ cfg.ContentRetention = opts.ContentRetention
+ }
return cfg
}
@@ -219,6 +223,9 @@ func loadOrDefault(userMode bool, logPath string) endpointconfig.Config {
}
func preflight(cfg endpointconfig.Config) error {
+ if err := endpointconfig.ValidateContentRetention(cfg.ContentRetention); err != nil {
+ return err
+ }
if runtime.GOOS != "darwin" {
return fmt.Errorf("production endpoint install is currently supported only on macOS")
}
diff --git a/cli/beacon/internal/endpoint/schema/event.go b/cli/beacon/internal/endpoint/schema/event.go
index e1f45b04..95294588 100644
--- a/cli/beacon/internal/endpoint/schema/event.go
+++ b/cli/beacon/internal/endpoint/schema/event.go
@@ -58,6 +58,31 @@ type ToolInfo struct {
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"`
+}
+
+type CommandInfo struct {
+ Command string `json:"command,omitempty"`
+ ExitCode *int `json:"exit_code,omitempty"`
+ DurationMS int64 `json:"duration_ms,omitempty"`
+}
+
+type MCPInfo struct {
+ Server string `json:"server,omitempty"`
+ Tool string `json:"tool,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"`
@@ -66,6 +91,13 @@ type PolicyInfo struct {
Reason string `json:"reason,omitempty"`
}
+type ContentInfo struct {
+ Retention string `json:"retention"`
+ Included bool `json:"included"`
+ Redacted bool `json:"redacted,omitempty"`
+ Truncated bool `json:"truncated,omitempty"`
+}
+
type DestinationInfo struct {
Type string `json:"type,omitempty"`
Mode string `json:"mode,omitempty"`
@@ -90,9 +122,17 @@ type Event struct {
Harness HarnessInfo `json:"harness"`
Session *SessionInfo `json:"session,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"`
+ Content *ContentInfo `json:"content,omitempty"`
Destination *DestinationInfo `json:"destination,omitempty"`
Health *HealthInfo `json:"health,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"`
diff --git a/cli/beacon/internal/endpoint/schema/event_test.go b/cli/beacon/internal/endpoint/schema/event_test.go
index 4e0f7456..2a8d81e6 100644
--- a/cli/beacon/internal/endpoint/schema/event_test.go
+++ b/cli/beacon/internal/endpoint/schema/event_test.go
@@ -34,6 +34,13 @@ func TestNewEventSetsRequiredInvariants(t *testing.T) {
if _, err := time.Parse(time.RFC3339, event.Timestamp); err != nil {
t.Fatalf("timestamp is not RFC3339: %q", event.Timestamp)
}
+ event.File = &FileInfo{Path: "main.go", Operation: "modify"}
+ event.Command = &CommandInfo{Command: "go test ./..."}
+ event.MCP = &MCPInfo{Server: "github", Tool: "get_issue"}
+ event.Content = &ContentInfo{Retention: "metadata", Included: false}
+ if err := event.Validate(); err != nil {
+ t.Fatalf("Validate rejected optional telemetry fields: %v", err)
+ }
}
func TestValidateRejectsMissingOrInvalidRequiredFields(t *testing.T) {
diff --git a/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml b/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml
index 73a6e94b..0273cf9e 100644
--- a/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml
+++ b/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml
@@ -15,13 +15,13 @@
<rule id="100520" level="7">
<if_sid>100500</if_sid>
- <field name="event.action">runtime.mode_disallowed</field>
- <description>AI agent runtime launched in a disallowed mode</description>
+ <field name="event.action">command.executed|mcp.tool_invoked</field>
+ <description>AI agent runtime performed command or MCP tool action</description>
</rule>
<rule id="100530" level="10">
<if_sid>100500</if_sid>
- <field name="policy.decision">block</field>
+ <field name="event.action">approval.denied|policy.blocked</field>
<description>AI agent runtime policy block</description>
</rule>
@@ -30,4 +30,16 @@
<field name="event.action">endpoint.tamper_detected|endpoint.health_failed</field>
<description>Beacon endpoint tamper or health failure detected</description>
</rule>
+
+ <rule id="100550" level="5">
+ <if_sid>100500</if_sid>
+ <field name="event.action">prompt.submitted|tool.invoked|tool.completed|file.read|file.modified</field>
+ <description>AI agent runtime workflow telemetry</description>
+ </rule>
+
+ <rule id="100560" level="9">
+ <if_sid>100500</if_sid>
+ <field name="event.action">tool.failed</field>
+ <description>AI agent runtime tool failure</description>
+ </rule>
</group>
diff --git a/cli/beacon/internal/endpoint/wazuh/wazuh_test.go b/cli/beacon/internal/endpoint/wazuh/wazuh_test.go
index f2e4a087..9ec8dd42 100644
--- a/cli/beacon/internal/endpoint/wazuh/wazuh_test.go
+++ b/cli/beacon/internal/endpoint/wazuh/wazuh_test.go
@@ -28,3 +28,16 @@ func TestInstallPackWritesExpectedFiles(t *testing.T) {
}
}
}
+
+func TestRulesCoverAgentWorkflowActions(t *testing.T) {
+ rules := mustRead("pack/beacon-rules.xml")
+ for _, action := range []string{"command.executed", "mcp.tool_invoked", "tool.failed"} {
+ if !strings.Contains(rules, action) {
+ t.Fatalf("rules missing action %s", action)
+ }
+ }
+ sample := mustRead("pack/sample-event.jsonl")
+ if !strings.Contains(sample, `"content":{"retention":"metadata","included":false}`) {
+ t.Fatalf("sample event missing metadata retention: %s", sample)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index 18f0ccd4..e83e77b3 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -121,6 +121,12 @@ func SanitizeEvent(event schema.Event, maxBytes int) schema.Event {
event.Tool.Command = redact(truncate(event.Tool.Command, 4096))
event.Tool.Path = truncate(event.Tool.Path, 2048)
}
+ if event.Command != nil {
+ event.Command.Command = redact(truncate(event.Command.Command, 4096))
+ }
+ if event.Approval != nil {
+ event.Approval.Reason = redact(truncate(event.Approval.Reason, 4096))
+ }
if event.Policy != nil {
event.Policy.Reason = redact(truncate(event.Policy.Reason, 4096))
}
diff --git a/collector-builder/exporter/beaconjsonexporter/config.go b/collector-builder/exporter/beaconjsonexporter/config.go
new file mode 100644
index 00000000..98f54834
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/config.go
@@ -0,0 +1,44 @@
+package beaconjsonexporter
+
+import "fmt"
+
+const (
+ defaultMaxEventBytes = 64 * 1024
+ defaultRotateBytes = 10 * 1024 * 1024
+)
+
+// Config controls local JSONL export for Beacon endpoint events.
+type Config struct {
+ Path string `mapstructure:"path"`
+ MaxEventBytes int `mapstructure:"max_event_bytes"`
+ RotateBytes int64 `mapstructure:"rotate_bytes"`
+ RedactSecrets bool `mapstructure:"redact_secrets"`
+ ContentRetention string `mapstructure:"content_retention"`
+}
+
+func createDefaultConfig() *Config {
+ return &Config{
+ MaxEventBytes: defaultMaxEventBytes,
+ RotateBytes: defaultRotateBytes,
+ RedactSecrets: true,
+ ContentRetention: "metadata",
+ }
+}
+
+func (c *Config) Validate() error {
+ if c.Path == "" {
+ return fmt.Errorf("path is required")
+ }
+ if c.MaxEventBytes <= 0 {
+ return fmt.Errorf("max_event_bytes must be positive")
+ }
+ if c.RotateBytes < 0 {
+ return fmt.Errorf("rotate_bytes cannot be negative")
+ }
+ switch c.ContentRetention {
+ case "", "metadata", "redacted", "full":
+ return nil
+ default:
+ return fmt.Errorf("content_retention must be metadata, redacted, or full")
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/event.go b/collector-builder/exporter/beaconjsonexporter/event.go
new file mode 100644
index 00000000..a52e25fa
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/event.go
@@ -0,0 +1,136 @@
+package beaconjsonexporter
+
+import (
+ "os"
+ "runtime"
+ "time"
+)
+
+const (
+ vendor = "beacon"
+ product = "endpoint-agent"
+ schemaVersion = "1.0"
+)
+
+type eventInfo struct {
+ Kind string `json:"kind"`
+ Action string `json:"action"`
+ Category string `json:"category,omitempty"`
+}
+
+type endpointInfo struct {
+ Hostname string `json:"hostname,omitempty"`
+ OS string `json:"os"`
+}
+
+type userInfo struct {
+ Name string `json:"name,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"`
+}
+
+type sessionInfo struct {
+ ID string `json:"id,omitempty"`
+ WorkingDirectory string `json:"working_directory,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"`
+}
+
+type commandInfo struct {
+ Command string `json:"command,omitempty"`
+ ExitCode *int `json:"exit_code,omitempty"`
+ DurationMS int64 `json:"duration_ms,omitempty"`
+}
+
+type mcpInfo struct {
+ Server string `json:"server,omitempty"`
+ Tool string `json:"tool,omitempty"`
+}
+
+type approvalInfo struct {
+ Required bool `json:"required,omitempty"`
+ Decision string `json:"decision,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+type contentInfo struct {
+ Retention string `json:"retention"`
+ Included bool `json:"included"`
+ Redacted bool `json:"redacted,omitempty"`
+ Truncated bool `json:"truncated,omitempty"`
+}
+
+type beaconEvent struct {
+ Timestamp string `json:"timestamp"`
+ Vendor string `json:"vendor"`
+ Product string `json:"product"`
+ SchemaVersion string `json:"schema_version"`
+ Event eventInfo `json:"event"`
+ Severity string `json:"severity"`
+ Endpoint endpointInfo `json:"endpoint"`
+ User userInfo `json:"user,omitempty"`
+ Harness harnessInfo `json:"harness"`
+ Session *sessionInfo `json:"session,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"`
+ Content *contentInfo `json:"content,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"`
+}
+
+func newBeaconEvent(action, category, severity, harnessName string, ts time.Time) beaconEvent {
+ if ts.IsZero() {
+ ts = time.Now().UTC()
+ }
+ if severity == "" {
+ severity = "info"
+ }
+ if harnessName == "" {
+ harnessName = "unknown"
+ }
+ hostname, _ := os.Hostname()
+ return beaconEvent{
+ Timestamp: ts.UTC().Format(time.RFC3339),
+ Vendor: vendor,
+ Product: product,
+ SchemaVersion: schemaVersion,
+ Event: eventInfo{
+ Kind: "agent_runtime",
+ Action: action,
+ Category: category,
+ },
+ Severity: severity,
+ Endpoint: endpointInfo{
+ Hostname: hostname,
+ OS: runtime.GOOS,
+ },
+ User: userInfo{
+ Name: os.Getenv("USER"),
+ },
+ Harness: harnessInfo{Name: harnessName},
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/exporter.go b/collector-builder/exporter/beaconjsonexporter/exporter.go
new file mode 100644
index 00000000..2d56012b
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/exporter.go
@@ -0,0 +1,342 @@
+package beaconjsonexporter
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "go.opentelemetry.io/collector/component"
+ "go.opentelemetry.io/collector/exporter"
+ "go.opentelemetry.io/collector/pdata/pcommon"
+ "go.opentelemetry.io/collector/pdata/plog"
+ "go.opentelemetry.io/collector/pdata/pmetric"
+ "go.opentelemetry.io/collector/pdata/ptrace"
+ "go.uber.org/zap"
+)
+
+type beaconExporter struct {
+ cfg *Config
+ writer jsonlWriter
+ logger *zap.Logger
+}
+
+func newExporter(raw component.Config, set exporter.Settings) (*beaconExporter, error) {
+ cfg, ok := raw.(*Config)
+ if !ok {
+ return nil, fmt.Errorf("unexpected config type %T", raw)
+ }
+ if cfg.MaxEventBytes == 0 {
+ cfg.MaxEventBytes = defaultMaxEventBytes
+ }
+ if cfg.RotateBytes == 0 {
+ cfg.RotateBytes = defaultRotateBytes
+ }
+ if cfg.ContentRetention == "" {
+ cfg.ContentRetention = "metadata"
+ }
+ if err := cfg.Validate(); err != nil {
+ return nil, err
+ }
+ return &beaconExporter{
+ cfg: cfg,
+ writer: jsonlWriter{
+ path: cfg.Path,
+ maxEventBytes: cfg.MaxEventBytes,
+ rotateBytes: cfg.RotateBytes,
+ redactSecrets: cfg.RedactSecrets,
+ },
+ logger: set.Logger,
+ }, nil
+}
+
+func (e *beaconExporter) consumeLogs(ctx context.Context, logs plog.Logs) error {
+ _ = ctx
+ var firstErr error
+ for i := 0; i < logs.ResourceLogs().Len(); i++ {
+ resourceLogs := logs.ResourceLogs().At(i)
+ resourceAttrs := attrsToMap(resourceLogs.Resource().Attributes())
+ for j := 0; j < resourceLogs.ScopeLogs().Len(); j++ {
+ scopeLogs := resourceLogs.ScopeLogs().At(j)
+ for k := 0; k < scopeLogs.LogRecords().Len(); k++ {
+ record := scopeLogs.LogRecords().At(k)
+ event := e.eventFromLog(resourceAttrs, record)
+ if err := e.writer.append(event); err != nil && firstErr == nil {
+ firstErr = err
+ }
+ }
+ }
+ }
+ return firstErr
+}
+
+func (e *beaconExporter) consumeTraces(ctx context.Context, traces ptrace.Traces) error {
+ _ = ctx
+ var firstErr error
+ for i := 0; i < traces.ResourceSpans().Len(); i++ {
+ resourceSpans := traces.ResourceSpans().At(i)
+ resourceAttrs := attrsToMap(resourceSpans.Resource().Attributes())
+ for j := 0; j < resourceSpans.ScopeSpans().Len(); j++ {
+ scopeSpans := resourceSpans.ScopeSpans().At(j)
+ for k := 0; k < scopeSpans.Spans().Len(); k++ {
+ span := scopeSpans.Spans().At(k)
+ event := e.eventFromSpan(resourceAttrs, span)
+ if err := e.writer.append(event); err != nil && firstErr == nil {
+ firstErr = err
+ }
+ }
+ }
+ }
+ return firstErr
+}
+
+func (e *beaconExporter) consumeMetrics(ctx context.Context, metrics pmetric.Metrics) error {
+ _ = ctx
+ var firstErr error
+ for i := 0; i < metrics.ResourceMetrics().Len(); i++ {
+ resourceMetrics := metrics.ResourceMetrics().At(i)
+ resourceAttrs := attrsToMap(resourceMetrics.Resource().Attributes())
+ for j := 0; j < resourceMetrics.ScopeMetrics().Len(); j++ {
+ scopeMetrics := resourceMetrics.ScopeMetrics().At(j)
+ for k := 0; k < scopeMetrics.Metrics().Len(); k++ {
+ metric := scopeMetrics.Metrics().At(k)
+ event := e.eventFromMetric(resourceAttrs, metric)
+ if err := e.writer.append(event); err != nil && firstErr == nil {
+ firstErr = err
+ }
+ }
+ }
+ }
+ return firstErr
+}
+
+func (e *beaconExporter) eventFromLog(resourceAttrs map[string]interface{}, record plog.LogRecord) beaconEvent {
+ attrs := mergeMaps(resourceAttrs, attrsToMap(record.Attributes()))
+ ts := timestamp(record.Timestamp().AsTime())
+ action := firstString(attrs, "beacon.event.action", "event.action", "gen_ai.agent.action", "ai.agent.action")
+ if action == "" {
+ action = inferAction(attrs, record.Body().AsString())
+ }
+ event := newBeaconEvent(action, firstString(attrs, "beacon.event.category", "event.category", "category"), severity(record.SeverityText(), record.SeverityNumber().String()), harnessName(attrs), ts)
+ event.Message = firstNonEmpty(record.Body().AsString(), firstString(attrs, "message", "log.message"))
+ e.populateCommon(&event, attrs)
+ event.Raw = e.rawPayload(attrs, map[string]interface{}{
+ "otel_signal": "logs",
+ "severity": record.SeverityText(),
+ })
+ return event
+}
+
+func (e *beaconExporter) eventFromSpan(resourceAttrs map[string]interface{}, span ptrace.Span) beaconEvent {
+ attrs := mergeMaps(resourceAttrs, attrsToMap(span.Attributes()))
+ action := firstString(attrs, "beacon.event.action", "event.action", "gen_ai.agent.action", "ai.agent.action")
+ if action == "" {
+ action = inferAction(attrs, span.Name())
+ }
+ event := newBeaconEvent(action, firstString(attrs, "beacon.event.category", "event.category", "tool"), spanSeverity(span.Status().Code().String()), harnessName(attrs), timestamp(span.StartTimestamp().AsTime()))
+ event.Message = firstNonEmpty(firstString(attrs, "message", "gen_ai.prompt", "gen_ai.response"), span.Name())
+ e.populateCommon(&event, attrs)
+ event.Raw = e.rawPayload(attrs, map[string]interface{}{
+ "otel_signal": "traces",
+ "span_name": span.Name(),
+ "span_kind": span.Kind().String(),
+ "status": span.Status().Code().String(),
+ })
+ return event
+}
+
+func (e *beaconExporter) eventFromMetric(resourceAttrs map[string]interface{}, metric pmetric.Metric) beaconEvent {
+ attrs := mergeMaps(resourceAttrs, map[string]interface{}{})
+ event := newBeaconEvent(firstString(attrs, "beacon.event.action", "event.action", "metric.observed"), "metric", "info", harnessName(attrs), time.Now().UTC())
+ event.Message = metric.Name()
+ e.populateCommon(&event, attrs)
+ event.Raw = e.rawPayload(attrs, map[string]interface{}{
+ "otel_signal": "metrics",
+ "metric_name": metric.Name(),
+ "metric_description": metric.Description(),
+ "metric_unit": metric.Unit(),
+ })
+ return event
+}
+
+func (e *beaconExporter) populateCommon(event *beaconEvent, attrs map[string]interface{}) {
+ event.Model = firstString(attrs, "gen_ai.request.model", "gen_ai.response.model", "model", "ai.model")
+ event.Repository = firstString(attrs, "vcs.repository.url", "repository", "repo.path", "workspace.repository")
+ event.Branch = firstString(attrs, "vcs.branch.name", "git.branch", "branch")
+ if id := firstString(attrs, "session.id", "conversation.id", "conversation_id", "gen_ai.conversation.id"); id != "" || firstString(attrs, "cwd", "working_directory") != "" {
+ event.Session = &sessionInfo{
+ ID: id,
+ WorkingDirectory: firstString(attrs, "cwd", "working_directory", "process.command_args.cwd"),
+ }
+ }
+ if name := firstString(attrs, "tool.name", "gen_ai.tool.name", "mcp.tool.name"); name != "" || firstString(attrs, "tool.command", "command") != "" {
+ event.Tool = &toolInfo{
+ Name: name,
+ Command: firstString(attrs, "tool.command", "command", "process.command_line"),
+ Path: firstString(attrs, "tool.path", "file.path"),
+ }
+ }
+ if path := firstString(attrs, "file.path", "file_path", "code.filepath"); path != "" {
+ event.File = &fileInfo{
+ Path: path,
+ Operation: firstString(attrs, "file.operation", "operation"),
+ Language: firstString(attrs, "code.language", "language"),
+ }
+ }
+ if command := firstString(attrs, "command", "process.command_line", "shell.command"); command != "" {
+ event.Command = &commandInfo{Command: command}
+ if exitCode, ok := intAttr(attrs, "exit_code", "process.exit_code", "command.exit_code"); ok {
+ event.Command.ExitCode = &exitCode
+ }
+ if duration, ok := int64Attr(attrs, "duration_ms", "command.duration_ms"); ok {
+ event.Command.DurationMS = duration
+ }
+ }
+ if server := firstString(attrs, "mcp.server.name", "mcp.server", "gen_ai.mcp.server"); server != "" || firstString(attrs, "mcp.tool.name") != "" {
+ event.MCP = &mcpInfo{
+ Server: server,
+ Tool: firstString(attrs, "mcp.tool.name", "tool.name"),
+ }
+ }
+ if decision := firstString(attrs, "approval.decision", "policy.decision"); decision != "" {
+ event.Approval = &approvalInfo{
+ Required: true,
+ Decision: decision,
+ Reason: firstString(attrs, "approval.reason", "policy.reason"),
+ }
+ }
+ event.Content = &contentInfo{Retention: e.cfg.ContentRetention, Included: e.cfg.ContentRetention != "metadata", Redacted: e.cfg.ContentRetention == "redacted"}
+}
+
+func (e *beaconExporter) rawPayload(attrs map[string]interface{}, extra map[string]interface{}) map[string]interface{} {
+ raw := map[string]interface{}{}
+ for k, v := range extra {
+ raw[k] = v
+ }
+ if e.cfg.ContentRetention == "metadata" {
+ raw["attribute_count"] = len(attrs)
+ return raw
+ }
+ raw["attributes"] = attrs
+ return raw
+}
+
+func attrsToMap(attrs pcommon.Map) map[string]interface{} {
+ out := make(map[string]interface{}, attrs.Len())
+ attrs.Range(func(k string, v pcommon.Value) bool {
+ out[k] = v.AsRaw()
+ return true
+ })
+ return out
+}
+
+func mergeMaps(a, b map[string]interface{}) map[string]interface{} {
+ out := make(map[string]interface{}, len(a)+len(b))
+ for k, v := range a {
+ out[k] = v
+ }
+ for k, v := range b {
+ out[k] = v
+ }
+ return out
+}
+
+func firstString(attrs map[string]interface{}, keys ...string) string {
+ for _, key := range keys {
+ if value, ok := attrs[key]; ok {
+ if str := strings.TrimSpace(fmt.Sprint(value)); str != "" && str != "<nil>" {
+ return str
+ }
+ }
+ }
+ return ""
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if strings.TrimSpace(value) != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func intAttr(attrs map[string]interface{}, keys ...string) (int, bool) {
+ value, ok := int64Attr(attrs, keys...)
+ return int(value), ok
+}
+
+func int64Attr(attrs map[string]interface{}, keys ...string) (int64, bool) {
+ for _, key := range keys {
+ switch typed := attrs[key].(type) {
+ case int:
+ return int64(typed), true
+ case int64:
+ return typed, true
+ case float64:
+ return int64(typed), true
+ }
+ }
+ return 0, false
+}
+
+func timestamp(ts time.Time) time.Time {
+ if ts.IsZero() || ts.UnixNano() == 0 {
+ return time.Now().UTC()
+ }
+ return ts
+}
+
+func severity(text, number string) string {
+ lower := strings.ToLower(text + " " + number)
+ switch {
+ case strings.Contains(lower, "fatal") || strings.Contains(lower, "critical"):
+ return "critical"
+ case strings.Contains(lower, "error"):
+ return "high"
+ case strings.Contains(lower, "warn"):
+ return "medium"
+ default:
+ return "info"
+ }
+}
+
+func spanSeverity(status string) string {
+ if strings.Contains(strings.ToLower(status), "error") {
+ return "high"
+ }
+ return "info"
+}
+
+func harnessName(attrs map[string]interface{}) string {
+ name := firstString(attrs, "beacon.harness.name", "harness.name", "service.name", "telemetry.sdk.name")
+ switch {
+ case strings.Contains(strings.ToLower(name), "claude"):
+ return "claude_cowork"
+ case strings.Contains(strings.ToLower(name), "codex"):
+ return "codex_cli"
+ case name != "":
+ return name
+ default:
+ return "otel"
+ }
+}
+
+func inferAction(attrs map[string]interface{}, fallback string) string {
+ tool := strings.ToLower(firstString(attrs, "tool.name", "gen_ai.tool.name", "mcp.tool.name"))
+ text := strings.ToLower(fallback + " " + tool)
+ switch {
+ case strings.Contains(text, "prompt"):
+ return "prompt.submitted"
+ case strings.Contains(text, "mcp"):
+ return "mcp.tool_invoked"
+ case strings.Contains(text, "command") || strings.Contains(text, "shell") || strings.Contains(text, "exec"):
+ return "command.executed"
+ case strings.Contains(text, "file") || strings.Contains(text, "write") || strings.Contains(text, "edit"):
+ return "file.modified"
+ case strings.Contains(text, "approval"):
+ return "approval.requested"
+ default:
+ return "tool.invoked"
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/exporter_test.go b/collector-builder/exporter/beaconjsonexporter/exporter_test.go
new file mode 100644
index 00000000..5ddb1a36
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/exporter_test.go
@@ -0,0 +1,94 @@
+package beaconjsonexporter
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "go.opentelemetry.io/collector/exporter"
+ "go.opentelemetry.io/collector/pdata/plog"
+)
+
+func TestConfigValidateRequiresPath(t *testing.T) {
+ cfg := createDefaultConfig()
+ if err := cfg.Validate(); err == nil {
+ t.Fatal("expected missing path error")
+ }
+ cfg.Path = filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := cfg.Validate(); err != nil {
+ t.Fatalf("Validate returned error: %v", err)
+ }
+}
+
+func TestConsumeLogsWritesBeaconJSONL(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ exp, err := newExporter(&Config{
+ Path: path,
+ MaxEventBytes: defaultMaxEventBytes,
+ RotateBytes: defaultRotateBytes,
+ RedactSecrets: true,
+ ContentRetention: "redacted",
+ }, exporter.Settings{})
+ if err != nil {
+ t.Fatalf("newExporter returned error: %v", err)
+ }
+
+ logs := plog.NewLogs()
+ rl := logs.ResourceLogs().AppendEmpty()
+ rl.Resource().Attributes().PutStr("service.name", "claude-cowork")
+ sl := rl.ScopeLogs().AppendEmpty()
+ rec := sl.LogRecords().AppendEmpty()
+ rec.Body().SetStr("tool call token=super-secret")
+ rec.Attributes().PutStr("beacon.event.action", "tool.invoked")
+ rec.Attributes().PutStr("session.id", "session-1")
+ rec.Attributes().PutStr("tool.name", "Shell")
+ rec.Attributes().PutStr("command", "kubectl get pods")
+
+ if err := exp.consumeLogs(context.Background(), logs); err != nil {
+ t.Fatalf("consumeLogs returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read runtime log: %v", err)
+ }
+ if strings.Contains(string(data), "super-secret") {
+ t.Fatalf("expected secret to be redacted: %s", string(data))
+ }
+ var event beaconEvent
+ if err := json.Unmarshal([]byte(strings.TrimSpace(string(data))), &event); err != nil {
+ t.Fatalf("unmarshal event: %v", err)
+ }
+ if event.Vendor != vendor || event.Event.Action != "tool.invoked" || event.Harness.Name != "claude_cowork" {
+ t.Fatalf("unexpected event: %#v", event)
+ }
+ if event.Session == nil || event.Session.ID != "session-1" {
+ t.Fatalf("session missing from event: %#v", event.Session)
+ }
+ if event.Command == nil || event.Command.Command != "kubectl get pods" {
+ t.Fatalf("command missing from event: %#v", event.Command)
+ }
+}
+
+func TestMetadataRetentionDropsRawAttributes(t *testing.T) {
+ exp, err := newExporter(&Config{
+ Path: filepath.Join(t.TempDir(), "runtime.jsonl"),
+ MaxEventBytes: defaultMaxEventBytes,
+ RotateBytes: defaultRotateBytes,
+ RedactSecrets: true,
+ ContentRetention: "metadata",
+ }, exporter.Settings{})
+ if err != nil {
+ t.Fatalf("newExporter returned error: %v", err)
+ }
+
+ raw := exp.rawPayload(map[string]interface{}{"prompt": "do a thing"}, map[string]interface{}{"otel_signal": "logs"})
+ if _, ok := raw["attributes"]; ok {
+ t.Fatalf("metadata retention should not include raw attributes: %#v", raw)
+ }
+ if raw["attribute_count"] != 1 {
+ t.Fatalf("attribute count missing: %#v", raw)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/factory.go b/collector-builder/exporter/beaconjsonexporter/factory.go
new file mode 100644
index 00000000..05a904cd
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/factory.go
@@ -0,0 +1,47 @@
+package beaconjsonexporter
+
+import (
+ "context"
+
+ "go.opentelemetry.io/collector/component"
+ "go.opentelemetry.io/collector/consumer"
+ "go.opentelemetry.io/collector/exporter"
+ "go.opentelemetry.io/collector/exporter/exporterhelper"
+)
+
+var componentType = component.MustNewType("beaconjson")
+
+// NewFactory creates the Beacon JSONL exporter factory.
+func NewFactory() exporter.Factory {
+ return exporter.NewFactory(
+ componentType,
+ func() component.Config { return createDefaultConfig() },
+ exporter.WithLogs(createLogsExporter, component.StabilityLevelBeta),
+ exporter.WithTraces(createTracesExporter, component.StabilityLevelBeta),
+ exporter.WithMetrics(createMetricsExporter, component.StabilityLevelBeta),
+ )
+}
+
+func createLogsExporter(ctx context.Context, set exporter.Settings, cfg component.Config) (exporter.Logs, error) {
+ exp, err := newExporter(cfg, set)
+ if err != nil {
+ return nil, err
+ }
+ return exporterhelper.NewLogs(ctx, set, cfg, consumer.ConsumeLogsFunc(exp.consumeLogs))
+}
+
+func createTracesExporter(ctx context.Context, set exporter.Settings, cfg component.Config) (exporter.Traces, error) {
+ exp, err := newExporter(cfg, set)
+ if err != nil {
+ return nil, err
+ }
+ return exporterhelper.NewTraces(ctx, set, cfg, consumer.ConsumeTracesFunc(exp.consumeTraces))
+}
+
+func createMetricsExporter(ctx context.Context, set exporter.Settings, cfg component.Config) (exporter.Metrics, error) {
+ exp, err := newExporter(cfg, set)
+ if err != nil {
+ return nil, err
+ }
+ return exporterhelper.NewMetrics(ctx, set, cfg, consumer.ConsumeMetricsFunc(exp.consumeMetrics))
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/go.mod b/collector-builder/exporter/beaconjsonexporter/go.mod
new file mode 100644
index 00000000..ecf0e932
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/go.mod
@@ -0,0 +1,45 @@
+module github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter
+
+go 1.24
+
+require (
+ go.opentelemetry.io/collector/component v1.27.0
+ go.opentelemetry.io/collector/consumer v1.27.0
+ go.opentelemetry.io/collector/exporter v0.121.0
+ go.opentelemetry.io/collector/pdata v1.27.0
+ go.uber.org/zap v1.27.0
+)
+
+require (
+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect
+ github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
+ github.com/gogo/protobuf v1.3.2 // indirect
+ github.com/hashicorp/go-version v1.7.0 // indirect
+ github.com/json-iterator/go v1.1.12 // indirect
+ github.com/knadh/koanf/maps v0.1.1 // indirect
+ github.com/knadh/koanf/providers/confmap v0.1.0 // indirect
+ github.com/knadh/koanf/v2 v2.1.2 // indirect
+ github.com/mitchellh/copystructure v1.2.0 // indirect
+ github.com/mitchellh/reflectwalk v1.0.2 // indirect
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+ github.com/modern-go/reflect2 v1.0.2 // indirect
+ go.opentelemetry.io/collector/config/configretry v1.27.0 // indirect
+ go.opentelemetry.io/collector/confmap v1.27.0 // indirect
+ go.opentelemetry.io/collector/consumer/consumererror v0.121.0 // indirect
+ go.opentelemetry.io/collector/extension v1.27.0 // indirect
+ go.opentelemetry.io/collector/extension/xextension v0.121.0 // indirect
+ go.opentelemetry.io/collector/featuregate v1.27.0 // indirect
+ go.opentelemetry.io/collector/pdata/pprofile v0.121.0 // indirect
+ go.opentelemetry.io/collector/pipeline v0.121.0 // indirect
+ go.opentelemetry.io/otel v1.34.0 // indirect
+ go.opentelemetry.io/otel/metric v1.34.0 // indirect
+ go.opentelemetry.io/otel/trace v1.34.0 // indirect
+ go.uber.org/multierr v1.11.0 // indirect
+ golang.org/x/net v0.33.0 // indirect
+ golang.org/x/sys v0.29.0 // indirect
+ golang.org/x/text v0.21.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a // indirect
+ google.golang.org/grpc v1.70.0 // indirect
+ google.golang.org/protobuf v1.36.5 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/collector-builder/exporter/beaconjsonexporter/go.sum b/collector-builder/exporter/beaconjsonexporter/go.sum
new file mode 100644
index 00000000..718f52f4
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/go.sum
@@ -0,0 +1,161 @@
+github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
+github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
+github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
+github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
+github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
+github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs=
+github.com/knadh/koanf/maps v0.1.1/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
+github.com/knadh/koanf/providers/confmap v0.1.0 h1:gOkxhHkemwG4LezxxN8DMOFopOPghxRVp7JbIvdvqzU=
+github.com/knadh/koanf/providers/confmap v0.1.0/go.mod h1:2uLhxQzJnyHKfxG927awZC7+fyHFdQkd697K4MdLnIU=
+github.com/knadh/koanf/v2 v2.1.2 h1:I2rtLRqXRy1p01m/utEtpZSSA6dcJbgGVuE27kW2PzQ=
+github.com/knadh/koanf/v2 v2.1.2/go.mod h1:Gphfaen0q1Fc1HTgJgSTC4oRX9R2R5ErYMZJy8fLJBo=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
+github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
+github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
+github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
+github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
+go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
+go.opentelemetry.io/collector/component v1.27.0 h1:6wk0K23YT9lSprX8BH9x5w8ssAORE109ekH/ix2S614=
+go.opentelemetry.io/collector/component v1.27.0/go.mod h1:fIyBHoa7vDyZL3Pcidgy45cx24tBe7iHWne097blGgo=
+go.opentelemetry.io/collector/component/componenttest v0.121.0 h1:4q1/7WnP9LPKaY4HAd8/OkzhllZpRACKAOlWsqbrzqc=
+go.opentelemetry.io/collector/component/componenttest v0.121.0/go.mod h1:H7bEXDPMYNeWcHal0xyKlVfRPByVxale7hCJ+Myjq3Q=
+go.opentelemetry.io/collector/config/configretry v1.27.0 h1:mM0X/7eiWRVmYTZJ5QTtly10uJWHnctIFuYST6tc/zU=
+go.opentelemetry.io/collector/config/configretry v1.27.0/go.mod h1:8gzFQ0qzKLYvzP2sNPwsB9gwzKSEls649yANmt/d6yE=
+go.opentelemetry.io/collector/confmap v1.27.0 h1:OIjPcjij1NxkVQsQVmHro4+t1eYNFiUGib9+J9YBZhM=
+go.opentelemetry.io/collector/confmap v1.27.0/go.mod h1:tmOa6iw3FJsEgfBHKALqvcdfRtf71JZGor0wSM5MoH8=
+go.opentelemetry.io/collector/consumer v1.27.0 h1:JoXdoCeFDJG3d9TYrKHvTT4eBhzKXDVTkWW5mDfnLiY=
+go.opentelemetry.io/collector/consumer v1.27.0/go.mod h1:1B/+kTDUI6u3mCIOAkm5ityIpv5uC0Ll78IA50SNZ24=
+go.opentelemetry.io/collector/consumer/consumererror v0.121.0 h1:yFcCqi4Djhl2oUxYIyi5FAeLit/m1ah0sAokZKsP3zM=
+go.opentelemetry.io/collector/consumer/consumererror v0.121.0/go.mod h1:kHrvHQ8AuWVjhSFixR51iEozdnoGkX6AjDWyhr3gSDo=
+go.opentelemetry.io/collector/consumer/consumertest v0.121.0 h1:EIJPAXQY0w9j1k/e5OzJqOYVEr6WljKpJBjgkkp/hWw=
+go.opentelemetry.io/collector/consumer/consumertest v0.121.0/go.mod h1:Hmj+TizzsLU0EmS2n/rJYScOybNmm3mrAjis6ed7qTw=
+go.opentelemetry.io/collector/consumer/xconsumer v0.121.0 h1:/FJ7L6+G++FvktXc/aBnnYDIKLoYsWLh0pKbvzFFwF8=
+go.opentelemetry.io/collector/consumer/xconsumer v0.121.0/go.mod h1:KKy8Qg/vOnyseoi7A9/x1a1oEqSmf0WBHkJFlnQH0Ow=
+go.opentelemetry.io/collector/exporter v0.121.0 h1:HkE/qvnhmPtI/O/ITloukHFt4Ywmz6YzyWyWAqNGoKI=
+go.opentelemetry.io/collector/exporter v0.121.0/go.mod h1:Xi4UtotE9QdA7UGkJVxHyg4grycYIKVDp/F+henuv3k=
+go.opentelemetry.io/collector/exporter/exportertest v0.121.0 h1:kjtZwZd0Mj5VZv3JGxuQBnqmfmOCcCdhpz0G4INd6o0=
+go.opentelemetry.io/collector/exporter/exportertest v0.121.0/go.mod h1:xGIi17/Ffteh308BRruHXVzq51o7wxYcUch0zXzyrqA=
+go.opentelemetry.io/collector/exporter/xexporter v0.121.0 h1:e5QIl51EutJrH8X4tfnQUgfz1ebXPlLUzTltlT40IAc=
+go.opentelemetry.io/collector/exporter/xexporter v0.121.0/go.mod h1:PGrW5pOQkNpaz8xqtkITCNEkcJVxOHSptg2chVTtv+o=
+go.opentelemetry.io/collector/extension v1.27.0 h1:7F+O8/+bcwo3Zk3B/+H8A75cz9dhqXUrbeiyiFajoy4=
+go.opentelemetry.io/collector/extension v1.27.0/go.mod h1:Fe0nUGMcr0c6IIBD3QEa3XmdUYpfmm5wCjc3PYho8DM=
+go.opentelemetry.io/collector/extension/extensiontest v0.121.0 h1:ce3IEWXBDOOSljd0niVbwHs7AhC8hOjC2RXGIoMOXog=
+go.opentelemetry.io/collector/extension/extensiontest v0.121.0/go.mod h1:yrZhZhf2a3aD0/17drjHnzSTlr0XnNREVrOLYBlcP1o=
+go.opentelemetry.io/collector/extension/xextension v0.121.0 h1:RIhFXwm9+2sc6H2PsM9asGfEBlIDBrK+dyyFMx257bs=
+go.opentelemetry.io/collector/extension/xextension v0.121.0/go.mod h1:EiGx9nRD/7TU4++2/f5+2wdxUnDvjINCpWKLgfF2JRA=
+go.opentelemetry.io/collector/featuregate v1.27.0 h1:4LLrccoMz/gJT5uym8ojBlMzY5tr4RzUUXzwlBuiRz0=
+go.opentelemetry.io/collector/featuregate v1.27.0/go.mod h1:Y/KsHbvREENKvvN9RlpiWk/IGBK+CATBYzIIpU7nccc=
+go.opentelemetry.io/collector/pdata v1.27.0 h1:66yI7FYkUDia74h48Fd2/KG2Vk8DxZnGw54wRXykCEU=
+go.opentelemetry.io/collector/pdata v1.27.0/go.mod h1:18e8/xDZsqyj00h/5HM5GLdJgBzzG9Ei8g9SpNoiMtI=
+go.opentelemetry.io/collector/pdata/pprofile v0.121.0 h1:DFBelDRsZYxEaSoxSRtseAazsHJfqfC/Yl64uPicl2g=
+go.opentelemetry.io/collector/pdata/pprofile v0.121.0/go.mod h1:j/fjrd7ybJp/PXkba92QLzx7hykUVmU8x/WJvI2JWSg=
+go.opentelemetry.io/collector/pdata/testdata v0.121.0 h1:FFz+rdb7o6JRZ82Zmp6WKEdKnEMaoF3jLb7F1F21ijg=
+go.opentelemetry.io/collector/pdata/testdata v0.121.0/go.mod h1:UhiSwmVpBbuKlPdmhBytiVTHipSz/JO6c4mbD4kWOPg=
+go.opentelemetry.io/collector/pipeline v0.121.0 h1:SOiocdyWCJCjWAb96HIxsy9enp2qyQ1NRFo26qyHlCE=
+go.opentelemetry.io/collector/pipeline v0.121.0/go.mod h1:TO02zju/K6E+oFIOdi372Wk0MXd+Szy72zcTsFQwXl4=
+go.opentelemetry.io/collector/receiver v0.121.0 h1:gQGAiSXX5ZjAqb3fZVlZc4DjT90at/HmnKzNG/XIdZw=
+go.opentelemetry.io/collector/receiver v0.121.0/go.mod h1:CqvQRwGGOqq6PRI6qmkKzF7AYWwRZTpCX6w7U3wIAmQ=
+go.opentelemetry.io/collector/receiver/receivertest v0.121.0 h1:kdwV0tkaawRwKoZ1hl2xeYo4Oqfoa5drNX5I2J+rKhk=
+go.opentelemetry.io/collector/receiver/receivertest v0.121.0/go.mod h1:H7N4CLG4J8Do3NWeo9gj7VmJCtDstDeeCffPBgHu1WQ=
+go.opentelemetry.io/collector/receiver/xreceiver v0.121.0 h1:F6IVdEArgicLVtDtZ2Ovmjv8o6+3AyxYaC3HdNIbakM=
+go.opentelemetry.io/collector/receiver/xreceiver v0.121.0/go.mod h1:ZsI1dzGq9J8y0f8h8MYYnoyC8SRJ5u1OqVRX2EwdZwo=
+go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
+go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
+go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
+go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
+go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
+go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
+go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
+go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
+go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
+go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
+go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
+go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
+golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
+golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
+golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a h1:hgh8P4EuoxpsuKMXX/To36nOFD7vixReXgn8lPGnt+o=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU=
+google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ=
+google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw=
+google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
+google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/collector-builder/exporter/beaconjsonexporter/writer.go b/collector-builder/exporter/beaconjsonexporter/writer.go
new file mode 100644
index 00000000..63c7d782
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/writer.go
@@ -0,0 +1,170 @@
+package beaconjsonexporter
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "syscall"
+)
+
+var secretPatterns = []*regexp.Regexp{
+ regexp.MustCompile(`(?i)authorization\s*[:=]\s*bearer\s+[^"',\s]+`),
+ regexp.MustCompile(`(?i)(api[_-]?key|token|secret|password|authorization)\s*[:=]\s*["']?[^"',\s]+`),
+ regexp.MustCompile(`(?i)bearer\s+[a-z0-9._~+/=-]+`),
+ regexp.MustCompile(`sk-[a-zA-Z0-9]{20,}`),
+}
+
+type jsonlWriter struct {
+ path string
+ maxEventBytes int
+ rotateBytes int64
+ redactSecrets bool
+}
+
+func (w jsonlWriter) append(event beaconEvent) error {
+ event = w.sanitize(event)
+ data, err := json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ if len(data) > w.maxEventBytes {
+ event.Raw = nil
+ event.Message = truncate(event.Message, 1024)
+ event.Truncated = true
+ data, err = json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ }
+ if len(data) > w.maxEventBytes {
+ return fmt.Errorf("event exceeds maximum size after truncation: %d bytes", len(data))
+ }
+ if err := os.MkdirAll(filepath.Dir(w.path), 0755); err != nil {
+ return err
+ }
+ if err := rotateIfNeeded(w.path, w.rotateBytes); err != nil {
+ return err
+ }
+ f, err := os.OpenFile(w.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ return err
+ }
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
+ _ = f.Close()
+ return err
+ }
+ defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+ defer f.Close()
+ _, err = f.Write(append(data, '\n'))
+ return err
+}
+
+func (w jsonlWriter) sanitize(event beaconEvent) beaconEvent {
+ event.Message = w.cleanString(event.Message, 4096)
+ if event.Tool != nil {
+ event.Tool.Command = w.cleanString(event.Tool.Command, 4096)
+ event.Tool.Path = truncate(event.Tool.Path, 2048)
+ }
+ if event.Command != nil {
+ event.Command.Command = w.cleanString(event.Command.Command, 4096)
+ }
+ if event.Approval != nil {
+ event.Approval.Reason = w.cleanString(event.Approval.Reason, 4096)
+ }
+ if event.Raw != nil {
+ event.Raw = w.sanitizeMap(event.Raw)
+ }
+ if data, err := json.Marshal(event); err == nil && len(data) > w.maxEventBytes {
+ event.Truncated = true
+ }
+ return event
+}
+
+func (w jsonlWriter) sanitizeMap(input map[string]interface{}) map[string]interface{} {
+ out := make(map[string]interface{}, len(input))
+ for k, v := range input {
+ switch typed := v.(type) {
+ case string:
+ out[k] = w.cleanString(typed, 2048)
+ case map[string]interface{}:
+ out[k] = w.sanitizeMap(typed)
+ case []interface{}:
+ out[k] = w.sanitizeSlice(typed)
+ default:
+ out[k] = typed
+ }
+ }
+ return out
+}
+
+func (w jsonlWriter) sanitizeSlice(input []interface{}) []interface{} {
+ out := make([]interface{}, len(input))
+ for i, v := range input {
+ switch typed := v.(type) {
+ case string:
+ out[i] = w.cleanString(typed, 2048)
+ case map[string]interface{}:
+ out[i] = w.sanitizeMap(typed)
+ case []interface{}:
+ out[i] = w.sanitizeSlice(typed)
+ default:
+ out[i] = typed
+ }
+ }
+ return out
+}
+
+func (w jsonlWriter) cleanString(value string, limit int) string {
+ value = truncate(value, limit)
+ if w.redactSecrets {
+ value = redact(value)
+ }
+ return value
+}
+
+func redact(value string) string {
+ for _, pattern := range secretPatterns {
+ value = pattern.ReplaceAllStringFunc(value, func(match string) string {
+ if strings.Contains(match, "=") {
+ return match[:strings.Index(match, "=")+1] + "[REDACTED]"
+ }
+ if strings.Contains(match, ":") {
+ return match[:strings.Index(match, ":")+1] + "[REDACTED]"
+ }
+ return "[REDACTED]"
+ })
+ }
+ return value
+}
+
+func truncate(value string, limit int) string {
+ if len(value) <= limit {
+ return value
+ }
+ if limit < 32 {
+ return value[:limit]
+ }
+ return value[:limit-15] + "...[truncated]"
+}
+
+func rotateIfNeeded(path string, maxSize int64) error {
+ if maxSize == 0 {
+ return nil
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ if info.Size() <= maxSize {
+ return nil
+ }
+ rotated := path + ".1"
+ _ = os.Remove(rotated)
+ return os.Rename(path, rotated)
+}