Skip to content

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

fix(codex): resolve install, hooks and inventory paths through CODEX_HOME (#869)

kyle-elliott-asymptoteb3f9f29ebc18
diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.go
index 0c386d4d..0478d854 100644
--- a/cli/beacon/internal/endpoint/harness/harness.go
+++ b/cli/beacon/internal/endpoint/harness/harness.go
@@ -11,6 +11,7 @@ import (
"strings"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork"
"gopkg.in/yaml.v3"
@@ -140,7 +141,13 @@ func DiscoverCodex() Harness {
h := Harness{Name: "codex_cli", DisplayName: "Codex CLI", Capability: "otel_config"}
detectExecutable(&h, "codex")
home, _ := os.UserHomeDir()
- h.ConfigPath = filepath.Join(home, ".codex", "config.toml")
+ dir, err := codexsession.HomeDir(home)
+ if err != nil {
+ h.TelemetryStatus = TelemetryMissing
+ h.Message = "Codex home directory could not be resolved: " + err.Error()
+ return h
+ }
+ h.ConfigPath = filepath.Join(dir, "config.toml")
if fileExists(h.ConfigPath) {
status, msg := codexStatus(h.ConfigPath)
h.TelemetryStatus = status
@@ -426,7 +433,11 @@ func ConfigureCodex(opts ConfigureOptions) (string, error) {
if err != nil {
return "", err
}
- path := filepath.Join(home, ".codex", "config.toml")
+ dir, err := codexsession.HomeDir(home)
+ if err != nil {
+ return "", err
+ }
+ path := filepath.Join(dir, "config.toml")
var existing string
if data, err := os.ReadFile(path); err == nil {
existing = string(data)
diff --git a/cli/beacon/internal/endpoint/harness/harness_test.go b/cli/beacon/internal/endpoint/harness/harness_test.go
index 35fc09cd..d961f434 100644
--- a/cli/beacon/internal/endpoint/harness/harness_test.go
+++ b/cli/beacon/internal/endpoint/harness/harness_test.go
@@ -355,6 +355,59 @@ func TestConfigureCodexEnablesPromptLogging(t *testing.T) {
}
}
+// Codex reads config.toml from CODEX_HOME when it is set, so an install that wrote ~/.codex would
+// leave Codex without the exporter and discovery reporting a file Codex never reads.
+func TestCodexConfigFollowsCodexHome(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("PATH", t.TempDir())
+ codexHome := t.TempDir()
+ t.Setenv("CODEX_HOME", codexHome)
+ resolved, err := filepath.EvalSymlinks(codexHome)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := filepath.Join(resolved, "config.toml")
+
+ 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 != want {
+ t.Fatalf("ConfigureCodex path = %q, want %q", written, want)
+ }
+ if _, err := os.Stat(filepath.Join(home, ".codex")); !os.IsNotExist(err) {
+ t.Fatalf("ConfigureCodex touched ~/.codex with CODEX_HOME set: %v", err)
+ }
+ h := DiscoverCodex()
+ if h.ConfigPath != want || h.TelemetryStatus != TelemetryEnabled {
+ t.Fatalf("DiscoverCodex = path %q status %q, want %q enabled", h.ConfigPath, h.TelemetryStatus, want)
+ }
+}
+
+// Codex refuses to start when CODEX_HOME is not an existing directory, so Beacon must not quietly
+// configure ~/.codex instead, or create the directory and hide the mistake.
+func TestCodexConfigRefusesMissingCodexHome(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("PATH", t.TempDir())
+ missing := filepath.Join(home, "missing")
+ t.Setenv("CODEX_HOME", missing)
+
+ if _, err := ConfigureCodex(ConfigureOptions{Endpoint: "http://127.0.0.1:4317", UserMode: true}); err == nil {
+ t.Fatal("ConfigureCodex accepted a CODEX_HOME that does not exist")
+ }
+ for _, dir := range []string{missing, filepath.Join(home, ".codex")} {
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ t.Fatalf("ConfigureCodex created %s: %v", dir, err)
+ }
+ }
+ h := DiscoverCodex()
+ if h.TelemetryStatus != TelemetryMissing || !strings.Contains(h.Message, "CODEX_HOME") {
+ t.Fatalf("DiscoverCodex = status %q message %q, want missing naming CODEX_HOME", h.TelemetryStatus, h.Message)
+ }
+}
+
func TestDiscoverCodexDoesNotDetectConfigDirectoryOnly(t *testing.T) {
home := t.TempDir()
testenv.SetHome(t, home)
diff --git a/cli/beacon/internal/endpoint/hooks/codex.go b/cli/beacon/internal/endpoint/hooks/codex.go
index b13dc236..2881b31f 100644
--- a/cli/beacon/internal/endpoint/hooks/codex.go
+++ b/cli/beacon/internal/endpoint/hooks/codex.go
@@ -4,6 +4,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
)
type CodexOptions struct {
@@ -87,7 +89,11 @@ func codexHooksPath(level Level) (string, error) {
if err != nil {
return "", err
}
- return filepath.Join(home, ".codex", "hooks.json"), nil
+ dir, err := codexsession.HomeDir(home)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, "hooks.json"), nil
case LevelProject:
cwd, err := os.Getwd()
if err != nil {
diff --git a/cli/beacon/internal/endpoint/hooks/codex_test.go b/cli/beacon/internal/endpoint/hooks/codex_test.go
index e275e3e0..7cb59430 100644
--- a/cli/beacon/internal/endpoint/hooks/codex_test.go
+++ b/cli/beacon/internal/endpoint/hooks/codex_test.go
@@ -5,6 +5,8 @@ import (
"path/filepath"
"strings"
"testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
)
func TestInstallCodexHooksWritesSessionContextOnly(t *testing.T) {
@@ -72,3 +74,40 @@ func TestRemoveCodexEndpointHooksPreservesOtherHooks(t *testing.T) {
t.Fatalf("Codex endpoint hook was not removed:\n%s", text)
}
}
+
+// Codex reads its user hooks.json from CODEX_HOME when that is set; project hooks stay in
+// <cwd>/.codex, which CODEX_HOME does not move.
+func TestCodexHooksPathFollowsCodexHome(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ codexHome := t.TempDir()
+ t.Setenv("CODEX_HOME", codexHome)
+ resolved, err := filepath.EvalSymlinks(codexHome)
+ if err != nil {
+ t.Fatal(err)
+ }
+ path, err := codexHooksPath(LevelUser)
+ if err != nil {
+ t.Fatalf("codexHooksPath(user): %v", err)
+ }
+ if want := filepath.Join(resolved, "hooks.json"); path != want {
+ t.Fatalf("codexHooksPath(user) = %q, want %q", path, want)
+ }
+
+ t.Chdir(t.TempDir())
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ path, err = codexHooksPath(LevelProject)
+ if err != nil {
+ t.Fatalf("codexHooksPath(project): %v", err)
+ }
+ if want := filepath.Join(cwd, ".codex", "hooks.json"); path != want {
+ t.Fatalf("codexHooksPath(project) = %q, want %q", path, want)
+ }
+
+ t.Setenv("CODEX_HOME", filepath.Join(codexHome, "missing"))
+ if path, err := codexHooksPath(LevelUser); err == nil {
+ t.Fatalf("codexHooksPath(user) = %q for a CODEX_HOME that does not exist, want an error", path)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.go
index 645fe2bb..4543649e 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory.go
@@ -15,6 +15,7 @@ import (
"github.com/pelletier/go-toml/v2"
"gopkg.in/yaml.v3"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
)
@@ -272,13 +273,21 @@ func claudeCandidates(home, wd string) []candidate {
}
}
+// codexCandidates resolves the user-scope files through CODEX_HOME, as Codex does, and leaves them
+// out when CODEX_HOME names something Codex itself would refuse to start with. Project scope is
+// always <wd>/.codex.
func codexCandidates(home, wd string) []candidate {
- return []candidate{
- {runtime: "codex_cli", path: filepath.Join(home, ".codex", "config.toml"), scope: ScopeUser, format: formatTOML, kind: KindNativeConfig},
- {runtime: "codex_cli", path: filepath.Join(home, ".codex", "hooks.json"), scope: ScopeUser, format: formatJSON, kind: KindHookConfig},
- {runtime: "codex_cli", path: filepath.Join(wd, ".codex", "config.toml"), scope: ScopeProject, format: formatTOML, kind: KindNativeConfig},
- {runtime: "codex_cli", path: filepath.Join(wd, ".codex", "hooks.json"), scope: ScopeProject, format: formatJSON, kind: KindHookConfig},
- }
+ items := []candidate{}
+ if dir, err := codexsession.HomeDir(home); err == nil {
+ items = append(items,
+ candidate{runtime: "codex_cli", path: filepath.Join(dir, "config.toml"), scope: ScopeUser, format: formatTOML, kind: KindNativeConfig},
+ candidate{runtime: "codex_cli", path: filepath.Join(dir, "hooks.json"), scope: ScopeUser, format: formatJSON, kind: KindHookConfig},
+ )
+ }
+ return append(items,
+ candidate{runtime: "codex_cli", path: filepath.Join(wd, ".codex", "config.toml"), scope: ScopeProject, format: formatTOML, kind: KindNativeConfig},
+ candidate{runtime: "codex_cli", path: filepath.Join(wd, ".codex", "hooks.json"), scope: ScopeProject, format: formatJSON, kind: KindHookConfig},
+ )
}
func cursorCandidates(home, wd string) []candidate {
diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.go
index 023b3bd0..a2022831 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory_test.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go
@@ -347,6 +347,28 @@ func TestMissingCandidatesAreReportedAsNotFound(t *testing.T) {
}
}
+// With CODEX_HOME set, the user-scope Codex files inventory reads are the ones Codex reads.
+func TestScanReadsCodexUserConfigFromCodexHome(t *testing.T) {
+ home := t.TempDir()
+ codexHome := t.TempDir()
+ t.Setenv("CODEX_HOME", codexHome)
+ writeFile(t, filepath.Join(codexHome, "config.toml"), "[mcp_servers.github]\ncommand = \"gh\"\n")
+ writeFile(t, filepath.Join(home, ".codex", "config.toml"), "[mcp_servers.stale]\ncommand = \"old\"\n")
+ resolved, err := filepath.EvalSymlinks(codexHome)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ result := Scan(Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"codex_cli"}, Now: fixedNow})
+ config := findConfig(result.Configs, "codex_cli", filepath.Join(resolved, "config.toml"))
+ if config == nil || !config.Exists || config.MCPServerCount != 1 {
+ t.Fatalf("CODEX_HOME config.toml = %#v, want it read with one MCP server", config)
+ }
+ if stale := findConfig(result.Configs, "codex_cli", filepath.Join(home, ".codex", "config.toml")); stale != nil {
+ t.Fatalf("inventory reported ~/.codex/config.toml, which Codex does not read with CODEX_HOME set: %#v", stale)
+ }
+}
+
func TestScanIncludesAllSupportedCurrentUserAndProjectConfigs(t *testing.T) {
home := t.TempDir()
work := t.TempDir()
@@ -361,6 +383,8 @@ func TestScanIncludesAllSupportedCurrentUserAndProjectConfigs(t *testing.T) {
// are cleared for the same reason.
t.Setenv("OMO_CODING_AGENT_DIR", "")
t.Setenv("SENPI_CODING_AGENT_DIR", "")
+ // Codex's user-scope files follow CODEX_HOME.
+ t.Setenv("CODEX_HOME", "")
result := Scan(Options{
HomeDir: home,
diff --git a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
index 1a1cad66..e3df1ac4 100644
--- a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
+++ b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
@@ -118,6 +118,41 @@ func TestReconcileInventoryJobSkipsUnsupportedWithoutError(t *testing.T) {
}
}
+// The scheduled job runs without the installing shell's environment, so a per-user install
+// records the CODEX_HOME it resolved, as an absolute path, and the job inventories what Codex reads.
+// System mode and an unusable CODEX_HOME record nothing, leaving the job on ~/.codex.
+func TestInventoryJobEnvRecordsCodexHomeForUserInstalls(t *testing.T) {
+ work := t.TempDir()
+ codexHome := filepath.Join(work, "codex-home")
+ if err := os.Mkdir(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ want, err := os.Stat(codexHome)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Chdir(work)
+
+ // Relative, so the job, which starts elsewhere, needs the absolute form.
+ t.Setenv("CODEX_HOME", "codex-home")
+ env := inventoryJobEnv(true)
+ got, err := os.Stat(env["CODEX_HOME"])
+ if len(env) != 1 || !filepath.IsAbs(env["CODEX_HOME"]) || err != nil || !os.SameFile(got, want) {
+ t.Fatalf("user mode env = %v, want CODEX_HOME as the absolute path of %s", env, codexHome)
+ }
+ if got := inventoryJobEnv(false); got != nil {
+ t.Fatalf("system mode env = %v, want none: root's environment is not the console user's", got)
+ }
+ t.Setenv("CODEX_HOME", filepath.Join(work, "missing"))
+ if got := inventoryJobEnv(true); got != nil {
+ t.Fatalf("env for a CODEX_HOME that does not exist = %v, want none", got)
+ }
+ t.Setenv("CODEX_HOME", "")
+ if got := inventoryJobEnv(true); got != nil {
+ t.Fatalf("env with CODEX_HOME unset = %v, want none", got)
+ }
+}
+
func TestReconcileInventoryJobWritesWithoutLoadingWhenAsked(t *testing.T) {
testenv.SetHome(t, t.TempDir())
calls := installFakeInventoryJob(t, true)
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 59f0a059..83a42427 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -10,6 +10,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/atomicfile"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/brewpath"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
endpointcollector "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
@@ -43,7 +44,7 @@ var (
// newInventoryJob and removeInventoryJob are the seams tests replace so Install, Uninstall
// and Repair can be exercised without touching launchd or systemd.
newInventoryJob = func(userMode bool, kind service.Kind) inventoryJobController {
- return service.InventoryManager{UserMode: userMode, Kind: kind}
+ return service.InventoryManager{UserMode: userMode, Kind: kind, Env: inventoryJobEnv(userMode)}
}
removeInventoryJob = func(userMode bool) {
job := newInventoryJob(userMode, service.KindAuto)
@@ -132,6 +133,25 @@ func reconcileInventoryJobWith(job inventoryJobController, opts InventoryJobOpti
return result, nil
}
+// inventoryJobEnv is the environment written into a per-user inventory job. launchd and systemd
+// start the job without the user's shell environment, so a CODEX_HOME exported in a shell profile
+// would not reach it and the scheduled scan would inventory ~/.codex while Codex reads
+// $CODEX_HOME. The value is resolved now, from the install's shell, as Codex resolves it: an
+// absolute path, so a relative CODEX_HOME still means the directory it named at install time. An
+// unset or invalid CODEX_HOME records nothing, and the job falls back to ~/.codex as before.
+//
+// System mode records nothing: this process's environment is root's, not the console user's.
+func inventoryJobEnv(userMode bool) map[string]string {
+ if !userMode || os.Getenv("CODEX_HOME") == "" {
+ return nil
+ }
+ dir, err := codexsession.HomeDir("")
+ if err != nil {
+ return nil
+ }
+ return map[string]string{"CODEX_HOME": dir}
+}
+
// inventoryEnabledFromConfigFile reads only the inventory_heartbeat.enabled key. A missing or
// unreadable config, or an absent key, means enabled: the job is on by default.
func inventoryEnabledFromConfigFile(path string) bool {
diff --git a/cli/beacon/internal/endpoint/service/inventory.go b/cli/beacon/internal/endpoint/service/inventory.go
index ec99694f..7f7c3e84 100644
--- a/cli/beacon/internal/endpoint/service/inventory.go
+++ b/cli/beacon/internal/endpoint/service/inventory.go
@@ -2,9 +2,11 @@ package service
import (
"fmt"
+ "maps"
"os"
"path/filepath"
"runtime"
+ "slices"
"strconv"
"strings"
"time"
@@ -48,6 +50,10 @@ type InventoryManager struct {
UserMode bool
// Kind selects the backend; the zero value auto-detects.
Kind Kind
+ // Env is set in the job's environment. launchd and systemd start the job without the
+ // installing user's shell environment, so anything the inventory scan reads from it has to
+ // be written into the unit.
+ Env map[string]string
}
func (m InventoryManager) resolvedKind() Kind {
@@ -170,7 +176,7 @@ func (m InventoryManager) WriteUnit(program, logPath string) (string, error) {
args := inventoryJobArgs(m.UserMode, logPath)
if m.resolvedKind() == KindSystemd {
svc := filepath.Join(filepath.Dir(path), InventoryServiceUnit)
- if err := os.WriteFile(svc, []byte(inventoryServiceUnit(program, args, m.UserMode)), 0o644); err != nil {
+ if err := os.WriteFile(svc, []byte(inventoryServiceUnit(program, args, m.UserMode, m.Env)), 0o644); err != nil {
return "", err
}
if err := os.WriteFile(path, []byte(inventoryTimerUnit(InventoryInterval())), 0o644); err != nil {
@@ -188,7 +194,7 @@ func (m InventoryManager) WriteUnit(program, logPath string) (string, error) {
if err != nil {
return "", err
}
- content := inventoryPlist(InventoryLabel, program, args, InventoryInterval(), stdout, stderr)
+ content := inventoryPlist(InventoryLabel, program, args, InventoryInterval(), stdout, stderr, m.Env)
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
return "", err
}
@@ -277,13 +283,16 @@ func (m InventoryManager) Status() Status {
}
// inventoryServiceUnit is the oneshot job the timer triggers.
-func inventoryServiceUnit(program string, args []string, userMode bool) string {
+func inventoryServiceUnit(program string, args []string, userMode bool, env map[string]string) string {
var b strings.Builder
b.WriteString("[Unit]\n")
b.WriteString("Description=Beacon endpoint inventory heartbeat\n")
b.WriteString("Documentation=https://docs.asymptotelabs.ai/cli/endpoint-inventory\n")
b.WriteString("\n[Service]\n")
b.WriteString("Type=oneshot\n")
+ for _, key := range slices.Sorted(maps.Keys(env)) {
+ fmt.Fprintf(&b, "Environment=%s\n", systemdArg(key+"="+env[key]))
+ }
fmt.Fprintf(&b, "ExecStart=%s", systemdArg(program))
for _, arg := range args {
fmt.Fprintf(&b, " %s", systemdArg(arg))
@@ -317,12 +326,20 @@ WantedBy=timers.target
// inventoryPlist renders the launchd job: one shot at load, then every interval. No KeepAlive,
// so launchd does not restart a job that exited normally.
-func inventoryPlist(label, program string, args []string, interval time.Duration, stdoutPath, stderrPath string) string {
+func inventoryPlist(label, program string, args []string, interval time.Duration, stdoutPath, stderrPath string, env map[string]string) string {
var argv strings.Builder
fmt.Fprintf(&argv, " <string>%s</string>\n", xmlEscape(program))
for _, arg := range args {
fmt.Fprintf(&argv, " <string>%s</string>\n", xmlEscape(arg))
}
+ var envBlock strings.Builder
+ if len(env) > 0 {
+ envBlock.WriteString(" <key>EnvironmentVariables</key>\n <dict>\n")
+ for _, key := range slices.Sorted(maps.Keys(env)) {
+ fmt.Fprintf(&envBlock, " <key>%s</key>\n <string>%s</string>\n", xmlEscape(key), xmlEscape(env[key]))
+ }
+ envBlock.WriteString(" </dict>\n")
+ }
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">
@@ -332,7 +349,7 @@ func inventoryPlist(label, program string, args []string, interval time.Duration
<key>ProgramArguments</key>
<array>
%s </array>
- <key>RunAtLoad</key>
+%s <key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>%d</integer>
@@ -342,5 +359,5 @@ func inventoryPlist(label, program string, args []string, interval time.Duration
<string>%s</string>
</dict>
</plist>
-`, xmlEscape(label), argv.String(), int(interval.Seconds()), xmlEscape(stdoutPath), xmlEscape(stderrPath))
+`, xmlEscape(label), argv.String(), envBlock.String(), int(interval.Seconds()), xmlEscape(stdoutPath), xmlEscape(stderrPath))
}
diff --git a/cli/beacon/internal/endpoint/service/inventory_test.go b/cli/beacon/internal/endpoint/service/inventory_test.go
index 2718c048..ec697111 100644
--- a/cli/beacon/internal/endpoint/service/inventory_test.go
+++ b/cli/beacon/internal/endpoint/service/inventory_test.go
@@ -19,7 +19,7 @@ func TestInventoryPlistIsAOneShotIntervalJob(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- got := inventoryPlist(InventoryLabel, "/opt/beacon/bin/beacon", args, 6*time.Hour, sysOut, sysErr)
+ got := inventoryPlist(InventoryLabel, "/opt/beacon/bin/beacon", args, 6*time.Hour, sysOut, sysErr, nil)
for _, want := range []string{
"<string>com.beacon.endpoint.inventory</string>",
"<string>/opt/beacon/bin/beacon</string>",
@@ -33,7 +33,7 @@ func TestInventoryPlistIsAOneShotIntervalJob(t *testing.T) {
t.Fatalf("plist missing %q:\n%s", want, got)
}
}
- for _, forbidden := range []string{"KeepAlive", "StartCalendarInterval", "--log-path", "/tmp/"} {
+ for _, forbidden := range []string{"KeepAlive", "StartCalendarInterval", "--log-path", "/tmp/", "EnvironmentVariables"} {
if strings.Contains(got, forbidden) {
t.Fatalf("plist must not contain %q:\n%s", forbidden, got)
}
@@ -44,7 +44,7 @@ func TestInventoryPlistIsAOneShotIntervalJob(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- user := inventoryPlist(InventoryLabel, "/usr/local/bin/beacon", inventoryJobArgs(true, "/Users/me/.beacon/endpoint/logs/runtime.jsonl"), time.Hour, userOut, userErr)
+ user := inventoryPlist(InventoryLabel, "/usr/local/bin/beacon", inventoryJobArgs(true, "/Users/me/.beacon/endpoint/logs/runtime.jsonl"), time.Hour, userOut, userErr, nil)
if !strings.Contains(user, "<string>--user</string>") || strings.Contains(user, "<string>--system</string>") {
t.Fatalf("user-mode plist must carry --user:\n%s", user)
}
@@ -57,7 +57,7 @@ func TestInventoryPlistIsAOneShotIntervalJob(t *testing.T) {
if !strings.Contains(user, "<string>"+userLogs+".err</string>") || strings.Contains(user, "<string>/Library/Logs/Beacon/") {
t.Fatalf("user-mode plist must log under the user's home, got:\n%s", user)
}
- escaped := inventoryPlist("l", "/tmp/a&b", []string{"--log-path", "/tmp/<c>.jsonl"}, time.Hour, "/x/l.out", "/x/l.err")
+ escaped := inventoryPlist("l", "/tmp/a&b", []string{"--log-path", "/tmp/<c>.jsonl"}, time.Hour, "/x/l.out", "/x/l.err", nil)
if !strings.Contains(escaped, "/tmp/a&amp;b") || !strings.Contains(escaped, "&lt;c&gt;") {
t.Fatalf("plist must XML-escape program and arguments:\n%s", escaped)
}
@@ -72,7 +72,7 @@ func TestInventoryIntervalEnvOverride(t *testing.T) {
if got := InventoryInterval(); got != time.Minute {
t.Fatalf("overridden interval = %s, want 1m", got)
}
- plist := inventoryPlist(InventoryLabel, "/opt/beacon/bin/beacon", inventoryJobArgs(false, ""), InventoryInterval(), "/x/l.out", "/x/l.err")
+ plist := inventoryPlist(InventoryLabel, "/opt/beacon/bin/beacon", inventoryJobArgs(false, ""), InventoryInterval(), "/x/l.out", "/x/l.err", nil)
if !strings.Contains(plist, "<key>StartInterval</key>\n <integer>60</integer>") {
t.Fatalf("plist should use the overridden interval:\n%s", plist)
}
@@ -88,7 +88,7 @@ func TestInventoryIntervalEnvOverride(t *testing.T) {
}
func TestInventorySystemdUnitsPairTimerWithOneshot(t *testing.T) {
- system := inventoryServiceUnit("/usr/bin/beacon", inventoryJobArgs(false, ""), false)
+ system := inventoryServiceUnit("/usr/bin/beacon", inventoryJobArgs(false, ""), false, nil)
for _, want := range []string{
"Type=oneshot",
`ExecStart="/usr/bin/beacon" "endpoint" "inventory" "heartbeat" "--scheduled" "--system"`,
@@ -99,7 +99,10 @@ func TestInventorySystemdUnitsPairTimerWithOneshot(t *testing.T) {
t.Fatalf("system service unit missing %q:\n%s", want, system)
}
}
- user := inventoryServiceUnit("/home/me/.local/bin/beacon", inventoryJobArgs(true, "/home/me/.beacon/endpoint/logs/runtime.jsonl"), true)
+ user := inventoryServiceUnit("/home/me/.local/bin/beacon", inventoryJobArgs(true, "/home/me/.beacon/endpoint/logs/runtime.jsonl"), true, nil)
+ if strings.Contains(user, "Environment=") {
+ t.Fatalf("a job with no environment must not set one:\n%s", user)
+ }
if strings.Contains(user, "User=root") {
t.Fatalf("user service unit must not run as root:\n%s", user)
}
@@ -123,6 +126,21 @@ func TestInventorySystemdUnitsPairTimerWithOneshot(t *testing.T) {
}
}
+// The job's environment reaches the scan only if the unit sets it: launchd and systemd do not pass
+// on the installing shell's variables. Values are escaped for each format, since a path can hold
+// characters XML or systemd would otherwise interpret.
+func TestInventoryUnitsCarryTheJobEnvironment(t *testing.T) {
+ env := map[string]string{"CODEX_HOME": `/Users/me/codex & "100%"`}
+ plist := inventoryPlist(InventoryLabel, "/usr/local/bin/beacon", inventoryJobArgs(true, ""), time.Hour, "/x/l.out", "/x/l.err", env)
+ if want := " <key>EnvironmentVariables</key>\n <dict>\n <key>CODEX_HOME</key>\n <string>/Users/me/codex &amp; &quot;100%&quot;</string>\n </dict>\n"; !strings.Contains(plist, want) {
+ t.Fatalf("plist missing escaped environment %q:\n%s", want, plist)
+ }
+ unit := inventoryServiceUnit("/usr/local/bin/beacon", inventoryJobArgs(true, ""), true, env)
+ if want := `Environment="CODEX_HOME=/Users/me/codex & \"100%%\""`; !strings.Contains(unit, want) {
+ t.Fatalf("service unit missing escaped environment %q:\n%s", want, unit)
+ }
+}
+
func TestInventoryUnitPathFollowsBackendAndMode(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("launchd and systemd unit paths are POSIX-only")
diff --git a/cli/beacon/internal/endpoint/service/launchd_logs_test.go b/cli/beacon/internal/endpoint/service/launchd_logs_test.go
index 37aaf43d..6aaf27c7 100644
--- a/cli/beacon/internal/endpoint/service/launchd_logs_test.go
+++ b/cli/beacon/internal/endpoint/service/launchd_logs_test.go
@@ -39,7 +39,7 @@ func TestSystemLaunchDaemonsNeverLogToTmp(t *testing.T) {
out, errPath = paths(UpdaterLabel)
plists[UpdaterLabel] = updaterPlist(UpdaterLabel, "/opt/beacon/bin/beacon", out, errPath)
out, errPath = paths(InventoryLabel)
- plists[InventoryLabel] = inventoryPlist(InventoryLabel, "/opt/beacon/bin/beacon", inventoryJobArgs(false, ""), InventoryInterval(), out, errPath)
+ plists[InventoryLabel] = inventoryPlist(InventoryLabel, "/opt/beacon/bin/beacon", inventoryJobArgs(false, ""), InventoryInterval(), out, errPath, nil)
for label, content := range plists {
if strings.Contains(content, "/tmp/") {
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index e62c99c7..7ebe7198 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -11,6 +11,8 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
## October 2026
+- **Codex install, hooks and inventory follow `CODEX_HOME`** · `beacon endpoint install`, `beacon endpoint hooks install --harness codex`, `beacon endpoint discover` and inventory now read and write `$CODEX_HOME/config.toml` and `$CODEX_HOME/hooks.json` when `CODEX_HOME` is set, as Codex does. They previously always used `~/.codex`, so with `CODEX_HOME` set, Codex never saw the OTLP exporter or the SessionStart hook and live capture silently recorded nothing. A per-user install or repair also writes the resolved `CODEX_HOME` into the scheduled inventory job, which launchd and systemd start without your shell's environment. A `CODEX_HOME` that is not an existing directory is now an install error rather than a silent write to `~/.codex`. Project-level `.codex` files are unchanged.
+
### v1.3.40 · October 14, 2026
- **Status shows customer forwarders and stops sending MDM installs to `connect`** · `beacon endpoint status` prints one line for each S3, GCS or Falcon LogScale forwarder the package helpers installed, such as `S3 forwarder: loaded=true running=true`, and `--json` adds `script_forwarders`. The `Beacon Cloud: not connected` line and its `beacon endpoint connect` hint are left out on a system install that was never connected and on any install with its own forwarder, where the line read as an unfinished step and named a command that needs a personal sign-in. A connected or partly connected endpoint still shows the line, and per-user installs keep the hint.
diff --git a/docs/cli/hooks.mdx b/docs/cli/hooks.mdx
index 30e36199..548ddf5f 100644
--- a/docs/cli/hooks.mdx
+++ b/docs/cli/hooks.mdx
@@ -31,7 +31,7 @@ beacon endpoint hooks [command]
|---------|-------------------|----------------------|-------------|-------------|
| Antigravity CLI | `~/.gemini/config/hooks.json` | `./.agents/hooks.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
| Claude Code | `~/.claude/settings.json` | `./.claude/settings.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
-| Codex CLI | `~/.codex/hooks.json` | `./.codex/hooks.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
+| Codex CLI | `$CODEX_HOME/hooks.json` (default `~/.codex/hooks.json`) | `./.codex/hooks.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
| Cursor | `~/.cursor/hooks.json` | `./.cursor/hooks.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
| Devin CLI | `~/.config/devin/config.json` | `./.devin/hooks.v1.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
| Devin Desktop | `~/.codeium/windsurf/hooks.json` | `./.windsurf/hooks.json` | `~/.beacon/endpoint/hooks/beacon-hooks` | `~/.beacon/endpoint/logs/runtime.jsonl` |
@@ -446,7 +446,7 @@ Beacon's `PreToolUse` hook answers with an empty object on purpose. Qwen reads `
## Codex CLI troubleshooting
-Beacon writes Codex CLI endpoint hooks to `~/.codex/hooks.json` for user-level installs or `./.codex/hooks.json` for project-level installs. `SessionStart` writes local OS-user/session context. This metadata-only hook does not replace the Codex OTLP runtime path for prompt, tool, or token events, and it no longer triggers inventory: that is the scheduled inventory job's work, in every mode, whether or not Codex runs.
+Beacon writes Codex CLI endpoint hooks to `$CODEX_HOME/hooks.json` (default `~/.codex/hooks.json`) for user-level installs or `./.codex/hooks.json` for project-level installs. `SessionStart` writes local OS-user/session context. This metadata-only hook does not replace the Codex OTLP runtime path for prompt, tool, or token events, and it no longer triggers inventory: that is the scheduled inventory job's work, in every mode, whether or not Codex runs.
If Codex session context is missing, check the selected level, confirm the hook file contains a command with `--platform codex`, and restart Codex CLI so new sessions pick up the updated hook configuration.
diff --git a/docs/runtimes/codex-cli.mdx b/docs/runtimes/codex-cli.mdx
index 22560bd6..91b7830f 100644
--- a/docs/runtimes/codex-cli.mdx
+++ b/docs/runtimes/codex-cli.mdx
@@ -38,11 +38,13 @@ Use `beacon endpoint codex sync --print` to preview mapped events without writin
Codex rollout files can contain prompts, assistant responses, tool inputs, command output, and code. Sync is therefore explicit: Beacon does not read `~/.codex/sessions` during normal Codex hook execution, and it never reads `~/.codex/auth.json`.
-Session status, sync, handoff, and `beacon mcp connect` honor Codex's literal `CODEX_HOME` directory: it must exist, and relative paths resolve from the current working directory. Unlike shell syntax, `~` and environment-variable references in the value are not expanded. Pass `--codex-dir <path>` to select a session store explicitly.
+Install, hook install, discovery, inventory, session status, sync, handoff, and `beacon mcp connect` honor Codex's literal `CODEX_HOME` directory: it must exist, and relative paths resolve from the current working directory. Unlike shell syntax, `~` and environment-variable references in the value are not expanded. Project-level `.codex` files are not affected. Pass `--codex-dir <path>` to select a session store explicitly.
+
+The scheduled inventory job starts without your shell's environment, so a per-user `beacon endpoint install` or `repair` writes the `CODEX_HOME` it resolved into the job's launchd or systemd definition. If you change `CODEX_HOME` later, run `beacon endpoint repair` from a shell that has the new value. System-mode installs do not record it.
### Token usage and cost
-`beacon endpoint install` configures Codex's log and trace exporters in `~/.codex/config.toml`. Beacon normalizes the completed turn span into the same canonical `gen_ai.usage` fields used for Claude Code: uncached `input_tokens`, `output_tokens`, `cache_read.input_tokens`, `cache_creation.input_tokens`, and `reasoning.output_tokens`. Codex's input count includes both cache reads and cache writes, so Beacon subtracts both before recording uncached input.
+`beacon endpoint install` configures Codex's log and trace exporters in `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`). Beacon normalizes the completed turn span into the same canonical `gen_ai.usage` fields used for Claude Code: uncached `input_tokens`, `output_tokens`, `cache_read.input_tokens`, `cache_creation.input_tokens`, and `reasoning.output_tokens`. Codex's input count includes both cache reads and cache writes, so Beacon subtracts both before recording uncached input.
The span directly supplies the model and `session.id` (from Codex `thread.id`). Beacon joins the matching SessionStart context event to attribute local reports by OS user. The runtime log therefore contains both the token event and its session identity context, and both forward through configured JSONL shippers.
@@ -83,11 +85,11 @@ Beacon can also capture Codex telemetry in CI with `beacon ci start` and `beacon
## Discovery and status
-Beacon detects Codex CLI through the `codex` executable and `~/.codex/config.toml`. Codex Desktop shares the same user-level configuration file, so Desktop app-server events appear once the app emits OTLP to Beacon's local collector. Use `beacon endpoint discover` or `beacon endpoint status` to confirm that Codex configuration is present.
+Beacon detects Codex CLI through the `codex` executable and `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`). Codex Desktop shares the same user-level configuration file, so Desktop app-server events appear once the app emits OTLP to Beacon's local collector. Use `beacon endpoint discover` or `beacon endpoint status` to confirm that Codex configuration is present.
## Install or configuration support
-`beacon endpoint install` writes Codex OTLP exporter tables to `~/.codex/config.toml`.
+`beacon endpoint install` writes Codex OTLP exporter tables to `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`).
`beacon endpoint install --harness codex` installs the required user-level
session context and inventory hooks with the OTLP configuration. To refresh
@@ -97,7 +99,7 @@ them independently, run:
beacon endpoint hooks install --harness codex
```
-The hook installer writes the metadata-only session context hook to `~/.codex/hooks.json` or project `.codex/hooks.json`, depending on `--level`. A successful user-level install prints:
+The hook installer writes the metadata-only session context hook to `$CODEX_HOME/hooks.json` (default `~/.codex/hooks.json`) or project `.codex/hooks.json`, depending on `--level`. A successful user-level install prints:
```text
Codex CLI endpoint hooks installed: /Users/you/.codex/hooks.json