Skip to content

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.

fix(foundation): properly escape JSON control characters as \u00XX

Saurav Kumarfdcafbb53f1f
diff --git a/src/foundation/str_util.c b/src/foundation/str_util.c
index 6275ab592..26542e927 100644
--- a/src/foundation/str_util.c
+++ b/src/foundation/str_util.c
@@ -6,6 +6,7 @@
#include "foundation/constants.h"
#include <string.h>
#include <ctype.h>
+#include <stdio.h>
enum {
JSON_ESC_LEN = 2, /* escaped char takes 2 bytes (backslash + char) */
@@ -328,8 +329,11 @@ int cbm_json_escape(char *buf, int bufsize, const char *src) {
buf[pos++] = '\\';
buf[pos++] = 't';
} else if (c < JSON_CTRL_LIMIT) {
- /* Other control chars: skip */
- continue;
+ /* Other control chars: escape as \u00XX */
+ if (pos + 6 > bufsize - JSON_NUL_RESERVE) {
+ break;
+ }
+ pos += snprintf(buf + pos, 7, "\\u%04x", c);
} else {
buf[pos++] = (char)c;
}
diff --git a/src/git/git_context.c b/src/git/git_context.c
index 5f27b9f20..99ae17cf3 100644
--- a/src/git/git_context.c
+++ b/src/git/git_context.c
@@ -316,7 +316,7 @@ static int json_escaped_len(const char *src) {
if (c == '"' || c == '\\' || c == '\n' || c == '\r' || c == '\t') {
len += 2;
} else if (c < 0x20) {
- continue;
+ len += 6; /* \u00XX */
} else {
len++;
}
diff --git a/tests/test_str_util.c b/tests/test_str_util.c
index d153a0987..cd6f54210 100644
--- a/tests/test_str_util.c
+++ b/tests/test_str_util.c
@@ -424,6 +424,18 @@ TEST(validate_shell_arg_spaces) {
PASS();
}
+/* ── JSON Escaping tests ──────────────────────────────────────── */
+
+TEST(json_escape_control_chars) {
+ char buf[64];
+ const char *input = "A\x01"
+ "B\n";
+ int len = cbm_json_escape(buf, sizeof(buf), input);
+ ASSERT_STR_EQ(buf, "A\\u0001B\\n");
+ ASSERT_EQ(len, 10);
+ PASS();
+}
+
/* ── SNPRINTF_APPEND tests ────────────────────────────────────── */
TEST(snprintf_append_basic) {
@@ -533,6 +545,8 @@ SUITE(str_util) {
RUN_TEST(validate_shell_arg_backslash);
RUN_TEST(validate_shell_arg_empty);
RUN_TEST(validate_shell_arg_spaces);
+ /* JSON Escaping */
+ RUN_TEST(json_escape_control_chars);
/* SNPRINTF_APPEND */
RUN_TEST(snprintf_append_basic);
RUN_TEST(snprintf_append_fills_exactly);