Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(install): keep foreign tables between the managed TOML markers (#2228)
Martin Vogel98e58acb8d6d
diff --git a/src/cli/cli.c b/src/cli/cli.cindex b868fdca2..32bcffe53 100644--- a/src/cli/cli.c+++ b/src/cli/cli.c@@ -3793,8 +3793,11 @@ int cbm_upsert_codex_mcp(const char *binary_path, const char *config_path) {}int cbm_remove_codex_mcp(const char *config_path) {+ /* #2228: only our table goes; foreign tables found between the markers+ * (Codex Desktop appends below a block that ends the file) stay. */if (!config_path ||- cbm_toml_remove_managed_block(config_path, CODEX_MCP_BEGIN, CODEX_MCP_END) != 0) {+ cbm_toml_remove_managed_block_owned(config_path, CODEX_MCP_BEGIN, CODEX_MCP_END,+ CODEX_CMM_SECTION "\n") != 0) {return CLI_ERR;}return cbm_remove_codex_legacy_mcp(config_path) >= 0 ? CLI_OK : CLI_ERR;@@ -4418,7 +4421,8 @@ static int cbm_upsert_grok_mcp(const char *binary_path, const char *config_path)static int cbm_remove_grok_mcp_owned(const char *binary_path, const char *config_path) {(void)binary_path;if (!config_path ||- cbm_toml_remove_managed_block(config_path, GROK_MCP_BEGIN, GROK_MCP_END) != 0) {+ cbm_toml_remove_managed_block_owned(config_path, GROK_MCP_BEGIN, GROK_MCP_END,+ GROK_CMM_SECTION "\n") != 0) {return CLI_ERR;}return cbm_remove_grok_legacy_mcp(config_path) >= 0 ? CLI_OK : CLI_ERR;@@ -4984,7 +4988,8 @@ static int cbm_upsert_kimi_context_hook(const char *config_path, const char *bin}static int cbm_remove_kimi_context_hook(const char *config_path) {- return cbm_toml_remove_managed_block(config_path, KIMI_HOOK_BEGIN, KIMI_HOOK_END) == 0+ return cbm_toml_remove_managed_block_owned(config_path, KIMI_HOOK_BEGIN, KIMI_HOOK_END,+ "[[hooks]]\n") == 0? CLI_OK: CLI_ERR;}diff --git a/src/cli/config_toml_edit.c b/src/cli/config_toml_edit.cindex 745bdda0d..56a7d60e1 100644--- a/src/cli/config_toml_edit.c+++ b/src/cli/config_toml_edit.c@@ -149,6 +149,10 @@ typedef struct {static int toml_managed_block_conflicts(const char *existing, size_t existing_len,size_t exclude_start, size_t exclude_end, const char *block,size_t block_len);+static int toml_managed_rewrite(const char *existing, size_t existing_len,+ const toml_line_t *begin_line, const toml_line_t *end_line,+ const char *begin_marker, const char *end_marker, const char *owned,+ size_t owned_len, int install, toml_buffer_t *output);static void toml_buffer_dispose(toml_buffer_t *buffer) {if (!buffer) {@@ -1067,15 +1071,20 @@ int cbm_toml_escape_basic_string(const char *input, char *out, size_t out_size)return TOML_EDIT_OK;}+static int toml_managed_body_valid(const char *body, const char *begin_marker,+ const char *end_marker, size_t *body_len) {+ return body && toml_bounded_length(body, TOML_EDIT_MAX_BYTES, body_len) == TOML_EDIT_OK &&+ toml_text_is_safe(body, *body_len, 1) &&+ !toml_contains_marker_line(body, *body_len, begin_marker, end_marker) &&+ toml_validate_lexical_strings(body, *body_len) == TOML_EDIT_OK;+}+int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marker,const char *end_marker, const char *block) {size_t block_len = 0U;if (!toml_valid_path(file_path) || !toml_valid_marker(begin_marker) ||- !toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0 || !block ||- toml_bounded_length(block, TOML_EDIT_MAX_BYTES, &block_len) != TOML_EDIT_OK ||- !toml_text_is_safe(block, block_len, 1) ||- toml_contains_marker_line(block, block_len, begin_marker, end_marker) ||- toml_validate_lexical_strings(block, block_len) != TOML_EDIT_OK) {+ !toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0 ||+ !toml_managed_body_valid(block, begin_marker, end_marker, &block_len)) {return TOML_EDIT_ERR;}@@ -1104,23 +1113,26 @@ int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marke}toml_buffer_t output = {0};- size_t prefix_len = has_pair ? begin_line.start : existing_len;- if (has_pair && prefix_len == 0U && existing_len >= 3U && (unsigned char)existing[0] == 0xefU &&- (unsigned char)existing[1] == 0xbbU && (unsigned char)existing[2] == 0xbfU) {- prefix_len = 3U;- }const char *newline = toml_newline_style(existing, existing_len);size_t payload_start = existing_len >= 3U && (unsigned char)existing[0] == 0xefU &&(unsigned char)existing[1] == 0xbbU &&(unsigned char)existing[2] == 0xbfU? 3U: 0U;- if (toml_buffer_append(&output, existing, prefix_len) != TOML_EDIT_OK ||- (!has_pair && existing_len > payload_start && existing[existing_len - 1] != '\n' &&- toml_buffer_append_cstr(&output, newline) != TOML_EDIT_OK) ||- toml_append_managed(&output, begin_marker, end_marker, block, newline) != TOML_EDIT_OK ||- (has_pair && toml_buffer_append(&output, existing + end_line.full_end,- existing_len - end_line.full_end) != TOML_EDIT_OK)) {+ int built = TOML_EDIT_OK;+ if (has_pair) {+ /* #2228: rebuild the span around the block, keeping what it holds that+ * is not ours instead of discarding the whole span. */+ built = toml_managed_rewrite(existing, existing_len, &begin_line, &end_line, begin_marker,+ end_marker, block, block_len, 1, &output);+ } else if (toml_buffer_append(&output, existing, existing_len) != TOML_EDIT_OK ||+ (existing_len > payload_start && existing[existing_len - 1] != '\n' &&+ toml_buffer_append_cstr(&output, newline) != TOML_EDIT_OK) ||+ toml_append_managed(&output, begin_marker, end_marker, block, newline) !=+ TOML_EDIT_OK) {+ built = TOML_EDIT_ERR;+ }+ if (built != TOML_EDIT_OK) {toml_buffer_dispose(&output);free(existing);return TOML_EDIT_ERR;@@ -1133,10 +1145,14 @@ int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_markereturn result;}-int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marker,- const char *end_marker) {+/* owned == NULL removes the whole span (the historical contract); otherwise+ * only the tables it declares go and the rest of the span stays (#2228). */+static int toml_remove_managed(const char *file_path, const char *begin_marker,+ const char *end_marker, const char *owned) {+ size_t owned_len = 0U;if (!toml_valid_path(file_path) || !toml_valid_marker(begin_marker) ||- !toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0) {+ !toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0 ||+ (owned && !toml_managed_body_valid(owned, begin_marker, end_marker, &owned_len))) {return TOML_EDIT_ERR;}char *existing = NULL;@@ -1187,9 +1203,14 @@ int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marke(unsigned char)existing[1] == 0xbbU && (unsigned char)existing[2] == 0xbfU) {prefix_len = 3U;}- if (toml_buffer_append(&output, existing, prefix_len) != TOML_EDIT_OK ||- toml_buffer_append(&output, existing + end_line.full_end,- existing_len - end_line.full_end) != TOML_EDIT_OK) {+ int built = owned ? toml_managed_rewrite(existing, existing_len, &begin_line, &end_line,+ begin_marker, end_marker, owned, owned_len, 0, &output)+ : toml_buffer_append(&output, existing, prefix_len) == TOML_EDIT_OK &&+ toml_buffer_append(&output, existing + end_line.full_end,+ existing_len - end_line.full_end) == TOML_EDIT_OK+ ? TOML_EDIT_OK+ : TOML_EDIT_ERR;+ if (built != TOML_EDIT_OK) {toml_buffer_dispose(&output);free(existing);return TOML_EDIT_ERR;@@ -1201,6 +1222,17 @@ int cbm_toml_remove_managed_block(const char *file_path, const char *begin_markereturn result;}+int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marker,+ const char *end_marker) {+ return toml_remove_managed(file_path, begin_marker, end_marker, NULL);+}++int cbm_toml_remove_managed_block_owned(const char *file_path, const char *begin_marker,+ const char *end_marker, const char *owned_tables) {+ return owned_tables ? toml_remove_managed(file_path, begin_marker, end_marker, owned_tables)+ : TOML_EDIT_ERR;+}+static int toml_hex_digit(unsigned char ch) {if (ch >= '0' && ch <= '9') {return ch - '0';@@ -1845,6 +1877,428 @@ static int toml_managed_block_conflicts(const char *existing, size_t existing_lereturn multiline_state == TOML_STRING_NONE ? TOML_EDIT_OK : TOML_EDIT_ERR;}+/* ── #2228: content found between the managed markers ─────────────────+ *+ * The span between our markers does not only hold what we wrote. A client+ * that appends tables at the end of the file (Codex Desktop does) puts them+ * INSIDE the markers whenever our closing marker is the last line, and users+ * add keys to our own table. Rewriting or removing the whole span deleted+ * all of that.+ *+ * The span is read as TOML sections -- the lines before its first header+ * (the lead) and one section per header -- and each is classified against+ * the tables the block declares:+ * owned a declared table; the k-th [[element]] of a declared array.+ * Keys the block writes are ours; every other key, comment and+ * blank line in it is the user's and stays in the table.+ * attached a sub-table of a declared table: part of our entry, kept with+ * it on install and removed with it on uninstall.+ * foreign anything else: moved byte for byte, in order, to just after+ * the closing marker (install) or left in place (removal).+ * lead moved above the opening marker, where it keeps the table it+ * belongs to. A block that itself starts with bare keys owns the+ * lead, which is then replaced exactly as before.+ * Whatever cannot be attributed safely is refused and the file is left+ * untouched: a second copy of a declared table, an undeclared [[element]]+ * of a declared array, a child of a declared array element, an unparsable+ * line in an owned table, a user key colliding with one the block writes, a+ * move that would hand the keys below the block to another table, or a+ * result whose tables would conflict with the block. */+#define TOML_MANAGED_MAX_TABLES 16U++enum {+ TOML_SPAN_LEAD = -1,+ TOML_SPAN_FOREIGN = 0,+ TOML_SPAN_OWNED = 1,+ TOML_SPAN_ATTACHED = 2,+};++typedef struct {+ size_t start;+ size_t body;+ size_t end;+ toml_header_t header;+} toml_section_t;++typedef struct {+ const char *data;+ size_t lead_end;+ size_t span_end;+ const char *owned;+ size_t owned_len;+ size_t owned_first;+} toml_managed_span_t;++/* End of the section whose body starts at pos: the next header line outside+ * a multiline string, or len. */+static int toml_section_end(const char *data, size_t pos, size_t len, size_t *end) {+ size_t cursor = pos;+ toml_line_t line;+ int multiline_state = TOML_STRING_NONE;+ while (toml_next_line(data, len, &cursor, &line)) {+ if (multiline_state == TOML_STRING_NONE) {+ toml_header_t header;+ if (toml_parse_header(data, &line, "", &header) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ int present = header.present;+ toml_header_dispose(&header);+ if (present) {+ *end = line.start;+ return TOML_EDIT_OK;+ }+ }+ if (toml_scan_line_strings(data, &line, &multiline_state) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ }+ *end = len;+ return multiline_state == TOML_STRING_NONE ? TOML_EDIT_OK : TOML_EDIT_ERR;+}++/* The section whose header line starts at pos. */+static int toml_section_at(const char *data, size_t pos, size_t len, toml_section_t *section) {+ memset(section, 0, sizeof(*section));+ section->start = pos;+ size_t cursor = pos;+ toml_line_t line;+ if (!toml_next_line(data, len, &cursor, &line) ||+ toml_parse_header(data, &line, "", §ion->header) != TOML_EDIT_OK ||+ !section->header.present ||+ toml_section_end(data, line.full_end, len, §ion->end) != TOML_EDIT_OK) {+ toml_header_dispose(§ion->header);+ return TOML_EDIT_ERR;+ }+ section->body = line.full_end;+ return TOML_EDIT_OK;+}++static int toml_lines_significant(const char *data, size_t start, size_t end) {+ size_t cursor = start;+ toml_line_t line;+ while (toml_next_line(data, end, &cursor, &line)) {+ if (!toml_line_is_blank_or_comment(data, &line)) {+ return 1;+ }+ }+ return 0;+}++/* Declared table `table` (1-based) of the block, or the number of declared+ * tables in *count when table is 0. */+static int toml_declared_table(const toml_managed_span_t *span, size_t table, size_t *count,+ toml_section_t *out) {+ size_t pos = span->owned_first;+ size_t index = 0U;+ while (pos < span->owned_len) {+ toml_section_t declared;+ if (++index > TOML_MANAGED_MAX_TABLES ||+ toml_section_at(span->owned, pos, span->owned_len, &declared) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ if (index == table) {+ *out = declared;+ return TOML_EDIT_OK;+ }+ pos = declared.end;+ toml_header_dispose(&declared.header);+ }+ if (count) {+ *count = index;+ }+ return table == 0U ? TOML_EDIT_OK : TOML_EDIT_ERR;+}++/* Classify one span header. seen[] marks the declared tables the span has+ * already supplied, so a second copy is refused instead of guessed at. */+static int toml_managed_classify(const toml_managed_span_t *span, const toml_header_t *header,+ unsigned char *seen, int *kind, size_t *table) {+ size_t exact = 0U;+ int exact_taken = 0;+ size_t parent = 0U;+ size_t parent_depth = 0U;+ int result = TOML_EDIT_OK;+ size_t pos = span->owned_first;+ for (size_t index = 1U; pos < span->owned_len && result == TOML_EDIT_OK; ++index) {+ toml_section_t declared;+ if (toml_section_at(span->owned, pos, span->owned_len, &declared) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ pos = declared.end;+ const toml_key_path_t *path = &declared.header.path;+ if (toml_key_path_equal(path, &header->path)) {+ if (declared.header.array != header->array) {+ result = TOML_EDIT_ERR;+ } else if (!seen[index] && exact == 0U) {+ exact = index;+ } else {+ exact_taken = 1;+ }+ } else if (toml_key_path_has_prefix(&header->path, path)) {+ if (declared.header.array) {+ result = TOML_EDIT_ERR;+ } else if (path->count > parent_depth) {+ parent = index;+ parent_depth = path->count;+ }+ }+ toml_header_dispose(&declared.header);+ }+ if (result != TOML_EDIT_OK || (exact == 0U && exact_taken)) {+ return TOML_EDIT_ERR;+ }+ if (exact != 0U) {+ seen[exact] = 1U;+ }+ *kind = exact != 0U ? TOML_SPAN_OWNED : parent != 0U ? TOML_SPAN_ATTACHED : TOML_SPAN_FOREIGN;+ *table = exact != 0U ? exact : parent;+ return TOML_EDIT_OK;+}++/* Sets *written when the declared table assigns key; a key that only shares+ * a dotted prefix with one it assigns would redefine it and is refused. */+static int toml_declared_writes_key(const toml_managed_span_t *span, const toml_section_t *declared,+ const toml_key_path_t *key, int *written) {+ *written = 0;+ size_t cursor = declared->body;+ toml_line_t line;+ int multiline_state = TOML_STRING_NONE;+ while (toml_next_line(span->owned, declared->end, &cursor, &line)) {+ if (multiline_state == TOML_STRING_NONE) {+ toml_assignment_t assignment;+ if (toml_parse_assignment(span->owned, &line, &assignment) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ int equal = assignment.present && toml_key_path_equal(&assignment.key, key);+ int collides = assignment.present && !equal &&+ (toml_key_path_has_prefix(&assignment.key, key) ||+ toml_key_path_has_prefix(key, &assignment.key));+ toml_assignment_dispose(&assignment);+ if (collides) {+ return TOML_EDIT_ERR;+ }+ *written |= equal;+ }+ if (toml_scan_line_strings(span->owned, &line, &multiline_state) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ }+ return TOML_EDIT_OK;+}++static size_t toml_line_first_char(const char *data, const toml_line_t *line) {+ size_t pos = line->start;+ while (pos < line->content_end && (data[pos] == ' ' || data[pos] == '\t')) {+ pos++;+ }+ return pos;+}++/* Is this line, outside any multiline string, one the user owns? Comments+ * are; an assignment is unless the declared table writes its key. */+static int toml_line_is_users(const toml_managed_span_t *span, const toml_section_t *declared,+ const toml_line_t *line, int *users) {+ if (span->data[toml_line_first_char(span->data, line)] == '#') {+ *users = 1;+ return TOML_EDIT_OK;+ }+ toml_assignment_t assignment;+ int written = 0;+ if (toml_parse_assignment(span->data, line, &assignment) != TOML_EDIT_OK ||+ !assignment.present ||+ toml_declared_writes_key(span, declared, &assignment.key, &written) != TOML_EDIT_OK) {+ toml_assignment_dispose(&assignment);+ return TOML_EDIT_ERR;+ }+ toml_assignment_dispose(&assignment);+ *users = !written;+ return TOML_EDIT_OK;+}++/* The lines of an owned section the block does not write, with the blank+ * lines between them; blank lines before a replaced key or at the end of the+ * section go with the section. */+static int toml_append_user_lines(const toml_managed_span_t *span, const toml_section_t *section,+ size_t table, toml_buffer_t *output) {+ toml_section_t declared;+ if (toml_declared_table(span, table, NULL, &declared) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ size_t cursor = section->body;+ toml_line_t line;+ int multiline_state = TOML_STRING_NONE;+ int keep = 0;+ size_t blank_start = SIZE_MAX;+ int result = TOML_EDIT_OK;+ while (result == TOML_EDIT_OK && toml_next_line(span->data, section->end, &cursor, &line)) {+ if (multiline_state == TOML_STRING_NONE) {+ if (toml_line_first_char(span->data, &line) == line.content_end) {+ blank_start = blank_start == SIZE_MAX ? line.start : blank_start;+ continue;+ }+ result = toml_line_is_users(span, &declared, &line, &keep);+ if (!keep) {+ blank_start = SIZE_MAX;+ }+ }+ if (result == TOML_EDIT_OK && keep) {+ size_t from = blank_start == SIZE_MAX ? line.start : blank_start;+ blank_start = SIZE_MAX;+ result = toml_buffer_append(output, span->data + from, line.full_end - from);+ }+ if (result == TOML_EDIT_OK &&+ toml_scan_line_strings(span->data, &line, &multiline_state) != TOML_EDIT_OK) {+ result = TOML_EDIT_ERR;+ }+ }+ toml_header_dispose(&declared.header);+ return result == TOML_EDIT_OK && multiline_state == TOML_STRING_NONE ? TOML_EDIT_OK+ : TOML_EDIT_ERR;+}++/* One pass over the span's tables in file order. Appends each section of+ * want_kind (and, unless foreign, of declared table want_table): foreign and+ * attached sections verbatim, an owned one as its user lines. Also reports+ * how many sections are foreign and the kind of the last one. */+static int toml_managed_span_pass(const toml_managed_span_t *span, int want_kind, size_t want_table,+ toml_buffer_t *output, size_t *foreign, int *last_kind) {+ unsigned char seen[TOML_MANAGED_MAX_TABLES + 1U] = {0};+ *foreign = 0U;+ *last_kind = TOML_SPAN_LEAD;+ size_t pos = span->lead_end;+ while (pos < span->span_end) {+ toml_section_t section;+ int kind = TOML_SPAN_FOREIGN;+ size_t table = 0U;+ if (toml_section_at(span->data, pos, span->span_end, §ion) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ int result = toml_managed_classify(span, §ion.header, seen, &kind, &table);+ toml_header_dispose(§ion.header);+ pos = section.end;+ *foreign += kind == TOML_SPAN_FOREIGN;+ *last_kind = kind;+ if (result == TOML_EDIT_OK && kind == want_kind &&+ (kind == TOML_SPAN_FOREIGN || table == want_table)) {+ result = kind == TOML_SPAN_OWNED+ ? toml_append_user_lines(span, §ion, table, output)+ : toml_buffer_append(output, span->data + section.start,+ section.end - section.start);+ }+ if (result != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ }+ return TOML_EDIT_OK;+}++/* The declared tables of an install, each followed by what the span keeps+ * for it: the user lines of its owned section, then its attached tables. */+static int toml_append_managed_tables(const toml_managed_span_t *span, size_t tables,+ const char *newline, toml_buffer_t *output) {+ size_t foreign = 0U;+ int last_kind = TOML_SPAN_LEAD;+ if (toml_append_normalized_text(output, span->owned, span->owned_first, newline) !=+ TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ for (size_t table = 1U; table <= tables; ++table) {+ toml_section_t declared;+ if (toml_declared_table(span, table, NULL, &declared) != TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ toml_header_dispose(&declared.header);+ if (toml_append_normalized_text(output, span->owned + declared.start,+ declared.end - declared.start, newline) != TOML_EDIT_OK ||+ (output->data[output->len - 1U] != '\n' &&+ toml_buffer_append_cstr(output, newline) != TOML_EDIT_OK) ||+ toml_managed_span_pass(span, TOML_SPAN_OWNED, table, output, &foreign, &last_kind) !=+ TOML_EDIT_OK ||+ toml_managed_span_pass(span, TOML_SPAN_ATTACHED, table, output, &foreign, &last_kind) !=+ TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ }+ return output->len == 0U || output->data[output->len - 1U] == '\n' ||+ toml_buffer_append_cstr(output, newline) == TOML_EDIT_OK+ ? TOML_EDIT_OK+ : TOML_EDIT_ERR;+}++/* Rebuild existing with its managed span rewritten around `owned` (install)+ * or removed (uninstall), keeping everything the span holds that is not+ * ours. `owned` is the block on install and the declaration of our tables on+ * removal. */+static int toml_managed_rewrite(const char *existing, size_t existing_len,+ const toml_line_t *begin_line, const toml_line_t *end_line,+ const char *begin_marker, const char *end_marker, const char *owned,+ size_t owned_len, int install, toml_buffer_t *output) {+ toml_managed_span_t span = {+ .data = existing,+ .span_end = end_line->start,+ .owned = owned,+ .owned_len = owned_len,+ };+ size_t tables = 0U;+ size_t tail_lead_end = existing_len;+ if (toml_section_end(owned, 0U, owned_len, &span.owned_first) != TOML_EDIT_OK ||+ toml_declared_table(&span, 0U, &tables, NULL) != TOML_EDIT_OK ||+ toml_section_end(existing, begin_line->full_end, span.span_end, &span.lead_end) !=+ TOML_EDIT_OK ||+ toml_section_end(existing, end_line->full_end, existing_len, &tail_lead_end) !=+ TOML_EDIT_OK) {+ return TOML_EDIT_ERR;+ }+ toml_buffer_t moved = {0};+ size_t foreign = 0U;+ int last_kind = TOML_SPAN_LEAD;+ if (toml_managed_span_pass(&span, TOML_SPAN_FOREIGN, 0U, &moved, &foreign, &last_kind) !=+ TOML_EDIT_OK ||+ (foreign != 0U && last_kind != TOML_SPAN_FOREIGN &&+ toml_lines_significant(existing, end_line->full_end, tail_lead_end))) {+ toml_buffer_dispose(&moved);+ return TOML_EDIT_ERR;+ }++ size_t prefix_len = begin_line->start;+ if (prefix_len == 0U && existing_len >= 3U && (unsigned char)existing[0] == 0xefU &&+ (unsigned char)existing[1] == 0xbbU && (unsigned char)existing[2] == 0xbfU) {+ prefix_len = 3U;+ }+ const char *newline = toml_newline_style(existing, existing_len);+ int keep_lead = !toml_lines_significant(owned, 0U, span.owned_first);+ size_t block_start = 0U;+ size_t block_end = 0U;+ int result = toml_buffer_append(output, existing, prefix_len) == TOML_EDIT_OK &&+ (!keep_lead ||+ toml_buffer_append(output, existing + begin_line->full_end,+ span.lead_end - begin_line->full_end) == TOML_EDIT_OK)+ ? TOML_EDIT_OK+ : TOML_EDIT_ERR;+ if (result == TOML_EDIT_OK && install) {+ block_start = output->len;+ result =+ toml_buffer_append_cstr(output, begin_marker) == TOML_EDIT_OK &&+ toml_buffer_append_cstr(output, newline) == TOML_EDIT_OK &&+ toml_append_managed_tables(&span, tables, newline, output) == TOML_EDIT_OK &&+ toml_buffer_append_cstr(output, end_marker) == TOML_EDIT_OK &&+ toml_buffer_append_cstr(output, newline) == TOML_EDIT_OK+ ? TOML_EDIT_OK+ : TOML_EDIT_ERR;+ block_end = output->len;+ }+ if (result == TOML_EDIT_OK &&+ (toml_buffer_append(output, moved.data, moved.len) != TOML_EDIT_OK ||+ toml_buffer_append(output, existing + end_line->full_end,+ existing_len - end_line->full_end) != TOML_EDIT_OK ||+ (install && toml_managed_block_conflicts(output->data, output->len, block_start, block_end,+ owned, owned_len) != TOML_EDIT_OK))) {+ result = TOML_EDIT_ERR;+ }+ toml_buffer_dispose(&moved);+ return result;+}+static int toml_finish_target_table(toml_target_table_t *current, toml_table_scan_t *result) {if (!current->active) {return TOML_EDIT_OK;diff --git a/src/cli/config_toml_edit.h b/src/cli/config_toml_edit.hindex 4e41a4d9c..616ed3e1d 100644--- a/src/cli/config_toml_edit.h+++ b/src/cli/config_toml_edit.h@@ -24,11 +24,21 @@ int cbm_toml_escape_basic_string(const char *input, char *out, size_t out_size);** Insert or replace one managed, line-delimited block. block is the body* between the two marker lines. Duplicate or unbalanced markers are rejected- * without changing the file. */+ * without changing the file. An existing span keeps what is not ours (#2228):+ * keys and comments the block does not write stay in the tables it declares,+ * with those tables' sub-tables; lines before the span's first table move+ * above the block and any other table moves, byte for byte and in order, to+ * just after it. Content whose ownership is ambiguous fails closed. */int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marker,const char *end_marker, const char *block);+/* Removes the whole span between the markers. */int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marker,const char *end_marker);+/* Removes the markers and only the tables owned_tables declares (e.g. the+ * block's header lines), with their keys and sub-tables; every other line of+ * the span stays in place. Ambiguous ownership fails closed (#2228). */+int cbm_toml_remove_managed_block_owned(const char *file_path, const char *begin_marker,+ const char *end_marker, const char *owned_tables);/* Remove one pre-marker codebase-memory-mcp table only when it has the known* historical schema: one owned command basename, optional empty args, and nodiff --git a/tests/test_cli.c b/tests/test_cli.cindex 4f95e9c43..bd94c57b9 100644--- a/tests/test_cli.c+++ b/tests/test_cli.c@@ -13420,6 +13420,81 @@ TEST(cli_upsert_codex_mcp_escapes_windows_path) {PASS();}+/* #2228: a 0.10.4 -> 0.11.0 upgrade deleted every table Codex Desktop had+ * appended between our markers (the closing marker stayed the file's last+ * line) and the startup_timeout_sec the user had added to our table. Install+ * must keep all of it; uninstall must remove only our table. */+TEST(cli_codex_mcp_keeps_foreign_tables_in_managed_region_issue2228) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-codex-2228-XXXXXX");+ if (!cbm_mkdtemp(tmpdir))+ FAIL("cbm_mkdtemp failed");+ char configpath[512];+ snprintf(configpath, sizeof(configpath), "%s/config.toml", tmpdir);+#define CLI_2228_PREFIX \+ "model = \"gpt-5\"\n\n[mcp_servers.codegraph]\ncommand = \"codegraph\"\n" \+ "args = [\"serve\", \"--mcp\"]\n"+#define CLI_2228_FOREIGN \+ "[mcp_servers.node_repl]\nargs = []\n" \+ "command = \"/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node_repl\"\n" \+ "startup_timeout_sec = 120\n\n" \+ "[mcp_servers.node_repl.env]\nNODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = \"5000\"\n\n" \+ "[desktop]\nfollowUpQueueMode = \"steer\"\n\n" \+ "[marketplaces.openai-codex]\nsource_type = \"git\"\n" \+ "source = \"https://github.com/openai/codex-plugin-cc.git\"\n"+ const char *before = CLI_2228_PREFIX "# >>> codebase-memory-mcp MCP >>>\n"+ "[mcp_servers.codebase-memory-mcp]\n"+ "command = \"/old/codebase-memory-mcp\"\n"+ "args = []\n"+ "startup_timeout_sec = 90\n\n" CLI_2228_FOREIGN+ "# <<< codebase-memory-mcp MCP <<<\n";+ const char *installed = CLI_2228_PREFIX "# >>> codebase-memory-mcp MCP >>>\n"+ "[mcp_servers.codebase-memory-mcp]\n"+ "command = \"/new/codebase-memory-mcp\"\n"+ "args = []\n"+ "env_vars = [\"CBM_CACHE_DIR\", \"CBM_RUNTIME_DIR\"]\n"+ "startup_timeout_sec = 90\n"+ "# <<< codebase-memory-mcp MCP <<<\n" CLI_2228_FOREIGN;+ const char *uninstalled = CLI_2228_PREFIX CLI_2228_FOREIGN;+#undef CLI_2228_PREFIX+#undef CLI_2228_FOREIGN++ write_test_file(configpath, before);+ int install_rc = cbm_upsert_codex_mcp("/new/codebase-memory-mcp", configpath);+ char *after_install = read_test_file_alloc(configpath);+ int reinstall_rc = cbm_upsert_codex_mcp("/new/codebase-memory-mcp", configpath);+ char *after_reinstall = read_test_file_alloc(configpath);+ int remove_rc = cbm_remove_codex_mcp(configpath);+ char *after_remove = read_test_file_alloc(configpath);+ /* Uninstall straight from the reported state: the foreign tables are+ * still inside the markers there. */+ write_test_file(configpath, before);+ int direct_remove_rc = cbm_remove_codex_mcp(configpath);+ char *after_direct_remove = read_test_file_alloc(configpath);+ bool install_kept = install_rc == 0 && after_install && strcmp(after_install, installed) == 0;+ bool reinstall_stable =+ reinstall_rc == 0 && after_reinstall && strcmp(after_reinstall, installed) == 0;+ bool remove_kept = remove_rc == 0 && after_remove && strcmp(after_remove, uninstalled) == 0 &&+ direct_remove_rc == 0 && after_direct_remove &&+ strcmp(after_direct_remove, uninstalled) == 0;+ if (!install_kept && after_install)+ printf(" install produced:\n%s\n", after_install);+ if (!remove_kept && after_direct_remove)+ printf(" uninstall produced:\n%s\n", after_direct_remove);+ free(after_install);+ free(after_reinstall);+ free(after_remove);+ free(after_direct_remove);+ test_rmdir_r(tmpdir);+ if (!install_kept)+ FAIL("Codex install must keep foreign tables and user keys found between its markers");+ if (!reinstall_stable)+ FAIL("Codex reinstall must be byte-identical once foreign tables sit outside the block");+ if (!remove_kept)+ FAIL("Codex uninstall must remove only its own table and keep foreign tables");+ PASS();+}+TEST(cli_upsert_codex_mcp_existing) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-codex-XXXXXX");@@ -16554,6 +16629,7 @@ SUITE(cli) {/* Codex MCP config upsert (3 tests — group B) */RUN_TEST(cli_upsert_codex_mcp_fresh);RUN_TEST(cli_upsert_codex_mcp_escapes_windows_path);+ RUN_TEST(cli_codex_mcp_keeps_foreign_tables_in_managed_region_issue2228);RUN_TEST(cli_upsert_codex_mcp_existing);RUN_TEST(cli_upsert_codex_mcp_replace);RUN_TEST(cli_codex_legacy_migration_ignores_header_text_in_multiline_string);diff --git a/tests/test_config_toml_edit.c b/tests/test_config_toml_edit.cindex cc64fd576..7a06421e8 100644--- a/tests/test_config_toml_edit.c+++ b/tests/test_config_toml_edit.c@@ -836,6 +836,181 @@ TEST(config_toml_managed_unbalanced_duplicate_fail_closed) {PASS();}+/* #2228: the region between the managed markers is not only ours. Codex+ * Desktop appended its own tables below a block that ended config.toml, the+ * closing marker stayed the last line, and [mcp_servers.node_repl], [desktop]+ * and the marketplaces ended up inside the markers. The next install rewrote+ * the whole region and deleted them, together with a key the user had added+ * to our own table. */+static const char *CTE_MCP_BEGIN = "# >>> codebase-memory-mcp MCP >>>";+static const char *CTE_MCP_END = "# <<< codebase-memory-mcp MCP <<<";+static const char *CTE_MCP_DECLARATION = "[mcp_servers.codebase-memory-mcp]\n";+#define CTE_MCP_BEGIN_LINE "# >>> codebase-memory-mcp MCP >>>\n"+#define CTE_MCP_END_LINE "# <<< codebase-memory-mcp MCP <<<\n"+#define CTE_MCP_PREFIX \+ "model = \"gpt-5\"\n\n[mcp_servers.codegraph]\ncommand = \"codegraph\"\n" \+ "args = [\"serve\", \"--mcp\"]\n"+/* The 0.10.4 shape of our block: no env_vars yet. */+#define CTE_MCP_OLD_TABLE \+ "[mcp_servers.codebase-memory-mcp]\ncommand = \"/old/codebase-memory-mcp\"\nargs = []\n"+#define CTE_MCP_NEW_TABLE \+ "[mcp_servers.codebase-memory-mcp]\ncommand = \"/new/codebase-memory-mcp\"\nargs = []\n" \+ "env_vars = [\"CBM_CACHE_DIR\", \"CBM_RUNTIME_DIR\"]\n"+#define CTE_MCP_USER_LINES "# raised for a 1.5 GB index\nstartup_timeout_sec = 90\n"+#define CTE_MCP_FOREIGN \+ "[mcp_servers.node_repl]\nargs = []\n" \+ "command = \"/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node_repl\"\n" \+ "startup_timeout_sec = 120\n\n" \+ "[mcp_servers.node_repl.env]\nNODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = \"5000\"\n\n" \+ "[desktop]\nfollowUpQueueMode = \"steer\"\n\n" \+ "[marketplaces.openai-codex]\nsource_type = \"git\"\n" \+ "source = \"https://github.com/openai/codex-plugin-cc.git\"\n"+#define CTE_MCP_ISSUE2228 \+ CTE_MCP_PREFIX CTE_MCP_BEGIN_LINE CTE_MCP_OLD_TABLE CTE_MCP_USER_LINES \+ "\n" CTE_MCP_FOREIGN CTE_MCP_END_LINE+#define CTE_MCP_LEAD_AND_CHILD \+ CTE_MCP_PREFIX CTE_MCP_BEGIN_LINE \+ "# pinned by hand\n" CTE_MCP_OLD_TABLE \+ "\n[mcp_servers.codebase-memory-mcp.env]\nRUST_LOG = \"warn\"\n\n" \+ "[notice]\nhide_full_access_warning = true\n" CTE_MCP_END_LINE \+ "\n[profiles.fast]\nmodel = \"o4-mini\"\n"++TEST(config_toml_managed_keeps_foreign_tables_and_user_keys_issue2228) {+ char dir[CTE_PATH_CAP];+ char path[CTE_PATH_CAP];+ char actual[CTE_FILE_CAP];+ /* Our table is rewritten in the current shape and keeps the user's comment+ * and key; the foreign tables move, byte for byte and in order, to just+ * after the block, so from now on the markers bracket only our table. */+ const char *expected = CTE_MCP_PREFIX CTE_MCP_BEGIN_LINE CTE_MCP_NEW_TABLE CTE_MCP_USER_LINES+ CTE_MCP_END_LINE CTE_MCP_FOREIGN;+ ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);+ ASSERT_EQ(th_write_file(path, CTE_MCP_ISSUE2228), 0);+ ASSERT_EQ(cbm_toml_upsert_managed_block(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_NEW_TABLE),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, expected);+ ASSERT_EQ(cbm_toml_upsert_managed_block(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_NEW_TABLE),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, expected);+ th_cleanup(dir);+ PASS();+}++/* Control: without foreign content the output is exactly what the whole-region+ * rewrite always produced — unchanged for the current shape, the new shape for+ * an old one. */+TEST(config_toml_managed_control_without_foreign_content_issue2228) {+ char dir[CTE_PATH_CAP];+ char path[CTE_PATH_CAP];+ char actual[CTE_FILE_CAP];+ const char *current = CTE_MCP_PREFIX CTE_MCP_BEGIN_LINE CTE_MCP_NEW_TABLE CTE_MCP_END_LINE+ "\n[profiles.fast]\nmodel = \"o4-mini\"\n";+ const char *old = CTE_MCP_PREFIX CTE_MCP_BEGIN_LINE CTE_MCP_OLD_TABLE CTE_MCP_END_LINE+ "\n[profiles.fast]\nmodel = \"o4-mini\"\n";+ ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);+ ASSERT_EQ(th_write_file(path, current), 0);+ ASSERT_EQ(cbm_toml_upsert_managed_block(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_NEW_TABLE),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, current);+ ASSERT_EQ(th_write_file(path, old), 0);+ ASSERT_EQ(cbm_toml_upsert_managed_block(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_NEW_TABLE),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, current);+ th_cleanup(dir);+ PASS();+}++/* A comment above our header belongs to no table of ours and moves above the+ * block; a sub-table of our table is part of our server entry and stays with+ * it (outside the markers it would collide with the next install). */+TEST(config_toml_managed_keeps_lead_and_owned_subtable_issue2228) {+ char dir[CTE_PATH_CAP];+ char path[CTE_PATH_CAP];+ char actual[CTE_FILE_CAP];+ const char *expected = CTE_MCP_PREFIX+ "# pinned by hand\n" CTE_MCP_BEGIN_LINE CTE_MCP_NEW_TABLE+ "[mcp_servers.codebase-memory-mcp.env]\nRUST_LOG = \"warn\"\n\n" CTE_MCP_END_LINE+ "[notice]\nhide_full_access_warning = true\n"+ "\n[profiles.fast]\nmodel = \"o4-mini\"\n";+ ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);+ ASSERT_EQ(th_write_file(path, CTE_MCP_LEAD_AND_CHILD), 0);+ ASSERT_EQ(cbm_toml_upsert_managed_block(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_NEW_TABLE),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, expected);+ ASSERT_EQ(cbm_toml_upsert_managed_block(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_NEW_TABLE),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, expected);+ th_cleanup(dir);+ PASS();+}++/* Where ownership cannot be decided, nothing is written: a second [[hooks]]+ * element we did not declare, or a move that would hand the keys below the+ * block to a different table. */+TEST(config_toml_managed_ambiguous_foreign_content_fails_closed_issue2228) {+ char dir[CTE_PATH_CAP];+ char path[CTE_PATH_CAP];+ const char *hook = "[[hooks]]\nevent = \"UserPromptSubmit\"\n"+ "command = \"cbm hook-augment --dialect kimi\"\ntimeout = 5\n";+ const char *extra_element = "# BEGIN codebase-memory-mcp\n"+ "[[hooks]]\nevent = \"UserPromptSubmit\"\n"+ "command = \"cbm hook-augment --dialect kimi\"\ntimeout = 5\n\n"+ "[[hooks]]\nevent = \"Stop\"\ncommand = \"notify-send done\"\n"+ "# END codebase-memory-mcp\n";+ const char *rescoped_tail = "# BEGIN codebase-memory-mcp\n"+ "[notice]\nhide_full_access_warning = true\n\n"+ "[[hooks]]\nevent = \"UserPromptSubmit\"\n"+ "command = \"cbm hook-augment --dialect kimi\"\ntimeout = 5\n"+ "# END codebase-memory-mcp\n"+ "matcher = \"user\"\n";+ ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);+ ASSERT(cte_assert_unchanged_after_managed_upsert(path, extra_element, hook));+ ASSERT(cte_assert_unchanged_after_managed_upsert(path, rescoped_tail, hook));+ th_cleanup(dir);+ PASS();+}++/* Uninstall takes only what we declare -- our table with its keys and+ * sub-tables -- and leaves everything else between the markers in place. */+TEST(config_toml_managed_remove_owned_keeps_foreign_content_issue2228) {+ char dir[CTE_PATH_CAP];+ char path[CTE_PATH_CAP];+ char actual[CTE_FILE_CAP];+ const char *extra_element = "keep = true\n# BEGIN codebase-memory-mcp\n"+ "[[hooks]]\nevent = \"UserPromptSubmit\"\n\n"+ "[[hooks]]\nevent = \"Stop\"\n"+ "# END codebase-memory-mcp\n";+ ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);+ ASSERT_EQ(th_write_file(path, CTE_MCP_ISSUE2228), 0);+ ASSERT_EQ(+ cbm_toml_remove_managed_block_owned(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_DECLARATION),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, CTE_MCP_PREFIX CTE_MCP_FOREIGN);++ ASSERT_EQ(th_write_file(path, CTE_MCP_LEAD_AND_CHILD), 0);+ ASSERT_EQ(+ cbm_toml_remove_managed_block_owned(path, CTE_MCP_BEGIN, CTE_MCP_END, CTE_MCP_DECLARATION),+ 0);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, CTE_MCP_PREFIX "# pinned by hand\n"+ "[notice]\nhide_full_access_warning = true\n"+ "\n[profiles.fast]\nmodel = \"o4-mini\"\n");++ ASSERT_EQ(th_write_file(path, extra_element), 0);+ ASSERT_EQ(cbm_toml_remove_managed_block_owned(path, CTE_BEGIN, CTE_END, "[[hooks]]\n"), -1);+ ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);+ ASSERT_STR_EQ(actual, extra_element);+ th_cleanup(dir);+ PASS();+}+TEST(config_toml_vibe_insert_among_other_tables) {char dir[CTE_PATH_CAP];char path[CTE_PATH_CAP];@@ -1490,6 +1665,11 @@ SUITE(config_toml_edit) {RUN_TEST(config_toml_managed_remove);RUN_TEST(config_toml_managed_idempotent);RUN_TEST(config_toml_managed_unbalanced_duplicate_fail_closed);+ RUN_TEST(config_toml_managed_keeps_foreign_tables_and_user_keys_issue2228);+ RUN_TEST(config_toml_managed_control_without_foreign_content_issue2228);+ RUN_TEST(config_toml_managed_keeps_lead_and_owned_subtable_issue2228);+ RUN_TEST(config_toml_managed_ambiguous_foreign_content_fails_closed_issue2228);+ RUN_TEST(config_toml_managed_remove_owned_keeps_foreign_content_issue2228);RUN_TEST(config_toml_vibe_insert_among_other_tables);RUN_TEST(config_toml_vibe_replace_target_preserves_comments_tables);RUN_TEST(config_toml_vibe_owned_table_installs_idempotently_and_removes_exact_state);