| 374 | } |
| 375 | |
| 376 | int cbm_activity_ingest(sqlite3 *db, const char *body, char **reply) { |
| 377 | *reply = NULL; |
| 378 | if (!db) |
| 379 | return 503; |
| 380 | yyjson_doc *doc = body ? yyjson_read(body, strlen(body), 0) : NULL; |
| 381 | yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL; |
| 382 | yyjson_val *events = yyjson_obj_get(root, "events"); |
| 383 | const char *project = string_field(root, "project"); |
| 384 | if (!yyjson_is_arr(events) || yyjson_arr_size(events) > 100 || strlen(project) > 255) { |
| 385 | yyjson_doc_free(doc); |
| 386 | return 400; |
| 387 | } |
| 388 | size_t i, max; |
| 389 | yyjson_val *e; |
| 390 | yyjson_arr_foreach(events, i, max, e) { |
| 391 | const char *run = string_field(e, "run"); |
| 392 | const char *agent = string_field(e, "agent"); |
| 393 | const char *tool = string_field(e, "tool"); |
| 394 | const char *phase = string_field(e, "phase"); |
| 395 | yyjson_val *seq = yyjson_obj_get(e, "seq"); |
| 396 | yyjson_val *ts = yyjson_obj_get(e, "ts"); |
| 397 | if (!*run || strlen(run) > 255 || !*agent || strlen(agent) > 255 || !*tool || |
| 398 | strlen(tool) > 255 || (!yyjson_is_uint(seq) && !yyjson_is_sint(seq)) || |
| 399 | yyjson_get_sint(seq) < 0 || yyjson_get_sint(seq) > 9007199254740991LL || |
| 400 | !yyjson_is_num(ts) || yyjson_get_num(ts) < 0 || |
| 401 | yyjson_get_num(ts) > 8640000000000000.0 || |
| 402 | (strcmp(phase, "start") && strcmp(phase, "end"))) { |
| 403 | yyjson_doc_free(doc); |
| 404 | return 400; |
| 405 | } |
| 406 | } |
| 407 | if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) { |
| 408 | yyjson_doc_free(doc); |
| 409 | return 503; |
| 410 | } |
| 411 | sqlite3_stmt *st = NULL; |
| 412 | bool ok = sqlite3_prepare_v2( |
| 413 | db, |
| 414 | "INSERT OR IGNORE INTO agent_events(project,run,seq,payload) SELECT ?1,?2,?3,?4 " |
| 415 | "WHERE NOT EXISTS(SELECT 1 FROM agent_retired WHERE project=?1 AND run=?2 AND " |
| 416 | "max_seq>=?3)", |
| 417 | -1, &st, NULL) == SQLITE_OK; |
| 418 | int accepted = 0; |
| 419 | yyjson_arr_foreach(events, i, max, e) { |
| 420 | if (!ok) |
| 421 | break; |
| 422 | /* Persist only the event contract, never arbitrary tool responses. */ |
| 423 | yyjson_mut_doc *clean = yyjson_mut_doc_new(NULL); |
| 424 | yyjson_mut_val *obj = yyjson_mut_obj(clean); |
| 425 | yyjson_mut_doc_set_root(clean, obj); |
| 426 | const char *fields[] = {"ts", "agent", "run", "seq", "phase", |
| 427 | "tool", "path", "lines", "detail", "intent", |
| 428 | "source", "replay", "ts_recorded"}; |
| 429 | for (size_t k = 0; k < sizeof(fields) / sizeof(fields[0]); k++) { |
| 430 | yyjson_val *v = yyjson_obj_get(e, fields[k]); |
| 431 | if (v) |
| 432 | yyjson_mut_obj_add(obj, yyjson_mut_str(clean, fields[k]), |
| 433 | yyjson_val_mut_copy(clean, v)); |
no test coverage detected