diff --git a/cmd/agentop/cmd_codex.go b/cmd/agentop/cmd_codex.go index 77bb58f01..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) } @@ -228,6 +235,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 +271,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 @@ -321,6 +354,43 @@ 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 +} + +// 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 297a7944f..0b75b0c93 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,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, 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,6 +772,343 @@ func openCodeByHand(env *setupEnv, cli string, pl openCodeDisablePlan, planned b return strings.Join(append(lines, restart), "\n") } +// 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) + // 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()) + named := "" + if st, err := readState(state); err == nil && st != nil { + named = st.Settings + } + var rs []removal + 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 == "" || !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 := "" + if named == "" { + record = state + } + rs = append(rs, unrouteCodex(env, def, record, want)) + } + 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 +// 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"} { + 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 +} + +// 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. +// +// 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) + 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. + f, _ := parseCodexEnv(envPath) + keys := pl.present + if planErr != nil && f != nil { + for _, k := range codexKeys { + if len(f.all(k)) > 0 { + keys = append(keys, k) + } + } + } + // 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 { + if d, ok := codexEnvValue(v); ok { + cortexProxy = d + } + } + } + } + where, suffix := env.tilde(envPath), "" + if !samePath(envPath, defaultCodexEnvPath(env.home)) { + suffix = " · " + env.tilde(envPath) + } + 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) + } + return removal{ + label: "unrouted", + item: checklist.Item{Verb: "unroute", What: "Codex", Where: where}, + fix: fix, + 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. + 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))) + } + detail = "removed Cortex's record (" + env.tilde(envPath) + " had nothing routed)" + } + // 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 + restored, err := applyCodexDisable(pl, state, &errb) + if err != nil { + return "", unchanged, err + } + detail := "Codex no longer goes through Cortex" + suffix + if len(restored) > 0 { + detail += " · restored your " + strings.Join(restored, ", ") + } + 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 +// 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]'" + +// 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, 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, ", ") + "\n" + + "then stop Codex's auto-updater and wait for it to exit: " + codexUpdaterStopByHand + "; " + codexUpdaterWaitByHand + "\n" + + "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 +// 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 + } + } + // 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 !removed[k] { + after[k] = f.all(k) + } + } + if planned { + if st, _ := readState(state); st != nil && st.Settings == envPath { + for _, k := range ours { + if p := st.Prior[k]; p != nil { + after[k] = []string{*p} + } + } + } + } + // 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] { + d, ok := codexEnvValue(v) + if (ok && pathUnder(env.cortexDir, d)) || (!ok && k == envSSLCert) { + keys = append(keys, k) + break + } + } + } + if len(keys) == 0 { + return "" + } + return someKeys(keys) + " in " + env.tilde(envPath) + " still points into it" +} + +// 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, 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, restartCmd)} + } + 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, restartCmd string, stopFailed bool) []string { + u, ok := runningCodexUpdater(codexHome) + if !ok { + return nil + } + switch codexIsRecorded(u) { + case codexRecordStale: + // A restart finds the record stale and starts a fresh updater. + return nil + case codexRecordUnknown: + 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"} + } + 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: %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: %s", u.PID, codexKillThenRestart(u.PID, restartCmd))} + } + return nil +} + // 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..0550fc61f 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" @@ -1663,3 +1664,568 @@ 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 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) { + sc := newUninstallScene(t) + sc.setUp(t) + f := &fakeCodexDaemon{} + if running { + f = runningCodex() + } + envPath := codexEnabledIn(t, sc, f) + code, out := sc.uninstall(t, "--yes") + // 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 = 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) { + 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 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") + // Every key, not someKeys' first three, since agentop is gone; and the updater + // 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, + "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) + } + 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. 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 && while kill -0 4103 2>/dev/null; do sleep 1; done && " + codexDaemonRestartCmd + ) + for _, tc := range []struct { + name string + tweak func(*fakeCodexDaemon) + left []string + }{ + {"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) + sc.setUp(t) + f := runningCodex() + tc.tweak(f) + envPath := codexEnabledIn(t, sc, f) + code, out := sc.uninstall(t, "--yes") + 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) + } + }) + } +} + +// 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.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) + } + }) + } +} + +// 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 + "; " + 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) + } + } +} + +// 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]() + } + // 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(agent, 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(agent, s) { + t.Errorf("%s is still routed after uninstall (configure status reads %v)", agent, s) + } + } +} + +// 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 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) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + 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") + } +} + +// 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 !slices.Equal(f.steps, []string{"stop-updater"}) { + 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) + } +} 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/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..3f8a27fae 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,19 +542,40 @@ 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, 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. + ### Undoing it by hand 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, 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]' +while pgrep -f 'app-server daemon pid-update-loo[p]' >/dev/null; do sleep 1; done codex app-server daemon restart ``` 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