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
feat(mcp): splice ADR sections instead of rebuilding the document
Martin Vogeld013555d28f6
diff --git a/README.md b/README.mdindex 3c99104e5..271773f45 100644--- a/README.md+++ b/README.md@@ -666,9 +666,11 @@ JSON arguments can also be piped on stdin, for tools that take arguments. A tool| `get_code_snippet` | Read source code for a function by qualified name. || `get_architecture` | Codebase overview: languages, packages, routes, hotspots, clusters, ADR. || `search_code` | Grep-like text search within indexed project files. |-| `manage_adr` | CRUD for Architecture Decision Records (`get` reads, `update` replaces the whole document, `set_sections` rewrites only the named sections, `sections` lists headings). Query modes do not wait behind a same-project reindex; writes remain serialized. |+| `manage_adr` | CRUD for Architecture Decision Records (`get` reads, `update` replaces the whole document, `set_sections` rewrites only the named sections and leaves every other byte untouched, `sections` lists headings). Query modes do not wait behind a same-project reindex; writes remain serialized. || `ingest_traces` | Ingest runtime traces to validate HTTP_CALLS edges. |+`manage_adr(mode='set_sections')` writes one or more sections by name and splices them into the stored document, so text outside the named sections — including a preamble, code fences and section ordering — is preserved byte-for-byte. Any `## Heading` works, not just the conventional PURPOSE / STACK / ARCHITECTURE / PATTERNS / TRADEOFFS / PHILOSOPHY set; names match exactly, including case. Writing the same section twice is a no-op, so a retry after a lost response cannot duplicate content.+`manage_adr` query modes (`get` and `sections`) use the server's cached query store so they can proceed while a same-project reindex is running. If another process publishes a replacement store during reindexing, they can return the pre-publication ADR until idle eviction refreshes that cache. Updates remain serialized through the project mutation guard.## Graph Data Modeldiff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex f07ab1f33..67df96831 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -713,12 +713,11 @@ static const tool_def_t TOOLS[] = {"document byte-identical, so retrying after a lost response is safe); sections only lists ""existing headings\"},\"content\":{\"type\":\"string\",\"description\":\"Complete replacement ""document required by update\"},\"section_updates\":{\"type\":\"object\",\"description\":"- "\"Required by set_sections: section name -> new body for that section. Only the six "- "canonical sections exist; any other name is rejected.\",\"properties\":{"- "\"PURPOSE\":{\"type\":\"string\"},\"STACK\":{\"type\":\"string\"},"- "\"ARCHITECTURE\":{\"type\":\"string\"},\"PATTERNS\":{\"type\":\"string\"},"- "\"TRADEOFFS\":{\"type\":\"string\"},\"PHILOSOPHY\":{\"type\":\"string\"}},"- "\"additionalProperties\":false}},\"additionalProperties\":false,"+ "\"Required by set_sections: section name -> new body for that section. Any heading name "+ "works, so a new entry can be added under its own heading; PURPOSE, STACK, ARCHITECTURE, "+ "PATTERNS, TRADEOFFS and PHILOSOPHY are the conventional ones. Names match exactly, "+ "including case, so 'Purpose' and 'PURPOSE' are different sections.\","+ "\"additionalProperties\":{\"type\":\"string\"}}},\"additionalProperties\":false,""\"required\":[\"project\"]}"},{"ingest_traces", "Ingest traces", "Ingest runtime traces to enhance the knowledge graph",@@ -11763,31 +11762,33 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {/* ── manage_adr ───────────────────────────────────────────────── */-/* ADR "sections" mode: list markdown headers ('#'-prefixed lines) from the- * ADR content string. */+typedef struct {+ yyjson_mut_doc *doc;+ yyjson_mut_val *arr;+} adr_sections_ctx_t;++static void adr_sections_cb(void *ctx, const cbm_adr_heading_t *h) {+ adr_sections_ctx_t *c = (adr_sections_ctx_t *)ctx;+ char hdr[CBM_SZ_1K];+ snprintf(hdr, sizeof(hdr), "## %.*s", h->name_len, h->name);+ yyjson_mut_arr_add_strcpy(c->doc, c->arr, hdr);+}++/* ADR "sections" mode: list the section headings of the ADR.+ *+ * This uses cbm_adr_scan_headings(), the SAME classifier the section-write+ * path splices with. It used to list any '#'-prefixed line, so a '## Foo' in+ * prose — or inside a fenced code block — was reported as a section that no+ * write could target. Two components disagreeing about what a section is was+ * how a section write came to be able to destroy one. */static void adr_list_sections_from_content(yyjson_mut_doc *doc, yyjson_mut_val *root_obj,const char *content) {yyjson_mut_val *sections = yyjson_mut_arr(doc);- const char *p = content;- while (p && *p) {- const char *eol = strchr(p, '\n');- size_t linelen = eol ? (size_t)(eol - p) : strlen(p);- while (linelen > 0 && p[linelen - SKIP_ONE] == '\r') {- linelen--;- }- if (linelen > 0 && p[0] == '#') {- char hdr[CBM_SZ_1K];- if (linelen >= sizeof(hdr)) {- linelen = sizeof(hdr) - SKIP_ONE;- }- memcpy(hdr, p, linelen);- hdr[linelen] = '\0';- yyjson_mut_arr_add_strcpy(doc, sections, hdr);- }- if (!eol) {- break;- }- p = eol + SKIP_ONE;+ adr_sections_ctx_t ctx = {doc, sections};+ if (content && cbm_adr_scan_headings(content, adr_sections_cb, &ctx) != CBM_STORE_OK) {+ /* The ambiguity that refuses a section write is reported here too,+ * rather than answering with a heading list that is quietly partial. */+ yyjson_mut_obj_add_str(doc, root_obj, "sections_status", "unterminated_code_fence");}yyjson_mut_obj_add_val(doc, root_obj, "sections", sections);}@@ -12011,12 +12012,12 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {char section_key_err[CBM_SZ_256] = "";if (set_sections_mode) {updates = adr_parse_section_updates(args);- /* Only the six canonical names are writable, and that is a correctness- * constraint rather than a house style: adr_try_section_header() parses- * ONLY canonical headers, so a '## FOO' written here would be read back- * as body text of the section above it and a second identical write- * would append a duplicate — destroying exactly the idempotence this- * mode exists to provide. */+ /* Any heading name is writable — the canonical six are a convention,+ * not a privilege. What is still refused is a name that could not+ * round-trip through a "## NAME" line (empty, '#'-leading, newline- or+ * edge-whitespace-bearing, over-long): such a name would scan back as+ * a different heading or as none, so a second identical write would+ * append a duplicate instead of being a no-op. */if (!updates.status && cbm_adr_validate_section_keys((const char **)updates.keys, updates.count, section_key_err,(int)sizeof(section_key_err)) != CBM_STORE_OK) {diff --git a/src/store/store.c b/src/store/store.cindex e8bc8e5f4..dd97ef2d8 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -8708,47 +8708,324 @@ int cbm_adr_validate_content(const char *content, char *errbuf, int errbuf_size)return CBM_STORE_OK;}-int cbm_adr_validate_section_keys(const char **keys, int count, char *errbuf, int errbuf_size) {- char invalid[CBM_SZ_256] = "";- int ilen = 0;- int ninvalid = 0;+/* ── ADR heading scanning and splicing ──────────────────────────── */- /* Collect and sort invalid keys */- const char *inv_keys[ST_MAX_SECTIONS];- int inv_n = 0;- for (int i = 0; i < count; i++) {- if (!is_canonical_section(keys[i])) {- if (inv_n < ST_BUF_16) {- inv_keys[inv_n++] = keys[i];+/* Length of a code-fence run (``` or ~~~, after at most three spaces of+ * indent), or 0 when the line does not open or close a fence. */+static int adr_fence_run(const char *line, int line_len, char *ch_out) {+ int i = 0;+ while (i < line_len && i < ST_HEADER_PREFIX && line[i] == ' ') {+ i++;+ }+ if (i >= line_len || (line[i] != '`' && line[i] != '~')) {+ return 0;+ }+ char c = line[i];+ int n = 0;+ while (i + n < line_len && line[i + n] == c) {+ n++;+ }+ if (n < ST_HEADER_PREFIX) {+ return 0;+ }+ *ch_out = c;+ return n;+}++/* True when the line is a closing fence for an open run of `open_n` `open_ch`:+ * same character, at least as long, and nothing but whitespace after it. */+static bool adr_fence_closes(const char *line, int line_len, char open_ch, int open_n) {+ char ch = 0;+ int n = adr_fence_run(line, line_len, &ch);+ if (n == 0 || ch != open_ch || n < open_n) {+ return false;+ }+ int i = 0;+ while (i < line_len && line[i] != open_ch) {+ i++;+ }+ i += n;+ while (i < line_len) {+ if (line[i] != ' ' && line[i] != '\t' && line[i] != '\r') {+ return false;+ }+ i++;+ }+ return true;+}++/* Name length of a "## NAME" heading line, or 0 when it is not a heading.+ * "###" fails on the third '#', so deeper markdown headings are body text. */+static int adr_heading_name_len(const char *line, int line_len) {+ if (line_len <= ST_HEADER_PREFIX || line[0] != '#' || line[SKIP_ONE] != '#' ||+ line[PAIR_LEN] != ' ') {+ return 0;+ }+ int len = line_len - ST_HEADER_PREFIX;+ const char *name = line + ST_HEADER_PREFIX;+ while (len > 0 && (name[len - SKIP_ONE] == ' ' || name[len - SKIP_ONE] == '\t' ||+ name[len - SKIP_ONE] == '\r')) {+ len--;+ }+ /* A leading space would not survive a render/scan round-trip. */+ if (len == 0 || name[0] == ' ' || name[0] == '\t') {+ return 0;+ }+ return len;+}++/* True when the document leaves a code fence open. Such a document cannot be+ * spliced: every heading after the opener is hidden, so an update would append+ * a duplicate heading instead of replacing the existing one. */+static bool adr_has_unterminated_fence(const char *content) {+ const char *p = content;+ bool in_fence = false;+ char fence_ch = 0;+ int fence_n = 0;+ while (p && *p) {+ const char *eol = strchr(p, '\n');+ int line_len = eol ? (int)(eol - p) : (int)strlen(p);+ if (in_fence) {+ if (adr_fence_closes(p, line_len, fence_ch, fence_n)) {+ in_fence = false;+ }+ } else {+ char ch = 0;+ int n = adr_fence_run(p, line_len, &ch);+ if (n > 0) {+ in_fence = true;+ fence_ch = ch;+ fence_n = n;}}+ if (!eol) {+ break;+ }+ p = eol + SKIP_ONE;}- /* Sort alphabetically */- for (int i = SKIP_ONE; i < inv_n; i++) {- int j = i;- while (j > 0 && strcmp(inv_keys[j], inv_keys[j - SKIP_ONE]) < 0) {- const char *tmp = inv_keys[j];- inv_keys[j] = inv_keys[j - SKIP_ONE];- inv_keys[j - SKIP_ONE] = tmp;- j--;+ return in_fence;+}++int cbm_adr_scan_headings(const char *content, void (*cb)(void *ctx, const cbm_adr_heading_t *h),+ void *ctx) {+ if (!content || !cb) {+ return content ? CBM_STORE_ERR : CBM_STORE_OK;+ }+ if (adr_has_unterminated_fence(content)) {+ return CBM_STORE_ERR;+ }++ cbm_adr_heading_t pending;+ memset(&pending, 0, sizeof(pending));+ bool have_pending = false;+ bool in_fence = false;+ char fence_ch = 0;+ int fence_n = 0;++ const char *p = content;+ while (*p) {+ const char *eol = strchr(p, '\n');+ int line_len = eol ? (int)(eol - p) : (int)strlen(p);+ size_t line_off = (size_t)(p - content);++ if (in_fence) {+ if (adr_fence_closes(p, line_len, fence_ch, fence_n)) {+ in_fence = false;+ }+ } else {+ char ch = 0;+ int fn = adr_fence_run(p, line_len, &ch);+ if (fn > 0) {+ in_fence = true;+ fence_ch = ch;+ fence_n = fn;+ } else {+ int name_len = adr_heading_name_len(p, line_len);+ if (name_len > 0) {+ /* The previous heading's body ends where this one starts. */+ if (have_pending) {+ pending.body_end = line_off;+ cb(ctx, &pending);+ }+ pending.name = p + ST_HEADER_PREFIX;+ pending.name_len = name_len;+ pending.heading_start = line_off;+ pending.body_start =+ eol ? line_off + (size_t)line_len + SKIP_ONE : line_off + (size_t)line_len;+ have_pending = true;+ }+ }+ }+ if (!eol) {+ break;}+ p = eol + SKIP_ONE;}+ if (have_pending) {+ pending.body_end = strlen(content);+ cb(ctx, &pending);+ }+ return CBM_STORE_OK;+}++int cbm_adr_check_structure(const char *content, char *errbuf, int errbuf_size) {+ if (content && adr_has_unterminated_fence(content)) {+ snprintf(errbuf, (size_t)errbuf_size,+ "the stored ADR leaves a code fence open, so its section boundaries are "+ "ambiguous and a section write could splice into a code sample; repair it "+ "with mode='update'");+ return CBM_STORE_ERR;+ }+ return CBM_STORE_OK;+}++typedef struct {+ const char *name;+ int name_len;+ bool found;+ size_t body_start;+ size_t body_end;+} adr_find_ctx_t;++static void adr_find_cb(void *ctx, const cbm_adr_heading_t *h) {+ adr_find_ctx_t *f = (adr_find_ctx_t *)ctx;+ /* First occurrence wins, so a document that repeats a heading updates+ * deterministically rather than depending on scan order. */+ if (f->found || h->name_len != f->name_len ||+ memcmp(h->name, f->name, (size_t)f->name_len) != 0) {+ return;+ }+ f->found = true;+ f->body_start = h->body_start;+ f->body_end = h->body_end;+}++char *cbm_adr_splice_section(const char *content, const char *name, const char *body) {+ if (!name || !body) {+ return NULL;+ }+ const char *doc = content ? content : "";+ size_t doc_len = strlen(doc);- for (int i = 0; i < inv_n; i++) {- if (ilen > 0) {- ilen += snprintf(invalid + ilen, sizeof(invalid) - ilen, ", ");+ /* Trailing newlines are stripped from the incoming body so that splicing+ * the same body twice is byte-identical: without this the separator run+ * would grow by one blank line on every repeat. */+ size_t body_len = strlen(body);+ while (body_len > 0 &&+ (body[body_len - SKIP_ONE] == '\n' || body[body_len - SKIP_ONE] == '\r')) {+ body_len--;+ }++ adr_find_ctx_t find;+ memset(&find, 0, sizeof(find));+ find.name = name;+ find.name_len = (int)strlen(name);+ if (cbm_adr_scan_headings(doc, adr_find_cb, &find) != CBM_STORE_OK) {+ return NULL;+ }++ char *out = NULL;+ if (find.found) {+ /* Keep the replaced region's own trailing newline run, so the blank+ * line that separates this section from the next survives untouched. */+ size_t ws = find.body_end;+ while (ws > find.body_start && (doc[ws - SKIP_ONE] == '\n' || doc[ws - SKIP_ONE] == '\r')) {+ ws--;+ }+ size_t ws_len = find.body_end - ws;+ size_t total = find.body_start + body_len + ws_len + (doc_len - find.body_end);+ out = malloc(total + SKIP_ONE);+ if (!out) {+ return NULL;}- ilen += snprintf(invalid + ilen, sizeof(invalid) - ilen, "%s", inv_keys[i]);- ninvalid++;+ size_t at = 0;+ memcpy(out, doc, find.body_start);+ at += find.body_start;+ memcpy(out + at, body, body_len);+ at += body_len;+ memcpy(out + at, doc + ws, ws_len);+ at += ws_len;+ memcpy(out + at, doc + find.body_end, doc_len - find.body_end);+ at += doc_len - find.body_end;+ out[at] = '\0';+ return out;+ }++ /* Absent: append. Enough newlines are added to leave exactly one blank+ * line before the new heading — never fewer, and never rewriting the+ * newlines the document already ends with. */+ size_t trailing = 0;+ while (trailing < doc_len && doc[doc_len - SKIP_ONE - trailing] == '\n') {+ trailing++;+ }+ size_t sep = 0;+ if (doc_len > 0 && trailing < PAIR_LEN) {+ sep = PAIR_LEN - trailing;+ }+ size_t name_len = strlen(name);+ size_t total = doc_len + sep + ST_HEADER_PREFIX + name_len + SKIP_ONE + body_len;+ out = malloc(total + SKIP_ONE);+ if (!out) {+ return NULL;}+ size_t at = 0;+ memcpy(out, doc, doc_len);+ at += doc_len;+ for (size_t i = 0; i < sep; i++) {+ out[at++] = '\n';+ }+ memcpy(out + at, "## ", ST_HEADER_PREFIX);+ at += ST_HEADER_PREFIX;+ memcpy(out + at, name, name_len);+ at += name_len;+ out[at++] = '\n';+ memcpy(out + at, body, body_len);+ at += body_len;+ out[at] = '\0';+ return out;+}- if (ninvalid > 0) {- snprintf(errbuf, errbuf_size,- "invalid section names: %s. Valid sections: PURPOSE, STACK, ARCHITECTURE, "- "PATTERNS, TRADEOFFS, PHILOSOPHY",- invalid);+int cbm_adr_validate_section_name(const char *name, char *errbuf, int errbuf_size) {+ if (!name || !name[0]) {+ snprintf(errbuf, (size_t)errbuf_size, "section name must not be empty");+ return CBM_STORE_ERR;+ }+ size_t len = strlen(name);+ if (len >= CBM_SZ_64) {+ snprintf(errbuf, (size_t)errbuf_size, "section name must be shorter than %d characters",+ CBM_SZ_64);return CBM_STORE_ERR;}+ /* Everything below would make the written "## NAME" line scan back as a+ * different heading, or as no heading at all. */+ if (name[0] == '#') {+ snprintf(errbuf, (size_t)errbuf_size, "section name must not start with '#': %s", name);+ return CBM_STORE_ERR;+ }+ for (size_t i = 0; i < len; i++) {+ if (name[i] == '\n' || name[i] == '\r') {+ snprintf(errbuf, (size_t)errbuf_size, "section name must not contain a line break");+ return CBM_STORE_ERR;+ }+ }+ if (name[0] == ' ' || name[0] == '\t' || name[len - SKIP_ONE] == ' ' ||+ name[len - SKIP_ONE] == '\t') {+ snprintf(errbuf, (size_t)errbuf_size,+ "section name must not start or end with whitespace: '%s'", name);+ return CBM_STORE_ERR;+ }+ return CBM_STORE_OK;+}++int cbm_adr_validate_section_keys(const char **keys, int count, char *errbuf, int errbuf_size) {+ /* Section names used to be restricted to the six canonical headings. They+ * are now a convention rather than a privilege, so the only names refused+ * are the ones that could not round-trip through a "## NAME" line. */+ for (int i = 0; i < count; i++) {+ if (cbm_adr_validate_section_name(keys[i], errbuf, errbuf_size) != CBM_STORE_OK) {+ return CBM_STORE_ERR;+ }+ }return CBM_STORE_OK;}@@ -8906,35 +9183,32 @@ int cbm_store_adr_update_sections(cbm_store_t *s, const char *project, const chareturn rc;}- /* Parse existing sections */- cbm_adr_sections_t sections = cbm_adr_parse_sections(existing.content);- cbm_store_adr_free(&existing);-- /* Merge new sections */- for (int i = 0; i < count; i++) {- bool found = false;- for (int j = 0; j < sections.count; j++) {- if (strcmp(sections.keys[j], keys[i]) == 0) {- free(sections.values[j]);- sections.values[j] = heap_strdup(values[i]);- found = true;- break;- }- }- if (!found && sections.count < ST_BUF_16) {- sections.keys[sections.count] = heap_strdup(keys[i]);- sections.values[sections.count] = heap_strdup(values[i]);- sections.count++;- }+ /* Splice each section in place. The document is NOT rebuilt from parsed+ * sections: that model drops the preamble, drops headings it does not+ * recognise (including a mis-cased '## Purpose', whose whole block then+ * disappears) and reorders the rest, so rendering from it would silently+ * rewrite text nobody asked to change. Replacing byte spans leaves every+ * untouched byte exactly as it was. */+ char structure_err[CBM_SZ_256] = "";+ if (cbm_adr_check_structure(existing.content, structure_err, (int)sizeof(structure_err)) !=+ CBM_STORE_OK) {+ cbm_store_adr_free(&existing);+ (void)cbm_store_rollback(s);+ store_set_error(s, structure_err);+ return CBM_STORE_ERR;}- /* Render merged */- char *merged = cbm_adr_render(§ions);- cbm_adr_sections_free(§ions);+ char *merged = heap_strdup(existing.content ? existing.content : "");+ cbm_store_adr_free(&existing);+ for (int i = 0; merged && i < count; i++) {+ char *next = cbm_adr_splice_section(merged, keys[i], values[i]);+ free(merged);+ merged = next;+ }if (!merged) {(void)cbm_store_rollback(s);- store_set_error(s, "failed to render merged ADR");+ store_set_error(s, "failed to splice ADR section");return CBM_STORE_ERR;}diff --git a/src/store/store.h b/src/store/store.hindex 2e952d064..e6538c35d 100644--- a/src/store/store.h+++ b/src/store/store.h@@ -877,6 +877,47 @@ int cbm_adr_validate_content(const char *content, char *errbuf, int errbuf_size)int cbm_adr_validate_section_keys(const char **keys, int count, char *errbuf, int errbuf_size);void cbm_adr_sections_free(cbm_adr_sections_t *s);+/* ── ADR section headings (the splice model) ────────────────────+ *+ * A section write must not rebuild the document. cbm_adr_parse_sections() ++ * cbm_adr_render() is a lossy model — it drops everything before the first+ * heading, drops headings it does not recognise, and reorders what is left —+ * so rebuilding from it silently rewrites text nobody asked to change. These+ * functions locate a heading's byte span instead, so a write replaces that+ * span and leaves every other byte of the document exactly as it was.+ *+ * A heading is a line of the form "## NAME" that is NOT inside a fenced code+ * block. NAME is matched EXACTLY, including case: "## Purpose" and+ * "## PURPOSE" are different sections, because folding them would silently+ * merge two blocks the author chose to keep apart. The six canonical names+ * are a convention (see ADR_EMPTY_HINT), not a privilege: any name that+ * round-trips is a section, and none of them gets ordering priority. */+typedef struct {+ const char *name; /* into the source buffer; NOT NUL-terminated */+ int name_len;+ size_t heading_start; /* offset of the first '#' of the heading line */+ size_t body_start; /* offset just past the heading line's newline */+ size_t body_end; /* offset of the next heading, or end of document */+} cbm_adr_heading_t;++/* Reports every heading in document order. Returns CBM_STORE_ERR without+ * calling `cb` when the document has an unterminated code fence: its structure+ * is ambiguous, and guessing could splice into a code sample. */+int cbm_adr_scan_headings(const char *content, void (*cb)(void *ctx, const cbm_adr_heading_t *h),+ void *ctx);++/* CBM_STORE_ERR + message when the document cannot be spliced safely. */+int cbm_adr_check_structure(const char *content, char *errbuf, int errbuf_size);++/* Replaces the body of `name`, or appends the section when it is absent.+ * Returns a new document (caller frees), or NULL on bad input, an unterminated+ * fence, or OOM. Bytes outside the replaced span are preserved exactly, and+ * splicing the same name and body twice is byte-identical to doing it once. */+char *cbm_adr_splice_section(const char *content, const char *name, const char *body);++/* Rejects names that could not round-trip through a "## NAME" heading. */+int cbm_adr_validate_section_name(const char *name, char *errbuf, int errbuf_size);+/* ── Search helpers (exposed for testing) ───────────────────────── *//* Convert a glob pattern to SQL LIKE pattern. Caller must free result. */diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex 21b5826b3..cacd4d88d 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -6012,11 +6012,11 @@ TEST(tool_manage_adr_set_sections_without_updates_errors) {PASS();}-/* An empty body would render a heading with nothing under it — a content- * deletion wearing the response shape of an update. A non-canonical name would- * be parsed back as body text of the section above it, so writing it twice- * would duplicate it: both are rejected before any store is opened. */-TEST(tool_manage_adr_set_sections_rejects_empty_and_unknown_sections) {+/* An empty body would leave a heading with nothing under it — a content+ * deletion wearing the response shape of an update. A name that cannot survive+ * a "## NAME" round-trip would scan back as a different heading or as none, so+ * writing it twice would duplicate it. Both are refused before a store opens. */+TEST(tool_manage_adr_set_sections_rejects_unwritable_sections) {const char *project = "adr-sec-guards";cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);ASSERT_NOT_NULL(srv);@@ -6034,12 +6034,21 @@ TEST(tool_manage_adr_set_sections_rejects_empty_and_unknown_sections) {ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));free(resp);+ /* A '#'-leading name would render "## # PURPOSE" and scan back different. */resp = cbm_mcp_handle_tool(srv, "manage_adr","{\"project\":\"adr-sec-guards\",\"mode\":\"set_sections\","- "\"section_updates\":{\"DECISIONS\":\"- Chose SQLite.\"}}");+ "\"section_updates\":{\"# PURPOSE\":\"x\"}}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "invalid_section_name"));+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));+ free(resp);++ /* A newline in the name would forge a second heading line. */+ resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-guards\",\"mode\":\"set_sections\","+ "\"section_updates\":{\"A\\nB\":\"x\"}}");ASSERT_NOT_NULL(resp);ASSERT_NOT_NULL(strstr(resp, "invalid_section_name"));- ASSERT_NOT_NULL(strstr(resp, "DECISIONS"));ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));free(resp);@@ -6062,6 +6071,201 @@ TEST(tool_manage_adr_set_sections_rejects_empty_and_unknown_sections) {PASS();}+/* The use case the whole change exists for: add an entry under its own+ * heading, and be able to retry it. Under the old canonical-only rules this+ * was the exact request that would have corrupted an ADR. */+TEST(tool_manage_adr_set_sections_adds_custom_heading) {+ const char *project = "adr-sec-custom";+ const char *request = "{\"project\":\"adr-sec-custom\",\"mode\":\"set_sections\","+ "\"section_updates\":{\"DECISIONS\":\"- Chose SQLite.\"}}";+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);+ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/adr-sec-custom"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_adr_store(st, project, "## PURPOSE\nFoo"), CBM_STORE_OK);++ char *resp = cbm_mcp_handle_tool(srv, "manage_adr", request);+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "sections_updated"));+ ASSERT_NULL(strstr(resp, "\"isError\":true"));+ free(resp);++ cbm_adr_t adr;+ memset(&adr, 0, sizeof(adr));+ ASSERT_EQ(cbm_store_adr_get(st, project, &adr), CBM_STORE_OK);+ ASSERT_STR_EQ(adr.content, "## PURPOSE\nFoo\n\n## DECISIONS\n- Chose SQLite.");+ cbm_store_adr_free(&adr);++ /* Retry the identical request: byte-identical, not duplicated. */+ resp = cbm_mcp_handle_tool(srv, "manage_adr", request);+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "sections_updated"));+ free(resp);++ memset(&adr, 0, sizeof(adr));+ ASSERT_EQ(cbm_store_adr_get(st, project, &adr), CBM_STORE_OK);+ ASSERT_STR_EQ(adr.content, "## PURPOSE\nFoo\n\n## DECISIONS\n- Chose SQLite.");+ cbm_store_adr_free(&adr);++ /* And it is now a real section the write path can target again. */+ resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-custom\",\"mode\":\"set_sections\","+ "\"section_updates\":{\"DECISIONS\":\"- Chose DuckDB.\"}}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "sections_updated"));+ free(resp);++ memset(&adr, 0, sizeof(adr));+ ASSERT_EQ(cbm_store_adr_get(st, project, &adr), CBM_STORE_OK);+ ASSERT_STR_EQ(adr.content, "## PURPOSE\nFoo\n\n## DECISIONS\n- Chose DuckDB.");+ cbm_store_adr_free(&adr);++ cbm_mcp_server_free(srv);+ PASS();+}++/* Regression for real data loss: rebuilding the document from parsed sections+ * dropped the preamble, dropped a mis-cased heading together with its whole+ * block, and reordered what survived. Splicing leaves all of it alone. */+TEST(tool_manage_adr_set_sections_preserves_preamble_and_order) {+ const char *project = "adr-sec-preserve";+ /* The fenced block sits inside the mis-cased section, NOT the one being+ * written: a section's body runs to the next heading, so rewriting STACK+ * would legitimately replace a fence that belonged to STACK. */+ const char *stored = "Notes before any heading.\n\n"+ "## Purpose\nMis-cased but real.\n\n"+ "```md\n## Example\nfenced sample\n```\n\n"+ "## STACK\nC and SQLite.\n\n"+ "## PURPOSE\nCanonical one.";+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);+ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/adr-sec-preserve"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_adr_store(st, project, stored), CBM_STORE_OK);++ char *resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-preserve\",\"mode\":\"set_sections\","+ "\"section_updates\":{\"STACK\":\"C only.\"}}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "sections_updated"));+ free(resp);++ cbm_adr_t adr;+ memset(&adr, 0, sizeof(adr));+ ASSERT_EQ(cbm_store_adr_get(st, project, &adr), CBM_STORE_OK);+ ASSERT_STR_EQ(adr.content, "Notes before any heading.\n\n"+ "## Purpose\nMis-cased but real.\n\n"+ "```md\n## Example\nfenced sample\n```\n\n"+ "## STACK\nC only.\n\n"+ "## PURPOSE\nCanonical one.");+ cbm_store_adr_free(&adr);++ cbm_mcp_server_free(srv);+ PASS();+}++/* An unterminated fence hides every heading after it, so a write would append+ * a duplicate heading rather than replace the real one. Refuse, explicitly,+ * and leave the document alone. */+TEST(tool_manage_adr_set_sections_refuses_unterminated_fence) {+ const char *project = "adr-sec-fence";+ const char *stored = "## PURPOSE\nFoo\n\n```\nunclosed sample\n\n## STACK\nBar";+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);+ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/adr-sec-fence"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_adr_store(st, project, stored), CBM_STORE_OK);++ char *resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-fence\",\"mode\":\"set_sections\","+ "\"section_updates\":{\"STACK\":\"New bar.\"}}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "write_error"));+ ASSERT_NOT_NULL(strstr(resp, "code fence"));+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));+ free(resp);++ cbm_adr_t adr;+ memset(&adr, 0, sizeof(adr));+ ASSERT_EQ(cbm_store_adr_get(st, project, &adr), CBM_STORE_OK);+ ASSERT_STR_EQ(adr.content, stored);+ cbm_store_adr_free(&adr);++ /* mode='sections' reports the same ambiguity rather than a partial list. */+ resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-fence\",\"mode\":\"sections\"}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "unterminated_code_fence"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+}++/* mode='sections' and the section write path must agree on what a heading is.+ * They used to disagree — 'sections' listed every '#'-prefixed line, including+ * ones inside code fences that no write could ever target — and two components+ * disagreeing about what a section is is how a section write came to be able+ * to destroy one. */+TEST(tool_manage_adr_sections_agrees_with_write_path) {+ const char *project = "adr-sec-agree";+ const char *stored = "Preamble.\n\n"+ "# Title\n\n"+ "## PURPOSE\nFoo\n\n"+ "### Sub\n\n"+ "```md\n## Fenced\n```\n\n"+ "## DECISIONS\nBar";+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);+ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/adr-sec-agree"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_adr_store(st, project, stored), CBM_STORE_OK);++ char *resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-agree\",\"mode\":\"sections\"}");+ ASSERT_NOT_NULL(resp);+ /* Listed: exactly the two headings the write path can target. */+ ASSERT_NOT_NULL(strstr(resp, "## PURPOSE"));+ ASSERT_NOT_NULL(strstr(resp, "## DECISIONS"));+ /* Not listed: a fenced '##', a '#' title, a '###' subheading. */+ ASSERT_NULL(strstr(resp, "## Fenced"));+ ASSERT_NULL(strstr(resp, "# Title"));+ ASSERT_NULL(strstr(resp, "### Sub"));+ free(resp);++ /* Every listed heading is writable, and the unlisted ones stay as text. */+ resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-sec-agree\",\"mode\":\"set_sections\","+ "\"section_updates\":{\"DECISIONS\":\"New bar\"}}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "sections_updated"));+ free(resp);++ /* The '#', '###' and fenced lines are body text of PURPOSE, and writing a+ * different section leaves every byte of them alone. */+ cbm_adr_t adr;+ memset(&adr, 0, sizeof(adr));+ ASSERT_EQ(cbm_store_adr_get(st, project, &adr), CBM_STORE_OK);+ ASSERT_STR_EQ(adr.content, "Preamble.\n\n"+ "# Title\n\n"+ "## PURPOSE\nFoo\n\n"+ "### Sub\n\n"+ "```md\n## Fenced\n```\n\n"+ "## DECISIONS\nNew bar");+ cbm_store_adr_free(&adr);++ cbm_mcp_server_free(srv);+ PASS();+}+/* CBM_ADR_MAX_LENGTH is enforced on this path — mode='update' bypasses it, so* exposing an incremental writer without the cap would make unbounded growth* cheap. The rejected merge must also roll back to the byte-identical prior@@ -13446,7 +13650,11 @@ SUITE(mcp) {RUN_TEST(tool_manage_adr_set_sections_is_idempotent);RUN_TEST(tool_manage_adr_set_sections_creates_when_absent);RUN_TEST(tool_manage_adr_set_sections_without_updates_errors);- RUN_TEST(tool_manage_adr_set_sections_rejects_empty_and_unknown_sections);+ RUN_TEST(tool_manage_adr_set_sections_rejects_unwritable_sections);+ RUN_TEST(tool_manage_adr_set_sections_adds_custom_heading);+ RUN_TEST(tool_manage_adr_set_sections_preserves_preamble_and_order);+ RUN_TEST(tool_manage_adr_set_sections_refuses_unterminated_fence);+ RUN_TEST(tool_manage_adr_sections_agrees_with_write_path);RUN_TEST(tool_manage_adr_set_sections_rejects_oversize);RUN_TEST(tool_manage_adr_set_sections_is_advertised);RUN_TEST(tool_index_repository_reports_store_backed_adr);diff --git a/tests/test_store_arch.c b/tests/test_store_arch.cindex 159c07f95..3a93c4722 100644--- a/tests/test_store_arch.c+++ b/tests/test_store_arch.c@@ -908,12 +908,181 @@ TEST(adr_validate_keys_valid) {PASS();}-TEST(adr_validate_keys_invalid) {- const char *keys[] = {"PURPOSE", "STACKS", "CUSTOM"};+/* Section names are no longer restricted to the canonical six — those are a+ * convention now, so "STACKS" and "CUSTOM" are ordinary sections. What is+ * still refused is a name that could not round-trip through a "## NAME" line:+ * such a name scans back as a different heading or as none, so a second+ * identical write would append a duplicate instead of being a no-op. */+TEST(adr_validate_keys_accepts_arbitrary_names) {+ const char *keys[] = {"PURPOSE", "STACKS", "CUSTOM", "Decisions (2026)"};char errbuf[256];- ASSERT_TRUE(cbm_adr_validate_section_keys(keys, 3, errbuf, sizeof(errbuf)) != CBM_STORE_OK);- ASSERT_TRUE(strstr(errbuf, "STACKS") != NULL);- ASSERT_TRUE(strstr(errbuf, "CUSTOM") != NULL);+ ASSERT_EQ(cbm_adr_validate_section_keys(keys, 4, errbuf, sizeof(errbuf)), CBM_STORE_OK);+ PASS();+}++TEST(adr_validate_keys_rejects_unroundtrippable) {+ char errbuf[256];+ const char *empty[] = {""};+ ASSERT_TRUE(cbm_adr_validate_section_keys(empty, 1, errbuf, sizeof(errbuf)) != CBM_STORE_OK);++ const char *hashed[] = {"# PURPOSE"};+ ASSERT_TRUE(cbm_adr_validate_section_keys(hashed, 1, errbuf, sizeof(errbuf)) != CBM_STORE_OK);++ const char *newline[] = {"PUR\nPOSE"};+ ASSERT_TRUE(cbm_adr_validate_section_keys(newline, 1, errbuf, sizeof(errbuf)) != CBM_STORE_OK);++ const char *padded[] = {" PURPOSE "};+ ASSERT_TRUE(cbm_adr_validate_section_keys(padded, 1, errbuf, sizeof(errbuf)) != CBM_STORE_OK);++ char toolong[128];+ memset(toolong, 'X', sizeof(toolong) - 1);+ toolong[sizeof(toolong) - 1] = '\0';+ const char *big[] = {toolong};+ ASSERT_TRUE(cbm_adr_validate_section_keys(big, 1, errbuf, sizeof(errbuf)) != CBM_STORE_OK);+ PASS();+}++/* ── Splice: bytes outside the target span never change ─────────── */++typedef struct {+ char buf[512];+ int n;+} adr_name_collect_t;++static void adr_collect_names(void *ctx, const cbm_adr_heading_t *h) {+ adr_name_collect_t *c = (adr_name_collect_t *)ctx;+ c->n += snprintf(c->buf + c->n, sizeof(c->buf) - (size_t)c->n, "[%.*s]", h->name_len, h->name);+}++static int adr_check_splice(const char *in, const char *name, const char *body,+ const char *expect) {+ char *out = cbm_adr_splice_section(in, name, body);+ ASSERT_NOT_NULL(out);+ if (strcmp(out, expect) != 0) {+ printf(" %sFAIL%s %s: splice(\"%s\")\n in >>>%s<<<\n got >>>%s<<<\n"+ " expect >>>%s<<<\n",+ tf_red(), tf_reset(), __FILE__, name, in, out, expect);+ free(out);+ return 1;+ }+ free(out);+ return 0;+}++#define CHECK_SPLICE(in, name, body, expect) \+ do { \+ if (adr_check_splice((in), (name), (body), (expect)) != 0) { \+ return 1; \+ } \+ } while (0)++/* THE acceptance property. Every document below is a case where rebuilding+ * from cbm_adr_parse_sections() would have rewritten or destroyed text: a+ * preamble (dropped), a mis-cased heading (dropped with its whole block), an+ * unrecognised heading in prose (absorbed), a fenced '##' (absorbed), and+ * out-of-canonical-order sections (reordered). Splicing touches only the+ * target span, so each survives byte-for-byte. */+TEST(adr_splice_preserves_untouched_bytes) {+ /* Preamble before the first heading. */+ CHECK_SPLICE("Some preamble.\n\n## PURPOSE\nFoo", "PURPOSE", "New foo",+ "Some preamble.\n\n## PURPOSE\nNew foo");++ /* Mis-cased heading: a real section now, and untouched when not targeted. */+ CHECK_SPLICE("## Purpose\nFoo\n\n## STACK\nBar", "STACK", "New bar",+ "## Purpose\nFoo\n\n## STACK\nNew bar");++ /* A heading in prose that the old parser absorbed into the section above. */+ CHECK_SPLICE("## PURPOSE\nFoo\n## CUSTOM\nStill here\n\n## STACK\nBar", "STACK", "New bar",+ "## PURPOSE\nFoo\n## CUSTOM\nStill here\n\n## STACK\nNew bar");++ /* Fenced code containing a '##' line. */+ CHECK_SPLICE("## PURPOSE\nFoo\n\n```md\n## Example\n```\n\n## STACK\nBar", "STACK", "New bar",+ "## PURPOSE\nFoo\n\n```md\n## Example\n```\n\n## STACK\nNew bar");++ /* Sections stored out of canonical order keep the author's order. */+ CHECK_SPLICE("## STACK\nBar\n\n## PURPOSE\nFoo", "PURPOSE", "New foo",+ "## STACK\nBar\n\n## PURPOSE\nNew foo");++ /* The separator run before the next heading is preserved exactly. */+ CHECK_SPLICE("## A\nx\n\n\n## B\ny", "A", "z", "## A\nz\n\n\n## B\ny");++ /* A trailing newline on the document is preserved. */+ CHECK_SPLICE("## A\nx\n", "A", "z", "## A\nz\n");+ PASS();+}++/* The original use case: add an entry under its own heading. */+TEST(adr_splice_appends_arbitrary_heading) {+ CHECK_SPLICE("## PURPOSE\nFoo", "DECISIONS", "- Chose SQLite.",+ "## PURPOSE\nFoo\n\n## DECISIONS\n- Chose SQLite.");+ /* A document already ending in a blank line does not gain another. */+ CHECK_SPLICE("## PURPOSE\nFoo\n\n", "DECISIONS", "- Chose SQLite.",+ "## PURPOSE\nFoo\n\n## DECISIONS\n- Chose SQLite.");+ /* An empty document becomes a plain create with no leading separator. */+ CHECK_SPLICE("", "PURPOSE", "Only entry.", "## PURPOSE\nOnly entry.");+ PASS();+}++/* Splicing twice must be byte-identical to splicing once — including for a+ * non-canonical heading, the case that would have corrupted an ADR under the+ * old rules. Trailing newlines on the body are normalised so the separator run+ * cannot grow by a blank line on every repeat. */+TEST(adr_splice_is_idempotent) {+ const char *doc = "## PURPOSE\nFoo\n\n## STACK\nBar";+ char *once = cbm_adr_splice_section(doc, "DECISIONS", "- Chose SQLite.\n");+ ASSERT_NOT_NULL(once);+ char *twice = cbm_adr_splice_section(once, "DECISIONS", "- Chose SQLite.\n");+ ASSERT_NOT_NULL(twice);+ ASSERT_STR_EQ(twice, once);+ char *thrice = cbm_adr_splice_section(twice, "DECISIONS", "- Chose SQLite.\n");+ ASSERT_NOT_NULL(thrice);+ ASSERT_STR_EQ(thrice, once);+ free(once);+ free(twice);+ free(thrice);+ PASS();+}++/* Names match exactly, including case: folding them would silently merge two+ * blocks the author chose to keep apart. */+TEST(adr_splice_matches_case_exactly) {+ CHECK_SPLICE("## Purpose\nLower\n\n## PURPOSE\nUpper", "PURPOSE", "New",+ "## Purpose\nLower\n\n## PURPOSE\nNew");+ CHECK_SPLICE("## Purpose\nLower\n\n## PURPOSE\nUpper", "Purpose", "New",+ "## Purpose\nNew\n\n## PURPOSE\nUpper");+ PASS();+}++/* A '##' line inside a fenced code block is a code sample, not a heading —+ * and '#' / '###' are not section headings at any position. */+TEST(adr_splice_ignores_heading_inside_fence) {+ adr_name_collect_t c;+ memset(&c, 0, sizeof(c));+ ASSERT_EQ(cbm_adr_scan_headings(+ "## PURPOSE\nFoo\n\n```md\n## Example\n```\n\n### Sub\n# Title\n\n## STACK\nBar",+ adr_collect_names, &c),+ CBM_STORE_OK);+ ASSERT_STR_EQ(c.buf, "[PURPOSE][STACK]");+ PASS();+}++/* An unterminated fence hides every heading after it, so an update would+ * append a duplicate rather than replace. Refuse instead of guessing. */+TEST(adr_splice_refuses_unterminated_fence) {+ const char *doc = "## PURPOSE\nFoo\n\n```\nunclosed sample\n\n## STACK\nBar";+ char errbuf[256];+ ASSERT_TRUE(cbm_adr_check_structure(doc, errbuf, sizeof(errbuf)) != CBM_STORE_OK);+ ASSERT_TRUE(strstr(errbuf, "code fence") != NULL);++ adr_name_collect_t c;+ memset(&c, 0, sizeof(c));+ ASSERT_TRUE(cbm_adr_scan_headings(doc, adr_collect_names, &c) != CBM_STORE_OK);+ ASSERT_EQ(c.n, 0);++ ASSERT_NULL(cbm_adr_splice_section(doc, "STACK", "New bar"));++ /* A closed fence is fine. */+ ASSERT_EQ(cbm_adr_check_structure("## A\n```\nx\n```\n", errbuf, sizeof(errbuf)), CBM_STORE_OK);PASS();}@@ -1448,7 +1617,14 @@ SUITE(store_arch) {RUN_TEST(adr_validate_missing_sections);RUN_TEST(adr_validate_empty);RUN_TEST(adr_validate_keys_valid);- RUN_TEST(adr_validate_keys_invalid);+ RUN_TEST(adr_validate_keys_accepts_arbitrary_names);+ RUN_TEST(adr_validate_keys_rejects_unroundtrippable);+ RUN_TEST(adr_splice_preserves_untouched_bytes);+ RUN_TEST(adr_splice_appends_arbitrary_heading);+ RUN_TEST(adr_splice_is_idempotent);+ RUN_TEST(adr_splice_matches_case_exactly);+ RUN_TEST(adr_splice_ignores_heading_inside_fence);+ RUN_TEST(adr_splice_refuses_unterminated_fence);RUN_TEST(adr_validate_keys_empty);/* Louvain */