diff --git a/cmd/agentop/cmd_codex.go b/cmd/agentop/cmd_codex.go index b3032efba..1fea6eac5 100644 --- a/cmd/agentop/cmd_codex.go +++ b/cmd/agentop/cmd_codex.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "strings" ) @@ -162,7 +163,8 @@ refuses rather than pick a side if a key is defined more than once. Codex parses this file with dotenvy, whose precedence is last-wins, so appending would quietly beat an earlier definition — including a corporate proxy someone set deliberately. The first run copies the original file to .env.bak -and never overwrites that copy. disable removes only the keys it added. +and never overwrites that copy. disable removes the keys it added, and leaves +one you changed since enable, naming it. Codex's background app-server, which makes the model calls for every codex window, reads the file only when it starts, and so does its auto-updater. So @@ -546,13 +548,15 @@ func planCodexEnable(envPath, cortexCfgPath string) (codexPlan, error) { return pl, nil } -// applyCodexEnable records what the managed keys held, then writes the plan's -// values. Failing to record is a warning on stderr, as it is for claude-code: -// the write still happens, and disable then deletes the keys rather than -// restoring them. +// applyCodexEnable records what the managed keys held and what it is about to set +// them to, then writes the plan's values. Written is what lets disable tell Cortex's +// own value from one changed since enable, as it does for claude-code (#1289). +// Failing to record is a warning on stderr, as it is for claude-code: the write still +// happens, and disable then deletes the keys rather than restoring or keeping any. func applyCodexEnable(pl codexPlan, statePath string, stderr io.Writer) error { - st := managedState{Settings: pl.envPath, Prior: map[string]*string{}} + st := managedState{Settings: pl.envPath, Prior: map[string]*string{}, Written: map[string]string{}} for _, k := range codexKeys { + st.Written[k] = pl.want[k] // A Cortex-shaped prior is recorded as absent, the same filtered capture // applyOpenCodeEnable makes: it is ours already, from an earlier enable, // and restoring it on disable would leave Codex on some earlier Cortex @@ -564,8 +568,8 @@ func applyCodexEnable(pl codexPlan, statePath string, stderr io.Writer) error { } } if werr := writeState(statePath, st); werr != nil { - fmt.Fprintf(stderr, "agentop: could not record Codex's prior values (%v); disable will\n"+ - " delete these keys rather than restore any you had set yourself\n", werr) + fmt.Fprintf(stderr, "agentop: could not record what Codex's keys held and what enable sets (%v);\n"+ + " disable will delete these keys rather than restore or keep any you set yourself\n", werr) } commented := false @@ -592,6 +596,7 @@ func codexEnable(envPath, cortexCfgPath, statePath string, yes bool, stdout, std // to be going through Cortex, and a daemon older than the file is the usual // reason. Reported, not restarted: there was nothing to apply. reportCodexDaemon(codexHome, pl.want["HTTPS_PROXY"], true, false, stdout) + topUpCodexWritten(pl, statePath, stderr) return 0 } fmt.Fprintf(stdout, "Sets in %s:\n%s\n", envPath, strings.Join(pl.changes, "\n")) @@ -611,15 +616,56 @@ func codexEnable(envPath, cortexCfgPath, statePath string, yes bool, stdout, std return 0 } +// topUpCodexWritten records what enable would set on a file that is already enabled, +// so disable can tell a later edit from Cortex's own value on an install enabled before +// enable recorded Written, as topUpWritten does for claude-code. A re-run of enable that +// finds nothing to change is how most of those installs reach it. +// +// It never creates a record. The file already holds Cortex's values here, so a Prior +// taken from them would be Cortex's own, and disable would "restore" those instead of +// removing the keys. A record of another file, or one that cannot be read, is not this +// file's to rewrite. writeState skips the write when Written already matches, so the +// usual re-run touches nothing. +func topUpCodexWritten(pl codexPlan, statePath string, stderr io.Writer) { + st, err := readState(statePath) + if err != nil || st == nil || !codexRecordNames(st, pl.envPath) { + return + } + written := map[string]string{} + for _, k := range codexKeys { + written[k] = pl.want[k] + } + if werr := writeState(statePath, managedState{Settings: st.Settings, Prior: st.Prior, Written: written}); werr != nil { + fmt.Fprintf(stderr, "agentop: could not record the values now set (%v); disable will not be\n"+ + " able to tell a later edit of yours from Cortex's own value, and may remove it.\n", werr) + } +} + +// codexRecordNames reports whether enable's record is envPath's: the same text, or an +// absolute path that resolves to the same file. +func codexRecordNames(st *managedState, envPath string) bool { + return st != nil && (st.Settings == envPath || (filepath.IsAbs(st.Settings) && samePath(st.Settings, envPath))) +} + // codexDisablePlan is what disable would remove, worked out without touching // anything. type codexDisablePlan struct { envPath string f *codexEnvFile - present []string // managed keys set in the file, in codexKeys order; none = nothing to do + present []string // managed keys holding Cortex's values, in codexKeys order; none = nothing to do + left []string // managed keys changed since enable, which disable leaves + st *managedState // enable's record of this file; nil when there is none } -func planCodexDisable(envPath string) (codexDisablePlan, error) { +// planCodexDisable is what disable would change in envPath, judged by enable's record at +// statePath ("" for none), as claude-code's disable judges by its own (#1289). A managed +// key whose value is not the one enable recorded writing was changed since enable — a +// corporate proxy, a CA bundle — and goes in left, untouched. Every other key is +// Cortex's, and so is every key when nothing records writing it: an install enabled +// before enable recorded Written, or a record that is gone. Removing a value of the +// user's then is the lesser harm, for the reason changedSinceEnable gives. Cortex's +// config is not read, so this works the same when Cortex is gone. +func planCodexDisable(envPath, statePath string) (codexDisablePlan, error) { f, err := parseCodexEnv(envPath) if err != nil { return codexDisablePlan{}, err @@ -630,18 +676,84 @@ func planCodexDisable(envPath string) (codexDisablePlan, error) { envPath, strings.Join(dup, ", ")) } pl := codexDisablePlan{envPath: envPath, f: f} + if statePath != "" { + // An unreadable record leaves st nil, so every key is removed; + // applyCodexDisable says so when it reads the record again. + if st, _ := readState(statePath); codexRecordNames(st, envPath) { + pl.st = st + } + } for _, k := range codexKeys { - if _, ok := f.get(k); ok { + v, ok := f.get(k) + switch { + case !ok: + case changedSinceEnable(pl.st, k, codexAsRead(v)): + pl.left = append(pl.left, k) + default: pl.present = append(pl.present, k) } } return pl, nil } -// applyCodexDisable puts back what enable recorded, removes what it added, and -// deletes the record. It returns the keys restored to a value the user had -// set. It restores Prior unconditionally, with no check on whether the value -// changed since enable. +// codexAsRead is v as Codex reads it, quotes stripped, or v as it stands when +// codexEnvValue cannot be sure. Compared with what enable wrote, which carries no quotes, +// a quoted copy of Cortex's own value is still Cortex's, and a value that may read +// otherwise is not: it is left, the safe side (#1783 review). +func codexAsRead(v string) string { + if d, ok := codexEnvValue(v); ok { + return d + } + return v +} + +// codexCortexProxy is the proxy the processes restarted after disable are compared with: +// the value of HTTPS_PROXY, else https_proxy, among the keys the plan removes. A proxy +// left in place is not Cortex's. With neither removed, enable's record says what +// Cortex's proxy was, if there is a record (#1783 review); "" means there is nothing +// to compare with. +func codexCortexProxy(pl codexDisablePlan) string { + for _, k := range []string{"HTTPS_PROXY", "https_proxy"} { + if v, ok := pl.f.get(k); ok && slices.Contains(pl.present, k) { + return codexAsRead(v) + } + } + if pl.st != nil { + return pl.st.Written["HTTPS_PROXY"] + } + return "" +} + +// noteCodexDaemonOnCortex names an app-server still on Cortex's proxy when disable has +// nothing of Cortex's to take out of the file. One started before the user changed the +// file keeps the proxy it started with, and drops it only when it restarts. Nothing is +// restarted here, since nothing was asked (#1783 review). +func noteCodexDaemonOnCortex(codexHome, cortexProxy string, stdout io.Writer) { + d, ok := runningCodexDaemon(codexHome) + if !ok || d.EnvErr != nil || cortexProxy == "" || !sameProxy(d.Proxy, cortexProxy) { + return + } + fmt.Fprintf(stdout, "\nCodex's background app-server (pid %d%s) still uses Cortex's proxy, from before\n"+ + " these changes. It picks up the file when it restarts:\n"+ + " %s # open Codex windows reconnect\n", d.PID, startedSuffix(d), codexDaemonRestartCmd) +} + +// printCodexLeft names the keys disable leaves because they changed since enable, in +// claude-code's words (printClaudeCodeLeft), before the question they bear on. +func printCodexLeft(pl codexDisablePlan, stdout io.Writer) { + if len(pl.left) == 0 { + return + } + fmt.Fprintf(stdout, "Leaving these alone — changed since Cortex set them:\n") + for _, k := range pl.left { + fmt.Fprintf(stdout, " %s\n", k) + } + fmt.Fprintf(stdout, "Removing them would lose that edit; edit %s by hand if you want them gone.\n", pl.envPath) +} + +// applyCodexDisable puts back what enable recorded for the plan's present keys, removes +// the rest of them, and deletes the record. It returns the keys restored to a value the +// user had set. A key in pl.left, changed since enable, is not touched. // // IN PRACTICE THE RESTORE BRANCH IS UNREACHABLE TODAY, and it is worth knowing // that before reading the warning below as a live case. planCodexEnable refuses @@ -695,27 +807,40 @@ func applyCodexDisable(pl codexDisablePlan, statePath string, stderr io.Writer) } func codexDisable(envPath, statePath string, yes bool, stdout, stderr io.Writer) int { - pl, err := planCodexDisable(envPath) + pl, err := planCodexDisable(envPath, statePath) if err != nil { fmt.Fprintf(stderr, "agentop: %v\n", err) return 1 } if len(pl.present) == 0 { - fmt.Fprintf(stdout, "Nothing to do: none of the Cortex variables are set in %s.\n", envPath) + // None of Cortex's own values is left in the file, so Cortex does not route it, + // and the record must not go on saying it does (removeDisabledRecord says why + // for claude-code). applyCodexDisable, which would have deleted it, is not reached. + if pl.st != nil { + _ = os.Remove(statePath) + } + if len(pl.left) == 0 { + fmt.Fprintf(stdout, "Nothing to do: none of the Cortex variables are set in %s.\n", envPath) + return 0 + } + // Every managed key the file holds was changed after enable: nothing of ours to + // take out, and nothing to ask about. + fmt.Fprintf(stdout, "Nothing to remove from %s.\n\n", envPath) + printCodexLeft(pl, stdout) + noteCodexDaemonOnCortex(filepath.Dir(envPath), codexCortexProxy(pl), stdout) return 0 } fmt.Fprintf(stdout, "This will remove from %s: %s\n", envPath, strings.Join(pl.present, ", ")) + // Before the question, not after it: what is left behind is part of what the + // answer is about. + printCodexLeft(pl, stdout) codexHome := filepath.Dir(envPath) was := noteCodexDaemonRestart(codexHome, stdout) fmt.Fprintln(stdout) // The proxy the restarted daemon is compared with, read before the file loses it. // Disable has to work when Cortex is gone, so this is what the file held, not - // Cortex's config; want is nil for the same reason, and codexIsOurs falls back to - // the value's shape. - cortexProxy, _ := pl.f.get("HTTPS_PROXY") - if cortexProxy == "" { - cortexProxy, _ = pl.f.get("https_proxy") - } + // Cortex's config, and only a value it removes: a proxy left in place is not Cortex's. + cortexProxy := codexCortexProxy(pl) if !yes && !codexConfirm(stdout) { fmt.Fprintln(stdout, "Not changed.") return exitDeclined @@ -728,7 +853,13 @@ func codexDisable(envPath, statePath string, yes bool, stdout, stderr io.Writer) if len(restored) > 0 { fmt.Fprintf(stdout, "\nRestored to the value(s) you had before: %s\n", strings.Join(restored, ", ")) } - fmt.Fprintf(stdout, "\nDisabled. Codex no longer routes through Cortex.\n") + if len(pl.left) > 0 { + // Not "no longer routes through Cortex": a left HTTPS_PROXY still points somewhere, + // as claude-code's disable says for the same reason. + fmt.Fprintf(stdout, "\nRemoved what Cortex set. The key(s) listed above are still in %s.\n", envPath) + } else { + fmt.Fprintf(stdout, "\nDisabled. Codex no longer routes through Cortex.\n") + } finishCodexChange(codexHome, cortexProxy, nil, false, was, stdout, stderr) return 0 } diff --git a/cmd/agentop/cmd_codex_test.go b/cmd/agentop/cmd_codex_test.go index 0ddb99396..849280ec6 100644 --- a/cmd/agentop/cmd_codex_test.go +++ b/cmd/agentop/cmd_codex_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "io" + "maps" "os" "path/filepath" "strings" @@ -707,6 +708,123 @@ func TestCodexEnable_RecordsAnAbsolutePath(t *testing.T) { } } +// readCodexRecord reads enable's record at path, failing the test when there is none. +func readCodexRecord(t *testing.T, path string) *managedState { + t.Helper() + st, err := readState(path) + if err != nil || st == nil { + t.Fatalf("enable's record at %s: %v, %v", path, st, err) + } + return st +} + +// editFile replaces old with new in path once, and fails the test when old is not there. +func editFile(t *testing.T, path, old, new string) { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), old) { + t.Fatalf("fixture: %s has no %q:\n%s", path, old, b) + } + if err := os.WriteFile(path, []byte(strings.Replace(string(b), old, new, 1)), 0o600); err != nil { + t.Fatal(err) + } +} + +// enable records the five values it writes, which is what lets disable tell Cortex's +// own value from one changed since, as claude-code's does (#1289). +func TestCodexEnable_RecordsWhatItWrote(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + enableCodex(t, envPath, cfgPath) + st := readCodexRecord(t, filepath.Join(filepath.Dir(envPath), "state.json")) + if got, want := st.Written, readCodexEnv(t, envPath); len(want) != len(codexKeys) || !maps.Equal(got, want) { + t.Errorf("Written = %v, want what enable set: %v", got, want) + } +} + +// An install enabled before enable recorded Written gets it from the next enable, which +// finds nothing to change: the re-run most installs see. One with no record gets none, +// since a Prior taken from Cortex's own values would make disable restore them. +func TestCodexEnable_AlreadyEnabledFillsInARecordWithoutWritten(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + statePath := filepath.Join(filepath.Dir(envPath), "state.json") + enableCodex(t, envPath, cfgPath) + st := readCodexRecord(t, statePath) + if err := writeStateFile(statePath, managedState{Settings: st.Settings, Prior: st.Prior}); err != nil { + t.Fatal(err) + } + enableCodex(t, envPath, cfgPath) + if got := readCodexRecord(t, statePath).Written; !maps.Equal(got, readCodexEnv(t, envPath)) { + t.Errorf("Written = %v after a second enable, want what the file holds", got) + } + + if err := os.Remove(statePath); err != nil { + t.Fatal(err) + } + enableCodex(t, envPath, cfgPath) + if fileExists(statePath) { + t.Error("a second enable created a record where there was none") + } +} + +// #1289's rule: a managed key set to something else after enable, here a corporate CA +// bundle, is left and named, and only Cortex's values come out. Before, disable removed +// all five, losing the user's. +func TestCodexDisable_LeavesAValueChangedSinceEnable(t *testing.T) { + envPath, cfgPath := codexFixture(t, "RUST_LOG=info\n") + statePath := filepath.Join(filepath.Dir(envPath), "state.json") + enableCodex(t, envPath, cfgPath) + const corp = "/etc/ssl/corp.pem" + editFile(t, envPath, envSSLCert+"="+readCodexEnv(t, envPath)[envSSLCert], envSSLCert+"="+corp) + + var out, errb bytes.Buffer + if code := codexDisable(envPath, statePath, true, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + wantAll(t, "disable output", out.String(), + "This will remove from "+envPath+": HTTP_PROXY, HTTPS_PROXY, http_proxy, https_proxy\n", + "Leaving these alone — changed since Cortex set them:\n "+envSSLCert+"\n", + "Removed what Cortex set. The key(s) listed above are still in "+envPath+".\n") + if strings.Contains(out.String(), "no longer routes through Cortex") { + t.Errorf("disable claimed Codex no longer routes through Cortex with a key left:\n%s", out.String()) + } + if env := readCodexEnv(t, envPath); !maps.Equal(env, map[string]string{envSSLCert: corp}) { + t.Errorf("after disable the managed keys are %v, want only the user's %s", env, envSSLCert) + } +} + +// disable judges by enable's record, not by Cortex's config, so a config that moved its +// port since enable, or is gone, still leaves no value of Cortex's behind (#1783 review). +func TestCodexDisable_JudgesByTheRecordNotTheConfig(t *testing.T) { + for name, change := range map[string]func(t *testing.T, cfgPath string){ + "port moved": func(t *testing.T, cfgPath string) { + editFile(t, cfgPath, `forward_proxy_addr: "127.0.0.1:8081"`, `forward_proxy_addr: "127.0.0.1:8082"`) + }, + "config gone": func(t *testing.T, cfgPath string) { + if err := os.Remove(cfgPath); err != nil { + t.Fatal(err) + } + }, + } { + t.Run(name, func(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + editFile(t, cfgPath, `forward_proxy_addr: "127.0.0.1:47600"`, `forward_proxy_addr: "127.0.0.1:8081"`) + enableCodex(t, envPath, cfgPath) + change(t, cfgPath) + var out, errb bytes.Buffer + if code := codexDisable(envPath, filepath.Join(filepath.Dir(envPath), "state.json"), true, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if env := readCodexEnv(t, envPath); len(env) != 0 { + t.Errorf("after disable the managed keys are %v, want none:\n%s", env, out.String()) + } + wantAll(t, "disable output", out.String(), "Disabled. Codex no longer routes through Cortex.\n") + }) + } +} + // 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) { @@ -731,3 +849,66 @@ func TestCodexEnvValue(t *testing.T) { } } } + +// With no record of what enable wrote, every managed key is Cortex's, as it is for +// claude-code: removing a value of the user's is the lesser harm than leaving Codex on a +// Cortex being turned off (changedSinceEnable). +func TestCodexDisable_WithNoRecordRemovesEveryKey(t *testing.T) { + envPath, _ := codexFixture(t, "HTTPS_PROXY=http://127.0.0.1:47600\nSSL_CERT_FILE=/etc/ssl/corp.pem\n") + var out, errb bytes.Buffer + if code := codexDisable(envPath, filepath.Join(filepath.Dir(envPath), "state.json"), true, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if env := readCodexEnv(t, envPath); len(env) != 0 { + t.Errorf("after disable the managed keys are %v, want none", env) + } +} + +// A file whose managed keys were all changed since enable has nothing of Cortex's to take +// out: disable names them, asks nothing, changes nothing, restarts nothing, and deletes +// the record, which would otherwise say Cortex routes a file it does not. +func TestCodexDisable_ChangesNothingWhenEveryKeyChangedSinceEnable(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + statePath := filepath.Join(filepath.Dir(envPath), "state.json") + enableCodex(t, envPath, cfgPath) + mine := "HTTP_PROXY=http://proxy.corp.example:8080\nHTTPS_PROXY=http://proxy.corp.example:8080\n" + + "http_proxy=http://proxy.corp.example:8080\nhttps_proxy=http://proxy.corp.example:8080\nSSL_CERT_FILE=/etc/ssl/corp.pem\n" + if err := os.WriteFile(envPath, []byte(mine), 0o600); err != nil { + t.Fatal(err) + } + f := &fakeCodexDaemon{pid: 5613, env: onCortex, newPID: 7001, newEnv: offCortex} + stubCodexDaemon(t, filepath.Dir(envPath), f) + var out, errb bytes.Buffer + if code := codexDisable(envPath, statePath, false, &out, &errb); code != 0 { + t.Fatalf("disable exit %d, want 0 with no question asked: %s", code, errb.String()) + } + // The app-server started before the changes still has Cortex's proxy: named, with the + // restart that drops it, and not restarted, since nothing was asked (#1783 review). + wantAll(t, "disable output", out.String(), "Nothing to remove from "+envPath+".\n", "Leaving these alone — changed since Cortex set them:\n", + "Codex's background app-server (pid 5613", "still uses Cortex's proxy, from before\n", codexDaemonRestartCmd) + if b, _ := os.ReadFile(envPath); string(b) != mine { + t.Errorf("the file is %q, want it untouched", b) + } + if len(f.steps) != 0 { + t.Errorf("the daemon saw %v, want nothing", f.steps) + } + if fileExists(statePath) { + t.Error("enable's record outlived the last of Cortex's values") + } +} + +// Codex reads a quoted value with its quotes stripped, so a quoted copy of the value +// enable wrote is still Cortex's, and disable removes it rather than leave Codex on a +// Cortex being turned off (#1783 review). +func TestCodexDisable_ReadsAQuotedValueAsCodexDoes(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + enableCodex(t, envPath, cfgPath) + editFile(t, envPath, "HTTPS_PROXY="+cortexProxyURL, `HTTPS_PROXY="`+cortexProxyURL+`"`) + var out, errb bytes.Buffer + if code := codexDisable(envPath, filepath.Join(filepath.Dir(envPath), "state.json"), true, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if env := readCodexEnv(t, envPath); len(env) != 0 { + t.Errorf("after disable the managed keys are %v, want none:\n%s", env, out.String()) + } +} diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index 0b75b0c93..3961343d0 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -860,8 +860,10 @@ func codexProxyIn(envPath string, want map[string]string) bool { } // 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. +// Cortex's values 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 +// key changed since enable is the user's: disable leaves it, so it is this row's "Left +// behind", as it is the Claude Code row's. // // 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 @@ -870,7 +872,7 @@ func codexProxyIn(envPath string, want map[string]string) bool { func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) removal { codexHome := filepath.Dir(envPath) restartCmd := codexRestartCmdFor(env, codexHome) - pl, planErr := planCodexDisable(envPath) + pl, planErr := planCodexDisable(envPath, state) // 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) @@ -882,18 +884,15 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) } } } - // The proxy the restarted processes are compared with: the one this file held, read - // before the row removes it, else the config's. + // The proxy the restarted processes are compared with: the one the row removes from + // this file, read now, else the config's. A proxy left in place is not Cortex'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 - } - } + if planErr == nil { + if v := codexCortexProxy(pl); v != "" { + cortexProxy = v } } + leftNote := codexLeftNote(env, envPath, pl.left) where, suffix := env.tilde(envPath), "" if !samePath(envPath, defaultCodexEnvPath(env.home)) { suffix = " · " + env.tilde(envPath) @@ -933,7 +932,8 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) return "", unchanged, planErr } if len(pl.present) == 0 { - // Nothing of Cortex's left in the file: removed by hand, say. The record + // Nothing of Cortex's left in the file: every managed key it holds was + // changed after enable, or it holds none, removed by hand say. The record // would otherwise outlive it. detail := "nothing routed in " + env.tilde(envPath) if state != "" { @@ -942,13 +942,17 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) } detail = "removed Cortex's record (" + env.tilde(envPath) + " had nothing routed)" } - // An app-server started before those lines went may still have Cortex's + if len(pl.left) > 0 { + detail = "left " + someKeys(pl.left) + " as they are" + suffix + } + // An app-server started before those lines changed may still have Cortex's // proxy, which uninstall is about to stop, so it gets the restart a changed - // file would have (#1783 review). + // file would have (#1783 review). cortexProxy is enable's record of it when + // the file no longer holds it. if d, ok := runningCodexDaemon(codexHome); ok && d.EnvErr == nil && cortexProxy != "" && sameProxy(d.Proxy, cortexProxy) { - return settleCodex(detail, "", nil, true) + return settleCodex(detail, "", leftNote, true) } - return detail, nil, nil + return detail, leftNote, nil } _, running := runningCodexDaemon(codexHome) var errb bytes.Buffer @@ -956,11 +960,16 @@ func unrouteCodex(env *setupEnv, envPath, state string, want map[string]string) if err != nil { return "", unchanged, err } + // Not "no longer goes through Cortex" when a key was left: a left HTTPS_PROXY + // still points somewhere, and the row would contradict the note below it. detail := "Codex no longer goes through Cortex" + suffix + if len(pl.left) > 0 { + detail = "removed what Cortex set" + suffix + } if len(restored) > 0 { detail += " · restored your " + strings.Join(restored, ", ") } - return settleCodex(detail, stderrNotes(env, errb.String()), nil, running) + return settleCodex(detail, stderrNotes(env, errb.String()), leftNote, running) }, } } @@ -984,6 +993,17 @@ 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) } +// codexLeftNote is the Codex row's "Left behind" line for the keys disable did not touch +// because they changed since enable, in the Claude Code row's words (claudeCodeLeftNote). +// Keys and the file, no values: this text is printed at the end of a run and gets pasted. +func codexLeftNote(env *setupEnv, envPath string, left []string) []string { + if len(left) == 0 { + return nil + } + return []string{someKeys(left) + " in " + env.tilde(envPath) + + ", changed since Cortex set them — remove them by hand if you want them gone"} +} + // 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 diff --git a/cmd/agentop/cmd_uninstall_test.go b/cmd/agentop/cmd_uninstall_test.go index 0550fc61f..2f41a0595 100644 --- a/cmd/agentop/cmd_uninstall_test.go +++ b/cmd/agentop/cmd_uninstall_test.go @@ -2229,3 +2229,80 @@ func TestUninstallRestartsACodexStillOnCortexAfterItsLinesWent(t *testing.T) { t.Errorf("the daemon saw %v, want the updater stopped and the app-server restarted", f.steps) } } + +// A managed key changed since enable, here a CA bundle swapped in, is the user's. +// Uninstall takes out Cortex's values, leaves that one and says so, as the Claude Code +// row leaves a key changed since enable. +func TestUninstallLeavesACodexValueChangedSinceEnable(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + const corp = "/etc/ssl/corp.pem" + replaceIn(t, envPath, envSSLCert+"="+readCodexEnv(t, envPath)[envSSLCert], envSSLCert+"="+corp) + 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, changed since Cortex set them — remove them by hand if you want them gone\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 CA bundle of the user's kept inside ~/.cortex, set after enable, is theirs by the +// record, so uninstall leaves the key, and --purge keeps ~/.cortex rather than delete the +// file it names. By shape alone it read as Cortex's, and both went (#1781 review). Quoted, +// it is the same path to Codex, whose loader strips the quotes (#1783 review). +func TestUninstallPurgeKeepsAnOwnCodexCAUnderCortex(t *testing.T) { + for name, quote := range map[string]string{"bare": "", "double-quoted": `"`, "single-quoted": "'"} { + t.Run(name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + envPath := codexEnabledIn(t, sc, &fakeCodexDaemon{}) + mine := filepath.Join(sc.home, ".cortex", "my-corp.pem") + writeHomeFile(t, mine, "corporate CA\n") + replaceIn(t, envPath, envSSLCert+"="+readCodexEnv(t, envPath)[envSSLCert], envSSLCert+"="+quote+mine+quote) + code, out := sc.uninstall(t, "--yes", "--purge") + wantLines(t, code, 1, out, markLine("·", "purged")+"kept ~/.cortex: "+envSSLCert+ + " in ~/.codex/.env still points into it — delete it once nothing points into it: rm -rf ~/.cortex\n") + if got := readCodexEnv(t, envPath)[envSSLCert]; got != quote+mine+quote { + t.Errorf("%s = %q after uninstall, want the user's %q", envSSLCert, got, quote+mine+quote) + } + if !fileExists(mine) { + t.Error("--purge deleted the user's CA bundle") + } + }) + } +} + +// Uninstall judges by enable's record, not by Cortex's config, so a forward_proxy_addr +// moved since enable still leaves no value of Cortex's behind (#1783 review). +func TestUninstallUnroutesACodexWhosePortMovedSinceEnable(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{}) + replaceIn(t, cfg, "forward_proxy_addr: 127.0.0.1:8081", "forward_proxy_addr: 127.0.0.1:8082") + 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", got) + } +} + +// A file whose managed keys were all changed since enable has nothing of Cortex's to take +// out, but an app-server started before the changes still has Cortex's proxy, which +// uninstall is about to stop. Enable's record says what that proxy was, so the row +// restarts it, as it would after removing the keys (#1783 review). +func TestUninstallRestartsACodexStillOnCortexWhenEveryKeyChanged(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + f := runningCodex() + envPath := codexEnabledIn(t, sc, f) + const corp = "http://proxy.corp.example:8080" + writeHomeFile(t, envPath, "HTTP_PROXY="+corp+"\nHTTPS_PROXY="+corp+"\nhttp_proxy="+corp+"\nhttps_proxy="+corp+"\nSSL_CERT_FILE=/etc/corp.pem\n") + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 1, out, markLine("!", "unrouted")+"left HTTP_PROXY, HTTPS_PROXY, http_proxy, … as they are · 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.go b/cmd/agentop/codex_daemon.go index 9511b3801..2dce7b3be 100644 --- a/cmd/agentop/codex_daemon.go +++ b/cmd/agentop/codex_daemon.go @@ -382,8 +382,8 @@ func codexRun(bin, codexHome string, want map[string]string, args ...string) err } // codexCLIEnv is env, a list of "NAME=value" strings, without those of the managed keys -// (codexKeys) whose value is Cortex's, judged as disable judges them (codexIsOurs). Every -// other entry is kept. +// (codexKeys) whose value is Cortex's, by codexIsOurs: Cortex's value or its shape, since +// a process environment has no record to judge by. Every other entry is kept. func codexCLIEnv(env []string, want map[string]string) []string { out := make([]string, 0, len(env)) for _, kv := range env { diff --git a/cmd/agentop/codex_daemon_test.go b/cmd/agentop/codex_daemon_test.go index fc6c913ef..9b8c188e6 100644 --- a/cmd/agentop/codex_daemon_test.go +++ b/cmd/agentop/codex_daemon_test.go @@ -906,3 +906,42 @@ func TestCodexDaemonAlive_RealProcesses(t *testing.T) { t.Error("a non-positive pid reads as running") } } + +// A proxy of the user's left in the file is not what the restarted daemon is judged by: +// one that now uses that proxy no longer uses Cortex, and is not told it still does. +func TestCodexDisable_JudgesTheRestartByCortexsProxyNotOneItLeft(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + enableCodex(t, envPath, cfgPath) + const corp = "http://proxy.corp.example:8080" + editFile(t, envPath, "HTTPS_PROXY="+cortexProxyURL, "HTTPS_PROXY="+corp) + f := &fakeCodexDaemon{pid: 5613, env: onCortex, newPID: 7001, newEnv: []string{"HOME=/home/someone", "HTTPS_PROXY=" + corp}} + stubCodexDaemon(t, filepath.Dir(envPath), f) + + var out, errb bytes.Buffer + if code := codexDisable(envPath, filepath.Join(filepath.Dir(envPath), "state.json"), true, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + wantAll(t, "disable output", out.String(), "restarted (pid 7001) and no longer uses Cortex") + if strings.Contains(out.String(), "still uses Cortex's proxy") { + t.Errorf("disable called the user's proxy Cortex's:\n%s", out.String()) + } +} + +// With both HTTPS_PROXY spellings changed by the user, disable still knows Cortex's proxy +// from enable's record, so a restarted daemon that kept it is told so rather than +// reported as plainly restarted (#1783 review). +func TestCodexDisable_JudgesTheRestartByTheRecordWhenBothProxiesChanged(t *testing.T) { + envPath, cfgPath := codexFixture(t, "") + enableCodex(t, envPath, cfgPath) + const corp = "http://proxy.corp.example:8080" + editFile(t, envPath, "HTTPS_PROXY="+cortexProxyURL, "HTTPS_PROXY="+corp) + editFile(t, envPath, "https_proxy="+cortexProxyURL, "https_proxy="+corp) + f := &fakeCodexDaemon{pid: 5613, env: onCortex, newPID: 7001, newEnv: onCortex} + stubCodexDaemon(t, filepath.Dir(envPath), f) + + var out, errb bytes.Buffer + if code := codexDisable(envPath, filepath.Join(filepath.Dir(envPath), "state.json"), true, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + wantAll(t, "disable output", out.String(), "restarted (pid 7001), but it still uses Cortex's proxy") +} diff --git a/docs/agents/codex.md b/docs/agents/codex.md index 3f8a27fae..4258ced62 100644 --- a/docs/agents/codex.md +++ b/docs/agents/codex.md @@ -443,24 +443,37 @@ newly-added lines the first time any are appended. ### The record -The record is always empty today. The first `enable` records what the five -variables held in `~/.cortex/codex-state.json`. In practice that record contains nothing to -restore, and the reason is worth stating plainly rather than leaving as a surprise: -`enable` **refuses** whenever one of the five holds a value that is not Cortex's own, and -a value that *is* Cortex's own is recorded as absent (so `disable` removes it rather than -putting back a stale Cortex address). Those two rules are exact opposites, so every value -that reaches the record is stored as "was not set". The file, and `disable`'s restore -branch, exist to keep Codex's state shape identical to claude-code's and OpenCode's. +The first `enable` records, in `~/.cortex/codex-state.json`, which file it changed, what the +five variables held before, and the five values it wrote. Every later `enable` refreshes +the values it wrote, and one that finds nothing to change fills them in for a record made +before they were recorded, so an older install gains them on its next `enable`. + +What the variables held before is always "not set" today, and the reason is worth stating +plainly rather than leaving as a surprise: `enable` **refuses** whenever one of the five holds +a value that is not Cortex's own, and a value that *is* Cortex's own is recorded as absent +(so `disable` removes it rather than putting back a stale Cortex address). Those two rules +are exact opposites, so every earlier value that reaches the record is stored as "was not +set". `disable`'s restore branch exists to keep Codex's state shape identical to +claude-code's and OpenCode's. ### What disable does -`disable` removes the five variables, removes the +`disable` removes the variables that still hold the value `enable` wrote, removes the `# Added by agentop configure codex enable` marker if it is still exactly as written, and deletes the record — so an `enable` / `disable` cycle is a round trip that leaves the file -as it found it. It would restore a recorded prior value if one existed, which per the -paragraph above does not happen today; if you hand-edit one of the five variables after -`enable`, `disable` simply removes it. Unlike Claude Code's `disable`, it does not check -whether a value changed since `enable`. +as it found it. A variable you changed after `enable`, such as to a company proxy or CA +bundle, is left as it is, and `disable` names it, as Claude Code's `disable` does. It judges +by the record, not by Cortex's config, so it works the same when the config has moved its +port or is gone. With no record of what `enable` wrote (an install enabled before it was +recorded, or a deleted `~/.cortex`), it removes all five variables, as Claude Code's does: +leaving Codex pointed at a Cortex being turned off would be worse than losing an edit. In +v0.9.5 and earlier, `disable` removed all five whatever the record said. + +It reads each value as Codex does, with surrounding quotes removed, so a quoted copy of +Cortex's value is still Cortex's. When every variable was changed since `enable`, there is +nothing to remove, but an app-server started before those changes still uses Cortex's +proxy: `disable` names it, with the restart that drops the proxy, and does not restart it +itself. ### What status says @@ -545,8 +558,8 @@ 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` +removes Cortex's values, leaves and names a variable you changed since `enable`, 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