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.

feat(mcp): ingest_traces stores observed runtime calls for real

Martin Vogelbaf0df8e9128
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 04316627b..eb55e6ce6 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -693,10 +693,20 @@ static const tool_def_t TOOLS[] = {
"required by update\"}},\"additionalProperties\":false,"
"\"required\":[\"project\"]}"},
- {"ingest_traces", "Ingest traces", "Ingest runtime traces to enhance the knowledge graph",
+ {"ingest_traces", "Ingest traces",
+ "Record observed runtime calls so the graph can distinguish observed from merely possible "
+ "paths. Each trace is a call path (qualified names, adjacent = caller\xe2\x86\x92"
+ "callee) or a bare caller/callee pair. Stored per run label, keyed by qualified name "
+ "(reindex-proof). Only pairs whose both endpoints are indexed symbols are stored; the "
+ "response reports unresolved names (up to 10) so the producer can fix its naming.",
"{\"type\":\"object\",\"properties\":{\"traces\":{\"type\":\"array\",\"items\":{\"type\":"
- "\"object\",\"properties\":{\"caller\":{\"type\":\"string\"},\"callee\":{\"type\":\"string\"},"
- "\"count\":{\"type\":\"integer\"}},\"additionalProperties\":false}},\"project\":{\"type\":"
+ "\"object\",\"properties\":{\"path\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
+ "\"description\":\"Call path of qualified names, caller before callee; 2..256 entries\"},"
+ "\"caller\":{\"type\":\"string\"},\"callee\":{\"type\":\"string\"},"
+ "\"count\":{\"type\":\"integer\",\"description\":\"How often this trace was observed "
+ "(default 1)\"}},\"additionalProperties\":false}},\"label\":{\"type\":\"string\","
+ "\"description\":\"Run identity, e.g. 'pytest 2026-08-27' (default 'unlabeled'); counts "
+ "accumulate per label and whole runs age out together\"},\"project\":{\"type\":"
"\"string\"}},\"required\":[\"traces\",\"project\"]}"},
};
@@ -11338,32 +11348,177 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {
/* ── ingest_traces ────────────────────────────────────────────── */
+enum {
+ INGEST_TRACES_MAX = 10000, /* trace entries per call */
+ INGEST_PATH_MAX = 256, /* hops per path */
+ INGEST_PAIR_CAP = 200000, /* observed pairs per project */
+ INGEST_UNMATCHED_SAMPLE = 10, /* distinct unresolved names reported */
+ INGEST_EVICT_MAX_ROUNDS = 32, /* runaway guard for the eviction loop */
+};
+
+/* Observed runtime calls: paths of qualified names (adjacent elements are
+ * caller→callee) or bare {caller, callee} pairs — stored qn-keyed in
+ * observed_calls/observed_paths (reindex-proof), per run label. The
+ * response is honest about resolution: only pairs whose BOTH endpoints
+ * exist as indexed symbols are stored, and up to 10 unresolved names come
+ * back so the producer can fix its naming instead of silently losing data. */
static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {
- (void)srv;
- /* Parse traces array from JSON args */
+ char *project = get_project_arg(args);
+ cbm_store_t *store = resolve_store(srv, project);
+ REQUIRE_STORE(store, project);
+
yyjson_doc *adoc = yyjson_read(args, strlen(args), 0);
- int trace_count = 0;
+ yyjson_val *aroot = adoc ? yyjson_doc_get_root(adoc) : NULL;
+ yyjson_val *traces = aroot ? yyjson_obj_get(aroot, "traces") : NULL;
+ size_t trace_count = traces && yyjson_is_arr(traces) ? yyjson_arr_size(traces) : 0U;
+ if (trace_count == 0U || trace_count > INGEST_TRACES_MAX) {
+ if (adoc)
+ yyjson_doc_free(adoc);
+ free(project);
+ return cbm_mcp_text_result(
+ "traces is required: a non-empty array (max 10000) of {path: [qualified_name, ...]} "
+ "or {caller, callee} entries",
+ true);
+ }
+ const char *label = yyjson_get_str(yyjson_obj_get(aroot, "label"));
+ if (!label || !label[0])
+ label = "unlabeled";
- if (adoc) {
- yyjson_val *aroot = yyjson_doc_get_root(adoc);
- yyjson_val *traces = yyjson_obj_get(aroot, "traces");
- if (traces && yyjson_is_arr(traces)) {
- trace_count = (int)yyjson_arr_size(traces);
- }
+ struct sqlite3 *db = cbm_store_get_db(store);
+ sqlite3_stmt *exists = NULL;
+ if (!db || sqlite3_prepare_v2(db,
+ "SELECT 1 FROM nodes WHERE project=?1 AND qualified_name=?2 "
+ "LIMIT 1",
+ -1, &exists, NULL) != SQLITE_OK) {
yyjson_doc_free(adoc);
+ free(project);
+ return cbm_mcp_text_result("store is not queryable", true);
+ }
+
+ long long pairs_stored = 0, pairs_unmatched = 0, paths_stored = 0, malformed = 0;
+ const char *unmatched_sample[INGEST_UNMATCHED_SAMPLE];
+ int unmatched_sample_count = 0;
+ (void)sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL);
+
+ size_t ti, tmax;
+ yyjson_val *trace;
+ yyjson_arr_foreach(traces, ti, tmax, trace) {
+ const char *hops[INGEST_PATH_MAX];
+ size_t hop_count = 0;
+ long long count = 1;
+ yyjson_val *count_val = yyjson_obj_get(trace, "count");
+ if (yyjson_is_int(count_val) && yyjson_get_int(count_val) > 0)
+ count = yyjson_get_int(count_val);
+
+ yyjson_val *path = yyjson_obj_get(trace, "path");
+ if (path && yyjson_is_arr(path)) {
+ size_t hi, hmax;
+ yyjson_val *hop;
+ bool ok = yyjson_arr_size(path) >= 2 && yyjson_arr_size(path) <= INGEST_PATH_MAX;
+ yyjson_arr_foreach(path, hi, hmax, hop) {
+ const char *qn = yyjson_get_str(hop);
+ if (!qn || !qn[0] || hop_count >= INGEST_PATH_MAX) {
+ ok = false;
+ break;
+ }
+ hops[hop_count++] = qn;
+ }
+ if (!ok) {
+ malformed++;
+ continue;
+ }
+ } else {
+ const char *caller = yyjson_get_str(yyjson_obj_get(trace, "caller"));
+ const char *callee = yyjson_get_str(yyjson_obj_get(trace, "callee"));
+ if (!caller || !caller[0] || !callee || !callee[0]) {
+ malformed++;
+ continue;
+ }
+ hops[0] = caller;
+ hops[1] = callee;
+ hop_count = 2;
+ }
+
+ /* Resolve every hop before storing anything from this trace: a
+ * partially-resolved path is not a real journey. */
+ bool all_resolved = true;
+ for (size_t h = 0; h < hop_count; h++) {
+ sqlite3_reset(exists);
+ sqlite3_bind_text(exists, 1, project, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(exists, 2, hops[h], -1, SQLITE_TRANSIENT);
+ if (sqlite3_step(exists) != SQLITE_ROW) {
+ all_resolved = false;
+ bool seen = false;
+ for (int u = 0; u < unmatched_sample_count; u++)
+ if (strcmp(unmatched_sample[u], hops[h]) == 0) {
+ seen = true;
+ break;
+ }
+ if (!seen && unmatched_sample_count < INGEST_UNMATCHED_SAMPLE)
+ unmatched_sample[unmatched_sample_count++] = hops[h];
+ }
+ }
+ if (!all_resolved) {
+ pairs_unmatched += (long long)(hop_count - 1);
+ continue;
+ }
+
+ for (size_t h = 0; h + 1 < hop_count; h++) {
+ if (cbm_store_observed_upsert_pair(store, project, hops[h], hops[h + 1], label,
+ count) == CBM_STORE_OK)
+ pairs_stored++;
+ }
+ if (path) {
+ char *path_json = yyjson_val_write(path, 0, NULL);
+ if (path_json) {
+ if (cbm_store_observed_upsert_path(store, project, path_json, label, count) ==
+ CBM_STORE_OK)
+ paths_stored++;
+ free(path_json);
+ }
+ }
+ }
+ sqlite3_finalize(exists);
+ (void)sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
+
+ /* Cap: evict whole oldest runs until under budget — a partially-evicted
+ * run could masquerade as a complete recording. */
+ long long evicted_runs = 0;
+ long long pair_total = cbm_store_observed_pair_total(store, project);
+ for (int round = 0; round < INGEST_EVICT_MAX_ROUNDS && pair_total > INGEST_PAIR_CAP; round++) {
+ char *evicted_label = NULL;
+ if (cbm_store_observed_evict_oldest_label(store, project, &evicted_label) != CBM_STORE_OK)
+ break;
+ evicted_runs++;
+ bool evicted_self = evicted_label && strcmp(evicted_label, label) == 0;
+ free(evicted_label);
+ pair_total = cbm_store_observed_pair_total(store, project);
+ if (evicted_self)
+ break; /* the current run alone exceeds the cap; stop here */
}
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
-
- yyjson_mut_obj_add_str(doc, root, "status", "accepted");
- yyjson_mut_obj_add_int(doc, root, "traces_received", trace_count);
- yyjson_mut_obj_add_str(doc, root, "note",
- "Runtime edge creation from traces not yet implemented");
+ yyjson_mut_obj_add_str(doc, root, "status", "stored");
+ yyjson_mut_obj_add_strcpy(doc, root, "label", label);
+ yyjson_mut_obj_add_int(doc, root, "pairs_stored", pairs_stored);
+ yyjson_mut_obj_add_int(doc, root, "paths_stored", paths_stored);
+ yyjson_mut_obj_add_int(doc, root, "pairs_unmatched", pairs_unmatched);
+ yyjson_mut_val *sample = yyjson_mut_arr(doc);
+ for (int u = 0; u < unmatched_sample_count; u++)
+ yyjson_mut_arr_add_strcpy(doc, sample, unmatched_sample[u]);
+ yyjson_mut_obj_add_val(doc, root, "unmatched_sample", sample);
+ if (malformed > 0)
+ yyjson_mut_obj_add_int(doc, root, "malformed", malformed);
+ yyjson_mut_obj_add_int(doc, root, "pair_total", pair_total);
+ if (evicted_runs > 0)
+ yyjson_mut_obj_add_int(doc, root, "evicted_runs", evicted_runs);
char *json = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
+ yyjson_doc_free(adoc);
+ free(project);
char *result = cbm_mcp_text_result(json, false);
free(json);
diff --git a/src/store/store.c b/src/store/store.c
index 015e50ca2..29e38249c 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -309,6 +309,34 @@ static int init_schema(cbm_store_t *s) {
" detail TEXT DEFAULT '',"
" PRIMARY KEY (project, rel_path, kind)"
");"
+ /* Observed runtime calls (ingest_traces). Deliberately SEPARATE from
+ * the graph tables (like index_coverage) and keyed by QUALIFIED NAME,
+ * not node id: node ids are reassigned on every reindex, so id-keyed
+ * observation would silently rot — qualified names survive by
+ * construction and join at read time. One row per (caller, callee,
+ * run label); count accumulates across ingests of the same run. */
+ "CREATE TABLE IF NOT EXISTS observed_calls ("
+ " project TEXT NOT NULL REFERENCES projects(name) ON DELETE CASCADE,"
+ " caller_qn TEXT NOT NULL,"
+ " callee_qn TEXT NOT NULL,"
+ " label TEXT NOT NULL DEFAULT '',"
+ " count INTEGER NOT NULL DEFAULT 1,"
+ " first_seen TEXT NOT NULL,"
+ " last_seen TEXT NOT NULL,"
+ " PRIMARY KEY (project, caller_qn, callee_qn, label)"
+ ");"
+ /* Whole observed journeys, kept alongside the pair decomposition so
+ * the Flows view can show "this path actually ran", not only
+ * per-edge markers. path_json is the JSON array of qualified names. */
+ "CREATE TABLE IF NOT EXISTS observed_paths ("
+ " project TEXT NOT NULL REFERENCES projects(name) ON DELETE CASCADE,"
+ " label TEXT NOT NULL DEFAULT '',"
+ " path_json TEXT NOT NULL,"
+ " count INTEGER NOT NULL DEFAULT 1,"
+ " first_seen TEXT NOT NULL,"
+ " last_seen TEXT NOT NULL,"
+ " PRIMARY KEY (project, label, path_json)"
+ ");"
/* One row per completed coverage persistence attempt. Kept separate
* from projects so existing graph/artifact schema stays compatible and
* a missing row unambiguously means coverage metadata is unavailable. */
@@ -8663,3 +8691,178 @@ int cbm_store_vector_search(cbm_store_t *s, const char *project, const char **ke
*out_count = count;
return CBM_STORE_OK;
}
+
+/* ── Observed runtime calls (ingest_traces) ─────────────────────────
+ *
+ * Qualified-name keyed on purpose: ids are reassigned on reindex, names
+ * survive. Low-frequency writes (one ingest per test run), so these use
+ * one-shot statements rather than the cached slots. */
+
+static int observed_upsert(cbm_store_t *s, const char *sql, const char *project, const char *a,
+ const char *b, const char *label, long long count) {
+ if (!s || !s->db || !project || !a)
+ return CBM_STORE_ERR;
+ sqlite3_stmt *stmt = NULL;
+ if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ store_set_error_sqlite(s, "observed_upsert prepare");
+ return CBM_STORE_ERR;
+ }
+ char ts[CBM_SZ_64];
+ iso_now(ts, sizeof(ts));
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, 2, a, -1, SQLITE_TRANSIENT);
+ if (b)
+ sqlite3_bind_text(stmt, 3, b, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, b ? 4 : 3, label ? label : "", -1, SQLITE_TRANSIENT);
+ sqlite3_bind_int64(stmt, b ? 5 : 4, count > 0 ? count : 1);
+ sqlite3_bind_text(stmt, b ? 6 : 5, ts, -1, SQLITE_TRANSIENT);
+ int rc = sqlite3_step(stmt);
+ sqlite3_finalize(stmt);
+ if (rc != SQLITE_DONE) {
+ store_set_error_sqlite(s, "observed_upsert");
+ return CBM_STORE_ERR;
+ }
+ return CBM_STORE_OK;
+}
+
+int cbm_store_observed_upsert_pair(cbm_store_t *s, const char *project, const char *caller_qn,
+ const char *callee_qn, const char *label, long long count) {
+ if (!caller_qn || !callee_qn)
+ return CBM_STORE_ERR;
+ return observed_upsert(
+ s,
+ "INSERT INTO observed_calls (project, caller_qn, callee_qn, label, count, first_seen,"
+ " last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6) "
+ "ON CONFLICT(project, caller_qn, callee_qn, label) DO UPDATE SET"
+ " count = count + excluded.count, last_seen = excluded.last_seen;",
+ project, caller_qn, callee_qn, label, count);
+}
+
+int cbm_store_observed_upsert_path(cbm_store_t *s, const char *project, const char *path_json,
+ const char *label, long long count) {
+ if (!path_json)
+ return CBM_STORE_ERR;
+ return observed_upsert(
+ s,
+ "INSERT INTO observed_paths (project, label, path_json, count, first_seen, last_seen)"
+ " VALUES (?1, ?3, ?2, ?4, ?5, ?5) "
+ "ON CONFLICT(project, label, path_json) DO UPDATE SET"
+ " count = count + excluded.count, last_seen = excluded.last_seen;",
+ project, path_json, NULL, label, count);
+}
+
+long long cbm_store_observed_pair_total(cbm_store_t *s, const char *project) {
+ if (!s || !s->db || !project)
+ return -1;
+ sqlite3_stmt *stmt = NULL;
+ if (sqlite3_prepare_v2(s->db, "SELECT COUNT(*) FROM observed_calls WHERE project=?1", -1, &stmt,
+ NULL) != SQLITE_OK)
+ return -1;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ long long total = -1;
+ if (sqlite3_step(stmt) == SQLITE_ROW)
+ total = sqlite3_column_int64(stmt, 0);
+ sqlite3_finalize(stmt);
+ return total;
+}
+
+/* Evict the run label whose newest observation is oldest — whole runs at a
+ * time, so a partially-evicted run can never masquerade as complete.
+ * evicted_label_out (optional) receives a heap copy the caller frees. */
+int cbm_store_observed_evict_oldest_label(cbm_store_t *s, const char *project,
+ char **evicted_label_out) {
+ if (evicted_label_out)
+ *evicted_label_out = NULL;
+ if (!s || !s->db || !project)
+ return CBM_STORE_ERR;
+ sqlite3_stmt *stmt = NULL;
+ if (sqlite3_prepare_v2(s->db,
+ /* rowid tiebreak: last_seen has second resolution,
+ * and eviction order must never be a timing lottery —
+ * on a tie the earliest-inserted run is the oldest. */
+ "SELECT label FROM observed_calls WHERE project=?1 GROUP BY label"
+ " ORDER BY MAX(last_seen) ASC, MIN(rowid) ASC LIMIT 1",
+ -1, &stmt, NULL) != SQLITE_OK)
+ return CBM_STORE_ERR;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ char label[CBM_SZ_256] = {0};
+ bool found = false;
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ const char *l = (const char *)sqlite3_column_text(stmt, 0);
+ snprintf(label, sizeof(label), "%s", l ? l : "");
+ found = true;
+ }
+ sqlite3_finalize(stmt);
+ if (!found)
+ return CBM_STORE_ERR;
+ static const char *const wipes[] = {
+ "DELETE FROM observed_calls WHERE project=?1 AND label=?2",
+ "DELETE FROM observed_paths WHERE project=?1 AND label=?2",
+ };
+ for (size_t i = 0; i < sizeof(wipes) / sizeof(wipes[0]); i++) {
+ if (sqlite3_prepare_v2(s->db, wipes[i], -1, &stmt, NULL) != SQLITE_OK)
+ return CBM_STORE_ERR;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, 2, label, -1, SQLITE_TRANSIENT);
+ int rc = sqlite3_step(stmt);
+ sqlite3_finalize(stmt);
+ if (rc != SQLITE_DONE) {
+ store_set_error_sqlite(s, "observed_evict");
+ return CBM_STORE_ERR;
+ }
+ }
+ if (evicted_label_out) {
+ size_t len = strlen(label) + 1;
+ char *copy = malloc(len);
+ if (copy)
+ memcpy(copy, label, len);
+ *evicted_label_out = copy;
+ }
+ return CBM_STORE_OK;
+}
+
+/* Aggregate observation for one call edge: total count across runs, the
+ * newest run's label and timestamp. Returns CBM_STORE_OK with *count_out=0
+ * when the pair was never observed (absence is data, not an error). */
+int cbm_store_observed_lookup(cbm_store_t *s, const char *project, const char *caller_qn,
+ const char *callee_qn, long long *count_out, char *label_buf,
+ size_t label_cap, char *last_seen_buf, size_t last_seen_cap) {
+ if (count_out)
+ *count_out = 0;
+ if (label_buf && label_cap)
+ label_buf[0] = '\0';
+ if (last_seen_buf && last_seen_cap)
+ last_seen_buf[0] = '\0';
+ if (!s || !s->db || !project || !caller_qn || !callee_qn)
+ return CBM_STORE_ERR;
+ sqlite3_stmt *stmt = NULL;
+ if (sqlite3_prepare_v2(s->db,
+ /* rowid tiebreak: last_seen has second resolution;
+ * on a tie the later-inserted run is the newer one. */
+ "SELECT count, label, last_seen FROM observed_calls WHERE project=?1"
+ " AND caller_qn=?2 AND callee_qn=?3"
+ " ORDER BY last_seen DESC, rowid DESC",
+ -1, &stmt, NULL) != SQLITE_OK)
+ return CBM_STORE_ERR;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, 2, caller_qn, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, 3, callee_qn, -1, SQLITE_TRANSIENT);
+ long long total = 0;
+ bool first = true;
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ total += sqlite3_column_int64(stmt, 0);
+ if (first) {
+ const char *l = (const char *)sqlite3_column_text(stmt, 1);
+ const char *seen = (const char *)sqlite3_column_text(stmt, 2);
+ if (label_buf && label_cap)
+ snprintf(label_buf, label_cap, "%s", l ? l : "");
+ if (last_seen_buf && last_seen_cap)
+ snprintf(last_seen_buf, last_seen_cap, "%s", seen ? seen : "");
+ first = false;
+ }
+ }
+ sqlite3_finalize(stmt);
+ if (count_out)
+ *count_out = total;
+ return CBM_STORE_OK;
+}
diff --git a/src/store/store.h b/src/store/store.h
index 8c2f76dd8..f6fa58a35 100644
--- a/src/store/store.h
+++ b/src/store/store.h
@@ -580,6 +580,23 @@ int cbm_store_coverage_get_scope(cbm_store_t *s, const char *project, const char
/* Fetch/free the metadata paired with the current coverage row set. */
int cbm_store_coverage_meta_get(cbm_store_t *s, const char *project, cbm_coverage_meta_t *out);
+
+/* ── Observed runtime calls (ingest_traces) ──────────────────────────
+ * Separate from the graph tables and keyed by qualified name: node ids are
+ * reassigned on reindex, names survive. A "label" identifies one run
+ * (e.g. "pytest 2026-08-27"); counts accumulate per (pair, label). */
+int cbm_store_observed_upsert_pair(cbm_store_t *s, const char *project, const char *caller_qn,
+ const char *callee_qn, const char *label, long long count);
+int cbm_store_observed_upsert_path(cbm_store_t *s, const char *project, const char *path_json,
+ const char *label, long long count);
+long long cbm_store_observed_pair_total(cbm_store_t *s, const char *project);
+int cbm_store_observed_evict_oldest_label(cbm_store_t *s, const char *project,
+ char **evicted_label_out);
+/* *count_out = 0 when never observed (absence is data, not an error);
+ * label/last_seen receive the NEWEST run's values. */
+int cbm_store_observed_lookup(cbm_store_t *s, const char *project, const char *caller_qn,
+ const char *callee_qn, long long *count_out, char *label_buf,
+ size_t label_cap, char *last_seen_buf, size_t last_seen_cap);
void cbm_store_coverage_meta_clear(cbm_coverage_meta_t *meta);
/* Name of the derived miss-graph shadow project ("<project>::missed").
diff --git a/src/ui/atlas.h b/src/ui/atlas.h
index 6e23209b9..ebdae86c1 100644
--- a/src/ui/atlas.h
+++ b/src/ui/atlas.h
@@ -83,6 +83,12 @@ char *cbm_atlas_trace_json(cbm_store_t *store, const char *project, int64_t from
char *cbm_atlas_impact_json(cbm_store_t *store, const char *project, int64_t node_id,
const char *node_qn);
+/* Attach runtime observation (observed_calls) to a trace ("path") or
+ * flow-detail ("steps") JSON: observed hops gain {count, label,
+ * last_seen}; unobserved hops stay merely possible. Takes ownership of
+ * `json` and returns it (or a replacement). */
+char *cbm_atlas_attach_observed(cbm_store_t *store, const char *project, char *json);
+
/* ── Region lookups (layout_regions.c) ────────────────────────────
* Cache-backed; computing on first use. name_out (optional) receives a
* heap copy the caller frees. Returns region id or -1. */
diff --git a/src/ui/http_server.c b/src/ui/http_server.c
index 7da082d2c..3e310b793 100644
--- a/src/ui/http_server.c
+++ b/src/ui/http_server.c
@@ -1925,10 +1925,106 @@ static void handle_atlas_trace(cbm_http_conn_t *c, const cbm_http_req_t *req) {
cbm_http_query_param(req->query, "guards", wantg, (int)sizeof(wantg));
if (json && wantg[0] == '1')
json = atlas_trace_attach_guards(store, project, json);
+ json = cbm_atlas_attach_observed(store, project, json);
cbm_store_close(store);
atlas_reply_json(c, json, 500, "{\"error\":\"trace failed\"}");
}
+/* Attach runtime observation to a trace ("path") or flow-detail ("steps")
+ * JSON: every hop whose (caller, callee) pair appears in observed_calls
+ * gains "observed": {count, label, last_seen}. Observation is qn-keyed
+ * (reindex-proof), so hop ids resolve to qualified names first. Absence
+ * adds nothing — an unobserved hop stays merely possible, never "dead". */
+char *cbm_atlas_attach_observed(cbm_store_t *store, const char *project, char *json) {
+ if (!json)
+ return json;
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ if (!doc)
+ return json;
+ yyjson_val *root = yyjson_doc_get_root(doc);
+ bool is_trace = yyjson_obj_get(root, "path") != NULL;
+ bool is_flow = yyjson_obj_get(root, "steps") != NULL;
+ if (!is_trace && !is_flow) {
+ yyjson_doc_free(doc);
+ return json;
+ }
+ yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, NULL);
+ yyjson_doc_free(doc);
+ if (!mut)
+ return json;
+ yyjson_mut_val *mroot = yyjson_mut_doc_get_root(mut);
+ yyjson_mut_val *arr = yyjson_mut_obj_get(mroot, is_trace ? "path" : "steps");
+ size_t count = arr ? yyjson_mut_arr_size(arr) : 0;
+ struct sqlite3 *db = cbm_store_get_db(store);
+ sqlite3_stmt *qn_stmt = NULL;
+ if (count >= 2 && db)
+ (void)sqlite3_prepare_v2(db, "SELECT qualified_name FROM nodes WHERE id=?1 LIMIT 1", -1,
+ &qn_stmt, NULL);
+ if (qn_stmt) {
+ /* Per-request id→qn memo: flows revisit parents for every child. */
+ enum { OBS_MEMO_MAX = 64 };
+ int64_t memo_id[OBS_MEMO_MAX];
+ char memo_qn[OBS_MEMO_MAX][512];
+ int memo_count = 0;
+ for (size_t i = is_trace ? 1 : 0; i < count; i++) {
+ yyjson_mut_val *step = yyjson_mut_arr_get(arr, i);
+ yyjson_mut_val *parent = NULL;
+ if (is_trace) {
+ parent = yyjson_mut_arr_get(arr, i - 1);
+ } else {
+ int64_t pidx = yyjson_mut_get_int(yyjson_mut_obj_get(step, "parent"));
+ if (pidx < 0 || (size_t)pidx >= count)
+ continue;
+ parent = yyjson_mut_arr_get(arr, (size_t)pidx);
+ }
+ const int64_t ids[2] = {yyjson_mut_get_int(yyjson_mut_obj_get(parent, "id")),
+ yyjson_mut_get_int(yyjson_mut_obj_get(step, "id"))};
+ const char *qns[2] = {NULL, NULL};
+ for (int side = 0; side < 2; side++) {
+ for (int m = 0; m < memo_count; m++)
+ if (memo_id[m] == ids[side]) {
+ qns[side] = memo_qn[m];
+ break;
+ }
+ if (qns[side])
+ continue;
+ sqlite3_reset(qn_stmt);
+ sqlite3_bind_int64(qn_stmt, 1, ids[side]);
+ if (sqlite3_step(qn_stmt) == SQLITE_ROW && memo_count < OBS_MEMO_MAX) {
+ const char *qn = (const char *)sqlite3_column_text(qn_stmt, 0);
+ if (qn) {
+ memo_id[memo_count] = ids[side];
+ snprintf(memo_qn[memo_count], sizeof(memo_qn[0]), "%s", qn);
+ qns[side] = memo_qn[memo_count];
+ memo_count++;
+ }
+ }
+ }
+ if (!qns[0] || !qns[1])
+ continue;
+ long long observed_count = 0;
+ char label[256], last_seen[64];
+ if (cbm_store_observed_lookup(store, project, qns[0], qns[1], &observed_count, label,
+ sizeof(label), last_seen,
+ sizeof(last_seen)) != CBM_STORE_OK ||
+ observed_count <= 0)
+ continue;
+ yyjson_mut_val *obs = yyjson_mut_obj(mut);
+ yyjson_mut_obj_add_int(mut, obs, "count", observed_count);
+ yyjson_mut_obj_add_strcpy(mut, obs, "label", label);
+ yyjson_mut_obj_add_strcpy(mut, obs, "last_seen", last_seen);
+ yyjson_mut_obj_add_val(mut, step, "observed", obs);
+ }
+ sqlite3_finalize(qn_stmt);
+ }
+ char *out = yyjson_mut_write(mut, 0, NULL);
+ yyjson_mut_doc_free(mut);
+ if (!out)
+ return json;
+ free(json);
+ return out;
+}
+
/* GET /api/symbol-history?project=X&file=PATH&start=N&end=N — per-symbol
* git history (log -L over the symbol's line range), on demand. */
static void handle_atlas_symbol_history(cbm_http_conn_t *c, const cbm_http_req_t *req) {
@@ -2164,6 +2260,7 @@ static void handle_atlas_flow(cbm_http_conn_t *c, const cbm_http_req_t *req) {
cbm_http_query_param(req->query, "guards", wantg, (int)sizeof(wantg));
if (json && wantg[0] == '1')
json = atlas_flow_attach_guards(store, project, json);
+ json = cbm_atlas_attach_observed(store, project, json);
cbm_store_close(store);
atlas_reply_json(c, json, 404, "{\"error\":\"unknown flow\"}");
}
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 278d33e68..6b3318d0f 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -2569,6 +2569,123 @@ TEST(tool_index_status_no_project) {
PASS();
}
+/* ingest_traces stores observed runtime calls qn-keyed (reindex-proof):
+ * paths decompose into pairs, counts accumulate per run label, unresolved
+ * names are reported (not silently dropped), whole runs evict together. */
+TEST(tool_ingest_traces_stores_observed_calls) {
+ 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);
+ const char *project = "traces-test";
+ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/traces-test"), CBM_STORE_OK);
+ cbm_mcp_server_set_project(srv, project);
+
+ static const char *const names[3] = {"alpha", "beta", "gamma"};
+ for (int i = 0; i < 3; i++) {
+ cbm_node_t node;
+ memset(&node, 0, sizeof(node));
+ node.project = project;
+ node.label = "Function";
+ node.name = names[i];
+ char qn[64];
+ snprintf(qn, sizeof(qn), "traces-test::%s", names[i]);
+ node.qualified_name = qn;
+ node.file_path = "src/t.c";
+ node.start_line = 1;
+ node.end_line = 3;
+ ASSERT_GT(cbm_store_upsert_node(st, &node), 0);
+ }
+
+ /* One 3-hop path, one bare pair with a count, one path with an
+ * unindexed hop (skipped, reported), one malformed 1-hop path. */
+ char *resp = cbm_mcp_handle_tool(
+ srv, "ingest_traces",
+ "{\"project\":\"traces-test\",\"label\":\"run1\",\"traces\":["
+ "{\"path\":[\"traces-test::alpha\",\"traces-test::beta\",\"traces-test::gamma\"]},"
+ "{\"caller\":\"traces-test::alpha\",\"callee\":\"traces-test::gamma\",\"count\":5},"
+ "{\"path\":[\"traces-test::alpha\",\"traces-test::missing\"]},"
+ "{\"path\":[\"traces-test::alpha\"]}]}");
+ ASSERT_NOT_NULL(resp);
+ char *inner = extract_text_content(resp);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NOT_NULL(strstr(inner, "\"status\":\"stored\""));
+ ASSERT_NOT_NULL(strstr(inner, "\"pairs_stored\":3"));
+ ASSERT_NOT_NULL(strstr(inner, "\"paths_stored\":1"));
+ ASSERT_NOT_NULL(strstr(inner, "\"pairs_unmatched\":1"));
+ ASSERT_NOT_NULL(strstr(inner, "traces-test::missing"));
+ ASSERT_NOT_NULL(strstr(inner, "\"malformed\":1"));
+ free(inner);
+ free(resp);
+
+ long long count = -1;
+ char label[64], seen[64];
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::beta",
+ &count, label, sizeof(label), seen, sizeof(seen)),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 1);
+ ASSERT_STR_EQ(label, "run1");
+ ASSERT_TRUE(seen[0] != '\0');
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::gamma",
+ &count, NULL, 0, NULL, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 5);
+ /* Never observed: zero count, not an error. */
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::beta", "traces-test::alpha",
+ &count, NULL, 0, NULL, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 0);
+
+ /* Same pair again under the same label accumulates; a second label
+ * aggregates in the lookup and reports as the newest run. */
+ resp = cbm_mcp_handle_tool(
+ srv, "ingest_traces",
+ "{\"project\":\"traces-test\",\"label\":\"run1\",\"traces\":[{\"caller\":"
+ "\"traces-test::alpha\",\"callee\":\"traces-test::gamma\",\"count\":2}]}");
+ ASSERT_NOT_NULL(resp);
+ free(resp);
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::gamma",
+ &count, NULL, 0, NULL, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 7);
+ resp = cbm_mcp_handle_tool(
+ srv, "ingest_traces",
+ "{\"project\":\"traces-test\",\"label\":\"run2\",\"traces\":[{\"caller\":"
+ "\"traces-test::alpha\",\"callee\":\"traces-test::beta\"}]}");
+ ASSERT_NOT_NULL(resp);
+ free(resp);
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::beta",
+ &count, label, sizeof(label), NULL, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 2);
+ ASSERT_STR_EQ(label, "run2");
+
+ /* Whole-run eviction: run1's newest observation is older, so run1 goes
+ * first and run2 survives intact. */
+ char *evicted = NULL;
+ ASSERT_EQ(cbm_store_observed_evict_oldest_label(st, project, &evicted), CBM_STORE_OK);
+ ASSERT_NOT_NULL(evicted);
+ ASSERT_STR_EQ(evicted, "run1");
+ free(evicted);
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::gamma",
+ &count, NULL, 0, NULL, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 0);
+ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::beta",
+ &count, NULL, 0, NULL, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ((int)count, 1);
+
+ /* Empty traces is a tool error, not a silent accept. */
+ resp = cbm_mcp_handle_tool(srv, "ingest_traces", "{\"project\":\"traces-test\",\"traces\":[]}");
+ ASSERT_NOT_NULL(resp);
+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));
+ free(resp);
+
+ cbm_mcp_server_free(srv);
+ PASS();
+}
+
/* Reproduce the exact-file false negative in the current Read hook: index_status
* intentionally caps each coverage category at 500 entries, so a later path is
* absent even though the authoritative index_coverage table contains it. The
@@ -7609,6 +7726,9 @@ TEST(detect_changes_zero_overlap_falls_back_issue1363) {
PASS();
}
+/* ingest_traces stores for real now (the stub answered "accepted" and
+ * discarded). Without a resolvable project there is nothing to store
+ * against — a tool error, not a polite lie. */
TEST(tool_ingest_traces_basic) {
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
@@ -7617,8 +7737,8 @@ TEST(tool_ingest_traces_basic) {
"\"params\":{\"name\":\"ingest_traces\","
"\"arguments\":{\"traces\":[{\"caller\":\"a\",\"callee\":\"b\"}]}}}");
ASSERT_NOT_NULL(resp);
- ASSERT_NOT_NULL(strstr(resp, "accepted"));
- ASSERT_NOT_NULL(strstr(resp, "traces_received"));
+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));
+ ASSERT_NULL(strstr(resp, "accepted"));
free(resp);
cbm_mcp_server_free(srv);
@@ -7633,7 +7753,7 @@ TEST(tool_ingest_traces_empty) {
"\"params\":{\"name\":\"ingest_traces\","
"\"arguments\":{\"traces\":[]}}}");
ASSERT_NOT_NULL(resp);
- ASSERT_NOT_NULL(strstr(resp, "accepted"));
+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));
free(resp);
cbm_mcp_server_free(srv);
@@ -11327,6 +11447,7 @@ SUITE(mcp) {
RUN_TEST(mcp_resource_discovery_methods_return_empty_lists);
RUN_TEST(tool_query_graph_basic);
RUN_TEST(tool_index_status_no_project);
+ RUN_TEST(tool_ingest_traces_stores_observed_calls);
RUN_TEST(tool_check_index_coverage_finds_path_beyond_status_cap);
RUN_TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges);
RUN_TEST(tool_check_index_coverage_preserves_multiple_scope_labels);
diff --git a/tests/test_ui.c b/tests/test_ui.c
index 65bc9627a..558a5c254 100644
--- a/tests/test_ui.c
+++ b/tests/test_ui.c
@@ -1845,6 +1845,91 @@ static const char *WHY_SAMPLE_C = "void beta(void);\n"
" }\n"
"}\n";
+/* Observed runtime calls attach to trace and flow JSON by qualified name:
+ * an observed hop gains {count, label, last_seen}; an unobserved hop and
+ * absent stores add nothing (absence is data, never "dead"). */
+TEST(atlas_attach_observed_marks_hops) {
+ cbm_layout_regions_cache_clear();
+ cbm_atlas_flows_cache_clear();
+ cbm_store_t *store = regions_fixture();
+ ASSERT_NOT_NULL(store);
+
+ /* alpha_one → beta_one observed twice in one run; the rest never ran. */
+ ASSERT_EQ(cbm_store_observed_upsert_pair(store, "regions-test", "regions-test::alpha_one",
+ "regions-test::beta_one", "pytest", 2),
+ CBM_STORE_OK);
+
+ char *json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::alpha_one", -1,
+ "regions-test::beta_three", "calls");
+ ASSERT_NOT_NULL(json);
+ json = cbm_atlas_attach_observed(store, "regions-test", json);
+ ASSERT_NOT_NULL(json);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *path = yyjson_obj_get(yyjson_doc_get_root(doc), "path");
+ ASSERT_GT((int)yyjson_arr_size(path), 2);
+ /* Hop 0→1 is alpha_one→beta_one: observed lands on the CALLEE hop. */
+ yyjson_val *hop1 = yyjson_arr_get(path, 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(hop1, "name")), "beta_one");
+ yyjson_val *obs = yyjson_obj_get(hop1, "observed");
+ ASSERT_NOT_NULL(obs);
+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(obs, "count")), 2);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(obs, "label")), "pytest");
+ ASSERT_NOT_NULL(yyjson_get_str(yyjson_obj_get(obs, "last_seen")));
+ /* The next hop (beta_one→beta_three) never ran: no marker. */
+ yyjson_val *hop2 = yyjson_arr_get(path, 2);
+ ASSERT_NULL(yyjson_obj_get(hop2, "observed"));
+ yyjson_doc_free(doc);
+ free(json);
+
+ /* Flow shape: steps with parent indices join the same way. */
+ int64_t alpha_one_id = -1, beta_one_id = -1;
+ const struct {
+ const char *qn;
+ int64_t *out;
+ } wanted[2] = {{"regions-test::alpha_one", &alpha_one_id},
+ {"regions-test::beta_one", &beta_one_id}};
+ for (int i = 0; i < 2; i++) {
+ cbm_search_params_t params;
+ memset(&params, 0, sizeof(params));
+ params.project = "regions-test";
+ params.qn_pattern = wanted[i].qn;
+ params.limit = 1;
+ params.min_degree = -1;
+ params.max_degree = -1;
+ cbm_search_output_t out;
+ memset(&out, 0, sizeof(out));
+ if (cbm_store_search(store, &params, &out) == CBM_STORE_OK && out.count == 1)
+ *wanted[i].out = out.results[0].node.id;
+ cbm_store_search_free(&out);
+ }
+ ASSERT_GT(alpha_one_id, 0);
+ ASSERT_GT(beta_one_id, 0);
+ char flow_json[256];
+ snprintf(flow_json, sizeof(flow_json),
+ "{\"steps\":[{\"id\":%lld,\"parent\":-1},{\"id\":%lld,\"parent\":0}]}",
+ (long long)alpha_one_id, (long long)beta_one_id);
+ char *owned = malloc(strlen(flow_json) + 1);
+ ASSERT_NOT_NULL(owned);
+ strcpy(owned, flow_json);
+ owned = cbm_atlas_attach_observed(store, "regions-test", owned);
+ ASSERT_NOT_NULL(owned);
+ doc = yyjson_read(owned, strlen(owned), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *steps = yyjson_obj_get(yyjson_doc_get_root(doc), "steps");
+ yyjson_val *step1 = yyjson_arr_get(steps, 1);
+ obs = yyjson_obj_get(step1, "observed");
+ ASSERT_NOT_NULL(obs);
+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(obs, "count")), 2);
+ yyjson_doc_free(doc);
+ free(owned);
+
+ cbm_store_close(store);
+ cbm_atlas_flows_cache_clear();
+ cbm_layout_regions_cache_clear();
+ PASS();
+}
+
/* Per-symbol history: `git log -L` over the symbol's line range, with the
* forge base URL normalized for the UI's commit/#ref links. Runs against a
* real throwaway git repo; environments without git pass through (the
@@ -2082,6 +2167,7 @@ SUITE(ui) {
RUN_TEST(atlas_symbol_overflow_tail_and_dataflow_presence);
RUN_TEST(atlas_blast_buckets_files_by_region);
RUN_TEST(atlas_handout_is_selfcontained_and_escaped);
+ RUN_TEST(atlas_attach_observed_marks_hops);
RUN_TEST(atlas_symbol_history_log_l_and_remote);
RUN_TEST(atlas_why_extracts_guard_chains);
}