From 7d609e2fa4316f42eef50384911be9d75d181357 Mon Sep 17 00:00:00 2001 From: Alan Cha Date: Wed, 11 Nov 2026 02:25:14 -0500 Subject: [PATCH 1/6] fix: Unroute Codex in agentop uninstall agentop uninstall unrouted Claude Code, OpenCode, Bob and Pi, but not Codex, which landed after it (#1337) and never added a row. After an uninstall, ~/.codex/.env still pointed Codex at a proxy that was gone, and with --purge its SSL_CERT_FILE named a CA bundle that had been deleted. Uninstall now takes Cortex's values out of Codex's dotenv file before the proxy stops, using configure codex disable's plan and apply, and restarts a running app-server, stopping its auto-updater first, as disable does. It removes only values that are Cortex's: a proxy or CA bundle of the user's own is left and listed under Left behind, since uninstall changes everything on one question. --purge keeps ~/.cortex while SSL_CERT_FILE still points into it, and the fix lines work without agentop. TestUninstallUnroutesEveryConfiguredAgent enables every agent configure status lists, runs uninstall, and checks configure status reads none of them routed. The list is configure status's own, so an agent added there that uninstall does not unroute fails it. Assisted-By: Claude (Anthropic AI) Signed-off-by: Alan Cha --- cmd/agentop/cmd_uninstall.go | 186 +++++++++++++++++++++- cmd/agentop/cmd_uninstall_test.go | 256 ++++++++++++++++++++++++++++++ cmd/agentop/configure_status.go | 11 +- docs/agents/codex.md | 15 ++ docs/laptop-service.md | 5 +- 5 files changed, 468 insertions(+), 5 deletions(-) diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index 297a7944f..4ae6bf9c1 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -25,7 +25,7 @@ const uninstallUsage = `agentop uninstall — remove Cortex from this machine, a Usage: agentop uninstall [--yes] [--purge] -Unroutes Claude Code, OpenCode, IBM Bob, and the bob and pi shell functions and +Unroutes Claude Code, OpenCode, Codex, IBM Bob, and the bob and pi shell functions and Pi's session extension where Cortex routed them; stops and removes the service, or the background proxy; removes the PATH lines setup added, unless other tools in ~/.local/bin still need them; and removes agentop, cortex, cortex-session-dump and cortex-gateway from @@ -381,7 +381,7 @@ func applyRemovals(env *setupEnv, ui *checklist.UI, removals []removal, sigs <-c // and config, as the service paths read the config. A run uses what its plan read. func planUninstall(env *setupEnv, opts uninstallOptions) []removal { rs := planUnrouteClaudeCode(env) - for _, plan := range []func(*setupEnv) (removal, bool){planUnrouteOpenCode, planUnrouteBob, planRemoveBobShell, planRemovePiShell, planRemovePiExtension, planStopService} { + for _, plan := range []func(*setupEnv) (removal, bool){planUnrouteOpenCode, planUnrouteCodex, planUnrouteBob, planRemoveBobShell, planRemovePiShell, planRemovePiExtension, planStopService} { if r, ok := plan(env); ok { rs = append(rs, r) } @@ -768,6 +768,188 @@ func openCodeByHand(env *setupEnv, cli string, pl openCodeDisablePlan, planned b return strings.Join(append(lines, restart), "\n") } +// planUnrouteCodex takes Cortex's values out of Codex's dotenv file, as configure codex +// disable does, when the file holds any. Only those: disable removes every managed key, +// but a value Cortex did not write — a corporate proxy, a CA bundle of the user's own — +// is the user's, and uninstall changes everything on one question, so the row leaves it +// and says so. The file is read now, as is enable's record, which --purge deletes. One +// that cannot be read fails the row only when that record says Cortex routed Codex. +// +// A running app-server is restarted after the change, as disable restarts it, so it +// drops the proxy that is about to stop. Its auto-updater is stopped first, for the +// reason codexUpdaterPIDRel gives: left running, the next update would start a daemon on +// that proxy again. +func planUnrouteCodex(env *setupEnv) (removal, bool) { + envPath := defaultCodexEnvPath(env.home) + codexHome := filepath.Dir(envPath) + state := filepath.Join(env.home, codexStateRel) + // Judged by Cortex's values when its config gives them. Without them codexIsOurs + // falls back to the value's shape, as disable does when Cortex is gone. + want, _ := codexWanted(env.configPath()) + f, readErr := parseCodexEnv(envPath) + var ours, theirs []string + cortexProxy := want["HTTPS_PROXY"] + if readErr == nil { + for _, k := range codexKeys { + v, ok := f.get(k) + switch { + case !ok: + case codexIsOurs(k, v, want): + ours = append(ours, k) + if k == "HTTPS_PROXY" || (k == "https_proxy" && cortexProxy == "") { + cortexProxy = v + } + default: + theirs = append(theirs, k) + } + } + } + if (readErr != nil && !fileExists(state)) || (readErr == nil && len(ours) == 0) { + return removal{}, false + } + pl, planErr := planCodexDisable(envPath) + if planErr == nil { + pl.present = ours + } + where := env.tilde(envPath) + if _, running := runningCodexDaemon(codexHome); running { + where += " · restarts its app-server, interrupting running turns" + } + fix := remedy{byHand: codexByHand(env, envPath, ours)} + if planErr == nil && len(theirs) == 0 { + // Not while a value is the user's: disable would remove that too. + fix.agentop = "agentop configure codex disable" + } + return removal{ + label: "unrouted", + item: checklist.Item{Verb: "unroute", What: "Codex", Where: where}, + fix: fix, + needsCortexDir: codexNeedsCortexDir(env, envPath, state, f, planErr == nil, ours), + run: func(*checklist.Running) (string, []string, error) { + unchanged := []string{env.tilde(envPath)} + if planErr != nil { + return "", unchanged, planErr + } + _, running := runningCodexDaemon(codexHome) + var errb bytes.Buffer + restored, err := applyCodexDisable(pl, state, &errb) + if err != nil { + return "", unchanged, err + } + detail := "Codex no longer goes through Cortex" + var left []string + if len(theirs) > 0 { + // Not "no longer goes through Cortex": a proxy of the user's still routes it. + detail = "removed what Cortex set" + left = append(left, someKeys(theirs)+" in "+env.tilde(envPath)+", not Cortex's values — left as they are") + } + if len(restored) > 0 { + detail += " · restored your " + strings.Join(restored, ", ") + } + notes := stderrNotes(env, errb.String()) + if !running { + return detail + notes, left, nil + } + // A failed stop is not this row's ✗, as it is not disable's: the restart still + // applies the change, and codexLeftAfterRestart names an updater left on the + // old proxy. + _ = codexStopUpdater(codexHome) + if err := codexRestartDaemon(codexHome, want); err != nil { + return detail + notes, append(left, "Codex's app-server, which may still use Cortex's proxy — restart it: "+codexDaemonRestartCmd), nil + } + return detail + " · restarted its app-server" + notes, append(left, codexLeftAfterRestart(codexHome, cortexProxy)...), nil + }, + }, true +} + +// codexByHand is the Codex row's change as fix lines, for when agentop is gone: the lines +// to delete from the dotenv file, then the restart. It names no value, as unrouteByHand +// names none. With no keys, from a file that could not be read, it names all five. +func codexByHand(env *setupEnv, envPath string, keys []string) string { + if len(keys) == 0 { + keys = codexKeys + } + return "in " + env.tilde(envPath) + ", remove the lines that set " + someKeys(keys) + " to Cortex's values\n" + + "then, if Codex's app-server runs: " + codexDaemonRestartCmd +} + +// codexNeedsCortexDir is why --purge must keep ~/.cortex: the managed keys of envPath that +// will still name something inside it once the row has run, as claudeCodeNeedsCortexDir +// gives them for Claude Code. Codex's SSL_CERT_FILE is Cortex's CA bundle, so this is what +// keeps the directory when the row cannot change the file (planned false: a key defined +// twice), and when it leaves or restores a value under it. A file that could not be read +// may point anywhere, so it keeps the directory too. +func codexNeedsCortexDir(env *setupEnv, envPath, state string, f *codexEnvFile, planned bool, ours []string) string { + if f == nil { + return env.tilde(envPath) + ", which could not be read, may still point into it" + } + removed := map[string]bool{} + if planned { + for _, k := range ours { + removed[k] = true + } + } + after := map[string]string{} + for _, k := range codexKeys { + if v, ok := f.get(k); ok && !removed[k] { + after[k] = v + } + } + if planned { + // What applyCodexDisable restores: enable's record, when it is this file's. + if st, _ := readState(state); st != nil && st.Settings == envPath { + for _, k := range ours { + if p := st.Prior[k]; p != nil { + after[k] = *p + } + } + } + } + var keys []string + for _, k := range codexKeys { + if pathUnder(env.cortexDir, after[k]) { + keys = append(keys, k) + } + } + if len(keys) == 0 { + return "" + } + return someKeys(keys) + " in " + env.tilde(envPath) + " still points into it" +} + +// codexLeftAfterRestart is what still has Cortex's proxy once the Codex row has restarted +// the app-server. The daemon, when that proxy reached it from somewhere other than the +// dotenv file. And the auto-updater, when stopping it failed, since the daemon it starts +// after its next update inherits its proxy — named only when codexIsRecorded confirms it, +// as reportRestartedUpdater names it, so a reused pid is never given a kill command. +func codexLeftAfterRestart(codexHome, cortexProxy string) []string { + if cortexProxy == "" { + return nil + } + var left []string + if d, ok := runningCodexDaemon(codexHome); ok && d.EnvErr == nil && sameProxy(d.Proxy, cortexProxy) { + left = append(left, fmt.Sprintf("Codex's app-server (pid %d), which still has Cortex's proxy from the environment it started in — "+ + "restart it from a shell without one: %s", d.PID, codexDaemonRestartCmd)) + } + u, ok := runningCodexUpdater(codexHome) + if !ok { + return left + } + switch codexIsRecorded(u) { + case codexRecordStale: + // The restart found the record stale and started a fresh updater. + case codexRecordUnknown: + left = append(left, "Codex's auto-updater, which agentop could not confirm picked up the change — "+ + "if Codex cannot connect after its next update, restart your computer") + default: + if u.EnvErr == nil && sameProxy(u.Proxy, cortexProxy) { + left = append(left, fmt.Sprintf("Codex's auto-updater (pid %d), which still has Cortex's proxy — "+ + "stop it, then restart the app-server: kill %d && %s", u.PID, u.PID, codexDaemonRestartCmd)) + } + } + return left +} + // planUnrouteBob removes IBM Bob's proxy setting when it may be Cortex's: one // bobOwns does not call someone else's. It also runs when only enable's shell block // is left, so uninstall takes out everything enable wrote. Bob's disable makes the diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index 548900c06..666e7d3eb 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -1663,3 +1663,259 @@ func TestUninstallLeavesAForeignPiExtension(t *testing.T) { t.Error("uninstall changed a file agentop did not write") } } + +// codexEnabledIn routes the scene's Codex through Cortex as configure codex enable does: +// ~/.codex/.env holds Cortex's five values beside a line of the user's own, and enable's +// record is where configure codex keeps it. Enable runs with no daemon, so its own +// restart spends nothing of f, which is the daemon uninstall then finds. +func codexEnabledIn(t *testing.T, sc setupScene, f *fakeCodexDaemon) string { + t.Helper() + t.Setenv(codexHomeEnv, "") + envPath := filepath.Join(sc.home, codexEnvRel) + codexHome, state := filepath.Dir(envPath), filepath.Join(sc.home, codexStateRel) + writeHomeFile(t, envPath, "RUST_LOG=info\n") + stubCodexDaemon(t, codexHome, &fakeCodexDaemon{}) + var out, errb bytes.Buffer + if code := codexEnable(envPath, filepath.Join(sc.home, cortexCfgRel), state, true, &out, &errb); code != 0 { + t.Fatalf("fixture: configure codex enable exit %d:\n%s%s", code, out.String(), errb.String()) + } + if got := readCodexEnv(t, envPath); len(got) != len(codexKeys) || !fileExists(state) { + t.Fatalf("fixture: enable left %v in ~/.codex/.env, and a record: %v", got, fileExists(state)) + } + stubCodexDaemon(t, codexHome, f) + return envPath +} + +// runningCodex is an app-server on Cortex's proxy with its auto-updater, both of which a +// restart replaces with processes on the file's new settings. +func runningCodex() *fakeCodexDaemon { + return &fakeCodexDaemon{ + pid: 4101, env: onCortex, newPID: 4102, newEnv: offCortex, + updaterPID: 4103, updaterEnv: onCortex, newUpdaterPID: 4104, + } +} + +// configure codex enable routes Codex through its dotenv file. Uninstall takes Cortex's +// values out of it before the proxy stops and agentop goes, keeping the user's own line, +// and restarts an app-server that runs, its auto-updater stopped first, since both read +// the file only when they start. +func TestUninstallUnroutesCodex(t *testing.T) { + for _, running := range []bool{true, false} { + t.Run(fmt.Sprintf("running=%v", running), func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + f := &fakeCodexDaemon{} + if running { + f = runningCodex() + } + envPath := codexEnabledIn(t, sc, f) + code, out := sc.uninstall(t, "--yes") + where, done, steps := "~/.codex/.env", "Codex no longer goes through Cortex", []string(nil) + if running { + where += " · restarts its app-server, interrupting running turns" + done += " · restarted its app-server" + steps = []string{"stop-updater", "restart"} + } + wantLines(t, code, 0, out, markLine("✓", "unrouted")+done+"\n", "\n Uninstalled.\n") + if row := consentRow(out, "unroute"); !strings.Contains(row, " Codex ") || !strings.HasSuffix(row, where) { + t.Errorf("the consent row is %q, want Codex and %q:\n%s", row, where, out) + } + if got := readCodexEnv(t, envPath); len(got) != 0 { + t.Errorf("Cortex's values survived the unroute: %v", got) + } + if body := readFile(t, envPath); !strings.Contains(body, "RUST_LOG=info\n") || strings.Contains(body, codexMarker) { + t.Errorf("~/.codex/.env is %q, want the user's line kept and enable's comment gone", body) + } + if fileExists(filepath.Join(sc.home, codexStateRel)) { + t.Error("enable's record is still there") + } + if !slices.Equal(f.steps, steps) { + t.Errorf("the daemon saw %v, want %v", f.steps, steps) + } + if i, j := strings.Index(out, markLine("✓", "unrouted")+"Codex"), strings.Index(out, markLine("✓", "stopped")); i < 0 || j < i { + t.Errorf("Codex is not unrouted before the service stops:\n%s", out) + } + }) + } +} + +// A Codex whose dotenv file holds nothing of Cortex's gets no row and no change: the proxy +// and CA there are the user's, which disable on its own would have removed. +func TestUninstallLeavesACodexCortexDidNotRoute(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + t.Setenv(codexHomeEnv, "") + stubCodexDaemon(t, filepath.Join(sc.home, ".codex"), runningCodex()) + envPath := filepath.Join(sc.home, codexEnvRel) + const mine = "HTTPS_PROXY=http://proxy.corp.example:8080\nSSL_CERT_FILE=/etc/ssl/corp.pem\n" + writeHomeFile(t, envPath, mine) + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, "\n Uninstalled.\n") + if strings.Contains(out, "Codex") { + t.Errorf("uninstall offered to change a Codex that Cortex did not route:\n%s", out) + } + if got := readFile(t, envPath); got != mine { + t.Errorf("~/.codex/.env is %q, want it untouched", got) + } +} + +// A managed key whose value is not Cortex's, here a CA bundle swapped in after enable, is +// the user's. Uninstall takes out Cortex's values, leaves that one and says so, where +// disable would remove it with the rest. +func TestUninstallLeavesACodexValueOfTheUsers(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + const corp = "/etc/ssl/corp.pem" + ours := envSSLCert + "=" + readCodexEnv(t, envPath)[envSSLCert] + writeHomeFile(t, envPath, strings.Replace(readFile(t, envPath), ours, envSSLCert+"="+corp, 1)) + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 1, out, markLine("!", "unrouted")+"removed what Cortex set\n", + "\n Left behind:\n "+envSSLCert+" in ~/.codex/.env, not Cortex's values — left as they are\n") + if got := readCodexEnv(t, envPath); !maps.Equal(got, map[string]string{envSSLCert: corp}) { + t.Errorf("~/.codex/.env holds %v, want only the user's %s", got, envSSLCert) + } +} + +// A dotenv file that defines a managed key twice is one disable refuses to guess about, so +// the row fails with the lines to fix by hand. Its SSL_CERT_FILE still names Cortex's CA +// bundle, so --purge keeps ~/.cortex rather than leave Codex trusting a file that is gone, +// and the consent screen never offers the delete. +func TestUninstallPurgeKeepsCortexForACodexItCannotUnroute(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + writeHomeFile(t, envPath, readFile(t, envPath)+"HTTP_PROXY="+cortexProxyURL+"\n") + code, out := sc.uninstall(t, "--yes", "--purge") + wantLines(t, code, 1, out, markLine("✗", "unrouted"), + markLine("·", "purged")+"kept ~/.cortex: "+envSSLCert+ + " in ~/.codex/.env still points into it — delete it once nothing points into it: rm -rf ~/.cortex\n") + fixes := strings.Join(fixesUnder(out, markLine("✗", "unrouted")), "\n") + if !strings.Contains(fixes, "in ~/.codex/.env, remove the lines that set ") || !strings.Contains(fixes, codexDaemonRestartCmd) { + t.Errorf("the fix rows are %q, want the dotenv lines to remove and the restart:\n%s", fixes, out) + } + if _, err := os.Stat(filepath.Join(sc.home, ".cortex", "config.yaml")); err != nil { + t.Errorf("--purge deleted ~/.cortex while Codex's %s named its CA: %v", envSSLCert, err) + } + if row := consentRow(out, "delete"); strings.Contains(row, ".cortex") { + t.Errorf("--purge asked to delete ~/.cortex and then kept it: %q", row) + } +} + +// What still has Cortex's proxy after the row's restart is left behind with the command +// that clears it: an app-server the restart did not replace, an updater that would not +// stop, and an app-server whose proxy came from somewhere other than the file. +func TestUninstallNamesWhatACodexRestartLeaves(t *testing.T) { + for _, tc := range []struct { + name string + tweak func(*fakeCodexDaemon) + left string + }{ + {"restart fails", func(f *fakeCodexDaemon) { f.restartErr = errors.New("daemon lock held") }, + "Codex's app-server, which may still use Cortex's proxy — restart it: " + codexDaemonRestartCmd}, + {"updater would not stop", func(f *fakeCodexDaemon) { f.stopErr = errors.New("it would not stop") }, + "Codex's auto-updater (pid 4103), which still has Cortex's proxy — stop it, then restart the app-server: kill 4103 && " + codexDaemonRestartCmd}, + {"proxy from elsewhere", func(f *fakeCodexDaemon) { f.newEnv = onCortex }, + "Codex's app-server (pid 4102), which still has Cortex's proxy from the environment it started in — restart it from a shell without one: " + codexDaemonRestartCmd}, + } { + t.Run(tc.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + f := runningCodex() + tc.tweak(f) + envPath := codexEnabledIn(t, sc, f) + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 1, out, markLine("!", "unrouted")+"Codex no longer goes through Cortex", "\n Left behind:\n", " "+tc.left+"\n") + if got := readCodexEnv(t, envPath); len(got) != 0 { + t.Errorf("Cortex's values survived the unroute: %v", got) + } + }) + } +} + +// Every agent configure status lists, routed through Cortex, comes out of uninstall +// unrouted by configure status's own verdict. The agents are that list's, not this +// test's, so one added there that uninstall does not unroute fails here: Codex was routed +// by configure codex and skipped by uninstall for a month (#1365). +func TestUninstallUnroutesEveryConfiguredAgent(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t, "--claude-code") + t.Setenv("SHELL", "/bin/zsh") + t.Setenv(piAgentDirEnv, "") + for _, v := range []string{bobShellEnvVar, piShellEnvVar} { + t.Setenv(v, "") // restores the developer's value; the unset below is what the test sees + if err := os.Unsetenv(v); err != nil { + t.Fatal(err) + } + } + saved := configureFindOpenCode + configureFindOpenCode = func() (string, error) { return "", errors.New("no opencode in this scene yet") } + t.Cleanup(func() { configureFindOpenCode = saved }) + + rc := filepath.Join(sc.home, ".zshrc") + enable := map[string]func(){ + "claude-code": func() {}, // setup's --claude-code + "bob": func() { + enableBobShellAt(t, rc) + if runtime.GOOS != "darwin" { + return // Bob the IDE's settings exist only on macOS + } + bob, err := bobSettingsPath(sc.home) + if err != nil { + t.Fatal(err) + } + writeHomeFile(t, bob, "{}\n") + want, _ := bobWanted(filepath.Join(sc.home, cortexCfgRel), sc.home) + if err := bobWriteKey(bob, bobProxyKey, want); err != nil { + t.Fatal(err) + } + }, + "opencode": func() { + openCodeEnabled(t, sc, false) + configureFindOpenCode = func() (string, error) { return fakeOpenCodePath, nil } + }, + "codex": func() { codexEnabledIn(t, sc, &fakeCodexDaemon{}) }, + "pi": func() { + var out, errb bytes.Buffer + if code := runPi([]string{"enable", "--yes"}, &out, &errb); code != 0 { + t.Fatalf("fixture: configure pi enable = %d\n%s%s", code, out.String(), errb.String()) + } + }, + } + states := func() map[string]configureState { + got := map[string]configureState{} + for _, fn := range configureStatusFuncs() { + r := fn(sc.home) + got[r.Agent] = r.State + } + return got + } + listed := states() + for agent := range listed { + if enable[agent] == nil { + t.Fatalf("configure status lists %q, which this test does not route: add it to enable here, "+ + "and give planUninstall a row that unroutes it", agent) + } + } + for _, agent := range slices.Sorted(maps.Keys(enable)) { + if _, ok := listed[agent]; !ok { + t.Errorf("enable routes %q, which configure status no longer lists", agent) + } + enable[agent]() + } + // Partial counts as routed: on Linux, Bob has its shell half only. + routed := func(s configureState) bool { return s == configureOn || s == configurePartial } + for agent, s := range states() { + if !routed(s) { + t.Fatalf("fixture: %s reads %v once enabled, want it routed", agent, s) + } + } + if code, out := sc.uninstall(t, "--yes"); code != 0 { + t.Fatalf("uninstall exit %d:\n%s", code, out) + } + for agent, s := range states() { + if routed(s) { + t.Errorf("%s still reads %v after uninstall", agent, s) + } + } +} diff --git a/cmd/agentop/configure_status.go b/cmd/agentop/configure_status.go index 66e1f3525..9dcc72524 100644 --- a/cmd/agentop/configure_status.go +++ b/cmd/agentop/configure_status.go @@ -80,6 +80,11 @@ type configureStatus struct { Detail string } +// configureFindOpenCode finds the opencode CLI the OpenCode row reads with. A var for +// the reason uninstallFindOpenCode is one: a test names a fake one, and no test may run +// the real one. +var configureFindOpenCode = findOpenCode + // configureStatusFuncs is the table's source: one closure per agent, in the order // configureUsage lists them. // @@ -98,6 +103,10 @@ type configureStatus struct { // defaultCodexEnvPath, findOpenCode and cortexCfgRel rather than through two copies of // the same join. None of them may return an error: see runConfigureStatus on why one // agent's missing file must not end the table. +// +// It is also the list of agents agentop routes: TestUninstallUnroutesEveryConfiguredAgent +// enables each one here and checks that uninstall unroutes it, so an agent added to +// this list without an uninstall row fails that test. func configureStatusFuncs() []func(home string) configureStatus { return []func(home string) configureStatus{ func(home string) configureStatus { @@ -107,7 +116,7 @@ func configureStatusFuncs() []func(home string) configureStatus { return bobRow(home) }, func(home string) configureStatus { - bin, err := findOpenCode() + bin, err := configureFindOpenCode() if err != nil { // The CLI is how OpenCode's service environment is read at all, so // without it there is nothing to read — "uncertain", not "not diff --git a/docs/agents/codex.md b/docs/agents/codex.md index 6903af17d..fbecf7775 100644 --- a/docs/agents/codex.md +++ b/docs/agents/codex.md @@ -18,6 +18,8 @@ Codex's dotenv file, and removes it again. `pending:codex@…` bucket with no tokens means that the daemon did not restart. `agentop configure codex status` shows what is set, and if the daemon uses Cortex. 4. Undo: `agentop configure codex disable`. It restarts the daemon in the same way. + `agentop uninstall` does the same undo for Codex before it removes Cortex. See + [When you uninstall Cortex](#when-you-uninstall-cortex). ## On a Chat Completions server @@ -540,6 +542,19 @@ OpenAI: lsof -nP -a -p "$(pgrep -f 'codex app-server --listen')" -iTCP -sTCP:ESTABLISHED ``` +### When you uninstall Cortex + +`agentop uninstall` unroutes Codex before it stops the proxy: it removes each of the five +variables whose value is Cortex's, deletes the record, and restarts a running app-server +the way `disable` does. Unlike `disable`, it leaves a variable whose value is not Cortex's, +such as a proxy or CA bundle of your own, and lists it under *Left behind*, because it +changes everything on one question. When it cannot change the file, for example when a +variable is defined twice, `--purge` keeps `~/.cortex`, since Codex's `SSL_CERT_FILE` still +names the CA bundle there. + +`agentop uninstall` in v0.9.5 and earlier skipped Codex. If you uninstalled with one of +those, Codex still points at a proxy that is gone: undo it by hand, as below. + ### Undoing it by hand Without `agentop`: open `$CODEX_HOME/.env` (or `~/.codex/.env`) and remove the lines for the five variables above, diff --git a/docs/laptop-service.md b/docs/laptop-service.md index 2525e8f82..951ac5daf 100644 --- a/docs/laptop-service.md +++ b/docs/laptop-service.md @@ -137,8 +137,9 @@ agentop uninstall --purge ``` `agentop uninstall` lists what it will remove and asks once; `--yes` skips the question. -It unroutes Claude Code, OpenCode, IBM Bob, the `bob` and `pi` shell functions and Pi's -session extension where Cortex routed them, restarting OpenCode's background service when it finds it running. It +It unroutes Claude Code, OpenCode, Codex, IBM Bob, the `bob` and `pi` shell functions and Pi's +session extension where Cortex routed them, restarting OpenCode's background service and +Codex's app-server when it finds them running. It stops and removes the service, or the background proxy. It removes the PATH lines setup added, unless other tools in `~/.local/bin` still need them, and removes `agentop`, `cortex`, `cortex-session-dump` and `cortex-gateway` from `~/.local/bin`. A step that fails is reported From 4f2725c1f2734a9d4036e07f5adcb44a1a721962 Mon Sep 17 00:00:00 2001 From: Alan Cha Date: Thu, 12 Nov 2026 04:40:56 -0500 Subject: [PATCH 2/6] test: Read Bob's shell function from disk in the every-agent uninstall test TestUninstallUnroutesEveryConfiguredAgent failed on Linux CI with "bob reads uncertain once enabled". configure status judges Bob's shell function by CORTEX_BOBSHELL in agentop's own environment, never by the rc file, and on Linux Bob the IDE has no settings to read, so status cannot see Bob there before or after uninstall. On macOS the editor half hid this. The test now reads what configure status cannot see from disk: for Bob, the shell block in the rc file. Checked on macOS with the Linux branch forced: the old test fails as CI did, the new one passes, and it fails again when uninstall leaves the bob shell function behind. Assisted-By: Claude (Anthropic AI) Signed-off-by: Alan Cha --- cmd/agentop/cmd_uninstall_test.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index 666e7d3eb..0807e0e25 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -1903,10 +1903,21 @@ func TestUninstallUnroutesEveryConfiguredAgent(t *testing.T) { } enable[agent]() } - // Partial counts as routed: on Linux, Bob has its shell half only. - routed := func(s configureState) bool { return s == configureOn || s == configurePartial } + // What configure status cannot see is read from disk instead. It judges Bob's shell + // function by CORTEX_BOBSHELL in agentop's own environment, never by the rc file, so + // that half is the rc block here. On Linux, where Bob the IDE has no settings to read, + // it is all there is of Bob: status reads "uncertain" before and after. + onDisk := map[string]func() bool{ + "bob": func() bool { return strings.Contains(readFile(t, rc), bobShellMarkerStart) }, + } + routed := func(agent string, s configureState) bool { + if s == configureOn || s == configurePartial { + return true + } + return onDisk[agent] != nil && onDisk[agent]() + } for agent, s := range states() { - if !routed(s) { + if !routed(agent, s) { t.Fatalf("fixture: %s reads %v once enabled, want it routed", agent, s) } } @@ -1914,8 +1925,8 @@ func TestUninstallUnroutesEveryConfiguredAgent(t *testing.T) { t.Fatalf("uninstall exit %d:\n%s", code, out) } for agent, s := range states() { - if routed(s) { - t.Errorf("%s still reads %v after uninstall", agent, s) + if routed(agent, s) { + t.Errorf("%s is still routed after uninstall (configure status reads %v)", agent, s) } } } From db799df912635904e9b463050313838a773000e8 Mon Sep 17 00:00:00 2001 From: Alan Cha Date: Thu, 12 Nov 2026 05:14:25 -0500 Subject: [PATCH 3/6] fix: Find Cortex's line in a duplicated key, and stop the updater by hand From review of the uninstall Codex row: - A key defined twice was judged by its first line only, while Codex uses the last. With the user's HTTPS_PROXY first and Cortex's last, the row was skipped and Codex kept a proxy that uninstall then stopped. A key is now Cortex's when any of its lines is, so the row appears and fails on the duplicate with its fix. Duplicates that are all the user's still get no row. - The by-hand fix restarted the app-server only. Codex's restart keeps a running auto-updater, and Codex has no command that stops one, so the updater kept the proxy and handed it to the next app-server. The fix line and docs/agents/codex.md now stop it by command line first, never by its recorded pid. The brackets in the pattern keep pkill from matching the shell that runs it. - The by-hand fix named three of the five keys; it names them all. - An updater the row could not stop is now named whether or not the restart works and whether or not its environment can be read: it kept the one it started with. Assisted-By: Claude (Anthropic AI) Signed-off-by: Alan Cha --- cmd/agentop/cmd_codex.go | 13 ++++ cmd/agentop/cmd_uninstall.go | 124 +++++++++++++++++++----------- cmd/agentop/cmd_uninstall_test.go | 103 ++++++++++++++++++++++--- cmd/agentop/codex_daemon_test.go | 3 +- docs/agents/codex.md | 10 ++- 5 files changed, 194 insertions(+), 59 deletions(-) diff --git a/cmd/agentop/cmd_codex.go b/cmd/agentop/cmd_codex.go index 77bb58f01..a5c44ad05 100644 --- a/cmd/agentop/cmd_codex.go +++ b/cmd/agentop/cmd_codex.go @@ -321,6 +321,19 @@ func (f *codexEnvFile) get(key string) (string, bool) { return m[2], true } +// all returns every value the file defines key as, in file order: one for a key defined +// once, more for a duplicate, of which Codex uses the last (dotenvy is last-wins). get +// gives only the first. +func (f *codexEnvFile) all(key string) []string { + var vals []string + for _, line := range f.lines { + if m := codexEnvLineRe.FindStringSubmatch(line); m != nil && m[1] == key { + vals = append(vals, m[2]) + } + } + return vals +} + // ambiguous names every key in keys defined more than once in the file. func (f *codexEnvFile) ambiguous(keys []string) []string { var out []string diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index 4ae6bf9c1..332366b90 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -791,15 +791,25 @@ func planUnrouteCodex(env *setupEnv) (removal, bool) { cortexProxy := want["HTTPS_PROXY"] if readErr == nil { for _, k := range codexKeys { - v, ok := f.get(k) - switch { - case !ok: - case codexIsOurs(k, v, want): - ours = append(ours, k) - if k == "HTTPS_PROXY" || (k == "https_proxy" && cortexProxy == "") { - cortexProxy = v + vals := f.all(k) + if len(vals) == 0 { + continue + } + // Every definition, not only the first that get returns: Codex uses the last + // of a duplicated key, so a line of Cortex's anywhere is Cortex's to unroute. + // The plan then refuses the duplicate, and the row fails with its fix. + cortexs := false + for _, v := range vals { + if codexIsOurs(k, v, want) { + cortexs = true + if k == "HTTPS_PROXY" || (k == "https_proxy" && cortexProxy == "") { + cortexProxy = v + } } - default: + } + if cortexs { + ours = append(ours, k) + } else { theirs = append(theirs, k) } } @@ -851,26 +861,38 @@ func planUnrouteCodex(env *setupEnv) (removal, bool) { return detail + notes, left, nil } // A failed stop is not this row's ✗, as it is not disable's: the restart still - // applies the change, and codexLeftAfterRestart names an updater left on the - // old proxy. - _ = codexStopUpdater(codexHome) + // applies the change to the daemon. It is remembered, so the updater it left on + // the old proxy is named whether or not the restart works. + stopFailed := codexStopUpdater(codexHome) != nil if err := codexRestartDaemon(codexHome, want); err != nil { - return detail + notes, append(left, "Codex's app-server, which may still use Cortex's proxy — restart it: "+codexDaemonRestartCmd), nil + left = append(left, "Codex's app-server, which may still use Cortex's proxy — restart it: "+codexDaemonRestartCmd) + return detail + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, stopFailed)...), nil } - return detail + " · restarted its app-server" + notes, append(left, codexLeftAfterRestart(codexHome, cortexProxy)...), nil + left = append(left, codexDaemonLeft(codexHome, cortexProxy)...) + return detail + " · restarted its app-server" + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, stopFailed)...), nil }, }, true } +// codexUpdaterStopByHand stops Codex's auto-updater without agentop. Codex's restart keeps +// a running updater (codexUpdaterPIDRel) and Codex has no command that stops one, so it is +// matched by its command line: never by the pid in its record, which may name another +// process by then (#1736). The brackets keep the pattern from matching the shell that +// runs it, as `sh -c "…"` would show the pattern's own text in its command line. +const codexUpdaterStopByHand = "pkill -f 'app-server daemon pid-update-loo[p]'" + // codexByHand is the Codex row's change as fix lines, for when agentop is gone: the lines -// to delete from the dotenv file, then the restart. It names no value, as unrouteByHand -// names none. With no keys, from a file that could not be read, it names all five. +// to delete from the dotenv file, then the auto-updater and the app-server, which read it +// only when they start. Every key is named, not someKeys' first three: with agentop gone, +// the user has nothing else to ask. It names no value, as unrouteByHand names none. With +// no keys, from a file that could not be read, it names all five. The `;` runs the restart +// when no updater was running, for which pkill exits 1. func codexByHand(env *setupEnv, envPath string, keys []string) string { if len(keys) == 0 { keys = codexKeys } - return "in " + env.tilde(envPath) + ", remove the lines that set " + someKeys(keys) + " to Cortex's values\n" + - "then, if Codex's app-server runs: " + codexDaemonRestartCmd + return "in " + env.tilde(envPath) + ", remove the lines that set " + strings.Join(keys, ", ") + " to Cortex's values\n" + + "then, if Codex's app-server runs: " + codexUpdaterStopByHand + "; " + codexDaemonRestartCmd } // codexNeedsCortexDir is why --purge must keep ~/.cortex: the managed keys of envPath that @@ -889,26 +911,31 @@ func codexNeedsCortexDir(env *setupEnv, envPath, state string, f *codexEnvFile, removed[k] = true } } - after := map[string]string{} + // What each key holds once the row has run: every definition it does not remove, a + // duplicate's included, and what applyCodexDisable restores from enable's record when + // the record is this file's. + after := map[string][]string{} for _, k := range codexKeys { - if v, ok := f.get(k); ok && !removed[k] { - after[k] = v + if !removed[k] { + after[k] = f.all(k) } } if planned { - // What applyCodexDisable restores: enable's record, when it is this file's. if st, _ := readState(state); st != nil && st.Settings == envPath { for _, k := range ours { if p := st.Prior[k]; p != nil { - after[k] = *p + after[k] = []string{*p} } } } } var keys []string for _, k := range codexKeys { - if pathUnder(env.cortexDir, after[k]) { - keys = append(keys, k) + for _, v := range after[k] { + if pathUnder(env.cortexDir, v) { + keys = append(keys, k) + break + } } } if len(keys) == 0 { @@ -917,37 +944,48 @@ func codexNeedsCortexDir(env *setupEnv, envPath, state string, f *codexEnvFile, return someKeys(keys) + " in " + env.tilde(envPath) + " still points into it" } -// codexLeftAfterRestart is what still has Cortex's proxy once the Codex row has restarted -// the app-server. The daemon, when that proxy reached it from somewhere other than the -// dotenv file. And the auto-updater, when stopping it failed, since the daemon it starts -// after its next update inherits its proxy — named only when codexIsRecorded confirms it, -// as reportRestartedUpdater names it, so a reused pid is never given a kill command. -func codexLeftAfterRestart(codexHome, cortexProxy string) []string { +// codexDaemonLeft names the app-server the Codex row restarted when it still has Cortex's +// proxy, which then reached it from somewhere other than the dotenv file. +func codexDaemonLeft(codexHome, cortexProxy string) []string { if cortexProxy == "" { return nil } - var left []string if d, ok := runningCodexDaemon(codexHome); ok && d.EnvErr == nil && sameProxy(d.Proxy, cortexProxy) { - left = append(left, fmt.Sprintf("Codex's app-server (pid %d), which still has Cortex's proxy from the environment it started in — "+ - "restart it from a shell without one: %s", d.PID, codexDaemonRestartCmd)) + return []string{fmt.Sprintf("Codex's app-server (pid %d), which still has Cortex's proxy from the environment it started in — "+ + "restart it from a shell without one: %s", d.PID, codexDaemonRestartCmd)} } + return nil +} + +// codexUpdaterLeft names an auto-updater that may still have Cortex's proxy after the +// Codex row ran, since the app-server it starts after its next update inherits that +// proxy. stopFailed is whether the row's stop failed. That updater is named whatever its +// environment reads, or fails to: it was not replaced, so it still has the environment +// it started with. Otherwise only one whose environment shows Cortex's proxy is. It names +// a pid only when codexIsRecorded confirms the process, as reportRestartedUpdater does, +// so a reused pid is never given a kill command. +func codexUpdaterLeft(codexHome, cortexProxy string, stopFailed bool) []string { u, ok := runningCodexUpdater(codexHome) if !ok { - return left + return nil } switch codexIsRecorded(u) { case codexRecordStale: - // The restart found the record stale and started a fresh updater. + // A restart finds the record stale and starts a fresh updater. + return nil case codexRecordUnknown: - left = append(left, "Codex's auto-updater, which agentop could not confirm picked up the change — "+ - "if Codex cannot connect after its next update, restart your computer") - default: - if u.EnvErr == nil && sameProxy(u.Proxy, cortexProxy) { - left = append(left, fmt.Sprintf("Codex's auto-updater (pid %d), which still has Cortex's proxy — "+ - "stop it, then restart the app-server: kill %d && %s", u.PID, u.PID, codexDaemonRestartCmd)) - } + return []string{"Codex's auto-updater, which agentop could not confirm picked up the change — " + + "if Codex cannot connect after its next update, restart your computer"} } - return left + switch { + case stopFailed: + return []string{fmt.Sprintf("Codex's auto-updater (pid %d), which agentop could not stop, so it may still have Cortex's proxy — "+ + "stop it, then restart the app-server: kill %d && %s", u.PID, u.PID, codexDaemonRestartCmd)} + case u.EnvErr == nil && cortexProxy != "" && sameProxy(u.Proxy, cortexProxy): + return []string{fmt.Sprintf("Codex's auto-updater (pid %d), which still has Cortex's proxy — "+ + "stop it, then restart the app-server: kill %d && %s", u.PID, u.PID, codexDaemonRestartCmd)} + } + return nil } // planUnrouteBob removes IBM Bob's proxy setting when it may be Cortex's: one diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index 0807e0e25..f754b88a3 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -11,6 +11,7 @@ import ( "os/exec" "path/filepath" "reflect" + "regexp" "runtime" "slices" "strconv" @@ -1790,9 +1791,14 @@ func TestUninstallPurgeKeepsCortexForACodexItCannotUnroute(t *testing.T) { wantLines(t, code, 1, out, markLine("✗", "unrouted"), markLine("·", "purged")+"kept ~/.cortex: "+envSSLCert+ " in ~/.codex/.env still points into it — delete it once nothing points into it: rm -rf ~/.cortex\n") - fixes := strings.Join(fixesUnder(out, markLine("✗", "unrouted")), "\n") - if !strings.Contains(fixes, "in ~/.codex/.env, remove the lines that set ") || !strings.Contains(fixes, codexDaemonRestartCmd) { - t.Errorf("the fix rows are %q, want the dotenv lines to remove and the restart:\n%s", fixes, out) + // Every key, not someKeys' first three, since agentop is gone; and the updater + // stopped before the restart, which would otherwise keep it on the proxy. + fixes := fixesUnder(out, markLine("✗", "unrouted")) + if want := []string{ + "in ~/.codex/.env, remove the lines that set HTTP_PROXY, HTTPS_PROXY, http_proxy, https_proxy, " + envSSLCert + " to Cortex's values", + "then, if Codex's app-server runs: " + codexUpdaterStopByHand + "; " + codexDaemonRestartCmd, + }; !slices.Equal(fixes, want) { + t.Errorf("the fix rows are %q, want %q:\n%s", fixes, want, out) } if _, err := os.Stat(filepath.Join(sc.home, ".cortex", "config.yaml")); err != nil { t.Errorf("--purge deleted ~/.cortex while Codex's %s named its CA: %v", envSSLCert, err) @@ -1804,19 +1810,31 @@ func TestUninstallPurgeKeepsCortexForACodexItCannotUnroute(t *testing.T) { // What still has Cortex's proxy after the row's restart is left behind with the command // that clears it: an app-server the restart did not replace, an updater that would not -// stop, and an app-server whose proxy came from somewhere other than the file. +// stop, and an app-server whose proxy came from somewhere other than the file. An updater +// that would not stop is named whatever else happened: when the restart fails too, and +// when its environment cannot be read, since either way it kept the one it started with. func TestUninstallNamesWhatACodexRestartLeaves(t *testing.T) { + const ( + appServer = "Codex's app-server, which may still use Cortex's proxy — restart it: " + codexDaemonRestartCmd + unstopped = "Codex's auto-updater (pid 4103), which agentop could not stop, so it may still have Cortex's proxy — " + + "stop it, then restart the app-server: kill 4103 && " + codexDaemonRestartCmd + ) for _, tc := range []struct { name string tweak func(*fakeCodexDaemon) - left string + left []string }{ - {"restart fails", func(f *fakeCodexDaemon) { f.restartErr = errors.New("daemon lock held") }, - "Codex's app-server, which may still use Cortex's proxy — restart it: " + codexDaemonRestartCmd}, - {"updater would not stop", func(f *fakeCodexDaemon) { f.stopErr = errors.New("it would not stop") }, - "Codex's auto-updater (pid 4103), which still has Cortex's proxy — stop it, then restart the app-server: kill 4103 && " + codexDaemonRestartCmd}, - {"proxy from elsewhere", func(f *fakeCodexDaemon) { f.newEnv = onCortex }, - "Codex's app-server (pid 4102), which still has Cortex's proxy from the environment it started in — restart it from a shell without one: " + codexDaemonRestartCmd}, + {"restart fails", func(f *fakeCodexDaemon) { f.restartErr = errors.New("daemon lock held") }, []string{appServer}}, + {"updater would not stop", func(f *fakeCodexDaemon) { f.stopErr = errors.New("it would not stop") }, []string{unstopped}}, + {"updater would not stop, and restart fails", func(f *fakeCodexDaemon) { + f.stopErr, f.restartErr = errors.New("it would not stop"), errors.New("daemon lock held") + }, []string{appServer, unstopped}}, + {"updater would not stop, its environment unreadable", func(f *fakeCodexDaemon) { + f.stopErr, f.updaterEnvErr = errors.New("it would not stop"), errors.New("operation not permitted") + }, []string{unstopped}}, + {"proxy from elsewhere", func(f *fakeCodexDaemon) { f.newEnv, f.newUpdaterPID = onCortex, 0 }, []string{ + "Codex's app-server (pid 4102), which still has Cortex's proxy from the environment it started in — restart it from a shell without one: " + codexDaemonRestartCmd, + }}, } { t.Run(tc.name, func(t *testing.T) { sc := newUninstallScene(t) @@ -1825,7 +1843,11 @@ func TestUninstallNamesWhatACodexRestartLeaves(t *testing.T) { tc.tweak(f) envPath := codexEnabledIn(t, sc, f) code, out := sc.uninstall(t, "--yes") - wantLines(t, code, 1, out, markLine("!", "unrouted")+"Codex no longer goes through Cortex", "\n Left behind:\n", " "+tc.left+"\n") + want := []string{markLine("!", "unrouted") + "Codex no longer goes through Cortex", "\n Left behind:\n"} + for _, l := range tc.left { + want = append(want, " "+l+"\n") + } + wantLines(t, code, 1, out, want...) if got := readCodexEnv(t, envPath); len(got) != 0 { t.Errorf("Cortex's values survived the unroute: %v", got) } @@ -1833,6 +1855,63 @@ func TestUninstallNamesWhatACodexRestartLeaves(t *testing.T) { } } +// Codex uses the last definition of a duplicated key, and get reads only the first. A +// file whose first HTTPS_PROXY is the user's and whose last is Cortex's still routes +// Codex through Cortex, so it gets a row, which fails on the duplicate with its fix; a +// file whose duplicates are all the user's gets none. +func TestUninstallFindsCortexsLineInADuplicatedKey(t *testing.T) { + const corp = "HTTPS_PROXY=http://proxy.corp.example:8080\n" + for _, tc := range []struct { + name, env string + row bool + }{ + {"Cortex's line last", corp + "HTTPS_PROXY=" + cortexProxyURL + "\n", true}, + {"only the user's lines", corp + "HTTPS_PROXY=http://proxy2.corp.example:8080\n", false}, + } { + t.Run(tc.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + t.Setenv(codexHomeEnv, "") + stubCodexDaemon(t, filepath.Join(sc.home, ".codex"), &fakeCodexDaemon{}) + envPath := filepath.Join(sc.home, codexEnvRel) + writeHomeFile(t, envPath, tc.env) + code, out := sc.uninstall(t, "--yes") + if got := readFile(t, envPath); got != tc.env { + t.Errorf("~/.codex/.env is %q, want it untouched", got) + } + if !tc.row { + wantLines(t, code, 0, out, "\n Uninstalled.\n") + if strings.Contains(out, "Codex") { + t.Errorf("uninstall offered to change a Codex that Cortex did not route:\n%s", out) + } + return + } + wantLines(t, code, 1, out, markLine("✗", "unrouted")+"~/.codex/.env defines HTTPS_PROXY more than once") + if fixes := fixesUnder(out, markLine("✗", "unrouted")); len(fixes) == 0 || !strings.Contains(fixes[0], "remove the lines that set HTTPS_PROXY to Cortex's values") { + t.Errorf("the fix rows are %q, want the HTTPS_PROXY line to remove:\n%s", fixes, out) + } + }) + } +} + +// The by-hand updater stop matches the updater's command line, and not its own: a shell +// that runs it, as `sh -c "…"` would, carries the pattern's text in its command line, and +// pkill -f would end that shell before the restart after it ran. +func TestCodexUpdaterStopByHandMatchesTheUpdaterNotItself(t *testing.T) { + pattern := strings.TrimSuffix(strings.TrimPrefix(codexUpdaterStopByHand, "pkill -f '"), "'") + re := regexp.MustCompile(pattern) + for cmdline, want := range map[string]bool{ + "/Users/someone/.codex/packages/standalone/current/codex app-server daemon pid-update-loop": true, + "codex app-server daemon pid-update-loop": true, + "sh -c " + codexUpdaterStopByHand + "; " + codexDaemonRestartCmd: false, + "codex app-server --managed-daemon": false, + } { + if got := re.MatchString(cmdline); got != want { + t.Errorf("%q matched %q: %v, want %v", pattern, cmdline, got, want) + } + } +} + // Every agent configure status lists, routed through Cortex, comes out of uninstall // unrouted by configure status's own verdict. The agents are that list's, not this // test's, so one added there that uninstall does not unroute fails here: Codex was routed diff --git a/cmd/agentop/codex_daemon_test.go b/cmd/agentop/codex_daemon_test.go index b593cbdae..fc6c913ef 100644 --- a/cmd/agentop/codex_daemon_test.go +++ b/cmd/agentop/codex_daemon_test.go @@ -38,6 +38,7 @@ type fakeCodexDaemon struct { updaterPID int updaterEnv []string + updaterEnvErr error // the updater's environment cannot be read newUpdaterPID int // the updater a restart starts when none is running stopErr error // stopping the updater fails, and it keeps running updaterReused bool // the updater's pid now names another process, so its record is stale @@ -79,7 +80,7 @@ func stubCodexDaemon(t *testing.T, codexHome string, f *fakeCodexDaemon) { case f.pid: return f.env, f.envErr case f.updaterPID: - return f.updaterEnv, nil + return f.updaterEnv, f.updaterEnvErr } t.Errorf("read the environment of pid %d, which is neither fake process", pid) return nil, errors.New("not a fake process") diff --git a/docs/agents/codex.md b/docs/agents/codex.md index fbecf7775..be82ba726 100644 --- a/docs/agents/codex.md +++ b/docs/agents/codex.md @@ -560,15 +560,19 @@ those, Codex still points at a proxy that is gone: undo it by hand, as below. Without `agentop`: open `$CODEX_HOME/.env` (or `~/.codex/.env`) and remove the lines for the five variables above, if they point at Cortex (a proxy on `localhost:476…`/`127.0.0.1:476…`, or a CA path under `~/.cortex/ca` unless you moved its `ca_dir`). Leave any that point elsewhere — they are not -Cortex's. Then delete the record, and restart Codex's background server so it stops using -the proxy. +Cortex's. Then delete the record, stop Codex's auto-updater, and restart Codex's background +server, so neither keeps using the proxy. The updater has to go first: `codex app-server +daemon restart` keeps a running updater, which still has the proxy and passes it to the +app-server it starts after its next update, and Codex has no command that stops one. The +`pkill` matches the updater by its command line; the brackets keep the pattern from +matching the shell that runs it. ```sh # Remove only lines matching these five keys, and only if they point at Cortex: # HTTP_PROXY HTTPS_PROXY http_proxy https_proxy SSL_CERT_FILE $EDITOR ~/.codex/.env rm -f ~/.cortex/codex-state.json -codex app-server daemon restart +pkill -f 'app-server daemon pid-update-loo[p]'; codex app-server daemon restart ``` ### CA trust From 169aaa06aed3fd26fd04ccff9dd45c803656f888 Mon Sep 17 00:00:00 2001 From: Alan Cha Date: Thu, 12 Nov 2026 05:59:38 -0500 Subject: [PATCH 4/6] fix: Know Cortex's Codex values with the TLS bridge off uninstall's Codex row read Cortex's values through codexWanted, which is enable's reading and refuses when the TLS bridge is off. The row then judged by shape alone, which a custom forward_proxy_addr or ca_dir does not have: on a custom port it left the four proxy values as the user's, and Codex on a proxy uninstall then stopped. Raised in review of #1783, whose disable has the same call. codexValues reads the same values through wantedFromConfig without enable's refusals, as OpenCode does, and codexWanted keeps them for enable. Assisted-By: Claude (Anthropic AI) Signed-off-by: Alan Cha --- cmd/agentop/cmd_codex.go | 28 +++++++++++++++++++++++++- cmd/agentop/cmd_uninstall.go | 2 +- cmd/agentop/cmd_uninstall_test.go | 33 +++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/cmd/agentop/cmd_codex.go b/cmd/agentop/cmd_codex.go index a5c44ad05..636a0a88a 100644 --- a/cmd/agentop/cmd_codex.go +++ b/cmd/agentop/cmd_codex.go @@ -228,6 +228,32 @@ func codexWanted(cortexCfgPath string) (map[string]string, error) { return nil, fmt.Errorf("%s has no tls_bridge.ca_dir, so Codex has no CA to trust;\n"+ " requests would fail certificate verification. Enable the TLS bridge first.", cortexCfgPath) } + return codexValuesFrom(want), nil +} + +// codexValues is Cortex's values for the five managed keys, for telling them from the +// user's: what codexWanted gives, without enable's refusals. A bridge turned off since +// enable changes nothing about the values enable wrote, and without them codexIsOurs +// falls back to their shape, which a custom forward_proxy_addr or ca_dir does not have: +// disable and uninstall would then call Cortex's own values the user's (#1783 review). +// OpenCode reads its values the same way. nil when the config cannot be read; a value +// the config does not give is left out, so it matches nothing. +func codexValues(cortexCfgPath string) map[string]string { + want, _, err := wantedFromConfig(cortexCfgPath) + if err != nil { + return nil + } + out := map[string]string{} + for k, v := range codexValuesFrom(want) { + if v != "" { + out[k] = v + } + } + return out +} + +// codexValuesFrom puts the values wantedFromConfig derived under Codex's five keys. +func codexValuesFrom(want map[string]string) map[string]string { proxy := want[envProxy] return map[string]string{ "HTTP_PROXY": proxy, @@ -238,7 +264,7 @@ func codexWanted(cortexCfgPath string) (map[string]string, error) { // vars resolve to — not the bare ca.crt envCACerts names. See the comment // at the top of this file for why SSL_CERT_FILE and not Codex's own name. envSSLCert: want[envSSLCert], - }, nil + } } // codexEnvLineRe matches a dotenv assignment as DOTENVY parses it, which is what diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index 332366b90..426e618d6 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -785,7 +785,7 @@ func planUnrouteCodex(env *setupEnv) (removal, bool) { state := filepath.Join(env.home, codexStateRel) // Judged by Cortex's values when its config gives them. Without them codexIsOurs // falls back to the value's shape, as disable does when Cortex is gone. - want, _ := codexWanted(env.configPath()) + want := codexValues(env.configPath()) f, readErr := parseCodexEnv(envPath) var ours, theirs []string cortexProxy := want["HTTPS_PROXY"] diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index f754b88a3..33a347d22 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -2009,3 +2009,36 @@ func TestUninstallUnroutesEveryConfiguredAgent(t *testing.T) { } } } + +// replaceIn replaces old with new in path once, and fails the test when old is not there, +// so a fixture edit that no longer matches the file it edits cannot pass unnoticed. +func replaceIn(t *testing.T, path, old, new string) { + t.Helper() + body := readFile(t, path) + if !strings.Contains(body, old) { + t.Fatalf("fixture: %s has no %q:\n%s", path, old, body) + } + writeHomeFile(t, path, strings.Replace(body, old, new, 1)) +} + +// Cortex's values are told from the user's by Cortex's config, even once its TLS bridge +// is turned off, which enable's own reading of the config refuses. Without them the +// values' shape decides, and on a custom port that calls the four proxy values the +// user's: uninstall would leave Codex on a proxy it then stops (#1783 review). +func TestUninstallUnroutesACodexOnACustomPortWithTheBridgeOff(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + cfg := filepath.Join(sc.home, cortexCfgRel) + replaceIn(t, cfg, "forward_proxy_addr: 127.0.0.1:47600", "forward_proxy_addr: 127.0.0.1:8081") + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + if got := readCodexEnv(t, envPath)["HTTPS_PROXY"]; got != "http://127.0.0.1:8081" { + t.Fatalf("fixture: enable set HTTPS_PROXY=%q, want the custom port", got) + } + replaceIn(t, cfg, "tls_bridge:\n mode: enabled\n", "tls_bridge:\n mode: disabled\n") + + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, markLine("✓", "unrouted")+"Codex no longer goes through Cortex\n") + if got := readCodexEnv(t, envPath); len(got) != 0 { + t.Errorf("Cortex's values survived the unroute: %v\n%s", got, out) + } +} From ed1ce64eb9385fe43a58063dbaddc7a86ec1d901 Mon Sep 17 00:00:00 2001 From: Alan Cha Date: Thu, 19 Nov 2026 12:16:53 -0500 Subject: [PATCH 5/6] fix: Unroute the Codex file enable's record names, as Claude Code's row does From review: the Codex row read only the default dotenv file, so a Codex enabled with --env, or with a CODEX_HOME the uninstalling shell does not have, stayed routed, and --purge then deleted the CA bundle its SSL_CERT_FILE named. The row also judged by shape which values were Cortex's, which a moved port or a different --config defeats. The row now has Claude Code's shape. planUnrouteCodex unroutes the file the record names, and the default file when one of its proxy lines is the proxy enable would write now. Each runs configure codex disable's plan unchanged: the managed keys, the marker comment and the record come out. Keeping a value the user changed since enable belongs to disable, in #1783, and the row will follow it there. Also from review: the auto-updater is stopped even when no app-server runs, since Codex's daemon stop leaves it running and uninstall is the last time agentop can, and the by-hand fix waits for the updater to exit before the restart, which would otherwise keep it. Assisted-By: Claude (Anthropic AI) Signed-off-by: Alan Cha --- cmd/agentop/cmd_uninstall.go | 191 +++++++++++++++++++----------- cmd/agentop/cmd_uninstall_test.go | 163 ++++++++++++++++++------- docs/agents/codex.md | 24 ++-- 3 files changed, 257 insertions(+), 121 deletions(-) diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index 426e618d6..c98db406f 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -381,7 +381,11 @@ func applyRemovals(env *setupEnv, ui *checklist.UI, removals []removal, sigs <-c // and config, as the service paths read the config. A run uses what its plan read. func planUninstall(env *setupEnv, opts uninstallOptions) []removal { rs := planUnrouteClaudeCode(env) - for _, plan := range []func(*setupEnv) (removal, bool){planUnrouteOpenCode, planUnrouteCodex, planUnrouteBob, planRemoveBobShell, planRemovePiShell, planRemovePiExtension, planStopService} { + if r, ok := planUnrouteOpenCode(env); ok { + rs = append(rs, r) + } + rs = append(rs, planUnrouteCodex(env)...) + for _, plan := range []func(*setupEnv) (removal, bool){planUnrouteBob, planRemoveBobShell, planRemovePiShell, planRemovePiExtension, planStopService} { if r, ok := plan(env); ok { rs = append(rs, r) } @@ -768,102 +772,142 @@ func openCodeByHand(env *setupEnv, cli string, pl openCodeDisablePlan, planned b return strings.Join(append(lines, restart), "\n") } -// planUnrouteCodex takes Cortex's values out of Codex's dotenv file, as configure codex -// disable does, when the file holds any. Only those: disable removes every managed key, -// but a value Cortex did not write — a corporate proxy, a CA bundle of the user's own — -// is the user's, and uninstall changes everything on one question, so the row leaves it -// and says so. The file is read now, as is enable's record, which --purge deletes. One -// that cannot be read fails the row only when that record says Cortex routed Codex. +// planUnrouteCodex is a removal for each dotenv file Cortex routed Codex through, as +// planUnrouteClaudeCode is for Claude Code's settings files: the one enable's record +// names, which --env or a CODEX_HOME may have put anywhere, and the default file +// ($CODEX_HOME/.env, else ~/.codex/.env) when one of its proxy lines is the proxy enable +// would write now. A file the record does not name is unrouted only then: disable +// without the record removes every managed key, a corporate proxy and CA included. The +// record is read now, before --purge can delete it. +func planUnrouteCodex(env *setupEnv) []removal { + state, def := filepath.Join(env.home, codexStateRel), defaultCodexEnvPath(env.home) + // Read without enable's refusals: a bridge turned off since enable changes nothing + // about what enable wrote (codexValues). + want := codexValues(env.configPath()) + named := "" + if st, err := readState(state); err == nil && st != nil { + named = st.Settings + } + var rs []removal + if named != "" { + rs = append(rs, unrouteCodex(env, named, state, want)) + } + if (named == "" || !samePath(named, def)) && codexProxyIn(def, want) { + // Without a record of its own: it restores nothing, and leaves the record alone + // unless the record names no file, as one that cannot be read does. + record := "" + if named == "" { + record = state + } + rs = append(rs, unrouteCodex(env, def, record, want)) + } + return rs +} + +// codexProxyIn reports whether any of envPath's proxy lines is the proxy enable would +// write from the current config, as cortexProxyIn asks of a Claude Code settings file. +// Every line of a duplicated key counts, since Codex uses the last and get gives the +// first. A file that cannot be read, or a config that gives no proxy, is not. +func codexProxyIn(envPath string, want map[string]string) bool { + proxy := want["HTTPS_PROXY"] + if proxy == "" { + return false + } + f, err := parseCodexEnv(envPath) + if err != nil { + return false + } + for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"} { + if slices.Contains(f.all(k), proxy) { + return true + } + } + return false +} + +// unrouteCodex is configure codex disable for one dotenv file, planned now: it removes +// the managed keys and enable's marker comment, restores what the record holds when the +// record is this file's, and deletes the record. state is that record, or "" for none. // -// A running app-server is restarted after the change, as disable restarts it, so it -// drops the proxy that is about to stop. Its auto-updater is stopped first, for the -// reason codexUpdaterPIDRel gives: left running, the next update would start a daemon on -// that proxy again. -func planUnrouteCodex(env *setupEnv) (removal, bool) { - envPath := defaultCodexEnvPath(env.home) +// Codex's auto-updater is stopped, and a running app-server restarted, as disable does, +// so neither keeps the proxy that is about to stop: both read the file only when they +// start (codexUpdaterPIDRel). The updater is stopped even when no app-server runs, since +// Codex's daemon stop leaves it running and uninstall is the last time agentop can. +func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) removal { codexHome := filepath.Dir(envPath) - state := filepath.Join(env.home, codexStateRel) - // Judged by Cortex's values when its config gives them. Without them codexIsOurs - // falls back to the value's shape, as disable does when Cortex is gone. - want := codexValues(env.configPath()) - f, readErr := parseCodexEnv(envPath) - var ours, theirs []string - cortexProxy := want["HTTPS_PROXY"] - if readErr == nil { + pl, planErr := planCodexDisable(envPath) + // Read here as well as by the plan: a file disable refuses, one defining a key twice, + // still names the keys to remove by hand and what may point into ~/.cortex. + f, _ := parseCodexEnv(envPath) + keys := pl.present + if planErr != nil && f != nil { for _, k := range codexKeys { - vals := f.all(k) - if len(vals) == 0 { - continue - } - // Every definition, not only the first that get returns: Codex uses the last - // of a duplicated key, so a line of Cortex's anywhere is Cortex's to unroute. - // The plan then refuses the duplicate, and the row fails with its fix. - cortexs := false - for _, v := range vals { - if codexIsOurs(k, v, want) { - cortexs = true - if k == "HTTPS_PROXY" || (k == "https_proxy" && cortexProxy == "") { - cortexProxy = v - } - } - } - if cortexs { - ours = append(ours, k) - } else { - theirs = append(theirs, k) + if len(f.all(k)) > 0 { + keys = append(keys, k) } } } - if (readErr != nil && !fileExists(state)) || (readErr == nil && len(ours) == 0) { - return removal{}, false + // The proxy the restarted processes are compared with: the one this file held, read + // before the row removes it, else the config's. + cortexProxy := want["HTTPS_PROXY"] + if f != nil { + for _, k := range []string{"https_proxy", "HTTPS_PROXY"} { + if v, ok := f.get(k); ok { + cortexProxy = v + } + } } - pl, planErr := planCodexDisable(envPath) - if planErr == nil { - pl.present = ours + where, suffix := env.tilde(envPath), "" + if !samePath(envPath, defaultCodexEnvPath(env.home)) { + suffix = " · " + env.tilde(envPath) } - where := env.tilde(envPath) if _, running := runningCodexDaemon(codexHome); running { where += " · restarts its app-server, interrupting running turns" } - fix := remedy{byHand: codexByHand(env, envPath, ours)} - if planErr == nil && len(theirs) == 0 { - // Not while a value is the user's: disable would remove that too. - fix.agentop = "agentop configure codex disable" + fix := remedy{byHand: codexByHand(env, envPath, keys)} + if planErr == nil { + fix.agentop = "agentop configure codex disable --env " + env.shellPath(envPath) } return removal{ label: "unrouted", item: checklist.Item{Verb: "unroute", What: "Codex", Where: where}, fix: fix, - needsCortexDir: codexNeedsCortexDir(env, envPath, state, f, planErr == nil, ours), + needsCortexDir: codexNeedsCortexDir(env, envPath, state, f, planErr == nil, keys), run: func(*checklist.Running) (string, []string, error) { unchanged := []string{env.tilde(envPath)} if planErr != nil { return "", unchanged, planErr } + if len(pl.present) == 0 { + // Nothing of Cortex's left in the file: removed by hand, say. The record + // would otherwise outlive it. + if state != "" { + if err := removeIfExists(state); err != nil { + return "", []string{env.tilde(state)}, withFixes(err, manual("rm "+env.shellPath(state))) + } + return "removed Cortex's record (" + env.tilde(envPath) + " had nothing routed)", nil, nil + } + return "nothing routed in " + env.tilde(envPath), nil, nil + } _, running := runningCodexDaemon(codexHome) var errb bytes.Buffer restored, err := applyCodexDisable(pl, state, &errb) if err != nil { return "", unchanged, err } - detail := "Codex no longer goes through Cortex" - var left []string - if len(theirs) > 0 { - // Not "no longer goes through Cortex": a proxy of the user's still routes it. - detail = "removed what Cortex set" - left = append(left, someKeys(theirs)+" in "+env.tilde(envPath)+", not Cortex's values — left as they are") - } + detail := "Codex no longer goes through Cortex" + suffix if len(restored) > 0 { detail += " · restored your " + strings.Join(restored, ", ") } notes := stderrNotes(env, errb.String()) - if !running { - return detail + notes, left, nil - } // A failed stop is not this row's ✗, as it is not disable's: the restart still // applies the change to the daemon. It is remembered, so the updater it left on // the old proxy is named whether or not the restart works. stopFailed := codexStopUpdater(codexHome) != nil + if !running { + return detail + notes, codexUpdaterLeft(codexHome, cortexProxy, stopFailed), nil + } + var left []string if err := codexRestartDaemon(codexHome, want); err != nil { left = append(left, "Codex's app-server, which may still use Cortex's proxy — restart it: "+codexDaemonRestartCmd) return detail + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, stopFailed)...), nil @@ -871,7 +915,7 @@ func planUnrouteCodex(env *setupEnv) (removal, bool) { left = append(left, codexDaemonLeft(codexHome, cortexProxy)...) return detail + " · restarted its app-server" + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, stopFailed)...), nil }, - }, true + } } // codexUpdaterStopByHand stops Codex's auto-updater without agentop. Codex's restart keeps @@ -881,18 +925,25 @@ func planUnrouteCodex(env *setupEnv) (removal, bool) { // runs it, as `sh -c "…"` would show the pattern's own text in its command line. const codexUpdaterStopByHand = "pkill -f 'app-server daemon pid-update-loo[p]'" +// codexUpdaterWaitByHand waits for that updater to exit. pkill only signals it, and +// Codex's restart starts a fresh updater only once the record names no live process, so +// a restart run straight after could keep the old one, proxy and all. +const codexUpdaterWaitByHand = "while pgrep -f 'app-server daemon pid-update-loo[p]' >/dev/null; do sleep 1; done" + // codexByHand is the Codex row's change as fix lines, for when agentop is gone: the lines -// to delete from the dotenv file, then the auto-updater and the app-server, which read it -// only when they start. Every key is named, not someKeys' first three: with agentop gone, -// the user has nothing else to ask. It names no value, as unrouteByHand names none. With -// no keys, from a file that could not be read, it names all five. The `;` runs the restart -// when no updater was running, for which pkill exits 1. +// to delete from the dotenv file, then the auto-updater, stopped and waited for, and the +// app-server, which read the file only when they start. Every key is named, not +// someKeys' first three: with agentop gone, the user has nothing else to ask. It names no +// value, as unrouteByHand names none. With no keys, from a file that could not be read, it +// names all five. The `;` runs the wait when no updater was running, for which pkill +// exits 1. func codexByHand(env *setupEnv, envPath string, keys []string) string { if len(keys) == 0 { keys = codexKeys } - return "in " + env.tilde(envPath) + ", remove the lines that set " + strings.Join(keys, ", ") + " to Cortex's values\n" + - "then, if Codex's app-server runs: " + codexUpdaterStopByHand + "; " + codexDaemonRestartCmd + return "in " + env.tilde(envPath) + ", remove the lines that set " + strings.Join(keys, ", ") + "\n" + + "then stop Codex's auto-updater and wait for it to exit: " + codexUpdaterStopByHand + "; " + codexUpdaterWaitByHand + "\n" + + "then, if Codex's app-server runs: " + codexDaemonRestartCmd } // codexNeedsCortexDir is why --purge must keep ~/.cortex: the managed keys of envPath that diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index 33a347d22..766754018 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -1698,8 +1698,8 @@ func runningCodex() *fakeCodexDaemon { // configure codex enable routes Codex through its dotenv file. Uninstall takes Cortex's // values out of it before the proxy stops and agentop goes, keeping the user's own line, -// and restarts an app-server that runs, its auto-updater stopped first, since both read -// the file only when they start. +// and restarts an app-server that runs. Its auto-updater is stopped first, and when no +// app-server runs too, since both read the file only when they start. func TestUninstallUnroutesCodex(t *testing.T) { for _, running := range []bool{true, false} { t.Run(fmt.Sprintf("running=%v", running), func(t *testing.T) { @@ -1711,11 +1711,12 @@ func TestUninstallUnroutesCodex(t *testing.T) { } envPath := codexEnabledIn(t, sc, f) code, out := sc.uninstall(t, "--yes") - where, done, steps := "~/.codex/.env", "Codex no longer goes through Cortex", []string(nil) + // The updater is stopped either way: Codex's daemon stop leaves it running. + where, done, steps := "~/.codex/.env", "Codex no longer goes through Cortex", []string{"stop-updater"} if running { where += " · restarts its app-server, interrupting running turns" done += " · restarted its app-server" - steps = []string{"stop-updater", "restart"} + steps = append(steps, "restart") } wantLines(t, code, 0, out, markLine("✓", "unrouted")+done+"\n", "\n Uninstalled.\n") if row := consentRow(out, "unroute"); !strings.Contains(row, " Codex ") || !strings.HasSuffix(row, where) { @@ -1760,24 +1761,6 @@ func TestUninstallLeavesACodexCortexDidNotRoute(t *testing.T) { } } -// A managed key whose value is not Cortex's, here a CA bundle swapped in after enable, is -// the user's. Uninstall takes out Cortex's values, leaves that one and says so, where -// disable would remove it with the rest. -func TestUninstallLeavesACodexValueOfTheUsers(t *testing.T) { - sc := newUninstallScene(t) - sc.setUp(t) - envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) - const corp = "/etc/ssl/corp.pem" - ours := envSSLCert + "=" + readCodexEnv(t, envPath)[envSSLCert] - writeHomeFile(t, envPath, strings.Replace(readFile(t, envPath), ours, envSSLCert+"="+corp, 1)) - code, out := sc.uninstall(t, "--yes") - wantLines(t, code, 1, out, markLine("!", "unrouted")+"removed what Cortex set\n", - "\n Left behind:\n "+envSSLCert+" in ~/.codex/.env, not Cortex's values — left as they are\n") - if got := readCodexEnv(t, envPath); !maps.Equal(got, map[string]string{envSSLCert: corp}) { - t.Errorf("~/.codex/.env holds %v, want only the user's %s", got, envSSLCert) - } -} - // A dotenv file that defines a managed key twice is one disable refuses to guess about, so // the row fails with the lines to fix by hand. Its SSL_CERT_FILE still names Cortex's CA // bundle, so --purge keeps ~/.cortex rather than leave Codex trusting a file that is gone, @@ -1792,11 +1775,12 @@ func TestUninstallPurgeKeepsCortexForACodexItCannotUnroute(t *testing.T) { markLine("·", "purged")+"kept ~/.cortex: "+envSSLCert+ " in ~/.codex/.env still points into it — delete it once nothing points into it: rm -rf ~/.cortex\n") // Every key, not someKeys' first three, since agentop is gone; and the updater - // stopped before the restart, which would otherwise keep it on the proxy. + // stopped and waited for before the restart, which would otherwise keep it on the proxy. fixes := fixesUnder(out, markLine("✗", "unrouted")) if want := []string{ - "in ~/.codex/.env, remove the lines that set HTTP_PROXY, HTTPS_PROXY, http_proxy, https_proxy, " + envSSLCert + " to Cortex's values", - "then, if Codex's app-server runs: " + codexUpdaterStopByHand + "; " + codexDaemonRestartCmd, + "in ~/.codex/.env, remove the lines that set HTTP_PROXY, HTTPS_PROXY, http_proxy, https_proxy, " + envSSLCert, + "then stop Codex's auto-updater and wait for it to exit: " + codexUpdaterStopByHand + "; " + codexUpdaterWaitByHand, + "then, if Codex's app-server runs: " + codexDaemonRestartCmd, }; !slices.Equal(fixes, want) { t.Errorf("the fix rows are %q, want %q:\n%s", fixes, want, out) } @@ -1887,7 +1871,7 @@ func TestUninstallFindsCortexsLineInADuplicatedKey(t *testing.T) { return } wantLines(t, code, 1, out, markLine("✗", "unrouted")+"~/.codex/.env defines HTTPS_PROXY more than once") - if fixes := fixesUnder(out, markLine("✗", "unrouted")); len(fixes) == 0 || !strings.Contains(fixes[0], "remove the lines that set HTTPS_PROXY to Cortex's values") { + if fixes := fixesUnder(out, markLine("✗", "unrouted")); len(fixes) == 0 || !strings.HasSuffix(fixes[0], "remove the lines that set HTTPS_PROXY") { t.Errorf("the fix rows are %q, want the HTTPS_PROXY line to remove:\n%s", fixes, out) } }) @@ -1901,10 +1885,10 @@ func TestCodexUpdaterStopByHandMatchesTheUpdaterNotItself(t *testing.T) { pattern := strings.TrimSuffix(strings.TrimPrefix(codexUpdaterStopByHand, "pkill -f '"), "'") re := regexp.MustCompile(pattern) for cmdline, want := range map[string]bool{ - "/Users/someone/.codex/packages/standalone/current/codex app-server daemon pid-update-loop": true, - "codex app-server daemon pid-update-loop": true, - "sh -c " + codexUpdaterStopByHand + "; " + codexDaemonRestartCmd: false, - "codex app-server --managed-daemon": false, + "/Users/someone/.codex/packages/standalone/current/codex app-server daemon pid-update-loop": true, + "codex app-server daemon pid-update-loop": true, + "sh -c " + codexUpdaterStopByHand + "; " + codexUpdaterWaitByHand + "; " + codexDaemonRestartCmd: false, + "codex app-server --managed-daemon": false, } { if got := re.MatchString(cmdline); got != want { t.Errorf("%q matched %q: %v, want %v", pattern, cmdline, got, want) @@ -2021,24 +2005,121 @@ func replaceIn(t *testing.T, path, old, new string) { writeHomeFile(t, path, strings.Replace(body, old, new, 1)) } -// Cortex's values are told from the user's by Cortex's config, even once its TLS bridge -// is turned off, which enable's own reading of the config refuses. Without them the -// values' shape decides, and on a custom port that calls the four proxy values the -// user's: uninstall would leave Codex on a proxy it then stops (#1783 review). +// Cortex's values come from its config even once its TLS bridge is turned off, which +// enable's own reading of the config refuses. A recorded file is unrouted by its record +// either way; one with no record is recognised by the config's proxy, and on a custom +// port the values' shape alone would not recognise it (#1783 review). func TestUninstallUnroutesACodexOnACustomPortWithTheBridgeOff(t *testing.T) { + for _, recorded := range []bool{true, false} { + t.Run(fmt.Sprintf("recorded=%v", recorded), func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + cfg := filepath.Join(sc.home, cortexCfgRel) + replaceIn(t, cfg, "forward_proxy_addr: 127.0.0.1:47600", "forward_proxy_addr: 127.0.0.1:8081") + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + if got := readCodexEnv(t, envPath)["HTTPS_PROXY"]; got != "http://127.0.0.1:8081" { + t.Fatalf("fixture: enable set HTTPS_PROXY=%q, want the custom port", got) + } + replaceIn(t, cfg, "tls_bridge:\n mode: enabled\n", "tls_bridge:\n mode: disabled\n") + if !recorded { + if err := os.Remove(filepath.Join(sc.home, codexStateRel)); err != nil { + t.Fatal(err) + } + } + + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, markLine("✓", "unrouted")+"Codex no longer goes through Cortex\n") + if got := readCodexEnv(t, envPath); len(got) != 0 { + t.Errorf("Cortex's values survived the unroute: %v\n%s", got, out) + } + }) + } +} + +// Uninstall unroutes the dotenv file enable's record names, wherever --env or a +// CODEX_HOME put it, and not only the default one: the shell that uninstalls need not +// have the CODEX_HOME Codex runs with. --purge then deletes ~/.cortex, since nothing +// left in that file points into it (#1781 review). +func TestUninstallUnroutesTheCodexFileTheRecordNames(t *testing.T) { + for _, tc := range []struct { + name string + enable func(t *testing.T, sc setupScene) string // routes Codex, returning its dotenv file + }{ + {"--env", func(t *testing.T, sc setupScene) string { + t.Setenv(codexHomeEnv, "") + return filepath.Join(sc.home, "proj", ".env") + }}, + {"CODEX_HOME only where Codex runs", func(t *testing.T, sc setupScene) string { + t.Setenv(codexHomeEnv, filepath.Join(sc.home, "codexhome")) + return defaultCodexEnvPath(sc.home) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := tc.enable(t, sc) + writeHomeFile(t, envPath, "RUST_LOG=info\n") + stubCodexDaemon(t, filepath.Dir(envPath), &fakeCodexDaemon{}) + var out, errb bytes.Buffer + if code := codexEnable(envPath, filepath.Join(sc.home, cortexCfgRel), filepath.Join(sc.home, codexStateRel), true, &out, &errb); code != 0 { + t.Fatalf("fixture: configure codex enable exit %d:\n%s%s", code, out.String(), errb.String()) + } + t.Setenv(codexHomeEnv, "") // the uninstalling shell has none + code, got := sc.uninstall(t, "--yes", "--purge") + wantLines(t, code, 0, got, markLine("✓", "unrouted")+"Codex no longer goes through Cortex · "+tildePath(sc.home, envPath)+"\n", + markLine("✓", "purged")+"~/.cortex\n") + if env := readCodexEnv(t, envPath); len(env) != 0 { + t.Errorf("Cortex's values survived in %s: %v", envPath, env) + } + }) + } +} + +// The default dotenv file with no record of enable's, one an older agentop wrote or one +// whose record is gone, is unrouted when one of its proxy lines is the proxy enable would +// write now, as planUnrouteClaudeCode treats ~/.claude/settings.json. +func TestUninstallUnroutesADefaultCodexFileWithNoRecord(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + if err := os.Remove(filepath.Join(sc.home, codexStateRel)); err != nil { + t.Fatal(err) + } + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, markLine("✓", "unrouted")+"Codex no longer goes through Cortex\n") + if env := readCodexEnv(t, envPath); len(env) != 0 { + t.Errorf("Cortex's values survived: %v", env) + } + if strings.Contains(out, "record") { + t.Errorf("uninstall spoke of a record there was none of:\n%s", out) + } +} + +// A record whose file no longer holds anything of Cortex's, removed by hand say, is +// deleted with the row, rather than outliving the routing it records. +func TestUninstallRemovesACodexRecordWithNothingLeftToUnroute(t *testing.T) { sc := newUninstallScene(t) sc.setUp(t) - cfg := filepath.Join(sc.home, cortexCfgRel) - replaceIn(t, cfg, "forward_proxy_addr: 127.0.0.1:47600", "forward_proxy_addr: 127.0.0.1:8081") envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) - if got := readCodexEnv(t, envPath)["HTTPS_PROXY"]; got != "http://127.0.0.1:8081" { - t.Fatalf("fixture: enable set HTTPS_PROXY=%q, want the custom port", got) + writeHomeFile(t, envPath, "RUST_LOG=info\n") + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, markLine("✓", "unrouted")+"removed Cortex's record (~/.codex/.env had nothing routed)\n") + if fileExists(filepath.Join(sc.home, codexStateRel)) { + t.Error("enable's record is still there") } - replaceIn(t, cfg, "tls_bridge:\n mode: enabled\n", "tls_bridge:\n mode: disabled\n") +} +// Codex's daemon stop leaves its auto-updater running, and that updater hands its proxy to +// the app-server it starts after an update. With no app-server to restart, uninstall still +// stops it: agentop is gone afterwards, so nothing else would. +func TestUninstallStopsCodexsUpdaterWhenNoAppServerRuns(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + f := &fakeCodexDaemon{updaterPID: 4103, updaterEnv: onCortex} + codexEnabledIn(t, sc, f) code, out := sc.uninstall(t, "--yes") wantLines(t, code, 0, out, markLine("✓", "unrouted")+"Codex no longer goes through Cortex\n") - if got := readCodexEnv(t, envPath); len(got) != 0 { - t.Errorf("Cortex's values survived the unroute: %v\n%s", got, out) + if !slices.Equal(f.steps, []string{"stop-updater"}) { + t.Errorf("the daemon saw %v, want only the updater stopped", f.steps) } } diff --git a/docs/agents/codex.md b/docs/agents/codex.md index be82ba726..3f8a27fae 100644 --- a/docs/agents/codex.md +++ b/docs/agents/codex.md @@ -544,13 +544,14 @@ lsof -nP -a -p "$(pgrep -f 'codex app-server --listen')" -iTCP -sTCP:ESTABLISHED ### When you uninstall Cortex -`agentop uninstall` unroutes Codex before it stops the proxy: it removes each of the five -variables whose value is Cortex's, deletes the record, and restarts a running app-server -the way `disable` does. Unlike `disable`, it leaves a variable whose value is not Cortex's, -such as a proxy or CA bundle of your own, and lists it under *Left behind*, because it -changes everything on one question. When it cannot change the file, for example when a -variable is defined twice, `--purge` keeps `~/.cortex`, since Codex's `SSL_CERT_FILE` still -names the CA bundle there. +`agentop uninstall` unroutes Codex before it stops the proxy, the way `disable` does: it +removes the five variables, deletes the record, stops Codex's auto-updater, and restarts +a running app-server. It does this for the file enable's record names, wherever `--env` +or a `CODEX_HOME` put it, and for the default file when one of its proxy lines is the +proxy `enable` would write now. When it cannot change a file, for example when a +variable is defined twice, the step fails with the lines to remove by hand, and +`--purge` keeps `~/.cortex`, since Codex's `SSL_CERT_FILE` still names the CA bundle +there. `agentop uninstall` in v0.9.5 and earlier skipped Codex. If you uninstalled with one of those, Codex still points at a proxy that is gone: undo it by hand, as below. @@ -564,15 +565,18 @@ Cortex's. Then delete the record, stop Codex's auto-updater, and restart Codex's server, so neither keeps using the proxy. The updater has to go first: `codex app-server daemon restart` keeps a running updater, which still has the proxy and passes it to the app-server it starts after its next update, and Codex has no command that stops one. The -`pkill` matches the updater by its command line; the brackets keep the pattern from -matching the shell that runs it. +`pkill` matches the updater by its command line, and the brackets keep the pattern from +matching the shell that runs it. `pkill` only signals the updater, so wait for it to +exit: a restart while it is still running keeps it. ```sh # Remove only lines matching these five keys, and only if they point at Cortex: # HTTP_PROXY HTTPS_PROXY http_proxy https_proxy SSL_CERT_FILE $EDITOR ~/.codex/.env rm -f ~/.cortex/codex-state.json -pkill -f 'app-server daemon pid-update-loo[p]'; codex app-server daemon restart +pkill -f 'app-server daemon pid-update-loo[p]' +while pgrep -f 'app-server daemon pid-update-loo[p]' >/dev/null; do sleep 1; done +codex app-server daemon restart ``` ### CA trust From a5a56df4c4aee017b3482916542e462339fdf830 Mon Sep 17 00:00:00 2001 From: Alan Cha Date: Thu, 19 Nov 2026 13:32:42 -0500 Subject: [PATCH 6/6] fix: Record Codex's dotenv file absolute, and read its values as Codex does From review of the uninstall Codex row: - enable recorded --env, or a relative CODEX_HOME, as typed. Read back by uninstall from another directory, a relative path named another project's file: uninstall removed that file's proxy and CA, left Codex's own file routed, and --purge deleted the CA it still named. runCodex now makes the path absolute before enable records it, as configure claude-code does for --settings, and a relative record from an older agentop is kept with the fix by hand, as keepOlderEntry keeps Claude Code's, with ~/.cortex kept under --purge. - Values were read raw, quotes and all, while Codex's loader strips them. A quoted SSL_CERT_FILE under ~/.cortex then read as no path, and a quoted proxy as not Cortex's. codexEnvValue reads a value as dotenvy does, and says when it cannot be sure; a CA path it cannot read keeps ~/.cortex. - The printed restart commands set CODEX_HOME for a Codex home that is not the shell's own, under the condition codexRun uses, and the kill line for a confirmed updater waits for it to exit before the restart. - A record whose file holds nothing of Cortex's any more still gets the restart when the running app-server has Cortex's proxy, which uninstall is about to stop. Assisted-By: Claude (Anthropic AI) Signed-off-by: Alan Cha --- cmd/agentop/cmd_codex.go | 31 ++++++++ cmd/agentop/cmd_codex_test.go | 71 +++++++++++++++++ cmd/agentop/cmd_uninstall.go | 128 +++++++++++++++++++++++------- cmd/agentop/cmd_uninstall_test.go | 108 ++++++++++++++++++++++++- 4 files changed, 308 insertions(+), 30 deletions(-) diff --git a/cmd/agentop/cmd_codex.go b/cmd/agentop/cmd_codex.go index 636a0a88a..b3032efba 100644 --- a/cmd/agentop/cmd_codex.go +++ b/cmd/agentop/cmd_codex.go @@ -198,6 +198,13 @@ func runCodex(args []string, stdout, stderr io.Writer) int { if *envPath == "" { *envPath = defaultCodexEnvPath(home) } + // Absolute, so enable's record names the file from any directory. A relative --env, + // or a relative CODEX_HOME, is relative to this one, and uninstall reads the record + // from wherever it runs: opened from there, the path names some other file (#1781 + // review). configure claude-code makes --settings absolute for the same reason. + if abs, err := filepath.Abs(*envPath); err == nil { + *envPath = abs + } if *cortexCfgPath == "" { *cortexCfgPath = filepath.Join(home, cortexCfgRel) } @@ -360,6 +367,30 @@ func (f *codexEnvFile) all(key string) []string { return vals } +// codexEnvValue is a dotenv value as Codex's loader, dotenvy, reads it, for the shapes a +// path or a proxy URL takes: one pair of single or double quotes stripped, or an unquoted +// value as it stands, surrounding space trimmed. ok is false for a value it might read +// otherwise, one with an escape, a $ substitution, a stray quote or a # that may start a +// comment, so a caller can take the safe side instead of misjudging it. get and all give +// values raw, quotes and all, as the file holds them (#1783 review). +func codexEnvValue(raw string) (string, bool) { + v := strings.TrimSpace(raw) + if n := len(v); n >= 2 && (v[0] == '"' || v[0] == '\'') && v[n-1] == v[0] { + inner, unsafe := v[1:n-1], `"\$` + if v[0] == '\'' { + unsafe = `'` // single quotes are literal to dotenvy + } + if strings.ContainsAny(inner, unsafe) { + return "", false + } + return inner, true + } + if strings.ContainsAny(v, `"'\$#`) { + return "", false + } + return v, true +} + // ambiguous names every key in keys defined more than once in the file. func (f *codexEnvFile) ambiguous(keys []string) []string { var out []string diff --git a/cmd/agentop/cmd_codex_test.go b/cmd/agentop/cmd_codex_test.go index 9a40c946b..0ddb99396 100644 --- a/cmd/agentop/cmd_codex_test.go +++ b/cmd/agentop/cmd_codex_test.go @@ -660,3 +660,74 @@ func TestConfigureUsage_CodexPersists(t *testing.T) { } } } + +// enable records its dotenv file as an absolute path, so the record names the file from +// any directory: a relative --env, or a relative CODEX_HOME, is relative to the one enable +// runs in, and uninstall reads the record from wherever it runs (#1781 review). +func TestCodexEnable_RecordsAnAbsolutePath(t *testing.T) { + for name, args := range map[string][]string{ + "--env .env": {"enable", "--yes", "--env", ".env"}, + "relative CODEX_HOME": {"enable", "--yes"}, + } { + t.Run(name, func(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv(codexHomeEnv, "") + cfg := filepath.Join(home, cortexCfgRel) + if err := os.MkdirAll(filepath.Dir(cfg), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(cfg, []byte(strings.Replace(cortexCfg, "CADIR", filepath.Join(home, ".cortex", "ca"), 1)), 0o600); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, "codexhome") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + t.Chdir(home) + want := filepath.Join(dir, ".env") + if name == "--env .env" { + t.Chdir(dir) + } else { + t.Setenv(codexHomeEnv, "codexhome") + } + stubCodexDaemon(t, dir, &fakeCodexDaemon{}) + var out, errb bytes.Buffer + if code := runCodex(args, &out, &errb); code != 0 { + t.Fatalf("enable exit %d:\n%s%s", code, out.String(), errb.String()) + } + st, err := readState(filepath.Join(home, codexStateRel)) + if err != nil || st == nil { + t.Fatalf("enable's record: %v, %v", st, err) + } + if !filepath.IsAbs(st.Settings) || !samePath(st.Settings, want) { + t.Errorf("the record names %q, want the absolute %s", st.Settings, want) + } + }) + } +} + +// codexEnvValue reads a value as dotenvy does for a path or a proxy URL, and says when it +// cannot be sure, so its callers can take the safe side. +func TestCodexEnvValue(t *testing.T) { + for _, tc := range []struct { + raw, want string + ok bool + }{ + {"/Users/x/.cortex/ca/bundle.crt", "/Users/x/.cortex/ca/bundle.crt", true}, + {`"/Users/x/.cortex/my-corp.pem"`, "/Users/x/.cortex/my-corp.pem", true}, + {`'/Users/x/.cortex/my-corp.pem'`, "/Users/x/.cortex/my-corp.pem", true}, + {` "http://127.0.0.1:47600" `, "http://127.0.0.1:47600", true}, + {`'$HOME/ca.pem'`, "$HOME/ca.pem", true}, // single quotes are literal + {`"$HOME/ca.pem"`, "", false}, // substituted + {`"a\"b"`, "", false}, // an escape + {`$HOME/ca.pem`, "", false}, + {`/a/b # a comment`, "", false}, + {`"/a/b`, "", false}, // unmatched + } { + got, ok := codexEnvValue(tc.raw) + if got != tc.want || ok != tc.ok { + t.Errorf("codexEnvValue(%q) = %q, %v, want %q, %v", tc.raw, got, ok, tc.want, tc.ok) + } + } +} diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index c98db406f..0b75b0c93 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -781,6 +781,11 @@ func openCodeByHand(env *setupEnv, cli string, pl openCodeDisablePlan, planned b // record is read now, before --purge can delete it. func planUnrouteCodex(env *setupEnv) []removal { state, def := filepath.Join(env.home, codexStateRel), defaultCodexEnvPath(env.home) + // Absolute, as enable now records it: a relative CODEX_HOME names a file relative to + // the directory uninstall runs from, which is not the one Codex runs in. + if abs, err := filepath.Abs(def); err == nil { + def = abs + } // Read without enable's refusals: a bridge turned off since enable changes nothing // about what enable wrote (codexValues). want := codexValues(env.configPath()) @@ -789,10 +794,14 @@ func planUnrouteCodex(env *setupEnv) []removal { named = st.Settings } var rs []removal - if named != "" { + switch { + case named == "": + case !filepath.IsAbs(named): + rs = append(rs, keepRelativeCodexEntry(env, named, state)) + default: rs = append(rs, unrouteCodex(env, named, state, want)) } - if (named == "" || !samePath(named, def)) && codexProxyIn(def, want) { + if (named == "" || !filepath.IsAbs(named) || !samePath(named, def)) && codexProxyIn(def, want) { // Without a record of its own: it restores nothing, and leaves the record alone // unless the record names no file, as one that cannot be read does. record := "" @@ -804,6 +813,28 @@ func planUnrouteCodex(env *setupEnv) []removal { return rs } +// keepRelativeCodexEntry is the row for a record that names its dotenv file by a relative +// path, as an agentop before this one recorded `enable --env .env` or a relative +// CODEX_HOME. The path is relative to the directory enable ran in, which the record does +// not keep, so uninstall cannot find the file, and opening the path from its own directory +// would change some other project's file of that name (#1781 review). It is kept, with +// the fix by hand, as keepOlderEntry keeps Claude Code's relative entries; so is ~/.cortex, +// since that file's SSL_CERT_FILE may name the CA bundle there. +func keepRelativeCodexEntry(env *setupEnv, rel, state string) removal { + fix := strings.Split(codexByHand(env, rel, nil), "\n") + fix[0] = "in the directory you enabled Codex in, " + fix[0] + return removal{ + label: "unrouted", + keep: &kept{ + what: "Codex's record of " + rel, + why: "an older agentop recorded it without its directory, so uninstall cannot find that file", + left: rel + " in the directory an older agentop enabled Codex in", + fix: append(fix, "then delete "+env.tilde(state)), + }, + needsCortexDir: rel + ", which uninstall cannot find, may still point into it", + } +} + // codexProxyIn reports whether any of envPath's proxy lines is the proxy enable would // write from the current config, as cortexProxyIn asks of a Claude Code settings file. // Every line of a duplicated key counts, since Codex uses the last and get gives the @@ -818,8 +849,11 @@ func codexProxyIn(envPath string, want map[string]string) bool { return false } for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"} { - if slices.Contains(f.all(k), proxy) { - return true + for _, v := range f.all(k) { + // As Codex reads it: a quoted copy of the proxy is still the proxy. + if d, ok := codexEnvValue(v); ok && d == proxy { + return true + } } } return false @@ -835,6 +869,7 @@ func codexProxyIn(envPath string, want map[string]string) bool { // Codex's daemon stop leaves it running and uninstall is the last time agentop can. func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) removal { codexHome := filepath.Dir(envPath) + restartCmd := codexRestartCmdFor(env, codexHome) pl, planErr := planCodexDisable(envPath) // Read here as well as by the plan: a file disable refuses, one defining a key twice, // still names the keys to remove by hand and what may point into ~/.cortex. @@ -853,7 +888,9 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) if f != nil { for _, k := range []string{"https_proxy", "HTTPS_PROXY"} { if v, ok := f.get(k); ok { - cortexProxy = v + if d, ok := codexEnvValue(v); ok { + cortexProxy = d + } } } } @@ -864,6 +901,23 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) if _, running := runningCodexDaemon(codexHome); running { where += " · restarts its app-server, interrupting running turns" } + // settleCodex stops Codex's auto-updater and restarts a running app-server once the + // file is settled, so neither keeps the proxy that is about to stop, and names what + // still has it. A failed stop is not the row's ✗, as it is not disable's: the restart + // still applies the change to the daemon. It is remembered, so the updater it left on + // the old proxy is named whether or not the restart works. + settleCodex := func(detail, notes string, left []string, running bool) (string, []string, error) { + stopFailed := codexStopUpdater(codexHome) != nil + if !running { + return detail + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, restartCmd, stopFailed)...), nil + } + if err := codexRestartDaemon(codexHome, want); err != nil { + left = append(left, "Codex's app-server, which may still use Cortex's proxy — restart it: "+restartCmd) + return detail + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, restartCmd, stopFailed)...), nil + } + left = append(left, codexDaemonLeft(codexHome, cortexProxy, restartCmd)...) + return detail + " · restarted its app-server" + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, restartCmd, stopFailed)...), nil + } fix := remedy{byHand: codexByHand(env, envPath, keys)} if planErr == nil { fix.agentop = "agentop configure codex disable --env " + env.shellPath(envPath) @@ -881,13 +935,20 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) if len(pl.present) == 0 { // Nothing of Cortex's left in the file: removed by hand, say. The record // would otherwise outlive it. + detail := "nothing routed in " + env.tilde(envPath) if state != "" { if err := removeIfExists(state); err != nil { return "", []string{env.tilde(state)}, withFixes(err, manual("rm "+env.shellPath(state))) } - return "removed Cortex's record (" + env.tilde(envPath) + " had nothing routed)", nil, nil + detail = "removed Cortex's record (" + env.tilde(envPath) + " had nothing routed)" } - return "nothing routed in " + env.tilde(envPath), nil, nil + // An app-server started before those lines went may still have Cortex's + // proxy, which uninstall is about to stop, so it gets the restart a changed + // file would have (#1783 review). + if d, ok := runningCodexDaemon(codexHome); ok && d.EnvErr == nil && cortexProxy != "" && sameProxy(d.Proxy, cortexProxy) { + return settleCodex(detail, "", nil, true) + } + return detail, nil, nil } _, running := runningCodexDaemon(codexHome) var errb bytes.Buffer @@ -899,25 +960,30 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) if len(restored) > 0 { detail += " · restored your " + strings.Join(restored, ", ") } - notes := stderrNotes(env, errb.String()) - // A failed stop is not this row's ✗, as it is not disable's: the restart still - // applies the change to the daemon. It is remembered, so the updater it left on - // the old proxy is named whether or not the restart works. - stopFailed := codexStopUpdater(codexHome) != nil - if !running { - return detail + notes, codexUpdaterLeft(codexHome, cortexProxy, stopFailed), nil - } - var left []string - if err := codexRestartDaemon(codexHome, want); err != nil { - left = append(left, "Codex's app-server, which may still use Cortex's proxy — restart it: "+codexDaemonRestartCmd) - return detail + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, stopFailed)...), nil - } - left = append(left, codexDaemonLeft(codexHome, cortexProxy)...) - return detail + " · restarted its app-server" + notes, append(left, codexUpdaterLeft(codexHome, cortexProxy, stopFailed)...), nil + return settleCodex(detail, stderrNotes(env, errb.String()), nil, running) }, } } +// codexRestartCmdFor is codexDaemonRestartCmd as the user should run it for the app-server +// of codexHome: with CODEX_HOME set when codexHome is not the home their shell's codex +// uses, under the condition codexRun sets it on. Bare, it would restart another Codex's +// app-server and leave this one on Cortex's proxy. +func codexRestartCmdFor(env *setupEnv, codexHome string) string { + if defaultCodexEnvPath(env.home) == filepath.Join(codexHome, ".env") { + return codexDaemonRestartCmd + } + return codexHomeEnv + "=" + env.shellPath(codexHome) + " " + codexDaemonRestartCmd +} + +// codexKillThenRestart is the command that ends a confirmed updater and restarts the +// app-server once it has gone. kill only signals it, and Codex's restart starts a fresh +// updater only when the record names no live process, so a restart run straight after +// the kill could keep the old one, proxy and all. A kill that fails stops the line there. +func codexKillThenRestart(pid int, restartCmd string) string { + return fmt.Sprintf("kill %d && while kill -0 %d 2>/dev/null; do sleep 1; done && %s", pid, pid, restartCmd) +} + // codexUpdaterStopByHand stops Codex's auto-updater without agentop. Codex's restart keeps // a running updater (codexUpdaterPIDRel) and Codex has no command that stops one, so it is // matched by its command line: never by the pid in its record, which may name another @@ -943,7 +1009,7 @@ func codexByHand(env *setupEnv, envPath string, keys []string) string { } return "in " + env.tilde(envPath) + ", remove the lines that set " + strings.Join(keys, ", ") + "\n" + "then stop Codex's auto-updater and wait for it to exit: " + codexUpdaterStopByHand + "; " + codexUpdaterWaitByHand + "\n" + - "then, if Codex's app-server runs: " + codexDaemonRestartCmd + "then, if Codex's app-server runs: " + codexRestartCmdFor(env, filepath.Dir(envPath)) } // codexNeedsCortexDir is why --purge must keep ~/.cortex: the managed keys of envPath that @@ -980,10 +1046,14 @@ func codexNeedsCortexDir(env *setupEnv, envPath, state string, f *codexEnvFile, } } } + // Each value as Codex reads it, quotes stripped: raw, a quoted path is not absolute + // and never counted, and --purge would delete the file it names. A CA path that + // cannot be read with confidence keeps the directory, the safe side. var keys []string for _, k := range codexKeys { for _, v := range after[k] { - if pathUnder(env.cortexDir, v) { + d, ok := codexEnvValue(v) + if (ok && pathUnder(env.cortexDir, d)) || (!ok && k == envSSLCert) { keys = append(keys, k) break } @@ -997,13 +1067,13 @@ func codexNeedsCortexDir(env *setupEnv, envPath, state string, f *codexEnvFile, // codexDaemonLeft names the app-server the Codex row restarted when it still has Cortex's // proxy, which then reached it from somewhere other than the dotenv file. -func codexDaemonLeft(codexHome, cortexProxy string) []string { +func codexDaemonLeft(codexHome, cortexProxy, restartCmd string) []string { if cortexProxy == "" { return nil } if d, ok := runningCodexDaemon(codexHome); ok && d.EnvErr == nil && sameProxy(d.Proxy, cortexProxy) { return []string{fmt.Sprintf("Codex's app-server (pid %d), which still has Cortex's proxy from the environment it started in — "+ - "restart it from a shell without one: %s", d.PID, codexDaemonRestartCmd)} + "restart it from a shell without one: %s", d.PID, restartCmd)} } return nil } @@ -1015,7 +1085,7 @@ func codexDaemonLeft(codexHome, cortexProxy string) []string { // it started with. Otherwise only one whose environment shows Cortex's proxy is. It names // a pid only when codexIsRecorded confirms the process, as reportRestartedUpdater does, // so a reused pid is never given a kill command. -func codexUpdaterLeft(codexHome, cortexProxy string, stopFailed bool) []string { +func codexUpdaterLeft(codexHome, cortexProxy, restartCmd string, stopFailed bool) []string { u, ok := runningCodexUpdater(codexHome) if !ok { return nil @@ -1031,10 +1101,10 @@ func codexUpdaterLeft(codexHome, cortexProxy string, stopFailed bool) []string { switch { case stopFailed: return []string{fmt.Sprintf("Codex's auto-updater (pid %d), which agentop could not stop, so it may still have Cortex's proxy — "+ - "stop it, then restart the app-server: kill %d && %s", u.PID, u.PID, codexDaemonRestartCmd)} + "stop it, then restart the app-server: %s", u.PID, codexKillThenRestart(u.PID, restartCmd))} case u.EnvErr == nil && cortexProxy != "" && sameProxy(u.Proxy, cortexProxy): return []string{fmt.Sprintf("Codex's auto-updater (pid %d), which still has Cortex's proxy — "+ - "stop it, then restart the app-server: kill %d && %s", u.PID, u.PID, codexDaemonRestartCmd)} + "stop it, then restart the app-server: %s", u.PID, codexKillThenRestart(u.PID, restartCmd))} } return nil } diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index 766754018..0550fc61f 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -1801,7 +1801,7 @@ func TestUninstallNamesWhatACodexRestartLeaves(t *testing.T) { const ( appServer = "Codex's app-server, which may still use Cortex's proxy — restart it: " + codexDaemonRestartCmd unstopped = "Codex's auto-updater (pid 4103), which agentop could not stop, so it may still have Cortex's proxy — " + - "stop it, then restart the app-server: kill 4103 && " + codexDaemonRestartCmd + "stop it, then restart the app-server: kill 4103 && while kill -0 4103 2>/dev/null; do sleep 1; done && " + codexDaemonRestartCmd ) for _, tc := range []struct { name string @@ -2123,3 +2123,109 @@ func TestUninstallStopsCodexsUpdaterWhenNoAppServerRuns(t *testing.T) { t.Errorf("the daemon saw %v, want only the updater stopped", f.steps) } } + +// A record from an older agentop can name its dotenv file by a relative path, which is +// relative to the directory enable ran in. Uninstall cannot find that directory, and +// opening the path from its own would change another project's file of that name, so +// the record is kept with the fix by hand, and --purge keeps ~/.cortex for the CA bundle +// that file may name (#1781 review). +func TestUninstallKeepsACodexRecordWithARelativePath(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + t.Setenv(codexHomeEnv, "") + stubCodexDaemon(t, filepath.Join(sc.home, ".codex"), &fakeCodexDaemon{}) + state := filepath.Join(sc.home, codexStateRel) + if err := writeStateFile(state, managedState{Settings: ".env", Prior: map[string]*string{}}); err != nil { + t.Fatal(err) + } + other := filepath.Join(sc.home, "otherproject") + const theirs = "HTTPS_PROXY=http://proxy.corp.example:8080\nSSL_CERT_FILE=/etc/corp.pem\nDB=1\n" + writeHomeFile(t, filepath.Join(other, ".env"), theirs) + t.Chdir(other) + + code, out := sc.uninstall(t, "--yes", "--purge") + wantLines(t, code, 1, out, + markLine("!", "unrouted")+"kept Codex's record of .env: an older agentop recorded it without its directory, so uninstall cannot find that file\n", + " .env in the directory an older agentop enabled Codex in\n") + if got := readFile(t, filepath.Join(other, ".env")); got != theirs { + t.Errorf("uninstall changed %s, a file Cortex never routed:\n%s", filepath.Join(other, ".env"), got) + } + if _, err := os.Stat(filepath.Join(sc.home, ".cortex", "config.yaml")); err != nil { + t.Errorf("--purge deleted ~/.cortex while a file it cannot find may name its CA: %v", err) + } +} + +// The commands printed for a Codex home other than the one the user's shell uses set +// CODEX_HOME, as codexRun sets it: bare, they would restart ~/.codex's app-server and +// leave this one on Cortex's proxy. +func TestUninstallNamesTheCodexHomeInItsRestartCommands(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + home := filepath.Join(sc.home, "codexhome") + t.Setenv(codexHomeEnv, home) + envPath := defaultCodexEnvPath(sc.home) + writeHomeFile(t, envPath, "RUST_LOG=info\n") + f := runningCodex() + f.restartErr = errors.New("daemon lock held") + stubCodexDaemon(t, home, &fakeCodexDaemon{}) + var out, errb bytes.Buffer + if code := codexEnable(envPath, filepath.Join(sc.home, cortexCfgRel), filepath.Join(sc.home, codexStateRel), true, &out, &errb); code != 0 { + t.Fatalf("fixture: configure codex enable exit %d:\n%s%s", code, out.String(), errb.String()) + } + stubCodexDaemon(t, home, f) + t.Setenv(codexHomeEnv, "") // the uninstalling shell's codex uses ~/.codex + code, got := sc.uninstall(t, "--yes") + wantLines(t, code, 1, got, "restart it: "+codexHomeEnv+"=~/codexhome "+codexDaemonRestartCmd+"\n") +} + +// A quoted value is the same value to Codex, whose loader strips the quotes. So a quoted +// SSL_CERT_FILE under ~/.cortex, in a file the row cannot change, still keeps ~/.cortex +// under --purge; raw, the quotes made it read as no path at all (#1783 review). +func TestUninstallPurgeKeepsCortexForAQuotedCodexCA(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + ca := readCodexEnv(t, envPath)[envSSLCert] + replaceIn(t, envPath, envSSLCert+"="+ca, envSSLCert+"=\""+ca+"\"") + writeHomeFile(t, envPath, readFile(t, envPath)+"HTTP_PROXY="+cortexProxyURL+"\n") + code, out := sc.uninstall(t, "--yes", "--purge") + wantLines(t, code, 1, out, markLine("✗", "unrouted"), + markLine("·", "purged")+"kept ~/.cortex: "+envSSLCert+ + " in ~/.codex/.env still points into it — delete it once nothing points into it: rm -rf ~/.cortex\n") + if _, err := os.Stat(filepath.Join(sc.home, ".cortex", "config.yaml")); err != nil { + t.Errorf("--purge deleted ~/.cortex while Codex's quoted %s named its CA: %v", envSSLCert, err) + } +} + +// A default dotenv file with no record whose proxy is quoted is still Cortex's, read as +// Codex reads it. +func TestUninstallUnroutesAQuotedCodexProxyWithNoRecord(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + t.Setenv(codexHomeEnv, "") + stubCodexDaemon(t, filepath.Join(sc.home, ".codex"), &fakeCodexDaemon{}) + envPath := filepath.Join(sc.home, codexEnvRel) + writeHomeFile(t, envPath, "HTTPS_PROXY=\""+cortexProxyURL+"\"\nRUST_LOG=info\n") + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, markLine("✓", "unrouted")+"Codex no longer goes through Cortex\n") + if got := readFile(t, envPath); got != "RUST_LOG=info\n" { + t.Errorf("~/.codex/.env is %q, want only the user's line", got) + } +} + +// An app-server started while the dotenv file still routed Codex keeps Cortex's proxy +// after the lines go, removed by hand say, and uninstall is about to stop that proxy. So +// a record whose file has nothing left still gets the restart a changed file would have +// (#1783 review). +func TestUninstallRestartsACodexStillOnCortexAfterItsLinesWent(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + f := runningCodex() + envPath := codexEnabledIn(t, sc, f) + writeHomeFile(t, envPath, "RUST_LOG=info\n") + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 0, out, markLine("✓", "unrouted")+"removed Cortex's record (~/.codex/.env had nothing routed) · restarted its app-server\n") + if !slices.Equal(f.steps, []string{"stop-updater", "restart"}) { + t.Errorf("the daemon saw %v, want the updater stopped and the app-server restarted", f.steps) + } +}