Skip to content

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

init commit

Justin D'Souza8363c93cc3be
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..f8e15834
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,52 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+
+jobs:
+ go-test:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version-file: cli/beacon/go.mod
+ - name: Test CLI
+ working-directory: cli/beacon
+ run: go test ./...
+ - name: Test CLI race-sensitive packages
+ working-directory: cli/beacon
+ run: go test -race ./internal/endpoint/...
+ - name: Test hooks
+ working-directory: cli/beacon-hooks
+ run: go test ./...
+ - name: Public CLI command tree smoke test
+ working-directory: cli/beacon
+ run: |
+ go build -o beacon .
+ ./beacon --help > /tmp/beacon-help.txt
+ ./beacon endpoint --help > /tmp/beacon-endpoint-help.txt
+ ./beacon endpoint hooks --help > /tmp/beacon-hooks-help.txt
+ ./beacon endpoint integrations claude-cowork --help > /tmp/beacon-cowork-help.txt
+ ./beacon endpoint wazuh --help > /tmp/beacon-wazuh-help.txt
+ for forbidden in login init update claude cursor dep-scan config whoami; do
+ if grep -E "^[[:space:]]+$forbidden([[:space:]]|$)" /tmp/beacon-help.txt; then
+ echo "forbidden command exposed: $forbidden"
+ exit 1
+ fi
+ done
+
+ package-smoke:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Validate packaging scripts
+ run: |
+ test -x packaging/macos/install-endpoint.sh
+ test -x packaging/macos/uninstall-endpoint.sh
+ test -f collector-builder/builder.yaml
+ sh packaging/macos/test-endpoint-scripts.sh
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..a6663427
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,37 @@
+# macOS
+.DS_Store
+
+# Editor and local environment
+.idea/
+.vscode/
+*.swp
+*.swo
+.env
+.env.*
+
+# Go build outputs
+*.test
+coverage.out
+coverage.html
+.gocache/
+.tmp/
+
+# Beacon CLI binaries and release output
+cli/beacon/beacon
+cli/beacon/beacon-*
+cli/beacon/dist/
+cli/beacon/internal/embedded/hooks.bin
+
+# Hook helper binaries
+cli/beacon-hooks/beacon-hooks
+cli/beacon-hooks/beacon-hooks-*
+cli/beacon-hooks/*.exe
+
+# Local endpoint logs/config generated during development
+.beacon/
+*.jsonl
+*.log
+
+# Collector builder outputs
+collector-builder/dist/
+
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..dc8cf894
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,62 @@
+# CLAUDE.md
+
+Guidance for Claude Code and other coding agents working in this repository.
+
+## Project Scope
+
+Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes. The shipping code paths are:
+
+- `cli/beacon`: public `beacon` CLI and endpoint runtime.
+- `cli/beacon-hooks`: hook adapter invoked by Cursor and other supported runtimes.
+- `collector-builder`: OpenTelemetry Collector distribution scaffold.
+- `packaging`: macOS packaging and deployment assets.
+
+Do not recreate or depend on removed `asymptote` mirror trees. Keep new work focused on the Beacon paths above.
+
+## Common Commands
+
+Run tests for the public CLI:
+
+```bash
+cd cli/beacon
+go test ./...
+go test -race ./internal/endpoint/...
+```
+
+Run hook adapter tests:
+
+```bash
+cd cli/beacon-hooks
+go test ./...
+```
+
+Run packaging wrapper checks:
+
+```bash
+sh packaging/macos/test-endpoint-scripts.sh
+```
+
+Build the CLI:
+
+```bash
+cd cli/beacon
+make build
+```
+
+## Implementation Notes
+
+- Prefer deterministic tests that use `t.TempDir()`, `t.Setenv("HOME", ...)`, fake binaries, and free local ports.
+- Avoid tests that require root, real `launchctl` service changes, Wazuh, a live collector, or external network access.
+- For macOS-only behavior, gate tests with `runtime.GOOS == "darwin"` or assert the non-Darwin contract explicitly.
+- Keep endpoint event schema fields stable: `vendor`, `product`, `schema_version`, required event fields, and Wazuh-compatible JSONL output are release contracts.
+- Preserve the local-only product posture. The public Beacon build should not require a hosted account or remote policy fetch.
+
+## CI Expectations
+
+CI runs:
+
+- `go test ./...` in `cli/beacon`.
+- `go test -race ./internal/endpoint/...` in `cli/beacon`.
+- `go test ./...` in `cli/beacon-hooks`.
+- CLI help smoke checks for the public command tree.
+- macOS packaging script validation via `packaging/macos/test-endpoint-scripts.sh`.
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..4e041eac
--- /dev/null
+++ b/README.md
@@ -0,0 +1,72 @@
+# Beacon Endpoint Agent
+
+Local endpoint telemetry for AI agent runtimes.
+
+Beacon Endpoint Agent configures local telemetry for tools like Claude Code,
+Codex CLI, Claude Cowork, and Cursor, then writes Wazuh-compatible JSONL logs.
+It runs local-only and does not require a Beacon account.
+
+## Quick Start
+
+Build the CLI:
+
+```bash
+cd cli/beacon
+make build
+```
+
+Install in user mode:
+
+```bash
+./beacon endpoint install --user
+./beacon endpoint status
+```
+
+Print Wazuh config and validate event output:
+
+```bash
+./beacon endpoint wazuh print-config --user
+./beacon endpoint wazuh validate --user
+```
+
+Optional integrations:
+
+```bash
+./beacon endpoint hooks install --harness cursor --user
+./beacon endpoint integrations claude-cowork print-config --user
+```
+
+Uninstall:
+
+```bash
+./beacon endpoint uninstall --user --keep-logs
+```
+
+## Commands
+
+- `beacon endpoint install`: configure the endpoint agent, Collector service, and Claude/Codex telemetry.
+- `beacon endpoint repair`: reapply service/config files and repair telemetry drift.
+- `beacon endpoint status`: show Collector, service, harness, and diagnostic status.
+- `beacon endpoint discover`: list supported local AI runtimes.
+- `beacon endpoint hooks`: install, check, or remove hook-based integrations such as Cursor.
+- `beacon endpoint integrations claude-cowork`: print setup and validate admin-configured Cowork OTLP export.
+- `beacon endpoint wazuh`: print/install Wazuh content and write a validation event.
+- `beacon endpoint uninstall`: stop services and remove managed endpoint files.
+
+## Repository Layout
+
+- `cli/beacon`: public `beacon` CLI.
+- `cli/beacon-hooks`: hook adapter invoked by supported agent runtimes.
+- `collector-builder`: custom OpenTelemetry Collector distribution scaffold.
+- `packaging`: macOS packaging and MDM deployment assets.
+
+## Test
+
+```bash
+cd cli/beacon
+go test ./...
+go test -race ./internal/endpoint/...
+
+cd ../beacon-hooks
+go test ./...
+```
diff --git a/cli/beacon-hooks/Makefile b/cli/beacon-hooks/Makefile
new file mode 100644
index 00000000..86c75c3c
--- /dev/null
+++ b/cli/beacon-hooks/Makefile
@@ -0,0 +1,80 @@
+# Beacon Hooks Makefile
+
+# Build variables
+BINARY := beacon-hooks
+LDFLAGS := -s -w
+
+.PHONY: all build clean test build-all build-darwin build-linux build-windows compress
+
+all: build
+
+# Build for current platform
+build:
+ @echo "Building $(BINARY)..."
+ go build -ldflags "$(LDFLAGS)" -o $(BINARY) .
+
+# Build and compress for current platform
+build-compressed: build
+ @echo "Compressing $(BINARY) with UPX..."
+ upx --best --lzma $(BINARY) || echo "UPX not available, skipping compression"
+
+# Build for all platforms
+build-all: build-darwin build-linux build-windows
+
+# macOS builds
+build-darwin: build-darwin-amd64 build-darwin-arm64
+
+build-darwin-amd64:
+ @echo "Building for macOS (amd64)..."
+ GOOS=darwin GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-darwin-amd64 .
+
+build-darwin-arm64:
+ @echo "Building for macOS (arm64)..."
+ GOOS=darwin GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-darwin-arm64 .
+
+# Linux builds
+build-linux: build-linux-amd64 build-linux-arm64
+
+build-linux-amd64:
+ @echo "Building for Linux (amd64)..."
+ GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-linux-amd64 .
+
+build-linux-arm64:
+ @echo "Building for Linux (arm64)..."
+ GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-linux-arm64 .
+
+# Windows builds
+build-windows: build-windows-amd64
+
+build-windows-amd64:
+ @echo "Building for Windows (amd64)..."
+ GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-windows-amd64.exe .
+
+# Compress all binaries with UPX
+compress:
+ @echo "Compressing binaries with UPX..."
+ @for f in $(BINARY)-*; do \
+ if [ -f "$$f" ]; then \
+ echo "Compressing $$f..."; \
+ upx --best --lzma "$$f" || echo "Failed to compress $$f"; \
+ fi; \
+ done
+
+# Build all and compress
+build-all-compressed: build-all compress
+
+# Clean build artifacts
+clean:
+ rm -f $(BINARY) $(BINARY)-*
+
+# Run tests
+test:
+ go test -v ./...
+
+# Format code
+fmt:
+ go fmt ./...
+
+# Tidy dependencies
+tidy:
+ go mod tidy
diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.go
new file mode 100644
index 00000000..590450b5
--- /dev/null
+++ b/cli/beacon-hooks/cmd/helpers.go
@@ -0,0 +1,112 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// readStdinJSON decodes JSON from stdin into a map.
+func readStdinJSON() (map[string]interface{}, error) {
+ var input map[string]interface{}
+ err := json.NewDecoder(os.Stdin).Decode(&input)
+ return input, err
+}
+
+// outputJSON writes a JSON object to stdout.
+func outputJSON(data map[string]interface{}) {
+ json.NewEncoder(os.Stdout).Encode(data)
+}
+
+// outputJSONAndExit writes a JSON object to stdout and exits.
+func outputJSONAndExit(data map[string]interface{}) {
+ json.NewEncoder(os.Stdout).Encode(data)
+ os.Exit(0)
+}
+
+// emptyResponse is a reusable empty JSON response.
+var emptyResponse = map[string]interface{}{}
+
+// getFirstStr returns the first non-empty string value from input for the given keys.
+func getFirstStr(input map[string]interface{}, keys ...string) string {
+ for _, key := range keys {
+ if v, ok := input[key].(string); ok && v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+// resolveSessionID extracts the session ID from input based on the platform.
+// For Copilot, it prefers the transcript filename UUID over the VS Code sessionId.
+// For Claude, it reads session_id directly.
+func resolveSessionID(input map[string]interface{}, platform string) string {
+ switch platform {
+ case "copilot":
+ transcriptPath := getFirstStr(input, "transcriptPath", "transcript_path")
+ if id := sessionIDFromTranscriptPath(transcriptPath); id != "" {
+ return id
+ }
+ return getFirstStr(input, "sessionId", "session_id")
+ case "cursor":
+ return getFirstStr(input, "conversation_id")
+ default:
+ id, _ := input["session_id"].(string)
+ return id
+ }
+}
+
+// resolveSessionIDWithTranscript extracts both session ID and transcript path.
+// Used by commands that need the transcript path for upload.
+func resolveSessionIDWithTranscript(input map[string]interface{}, platform string) (sessionID, transcriptPath string) {
+ switch platform {
+ case "copilot":
+ transcriptPath = getFirstStr(input, "transcriptPath", "transcript_path")
+ sessionID = sessionIDFromTranscriptPath(transcriptPath)
+ if sessionID == "" {
+ sessionID = getFirstStr(input, "sessionId", "session_id")
+ }
+ return
+ case "cursor":
+ sessionID = getFirstStr(input, "conversation_id")
+ transcriptPath = getFirstStr(input, "transcript_path")
+ return
+ default:
+ sessionID, _ = input["session_id"].(string)
+ transcriptPath, _ = input["transcript_path"].(string)
+ return
+ }
+}
+
+// sessionIDFromTranscriptPath extracts the UUID from a transcript filename.
+// Example: ".../transcripts/ff2d7803-5799-4f18-83f0-3633b2c11809.jsonl" -> "ff2d7803-..."
+func sessionIDFromTranscriptPath(transcriptPath string) string {
+ if transcriptPath == "" {
+ return ""
+ }
+ base := filepath.Base(transcriptPath)
+ return strings.TrimSuffix(base, filepath.Ext(base))
+}
+
+// resolveCwd extracts the working directory from hook input based on platform.
+// For Cursor: tries input["cwd"], then workspace_roots[0], then CURSOR_PROJECT_DIR env var.
+// For other platforms: reads input["cwd"] directly.
+func resolveCwd(input map[string]interface{}, platform string) string {
+ if platform == "cursor" {
+ if cwd := getFirstStr(input, "cwd"); cwd != "" {
+ return cwd
+ }
+ if roots, ok := input["workspace_roots"].([]interface{}); ok && len(roots) > 0 {
+ if cwd, ok := roots[0].(string); ok && cwd != "" {
+ return cwd
+ }
+ }
+ if cwd := os.Getenv("CURSOR_PROJECT_DIR"); cwd != "" {
+ return cwd
+ }
+ return ""
+ }
+ cwd, _ := input["cwd"].(string)
+ return cwd
+}
diff --git a/cli/beacon-hooks/cmd/helpers_test.go b/cli/beacon-hooks/cmd/helpers_test.go
new file mode 100644
index 00000000..37ca3751
--- /dev/null
+++ b/cli/beacon-hooks/cmd/helpers_test.go
@@ -0,0 +1,225 @@
+package cmd
+
+import (
+ "testing"
+)
+
+func TestResolveSessionID_Cursor(t *testing.T) {
+ tests := []struct {
+ name string
+ input map[string]interface{}
+ platform string
+ want string
+ }{
+ {
+ name: "cursor uses conversation_id",
+ input: map[string]interface{}{
+ "conversation_id": "conv_abc123",
+ },
+ platform: "cursor",
+ want: "conv_abc123",
+ },
+ {
+ name: "cursor ignores session_id",
+ input: map[string]interface{}{
+ "session_id": "should-be-ignored",
+ "conversation_id": "conv_abc123",
+ },
+ platform: "cursor",
+ want: "conv_abc123",
+ },
+ {
+ name: "cursor returns empty when no conversation_id",
+ input: map[string]interface{}{},
+ platform: "cursor",
+ want: "",
+ },
+ {
+ name: "claude uses session_id",
+ input: map[string]interface{}{
+ "session_id": "sess_123",
+ },
+ platform: "claude",
+ want: "sess_123",
+ },
+ {
+ name: "copilot prefers transcript path UUID",
+ input: map[string]interface{}{
+ "transcriptPath": "/path/to/transcripts/ff2d7803-5799-4f18-83f0-3633b2c11809.jsonl",
+ "sessionId": "vscode-session-id",
+ },
+ platform: "copilot",
+ want: "ff2d7803-5799-4f18-83f0-3633b2c11809",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := resolveSessionID(tt.input, tt.platform)
+ if got != tt.want {
+ t.Errorf("resolveSessionID() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestResolveSessionIDWithTranscript_Cursor(t *testing.T) {
+ tests := []struct {
+ name string
+ input map[string]interface{}
+ platform string
+ wantSessionID string
+ wantTranscriptPath string
+ }{
+ {
+ name: "cursor extracts both conversation_id and transcript_path",
+ input: map[string]interface{}{
+ "conversation_id": "conv_abc123",
+ "transcript_path": "/path/to/transcript.jsonl",
+ },
+ platform: "cursor",
+ wantSessionID: "conv_abc123",
+ wantTranscriptPath: "/path/to/transcript.jsonl",
+ },
+ {
+ name: "cursor with only conversation_id",
+ input: map[string]interface{}{
+ "conversation_id": "conv_abc123",
+ },
+ platform: "cursor",
+ wantSessionID: "conv_abc123",
+ wantTranscriptPath: "",
+ },
+ {
+ name: "cursor with neither field",
+ input: map[string]interface{}{},
+ platform: "cursor",
+ wantSessionID: "",
+ wantTranscriptPath: "",
+ },
+ {
+ name: "claude extracts session_id and transcript_path",
+ input: map[string]interface{}{
+ "session_id": "sess_123",
+ "transcript_path": "/path/to/transcript.jsonl",
+ },
+ platform: "claude",
+ wantSessionID: "sess_123",
+ wantTranscriptPath: "/path/to/transcript.jsonl",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sessionID, transcriptPath := resolveSessionIDWithTranscript(tt.input, tt.platform)
+ if sessionID != tt.wantSessionID {
+ t.Errorf("sessionID = %q, want %q", sessionID, tt.wantSessionID)
+ }
+ if transcriptPath != tt.wantTranscriptPath {
+ t.Errorf("transcriptPath = %q, want %q", transcriptPath, tt.wantTranscriptPath)
+ }
+ })
+ }
+}
+
+func TestResolveCwd(t *testing.T) {
+ tests := []struct {
+ name string
+ input map[string]interface{}
+ platform string
+ envCwd string // CURSOR_PROJECT_DIR env var
+ want string
+ }{
+ {
+ name: "cursor uses cwd field",
+ input: map[string]interface{}{"cwd": "/projects/myapp"},
+ platform: "cursor",
+ want: "/projects/myapp",
+ },
+ {
+ name: "cursor falls back to workspace_roots",
+ input: map[string]interface{}{
+ "workspace_roots": []interface{}{"/workspace/root"},
+ },
+ platform: "cursor",
+ want: "/workspace/root",
+ },
+ {
+ name: "cursor falls back to CURSOR_PROJECT_DIR env",
+ input: map[string]interface{}{},
+ platform: "cursor",
+ envCwd: "/env/project/dir",
+ want: "/env/project/dir",
+ },
+ {
+ name: "cursor returns empty when no sources",
+ input: map[string]interface{}{},
+ platform: "cursor",
+ want: "",
+ },
+ {
+ name: "cursor cwd takes precedence over workspace_roots",
+ input: map[string]interface{}{
+ "cwd": "/projects/myapp",
+ "workspace_roots": []interface{}{"/workspace/root"},
+ },
+ platform: "cursor",
+ want: "/projects/myapp",
+ },
+ {
+ name: "claude uses cwd field",
+ input: map[string]interface{}{"cwd": "/projects/myapp"},
+ platform: "claude",
+ want: "/projects/myapp",
+ },
+ {
+ name: "claude returns empty when no cwd",
+ input: map[string]interface{}{},
+ platform: "claude",
+ want: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Set/unset CURSOR_PROJECT_DIR env var
+ if tt.envCwd != "" {
+ t.Setenv("CURSOR_PROJECT_DIR", tt.envCwd)
+ } else {
+ t.Setenv("CURSOR_PROJECT_DIR", "")
+ }
+ got := resolveCwd(tt.input, tt.platform)
+ if got != tt.want {
+ t.Errorf("resolveCwd() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestGetFirstStr(t *testing.T) {
+ input := map[string]interface{}{
+ "key1": "value1",
+ "key2": "",
+ "key3": "value3",
+ }
+
+ tests := []struct {
+ name string
+ keys []string
+ want string
+ }{
+ {"first key found", []string{"key1"}, "value1"},
+ {"skip empty, return second", []string{"key2", "key3"}, "value3"},
+ {"no matching key", []string{"nonexistent"}, ""},
+ {"first non-empty wins", []string{"key1", "key3"}, "value1"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := getFirstStr(input, tt.keys...)
+ if got != tt.want {
+ t.Errorf("getFirstStr() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.go
new file mode 100644
index 00000000..a6808a14
--- /dev/null
+++ b/cli/beacon-hooks/cmd/post_tool.go
@@ -0,0 +1,343 @@
+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",
+ Long: `PostToolUse hook - triggered after Write, Edit, or MultiEdit operations.
+The public Beacon build records local metadata and dependency scan findings only.`,
+ Run: runPostTool,
+}
+
+func init() {
+ rootCmd.AddCommand(postToolCmd)
+}
+
+// evaluationParams holds the platform-independent fields needed for local hook handling.
+type evaluationParams struct {
+ sessionID string
+ toolName string
+ filePath string
+ diffStr string
+}
+
+func runPostTool(cmd *cobra.Command, args []string) {
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(emptyResponse)
+ return
+ }
+
+ // Resolve session ID early so we can use per-session logger
+ sessionID := resolveSessionID(input, platformFlag)
+ var logger *logging.Logger
+ if sessionID != "" {
+ logger = logging.NewSessionLogger("post-tool-async-scan", platformFlag, sessionID)
+ } else {
+ logger = logging.NewLoggerForPlatform("post-tool-async-scan", platformFlag)
+ }
+
+ var params *evaluationParams
+
+ // Check if dep-scan is enabled before parsing, so parsers can allow dep files through
+ depScanEnabled := config.IsDepScanEnabled()
+
+ if platformFlag == "cursor" {
+ // Cursor fires two hook types through post-tool:
+ // - afterFileEdit: has "edits" array and top-level "file_path" (no output supported)
+ // - postToolUse: has "tool_name" and "tool_input" (supports additional_context/followup via stop)
+ // 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)
+ } else {
+ params = parseClaudeCopilotInput(input, logger, depScanEnabled)
+ }
+
+ if params == nil {
+ outputJSON(emptyResponse)
+ 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 {
+ sessionID := resolveSessionID(input, "cursor")
+ filePath, _ := input["file_path"].(string)
+ if sessionID == "" || filePath == "" {
+ return nil
+ }
+
+ if !config.IsScannableFile(filePath) && !(depScanEnabled && depscan.IsDependencyFile(filePath)) {
+ logger.Debug("Skipping non-scannable file: " + filePath)
+ return nil
+ }
+
+ // Construct diff from Cursor's edits array
+ edits, _ := input["edits"].([]interface{})
+ if len(edits) == 0 {
+ logger.Debug("No edits in input, skipping")
+ return nil
+ }
+
+ diffStr := diff.FromCursorEdits(filePath, edits)
+ if diffStr == "" {
+ logger.Debug("Could not construct diff from edits, skipping")
+ return nil
+ }
+
+ logger.Debug("Constructed diff from cursor edits", "file_path", filePath, "num_edits", len(edits))
+
+ return &evaluationParams{
+ sessionID: sessionID,
+ toolName: "afterFileEdit",
+ filePath: filePath,
+ diffStr: diffStr,
+ }
+}
+
+// parseClaudeCopilotInput extracts evaluation params from Claude/Copilot PostToolUse format.
+func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logger, depScanEnabled bool) *evaluationParams {
+ var sessionID, toolName string
+ var toolInput, toolResponse map[string]interface{}
+
+ if platformFlag == "copilot" {
+ sessionID = resolveSessionID(input, platformFlag)
+ toolName = getFirstStr(input, "toolName", "tool_name")
+ toolInput = resolveToolInput(input)
+ toolResponse = resolveToolResponse(input)
+ } else {
+ sessionID, _ = input["session_id"].(string)
+ toolName, _ = input["tool_name"].(string)
+ toolInput, _ = input["tool_input"].(map[string]interface{})
+ toolResponse, _ = input["tool_response"].(map[string]interface{})
+ }
+
+ if !isFileEditTool(platformFlag, toolName) {
+ return nil
+ }
+
+ filePath := diff.GetStringFromMaps("file_path", toolInput, toolResponse)
+ if filePath == "" {
+ filePath = diff.GetStringFromMaps("filePath", toolInput, toolResponse)
+ }
+
+ if sessionID == "" || toolName == "" || filePath == "" {
+ return nil
+ }
+
+ if !config.IsScannableFile(filePath) && !(depScanEnabled && depscan.IsDependencyFile(filePath)) {
+ logger.Debug("Skipping non-scannable file: " + filePath)
+ return nil
+ }
+
+ logger.Debug("Constructing diff", "tool_name", toolName, "file_path", filePath,
+ "has_tool_input", toolInput != nil, "has_tool_response", toolResponse != nil)
+
+ diffStr := diff.FromToolResponse(toolName, toolInput, toolResponse)
+ if diffStr == "" {
+ logger.Debug("Could not construct diff, skipping", "tool_name", toolName)
+ return nil
+ }
+
+ return &evaluationParams{
+ sessionID: sessionID,
+ toolName: toolName,
+ filePath: filePath,
+ diffStr: diffStr,
+ }
+}
+
+// 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)
+}
+
+// resolveToolInput extracts tool input from Copilot's various formats.
+func resolveToolInput(input map[string]interface{}) map[string]interface{} {
+ if m, ok := input["tool_input"].(map[string]interface{}); ok {
+ return m
+ }
+ // Fallback: some Copilot versions send toolArgs as stringified JSON
+ if argsStr, ok := input["toolArgs"].(string); ok && argsStr != "" {
+ var parsed map[string]interface{}
+ if err := json.Unmarshal([]byte(argsStr), &parsed); err == nil {
+ return parsed
+ }
+ }
+ if m, ok := input["toolArgs"].(map[string]interface{}); ok {
+ return m
+ }
+ return nil
+}
+
+// resolveToolResponse extracts tool response from Copilot's various formats.
+func resolveToolResponse(input map[string]interface{}) map[string]interface{} {
+ if m, ok := input["tool_response"].(map[string]interface{}); ok {
+ return m
+ }
+ if m, ok := input["toolResult"].(map[string]interface{}); ok {
+ return m
+ }
+ // If tool_response is a plain string, wrap it for downstream compatibility
+ if respStr, ok := input["tool_response"].(string); ok && respStr != "" {
+ return map[string]interface{}{"result": respStr}
+ }
+ 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
+ }
+
+ pkgNames := make([]string, len(packages))
+ for i, p := range packages {
+ pkgNames[i] = p.Name + "@" + p.Version
+ }
+ 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)
+ return
+ }
+
+ // Deduplicate and format
+ deduplicated := depscan.DeduplicateFindings(packages, findings)
+ report := depscan.FormatCVEReport(deduplicated)
+
+ totalCVEs := 0
+ for _, f := range deduplicated {
+ totalCVEs += len(f.CVEs)
+ }
+
+ 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,
+ }
+}
+
+// isFileEditTool returns true if the tool name represents a file edit operation.
+func isFileEditTool(platform, toolName string) bool {
+ if platform == "copilot" {
+ lower := strings.ToLower(toolName)
+ return strings.Contains(lower, "edit") ||
+ strings.Contains(lower, "write") ||
+ strings.Contains(lower, "create") ||
+ strings.Contains(lower, "patch")
+ }
+ if platform == "factory" {
+ return toolName == "Write" || toolName == "Edit" || toolName == "MultiEdit" || toolName == "Create"
+ }
+ return toolName == "Write" || toolName == "Edit" || toolName == "MultiEdit"
+}
diff --git a/cli/beacon-hooks/cmd/post_tool_test.go b/cli/beacon-hooks/cmd/post_tool_test.go
new file mode 100644
index 00000000..48fb99d4
--- /dev/null
+++ b/cli/beacon-hooks/cmd/post_tool_test.go
@@ -0,0 +1,76 @@
+package cmd
+
+import (
+ "testing"
+)
+
+func TestIsFileEditTool(t *testing.T) {
+ tests := []struct {
+ name string
+ platform string
+ toolName string
+ want bool
+ }{
+ // Claude tools
+ {"claude Write", "claude", "Write", true},
+ {"claude Edit", "claude", "Edit", true},
+ {"claude MultiEdit", "claude", "MultiEdit", true},
+ {"claude Read (not edit)", "claude", "Read", false},
+
+ // Copilot tools
+ {"copilot edit tool", "copilot", "copilot_insertEdit", true},
+ {"copilot write tool", "copilot", "copilot_createFile", true},
+ {"copilot patch tool", "copilot", "apply_patch", true},
+ {"copilot read (not edit)", "copilot", "readFile", false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := isFileEditTool(tt.platform, tt.toolName)
+ if got != tt.want {
+ t.Errorf("isFileEditTool(%q, %q) = %v, want %v", tt.platform, tt.toolName, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestResolveToolInput(t *testing.T) {
+ tests := []struct {
+ name string
+ input map[string]interface{}
+ want bool // whether result is non-nil
+ }{
+ {
+ name: "tool_input map",
+ input: map[string]interface{}{"tool_input": map[string]interface{}{"file_path": "/test.py"}},
+ want: true,
+ },
+ {
+ name: "toolArgs string JSON",
+ input: map[string]interface{}{"toolArgs": `{"file_path": "/test.py"}`},
+ want: true,
+ },
+ {
+ name: "toolArgs map",
+ input: map[string]interface{}{"toolArgs": map[string]interface{}{"file_path": "/test.py"}},
+ want: true,
+ },
+ {
+ name: "empty input",
+ input: map[string]interface{}{},
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := resolveToolInput(tt.input)
+ if tt.want && got == nil {
+ t.Error("resolveToolInput() = nil, want non-nil")
+ }
+ if !tt.want && got != nil {
+ t.Errorf("resolveToolInput() = %v, want nil", got)
+ }
+ })
+ }
+}
diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.go
new file mode 100644
index 00000000..67e22507
--- /dev/null
+++ b/cli/beacon-hooks/cmd/pre_tool.go
@@ -0,0 +1,106 @@
+package cmd
+
+import (
+ "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/logging"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+)
+
+var preToolCmd = &cobra.Command{
+ Use: "pre-tool",
+ Short: "Gate file writes to inject security policy context",
+ Long: `PreToolUse hook - triggered before a Write tool execution in Cursor.
+On the first Write of a prompt cycle, denies the operation to inject cached
+security policies into the agent's context. Subsequent writes are allowed.`,
+ Run: runPreTool,
+}
+
+func init() {
+ rootCmd.AddCommand(preToolCmd)
+}
+
+// allowResponse is the standard allow response for preToolUse.
+var allowResponse = map[string]interface{}{"permission": "allow"}
+
+func runPreTool(cmd *cobra.Command, args []string) {
+ start := time.Now()
+
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(allowResponse)
+ return
+ }
+
+ sessionID := resolveSessionID(input, platformFlag)
+ var logger *logging.Logger
+ if sessionID != "" {
+ logger = logging.NewSessionLogger("pre-tool", platformFlag, sessionID)
+ } else {
+ logger = logging.NewLoggerForPlatform("pre-tool", platformFlag)
+ }
+
+ // Short-circuit: SbD disabled → no-op
+ if !config.IsSecureByDesignEnabled(platformFlag) {
+ logger.Debug("Secure by design is disabled, allowing")
+ outputJSON(allowResponse)
+ return
+ }
+
+ if sessionID == "" {
+ logger.Debug("No session ID, allowing")
+ outputJSON(allowResponse)
+ return
+ }
+
+ // Read generation_id from input to validate against stored state
+ inputGenerationID, _ := input["generation_id"].(string)
+
+ // Check SbD state for this conversation
+ st := state.NewSessionState(sessionID, platformFlag)
+ policies, storedGenerationID, injected := st.GetSbdState()
+
+ // No policies cached → no-op
+ if policies == "" {
+ logger.Debug("No policies cached, allowing")
+ outputJSON(allowResponse)
+ return
+ }
+
+ // Generation mismatch → stale state, allow through
+ if inputGenerationID != "" && storedGenerationID != "" && inputGenerationID != storedGenerationID {
+ logger.Debug("Generation ID mismatch, allowing Write (stale state)",
+ "input_generation_id", inputGenerationID,
+ "stored_generation_id", storedGenerationID)
+ outputJSON(allowResponse)
+ return
+ }
+
+ // Already injected for this generation → allow
+ if injected {
+ logger.Debug("Policy already injected, allowing Write",
+ "generation_id", storedGenerationID)
+ outputJSON(allowResponse)
+ return
+ }
+
+ // First Write of this generation: deny once to inject policy context
+ st.MarkSbdInjected()
+
+ message := policies + "You must comply with these policies. Retry your file write with policy-compliant code, or inform the user if the requested change would violate a policy."
+
+ elapsed := time.Since(start)
+ logger.Info("Policy gate: denying Write for context injection",
+ "generation_id", storedGenerationID,
+ "policy_length", len(policies),
+ "duration_ms", elapsed.Milliseconds())
+
+ outputJSON(map[string]interface{}{
+ "permission": "deny",
+ "user_message": message,
+ "agent_message": message,
+ })
+}
diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.go
new file mode 100644
index 00000000..d932c097
--- /dev/null
+++ b/cli/beacon-hooks/cmd/pre_tool_test.go
@@ -0,0 +1,246 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+
+ hookconfig "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+)
+
+func TestRunPreToolSecureByDesignGateBranches(t *testing.T) {
+ tests := []struct {
+ name string
+ enableSBD bool
+ sessionID string
+ inputGen string
+ storedGen string
+ policies string
+ injected bool
+ wantPerm string
+ wantInject bool
+ }{
+ {
+ name: "disabled allows",
+ sessionID: "conv-disabled",
+ policies: "policy\n",
+ wantPerm: "allow",
+ },
+ {
+ name: "missing session allows",
+ enableSBD: true,
+ wantPerm: "allow",
+ },
+ {
+ name: "no policies allows",
+ enableSBD: true,
+ sessionID: "conv-no-policies",
+ wantPerm: "allow",
+ },
+ {
+ name: "generation mismatch allows",
+ enableSBD: true,
+ sessionID: "conv-stale",
+ inputGen: "gen-2",
+ storedGen: "gen-1",
+ policies: "policy\n",
+ wantPerm: "allow",
+ },
+ {
+ name: "already injected allows",
+ enableSBD: true,
+ sessionID: "conv-injected",
+ inputGen: "gen-1",
+ storedGen: "gen-1",
+ policies: "policy\n",
+ injected: true,
+ wantPerm: "allow",
+ },
+ {
+ name: "first write denies and marks injected",
+ enableSBD: true,
+ sessionID: "conv-deny",
+ inputGen: "gen-1",
+ storedGen: "gen-1",
+ policies: "policy\n",
+ wantPerm: "deny",
+ wantInject: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "cursor"
+ if tt.enableSBD {
+ writePlatformConfig(t, "cursor", `{"secure_by_design":true}`)
+ }
+ if tt.sessionID != "" && tt.policies != "" {
+ st := state.NewSessionState(tt.sessionID, "cursor")
+ st.SetSbdPolicies(tt.policies, tt.storedGen)
+ if tt.injected {
+ st.MarkSbdInjected()
+ }
+ }
+
+ input := map[string]interface{}{}
+ if tt.sessionID != "" {
+ input["conversation_id"] = tt.sessionID
+ }
+ if tt.inputGen != "" {
+ input["generation_id"] = tt.inputGen
+ }
+ out := runHookWithInput(t, runPreTool, input)
+
+ if out["permission"] != tt.wantPerm {
+ t.Fatalf("permission = %v, want %s; output=%#v", out["permission"], tt.wantPerm, out)
+ }
+ if tt.wantPerm == "deny" {
+ message, _ := out["agent_message"].(string)
+ if !strings.Contains(message, tt.policies) || !strings.Contains(message, "Retry your file write") {
+ t.Fatalf("deny message missing policy context: %#v", out)
+ }
+ }
+ if tt.sessionID != "" {
+ _, _, injected := state.NewSessionState(tt.sessionID, "cursor").GetSbdState()
+ if injected != (tt.injected || tt.wantInject) {
+ t.Fatalf("injected = %v, want %v", injected, tt.injected || tt.wantInject)
+ }
+ }
+ })
+ }
+}
+
+func TestRunPromptSubmitClearsSbdPoliciesAndUsesCursorResponse(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "cursor"
+ st := state.NewSessionState("conv-clear", "cursor")
+ st.SetSbdPolicies("policy", "gen-1")
+
+ out := runHookWithInput(t, runPromptSubmit, map[string]interface{}{"conversation_id": "conv-clear"})
+ if out["continue"] != true {
+ t.Fatalf("cursor prompt response = %#v, want continue=true", out)
+ }
+ policies, generationID, injected := st.GetSbdState()
+ if policies != "" || generationID != "" || injected {
+ t.Fatalf("SbD state was not cleared: policies=%q generation=%q injected=%v", policies, generationID, injected)
+ }
+}
+
+func TestRunSessionStartStoresModel(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "cursor"
+
+ out := runHookWithInput(t, runSessionStart, map[string]interface{}{
+ "conversation_id": "conv-model",
+ "model": "gpt-5.5",
+ })
+ if len(out) != 0 {
+ t.Fatalf("session-start response = %#v, want empty response", out)
+ }
+ if got := state.NewSessionState("conv-model", "cursor").GetModel(); got != "gpt-5.5" {
+ t.Fatalf("stored model = %q, want gpt-5.5", got)
+ }
+}
+
+func TestRunSessionEndRemovesSessionLog(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "cursor"
+ logFile := hookconfig.GetSessionLogFile("cursor", "conv-end")
+ if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil {
+ t.Fatalf("mkdir session log dir: %v", err)
+ }
+ if err := os.WriteFile(logFile, []byte("session log"), 0644); err != nil {
+ t.Fatalf("write session log: %v", err)
+ }
+
+ out := runHookWithInput(t, runSessionEnd, map[string]interface{}{"conversation_id": "conv-end"})
+ if len(out) != 0 {
+ t.Fatalf("session-end response = %#v, want empty response", out)
+ }
+ if _, err := os.Stat(logFile); !os.IsNotExist(err) {
+ t.Fatalf("session log still exists or unexpected error: %v", err)
+ }
+}
+
+func setupHookConfigDirs(t *testing.T) {
+ t.Helper()
+ tmp := t.TempDir()
+ origBeaconDir := hookconfig.BeaconDir
+ origClaudeDir := hookconfig.ClaudeDir
+ origCopilotDir := hookconfig.CopilotDir
+ origCursorDir := hookconfig.CursorDir
+ origFactoryDir := hookconfig.FactoryDir
+ origPlatform := platformFlag
+ hookconfig.BeaconDir = tmp
+ hookconfig.ClaudeDir = filepath.Join(tmp, "claude")
+ hookconfig.CopilotDir = filepath.Join(tmp, "copilot")
+ hookconfig.CursorDir = filepath.Join(tmp, "cursor")
+ hookconfig.FactoryDir = filepath.Join(tmp, "factory")
+ t.Cleanup(func() {
+ hookconfig.BeaconDir = origBeaconDir
+ hookconfig.ClaudeDir = origClaudeDir
+ hookconfig.CopilotDir = origCopilotDir
+ hookconfig.CursorDir = origCursorDir
+ hookconfig.FactoryDir = origFactoryDir
+ platformFlag = origPlatform
+ })
+}
+
+func writePlatformConfig(t *testing.T, platform, body string) {
+ t.Helper()
+ path := filepath.Join(hookconfig.GetStateDir(platform), "config.json")
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatalf("mkdir platform config dir: %v", err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0644); err != nil {
+ t.Fatalf("write platform config: %v", err)
+ }
+}
+
+func runHookWithInput(t *testing.T, run func(cmd *cobra.Command, args []string), input map[string]interface{}) map[string]interface{} {
+ t.Helper()
+ stdinR, stdinW, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("create stdin pipe: %v", err)
+ }
+ stdoutR, stdoutW, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("create stdout pipe: %v", err)
+ }
+ origStdin := os.Stdin
+ origStdout := os.Stdout
+ os.Stdin = stdinR
+ os.Stdout = stdoutW
+ defer func() {
+ os.Stdin = origStdin
+ os.Stdout = origStdout
+ _ = stdinR.Close()
+ _ = stdoutR.Close()
+ }()
+
+ if err := json.NewEncoder(stdinW).Encode(input); err != nil {
+ t.Fatalf("encode input: %v", err)
+ }
+ if err := stdinW.Close(); err != nil {
+ t.Fatalf("close stdin writer: %v", err)
+ }
+
+ run(nil, nil)
+
+ if err := stdoutW.Close(); err != nil {
+ t.Fatalf("close stdout writer: %v", err)
+ }
+ os.Stdin = origStdin
+ os.Stdout = origStdout
+ var out map[string]interface{}
+ if err := json.NewDecoder(stdoutR).Decode(&out); err != nil {
+ t.Fatalf("decode hook output: %v", err)
+ }
+ return out
+}
diff --git a/cli/beacon-hooks/cmd/prompt_submit.go b/cli/beacon-hooks/cmd/prompt_submit.go
new file mode 100644
index 00000000..5e2e02b1
--- /dev/null
+++ b/cli/beacon-hooks/cmd/prompt_submit.go
@@ -0,0 +1,53 @@
+package cmd
+
+import (
+ "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/logging"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+)
+
+var promptSubmitCmd = &cobra.Command{
+ Use: "prompt-submit",
+ Short: "Handle prompt submission for local endpoint telemetry",
+ Long: `UserPromptSubmit hook - triggered when the user submits a prompt.
+The public Beacon build does not fetch hosted policies or inject remote context.`,
+ Run: runPromptSubmit,
+}
+
+func init() {
+ rootCmd.AddCommand(promptSubmitCmd)
+}
+
+func runPromptSubmit(cmd *cobra.Command, args []string) {
+ noopResponse := emptyResponse
+ if platformFlag == "cursor" {
+ noopResponse = map[string]interface{}{"continue": true}
+ }
+
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(noopResponse)
+ return
+ }
+
+ sessionID := resolveSessionID(input, platformFlag)
+ var logger *logging.Logger
+ if sessionID != "" {
+ logger = logging.NewSessionLogger("prompt-submit", platformFlag, sessionID)
+ } else {
+ logger = logging.NewLoggerForPlatform("prompt-submit", platformFlag)
+ }
+
+ if sessionID != "" {
+ state.NewSessionState(sessionID, platformFlag).ClearSbdPolicies()
+ }
+ if config.IsSecureByDesignEnabled(platformFlag) {
+ logger.Warn("Secure by Design policy injection is unavailable in the local-only Beacon build")
+ } else {
+ logger.Debug("Prompt submit observed")
+ }
+
+ outputJSON(noopResponse)
+}
diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.go
new file mode 100644
index 00000000..ef962ab1
--- /dev/null
+++ b/cli/beacon-hooks/cmd/root.go
@@ -0,0 +1,33 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/spf13/cobra"
+)
+
+var platformFlag string
+
+var rootCmd = &cobra.Command{
+ Use: "beacon-hooks",
+ Short: "Beacon hooks for Claude Code, GitHub Copilot, Cursor, and Factory",
+ Long: `Beacon hooks binary for Claude Code, GitHub Copilot, Cursor, and Factory integration.
+
+This binary provides hook commands that are called by IDE plugin systems
+to evaluate code changes for security violations.
+
+Use --platform to specify the calling platform (default: claude).`,
+}
+
+func init() {
+ rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, copilot, cursor, or factory")
+}
+
+// Execute runs the root command
+func Execute() {
+ if err := rootCmd.Execute(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/cli/beacon-hooks/cmd/session_end.go b/cli/beacon-hooks/cmd/session_end.go
new file mode 100644
index 00000000..c34e3d0b
--- /dev/null
+++ b/cli/beacon-hooks/cmd/session_end.go
@@ -0,0 +1,51 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+
+ "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/logging"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+)
+
+var sessionEndCmd = &cobra.Command{
+ Use: "session-end",
+ Short: "Cleanup session data when coding session exits",
+ Long: `SessionEnd hook - triggered when the coding session terminates.`,
+ Run: runSessionEnd,
+}
+
+func init() {
+ rootCmd.AddCommand(sessionEndCmd)
+}
+
+func runSessionEnd(cmd *cobra.Command, args []string) {
+ platformLogger := logging.NewLoggerForPlatform("session-end", platformFlag)
+
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(emptyResponse)
+ return
+ }
+
+ sessionID := resolveSessionID(input, platformFlag)
+ if sessionID != "" {
+ logger := logging.NewSessionLogger("session-end", platformFlag, sessionID)
+ logger.Info("Session ended", "session_id", sessionID, "platform", platformFlag)
+
+ logFile := config.GetSessionLogFile(platformFlag, sessionID)
+ if err := os.Remove(logFile); err != nil && !os.IsNotExist(err) {
+ platformLogger.Warn("Failed to remove session log", "session_id", sessionID, "error", err.Error())
+ }
+ }
+
+ cleaned := state.CleanupStaleForPlatform(platformFlag)
+ if cleaned > 0 {
+ platformLogger.Info(fmt.Sprintf("Cleaned up %d stale sessions", cleaned))
+ }
+
+ outputJSON(emptyResponse)
+}
diff --git a/cli/beacon-hooks/cmd/session_start.go b/cli/beacon-hooks/cmd/session_start.go
new file mode 100644
index 00000000..fcfea133
--- /dev/null
+++ b/cli/beacon-hooks/cmd/session_start.go
@@ -0,0 +1,60 @@
+package cmd
+
+import (
+ "fmt"
+
+ "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/logging"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+)
+
+var sessionStartCmd = &cobra.Command{
+ Use: "session-start",
+ Short: "Initialize session and cleanup stale data",
+ Long: `SessionStart hook - triggered when a new coding session begins.`,
+ Run: runSessionStart,
+}
+
+func init() {
+ rootCmd.AddCommand(sessionStartCmd)
+}
+
+func runSessionStart(cmd *cobra.Command, args []string) {
+ platformLogger := logging.NewLoggerForPlatform("session-start", platformFlag)
+
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(emptyResponse)
+ return
+ }
+
+ sessionID := resolveSessionID(input, platformFlag)
+ if sessionID == "" {
+ outputJSON(emptyResponse)
+ return
+ }
+
+ // Switch to per-session logger now that we have a session ID
+ logger := logging.NewSessionLogger("session-start", platformFlag, sessionID)
+
+ if config.RotateLogIfNeededForPlatform(platformFlag) {
+ platformLogger.Info("Rotated log file (exceeded size limit)")
+ }
+
+ cleaned := state.CleanupStaleForPlatform(platformFlag)
+ if cleaned > 0 {
+ logger.Info(fmt.Sprintf("Cleaned up %d stale evaluations", cleaned))
+ }
+
+ // Persist model name so post-tool can include it in evaluations
+ if model, ok := input["model"].(string); ok && model != "" {
+ st := state.NewSessionState(sessionID, platformFlag)
+ st.SetModel(model)
+ logger.Debug("Stored session model", "model", model)
+ }
+
+ logger.Info("Session initialized", "session_id", sessionID, "platform", platformFlag)
+ outputJSON(emptyResponse)
+}
diff --git a/cli/beacon-hooks/cmd/stop.go b/cli/beacon-hooks/cmd/stop.go
new file mode 100644
index 00000000..9b0ef5a0
--- /dev/null
+++ b/cli/beacon-hooks/cmd/stop.go
@@ -0,0 +1,417 @@
+package cmd
+
+import (
+ "bufio"
+ "encoding/json"
+ "os"
+ "regexp"
+ "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/logging"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+)
+
+var stopCmd = &cobra.Command{
+ Use: "stop",
+ Short: "Deliver local dependency scan findings",
+ 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.`,
+ Run: runStop,
+}
+
+func init() {
+ rootCmd.AddCommand(stopCmd)
+}
+
+func runStop(cmd *cobra.Command, args []string) {
+ start := time.Now()
+
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSONAndExit(emptyResponse)
+ return
+ }
+
+ sessionID, transcriptPath := resolveSessionIDWithTranscript(input, platformFlag)
+
+ var logger *logging.Logger
+ if sessionID != "" {
+ logger = logging.NewSessionLogger("stop", platformFlag, sessionID)
+ } else {
+ logger = logging.NewLoggerForPlatform("stop", platformFlag)
+ }
+
+ logger.Debug("Stop hook called", "session_id", sessionID, "has_transcript", transcriptPath != "", "platform", platformFlag)
+ if sessionID == "" {
+ outputJSONAndExit(emptyResponse)
+ return
+ }
+
+ 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.
+ pendingEvals := st.GetPendingEvaluations()
+ if len(pendingEvals) > 0 {
+ st.ClearEvaluations()
+ 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})
+ }
+}
+
+// platformToTranscriptName maps the platform flag to the transcript platform identifier.
+func platformToTranscriptName(platform string) string {
+ switch platform {
+ case "copilot":
+ return "copilot"
+ case "cursor":
+ return "cursor"
+ case "factory":
+ return "factory"
+ default:
+ return "claude_code"
+ }
+}
+
+// extractMessages dispatches to the correct transcript parser based on platform.
+func extractMessages(transcriptPath, platform string) []map[string]interface{} {
+ switch platform {
+ case "copilot":
+ return extractMessagesFromCopilotTranscript(transcriptPath)
+ case "cursor":
+ return extractMessagesFromCursorTranscript(transcriptPath)
+ case "factory":
+ return extractMessagesFromFactoryTranscript(transcriptPath)
+ default:
+ return extractMessagesFromClaudeTranscript(transcriptPath)
+ }
+}
+
+// extractMessagesFromClaudeTranscript parses Claude Code's JSONL transcript format.
+func extractMessagesFromClaudeTranscript(transcriptPath string) []map[string]interface{} {
+ file, err := os.Open(transcriptPath)
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+
+ var messages []map[string]interface{}
+ decoder := json.NewDecoder(file)
+ for decoder.More() {
+ var entry map[string]interface{}
+ if err := decoder.Decode(&entry); err != nil {
+ break
+ }
+
+ msgType, _ := entry["type"].(string)
+ message, _ := entry["message"].(map[string]interface{})
+
+ // Skip meta entries (e.g., Conductor local-command-caveat messages),
+ // but preserve stop hook feedback which also has isMeta=true.
+ if isMeta, _ := entry["isMeta"].(bool); isMeta {
+ if !isStopHookFeedback(entry) {
+ continue
+ }
+ }
+
+ switch msgType {
+ case "user":
+ var userContent string
+ if content, ok := message["content"].(string); ok && content != "" {
+ // Terminal Claude Code: content is a plain string
+ if isLocalCommandBlock(content) {
+ continue
+ }
+ userContent = stripSystemInstructions(content)
+ } else if contentBlocks, ok := message["content"].([]interface{}); ok {
+ // VS Code Claude Code: content is an array of content blocks
+ userContent = extractTextFromBlocks(contentBlocks, true)
+ }
+ if userContent != "" {
+ messages = append(messages, map[string]interface{}{
+ "role": "user",
+ "content": userContent,
+ })
+ }
+ case "assistant":
+ contentBlocks, _ := message["content"].([]interface{})
+ if text := extractTextFromBlocks(contentBlocks, false); text != "" {
+ messages = append(messages, map[string]interface{}{
+ "role": "assistant",
+ "content": text,
+ })
+ }
+ }
+ }
+
+ return messages
+}
+
+// extractMessagesFromCopilotTranscript parses Copilot's JSONL transcript format.
+func extractMessagesFromCopilotTranscript(transcriptPath string) []map[string]interface{} {
+ file, err := os.Open(transcriptPath)
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+
+ var messages []map[string]interface{}
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
+
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if len(line) == 0 {
+ continue
+ }
+
+ var entry map[string]interface{}
+ if err := json.Unmarshal(line, &entry); err != nil {
+ continue
+ }
+
+ entryType, _ := entry["type"].(string)
+ data, _ := entry["data"].(map[string]interface{})
+ if data == nil {
+ continue
+ }
+
+ var role string
+ switch entryType {
+ case "user.message":
+ role = "user"
+ case "assistant.message":
+ role = "assistant"
+ default:
+ continue
+ }
+
+ if content, ok := data["content"].(string); ok && content != "" {
+ messages = append(messages, map[string]interface{}{
+ "role": role,
+ "content": content,
+ })
+ }
+ }
+
+ return messages
+}
+
+// extractMessagesFromCursorTranscript parses Cursor's JSONL transcript format.
+// Format: {"role":"user","message":{"content":[{"type":"text","text":"..."}]}}
+func extractMessagesFromCursorTranscript(transcriptPath string) []map[string]interface{} {
+ file, err := os.Open(transcriptPath)
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+
+ var messages []map[string]interface{}
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
+
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if len(line) == 0 {
+ continue
+ }
+
+ var entry map[string]interface{}
+ if err := json.Unmarshal(line, &entry); err != nil {
+ continue
+ }
+
+ role, _ := entry["role"].(string)
+ if role != "user" && role != "assistant" {
+ continue
+ }
+
+ message, _ := entry["message"].(map[string]interface{})
+ if message == nil {
+ continue
+ }
+
+ contentBlocks, _ := message["content"].([]interface{})
+ if text := extractTextFromBlocks(contentBlocks, false); text != "" {
+ content := stripCursorXMLTags(text)
+ if content != "" {
+ messages = append(messages, map[string]interface{}{
+ "role": role,
+ "content": content,
+ })
+ }
+ }
+ }
+
+ return messages
+}
+
+// cursorXMLTagPattern matches known Cursor-injected wrapper tags in transcript text.
+// These tags are added by Cursor to wrap user input and context — they are not part
+// of the actual conversation content.
+// Known tags: <user_query>, <attached_files>, <git_diff_from_branch_to_main>
+var cursorXMLTagPattern = regexp.MustCompile(`</?(?:user_query|attached_files|git_diff_from_branch_to_main)>`)
+
+// stripCursorXMLTags removes Cursor's wrapper tags from transcript text.
+func stripCursorXMLTags(text string) string {
+ text = cursorXMLTagPattern.ReplaceAllString(text, "")
+ return strings.TrimSpace(text)
+}
+
+// extractMessagesFromFactoryTranscript parses Factory's JSONL transcript format.
+// Format: {"type":"message","message":{"role":"user"|"assistant","content":[{"type":"text","text":"..."}]}}
+// Skips tool_use-only assistant messages and tool_result-only user messages.
+func extractMessagesFromFactoryTranscript(transcriptPath string) []map[string]interface{} {
+ file, err := os.Open(transcriptPath)
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+
+ var messages []map[string]interface{}
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
+
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if len(line) == 0 {
+ continue
+ }
+
+ var entry map[string]interface{}
+ if err := json.Unmarshal(line, &entry); err != nil {
+ continue
+ }
+
+ entryType, _ := entry["type"].(string)
+ if entryType != "message" {
+ continue
+ }
+
+ message, _ := entry["message"].(map[string]interface{})
+ if message == nil {
+ continue
+ }
+
+ role, _ := message["role"].(string)
+ if role != "user" && role != "assistant" {
+ continue
+ }
+
+ contentBlocks, _ := message["content"].([]interface{})
+
+ // Skip messages that have no text blocks (e.g., tool_use-only or tool_result-only)
+ if !hasTextBlocks(contentBlocks) {
+ continue
+ }
+
+ if text := extractTextFromBlocks(contentBlocks, role == "user"); text != "" {
+ messages = append(messages, map[string]interface{}{
+ "role": role,
+ "content": text,
+ })
+ }
+ }
+
+ return messages
+}
+
+// hasTextBlocks returns true if the content blocks contain at least one text block.
+func hasTextBlocks(blocks []interface{}) bool {
+ for _, block := range blocks {
+ blockMap, ok := block.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if blockMap["type"] == "text" {
+ return true
+ }
+ }
+ return false
+}
+
+// extractTextFromBlocks extracts and joins text content from an array of content blocks.
+// When filterIDEContext is true, IDE-injected context blocks are excluded (for user messages).
+func extractTextFromBlocks(blocks []interface{}, filterIDEContext bool) string {
+ var parts []string
+ for _, block := range blocks {
+ blockMap, ok := block.(map[string]interface{})
+ if !ok || blockMap["type"] != "text" {
+ continue
+ }
+ text, ok := blockMap["text"].(string)
+ if !ok || text == "" {
+ continue
+ }
+ if filterIDEContext && isIDEContextBlock(text) {
+ continue
+ }
+ parts = append(parts, text)
+ }
+ return strings.Join(parts, " ")
+}
+
+// isIDEContextBlock checks if a text block is IDE-injected context
+// (e.g. <ide_opened_file>...</ide_opened_file> or <system-reminder>...</system-reminder>)
+func isIDEContextBlock(text string) bool {
+ trimmed := strings.TrimSpace(text)
+ return strings.HasPrefix(trimmed, "<ide_") ||
+ strings.HasPrefix(trimmed, "<system-reminder>") ||
+ strings.HasPrefix(trimmed, "<system_instruction>") ||
+ strings.HasPrefix(trimmed, "<system-instruction>") ||
+ strings.HasPrefix(trimmed, "<local-command-caveat>") ||
+ strings.HasPrefix(trimmed, "<command-name>") ||
+ strings.HasPrefix(trimmed, "<local-command-stdout>")
+}
+
+// isStopHookFeedback checks if a transcript entry is stop hook feedback from Beacon.
+// These entries have isMeta=true but contain security feedback that should be in the transcript.
+func isStopHookFeedback(entry map[string]interface{}) bool {
+ msgType, _ := entry["type"].(string)
+ if msgType != "user" {
+ return false
+ }
+ message, _ := entry["message"].(map[string]interface{})
+ if message == nil {
+ return false
+ }
+ content, _ := message["content"].(string)
+ return strings.HasPrefix(content, "Stop hook feedback:")
+}
+
+// isLocalCommandBlock checks if a plain-string user message is a Conductor local command block.
+func isLocalCommandBlock(text string) bool {
+ trimmed := strings.TrimSpace(text)
+ return strings.HasPrefix(trimmed, "<local-command-caveat>") ||
+ strings.HasPrefix(trimmed, "<command-name>") ||
+ strings.HasPrefix(trimmed, "<local-command-stdout>")
+}
+
+// systemInstructionPattern matches <system_instruction>...</system_instruction> and
+// <system-instruction>...</system-instruction> blocks including their content.
+var systemInstructionPattern = regexp.MustCompile(`(?s)<system[_-]instruction>.*?</system[_-]instruction>\s*`)
+
+// stripSystemInstructions removes system instruction blocks from user message text.
+func stripSystemInstructions(text string) string {
+ return strings.TrimSpace(systemInstructionPattern.ReplaceAllString(text, ""))
+}
diff --git a/cli/beacon-hooks/cmd/stop_test.go b/cli/beacon-hooks/cmd/stop_test.go
new file mode 100644
index 00000000..7f642a2a
--- /dev/null
+++ b/cli/beacon-hooks/cmd/stop_test.go
@@ -0,0 +1,246 @@
+package cmd
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestPlatformToTranscriptName(t *testing.T) {
+ tests := []struct {
+ platform string
+ want string
+ }{
+ {"claude", "claude_code"},
+ {"copilot", "copilot"},
+ {"cursor", "cursor"},
+ {"unknown", "claude_code"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.platform, func(t *testing.T) {
+ got := platformToTranscriptName(tt.platform)
+ if got != tt.want {
+ t.Errorf("platformToTranscriptName(%q) = %q, want %q", tt.platform, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestExtractMessagesFromCursorTranscript(t *testing.T) {
+ // Create a temp transcript file matching Cursor's format
+ tmpDir := t.TempDir()
+ transcriptPath := filepath.Join(tmpDir, "transcript.jsonl")
+
+ content := `{"role":"user","message":{"content":[{"type":"text","text":"<user_query>\nPlease fix the bug\n</user_query>"}]}}
+{"role":"assistant","message":{"content":[{"type":"text","text":"I'll fix the bug now."}]}}
+{"role":"user","message":{"content":[{"type":"text","text":"<user_query>\nThanks!\n</user_query>"}]}}
+{"role":"assistant","message":{"content":[{"type":"text","text":"You're welcome!"},{"type":"text","text":"Let me know if you need anything else."}]}}
+`
+
+ if err := os.WriteFile(transcriptPath, []byte(content), 0644); err != nil {
+ t.Fatalf("Failed to write transcript: %v", err)
+ }
+
+ messages := extractMessagesFromCursorTranscript(transcriptPath)
+
+ if len(messages) != 4 {
+ t.Fatalf("Expected 4 messages, got %d", len(messages))
+ }
+
+ // Check first user message
+ if messages[0]["role"] != "user" {
+ t.Errorf("Message 0 role = %q, want 'user'", messages[0]["role"])
+ }
+ if messages[0]["content"] != "Please fix the bug" {
+ t.Errorf("Message 0 content = %q, want 'Please fix the bug'", messages[0]["content"])
+ }
+
+ // Check first assistant message
+ if messages[1]["role"] != "assistant" {
+ t.Errorf("Message 1 role = %q, want 'assistant'", messages[1]["role"])
+ }
+ if messages[1]["content"] != "I'll fix the bug now." {
+ t.Errorf("Message 1 content = %q", messages[1]["content"])
+ }
+
+ // Check multi-block assistant message (blocks joined with space)
+ if messages[3]["role"] != "assistant" {
+ t.Errorf("Message 3 role = %q, want 'assistant'", messages[3]["role"])
+ }
+ expected := "You're welcome! Let me know if you need anything else."
+ if messages[3]["content"] != expected {
+ t.Errorf("Message 3 content = %q, want %q", messages[3]["content"], expected)
+ }
+}
+
+func TestExtractMessagesFromCursorTranscript_SkipsNonTextBlocks(t *testing.T) {
+ tmpDir := t.TempDir()
+ transcriptPath := filepath.Join(tmpDir, "transcript.jsonl")
+
+ // Include a non-text block (e.g., tool_use) that should be skipped
+ content := `{"role":"assistant","message":{"content":[{"type":"tool_use","name":"write_file"},{"type":"text","text":"Done editing."}]}}
+`
+
+ if err := os.WriteFile(transcriptPath, []byte(content), 0644); err != nil {
+ t.Fatalf("Failed to write transcript: %v", err)
+ }
+
+ messages := extractMessagesFromCursorTranscript(transcriptPath)
+
+ if len(messages) != 1 {
+ t.Fatalf("Expected 1 message, got %d", len(messages))
+ }
+ if messages[0]["content"] != "Done editing." {
+ t.Errorf("content = %q, want 'Done editing.'", messages[0]["content"])
+ }
+}
+
+func TestExtractMessagesFromCursorTranscript_EmptyFile(t *testing.T) {
+ tmpDir := t.TempDir()
+ transcriptPath := filepath.Join(tmpDir, "transcript.jsonl")
+
+ if err := os.WriteFile(transcriptPath, []byte(""), 0644); err != nil {
+ t.Fatalf("Failed to write transcript: %v", err)
+ }
+
+ messages := extractMessagesFromCursorTranscript(transcriptPath)
+ if len(messages) != 0 {
+ t.Errorf("Expected 0 messages from empty file, got %d", len(messages))
+ }
+}
+
+func TestExtractMessagesFromCursorTranscript_FileNotFound(t *testing.T) {
+ messages := extractMessagesFromCursorTranscript("/nonexistent/path.jsonl")
+ if messages != nil {
+ t.Errorf("Expected nil for nonexistent file, got %v", messages)
+ }
+}
+
+func TestExtractMessagesFromClaudeTranscript_IncludesStopHookFeedback(t *testing.T) {
+ tmpDir := t.TempDir()
+ transcriptPath := filepath.Join(tmpDir, "transcript.jsonl")
+
+ // Simulate a Claude Code transcript with:
+ // 1. A normal user message
+ // 2. An assistant response
+ // 3. A stop hook feedback message (isMeta=true, should be included)
+ // 4. A system stop_hook_summary (should be excluded - type "system")
+ // 5. A Conductor meta message (isMeta=true, should be excluded)
+ content := `{"type":"user","message":{"role":"user","content":"write a vulnerable file"},"uuid":"u1"}
+{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Here is the file."}]},"uuid":"a1"}
+{"type":"user","message":{"role":"user","content":"Stop hook feedback:\n## Security Vulnerabilities Detected\n\nPlease fix these issues."},"isMeta":true,"uuid":"u2"}
+{"type":"system","subtype":"stop_hook_summary","hookErrors":["## Security Vulnerabilities Detected"],"uuid":"s1"}
+{"type":"user","message":{"role":"user","content":"<local-command-caveat>some conductor metadata</local-command-caveat>"},"isMeta":true,"uuid":"u3"}
+`
+
+ if err := os.WriteFile(transcriptPath, []byte(content), 0644); err != nil {
+ t.Fatalf("Failed to write transcript: %v", err)
+ }
+
+ messages := extractMessagesFromClaudeTranscript(transcriptPath)
+
+ if len(messages) != 3 {
+ t.Fatalf("Expected 3 messages (user + assistant + stop hook feedback), got %d", len(messages))
+ }
+
+ // First message: normal user message
+ if messages[0]["role"] != "user" || messages[0]["content"] != "write a vulnerable file" {
+ t.Errorf("Message 0: unexpected content %v", messages[0])
+ }
+
+ // Second message: assistant response
+ if messages[1]["role"] != "assistant" || messages[1]["content"] != "Here is the file." {
+ t.Errorf("Message 1: unexpected content %v", messages[1])
+ }
+
+ // Third message: stop hook feedback (should NOT be filtered despite isMeta=true)
+ content3, _ := messages[2]["content"].(string)
+ if messages[2]["role"] != "user" || content3 == "" {
+ t.Errorf("Message 2: expected stop hook feedback as user message, got %v", messages[2])
+ }
+ if !strings.Contains(content3, "Security Vulnerabilities Detected") {
+ t.Errorf("Message 2: expected security feedback content, got %q", content3)
+ }
+}
+
+func TestExtractMessages_DispatchesByPlatform(t *testing.T) {
+ // Create a Cursor-format transcript
+ tmpDir := t.TempDir()
+ transcriptPath := filepath.Join(tmpDir, "transcript.jsonl")
+
+ content := `{"role":"user","message":{"content":[{"type":"text","text":"hello"}]}}
+`
+
+ if err := os.WriteFile(transcriptPath, []byte(content), 0644); err != nil {
+ t.Fatalf("Failed to write transcript: %v", err)
+ }
+
+ // Cursor dispatch should work
+ messages := extractMessages(transcriptPath, "cursor")
+ if len(messages) != 1 {
+ t.Errorf("cursor dispatch: expected 1 message, got %d", len(messages))
+ }
+
+ // Same file through Claude dispatch should return 0 (different format)
+ messages = extractMessages(transcriptPath, "claude")
+ // Claude parser uses json.Decoder which may or may not parse this,
+ // but it won't match the "type" field pattern, so 0 messages expected
+ if len(messages) != 0 {
+ t.Errorf("claude dispatch: expected 0 messages from cursor-format file, got %d", len(messages))
+ }
+}
+
+func TestStripCursorXMLTags(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ want string
+ }{
+ {
+ "user_query tags",
+ "<user_query>\nPlease fix the bug\n</user_query>",
+ "Please fix the bug",
+ },
+ {
+ "no tags",
+ "Just a plain message",
+ "Just a plain message",
+ },
+ {
+ "attached_files tags",
+ "<user_query>\nFix this\n</user_query>\n<attached_files>\nfile.py\n</attached_files>",
+ "Fix this\n\n\nfile.py",
+ },
+ {
+ "git_diff tag",
+ "<git_diff_from_branch_to_main>\n+new line\n</git_diff_from_branch_to_main>",
+ "+new line",
+ },
+ {
+ "empty after stripping",
+ "<user_query>\n</user_query>",
+ "",
+ },
+ {
+ "preserves HTML tags in assistant content",
+ "Use a <div> element with <span> styling",
+ "Use a <div> element with <span> styling",
+ },
+ {
+ "preserves think tags",
+ "<think>\nLet me consider this\n</think>",
+ "<think>\nLet me consider this\n</think>",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := stripCursorXMLTags(tt.input)
+ if got != tt.want {
+ t.Errorf("stripCursorXMLTags() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/cli/beacon-hooks/cmd/version.go b/cli/beacon-hooks/cmd/version.go
new file mode 100644
index 00000000..d70c60dc
--- /dev/null
+++ b/cli/beacon-hooks/cmd/version.go
@@ -0,0 +1,21 @@
+package cmd
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/version"
+)
+
+var versionCmd = &cobra.Command{
+ Use: "version",
+ Short: "Print the hooks binary version",
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println(version.Version)
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(versionCmd)
+}
diff --git a/cli/beacon-hooks/go.mod b/cli/beacon-hooks/go.mod
new file mode 100644
index 00000000..9f629079
--- /dev/null
+++ b/cli/beacon-hooks/go.mod
@@ -0,0 +1,10 @@
+module github.com/asymptote-labs/agent-beacon/cli/beacon-hooks
+
+go 1.24
+
+require github.com/spf13/cobra v1.8.1
+
+require (
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/spf13/pflag v1.0.5 // indirect
+)
diff --git a/cli/beacon-hooks/go.sum b/cli/beacon-hooks/go.sum
new file mode 100644
index 00000000..912390a7
--- /dev/null
+++ b/cli/beacon-hooks/go.sum
@@ -0,0 +1,10 @@
+github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
+github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.go
new file mode 100644
index 00000000..8e507251
--- /dev/null
+++ b/cli/beacon-hooks/internal/config/config.go
@@ -0,0 +1,158 @@
+package config
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// Directories
+var (
+ BeaconDir = getBeaconDir()
+ ClaudeDir = filepath.Join(BeaconDir, "claude")
+ CopilotDir = filepath.Join(BeaconDir, "copilot")
+ CursorDir = filepath.Join(BeaconDir, "cursor")
+ FactoryDir = filepath.Join(BeaconDir, "factory")
+)
+
+// Log rotation
+const (
+ LogMaxSizeBytes = 10 * 1024 * 1024 // 10 MB
+)
+
+// Scannable extensions
+var scannableExtensions = map[string]bool{
+ // JavaScript/TypeScript
+ ".js": true, ".jsx": true, ".ts": true, ".tsx": true, ".mjs": true, ".cjs": true,
+ // Python
+ ".py": true, ".pyw": true,
+ // Java/Kotlin
+ ".java": true, ".kt": true, ".kts": true,
+ // Go
+ ".go": true,
+ // Rust
+ ".rs": true,
+ // C/C++
+ ".c": true, ".h": true, ".cpp": true, ".cc": true, ".cxx": true, ".hpp": true, ".hxx": true,
+ // C#
+ ".cs": true,
+ // Ruby
+ ".rb": true,
+ // PHP
+ ".php": true,
+ // Swift
+ ".swift": true,
+ // Solidity
+ ".sol": true,
+ // Shell
+ ".sh": true, ".bash": true, ".zsh": true,
+ // SQL
+ ".sql": true,
+ // YAML (for IaC)
+ ".yaml": true, ".yml": true,
+}
+
+func getBeaconDir() string {
+ homeDir, err := os.UserHomeDir()
+ if err != nil {
+ return ".beacon"
+ }
+ return filepath.Join(homeDir, ".beacon")
+}
+
+// IsScannableFile checks if a file should be scanned based on its extension
+func IsScannableFile(filePath string) bool {
+ if filePath == "" {
+ return false
+ }
+ ext := strings.ToLower(filepath.Ext(filePath))
+ return scannableExtensions[ext]
+}
+
+// GetStateDir returns the state directory for the given platform
+func GetStateDir(platform string) string {
+ switch platform {
+ case "copilot":
+ return CopilotDir
+ case "cursor":
+ return CursorDir
+ case "factory":
+ return FactoryDir
+ default:
+ return ClaudeDir
+ }
+}
+
+// GetLogFile returns the log file path for the given platform
+func GetLogFile(platform string) string {
+ return filepath.Join(GetStateDir(platform), "hooks.log")
+}
+
+// GetSessionLogDir returns the session logs directory for the given platform
+func GetSessionLogDir(platform string) string {
+ return filepath.Join(GetStateDir(platform), "logs")
+}
+
+// GetSessionLogFile returns the per-session log file path
+func GetSessionLogFile(platform, sessionID string) string {
+ return filepath.Join(GetSessionLogDir(platform), sessionID+".log")
+}
+
+// EnsureSessionLogDir creates the session logs directory if it doesn't exist
+func EnsureSessionLogDir(platform string) error {
+ return os.MkdirAll(GetSessionLogDir(platform), 0755)
+}
+
+// RotateLogIfNeededForPlatform clears the platform-specific log file if it exceeds LogMaxSizeBytes
+func RotateLogIfNeededForPlatform(platform string) bool {
+ logFile := GetLogFile(platform)
+ info, err := os.Stat(logFile)
+ if err != nil {
+ return false
+ }
+
+ if info.Size() > LogMaxSizeBytes {
+ os.WriteFile(logFile, []byte{}, 0644)
+ return true
+ }
+
+ return false
+}
+
+// EnsureStateDir ensures the state directory for the given platform exists
+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)
+ if err != nil {
+ return false
+ }
+ var cfg map[string]interface{}
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return false
+ }
+ enabled, ok := cfg["dep_scan"].(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)
+ if err != nil {
+ return false
+ }
+ var cfg map[string]interface{}
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return false
+ }
+ enabled, ok := cfg["secure_by_design"].(bool)
+ return ok && enabled
+}
diff --git a/cli/beacon-hooks/internal/config/config_test.go b/cli/beacon-hooks/internal/config/config_test.go
new file mode 100644
index 00000000..973e0bd3
--- /dev/null
+++ b/cli/beacon-hooks/internal/config/config_test.go
@@ -0,0 +1,198 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestGetStateDir(t *testing.T) {
+ tests := []struct {
+ platform string
+ wantDir string
+ }{
+ {"claude", ClaudeDir},
+ {"copilot", CopilotDir},
+ {"cursor", CursorDir},
+ {"unknown", ClaudeDir}, // defaults to claude
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.platform, func(t *testing.T) {
+ got := GetStateDir(tt.platform)
+ if got != tt.wantDir {
+ t.Errorf("GetStateDir(%q) = %q, want %q", tt.platform, got, tt.wantDir)
+ }
+ })
+ }
+}
+
+func TestGetLogFile(t *testing.T) {
+ tests := []struct {
+ platform string
+ wantBase string
+ }{
+ {"claude", "hooks.log"},
+ {"copilot", "hooks.log"},
+ {"cursor", "hooks.log"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.platform, func(t *testing.T) {
+ got := GetLogFile(tt.platform)
+ if filepath.Base(got) != tt.wantBase {
+ t.Errorf("GetLogFile(%q) base = %q, want %q", tt.platform, filepath.Base(got), tt.wantBase)
+ }
+ })
+ }
+}
+
+func TestGetSessionLogDir(t *testing.T) {
+ tests := []struct {
+ platform string
+ wantBase string
+ }{
+ {"claude", "logs"},
+ {"copilot", "logs"},
+ {"cursor", "logs"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.platform, func(t *testing.T) {
+ got := GetSessionLogDir(tt.platform)
+ if filepath.Base(got) != tt.wantBase {
+ t.Errorf("GetSessionLogDir(%q) base = %q, want %q", tt.platform, filepath.Base(got), tt.wantBase)
+ }
+ // Parent should be the platform state dir
+ if filepath.Dir(got) != GetStateDir(tt.platform) {
+ t.Errorf("GetSessionLogDir(%q) parent = %q, want %q", tt.platform, filepath.Dir(got), GetStateDir(tt.platform))
+ }
+ })
+ }
+}
+
+func TestGetSessionLogFile(t *testing.T) {
+ tests := []struct {
+ platform string
+ sessionID string
+ wantFile string
+ }{
+ {"claude", "abc-123", "abc-123.log"},
+ {"copilot", "sess-456", "sess-456.log"},
+ {"cursor", "conv-789", "conv-789.log"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.platform+"_"+tt.sessionID, func(t *testing.T) {
+ got := GetSessionLogFile(tt.platform, tt.sessionID)
+ if filepath.Base(got) != tt.wantFile {
+ t.Errorf("GetSessionLogFile(%q, %q) base = %q, want %q", tt.platform, tt.sessionID, filepath.Base(got), tt.wantFile)
+ }
+ // Parent should be the session log dir
+ if filepath.Dir(got) != GetSessionLogDir(tt.platform) {
+ t.Errorf("GetSessionLogFile(%q, %q) parent = %q, want %q", tt.platform, tt.sessionID, filepath.Dir(got), GetSessionLogDir(tt.platform))
+ }
+ })
+ }
+}
+
+func TestCursorDirPath(t *testing.T) {
+ // CursorDir should be ~/.beacon/cursor
+ if filepath.Base(CursorDir) != "cursor" {
+ t.Errorf("CursorDir should end with 'cursor', got %q", CursorDir)
+ }
+ if filepath.Base(filepath.Dir(CursorDir)) != ".beacon" {
+ t.Errorf("CursorDir parent should be '.beacon', got %q", filepath.Dir(CursorDir))
+ }
+}
+
+func TestIsSecureByDesignEnabled_PlatformSpecific(t *testing.T) {
+ tmpDir := t.TempDir()
+
+ origCursorDir := CursorDir
+ origBeaconDir := BeaconDir
+ CursorDir = filepath.Join(tmpDir, "cursor")
+ BeaconDir = tmpDir
+ defer func() {
+ CursorDir = origCursorDir
+ BeaconDir = origBeaconDir
+ }()
+
+ os.MkdirAll(filepath.Join(tmpDir, "cursor"), 0755)
+
+ // No config file → false
+ if IsSecureByDesignEnabled("cursor") {
+ t.Error("should be false when no config exists")
+ }
+
+ // Platform config enabled
+ os.WriteFile(filepath.Join(tmpDir, "cursor", "config.json"), []byte(`{"secure_by_design": true}`), 0644)
+ if !IsSecureByDesignEnabled("cursor") {
+ t.Error("should be true when platform config has secure_by_design: true")
+ }
+
+ // Platform-specific false overrides global true
+ os.WriteFile(filepath.Join(tmpDir, "cursor", "config.json"), []byte(`{"secure_by_design": false}`), 0644)
+ os.WriteFile(filepath.Join(tmpDir, "config.json"), []byte(`{"secure_by_design": true}`), 0644)
+ if IsSecureByDesignEnabled("cursor") {
+ t.Error("platform-specific false should take precedence over global true")
+ }
+}
+
+func TestIsSecureByDesignEnabled_GlobalIgnored(t *testing.T) {
+ tmpDir := t.TempDir()
+
+ origClaudeDir := ClaudeDir
+ origBeaconDir := BeaconDir
+ ClaudeDir = filepath.Join(tmpDir, "claude")
+ BeaconDir = tmpDir
+ defer func() {
+ ClaudeDir = origClaudeDir
+ BeaconDir = origBeaconDir
+ }()
+
+ // No platform config, global has SbD enabled → should NOT fall back (global deprecated)
+ os.WriteFile(filepath.Join(tmpDir, "config.json"), []byte(`{"secure_by_design": true}`), 0644)
+ if IsSecureByDesignEnabled("claude") {
+ t.Error("should ignore global config, only platform-specific config matters")
+ }
+}
+
+func TestIsSecureByDesignEnabled_NoConfigFiles(t *testing.T) {
+ tmpDir := t.TempDir()
+
+ origClaudeDir := ClaudeDir
+ origBeaconDir := BeaconDir
+ ClaudeDir = filepath.Join(tmpDir, "claude")
+ BeaconDir = tmpDir
+ defer func() {
+ ClaudeDir = origClaudeDir
+ BeaconDir = origBeaconDir
+ }()
+
+ // No config files at all → false
+ if IsSecureByDesignEnabled("claude") {
+ t.Error("should be false when no config files exist")
+ }
+}
+
+func TestIsSecureByDesignEnabled_InvalidJSON(t *testing.T) {
+ tmpDir := t.TempDir()
+
+ origCursorDir := CursorDir
+ origBeaconDir := BeaconDir
+ CursorDir = filepath.Join(tmpDir, "cursor")
+ BeaconDir = tmpDir
+ defer func() {
+ CursorDir = origCursorDir
+ BeaconDir = origBeaconDir
+ }()
+
+ os.MkdirAll(filepath.Join(tmpDir, "cursor"), 0755)
+
+ // Invalid JSON in platform config → false (no fallback)
+ os.WriteFile(filepath.Join(tmpDir, "cursor", "config.json"), []byte(`not json`), 0644)
+ if IsSecureByDesignEnabled("cursor") {
+ t.Error("should be false when platform config has invalid JSON")
+ }
+}
diff --git a/cli/beacon-hooks/internal/depscan/depscan.go b/cli/beacon-hooks/internal/depscan/depscan.go
new file mode 100644
index 00000000..2304fa38
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/depscan.go
@@ -0,0 +1,125 @@
+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
new file mode 100644
index 00000000..77117d6f
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/depscan_test.go
@@ -0,0 +1,253 @@
+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
new file mode 100644
index 00000000..43a62d23
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/format.go
@@ -0,0 +1,191 @@
+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
new file mode 100644
index 00000000..22c084e6
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/format_test.go
@@ -0,0 +1,203 @@
+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
new file mode 100644
index 00000000..8a879813
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/npm.go
@@ -0,0 +1,37 @@
+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
new file mode 100644
index 00000000..46099f51
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/npm_test.go
@@ -0,0 +1,64 @@
+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
new file mode 100644
index 00000000..91398ae8
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/osv.go
@@ -0,0 +1,200 @@
+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
new file mode 100644
index 00000000..798d8587
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/osv_test.go
@@ -0,0 +1,139 @@
+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
new file mode 100644
index 00000000..02442ca2
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/pypi.go
@@ -0,0 +1,94 @@
+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
new file mode 100644
index 00000000..c51c6b94
--- /dev/null
+++ b/cli/beacon-hooks/internal/depscan/pypi_test.go
@@ -0,0 +1,113 @@
+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/diff/diff.go b/cli/beacon-hooks/internal/diff/diff.go
new file mode 100644
index 00000000..72172290
--- /dev/null
+++ b/cli/beacon-hooks/internal/diff/diff.go
@@ -0,0 +1,318 @@
+package diff
+
+import (
+ "fmt"
+ "path/filepath"
+ "strings"
+)
+
+// FromToolResponse builds a diff from any supported tool type
+func FromToolResponse(toolName string, toolInput, toolResponse map[string]interface{}) string {
+ filePath := GetStringFromMaps("file_path", toolInput, toolResponse)
+ if filePath == "" {
+ filePath = GetStringFromMaps("filePath", toolInput, toolResponse)
+ }
+ if filePath == "" {
+ return ""
+ }
+
+ // Prefer structuredPatch if available (most accurate)
+ if structuredPatch, ok := toolResponse["structuredPatch"].([]interface{}); ok && len(structuredPatch) > 0 {
+ return fromStructuredPatch(filePath, structuredPatch)
+ }
+
+ // Fall back to tool-specific construction
+ switch toolName {
+ case "Edit":
+ oldString := resolveEditString("old_string", "oldString", "old_str", toolInput, toolResponse)
+ newString := resolveEditString("new_string", "newString", "new_str", toolInput, toolResponse)
+ return fromEditTool(filePath, oldString, newString)
+
+ case "copilot_insertEdit":
+ // Copilot sends full file content as "code" field
+ content := GetStringFromMaps("code", toolInput, toolResponse)
+ return fromWriteTool(filePath, content, "")
+
+ case "Write", "Create":
+ content := GetStringFromMaps("content", toolInput, toolResponse)
+ originalFile := GetStringFromMaps("originalFile", toolInput, toolResponse)
+ return fromWriteTool(filePath, content, originalFile)
+
+ case "MultiEdit":
+ edits, ok := toolInput["edits"].([]interface{})
+ if !ok || len(edits) == 0 {
+ return ""
+ }
+
+ var allDiffs []string
+ for _, edit := range edits {
+ editMap, ok := edit.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ editFile := GetStringFromMaps("file_path", editMap)
+ if editFile == "" {
+ editFile = filePath
+ }
+ oldStr := resolveEditString("old_string", "oldString", "old_str", editMap)
+ newStr := resolveEditString("new_string", "newString", "new_str", editMap)
+ if d := fromEditTool(editFile, oldStr, newStr); d != "" {
+ allDiffs = append(allDiffs, d)
+ }
+ }
+ return strings.Join(allDiffs, "\n\n")
+
+ case "create_file", "copilot_createFile":
+ content := GetStringFromMaps("content", toolInput, toolResponse)
+ return fromWriteTool(filePath, content, "")
+
+ case "apply_patch", "copilot_applyPatch":
+ patchInput := GetStringFromMaps("input", toolInput, toolResponse)
+ if patchInput == "" {
+ patchInput = GetStringFromMaps("textResultForLlm", toolInput, toolResponse)
+ }
+ if patchInput != "" {
+ return fromCopilotPatch(filePath, patchInput)
+ }
+ return ""
+ }
+
+ return ""
+}
+
+// resolveEditString tries multiple key variants for edit fields.
+// Claude uses old_string/new_string, Copilot uses oldString/newString, Factory uses old_str/new_str.
+func resolveEditString(snakeKey, camelKey, shortKey string, maps ...map[string]interface{}) string {
+ if v := GetStringFromMaps(snakeKey, maps...); v != "" {
+ return v
+ }
+ if v := GetStringFromMaps(camelKey, maps...); v != "" {
+ return v
+ }
+ return GetStringFromMaps(shortKey, maps...)
+}
+
+// fromCopilotPatch parses Copilot's patch format and converts to unified diff.
+// Format:
+//
+// *** Begin Patch
+// *** Update File: path/to/file.py
+// @@@ -10,3 +10,5 @@@
+// context line
+// -removed line
+// +added line
+// *** End Patch
+func fromCopilotPatch(filePath, patchInput string) string {
+ lines := strings.Split(patchInput, "\n")
+ var result []string
+
+ for _, line := range lines {
+ trimmed := strings.TrimSpace(line)
+
+ // Skip patch boundaries
+ if trimmed == "*** Begin Patch" || trimmed == "*** End Patch" {
+ continue
+ }
+
+ // File headers: extract filename and emit appropriate diff header
+ if oldPath, newPath, ok := parsePatchFileHeader(trimmed, filePath); ok {
+ result = append(result, oldPath, newPath)
+ continue
+ }
+
+ // Convert @@@ markers to standard @@ markers
+ if strings.HasPrefix(trimmed, "@@@") {
+ result = append(result, strings.Replace(line, "@@@", "@@", 2))
+ continue
+ }
+
+ // Pass through diff content lines (context, additions, removals)
+ if len(result) > 0 {
+ result = append(result, line)
+ }
+ }
+
+ if len(result) == 0 {
+ filename := filepath.Base(filePath)
+ return fmt.Sprintf("--- a/%s\n+++ b/%s\n%s", filename, filename, patchInput)
+ }
+
+ return strings.Join(result, "\n")
+}
+
+// parsePatchFileHeader parses a Copilot patch file header line and returns the
+// diff header lines. Returns ok=true if the line was a file header.
+func parsePatchFileHeader(trimmed, fallbackPath string) (oldPath, newPath string, ok bool) {
+ type headerDef struct {
+ prefix string
+ oldFmt string
+ newFmt string
+ }
+
+ headers := []headerDef{
+ {"*** Update File:", "--- a/%s", "+++ b/%s"},
+ {"*** Add File:", "--- /dev/null", "+++ b/%s"},
+ {"*** Delete File:", "--- a/%s", "+++ /dev/null"},
+ }
+
+ for _, h := range headers {
+ if !strings.HasPrefix(trimmed, h.prefix) {
+ continue
+ }
+ file := strings.TrimSpace(strings.TrimPrefix(trimmed, h.prefix))
+ if file == "" {
+ file = fallbackPath
+ }
+ name := filepath.Base(file)
+
+ old := h.oldFmt
+ if strings.Contains(old, "%s") {
+ old = fmt.Sprintf(old, name)
+ }
+ newP := h.newFmt
+ if strings.Contains(newP, "%s") {
+ newP = fmt.Sprintf(newP, name)
+ }
+ return old, newP, true
+ }
+ return "", "", false
+}
+
+func fromStructuredPatch(filePath string, structuredPatch []interface{}) string {
+ if len(structuredPatch) == 0 {
+ return ""
+ }
+
+ filename := filepath.Base(filePath)
+ lines := []string{
+ fmt.Sprintf("--- a/%s", filename),
+ fmt.Sprintf("+++ b/%s", filename),
+ }
+
+ for _, hunk := range structuredPatch {
+ hunkMap, ok := hunk.(map[string]interface{})
+ if !ok {
+ continue
+ }
+
+ oldStart := getIntFromMap(hunkMap, "oldStart", 1)
+ oldLines := getIntFromMap(hunkMap, "oldLines", 0)
+ newStart := getIntFromMap(hunkMap, "newStart", 1)
+ newLines := getIntFromMap(hunkMap, "newLines", 0)
+
+ lines = append(lines, fmt.Sprintf("@@ -%d,%d +%d,%d @@", oldStart, oldLines, newStart, newLines))
+
+ if hunkLines, ok := hunkMap["lines"].([]interface{}); ok {
+ for _, line := range hunkLines {
+ if lineStr, ok := line.(string); ok {
+ lines = append(lines, lineStr)
+ }
+ }
+ }
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+// FromCursorEdits builds a unified diff from Cursor's afterFileEdit edits array.
+// Each edit has old_string and new_string fields, reusing the existing fromEditTool helper.
+func FromCursorEdits(filePath string, edits []interface{}) string {
+ var allDiffs []string
+ for _, edit := range edits {
+ editMap, ok := edit.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ oldStr, _ := editMap["old_string"].(string)
+ newStr, _ := editMap["new_string"].(string)
+ if d := fromEditTool(filePath, oldStr, newStr); d != "" {
+ allDiffs = append(allDiffs, d)
+ }
+ }
+ return strings.Join(allDiffs, "\n\n")
+}
+
+func fromEditTool(filePath, oldString, newString string) string {
+ if oldString == "" && newString == "" {
+ return ""
+ }
+
+ filename := filepath.Base(filePath)
+ oldLines := splitLines(oldString)
+ newLines := splitLines(newString)
+
+ lines := []string{
+ fmt.Sprintf("--- a/%s", filename),
+ fmt.Sprintf("+++ b/%s", filename),
+ fmt.Sprintf("@@ -1,%d +1,%d @@", len(oldLines), len(newLines)),
+ }
+
+ for _, line := range oldLines {
+ lines = append(lines, "-"+line)
+ }
+ for _, line := range newLines {
+ lines = append(lines, "+"+line)
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+func fromWriteTool(filePath, content, originalFile string) string {
+ filename := filepath.Base(filePath)
+ newLines := splitLines(content)
+ oldLines := splitLines(originalFile)
+
+ lines := []string{
+ fmt.Sprintf("--- a/%s", filename),
+ fmt.Sprintf("+++ b/%s", filename),
+ }
+
+ if originalFile != "" {
+ // This is an update - show as replacement
+ lines = append(lines, fmt.Sprintf("@@ -1,%d +1,%d @@", len(oldLines), len(newLines)))
+ for _, line := range oldLines {
+ lines = append(lines, "-"+line)
+ }
+ for _, line := range newLines {
+ lines = append(lines, "+"+line)
+ }
+ } else {
+ // This is a new file
+ lines = append(lines, fmt.Sprintf("@@ -0,0 +1,%d @@", len(newLines)))
+ for _, line := range newLines {
+ lines = append(lines, "+"+line)
+ }
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+func splitLines(s string) []string {
+ if s == "" {
+ return []string{}
+ }
+ return strings.Split(s, "\n")
+}
+
+// GetStringFromMaps returns the first non-empty string value for key across the given maps.
+func GetStringFromMaps(key string, maps ...map[string]interface{}) string {
+ for _, m := range maps {
+ if m == nil {
+ continue
+ }
+ if v, ok := m[key].(string); ok && v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+func getIntFromMap(m map[string]interface{}, key string, defaultVal int) int {
+ if v, ok := m[key].(float64); ok {
+ return int(v)
+ }
+ if v, ok := m[key].(int); ok {
+ return v
+ }
+ return defaultVal
+}
diff --git a/cli/beacon-hooks/internal/diff/diff_test.go b/cli/beacon-hooks/internal/diff/diff_test.go
new file mode 100644
index 00000000..f17ceb4a
--- /dev/null
+++ b/cli/beacon-hooks/internal/diff/diff_test.go
@@ -0,0 +1,128 @@
+package diff
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestFromCursorEdits_SingleEdit(t *testing.T) {
+ edits := []interface{}{
+ map[string]interface{}{
+ "old_string": "x = 1",
+ "new_string": "x = 2",
+ },
+ }
+
+ result := FromCursorEdits("/path/to/file.py", edits)
+
+ if result == "" {
+ t.Fatal("FromCursorEdits() returned empty string")
+ }
+
+ if !strings.Contains(result, "--- a/file.py") {
+ t.Error("Missing --- header")
+ }
+ if !strings.Contains(result, "+++ b/file.py") {
+ t.Error("Missing +++ header")
+ }
+ if !strings.Contains(result, "-x = 1") {
+ t.Error("Missing old string in diff")
+ }
+ if !strings.Contains(result, "+x = 2") {
+ t.Error("Missing new string in diff")
+ }
+}
+
+func TestFromCursorEdits_MultipleEdits(t *testing.T) {
+ edits := []interface{}{
+ map[string]interface{}{
+ "old_string": "x = 1",
+ "new_string": "x = 2",
+ },
+ map[string]interface{}{
+ "old_string": "y = 3",
+ "new_string": "y = 4",
+ },
+ }
+
+ result := FromCursorEdits("/path/to/file.py", edits)
+
+ if result == "" {
+ t.Fatal("FromCursorEdits() returned empty string")
+ }
+
+ // Should contain two diffs separated by double newline
+ parts := strings.Split(result, "\n\n")
+ if len(parts) < 2 {
+ t.Errorf("Expected at least 2 diff sections, got %d", len(parts))
+ }
+
+ if !strings.Contains(result, "-x = 1") {
+ t.Error("Missing first old string")
+ }
+ if !strings.Contains(result, "+x = 2") {
+ t.Error("Missing first new string")
+ }
+ if !strings.Contains(result, "-y = 3") {
+ t.Error("Missing second old string")
+ }
+ if !strings.Contains(result, "+y = 4") {
+ t.Error("Missing second new string")
+ }
+}
+
+func TestFromCursorEdits_EmptyEdits(t *testing.T) {
+ result := FromCursorEdits("/path/to/file.py", []interface{}{})
+
+ if result != "" {
+ t.Errorf("FromCursorEdits() with empty edits = %q, want empty", result)
+ }
+}
+
+func TestFromCursorEdits_InvalidEditFormat(t *testing.T) {
+ edits := []interface{}{
+ "not a map",
+ 42,
+ }
+
+ result := FromCursorEdits("/path/to/file.py", edits)
+
+ if result != "" {
+ t.Errorf("FromCursorEdits() with invalid edits = %q, want empty", result)
+ }
+}
+
+func TestFromCursorEdits_EmptyStrings(t *testing.T) {
+ edits := []interface{}{
+ map[string]interface{}{
+ "old_string": "",
+ "new_string": "",
+ },
+ }
+
+ result := FromCursorEdits("/path/to/file.py", edits)
+
+ // fromEditTool returns "" for empty old and new strings
+ if result != "" {
+ t.Errorf("FromCursorEdits() with empty strings = %q, want empty", result)
+ }
+}
+
+func TestFromCursorEdits_MultilineEdit(t *testing.T) {
+ edits := []interface{}{
+ map[string]interface{}{
+ "old_string": "func main() {\n\tfmt.Println(\"hello\")\n}",
+ "new_string": "func main() {\n\tfmt.Println(\"world\")\n\treturn\n}",
+ },
+ }
+
+ result := FromCursorEdits("/path/to/main.go", edits)
+
+ if result == "" {
+ t.Fatal("FromCursorEdits() returned empty string")
+ }
+
+ if !strings.Contains(result, "--- a/main.go") {
+ t.Error("Missing file header")
+ }
+}
diff --git a/cli/beacon-hooks/internal/format/format.go b/cli/beacon-hooks/internal/format/format.go
new file mode 100644
index 00000000..2ba3b34c
--- /dev/null
+++ b/cli/beacon-hooks/internal/format/format.go
@@ -0,0 +1,98 @@
+package format
+
+import (
+ "fmt"
+ "strings"
+)
+
+// FormatViolation formats a single violation
+func FormatViolation(violation map[string]interface{}, index int) string {
+ severity := strings.ToUpper(getStringOrDefault(violation, "severity", "unknown"))
+ title := getStringOrDefault(violation, "title", "")
+ if title == "" {
+ title = getStringOrDefault(violation, "policy_name", "Unknown Policy")
+ }
+ message := getStringOrDefault(violation, "message", "No description")
+ remediation := getStringOrDefault(violation, "remediation", "")
+
+ location, _ := violation["location"].(map[string]interface{})
+ filePath := getStringOrDefault(location, "file", "unknown")
+ line := getIntOrDefault(location, "line_start", 0)
+
+ var lines []string
+ lines = append(lines, fmt.Sprintf("### %d. [%s] %s", index, severity, title))
+ lines = append(lines, fmt.Sprintf("**File:** `%s` (line %d)", filePath, line))
+ lines = append(lines, "")
+ lines = append(lines, fmt.Sprintf("**Issue:** %s", message))
+
+ if remediation != "" {
+ lines = append(lines, "")
+ lines = append(lines, fmt.Sprintf("**Fix:** %s", remediation))
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+// FormatReport formats a full violation report for re-prompting Claude
+func FormatReport(violations []map[string]interface{}) string {
+ if len(violations) == 0 {
+ return ""
+ }
+
+ header := "## Security Vulnerabilities Detected\n\n"
+ header += "The following security issues were found in your code changes:\n\n"
+
+ var body []string
+ for i, v := range violations {
+ body = append(body, FormatViolation(v, i+1))
+ }
+
+ footer := "\n\n---\n\nPlease fix these security vulnerabilities before completing the task."
+
+ return header + strings.Join(body, "\n\n---\n\n") + footer
+}
+
+// FormatWarning formats a warning message when violations persist after max retries
+func FormatWarning(violations []map[string]interface{}) string {
+ count := len(violations)
+ severityCounts := make(map[string]int)
+
+ for _, v := range violations {
+ sev := getStringOrDefault(v, "severity", "unknown")
+ severityCounts[sev]++
+ }
+
+ var parts []string
+ for sev, c := range severityCounts {
+ parts = append(parts, fmt.Sprintf("%d %s", c, sev))
+ }
+ summary := strings.Join(parts, ", ")
+
+ return fmt.Sprintf(
+ "Warning: %d security issue(s) (%s) could not be automatically fixed. "+
+ "Please review manually before deployment.",
+ count, summary)
+}
+
+func getStringOrDefault(m map[string]interface{}, key, defaultVal string) string {
+ if m == nil {
+ return defaultVal
+ }
+ if v, ok := m[key].(string); ok {
+ return v
+ }
+ return defaultVal
+}
+
+func getIntOrDefault(m map[string]interface{}, key string, defaultVal int) int {
+ if m == nil {
+ return defaultVal
+ }
+ if v, ok := m[key].(float64); ok {
+ return int(v)
+ }
+ if v, ok := m[key].(int); ok {
+ return v
+ }
+ return defaultVal
+}
diff --git a/cli/beacon-hooks/internal/git/git.go b/cli/beacon-hooks/internal/git/git.go
new file mode 100644
index 00000000..ee3a7843
--- /dev/null
+++ b/cli/beacon-hooks/internal/git/git.go
@@ -0,0 +1,176 @@
+package git
+
+import (
+ "bufio"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+// GetRemoteInfo returns the owner and repository name from the git remote origin.
+// Returns empty strings if not in a git repo or no origin remote is configured.
+// Supports both SSH ([email protected]:owner/name.git) and HTTPS (https://github.com/owner/name.git) URLs.
+// If cwd is provided, it uses that directory as the starting point; otherwise uses os.Getwd().
+func GetRemoteInfo(cwd string) (owner, name string) {
+ // Find .git directory by walking up from cwd
+ gitDir := findGitDir(cwd)
+ if gitDir == "" {
+ return "", ""
+ }
+
+ // Read .git/config
+ configPath := filepath.Join(gitDir, "config")
+ url := parseRemoteOriginURL(configPath)
+ if url == "" {
+ return "", ""
+ }
+
+ // Parse owner/name from URL
+ return parseGitURL(url)
+}
+
+// findGitDir walks up the directory tree to find the .git directory.
+// If cwd is provided, it uses that directory as the starting point; otherwise uses os.Getwd().
+// Handles both normal repositories (.git is a directory) and worktrees (.git is a file
+// containing a "gitdir:" reference).
+func findGitDir(cwd string) string {
+ if cwd == "" {
+ var err error
+ cwd, err = os.Getwd()
+ if err != nil {
+ return ""
+ }
+ }
+
+ dir := cwd
+ for {
+ gitPath := filepath.Join(dir, ".git")
+ info, err := os.Stat(gitPath)
+ if err == nil {
+ if info.IsDir() {
+ // Normal repository: .git is a directory
+ return gitPath
+ }
+ // Worktree: .git is a file with "gitdir: <path>"
+ if resolved := resolveWorktreeGitDir(gitPath); resolved != "" {
+ return resolved
+ }
+ }
+
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ // Reached root
+ return ""
+ }
+ dir = parent
+ }
+}
+
+// resolveWorktreeGitDir reads a .git file (as found in worktrees),
+// extracts the gitdir path, and resolves the common git directory
+// that contains the config with remote URLs.
+func resolveWorktreeGitDir(dotGitFile string) string {
+ data, err := os.ReadFile(dotGitFile)
+ if err != nil {
+ return ""
+ }
+
+ // Parse "gitdir: <path>" from the .git file
+ line := strings.TrimSpace(string(data))
+ if !strings.HasPrefix(line, "gitdir:") {
+ return ""
+ }
+ gitdir := strings.TrimSpace(strings.TrimPrefix(line, "gitdir:"))
+ if gitdir == "" {
+ return ""
+ }
+
+ // Resolve relative paths against the .git file's parent directory
+ if !filepath.IsAbs(gitdir) {
+ gitdir = filepath.Join(filepath.Dir(dotGitFile), gitdir)
+ }
+ gitdir = filepath.Clean(gitdir)
+
+ // In a worktree, gitdir points to e.g. /repo/.git/worktrees/foo
+ // which contains a "commondir" file with a relative path to the shared .git dir
+ commondirPath := filepath.Join(gitdir, "commondir")
+ if commondirData, err := os.ReadFile(commondirPath); err == nil {
+ commondir := strings.TrimSpace(string(commondirData))
+ if commondir != "" {
+ if !filepath.IsAbs(commondir) {
+ commondir = filepath.Join(gitdir, commondir)
+ }
+ commondir = filepath.Clean(commondir)
+ // Verify it looks like a git dir (has a config file)
+ if _, err := os.Stat(filepath.Join(commondir, "config")); err == nil {
+ return commondir
+ }
+ }
+ }
+
+ // No commondir means this is not a worktree (likely a submodule).
+ // Return "" so findGitDir continues walking up to the parent repo.
+ return ""
+}
+
+// parseRemoteOriginURL reads .git/config and extracts the origin remote URL
+func parseRemoteOriginURL(configPath string) string {
+ file, err := os.Open(configPath)
+ if err != nil {
+ return ""
+ }
+ defer file.Close()
+
+ scanner := bufio.NewScanner(file)
+ inOriginSection := false
+
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+
+ // Check for section headers
+ if strings.HasPrefix(line, "[") {
+ inOriginSection = line == `[remote "origin"]`
+ continue
+ }
+
+ // Look for url in origin section
+ if inOriginSection && strings.HasPrefix(line, "url") {
+ parts := strings.SplitN(line, "=", 2)
+ if len(parts) == 2 {
+ return strings.TrimSpace(parts[1])
+ }
+ }
+ }
+
+ return ""
+}
+
+// parseGitURL extracts owner and repository name from a git URL
+// Supports:
+// - [email protected]:owner/name.git
+// - [email protected]:owner/name
+// - https://github.com/owner/name.git
+// - https://github.com/owner/name
+// - ssh://[email protected]/owner/name.git
+func parseGitURL(url string) (owner, name string) {
+ // SSH format: [email protected]:owner/name.git
+ sshRegex := regexp.MustCompile(`^git@[^:]+:([^/]+)/([^/]+?)(?:\.git)?$`)
+ if matches := sshRegex.FindStringSubmatch(url); len(matches) == 3 {
+ return matches[1], matches[2]
+ }
+
+ // HTTPS format: https://github.com/owner/name.git
+ httpsRegex := regexp.MustCompile(`^https?://[^/]+/([^/]+)/([^/]+?)(?:\.git)?$`)
+ if matches := httpsRegex.FindStringSubmatch(url); len(matches) == 3 {
+ return matches[1], matches[2]
+ }
+
+ // SSH with ssh:// prefix: ssh://[email protected]/owner/name.git
+ sshPrefixRegex := regexp.MustCompile(`^ssh://[^/]+/([^/]+)/([^/]+?)(?:\.git)?$`)
+ if matches := sshPrefixRegex.FindStringSubmatch(url); len(matches) == 3 {
+ return matches[1], matches[2]
+ }
+
+ return "", ""
+}
diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
new file mode 100644
index 00000000..e8cded6d
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
@@ -0,0 +1,24 @@
+package logging
+
+import "testing"
+
+func TestEndpointActionDoesNotClassifyRoutineStopAsBlocked(t *testing.T) {
+ action, severity := endpointAction("stop-async-handler", map[string]interface{}{"message": "stop completed"})
+ if action != "session.ended" || severity != "info" {
+ t.Fatalf("endpointAction() = %s/%s, want session.ended/info", action, severity)
+ }
+}
+
+func TestEndpointActionClassifiesViolationBlock(t *testing.T) {
+ action, severity := endpointAction("stop-async-handler", map[string]interface{}{"message": "Blocking with violations"})
+ if action != "policy.blocked" || severity != "high" {
+ t.Fatalf("endpointAction() = %s/%s, want policy.blocked/high", action, severity)
+ }
+}
+
+func TestEndpointRedaction(t *testing.T) {
+ got := redactEndpointString("token=super-secret")
+ if got == "token=super-secret" {
+ t.Fatal("expected token to be redacted")
+ }
+}
diff --git a/cli/beacon-hooks/internal/logging/extract.go b/cli/beacon-hooks/internal/logging/extract.go
new file mode 100644
index 00000000..319250d5
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/extract.go
@@ -0,0 +1,48 @@
+package logging
+
+import (
+ "io"
+ "os"
+)
+
+// ReadSessionLogs reads log data from a session log file starting at byteOffset.
+// Returns the raw bytes (JSONL) and the new byte offset.
+// If the file doesn't exist or is empty from offset, returns nil with no error.
+func ReadSessionLogs(logFile string, byteOffset int64) ([]byte, int64, error) {
+ f, err := os.Open(logFile)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, byteOffset, nil
+ }
+ return nil, byteOffset, err
+ }
+ defer f.Close()
+
+ // Check file size
+ info, err := f.Stat()
+ if err != nil {
+ return nil, byteOffset, err
+ }
+
+ fileSize := info.Size()
+ if fileSize <= byteOffset {
+ // File was truncated or nothing new — reset to current size
+ return nil, fileSize, nil
+ }
+
+ // Seek to offset and read to EOF
+ if _, err := f.Seek(byteOffset, io.SeekStart); err != nil {
+ return nil, byteOffset, err
+ }
+
+ data, err := io.ReadAll(f)
+ if err != nil {
+ return nil, byteOffset, err
+ }
+
+ if len(data) == 0 {
+ return nil, byteOffset, nil
+ }
+
+ return data, byteOffset + int64(len(data)), nil
+}
diff --git a/cli/beacon-hooks/internal/logging/extract_test.go b/cli/beacon-hooks/internal/logging/extract_test.go
new file mode 100644
index 00000000..135e3805
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/extract_test.go
@@ -0,0 +1,153 @@
+package logging
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestReadSessionLogs_FileNotExist(t *testing.T) {
+ data, offset, err := ReadSessionLogs("/nonexistent/file.log", 0)
+ if err != nil {
+ t.Fatalf("Expected no error for missing file, got %v", err)
+ }
+ if data != nil {
+ t.Errorf("Expected nil data, got %d bytes", len(data))
+ }
+ if offset != 0 {
+ t.Errorf("Expected offset 0, got %d", offset)
+ }
+}
+
+func TestReadSessionLogs_EmptyFile(t *testing.T) {
+ tmpDir := t.TempDir()
+ logFile := filepath.Join(tmpDir, "test.log")
+ os.WriteFile(logFile, []byte{}, 0644)
+
+ data, offset, err := ReadSessionLogs(logFile, 0)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if data != nil {
+ t.Errorf("Expected nil data for empty file, got %d bytes", len(data))
+ }
+ if offset != 0 {
+ t.Errorf("Expected offset 0, got %d", offset)
+ }
+}
+
+func TestReadSessionLogs_FullRead(t *testing.T) {
+ tmpDir := t.TempDir()
+ logFile := filepath.Join(tmpDir, "test.log")
+ content := `{"level":"info","message":"line1"}
+{"level":"info","message":"line2"}
+`
+ os.WriteFile(logFile, []byte(content), 0644)
+
+ data, offset, err := ReadSessionLogs(logFile, 0)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if string(data) != content {
+ t.Errorf("Data mismatch.\nGot: %q\nWant: %q", string(data), content)
+ }
+ if offset != int64(len(content)) {
+ t.Errorf("Expected offset %d, got %d", len(content), offset)
+ }
+}
+
+func TestReadSessionLogs_DeltaRead(t *testing.T) {
+ tmpDir := t.TempDir()
+ logFile := filepath.Join(tmpDir, "test.log")
+
+ line1 := `{"level":"info","message":"line1"}` + "\n"
+ line2 := `{"level":"info","message":"line2"}` + "\n"
+ os.WriteFile(logFile, []byte(line1+line2), 0644)
+
+ // Read from offset after line1 — should only get line2
+ startOffset := int64(len(line1))
+ data, offset, err := ReadSessionLogs(logFile, startOffset)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if string(data) != line2 {
+ t.Errorf("Data mismatch.\nGot: %q\nWant: %q", string(data), line2)
+ }
+ if offset != int64(len(line1)+len(line2)) {
+ t.Errorf("Expected offset %d, got %d", len(line1)+len(line2), offset)
+ }
+}
+
+func TestReadSessionLogs_OffsetAtEOF(t *testing.T) {
+ tmpDir := t.TempDir()
+ logFile := filepath.Join(tmpDir, "test.log")
+ content := "some data\n"
+ os.WriteFile(logFile, []byte(content), 0644)
+
+ // Offset equals file size — nothing new
+ data, offset, err := ReadSessionLogs(logFile, int64(len(content)))
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if data != nil {
+ t.Errorf("Expected nil data at EOF, got %d bytes", len(data))
+ }
+ if offset != int64(len(content)) {
+ t.Errorf("Expected offset %d, got %d", len(content), offset)
+ }
+}
+
+func TestReadSessionLogs_OffsetBeyondFileSize(t *testing.T) {
+ tmpDir := t.TempDir()
+ logFile := filepath.Join(tmpDir, "test.log")
+ content := "short"
+ os.WriteFile(logFile, []byte(content), 0644)
+
+ // Offset past file size (e.g. file was truncated) — should reset
+ data, offset, err := ReadSessionLogs(logFile, 9999)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if data != nil {
+ t.Errorf("Expected nil data, got %d bytes", len(data))
+ }
+ if offset != int64(len(content)) {
+ t.Errorf("Expected offset reset to file size %d, got %d", len(content), offset)
+ }
+}
+
+func TestReadSessionLogs_IncrementalAppend(t *testing.T) {
+ tmpDir := t.TempDir()
+ logFile := filepath.Join(tmpDir, "test.log")
+
+ // Write first chunk
+ chunk1 := `{"msg":"first"}` + "\n"
+ os.WriteFile(logFile, []byte(chunk1), 0644)
+
+ // Read first chunk
+ data, offset, err := ReadSessionLogs(logFile, 0)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if string(data) != chunk1 {
+ t.Errorf("First read: got %q, want %q", string(data), chunk1)
+ }
+
+ // Append second chunk
+ chunk2 := `{"msg":"second"}` + "\n"
+ f, _ := os.OpenFile(logFile, os.O_APPEND|os.O_WRONLY, 0644)
+ f.WriteString(chunk2)
+ f.Close()
+
+ // Read from saved offset — should only get chunk2
+ data, newOffset, err := ReadSessionLogs(logFile, offset)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if string(data) != chunk2 {
+ t.Errorf("Delta read: got %q, want %q", string(data), chunk2)
+ }
+ if newOffset != int64(len(chunk1)+len(chunk2)) {
+ t.Errorf("Expected final offset %d, got %d", len(chunk1)+len(chunk2), newOffset)
+ }
+}
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
new file mode 100644
index 00000000..78edc9b7
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -0,0 +1,247 @@
+package logging
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+)
+
+var endpointSecretPatterns = []*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,}`),
+}
+
+// Logger provides structured JSON logging for hook events
+type Logger struct {
+ hookName string
+ logFile string
+ sessionID string
+ platform string
+}
+
+// NewLoggerForPlatform creates a logger for a specific hook and platform
+func NewLoggerForPlatform(hookName, platform string) *Logger {
+ config.EnsureStateDir(platform)
+ return &Logger{hookName: hookName, logFile: config.GetLogFile(platform), platform: platform}
+}
+
+// NewSessionLogger creates a logger that writes to a per-session log file.
+// Log file path: ~/.beacon/{platform}/logs/{session_id}.log
+func NewSessionLogger(hookName, platform, sessionID string) *Logger {
+ config.EnsureSessionLogDir(platform)
+ return &Logger{
+ hookName: hookName,
+ logFile: config.GetSessionLogFile(platform, sessionID),
+ sessionID: sessionID,
+ platform: platform,
+ }
+}
+
+func (l *Logger) formatEntry(level, message string, fields ...interface{}) map[string]interface{} {
+ entry := map[string]interface{}{
+ "timestamp": time.Now().UTC().Format(time.RFC3339),
+ "hook": l.hookName,
+ "level": level,
+ "message": message,
+ }
+
+ if l.sessionID != "" {
+ entry["session_id"] = l.sessionID
+ }
+
+ // Add additional fields
+ for i := 0; i < len(fields)-1; i += 2 {
+ if key, ok := fields[i].(string); ok {
+ entry[key] = fields[i+1]
+ }
+ }
+
+ return entry
+}
+
+func (l *Logger) write(entry map[string]interface{}) {
+ data, err := json.Marshal(entry)
+ if err != nil {
+ return
+ }
+
+ f, err := os.OpenFile(l.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ return
+ }
+ defer func() {
+ if cerr := f.Close(); cerr != nil {
+ fmt.Fprintf(os.Stderr, "logging: failed to close log file %s: %v\n", l.logFile, cerr)
+ }
+ }()
+
+ if _, err := f.Write(data); err != nil {
+ fmt.Fprintf(os.Stderr, "logging: failed to write log entry to %s: %v\n", l.logFile, err)
+ return
+ }
+ if _, err := f.WriteString("\n"); err != nil {
+ fmt.Fprintf(os.Stderr, "logging: failed to write newline to %s: %v\n", l.logFile, err)
+ return
+ }
+ l.writeEndpointEvent(entry)
+}
+
+func (l *Logger) writeEndpointEvent(entry map[string]interface{}) {
+ path := endpointLogPath()
+ if path == "" {
+ return
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return
+ }
+ hostname, _ := os.Hostname()
+ action, severity := endpointAction(l.hookName, entry)
+ 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": "hook",
+ },
+ "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(fmt.Sprint(entry["message"]), 4096)),
+ }
+ if l.sessionID != "" {
+ event["session"] = map[string]interface{}{"id": l.sessionID}
+ }
+ data, err := json.Marshal(event)
+ if err != nil {
+ return
+ }
+ if len(data) > 64*1024 {
+ event["field_truncated"] = true
+ event["message"] = truncateEndpoint(fmt.Sprint(event["message"]), 1024)
+ data, err = json.Marshal(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 {
+ case "session-start":
+ return "session.started", "info"
+ case "session-end":
+ return "session.ended", "info"
+ case "pre-tool":
+ if strings.Contains(message, "denying") || strings.Contains(message, "block") {
+ return "policy.warned", "medium"
+ }
+ return "tool.invoked", "info"
+ case "stop-async-handler":
+ if strings.Contains(message, "blocking with violations") {
+ return "policy.blocked", "high"
+ }
+ if strings.Contains(message, "warning") {
+ return "policy.warned", "medium"
+ }
+ return "session.ended", "info"
+ default:
+ return "tool.invoked", "info"
+ }
+}
+
+func endpointLogPath() string {
+ if path := os.Getenv("BEACON_ENDPOINT_LOG"); path != "" {
+ return path
+ }
+ if os.Getenv("BEACON_ENDPOINT_MODE") == "" {
+ return ""
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ return filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
+}
+
+func redactEndpointString(value string) string {
+ for _, pattern := range endpointSecretPatterns {
+ 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 truncateEndpoint(value string, limit int) string {
+ if len(value) <= limit {
+ return value
+ }
+ if limit < 32 {
+ return value[:limit]
+ }
+ return value[:limit-15] + "...[truncated]"
+}
+
+// Debug logs a debug message
+func (l *Logger) Debug(message string, fields ...interface{}) {
+ entry := l.formatEntry("debug", message, fields...)
+ l.write(entry)
+}
+
+// Info logs an info message
+func (l *Logger) Info(message string, fields ...interface{}) {
+ entry := l.formatEntry("info", message, fields...)
+ l.write(entry)
+}
+
+// Warn logs a warning message
+func (l *Logger) Warn(message string, fields ...interface{}) {
+ entry := l.formatEntry("warn", message, fields...)
+ l.write(entry)
+}
+
+// Error logs an error message and also writes to stderr
+func (l *Logger) Error(message string, fields ...interface{}) {
+ entry := l.formatEntry("error", message, fields...)
+ l.write(entry)
+ fmt.Fprintf(os.Stderr, "[%s] ERROR: %s\n", l.hookName, message)
+}
diff --git a/cli/beacon-hooks/internal/state/state.go b/cli/beacon-hooks/internal/state/state.go
new file mode 100644
index 00000000..b1cb8057
--- /dev/null
+++ b/cli/beacon-hooks/internal/state/state.go
@@ -0,0 +1,347 @@
+package state
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+)
+
+var stateMutex sync.Mutex
+
+const (
+ staleEvaluationTTLHours = 2
+)
+
+// Evaluation represents a pending evaluation
+type Evaluation struct {
+ EvaluationID string `json:"evaluation_id"`
+ FilePath string `json:"file_path"`
+ CreatedAt string `json:"created_at"`
+}
+
+// SessionData represents data for a single session
+type SessionData struct {
+ Evaluations []Evaluation `json:"evaluations"`
+ RepromptCount int `json:"reprompt_count"`
+ Model string `json:"model,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+
+ // Secure-by-Design fields (used by Cursor's pre-tool gate)
+ 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
+type SessionState struct {
+ sessionID string
+ stateFilePath string
+ platform string
+}
+
+// NewSessionState creates a new session state manager
+func NewSessionState(sessionID, platform string) *SessionState {
+ return &SessionState{
+ sessionID: sessionID,
+ stateFilePath: filepath.Join(config.GetStateDir(platform), "state.json"),
+ platform: platform,
+ }
+}
+
+func (s *SessionState) loadStateFile() map[string]*SessionData {
+ data, err := os.ReadFile(s.stateFilePath)
+ if err != nil {
+ return make(map[string]*SessionData)
+ }
+
+ var state map[string]*SessionData
+ if err := json.Unmarshal(data, &state); err != nil {
+ return make(map[string]*SessionData)
+ }
+
+ return state
+}
+
+func (s *SessionState) saveStateFile(state map[string]*SessionData) error {
+ config.EnsureStateDir(s.platform)
+
+ data, err := json.MarshalIndent(state, "", " ")
+ if err != nil {
+ return err
+ }
+
+ // Write to temp file first, then rename (atomic)
+ tmpPath := s.stateFilePath + ".tmp"
+ if err := os.WriteFile(tmpPath, data, 0644); err != nil {
+ return err
+ }
+
+ return os.Rename(tmpPath, s.stateFilePath)
+}
+
+func (s *SessionState) ensureSession(state map[string]*SessionData) {
+ if state[s.sessionID] == nil {
+ state[s.sessionID] = &SessionData{
+ Evaluations: []Evaluation{},
+ RepromptCount: 0,
+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
+ }
+ }
+}
+
+// SetModel stores the AI model name for this session
+func (s *SessionState) SetModel(model string) {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ state[s.sessionID].Model = model
+ s.saveStateFile(state)
+}
+
+// GetModel returns the AI model name for this session
+func (s *SessionState) GetModel() string {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ if sessionData, ok := state[s.sessionID]; ok {
+ return sessionData.Model
+ }
+ return ""
+}
+
+// AddEvaluation adds a new pending evaluation
+func (s *SessionState) AddEvaluation(evaluationID, filePath string) {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+
+ state[s.sessionID].Evaluations = append(state[s.sessionID].Evaluations, Evaluation{
+ EvaluationID: evaluationID,
+ FilePath: filePath,
+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
+ })
+
+ s.saveStateFile(state)
+}
+
+// GetPendingEvaluations returns pending evaluations for this session
+func (s *SessionState) GetPendingEvaluations() []Evaluation {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ if sessionData, ok := state[s.sessionID]; ok {
+ return sessionData.Evaluations
+ }
+ return []Evaluation{}
+}
+
+// ClearEvaluations removes all evaluations for this session
+func (s *SessionState) ClearEvaluations() {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ state[s.sessionID].Evaluations = []Evaluation{}
+ s.saveStateFile(state)
+}
+
+// GetRepromptCount returns the current re-prompt count
+func (s *SessionState) GetRepromptCount() int {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ if sessionData, ok := state[s.sessionID]; ok {
+ return sessionData.RepromptCount
+ }
+ return 0
+}
+
+// IncrementRepromptCount increments and returns the re-prompt count
+func (s *SessionState) IncrementRepromptCount() int {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ state[s.sessionID].RepromptCount++
+ newCount := state[s.sessionID].RepromptCount
+ s.saveStateFile(state)
+ return newCount
+}
+
+// ResetRepromptCount resets the re-prompt count to 0
+func (s *SessionState) ResetRepromptCount() {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ state[s.sessionID].RepromptCount = 0
+ s.saveStateFile(state)
+}
+
+// SetSbdPolicies stores local policy context and resets the injection flag for a new generation.
+func (s *SessionState) SetSbdPolicies(policies, generationID string) {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ state[s.sessionID].SbdPolicies = policies
+ state[s.sessionID].SbdGenerationID = generationID
+ state[s.sessionID].SbdInjected = false
+ s.saveStateFile(state)
+}
+
+// GetSbdState returns the current Secure-by-Design state for this session.
+func (s *SessionState) GetSbdState() (policies, generationID string, injected bool) {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ if sessionData, ok := state[s.sessionID]; ok {
+ return sessionData.SbdPolicies, sessionData.SbdGenerationID, sessionData.SbdInjected
+ }
+ return "", "", false
+}
+
+// ClearSbdPolicies removes cached SbD policies for this session.
+// Called on Cursor early-return paths in prompt-submit to prevent stale policies
+// from being injected in later generations.
+func (s *SessionState) ClearSbdPolicies() {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ if sessionData, ok := state[s.sessionID]; ok {
+ sessionData.SbdPolicies = ""
+ sessionData.SbdGenerationID = ""
+ sessionData.SbdInjected = false
+ s.saveStateFile(state)
+ }
+}
+
+// MarkSbdInjected sets the injection flag to true, indicating policies have been
+// delivered to the agent for the current generation.
+func (s *SessionState) MarkSbdInjected() {
+ stateMutex.Lock()
+ defer stateMutex.Unlock()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ state[s.sessionID].SbdInjected = true
+ 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()
+ defer stateMutex.Unlock()
+
+ stateFilePath := filepath.Join(config.GetStateDir(platform), "state.json")
+
+ data, err := os.ReadFile(stateFilePath)
+ if err != nil {
+ return 0
+ }
+
+ var state map[string]*SessionData
+ if err := json.Unmarshal(data, &state); err != nil {
+ return 0
+ }
+
+ if len(state) == 0 {
+ return 0
+ }
+
+ cutoff := time.Now().Add(-time.Duration(staleEvaluationTTLHours) * time.Hour)
+ removedCount := 0
+ sessionsToRemove := []string{}
+
+ for sessionID, sessionData := range state {
+ var freshEvals []Evaluation
+ for _, eval := range sessionData.Evaluations {
+ createdAt, err := time.Parse(time.RFC3339, eval.CreatedAt)
+ if err != nil || createdAt.After(cutoff) {
+ freshEvals = append(freshEvals, eval)
+ } else {
+ removedCount++
+ }
+ }
+ sessionData.Evaluations = freshEvals
+
+ // Mark empty sessions for removal only if they are stale
+ if len(freshEvals) == 0 && sessionData.RepromptCount == 0 {
+ createdAt, err := time.Parse(time.RFC3339, sessionData.CreatedAt)
+ if err != nil || createdAt.Before(cutoff) {
+ sessionsToRemove = append(sessionsToRemove, sessionID)
+ }
+ }
+ }
+
+ for _, sessionID := range sessionsToRemove {
+ delete(state, sessionID)
+ // Remove orphan session log file
+ os.Remove(config.GetSessionLogFile(platform, sessionID))
+ }
+
+ if removedCount > 0 || len(sessionsToRemove) > 0 {
+ config.EnsureStateDir(platform)
+ jsonData, err := json.MarshalIndent(state, "", " ")
+ if err == nil {
+ tmpPath := stateFilePath + ".tmp"
+ if err := os.WriteFile(tmpPath, jsonData, 0644); err == nil {
+ os.Rename(tmpPath, stateFilePath)
+ }
+ }
+ }
+
+ return removedCount
+}
diff --git a/cli/beacon-hooks/internal/state/state_test.go b/cli/beacon-hooks/internal/state/state_test.go
new file mode 100644
index 00000000..1faa103e
--- /dev/null
+++ b/cli/beacon-hooks/internal/state/state_test.go
@@ -0,0 +1,255 @@
+package state
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+)
+
+func setupTestStateDir(t *testing.T) (tmpDir string, cleanup func()) {
+ t.Helper()
+ tmpDir = t.TempDir()
+
+ origCursorDir := config.CursorDir
+ config.CursorDir = tmpDir
+ os.MkdirAll(tmpDir, 0755)
+
+ return tmpDir, func() {
+ config.CursorDir = origCursorDir
+ }
+}
+
+func TestSetSbdPolicies(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+ st.SetSbdPolicies("policy content", "gen-1")
+
+ policies, generationID, injected := st.GetSbdState()
+ if policies != "policy content" {
+ t.Errorf("policies = %q, want %q", policies, "policy content")
+ }
+ if generationID != "gen-1" {
+ t.Errorf("generationID = %q, want %q", generationID, "gen-1")
+ }
+ if injected {
+ t.Error("injected should be false after SetSbdPolicies")
+ }
+}
+
+func TestSetSbdPolicies_ResetsInjectedFlag(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+
+ // Set policies and mark as injected
+ st.SetSbdPolicies("policy v1", "gen-1")
+ st.MarkSbdInjected()
+
+ _, _, injected := st.GetSbdState()
+ if !injected {
+ t.Fatal("injected should be true after MarkSbdInjected")
+ }
+
+ // New generation resets the injected flag
+ st.SetSbdPolicies("policy v2", "gen-2")
+
+ policies, generationID, injected := st.GetSbdState()
+ if policies != "policy v2" {
+ t.Errorf("policies = %q, want %q", policies, "policy v2")
+ }
+ if generationID != "gen-2" {
+ t.Errorf("generationID = %q, want %q", generationID, "gen-2")
+ }
+ if injected {
+ t.Error("injected should be reset to false on new generation")
+ }
+}
+
+func TestMarkSbdInjected(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+ st.SetSbdPolicies("policy content", "gen-1")
+
+ st.MarkSbdInjected()
+
+ _, _, injected := st.GetSbdState()
+ if !injected {
+ t.Error("injected should be true after MarkSbdInjected")
+ }
+}
+
+func TestGetSbdState_NoSession(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("nonexistent-session", "cursor")
+
+ policies, generationID, injected := st.GetSbdState()
+ if policies != "" {
+ t.Errorf("policies = %q, want empty", policies)
+ }
+ if generationID != "" {
+ t.Errorf("generationID = %q, want empty", generationID)
+ }
+ if injected {
+ t.Error("injected should be false for nonexistent session")
+ }
+}
+
+func TestSbdState_PersistsToDisk(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ // Write with one SessionState instance
+ st1 := NewSessionState("test-session", "cursor")
+ st1.SetSbdPolicies("persisted policy", "gen-1")
+
+ // Read with a fresh instance
+ st2 := NewSessionState("test-session", "cursor")
+ policies, generationID, injected := st2.GetSbdState()
+ if policies != "persisted policy" {
+ t.Errorf("policies = %q, want %q", policies, "persisted policy")
+ }
+ if generationID != "gen-1" {
+ t.Errorf("generationID = %q, want %q", generationID, "gen-1")
+ }
+ if injected {
+ t.Error("injected should be false")
+ }
+}
+
+func TestSbdState_IsolatedBySessions(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st1 := NewSessionState("session-a", "cursor")
+ st2 := NewSessionState("session-b", "cursor")
+
+ st1.SetSbdPolicies("policy-a", "gen-a")
+ st2.SetSbdPolicies("policy-b", "gen-b")
+
+ policies1, gen1, _ := st1.GetSbdState()
+ policies2, gen2, _ := st2.GetSbdState()
+
+ if policies1 != "policy-a" || gen1 != "gen-a" {
+ t.Errorf("session-a: policies=%q gen=%q, want policy-a/gen-a", policies1, gen1)
+ }
+ if policies2 != "policy-b" || gen2 != "gen-b" {
+ t.Errorf("session-b: policies=%q gen=%q, want policy-b/gen-b", policies2, gen2)
+ }
+}
+
+func TestSbdState_DoesNotAffectOtherFields(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+
+ // Set non-SbD fields first
+ st.SetModel("gpt-4")
+ st.AddEvaluation("eval-1", "/path/to/file.go")
+
+ // Set SbD fields
+ st.SetSbdPolicies("policy", "gen-1")
+
+ // Verify non-SbD fields are preserved
+ model := st.GetModel()
+ if model != "gpt-4" {
+ t.Errorf("model = %q, want %q", model, "gpt-4")
+ }
+ evals := st.GetPendingEvaluations()
+ if len(evals) != 1 || evals[0].EvaluationID != "eval-1" {
+ t.Errorf("evaluations not preserved after SetSbdPolicies")
+ }
+}
+
+func TestClearSbdPolicies(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+ st.SetSbdPolicies("policy content", "gen-1")
+ st.MarkSbdInjected()
+
+ // Verify state is set
+ policies, _, injected := st.GetSbdState()
+ if policies == "" || !injected {
+ t.Fatal("precondition failed: state should be set")
+ }
+
+ // Clear
+ st.ClearSbdPolicies()
+
+ policies, generationID, injected := st.GetSbdState()
+ if policies != "" {
+ t.Errorf("policies = %q, want empty after clear", policies)
+ }
+ if generationID != "" {
+ t.Errorf("generationID = %q, want empty after clear", generationID)
+ }
+ if injected {
+ t.Error("injected should be false after clear")
+ }
+}
+
+func TestClearSbdPolicies_NoSession(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ // Should not panic on nonexistent session
+ st := NewSessionState("nonexistent", "cursor")
+ st.ClearSbdPolicies()
+
+ policies, _, _ := st.GetSbdState()
+ if policies != "" {
+ t.Error("should remain empty for nonexistent session")
+ }
+}
+
+func TestClearSbdPolicies_PreservesOtherFields(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+ st.SetModel("gpt-4")
+ st.AddEvaluation("eval-1", "/path/to/file.go")
+ st.SetSbdPolicies("policy", "gen-1")
+
+ st.ClearSbdPolicies()
+
+ // SbD fields cleared
+ policies, _, _ := st.GetSbdState()
+ if policies != "" {
+ t.Error("policies should be cleared")
+ }
+
+ // Other fields preserved
+ if st.GetModel() != "gpt-4" {
+ t.Error("model should be preserved after ClearSbdPolicies")
+ }
+ evals := st.GetPendingEvaluations()
+ if len(evals) != 1 {
+ t.Error("evaluations should be preserved after ClearSbdPolicies")
+ }
+}
+
+func TestSbdState_StateFileLocation(t *testing.T) {
+ tmpDir, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ st := NewSessionState("test-session", "cursor")
+ st.SetSbdPolicies("policy", "gen-1")
+
+ // Verify state.json was created in the expected location
+ stateFile := filepath.Join(tmpDir, "state.json")
+ if _, err := os.Stat(stateFile); err != nil {
+ t.Errorf("state.json not found at expected path %s: %v", stateFile, err)
+ }
+}
diff --git a/cli/beacon-hooks/internal/version/version.go b/cli/beacon-hooks/internal/version/version.go
new file mode 100644
index 00000000..e23d52c8
--- /dev/null
+++ b/cli/beacon-hooks/internal/version/version.go
@@ -0,0 +1,4 @@
+package version
+
+// Version is set at build time via ldflags
+var Version = "dev"
diff --git a/cli/beacon-hooks/main.go b/cli/beacon-hooks/main.go
new file mode 100644
index 00000000..c32f3095
--- /dev/null
+++ b/cli/beacon-hooks/main.go
@@ -0,0 +1,7 @@
+package main
+
+import "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/cmd"
+
+func main() {
+ cmd.Execute()
+}
diff --git a/cli/beacon/.goreleaser.yaml b/cli/beacon/.goreleaser.yaml
new file mode 100644
index 00000000..6fb0d893
--- /dev/null
+++ b/cli/beacon/.goreleaser.yaml
@@ -0,0 +1,124 @@
+# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
+version: 2
+
+project_name: beacon
+
+before:
+ hooks:
+ - go mod tidy
+ - bash -c 'cd ../beacon-hooks && go mod tidy'
+
+builds:
+ - id: beacon
+ main: .
+ binary: beacon
+ env:
+ - CGO_ENABLED=0
+ flags:
+ - -a
+ ldflags:
+ - -s -w
+ - -X github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version.Version={{.Version}}
+ - -X github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version.GitCommit={{.ShortCommit}}
+ - -X github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version.BuildDate={{.Date}}
+ goos:
+ - darwin
+ - linux
+ - windows
+ goarch:
+ - amd64
+ - arm64
+ ignore:
+ - goos: windows
+ goarch: arm64
+ hooks:
+ pre:
+ # Build the hooks binary for this target platform and embed it.
+ # IMPORTANT: This writes to a shared hooks.bin file. The -a flag above
+ # forces a full rebuild for each target so Go re-reads the freshly-built
+ # hooks.bin instead of serving a stale copy from the build cache.
+ - cmd: bash -c 'cd ../beacon-hooks && GOOS={{ .Os }} GOARCH={{ .Arch }} go build -ldflags "-s -w -X github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/version.Version={{ .Version }}" -o ../beacon/internal/embedded/hooks.bin .'
+ output: true
+
+archives:
+ - formats:
+ - tar.gz
+ name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
+ format_overrides:
+ - goos: windows
+ formats:
+ - zip
+ files:
+ - README*
+
+checksum:
+ name_template: "checksums.txt"
+ algorithm: sha256
+
+changelog:
+ sort: asc
+ filters:
+ exclude:
+ - "^docs:"
+ - "^test:"
+ - "^chore:"
+ - "^ci:"
+ - Merge pull request
+ - Merge branch
+ groups:
+ - title: Features
+ regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
+ order: 0
+ - title: Bug Fixes
+ regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
+ order: 1
+ - title: Other
+ order: 999
+
+brews:
+ - name: beacon
+ repository:
+ owner: asymptote-labs
+ name: homebrew-tap
+ token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
+ directory: Formula
+ homepage: https://asymptotelabs.ai
+ description: "Open-source endpoint agent for local AI runtime telemetry"
+ license: "MIT"
+ commit_author:
+ name: asymptote-bot
+ commit_msg_template: "Homebrew formula update for {{ .ProjectName }} version {{ .Tag }}"
+ install: |
+ bin.install "beacon"
+ caveats: |
+ To configure local endpoint telemetry, run:
+ beacon endpoint install --user
+ test: |
+ system "#{bin}/beacon", "version"
+
+release:
+ github:
+ owner: asymptote-labs
+ name: beacon
+ draft: false
+ prerelease: auto
+ name_template: "v{{.Version}}"
+ footer: |
+ ## Installation
+
+ ### Homebrew (macOS/Linux)
+ ```bash
+ brew tap asymptote-labs/tap
+ brew install beacon
+ ```
+
+ ### Manual Download
+ Download the appropriate archive for your platform from the assets below, extract it, and add the binary to your PATH.
+
+ ## Quick Start
+ ```bash
+ beacon endpoint install --user
+ beacon endpoint status
+ beacon endpoint wazuh print-config
+ ```
diff --git a/cli/beacon/Makefile b/cli/beacon/Makefile
new file mode 100644
index 00000000..378be77a
--- /dev/null
+++ b/cli/beacon/Makefile
@@ -0,0 +1,125 @@
+# Beacon CLI Makefile
+
+# Build variables
+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
+GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+BUILD_DATE ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
+
+# Go build flags
+LDFLAGS := -X github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version.Version=$(VERSION) \
+ -X github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version.GitCommit=$(GIT_COMMIT) \
+ -X github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version.BuildDate=$(BUILD_DATE)
+
+# Hooks binary ldflags (embed version for upgrade display)
+HOOKS_LDFLAGS := -s -w -X github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/version.Version=$(VERSION)
+
+# Output binary name
+BINARY := beacon
+HOOKS_BINARY := beacon-hooks
+HOOKS_DIR := ../beacon-hooks
+EMBEDDED_DIR := internal/embedded
+
+# Detect current platform
+GOOS ?= $(shell go env GOOS)
+GOARCH ?= $(shell go env GOARCH)
+
+.PHONY: all build clean test install build-hooks build-hooks-current ensure-placeholder
+
+all: build
+
+# Ensure placeholder exists (for fresh clones where hooks.bin is gitignored)
+ensure-placeholder:
+ @if [ ! -f $(EMBEDDED_DIR)/hooks.bin ]; then \
+ echo "Creating placeholder hooks.bin..."; \
+ echo "PLACEHOLDER" > $(EMBEDDED_DIR)/hooks.bin; \
+ fi
+
+# Build hooks binary for current platform and copy to embedded directory
+build-hooks-current: ensure-placeholder
+ @echo "Building hooks binary for $(GOOS)/$(GOARCH)..."
+ cd $(HOOKS_DIR) && GOOS=$(GOOS) GOARCH=$(GOARCH) go build -ldflags "$(HOOKS_LDFLAGS)" -o $(HOOKS_BINARY) .
+ @echo "Copying hooks binary to embedded directory..."
+ cp $(HOOKS_DIR)/$(HOOKS_BINARY) $(EMBEDDED_DIR)/hooks.bin
+ @echo "Hooks binary ready."
+
+# Build hooks binary for specific platform (used by goreleaser)
+build-hooks-for-platform:
+ @echo "Building hooks binary for $(TARGET_OS)/$(TARGET_ARCH)..."
+ cd $(HOOKS_DIR) && GOOS=$(TARGET_OS) GOARCH=$(TARGET_ARCH) go build -ldflags "$(HOOKS_LDFLAGS)" -o $(HOOKS_BINARY)-$(TARGET_OS)-$(TARGET_ARCH)$(if $(filter windows,$(TARGET_OS)),.exe,) .
+ @if command -v upx >/dev/null 2>&1; then \
+ echo "Compressing with UPX..."; \
+ upx --best --lzma $(HOOKS_DIR)/$(HOOKS_BINARY)-$(TARGET_OS)-$(TARGET_ARCH)$(if $(filter windows,$(TARGET_OS)),.exe,) || true; \
+ fi
+ cp $(HOOKS_DIR)/$(HOOKS_BINARY)-$(TARGET_OS)-$(TARGET_ARCH)$(if $(filter windows,$(TARGET_OS)),.exe,) $(EMBEDDED_DIR)/hooks.bin
+
+# Build the CLI (with hooks for current platform)
+build: build-hooks-current
+ @echo "Building $(BINARY) $(VERSION)..."
+ go build -ldflags "$(LDFLAGS)" -o $(BINARY) .
+
+# Build CLI only (assumes hooks.bin is already in place)
+build-cli-only:
+ @echo "Building $(BINARY) $(VERSION)..."
+ go build -ldflags "$(LDFLAGS)" -o $(BINARY) .
+
+# Build for all platforms (each with matching hooks binary)
+build-all: build-darwin build-linux build-windows
+
+build-darwin: build-darwin-amd64 build-darwin-arm64
+
+build-darwin-amd64:
+ @echo "Building for macOS (amd64)..."
+ $(MAKE) build-hooks-for-platform TARGET_OS=darwin TARGET_ARCH=amd64
+ GOOS=darwin GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-darwin-amd64 .
+
+build-darwin-arm64:
+ @echo "Building for macOS (arm64)..."
+ $(MAKE) build-hooks-for-platform TARGET_OS=darwin TARGET_ARCH=arm64
+ GOOS=darwin GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-darwin-arm64 .
+
+build-linux: build-linux-amd64 build-linux-arm64
+
+build-linux-amd64:
+ @echo "Building for Linux (amd64)..."
+ $(MAKE) build-hooks-for-platform TARGET_OS=linux TARGET_ARCH=amd64
+ GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-linux-amd64 .
+
+build-linux-arm64:
+ @echo "Building for Linux (arm64)..."
+ $(MAKE) build-hooks-for-platform TARGET_OS=linux TARGET_ARCH=arm64
+ GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-linux-arm64 .
+
+build-windows: build-windows-amd64
+
+build-windows-amd64:
+ @echo "Building for Windows (amd64)..."
+ $(MAKE) build-hooks-for-platform TARGET_OS=windows TARGET_ARCH=amd64
+ GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-windows-amd64.exe .
+
+# Clean build artifacts
+clean:
+ rm -f $(BINARY) $(BINARY)-*
+ rm -f $(HOOKS_DIR)/$(HOOKS_BINARY) $(HOOKS_DIR)/$(HOOKS_BINARY)-*
+ # Reset hooks.bin to placeholder
+ echo "PLACEHOLDER" > $(EMBEDDED_DIR)/hooks.bin
+
+# Run tests
+test:
+ go test -v ./...
+
+# Install to GOPATH/bin
+install: build
+ @echo "Installing $(BINARY)..."
+ go install -ldflags "$(LDFLAGS)" .
+
+# Format code
+fmt:
+ go fmt ./...
+
+# Lint code
+lint:
+ golangci-lint run
+
+# Run go mod tidy
+tidy:
+ go mod tidy
diff --git a/cli/beacon/README.md b/cli/beacon/README.md
new file mode 100644
index 00000000..acb4d495
--- /dev/null
+++ b/cli/beacon/README.md
@@ -0,0 +1,44 @@
+# beacon
+
+Public CLI for Beacon Endpoint Agent.
+
+## Build
+
+```bash
+make build
+```
+
+## Common Commands
+
+```bash
+./beacon endpoint install --user
+./beacon endpoint status --json
+./beacon endpoint discover --json
+./beacon endpoint repair --user
+./beacon endpoint uninstall --user --keep-logs
+```
+
+## Wazuh
+
+```bash
+./beacon endpoint wazuh print-config --user
+./beacon endpoint wazuh install-pack --output ./beacon-wazuh --user
+./beacon endpoint wazuh validate --user
+```
+
+## Optional Integrations
+
+```bash
+./beacon endpoint hooks install --harness cursor --user
+./beacon endpoint hooks status --harness cursor --user
+
+./beacon endpoint integrations claude-cowork print-config --user
+./beacon endpoint integrations claude-cowork validate --user
+```
+
+## Test
+
+```bash
+go test ./...
+go test -race ./internal/endpoint/...
+```
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
new file mode 100644
index 00000000..b85e1454
--- /dev/null
+++ b/cli/beacon/cmd/endpoint.go
@@ -0,0 +1,496 @@
+package cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
+ endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/wazuh"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+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
+}
+
+var endpointCmd = &cobra.Command{
+ Use: "endpoint",
+ Short: "Manage the local Beacon endpoint agent",
+ Long: `Manage the open-source Beacon endpoint agent for local AI runtime
+discovery, telemetry collection, and Wazuh-compatible JSON logs.`,
+}
+
+var endpointInstallCmd = &cobra.Command{
+ Use: "install",
+ Short: "Install local endpoint telemetry configuration",
+ SilenceUsage: true,
+ RunE: runEndpointInstall,
+}
+
+var endpointStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show local endpoint status",
+ SilenceUsage: true,
+ RunE: runEndpointStatus,
+}
+
+var endpointDiscoverCmd = &cobra.Command{
+ Use: "discover",
+ Short: "Discover supported local AI agent runtimes",
+ SilenceUsage: true,
+ RunE: runEndpointDiscover,
+}
+
+var endpointUninstallCmd = &cobra.Command{
+ Use: "uninstall",
+ Short: "Remove local endpoint service files",
+ SilenceUsage: true,
+ RunE: runEndpointUninstall,
+}
+
+var endpointRepairCmd = &cobra.Command{
+ Use: "repair",
+ Short: "Repair local endpoint service and telemetry configuration",
+ SilenceUsage: true,
+ RunE: runEndpointRepair,
+}
+
+var endpointWazuhCmd = &cobra.Command{
+ Use: "wazuh",
+ Short: "Manage Wazuh integration content",
+}
+
+var endpointIntegrationsCmd = &cobra.Command{
+ Use: "integrations",
+ Short: "Manage admin-configured endpoint integrations",
+}
+
+var endpointHooksCmd = &cobra.Command{
+ Use: "hooks",
+ Short: "Manage endpoint hook integrations",
+}
+
+var endpointHooksInstallCmd = &cobra.Command{
+ Use: "install",
+ Short: "Install endpoint hooks for supported harnesses",
+ SilenceUsage: true,
+ RunE: runEndpointHooksInstall,
+}
+
+var endpointHooksUninstallCmd = &cobra.Command{
+ Use: "uninstall",
+ Short: "Uninstall endpoint hooks for supported harnesses",
+ SilenceUsage: true,
+ RunE: runEndpointHooksUninstall,
+}
+
+var endpointHooksStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show endpoint hook integration status",
+ SilenceUsage: true,
+ RunE: runEndpointHooksStatus,
+}
+
+var endpointCoworkCmd = &cobra.Command{
+ Use: "claude-cowork",
+ Short: "Manage Claude Cowork OpenTelemetry integration",
+}
+
+var endpointCoworkPrintConfigCmd = &cobra.Command{
+ Use: "print-config",
+ Short: "Print Claude Cowork OTLP setup guidance",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := loadOrDefaultConfig()
+ fmt.Print(cowork.PrintConfig(cowork.Config{
+ Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.Collector.HTTPPort),
+ Protocol: "HTTP/protobuf",
+ Headers: endpointOpts.coworkHeaders,
+ }))
+ },
+}
+
+var endpointCoworkStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show Claude Cowork endpoint integration status",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := loadOrDefaultConfig()
+ status := cowork.GetStatus(cfg.LogPath)
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(os.Stdout).Encode(status)
+ return
+ }
+ fmt.Printf("%s: detected=%t observed=%t\n", status.DisplayName, status.Detected, status.LastEventObserved)
+ fmt.Println(status.Message)
+ },
+}
+
+var endpointCoworkValidateCmd = &cobra.Command{
+ Use: "validate",
+ Short: "Validate whether Claude Cowork events are arriving",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg := loadOrDefaultConfig()
+ status := cowork.GetStatus(cfg.LogPath)
+ if !status.LastEventObserved {
+ fmt.Print(cowork.PrintConfig(cowork.Config{
+ Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.Collector.HTTPPort),
+ Protocol: "HTTP/protobuf",
+ Headers: endpointOpts.coworkHeaders,
+ }))
+ return fmt.Errorf("no Claude Cowork events observed in %s", cfg.LogPath)
+ }
+ fmt.Println("Claude Cowork events observed in endpoint runtime log.")
+ return nil
+ },
+}
+
+var endpointWazuhPrintConfigCmd = &cobra.Command{
+ Use: "print-config",
+ Short: "Print a Wazuh localfile snippet",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := loadOrDefaultConfig()
+ fmt.Print(wazuh.LocalfileSnippet(cfg.LogPath))
+ },
+}
+
+var endpointWazuhInstallPackCmd = &cobra.Command{
+ Use: "install-pack",
+ Short: "Write Wazuh rules and config snippets to a directory",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if endpointOpts.outputDir == "" {
+ return fmt.Errorf("--output is required")
+ }
+ cfg := loadOrDefaultConfig()
+ if err := wazuh.InstallPack(endpointOpts.outputDir, cfg.LogPath); err != nil {
+ return err
+ }
+ fmt.Printf("Wazuh content pack written to %s\n", endpointOpts.outputDir)
+ return nil
+ },
+}
+
+var endpointWazuhValidateCmd = &cobra.Command{
+ Use: "validate",
+ Short: "Write and describe a Wazuh validation event",
+ SilenceUsage: true,
+ RunE: runEndpointWazuhValidate,
+}
+
+func init() {
+ rootCmd.AddCommand(endpointCmd)
+
+ endpointCmd.AddCommand(endpointInstallCmd)
+ endpointCmd.AddCommand(endpointStatusCmd)
+ endpointCmd.AddCommand(endpointDiscoverCmd)
+ endpointCmd.AddCommand(endpointUninstallCmd)
+ endpointCmd.AddCommand(endpointRepairCmd)
+ endpointCmd.AddCommand(endpointWazuhCmd)
+ endpointCmd.AddCommand(endpointIntegrationsCmd)
+ endpointCmd.AddCommand(endpointHooksCmd)
+ endpointWazuhCmd.AddCommand(endpointWazuhPrintConfigCmd)
+ endpointWazuhCmd.AddCommand(endpointWazuhInstallPackCmd)
+ endpointWazuhCmd.AddCommand(endpointWazuhValidateCmd)
+ endpointIntegrationsCmd.AddCommand(endpointCoworkCmd)
+ endpointHooksCmd.AddCommand(endpointHooksInstallCmd)
+ endpointHooksCmd.AddCommand(endpointHooksUninstallCmd)
+ endpointHooksCmd.AddCommand(endpointHooksStatusCmd)
+ endpointCoworkCmd.AddCommand(endpointCoworkPrintConfigCmd)
+ endpointCoworkCmd.AddCommand(endpointCoworkStatusCmd)
+ endpointCoworkCmd.AddCommand(endpointCoworkValidateCmd)
+
+ for _, c := range []*cobra.Command{endpointInstallCmd, endpointStatusCmd, endpointDiscoverCmd, endpointUninstallCmd, endpointRepairCmd} {
+ c.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")
+ c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ }
+
+ endpointInstallCmd.Flags().StringVar(&endpointOpts.harnesses, "harness", "claude,codex", "Comma-separated harnesses to configure")
+ endpointInstallCmd.Flags().IntVar(&endpointOpts.grpcPort, "otlp-grpc-port", endpointconfig.DefaultGRPCPort, "Local OTLP gRPC port")
+ 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")
+ 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")
+
+ endpointDiscoverCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print discovery as JSON")
+ endpointStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")
+ endpointWazuhPrintConfigCmd.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")
+ endpointWazuhPrintConfigCmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ endpointWazuhInstallPackCmd.Flags().StringVar(&endpointOpts.outputDir, "output", "", "Output directory for Wazuh content pack")
+ endpointWazuhInstallPackCmd.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")
+ endpointWazuhInstallPackCmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ endpointWazuhValidateCmd.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")
+ endpointWazuhValidateCmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ for _, c := range []*cobra.Command{endpointCoworkPrintConfigCmd, endpointCoworkStatusCmd, endpointCoworkValidateCmd} {
+ c.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")
+ c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ }
+ endpointCoworkPrintConfigCmd.Flags().StringVar(&endpointOpts.coworkHeaders, "headers", "", "Optional OTLP headers to show in setup guidance")
+ endpointCoworkValidateCmd.Flags().StringVar(&endpointOpts.coworkHeaders, "headers", "", "Optional OTLP headers to show when validation fails")
+ endpointCoworkStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")
+ for _, c := range []*cobra.Command{endpointHooksInstallCmd, endpointHooksUninstallCmd, endpointHooksStatusCmd} {
+ c.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")
+ c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ c.Flags().StringVar(&endpointOpts.harnesses, "harness", "cursor", "Comma-separated hook harnesses")
+ c.Flags().StringVar(&endpointOpts.hookLevel, "level", "user", "Hook install level: user or project")
+ }
+ endpointHooksStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")
+ endpointUninstallCmd.Flags().BoolVar(&endpointOpts.keepLogs, "keep-logs", false, "Keep runtime logs during uninstall")
+ endpointUninstallCmd.Flags().BoolVar(&endpointOpts.keepConfig, "keep-config", false, "Keep harness telemetry configuration during uninstall")
+}
+
+func runEndpointHooksInstall(cmd *cobra.Command, args []string) error {
+ cfg := loadOrDefaultConfig()
+ for _, name := range splitCSV(endpointOpts.harnesses) {
+ switch strings.TrimSpace(name) {
+ case "cursor":
+ status, err := endpointhooks.InstallCursor(endpointhooks.CursorOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Cursor hooks installed: %s\n", status.HooksJSONPath)
+ case "":
+ default:
+ return fmt.Errorf("unsupported hook harness %q", name)
+ }
+ }
+ return nil
+}
+
+func runEndpointHooksUninstall(cmd *cobra.Command, args []string) error {
+ cfg := loadOrDefaultConfig()
+ for _, name := range splitCSV(endpointOpts.harnesses) {
+ switch strings.TrimSpace(name) {
+ case "cursor":
+ status, err := endpointhooks.UninstallCursor(endpointhooks.CursorOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Println(status.Message)
+ case "":
+ default:
+ return fmt.Errorf("unsupported hook harness %q", name)
+ }
+ }
+ return nil
+}
+
+func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {
+ cfg := loadOrDefaultConfig()
+ status := endpointhooks.CursorHookStatus(endpointhooks.CursorOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(os.Stdout).Encode(status)
+ }
+ fmt.Printf("Cursor hooks: installed=%t path=%s\n", status.Installed, status.HooksJSONPath)
+ fmt.Println(status.Message)
+ return nil
+}
+
+func runEndpointWazuhValidate(cmd *cobra.Command, args []string) error {
+ cfg := loadOrDefaultConfig()
+ path, err := writeValidationEvent(cfg, "wazuh")
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Validation event written to %s\n", path)
+ fmt.Println("Expected Wazuh fields: vendor=beacon product=endpoint-agent event.kind=agent_runtime")
+ fmt.Println("Wazuh localfile snippet:")
+ fmt.Print(wazuh.LocalfileSnippet(cfg.LogPath))
+ fmt.Println("Expected base rule: 100500")
+ return nil
+}
+
+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,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Endpoint config written to %s\n", result.ConfigPath)
+ fmt.Printf("Collector config written to %s\n", result.CollectorConfigPath)
+ fmt.Printf("Launch plist written to %s\n", result.PlistPath)
+ fmt.Printf("Install manifest written to %s\n", result.ManifestPath)
+ fmt.Printf("Runtime log: %s\n", result.LogPath)
+ return nil
+}
+
+func runEndpointStatus(cmd *cobra.Command, args []string) error {
+ status := lifecycle.GetStatus(endpointOpts.userMode, endpointOpts.logPath)
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(os.Stdout).Encode(status)
+ }
+ fmt.Printf("Beacon Endpoint Agent %s\n", status.Version)
+ fmt.Printf("Config: %s\n", status.ConfigPath)
+ fmt.Printf("Runtime log: %s\n", status.LogPath)
+ fmt.Printf("Collector: grpc=%t http=%t", status.Collector.GRPCReady, status.Collector.HTTPReady)
+ if status.Collector.Message != "" {
+ fmt.Printf(" (%s)", status.Collector.Message)
+ }
+ fmt.Println()
+ fmt.Printf("Service: loaded=%t running=%t", status.Service.Loaded, status.Service.Running)
+ if status.Service.Message != "" {
+ fmt.Printf(" (%s)", status.Service.Message)
+ }
+ fmt.Println()
+ for _, h := range status.Harnesses {
+ if h.Detected {
+ fmt.Printf("Harness: %s %s telemetry=%s\n", h.DisplayName, h.Version, h.TelemetryStatus)
+ }
+ }
+ for _, check := range status.Diagnostics {
+ if check.Status != "ok" {
+ fmt.Printf("Diagnostic: %s %s (%s)\n", check.Name, check.Status, check.Message)
+ }
+ }
+ if status.LastEvent == "" {
+ fmt.Println("Last event: none")
+ } else {
+ fmt.Println("Last event: present")
+ }
+ return nil
+}
+
+func runEndpointDiscover(cmd *cobra.Command, args []string) error {
+ discovered := harness.DiscoverAll()
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(os.Stdout).Encode(discovered)
+ }
+ for _, h := range discovered {
+ state := "not detected"
+ if h.Detected {
+ state = "detected"
+ }
+ fmt.Printf("%s: %s, telemetry=%s", h.DisplayName, state, h.TelemetryStatus)
+ if h.ExecutablePath != "" {
+ fmt.Printf(", path=%s", h.ExecutablePath)
+ }
+ fmt.Println()
+ }
+ cfg := loadOrDefaultConfig()
+ for _, h := range discovered {
+ if h.Detected {
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Category: "inventory",
+ Severity: schema.SeverityInfo,
+ AgentVersion: version.GetVersion(),
+ Harness: schema.HarnessInfo{
+ Name: h.Name,
+ Version: h.Version,
+ ExecutablePath: h.ExecutablePath,
+ ConfigPath: h.ConfigPath,
+ },
+ Message: h.DisplayName + " detected",
+ })
+ _, _ = writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode})
+ }
+ }
+ return nil
+}
+
+func writeValidationEvent(cfg endpointconfig.Config, destination string) (string, error) {
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Category: "validation",
+ Severity: schema.SeverityInfo,
+ AgentVersion: version.GetVersion(),
+ Harness: schema.HarnessInfo{Name: "test_harness", Version: "test"},
+ Message: "Beacon endpoint Wazuh validation event",
+ })
+ event.Destination = &schema.DestinationInfo{Type: destination, Mode: "localfile", Status: "configured"}
+ return writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode})
+}
+
+func runEndpointUninstall(cmd *cobra.Command, args []string) error {
+ if err := lifecycle.Uninstall(lifecycle.UninstallOptions{UserMode: endpointOpts.userMode, LogPath: endpointOpts.logPath, KeepLogs: endpointOpts.keepLogs, KeepConfig: endpointOpts.keepConfig}); err != nil {
+ return err
+ }
+ fmt.Println("Endpoint service, config, and managed files removed.")
+ return nil
+}
+
+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,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Endpoint repaired. Manifest: %s\n", result.ManifestPath)
+ return nil
+}
+
+func loadOrDefaultConfig() endpointconfig.Config {
+ if cfg, err := endpointconfig.Load(endpointOpts.userMode); err == nil {
+ if endpointOpts.logPath != "" {
+ cfg.LogPath = endpointOpts.logPath
+ }
+ return cfg
+ }
+ logPath := endpointOpts.logPath
+ if logPath == "" {
+ logPath = writer.DefaultPath(endpointOpts.userMode)
+ }
+ return endpointconfig.Default(endpointOpts.userMode, logPath)
+}
+
+func splitCSV(value string) []string {
+ parts := strings.Split(value, ",")
+ out := make([]string, 0, len(parts))
+ for _, part := range parts {
+ part = strings.TrimSpace(part)
+ if part != "" {
+ out = append(out, part)
+ }
+ }
+ return out
+}
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.go
new file mode 100644
index 00000000..cab3fa9e
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_test.go
@@ -0,0 +1,16 @@
+package cmd
+
+import "testing"
+
+func TestSplitCSV(t *testing.T) {
+ got := splitCSV("cursor, claude-cowork,,codex")
+ want := []string{"cursor", "claude-cowork", "codex"}
+ if len(got) != len(want) {
+ t.Fatalf("splitCSV length = %d, want %d", len(got), len(want))
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("splitCSV[%d] = %q, want %q", i, got[i], want[i])
+ }
+ }
+}
diff --git a/cli/beacon/cmd/root.go b/cli/beacon/cmd/root.go
new file mode 100644
index 00000000..22152dd3
--- /dev/null
+++ b/cli/beacon/cmd/root.go
@@ -0,0 +1,44 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+var rootCmd = &cobra.Command{
+ Use: "beacon",
+ Short: "Beacon Endpoint Agent - local AI runtime telemetry",
+ Long: `Beacon Endpoint Agent discovers local AI agent runtimes, configures
+local telemetry, and writes Wazuh-compatible JSON logs without requiring an
+Beacon-hosted backend.`,
+ Version: version.GetVersion(),
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println("Beacon Endpoint Agent")
+ fmt.Println()
+ fmt.Println("Start with:")
+ fmt.Println(" beacon endpoint install --user")
+ fmt.Println(" beacon endpoint status")
+ fmt.Println(" beacon endpoint wazuh print-config")
+ fmt.Println()
+ cmd.Usage()
+ },
+}
+
+// Execute runs the root command
+func Execute() {
+ if err := rootCmd.Execute(); err != nil {
+ os.Exit(1)
+ }
+}
+
+func init() {
+ // Set version template
+ rootCmd.SetVersionTemplate(`{{printf "beacon version %s\n" .Version}}`)
+
+ // Add version flag shorthand
+ rootCmd.Flags().BoolP("version", "v", false, "Print the version number")
+}
diff --git a/cli/beacon/cmd/version.go b/cli/beacon/cmd/version.go
new file mode 100644
index 00000000..c7c1837a
--- /dev/null
+++ b/cli/beacon/cmd/version.go
@@ -0,0 +1,22 @@
+package cmd
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+var versionCmd = &cobra.Command{
+ Use: "version",
+ Short: "Display the version of the Beacon CLI",
+ Long: `Display the version number, git commit, and build date of the Beacon CLI.`,
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println("beacon version", version.GetFullVersion())
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(versionCmd)
+}
diff --git a/cli/beacon/go.mod b/cli/beacon/go.mod
new file mode 100644
index 00000000..ac9e06a8
--- /dev/null
+++ b/cli/beacon/go.mod
@@ -0,0 +1,10 @@
+module github.com/asymptote-labs/agent-beacon/cli/beacon
+
+go 1.24
+
+require github.com/spf13/cobra v1.8.1
+
+require (
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/spf13/pflag v1.0.5 // indirect
+)
diff --git a/cli/beacon/go.sum b/cli/beacon/go.sum
new file mode 100644
index 00000000..912390a7
--- /dev/null
+++ b/cli/beacon/go.sum
@@ -0,0 +1,10 @@
+github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
+github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/cli/beacon/internal/embedded/embed.go b/cli/beacon/internal/embedded/embed.go
new file mode 100644
index 00000000..658a703c
--- /dev/null
+++ b/cli/beacon/internal/embedded/embed.go
@@ -0,0 +1,27 @@
+package embedded
+
+import (
+ _ "embed"
+ "runtime"
+)
+
+// HooksBinary is the compressed hooks binary for the current platform.
+// This file is replaced at build time with the platform-specific binary.
+//
+//go:embed hooks.bin
+var HooksBinary []byte
+
+// GetBinaryName returns the appropriate binary name for the current platform
+func GetBinaryName() string {
+ if runtime.GOOS == "windows" {
+ return "beacon-hooks.exe"
+ }
+ return "beacon-hooks"
+}
+
+// HasEmbeddedBinary returns true if a real binary is embedded (not just placeholder)
+func HasEmbeddedBinary() bool {
+ // Placeholder file contains "PLACEHOLDER" text
+ // Real binary will be much larger and start with ELF/Mach-O/PE headers
+ return len(HooksBinary) > 100
+}
diff --git a/cli/beacon/internal/embedded/validate.go b/cli/beacon/internal/embedded/validate.go
new file mode 100644
index 00000000..bf1288ad
--- /dev/null
+++ b/cli/beacon/internal/embedded/validate.go
@@ -0,0 +1,117 @@
+package embedded
+
+import (
+ "bytes"
+ "debug/elf"
+ "debug/macho"
+ "debug/pe"
+ "fmt"
+ "runtime"
+)
+
+// ValidateArchitecture checks that the embedded hooks binary matches the
+// current runtime OS and architecture. Returns an error with a descriptive
+// message if there is a mismatch (e.g., an x86_64 binary on an arm64 host).
+func ValidateArchitecture() error {
+ if len(HooksBinary) < 4 {
+ return fmt.Errorf("embedded binary too small to validate")
+ }
+
+ reader := bytes.NewReader(HooksBinary)
+
+ // Try Mach-O (macOS)
+ if f, err := macho.NewFile(reader); err == nil {
+ return validateMachO(f)
+ }
+
+ // Try ELF (Linux)
+ reader.Reset(HooksBinary)
+ if f, err := elf.NewFile(reader); err == nil {
+ return validateELF(f)
+ }
+
+ // Try PE (Windows)
+ reader.Reset(HooksBinary)
+ if f, err := pe.NewFile(reader); err == nil {
+ return validatePE(f)
+ }
+
+ return fmt.Errorf("embedded binary has unrecognized format (not Mach-O, ELF, or PE)")
+}
+
+func validateMachO(f *macho.File) error {
+ if runtime.GOOS != "darwin" {
+ return fmt.Errorf("embedded binary is a macOS Mach-O binary but runtime OS is %s", runtime.GOOS)
+ }
+
+ binaryArch := machoArch(f.Cpu)
+ if binaryArch != runtime.GOARCH {
+ return archMismatchError(binaryArch)
+ }
+ return nil
+}
+
+func validateELF(f *elf.File) error {
+ if runtime.GOOS != "linux" {
+ return fmt.Errorf("embedded binary is a Linux ELF binary but runtime OS is %s", runtime.GOOS)
+ }
+
+ binaryArch := elfArch(f.Machine)
+ if binaryArch != runtime.GOARCH {
+ return archMismatchError(binaryArch)
+ }
+ return nil
+}
+
+func validatePE(f *pe.File) error {
+ if runtime.GOOS != "windows" {
+ return fmt.Errorf("embedded binary is a Windows PE binary but runtime OS is %s", runtime.GOOS)
+ }
+
+ binaryArch := peArch(f.FileHeader.Machine)
+ if binaryArch != runtime.GOARCH {
+ return archMismatchError(binaryArch)
+ }
+ return nil
+}
+
+func machoArch(cpu macho.Cpu) string {
+ switch cpu {
+ case macho.CpuAmd64:
+ return "amd64"
+ case macho.CpuArm64:
+ return "arm64"
+ default:
+ return fmt.Sprintf("unknown(0x%x)", cpu)
+ }
+}
+
+func elfArch(machine elf.Machine) string {
+ switch machine {
+ case elf.EM_X86_64:
+ return "amd64"
+ case elf.EM_AARCH64:
+ return "arm64"
+ default:
+ return fmt.Sprintf("unknown(0x%x)", machine)
+ }
+}
+
+func peArch(machine uint16) string {
+ switch machine {
+ case pe.IMAGE_FILE_MACHINE_AMD64:
+ return "amd64"
+ case pe.IMAGE_FILE_MACHINE_ARM64:
+ return "arm64"
+ default:
+ return fmt.Sprintf("unknown(0x%x)", machine)
+ }
+}
+
+func archMismatchError(binaryArch string) error {
+ return fmt.Errorf(
+ "architecture mismatch: embedded hooks binary is %s/%s but this CLI is %s/%s — "+
+ "this is a build error, please report it at https://github.com/asymptote-labs/agent-beacon/issues",
+ runtime.GOOS, binaryArch, runtime.GOOS, runtime.GOARCH,
+ )
+}
diff --git a/cli/beacon/internal/embedded/validate_test.go b/cli/beacon/internal/embedded/validate_test.go
new file mode 100644
index 00000000..eb10a9c3
--- /dev/null
+++ b/cli/beacon/internal/embedded/validate_test.go
@@ -0,0 +1,73 @@
+package embedded
+
+import (
+ "debug/elf"
+ "debug/macho"
+ "debug/pe"
+ "runtime"
+ "testing"
+)
+
+func TestValidateArchitecture_CurrentPlatform(t *testing.T) {
+ if !HasEmbeddedBinary() {
+ t.Skip("no real binary embedded (placeholder)")
+ }
+
+ err := ValidateArchitecture()
+ if err != nil {
+ t.Logf("ValidateArchitecture returned error (may be expected in dev): %v", err)
+ }
+}
+
+func TestMachoArch(t *testing.T) {
+ if got := machoArch(macho.CpuAmd64); got != "amd64" {
+ t.Errorf("machoArch(CpuAmd64) = %q, want %q", got, "amd64")
+ }
+ if got := machoArch(macho.CpuArm64); got != "arm64" {
+ t.Errorf("machoArch(CpuArm64) = %q, want %q", got, "arm64")
+ }
+}
+
+func TestElfArch(t *testing.T) {
+ if got := elfArch(elf.EM_X86_64); got != "amd64" {
+ t.Errorf("elfArch(EM_X86_64) = %q, want %q", got, "amd64")
+ }
+ if got := elfArch(elf.EM_AARCH64); got != "arm64" {
+ t.Errorf("elfArch(EM_AARCH64) = %q, want %q", got, "arm64")
+ }
+}
+
+func TestPeArch(t *testing.T) {
+ if got := peArch(pe.IMAGE_FILE_MACHINE_AMD64); got != "amd64" {
+ t.Errorf("peArch(AMD64) = %q, want %q", got, "amd64")
+ }
+ if got := peArch(pe.IMAGE_FILE_MACHINE_ARM64); got != "arm64" {
+ t.Errorf("peArch(ARM64) = %q, want %q", got, "arm64")
+ }
+}
+
+func TestArchMismatchError(t *testing.T) {
+ err := archMismatchError("amd64")
+ if err == nil {
+ t.Fatal("expected error")
+ }
+ msg := err.Error()
+ if got := runtime.GOOS; !containsStr(msg, got) {
+ t.Errorf("error message missing runtime OS %q: %s", got, msg)
+ }
+ if got := runtime.GOARCH; !containsStr(msg, got) {
+ t.Errorf("error message missing runtime GOARCH %q: %s", got, msg)
+ }
+ if !containsStr(msg, "architecture mismatch") {
+ t.Errorf("error message missing 'architecture mismatch': %s", msg)
+ }
+}
+
+func containsStr(s, substr string) bool {
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ return true
+ }
+ }
+ return false
+}
diff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.go
new file mode 100644
index 00000000..e8a061ad
--- /dev/null
+++ b/cli/beacon/internal/endpoint/collector/collector.go
@@ -0,0 +1,175 @@
+package collector
+
+import (
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+type Status struct {
+ BinaryPath string `json:"binary_path,omitempty"`
+ ConfigPath string `json:"config_path,omitempty"`
+ GRPCPort int `json:"grpc_port"`
+ HTTPPort int `json:"http_port"`
+ GRPCReady bool `json:"grpc_ready"`
+ HTTPReady bool `json:"http_ready"`
+ Message string `json:"message,omitempty"`
+}
+
+func DiscoverBinary(configured string) string {
+ if configured != "" {
+ if _, err := os.Stat(configured); err == nil {
+ return configured
+ }
+ }
+ if path, err := exec.LookPath("otelcol-contrib"); err == nil {
+ return path
+ }
+ if path, err := exec.LookPath("otelcol"); err == nil {
+ return path
+ }
+ return ""
+}
+
+func WriteConfig(cfg endpointconfig.Config) error {
+ if err := os.MkdirAll(filepath.Dir(cfg.Collector.ConfigPath), 0755); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(cfg.Collector.SpoolPath), 0755); err != nil {
+ return err
+ }
+ return os.WriteFile(cfg.Collector.ConfigPath, []byte(ConfigYAML(cfg)), 0644)
+}
+
+func ConfigYAML(cfg endpointconfig.Config) string {
+ return fmt.Sprintf(`receivers:
+ otlp:
+ protocols:
+ grpc:
+ endpoint: 127.0.0.1:%d
+ http:
+ endpoint: 127.0.0.1:%d
+
+processors:
+ memory_limiter:
+ check_interval: 1s
+ limit_mib: 128
+ batch:
+ timeout: 5s
+ send_batch_size: 128
+
+exporters:
+ beaconjson:
+ path: %q
+ max_event_bytes: 65536
+ rotate_bytes: 10485760
+ redact_secrets: true
+
+extensions:
+ health_check:
+ endpoint: 127.0.0.1:13133
+
+service:
+ extensions: [health_check]
+ pipelines:
+ logs:
+ receivers: [otlp]
+ processors: [memory_limiter, batch]
+ exporters: [beaconjson]
+ traces:
+ receivers: [otlp]
+ processors: [memory_limiter, batch]
+ exporters: [beaconjson]
+ metrics:
+ receivers: [otlp]
+ processors: [memory_limiter, batch]
+ exporters: [beaconjson]
+`, cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, cfg.LogPath)
+}
+
+func CheckStatus(cfg endpointconfig.Config) Status {
+ binary := DiscoverBinary(cfg.Collector.BinaryPath)
+ status := Status{
+ BinaryPath: binary,
+ ConfigPath: cfg.Collector.ConfigPath,
+ GRPCPort: cfg.Collector.GRPCPort,
+ HTTPPort: cfg.Collector.HTTPPort,
+ GRPCReady: portOpen(cfg.Collector.GRPCPort),
+ HTTPReady: portOpen(cfg.Collector.HTTPPort),
+ }
+ if binary == "" {
+ status.Message = "OpenTelemetry Collector binary was not found on PATH"
+ } else if !status.GRPCReady && !status.HTTPReady {
+ status.Message = "Collector ports are not listening"
+ }
+ return status
+}
+
+func PortAvailable(port int) bool {
+ ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
+ if err != nil {
+ return false
+ }
+ _ = ln.Close()
+ return true
+}
+
+func portOpen(port int) bool {
+ conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
+ if err != nil {
+ return false
+ }
+ _ = conn.Close()
+ return true
+}
+
+func LaunchAgentPlist(cfg endpointconfig.Config) string {
+ binary := DiscoverBinary(cfg.Collector.BinaryPath)
+ if binary == "" {
+ binary = "otelcol"
+ }
+ label := "com.beacon.endpoint.collector"
+ if cfg.UserMode {
+ label = "com.beacon.endpoint.collector.user"
+ }
+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>%s</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>%s</string>
+ <string>--config</string>
+ <string>%s</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+</dict>
+</plist>
+`, label, binary, cfg.Collector.ConfigPath)
+}
+
+func WriteLaunchPlist(cfg endpointconfig.Config) (string, error) {
+ var path string
+ if cfg.UserMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ path = filepath.Join(home, "Library", "LaunchAgents", "com.beacon.endpoint.collector.plist")
+ } else {
+ path = "/Library/LaunchDaemons/com.beacon.endpoint.collector.plist"
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ return path, os.WriteFile(path, []byte(LaunchAgentPlist(cfg)), 0644)
+}
diff --git a/cli/beacon/internal/endpoint/collector/collector_test.go b/cli/beacon/internal/endpoint/collector/collector_test.go
new file mode 100644
index 00000000..aacc0b9f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/collector/collector_test.go
@@ -0,0 +1,127 @@
+package collector
+
+import (
+ "net"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+func testConfig(t *testing.T) endpointconfig.Config {
+ t.Helper()
+ dir := t.TempDir()
+ return endpointconfig.Config{
+ UserMode: true,
+ LogPath: filepath.Join(dir, "logs", "runtime.jsonl"),
+ Collector: endpointconfig.Collector{
+ ConfigPath: filepath.Join(dir, "otelcol.yaml"),
+ GRPCPort: 14317,
+ HTTPPort: 14318,
+ SpoolPath: filepath.Join(dir, "spool", "otlp.jsonl"),
+ },
+ }
+}
+
+func TestConfigYAMLIncludesReleaseContractFields(t *testing.T) {
+ cfg := testConfig(t)
+
+ yaml := ConfigYAML(cfg)
+
+ for _, want := range []string{
+ "endpoint: 127.0.0.1:14317",
+ "endpoint: 127.0.0.1:14318",
+ "beaconjson:",
+ "path: " + `"` + cfg.LogPath + `"`,
+ "max_event_bytes: 65536",
+ "rotate_bytes: 10485760",
+ "redact_secrets: true",
+ "receivers: [otlp]",
+ "exporters: [beaconjson]",
+ } {
+ if !strings.Contains(yaml, want) {
+ t.Fatalf("ConfigYAML missing %q:\n%s", want, yaml)
+ }
+ }
+}
+
+func TestWriteConfigCreatesConfigAndSpoolDirectory(t *testing.T) {
+ cfg := testConfig(t)
+
+ if err := WriteConfig(cfg); err != nil {
+ t.Fatalf("WriteConfig returned error: %v", err)
+ }
+ if _, err := os.Stat(cfg.Collector.ConfigPath); err != nil {
+ t.Fatalf("collector config not written: %v", err)
+ }
+ if info, err := os.Stat(filepath.Dir(cfg.Collector.SpoolPath)); err != nil || !info.IsDir() {
+ t.Fatalf("spool dir not created: info=%v err=%v", info, err)
+ }
+}
+
+func TestDiscoverBinaryPrefersConfiguredExistingPath(t *testing.T) {
+ bin := filepath.Join(t.TempDir(), "collector")
+ if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0755); err != nil {
+ t.Fatalf("write fake collector: %v", err)
+ }
+
+ if got := DiscoverBinary(bin); got != bin {
+ t.Fatalf("DiscoverBinary = %q, want configured path %q", got, bin)
+ }
+}
+
+func TestPortAvailabilityAndOpenChecks(t *testing.T) {
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen: %v", err)
+ }
+ defer ln.Close()
+ port := ln.Addr().(*net.TCPAddr).Port
+
+ if PortAvailable(port) {
+ t.Fatalf("PortAvailable(%d) = true while listener is active", port)
+ }
+ if !portOpen(port) {
+ t.Fatalf("portOpen(%d) = false while listener is active", port)
+ }
+}
+
+func TestLaunchAgentPlistUsesFallbackBinaryAndUserLabel(t *testing.T) {
+ cfg := testConfig(t)
+ cfg.UserMode = true
+ cfg.Collector.BinaryPath = filepath.Join(t.TempDir(), "missing-otelcol")
+
+ plist := LaunchAgentPlist(cfg)
+
+ for _, want := range []string{
+ "<string>com.beacon.endpoint.collector.user</string>",
+ "<string>otelcol</string>",
+ "<string>--config</string>",
+ "<string>" + cfg.Collector.ConfigPath + "</string>",
+ } {
+ if !strings.Contains(plist, want) {
+ t.Fatalf("LaunchAgentPlist missing %q:\n%s", want, plist)
+ }
+ }
+}
+
+func TestWriteLaunchPlistUserMode(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("launch plist paths are POSIX-specific")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ cfg := testConfig(t)
+ cfg.UserMode = true
+
+ path, err := WriteLaunchPlist(cfg)
+ if err != nil {
+ t.Fatalf("WriteLaunchPlist returned error: %v", err)
+ }
+ if got, want := path, filepath.Join(home, "Library", "LaunchAgents", "com.beacon.endpoint.collector.plist"); got != want {
+ t.Fatalf("plist path = %q, want %q", got, want)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.go
new file mode 100644
index 00000000..6d65555f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/config/config.go
@@ -0,0 +1,92 @@
+package config
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+)
+
+const (
+ SystemConfigPath = "/Library/Application Support/Beacon/Endpoint/config.json"
+ UserConfigPath = ".beacon/endpoint/config.json"
+ DefaultGRPCPort = 4317
+ DefaultHTTPPort = 4318
+)
+
+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"`
+}
+
+type Collector struct {
+ BinaryPath string `json:"binary_path,omitempty"`
+ ConfigPath string `json:"config_path,omitempty"`
+ GRPCPort int `json:"grpc_port"`
+ HTTPPort int `json:"http_port"`
+ SpoolPath string `json:"spool_path,omitempty"`
+}
+
+func Default(userMode bool, logPath string) Config {
+ base := BaseDir(userMode)
+ return Config{
+ UserMode: userMode,
+ LogPath: logPath,
+ Harnesses: []string{"claude", "codex"},
+ Collector: Collector{
+ ConfigPath: filepath.Join(base, "otelcol.yaml"),
+ GRPCPort: DefaultGRPCPort,
+ HTTPPort: DefaultHTTPPort,
+ SpoolPath: filepath.Join(base, "spool", "otlp.jsonl"),
+ },
+ }
+}
+
+func BaseDir(userMode bool) string {
+ if userMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return filepath.Join(".", ".beacon", "endpoint")
+ }
+ return filepath.Join(home, ".beacon", "endpoint")
+ }
+ return "/Library/Application Support/Beacon/Endpoint"
+}
+
+func ConfigPath(userMode bool) string {
+ if userMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return filepath.Join(".", UserConfigPath)
+ }
+ return filepath.Join(home, UserConfigPath)
+ }
+ return SystemConfigPath
+}
+
+func Load(userMode bool) (Config, error) {
+ path := ConfigPath(userMode)
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return Config{}, err
+ }
+ var cfg Config
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return Config{}, err
+ }
+ return cfg, nil
+}
+
+func Save(cfg Config) (string, error) {
+ path := ConfigPath(cfg.UserMode)
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ data, err := json.MarshalIndent(cfg, "", " ")
+ if err != nil {
+ return "", err
+ }
+ return path, os.WriteFile(path, data, 0644)
+}
diff --git a/cli/beacon/internal/endpoint/config/config_test.go b/cli/beacon/internal/endpoint/config/config_test.go
new file mode 100644
index 00000000..bd8c4a6f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/config/config_test.go
@@ -0,0 +1,78 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestDefaultUserConfigUsesHomeScopedPaths(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ cfg := Default(true, filepath.Join(home, "runtime.jsonl"))
+
+ if !cfg.UserMode {
+ t.Fatal("expected user mode config")
+ }
+ if cfg.Collector.GRPCPort != DefaultGRPCPort || cfg.Collector.HTTPPort != DefaultHTTPPort {
+ t.Fatalf("unexpected ports: grpc=%d http=%d", cfg.Collector.GRPCPort, cfg.Collector.HTTPPort)
+ }
+ if got, want := cfg.Collector.ConfigPath, filepath.Join(home, ".beacon", "endpoint", "otelcol.yaml"); got != want {
+ t.Fatalf("ConfigPath = %q, want %q", got, want)
+ }
+ if got, want := cfg.Collector.SpoolPath, filepath.Join(home, ".beacon", "endpoint", "spool", "otlp.jsonl"); got != want {
+ t.Fatalf("SpoolPath = %q, want %q", got, want)
+ }
+ if len(cfg.Harnesses) != 2 || cfg.Harnesses[0] != "claude" || cfg.Harnesses[1] != "codex" {
+ t.Fatalf("unexpected default harnesses: %#v", cfg.Harnesses)
+ }
+}
+
+func TestSaveLoadRoundTrip(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ logPath := filepath.Join(home, "logs", "runtime.jsonl")
+
+ cfg := Default(true, logPath)
+ cfg.Collector.BinaryPath = filepath.Join(home, "bin", "otelcol")
+ cfg.EventCategories = []string{"tool", "session"}
+
+ path, err := Save(cfg)
+ if err != nil {
+ t.Fatalf("Save returned error: %v", err)
+ }
+ if got, want := path, filepath.Join(home, UserConfigPath); got != want {
+ t.Fatalf("Save path = %q, want %q", got, want)
+ }
+
+ loaded, err := Load(true)
+ if err != nil {
+ t.Fatalf("Load returned error: %v", err)
+ }
+ if loaded.LogPath != logPath {
+ t.Fatalf("LogPath = %q, want %q", loaded.LogPath, logPath)
+ }
+ if loaded.Collector.BinaryPath != cfg.Collector.BinaryPath {
+ t.Fatalf("BinaryPath = %q, want %q", loaded.Collector.BinaryPath, cfg.Collector.BinaryPath)
+ }
+ if len(loaded.EventCategories) != 2 || loaded.EventCategories[1] != "session" {
+ t.Fatalf("EventCategories did not round-trip: %#v", loaded.EventCategories)
+ }
+}
+
+func TestLoadRejectsCorruptJSON(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ path := filepath.Join(home, UserConfigPath)
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatalf("mkdir config dir: %v", err)
+ }
+ if err := os.WriteFile(path, []byte("{not json"), 0644); err != nil {
+ t.Fatalf("write corrupt config: %v", err)
+ }
+
+ if _, err := Load(true); err == nil {
+ t.Fatal("expected corrupt JSON error")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
new file mode 100644
index 00000000..9199f0a7
--- /dev/null
+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
@@ -0,0 +1,78 @@
+package diagnostics
+
+import (
+ "fmt"
+ "os"
+ "runtime"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+type Check struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Severity string `json:"severity"`
+ Message string `json:"message,omitempty"`
+}
+
+func Run(cfg endpointconfig.Config) []Check {
+ checks := []Check{
+ checkFile("config", endpointconfig.ConfigPath(cfg.UserMode), true),
+ checkFile("collector_config", cfg.Collector.ConfigPath, true),
+ checkFile("runtime_log", cfg.LogPath, false),
+ checkLogPermissions(cfg.LogPath),
+ }
+ if runtime.GOOS == "darwin" {
+ checks = append(checks, checkFile("launchd_plist", launchPlistPath(cfg.UserMode), true))
+ }
+ return checks
+}
+
+func HasFailures(checks []Check) bool {
+ for _, check := range checks {
+ if check.Status != "ok" {
+ return true
+ }
+ }
+ return false
+}
+
+func checkFile(name, path string, required bool) Check {
+ info, err := os.Stat(path)
+ if err != nil {
+ if os.IsNotExist(err) && !required {
+ return Check{Name: name, Status: "warn", Severity: "low", Message: fmt.Sprintf("%s does not exist yet", path)}
+ }
+ return Check{Name: name, Status: "fail", Severity: "medium", Message: err.Error()}
+ }
+ if info.IsDir() {
+ return Check{Name: name, Status: "fail", Severity: "medium", Message: path + " is a directory"}
+ }
+ return Check{Name: name, Status: "ok", Severity: "info", Message: path}
+}
+
+func checkLogPermissions(path string) Check {
+ info, err := os.Stat(path)
+ if err != nil {
+ return Check{Name: "runtime_log_permissions", Status: "warn", Severity: "low", Message: "runtime log not created yet"}
+ }
+ mode := info.Mode().Perm()
+ if mode&0022 != 0 {
+ return Check{Name: "runtime_log_permissions", Status: "fail", Severity: "high", Message: fmt.Sprintf("runtime log is group/world writable: %o", mode)}
+ }
+ if mode&0044 == 0 {
+ return Check{Name: "runtime_log_permissions", Status: "warn", Severity: "low", Message: fmt.Sprintf("runtime log may not be readable by Wazuh: %o", mode)}
+ }
+ return Check{Name: "runtime_log_permissions", Status: "ok", Severity: "info", Message: fmt.Sprintf("mode %o", mode)}
+}
+
+func launchPlistPath(userMode bool) string {
+ if userMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "Library/LaunchAgents/com.beacon.endpoint.collector.plist"
+ }
+ return home + "/Library/LaunchAgents/com.beacon.endpoint.collector.plist"
+ }
+ return "/Library/LaunchDaemons/com.beacon.endpoint.collector.plist"
+}
diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go
new file mode 100644
index 00000000..97559fcd
--- /dev/null
+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go
@@ -0,0 +1,101 @@
+package diagnostics
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+func TestCheckFileRequiredOptionalAndDirectory(t *testing.T) {
+ dir := t.TempDir()
+ missing := filepath.Join(dir, "missing")
+
+ if check := checkFile("required", missing, true); check.Status != "fail" || check.Severity != "medium" {
+ t.Fatalf("required missing check = %#v", check)
+ }
+ if check := checkFile("optional", missing, false); check.Status != "warn" || check.Severity != "low" {
+ t.Fatalf("optional missing check = %#v", check)
+ }
+ if check := checkFile("dir", dir, true); check.Status != "fail" || check.Severity != "medium" {
+ t.Fatalf("directory check = %#v", check)
+ }
+
+ file := filepath.Join(dir, "file")
+ if err := os.WriteFile(file, []byte("ok"), 0644); err != nil {
+ t.Fatalf("write file: %v", err)
+ }
+ if check := checkFile("file", file, true); check.Status != "ok" || check.Severity != "info" {
+ t.Fatalf("file check = %#v", check)
+ }
+}
+
+func TestCheckLogPermissions(t *testing.T) {
+ dir := t.TempDir()
+ logPath := filepath.Join(dir, "runtime.jsonl")
+
+ if check := checkLogPermissions(logPath); check.Status != "warn" || check.Severity != "low" {
+ t.Fatalf("missing log permissions check = %#v", check)
+ }
+
+ if err := os.WriteFile(logPath, []byte("{}\n"), 0644); err != nil {
+ t.Fatalf("write log: %v", err)
+ }
+ if check := checkLogPermissions(logPath); check.Status != "ok" {
+ t.Fatalf("0644 log permissions check = %#v", check)
+ }
+
+ if err := os.Chmod(logPath, 0666); err != nil {
+ t.Fatalf("chmod writable log: %v", err)
+ }
+ if check := checkLogPermissions(logPath); check.Status != "fail" || check.Severity != "high" {
+ t.Fatalf("0666 log permissions check = %#v", check)
+ }
+
+ if err := os.Chmod(logPath, 0200); err != nil {
+ t.Fatalf("chmod unreadable log: %v", err)
+ }
+ if check := checkLogPermissions(logPath); check.Status != "warn" || check.Severity != "low" {
+ t.Fatalf("0200 log permissions check = %#v", check)
+ }
+}
+
+func TestRunAndHasFailures(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ cfg := endpointconfig.Default(true, filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl"))
+ if _, err := endpointconfig.Save(cfg); err != nil {
+ t.Fatalf("save config: %v", err)
+ }
+ if err := os.MkdirAll(filepath.Dir(cfg.Collector.ConfigPath), 0755); err != nil {
+ t.Fatalf("mkdir collector dir: %v", err)
+ }
+ if err := os.WriteFile(cfg.Collector.ConfigPath, []byte("receivers: {}\n"), 0644); err != nil {
+ t.Fatalf("write collector config: %v", err)
+ }
+ if err := os.MkdirAll(filepath.Dir(cfg.LogPath), 0755); err != nil {
+ t.Fatalf("mkdir log dir: %v", err)
+ }
+ if err := os.WriteFile(cfg.LogPath, []byte("{}\n"), 0644); err != nil {
+ t.Fatalf("write log: %v", err)
+ }
+ if runtime.GOOS == "darwin" {
+ plistPath := launchPlistPath(true)
+ if err := os.MkdirAll(filepath.Dir(plistPath), 0755); err != nil {
+ t.Fatalf("mkdir plist dir: %v", err)
+ }
+ if err := os.WriteFile(plistPath, []byte("<plist/>"), 0644); err != nil {
+ t.Fatalf("write plist: %v", err)
+ }
+ }
+
+ checks := Run(cfg)
+ if HasFailures(checks) {
+ t.Fatalf("expected no failures, got %#v", checks)
+ }
+ if !HasFailures([]Check{{Name: "x", Status: "fail"}}) {
+ t.Fatal("expected HasFailures to report failed check")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.go
new file mode 100644
index 00000000..979cdb08
--- /dev/null
+++ b/cli/beacon/internal/endpoint/harness/harness.go
@@ -0,0 +1,344 @@
+package harness
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+type TelemetryStatus string
+
+const (
+ TelemetryEnabled TelemetryStatus = "enabled"
+ TelemetryDisabled TelemetryStatus = "disabled"
+ TelemetryMissing TelemetryStatus = "missing"
+ TelemetryMisconfigured TelemetryStatus = "misconfigured"
+)
+
+type Harness struct {
+ Name string `json:"name"`
+ DisplayName string `json:"display_name"`
+ Detected bool `json:"detected"`
+ Version string `json:"version,omitempty"`
+ ExecutablePath string `json:"executable_path,omitempty"`
+ ConfigPath string `json:"config_path,omitempty"`
+ TelemetryStatus TelemetryStatus `json:"telemetry_status"`
+ Capability string `json:"capability,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+type ConfigureOptions struct {
+ Endpoint string
+ UserMode bool
+}
+
+type ValidationResult struct {
+ Harness string `json:"harness"`
+ Status TelemetryStatus `json:"status"`
+ Message string `json:"message"`
+}
+
+func DiscoverAll() []Harness {
+ return []Harness{
+ DiscoverClaude(),
+ DiscoverCodex(),
+ DiscoverCursor(),
+ DiscoverClaudeCowork(),
+ }
+}
+
+func DiscoverClaude() Harness {
+ h := Harness{Name: "claude_code", DisplayName: "Claude Code", Capability: "otel_env"}
+ path, err := exec.LookPath("claude")
+ if err == nil {
+ h.Detected = true
+ h.ExecutablePath = path
+ h.Version = commandVersion(path)
+ }
+ home, _ := os.UserHomeDir()
+ userConfig := filepath.Join(home, ".claude", "settings.json")
+ managedConfig := "/Library/Application Support/ClaudeCode/managed-settings.json"
+ if fileExists(managedConfig) {
+ h.ConfigPath = managedConfig
+ status, msg := claudeStatus(managedConfig)
+ h.TelemetryStatus = status
+ h.Message = msg
+ } else if fileExists(userConfig) {
+ h.ConfigPath = userConfig
+ status, msg := claudeStatus(userConfig)
+ h.TelemetryStatus = status
+ h.Message = msg
+ } else {
+ h.ConfigPath = userConfig
+ h.TelemetryStatus = TelemetryMissing
+ h.Message = "Claude settings file was not found"
+ }
+ if !h.Detected && dirExists(filepath.Join(home, ".claude")) {
+ h.Detected = true
+ }
+ return h
+}
+
+func DiscoverCodex() Harness {
+ h := Harness{Name: "codex_cli", DisplayName: "Codex CLI", Capability: "otel_config"}
+ path, err := exec.LookPath("codex")
+ if err == nil {
+ h.Detected = true
+ h.ExecutablePath = path
+ h.Version = commandVersion(path)
+ }
+ home, _ := os.UserHomeDir()
+ h.ConfigPath = filepath.Join(home, ".codex", "config.toml")
+ if fileExists(h.ConfigPath) {
+ status, msg := codexStatus(h.ConfigPath)
+ h.TelemetryStatus = status
+ h.Message = msg
+ } else {
+ h.TelemetryStatus = TelemetryMissing
+ h.Message = "Codex config file was not found"
+ }
+ if !h.Detected && dirExists(filepath.Join(home, ".codex")) {
+ h.Detected = true
+ }
+ return h
+}
+
+func DiscoverCursor() Harness {
+ h := Harness{Name: "cursor", DisplayName: "Cursor", Capability: "hooks"}
+ path, err := exec.LookPath("cursor")
+ if err == nil {
+ h.Detected = true
+ h.ExecutablePath = path
+ h.Version = commandVersion(path)
+ }
+ home, _ := os.UserHomeDir()
+ h.ConfigPath = filepath.Join(home, ".cursor", "hooks.json")
+ if !h.Detected && dirExists(filepath.Join(home, ".cursor")) {
+ h.Detected = true
+ }
+ if fileExists(h.ConfigPath) {
+ data, _ := os.ReadFile(h.ConfigPath)
+ if strings.Contains(string(data), "BEACON_ENDPOINT_MODE=1") {
+ h.TelemetryStatus = TelemetryEnabled
+ h.Message = "Cursor endpoint hooks are configured"
+ } else {
+ h.TelemetryStatus = TelemetryDisabled
+ h.Message = "Cursor hooks exist but endpoint hooks were not found"
+ }
+ } else {
+ h.TelemetryStatus = TelemetryMissing
+ h.Message = "Cursor hooks.json was not found"
+ }
+ return h
+}
+
+func DiscoverClaudeCowork() Harness {
+ h := Harness{Name: "claude_cowork", DisplayName: "Claude Cowork", Capability: "admin_otel"}
+ if fileExists("/Applications/Claude.app/Contents/Info.plist") {
+ h.Detected = true
+ h.ExecutablePath = "/Applications/Claude.app"
+ }
+ h.TelemetryStatus = TelemetryMissing
+ h.Message = "Claude Cowork telemetry is configured in Claude organization settings"
+ return h
+}
+
+func ConfigureClaude(opts ConfigureOptions) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ path := filepath.Join(home, ".claude", "settings.json")
+ settings := map[string]interface{}{}
+ if data, err := os.ReadFile(path); err == nil {
+ _ = json.Unmarshal(data, &settings)
+ if err := backup(path, data); err != nil {
+ return "", err
+ }
+ }
+ env, _ := settings["env"].(map[string]interface{})
+ if env == nil {
+ env = map[string]interface{}{}
+ }
+ env["CLAUDE_CODE_ENABLE_TELEMETRY"] = "1"
+ env["OTEL_LOGS_EXPORTER"] = "otlp"
+ env["OTEL_METRICS_EXPORTER"] = "otlp"
+ env["OTEL_EXPORTER_OTLP_PROTOCOL"] = "grpc"
+ env["OTEL_EXPORTER_OTLP_ENDPOINT"] = opts.Endpoint
+ settings["env"] = env
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ data, err := json.MarshalIndent(settings, "", " ")
+ if err != nil {
+ return "", err
+ }
+ return path, os.WriteFile(path, data, 0600)
+}
+
+func ConfigureCodex(opts ConfigureOptions) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ path := filepath.Join(home, ".codex", "config.toml")
+ var existing string
+ if data, err := os.ReadFile(path); err == nil {
+ existing = string(data)
+ if err := backup(path, data); err != nil {
+ return "", err
+ }
+ }
+ updated := mergeCodexOTEL(existing, opts.Endpoint)
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ return path, os.WriteFile(path, []byte(updated), 0600)
+}
+
+func ValidateConfigured(endpoint string) []ValidationResult {
+ claude := DiscoverClaude()
+ codex := DiscoverCodex()
+ return []ValidationResult{
+ {
+ Harness: claude.Name,
+ Status: claude.TelemetryStatus,
+ Message: validateEndpointMessage(claude.TelemetryStatus, claude.Message, endpoint),
+ },
+ {
+ Harness: codex.Name,
+ Status: codex.TelemetryStatus,
+ Message: validateEndpointMessage(codex.TelemetryStatus, codex.Message, endpoint),
+ },
+ }
+}
+
+func mergeCodexOTEL(existing, endpoint string) string {
+ lines := strings.Split(existing, "\n")
+ var out []string
+ inOTEL := false
+ wroteOTEL := false
+ for _, line := range lines {
+ trim := strings.TrimSpace(line)
+ if strings.HasPrefix(trim, "[") && strings.HasSuffix(trim, "]") {
+ if inOTEL && !wroteOTEL {
+ out = append(out, codexOTELBlock(endpoint)...)
+ wroteOTEL = true
+ }
+ inOTEL = trim == "[otel]"
+ if !inOTEL {
+ out = append(out, line)
+ }
+ continue
+ }
+ if inOTEL {
+ continue
+ }
+ out = append(out, line)
+ }
+ if inOTEL && !wroteOTEL {
+ out = append(out, codexOTELBlock(endpoint)...)
+ wroteOTEL = true
+ }
+ if !wroteOTEL {
+ if strings.TrimSpace(existing) != "" {
+ out = append(out, "")
+ }
+ out = append(out, codexOTELBlock(endpoint)...)
+ }
+ return strings.TrimRight(strings.Join(out, "\n"), "\n") + "\n"
+}
+
+func codexOTELBlock(endpoint string) []string {
+ return []string{
+ "[otel]",
+ "enabled = true",
+ fmt.Sprintf("endpoint = %q", endpoint),
+ "service_name = \"codex-cli\"",
+ "sampling_ratio = 1.0",
+ }
+}
+
+func claudeStatus(path string) (TelemetryStatus, string) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return TelemetryMissing, err.Error()
+ }
+ var settings map[string]interface{}
+ if err := json.Unmarshal(data, &settings); err != nil {
+ return TelemetryMisconfigured, "Claude settings JSON is invalid"
+ }
+ env, _ := settings["env"].(map[string]interface{})
+ if env == nil {
+ return TelemetryDisabled, "Claude telemetry env is missing"
+ }
+ if fmt.Sprint(env["CLAUDE_CODE_ENABLE_TELEMETRY"]) != "1" {
+ return TelemetryDisabled, "CLAUDE_CODE_ENABLE_TELEMETRY is not enabled"
+ }
+ if !strings.Contains(fmt.Sprint(env["OTEL_EXPORTER_OTLP_ENDPOINT"]), "127.0.0.1") &&
+ !strings.Contains(fmt.Sprint(env["OTEL_EXPORTER_OTLP_ENDPOINT"]), "localhost") {
+ return TelemetryMisconfigured, "OTLP endpoint does not point to localhost"
+ }
+ return TelemetryEnabled, "Claude telemetry is configured for local OTLP"
+}
+
+func codexStatus(path string) (TelemetryStatus, string) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return TelemetryMissing, err.Error()
+ }
+ text := string(data)
+ if !strings.Contains(text, "[otel]") {
+ return TelemetryDisabled, "Codex [otel] config is missing"
+ }
+ if !strings.Contains(text, "enabled = true") {
+ return TelemetryDisabled, "Codex OTEL is not enabled"
+ }
+ if !strings.Contains(text, "127.0.0.1") && !strings.Contains(text, "localhost") {
+ return TelemetryMisconfigured, "Codex OTLP endpoint does not point to localhost"
+ }
+ return TelemetryEnabled, "Codex telemetry is configured for local OTLP"
+}
+
+func commandVersion(path string) string {
+ cmd := exec.Command(path, "--version")
+ timer := time.AfterFunc(2*time.Second, func() { _ = cmd.Process.Kill() })
+ out, err := cmd.CombinedOutput()
+ timer.Stop()
+ if err != nil {
+ return "unknown"
+ }
+ return strings.TrimSpace(string(out))
+}
+
+func backup(path string, data []byte) error {
+ if len(data) == 0 {
+ return nil
+ }
+ backupPath := fmt.Sprintf("%s.beacon.%s.bak", path, time.Now().UTC().Format("20060102T150405Z"))
+ return os.WriteFile(backupPath, data, 0600)
+}
+
+func validateEndpointMessage(status TelemetryStatus, msg, endpoint string) string {
+ if status != TelemetryEnabled {
+ return msg
+ }
+ if endpoint != "" && !strings.Contains(msg, "local OTLP") {
+ return "telemetry enabled but endpoint could not be fully validated"
+ }
+ return msg
+}
+
+func fileExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && !info.IsDir()
+}
+
+func dirExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && info.IsDir()
+}
diff --git a/cli/beacon/internal/endpoint/harness/harness_test.go b/cli/beacon/internal/endpoint/harness/harness_test.go
new file mode 100644
index 00000000..a196114b
--- /dev/null
+++ b/cli/beacon/internal/endpoint/harness/harness_test.go
@@ -0,0 +1,180 @@
+package harness
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestMergeCodexOTELAddsBlock(t *testing.T) {
+ got := mergeCodexOTEL("model = \"gpt-5\"\n", "http://127.0.0.1:4317")
+ if !strings.Contains(got, "[otel]") {
+ t.Fatalf("expected otel block: %s", got)
+ }
+ if !strings.Contains(got, "endpoint = \"http://127.0.0.1:4317\"") {
+ t.Fatalf("expected endpoint: %s", got)
+ }
+ if !strings.Contains(got, "model = \"gpt-5\"") {
+ t.Fatalf("expected existing config to be preserved: %s", got)
+ }
+}
+
+func TestMergeCodexOTELReplacesExistingBlock(t *testing.T) {
+ input := "[otel]\nenabled = false\nendpoint = \"https://example.com\"\n\n[profile]\nname = \"default\"\n"
+ got := mergeCodexOTEL(input, "http://127.0.0.1:4317")
+ if strings.Contains(got, "https://example.com") || strings.Contains(got, "enabled = false") {
+ t.Fatalf("old otel config was not replaced: %s", got)
+ }
+ if !strings.Contains(got, "[profile]\nname = \"default\"") {
+ t.Fatalf("following section was not preserved: %s", got)
+ }
+}
+
+func TestConfigureClaudeWritesTelemetryEnvAndBackup(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ path := filepath.Join(home, ".claude", "settings.json")
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatalf("mkdir claude config dir: %v", err)
+ }
+ if err := os.WriteFile(path, []byte(`{"env":{"EXISTING":"1"}}`), 0600); err != nil {
+ t.Fatalf("write existing claude config: %v", err)
+ }
+
+ written, err := ConfigureClaude(ConfigureOptions{Endpoint: "http://127.0.0.1:4317", UserMode: true})
+ if err != nil {
+ t.Fatalf("ConfigureClaude returned error: %v", err)
+ }
+ if written != path {
+ t.Fatalf("ConfigureClaude path = %q, want %q", written, path)
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read claude config: %v", err)
+ }
+ var settings map[string]map[string]string
+ if err := json.Unmarshal(data, &settings); err != nil {
+ t.Fatalf("unmarshal claude config: %v", err)
+ }
+ env := settings["env"]
+ for key, want := range map[string]string{
+ "EXISTING": "1",
+ "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
+ "OTEL_LOGS_EXPORTER": "otlp",
+ "OTEL_METRICS_EXPORTER": "otlp",
+ "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
+ "OTEL_EXPORTER_OTLP_ENDPOINT": "http://127.0.0.1:4317",
+ } {
+ if got := env[key]; got != want {
+ t.Fatalf("env[%s] = %q, want %q; env=%#v", key, got, want, env)
+ }
+ }
+ backups, err := filepath.Glob(path + ".beacon.*.bak")
+ if err != nil {
+ t.Fatalf("glob backups: %v", err)
+ }
+ if len(backups) != 1 {
+ t.Fatalf("expected one backup, got %#v", backups)
+ }
+}
+
+func TestClaudeStatusVariants(t *testing.T) {
+ dir := t.TempDir()
+ tests := []struct {
+ name string
+ body string
+ status TelemetryStatus
+ }{
+ {name: "invalid json", body: `{`, status: TelemetryMisconfigured},
+ {name: "missing env", body: `{}`, status: TelemetryDisabled},
+ {name: "disabled", body: `{"env":{"CLAUDE_CODE_ENABLE_TELEMETRY":"0"}}`, status: TelemetryDisabled},
+ {name: "remote endpoint", body: `{"env":{"CLAUDE_CODE_ENABLE_TELEMETRY":"1","OTEL_EXPORTER_OTLP_ENDPOINT":"https://example.com"}}`, status: TelemetryMisconfigured},
+ {name: "enabled", body: `{"env":{"CLAUDE_CODE_ENABLE_TELEMETRY":"1","OTEL_EXPORTER_OTLP_ENDPOINT":"http://127.0.0.1:4317"}}`, status: TelemetryEnabled},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ path := filepath.Join(dir, strings.ReplaceAll(tt.name, " ", "_")+".json")
+ if err := os.WriteFile(path, []byte(tt.body), 0600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ status, _ := claudeStatus(path)
+ if status != tt.status {
+ t.Fatalf("claudeStatus = %q, want %q", status, tt.status)
+ }
+ })
+ }
+}
+
+func TestConfigureCodexWritesTelemetryBlockAndBackup(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ path := filepath.Join(home, ".codex", "config.toml")
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatalf("mkdir codex config dir: %v", err)
+ }
+ if err := os.WriteFile(path, []byte("model = \"gpt-5\"\n"), 0600); err != nil {
+ t.Fatalf("write existing codex config: %v", err)
+ }
+
+ written, err := ConfigureCodex(ConfigureOptions{Endpoint: "http://127.0.0.1:4317", UserMode: true})
+ if err != nil {
+ t.Fatalf("ConfigureCodex returned error: %v", err)
+ }
+ if written != path {
+ t.Fatalf("ConfigureCodex path = %q, want %q", written, path)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read codex config: %v", err)
+ }
+ text := string(data)
+ for _, want := range []string{
+ "model = \"gpt-5\"",
+ "[otel]",
+ "enabled = true",
+ "endpoint = \"http://127.0.0.1:4317\"",
+ "service_name = \"codex-cli\"",
+ } {
+ if !strings.Contains(text, want) {
+ t.Fatalf("codex config missing %q:\n%s", want, text)
+ }
+ }
+ backups, err := filepath.Glob(path + ".beacon.*.bak")
+ if err != nil {
+ t.Fatalf("glob backups: %v", err)
+ }
+ if len(backups) != 1 {
+ t.Fatalf("expected one backup, got %#v", backups)
+ }
+}
+
+func TestCodexStatusVariants(t *testing.T) {
+ dir := t.TempDir()
+ tests := []struct {
+ name string
+ body string
+ status TelemetryStatus
+ }{
+ {name: "missing block", body: `model = "gpt-5"`, status: TelemetryDisabled},
+ {name: "disabled", body: "[otel]\nenabled = false\nendpoint = \"http://127.0.0.1:4317\"\n", status: TelemetryDisabled},
+ {name: "remote endpoint", body: "[otel]\nenabled = true\nendpoint = \"https://example.com\"\n", status: TelemetryMisconfigured},
+ {name: "enabled", body: "[otel]\nenabled = true\nendpoint = \"http://localhost:4317\"\n", status: TelemetryEnabled},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ path := filepath.Join(dir, strings.ReplaceAll(tt.name, " ", "_")+".toml")
+ if err := os.WriteFile(path, []byte(tt.body), 0600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ status, _ := codexStatus(path)
+ if status != tt.status {
+ t.Fatalf("codexStatus = %q, want %q", status, tt.status)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/cursor.go b/cli/beacon/internal/endpoint/hooks/cursor.go
new file mode 100644
index 00000000..8c6b5347
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/cursor.go
@@ -0,0 +1,263 @@
+package hooks
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/embedded"
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+type Level string
+
+const (
+ LevelUser Level = "user"
+ LevelProject Level = "project"
+)
+
+type HookRef struct {
+ Command string `json:"command"`
+ Matcher string `json:"matcher,omitempty"`
+ Timeout int `json:"timeout,omitempty"`
+}
+
+type HooksJSON struct {
+ Version int `json:"version"`
+ Hooks map[string][]HookRef `json:"hooks"`
+}
+
+type CursorOptions struct {
+ Level Level
+ LogPath string
+ UserMode bool
+}
+
+type CursorStatus struct {
+ Installed bool `json:"installed"`
+ BinaryPath string `json:"binary_path,omitempty"`
+ HooksJSONPath string `json:"hooks_json_path,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+func InstallCursor(opts CursorOptions) (CursorStatus, error) {
+ if !embedded.HasEmbeddedBinary() {
+ return CursorStatus{}, fmt.Errorf("no hooks binary embedded")
+ }
+ if opts.LogPath == "" {
+ opts.LogPath = defaultLogPath(opts.UserMode)
+ }
+ binaryPath, err := writeEndpointHookBinary(opts.UserMode)
+ if err != nil {
+ return CursorStatus{}, err
+ }
+ targetDir, err := cursorTargetDir(opts.Level)
+ if err != nil {
+ return CursorStatus{}, err
+ }
+ if err := os.MkdirAll(targetDir, 0755); err != nil {
+ return CursorStatus{}, err
+ }
+ hooksPath := filepath.Join(targetDir, "hooks.json")
+ if err := installCursorHooksJSON(hooksPath, binaryPath, opts.LogPath); err != nil {
+ return CursorStatus{}, err
+ }
+ return CursorStatus{Installed: true, BinaryPath: binaryPath, HooksJSONPath: hooksPath, Message: "Cursor endpoint hooks installed"}, nil
+}
+
+func UninstallCursor(opts CursorOptions) (CursorStatus, error) {
+ targetDir, err := cursorTargetDir(opts.Level)
+ if err != nil {
+ return CursorStatus{}, err
+ }
+ hooksPath := filepath.Join(targetDir, "hooks.json")
+ updated, err := removeEndpointHooks(hooksPath)
+ if err != nil {
+ return CursorStatus{}, err
+ }
+ status := CursorStatus{HooksJSONPath: hooksPath, Message: "Cursor endpoint hooks were not present"}
+ if updated {
+ status.Message = "Cursor endpoint hooks removed"
+ }
+ status.Installed = IsCursorInstalled(opts)
+ return status, nil
+}
+
+func CursorHookStatus(opts CursorOptions) CursorStatus {
+ targetDir, err := cursorTargetDir(opts.Level)
+ if err != nil {
+ return CursorStatus{Message: err.Error()}
+ }
+ hooksPath := filepath.Join(targetDir, "hooks.json")
+ status := CursorStatus{HooksJSONPath: hooksPath}
+ status.Installed = IsCursorInstalled(opts)
+ if status.Installed {
+ status.Message = "Cursor endpoint hooks are installed"
+ } else {
+ status.Message = "Cursor endpoint hooks are not installed"
+ }
+ if path, err := endpointHookBinaryPath(opts.UserMode); err == nil {
+ status.BinaryPath = path
+ }
+ return status
+}
+
+func IsCursorInstalled(opts CursorOptions) bool {
+ targetDir, err := cursorTargetDir(opts.Level)
+ if err != nil {
+ return false
+ }
+ data, err := os.ReadFile(filepath.Join(targetDir, "hooks.json"))
+ if err != nil {
+ return false
+ }
+ return strings.Contains(string(data), "BEACON_ENDPOINT_MODE=1") && strings.Contains(string(data), "beacon-hooks")
+}
+
+func installCursorHooksJSON(path, binaryPath, logPath string) error {
+ hooksJSON, err := readHooksJSON(path)
+ if err != nil {
+ return err
+ }
+ commandPrefix := fmt.Sprintf("BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG=%s %s --platform cursor", shellQuote(logPath), shellQuote(binaryPath))
+ endpointHooks := map[string]HookRef{
+ "sessionStart": {Command: commandPrefix + " session-start"},
+ "beforeSubmitPrompt": {Command: commandPrefix + " prompt-submit", Timeout: 30},
+ "preToolUse": {Command: commandPrefix + " pre-tool", Matcher: "Write|Edit|MultiEdit|Shell|MCP"},
+ "afterFileEdit": {Command: commandPrefix + " post-tool"},
+ "postToolUse": {Command: commandPrefix + " post-tool"},
+ "postToolUseFailure": {Command: commandPrefix + " post-tool"},
+ "stop": {Command: commandPrefix + " stop"},
+ "sessionEnd": {Command: commandPrefix + " session-end"},
+ }
+ for hookName, ref := range endpointHooks {
+ hooksJSON.Hooks[hookName] = mergeEndpointHook(hooksJSON.Hooks[hookName], ref)
+ }
+ data, err := json.MarshalIndent(hooksJSON, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, data, 0644)
+}
+
+func readHooksJSON(path string) (HooksJSON, error) {
+ var hooksJSON HooksJSON
+ data, err := os.ReadFile(path)
+ if err == nil {
+ _ = json.Unmarshal(data, &hooksJSON)
+ }
+ if hooksJSON.Version == 0 {
+ hooksJSON.Version = 1
+ }
+ if hooksJSON.Hooks == nil {
+ hooksJSON.Hooks = map[string][]HookRef{}
+ }
+ return hooksJSON, nil
+}
+
+func mergeEndpointHook(existing []HookRef, ref HookRef) []HookRef {
+ out := make([]HookRef, 0, len(existing)+1)
+ for _, item := range existing {
+ if !isEndpointHook(item.Command) {
+ out = append(out, item)
+ }
+ }
+ return append(out, ref)
+}
+
+func removeEndpointHooks(path string) (bool, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ var hooksJSON HooksJSON
+ if err := json.Unmarshal(data, &hooksJSON); err != nil {
+ return false, err
+ }
+ changed := false
+ for hookName, refs := range hooksJSON.Hooks {
+ filtered := refs[:0]
+ for _, ref := range refs {
+ if isEndpointHook(ref.Command) {
+ changed = true
+ continue
+ }
+ filtered = append(filtered, ref)
+ }
+ if len(filtered) == 0 {
+ delete(hooksJSON.Hooks, hookName)
+ } else {
+ hooksJSON.Hooks[hookName] = filtered
+ }
+ }
+ if !changed {
+ return false, nil
+ }
+ if len(hooksJSON.Hooks) == 0 {
+ return true, os.Remove(path)
+ }
+ out, err := json.MarshalIndent(hooksJSON, "", " ")
+ if err != nil {
+ return false, err
+ }
+ return true, os.WriteFile(path, out, 0644)
+}
+
+func isEndpointHook(command string) bool {
+ return strings.Contains(command, "BEACON_ENDPOINT_MODE=1") || strings.Contains(command, "beacon-hooks")
+}
+
+func writeEndpointHookBinary(userMode bool) (string, error) {
+ path, err := endpointHookBinaryPath(userMode)
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ _ = os.Remove(path)
+ return path, os.WriteFile(path, embedded.HooksBinary, 0755)
+}
+
+func endpointHookBinaryPath(userMode bool) (string, error) {
+ base := endpointconfig.BaseDir(userMode)
+ return filepath.Join(base, "hooks", embedded.GetBinaryName()), nil
+}
+
+func cursorTargetDir(level Level) (string, error) {
+ switch level {
+ case "", LevelUser:
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".cursor"), nil
+ case LevelProject:
+ cwd, err := os.Getwd()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(cwd, ".cursor"), nil
+ default:
+ return "", fmt.Errorf("unknown hook level %q", level)
+ }
+}
+
+func defaultLogPath(userMode bool) string {
+ if userMode {
+ home, err := os.UserHomeDir()
+ if err == nil {
+ return filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
+ }
+ }
+ return "/var/log/beacon-agent/runtime.jsonl"
+}
+
+func shellQuote(value string) string {
+ return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
+}
diff --git a/cli/beacon/internal/endpoint/hooks/cursor_test.go b/cli/beacon/internal/endpoint/hooks/cursor_test.go
new file mode 100644
index 00000000..2946589f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/cursor_test.go
@@ -0,0 +1,146 @@
+package hooks
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestInstallCursorHooksJSONPreservesNonBeaconHooks(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"sessionStart":[{"command":"echo keep"}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl"); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(data)
+ if !strings.Contains(text, "echo keep") {
+ t.Fatalf("non-Beacon hook was not preserved: %s", text)
+ }
+ if !strings.Contains(text, "BEACON_ENDPOINT_MODE=1") {
+ t.Fatalf("endpoint env was not added: %s", text)
+ }
+ if !strings.Contains(text, "BEACON_ENDPOINT_LOG='/tmp/runtime.jsonl'") {
+ t.Fatalf("endpoint log env was not added: %s", text)
+ }
+}
+
+func TestRemoveEndpointHooksPreservesOtherHooks(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"sessionStart":[{"command":"echo keep"},{"command":"BEACON_ENDPOINT_MODE=1 beacon-hooks session-start"}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0644); err != nil {
+ t.Fatal(err)
+ }
+ changed, err := removeEndpointHooks(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed {
+ t.Fatal("expected endpoint hook removal")
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(data)
+ if !strings.Contains(text, "echo keep") {
+ t.Fatalf("non-Beacon hook was not preserved: %s", text)
+ }
+ if strings.Contains(text, "BEACON_ENDPOINT_MODE") {
+ t.Fatalf("endpoint hook was not removed: %s", text)
+ }
+}
+
+func TestCursorTargetDirProjectLevel(t *testing.T) {
+ dir := t.TempDir()
+ t.Chdir(dir)
+
+ target, err := cursorTargetDir(LevelProject)
+ if err != nil {
+ t.Fatalf("cursorTargetDir returned error: %v", err)
+ }
+ if got, want := target, filepath.Join(dir, ".cursor"); got != want {
+ t.Fatalf("project target dir = %q, want %q", got, want)
+ }
+}
+
+func TestReadHooksJSONTreatsCorruptJSONAsEmptyConfig(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ if err := os.WriteFile(path, []byte("{not json"), 0644); err != nil {
+ t.Fatalf("write corrupt hooks.json: %v", err)
+ }
+
+ hooksJSON, err := readHooksJSON(path)
+ if err != nil {
+ t.Fatalf("readHooksJSON returned error: %v", err)
+ }
+ if hooksJSON.Version != 1 {
+ t.Fatalf("Version = %d, want 1", hooksJSON.Version)
+ }
+ if len(hooksJSON.Hooks) != 0 {
+ t.Fatalf("Hooks = %#v, want empty map", hooksJSON.Hooks)
+ }
+}
+
+func TestRemoveEndpointHooksDeletesFileWhenOnlyBeaconHooksRemain(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"sessionStart":[{"command":"BEACON_ENDPOINT_MODE=1 beacon-hooks session-start"}],"stop":[{"command":"beacon-hooks stop"}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ changed, err := removeEndpointHooks(path)
+ if err != nil {
+ t.Fatalf("removeEndpointHooks returned error: %v", err)
+ }
+ if !changed {
+ t.Fatal("expected endpoint hook removal")
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("hooks.json still exists or unexpected error: %v", err)
+ }
+}
+
+func TestInstallCursorHooksJSONReplacesExistingBeaconHook(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"preToolUse":[{"command":"BEACON_ENDPOINT_MODE=1 old-beacon-hooks pre-tool"},{"command":"echo keep"}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := installCursorHooksJSON(path, "/tmp/new beacon-hooks", "/tmp/runtime's.jsonl"); err != nil {
+ t.Fatalf("installCursorHooksJSON returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read hooks.json: %v", err)
+ }
+ if strings.Contains(string(data), "old-beacon-hooks") {
+ t.Fatalf("old endpoint hook was not replaced: %s", string(data))
+ }
+ if !strings.Contains(string(data), "echo keep") {
+ t.Fatalf("non-endpoint hook was not preserved: %s", string(data))
+ }
+ if !strings.Contains(string(data), "'/tmp/new beacon-hooks'") || !strings.Contains(string(data), "BEACON_ENDPOINT_LOG=") || !strings.Contains(string(data), "runtime") {
+ t.Fatalf("command values were not shell-quoted: %s", string(data))
+ }
+}
+
+func TestInstallCursorWithUnknownLevelFailsBeforeWritingTarget(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ status, err := InstallCursor(CursorOptions{Level: Level("workspace"), UserMode: true})
+ if err == nil {
+ t.Fatal("expected unknown hook level error")
+ }
+ if status.Installed {
+ t.Fatalf("status should not be installed on error: %#v", status)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/integrations/cowork/cowork.go b/cli/beacon/internal/endpoint/integrations/cowork/cowork.go
new file mode 100644
index 00000000..f1354ecb
--- /dev/null
+++ b/cli/beacon/internal/endpoint/integrations/cowork/cowork.go
@@ -0,0 +1,126 @@
+package cowork
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+const (
+ Name = "claude_cowork"
+ DisplayName = "Claude Cowork"
+ MinVersion = "1.1.4173"
+)
+
+type Config struct {
+ Endpoint string `json:"endpoint"`
+ Protocol string `json:"protocol"`
+ Headers string `json:"headers,omitempty"`
+}
+
+type Status struct {
+ Name string `json:"name"`
+ DisplayName string `json:"display_name"`
+ Detected bool `json:"detected"`
+ DesktopPath string `json:"desktop_path,omitempty"`
+ MinimumVersion string `json:"minimum_version"`
+ Configuration string `json:"configuration"`
+ LastEventObserved bool `json:"last_event_observed"`
+ Message string `json:"message"`
+}
+
+func DefaultConfig(grpcPort, httpPort int) Config {
+ return Config{
+ Endpoint: fmt.Sprintf("http://127.0.0.1:%d", httpPort),
+ Protocol: "HTTP/protobuf",
+ }
+}
+
+func PrintConfig(cfg Config) string {
+ if cfg.Endpoint == "" {
+ cfg = DefaultConfig(4317, 4318)
+ }
+ return fmt.Sprintf(`Claude Cowork OpenTelemetry setup
+
+Configure this in Claude Desktop:
+
+ Organization settings > Cowork > OpenTelemetry
+
+OTLP endpoint:
+ %s
+
+OTLP protocol:
+ %s
+
+Headers:
+ %s
+
+Notes:
+- Claude Cowork export is configured by a Team/Enterprise admin.
+- Claude Desktop must be version %s or newer.
+- Cowork may include prompt text and tool parameters. Beacon's collector should redact/drop content by default before writing Wazuh JSONL.
+`, cfg.Endpoint, cfg.Protocol, headerText(cfg.Headers), MinVersion)
+}
+
+func GetStatus(logPath string) Status {
+ status := Status{
+ Name: Name,
+ DisplayName: DisplayName,
+ MinimumVersion: MinVersion,
+ Configuration: "admin_configured",
+ Message: "Configure Claude Cowork in Claude Desktop organization settings",
+ }
+ if runtime.GOOS == "darwin" {
+ for _, path := range []string{
+ "/Applications/Claude.app",
+ filepath.Join(os.Getenv("HOME"), "Applications", "Claude.app"),
+ } {
+ if info, err := os.Stat(path); err == nil && info.IsDir() {
+ status.Detected = true
+ status.DesktopPath = path
+ break
+ }
+ }
+ }
+ status.LastEventObserved = HasRecentCoworkEvent(logPath)
+ if status.LastEventObserved {
+ status.Message = "Claude Cowork events have been observed in the endpoint runtime log"
+ }
+ return status
+}
+
+func HasRecentCoworkEvent(logPath string) bool {
+ if logPath == "" {
+ return false
+ }
+ file, err := os.Open(logPath)
+ if err != nil {
+ return false
+ }
+ defer file.Close()
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ var event map[string]interface{}
+ if err := json.Unmarshal(scanner.Bytes(), &event); err != nil {
+ continue
+ }
+ if harness, ok := event["harness"].(map[string]interface{}); ok {
+ if name, _ := harness["name"].(string); strings.EqualFold(name, Name) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func headerText(headers string) string {
+ if strings.TrimSpace(headers) == "" {
+ return "(none)"
+ }
+ return headers
+}
diff --git a/cli/beacon/internal/endpoint/integrations/cowork/cowork_test.go b/cli/beacon/internal/endpoint/integrations/cowork/cowork_test.go
new file mode 100644
index 00000000..68d68730
--- /dev/null
+++ b/cli/beacon/internal/endpoint/integrations/cowork/cowork_test.go
@@ -0,0 +1,29 @@
+package cowork
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestPrintConfigIncludesEndpointAndPrivacyNote(t *testing.T) {
+ out := PrintConfig(Config{Endpoint: "http://127.0.0.1:4318", Protocol: "HTTP/protobuf"})
+ if !strings.Contains(out, "http://127.0.0.1:4318") {
+ t.Fatalf("missing endpoint: %s", out)
+ }
+ if !strings.Contains(out, "prompt text") {
+ t.Fatalf("missing privacy note: %s", out)
+ }
+}
+
+func TestHasRecentCoworkEvent(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ data := `{"harness":{"name":"claude_cowork"}}` + "\n"
+ if err := os.WriteFile(path, []byte(data), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if !HasRecentCoworkEvent(path) {
+ t.Fatal("expected cowork event to be detected")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
new file mode 100644
index 00000000..aed041c4
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -0,0 +1,331 @@
+package lifecycle
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "time"
+
+ endpointcollector "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+type InstallOptions struct {
+ UserMode bool
+ LogPath string
+ Harnesses []string
+ GRPCPort int
+ HTTPPort int
+ CollectorPath string
+ StartService bool
+}
+
+type UninstallOptions struct {
+ UserMode bool
+ LogPath string
+ KeepLogs bool
+ KeepConfig bool
+}
+
+type InstallResult struct {
+ ConfigPath string `json:"config_path"`
+ CollectorConfigPath string `json:"collector_config_path"`
+ PlistPath string `json:"plist_path"`
+ LogPath string `json:"log_path"`
+ ManifestPath string `json:"manifest_path"`
+ HarnessConfigPaths []string `json:"harness_config_paths,omitempty"`
+}
+
+type Status struct {
+ Version string `json:"version"`
+ ConfigPath string `json:"config_path"`
+ LogPath string `json:"log_path"`
+ Collector endpointcollector.Status `json:"collector"`
+ Service service.Status `json:"service"`
+ Harnesses []harness.Harness `json:"harnesses"`
+ Diagnostics []diagnostics.Check `json:"diagnostics"`
+ LastEvent string `json:"last_event,omitempty"`
+}
+
+type Manifest struct {
+ CreatedAt string `json:"created_at"`
+ UserMode bool `json:"user_mode"`
+ Files []string `json:"files"`
+ Backups []string `json:"backups,omitempty"`
+ HarnessConfigs []string `json:"harness_configs,omitempty"`
+ ServiceLabel string `json:"service_label"`
+ LogPath string `json:"log_path"`
+}
+
+func Install(opts InstallOptions) (InstallResult, error) {
+ cfg := buildConfig(opts)
+ if err := preflight(cfg); err != nil {
+ return InstallResult{}, err
+ }
+ manager := service.Manager{UserMode: cfg.UserMode}
+ collectorBinary := endpointcollector.DiscoverBinary(cfg.Collector.BinaryPath)
+ if collectorBinary == "" {
+ collectorBinary = cfg.Collector.BinaryPath
+ }
+ if collectorBinary == "" {
+ collectorBinary = filepath.Join(endpointconfig.BaseDir(cfg.UserMode), "bin", "beacon-otelcol")
+ }
+
+ manifest := Manifest{
+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
+ UserMode: cfg.UserMode,
+ ServiceLabel: manager.Label(),
+ LogPath: cfg.LogPath,
+ }
+ if err := endpointcollector.WriteConfig(cfg); err != nil {
+ return InstallResult{}, err
+ }
+ manifest.Files = append(manifest.Files, cfg.Collector.ConfigPath)
+ plistPath, err := manager.WritePlist(collectorBinary, cfg.Collector.ConfigPath)
+ if err != nil {
+ rollback(manifest)
+ return InstallResult{}, err
+ }
+ manifest.Files = append(manifest.Files, plistPath)
+ configPath, err := endpointconfig.Save(cfg)
+ if err != nil {
+ rollback(manifest)
+ return InstallResult{}, err
+ }
+ manifest.Files = append(manifest.Files, configPath)
+ harnessPaths, err := configureHarnesses(cfg)
+ if err != nil {
+ rollback(manifest)
+ return InstallResult{}, err
+ }
+ manifest.HarnessConfigs = harnessPaths
+ manifest.Backups = discoverBackups(harnessPaths)
+ if opts.StartService {
+ if err := manager.Load(); err != nil {
+ rollback(manifest)
+ return InstallResult{}, err
+ }
+ }
+ manifestPath, err := writeManifest(cfg.UserMode, manifest)
+ if err != nil {
+ rollback(manifest)
+ return InstallResult{}, err
+ }
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "telemetry.enabled",
+ Category: "telemetry",
+ Severity: schema.SeverityInfo,
+ AgentVersion: version.GetVersion(),
+ Harness: schema.HarnessInfo{Name: "endpoint"},
+ Message: "Beacon endpoint local telemetry configured",
+ })
+ event.Destination = &schema.DestinationInfo{Type: "wazuh", Mode: "localfile", Status: "configured"}
+ if _, err := writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode}); err != nil {
+ return InstallResult{}, err
+ }
+ return InstallResult{
+ ConfigPath: configPath,
+ CollectorConfigPath: cfg.Collector.ConfigPath,
+ PlistPath: plistPath,
+ LogPath: cfg.LogPath,
+ ManifestPath: manifestPath,
+ HarnessConfigPaths: harnessPaths,
+ }, nil
+}
+
+func Uninstall(opts UninstallOptions) error {
+ cfg := loadOrDefault(opts.UserMode, opts.LogPath)
+ manager := service.Manager{UserMode: cfg.UserMode}
+ _ = manager.Unload()
+ manifest, _ := ReadManifest(cfg.UserMode)
+ if !opts.KeepConfig {
+ restoreBackups(manifest.Backups)
+ }
+ for _, path := range manifest.Files {
+ _ = os.Remove(path)
+ }
+ if len(manifest.Files) == 0 {
+ if path, err := manager.PlistPath(); err == nil {
+ _ = os.Remove(path)
+ }
+ _ = os.Remove(cfg.Collector.ConfigPath)
+ _ = os.Remove(endpointconfig.ConfigPath(cfg.UserMode))
+ }
+ if !opts.KeepLogs {
+ _ = os.Remove(cfg.LogPath)
+ }
+ _ = os.Remove(manifestPath(cfg.UserMode))
+ return nil
+}
+
+func Repair(opts InstallOptions) (InstallResult, error) {
+ _ = Uninstall(UninstallOptions{UserMode: opts.UserMode, LogPath: opts.LogPath, KeepLogs: true, KeepConfig: true})
+ return Install(opts)
+}
+
+func GetStatus(userMode bool, logPath string) Status {
+ cfg := loadOrDefault(userMode, logPath)
+ last, _ := writer.LastLine(cfg.LogPath)
+ return Status{
+ Version: version.GetVersion(),
+ ConfigPath: endpointconfig.ConfigPath(cfg.UserMode),
+ LogPath: cfg.LogPath,
+ Collector: endpointcollector.CheckStatus(cfg),
+ Service: service.Manager{UserMode: cfg.UserMode}.Status(),
+ Harnesses: harness.DiscoverAll(),
+ Diagnostics: diagnostics.Run(cfg),
+ LastEvent: last,
+ }
+}
+
+func buildConfig(opts InstallOptions) endpointconfig.Config {
+ logPath := opts.LogPath
+ if logPath == "" {
+ logPath = writer.DefaultPath(opts.UserMode)
+ }
+ cfg := endpointconfig.Default(opts.UserMode, logPath)
+ if len(opts.Harnesses) > 0 {
+ cfg.Harnesses = opts.Harnesses
+ }
+ if opts.GRPCPort != 0 {
+ cfg.Collector.GRPCPort = opts.GRPCPort
+ }
+ if opts.HTTPPort != 0 {
+ cfg.Collector.HTTPPort = opts.HTTPPort
+ }
+ cfg.Collector.BinaryPath = opts.CollectorPath
+ return cfg
+}
+
+func loadOrDefault(userMode bool, logPath string) endpointconfig.Config {
+ if cfg, err := endpointconfig.Load(userMode); err == nil {
+ if logPath != "" {
+ cfg.LogPath = logPath
+ }
+ return cfg
+ }
+ if logPath == "" {
+ logPath = writer.DefaultPath(userMode)
+ }
+ return endpointconfig.Default(userMode, logPath)
+}
+
+func preflight(cfg endpointconfig.Config) error {
+ if runtime.GOOS != "darwin" {
+ return fmt.Errorf("production endpoint install is currently supported only on macOS")
+ }
+ if !cfg.UserMode && os.Geteuid() != 0 {
+ return fmt.Errorf("system install requires root; rerun with sudo or use --user")
+ }
+ if !endpointcollector.PortAvailable(cfg.Collector.GRPCPort) {
+ return fmt.Errorf("OTLP gRPC port %d is already in use", cfg.Collector.GRPCPort)
+ }
+ if !endpointcollector.PortAvailable(cfg.Collector.HTTPPort) {
+ return fmt.Errorf("OTLP HTTP port %d is already in use", cfg.Collector.HTTPPort)
+ }
+ return nil
+}
+
+func configureHarnesses(cfg endpointconfig.Config) ([]string, error) {
+ endpoint := fmt.Sprintf("http://127.0.0.1:%d", cfg.Collector.GRPCPort)
+ var paths []string
+ for _, name := range cfg.Harnesses {
+ switch name {
+ case "claude", "claude_code":
+ path, err := harness.ConfigureClaude(harness.ConfigureOptions{Endpoint: endpoint, UserMode: cfg.UserMode})
+ if err != nil {
+ return paths, err
+ }
+ paths = append(paths, path)
+ case "codex", "codex_cli":
+ path, err := harness.ConfigureCodex(harness.ConfigureOptions{Endpoint: endpoint, UserMode: cfg.UserMode})
+ if err != nil {
+ return paths, err
+ }
+ paths = append(paths, path)
+ case "":
+ default:
+ return paths, fmt.Errorf("unsupported harness %q", name)
+ }
+ }
+ return paths, nil
+}
+
+func discoverBackups(paths []string) []string {
+ var backups []string
+ for _, path := range paths {
+ matches, _ := filepath.Glob(path + ".beacon.*.bak")
+ backups = append(backups, matches...)
+ if _, err := os.Stat(path + ".beacon.bak"); err == nil {
+ backups = append(backups, path+".beacon.bak")
+ }
+ }
+ return backups
+}
+
+func restoreBackups(backups []string) {
+ for _, backup := range backups {
+ target := restoreTarget(backup)
+ if target == "" {
+ continue
+ }
+ data, err := os.ReadFile(backup)
+ if err == nil {
+ _ = os.WriteFile(target, data, 0600)
+ }
+ }
+}
+
+func writeManifest(userMode bool, manifest Manifest) (string, error) {
+ path := manifestPath(userMode)
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ data, err := json.MarshalIndent(manifest, "", " ")
+ if err != nil {
+ return "", err
+ }
+ return path, os.WriteFile(path, data, 0600)
+}
+
+func ReadManifest(userMode bool) (Manifest, error) {
+ data, err := os.ReadFile(manifestPath(userMode))
+ if err != nil {
+ return Manifest{}, err
+ }
+ var manifest Manifest
+ if err := json.Unmarshal(data, &manifest); err != nil {
+ return Manifest{}, err
+ }
+ return manifest, nil
+}
+
+func manifestPath(userMode bool) string {
+ return filepath.Join(endpointconfig.BaseDir(userMode), "install-manifest.json")
+}
+
+func rollback(manifest Manifest) {
+ restoreBackups(manifest.Backups)
+ for i := len(manifest.Files) - 1; i >= 0; i-- {
+ _ = os.Remove(manifest.Files[i])
+ }
+}
+
+func restoreTarget(backup string) string {
+ for _, suffix := range []string{".beacon.bak", ".beacon."} {
+ for i := len(backup) - len(suffix); i >= 0; i-- {
+ if i+len(suffix) <= len(backup) && backup[i:i+len(suffix)] == suffix {
+ return backup[:i]
+ }
+ }
+ }
+ return ""
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go
new file mode 100644
index 00000000..16a2d8f7
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go
@@ -0,0 +1,243 @@
+package lifecycle
+
+import (
+ "net"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+func TestRestoreTargetTimestampedBackup(t *testing.T) {
+ got := restoreTarget("/tmp/settings.json.beacon.20260511T230000Z.bak")
+ want := "/tmp/settings.json"
+ if got != want {
+ t.Fatalf("restoreTarget() = %q, want %q", got, want)
+ }
+}
+
+func TestRestoreTargetLegacyBackup(t *testing.T) {
+ got := restoreTarget("/tmp/settings.json.beacon.bak")
+ want := "/tmp/settings.json"
+ if got != want {
+ t.Fatalf("restoreTarget() = %q, want %q", got, want)
+ }
+}
+
+func TestBuildConfigAppliesInstallOptions(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ logPath := filepath.Join(home, "runtime.jsonl")
+ collectorPath := filepath.Join(home, "bin", "otelcol")
+
+ cfg := buildConfig(InstallOptions{
+ UserMode: true,
+ LogPath: logPath,
+ Harnesses: []string{"codex"},
+ GRPCPort: 54317,
+ HTTPPort: 54318,
+ CollectorPath: collectorPath,
+ })
+
+ if !cfg.UserMode || cfg.LogPath != logPath {
+ t.Fatalf("unexpected mode/log path: %#v", cfg)
+ }
+ if got := cfg.Harnesses; len(got) != 1 || got[0] != "codex" {
+ t.Fatalf("Harnesses = %#v, want codex", got)
+ }
+ if cfg.Collector.GRPCPort != 54317 || cfg.Collector.HTTPPort != 54318 {
+ t.Fatalf("unexpected ports: %#v", cfg.Collector)
+ }
+ if cfg.Collector.BinaryPath != collectorPath {
+ t.Fatalf("BinaryPath = %q, want %q", cfg.Collector.BinaryPath, collectorPath)
+ }
+}
+
+func TestConfigureHarnessesRejectsUnsupportedHarness(t *testing.T) {
+ cfg := endpointconfig.Config{Harnesses: []string{"unknown"}}
+ if _, err := configureHarnesses(cfg); err == nil || !strings.Contains(err.Error(), "unsupported harness") {
+ t.Fatalf("configureHarnesses error = %v, want unsupported harness", err)
+ }
+}
+
+func TestWriteReadManifestRoundTrip(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ manifest := Manifest{
+ CreatedAt: "2026-05-12T00:00:00Z",
+ UserMode: true,
+ Files: []string{filepath.Join(home, "config.json")},
+ Backups: []string{filepath.Join(home, "settings.json.beacon.bak")},
+ HarnessConfigs: []string{filepath.Join(home, ".claude", "settings.json")},
+ ServiceLabel: "com.beacon.endpoint.collector.user",
+ LogPath: filepath.Join(home, "runtime.jsonl"),
+ }
+
+ path, err := writeManifest(true, manifest)
+ if err != nil {
+ t.Fatalf("writeManifest returned error: %v", err)
+ }
+ if got, want := path, filepath.Join(home, ".beacon", "endpoint", "install-manifest.json"); got != want {
+ t.Fatalf("manifest path = %q, want %q", got, want)
+ }
+ loaded, err := ReadManifest(true)
+ if err != nil {
+ t.Fatalf("ReadManifest returned error: %v", err)
+ }
+ if loaded.ServiceLabel != manifest.ServiceLabel || loaded.Files[0] != manifest.Files[0] || loaded.Backups[0] != manifest.Backups[0] {
+ t.Fatalf("manifest did not round-trip: %#v", loaded)
+ }
+}
+
+func TestDiscoverAndRestoreBackups(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "settings.json")
+ backup := target + ".beacon.20260512T120000Z.bak"
+ if err := os.WriteFile(backup, []byte("restored"), 0600); err != nil {
+ t.Fatalf("write backup: %v", err)
+ }
+
+ backups := discoverBackups([]string{target})
+ if len(backups) != 1 || backups[0] != backup {
+ t.Fatalf("discoverBackups = %#v, want %q", backups, backup)
+ }
+ restoreBackups(backups)
+ data, err := os.ReadFile(target)
+ if err != nil {
+ t.Fatalf("read restored target: %v", err)
+ }
+ if string(data) != "restored" {
+ t.Fatalf("restored target = %q", string(data))
+ }
+}
+
+func TestRollbackRestoresBackupsAndRemovesFiles(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "settings.json")
+ backup := target + ".beacon.bak"
+ created := filepath.Join(dir, "created.txt")
+ if err := os.WriteFile(backup, []byte("original"), 0600); err != nil {
+ t.Fatalf("write backup: %v", err)
+ }
+ if err := os.WriteFile(created, []byte("created"), 0600); err != nil {
+ t.Fatalf("write created file: %v", err)
+ }
+
+ rollback(Manifest{Files: []string{created}, Backups: []string{backup}})
+
+ if _, err := os.Stat(created); !os.IsNotExist(err) {
+ t.Fatalf("created file still exists or unexpected error: %v", err)
+ }
+ data, err := os.ReadFile(target)
+ if err != nil {
+ t.Fatalf("read restored target: %v", err)
+ }
+ if string(data) != "original" {
+ t.Fatalf("restored target = %q", string(data))
+ }
+}
+
+func TestPreflightRejectsPortInUse(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("preflight is macOS-only")
+ }
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen: %v", err)
+ }
+ defer ln.Close()
+ port := ln.Addr().(*net.TCPAddr).Port
+
+ cfg := endpointconfig.Default(true, filepath.Join(t.TempDir(), "runtime.jsonl"))
+ cfg.Collector.GRPCPort = port
+ cfg.Collector.HTTPPort = freePort(t)
+
+ err = preflight(cfg)
+ if err == nil || !strings.Contains(err.Error(), "OTLP gRPC port") {
+ t.Fatalf("preflight error = %v, want gRPC port in use", err)
+ }
+}
+
+func TestUninstallFallbackRemovesKnownFiles(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("launchd paths are macOS-only")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
+ cfg := endpointconfig.Default(true, logPath)
+ for _, path := range []string{endpointconfig.ConfigPath(true), cfg.Collector.ConfigPath, logPath} {
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatalf("mkdir %s: %v", path, err)
+ }
+ if err := os.WriteFile(path, []byte("data"), 0600); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+ }
+
+ if err := Uninstall(UninstallOptions{UserMode: true, LogPath: logPath}); err != nil {
+ t.Fatalf("Uninstall returned error: %v", err)
+ }
+ for _, path := range []string{endpointconfig.ConfigPath(true), cfg.Collector.ConfigPath, logPath} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("%s still exists or unexpected error: %v", path, err)
+ }
+ }
+}
+
+func TestInstallUserModeWithoutStartingService(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("install preflight is macOS-only")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ collectorPath := filepath.Join(home, "bin", "otelcol")
+ if err := os.MkdirAll(filepath.Dir(collectorPath), 0755); err != nil {
+ t.Fatalf("mkdir fake collector dir: %v", err)
+ }
+ if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0755); err != nil {
+ t.Fatalf("write fake collector: %v", err)
+ }
+ logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
+
+ result, err := Install(InstallOptions{
+ UserMode: true,
+ LogPath: logPath,
+ Harnesses: []string{""},
+ GRPCPort: freePort(t),
+ HTTPPort: freePort(t),
+ CollectorPath: collectorPath,
+ StartService: false,
+ })
+ if err != nil {
+ t.Fatalf("Install returned error: %v", err)
+ }
+ for _, path := range []string{result.ConfigPath, result.CollectorConfigPath, result.PlistPath, result.ManifestPath, result.LogPath} {
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("expected install artifact %s: %v", path, err)
+ }
+ }
+ manifest, err := ReadManifest(true)
+ if err != nil {
+ t.Fatalf("ReadManifest returned error: %v", err)
+ }
+ if len(manifest.Files) != 3 {
+ t.Fatalf("manifest files = %#v, want collector config, plist, config", manifest.Files)
+ }
+ if len(result.HarnessConfigPaths) != 0 {
+ t.Fatalf("unexpected harness config paths: %#v", result.HarnessConfigPaths)
+ }
+}
+
+func freePort(t *testing.T) int {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen for free port: %v", err)
+ }
+ defer ln.Close()
+ return ln.Addr().(*net.TCPAddr).Port
+}
diff --git a/cli/beacon/internal/endpoint/schema/event.go b/cli/beacon/internal/endpoint/schema/event.go
new file mode 100644
index 00000000..e1f45b04
--- /dev/null
+++ b/cli/beacon/internal/endpoint/schema/event.go
@@ -0,0 +1,168 @@
+package schema
+
+import (
+ "errors"
+ "os"
+ "runtime"
+ "time"
+)
+
+const (
+ Vendor = "beacon"
+ Product = "endpoint-agent"
+ SchemaVersion = "1.0"
+)
+
+type Severity string
+
+const (
+ SeverityInfo Severity = "info"
+ SeverityLow Severity = "low"
+ SeverityMedium Severity = "medium"
+ SeverityHigh Severity = "high"
+ SeverityCritical Severity = "critical"
+)
+
+type 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"`
+ AgentVersion string `json:"agent_version,omitempty"`
+}
+
+type UserInfo struct {
+ Name string `json:"name,omitempty"`
+ UID string `json:"uid,omitempty"`
+}
+
+type HarnessInfo struct {
+ Name string `json:"name"`
+ Version string `json:"version,omitempty"`
+ ExecutablePath string `json:"executable_path,omitempty"`
+ ConfigPath string `json:"config_path,omitempty"`
+}
+
+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 PolicyInfo struct {
+ ID string `json:"id,omitempty"`
+ Name string `json:"name,omitempty"`
+ Decision string `json:"decision,omitempty"`
+ Enforcement string `json:"enforcement,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+type DestinationInfo struct {
+ Type string `json:"type,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ Status string `json:"status,omitempty"`
+}
+
+type HealthInfo struct {
+ Component string `json:"component,omitempty"`
+ Status string `json:"status,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+type Event struct {
+ Timestamp string `json:"timestamp"`
+ Vendor string `json:"vendor"`
+ Product string `json:"product"`
+ SchemaVersion string `json:"schema_version"`
+ Event EventInfo `json:"event"`
+ Severity Severity `json:"severity"`
+ Endpoint EndpointInfo `json:"endpoint"`
+ User UserInfo `json:"user,omitempty"`
+ Harness HarnessInfo `json:"harness"`
+ Session *SessionInfo `json:"session,omitempty"`
+ Tool *ToolInfo `json:"tool,omitempty"`
+ Policy *PolicyInfo `json:"policy,omitempty"`
+ Destination *DestinationInfo `json:"destination,omitempty"`
+ Health *HealthInfo `json:"health,omitempty"`
+ Message string `json:"message,omitempty"`
+ Raw map[string]interface{} `json:"raw,omitempty"`
+ Truncated bool `json:"field_truncated,omitempty"`
+}
+
+type NewEventOptions struct {
+ Action string
+ Category string
+ Severity Severity
+ Harness HarnessInfo
+ AgentVersion string
+ Message string
+}
+
+func NewEvent(opts NewEventOptions) Event {
+ hostname, _ := os.Hostname()
+ userName := os.Getenv("USER")
+ if userName == "" {
+ userName = os.Getenv("USERNAME")
+ }
+ severity := opts.Severity
+ if severity == "" {
+ severity = SeverityInfo
+ }
+ return Event{
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
+ Vendor: Vendor,
+ Product: Product,
+ SchemaVersion: SchemaVersion,
+ Event: EventInfo{
+ Kind: "agent_runtime",
+ Action: opts.Action,
+ Category: opts.Category,
+ },
+ Severity: severity,
+ Endpoint: EndpointInfo{
+ Hostname: hostname,
+ OS: runtime.GOOS,
+ AgentVersion: opts.AgentVersion,
+ },
+ User: UserInfo{
+ Name: userName,
+ UID: os.Getenv("UID"),
+ },
+ Harness: opts.Harness,
+ Message: opts.Message,
+ }
+}
+
+func (e Event) Validate() error {
+ if e.Vendor != Vendor {
+ return errors.New("vendor must be beacon")
+ }
+ if e.Product != Product {
+ return errors.New("product must be endpoint-agent")
+ }
+ if e.SchemaVersion == "" {
+ return errors.New("schema_version is required")
+ }
+ if e.Event.Kind == "" || e.Event.Action == "" {
+ return errors.New("event.kind and event.action are required")
+ }
+ if e.Severity == "" {
+ return errors.New("severity is required")
+ }
+ if e.Endpoint.OS == "" {
+ return errors.New("endpoint.os is required")
+ }
+ if e.Harness.Name == "" {
+ return errors.New("harness.name is required")
+ }
+ return nil
+}
diff --git a/cli/beacon/internal/endpoint/schema/event_test.go b/cli/beacon/internal/endpoint/schema/event_test.go
new file mode 100644
index 00000000..4e0f7456
--- /dev/null
+++ b/cli/beacon/internal/endpoint/schema/event_test.go
@@ -0,0 +1,98 @@
+package schema
+
+import (
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestNewEventSetsRequiredInvariants(t *testing.T) {
+ event := NewEvent(NewEventOptions{
+ Action: "telemetry.enabled",
+ Category: "telemetry",
+ AgentVersion: "test-version",
+ Harness: HarnessInfo{Name: "endpoint"},
+ Message: "configured",
+ })
+
+ if err := event.Validate(); err != nil {
+ t.Fatalf("Validate returned error: %v", err)
+ }
+ if event.Vendor != Vendor || event.Product != Product || event.SchemaVersion != SchemaVersion {
+ t.Fatalf("unexpected schema identity: %#v", event)
+ }
+ if event.Event.Kind != "agent_runtime" || event.Event.Action != "telemetry.enabled" || event.Event.Category != "telemetry" {
+ t.Fatalf("unexpected event info: %#v", event.Event)
+ }
+ if event.Severity != SeverityInfo {
+ t.Fatalf("default severity = %q, want %q", event.Severity, SeverityInfo)
+ }
+ if event.Endpoint.OS != runtime.GOOS || event.Endpoint.AgentVersion != "test-version" {
+ t.Fatalf("unexpected endpoint info: %#v", event.Endpoint)
+ }
+ if _, err := time.Parse(time.RFC3339, event.Timestamp); err != nil {
+ t.Fatalf("timestamp is not RFC3339: %q", event.Timestamp)
+ }
+}
+
+func TestValidateRejectsMissingOrInvalidRequiredFields(t *testing.T) {
+ valid := NewEvent(NewEventOptions{
+ Action: "tool.invoked",
+ Harness: HarnessInfo{Name: "cursor"},
+ Severity: SeverityHigh,
+ })
+
+ tests := []struct {
+ name string
+ edit func(*Event)
+ want string
+ }{
+ {
+ name: "vendor",
+ edit: func(e *Event) { e.Vendor = "other" },
+ want: "vendor must be beacon",
+ },
+ {
+ name: "product",
+ edit: func(e *Event) { e.Product = "other" },
+ want: "product must be endpoint-agent",
+ },
+ {
+ name: "schema version",
+ edit: func(e *Event) { e.SchemaVersion = "" },
+ want: "schema_version is required",
+ },
+ {
+ name: "action",
+ edit: func(e *Event) { e.Event.Action = "" },
+ want: "event.kind and event.action are required",
+ },
+ {
+ name: "severity",
+ edit: func(e *Event) { e.Severity = "" },
+ want: "severity is required",
+ },
+ {
+ name: "os",
+ edit: func(e *Event) { e.Endpoint.OS = "" },
+ want: "endpoint.os is required",
+ },
+ {
+ name: "harness",
+ edit: func(e *Event) { e.Harness.Name = "" },
+ want: "harness.name is required",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ event := valid
+ tt.edit(&event)
+ err := event.Validate()
+ if err == nil || !strings.Contains(err.Error(), tt.want) {
+ t.Fatalf("Validate error = %v, want %q", err, tt.want)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.go
new file mode 100644
index 00000000..bc3339e2
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/service.go
@@ -0,0 +1,146 @@
+package service
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+const (
+ SystemLabel = "com.beacon.endpoint.collector"
+ UserLabel = "com.beacon.endpoint.collector.user"
+)
+
+type Manager struct {
+ UserMode bool
+}
+
+type Status struct {
+ Label string `json:"label"`
+ Loaded bool `json:"loaded"`
+ Running bool `json:"running"`
+ Message string `json:"message,omitempty"`
+}
+
+func (m Manager) Label() string {
+ if m.UserMode {
+ return UserLabel
+ }
+ return SystemLabel
+}
+
+func (m Manager) PlistPath() (string, error) {
+ if m.UserMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"), nil
+ }
+ return filepath.Join("/Library/LaunchDaemons", SystemLabel+".plist"), nil
+}
+
+func (m Manager) WritePlist(program, configPath string) (string, error) {
+ if runtime.GOOS != "darwin" {
+ return "", fmt.Errorf("launchd service management is supported only on macOS")
+ }
+ path, err := m.PlistPath()
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return "", err
+ }
+ content := plist(m.Label(), program, configPath)
+ return path, os.WriteFile(path, []byte(content), 0644)
+}
+
+func (m Manager) Load() error {
+ if runtime.GOOS != "darwin" {
+ return nil
+ }
+ path, err := m.PlistPath()
+ if err != nil {
+ return err
+ }
+ if m.UserMode {
+ return runLaunchctl("bootstrap", "gui/"+fmt.Sprint(os.Getuid()), path)
+ }
+ return runLaunchctl("bootstrap", "system", path)
+}
+
+func (m Manager) Unload() error {
+ if runtime.GOOS != "darwin" {
+ return nil
+ }
+ if m.UserMode {
+ return runLaunchctl("bootout", "gui/"+fmt.Sprint(os.Getuid())+"/"+m.Label())
+ }
+ return runLaunchctl("bootout", "system/"+m.Label())
+}
+
+func (m Manager) Status() Status {
+ status := Status{Label: m.Label()}
+ if runtime.GOOS != "darwin" {
+ status.Message = "service status is available only on macOS"
+ return status
+ }
+ out, err := exec.Command("launchctl", "print", serviceDomain(m.UserMode)+"/"+m.Label()).CombinedOutput()
+ if err != nil {
+ status.Message = strings.TrimSpace(string(out))
+ return status
+ }
+ status.Loaded = true
+ text := string(out)
+ status.Running = strings.Contains(text, "state = running") || strings.Contains(text, "pid =")
+ return status
+}
+
+func runLaunchctl(args ...string) error {
+ cmd := exec.Command("launchctl", args...)
+ out, err := cmd.CombinedOutput()
+ if err == nil {
+ return nil
+ }
+ text := strings.TrimSpace(string(out))
+ if strings.Contains(text, "already bootstrapped") || strings.Contains(text, "No such process") {
+ return nil
+ }
+ return fmt.Errorf("launchctl %s failed: %s: %w", strings.Join(args, " "), text, err)
+}
+
+func serviceDomain(userMode bool) string {
+ if userMode {
+ return "gui/" + fmt.Sprint(os.Getuid())
+ }
+ return "system"
+}
+
+func plist(label, program, configPath string) string {
+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>%s</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>%s</string>
+ <string>--config</string>
+ <string>%s</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>StandardOutPath</key>
+ <string>/tmp/%s.out</string>
+ <key>StandardErrorPath</key>
+ <string>/tmp/%s.err</string>
+</dict>
+</plist>
+`, label, program, configPath, label, label)
+}
diff --git a/cli/beacon/internal/endpoint/service/service_test.go b/cli/beacon/internal/endpoint/service/service_test.go
new file mode 100644
index 00000000..175ad467
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/service_test.go
@@ -0,0 +1,100 @@
+package service
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func TestManagerLabelAndPlistPath(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ userManager := Manager{UserMode: true}
+ if got := userManager.Label(); got != UserLabel {
+ t.Fatalf("user label = %q, want %q", got, UserLabel)
+ }
+ userPath, err := userManager.PlistPath()
+ if err != nil {
+ t.Fatalf("user PlistPath returned error: %v", err)
+ }
+ if want := filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"); userPath != want {
+ t.Fatalf("user plist path = %q, want %q", userPath, want)
+ }
+
+ systemManager := Manager{}
+ if got := systemManager.Label(); got != SystemLabel {
+ t.Fatalf("system label = %q, want %q", got, SystemLabel)
+ }
+ systemPath, err := systemManager.PlistPath()
+ if err != nil {
+ t.Fatalf("system PlistPath returned error: %v", err)
+ }
+ if want := filepath.Join("/Library/LaunchDaemons", SystemLabel+".plist"); systemPath != want {
+ t.Fatalf("system plist path = %q, want %q", systemPath, want)
+ }
+}
+
+func TestPlistContainsLaunchdContract(t *testing.T) {
+ content := plist(UserLabel, "/tmp/otelcol", "/tmp/otelcol.yaml")
+
+ for _, want := range []string{
+ "<string>" + UserLabel + "</string>",
+ "<string>/tmp/otelcol</string>",
+ "<string>--config</string>",
+ "<string>/tmp/otelcol.yaml</string>",
+ "<key>RunAtLoad</key>",
+ "<key>KeepAlive</key>",
+ "<string>/tmp/" + UserLabel + ".out</string>",
+ "<string>/tmp/" + UserLabel + ".err</string>",
+ } {
+ if !strings.Contains(content, want) {
+ t.Fatalf("plist missing %q:\n%s", want, content)
+ }
+ }
+}
+
+func TestWritePlistUserMode(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ manager := Manager{UserMode: true}
+
+ path, err := manager.WritePlist("/tmp/otelcol", "/tmp/otelcol.yaml")
+ if runtime.GOOS != "darwin" {
+ if err == nil || !strings.Contains(err.Error(), "supported only on macOS") {
+ t.Fatalf("WritePlist non-darwin error = %v, want macOS support error", err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("WritePlist returned error: %v", err)
+ }
+ if got, want := path, filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"); got != want {
+ t.Fatalf("plist path = %q, want %q", got, want)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read plist: %v", err)
+ }
+ if !strings.Contains(string(data), "<string>/tmp/otelcol</string>") {
+ t.Fatalf("plist content missing program: %s", string(data))
+ }
+}
+
+func TestStatusNonDarwinDocumentsUnsupportedMessage(t *testing.T) {
+ if runtime.GOOS == "darwin" {
+ t.Skip("non-darwin status contract")
+ }
+ status := (Manager{UserMode: true}).Status()
+ if status.Label != UserLabel {
+ t.Fatalf("Label = %q, want %q", status.Label, UserLabel)
+ }
+ if status.Loaded || status.Running {
+ t.Fatalf("non-darwin status should not be loaded/running: %#v", status)
+ }
+ if !strings.Contains(status.Message, "available only on macOS") {
+ t.Fatalf("unexpected status message: %q", status.Message)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/wazuh/pack/README.md b/cli/beacon/internal/endpoint/wazuh/pack/README.md
new file mode 100644
index 00000000..e2f5468e
--- /dev/null
+++ b/cli/beacon/internal/endpoint/wazuh/pack/README.md
@@ -0,0 +1,13 @@
+# Beacon Endpoint Agent Wazuh Pack
+
+Install `beacon-rules.xml` on the Wazuh manager and add the localfile
+snippet to the Wazuh agent configuration on managed endpoints.
+
+The generated `ossec-localfile.xml` should point at the endpoint runtime log
+configured on the endpoint.
+
+Validate locally with:
+
+```bash
+beacon endpoint wazuh validate
+```
diff --git a/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml b/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml
new file mode 100644
index 00000000..73a6e94b
--- /dev/null
+++ b/cli/beacon/internal/endpoint/wazuh/pack/beacon-rules.xml
@@ -0,0 +1,33 @@
+<group name="beacon,agent_runtime,">
+ <rule id="100500" level="3">
+ <decoded_as>json</decoded_as>
+ <field name="vendor">beacon</field>
+ <field name="product">endpoint-agent</field>
+ <field name="event.kind">agent_runtime</field>
+ <description>Beacon endpoint agent runtime event</description>
+ </rule>
+
+ <rule id="100510" level="5">
+ <if_sid>100500</if_sid>
+ <field name="event.action">telemetry.disabled|telemetry.misconfigured</field>
+ <description>Beacon endpoint telemetry disabled or misconfigured</description>
+ </rule>
+
+ <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>
+ </rule>
+
+ <rule id="100530" level="10">
+ <if_sid>100500</if_sid>
+ <field name="policy.decision">block</field>
+ <description>AI agent runtime policy block</description>
+ </rule>
+
+ <rule id="100540" level="12">
+ <if_sid>100500</if_sid>
+ <field name="event.action">endpoint.tamper_detected|endpoint.health_failed</field>
+ <description>Beacon endpoint tamper or health failure detected</description>
+ </rule>
+</group>
diff --git a/cli/beacon/internal/endpoint/wazuh/pack/ossec-localfile.xml b/cli/beacon/internal/endpoint/wazuh/pack/ossec-localfile.xml
new file mode 100644
index 00000000..144c77fd
--- /dev/null
+++ b/cli/beacon/internal/endpoint/wazuh/pack/ossec-localfile.xml
@@ -0,0 +1,4 @@
+<localfile>
+ <location>{{LOG_PATH}}</location>
+ <log_format>json</log_format>
+</localfile>
diff --git a/cli/beacon/internal/endpoint/wazuh/wazuh.go b/cli/beacon/internal/endpoint/wazuh/wazuh.go
new file mode 100644
index 00000000..70173691
--- /dev/null
+++ b/cli/beacon/internal/endpoint/wazuh/wazuh.go
@@ -0,0 +1,62 @@
+package wazuh
+
+import (
+ "embed"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+//go:embed pack/*
+var packFS embed.FS
+
+const DefaultLogPath = "/var/log/beacon-agent/runtime.jsonl"
+
+type File struct {
+ Name string
+ Content string
+}
+
+func Files() []File {
+ localfile := LocalfileSnippet(DefaultLogPath)
+ rules := mustRead("pack/beacon-rules.xml")
+ sample := mustRead("pack/sample-event.jsonl")
+ readme := mustRead("pack/README.md")
+ return []File{
+ {Name: "ossec-localfile.xml", Content: localfile},
+ {Name: "beacon-rules.xml", Content: rules},
+ {Name: "sample-event.jsonl", Content: sample},
+ {Name: "README.md", Content: readme},
+ }
+}
+
+func LocalfileSnippet(logPath string) string {
+ if logPath == "" {
+ logPath = DefaultLogPath
+ }
+ return strings.ReplaceAll(mustRead("pack/ossec-localfile.xml"), "{{LOG_PATH}}", logPath)
+}
+
+func InstallPack(outputDir, logPath string) error {
+ if err := os.MkdirAll(outputDir, 0755); err != nil {
+ return err
+ }
+ for _, file := range Files() {
+ content := file.Content
+ if file.Name == "ossec-localfile.xml" {
+ content = LocalfileSnippet(logPath)
+ }
+ if err := os.WriteFile(filepath.Join(outputDir, file.Name), []byte(content), 0644); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func mustRead(path string) string {
+ data, err := packFS.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+ return string(data)
+}
diff --git a/cli/beacon/internal/endpoint/wazuh/wazuh_test.go b/cli/beacon/internal/endpoint/wazuh/wazuh_test.go
new file mode 100644
index 00000000..f2e4a087
--- /dev/null
+++ b/cli/beacon/internal/endpoint/wazuh/wazuh_test.go
@@ -0,0 +1,30 @@
+package wazuh
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestLocalfileSnippetUsesConfiguredPath(t *testing.T) {
+ got := LocalfileSnippet("/tmp/beacon/runtime.jsonl")
+ if !strings.Contains(got, "/tmp/beacon/runtime.jsonl") {
+ t.Fatalf("snippet did not include configured path: %s", got)
+ }
+ if strings.Contains(got, "{{LOG_PATH}}") {
+ t.Fatalf("snippet still contains template token: %s", got)
+ }
+}
+
+func TestInstallPackWritesExpectedFiles(t *testing.T) {
+ dir := t.TempDir()
+ if err := InstallPack(dir, "/tmp/beacon/runtime.jsonl"); err != nil {
+ t.Fatalf("InstallPack returned error: %v", err)
+ }
+ for _, name := range []string{"ossec-localfile.xml", "beacon-rules.xml", "sample-event.jsonl", "README.md"} {
+ if _, err := os.Stat(filepath.Join(dir, name)); err != nil {
+ t.Fatalf("expected %s: %v", name, err)
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
new file mode 100644
index 00000000..18f0ccd4
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -0,0 +1,209 @@
+package writer
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "syscall"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+const (
+ SystemLogPath = "/var/log/beacon-agent/runtime.jsonl"
+ UserLogPath = ".beacon/endpoint/logs/runtime.jsonl"
+ MaxEventBytes = 64 * 1024
+ RotateBytes = 10 * 1024 * 1024
+)
+
+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 Options struct {
+ Path string
+ UserMode bool
+ MaxBytes int
+ RotateSize int64
+}
+
+func DefaultPath(userMode bool) string {
+ if userMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return filepath.Join(".", UserLogPath)
+ }
+ return filepath.Join(home, UserLogPath)
+ }
+ return SystemLogPath
+}
+
+func AppendEvent(event schema.Event, opts Options) (string, error) {
+ if opts.Path == "" {
+ opts.Path = DefaultPath(opts.UserMode)
+ }
+ if opts.MaxBytes == 0 {
+ opts.MaxBytes = MaxEventBytes
+ }
+ if opts.RotateSize == 0 {
+ opts.RotateSize = RotateBytes
+ }
+ event = SanitizeEvent(event, opts.MaxBytes)
+ if err := event.Validate(); err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(filepath.Dir(opts.Path), 0755); err != nil {
+ return "", err
+ }
+ if err := rotateIfNeeded(opts.Path, opts.RotateSize); err != nil {
+ return "", err
+ }
+ data, err := json.Marshal(event)
+ if err != nil {
+ return "", err
+ }
+ if len(data) > opts.MaxBytes {
+ 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) > opts.MaxBytes {
+ return "", fmt.Errorf("event exceeds maximum size after truncation: %d bytes", len(data))
+ }
+ f, err := os.OpenFile(opts.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()
+ if _, err := f.Write(append(data, '\n')); err != nil {
+ return "", err
+ }
+ return opts.Path, nil
+}
+
+func LastLine(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ var last string
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), MaxEventBytes)
+ for scanner.Scan() {
+ last = scanner.Text()
+ }
+ if err := scanner.Err(); err != nil {
+ return "", err
+ }
+ return last, nil
+}
+
+func SanitizeEvent(event schema.Event, maxBytes int) schema.Event {
+ event.Message = redact(truncate(event.Message, 4096))
+ if event.Tool != nil {
+ event.Tool.Command = redact(truncate(event.Tool.Command, 4096))
+ event.Tool.Path = truncate(event.Tool.Path, 2048)
+ }
+ if event.Policy != nil {
+ event.Policy.Reason = redact(truncate(event.Policy.Reason, 4096))
+ }
+ if event.Raw != nil {
+ event.Raw = sanitizeMap(event.Raw)
+ }
+ if data, err := json.Marshal(event); err == nil && len(data) > maxBytes {
+ event.Truncated = true
+ }
+ return event
+}
+
+func 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] = redact(truncate(typed, 2048))
+ case map[string]interface{}:
+ out[k] = sanitizeMap(typed)
+ case []interface{}:
+ out[k] = sanitizeSlice(typed)
+ default:
+ out[k] = typed
+ }
+ }
+ return out
+}
+
+func sanitizeSlice(input []interface{}) []interface{} {
+ out := make([]interface{}, len(input))
+ for i, v := range input {
+ switch typed := v.(type) {
+ case string:
+ out[i] = redact(truncate(typed, 2048))
+ case map[string]interface{}:
+ out[i] = sanitizeMap(typed)
+ case []interface{}:
+ out[i] = sanitizeSlice(typed)
+ default:
+ out[i] = typed
+ }
+ }
+ return out
+}
+
+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 {
+ 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)
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer_test.go b/cli/beacon/internal/endpoint/writer/writer_test.go
new file mode 100644
index 00000000..184fd894
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/writer_test.go
@@ -0,0 +1,190 @@
+package writer
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+func TestAppendEventWritesSingleJSONLine(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "test event",
+ })
+ written, err := AppendEvent(event, Options{Path: path})
+ if err != nil {
+ t.Fatalf("AppendEvent returned error: %v", err)
+ }
+ if written != path {
+ t.Fatalf("expected path %q, got %q", path, written)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read log: %v", err)
+ }
+ lines := strings.Split(strings.TrimSpace(string(data)), "\n")
+ if len(lines) != 1 {
+ t.Fatalf("expected one line, got %d", len(lines))
+ }
+ var decoded map[string]interface{}
+ if err := json.Unmarshal([]byte(lines[0]), &decoded); err != nil {
+ t.Fatalf("line is not JSON: %v", err)
+ }
+ if decoded["vendor"] != schema.Vendor {
+ t.Fatalf("unexpected vendor: %v", decoded["vendor"])
+ }
+}
+
+func TestAppendEventRedactsSecrets(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "tool.invoked",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "token=super-secret-value",
+ })
+ if _, err := AppendEvent(event, Options{Path: path}); err != nil {
+ t.Fatalf("AppendEvent returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read log: %v", err)
+ }
+ if strings.Contains(string(data), "super-secret-value") {
+ t.Fatalf("secret was not redacted: %s", string(data))
+ }
+}
+
+func TestAppendEventRedactsNestedSlices(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "tool.invoked",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "nested event",
+ })
+ event.Raw = map[string]interface{}{
+ "items": []interface{}{
+ map[string]interface{}{"value": "authorization: Bearer secret-token"},
+ },
+ }
+ if _, err := AppendEvent(event, Options{Path: path}); err != nil {
+ t.Fatalf("AppendEvent returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read log: %v", err)
+ }
+ if strings.Contains(string(data), "secret-token") {
+ t.Fatalf("nested secret was not redacted: %s", string(data))
+ }
+}
+
+func TestAppendEventRotatesExistingLog(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "runtime.jsonl")
+ if err := os.WriteFile(path, []byte("old log contents"), 0644); err != nil {
+ t.Fatalf("write existing log: %v", err)
+ }
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "new event",
+ })
+
+ if _, err := AppendEvent(event, Options{Path: path, RotateSize: 1}); err != nil {
+ t.Fatalf("AppendEvent returned error: %v", err)
+ }
+ rotated, err := os.ReadFile(path + ".1")
+ if err != nil {
+ t.Fatalf("read rotated log: %v", err)
+ }
+ if string(rotated) != "old log contents" {
+ t.Fatalf("rotated log = %q", string(rotated))
+ }
+ current, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read current log: %v", err)
+ }
+ if !strings.Contains(string(current), "new event") {
+ t.Fatalf("current log missing new event: %s", string(current))
+ }
+}
+
+func TestLastLine(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if _, err := LastLine(path); err == nil {
+ t.Fatal("expected missing file error")
+ }
+ if err := os.WriteFile(path, []byte("first\nsecond\n"), 0644); err != nil {
+ t.Fatalf("write log: %v", err)
+ }
+ last, err := LastLine(path)
+ if err != nil {
+ t.Fatalf("LastLine returned error: %v", err)
+ }
+ if last != "second" {
+ t.Fatalf("LastLine = %q, want second", last)
+ }
+}
+
+func TestAppendEventRejectsInvalidEvent(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "tool.invoked",
+ Harness: schema.HarnessInfo{Name: "test"},
+ })
+ event.Event.Action = ""
+
+ if _, err := AppendEvent(event, Options{Path: path}); err == nil {
+ t.Fatal("expected validation error")
+ }
+}
+
+func TestAppendEventRejectsOversizedEventAfterTruncation(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "tool.invoked",
+ Harness: schema.HarnessInfo{Name: strings.Repeat("h", 2048)},
+ Message: strings.Repeat("m", 2048),
+ })
+
+ if _, err := AppendEvent(event, Options{Path: path, MaxBytes: 512}); err == nil {
+ t.Fatal("expected oversized event error")
+ }
+}
+
+func TestSanitizeEventRedactsToolPolicyAndRawValues(t *testing.T) {
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "tool.invoked",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "authorization=Bearer message-secret",
+ })
+ event.Tool = &schema.ToolInfo{
+ Command: "curl -H 'Authorization: Bearer command-secret'",
+ Path: strings.Repeat("p", 3000),
+ }
+ event.Policy = &schema.PolicyInfo{Reason: "api_key=policy-secret"}
+ event.Raw = map[string]interface{}{
+ "nested": map[string]interface{}{"token": "token=raw-secret"},
+ }
+
+ sanitized := SanitizeEvent(event, MaxEventBytes)
+ data, err := json.Marshal(sanitized)
+ if err != nil {
+ t.Fatalf("marshal sanitized event: %v", err)
+ }
+ text := string(data)
+ for _, secret := range []string{"message-secret", "command-secret", "policy-secret", "raw-secret"} {
+ if strings.Contains(text, secret) {
+ t.Fatalf("secret %q was not redacted: %s", secret, text)
+ }
+ }
+ if len(sanitized.Tool.Path) > 2048 {
+ t.Fatalf("tool path was not truncated: %d", len(sanitized.Tool.Path))
+ }
+}
diff --git a/cli/beacon/internal/version/version.go b/cli/beacon/internal/version/version.go
new file mode 100644
index 00000000..a539671b
--- /dev/null
+++ b/cli/beacon/internal/version/version.go
@@ -0,0 +1,21 @@
+package version
+
+// These variables are set at build time using ldflags
+var (
+ // Version is the semantic version of the CLI
+ Version = "dev"
+ // GitCommit is the git commit hash
+ GitCommit = "unknown"
+ // BuildDate is the date the binary was built
+ BuildDate = "unknown"
+)
+
+// GetVersion returns the full version string
+func GetVersion() string {
+ return Version
+}
+
+// GetFullVersion returns the version with commit and build date
+func GetFullVersion() string {
+ return Version + " (" + GitCommit + ") built on " + BuildDate
+}
diff --git a/cli/beacon/internal/version/version_test.go b/cli/beacon/internal/version/version_test.go
new file mode 100644
index 00000000..9400dee9
--- /dev/null
+++ b/cli/beacon/internal/version/version_test.go
@@ -0,0 +1,136 @@
+package version
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestGetVersion(t *testing.T) {
+ // Store original values
+ origVersion := Version
+ defer func() { Version = origVersion }()
+
+ tests := []struct {
+ name string
+ version string
+ expected string
+ }{
+ {
+ name: "default dev version",
+ version: "dev",
+ expected: "dev",
+ },
+ {
+ name: "semantic version",
+ version: "v1.2.3",
+ expected: "v1.2.3",
+ },
+ {
+ name: "version with prerelease",
+ version: "v1.0.0-beta.1",
+ expected: "v1.0.0-beta.1",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ Version = tt.version
+ got := GetVersion()
+ if got != tt.expected {
+ t.Errorf("GetVersion() = %q, want %q", got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestGetFullVersion(t *testing.T) {
+ // Store original values
+ origVersion := Version
+ origCommit := GitCommit
+ origDate := BuildDate
+ defer func() {
+ Version = origVersion
+ GitCommit = origCommit
+ BuildDate = origDate
+ }()
+
+ tests := []struct {
+ name string
+ version string
+ commit string
+ date string
+ wantParts []string
+ }{
+ {
+ name: "default values",
+ version: "dev",
+ commit: "unknown",
+ date: "unknown",
+ wantParts: []string{"dev", "unknown", "built on", "unknown"},
+ },
+ {
+ name: "release values",
+ version: "v1.0.0",
+ commit: "abc1234",
+ date: "2025-01-15",
+ wantParts: []string{"v1.0.0", "abc1234", "built on", "2025-01-15"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ Version = tt.version
+ GitCommit = tt.commit
+ BuildDate = tt.date
+
+ got := GetFullVersion()
+
+ for _, part := range tt.wantParts {
+ if !strings.Contains(got, part) {
+ t.Errorf("GetFullVersion() = %q, missing part %q", got, part)
+ }
+ }
+ })
+ }
+}
+
+func TestGetFullVersion_Format(t *testing.T) {
+ // Store original values
+ origVersion := Version
+ origCommit := GitCommit
+ origDate := BuildDate
+ defer func() {
+ Version = origVersion
+ GitCommit = origCommit
+ BuildDate = origDate
+ }()
+
+ Version = "v1.2.3"
+ GitCommit = "abc1234"
+ BuildDate = "2025-01-15"
+
+ got := GetFullVersion()
+ expected := "v1.2.3 (abc1234) built on 2025-01-15"
+
+ if got != expected {
+ t.Errorf("GetFullVersion() = %q, want %q", got, expected)
+ }
+}
+
+func TestDefaultValues(t *testing.T) {
+ // These tests verify the default values are set correctly
+ // In a real build, these would be overridden by ldflags
+ // but in tests, we should see the defaults
+
+ // Note: We can't actually test defaults here because other tests
+ // may have modified them. Instead, verify the variables are non-empty.
+ if Version == "" {
+ t.Error("Version should not be empty")
+ }
+ if GitCommit == "" {
+ t.Error("GitCommit should not be empty")
+ }
+ if BuildDate == "" {
+ t.Error("BuildDate should not be empty")
+ }
+}
diff --git a/cli/beacon/main.go b/cli/beacon/main.go
new file mode 100644
index 00000000..78c3c3b2
--- /dev/null
+++ b/cli/beacon/main.go
@@ -0,0 +1,9 @@
+package main
+
+import (
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/cmd"
+)
+
+func main() {
+ cmd.Execute()
+}
diff --git a/collector-builder/builder.yaml b/collector-builder/builder.yaml
new file mode 100644
index 00000000..dfe03e08
--- /dev/null
+++ b/collector-builder/builder.yaml
@@ -0,0 +1,19 @@
+dist:
+ name: beacon-otelcol
+ description: Beacon Endpoint Agent OpenTelemetry Collector
+ output_path: ./dist/beacon-otelcol
+
+receivers:
+ - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.121.0
+
+processors:
+ - gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.121.0
+ - gomod: go.opentelemetry.io/collector/processor/memorylimiterprocessor v0.121.0
+
+exporters:
+ - gomod: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter v0.0.0
+ path: ./exporter/beaconjsonexporter
+
+extensions:
+ - gomod: go.opentelemetry.io/collector/extension/healthcheckextension v0.121.0
+
diff --git a/collector-builder/exporter/beaconjsonexporter/README.md b/collector-builder/exporter/beaconjsonexporter/README.md
new file mode 100644
index 00000000..1ba1383b
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/README.md
@@ -0,0 +1,24 @@
+# beaconjsonexporter
+
+Production Collector exporter for Beacon Endpoint Agent.
+
+This exporter is built into the custom `beacon-otelcol` distribution. It is
+responsible for converting OTLP logs, traces, metrics, and resource attributes
+into Wazuh-compatible Beacon endpoint JSONL events.
+
+Required behavior:
+
+- Bind only through Collector receivers configured on localhost.
+- Write one complete JSON object per line.
+- Use the canonical `vendor=beacon`, `product=endpoint-agent`,
+ `schema_version=1.0` event contract.
+- Identify Claude Cowork OTLP resources and map prompts, tool/MCP calls, file
+ access, approval decisions, API usage, token counts, costs, and errors into
+ metadata-first endpoint events.
+- Drop or summarize prompt/content fields by default.
+- Redact common secrets and cap event size before writing.
+- Emit health failure events when write failures occur.
+
+The production implementation should live here and be included by
+`collector-builder/builder.yaml`.
+
diff --git a/packaging/macos/README.md b/packaging/macos/README.md
new file mode 100644
index 00000000..4350ec15
--- /dev/null
+++ b/packaging/macos/README.md
@@ -0,0 +1,30 @@
+# macOS Deployment
+
+This directory contains lightweight deployment scaffolding for the Beacon
+Endpoint Agent MVP.
+
+The alpha install path assumes the `beacon` binary is already available on the
+endpoint through Homebrew, a direct download, or an MDM-managed package.
+
+## Manual Install
+
+```bash
+sudo beacon endpoint install
+beacon endpoint status
+beacon endpoint wazuh print-config
+```
+
+## MDM Install Script
+
+Use `install-endpoint.sh` from Jamf, Kandji, or a generic macOS MDM command
+runner. The script installs system-level endpoint configuration and writes logs
+to `/var/log/beacon-agent/runtime.jsonl`.
+
+Set `BEACON_ENDPOINT_HARNESSES` to override the default `claude,codex` harness
+list.
+
+## MDM Uninstall Script
+
+Use `uninstall-endpoint.sh` to remove endpoint service files. Set
+`BEACON_KEEP_LOGS=1` to preserve runtime logs during removal.
+
diff --git a/packaging/macos/install-endpoint.sh b/packaging/macos/install-endpoint.sh
new file mode 100755
index 00000000..348b5e53
--- /dev/null
+++ b/packaging/macos/install-endpoint.sh
@@ -0,0 +1,13 @@
+#!/bin/sh
+set -eu
+
+BEACON_BIN="${BEACON_BIN:-beacon}"
+BEACON_ENDPOINT_HARNESSES="${BEACON_ENDPOINT_HARNESSES:-claude,codex}"
+BEACON_OTLP_GRPC_PORT="${BEACON_OTLP_GRPC_PORT:-4317}"
+BEACON_OTLP_HTTP_PORT="${BEACON_OTLP_HTTP_PORT:-4318}"
+
+exec "$BEACON_BIN" endpoint install \
+ --harness "$BEACON_ENDPOINT_HARNESSES" \
+ --otlp-grpc-port "$BEACON_OTLP_GRPC_PORT" \
+ --otlp-http-port "$BEACON_OTLP_HTTP_PORT"
+
diff --git a/packaging/macos/pkgbuild.md b/packaging/macos/pkgbuild.md
new file mode 100644
index 00000000..62d5771f
--- /dev/null
+++ b/packaging/macos/pkgbuild.md
@@ -0,0 +1,22 @@
+# macOS Package Build Notes
+
+Production releases should ship a signed and notarized macOS package that
+installs:
+
+- `beacon`
+- `beacon-hooks` when hook integrations are enabled
+- `beacon-otelcol`
+- launchd plist templates
+- Wazuh content pack files
+
+The package should run `beacon endpoint install --no-start` in a
+postinstall script, then bootstrap the launchd service once files and configs
+are present.
+
+Release gates:
+
+- package signature verified with `pkgutil --check-signature`
+- notarization accepted by Apple
+- install/uninstall tested on a clean macOS runner or VM
+- Wazuh validation event successfully written after install
+
diff --git a/packaging/macos/test-endpoint-scripts.sh b/packaging/macos/test-endpoint-scripts.sh
new file mode 100644
index 00000000..9c5a81b4
--- /dev/null
+++ b/packaging/macos/test-endpoint-scripts.sh
@@ -0,0 +1,62 @@
+#!/bin/sh
+set -eu
+
+ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
+INSTALL_SCRIPT="$ROOT_DIR/packaging/macos/install-endpoint.sh"
+UNINSTALL_SCRIPT="$ROOT_DIR/packaging/macos/uninstall-endpoint.sh"
+TMP_DIR="$(mktemp -d)"
+trap 'rm -rf "$TMP_DIR"' EXIT INT TERM
+
+sh -n "$INSTALL_SCRIPT"
+sh -n "$UNINSTALL_SCRIPT"
+
+STUB_BIN="$TMP_DIR/beacon-stub"
+STUB_LOG="$TMP_DIR/argv.log"
+cat >"$STUB_BIN" <<'STUB'
+#!/bin/sh
+printf '%s\n' "$*" > "$STUB_LOG"
+STUB
+chmod +x "$STUB_BIN"
+
+BEACON_BIN="$STUB_BIN" \
+BEACON_ENDPOINT_HARNESSES="claude,codex,cursor" \
+BEACON_OTLP_GRPC_PORT="5317" \
+BEACON_OTLP_HTTP_PORT="5318" \
+STUB_LOG="$STUB_LOG" \
+"$INSTALL_SCRIPT"
+
+INSTALL_ARGS="$(cat "$STUB_LOG")"
+case "$INSTALL_ARGS" in
+ "endpoint install --harness claude,codex,cursor --otlp-grpc-port 5317 --otlp-http-port 5318") ;;
+ *)
+ echo "unexpected install args: $INSTALL_ARGS" >&2
+ exit 1
+ ;;
+esac
+
+BEACON_BIN="$STUB_BIN" \
+BEACON_KEEP_LOGS="1" \
+STUB_LOG="$STUB_LOG" \
+"$UNINSTALL_SCRIPT"
+
+UNINSTALL_ARGS="$(cat "$STUB_LOG")"
+case "$UNINSTALL_ARGS" in
+ "endpoint uninstall --keep-logs") ;;
+ *)
+ echo "unexpected uninstall args with keep logs: $UNINSTALL_ARGS" >&2
+ exit 1
+ ;;
+esac
+
+BEACON_BIN="$STUB_BIN" \
+STUB_LOG="$STUB_LOG" \
+"$UNINSTALL_SCRIPT"
+
+UNINSTALL_ARGS="$(cat "$STUB_LOG")"
+case "$UNINSTALL_ARGS" in
+ "endpoint uninstall") ;;
+ *)
+ echo "unexpected uninstall args without keep logs: $UNINSTALL_ARGS" >&2
+ exit 1
+ ;;
+esac
diff --git a/packaging/macos/uninstall-endpoint.sh b/packaging/macos/uninstall-endpoint.sh
new file mode 100755
index 00000000..cbbb48cb
--- /dev/null
+++ b/packaging/macos/uninstall-endpoint.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+set -eu
+
+BEACON_BIN="${BEACON_BIN:-beacon}"
+KEEP_LOGS_FLAG=""
+
+if [ "${BEACON_KEEP_LOGS:-0}" = "1" ]; then
+ KEEP_LOGS_FLAG="--keep-logs"
+fi
+
+exec "$BEACON_BIN" endpoint uninstall $KEEP_LOGS_FLAG
+