Skip to content

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

add factory hooks refactor

Justin D'Souza9c877e3e21cb
diff --git a/README.md b/README.md
index 573c9ebd..e1e42509 100644
--- a/README.md
+++ b/README.md
@@ -120,10 +120,10 @@ Beacon can currently:
Codex CLI, Factory Droid, Cursor, and Claude Cowork.
- **Local OTLP setup:** configure Claude Code, Codex CLI, and Factory Droid to
export OpenTelemetry to a localhost collector.
-- **Cursor hooks:** install Cursor hooks that emit local endpoint events for
+- **Cursor and Factory hooks:** install hooks that emit local endpoint events for
sessions, prompt submission, tool use, command execution, MCP-like tool
- activity, approval decisions, and file edits where Cursor exposes those hook
- payloads.
+ activity, approval decisions, and file edits where each runtime exposes those
+ hook payloads.
- **Collector export:** convert OTLP logs, traces, metrics, and resource
attributes into Beacon endpoint JSONL with the `beaconjson` collector exporter,
and optionally forward the same OTLP signals to Splunk HEC.
@@ -215,13 +215,14 @@ beacon endpoint install
beacon endpoint status
```
-The normal CLI flow uses per-user endpoint paths by default. Cursor hooks,
-Claude Code OTLP, Codex OTLP, and Factory Droid OTLP metrics can all write to
-the same user runtime log: `~/.beacon/endpoint/logs/runtime.jsonl`. Use
-`--system` only for root-managed package or MDM deployments.
+The normal CLI flow uses per-user endpoint paths by default. Claude Code and
+Codex export OTLP to the local collector, and Cursor/Factory hooks write direct
+JSONL events. When installed from the same endpoint config, they all write to the
+same user runtime log: `~/.beacon/endpoint/logs/runtime.jsonl`. Use `--system`
+only for root-managed package or MDM deployments.
-Factory Droid exports OTLP metrics over HTTP from its launch environment.
-For local testing, set the Factory OTEL endpoint before launching `droid`:
+Factory Droid OTLP metrics are managed through Droid's launch environment. For
+local testing, set the Factory OTEL endpoint before launching `droid`:
```bash
export OTEL_TELEMETRY_ENDPOINT="http://127.0.0.1:4318"
@@ -275,14 +276,24 @@ sh packaging/macos/smoke-endpoint.sh
## Optional Integrations
-### Cursor Hooks
+### Cursor And Factory Hooks
```bash
beacon endpoint hooks install --harness cursor
+beacon endpoint hooks install --harness factory
```
-See [Cursor Hooks](https://docs.asymptotelabs.ai/cli/hooks) for install, status,
-and uninstall guidance.
+Cursor and Factory hooks are opt-in user/project integrations for richer local
+telemetry than OTLP metrics alone. Cursor hooks are configured through
+`.cursor/hooks.json` and Factory hooks are configured through
+`.factory/settings.json`. Both commands embed the configured endpoint log path
+and content-retention config in the hook command, so install or repair the
+endpoint config first when you want all runtime telemetry in the same dashboard
+log. Restart Cursor/Droid after installing hooks so new sessions pick up the
+settings. Factory hooks include `UserPromptSubmit` for prompt telemetry plus
+session, tool/file, stop, and session-end events. See
+[Cursor Hooks](https://docs.asymptotelabs.ai/cli/hooks) for install, status, and
+uninstall guidance.
### Claude Cowork
@@ -377,12 +388,12 @@ beacon endpoint integrations claude-cowork validate --since 10m
beacon endpoint uninstall --keep-logs
```
-- `beacon endpoint install`: configure the endpoint agent, Collector service, and Claude/Codex/Factory telemetry.
+- `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 dashboard`: run a localhost-only dashboard over the runtime JSONL log.
-- `beacon endpoint hooks`: install, check, or remove hook-based integrations such as Cursor.
+- `beacon endpoint hooks`: install, check, or remove hook-based integrations such as Cursor and Factory.
- `beacon endpoint integrations claude-cowork`: set up 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.
diff --git a/cli/beacon-hooks/cmd/post_tool_test.go b/cli/beacon-hooks/cmd/post_tool_test.go
index 48fb99d4..660860d7 100644
--- a/cli/beacon-hooks/cmd/post_tool_test.go
+++ b/cli/beacon-hooks/cmd/post_tool_test.go
@@ -1,6 +1,7 @@
package cmd
import (
+ "path/filepath"
"testing"
)
@@ -22,6 +23,13 @@ func TestIsFileEditTool(t *testing.T) {
{"copilot write tool", "copilot", "copilot_createFile", true},
{"copilot patch tool", "copilot", "apply_patch", true},
{"copilot read (not edit)", "copilot", "readFile", false},
+
+ // Factory tools
+ {"factory Write", "factory", "Write", true},
+ {"factory Edit", "factory", "Edit", true},
+ {"factory MultiEdit", "factory", "MultiEdit", true},
+ {"factory Create", "factory", "Create", true},
+ {"factory Read (not edit)", "factory", "Read", false},
}
for _, tt := range tests {
@@ -34,6 +42,50 @@ func TestIsFileEditTool(t *testing.T) {
}
}
+func TestRunPostToolEmitsFactoryFileModifiedEvent(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "factory"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+
+ out := runHookWithInput(t, runPostTool, map[string]interface{}{
+ "session_id": "factory-session",
+ "cwd": "/repo",
+ "model": "opus",
+ "tool_name": "Edit",
+ "tool_input": map[string]interface{}{
+ "file_path": "/repo/main.go",
+ "old_str": "old",
+ "new_str": "new token=factory-secret",
+ },
+ })
+ if len(out) != 0 {
+ t.Fatalf("post-tool response = %#v, want empty response", out)
+ }
+
+ event := lastEndpointEvent(t, logPath)
+ if got := event["message"]; got != "File edit observed" {
+ t.Fatalf("message = %q, want file edit", got)
+ }
+ if harness := event["harness"].(map[string]interface{}); harness["name"] != "factory" {
+ t.Fatalf("harness = %#v, want factory", harness)
+ }
+ file := event["file"].(map[string]interface{})
+ if file["path"] != "/repo/main.go" || file["operation"] != "modify" {
+ t.Fatalf("file = %#v, want main.go modify", file)
+ }
+ if _, ok := file["diff_hash"]; !ok {
+ t.Fatalf("file diff_hash missing: %#v", file)
+ }
+ if diff, _ := file["diff"].(string); diff == "" || diff == "new token=factory-secret" {
+ t.Fatalf("expected redacted diff content, got %q", diff)
+ }
+ session := event["session"].(map[string]interface{})
+ if session["id"] != "factory-session" {
+ t.Fatalf("session = %#v, want factory-session", session)
+ }
+}
+
func TestResolveToolInput(t *testing.T) {
tests := []struct {
name string
diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.go
index a68bda83..0013d6f0 100644
--- a/cli/beacon-hooks/cmd/pre_tool_test.go
+++ b/cli/beacon-hooks/cmd/pre_tool_test.go
@@ -55,6 +55,42 @@ func TestRunPromptSubmitUsesCursorResponse(t *testing.T) {
}
}
+func TestRunPromptSubmitEmitsFactoryPromptEvent(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "factory"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("BEACON_CONTENT_RETENTION", "full")
+
+ out := runHookWithInput(t, runPromptSubmit, map[string]interface{}{
+ "session_id": "factory-session",
+ "transcript_path": "/tmp/factory-session.jsonl",
+ "cwd": "/repo",
+ "hook_event_name": "UserPromptSubmit",
+ "permission_mode": "off",
+ "prompt": "summarize token=prompt-secret",
+ })
+ if len(out) != 0 {
+ t.Fatalf("factory prompt response = %#v, want empty response", out)
+ }
+
+ event := lastEndpointEvent(t, logPath)
+ if got := event["message"]; got != "Prompt submitted to agent" {
+ t.Fatalf("message = %q, want prompt submitted", got)
+ }
+ harness := event["harness"].(map[string]interface{})
+ if harness["name"] != "factory" {
+ t.Fatalf("harness = %#v, want factory", harness)
+ }
+ if action := event["event"].(map[string]interface{})["action"]; action != "prompt.submitted" {
+ t.Fatalf("event.action = %q, want prompt.submitted", action)
+ }
+ prompt := event["prompt"].(map[string]interface{})
+ if got := prompt["text"]; got != "summarize token=[REDACTED]" {
+ t.Fatalf("prompt.text = %q, want redacted prompt", got)
+ }
+}
+
func TestRunPromptSubmitEmitsTypedPromptForFullRetention(t *testing.T) {
setupHookConfigDirs(t)
platformFlag = "cursor"
diff --git a/cli/beacon-hooks/cmd/stop_test.go b/cli/beacon-hooks/cmd/stop_test.go
index 7f642a2a..ca4aa25f 100644
--- a/cli/beacon-hooks/cmd/stop_test.go
+++ b/cli/beacon-hooks/cmd/stop_test.go
@@ -15,6 +15,7 @@ func TestPlatformToTranscriptName(t *testing.T) {
{"claude", "claude_code"},
{"copilot", "copilot"},
{"cursor", "cursor"},
+ {"factory", "factory"},
{"unknown", "claude_code"},
}
@@ -28,6 +29,30 @@ func TestPlatformToTranscriptName(t *testing.T) {
}
}
+func TestExtractMessagesFromFactoryTranscript(t *testing.T) {
+ tmpDir := t.TempDir()
+ transcriptPath := filepath.Join(tmpDir, "factory.jsonl")
+ content := `{"type":"message","message":{"role":"user","content":[{"type":"text","text":"Please edit the file"}]}}
+{"type":"message","message":{"role":"assistant","content":[{"type":"tool_use","name":"Edit"}]}}
+{"type":"message","message":{"role":"user","content":[{"type":"tool_result","content":"ok"}]}}
+{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"Done editing."}]}}
+`
+ if err := os.WriteFile(transcriptPath, []byte(content), 0644); err != nil {
+ t.Fatalf("write transcript: %v", err)
+ }
+
+ messages := extractMessagesFromFactoryTranscript(transcriptPath)
+ if len(messages) != 2 {
+ t.Fatalf("expected 2 text messages, got %d: %#v", len(messages), messages)
+ }
+ if messages[0]["role"] != "user" || messages[0]["content"] != "Please edit the file" {
+ t.Fatalf("unexpected first message: %#v", messages[0])
+ }
+ if messages[1]["role"] != "assistant" || messages[1]["content"] != "Done editing." {
+ t.Fatalf("unexpected second message: %#v", messages[1])
+ }
+}
+
func TestExtractMessagesFromCursorTranscript(t *testing.T) {
// Create a temp transcript file matching Cursor's format
tmpDir := t.TempDir()
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index 023d7855..91991ac2 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -335,6 +335,16 @@ func runEndpointHooksInstall(cmd *cobra.Command, args []string) error {
return err
}
fmt.Printf("Cursor hooks installed: %s\n", status.HooksJSONPath)
+ case "factory", "droid":
+ status, err := endpointhooks.InstallFactory(endpointhooks.FactoryOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Factory hooks installed: %s\n", status.SettingsPath)
case "":
default:
return fmt.Errorf("unsupported hook harness %q", name)
@@ -357,6 +367,16 @@ func runEndpointHooksUninstall(cmd *cobra.Command, args []string) error {
return err
}
fmt.Println(status.Message)
+ case "factory", "droid":
+ status, err := endpointhooks.UninstallFactory(endpointhooks.FactoryOptions{
+ 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)
@@ -367,16 +387,41 @@ func runEndpointHooksUninstall(cmd *cobra.Command, args []string) error {
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,
- })
+ statuses := map[string]interface{}{}
+ for _, name := range splitCSV(endpointOpts.hookHarnesses) {
+ switch strings.TrimSpace(name) {
+ case "cursor":
+ statuses["cursor"] = endpointhooks.CursorHookStatus(endpointhooks.CursorOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ case "factory", "droid":
+ statuses["factory"] = endpointhooks.FactoryHookStatus(endpointhooks.FactoryOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ case "":
+ default:
+ return fmt.Errorf("unsupported hook harness %q", name)
+ }
+ }
if endpointOpts.jsonOutput {
- return json.NewEncoder(os.Stdout).Encode(status)
+ return json.NewEncoder(os.Stdout).Encode(statuses)
+ }
+ for _, name := range splitCSV(endpointOpts.hookHarnesses) {
+ switch strings.TrimSpace(name) {
+ case "cursor":
+ status := statuses["cursor"].(endpointhooks.CursorStatus)
+ fmt.Printf("Cursor hooks: installed=%t path=%s\n", status.Installed, status.HooksJSONPath)
+ fmt.Println(status.Message)
+ case "factory", "droid":
+ status := statuses["factory"].(endpointhooks.FactoryStatus)
+ fmt.Printf("Factory hooks: installed=%t path=%s\n", status.Installed, status.SettingsPath)
+ fmt.Println(status.Message)
+ }
}
- fmt.Printf("Cursor hooks: installed=%t path=%s\n", status.Installed, status.HooksJSONPath)
- fmt.Println(status.Message)
return nil
}
diff --git a/cli/beacon/internal/endpoint/dashboard/events.go b/cli/beacon/internal/endpoint/dashboard/events.go
index d303080e..f90667cb 100644
--- a/cli/beacon/internal/endpoint/dashboard/events.go
+++ b/cli/beacon/internal/endpoint/dashboard/events.go
@@ -86,9 +86,7 @@ func ReadEvents(path string, query EventQuery) (EventResult, error) {
result.MalformedLines++
continue
}
- if event.Event.Category == "" {
- event.Event.Category = inferEventCategory(event.Event.Action)
- }
+ normalizeDashboardEvent(&event)
parsed, _ := time.Parse(time.RFC3339, event.Timestamp)
record := EventRecord{
ID: fmt.Sprintf("line-%d", lineNo),
@@ -150,9 +148,7 @@ func FindEvent(path, id string) (EventRecord, bool, error) {
if err := json.Unmarshal(line, &event); err != nil {
return EventRecord{}, false, nil
}
- if event.Event.Category == "" {
- event.Event.Category = inferEventCategory(event.Event.Action)
- }
+ normalizeDashboardEvent(&event)
parsed, _ := time.Parse(time.RFC3339, event.Timestamp)
return EventRecord{
ID: id,
@@ -169,6 +165,37 @@ func FindEvent(path, id string) (EventRecord, bool, error) {
return EventRecord{}, false, nil
}
+func normalizeDashboardEvent(event *schema.Event) {
+ metricName := metricEventName(event)
+ if event.Event.Category == "" && metricName != "" {
+ event.Event.Category = "metric"
+ }
+ if event.Event.Category == "" {
+ event.Event.Category = inferEventCategory(event.Event.Action)
+ }
+ if event.Event.Category == "metric" && (event.Event.Action == "" || event.Event.Action == "metric.observed") {
+ event.Event.Action = metricName
+ if event.Event.Action == "" {
+ event.Event.Action = "metric.observed"
+ }
+ }
+}
+
+func metricEventName(event *schema.Event) string {
+ if event == nil {
+ return ""
+ }
+ if event.Raw != nil {
+ if value, ok := event.Raw["metric_name"].(string); ok {
+ return strings.TrimSpace(value)
+ }
+ }
+ if event.Event.Category == "metric" {
+ return strings.TrimSpace(event.Message)
+ }
+ return ""
+}
+
func normalizeLimit(limit int) int {
if limit <= 0 {
return defaultEventLimit
diff --git a/cli/beacon/internal/endpoint/dashboard/events_test.go b/cli/beacon/internal/endpoint/dashboard/events_test.go
index 80cbe59f..dec8639b 100644
--- a/cli/beacon/internal/endpoint/dashboard/events_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/events_test.go
@@ -51,6 +51,43 @@ func TestReadEventsInfersMissingCategory(t *testing.T) {
}
}
+func TestReadEventsNormalizesMetricWithMissingAction(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := testSchemaEvent("2026-05-13T01:00:00Z", "cli", "", "metric", "")
+ event.Message = "droid.hook.invocations"
+ writeTestLog(t, path, marshalEvents(t, event)...)
+
+ result, err := ReadEvents(path, EventQuery{Limit: 10})
+ if err != nil {
+ t.Fatalf("ReadEvents returned error: %v", err)
+ }
+ if len(result.Events) != 1 {
+ t.Fatalf("events length = %d, want 1", len(result.Events))
+ }
+ if got := result.Events[0].Event.Event.Action; got != "droid.hook.invocations" {
+ t.Fatalf("Action = %q, want droid.hook.invocations", got)
+ }
+}
+
+func TestReadEventsPromotesRawMetricName(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := testSchemaEvent("2026-05-13T01:00:00Z", "cli", "metric.observed", "metric", "")
+ event.Message = "fallback.metric"
+ event.Raw = map[string]interface{}{"metric_name": "droid.tool.execution_time"}
+ writeTestLog(t, path, marshalEvents(t, event)...)
+
+ result, err := ReadEvents(path, EventQuery{Limit: 10})
+ if err != nil {
+ t.Fatalf("ReadEvents returned error: %v", err)
+ }
+ if len(result.Events) != 1 {
+ t.Fatalf("events length = %d, want 1", len(result.Events))
+ }
+ if got := result.Events[0].Event.Event.Action; got != "droid.tool.execution_time" {
+ t.Fatalf("Action = %q, want droid.tool.execution_time", got)
+ }
+}
+
func TestBuildSummaryAggregatesSignals(t *testing.T) {
result := EventResult{
TotalMatched: 4,
diff --git a/cli/beacon/internal/endpoint/dashboard/static/app.js b/cli/beacon/internal/endpoint/dashboard/static/app.js
index 20738fdc..35c49e5b 100644
--- a/cli/beacon/internal/endpoint/dashboard/static/app.js
+++ b/cli/beacon/internal/endpoint/dashboard/static/app.js
@@ -257,13 +257,24 @@ function signalCell(record) {
const info = event.event || {};
const harness = event.harness || {};
const parts = [
- `<strong>${escapeHTML(info.action || "unknown")}</strong>`,
+ `<strong>${escapeHTML(signalAction(record))}</strong>`,
`<span class="muted">${escapeHTML(info.category || "uncategorized")} · ${escapeHTML(harness.name || "unknown")}</span>`,
record.wazuh_level ? `<span class="muted">Wazuh level ${escapeHTML(record.wazuh_level)}</span>` : "",
].filter(Boolean);
return parts.join("<br />");
}
+function signalAction(record) {
+ const event = record.event || {};
+ const info = event.event || {};
+ if (info.category === "metric") return metricName(event) || info.action || "metric.observed";
+ return info.action || "unknown";
+}
+
+function metricName(event) {
+ return event.raw?.metric_name || event.message || "";
+}
+
function primaryArtifact(event) {
if (event.prompt?.text) return event.prompt.text;
if (event.command?.command) return event.command.command;
@@ -272,7 +283,7 @@ function primaryArtifact(event) {
if (event.tool?.name || event.tool?.command) return [event.tool.name, event.tool.command].filter(Boolean).join(" ");
if (event.approval?.decision || event.approval?.reason) return [event.approval.decision, event.approval.reason].filter(Boolean).join(": ");
if (event.policy?.decision || event.policy?.name) return [event.policy.decision, event.policy.name].filter(Boolean).join(": ");
- if (event.raw?.metric_name) return event.raw.metric_name;
+ if (event.event?.category === "metric") return metricName(event);
return event.model || event.branch || "";
}
@@ -293,7 +304,7 @@ function detailSummary(record) {
const event = record.event || {};
const info = event.event || {};
const rows = [
- ["Action", info.action],
+ ["Action", signalAction(record)],
["Category", info.category],
["Severity", event.severity],
["Wazuh level", record.wazuh_level || ""],
diff --git a/cli/beacon/internal/endpoint/hooks/cursor.go b/cli/beacon/internal/endpoint/hooks/cursor.go
index 537b4e7c..dc33ac20 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor.go
@@ -5,10 +5,6 @@ import (
"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
@@ -42,78 +38,45 @@ type CursorStatus struct {
Message string `json:"message,omitempty"`
}
+var cursorRuntime = hookRuntime{
+ displayName: "Cursor",
+ configPath: cursorHooksJSONPath,
+ install: installCursorHooksJSON,
+ uninstall: removeEndpointHooks,
+ isInstalled: isCursorInstalledAt,
+}
+
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)
+ status, err := installRuntimeHooks(cursorRuntime, RuntimeOptions(opts))
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, endpointconfig.ConfigPath(opts.UserMode)); err != nil {
- return CursorStatus{}, err
- }
- return CursorStatus{Installed: true, BinaryPath: binaryPath, HooksJSONPath: hooksPath, Message: "Cursor endpoint hooks installed"}, nil
+ return cursorStatusFromRuntime(status), nil
}
func UninstallCursor(opts CursorOptions) (CursorStatus, error) {
- targetDir, err := cursorTargetDir(opts.Level)
+ status, err := uninstallRuntimeHooks(cursorRuntime, RuntimeOptions(opts))
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
+ return cursorStatusFromRuntime(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
+ return cursorStatusFromRuntime(runtimeHookStatus(cursorRuntime, RuntimeOptions(opts)))
}
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 isRuntimeInstalled(cursorRuntime, RuntimeOptions(opts))
+}
+
+func cursorStatusFromRuntime(status runtimeStatus) CursorStatus {
+ return CursorStatus{
+ Installed: status.Installed,
+ BinaryPath: status.BinaryPath,
+ HooksJSONPath: status.ConfigPath,
+ Message: status.Message,
}
- return strings.Contains(string(data), "BEACON_ENDPOINT_MODE=1") && strings.Contains(string(data), "beacon-hooks")
}
func installCursorHooksJSON(path, binaryPath, logPath, configPath string) error {
@@ -121,7 +84,7 @@ func installCursorHooksJSON(path, binaryPath, logPath, configPath string) error
if err != nil {
return err
}
- commandPrefix := fmt.Sprintf("BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG=%s BEACON_ENDPOINT_CONFIG=%s %s --platform cursor", shellQuote(logPath), shellQuote(configPath), shellQuote(binaryPath))
+ commandPrefix := endpointCommandPrefix("cursor", binaryPath, logPath, configPath)
endpointHooks := map[string]HookRef{
"sessionStart": {Command: commandPrefix + " session-start"},
"beforeSubmitPrompt": {Command: commandPrefix + " prompt-submit", Timeout: 30},
@@ -146,7 +109,11 @@ func readHooksJSON(path string) (HooksJSON, error) {
var hooksJSON HooksJSON
data, err := os.ReadFile(path)
if err == nil {
- _ = json.Unmarshal(data, &hooksJSON)
+ if err := json.Unmarshal(data, &hooksJSON); err != nil {
+ return HooksJSON{}, err
+ }
+ } else if !os.IsNotExist(err) {
+ return HooksJSON{}, err
}
if hooksJSON.Version == 0 {
hooksJSON.Version = 1
@@ -209,24 +176,34 @@ func removeEndpointHooks(path string) (bool, error) {
}
func isEndpointHook(command string) bool {
- return strings.Contains(command, "BEACON_ENDPOINT_MODE=1") || strings.Contains(command, "beacon-hooks")
+ return isEndpointHookCommand(command, "cursor")
}
-func writeEndpointHookBinary(userMode bool) (string, error) {
- path, err := endpointHookBinaryPath(userMode)
+func isCursorInstalledAt(path string) bool {
+ data, err := os.ReadFile(path)
if err != nil {
- return "", err
+ return false
}
- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
- return "", err
+ var hooksJSON HooksJSON
+ if err := json.Unmarshal(data, &hooksJSON); err != nil {
+ return false
}
- _ = os.Remove(path)
- return path, os.WriteFile(path, embedded.HooksBinary, 0755)
+ for _, refs := range hooksJSON.Hooks {
+ for _, ref := range refs {
+ if isEndpointHook(ref.Command) {
+ return true
+ }
+ }
+ }
+ return false
}
-func endpointHookBinaryPath(userMode bool) (string, error) {
- base := endpointconfig.BaseDir(userMode)
- return filepath.Join(base, "hooks", embedded.GetBinaryName()), nil
+func cursorHooksJSONPath(level Level) (string, error) {
+ targetDir, err := cursorTargetDir(level)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(targetDir, "hooks.json"), nil
}
func cursorTargetDir(level Level) (string, error) {
@@ -247,17 +224,3 @@ func cursorTargetDir(level Level) (string, error) {
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
index bf8b843e..879fe834 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor_test.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor_test.go
@@ -5,6 +5,8 @@ import (
"path/filepath"
"strings"
"testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
)
func TestInstallCursorHooksJSONPreservesNonBeaconHooks(t *testing.T) {
@@ -74,21 +76,14 @@ func TestCursorTargetDirProjectLevel(t *testing.T) {
}
}
-func TestReadHooksJSONTreatsCorruptJSONAsEmptyConfig(t *testing.T) {
+func TestReadHooksJSONReturnsCorruptJSONError(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)
+ if _, err := readHooksJSON(path); err == nil {
+ t.Fatal("expected corrupt hooks.json error")
}
}
@@ -139,6 +134,25 @@ func TestInstallCursorHooksJSONReplacesExistingBeaconHook(t *testing.T) {
}
}
+func TestInstallCursorHooksJSONDoesNotReplaceUserCommandWithBeaconEnvOnly(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"sessionStart":[{"command":"BEACON_ENDPOINT_MODE=1 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", "/tmp/config.json"); 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), "BEACON_ENDPOINT_MODE=1 echo keep") {
+ t.Fatalf("user hook with Beacon-like env token was removed: %s", string(data))
+ }
+}
+
func TestInstallCursorWithUnknownLevelFailsBeforeWritingTarget(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
@@ -150,3 +164,12 @@ func TestInstallCursorWithUnknownLevelFailsBeforeWritingTarget(t *testing.T) {
t.Fatalf("status should not be installed on error: %#v", status)
}
}
+
+func TestEndpointConfigPathForHookUsesSystemConfigForSystemLog(t *testing.T) {
+ if got := endpointConfigPathForHook("/var/log/beacon-agent/runtime.jsonl", true); got != endpointconfig.ConfigPath(false) {
+ t.Fatalf("system log config path = %q, want system endpoint config", got)
+ }
+ if got := endpointConfigPathForHook("/tmp/runtime.jsonl", true); got != endpointconfig.ConfigPath(true) {
+ t.Fatalf("user log config path = %q, want user endpoint config", got)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/factory.go b/cli/beacon/internal/endpoint/hooks/factory.go
new file mode 100644
index 00000000..2ef05cf8
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/factory.go
@@ -0,0 +1,226 @@
+package hooks
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+type FactoryOptions struct {
+ Level Level
+ LogPath string
+ UserMode bool
+}
+
+type FactoryStatus struct {
+ Installed bool `json:"installed"`
+ BinaryPath string `json:"binary_path,omitempty"`
+ SettingsPath string `json:"settings_path,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+type factoryHookGroup struct {
+ Matcher string `json:"matcher,omitempty"`
+ Hooks []factoryHookRef `json:"hooks"`
+}
+
+type factoryHookRef struct {
+ Type string `json:"type"`
+ Command string `json:"command"`
+ Timeout int `json:"timeout,omitempty"`
+}
+
+type factorySettings struct {
+ values map[string]json.RawMessage
+ hooks map[string][]factoryHookGroup
+}
+
+var factoryRuntime = hookRuntime{
+ displayName: "Factory",
+ configPath: factorySettingsPath,
+ install: installFactorySettings,
+ uninstall: removeFactoryEndpointHooks,
+ isInstalled: isFactoryInstalledAt,
+}
+
+func InstallFactory(opts FactoryOptions) (FactoryStatus, error) {
+ status, err := installRuntimeHooks(factoryRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return FactoryStatus{}, err
+ }
+ return factoryStatusFromRuntime(status), nil
+}
+
+func UninstallFactory(opts FactoryOptions) (FactoryStatus, error) {
+ status, err := uninstallRuntimeHooks(factoryRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return FactoryStatus{}, err
+ }
+ return factoryStatusFromRuntime(status), nil
+}
+
+func FactoryHookStatus(opts FactoryOptions) FactoryStatus {
+ return factoryStatusFromRuntime(runtimeHookStatus(factoryRuntime, RuntimeOptions(opts)))
+}
+
+func IsFactoryInstalled(opts FactoryOptions) bool {
+ return isRuntimeInstalled(factoryRuntime, RuntimeOptions(opts))
+}
+
+func factoryStatusFromRuntime(status runtimeStatus) FactoryStatus {
+ return FactoryStatus{
+ Installed: status.Installed,
+ BinaryPath: status.BinaryPath,
+ SettingsPath: status.ConfigPath,
+ Message: status.Message,
+ }
+}
+
+func installFactorySettings(path, binaryPath, logPath, configPath string) error {
+ settings, err := readFactorySettings(path)
+ if err != nil {
+ return err
+ }
+ prefix := endpointCommandPrefix("factory", binaryPath, logPath, configPath)
+ endpointHooks := map[string]factoryHookGroup{
+ "SessionStart": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " session-start"}}},
+ "UserPromptSubmit": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " prompt-submit", Timeout: 30}}},
+ "PostToolUse": {Matcher: "Write|Edit|MultiEdit|Create", Hooks: []factoryHookRef{{Type: "command", Command: prefix + " post-tool"}}},
+ "Stop": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " stop", Timeout: 45}}},
+ "SessionEnd": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " session-end"}}},
+ }
+ for eventName, group := range endpointHooks {
+ settings.hooks[eventName] = mergeFactoryEndpointHook(settings.hooks[eventName], group)
+ }
+ data, err := settings.marshal()
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, data, 0600)
+}
+
+func readFactorySettings(path string) (factorySettings, error) {
+ settings := factorySettings{
+ values: map[string]json.RawMessage{},
+ hooks: map[string][]factoryHookGroup{},
+ }
+ data, err := os.ReadFile(path)
+ if err == nil {
+ if err := json.Unmarshal(data, &settings.values); err != nil {
+ return factorySettings{}, err
+ }
+ if rawHooks, ok := settings.values["hooks"]; ok {
+ if err := json.Unmarshal(rawHooks, &settings.hooks); err != nil {
+ return factorySettings{}, err
+ }
+ }
+ } else if !os.IsNotExist(err) {
+ return factorySettings{}, err
+ }
+ return settings, nil
+}
+
+func (settings factorySettings) marshal() ([]byte, error) {
+ out := make(map[string]json.RawMessage, len(settings.values)+1)
+ for key, value := range settings.values {
+ if key != "hooks" {
+ out[key] = value
+ }
+ }
+ if len(settings.hooks) > 0 {
+ data, err := json.Marshal(settings.hooks)
+ if err != nil {
+ return nil, err
+ }
+ out["hooks"] = data
+ }
+ return json.MarshalIndent(out, "", " ")
+}
+
+func mergeFactoryEndpointHook(existing []factoryHookGroup, group factoryHookGroup) []factoryHookGroup {
+ out := make([]factoryHookGroup, 0, len(existing)+1)
+ for _, item := range existing {
+ if !isFactoryEndpointHookGroup(item) {
+ out = append(out, item)
+ }
+ }
+ return append(out, group)
+}
+
+func removeFactoryEndpointHooks(path string) (bool, error) {
+ settings, err := readFactorySettings(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ changed := false
+ for eventName, groups := range settings.hooks {
+ filtered := groups[:0]
+ for _, group := range groups {
+ if isFactoryEndpointHookGroup(group) {
+ changed = true
+ continue
+ }
+ filtered = append(filtered, group)
+ }
+ if len(filtered) == 0 {
+ delete(settings.hooks, eventName)
+ } else {
+ settings.hooks[eventName] = filtered
+ }
+ }
+ if !changed {
+ return false, nil
+ }
+ out, err := settings.marshal()
+ if err != nil {
+ return false, err
+ }
+ return true, os.WriteFile(path, out, 0600)
+}
+
+func isFactoryEndpointHookGroup(group factoryHookGroup) bool {
+ for _, hook := range group.Hooks {
+ if isEndpointHookCommand(hook.Command, "factory") {
+ return true
+ }
+ }
+ return false
+}
+
+func isFactoryInstalledAt(path string) bool {
+ settings, err := readFactorySettings(path)
+ if err != nil {
+ return false
+ }
+ for _, groups := range settings.hooks {
+ for _, group := range groups {
+ if isFactoryEndpointHookGroup(group) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func factorySettingsPath(level Level) (string, error) {
+ switch level {
+ case "", LevelUser:
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".factory", "settings.json"), nil
+ case LevelProject:
+ cwd, err := os.Getwd()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(cwd, ".factory", "settings.json"), nil
+ default:
+ return "", fmt.Errorf("unknown hook level %q", level)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/factory_test.go b/cli/beacon/internal/endpoint/hooks/factory_test.go
new file mode 100644
index 00000000..d10793a3
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/factory_test.go
@@ -0,0 +1,179 @@
+package hooks
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestInstallFactorySettingsPreservesNonBeaconHooks(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ existing := `{"enabledPlugins":{"core@factory-plugins":true},"logoAnimation":"off","hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"}]}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := installFactorySettings(path, "/tmp/beacon hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installFactorySettings returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read settings: %v", err)
+ }
+ text := string(data)
+ for _, want := range []string{
+ "enabledPlugins",
+ "logoAnimation",
+ "echo keep",
+ "BEACON_ENDPOINT_MODE=1",
+ "BEACON_ENDPOINT_LOG='/tmp/runtime.jsonl'",
+ "BEACON_ENDPOINT_CONFIG='/tmp/config.json'",
+ "'/tmp/beacon hooks' --platform factory",
+ "SessionStart",
+ "UserPromptSubmit",
+ "prompt-submit",
+ "PostToolUse",
+ "Write|Edit|MultiEdit|Create",
+ "Stop",
+ "SessionEnd",
+ } {
+ if !strings.Contains(text, want) {
+ t.Fatalf("settings missing %q:\n%s", want, text)
+ }
+ }
+}
+
+func TestInstallFactorySettingsReplacesOldBeaconAndAsymptoteHooks(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ existing := `{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 old-beacon-hooks --platform factory post-tool"}]},{"hooks":[{"type":"command","command":"/tmp/asym-hooks --platform factory post-tool"}]},{"hooks":[{"type":"command","command":"echo keep"}]}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := installFactorySettings(path, "/tmp/new-beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installFactorySettings returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read settings: %v", err)
+ }
+ text := string(data)
+ if strings.Contains(text, "old-beacon-hooks") || strings.Contains(text, "asym-hooks") {
+ t.Fatalf("old endpoint hook was not replaced:\n%s", text)
+ }
+ if !strings.Contains(text, "echo keep") || !strings.Contains(text, "/tmp/new-beacon-hooks") {
+ t.Fatalf("expected preserved hook and new hook:\n%s", text)
+ }
+}
+
+func TestRemoveFactoryEndpointHooksPreservesOtherHooks(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ existing := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"}]},{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform factory session-start"}]}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ changed, err := removeFactoryEndpointHooks(path)
+ if err != nil {
+ t.Fatalf("removeFactoryEndpointHooks returned error: %v", err)
+ }
+ if !changed {
+ t.Fatal("expected endpoint hook removal")
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read settings: %v", err)
+ }
+ text := string(data)
+ if !strings.Contains(text, "echo keep") {
+ t.Fatalf("non-Beacon hook was not preserved:\n%s", text)
+ }
+ if strings.Contains(text, "BEACON_ENDPOINT_MODE=1") {
+ t.Fatalf("endpoint hook was not removed:\n%s", text)
+ }
+}
+
+func TestReadFactorySettingsReturnsCorruptJSONError(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ if err := os.WriteFile(path, []byte("{not json"), 0600); err != nil {
+ t.Fatalf("write corrupt settings: %v", err)
+ }
+
+ if _, err := readFactorySettings(path); err == nil {
+ t.Fatal("expected corrupt settings error")
+ }
+}
+
+func TestInstallFactorySettingsDoesNotReplaceUserCommandWithBeaconEnvOnly(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ existing := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 echo keep"}]}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := installFactorySettings(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installFactorySettings returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read settings: %v", err)
+ }
+ if !strings.Contains(string(data), "BEACON_ENDPOINT_MODE=1 echo keep") {
+ t.Fatalf("user hook with Beacon-like env token was removed:\n%s", string(data))
+ }
+}
+
+func TestFactorySettingsPathProjectLevel(t *testing.T) {
+ dir := t.TempDir()
+ t.Chdir(dir)
+
+ target, err := factorySettingsPath(LevelProject)
+ if err != nil {
+ t.Fatalf("factorySettingsPath returned error: %v", err)
+ }
+ if got, want := target, filepath.Join(dir, ".factory", "settings.json"); got != want {
+ t.Fatalf("project settings path = %q, want %q", got, want)
+ }
+}
+
+func TestFactoryHookStatusDetectsInstalled(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ path := filepath.Join(home, ".factory", "settings.json")
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(`{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform factory stop"}]}]}}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ status := FactoryHookStatus(FactoryOptions{Level: LevelUser, UserMode: true})
+ if !status.Installed {
+ t.Fatalf("FactoryHookStatus installed = false, status=%#v", status)
+ }
+ if status.SettingsPath != path {
+ t.Fatalf("SettingsPath = %q, want %q", status.SettingsPath, path)
+ }
+}
+
+func TestInstallFactoryUsesSystemConfigForSystemLog(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ status, err := InstallFactory(FactoryOptions{
+ Level: LevelUser,
+ LogPath: "/var/log/beacon-agent/runtime.jsonl",
+ UserMode: true,
+ })
+ if err != nil {
+ t.Fatalf("InstallFactory returned error: %v", err)
+ }
+ data, err := os.ReadFile(status.SettingsPath)
+ if err != nil {
+ t.Fatalf("read Factory settings: %v", err)
+ }
+ if !strings.Contains(string(data), "BEACON_ENDPOINT_CONFIG='/Library/Application Support/Beacon/Endpoint/config.json'") {
+ t.Fatalf("Factory hook did not use system config for system log:\n%s", string(data))
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/runtime.go b/cli/beacon/internal/endpoint/hooks/runtime.go
new file mode 100644
index 00000000..6bfa62d3
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/runtime.go
@@ -0,0 +1,164 @@
+package hooks
+
+import (
+ "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 RuntimeOptions struct {
+ Level Level
+ LogPath string
+ UserMode bool
+}
+
+type runtimeStatus struct {
+ Installed bool
+ BinaryPath string
+ ConfigPath string
+ Message string
+}
+
+type hookRuntime struct {
+ displayName string
+ configPath func(Level) (string, error)
+ install func(path, binaryPath, logPath, configPath string) error
+ uninstall func(path string) (bool, error)
+ isInstalled func(path string) bool
+}
+
+func installRuntimeHooks(runtime hookRuntime, opts RuntimeOptions) (runtimeStatus, error) {
+ if !embedded.HasEmbeddedBinary() {
+ return runtimeStatus{}, fmt.Errorf("no hooks binary embedded")
+ }
+ if opts.LogPath == "" {
+ opts.LogPath = defaultLogPath(opts.UserMode)
+ }
+ configPath, err := runtime.configPath(opts.Level)
+ if err != nil {
+ return runtimeStatus{}, err
+ }
+ if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ return runtimeStatus{}, err
+ }
+ binaryPath, err := writeEndpointHookBinary(opts.UserMode)
+ if err != nil {
+ return runtimeStatus{}, err
+ }
+ hookConfigPath := endpointConfigPathForHook(opts.LogPath, opts.UserMode)
+ if err := runtime.install(configPath, binaryPath, opts.LogPath, hookConfigPath); err != nil {
+ return runtimeStatus{}, err
+ }
+ return runtimeStatus{
+ Installed: true,
+ BinaryPath: binaryPath,
+ ConfigPath: configPath,
+ Message: fmt.Sprintf("%s endpoint hooks installed", runtime.displayName),
+ }, nil
+}
+
+func uninstallRuntimeHooks(runtime hookRuntime, opts RuntimeOptions) (runtimeStatus, error) {
+ configPath, err := runtime.configPath(opts.Level)
+ if err != nil {
+ return runtimeStatus{}, err
+ }
+ updated, err := runtime.uninstall(configPath)
+ if err != nil {
+ return runtimeStatus{}, err
+ }
+ status := runtimeStatus{
+ ConfigPath: configPath,
+ Message: fmt.Sprintf("%s endpoint hooks were not present", runtime.displayName),
+ }
+ if updated {
+ status.Message = fmt.Sprintf("%s endpoint hooks removed", runtime.displayName)
+ }
+ status.Installed = isRuntimeInstalled(runtime, opts)
+ return status, nil
+}
+
+func runtimeHookStatus(runtime hookRuntime, opts RuntimeOptions) runtimeStatus {
+ configPath, err := runtime.configPath(opts.Level)
+ if err != nil {
+ return runtimeStatus{Message: err.Error()}
+ }
+ status := runtimeStatus{ConfigPath: configPath}
+ status.Installed = isRuntimeInstalled(runtime, opts)
+ if status.Installed {
+ status.Message = fmt.Sprintf("%s endpoint hooks are installed", runtime.displayName)
+ } else {
+ status.Message = fmt.Sprintf("%s endpoint hooks are not installed", runtime.displayName)
+ }
+ if path, err := endpointHookBinaryPath(opts.UserMode); err == nil {
+ status.BinaryPath = path
+ }
+ return status
+}
+
+func isRuntimeInstalled(runtime hookRuntime, opts RuntimeOptions) bool {
+ configPath, err := runtime.configPath(opts.Level)
+ if err != nil {
+ return false
+ }
+ return runtime.isInstalled(configPath)
+}
+
+func endpointCommandPrefix(platform, binaryPath, logPath, configPath string) string {
+ return fmt.Sprintf("BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG=%s BEACON_ENDPOINT_CONFIG=%s %s --platform %s", shellQuote(logPath), shellQuote(configPath), shellQuote(binaryPath), platform)
+}
+
+func isEndpointHookCommand(command, platform string) bool {
+ hasPlatform := platform == "" || strings.Contains(command, "--platform "+platform)
+ hasBeaconBinary := strings.Contains(command, embedded.GetBinaryName())
+ hasLegacyBinary := strings.Contains(command, "asym-hooks")
+
+ if strings.Contains(command, "BEACON_ENDPOINT_MODE=1") && hasBeaconBinary {
+ return hasPlatform || !strings.Contains(command, "--platform ")
+ }
+ if hasBeaconBinary && !strings.Contains(command, "--platform ") {
+ return true
+ }
+ return hasLegacyBinary && hasPlatform
+}
+
+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 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 endpointConfigPathForHook(logPath string, userMode bool) string {
+ if strings.HasPrefix(logPath, "/var/log/") || strings.HasPrefix(logPath, "/Library/") {
+ return endpointconfig.ConfigPath(false)
+ }
+ return endpointconfig.ConfigPath(userMode)
+}
+
+func shellQuote(value string) string {
+ return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
+}
diff --git a/packaging/macos/README.md b/packaging/macos/README.md
index 0e3ba67d..232b80b7 100644
--- a/packaging/macos/README.md
+++ b/packaging/macos/README.md
@@ -112,13 +112,17 @@ Recommended rollout:
4. Scope repair/remediation to unhealthy devices.
5. Broaden deployment in stages after inventory and validation stay healthy.
-Cursor hook installation is separate from the base system package because Cursor
-configuration is per user. Run the Cursor hook helper only when an interactive
-console user is present.
-
-Factory Droid telemetry is also managed outside the base system package. Droid
-reads OTLP settings from its launch environment, so deploy the environment from
-a user-context MDM policy or another customer-owned launch policy:
+Cursor and Factory hook installation is separate from the base system package
+because both integrations write per-user or per-project runtime settings. Run
+hook helpers only when an interactive console user is present. Cursor hooks use
+`.cursor/hooks.json`; Factory hooks use `.factory/settings.json`; restart the
+runtime after installation so new sessions pick up the settings. Install hooks
+with the same endpoint log path as the collector when you want hook telemetry and
+OTLP telemetry to appear in one dashboard.
+
+Factory Droid OTLP metrics are also managed outside the base system package.
+Droid reads OTLP settings from its launch environment, so deploy the environment
+from a user-context MDM policy or another customer-owned launch policy:
```sh
export OTEL_TELEMETRY_ENDPOINT="http://127.0.0.1:4318"
@@ -129,6 +133,13 @@ effective Droid environment points at the local OTLP HTTP receiver. If
`OTEL_TELEMETRY_HEADERS` is needed, treat it as customer-managed secret material
and avoid storing it in Beacon defaults or package parameters.
+For richer Factory prompt/session/tool/file telemetry, install Beacon's Factory
+hooks in the logged-in user's context:
+
+```bash
+beacon endpoint hooks install --harness factory --level user --log-path /var/log/beacon-agent/runtime.jsonl
+```
+
## Jamf Pro
Upload the generated `.pkg` to Jamf Pro and create a Policy scoped to a pilot
@@ -166,7 +177,9 @@ tokens do not need to be entered as visible script parameters.
Use `/opt/beacon/jamf/scripts/repair.sh` as a remediation policy for Macs where
Extension Attributes report a stale or unhealthy install. Use
`/opt/beacon/jamf/scripts/install-cursor-hooks.sh` as a separate user-context
-policy for Cursor telemetry.
+policy for hook telemetry. Set `BEACON_HOOK_HARNESSES=cursor,factory` to install
+both supported hook integrations; the helper writes hook events to
+`/var/log/beacon-agent/runtime.jsonl` by default.
### Jamf Extension Attributes
@@ -290,6 +303,7 @@ removal remains under the MDM/package receipt lifecycle.
writable by the collector.
- No recent runtime events: confirm supported harnesses are configured and the
local OTLP ports are not in use by another process.
-- Cursor hooks are missing: run the Cursor hook helper while a non-root console
- user is logged in.
+- Cursor or Factory hooks are missing: run the hook helper while a non-root
+ console user is logged in, and confirm the helper uses the same runtime log
+ path as the endpoint collector.
diff --git a/packaging/macos/jamf/scripts/install-cursor-hooks.sh b/packaging/macos/jamf/scripts/install-cursor-hooks.sh
index 35f338c3..a141e7b2 100755
--- a/packaging/macos/jamf/scripts/install-cursor-hooks.sh
+++ b/packaging/macos/jamf/scripts/install-cursor-hooks.sh
@@ -4,6 +4,7 @@ set -eu
BEACON_BIN="${BEACON_BIN:-/opt/beacon/bin/beacon}"
HOOK_HARNESSES="${BEACON_HOOK_HARNESSES:-${4:-cursor}}"
HOOK_LEVEL="${BEACON_HOOK_LEVEL:-${5:-user}}"
+HOOK_LOG_PATH="${BEACON_HOOK_LOG_PATH:-${6:-/var/log/beacon-agent/runtime.jsonl}}"
CONSOLE_USER="$(stat -f %Su /dev/console 2>/dev/null || echo "")"
if [ -z "$CONSOLE_USER" ] || [ "$CONSOLE_USER" = "root" ] || [ "$CONSOLE_USER" = "loginwindow" ]; then
@@ -19,4 +20,5 @@ fi
exec sudo -u "$CONSOLE_USER" HOME="$HOME_DIR" "$BEACON_BIN" endpoint hooks install \
--harness "$HOOK_HARNESSES" \
- --level "$HOOK_LEVEL"
+ --level "$HOOK_LEVEL" \
+ --log-path "$HOOK_LOG_PATH"
diff --git a/packaging/macos/pkgbuild.md b/packaging/macos/pkgbuild.md
index 49680073..798a423d 100644
--- a/packaging/macos/pkgbuild.md
+++ b/packaging/macos/pkgbuild.md
@@ -9,10 +9,10 @@ installs:
- Fleet scripts and osquery policy/label examples
- Wazuh content pack files for admins that want to import examples/rules
-`beacon-hooks` is embedded in the `beacon` binary for Cursor hook installation.
-Do not configure Cursor hooks during the base package install; use the Jamf
-`install-cursor-hooks.sh` helper or an equivalent Fleet user-context script so
-the command runs in the target user's context.
+`beacon-hooks` is embedded in the `beacon` binary for Cursor and Factory hook
+installation. Do not configure hooks during the base package install; use the
+Jamf `install-cursor-hooks.sh` helper or an equivalent Fleet user-context script
+so the command runs in the target user's context.
## Build Inputs
diff --git a/packaging/macos/test-endpoint-scripts.sh b/packaging/macos/test-endpoint-scripts.sh
index 95491a66..264fc29c 100644
--- a/packaging/macos/test-endpoint-scripts.sh
+++ b/packaging/macos/test-endpoint-scripts.sh
@@ -65,6 +65,52 @@ case "$REPAIR_ARGS" in
;;
esac
+FAKE_BIN="$TMP_DIR/fake-bin"
+FAKE_HOME="$TMP_DIR/fake-home"
+mkdir -p "$FAKE_BIN" "$FAKE_HOME"
+cat >"$FAKE_BIN/stat" <<'STUB'
+#!/bin/sh
+printf 'alice\n'
+STUB
+cat >"$FAKE_BIN/dscl" <<'STUB'
+#!/bin/sh
+printf 'NFSHomeDirectory: %s\n' "$FAKE_HOME"
+STUB
+cat >"$FAKE_BIN/sudo" <<'STUB'
+#!/bin/sh
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ -u)
+ shift 2
+ ;;
+ *=*)
+ shift
+ ;;
+ *)
+ exec "$@"
+ ;;
+ esac
+done
+STUB
+chmod +x "$FAKE_BIN/stat" "$FAKE_BIN/dscl" "$FAKE_BIN/sudo"
+
+BEACON_BIN="$STUB_BIN" \
+PATH="$FAKE_BIN:$PATH" \
+FAKE_HOME="$FAKE_HOME" \
+BEACON_HOOK_HARNESSES="cursor,factory" \
+BEACON_HOOK_LEVEL="user" \
+STUB_LOG="$STUB_LOG" \
+"$ROOT_DIR/packaging/macos/jamf/scripts/install-cursor-hooks.sh"
+
+HOOK_ARGS="$(cat "$STUB_LOG")"
+case "$HOOK_ARGS" in
+ "endpoint hooks install --harness cursor,factory --level user --log-path /var/log/beacon-agent/runtime.jsonl") ;;
+ *)
+ echo "unexpected hook install args: $HOOK_ARGS" >&2
+ exit 1
+ ;;
+esac
+
BEACON_BIN="$STUB_BIN" \
STUB_LOG="$STUB_LOG" \
"$INSTALL_SCRIPT" _ _ _ "claude" "metadata" "6317" "6318" "/tmp/jamf-otelcol" "1" "https://jamf-splunk.example:8088/services/collector" "jamf-token" "jamf-index" "jamf-source" "jamf:sourcetype" "true" "/tmp/jamf-ca.pem"