| 1300 | } |
| 1301 | |
| 1302 | static int agent_continue_edit(const char *config_path, const char *binary_path, bool remove) { |
| 1303 | char *document = NULL; |
| 1304 | size_t length = 0U; |
| 1305 | if (cbm_json_like_read_document(config_path, &document, &length) != 0 || !document) { |
| 1306 | free(document); |
| 1307 | return CBM_AGENT_EDIT_NOT_APPLICABLE; |
| 1308 | } |
| 1309 | char *quoted = NULL; |
| 1310 | if (cbm_yaml_encode_double_quoted_scalar(binary_path, "ed) != 0) { |
| 1311 | free(document); |
| 1312 | return CBM_AGENT_EDIT_ERROR; |
| 1313 | } |
| 1314 | const char *eol = strstr(document, "\r\n") ? "\r\n" : "\n"; |
| 1315 | size_t canonical_size = strlen(quoted) + strlen(eol) * 3U + 96U; |
| 1316 | char *canonical = (char *)malloc(canonical_size); |
| 1317 | if (!canonical) { |
| 1318 | free(quoted); |
| 1319 | free(document); |
| 1320 | return CBM_AGENT_EDIT_ERROR; |
| 1321 | } |
| 1322 | int canonical_written = snprintf(canonical, canonical_size, |
| 1323 | " - name: codebase-memory-mcp%s command: %s%s" |
| 1324 | " args: []%s", |
| 1325 | eol, quoted, eol, eol); |
| 1326 | free(quoted); |
| 1327 | if (canonical_written < 0 || (size_t)canonical_written >= canonical_size) { |
| 1328 | free(canonical); |
| 1329 | free(document); |
| 1330 | return CBM_AGENT_EDIT_ERROR; |
| 1331 | } |
| 1332 | |
| 1333 | size_t section_start = SIZE_MAX; |
| 1334 | size_t section_body = SIZE_MAX; |
| 1335 | size_t section_end = length; |
| 1336 | size_t sections = 0U; |
| 1337 | bool invalid_section = false; |
| 1338 | size_t cursor = 0U; |
| 1339 | while (cursor < length) { |
| 1340 | size_t line_end = 0U; |
| 1341 | size_t next = agent_next_line(document, length, cursor, &line_end); |
| 1342 | size_t indent = agent_line_indent(document, cursor, line_end); |
| 1343 | bool blank_or_comment = cursor + indent >= line_end || document[cursor + indent] == '#'; |
| 1344 | bool empty_section_value = false; |
| 1345 | if (indent == 0U && agent_yaml_top_level_key(document, cursor, line_end, "mcpServers", |
| 1346 | &empty_section_value)) { |
| 1347 | sections++; |
| 1348 | section_start = cursor; |
| 1349 | section_body = next; |
| 1350 | section_end = length; |
| 1351 | invalid_section = invalid_section || !empty_section_value; |
| 1352 | } else if (sections == 1U && section_body != SIZE_MAX && cursor >= section_body && |
| 1353 | indent == 0U && !blank_or_comment) { |
| 1354 | section_end = cursor; |
| 1355 | section_body = SIZE_MAX; |
| 1356 | } |
| 1357 | cursor = next; |
| 1358 | } |
| 1359 | if (sections > 1U || invalid_section) { |
no test coverage detected