From eee7d07df995bbd7cee63573771cc72af3e146a0 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:33:08 -0700 Subject: [PATCH 1/8] :bug: Unroute Claude Code settings on uninstall Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 188 +++++++++++++--- cmd/agentop/cmd_claudecode_edits_test.go | 17 +- .../cmd_claudecode_settingspath_test.go | 208 ++++++++++++++++++ cmd/agentop/cmd_doctor.go | 54 +++-- cmd/agentop/cmd_doctor_checks_test.go | 27 +++ cmd/agentop/cmd_uninstall.go | 19 +- cmd/cortex/local.go | 18 +- cmd/cortex/local_test.go | 27 ++- cmd/cortex/main.go | 6 +- core/clientstate/clientstate.go | 37 +++- core/clientstate/clientstate_test.go | 19 ++ docs/agents/claude-code.md | 10 +- 12 files changed, 524 insertions(+), 106 deletions(-) create mode 100644 cmd/agentop/cmd_claudecode_settingspath_test.go diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index 77925827f..8eeac5382 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -104,6 +104,12 @@ func readState(path string) (*managedState, error) { if st.Prior == nil { return nil, fmt.Errorf("%s has no prior-value record", path) } + // One bad entry makes the whole record untrusted, as a bad first entry does. + for _, o := range st.OtherFiles { + if o.Settings == "" || o.Prior == nil { + return nil, fmt.Errorf("%s has an entry with no settings file or prior-value record", path) + } + } return &st, nil } @@ -119,6 +125,9 @@ func readState(path string) (*managedState, error) { // install.sh --claude-code makes on every upgrade still does not touch the file — // which is what lets setup's routed step top the record up unconditionally on its // already-routed path without writing on every upgrade. +// +// Claude Code's record holds an entry per settings file, through +// writeClaudeCodeState; the other agents' records hold one. func writeState(path string, st managedState) error { // An unreadable existing record is not a reason to overwrite it: if it can be // repaired by hand it is still the only copy of what the user had. @@ -132,17 +141,115 @@ func writeState(path string, st managedState) error { } st.Prior = existing.Prior } + return writeStateFile(path, st) +} + +// writeStateFile writes st as the whole record. +func writeStateFile(path string, st managedState) error { b, err := json.MarshalIndent(st, "", " ") if err != nil { return err } // Atomic, never truncate-in-place: this file is the only copy of what the // user had, and a kill mid-write used to leave it torn — after which the - // refusal above blocked every later enable while holding the Prior hostage - // (#1565). + // refusal in writeState blocked every later enable while holding the Prior + // hostage (#1565). return writeFileAtomic(path, append(b, '\n'), 0o600) } +// recordIndex is where the record keeps settingsPath's entry: 0 for the first +// file, i+1 for OtherFiles[i], and -1 for none. An entry names settingsPath when +// its text is the same, or when it is absolute and resolves to the same file. +func recordIndex(st *managedState, settingsPath string) int { + if st == nil { + return -1 + } + entries := append([]managedState{*st}, st.OtherFiles...) + for _, names := range []func(string) bool{ + func(recorded string) bool { return recorded == settingsPath }, + func(recorded string) bool { return filepath.IsAbs(recorded) && samePath(recorded, settingsPath) }, + } { + for i, e := range entries { + if names(e.Settings) { + return i + } + } + } + return -1 +} + +// adoptRelativeEntry records as abs the entry an older enable recorded as rel, +// the relative path given again here. An entry abs already has stays as it is. +func adoptRelativeEntry(statePath, rel, abs string) error { + st, err := readState(statePath) + if err != nil || recordFor(st, abs) != nil { + return nil + } + e := recordFor(st, rel) + if e == nil { + return nil + } + e.Settings = abs + return writeStateFile(statePath, *st) +} + +// recordFor is the record's entry for settingsPath, nil when it has none. +func recordFor(st *managedState, settingsPath string) *managedState { + switch i := recordIndex(st, settingsPath); i { + case -1: + return nil + case 0: + return st + default: + return &st.OtherFiles[i-1] + } +} + +// writeClaudeCodeState is writeState for a record of several settings files: e +// becomes its file's entry, and every other file's entry stays. An existing entry +// keeps its Prior, by writeState's rule. +func writeClaudeCodeState(path string, e managedState) error { + existing, err := readState(path) + if err != nil { + return fmt.Errorf("refusing to overwrite the existing record: %w", err) + } + cur := recordFor(existing, e.Settings) + switch { + case existing == nil: + existing = &e + case cur == nil: + existing.OtherFiles = append(existing.OtherFiles, e) + case cur.Settings == e.Settings && maps.Equal(cur.Written, e.Written): + return nil + default: + cur.Settings, cur.Written = e.Settings, e.Written + } + return writeStateFile(path, *existing) +} + +// dropRecord takes settingsPath's entry out of the record, and deletes the record +// with its last entry. A record that cannot be read is deleted whole, as disable +// has always done. +func dropRecord(path, settingsPath string) error { + st, err := readState(path) + if err != nil { + return removeIfExists(path) + } + switch i := recordIndex(st, settingsPath); { + case i == -1: + return nil + case i == 0 && len(st.OtherFiles) == 0: + return removeIfExists(path) + case i == 0: + next := st.OtherFiles[0] + next.OtherFiles = st.OtherFiles[1:] + return writeStateFile(path, next) + default: + st.OtherFiles = slices.Delete(st.OtherFiles, i-1, i) + return writeStateFile(path, *st) + } +} + // managedKeys is exactly what enable writes and disable removes. Nothing else in // the file is touched — notably not ANTHROPIC_BASE_URL or any auth token, which // commonly live in the same env block. @@ -281,6 +388,16 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { *cortexCfg = filepath.Join(home, cortexCfgRel) } statePath := filepath.Join(home, stateRel) + // Absolute, so the record names the file from any directory. + if abs, err := filepath.Abs(*settingsPath); err == nil { + if action != "status" && !filepath.IsAbs(*settingsPath) { + if err := adoptRelativeEntry(statePath, *settingsPath, abs); err != nil { + fmt.Fprintf(stderr, "agentop: %v\n", err) + return 1 + } + } + *settingsPath = abs + } switch action { case "enable": @@ -456,8 +573,10 @@ func planClaudeCodeEnable(settingsPath, cortexCfgPath, statePath string) (claude } } // An unreadable record is no proof of ownership, so it retires nothing. - if st, _ := readState(statePath); statePath != "" && st != nil && st.Settings == settingsPath { - pl.retire = ownedRetired(st, env) + if st, _ := readState(statePath); statePath != "" { + if e := recordFor(st, settingsPath); e != nil { + pl.retire = ownedRetired(e, env) + } } for _, k := range slices.Sorted(maps.Keys(pl.retire)) { pl.changes = append(pl.changes, " -"+k) @@ -522,21 +641,22 @@ func printTrustFileNotes(want map[string]string, stdout io.Writer) { // the right answer; only a record that exists gets its Written filled in. A record // that cannot be read is not ours to rewrite either — writeState says why. // -// Writing is left to writeState, which keeps Prior and skips the write entirely when +// Writing is left to writeClaudeCodeState, which keeps Prior and skips the write entirely when // Written already matches, so the usual upgrade re-run still touches no file. func topUpWritten(pl claudeCodePlan, statePath string, stderr io.Writer) { if statePath == "" { return } st, err := readState(statePath) - if err != nil || st == nil || st.Settings != pl.settingsPath { + e := recordFor(st, pl.settingsPath) + if err != nil || e == nil { return } - st.Written = map[string]string{} + written := map[string]string{} for _, k := range managedKeys { - st.Written[k] = pl.want[k] + written[k] = pl.want[k] } - if werr := writeState(statePath, *st); werr != nil { + if werr := writeClaudeCodeState(statePath, managedState{Settings: pl.settingsPath, Prior: e.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) } @@ -569,7 +689,7 @@ func applyClaudeCodeEnable(pl claudeCodePlan, statePath string, stderr io.Writer for k := range pl.retire { st.Written[k] = pl.env[k] } - if werr := writeState(statePath, st); werr != nil { + if werr := writeClaudeCodeState(statePath, st); werr != nil { fmt.Fprintf(stderr, "agentop: could not record prior settings (%v); disable will delete\n"+ " these keys rather than restore any you had set yourself\n", werr) } @@ -578,7 +698,7 @@ func applyClaudeCodeEnable(pl claudeCodePlan, statePath string, stderr io.Writer for k := range pl.retire { delete(st.Written, k) } - _ = writeState(statePath, st) + _ = writeClaudeCodeState(statePath, st) } }() } @@ -661,7 +781,7 @@ type claudeCodeDisablePlan struct { settingsPath string doc map[string]any env map[string]string // the env block as read, so output can name a left key's value - st *managedState // the ownership record, nil when none names this settings file + st *managedState // this settings file's entry in the ownership record, nil when it has none stErr error // the record was there and could not be read present []string // managed keys disable will change, in managedKeys order left []string // managed keys disable will not touch: changed since enable @@ -680,12 +800,9 @@ func planClaudeCodeDisable(settingsPath, statePath string) (claudeCodeDisablePla if statePath != "" { st, sterr := readState(statePath) pl.stErr = sterr - // A record naming a different settings file is another enable's, so it says - // nothing about this one — the rule the restore below has always applied, - // hoisted here so the ownership check uses it too. - if st != nil && st.Settings == settingsPath { - pl.st = st - } + // Another settings file's entry is that file's enable, so it says nothing + // about this one — the rule both the restore and the ownership check use. + pl.st = recordFor(st, settingsPath) } for _, k := range managedKeys { cur, ok := env[k] @@ -747,9 +864,9 @@ func changedSinceEnable(st *managedState, key, cur string) bool { // the edit itself, and the value survives — see claudeCodeNeedsCortexDir for what // that then means for --purge. // -// Only a record naming THIS settings file is ours to delete, which planClaudeCodeDisable -// has already decided: pl.st is nil unless the record names this file, and a disable -// here must not take another enable's record away. removeDisabledRecord says the rest. +// Only THIS settings file's entry is ours to delete, which planClaudeCodeDisable has +// already decided: pl.st is nil unless the record has one, and a disable here must +// not take another file's entry away. removeDisabledRecord says the rest. func applyClaudeCodeDisable(pl claudeCodeDisablePlan, statePath string, stderr io.Writer) ([]string, error) { if len(pl.present) == 0 { return nil, nil @@ -790,15 +907,15 @@ func applyClaudeCodeDisable(pl claudeCodeDisablePlan, statePath string, stderr i if err := writeSettings(pl.settingsPath, pl.doc); err != nil { return nil, err } - // A nil st with no read error means the record is some other settings file's (or - // there is none), and deleting it would strand that file's Written — the next + // A nil st with no read error means the record has no entry for this file (or + // there is none), and deleting it would strand another file's Written — the next // disable there would have no ownership to check an edit against, which is the // bug this change fixes, reached by way of a disable on an unrelated file. stErr // keeps today's behaviour for a record that is there and unreadable: left in // place it would outlive every disable, and doctor would report Claude Code as // routed for good. if statePath != "" && (pl.st != nil || pl.stErr != nil) { - _ = os.Remove(statePath) + _ = dropRecord(statePath, pl.settingsPath) } return restored, nil } @@ -825,23 +942,24 @@ func printClaudeCodeLeft(pl claudeCodeDisablePlan, stdout io.Writer) { pl.settingsPath) } -// removeDisabledRecord deletes the ownership record on the disable paths that -// never reach applyClaudeCodeDisable, because the file holds none of Cortex's own -// values: all of its managed keys were changed after enable, or it has none at all. -// Cortex does not route it either way, and the record is what says it does — -// claudeCodeRouted answers from the record's existence alone, so leaving it makes -// `agentop doctor` report a routing that is gone and offer a fix that restores it. +// removeDisabledRecord deletes this file's entry in the ownership record on the +// disable paths that never reach applyClaudeCodeDisable, because the file holds +// none of Cortex's own values: all of its managed keys were changed after enable, +// or it has none at all. Cortex does not route it either way, and the record is +// what says it does — claudeCodeRouted answers from the record's existence alone, +// so leaving it makes `agentop doctor` report a routing that is gone and offer a +// fix that restores it. // -// Only a record naming THIS settings file is ours to delete: one naming another is -// a different enable's, and `disable --settings` on a project file must not take it -// away. planClaudeCodeDisable has already applied that rule — pl.st is nil unless -// the record names this file — so a nil st means there is nothing here to remove. +// Only THIS settings file's entry is ours to delete: another file's is a different +// enable's, and `disable --settings` on a project file must not take it away. +// planClaudeCodeDisable has already applied that rule — pl.st is nil unless the +// record has an entry for this file — so a nil st means there is nothing to remove. // A record that could not be read is left too, for the reason writeState gives. func removeDisabledRecord(pl claudeCodeDisablePlan, statePath string, stderr io.Writer) { if statePath == "" || pl.st == nil { return } - if err := os.Remove(statePath); err != nil && !os.IsNotExist(err) { + if err := dropRecord(statePath, pl.settingsPath); err != nil { fmt.Fprintf(stderr, "agentop: could not remove %s (%v); `agentop doctor` will go on\n"+ " reporting Claude Code as routed through Cortex. Delete it by hand.\n", statePath, err) } diff --git a/cmd/agentop/cmd_claudecode_edits_test.go b/cmd/agentop/cmd_claudecode_edits_test.go index 74f49ca08..d6ee1c3c8 100644 --- a/cmd/agentop/cmd_claudecode_edits_test.go +++ b/cmd/agentop/cmd_claudecode_edits_test.go @@ -351,29 +351,28 @@ func TestClaudeCodeDisable_RecordWithoutWrittenStillRemoves(t *testing.T) { } } -// A record naming another settings file belongs to another enable, and a disable -// here must not take it away. planClaudeCodeDisable already refuses to *read* it — +// Another settings file's entry belongs to another enable, and a disable here +// must not take it away. planClaudeCodeDisable already refuses to *read* it — // pl.st stays nil unless the record names this file — but the removal at the end // ran on statePath alone, so `disable --settings` on a project file deleted the // default file's record. That strands the default file's Written, and the next // disable there has no ownership to check an edit against: #1289 again, reached // by way of a disable on a file that has nothing to do with it. -func TestClaudeCodeDisable_KeepsARecordNamingAnotherSettingsFile(t *testing.T) { +func TestClaudeCodeDisable_KeepsAnotherSettingsFilesEntry(t *testing.T) { const corp = "http://corp.example:3128" main, cfg := fixture(t, settingsWithSecret) proj := filepath.Join(t.TempDir(), "settings.json") state := filepath.Join(t.TempDir(), "state.json") var out, errb bytes.Buffer - // The project file first, so the main file's enable is the one that replaces the - // record: it names whichever file enabled last. + // The project file first, so the main file's entry is the one disable promotes. if code := claudeCodeEnable2(proj, cfg, state, true, &out, &errb); code != 0 { t.Fatalf("enable on the project file failed: %s", errb.String()) } if code := claudeCodeEnable2(main, cfg, state, true, &out, &errb); code != 0 { t.Fatalf("enable on the main file failed: %s", errb.String()) } - if st, err := readState(state); err != nil || st == nil || st.Settings != main { - t.Fatalf("fixture: the record names %+v (err %v), want %s", st, err, main) + if st, err := readState(state); err != nil || recordFor(st, main) == nil || recordFor(st, proj) == nil { + t.Fatalf("fixture: the record is %+v (err %v), want entries for %s and %s", st, err, proj, main) } // The project file still holds Cortex's values, so this disable goes through @@ -387,8 +386,8 @@ func TestClaudeCodeDisable_KeepsARecordNamingAnotherSettingsFile(t *testing.T) { if err != nil || st == nil { t.Fatalf("a disable on another settings file deleted the main file's record (err %v)", err) } - if st.Settings != main { - t.Errorf("the record names %q, want %q", st.Settings, main) + if st.Settings != main || len(st.OtherFiles) != 0 { + t.Errorf("the record is %+v, want only the entry for %s", st, main) } // And what keeping it is for: the main file's Written is still there to check a diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go new file mode 100644 index 000000000..357907c65 --- /dev/null +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -0,0 +1,208 @@ +package main + +import ( + "bytes" + "io" + "os" + "path/filepath" + "slices" + "testing" +) + +// A relative --settings is recorded as the absolute path it named, so uninstall +// finds the project file from any directory. +func TestClaudeCodeEnable_RecordsARelativeSettingsPathAbsolute(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + projDir := filepath.Join(sc.home, "proj") + proj := filepath.Join(projDir, ".claude", "settings.json") + writeHomeFile(t, proj, "{}\n") + t.Chdir(projDir) + var out, errb bytes.Buffer + if code := runClaudeCode([]string{"enable", "--yes", "--settings", ".claude/settings.json"}, &out, &errb); code != 0 { + t.Fatalf("enable exit %d: %s", code, errb.String()) + } + if st, err := readState(filepath.Join(sc.home, stateRel)); err != nil || st == nil || st.Settings != proj { + t.Fatalf("the record is %+v (%v), want one naming %s", st, err, proj) + } + + t.Chdir(sc.home) + code, got := sc.uninstall(t, "--yes") + wantLines(t, code, 0, got, markLine("✓", "unrouted")+"Claude Code no longer goes through Cortex · ~/proj/.claude/settings.json\n") + if doc, err := readSettings(proj); err != nil || len(envStrings(doc)) != 0 { + t.Errorf("the project's settings still route: %v (%v)", doc, err) + } +} + +// setup --claude-code after a project enable, as every upgrade runs it, routes +// the default file too. Uninstall unroutes both, and keeps the CA the user set in +// the project file since. +func TestUninstallUnroutesEverySettingsFileCortexRouted(t *testing.T) { + const corpCA = "/etc/corp-ca.pem" + sc := newUninstallScene(t) + sc.setUp(t) + proj := filepath.Join(sc.home, "proj", ".claude", "settings.json") + writeHomeFile(t, proj, "{}\n") + cfg := filepath.Join(sc.home, ".cortex", "config.yaml") + if code := claudeCodeEnable2(proj, cfg, filepath.Join(sc.home, stateRel), true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: enable --settings exit %d", code) + } + handEdit(t, proj, map[string]string{envCACerts: corpCA}) + sc.setUp(t, "--claude-code") + + code, out := sc.uninstall(t, "--yes") + wantLines(t, code, 1, out, + markLine("!", "unrouted")+"removed what Cortex set · ~/proj/.claude/settings.json\n", + markLine("✓", "unrouted")+"Claude Code no longer goes through Cortex\n") + if env := readEnv(t, proj); env[envCACerts] != corpCA || len(env) != 1 { + t.Errorf("the project's env is %v, want only %s=%s:\n%s", env, envCACerts, corpCA, out) + } + if env := readEnv(t, filepath.Join(sc.home, settingsRel)); len(env) != 0 { + t.Errorf("the default settings still route: %v", env) + } +} + +// A disable on the first of two enabled files keeps a value set there since its +// enable. +func TestClaudeCodeDisable_KeepsAnEditToTheFirstFileAfterAnotherEnable(t *testing.T) { + const corp = "http://corp.example:3128" + first, cfg := fixture(t, "{}") + second := filepath.Join(t.TempDir(), "settings.json") + state := filepath.Join(t.TempDir(), "state.json") + if code := claudeCodeEnable2(first, cfg, state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: enable on the first file exit %d", code) + } + handEdit(t, first, map[string]string{envProxy: corp}) + if code := claudeCodeEnable2(second, cfg, state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: enable on the second file exit %d", code) + } + var errb bytes.Buffer + if code := claudeCodeDisable2(first, state, true, io.Discard, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if env := readEnv(t, first); env[envProxy] != corp || len(env) != 1 { + t.Errorf("the first file's env is %v, want only %s=%s", env, envProxy, corp) + } +} + +// Each settings file keeps its own entry: a later enable adds one beside the +// others, a re-enable refreshes only its Written, and a drop takes out only its +// own, keeping the next entry whole when it moves up and deleting the record +// with the last. +func TestClaudeCodeRecordKeepsAnEntryPerSettingsFile(t *testing.T) { + state := filepath.Join(t.TempDir(), "state.json") + corp := "http://corp.example:3128" + entry := func(settings, written string, prior *string) managedState { + return managedState{Settings: settings, Prior: map[string]*string{envProxy: prior}, Written: map[string]string{envProxy: written}} + } + for _, e := range []managedState{entry("/a", "w1", nil), entry("/b", "w1", &corp), entry("/c", "w3", &corp), entry("/b", "w2", nil)} { + if err := writeClaudeCodeState(state, e); err != nil { + t.Fatal(err) + } + } + st, err := readState(state) + if err != nil || len(st.OtherFiles) != 2 { + t.Fatalf("the record is %+v (%v), want three entries", st, err) + } + if b := recordFor(st, "/b"); b.Written[envProxy] != "w2" || b.Prior[envProxy] == nil || *b.Prior[envProxy] != corp { + t.Errorf("/b's entry is %+v, want Written w2 and its first Prior kept", b) + } + + for _, c := range []struct { + drop string + want []string // the files the record names afterwards, first one first + }{{"/b", []string{"/a", "/c"}}, {"/a", []string{"/c"}}, {"/elsewhere", []string{"/c"}}, {"/c", nil}} { + if err := dropRecord(state, c.drop); err != nil { + t.Fatal(err) + } + st, err := readState(state) + if err != nil { + t.Fatal(err) + } + var got []string + if st != nil { + got = append(got, st.Settings) + for _, o := range st.OtherFiles { + got = append(got, o.Settings) + } + } + if !slices.Equal(got, c.want) { + t.Errorf("after dropping %s the record names %q, want %q", c.drop, got, c.want) + } + if c.drop == "/a" && (st.Written[envProxy] != "w3" || st.Prior[envProxy] == nil || *st.Prior[envProxy] != corp) { + t.Errorf("/c's entry moved up as %+v, want its Written w3 and Prior kept", st) + } + } + if _, err := os.Stat(state); !os.IsNotExist(err) { + t.Errorf("the record outlived its last entry (%v)", err) + } +} + +// An entry an older enable recorded relative to a project names only that +// project's file: an enable on the default file from $HOME adds its own entry. +func TestClaudeCodeEnable_LeavesAnOlderRelativeEntryToItsProject(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + projDir := filepath.Join(sc.home, "proj") + writeHomeFile(t, filepath.Join(projDir, settingsRel), "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(projDir) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + + t.Chdir(sc.home) + var errb bytes.Buffer + if code := runClaudeCode([]string{"enable", "--yes"}, io.Discard, &errb); code != 0 { + t.Fatalf("enable exit %d: %s", code, errb.String()) + } + st, err := readState(state) + if err != nil || st.Settings != settingsRel || len(st.OtherFiles) != 1 || st.OtherFiles[0].Settings != filepath.Join(sc.home, settingsRel) { + t.Errorf("the record is %+v (%v), want the relative entry and one for the default file", st, err) + } +} + +// A relative --settings given again where an older enable recorded it finds +// that entry, so disable takes it out. +func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + projDir := filepath.Join(sc.home, "proj") + writeHomeFile(t, filepath.Join(projDir, settingsRel), "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(projDir) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + + var errb bytes.Buffer + if code := runClaudeCode([]string{"disable", "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if _, err := os.Stat(state); !os.IsNotExist(err) { + t.Errorf("the record outlived the disable of the file it names (%v)", err) + } +} + +// An entry recorded under a symlink names the file it resolves to. +func TestClaudeCodeRecordMatchesASymlinkedPath(t *testing.T) { + dir := t.TempDir() + link := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(dir, link); err != nil { + t.Fatal(err) + } + st := &managedState{Settings: "/a", OtherFiles: []managedState{{Settings: filepath.Join(link, "settings.json")}}} + if got := recordIndex(st, filepath.Join(dir, "settings.json")); got != 1 { + t.Errorf("recordIndex = %d, want 1, the entry under the link", got) + } +} + +// One entry with no Prior makes the record unreadable, as a first entry with none +// does. +func TestClaudeCodeRecordRefusesAnEntryWithNoPrior(t *testing.T) { + state := filepath.Join(t.TempDir(), "state.json") + writeHomeFile(t, state, `{"settings":"/a","prior":{},"other_files":[{"settings":"/b"}]}`) + if st, err := readState(state); err == nil { + t.Errorf("readState = %+v, want an error for the entry with no prior", st) + } +} diff --git a/cmd/agentop/cmd_doctor.go b/cmd/agentop/cmd_doctor.go index b6d7b36a2..e93dc60d7 100644 --- a/cmd/agentop/cmd_doctor.go +++ b/cmd/agentop/cmd_doctor.go @@ -57,7 +57,7 @@ func runDoctor(args []string, stdout, stderr io.Writer) int { _, _ = fmt.Fprintf(stderr, "agentop: %v\n", err) return 1 } - var elsewhere string + var elsewhere []string env.opts.claudeCode, env.opts.noService, elsewhere = installShape(env) fix := "agentop setup" if env.opts.claudeCode { @@ -87,12 +87,12 @@ func runDoctor(args []string, stdout, stderr io.Writer) int { if _, ok := s.(serviceStep); !ok { continue } - switch { - case elsewhere != "": - if checkRoutedElsewhere(env, ui, elsewhere, fix) { + for _, f := range elsewhere { + if checkRoutedElsewhere(env, ui, f, fix) { failed = true } - case !env.opts.claudeCode: + } + if len(elsewhere) == 0 && !env.opts.claudeCode { hint := "agentop setup --claude-code" if env.opts.noService { hint += " --no-service" @@ -162,19 +162,24 @@ func wouldChange(p stepPlan) string { // a project's, is elsewhere and is checked on its own: setup's step writes only the // default file, so its plan would read that file as unrouted, and its fix would // route Claude Code globally. -func installShape(env *setupEnv) (claudeCode, noService bool, elsewhere string) { - elsewhere = recordedSettings(env) - if elsewhere != "" && samePath(elsewhere, filepath.Join(env.home, settingsRel)) { - elsewhere = "" +func installShape(env *setupEnv) (claudeCode, noService bool, elsewhere []string) { + def := filepath.Join(env.home, settingsRel) + recorded := false + for _, s := range recordedSettings(env) { + if samePath(s, def) { + recorded = true + continue + } + elsewhere = append(elsewhere, s) } - return elsewhere == "" && claudeCodeRouted(env), backgroundOnly(env), elsewhere + return recorded || len(elsewhere) == 0 && claudeCodeRouted(env), backgroundOnly(env), elsewhere } // claudeCodeRouted reports whether Cortex routed Claude Code: enable's state // record is there, or settings.json's HTTPS_PROXY is the proxy enable would write -// from the current config. Enable writes the record and every disable deletes it, -// including one that left a key behind because its value changed since enable set -// it — the record's existence is read here as "Cortex routes this", so it must not +// from the current config. Enable writes the record and every disable deletes its +// file's entry, the record going with the last, including one that left a key +// behind because its value changed since enable set it — the record's existence is read here as "Cortex routes this", so it must not // outlive the values it describes, or doctor reports a routing that is gone and // offers a fix that puts it back. Keeping it for a left key's sake would cost that // key its edit too — applyClaudeCodeDisable says why. @@ -187,16 +192,23 @@ func claudeCodeRouted(env *setupEnv) bool { return fileExists(filepath.Join(env.home, stateRel)) || cortexProxyIn(env, filepath.Join(env.home, settingsRel)) } -// recordedSettings is the settings file enable's record names, which --settings -// may have made a project's: the file doctor checks and uninstall unroutes. It -// is "" when the record names none: there is no record, it cannot be read, or the -// path in it is relative, as enable wrote it from where it ran, so it is a guess. -func recordedSettings(env *setupEnv) string { +// recordedSettings is each settings file enable's record names, which --settings +// may have made a project's: the files doctor checks and uninstall unroutes. It +// is empty when the record names none: there is no record or it cannot be read. A +// relative path, as an older enable wrote it from where it ran, is a guess and is +// left out, so a record of only those is empty too. +func recordedSettings(env *setupEnv) []string { st, err := readState(filepath.Join(env.home, stateRel)) - if err != nil || st == nil || !filepath.IsAbs(st.Settings) { - return "" + if err != nil || st == nil { + return nil + } + var files []string + for _, e := range append([]managedState{*st}, st.OtherFiles...) { + if filepath.IsAbs(e.Settings) { + files = append(files, e.Settings) + } } - return st.Settings + return files } // cortexProxyIn reports whether the settings file's HTTPS_PROXY is the proxy diff --git a/cmd/agentop/cmd_doctor_checks_test.go b/cmd/agentop/cmd_doctor_checks_test.go index 1ffa2409d..66c4c28ee 100644 --- a/cmd/agentop/cmd_doctor_checks_test.go +++ b/cmd/agentop/cmd_doctor_checks_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "io" "os" "path/filepath" "slices" @@ -383,6 +384,32 @@ func TestDoctorFailsTheRecordedSettingsFileWhenItNoLongerRoutes(t *testing.T) { } } +// With the default file routed as well, doctor still checks the project file, +// and update keeps --claude-code for the default one. +func TestDoctorChecksTheProjectFileBesideTheDefaultOne(t *testing.T) { + sc := newDoctorScene(t) + sc.installed(t) + proj := routeProject(t, sc) + var errb bytes.Buffer + if code := claudeCodeEnable2(filepath.Join(sc.home, settingsRel), filepath.Join(sc.home, ".cortex", "config.yaml"), + filepath.Join(sc.home, stateRel), true, io.Discard, &errb); code != 0 { + t.Fatalf("fixture: enable on the default file exit %d: %s", code, errb.String()) + } + writeHomeFile(t, proj, "{}\n") + code, out := sc.doctor(t) + wantLines(t, code, 1, out, "\n"+markLine("✗", "routed")+"Claude Code is not routed through Cortex in ~/proj/.claude/settings.json\n") + if strings.Contains(out, "is not routed;") { + t.Errorf("doctor reads the default file as unrouted:\n%s", out) + } + env, err := newSetupEnv(setupOptions{}) + if err != nil { + t.Fatal(err) + } + if flags := updateFlags(env, "", false); !slices.Contains(flags, "--claude-code") { + t.Errorf("update flags %q, want --claude-code", flags) + } +} + // Off PATH with no marker, as setup --no-modify-path leaves it, the ✗ PATH line // has two fixes: setup, which adds the lines, and the line to add by hand, for // whoever chose to keep setup out of their dotfiles. diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index c20d34e3e..211b9a320 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -389,7 +389,7 @@ func cortexDirNeededBy(rs []removal) []string { return why } -// planUnrouteClaudeCode is a removal for each settings file Cortex routed: the +// planUnrouteClaudeCode is a removal for each settings file Cortex routed: each // one enable's record names, which --settings may have made a project's, and // ~/.claude/settings.json when its own HTTPS_PROXY is Cortex's. The record is read // now. A file the record does not name is unrouted only when its proxy is @@ -399,14 +399,14 @@ func planUnrouteClaudeCode(env *setupEnv) []removal { state, def := filepath.Join(env.home, stateRel), filepath.Join(env.home, settingsRel) named := recordedSettings(env) var rs []removal - if named != "" { - rs = append(rs, unrouteClaudeCode(env, named, state)) + for _, s := range named { + rs = append(rs, unrouteClaudeCode(env, s, state)) } - if (named == "" || !samePath(named, def)) && cortexProxyIn(env, def) { + if !slices.ContainsFunc(named, func(s string) bool { return samePath(s, def) }) && cortexProxyIn(env, def) { // 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 == "" { + if len(named) == 0 { record = state } rs = append(rs, unrouteClaudeCode(env, def, record)) @@ -452,7 +452,12 @@ func unrouteClaudeCode(env *setupEnv, settings, state string) removal { // have deleted goes here. Left, doctor reads Claude Code as routed for // good, a left key or not: it answers from the record's existence. if state != "" { - if err := removeIfExists(state); err != nil { + // This file's entry, or a record that names no file whole. + drop := removeIfExists + if pl.st != nil { + drop = func(state string) error { return dropRecord(state, settings) } + } + if err := drop(state); err != nil { return "", []string{env.tilde(state)}, withFixes(err, manual("rm "+env.shellPath(state))) } } @@ -579,7 +584,7 @@ func unrouteByHand(env *setupEnv, settings, state string, keys, left []string) s } var remove, restore []string for _, k := range keys { - if st != nil && st.Settings == settings && st.Prior[k] != nil { + if e := recordFor(st, settings); e != nil && e.Prior[k] != nil { restore = append(restore, k) } else { remove = append(remove, k) diff --git a/cmd/cortex/local.go b/cmd/cortex/local.go index b1d178e1b..6b04564e5 100644 --- a/cmd/cortex/local.go +++ b/cmd/cortex/local.go @@ -66,16 +66,16 @@ func defaultCortexDir() (string, error) { // what makes two of them indistinguishable from each other. const bridgeCACommonName = "authbridge-tls-bridge-ca" -// clientCAFromState returns the CA file the agentop-managed client is configured with -// right now, or "" when that cannot be established. The record's name and shape, and -// the reason `prior` is the wrong field to read, live in core/clientstate — shared -// with agentop, which writes the file. -func clientCAFromState(statePath string) string { +// clientCAsFromState returns the CA file each agentop-managed settings file is +// configured with right now, leaving out those that cannot be established. The +// record's name and shape, and the reason `prior` is the wrong field to read, live +// in core/clientstate — shared with agentop, which writes the file. +func clientCAsFromState(statePath string) []string { st, err := clientstate.Load(statePath) - if err != nil || st == nil { - return "" + if err != nil { + return nil } - return st.CurrentCA() + return st.CurrentCAs() } // staleClientCAWarning reports a client pointed at a DIFFERENT bridge CA than the @@ -92,7 +92,7 @@ func clientCAFromState(statePath string) string { // // Two properties make this safe to print on every boot, and both are load-bearing: // -// - It reads the client's CURRENT CA (clientCAFromState), not agentop's record of +// - It reads the client's CURRENT CA (clientCAsFromState), not agentop's record of // what it displaced. The displaced value is a different CA by construction on // every enable, so comparing it warns about clients that are already correct. // - It compares the CERTIFICATES, not their paths. The configured file is often diff --git a/cmd/cortex/local_test.go b/cmd/cortex/local_test.go index a8b071b94..5fa186ca1 100644 --- a/cmd/cortex/local_test.go +++ b/cmd/cortex/local_test.go @@ -286,13 +286,18 @@ func TestStaleClientCAWarning_SilentWithoutInputs(t *testing.T) { // core/tlsbridge (TestFingerprintSHA256_MatchesOpenSSL). It used to be duplicated // here against a local copy of the byte loop; both collapsed into the shared helper. -// clientCAFromState reads the CA the client is configured with RIGHT NOW, which is +// clientCAsFromState reads the CA the client is configured with RIGHT NOW, which is // the only value that can justify this warning. These tests pin why `prior` cannot: // agentop snapshots `prior` from the settings env block BEFORE overwriting it in the // same run (cmd_claudecode.go:468-478), so it is what agentop displaced, never what // the client holds. In the actual #1033 repro that makes it doubly wrong — the run // that put a foreign CA into `prior` also pointed the client at the correct one. +// oneClientCA is clientCAsFromState for a record of one settings file. +func oneClientCA(statePath string) string { + return strings.Join(clientCAsFromState(statePath), ",") +} + // writeStateAndSettings lays down agentop's two files: the state record naming a // settings path, and that settings file with the given current CA value. Passing // currentCA == "" writes an env block with no NODE_EXTRA_CA_CERTS at all. @@ -336,7 +341,7 @@ func TestClientCAFromState_ReadsTheCurrentValueNotPrior(t *testing.T) { "/old/sandbox/.cortex/ca/ca.crt", // what agentop displaced "/current/.cortex/ca/ca.crt") // what the client actually loads now - got := clientCAFromState(statePath) + got := oneClientCA(statePath) if got == "/old/sandbox/.cortex/ca/ca.crt" { t.Fatal("read `prior` — agentop's record of what it DISPLACED. The same enable that " + @@ -344,7 +349,7 @@ func TestClientCAFromState_ReadsTheCurrentValueNotPrior(t *testing.T) { "client that is already correct, and can never go quiet") } if got != "/current/.cortex/ca/ca.crt" { - t.Errorf("clientCAFromState = %q, want the live NODE_EXTRA_CA_CERTS", got) + t.Errorf("oneClientCA = %q, want the live NODE_EXTRA_CA_CERTS", got) } } @@ -371,8 +376,8 @@ func TestClientCAFromState_ToleratesEveryFailure(t *testing.T) { } for name, p := range cases { t.Run(name, func(t *testing.T) { - if got := clientCAFromState(p); got != "" { - t.Errorf("clientCAFromState(%s) = %q, want \"\"", name, got) + if got := oneClientCA(p); got != "" { + t.Errorf("oneClientCA(%s) = %q, want \"\"", name, got) } }) } @@ -388,8 +393,8 @@ func TestClientCAFromState_ToleratesEveryFailure(t *testing.T) { if err := os.WriteFile(p, []byte(body), 0o600); err != nil { t.Fatal(err) } - if got := clientCAFromState(p); got != "" { - t.Errorf("clientCAFromState(%s) = %q, want \"\"", name, got) + if got := oneClientCA(p); got != "" { + t.Errorf("oneClientCA(%s) = %q, want \"\"", name, got) } }) } @@ -404,8 +409,8 @@ func TestClientCAFromState_ToleratesEveryFailure(t *testing.T) { if err := os.WriteFile(p, st, 0o600); err != nil { t.Fatal(err) } - if got := clientCAFromState(p); got != "" { - t.Errorf("clientCAFromState with unparseable settings = %q, want \"\"", got) + if got := oneClientCA(p); got != "" { + t.Errorf("oneClientCA with unparseable settings = %q, want \"\"", got) } } @@ -422,13 +427,13 @@ func TestStaleClientCAWarning_GoesQuietAfterTheClientIsFixed(t *testing.T) { // Misconfigured: settings point at another $HOME's bridge CA. statePath := writeStateAndSettings(t, dir, "/whatever/prior.crt", otherCA) - if got := staleClientCAWarning("/current/.cortex/ca", clientCAFromState(statePath), inForce); got == nil { + if got := staleClientCAWarning("/current/.cortex/ca", oneClientCA(statePath), inForce); got == nil { t.Fatal("no warning while the client is genuinely pointed at a different bridge CA") } // Fixed: settings now name the CA in force. `prior` is unchanged and still stale. statePath = writeStateAndSettings(t, dir, "/whatever/prior.crt", currentCAPath) - if got := staleClientCAWarning("/current/.cortex/ca", clientCAFromState(statePath), inForce); got != nil { + if got := staleClientCAWarning("/current/.cortex/ca", oneClientCA(statePath), inForce); got != nil { t.Errorf("still warning after the client was fixed — this is the every-boot-forever "+ "failure the comparison exists to avoid: %v", got) } diff --git a/cmd/cortex/main.go b/cmd/cortex/main.go index 3def5f90c..4ad648fdc 100644 --- a/cmd/cortex/main.go +++ b/cmd/cortex/main.go @@ -934,8 +934,10 @@ func main() { // the comparison is on certificates, so ours must exist first. Skipped outside // --local, where there is no agentop-managed client to reason about. if localStatePath != "" { - if args := staleClientCAWarning(cfg.TLSBridge.CADir, clientCAFromState(localStatePath), src.CACertPEM()); args != nil { - slog.Warn("a client is configured against a different bridge CA than the one now in force", args...) + for _, ca := range clientCAsFromState(localStatePath) { + if args := staleClientCAWarning(cfg.TLSBridge.CADir, ca, src.CACertPEM()); args != nil { + slog.Warn("a client is configured against a different bridge CA than the one now in force", args...) + } } } // Assemble the CA + platform-roots bundle for tools whose CA setting diff --git a/core/clientstate/clientstate.go b/core/clientstate/clientstate.go index 29f17c56f..7b5fd145e 100644 --- a/core/clientstate/clientstate.go +++ b/core/clientstate/clientstate.go @@ -29,10 +29,11 @@ const CAEnvVar = "NODE_EXTRA_CA_CERTS" // State is the record agentop writes. // -// Prior holds what agentop DISPLACED, captured before it overwrote the settings, and -// exists so `disable` can restore rather than delete. It is emphatically not what -// the client currently uses — every enable makes the two differ — so a reader asking -// "what CA does this client load?" must go through Settings. See CurrentCA. +// Prior holds what agentop DISPLACED, captured before it overwrote the settings +// file, and exists so `disable` can restore rather than delete. It is emphatically +// not what the client currently uses — every enable makes the two differ — so a +// reader asking "what CA does this client load?" must go through Settings. See +// CurrentCA. // // Written holds what agentop ITSELF SET for each managed key, so `disable` can tell // its own value from one changed since. Without it, disable restored Prior over @@ -48,10 +49,15 @@ const CAEnvVar = "NODE_EXTRA_CA_CERTS" // Written is omitempty and may be absent or incomplete: a record from before it // existed has none, and a key added to the managed set later is missing from an // older record. A reader must treat "not recorded" as "unknown", never as "". +// +// Both are per settings file. OtherFiles holds one entry, in the same shape, for +// each further settings file agentop routed, so each file keeps its own Prior +// and Written. CurrentCAs reads every file's. type State struct { - Settings string `json:"settings"` - Prior map[string]*string `json:"prior"` - Written map[string]string `json:"written,omitempty"` + Settings string `json:"settings"` + Prior map[string]*string `json:"prior"` + Written map[string]string `json:"written,omitempty"` + OtherFiles []State `json:"other_files,omitempty"` } // Load reads the record at path. A missing file is (nil, nil): absent is a normal @@ -72,7 +78,7 @@ func Load(path string) (*State, error) { } // CurrentCA returns the CA file the recorded client is configured with RIGHT NOW, by -// reading the live value out of the settings file the record names. Returns "" when +// reading the live value out of the entry's settings file. Returns "" when // that cannot be established for any reason. // // Deliberately never consults State.Prior. Doing so answers a different question — @@ -104,3 +110,18 @@ func (s *State) CurrentCA() string { } return "" } + +// CurrentCAs is CurrentCA for each settings file the record names, first file +// first, leaving out each one CurrentCA answers "" for. +func (s *State) CurrentCAs() []string { + if s == nil { + return nil + } + var cas []string + for _, e := range append([]State{*s}, s.OtherFiles...) { + if ca := e.CurrentCA(); ca != "" { + cas = append(cas, ca) + } + } + return cas +} diff --git a/core/clientstate/clientstate_test.go b/core/clientstate/clientstate_test.go index 2287cd76b..13c33fbe1 100644 --- a/core/clientstate/clientstate_test.go +++ b/core/clientstate/clientstate_test.go @@ -192,3 +192,22 @@ func TestCurrentCA_EmptyOnEveryFailure(t *testing.T) { }) } } + +// CurrentCAs reads each entry's settings file, so a stale CA in a second file is +// seen too. +func TestCurrentCAs_ReadsEverySettingsFile(t *testing.T) { + first := write(t, t.TempDir(), "", "/ca/first.crt") + second := write(t, t.TempDir(), "", "/ca/second.crt") + st, err := Load(first) + if err != nil { + t.Fatal(err) + } + other, err := Load(second) + if err != nil { + t.Fatal(err) + } + st.OtherFiles = []State{*other, {Settings: filepath.Join(t.TempDir(), "absent.json")}} + if got := st.CurrentCAs(); strings.Join(got, ",") != "/ca/first.crt,/ca/second.crt" { + t.Errorf("CurrentCAs() = %q, want both files' CAs", got) + } +} diff --git a/docs/agents/claude-code.md b/docs/agents/claude-code.md index af691f29c..d55258328 100644 --- a/docs/agents/claude-code.md +++ b/docs/agents/claude-code.md @@ -45,10 +45,12 @@ The same goes after `disable`. While enabled, Claude Code needs Cortex running, because its requests go to the proxy: `disable` is the off switch, and `agentop service status` says whether the proxy is up. -**The record.** The first `enable` records what each of the six keys held before, in -`~/.cortex/claude-code-state.json`. `disable` removes only the keys `enable` added, and -puts back any value it recorded. It does not change a key whose value changed after -`enable`, and it names each key it did not change. `agentop uninstall` runs the same `disable`. +**The record.** The first `enable` on each settings file records what each of the six +keys held before, in `~/.cortex/claude-code-state.json`. `disable` removes only the +keys `enable` added, and puts back any value it recorded. It does not change a key +whose value changed after `enable`, and it names each key it did not change. Each +settings file `enable` routed, such as a project's and the default one, has its own +entry. `agentop uninstall` runs the same `disable` on each. `disable` restores every value, but not the file's text. For example, it sorts the keys, uses a 2-space indent, puts each array item on its own line, and writes `&`, `<` and `>` as From ca5aef1aca672d8c1221926df008f0688dad6df3 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:40:15 -0700 Subject: [PATCH 2/8] :fire: Remove duplicate test Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- .../cmd_claudecode_settingspath_test.go | 23 ------------------- 1 file changed, 23 deletions(-) diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index 357907c65..5092ee123 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -62,29 +62,6 @@ func TestUninstallUnroutesEverySettingsFileCortexRouted(t *testing.T) { } } -// A disable on the first of two enabled files keeps a value set there since its -// enable. -func TestClaudeCodeDisable_KeepsAnEditToTheFirstFileAfterAnotherEnable(t *testing.T) { - const corp = "http://corp.example:3128" - first, cfg := fixture(t, "{}") - second := filepath.Join(t.TempDir(), "settings.json") - state := filepath.Join(t.TempDir(), "state.json") - if code := claudeCodeEnable2(first, cfg, state, true, io.Discard, io.Discard); code != 0 { - t.Fatalf("fixture: enable on the first file exit %d", code) - } - handEdit(t, first, map[string]string{envProxy: corp}) - if code := claudeCodeEnable2(second, cfg, state, true, io.Discard, io.Discard); code != 0 { - t.Fatalf("fixture: enable on the second file exit %d", code) - } - var errb bytes.Buffer - if code := claudeCodeDisable2(first, state, true, io.Discard, &errb); code != 0 { - t.Fatalf("disable exit %d: %s", code, errb.String()) - } - if env := readEnv(t, first); env[envProxy] != corp || len(env) != 1 { - t.Errorf("the first file's env is %v, want only %s=%s", env, envProxy, corp) - } -} - // Each settings file keeps its own entry: a later enable adds one beside the // others, a re-enable refreshes only its Written, and a drop takes out only its // own, keeping the next entry whole when it moves up and deleting the record From a304a677a4c44063c838a25ee75a7ca64a51002a Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:30:04 -0700 Subject: [PATCH 3/8] :art: Address review comments Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 38 ++++++-- .../cmd_claudecode_settingspath_test.go | 86 +++++++++++++++++++ cmd/agentop/cmd_doctor.go | 11 +-- cmd/agentop/cmd_uninstall.go | 8 +- 4 files changed, 129 insertions(+), 14 deletions(-) diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index 8eeac5382..19e63e3e2 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -179,8 +179,10 @@ func recordIndex(st *managedState, settingsPath string) int { } // adoptRelativeEntry records as abs the entry an older enable recorded as rel, -// the relative path given again here. An entry abs already has stays as it is. -func adoptRelativeEntry(statePath, rel, abs string) error { +// the relative path given again here. The entry has no directory, so abs must +// show it is the file: it holds every value the entry's Written records. An +// entry abs already has stays as it is. +func adoptRelativeEntry(statePath, rel, abs string, stderr io.Writer) error { st, err := readState(statePath) if err != nil || recordFor(st, abs) != nil { return nil @@ -189,6 +191,18 @@ func adoptRelativeEntry(statePath, rel, abs string) error { if e == nil { return nil } + doc, err := readSettings(abs) + holds := err == nil && len(e.Written) > 0 + for k, w := range e.Written { + if v, set := envStrings(doc)[k]; !set || v != w { + holds = false + } + } + if !holds { + fmt.Fprintf(stderr, "agentop: the record's entry for %s is from an older enable in another\n"+ + " directory, so it is left as it is.\n", rel) + return nil + } e.Settings = abs return writeStateFile(statePath, *st) } @@ -388,10 +402,11 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { *cortexCfg = filepath.Join(home, cortexCfgRel) } statePath := filepath.Join(home, stateRel) - // Absolute, so the record names the file from any directory. + // Absolute, so the record names the file from any directory. status reads + // only the settings file, so it leaves the record as it is. if abs, err := filepath.Abs(*settingsPath); err == nil { if action != "status" && !filepath.IsAbs(*settingsPath) { - if err := adoptRelativeEntry(statePath, *settingsPath, abs); err != nil { + if err := adoptRelativeEntry(statePath, *settingsPath, abs, stderr); err != nil { fmt.Fprintf(stderr, "agentop: %v\n", err) return 1 } @@ -915,7 +930,9 @@ func applyClaudeCodeDisable(pl claudeCodeDisablePlan, statePath string, stderr i // place it would outlive every disable, and doctor would report Claude Code as // routed for good. if statePath != "" && (pl.st != nil || pl.stErr != nil) { - _ = dropRecord(statePath, pl.settingsPath) + if err := dropRecord(statePath, pl.settingsPath); err != nil { + warnEntryKept(stderr, statePath, pl.settingsPath, err) + } } return restored, nil } @@ -960,11 +977,18 @@ func removeDisabledRecord(pl claudeCodeDisablePlan, statePath string, stderr io. return } if err := dropRecord(statePath, pl.settingsPath); err != nil { - fmt.Fprintf(stderr, "agentop: could not remove %s (%v); `agentop doctor` will go on\n"+ - " reporting Claude Code as routed through Cortex. Delete it by hand.\n", statePath, err) + warnEntryKept(stderr, statePath, pl.settingsPath, err) } } +// warnEntryKept says a disable restored settingsPath but kept its entry in the +// record. A disable run again takes the entry out, and keeps every other file's. +func warnEntryKept(stderr io.Writer, statePath, settingsPath string, err error) { + fmt.Fprintf(stderr, "agentop: could not take %s out of %s (%v);\n"+ + " `agentop doctor` will go on reporting it as routed through Cortex. Run disable\n"+ + " again to retry.\n", settingsPath, statePath, err) +} + func claudeCodeDisable2(settingsPath, statePath string, yes bool, stdout, stderr io.Writer) int { pl, err := planClaudeCodeDisable(settingsPath, statePath) if err != nil { diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index 5092ee123..9af8983ce 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -5,7 +5,9 @@ import ( "io" "os" "path/filepath" + "runtime" "slices" + "strings" "testing" ) @@ -62,6 +64,35 @@ func TestUninstallUnroutesEverySettingsFileCortexRouted(t *testing.T) { } } +// The same relative --settings in another project names another file, so +// disable and enable there leave the older entry to its own project. +func TestClaudeCodeLeavesAnOlderRelativeEntryToTheProjectThatHoldsIt(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + a, b := filepath.Join(sc.home, "a"), filepath.Join(sc.home, "b") + writeHomeFile(t, filepath.Join(a, settingsRel), "{}\n") + writeHomeFile(t, filepath.Join(b, settingsRel), "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(a) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + + t.Chdir(b) + for _, action := range []string{"disable", "enable"} { + var errb bytes.Buffer + if code := runClaudeCode([]string{action, "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { + t.Fatalf("%s in b exit %d: %s", action, code, errb.String()) + } + if st, err := readState(state); err != nil || st == nil || st.Settings != settingsRel { + t.Errorf("after %s in b the record is %+v (%v), want a's relative entry first", action, st, err) + } + } + if st, _ := readState(state); st == nil || len(st.OtherFiles) != 1 || st.OtherFiles[0].Settings != filepath.Join(b, settingsRel) { + t.Errorf("the record is %+v, want an entry of b's own beside a's", st) + } +} + // Each settings file keeps its own entry: a later enable adds one beside the // others, a re-enable refreshes only its Written, and a drop takes out only its // own, keeping the next entry whole when it moves up and deleting the record @@ -183,3 +214,58 @@ func TestClaudeCodeRecordRefusesAnEntryWithNoPrior(t *testing.T) { t.Errorf("readState = %+v, want an error for the entry with no prior", st) } } + +// readOnlyDir makes dir read-only for the rest of the test, so a record written +// there cannot be replaced. +func readOnlyDir(t *testing.T, dir string) { + t.Helper() + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) +} + +// A disable that restores the file but cannot take its entry out says so, and +// still succeeds. +func TestClaudeCodeDisable_WarnsWhenItKeepsTheEntry(t *testing.T) { + first, cfg := fixture(t, "{}") + second := filepath.Join(t.TempDir(), "settings.json") + state := filepath.Join(t.TempDir(), "state.json") + for _, s := range []string{first, second} { + if code := claudeCodeEnable2(s, cfg, state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: enable on %s exit %d", s, code) + } + } + readOnlyDir(t, filepath.Dir(state)) + var errb bytes.Buffer + if code := claudeCodeDisable2(first, state, true, io.Discard, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if !strings.Contains(errb.String(), "could not take "+first+" out of "+state) { + t.Errorf("disable kept the entry and said nothing:\n%s", errb.String()) + } +} + +// When uninstall cannot take one file's entry out, its fix keeps the other +// files' entries, which their own fixes read. +func TestUninstallFixForAKeptEntryKeepsTheOthers(t *testing.T) { + home := t.TempDir() + env := &setupEnv{home: home, goos: runtime.GOOS} + state, proj := filepath.Join(home, stateRel), filepath.Join(home, "proj", settingsRel) + writeHomeFile(t, state, "") + if err := writeStateFile(state, managedState{Settings: proj, Prior: map[string]*string{}, + OtherFiles: []managedState{{Settings: filepath.Join(home, settingsRel), Prior: map[string]*string{}}}}); err != nil { + t.Fatal(err) + } + readOnlyDir(t, filepath.Dir(state)) + + r := unrouteClaudeCode(env, proj, state) + _, _, err := r.run(nil) + if err == nil { + t.Fatal("the row took the entry out of a read-only record") + } + if fixes := r.fixesFor(err); len(fixes) != 1 || strings.HasPrefix(fixes[0].byHand, "rm ") || + !strings.Contains(fixes[0].byHand, "delete the entry for ~/proj/"+settingsRel) { + t.Errorf("the fix is %+v, want one deleting only this file's entry", fixes) + } +} diff --git a/cmd/agentop/cmd_doctor.go b/cmd/agentop/cmd_doctor.go index e93dc60d7..2859aac87 100644 --- a/cmd/agentop/cmd_doctor.go +++ b/cmd/agentop/cmd_doctor.go @@ -172,17 +172,18 @@ func installShape(env *setupEnv) (claudeCode, noService bool, elsewhere []string } elsewhere = append(elsewhere, s) } - return recorded || len(elsewhere) == 0 && claudeCodeRouted(env), backgroundOnly(env), elsewhere + return recorded || (len(elsewhere) == 0 && claudeCodeRouted(env)), backgroundOnly(env), elsewhere } // claudeCodeRouted reports whether Cortex routed Claude Code: enable's state // record is there, or settings.json's HTTPS_PROXY is the proxy enable would write // from the current config. Enable writes the record and every disable deletes its // file's entry, the record going with the last, including one that left a key -// behind because its value changed since enable set it — the record's existence is read here as "Cortex routes this", so it must not -// outlive the values it describes, or doctor reports a routing that is gone and -// offers a fix that puts it back. Keeping it for a left key's sake would cost that -// key its edit too — applyClaudeCodeDisable says why. +// behind because its value changed since enable set it — the record's existence +// is read here as "Cortex routes this", so it must not outlive the values it +// describes, or doctor reports a routing that is gone and offers a fix that puts +// it back. Keeping it for a left key's sake would cost that key its edit too — +// applyClaudeCodeDisable says why. // // Any managed key being set is not enough: a corporate HTTPS_PROXY is the user's // own, and disable, with no record, would remove it. A settings file that cannot be diff --git a/cmd/agentop/cmd_uninstall.go b/cmd/agentop/cmd_uninstall.go index 211b9a320..eaebfc273 100644 --- a/cmd/agentop/cmd_uninstall.go +++ b/cmd/agentop/cmd_uninstall.go @@ -453,12 +453,16 @@ func unrouteClaudeCode(env *setupEnv, settings, state string) removal { // good, a left key or not: it answers from the record's existence. if state != "" { // This file's entry, or a record that names no file whole. - drop := removeIfExists + drop, fix := removeIfExists, manual("rm "+env.shellPath(state)) if pl.st != nil { drop = func(state string) error { return dropRecord(state, settings) } } + if st, _ := readState(state); st != nil && len(st.OtherFiles) > 0 { + // rm would take the other files' entries, which their own rows' fixes need. + fix = remedy{agentop: disable.agentop, byHand: "in " + env.tilde(state) + ", delete the entry for " + env.tilde(settings)} + } if err := drop(state); err != nil { - return "", []string{env.tilde(state)}, withFixes(err, manual("rm "+env.shellPath(state))) + return "", []string{env.tilde(state)}, withFixes(err, fix) } } if len(pl.left) > 0 { From 1f2ef60ba3991c6b386352c0f3e57028e8b2e1a6 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:15:34 -0700 Subject: [PATCH 4/8] :bug: Keep old entry's match after edit Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 26 +++++---- .../cmd_claudecode_settingspath_test.go | 56 +++++++++++++------ 2 files changed, 56 insertions(+), 26 deletions(-) diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index 19e63e3e2..314cd232b 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -180,9 +180,10 @@ func recordIndex(st *managedState, settingsPath string) int { // adoptRelativeEntry records as abs the entry an older enable recorded as rel, // the relative path given again here. The entry has no directory, so abs must -// show it is the file: it holds every value the entry's Written records. An -// entry abs already has stays as it is. -func adoptRelativeEntry(statePath, rel, abs string, stderr io.Writer) error { +// show Cortex routed it: it holds a value the entry's Written records, or, for a +// record from before Written, one in want. A key edited since keeps its match. +// An entry abs already has stays as it is. +func adoptRelativeEntry(statePath, rel, abs string, want map[string]string, stderr io.Writer) error { st, err := readState(statePath) if err != nil || recordFor(st, abs) != nil { return nil @@ -191,16 +192,20 @@ func adoptRelativeEntry(statePath, rel, abs string, stderr io.Writer) error { if e == nil { return nil } + ours := e.Written + if len(ours) == 0 { + ours = want + } doc, err := readSettings(abs) - holds := err == nil && len(e.Written) > 0 - for k, w := range e.Written { - if v, set := envStrings(doc)[k]; !set || v != w { - holds = false + holds := false + for k, w := range ours { + if v, set := envStrings(doc)[k]; err == nil && set && v == w { + holds = true } } if !holds { - fmt.Fprintf(stderr, "agentop: the record's entry for %s is from an older enable in another\n"+ - " directory, so it is left as it is.\n", rel) + fmt.Fprintf(stderr, "agentop: %s holds none of the values the record's entry for %s\n"+ + " says Cortex wrote, so that entry is left as it is.\n", abs, rel) return nil } e.Settings = abs @@ -406,7 +411,8 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { // only the settings file, so it leaves the record as it is. if abs, err := filepath.Abs(*settingsPath); err == nil { if action != "status" && !filepath.IsAbs(*settingsPath) { - if err := adoptRelativeEntry(statePath, *settingsPath, abs, stderr); err != nil { + want, _ := wanted(*cortexCfg) + if err := adoptRelativeEntry(statePath, *settingsPath, abs, want, stderr); err != nil { fmt.Fprintf(stderr, "agentop: %v\n", err) return 1 } diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index 9af8983ce..bde94890c 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -171,24 +171,45 @@ func TestClaudeCodeEnable_LeavesAnOlderRelativeEntryToItsProject(t *testing.T) { } // A relative --settings given again where an older enable recorded it finds -// that entry, so disable takes it out. +// that entry, so disable takes it out: after a key was edited since, which keeps +// the edit, and in a record from before Written. func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { - sc := newUninstallScene(t) - sc.setUp(t) - projDir := filepath.Join(sc.home, "proj") - writeHomeFile(t, filepath.Join(projDir, settingsRel), "{}\n") - state := filepath.Join(sc.home, stateRel) - t.Chdir(projDir) - if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { - t.Fatalf("fixture: relative enable exit %d", code) - } + const corpCA = "/etc/corp-ca.pem" + for _, c := range []struct { + name string + edited bool + }{{"a key edited since", true}, {"a record from before Written", false}} { + t.Run(c.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + proj := filepath.Join(sc.home, "proj", settingsRel) + writeHomeFile(t, proj, "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "proj")) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + if c.edited { + handEdit(t, proj, map[string]string{envCACerts: corpCA}) + } else { + st, _ := readState(state) + st.Written = nil + if err := writeStateFile(state, *st); err != nil { + t.Fatal(err) + } + } - var errb bytes.Buffer - if code := runClaudeCode([]string{"disable", "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { - t.Fatalf("disable exit %d: %s", code, errb.String()) - } - if _, err := os.Stat(state); !os.IsNotExist(err) { - t.Errorf("the record outlived the disable of the file it names (%v)", err) + var errb bytes.Buffer + if code := runClaudeCode([]string{"disable", "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if _, err := os.Stat(state); !os.IsNotExist(err) { + t.Errorf("the record outlived the disable of the file it names (%v)", err) + } + if env := readEnv(t, proj); c.edited && (env[envCACerts] != corpCA || len(env) != 1) { + t.Errorf("env is %v, want only the edited %s=%s", env, envCACerts, corpCA) + } + }) } } @@ -219,6 +240,9 @@ func TestClaudeCodeRecordRefusesAnEntryWithNoPrior(t *testing.T) { // there cannot be replaced. func readOnlyDir(t *testing.T, dir string) { t.Helper() + if os.Geteuid() == 0 { + t.Skip("root writes through a read-only directory") + } if err := os.Chmod(dir, 0o500); err != nil { t.Fatal(err) } From d561ed6e1e824ea5745a4b47c634b391cc6bb091 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:30:53 -0700 Subject: [PATCH 5/8] :bug: Confirm takeover for older entry Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 90 +++++++--- .../cmd_claudecode_settingspath_test.go | 167 ++++++++++++++++-- 2 files changed, 213 insertions(+), 44 deletions(-) diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index 314cd232b..d607e56dc 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "encoding/json" "flag" "fmt" @@ -179,37 +180,57 @@ func recordIndex(st *managedState, settingsPath string) int { } // adoptRelativeEntry records as abs the entry an older enable recorded as rel, -// the relative path given again here. The entry has no directory, so abs must -// show Cortex routed it: it holds a value the entry's Written records, or, for a -// record from before Written, one in want. A key edited since keeps its match. -// An entry abs already has stays as it is. -func adoptRelativeEntry(statePath, rel, abs string, want map[string]string, stderr io.Writer) error { +// the relative path given again here, and returns a func that puts the record +// back as it was. The entry has no directory, and Cortex's values are the same +// in every project, so runClaudeCode keeps the change only when the run succeeds +// and either changes abs or has --yes. A file holding none of the keys Cortex +// manages leaves the entry as it is, as does an entry abs already has. +func adoptRelativeEntry(statePath, rel, abs string, stdout io.Writer) (func() error, error) { + orig, err := os.ReadFile(statePath) + if err != nil { + return nil, nil + } st, err := readState(statePath) if err != nil || recordFor(st, abs) != nil { - return nil + return nil, nil } e := recordFor(st, rel) if e == nil { - return nil - } - ours := e.Written - if len(ours) == 0 { - ours = want + return nil, nil } doc, err := readSettings(abs) - holds := false - for k, w := range ours { - if v, set := envStrings(doc)[k]; err == nil && set && v == w { - holds = true - } + if err != nil { + return nil, nil } - if !holds { - fmt.Fprintf(stderr, "agentop: %s holds none of the values the record's entry for %s\n"+ - " says Cortex wrote, so that entry is left as it is.\n", abs, rel) - return nil + if !holdsManagedKey(envStrings(doc)) { + fmt.Fprintf(stdout, "The record's entry for %s is from an older agentop, which did not record\n"+ + "its directory, and %s holds none of the keys Cortex\n"+ + "manages, so the entry stays. If it names this file, delete it from %s.\n\n", rel, abs, statePath) + return nil, nil } + fmt.Fprintf(stdout, "The record's entry for %s is from an older agentop, which did not record\n"+ + "its directory. A change confirmed here, or --yes, takes it as %s;\n"+ + "give --settings as an absolute path to leave the entry as it is.\n\n", rel, abs) e.Settings = abs - return writeStateFile(statePath, *st) + if err := writeStateFile(statePath, *st); err != nil { + return nil, err + } + return func() error { return writeFileAtomic(statePath, orig, 0o600) }, nil +} + +// holdsManagedKey reports whether env sets a key Cortex manages or once wrote. +func holdsManagedKey(env map[string]string) bool { + for _, k := range managedKeys { + if _, set := env[k]; set { + return true + } + } + for k := range retiredKeys { + if _, set := env[k]; set { + return true + } + } + return false } // recordFor is the record's entry for settingsPath, nil when it has none. @@ -409,25 +430,44 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { statePath := filepath.Join(home, stateRel) // Absolute, so the record names the file from any directory. status reads // only the settings file, so it leaves the record as it is. + var undo func() error if abs, err := filepath.Abs(*settingsPath); err == nil { if action != "status" && !filepath.IsAbs(*settingsPath) { - want, _ := wanted(*cortexCfg) - if err := adoptRelativeEntry(statePath, *settingsPath, abs, want, stderr); err != nil { + if undo, err = adoptRelativeEntry(statePath, *settingsPath, abs, stdout); err != nil { fmt.Fprintf(stderr, "agentop: %v\n", err) return 1 } } *settingsPath = abs } + var before []byte + if undo != nil { + before, _ = os.ReadFile(*settingsPath) + } switch action { case "enable": - return claudeCodeEnable2(*settingsPath, *cortexCfg, statePath, yes, stdout, stderr) + code = claudeCodeEnable2(*settingsPath, *cortexCfg, statePath, yes, stdout, stderr) case "disable": - return claudeCodeDisable2(*settingsPath, statePath, yes, stdout, stderr) + code = claudeCodeDisable2(*settingsPath, statePath, yes, stdout, stderr) default: return claudeCodeStatus(*settingsPath, stdout) } + // An adopted entry stays when the run succeeded and the user confirmed it: by + // a change they agreed to, or by --yes. + if undo != nil { + after, _ := os.ReadFile(*settingsPath) + if code != 0 || !yes && bytes.Equal(before, after) { + if err := undo(); err != nil { + fmt.Fprintf(stderr, "agentop: could not put back %s (%v)\n", statePath, err) + return 1 + } + if code == 0 { + fmt.Fprintf(stdout, "The older entry stays as it was; run again with --yes if it names %s.\n", *settingsPath) + } + } + } + return code } // wanted derives the three values from the Cortex config, so they cannot drift diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index bde94890c..d7c867557 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "io" + "maps" "os" "path/filepath" "runtime" @@ -65,7 +66,8 @@ func TestUninstallUnroutesEverySettingsFileCortexRouted(t *testing.T) { } // The same relative --settings in another project names another file, so -// disable and enable there leave the older entry to its own project. +// disable and enable there leave the older entry to its own project, and say +// how to delete it. func TestClaudeCodeLeavesAnOlderRelativeEntryToTheProjectThatHoldsIt(t *testing.T) { sc := newUninstallScene(t) sc.setUp(t) @@ -80,10 +82,13 @@ func TestClaudeCodeLeavesAnOlderRelativeEntryToTheProjectThatHoldsIt(t *testing. t.Chdir(b) for _, action := range []string{"disable", "enable"} { - var errb bytes.Buffer - if code := runClaudeCode([]string{action, "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { + var out, errb bytes.Buffer + if code := runClaudeCode([]string{action, "--yes", "--settings", settingsRel}, &out, &errb); code != 0 { t.Fatalf("%s in b exit %d: %s", action, code, errb.String()) } + if action == "disable" && !strings.Contains(out.String(), "delete it from "+state) { + t.Errorf("disable in b does not say how to delete the older entry:\n%s", out.String()) + } if st, err := readState(state); err != nil || st == nil || st.Settings != settingsRel { t.Errorf("after %s in b the record is %+v (%v), want a's relative entry first", action, st, err) } @@ -171,14 +176,38 @@ func TestClaudeCodeEnable_LeavesAnOlderRelativeEntryToItsProject(t *testing.T) { } // A relative --settings given again where an older enable recorded it finds -// that entry, so disable takes it out: after a key was edited since, which keeps -// the edit, and in a record from before Written. +// that entry, so disable takes it out and keeps every edit: one key edited +// since, that key alone left, every key edited, and a record from before +// Written. func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { const corpCA = "/etc/corp-ca.pem" + everyKey := map[string]string{} + for _, k := range managedKeys { + everyKey[k] = corpCA + } + everyKey[envProxy] = "http://corp.example:3128" for _, c := range []struct { - name string - edited bool - }{{"a key edited since", true}, {"a record from before Written", false}} { + name string + want map[string]string // the env disable leaves + edit func(t *testing.T, proj, state string) + }{ + {"a key edited since", map[string]string{envCACerts: corpCA}, func(t *testing.T, proj, _ string) { + handEdit(t, proj, map[string]string{envCACerts: corpCA}) + }}, + {"only an edited key left", map[string]string{envCACerts: corpCA}, func(t *testing.T, proj, _ string) { + writeHomeFile(t, proj, `{"env":{"`+envCACerts+`":"`+corpCA+`"}}`) + }}, + {"every key edited", everyKey, func(t *testing.T, proj, _ string) { + handEdit(t, proj, everyKey) + }}, + {"a record from before Written", nil, func(t *testing.T, _, state string) { + st, _ := readState(state) + st.Written = nil + if err := writeStateFile(state, *st); err != nil { + t.Fatal(err) + } + }}, + } { t.Run(c.name, func(t *testing.T) { sc := newUninstallScene(t) sc.setUp(t) @@ -189,15 +218,7 @@ func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { t.Fatalf("fixture: relative enable exit %d", code) } - if c.edited { - handEdit(t, proj, map[string]string{envCACerts: corpCA}) - } else { - st, _ := readState(state) - st.Written = nil - if err := writeStateFile(state, *st); err != nil { - t.Fatal(err) - } - } + c.edit(t, proj, state) var errb bytes.Buffer if code := runClaudeCode([]string{"disable", "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { @@ -206,8 +227,116 @@ func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { if _, err := os.Stat(state); !os.IsNotExist(err) { t.Errorf("the record outlived the disable of the file it names (%v)", err) } - if env := readEnv(t, proj); c.edited && (env[envCACerts] != corpCA || len(env) != 1) { - t.Errorf("env is %v, want only the edited %s=%s", env, envCACerts, corpCA) + if env := readEnv(t, proj); !maps.Equal(env, c.want) { + t.Errorf("env is %v, want %v", env, c.want) + } + }) + } +} + +// Another project's file can hold the same Cortex values, so a relative +// --settings there keeps the older entry as it is unless the run confirms it: +// a declined change, a run with nothing to change, and a failed enable all +// leave it. +func TestClaudeCodeKeepsAnOlderRelativeEntryUnlessTheRunConfirmsIt(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + a, b := filepath.Join(sc.home, "a"), filepath.Join(sc.home, "b") + writeHomeFile(t, filepath.Join(a, settingsRel), "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(a) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + routed, err := os.ReadFile(filepath.Join(a, settingsRel)) + if err != nil { + t.Fatal(err) + } + bFile := filepath.Join(b, settingsRel) + writeHomeFile(t, bFile, string(routed)) + + t.Chdir(b) + answerPrompt(t, &claudeCodeConfirm, "n\n") + for _, c := range []struct { + name string + args []string + edit map[string]string + code int + }{ + {"a declined disable", []string{"disable"}, nil, exitDeclined}, + {"an enable with nothing to change", []string{"enable"}, nil, 0}, + {"a failed enable", []string{"enable", "--yes"}, map[string]string{envCACerts: "/etc/b-corp.pem"}, 1}, + } { + if c.edit != nil { + handEdit(t, bFile, c.edit) + } + var out bytes.Buffer + if code := runClaudeCode(append(c.args, "--settings", settingsRel), &out, io.Discard); code != c.code { + t.Errorf("%s: exit %d, want %d", c.name, code, c.code) + } + if !strings.Contains(out.String(), "older agentop") { + t.Errorf("%s: no note on the older entry:\n%s", c.name, out.String()) + } + if st, _ := readState(state); st == nil || st.Settings != settingsRel { + t.Errorf("after %s the record is %+v, want a's relative entry", c.name, st) + } + } +} + +// Without --yes, a change the user confirms takes the older relative entry for +// the file, and a disable with nothing to remove keeps the entry and says how to +// take it. +func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { + for _, c := range []struct { + name string + action string + edit func(t *testing.T, proj string) + want string // the record's first entry afterwards; "" is proj itself + note string + }{ + {"a confirmed enable", "enable", func(t *testing.T, proj string) { + doc, err := readSettings(proj) + if err != nil { + t.Fatal(err) + } + delete(envRaw(doc), envProxy) + if err := writeSettings(proj, doc); err != nil { + t.Fatal(err) + } + }, "", ""}, + {"a disable with nothing to remove", "disable", func(t *testing.T, proj string) { + edits := map[string]string{} + for _, k := range managedKeys { + edits[k] = "/etc/corp-ca.pem" + } + handEdit(t, proj, edits) + }, settingsRel, "run again with --yes"}, + } { + t.Run(c.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + proj := filepath.Join(sc.home, "proj", settingsRel) + writeHomeFile(t, proj, "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "proj")) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + c.edit(t, proj) + if c.want == "" { + c.want = proj + } + + answerPrompt(t, &claudeCodeConfirm, "y\n") + var out, errb bytes.Buffer + if code := runClaudeCode([]string{c.action, "--settings", settingsRel}, &out, &errb); code != 0 { + t.Fatalf("%s exit %d: %s", c.action, code, errb.String()) + } + if st, _ := readState(state); st == nil || st.Settings != c.want { + t.Errorf("the record is %+v, want its first entry %s", st, c.want) + } + if !strings.Contains(out.String(), c.note) { + t.Errorf("the output does not say %q:\n%s", c.note, out.String()) } }) } From 6ace641b1973dfdf44c4af21e186e9ab6dc53c49 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:09:50 -0700 Subject: [PATCH 6/8] :bug: Put back older entry Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 51 ++++-- .../cmd_claudecode_settingspath_test.go | 170 ++++++++++++++++-- 2 files changed, 196 insertions(+), 25 deletions(-) diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index d607e56dc..072dae169 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -108,7 +108,7 @@ func readState(path string) (*managedState, error) { // One bad entry makes the whole record untrusted, as a bad first entry does. for _, o := range st.OtherFiles { if o.Settings == "" || o.Prior == nil { - return nil, fmt.Errorf("%s has an entry with no settings file or prior-value record", path) + return nil, fmt.Errorf("%s has an entry with no settings file or prior-value record (%q); fix or delete that entry by hand", path, o.Settings) } } return &st, nil @@ -180,16 +180,12 @@ func recordIndex(st *managedState, settingsPath string) int { } // adoptRelativeEntry records as abs the entry an older enable recorded as rel, -// the relative path given again here, and returns a func that puts the record +// the relative path given again here, and returns a func that puts that entry // back as it was. The entry has no directory, and Cortex's values are the same // in every project, so runClaudeCode keeps the change only when the run succeeds // and either changes abs or has --yes. A file holding none of the keys Cortex // manages leaves the entry as it is, as does an entry abs already has. func adoptRelativeEntry(statePath, rel, abs string, stdout io.Writer) (func() error, error) { - orig, err := os.ReadFile(statePath) - if err != nil { - return nil, nil - } st, err := readState(statePath) if err != nil || recordFor(st, abs) != nil { return nil, nil @@ -208,14 +204,35 @@ func adoptRelativeEntry(statePath, rel, abs string, stdout io.Writer) (func() er "manages, so the entry stays. If it names this file, delete it from %s.\n\n", rel, abs, statePath) return nil, nil } - fmt.Fprintf(stdout, "The record's entry for %s is from an older agentop, which did not record\n"+ - "its directory. A change confirmed here, or --yes, takes it as %s;\n"+ - "give --settings as an absolute path to leave the entry as it is.\n\n", rel, abs) + was := *e e.Settings = abs if err := writeStateFile(statePath, *st); err != nil { return nil, err } - return func() error { return writeFileAtomic(statePath, orig, 0o600) }, nil + fmt.Fprintf(stdout, "The record's entry for %s is from an older agentop, which did not record\n"+ + "its directory. A change confirmed here, or --yes, takes it as %s;\n"+ + "give --settings as an absolute path to leave the entry as it is.\n\n", rel, abs) + was.Settings, was.OtherFiles = rel, nil + // The undo keeps every other entry as the record then holds it. An entry the + // run took out comes back while abs still holds a key Cortex manages. + return func() error { + st, err := readState(statePath) + if err != nil { + return err + } + if cur := recordFor(st, abs); cur != nil && cur.Settings == abs { + cur.Settings, cur.Written = was.Settings, was.Written + return writeStateFile(statePath, *st) + } + if doc, err := readSettings(abs); err != nil || !holdsManagedKey(envStrings(doc)) { + return nil + } + if st == nil { + return writeStateFile(statePath, was) + } + st.OtherFiles = append(st.OtherFiles, was) + return writeStateFile(statePath, *st) + }, nil } // holdsManagedKey reports whether env sets a key Cortex manages or once wrote. @@ -247,8 +264,12 @@ func recordFor(st *managedState, settingsPath string) *managedState { // writeClaudeCodeState is writeState for a record of several settings files: e // becomes its file's entry, and every other file's entry stays. An existing entry -// keeps its Prior, by writeState's rule. +// keeps its Prior, by writeState's rule. e needs a settings file and a Prior, as +// readState needs of every entry. func writeClaudeCodeState(path string, e managedState) error { + if e.Settings == "" || e.Prior == nil { + return fmt.Errorf("refusing to record an entry with no settings file or prior-value record") + } existing, err := readState(path) if err != nil { return fmt.Errorf("refusing to overwrite the existing record: %w", err) @@ -429,13 +450,15 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { } statePath := filepath.Join(home, stateRel) // Absolute, so the record names the file from any directory. status reads - // only the settings file, so it leaves the record as it is. + // only the settings file, so it leaves the record as it is. A record that + // cannot take the older entry as abs keeps the relative path for this run, so + // the run still finds that entry. var undo func() error if abs, err := filepath.Abs(*settingsPath); err == nil { if action != "status" && !filepath.IsAbs(*settingsPath) { if undo, err = adoptRelativeEntry(statePath, *settingsPath, abs, stdout); err != nil { - fmt.Fprintf(stderr, "agentop: %v\n", err) - return 1 + fmt.Fprintf(stderr, "agentop: could not record the older entry as %s (%v); this run uses it as %s\n", abs, err, *settingsPath) + abs = *settingsPath } } *settingsPath = abs diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index d7c867557..0f960b059 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -284,15 +284,16 @@ func TestClaudeCodeKeepsAnOlderRelativeEntryUnlessTheRunConfirmsIt(t *testing.T) } // Without --yes, a change the user confirms takes the older relative entry for -// the file, and a disable with nothing to remove keeps the entry and says how to -// take it. +// the file, and a disable with nothing to remove keeps the entry, alone or beside +// the default file's, and says how to take it. func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { for _, c := range []struct { name string action string edit func(t *testing.T, proj string) - want string // the record's first entry afterwards; "" is proj itself + want string // the entry the record holds afterwards; "" is proj itself note string + others bool // the default file is routed too }{ {"a confirmed enable", "enable", func(t *testing.T, proj string) { doc, err := readSettings(proj) @@ -303,14 +304,21 @@ func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { if err := writeSettings(proj, doc); err != nil { t.Fatal(err) } - }, "", ""}, + }, "", "", false}, {"a disable with nothing to remove", "disable", func(t *testing.T, proj string) { edits := map[string]string{} for _, k := range managedKeys { edits[k] = "/etc/corp-ca.pem" } handEdit(t, proj, edits) - }, settingsRel, "run again with --yes"}, + }, settingsRel, "run again with --yes", false}, + {"a disable with nothing to remove beside another file", "disable", func(t *testing.T, proj string) { + edits := map[string]string{} + for _, k := range managedKeys { + edits[k] = "/etc/corp-ca.pem" + } + handEdit(t, proj, edits) + }, settingsRel, "run again with --yes", true}, } { t.Run(c.name, func(t *testing.T) { sc := newUninstallScene(t) @@ -322,9 +330,17 @@ func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { t.Fatalf("fixture: relative enable exit %d", code) } + if c.others { + if code := claudeCodeEnable2(filepath.Join(sc.home, settingsRel), filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: default enable exit %d", code) + } + } c.edit(t, proj) + gone := settingsRel if c.want == "" { c.want = proj + } else { + gone = proj } answerPrompt(t, &claudeCodeConfirm, "y\n") @@ -332,8 +348,15 @@ func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { if code := runClaudeCode([]string{c.action, "--settings", settingsRel}, &out, &errb); code != 0 { t.Fatalf("%s exit %d: %s", c.action, code, errb.String()) } - if st, _ := readState(state); st == nil || st.Settings != c.want { - t.Errorf("the record is %+v, want its first entry %s", st, c.want) + var names []string + if st, _ := readState(state); st != nil { + names = append(names, st.Settings) + for _, o := range st.OtherFiles { + names = append(names, o.Settings) + } + } + if !slices.Contains(names, c.want) || slices.Contains(names, gone) || c.others && len(names) != 2 { + t.Errorf("the record names %q, want %s and not %s", names, c.want, gone) } if !strings.Contains(out.String(), c.note) { t.Errorf("the output does not say %q:\n%s", c.note, out.String()) @@ -342,12 +365,126 @@ func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { } } +// Putting the older entry back keeps what another run records while the prompt +// waits: an entry for another file, and the disable of this one. +func TestClaudeCodeKeepsWhatAnotherRunRecordsDuringThePrompt(t *testing.T) { + for _, c := range []struct { + name string + other func(proj, other, cfg, state string) int + want func(proj, other string) []string // the files the record names afterwards + }{ + {"an enable on another file", func(_, other, cfg, state string) int { + return claudeCodeEnable2(other, cfg, state, true, io.Discard, io.Discard) + }, func(_, other string) []string { return []string{settingsRel, other} }}, + {"a disable of this file", func(proj, _, _, state string) int { + return claudeCodeDisable2(proj, state, true, io.Discard, io.Discard) + }, func(string, string) []string { return nil }}, + } { + t.Run(c.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + proj, other := filepath.Join(sc.home, "proj", settingsRel), filepath.Join(sc.home, "other", settingsRel) + writeHomeFile(t, proj, "{}\n") + writeHomeFile(t, other, "{}\n") + cfg, state := filepath.Join(sc.home, cortexCfgRel), filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "proj")) + if code := claudeCodeEnable2(settingsRel, cfg, state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + + saved := claudeCodeConfirm + t.Cleanup(func() { claudeCodeConfirm = saved }) + claudeCodeConfirm = func(io.Writer) bool { + if code := c.other(proj, other, cfg, state); code != 0 { + t.Errorf("%s during the prompt exit %d", c.name, code) + } + return false + } + if code := runClaudeCode([]string{"disable", "--settings", settingsRel}, io.Discard, io.Discard); code != exitDeclined { + t.Fatalf("disable exit %d, want %d", code, exitDeclined) + } + var names []string + if st, _ := readState(state); st != nil { + names = append(names, st.Settings) + for _, o := range st.OtherFiles { + names = append(names, o.Settings) + } + } + if want := c.want(proj, other); !slices.Equal(names, want) { + t.Errorf("the record names %q, want %q", names, want) + } + }) + } +} + +// An enable that records its values and then cannot write the settings file +// puts the older entry back as it was. +func TestClaudeCodeEnable_PutsBackTheOlderEntryItFailedToApply(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + proj := filepath.Join(sc.home, "proj", settingsRel) + writeHomeFile(t, proj, "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "proj")) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + st, _ := readState(state) + st.Written[envProxy] = "http://127.0.0.1:47699" + if err := writeStateFile(state, *st); err != nil { + t.Fatal(err) + } + doc, err := readSettings(proj) + if err != nil { + t.Fatal(err) + } + delete(envRaw(doc), envProxy) + if err := writeSettings(proj, doc); err != nil { + t.Fatal(err) + } + readOnlyDir(t, filepath.Dir(proj)) + + if code := runClaudeCode([]string{"enable", "--yes", "--settings", settingsRel}, io.Discard, io.Discard); code != 1 { + t.Fatalf("enable exit %d, want 1", code) + } + if got, _ := readState(state); got == nil || got.Settings != settingsRel || !maps.Equal(got.Written, st.Written) { + t.Errorf("the record is %+v, want the relative entry with Written %v", got, st.Written) + } +} + +// A record that cannot take the older entry as absolute still lets a relative +// disable restore what the entry recorded. +func TestClaudeCodeDisable_RestoresWhenTheOlderEntryCannotBeRecorded(t *testing.T) { + const mine = "http://127.0.0.1:47699" + sc := newUninstallScene(t) + sc.setUp(t) + proj := filepath.Join(sc.home, "proj", settingsRel) + writeHomeFile(t, proj, `{"env":{"`+envProxy+`":"`+mine+`"}}`) + state := filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "proj")) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + readOnlyDir(t, filepath.Dir(state)) + + var errb bytes.Buffer + if code := runClaudeCode([]string{"disable", "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if env := readEnv(t, proj); !maps.Equal(env, map[string]string{envProxy: mine}) { + t.Errorf("env is %v, want only %s=%s restored", env, envProxy, mine) + } + if !strings.Contains(errb.String(), "could not record the older entry") { + t.Errorf("disable did not say it kept the relative path:\n%s", errb.String()) + } +} + // An entry recorded under a symlink names the file it resolves to. func TestClaudeCodeRecordMatchesASymlinkedPath(t *testing.T) { dir := t.TempDir() link := filepath.Join(t.TempDir(), "link") if err := os.Symlink(dir, link); err != nil { - t.Fatal(err) + t.Skip("symlinks unavailable: ", err) } st := &managedState{Settings: "/a", OtherFiles: []managedState{{Settings: filepath.Join(link, "settings.json")}}} if got := recordIndex(st, filepath.Join(dir, "settings.json")); got != 1 { @@ -356,12 +493,23 @@ func TestClaudeCodeRecordMatchesASymlinkedPath(t *testing.T) { } // One entry with no Prior makes the record unreadable, as a first entry with none -// does. +// does, with an error naming the entry. Such an entry is never written: the record +// keeps the entries it had. func TestClaudeCodeRecordRefusesAnEntryWithNoPrior(t *testing.T) { state := filepath.Join(t.TempDir(), "state.json") writeHomeFile(t, state, `{"settings":"/a","prior":{},"other_files":[{"settings":"/b"}]}`) - if st, err := readState(state); err == nil { - t.Errorf("readState = %+v, want an error for the entry with no prior", st) + if st, err := readState(state); err == nil || !strings.Contains(err.Error(), `("/b"); fix or delete that entry by hand`) { + t.Errorf("readState = %+v (%v), want an error naming the entry with no prior and how to recover", st, err) + } + + writeHomeFile(t, state, `{"settings":"/a","prior":{}}`) + for _, e := range []managedState{{Settings: "/b"}, {Prior: map[string]*string{}}} { + if err := writeClaudeCodeState(state, e); err == nil { + t.Errorf("writeClaudeCodeState(%+v) recorded an entry readState refuses", e) + } + } + if st, err := readState(state); err != nil || st.Settings != "/a" || len(st.OtherFiles) != 0 { + t.Errorf("the record is %+v (%v), want /a's entry alone", st, err) } } From 55b9eeea8bf63cc7f47a2ed735997f60db661449 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:28:10 -0700 Subject: [PATCH 7/8] :bug: Keep older entry on no-change run Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 14 ++-- .../cmd_claudecode_settingspath_test.go | 72 +++++++++++++++---- docs/agents/claude-code.md | 6 ++ 3 files changed, 70 insertions(+), 22 deletions(-) diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index 072dae169..6ba8e87b8 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -183,8 +183,8 @@ func recordIndex(st *managedState, settingsPath string) int { // the relative path given again here, and returns a func that puts that entry // back as it was. The entry has no directory, and Cortex's values are the same // in every project, so runClaudeCode keeps the change only when the run succeeds -// and either changes abs or has --yes. A file holding none of the keys Cortex -// manages leaves the entry as it is, as does an entry abs already has. +// and changes abs. A file holding none of the keys Cortex manages leaves the +// entry as it is, as does an entry abs already has. func adoptRelativeEntry(statePath, rel, abs string, stdout io.Writer) (func() error, error) { st, err := readState(statePath) if err != nil || recordFor(st, abs) != nil { @@ -210,7 +210,7 @@ func adoptRelativeEntry(statePath, rel, abs string, stdout io.Writer) (func() er return nil, err } fmt.Fprintf(stdout, "The record's entry for %s is from an older agentop, which did not record\n"+ - "its directory. A change confirmed here, or --yes, takes it as %s;\n"+ + "its directory. A run that changes this file takes it as %s;\n"+ "give --settings as an absolute path to leave the entry as it is.\n\n", rel, abs) was.Settings, was.OtherFiles = rel, nil // The undo keeps every other entry as the record then holds it. An entry the @@ -476,17 +476,17 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { default: return claudeCodeStatus(*settingsPath, stdout) } - // An adopted entry stays when the run succeeded and the user confirmed it: by - // a change they agreed to, or by --yes. + // An adopted entry stays when the run succeeded and changed the file: a run + // that changes nothing, --yes or not, says nothing of whose file it is. if undo != nil { after, _ := os.ReadFile(*settingsPath) - if code != 0 || !yes && bytes.Equal(before, after) { + if code != 0 || bytes.Equal(before, after) { if err := undo(); err != nil { fmt.Fprintf(stderr, "agentop: could not put back %s (%v)\n", statePath, err) return 1 } if code == 0 { - fmt.Fprintf(stdout, "The older entry stays as it was; run again with --yes if it names %s.\n", *settingsPath) + fmt.Fprintf(stdout, "The older entry stays as it was. If it names %s, delete it from %s.\n", *settingsPath, statePath) } } } diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index 0f960b059..f1db3c896 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -177,15 +177,9 @@ func TestClaudeCodeEnable_LeavesAnOlderRelativeEntryToItsProject(t *testing.T) { // A relative --settings given again where an older enable recorded it finds // that entry, so disable takes it out and keeps every edit: one key edited -// since, that key alone left, every key edited, and a record from before -// Written. +// since, and a record from before Written. func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { const corpCA = "/etc/corp-ca.pem" - everyKey := map[string]string{} - for _, k := range managedKeys { - everyKey[k] = corpCA - } - everyKey[envProxy] = "http://corp.example:3128" for _, c := range []struct { name string want map[string]string // the env disable leaves @@ -194,12 +188,6 @@ func TestClaudeCodeDisable_FindsAnOlderRelativeEntry(t *testing.T) { {"a key edited since", map[string]string{envCACerts: corpCA}, func(t *testing.T, proj, _ string) { handEdit(t, proj, map[string]string{envCACerts: corpCA}) }}, - {"only an edited key left", map[string]string{envCACerts: corpCA}, func(t *testing.T, proj, _ string) { - writeHomeFile(t, proj, `{"env":{"`+envCACerts+`":"`+corpCA+`"}}`) - }}, - {"every key edited", everyKey, func(t *testing.T, proj, _ string) { - handEdit(t, proj, everyKey) - }}, {"a record from before Written", nil, func(t *testing.T, _, state string) { st, _ := readState(state) st.Written = nil @@ -311,14 +299,14 @@ func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { edits[k] = "/etc/corp-ca.pem" } handEdit(t, proj, edits) - }, settingsRel, "run again with --yes", false}, + }, settingsRel, "delete it from", false}, {"a disable with nothing to remove beside another file", "disable", func(t *testing.T, proj string) { edits := map[string]string{} for _, k := range managedKeys { edits[k] = "/etc/corp-ca.pem" } handEdit(t, proj, edits) - }, settingsRel, "run again with --yes", true}, + }, settingsRel, "delete it from", true}, } { t.Run(c.name, func(t *testing.T) { sc := newUninstallScene(t) @@ -365,6 +353,60 @@ func TestClaudeCodeTakesAnOlderRelativeEntryWithAConfirmedChange(t *testing.T) { } } +// A disable with --yes that removes nothing keeps the older relative entry and +// says how to delete it: in the project that holds it, with every key edited or +// only an edited key left, and in another project holding only the user's own +// key. +func TestClaudeCodeKeepsAnOlderRelativeEntryWhenADisableRemovesNothing(t *testing.T) { + everyKey := map[string]string{envProxy: "http://corp.example:3128"} + for _, k := range managedKeys[1:] { + everyKey[k] = "/etc/corp-ca.pem" + } + for _, c := range []struct { + name string + dir string // where disable runs, under home + env map[string]string + }{ + {"every key edited", "a", everyKey}, + {"only an edited key left", "a", map[string]string{envCACerts: "/etc/corp-ca.pem"}}, + {"another project with only its own key", "b", map[string]string{envCACerts: "/etc/b-corp.pem"}}, + } { + t.Run(c.name, func(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + a := filepath.Join(sc.home, "a", settingsRel) + writeHomeFile(t, a, "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "a")) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + routed := readEnv(t, a) + file := filepath.Join(sc.home, c.dir, settingsRel) + writeHomeFile(t, file, `{"env":{}}`) + handEdit(t, file, c.env) + + t.Chdir(filepath.Join(sc.home, c.dir)) + var out, errb bytes.Buffer + if code := runClaudeCode([]string{"disable", "--yes", "--settings", settingsRel}, &out, &errb); code != 0 { + t.Fatalf("disable exit %d: %s", code, errb.String()) + } + if env := readEnv(t, file); !maps.Equal(env, c.env) { + t.Errorf("env is %v, want %v kept", env, c.env) + } + if st, _ := readState(state); st == nil || st.Settings != settingsRel || len(st.OtherFiles) != 0 { + t.Errorf("the record is %+v, want the relative entry alone", st) + } + if !strings.Contains(out.String(), "delete it from "+state) { + t.Errorf("disable does not say how to delete the older entry:\n%s", out.String()) + } + if c.dir == "b" && !maps.Equal(readEnv(t, a), routed) { + t.Errorf("a's settings changed: %v", readEnv(t, a)) + } + }) + } +} + // Putting the older entry back keeps what another run records while the prompt // waits: an entry for another file, and the disable of this one. func TestClaudeCodeKeepsWhatAnotherRunRecordsDuringThePrompt(t *testing.T) { diff --git a/docs/agents/claude-code.md b/docs/agents/claude-code.md index d55258328..04f002665 100644 --- a/docs/agents/claude-code.md +++ b/docs/agents/claude-code.md @@ -52,6 +52,12 @@ whose value changed after `enable`, and it names each key it did not change. Eac settings file `enable` routed, such as a project's and the default one, has its own entry. `agentop uninstall` runs the same `disable` on each. +An older `agentop` recorded a relative `--settings` as given, with no directory, so +after an upgrade `enable` or `disable` with that relative path says the entry is +from an older agentop. A run that changes the file takes the entry for it; a run +that changes nothing leaves the entry and names the record to delete it from if it +is this file's. An absolute `--settings` leaves the entry alone. + `disable` restores every value, but not the file's text. For example, it sorts the keys, uses a 2-space indent, puts each array item on its own line, and writes `&`, `<` and `>` as `\u0026`, `\u003c` and `\u003e`. `settings.json.bak` holds the file as it was before the From 8ccdc0a1931c0aac5a4f524a501dbd4915ed2701 Mon Sep 17 00:00:00 2001 From: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:53:39 -0700 Subject: [PATCH 8/8] :goal_net: No-op enable Signed-off-by: Evaline Ju <69598118+evaline-ju@users.noreply.github.com> --- cmd/agentop/cmd_claudecode.go | 7 ++++- .../cmd_claudecode_settingspath_test.go | 30 +++++++++++++++++++ docs/agents/claude-code.md | 7 +++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/cmd/agentop/cmd_claudecode.go b/cmd/agentop/cmd_claudecode.go index 6ba8e87b8..3cf2e98bd 100644 --- a/cmd/agentop/cmd_claudecode.go +++ b/cmd/agentop/cmd_claudecode.go @@ -485,7 +485,12 @@ func runClaudeCode(args []string, stdout, stderr io.Writer) int { fmt.Fprintf(stderr, "agentop: could not put back %s (%v)\n", statePath, err) return 1 } - if code == 0 { + // After enable the file still routes, so the entry is what lets + // uninstall find it; disable and then enable record it under abs. + if code == 0 && action == "enable" { + fmt.Fprintf(stdout, "The older entry stays as it was. If it names %s,\n"+ + "run disable and then enable with this --settings to record it there.\n", *settingsPath) + } else if code == 0 { fmt.Fprintf(stdout, "The older entry stays as it was. If it names %s, delete it from %s.\n", *settingsPath, statePath) } } diff --git a/cmd/agentop/cmd_claudecode_settingspath_test.go b/cmd/agentop/cmd_claudecode_settingspath_test.go index f1db3c896..52af761cb 100644 --- a/cmd/agentop/cmd_claudecode_settingspath_test.go +++ b/cmd/agentop/cmd_claudecode_settingspath_test.go @@ -407,6 +407,36 @@ func TestClaudeCodeKeepsAnOlderRelativeEntryWhenADisableRemovesNothing(t *testin } } +// An enable that changes nothing leaves the file routed, so its note keeps the +// entry and names the runs that record it under the absolute path. +func TestClaudeCodeEnableThatChangesNothingSaysHowToRecordTheOlderEntry(t *testing.T) { + sc := newUninstallScene(t) + sc.setUp(t) + proj := filepath.Join(sc.home, "proj", settingsRel) + writeHomeFile(t, proj, "{}\n") + state := filepath.Join(sc.home, stateRel) + t.Chdir(filepath.Join(sc.home, "proj")) + if code := claudeCodeEnable2(settingsRel, filepath.Join(sc.home, cortexCfgRel), state, true, io.Discard, io.Discard); code != 0 { + t.Fatalf("fixture: relative enable exit %d", code) + } + + var out, errb bytes.Buffer + if code := runClaudeCode([]string{"enable", "--yes", "--settings", settingsRel}, &out, &errb); code != 0 { + t.Fatalf("enable exit %d: %s", code, errb.String()) + } + if s := out.String(); !strings.Contains(s, "run disable and then enable") || strings.Contains(s, "delete it from") { + t.Errorf("the note after an enable that changes nothing is:\n%s", s) + } + for _, action := range []string{"disable", "enable"} { + if code := runClaudeCode([]string{action, "--yes", "--settings", settingsRel}, io.Discard, &errb); code != 0 { + t.Fatalf("%s exit %d: %s", action, code, errb.String()) + } + } + if st, _ := readState(state); st == nil || st.Settings != proj || len(st.OtherFiles) != 0 { + t.Errorf("the record is %+v, want %s alone", st, proj) + } +} + // Putting the older entry back keeps what another run records while the prompt // waits: an entry for another file, and the disable of this one. func TestClaudeCodeKeepsWhatAnotherRunRecordsDuringThePrompt(t *testing.T) { diff --git a/docs/agents/claude-code.md b/docs/agents/claude-code.md index 04f002665..d8245d87d 100644 --- a/docs/agents/claude-code.md +++ b/docs/agents/claude-code.md @@ -54,9 +54,10 @@ entry. `agentop uninstall` runs the same `disable` on each. An older `agentop` recorded a relative `--settings` as given, with no directory, so after an upgrade `enable` or `disable` with that relative path says the entry is -from an older agentop. A run that changes the file takes the entry for it; a run -that changes nothing leaves the entry and names the record to delete it from if it -is this file's. An absolute `--settings` leaves the entry alone. +from an older agentop. A run that changes the file takes the entry for it, so +`disable` and then `enable` from the project moves the entry to its absolute path. +A run that changes nothing leaves the entry as it was. An absolute `--settings` +leaves the entry alone. `disable` restores every value, but not the file's text. For example, it sorts the keys, uses a 2-space indent, puts each array item on its own line, and writes `&`, `<` and `>` as