The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(harness): keep codex config sections whose header has a comment (#1070)
Rudy Mizrahi Celeklia2cf26cc9587
diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.goindex f92445f4..fee150e4 100644--- a/cli/beacon/internal/endpoint/harness/harness.go+++ b/cli/beacon/internal/endpoint/harness/harness.go@@ -17,6 +17,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tomledit""gopkg.in/yaml.v3")@@ -515,45 +516,13 @@ func mergeCodexOTEL(existing, endpoint string) string {return mergeCodexOTELWithPrompt(existing, endpoint, true)}+// mergeCodexOTELWithPrompt replaces every [otel] and [otel.*] table with Beacon's, appended at+// the end of the document.func mergeCodexOTELWithPrompt(existing, endpoint string, logUserPrompt bool) string {- lines := strings.Split(existing, "\n")- var out []string- inOTEL := false- wroteOTEL := false- for _, line := range lines {- trim := strings.TrimSpace(line)- if strings.HasPrefix(trim, "[") && strings.HasSuffix(trim, "]") {- isOTELHeader := codexOTELHeader(trim)- if inOTEL && !isOTELHeader && !wroteOTEL {- out = append(out, codexOTELBlock(endpoint, logUserPrompt)...)- wroteOTEL = true- }- inOTEL = isOTELHeader- if !inOTEL {- out = append(out, line)- }- continue- }- if inOTEL {- continue- }- out = append(out, line)- }- if inOTEL && !wroteOTEL {- out = append(out, codexOTELBlock(endpoint, logUserPrompt)...)- wroteOTEL = true- }- if !wroteOTEL {- if strings.TrimSpace(existing) != "" {- out = append(out, "")- }- out = append(out, codexOTELBlock(endpoint, logUserPrompt)...)- }- return strings.TrimRight(strings.Join(out, "\n"), "\n") + "\n"-}--func codexOTELHeader(header string) bool {- return header == "[otel]" || strings.HasPrefix(header, "[otel.")+ eol := tomledit.LineEnding(existing, "\n")+ stripped, _ := tomledit.RemoveTable(existing, "otel")+ block := strings.Join(codexOTELBlock(endpoint, logUserPrompt), eol) + eol+ return tomledit.Append(stripped, block, eol)}func codexOTELBlock(endpoint string, logUserPrompt bool) []string {diff --git a/cli/beacon/internal/endpoint/harness/harness_test.go b/cli/beacon/internal/endpoint/harness/harness_test.goindex 9e3e8065..2fe1c437 100644--- a/cli/beacon/internal/endpoint/harness/harness_test.go+++ b/cli/beacon/internal/endpoint/harness/harness_test.go@@ -9,6 +9,8 @@ import ("strings""testing"+ "github.com/pelletier/go-toml/v2"+"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/fxsession""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/groksession""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"@@ -54,6 +56,64 @@ func TestConfigureClaudeRefusesSettingsItCannotParse(t *testing.T) {}}+func TestMergeCodexOTELReadsHeadersWithComments(t *testing.T) {+ input := "model = \"gpt-5\"\n\n[otel] # telemetry\nenvironment = \"prod\"\n\n[otel.exporter.\"otlp-grpc\"]\nendpoint = \"http://old.example.com\"\n\n[profiles.fast] # my profile\nmodel = \"o3\"\n"+ got := mergeCodexOTEL(input, "http://127.0.0.1:4317")+ var parsed map[string]interface{}+ if err := toml.Unmarshal([]byte(got), &parsed); err != nil {+ t.Fatalf("merged config is not valid TOML: %v\n%s", err, got)+ }+ if strings.Contains(got, "old.example.com") || strings.Contains(got, "\"prod\"") {+ t.Fatalf("old otel config was not replaced: %s", got)+ }+ if !strings.Contains(got, "[profiles.fast] # my profile\nmodel = \"o3\"") {+ t.Fatalf("following section was not preserved: %s", got)+ }+}++// parseCodexConfig fails the test unless text is a config Codex can load.+func parseCodexConfig(t *testing.T, text string) map[string]interface{} {+ t.Helper()+ var parsed map[string]interface{}+ if err := toml.Unmarshal([]byte(text), &parsed); err != nil {+ t.Fatalf("merged config is not valid TOML: %v\n%s", err, text)+ }+ return parsed+}++func TestMergeCodexOTELReplacesACommentedOTELHeader(t *testing.T) {+ got := mergeCodexOTEL("model = \"gpt-5\"\n\n[otel] # telemetry\nenvironment = \"prod\"\n\n[mcp_servers.x]\ncommand = \"npx\"\n", "http://127.0.0.1:4317")+ parsed := parseCodexConfig(t, got)+ if otel, _ := parsed["otel"].(map[string]interface{}); otel["environment"] != "dev" {+ t.Fatalf("otel = %v, want Beacon's block:\n%s", parsed["otel"], got)+ }+ if servers, _ := parsed["mcp_servers"].(map[string]interface{}); servers["x"] == nil {+ t.Fatalf("mcp_servers.x was dropped:\n%s", got)+ }+}++// Beacon's [otel] block sits at the end of the file, so a server the person adds afterwards follows+// it; a reinstall must not take that server for part of the block.+func TestMergeCodexOTELKeepsCommentedTablesAfterTheBlock(t *testing.T) {+ for name, header := range map[string]string{+ "bare": "[mcp_servers.x] # mine",+ "quoted #": "[mcp_servers.\"x#1\"] # mine",+ "literal #": "[mcp_servers.'x#1']",+ } {+ first := mergeCodexOTEL("model = \"gpt-5\"\n", "http://127.0.0.1:4317")+ input := first + "\n" + header + "\ncommand = \"npx\"\n"+ got := mergeCodexOTEL(input, "http://127.0.0.1:4318")+ parsed := parseCodexConfig(t, got)+ servers, _ := parsed["mcp_servers"].(map[string]interface{})+ if len(servers) != 1 || !strings.Contains(got, header+"\ncommand = \"npx\"") {+ t.Errorf("%s: server was dropped:\n%s", name, got)+ }+ if strings.Contains(got, "4317") {+ t.Errorf("%s: old endpoint kept:\n%s", name, got)+ }+ }+}+func TestConfigureClaudeWritesTelemetryEnvAndBackup(t *testing.T) {home := t.TempDir()testenv.SetHome(t, home)diff --git a/cli/beacon/internal/endpoint/hooks/kimi.go b/cli/beacon/internal/endpoint/hooks/kimi.goindex 2f2d5ac1..dc7ddce5 100644--- a/cli/beacon/internal/endpoint/hooks/kimi.go+++ b/cli/beacon/internal/endpoint/hooks/kimi.go@@ -9,6 +9,8 @@ import ("strings""github.com/pelletier/go-toml/v2"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tomledit")// Kimi Code is the one supported runtime whose hook registration lives inside a file that also@@ -327,7 +329,7 @@ func installKimiHooks(path, binaryPath, logPath, configPath string) error {if err != nil {return err}- updated := kimiEndWithNewline(kimiJoin(stripped, block, eol), eol)+ updated := tomledit.EndWithNewline(tomledit.Append(stripped, block, eol), eol)want := append(kept, kimiExpectedEntries(binaryPath, logPath, configPath)...)if err := verifyKimiRewrite(path, original, updated, want); err != nil {@@ -361,7 +363,7 @@ func removeKimiHooks(path string) (bool, error) {}stripped, kept := stripKimiHooks(original)- updated := kimiEndWithNewline(stripped, kimiLineEnding(original))+ updated := tomledit.EndWithNewline(stripped, kimiLineEnding(original))if err := verifyKimiRewrite(path, original, updated, kept); err != nil {return false, err}@@ -449,31 +451,12 @@ func kimiHooksAreAppendable(path, text string, parsed map[string]interface{}) erpath)}-// kimiHookHeaderPattern matches an array-of-tables header for the hooks key.-//-// Whitespace inside the brackets is allowed because TOML allows it, and a trailing comment is-// allowed because a person may have written one. A dotted or quoted spelling is deliberately not-// matched: `["hooks"]` and `[a.hooks]` are different keys, and treating them as this one would-// have Beacon delete a table it does not own.+// kimiHookHeaderPattern matches an array-of-tables header for the hooks key, in any of TOML's+// spellings of it and with or without a trailing comment. `[hooks]` and `[[a.hooks]]` are+// different keys, and treating them as this one would have Beacon delete a table it does not own.func kimiHookHeaderPattern(line string) bool {- trimmed := strings.TrimSpace(line)- if !strings.HasPrefix(trimmed, "[[") {- return false- }- closing := strings.Index(trimmed, "]]")- if closing < 0 {- return false- }- if strings.TrimSpace(trimmed[2:closing]) != kimiHooksKey {- return false- }- rest := strings.TrimSpace(trimmed[closing+2:])- return rest == "" || strings.HasPrefix(rest, "#")-}--// kimiIsTopLevelHeader reports whether a line opens any table, which is what ends a hooks block.-func kimiIsTopLevelHeader(line string) bool {- return strings.HasPrefix(strings.TrimSpace(line), "[")+ key, array, ok := tomledit.Header(line)+ return ok && array && len(key) == 1 && key[0] == kimiHooksKey}func kimiCountHookHeaders(text string) int {@@ -509,8 +492,12 @@ func stripKimiHooks(text string) (string, []kimiHookEntry) {kept = append(kept, lines[index])continue}+ // The block runs to the next table header of any kind.end := index + 1- for end < len(lines) && !kimiIsTopLevelHeader(lines[end]) {+ for end < len(lines) {+ if _, _, header := tomledit.Header(lines[end]); header {+ break+ }end++}block := lines[index:end]@@ -652,45 +639,15 @@ func verifyKimiRewrite(path, original, updated string, want []kimiHookEntry) errreturn nil}-// kimiJoin appends a block to a document, keeping exactly one blank line between them.-func kimiJoin(text, block, eol string) string {- trimmed := strings.TrimRight(text, " \t\r\n")- if trimmed == "" {- return block- }- return trimmed + eol + eol + block-}--// kimiEndWithNewline gives a non-empty document exactly one trailing line ending.-//-// stripKimiHooks trims the blank lines that sat above a removed block, which on a config whose-// only hooks were Beacon's takes the file's final newline with them. A POSIX text file ends in a-// newline, several editors add one back on the next save, and a config that gained or lost one-// every time Beacon was installed and removed would show up as a spurious diff in any dotfiles-// repository the user keeps.-func kimiEndWithNewline(text, eol string) string {- trimmed := strings.TrimRight(text, " \t\r\n")- if trimmed == "" {- return ""- }- return trimmed + eol-}-// kimiLineEnding is the line ending the existing document uses, so an edit does not mix them.//// A file with no newline at all -- empty, or one line -- gets the platform's, which is what a// fresh install on Windows should write.func kimiLineEnding(text string) string {- if strings.Contains(text, "\r\n") {- return "\r\n"- }- if strings.Contains(text, "\n") {- return "\n"- }if runtime.GOOS == "windows" {- return "\r\n"+ return tomledit.LineEnding(text, "\r\n")}- return "\n"+ return tomledit.LineEnding(text, "\n")}func readKimiConfigText(path string) (string, error) {diff --git a/cli/beacon/internal/mcpconnect/edit_test.go b/cli/beacon/internal/mcpconnect/edit_test.goindex a48eee27..b65f172d 100644--- a/cli/beacon/internal/mcpconnect/edit_test.go+++ b/cli/beacon/internal/mcpconnect/edit_test.go@@ -60,15 +60,3 @@ func TestVerifierRejectsEditsBeyondBeaconsEntry(t *testing.T) {t.Error("a disconnect that dropped an unrelated key was accepted")}}--func TestStripTOMLTableHandlesQuotingAndSubtables(t *testing.T) {- doc := "a = 1\n\n[mcp_servers.\"beacon-managed\"]\nurl = \"x\"\n\n[mcp_servers.beacon-managed.env]\nK = \"v\"\n\n[mcp_servers.beacon-managed-other]\nurl = \"y\"\n"- got, found := stripTOMLTable(doc, "mcp_servers", ServerName)- if !found {- t.Fatal("not found")- }- want := "a = 1\n\n[mcp_servers.beacon-managed-other]\nurl = \"y\"\n"- if got != want {- t.Fatalf("got %q want %q", got, want)- }-}diff --git a/cli/beacon/internal/mcpconnect/engine.go b/cli/beacon/internal/mcpconnect/engine.goindex 2deeaf9e..7f210252 100644--- a/cli/beacon/internal/mcpconnect/engine.go+++ b/cli/beacon/internal/mcpconnect/engine.go@@ -12,6 +12,7 @@ import ("time""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tomledit")// Action is what connect will do, or did, for one target.@@ -382,17 +383,17 @@ func applyOne(ctx context.Context, opts Options, m *manifest, it Item) (Record,func editForConnect(t Target, text string, st state, opts Options) (updated string, created int, createdInputs bool, err error) {entry := t.desiredEntry(opts, st.entry)if t.format == formatTOML {- eol := tomlLineEnding(text)+ eol := tomledit.LineEnding(text, "\n")stripped := textif st.exists {var found bool- stripped, found = stripTOMLTable(text, t.container[0], ServerName)+ stripped, found = tomledit.RemoveTable(text, t.container[0], ServerName)if !found {return "", 0, false, errors.New("the existing " + ServerName + " entry is not a [" + t.container[0] + "." + ServerName + "] table, so Beacon cannot replace it; remove it by hand")}- stripped = endTOMLWithNewline(stripped, eol)+ stripped = tomledit.EndWithNewline(stripped, eol)}- return appendTOMLBlock(stripped, tomlBlock(t.container[0], ServerName, entry, eol), eol), 0, false, nil+ return tomledit.Append(stripped, tomlBlock(t.container[0], ServerName, entry, eol), eol), 0, false, nil}updated = textif strings.TrimSpace(updated) == "" && len(t.skeleton) > 0 {@@ -772,11 +773,11 @@ func disconnectOne(ctx context.Context, opts Options, t Target, rec Record) (Actfunc editForDisconnect(t Target, text string, rec Record) (string, error) {if t.format == formatTOML {- stripped, found := stripTOMLTable(text, t.container[0], ServerName)+ stripped, found := tomledit.RemoveTable(text, t.container[0], ServerName)if !found {return "", errors.New("the " + ServerName + " entry is not a [" + t.container[0] + "." + ServerName + "] table; remove it by hand")}- return endTOMLWithNewline(stripped, tomlLineEnding(text)), nil+ return tomledit.EndWithNewline(stripped, tomledit.LineEnding(text, "\n")), nil}updated, err := jsonc.RemoveMember(text, t.container, ServerName, rec.CreatedParents)if err != nil {diff --git a/cli/beacon/internal/mcpconnect/tomledit.go b/cli/beacon/internal/mcpconnect/tomledit.goindex ec4b0f31..48b70576 100644--- a/cli/beacon/internal/mcpconnect/tomledit.go+++ b/cli/beacon/internal/mcpconnect/tomledit.go@@ -11,9 +11,9 @@ import ()// Codex CLI keeps MCP servers in ~/.codex/config.toml as [mcp_servers.<name>] tables. The file-// also holds the user's model, profile and sandbox settings, so Beacon edits it the way the Kimi-// Code installer edits config.toml: it appends or removes its own table as lines of text, never-// re-serializes the document, and parses the result to prove nothing else changed.+// also holds the user's model, profile and sandbox settings, so Beacon edits it through tomledit:+// it appends or removes its own table as lines of text, never re-serializes the document, and+// parses the result to prove nothing else changed.func parseTOML(text string) (map[string]any, error) {parsed := map[string]any{}@@ -33,15 +33,6 @@ func tomlString(value string) string {return jsonc.Quote(value)}-// tomlLineEnding is the line ending the document already uses. A new document gets "\n" on every-// platform, as `codex mcp add` writes it.-func tomlLineEnding(text string) string {- if strings.Contains(text, "\r\n") {- return "\r\n"- }- return "\n"-}-// tomlBlock renders [mcp_servers.<name>] with fields in the order given. Values are strings, or// the person's own `enabled` boolean that connect carries over.func tomlBlock(table string, name string, fields []jsonc.Field, eol string) string {@@ -66,61 +57,6 @@ func tomlKey(name string) string {return tomlString(name)}-// tomlHeaderFor matches the header of table.name and of its subtables (for example-// [mcp_servers.beacon-managed.env]), in any of TOML's quoting styles.-func tomlHeaderFor(table, name string) *regexp.Regexp {- key := `(?:` + regexp.QuoteMeta(name) + `|"` + regexp.QuoteMeta(name) + `"|'` + regexp.QuoteMeta(name) + `')`- return regexp.MustCompile(`^\s*\[\s*` + regexp.QuoteMeta(table) + `\s*\.\s*` + key + `\s*(?:\.[^\]]*)?\]\s*(?:#.*)?$`)-}--var tomlAnyHeader = regexp.MustCompile(`^\s*\[`)--// stripTOMLTable removes every [table.name] block (and its subtables) from text. A block runs-// from its header to the next header, so its own trailing blank lines go with it; a block at the-// end of the document also takes the blank lines above it, which is what appendTOMLBlock added.-// It reports whether any block was found.-func stripTOMLTable(text, table, name string) (string, bool) {- header := tomlHeaderFor(table, name)- lines := strings.SplitAfter(text, "\n")- var out []string- found, skipping := false, false- for _, line := range lines {- bare := strings.TrimRight(line, "\r\n")- if tomlAnyHeader.MatchString(bare) {- skipping = header.MatchString(bare)- found = found || skipping- }- if !skipping {- out = append(out, line)- }- }- if skipping {- for len(out) > 0 && strings.TrimSpace(out[len(out)-1]) == "" {- out = out[:len(out)-1]- }- }- return strings.Join(out, ""), found-}--// appendTOMLBlock adds block at the end of the document, one blank line after existing content.-func appendTOMLBlock(text, block, eol string) string {- trimmed := strings.TrimRight(text, " \t\r\n")- if trimmed == "" {- return block- }- return trimmed + eol + eol + block-}--// endTOMLWithNewline gives a non-empty document exactly one trailing line ending, so a document-// whose last table was Beacon's does not lose its final newline when the table is removed.-func endTOMLWithNewline(text, eol string) string {- trimmed := strings.TrimRight(text, " \t\r\n")- if trimmed == "" {- return ""- }- return trimmed + eol-}-func tomlTableEntry(parsed map[string]any, table, name string) (map[string]any, bool) {servers, ok := parsed[table].(map[string]any)if !ok {diff --git a/cli/beacon/internal/tomledit/tomledit.go b/cli/beacon/internal/tomledit/tomledit.gonew file mode 100644index 00000000..19558a40--- /dev/null+++ b/cli/beacon/internal/tomledit/tomledit.go@@ -0,0 +1,153 @@+// Package tomledit edits TOML documents Beacon does not own -- Codex's and Kimi Code's+// config.toml -- as lines of text. Those files carry the user's comments and layout, which a+// parse-and-serialize round trip would discard, so Beacon only ever removes its own tables and+// appends new ones; callers parse the result to prove nothing else changed.+//+// It does not track multi-line strings: a line inside a """ value that looks like a header is+// read as one.+package tomledit++import (+ "strconv"+ "strings"+)++// Header parses a table header (`[a.b]`) or array-of-tables header (`[[a.b]]`) line, with+// whitespace around the key parts, bare, "basic" or 'literal' key parts, and an optional trailing+// comment. It returns the key's parts with quoting removed.+func Header(line string) (key []string, array bool, ok bool) {+ rest := strings.TrimSpace(line)+ if !strings.HasPrefix(rest, "[") {+ return nil, false, false+ }+ rest = rest[1:]+ if strings.HasPrefix(rest, "[") {+ array = true+ rest = rest[1:]+ }+ for {+ var part string+ part, rest, ok = keyPart(strings.TrimLeft(rest, " \t"))+ if !ok {+ return nil, false, false+ }+ key = append(key, part)+ rest = strings.TrimLeft(rest, " \t")+ if !strings.HasPrefix(rest, ".") {+ break+ }+ rest = rest[1:]+ }+ closing := "]"+ if array {+ closing = "]]"+ }+ if !strings.HasPrefix(rest, closing) {+ return nil, false, false+ }+ rest = strings.TrimLeft(rest[len(closing):], " \t")+ if rest != "" && !strings.HasPrefix(rest, "#") {+ return nil, false, false+ }+ return key, array, true+}++// keyPart reads one bare, basic-quoted or literal-quoted key part from the start of s.+func keyPart(s string) (part, rest string, ok bool) {+ switch {+ case strings.HasPrefix(s, `"`):+ for i := 1; i < len(s); i++ {+ switch s[i] {+ case '\\':+ i+++ case '"':+ part, err := strconv.Unquote(s[:i+1])+ return part, s[i+1:], err == nil+ }+ }+ return "", "", false+ case strings.HasPrefix(s, "'"):+ end := strings.IndexByte(s[1:], '\'')+ if end < 0 {+ return "", "", false+ }+ return s[1 : end+1], s[end+2:], true+ }+ end := 0+ for end < len(s) && isBareKeyChar(s[end]) {+ end+++ }+ return s[:end], s[end:], end > 0+}++func isBareKeyChar(c byte) bool {+ return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_' || c == '-'+}++// RemoveTable removes the table at key and every table under it (for key ["otel"]: [otel],+// [otel.exporter."otlp-grpc"], [[otel.x]]) from text. A block runs from its header to the next+// header, so its own trailing blank lines go with it; a block at the end of the document also+// takes the blank lines above it, which is what Append added. It reports whether any block was+// found.+func RemoveTable(text string, key ...string) (string, bool) {+ var out []string+ found, skipping := false, false+ for _, line := range strings.SplitAfter(text, "\n") {+ if header, _, ok := Header(line); ok {+ skipping = hasPrefix(header, key)+ found = found || skipping+ }+ if !skipping {+ out = append(out, line)+ }+ }+ if skipping {+ for len(out) > 0 && strings.TrimSpace(out[len(out)-1]) == "" {+ out = out[:len(out)-1]+ }+ }+ return strings.Join(out, ""), found+}++func hasPrefix(key, prefix []string) bool {+ if len(key) < len(prefix) {+ return false+ }+ for i := range prefix {+ if key[i] != prefix[i] {+ return false+ }+ }+ return true+}++// Append adds block at the end of the document, one blank line after existing content.+func Append(text, block, eol string) string {+ trimmed := strings.TrimRight(text, " \t\r\n")+ if trimmed == "" {+ return block+ }+ return trimmed + eol + eol + block+}++// EndWithNewline gives a non-empty document exactly one trailing line ending, so a document whose+// last table was Beacon's does not lose its final newline when the table is removed.+func EndWithNewline(text, eol string) string {+ trimmed := strings.TrimRight(text, " \t\r\n")+ if trimmed == "" {+ return ""+ }+ return trimmed + eol+}++// LineEnding is the line ending the document already uses, so an edit does not mix them; a+// document without one gets fallback.+func LineEnding(text, fallback string) string {+ if strings.Contains(text, "\r\n") {+ return "\r\n"+ }+ if strings.Contains(text, "\n") {+ return "\n"+ }+ return fallback+}diff --git a/cli/beacon/internal/tomledit/tomledit_test.go b/cli/beacon/internal/tomledit/tomledit_test.gonew file mode 100644index 00000000..a5890851--- /dev/null+++ b/cli/beacon/internal/tomledit/tomledit_test.go@@ -0,0 +1,72 @@+package tomledit++import (+ "reflect"+ "testing"+)++func TestHeaderReadsEveryTOMLSpelling(t *testing.T) {+ for line, want := range map[string][]string{+ `[otel]`: {"otel"},+ ` [ otel . exporter ] `: {"otel", "exporter"},+ `[otel.exporter."otlp-grpc"]`: {"otel", "exporter", "otlp-grpc"},+ `[mcp_servers.x] # mine`: {"mcp_servers", "x"},+ `[mcp_servers."a#b"] # c`: {"mcp_servers", "a#b"},+ `[mcp_servers.'a.b']`: {"mcp_servers", "a.b"},+ `["mcp_servers"."beacon-managed"]`: {"mcp_servers", "beacon-managed"},+ `[mcp_servers."q\"]"]`: {"mcp_servers", `q"]`},+ "[profiles.fast]\r": {"profiles", "fast"},+ `[[hooks]] # Beacon`: {"hooks"},+ `[[ "hooks" ]]`: {"hooks"},+ } {+ got, _, ok := Header(line)+ if !ok || !reflect.DeepEqual(got, want) {+ t.Errorf("Header(%q) = %q, %v; want %q", line, got, ok, want)+ }+ }+ for _, line := range []string{+ `model = "o3"`,+ `args = ["a", "b"]`,+ `["a", "b"],`,+ `[1, 2]`,+ `[otel`,+ `[otel] trailing`,+ `[[hooks]`,+ `[hooks]]`,+ `[]`,+ `# [otel]`,+ } {+ if key, _, ok := Header(line); ok {+ t.Errorf("Header(%q) = %q, want no header", line, key)+ }+ }+ if _, array, _ := Header("[[hooks]]"); !array {+ t.Error("[[hooks]] not reported as an array of tables")+ }+ if _, array, _ := Header("[hooks]"); array {+ t.Error("[hooks] reported as an array of tables")+ }+}++func TestRemoveTableHandlesQuotingCommentsAndSubtables(t *testing.T) {+ doc := "a = 1\n\n[mcp_servers.\"beacon-managed\"] # Beacon\nurl = \"x\"\n\n[mcp_servers.beacon-managed.env]\nK = \"v\"\n\n[mcp_servers.beacon-managed-other] # mine\nurl = \"y\"\n"+ got, found := RemoveTable(doc, "mcp_servers", "beacon-managed")+ if !found {+ t.Fatal("not found")+ }+ want := "a = 1\n\n[mcp_servers.beacon-managed-other] # mine\nurl = \"y\"\n"+ if got != want {+ t.Fatalf("got %q want %q", got, want)+ }+}++func TestRemoveTableKeepsCRLFAndTrimsTrailingBlock(t *testing.T) {+ doc := "model = \"o3\"\r\n\r\n[otel] # telemetry\r\nenvironment = \"prod\"\r\n"+ got, found := RemoveTable(doc, "otel")+ if !found || got != "model = \"o3\"\r\n" {+ t.Fatalf("got %q, %v", got, found)+ }+ if _, found := RemoveTable("[otelx]\na = 1\n", "otel"); found {+ t.Fatal("[otelx] removed as [otel]")+ }+}