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(test-impact): detect_changes scope:"tests" end to end

Martin Vogelc5abb64943ec
diff --git a/.codebase-memory.json b/.codebase-memory.json
new file mode 100644
index 000000000..855970754
--- /dev/null
+++ b/.codebase-memory.json
@@ -0,0 +1,49 @@
+{
+ "test_impact": {
+ "version": 1,
+ "tests": {
+ "presets": {
+ "c-cbm": true
+ }
+ },
+ "rules": [
+ {
+ "id": "harness",
+ "paths": ["tests/test_framework.h", "tests/test_helpers.*", "tests/test_main.c"],
+ "action": "run_all"
+ },
+ {
+ "id": "engine",
+ "paths": [".codebase-memory.json", "src/mcp/test_impact*", "src/store/store_impact.*"],
+ "action": "run_all"
+ },
+ {
+ "id": "build",
+ "paths": ["scripts/**", "test-infrastructure/**", "pkg/**"],
+ "action": "run_all"
+ },
+ {
+ "id": "grammars",
+ "paths": ["internal/cbm/vendored/**"],
+ "action": "run_all"
+ },
+ {
+ "id": "fixtures",
+ "paths": ["tests/fixtures/*/**"],
+ "action": "referencing_tests",
+ "key": "path_segment:2"
+ },
+ {
+ "id": "contracts",
+ "paths": ["tests/**/*.{sh,py,json,txt}"],
+ "action": "ignore"
+ },
+ {
+ "id": "notices",
+ "paths": ["NOTICE*", "CHANGELOG*", "THIRD_PARTY*"],
+ "action": "ignore"
+ }
+ ],
+ "unmapped_files": "run_all"
+ }
+}
diff --git a/Makefile.cbm b/Makefile.cbm
index a545e246b..3c4e3d2a5 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -429,7 +429,7 @@ CYPHER_SRCS = src/cypher/cypher.c
# MCP server module (new)
MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c \
- src/mcp/test_impact.c src/mcp/test_impact_diff.c src/mcp/test_impact_changes.c src/mcp/test_impact_origins.c src/mcp/test_impact_coverage.c src/mcp/test_impact_config.c src/mcp/test_impact_select.c src/mcp/test_impact_policy.c src/mcp/test_impact_git.c src/mcp/test_impact_inventory.c src/mcp/test_impact_inventory_input.c src/mcp/test_impact_tree.c src/mcp/test_impact_tree_audit.c src/mcp/test_impact_tree_read.c src/mcp/test_impact_tree_batch.c src/mcp/test_impact_tree_digest.c src/mcp/test_impact_tree_names.c src/mcp/test_impact_tree_plan.c src/mcp/test_impact_tree_posix.c src/mcp/test_impact_tree_posix_acl.c src/mcp/test_impact_tree_posix_io.c src/mcp/test_impact_tree_util.c src/mcp/test_impact_tree_windows.c src/mcp/test_impact_tree_windows_acl.c src/mcp/test_impact_tree_windows_io.c \
+ src/mcp/test_impact.c src/mcp/test_impact_diff.c src/mcp/test_impact_classify.c src/mcp/test_impact_source.c src/mcp/test_impact_seed.c src/mcp/test_impact_engine.c src/mcp/test_impact_engine_snapshot.c src/mcp/test_impact_engine_reach.c src/mcp/test_impact_changes.c src/mcp/test_impact_origins.c src/mcp/test_impact_coverage.c src/mcp/test_impact_config.c src/mcp/test_impact_select.c src/mcp/test_impact_policy.c src/mcp/test_impact_git.c src/mcp/test_impact_inventory.c src/mcp/test_impact_inventory_input.c src/mcp/test_impact_tree.c src/mcp/test_impact_tree_audit.c src/mcp/test_impact_tree_read.c src/mcp/test_impact_tree_batch.c src/mcp/test_impact_tree_digest.c src/mcp/test_impact_tree_names.c src/mcp/test_impact_tree_plan.c src/mcp/test_impact_tree_posix.c src/mcp/test_impact_tree_posix_acl.c src/mcp/test_impact_tree_posix_io.c src/mcp/test_impact_tree_util.c src/mcp/test_impact_tree_windows.c src/mcp/test_impact_tree_windows_acl.c src/mcp/test_impact_tree_windows_io.c \
src/mcp/test_impact_result.c src/mcp/test_impact_result_json.c src/mcp/test_impact_result_project.c src/mcp/test_impact_result_receipt.c src/mcp/test_impact_result_rows.c src/mcp/test_impact_result_util.c src/mcp/test_impact_result_validate.c src/mcp/test_impact_result_wire.c
# Shared MCP daemon coordination and local transport
@@ -705,6 +705,10 @@ TEST_MCP_SRCS = \
tests/test_test_impact_git.c \
tests/test_test_impact_tree.c \
tests/test_test_impact_inventory.c \
+ tests/test_test_impact_classify.c \
+ tests/test_test_impact_source.c \
+ tests/test_test_impact_seed.c \
+ tests/test_test_impact_engine.c \
tests/test_test_impact_inventory_errors.c \
tests/test_test_impact_inventory_support.c \
tests/test_test_impact_runner_filter.c \
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c
index 3c29bd8dd..ceb08843e 100644
--- a/internal/cbm/cbm.c
+++ b/internal/cbm/cbm.c
@@ -2380,16 +2380,18 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
cbm_run_go_lsp(a, result, source, source_len, root);
}
if (language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA) {
- if (!cbm_run_c_lsp_with_test_owners(
- a, result, source, source_len, root, language != CBM_LANG_C,
- CBM_SOURCE_ORIGIN_RAW, result)) {
+ if (!cbm_run_c_lsp_with_test_owners(a, result, source, source_len, root,
+ language != CBM_LANG_C, CBM_SOURCE_ORIGIN_RAW,
+ result)) {
result->has_error = true;
if (result->test_declarations_status == CBM_TEST_EXTRACT_OK) {
result->test_declarations_status = CBM_TEST_EXTRACT_UNSUPPORTED_FORM;
result->test_declaration_index = -1;
result->test_declaration_line = 0;
- result->error_msg = cbm_arena_strdup(a, "configured owner source identity mismatch");
- if (!result->error_msg) result->test_declarations_status = CBM_TEST_EXTRACT_OOM;
+ result->error_msg =
+ cbm_arena_strdup(a, "configured owner source identity mismatch");
+ if (!result->error_msg)
+ result->test_declarations_status = CBM_TEST_EXTRACT_OOM;
}
}
}
@@ -3068,16 +3070,15 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua
const char **include_paths, const CBMMacroTable *macro_table,
const CBMReturnTypeTable *return_type_table) {
return cbm_extract_file_ex_with_tests(source, source_len, language, project, rel_path,
- timeout_micros, extra_defines, include_paths,
- macro_table, return_type_table, NULL);
+ timeout_micros, extra_defines, include_paths, macro_table,
+ return_type_table, NULL);
}
CBMFileResult *cbm_extract_file_ex_with_tests(
const char *source, int source_len, CBMLanguage language, const char *project,
const char *rel_path, int64_t timeout_micros, const char **extra_defines,
const char **include_paths, const CBMMacroTable *macro_table,
- const CBMReturnTypeTable *return_type_table,
- const cbm_test_declarations_t *test_declarations) {
+ const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations) {
CBMArena scratch;
if (tl_scratch_live && tl_scratch_slot) {
scratch = *tl_scratch_slot;
@@ -3086,10 +3087,9 @@ CBMFileResult *cbm_extract_file_ex_with_tests(
} else {
cbm_arena_init_lazy(&scratch, CBM_EXTRACT_SCRATCH_BLOCK);
}
- CBMFileResult *result = extract_file_ex_body(source, source_len, language, project, rel_path,
- timeout_micros, extra_defines, include_paths,
- macro_table, return_type_table, &scratch,
- test_declarations);
+ CBMFileResult *result = extract_file_ex_body(
+ source, source_len, language, project, rel_path, timeout_micros, extra_defines,
+ include_paths, macro_table, return_type_table, &scratch, test_declarations);
/* !tl_scratch_live: a nested extraction (an embedded language inside this
* file) may already have parked its own; never overwrite it. */
/* Kept up to CBM_EXTRACT_SCRATCH_KEEP_BYTES, grown blocks included: the
@@ -3110,6 +3110,7 @@ CBMFileResult *cbm_extract_file_ex_with_tests(
} else {
cbm_arena_destroy(&scratch);
}
+ cbm_test_declarations_degrade(result);
return result;
}
diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h
index b14a4aaca..9595f1aff 100644
--- a/internal/cbm/cbm.h
+++ b/internal/cbm/cbm.h
@@ -636,12 +636,21 @@ typedef struct CBMFileResult {
// by cbm_free_result(); ordinary single-file results leave these zeroed.
struct CBMFileResult **owned_results;
int owned_result_count;
- /* A consumed configured definition could not be mapped safely. Pipeline
- * callers must abort publication; error_msg is arena-owned as usual. */
+ /* A consumed configured definition could not be mapped safely. Only an
+ * allocation failure (OOM) still aborts publication: any other status is
+ * degraded per file by cbm_test_declarations_degrade. error_msg is
+ * arena-owned as usual. */
CBMTestExtractStatus test_declarations_status;
- int test_declaration_index; /* meaningful on failure; -1 = preset */
+ int test_declaration_index; /* meaningful on failure; -1 = preset */
uint32_t test_declaration_line; /* 0 = snapshot preflight */
bool has_test_definition_owners;
+ /* has_error was raised by a configured-definition issue alone. */
+ bool test_error_only;
+ /* The file's configured test forms could not be mapped: it carries no
+ * configured test roles; the status names why (no pointer: compaction
+ * and spill relocate only the strings they know). */
+ bool test_declarations_degraded;
+ CBMTestExtractStatus test_declarations_degraded_status;
int test_owner_source_len;
CBMLanguage test_owner_language;
char test_owner_source_sha256[65]; /* exact raw source; identity, not authentication */
@@ -739,6 +748,15 @@ typedef struct {
} CBMExtractCtx;
/* Internal configured-definition seams. No declarations pointer enters a result. */
+/* A configured test form the extractor cannot map degrades the FILE, not
+ * the index (user decision 2026-10-04): its configured test roles, owner
+ * spans and owner flag are dropped, the status reads OK again, an error the
+ * issue alone raised is cleared, and test_declarations_degraded keeps the
+ * reason for a per-file diagnostic. OK and OOM results are left unchanged:
+ * an allocation failure still fails. Idempotent. */
+void cbm_test_declarations_degrade(CBMFileResult *result);
+/* The fixed description of a configured-definition status (static). */
+const char *cbm_test_extract_status_message(CBMTestExtractStatus status);
bool cbm_test_declarations_validate(CBMFileResult *result,
const cbm_test_declarations_t *declarations);
void cbm_test_declarations_finish(CBMExtractCtx *ctx);
@@ -859,10 +877,9 @@ CBMFileResult *cbm_extract_file_ex(
* successful empty inventory. error_msg may be NULL on diagnostic OOM. */
CBMFileResult *cbm_extract_file_ex_with_tests(
const char *source, int source_len, CBMLanguage language, const char *project,
- const char *rel_path, int64_t timeout_micros,
- const char **extra_defines, const char **include_paths,
- const CBMMacroTable *macro_table, const CBMReturnTypeTable *return_type_table,
- const cbm_test_declarations_t *test_declarations);
+ const char *rel_path, int64_t timeout_micros, const char **extra_defines,
+ const char **include_paths, const CBMMacroTable *macro_table,
+ const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations);
// Free all memory associated with a result.
void cbm_free_result(CBMFileResult *result);
diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c
index c1349c8a8..a00300910 100644
--- a/internal/cbm/extract_defs.c
+++ b/internal/cbm/extract_defs.c
@@ -3,7 +3,7 @@
#include "helpers.h"
#include "lang_specs.h"
#include "foundation/constants.h"
-#include "foundation/log.h" // cbm_log_error
+#include "foundation/log.h" // cbm_log_error
#include "discover/test_conventions.h"
#include "foundation/sha256.h"
#include "foundation/mem_core.h" // cbm_realloc/cbm_free -- walk_defs stack
@@ -3796,7 +3796,7 @@ static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode
* The map lives in traversal scratch; its QNs live in the result arena. */
struct CBMTestDefinitionMatch {
uint32_t name_byte;
- TSNode name_node; /* same raw tree; never retained beyond extraction */
+ TSNode name_node; /* same raw tree; never retained beyond extraction */
TSNode scope_node; /* function, or split invocation's compound body */
uint32_t line;
int declaration;
@@ -3811,48 +3811,88 @@ typedef struct {
} TDXRule;
static int tdx_language(const char *name) {
- if (!name) return 0;
- if (strcmp(name, "c") == 0 || strcmp(name, "C") == 0) return 1;
- if (strcmp(name, "cpp") == 0 || strcmp(name, "c++") == 0 ||
- strcmp(name, "C++") == 0) return 2;
- if (strcmp(name, "cuda") == 0 || strcmp(name, "CUDA") == 0) return 3;
+ if (!name)
+ return 0;
+ if (strcmp(name, "c") == 0 || strcmp(name, "C") == 0)
+ return 1;
+ if (strcmp(name, "cpp") == 0 || strcmp(name, "c++") == 0 || strcmp(name, "C++") == 0)
+ return 2;
+ if (strcmp(name, "cuda") == 0 || strcmp(name, "CUDA") == 0)
+ return 3;
return 0;
}
static int tdx_source_language(CBMLanguage language) {
- return language == CBM_LANG_C ? 1 : language == CBM_LANG_CPP ? 2 :
- language == CBM_LANG_CUDA ? 3 : 0;
-}
-
-static bool tdx_issue(CBMFileResult *result, CBMTestExtractStatus status,
- int declaration, uint32_t line) {
- if (result->test_declarations_status == CBM_TEST_EXTRACT_OOM) return false;
- bool earlier = result->test_declarations_status == CBM_TEST_EXTRACT_OK ||
- status == CBM_TEST_EXTRACT_OOM || line < result->test_declaration_line ||
- (line == result->test_declaration_line &&
- (declaration < result->test_declaration_index ||
- (declaration == result->test_declaration_index &&
- status < result->test_declarations_status)));
- if (!earlier) return false;
- static const char *const messages[] = {
- "", "unsupported configured definition language",
- "unsupported disabled native test preset", "unsupported configured definition name",
- "configured definition argument is missing", "configured definition argument is not an identifier",
- "ambiguous configured definition mapping", "unsupported configured definition form",
- "configured definition allocation failed"
- };
+ return language == CBM_LANG_C ? 1
+ : language == CBM_LANG_CPP ? 2
+ : language == CBM_LANG_CUDA ? 3
+ : 0;
+}
+
+const char *cbm_test_extract_status_message(CBMTestExtractStatus status) {
+ static const char *const messages[] = {"",
+ "unsupported configured definition language",
+ "unsupported disabled native test preset",
+ "unsupported configured definition name",
+ "configured definition argument is missing",
+ "configured definition argument is not an identifier",
+ "ambiguous configured definition mapping",
+ "unsupported configured definition form",
+ "configured definition allocation failed"};
+ size_t count = sizeof(messages) / sizeof(messages[0]);
+ return (size_t)status < count ? messages[status] : "configured definition issue";
+}
+
+static bool tdx_issue(CBMFileResult *result, CBMTestExtractStatus status, int declaration,
+ uint32_t line) {
+ if (result->test_declarations_status == CBM_TEST_EXTRACT_OOM)
+ return false;
+ bool earlier =
+ result->test_declarations_status == CBM_TEST_EXTRACT_OK || status == CBM_TEST_EXTRACT_OOM ||
+ line < result->test_declaration_line ||
+ (line == result->test_declaration_line && (declaration < result->test_declaration_index ||
+ (declaration == result->test_declaration_index &&
+ status < result->test_declarations_status)));
+ if (!earlier)
+ return false;
+ if (!result->has_error)
+ result->test_error_only = true;
+
result->has_error = true;
result->test_declarations_status = status;
result->test_declaration_index = declaration;
result->test_declaration_line = line;
- result->error_msg = cbm_arena_strdup(&result->arena, messages[status]);
- if (!result->error_msg) result->test_declarations_status = CBM_TEST_EXTRACT_OOM;
+ result->error_msg = cbm_arena_strdup(&result->arena, cbm_test_extract_status_message(status));
+ if (!result->error_msg)
+ result->test_declarations_status = CBM_TEST_EXTRACT_OOM;
return false;
}
+void cbm_test_declarations_degrade(CBMFileResult *result) {
+ if (!result || result->test_declarations_status == CBM_TEST_EXTRACT_OK ||
+ result->test_declarations_status == CBM_TEST_EXTRACT_OOM)
+ return;
+ result->test_declarations_degraded = true;
+ result->test_declarations_degraded_status = result->test_declarations_status;
+ for (int i = 0; i < result->defs.count; i++) {
+ CBMDefinition *def = &result->defs.items[i];
+ def->test_role = CBM_TEST_ROLE_NONE;
+ def->test_name_start_byte = def->test_name_end_byte = 0;
+ def->test_body_start_byte = def->test_body_end_byte = 0;
+ }
+ result->has_test_definition_owners = false;
+ result->test_declarations_status = CBM_TEST_EXTRACT_OK;
+ if (result->test_error_only) {
+ result->has_error = false;
+ result->error_msg = NULL;
+ result->test_error_only = false;
+ }
+}
+
bool cbm_test_declarations_validate(CBMFileResult *result,
const cbm_test_declarations_t *declarations) {
- if (!declarations) return true;
+ if (!declarations)
+ return true;
for (int i = 0; i < CBM_TEST_PRESET_COUNT; i++) {
bool enabled = false;
if (!cbm_test_declarations_preset(declarations, (cbm_test_preset_t)i, &enabled))
@@ -3864,7 +3904,8 @@ bool cbm_test_declarations_validate(CBMFileResult *result,
const cbm_test_declaration_t *items = cbm_test_declarations_items(declarations, &count);
for (int i = 0; i < count; i++) {
const cbm_test_declaration_t *rule = &items[i];
- if (rule->role != CBM_TEST_DECL_CASE && rule->role != CBM_TEST_DECL_SUITE) continue;
+ if (rule->role != CBM_TEST_DECL_CASE && rule->role != CBM_TEST_DECL_SUITE)
+ continue;
if (!tdx_language(rule->language))
tdx_issue(result, CBM_TEST_EXTRACT_UNSUPPORTED_LANGUAGE, i, 0);
if (rule->name_arg_count != 1 || !rule->name_args || rule->name_args[0] < 0)
@@ -3874,7 +3915,8 @@ bool cbm_test_declarations_validate(CBMFileResult *result,
}
static bool tdx_preset(const CBMExtractCtx *ctx, cbm_test_preset_t preset) {
- if (!ctx->test_declarations) return preset != CBM_TEST_PRESET_C_CBM;
+ if (!ctx->test_declarations)
+ return preset != CBM_TEST_PRESET_C_CBM;
bool enabled = false;
return cbm_test_declarations_preset(ctx->test_declarations, preset, &enabled) && enabled;
}
@@ -3883,12 +3925,14 @@ static bool tdx_equal(const char *name, const char *text, size_t size) {
return name && strlen(name) == size && memcmp(name, text, size) == 0;
}
-static bool tdx_match(CBMExtractCtx *ctx, const char *text, size_t size,
- uint32_t line, TDXRule *chosen) {
+static bool tdx_match(CBMExtractCtx *ctx, const char *text, size_t size, uint32_t line,
+ TDXRule *chosen) {
*chosen = (TDXRule){.argument = -1, .declaration = -1};
- if (!ctx->test_declarations || !ctx->test_declarations_raw_source) return false;
+ if (!ctx->test_declarations || !ctx->test_declarations_raw_source)
+ return false;
int language = tdx_source_language(ctx->language), count = 0;
- if (!language) return false;
+ if (!language)
+ return false;
const cbm_test_declaration_t *items =
cbm_test_declarations_items(ctx->test_declarations, &count);
bool matched = false, valid = true;
@@ -3897,8 +3941,8 @@ static bool tdx_match(CBMExtractCtx *ctx, const char *text, size_t size,
if ((rule->role != CBM_TEST_DECL_CASE && rule->role != CBM_TEST_DECL_SUITE) ||
tdx_language(rule->language) != language || !tdx_equal(rule->define_macro, text, size))
continue;
- CBMTestDefinitionRole role = rule->role == CBM_TEST_DECL_CASE ?
- CBM_TEST_ROLE_CASE : CBM_TEST_ROLE_SUITE;
+ CBMTestDefinitionRole role =
+ rule->role == CBM_TEST_DECL_CASE ? CBM_TEST_ROLE_CASE : CBM_TEST_ROLE_SUITE;
if (rule->name_arg_count != 1 || !rule->name_args || rule->name_args[0] < 0) {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_NAME, i, line);
valid = false;
@@ -3909,19 +3953,21 @@ static bool tdx_match(CBMExtractCtx *ctx, const char *text, size_t size,
tdx_issue(ctx->result, CBM_TEST_EXTRACT_AMBIGUOUS, i, line);
valid = false;
}
- if (!matched) *chosen = (TDXRule){role, rule->name_args[0], i, true};
+ if (!matched)
+ *chosen = (TDXRule){role, rule->name_args[0], i, true};
matched = true;
}
if (language == 1 && tdx_preset(ctx, CBM_TEST_PRESET_C_CBM)) {
- CBMTestDefinitionRole role = tdx_equal("TEST", text, size) ? CBM_TEST_ROLE_CASE :
- tdx_equal("SUITE", text, size) ? CBM_TEST_ROLE_SUITE :
- CBM_TEST_ROLE_NONE;
+ CBMTestDefinitionRole role = tdx_equal("TEST", text, size) ? CBM_TEST_ROLE_CASE
+ : tdx_equal("SUITE", text, size) ? CBM_TEST_ROLE_SUITE
+ : CBM_TEST_ROLE_NONE;
if (role != CBM_TEST_ROLE_NONE) {
if (matched && (chosen->role != role || chosen->argument != 0)) {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_AMBIGUOUS, -1, line);
valid = false;
}
- if (!matched) *chosen = (TDXRule){role, 0, -1, true};
+ if (!matched)
+ *chosen = (TDXRule){role, 0, -1, true};
matched = true;
}
}
@@ -3957,7 +4003,10 @@ static bool tdx_pp_number(const char *s, size_t n, size_t *at) {
i++;
while (i < n) {
unsigned char c = (unsigned char)s[i];
- if (tdx_ident(c) || c == '.') { i++; continue; }
+ if (tdx_ident(c) || c == '.') {
+ i++;
+ continue;
+ }
if (c == '\'' && i + 1 < n && tdx_ident((unsigned char)s[i + 1])) {
i += 2;
continue;
@@ -3986,38 +4035,51 @@ static bool tdx_splice(const char *s, size_t n, size_t at) {
* line splicing/raw strings are explicit uncertainty, not token guesses. */
static bool tdx_trivia(const char *s, size_t n, size_t *at) {
for (;;) {
- while (*at < n && tdx_space((unsigned char)s[*at])) (*at)++;
- if (*at + 1 >= n || s[*at] != '/') return true;
+ while (*at < n && tdx_space((unsigned char)s[*at]))
+ (*at)++;
+ if (*at + 1 >= n || s[*at] != '/')
+ return true;
if (s[*at + 1] == '/') {
*at += 2;
while (*at < n && s[*at] != '\n') {
- if (tdx_splice(s, n, *at)) return false;
+ if (tdx_splice(s, n, *at))
+ return false;
(*at)++;
}
} else if (s[*at + 1] == '*') {
*at += 2;
while (*at + 1 < n && !(s[*at] == '*' && s[*at + 1] == '/')) {
- if (tdx_splice(s, n, *at)) return false;
+ if (tdx_splice(s, n, *at))
+ return false;
(*at)++;
}
- if (*at + 1 >= n) return false;
+ if (*at + 1 >= n)
+ return false;
*at += 2;
- } else return true;
+ } else
+ return true;
}
}
static bool tdx_literal(const char *s, size_t n, size_t *at) {
char quote = s[*at];
- if (quote == '"' && *at && s[*at - 1] == 'R') return false;
+ if (quote == '"' && *at && s[*at - 1] == 'R')
+ return false;
(*at)++;
while (*at < n) {
char c = s[*at];
- if (c == quote) { (*at)++; return true; }
- if (c == '\0' || c == '\n' || c == '\r' || tdx_splice(s, n, *at)) return false;
+ if (c == quote) {
+ (*at)++;
+ return true;
+ }
+ if (c == '\0' || c == '\n' || c == '\r' || tdx_splice(s, n, *at))
+ return false;
if (c == '\\') {
- if (*at + 1 >= n) return false;
+ if (*at + 1 >= n)
+ return false;
*at += 2;
- } else (*at)++;
+ } else
+ (*at)++;
}
return false;
}
@@ -4025,7 +4087,8 @@ static bool tdx_literal(const char *s, size_t n, size_t *at) {
/* The audit skips complete raw strings outside consumed invocations. The
* invocation adapter remains deliberately stricter (tdx_literal above). */
static bool tdx_audit_literal(const char *s, size_t n, size_t *at) {
- if (s[*at] != '"' || !*at || s[*at - 1] != 'R') return tdx_literal(s, n, at);
+ if (s[*at] != '"' || !*at || s[*at - 1] != 'R')
+ return tdx_literal(s, n, at);
size_t delimiter = *at + 1, open = delimiter;
while (open < n && s[open] != '(') {
unsigned char c = (unsigned char)s[open];
@@ -4033,12 +4096,12 @@ static bool tdx_audit_literal(const char *s, size_t n, size_t *at) {
return false;
open++;
}
- if (open == n) return false;
+ if (open == n)
+ return false;
size_t length = open - delimiter;
for (size_t end = open + 1; end < n; end++) {
if (s[end] == ')' && length + 2 <= n - end &&
- memcmp(s + end + 1, s + delimiter, length) == 0 &&
- s[end + length + 1] == '"') {
+ memcmp(s + end + 1, s + delimiter, length) == 0 && s[end + length + 1] == '"') {
*at = end + length + 2;
return true;
}
@@ -4046,9 +4109,8 @@ static bool tdx_audit_literal(const char *s, size_t n, size_t *at) {
return false;
}
-static bool tdx_argument(CBMExtractCtx *ctx, size_t at, int wanted,
- size_t *name_at, size_t *name_length, size_t *after,
- const TDXRule *rule, uint32_t line) {
+static bool tdx_argument(CBMExtractCtx *ctx, size_t at, int wanted, size_t *name_at,
+ size_t *name_length, size_t *after, const TDXRule *rule, uint32_t line) {
const char *s = ctx->source;
size_t n = (size_t)ctx->source_len;
if (!tdx_trivia(s, n, &at) || at >= n || s[at] != '(')
@@ -4058,21 +4120,28 @@ static bool tdx_argument(CBMExtractCtx *ctx, size_t at, int wanted,
int argument = 0;
bool selected = false, closed = false;
while (at < n && depth) {
- if (!tdx_trivia(s, n, &at) || at >= n || s[at] == '\0' || tdx_splice(s, n, at)) break;
- if (tdx_pp_number(s, n, &at)) continue;
+ if (!tdx_trivia(s, n, &at) || at >= n || s[at] == '\0' || tdx_splice(s, n, at))
+ break;
+ if (tdx_pp_number(s, n, &at))
+ continue;
char c = s[at];
if (c == '"' || c == '\'') {
- if (!tdx_literal(s, n, &at)) break;
+ if (!tdx_literal(s, n, &at))
+ break;
continue;
}
if (c == '(' || c == '[' || c == '{') {
- if (depth == sizeof(closing)) break;
+ if (depth == sizeof(closing))
+ break;
closing[depth++] = c == '(' ? ')' : c == '[' ? ']' : '}';
} else if (c == ')' || c == ']' || c == '}') {
- if (c != closing[depth - 1]) break;
+ if (c != closing[depth - 1])
+ break;
if (--depth == 0) {
if (argument == wanted) {
- selected_begin = begin; selected_end = at; selected = true;
+ selected_begin = begin;
+ selected_end = at;
+ selected = true;
}
*after = at + 1;
closed = true;
@@ -4080,7 +4149,9 @@ static bool tdx_argument(CBMExtractCtx *ctx, size_t at, int wanted,
}
} else if (c == ',' && depth == 1) {
if (argument == wanted) {
- selected_begin = begin; selected_end = at; selected = true;
+ selected_begin = begin;
+ selected_end = at;
+ selected = true;
}
argument++;
begin = at + 1;
@@ -4095,12 +4166,15 @@ static bool tdx_argument(CBMExtractCtx *ctx, size_t at, int wanted,
if (!tdx_trivia(s, selected_end, &at) || at == selected_end)
return tdx_issue(ctx->result, CBM_TEST_EXTRACT_MISSING_ARGUMENT, rule->declaration, line);
if (!tdx_ident_first((unsigned char)s[at]))
- return tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_ARGUMENT, rule->declaration, line);
+ return tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_ARGUMENT, rule->declaration,
+ line);
*name_at = at++;
- while (at < selected_end && tdx_ident((unsigned char)s[at])) at++;
+ while (at < selected_end && tdx_ident((unsigned char)s[at]))
+ at++;
*name_length = at - *name_at;
if (!tdx_trivia(s, selected_end, &at) || at != selected_end)
- return tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_ARGUMENT, rule->declaration, line);
+ return tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_ARGUMENT, rule->declaration,
+ line);
return true;
}
@@ -4160,12 +4234,14 @@ bool cbm_test_definition_candidate(TSNode scope, CBMLanguage language, TSNode *n
static bool tdx_observe(CBMExtractCtx *ctx, TSNode name_node, TSNode scope_node, const char *qn,
const TDXRule *rule);
-static bool tdx_resolve(CBMExtractCtx *ctx, TSNode node, TSNode name_node,
- const char *macro, const char **name, TDXRule *rule) {
+static bool tdx_resolve(CBMExtractCtx *ctx, TSNode node, TSNode name_node, const char *macro,
+ const char **name, TDXRule *rule) {
*name = NULL;
uint32_t line = ts_node_start_point(name_node).row + 1;
- if (!tdx_match(ctx, macro, strlen(macro), line, rule)) return false;
- if (ctx->result->test_declarations_status == CBM_TEST_EXTRACT_OOM) return true;
+ if (!tdx_match(ctx, macro, strlen(macro), line, rule))
+ return false;
+ if (ctx->result->test_declarations_status == CBM_TEST_EXTRACT_OOM)
+ return true;
if (!tdx_observe(ctx, name_node, node, NULL, rule) || !rule->valid)
return true;
uint32_t end = ts_node_end_byte(name_node);
@@ -4174,7 +4250,8 @@ static bool tdx_resolve(CBMExtractCtx *ctx, TSNode node, TSNode name_node,
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, rule->declaration, line);
return true;
}
- if (!tdx_argument(ctx, end, rule->argument, &id_at, &id_length, &after, rule, line)) return true;
+ if (!tdx_argument(ctx, end, rule->argument, &id_at, &id_length, &after, rule, line))
+ return true;
TSNode candidate_name, body;
if (!cbm_test_definition_candidate(node, ctx->language, &candidate_name, &body) ||
!ts_node_eq(candidate_name, name_node)) {
@@ -4182,16 +4259,16 @@ static bool tdx_resolve(CBMExtractCtx *ctx, TSNode node, TSNode name_node,
return true;
}
if (!tdx_trivia(ctx->source, (size_t)ctx->source_len, &after) ||
- after >= (size_t)ctx->source_len || ctx->source[after] != '{' ||
- ts_node_is_null(body) || ts_node_has_error(body) || ts_node_is_missing(body) ||
- ts_node_start_byte(body) != after || ts_node_end_byte(body) <= after ||
- ts_node_end_byte(body) > (uint32_t)ctx->source_len ||
+ after >= (size_t)ctx->source_len || ctx->source[after] != '{' || ts_node_is_null(body) ||
+ ts_node_has_error(body) || ts_node_is_missing(body) || ts_node_start_byte(body) != after ||
+ ts_node_end_byte(body) <= after || ts_node_end_byte(body) > (uint32_t)ctx->source_len ||
ctx->source[ts_node_end_byte(body) - 1] != '}') {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, rule->declaration, line);
return true;
}
*name = cbm_arena_sprintf(ctx->arena, "%s_%.*s", macro, (int)id_length, ctx->source + id_at);
- if (!*name) tdx_issue(ctx->result, CBM_TEST_EXTRACT_OOM, rule->declaration, line);
+ if (!*name)
+ tdx_issue(ctx->result, CBM_TEST_EXTRACT_OOM, rule->declaration, line);
return true;
}
@@ -4205,7 +4282,8 @@ static bool tdx_observe(CBMExtractCtx *ctx, TSNode name_node, TSNode scope_node,
for (int i = 0; i < count; i++) {
struct CBMTestDefinitionMatch *match = &ctx->test_definition_matches[i];
if (ts_node_eq(match->name_node, name_node)) {
- if (qn) match->qn = qn;
+ if (qn)
+ match->qn = qn;
return true;
}
}
@@ -4219,8 +4297,10 @@ static bool tdx_observe(CBMExtractCtx *ctx, TSNode name_node, TSNode scope_node,
CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;
struct CBMTestDefinitionMatch *items =
cbm_arena_alloc(scratch, (size_t)next * sizeof(*items));
- if (!items) return tdx_issue(ctx->result, CBM_TEST_EXTRACT_OOM, rule->declaration, line);
- if (count) memcpy(items, ctx->test_definition_matches, (size_t)count * sizeof(*items));
+ if (!items)
+ return tdx_issue(ctx->result, CBM_TEST_EXTRACT_OOM, rule->declaration, line);
+ if (count)
+ memcpy(items, ctx->test_definition_matches, (size_t)count * sizeof(*items));
ctx->test_definition_matches = items;
ctx->test_definition_match_cap = next;
}
@@ -4232,7 +4312,8 @@ static bool tdx_observe(CBMExtractCtx *ctx, TSNode name_node, TSNode scope_node,
const char *cbm_test_definition_qn(CBMExtractCtx *ctx, TSNode function) {
if (!ctx->test_declarations_raw_source || ctx->test_definition_match_count == 0 ||
- ts_node_is_null(function)) return NULL;
+ ts_node_is_null(function))
+ return NULL;
for (int i = 0; i < ctx->test_definition_match_count; i++)
if (ts_node_eq(ctx->test_definition_matches[i].scope_node, function))
return ctx->test_definition_matches[i].qn;
@@ -4243,13 +4324,17 @@ const char *cbm_test_definition_qn(CBMExtractCtx *ctx, TSNode function) {
* A local digest is identity evidence only, never artifact authentication. */
bool cbm_test_definition_owners_match(const CBMFileResult *owners, const char *source,
int source_len, bool cpp_mode, const char *module_qn) {
- if (!owners) return true;
- if (owners->test_declarations_status != CBM_TEST_EXTRACT_OK) return false;
- if (!owners->has_test_definition_owners) return true;
- if (!source || source_len < 0 || source_len != owners->test_owner_source_len ||
- !module_qn || !owners->module_qn || strcmp(module_qn, owners->module_qn) != 0 ||
+ if (!owners)
+ return true;
+ if (owners->test_declarations_status != CBM_TEST_EXTRACT_OK)
+ return false;
+ if (!owners->has_test_definition_owners)
+ return true;
+ if (!source || source_len < 0 || source_len != owners->test_owner_source_len || !module_qn ||
+ !owners->module_qn || strcmp(module_qn, owners->module_qn) != 0 ||
!tdx_source_language(owners->test_owner_language) ||
- cpp_mode != (owners->test_owner_language != CBM_LANG_C)) return false;
+ cpp_mode != (owners->test_owner_language != CBM_LANG_C))
+ return false;
char digest[65];
cbm_sha256_hex(source, (size_t)source_len, digest);
return memcmp(digest, owners->test_owner_source_sha256, sizeof(digest)) == 0;
@@ -4259,7 +4344,8 @@ bool cbm_test_definition_owners_match(const CBMFileResult *owners, const char *s
* Exact name AND body spans distinguish nodes, including nested definitions;
* never infer an owner from a line window or a guessed macro name. */
const char *cbm_test_definition_owner_qn(const CBMFileResult *owners, TSNode function) {
- if (!owners || !owners->has_test_definition_owners || ts_node_is_null(function)) return NULL;
+ if (!owners || !owners->has_test_definition_owners || ts_node_is_null(function))
+ return NULL;
TSNode name, body;
if (!cbm_test_definition_candidate(function, owners->test_owner_language, &name, &body) ||
ts_node_is_null(body))
@@ -4271,8 +4357,10 @@ const char *cbm_test_definition_owner_qn(const CBMFileResult *owners, TSNode fun
def->test_name_start_byte != ts_node_start_byte(name) ||
def->test_name_end_byte != ts_node_end_byte(name) ||
def->test_body_start_byte != ts_node_start_byte(body) ||
- def->test_body_end_byte != ts_node_end_byte(body)) continue;
- if (found) return NULL; /* duplicate rows are rejected by finish */
+ def->test_body_end_byte != ts_node_end_byte(body))
+ continue;
+ if (found)
+ return NULL; /* duplicate rows are rejected by finish */
found = def->qualified_name;
}
return found;
@@ -4283,28 +4371,38 @@ const char *cbm_test_definition_owner_qn(const CBMFileResult *owners, TSNode fun
* removed. This locates its extent; tdx_directive validates consumed content. */
static bool tdx_directive_end(const char *s, size_t n, size_t *at, uint32_t *line) {
while (*at < n) {
- if (s[*at] == '\0') return false;
- if (s[*at] == '\n') { (*at)++; (*line)++; return true; }
+ if (s[*at] == '\0')
+ return false;
+ if (s[*at] == '\n') {
+ (*at)++;
+ (*line)++;
+ return true;
+ }
if (*at + 1 < n && s[*at] == '/' && s[*at + 1] == '*') {
*at += 2;
while (*at + 1 < n && !(s[*at] == '*' && s[*at + 1] == '/')) {
- if (s[*at] == '\0') return false;
- if (s[*at] == '\n') (*line)++;
+ if (s[*at] == '\0')
+ return false;
+ if (s[*at] == '\n')
+ (*line)++;
(*at)++;
}
- if (*at + 1 >= n) return false;
+ if (*at + 1 >= n)
+ return false;
*at += 2;
continue;
}
if (*at + 1 < n && s[*at] == '/' && s[*at + 1] == '/') {
*at += 2;
while (*at < n && s[*at] != '\n') {
- if (s[*at] == '\0') return false;
+ if (s[*at] == '\0')
+ return false;
(*at)++;
}
continue;
}
- if (tdx_pp_number(s, n, at)) continue;
+ if (tdx_pp_number(s, n, at))
+ continue;
if (s[*at] == '"' || s[*at] == '\'') {
size_t before = *at;
if (!tdx_audit_literal(s, n, at)) {
@@ -4312,11 +4410,14 @@ static bool tdx_directive_end(const char *s, size_t n, size_t *at, uint32_t *lin
* content. Do not reinterpret its comment punctuation here. */
*at = before + 1;
while (*at < n && s[*at] != '\n') {
- if (s[*at] == '\0') return false;
+ if (s[*at] == '\0')
+ return false;
(*at)++;
}
}
- for (size_t i = before; i < *at; i++) if (s[i] == '\n') (*line)++;
+ for (size_t i = before; i < *at; i++)
+ if (s[i] == '\n')
+ (*line)++;
continue;
}
(*at)++;
@@ -4334,7 +4435,10 @@ static void tdx_directive(CBMExtractCtx *ctx, size_t begin, size_t end, uint32_t
* the joined bytes never become declaration or graph source evidence. */
bool spliced = false;
for (size_t i = 0; i < end; i++)
- if (tdx_splice(s, end, i)) { spliced = true; break; }
+ if (tdx_splice(s, end, i)) {
+ spliced = true;
+ break;
+ }
if (spliced) {
CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;
char *joined = cbm_arena_alloc(scratch, end + 1);
@@ -4344,8 +4448,10 @@ static void tdx_directive(CBMExtractCtx *ctx, size_t begin, size_t end, uint32_t
}
size_t used = 0;
for (size_t i = 0; i < end;) {
- if (tdx_splice(s, end, i)) i += s[i + 1] == '\r' ? 3 : 2;
- else joined[used++] = s[i++];
+ if (tdx_splice(s, end, i))
+ i += s[i + 1] == '\r' ? 3 : 2;
+ else
+ joined[used++] = s[i++];
}
joined[used] = '\0';
s = joined;
@@ -4357,16 +4463,20 @@ static void tdx_directive(CBMExtractCtx *ctx, size_t begin, size_t end, uint32_t
return;
}
size_t word = at;
- while (at < end && tdx_ident((unsigned char)s[at])) at++;
- if (!tdx_equal("define", s + word, at - word)) return;
+ while (at < end && tdx_ident((unsigned char)s[at]))
+ at++;
+ if (!tdx_equal("define", s + word, at - word))
+ return;
if (!tdx_trivia(s, end, &at) || at == end || !tdx_ident_first((unsigned char)s[at])) {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, -1, line);
return;
}
- while (at < end && tdx_ident((unsigned char)s[at])) at++;
+ while (at < end && tdx_ident((unsigned char)s[at]))
+ at++;
/* A function-like macro's formal parameters are not its replacement. */
if (at < end && s[at] == '(') {
- while (at < end && s[at] != ')') at++;
+ while (at < end && s[at] != ')')
+ at++;
if (at == end) {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, -1, line);
return;
@@ -4374,13 +4484,18 @@ static void tdx_directive(CBMExtractCtx *ctx, size_t begin, size_t end, uint32_t
at++;
}
while (at < end) {
- if (tdx_splice(s, end, at)) { at += s[at + 1] == '\r' ? 3 : 2; continue; }
+ if (tdx_splice(s, end, at)) {
+ at += s[at + 1] == '\r' ? 3 : 2;
+ continue;
+ }
if (!tdx_trivia(s, end, &at)) {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, -1, line);
return;
}
- if (at == end) return;
- if (tdx_pp_number(s, end, &at)) continue;
+ if (at == end)
+ return;
+ if (tdx_pp_number(s, end, &at))
+ continue;
if (s[at] == '"' || s[at] == '\'') {
if (!tdx_audit_literal(s, end, &at)) {
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, -1, line);
@@ -4388,9 +4503,13 @@ static void tdx_directive(CBMExtractCtx *ctx, size_t begin, size_t end, uint32_t
}
continue;
}
- if (!tdx_ident_first((unsigned char)s[at])) { at++; continue; }
+ if (!tdx_ident_first((unsigned char)s[at])) {
+ at++;
+ continue;
+ }
word = at++;
- while (at < end && tdx_ident((unsigned char)s[at])) at++;
+ while (at < end && tdx_ident((unsigned char)s[at]))
+ at++;
TDXRule rule;
if (tdx_match(ctx, s + word, at - word, line, &rule))
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, rule.declaration, line);
@@ -4399,16 +4518,19 @@ static void tdx_directive(CBMExtractCtx *ctx, size_t begin, size_t end, uint32_t
void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
if (!ctx->test_declarations || !ctx->test_declarations_raw_source ||
- ctx->result->test_declarations_status == CBM_TEST_EXTRACT_OOM) return;
+ ctx->result->test_declarations_status == CBM_TEST_EXTRACT_OOM)
+ return;
int language = tdx_source_language(ctx->language), count = 0;
- if (!language) return;
+ if (!language)
+ return;
const cbm_test_declaration_t *items =
cbm_test_declarations_items(ctx->test_declarations, &count);
bool active = language == 1 && tdx_preset(ctx, CBM_TEST_PRESET_C_CBM);
for (int i = 0; i < count && !active; i++)
active = (items[i].role == CBM_TEST_DECL_CASE || items[i].role == CBM_TEST_DECL_SUITE) &&
tdx_language(items[i].language) == language;
- if (!active) return;
+ if (!active)
+ return;
/* Detect configured invocations dropped by a grammar/error region. Never
* invent definitions here; an unmatched raw invocation is uncertainty.
* Normalize line splices for AUDIT ONLY, so a split macro cannot disappear.
@@ -4420,8 +4542,10 @@ void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
size_t n = ctx->source_len > 0 ? (size_t)ctx->source_len : 0, at = 0;
uint32_t splice_line = 0, physical_line = 1;
for (size_t i = 0; i < n; i++) {
- if (!splice_line && tdx_splice(s, n, i)) splice_line = physical_line;
- if (s[i] == '\n') physical_line++;
+ if (!splice_line && tdx_splice(s, n, i))
+ splice_line = physical_line;
+ if (s[i] == '\n')
+ physical_line++;
}
if (splice_line) {
CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;
@@ -4432,8 +4556,10 @@ void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
}
size_t used = 0;
for (size_t i = 0; i < n;) {
- if (tdx_splice(s, n, i)) i += s[i + 1] == '\r' ? 3 : 2;
- else joined[used++] = s[i++];
+ if (tdx_splice(s, n, i))
+ i += s[i + 1] == '\r' ? 3 : 2;
+ else
+ joined[used++] = s[i++];
}
joined[used] = '\0';
s = joined;
@@ -4446,10 +4572,21 @@ void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
bool line_start = true;
while (at < n) {
size_t before = at;
- if (!tdx_trivia(s, n, &at)) { uncertain_line = line; break; }
- for (size_t i = before; i < at; i++) if (s[i] == '\n') { line++; line_start = true; }
- if (at == n) break;
- if (s[at] == '\0') { uncertain_line = line; break; }
+ if (!tdx_trivia(s, n, &at)) {
+ uncertain_line = line;
+ break;
+ }
+ for (size_t i = before; i < at; i++)
+ if (s[i] == '\n') {
+ line++;
+ line_start = true;
+ }
+ if (at == n)
+ break;
+ if (s[at] == '\0') {
+ uncertain_line = line;
+ break;
+ }
if (line_start && s[at] == '#') {
size_t directive_begin = at;
uint32_t directive_line = splice_line ? splice_line : line;
@@ -4462,26 +4599,44 @@ void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
continue;
}
line_start = false;
- if (tdx_pp_number(s, n, &at)) continue;
+ if (tdx_pp_number(s, n, &at))
+ continue;
if (s[at] == '"' || s[at] == '\'') {
before = at;
- if (!tdx_audit_literal(s, n, &at)) { uncertain_line = line; break; }
- for (size_t i = before; i < at; i++) if (s[i] == '\n') line++;
+ if (!tdx_audit_literal(s, n, &at)) {
+ uncertain_line = line;
+ break;
+ }
+ for (size_t i = before; i < at; i++)
+ if (s[i] == '\n')
+ line++;
+ continue;
+ }
+ if (!tdx_ident_first((unsigned char)s[at])) {
+ at++;
continue;
}
- if (!tdx_ident_first((unsigned char)s[at])) { at++; continue; }
size_t begin = at++;
- while (at < n && tdx_ident((unsigned char)s[at])) at++;
+ while (at < n && tdx_ident((unsigned char)s[at]))
+ at++;
size_t after = at;
- if (!tdx_trivia(s, n, &after)) { uncertain_line = line; break; }
- if (after == n || s[after] != '(') continue;
+ if (!tdx_trivia(s, n, &after)) {
+ uncertain_line = line;
+ break;
+ }
+ if (after == n || s[after] != '(')
+ continue;
TDXRule rule;
uint32_t issue_line = splice_line ? splice_line : line;
- if (!tdx_match(ctx, s + begin, at - begin, issue_line, &rule)) continue;
+ if (!tdx_match(ctx, s + begin, at - begin, issue_line, &rule))
+ continue;
bool found = false;
if (!splice_line) {
for (int i = 0; i < ctx->test_definition_match_count; i++)
- if (ctx->test_definition_matches[i].name_byte == begin) { found = true; break; }
+ if (ctx->test_definition_matches[i].name_byte == begin) {
+ found = true;
+ break;
+ }
}
if (!found)
tdx_issue(ctx->result, CBM_TEST_EXTRACT_UNSUPPORTED_FORM, rule.declaration, issue_line);
@@ -4492,11 +4647,13 @@ void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
/* A configured QN collision is explicit rather than a later upsert loss. */
for (int i = 0; i < ctx->test_definition_match_count; i++) {
const struct CBMTestDefinitionMatch *match = &ctx->test_definition_matches[i];
- if (!match->qn) continue; /* failed invocation; diagnostic already retained */
+ if (!match->qn)
+ continue; /* failed invocation; diagnostic already retained */
int found = 0;
for (int j = 0; j < ctx->result->defs.count; j++) {
const char *qn = ctx->result->defs.items[j].qualified_name;
- if (qn && strcmp(qn, match->qn) == 0) found++;
+ if (qn && strcmp(qn, match->qn) == 0)
+ found++;
}
if (found != 1)
tdx_issue(ctx->result, CBM_TEST_EXTRACT_AMBIGUOUS, match->declaration, match->line);
@@ -4506,8 +4663,7 @@ void cbm_test_declarations_finish(CBMExtractCtx *ctx) {
ctx->result->has_test_definition_owners = true;
ctx->result->test_owner_source_len = ctx->source_len;
ctx->result->test_owner_language = ctx->language;
- cbm_sha256_hex(ctx->source, (size_t)ctx->source_len,
- ctx->result->test_owner_source_sha256);
+ cbm_sha256_hex(ctx->source, (size_t)ctx->source_len, ctx->result->test_owner_source_sha256);
}
}
@@ -4554,7 +4710,8 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
TDXRule configured_rule;
bool configured = tdx_resolve(ctx, node, name_node, name, &configured_name, &configured_rule);
if (configured) {
- if (!configured_name) return;
+ if (!configured_name)
+ return;
name = (char *)configured_name;
}
if (!configured && tdx_preset(ctx, CBM_TEST_PRESET_GTEST) &&
diff --git a/scripts/memory-core-baseline.txt b/scripts/memory-core-baseline.txt
index 138ef0f77..c5cbe0727 100644
--- a/scripts/memory-core-baseline.txt
+++ b/scripts/memory-core-baseline.txt
@@ -44,15 +44,15 @@ src/foundation/platform.c 11
src/foundation/platform.h 5
src/foundation/private_file_lock.c 56
src/foundation/str_intern.c 7
-src/foundation/subprocess.c 24
-src/foundation/win_utf8.h 17
+src/foundation/subprocess.c 17
+src/foundation/win_utf8.h 7
src/foundation/workspace.c 3
src/foundation/yaml.c 10
src/git/git_context.c 18
src/main.c 32
src/mcp/compact_out.c 39
src/mcp/index_supervisor.c 8
-src/mcp/mcp.c 784
+src/mcp/mcp.c 779
src/pipeline/artifact.c 38
src/pipeline/fqn.c 23
src/pipeline/lsp_resolve.h 4
@@ -62,7 +62,7 @@ src/pipeline/pass_compile_commands.c 17
src/pipeline/pass_complexity.c 15
src/pipeline/pass_configlink.c 3
src/pipeline/pass_cross_repo.c 8
-src/pipeline/pass_definitions.c 14
+src/pipeline/pass_definitions.c 11
src/pipeline/pass_enrichment.c 15
src/pipeline/pass_ensemble_routing.c 10
src/pipeline/pass_envscan.c 2
@@ -70,7 +70,7 @@ src/pipeline/pass_githistory.c 27
src/pipeline/pass_importance.c 4
src/pipeline/pass_infrascan.c 2
src/pipeline/pass_k8s.c 6
-src/pipeline/pass_lsp_cross.c 50
+src/pipeline/pass_lsp_cross.c 49
src/pipeline/pass_parallel.c 31
src/pipeline/pass_pkgmap.c 82
src/pipeline/pass_semantic.c 3
@@ -79,7 +79,7 @@ src/pipeline/pass_usages.c 4
src/pipeline/path_alias.c 42
src/pipeline/pipeline.c 134
src/pipeline/pipeline_delta.c 19
-src/pipeline/pipeline_incremental.c 144
+src/pipeline/pipeline_incremental.c 143
src/pipeline/registry.c 17
src/pipeline/worker_pool.c 2
src/store/store.c 358
diff --git a/src/discover/discover.c b/src/discover/discover.c
index 5f4febb0a..003084edf 100644
--- a/src/discover/discover.c
+++ b/src/discover/discover.c
@@ -108,20 +108,6 @@ static const char *FAST_PATTERNS[] = {".d.ts", ".bundle.", ".chunk.", ".gen
"_string.go", "mock_", "_mock.", "_test_helpers.",
".stories.", ".spec.", ".test.", NULL};
-/* ── Ignored JSON filenames ──────────────────────── */
-
-static const char *IGNORED_JSON_FILES[] = {
- "package.json", "package-lock.json", "tsconfig.json",
- "jsconfig.json", "composer.json", "composer.lock",
- "yarn.lock", "openapi.json", "swagger.json",
- "jest.config.json", ".eslintrc.json", ".prettierrc.json",
- ".babelrc.json", "tslint.json", "angular.json",
- "firebase.json", "renovate.json", "lerna.json",
- "turbo.json", ".stylelintrc.json", "pnpm-lock.json",
- "deno.json", "biome.json", "devcontainer.json",
- ".devcontainer.json", "launch.json", "settings.json",
- "extensions.json", "tasks.json", NULL};
-
/* ── Helper: check if string is in NULL-terminated array ─────────── */
static bool str_in_list(const char *s, const char *const *list) {
@@ -826,60 +812,11 @@ static const char *file_skip_reason(const char *entry_name, const char *rel_path
return global_ignored ? "gitignore" : NULL;
}
-/* Detect language for a file, handling .m disambiguation and JSON filtering. */
+/* Detect language for a file: its name, and its first bytes where the name is
+ * not enough (cbm_language_classify; the pinned test-impact inventory uses the
+ * same rule on git blobs). */
static CBMLanguage detect_file_language(const char *entry_name, const char *abs_path) {
- CBMLanguage lang = cbm_language_for_filename(entry_name);
- if (lang == CBM_LANG_COUNT) {
- /* Filename/extension detection failed: fall back to a conservative
- * shebang probe so extensionless scripts get indexed (#1199). Filename
- * detection stays authoritative — this runs only when it returns
- * unknown. */
- return cbm_language_from_shebang(abs_path);
- }
- /* Special: .m files need content-based disambiguation */
- const char *dot = strrchr(entry_name, '.');
- if (dot && strcmp(dot, ".m") == 0) {
- lang = cbm_disambiguate_m(abs_path);
- }
- /* Special: .cls is shared by ObjectScript UDL, Apex and VB6 class modules */
- if (dot && strcmp(dot, ".cls") == 0) {
- lang = cbm_disambiguate_cls(abs_path);
- }
- /* Special: .inc is shared by BitBake and ObjectScript include files */
- if (dot && strcmp(dot, ".inc") == 0) {
- lang = cbm_disambiguate_inc(abs_path);
- }
- /* Special: .cfc components may be script-dialect or tag-dialect (<cfcomponent>) */
- if (dot && strcmp(dot, ".cfc") == 0) {
- lang = cbm_disambiguate_cfc(abs_path);
- }
- /* Special: .frm is shared by FORM and VB6 forms (#721) */
- if (dot && strcmp(dot, ".frm") == 0) {
- lang = cbm_disambiguate_frm(abs_path);
- }
- /* Special: .res is also a binary Godot / Windows resource (#2176) */
- if (dot && strcmp(dot, ".res") == 0) {
- lang = cbm_disambiguate_res(abs_path);
- }
- /* Special: ObjectScript Studio Export XML (<Export generator="...">) is
- * detected by content; otherwise .xml stays XML. */
- if (lang == CBM_LANG_XML) {
- FILE *xf = cbm_fopen(abs_path, "r");
- if (xf) {
- char xbuf[CBM_SZ_256];
- size_t xn = fread(xbuf, SKIP_ONE, sizeof(xbuf) - SKIP_ONE, xf);
- (void)fclose(xf);
- xbuf[xn] = '\0';
- if (strstr(xbuf, "<Export generator=")) {
- return CBM_LANG_OBJECTSCRIPT_EXPORT;
- }
- }
- }
- /* Check ignored JSON files */
- if (lang == CBM_LANG_JSON && str_in_list(entry_name, IGNORED_JSON_FILES)) {
- return CBM_LANG_COUNT;
- }
- return lang;
+ return cbm_language_for_file(entry_name, abs_path);
}
/* UTF-8-safe stat: wide API on Windows, regular stat on POSIX. */
diff --git a/src/discover/discover.h b/src/discover/discover.h
index 89ccca4f3..b414f99ae 100644
--- a/src/discover/discover.h
+++ b/src/discover/discover.h
@@ -18,6 +18,7 @@
/* Use the existing CBMLanguage enum from extraction layer */
#include "cbm.h"
#include "foundation/index_policy.h"
+#include "discover/userconfig.h"
/* ── Language detection ──────────────────────────────────────────── */
@@ -83,6 +84,32 @@ CBMLanguage cbm_language_from_shebang(const char *path);
* On read failure, defaults to CBM_LANG_CFSCRIPT. */
CBMLanguage cbm_disambiguate_cfc(const char *path);
+/* The language of a file from its base name and, where the name is not enough,
+ * its first bytes: the one rule discovery and the pinned test-impact inventory
+ * share. cbm_language_probe_bytes says how many leading bytes the name needs
+ * (0: the name decides). cbm_language_classify takes those bytes raw, `more`
+ * when the file has bytes beyond them, and `readable` false when they could
+ * not be read (each probe then keeps the name's default, as a failed open
+ * always did). The name lookup consults the installed user language config. */
+size_t cbm_language_probe_bytes(const char *filename);
+CBMLanguage cbm_language_classify(const char *filename, const unsigned char *head, size_t head_len,
+ bool more, bool readable);
+
+/* The same with the language config given explicitly (NULL: none) instead of
+ * the installed process-wide one, for a caller that classifies a snapshot
+ * under that snapshot's config while another index may have its own
+ * installed. */
+size_t cbm_language_probe_bytes_with(const cbm_userconfig_t *config, const char *filename);
+CBMLanguage cbm_language_classify_with(const cbm_userconfig_t *config, const char *filename,
+ const unsigned char *head, size_t head_len, bool more,
+ bool readable);
+
+/* The most leading bytes any name asks cbm_language_probe_bytes for. */
+#define CBM_LANGUAGE_PROBE_MAX 16384
+
+/* cbm_language_classify on the file at `path`, read raw. */
+CBMLanguage cbm_language_for_file(const char *filename, const char *path);
+
/* ── Gitignore pattern matching ──────────────────────────────────── */
typedef struct cbm_gitignore cbm_gitignore_t;
diff --git a/src/discover/inventory_filter.h b/src/discover/inventory_filter.h
index 10acf983f..660497e38 100644
--- a/src/discover/inventory_filter.h
+++ b/src/discover/inventory_filter.h
@@ -26,9 +26,9 @@ typedef enum {
typedef struct {
cbm_inventory_status_t status;
- size_t file_index; /* SIZE_MAX unless a particular input row is known. */
+ size_t file_index; /* SIZE_MAX unless a particular input row is known. */
bool cleanup_required; /* Independent provider cleanup obligation. */
- char diagnostic[256]; /* Owned bounded generic text, no input contents. */
+ char diagnostic[256]; /* Owned bounded generic text, no input contents. */
} cbm_inventory_error_t;
typedef struct {
@@ -38,28 +38,28 @@ typedef struct {
typedef struct {
cbm_inventory_path_t path; /* data[length]==0; no earlier NUL. */
- uint32_t git_mode; /* 0100644 or 0100755. */
- char oid[65]; /* First NUL at 40 or 64; preceding lowercase hex only. */
+ uint32_t git_mode; /* 0100644 or 0100755. */
+ char oid[65]; /* First NUL at 40 or 64; preceding lowercase hex only. */
uint64_t content_length;
unsigned char content_sha256[32];
} cbm_inventory_file_t;
typedef struct {
- uint64_t deadline_ms; /* Positive absolute cbm_now_ms deadline. */
+ uint64_t deadline_ms; /* Positive absolute cbm_now_ms deadline. */
bool (*cancelled)(void *context); /* Optional prompt, pure, non-reentrant. */
- void *context; /* Borrowed only until prepare returns. */
+ void *context; /* Borrowed only until prepare returns. */
} cbm_inventory_control_t;
typedef struct {
- size_t max_files; /* Positive, <=INT_MAX; complete inventory, not survivors. */
- size_t max_directories; /* Positive, <=INT_MAX; root plus proper prefixes. */
- size_t max_arena_bytes; /* Total cumulative logical requests/reservations. */
+ size_t max_files; /* Positive, <=INT_MAX; complete inventory, not survivors. */
+ size_t max_directories; /* Positive, <=INT_MAX; root plus proper prefixes. */
+ size_t max_arena_bytes; /* Total cumulative logical requests/reservations. */
size_t max_ignore_arena_bytes; /* Positive reserved slice <= total. */
size_t max_control_file_bytes;
uint64_t max_control_total_bytes;
- size_t max_ignore_patterns; /* Positive, <=INT_MAX. */
+ size_t max_ignore_patterns; /* Positive, <=INT_MAX. */
size_t max_probe_prefix_bytes; /* Copied/validated; unused before language. */
- uint64_t max_ignore_work; /* Exclusive checked parse+match allowance. */
+ uint64_t max_ignore_work; /* Exclusive checked parse+match allowance. */
uint64_t max_verified_file_reads;
uint64_t max_verified_content_bytes;
} cbm_inventory_limits_t;
@@ -69,9 +69,11 @@ typedef struct {
* Serial; all inputs borrowed. An error may require caller-owned native cleanup.
* This callback type cannot authenticate a synthetic provider.
*/
-typedef cbm_inventory_status_t (*cbm_inventory_read_fn)(
- void *context, size_t file_index, unsigned char *prefix, size_t capacity,
- size_t *copied, const cbm_inventory_control_t *control, cbm_inventory_error_t *error);
+typedef cbm_inventory_status_t (*cbm_inventory_read_fn)(void *context, size_t file_index,
+ unsigned char *prefix, size_t capacity,
+ size_t *copied,
+ const cbm_inventory_control_t *control,
+ cbm_inventory_error_t *error);
typedef struct {
const char *native_root;
@@ -128,7 +130,7 @@ typedef enum {
typedef struct {
cbm_inventory_control_kind_t kind;
cbm_inventory_path_t directory; /* Empty root or reached directory. */
- size_t file_index; /* SIZE_MAX iff ABSENT. */
+ size_t file_index; /* SIZE_MAX iff ABSENT. */
cbm_inventory_control_outcome_t outcome;
size_t effective_patterns;
} cbm_inventory_control_row_t;
@@ -142,7 +144,7 @@ typedef struct {
size_t ignore_patterns_reserved;
size_t ignore_arena_requested_bytes;
size_t non_ignore_arena_requested_bytes;
- size_t arena_requested_bytes; /* D+C actual logical requests. */
+ size_t arena_requested_bytes; /* D+C actual logical requests. */
size_t arena_budget_used_bytes; /* D+I unavailable quota. */
} cbm_inventory_filter_usage_t;
@@ -152,7 +154,7 @@ typedef struct {
const char *native_root;
const cbm_inventory_file_t *files;
const cbm_inventory_filter_row_t *rows;
- size_t file_count; /* Exactly the complete input count. */
+ size_t file_count; /* Exactly the complete input count. */
size_t directory_count; /* Includes excluded directories and root. */
const cbm_inventory_control_row_t *controls;
size_t control_count;
@@ -168,10 +170,11 @@ typedef struct {
* retains neither callbacks nor caller contexts. Failure: out==NULL, no partial
* view. Native cleanup remains the provider caller's responsibility.
*/
-cbm_inventory_status_t cbm_inventory_filter_prepare(
- const cbm_inventory_source_t *source, const cbm_inventory_limits_t *limits,
- const cbm_inventory_control_t *control, cbm_inventory_filter_t **out,
- cbm_inventory_error_t *error);
+cbm_inventory_status_t cbm_inventory_filter_prepare(const cbm_inventory_source_t *source,
+ const cbm_inventory_limits_t *limits,
+ const cbm_inventory_control_t *control,
+ cbm_inventory_filter_t **out,
+ cbm_inventory_error_t *error);
/* Borrowed read-only view until free; NULL for NULL. No IO/poll/allocation. */
const cbm_inventory_filter_view_t *cbm_inventory_filter_view(const cbm_inventory_filter_t *owner);
@@ -181,8 +184,7 @@ const cbm_inventory_filter_view_t *cbm_inventory_filter_view(const cbm_inventory
*/
bool cbm_inventory_filter_usage(const cbm_inventory_filter_t *owner,
cbm_inventory_filter_usage_t *out);
-bool cbm_inventory_filter_limits(const cbm_inventory_filter_t *owner,
- cbm_inventory_limits_t *out);
+bool cbm_inventory_filter_limits(const cbm_inventory_filter_t *owner, cbm_inventory_limits_t *out);
/* NULL-safe; frees checked owner before the containing arena; no callback/IO. */
void cbm_inventory_filter_free(cbm_inventory_filter_t *owner);
diff --git a/src/discover/language.c b/src/discover/language.c
index dcc41dafd..342655e23 100644
--- a/src/discover/language.c
+++ b/src/discover/language.c
@@ -918,13 +918,12 @@ static const char *LANG_NAMES[CBM_LANG_COUNT] = {
/* ── Public API ──────────────────────────────────────────────────── */
-CBMLanguage cbm_language_for_extension(const char *ext) {
+static CBMLanguage lang_for_extension(const cbm_userconfig_t *ucfg, const char *ext) {
if (!ext || !ext[0]) {
return CBM_LANG_COUNT;
}
/* Check user-defined overrides first */
- const cbm_userconfig_t *ucfg = cbm_get_user_lang_config();
if (ucfg) {
CBMLanguage ulang = cbm_userconfig_lookup(ucfg, ext);
if (ulang != CBM_LANG_COUNT) {
@@ -940,7 +939,11 @@ CBMLanguage cbm_language_for_extension(const char *ext) {
return CBM_LANG_COUNT;
}
-CBMLanguage cbm_language_for_filename(const char *filename) {
+CBMLanguage cbm_language_for_extension(const char *ext) {
+ return lang_for_extension(cbm_get_user_lang_config(), ext);
+}
+
+static CBMLanguage lang_for_filename(const cbm_userconfig_t *ucfg, const char *filename) {
if (!filename || !filename[0]) {
return CBM_LANG_COUNT;
}
@@ -980,7 +983,6 @@ CBMLanguage cbm_language_for_filename(const char *filename) {
} COMPOUND_EXT_TABLE[] = {
{".blade.php", CBM_LANG_BLADE},
};
- const cbm_userconfig_t *ucfg = cbm_get_user_lang_config();
const char *p = strchr(filename, '.');
while (p && p < last_dot) {
for (size_t i = 0; i < sizeof(COMPOUND_EXT_TABLE) / sizeof(COMPOUND_EXT_TABLE[0]); i++) {
@@ -998,7 +1000,11 @@ CBMLanguage cbm_language_for_filename(const char *filename) {
}
/* Standard single-extension lookup (built-ins + user overrides). */
- return cbm_language_for_extension(last_dot);
+ return lang_for_extension(ucfg, last_dot);
+}
+
+CBMLanguage cbm_language_for_filename(const char *filename) {
+ return lang_for_filename(cbm_get_user_lang_config(), filename);
}
const char *cbm_language_name(CBMLanguage lang) {
@@ -1089,45 +1095,61 @@ static char *shebang_next_token(char **cursor) {
return start;
}
-CBMLanguage cbm_language_from_shebang(const char *path) {
- if (!path) {
- return CBM_LANG_COUNT;
+/* ── Content probes ────────────────────────────────────────────────
+ * A few names do not decide a language alone; the file's first bytes do. Every
+ * probe is a function of those bytes only, so discovery (which reads files)
+ * and the pinned test-impact inventory (which reads git blobs) give a file the
+ * same language. The bytes are raw on every platform: a Windows text-mode read
+ * dropped carriage returns and stopped at a Ctrl-Z, which made the answer
+ * depend on the host. */
+enum {
+ LANG_PROBE_LINE = 255, /* a shebang first line; the ObjectScript export marker */
+ LANG_PROBE_HEAD = CBM_SZ_4K, /* .m .cls .inc .frm .res */
+ LANG_PROBE_CFC = CBM_SZ_16K, /* .cfc: a long license block may precede the first tag */
+};
+
+/* The first min(n, cap) bytes as a C string in dst[cap + 1]. The probes are
+ * string scans, so an embedded NUL ends what they see, as it always did. */
+static void lang_head_text(char *dst, size_t cap, const unsigned char *head, size_t n) {
+ size_t len = n < cap ? n : cap;
+ if (len > 0) {
+ memcpy(dst, head, len);
}
+ dst[len] = '\0';
+}
- FILE *f = cbm_fopen(path, "rb");
+/* The first `cap` bytes of a file, raw. false when the file cannot be opened.
+ * A read error keeps the bytes read before it, as the probes always did. */
+static bool lang_read_head(const char *path, unsigned char *buf, size_t cap, size_t *n) {
+ *n = 0;
+ FILE *f = path ? cbm_fopen(path, "rb") : NULL;
if (!f) {
- return CBM_LANG_COUNT; /* fail closed on read error */
+ return false;
}
+ *n = fread(buf, SKIP_ONE, cap, f);
+ (void)fclose(f);
+ return true;
+}
- /* Read only a bounded first line. */
- char buf[CBM_SZ_256];
- size_t n = fread(buf, SKIP_ONE, sizeof(buf) - SKIP_ONE, f);
-
- /* Fail closed on any read error rather than parsing a partial buffer. */
- if (ferror(f)) {
- (void)fclose(f);
- return CBM_LANG_COUNT;
+/* `more`: the file has bytes beyond head[0..n). A first line that fills the
+ * probe and goes on is cut, and a cut line names no interpreter. */
+static CBMLanguage lang_shebang(const unsigned char *head, size_t n, bool more) {
+ if (n > LANG_PROBE_LINE) {
+ n = LANG_PROBE_LINE;
+ more = true;
}
-
- /* If the bounded buffer filled without containing a newline, the first
- * line may extend past our bound. Probe a single extra byte to tell an
- * exact EOF (the whole file is <= 255 bytes) from a truncated longer
- * line: any surviving byte -- including a newline just beyond the bound --
- * means the first line was cut off, so fail closed. A probe read error
- * fails closed too. This keeps the read bounded (no unbounded line read
- * or allocation). */
+ if (n < PAIR_LEN) {
+ return CBM_LANG_COUNT; /* too short to begin with "#!" */
+ }
+ char buf[LANG_PROBE_LINE + SKIP_ONE];
+ memcpy(buf, head, n);
bool have_newline = (memchr(buf, '\n', n) != NULL);
- if (!have_newline && n == sizeof(buf) - SKIP_ONE) {
- int probe = fgetc(f);
- if (probe != EOF || ferror(f)) {
- (void)fclose(f);
- return CBM_LANG_COUNT;
- }
+ if (!have_newline && n == LANG_PROBE_LINE && more) {
+ return CBM_LANG_COUNT;
}
- (void)fclose(f);
/* Must begin with "#!". */
- if (n < PAIR_LEN || buf[0] != '#' || buf[1] != '!') {
+ if (buf[0] != '#' || buf[1] != '!') {
return CBM_LANG_COUNT;
}
@@ -1174,6 +1196,29 @@ CBMLanguage cbm_language_from_shebang(const char *path) {
return lang_for_interpreter(base);
}
+CBMLanguage cbm_language_from_shebang(const char *path) {
+ if (!path) {
+ return CBM_LANG_COUNT;
+ }
+
+ FILE *f = cbm_fopen(path, "rb");
+ if (!f) {
+ return CBM_LANG_COUNT; /* fail closed on read error */
+ }
+
+ /* Read only a bounded first line, plus one byte to tell an exact end of
+ * file from a longer first line. A read error fails closed rather than
+ * parsing a partial buffer. */
+ unsigned char buf[LANG_PROBE_LINE + SKIP_ONE];
+ size_t n = fread(buf, SKIP_ONE, sizeof(buf), f);
+ bool failed = ferror(f) != 0;
+ (void)fclose(f);
+ if (failed) {
+ return CBM_LANG_COUNT;
+ }
+ return lang_shebang(buf, n > LANG_PROBE_LINE ? LANG_PROBE_LINE : n, n > LANG_PROBE_LINE);
+}
+
/* ── .m file disambiguation ──────────────────────────────────────── */
/* Simple substring search helper */
@@ -1238,22 +1283,7 @@ static bool has_matlab_line_markers(const char *buf) {
return false;
}
-CBMLanguage cbm_disambiguate_m(const char *path) {
- if (!path) {
- return CBM_LANG_MATLAB;
- }
-
- FILE *f = cbm_fopen(path, "r");
- if (!f) {
- return CBM_LANG_MATLAB;
- }
-
- /* Read first 4KB */
- char buf[CBM_SZ_4K + SKIP_ONE];
- size_t n = fread(buf, SKIP_ONE, CBM_SZ_4K, f);
- buf[n] = '\0';
- (void)fclose(f);
-
+static CBMLanguage lang_m_text(const char *buf) {
if (has_objc_markers(buf)) {
return CBM_LANG_OBJC;
}
@@ -1271,6 +1301,17 @@ CBMLanguage cbm_disambiguate_m(const char *path) {
return CBM_LANG_MATLAB;
}
+CBMLanguage cbm_disambiguate_m(const char *path) {
+ unsigned char head[LANG_PROBE_HEAD];
+ size_t n = 0;
+ if (!lang_read_head(path, head, sizeof(head), &n)) {
+ return CBM_LANG_MATLAB;
+ }
+ char buf[LANG_PROBE_HEAD + SKIP_ONE];
+ lang_head_text(buf, LANG_PROBE_HEAD, head, n);
+ return lang_m_text(buf);
+}
+
/* Visual Basic 6 / VBA source exports are recognisable from their header (#721):
* every module carries `Attribute VB_Name = "..."`, class modules open with
* `VERSION 1.0 CLASS`, forms/controls with `VERSION 5.00` + `Begin VB.Form` /
@@ -1286,21 +1327,7 @@ static bool has_vb6_markers(const char *buf) {
* VB6 form is reported as unsupported (CBM_LANG_COUNT) rather than handed to
* the FORM grammar, which yields no defs and stray junk nodes. Defaults to
* FORM on any doubt (preserves existing behaviour). */
-CBMLanguage cbm_disambiguate_frm(const char *path) {
- if (!path) {
- return CBM_LANG_FORM;
- }
-
- FILE *f = cbm_fopen(path, "r");
- if (!f) {
- return CBM_LANG_FORM;
- }
-
- char buf[CBM_SZ_4K + SKIP_ONE];
- size_t n = fread(buf, SKIP_ONE, CBM_SZ_4K, f);
- buf[n] = '\0';
- (void)fclose(f);
-
+static CBMLanguage lang_frm_text(const char *buf) {
/* VB6 form files open with "VERSION x.yy" on line 1. */
if (strncmp(buf, "VERSION ", SLEN("VERSION ")) == 0 &&
isdigit((unsigned char)buf[SLEN("VERSION ")])) {
@@ -1309,25 +1336,34 @@ CBMLanguage cbm_disambiguate_frm(const char *path) {
return has_vb6_markers(buf) ? CBM_LANG_COUNT : CBM_LANG_FORM;
}
+CBMLanguage cbm_disambiguate_frm(const char *path) {
+ unsigned char head[LANG_PROBE_HEAD];
+ size_t n = 0;
+ if (!lang_read_head(path, head, sizeof(head), &n)) {
+ return CBM_LANG_FORM;
+ }
+ char buf[LANG_PROBE_HEAD + SKIP_ONE];
+ lang_head_text(buf, LANG_PROBE_HEAD, head, n);
+ return lang_frm_text(buf);
+}
+
/* Disambiguate .res files (#2176): ReScript source shares the extension with
* two binary formats -- Godot resources (RSRC/RSCC magic, the default save
* format for imported meshes) and Windows compiled resource files. Binary
* content has no ReScript meaning, and a NUL byte never occurs in ReScript
* text while both binary formats carry NULs in their first bytes. */
-CBMLanguage cbm_disambiguate_res(const char *path) {
- if (!path) {
- return CBM_LANG_RESCRIPT;
- }
+static CBMLanguage lang_res_bytes(const unsigned char *head, size_t n) {
+ size_t len = n < LANG_PROBE_HEAD ? n : LANG_PROBE_HEAD;
+ return (len > 0 && memchr(head, '\0', len)) ? CBM_LANG_COUNT : CBM_LANG_RESCRIPT;
+}
- FILE *f = cbm_fopen(path, "rb");
- if (!f) {
+CBMLanguage cbm_disambiguate_res(const char *path) {
+ unsigned char head[LANG_PROBE_HEAD];
+ size_t n = 0;
+ if (!lang_read_head(path, head, sizeof(head), &n)) {
return CBM_LANG_RESCRIPT;
}
-
- char buf[CBM_SZ_4K];
- size_t n = fread(buf, SKIP_ONE, sizeof(buf), f);
- (void)fclose(f);
- return memchr(buf, '\0', n) ? CBM_LANG_COUNT : CBM_LANG_RESCRIPT;
+ return lang_res_bytes(head, n);
}
/* Disambiguate .cls files: shared by InterSystems ObjectScript UDL, Salesforce
@@ -1335,21 +1371,7 @@ CBMLanguage cbm_disambiguate_res(const char *path) {
* with a line of the form "Class <UppercasePackage>..."; VB6 class modules
* carry the VB6 header markers and are reported as unsupported (CBM_LANG_COUNT)
* until a Visual Basic grammar exists. Defaults to Apex on any doubt. */
-CBMLanguage cbm_disambiguate_cls(const char *path) {
- if (!path) {
- return CBM_LANG_APEX;
- }
-
- FILE *f = cbm_fopen(path, "r");
- if (!f) {
- return CBM_LANG_APEX;
- }
-
- char buf[CBM_SZ_4K + SKIP_ONE];
- size_t n = fread(buf, SKIP_ONE, CBM_SZ_4K, f);
- buf[n] = '\0';
- (void)fclose(f);
-
+static CBMLanguage lang_cls_text(const char *buf) {
if (has_vb6_markers(buf)) {
return CBM_LANG_COUNT;
}
@@ -1369,6 +1391,17 @@ CBMLanguage cbm_disambiguate_cls(const char *path) {
return CBM_LANG_APEX;
}
+CBMLanguage cbm_disambiguate_cls(const char *path) {
+ unsigned char head[LANG_PROBE_HEAD];
+ size_t n = 0;
+ if (!lang_read_head(path, head, sizeof(head), &n)) {
+ return CBM_LANG_APEX;
+ }
+ char buf[LANG_PROBE_HEAD + SKIP_ONE];
+ lang_head_text(buf, LANG_PROBE_HEAD, head, n);
+ return lang_cls_text(buf);
+}
+
/* Disambiguate .inc files: shared by BitBake include fragments and
* InterSystems ObjectScript include (macro) files. ObjectScript .inc files are
* predominantly macro definitions ("#define NAME ..." / "#def1arg NAME ...");
@@ -1378,21 +1411,7 @@ CBMLanguage cbm_disambiguate_cls(const char *path) {
* We therefore match ObjectScript preprocessor directives ('#' immediately
* followed by 'def'/';'), which BitBake never produces. Defaults to BitBake on
* any doubt (preserves existing behaviour). */
-CBMLanguage cbm_disambiguate_inc(const char *path) {
- if (!path) {
- return CBM_LANG_BITBAKE;
- }
-
- FILE *f = cbm_fopen(path, "r");
- if (!f) {
- return CBM_LANG_BITBAKE;
- }
-
- char buf[CBM_SZ_4K + SKIP_ONE];
- size_t n = fread(buf, SKIP_ONE, CBM_SZ_4K, f);
- buf[n] = '\0';
- (void)fclose(f);
-
+static CBMLanguage lang_inc_text(const char *buf) {
const char *line = buf;
while (*line) {
/* ObjectScript include header: a line beginning "ROUTINE <Uppercase>". */
@@ -1417,6 +1436,17 @@ CBMLanguage cbm_disambiguate_inc(const char *path) {
return CBM_LANG_BITBAKE;
}
+CBMLanguage cbm_disambiguate_inc(const char *path) {
+ unsigned char head[LANG_PROBE_HEAD];
+ size_t n = 0;
+ if (!lang_read_head(path, head, sizeof(head), &n)) {
+ return CBM_LANG_BITBAKE;
+ }
+ char buf[LANG_PROBE_HEAD + SKIP_ONE];
+ lang_head_text(buf, LANG_PROBE_HEAD, head, n);
+ return lang_inc_text(buf);
+}
+
/* Case-insensitive prefix match (portable — no strncasecmp dependency). */
static bool starts_with_ci(const char *s, const char *prefix) {
for (; *prefix; s++, prefix++) {
@@ -1442,23 +1472,7 @@ static bool starts_with_ci(const char *s, const char *prefix) {
* - a different leading tag (e.g. <cfquery> in a bare-tag file) ⇒ cfml;
* - anything else ("component { ... }") ⇒ cfscript.
* Defaults to CBM_LANG_CFSCRIPT on any doubt (preserves table behaviour). */
-CBMLanguage cbm_disambiguate_cfc(const char *path) {
- if (!path) {
- return CBM_LANG_CFSCRIPT;
- }
-
- FILE *f = cbm_fopen(path, "r");
- if (!f) {
- return CBM_LANG_CFSCRIPT;
- }
-
- /* Read a generous head: tag components can carry a large license/revision
- * comment block before the <cfcomponent> opener. */
- char buf[CBM_SZ_16K + SKIP_ONE];
- size_t n = fread(buf, SKIP_ONE, CBM_SZ_16K, f);
- buf[n] = '\0';
- (void)fclose(f);
-
+static CBMLanguage lang_cfc_text(const char *buf) {
/* Rule 1: explicit tag-component markers ⇒ tag dialect. */
if (cbm_strcasestr(buf, "<cfcomponent") != NULL || cbm_strcasestr(buf, "<cffunction") != NULL) {
return CBM_LANG_CFML;
@@ -1487,3 +1501,149 @@ CBMLanguage cbm_disambiguate_cfc(const char *path) {
}
return CBM_LANG_CFSCRIPT;
}
+
+CBMLanguage cbm_disambiguate_cfc(const char *path) {
+ unsigned char head[LANG_PROBE_CFC];
+ size_t n = 0;
+ if (!lang_read_head(path, head, sizeof(head), &n)) {
+ return CBM_LANG_CFSCRIPT;
+ }
+ char buf[LANG_PROBE_CFC + SKIP_ONE];
+ lang_head_text(buf, LANG_PROBE_CFC, head, n);
+ return lang_cfc_text(buf);
+}
+
+/* ── One classifier for a name plus its first bytes ──────────────── */
+
+/* JSON files that are configuration, not source worth indexing. */
+static const char *const IGNORED_JSON_FILES[] = {
+ "package.json", "package-lock.json", "tsconfig.json",
+ "jsconfig.json", "composer.json", "composer.lock",
+ "yarn.lock", "openapi.json", "swagger.json",
+ "jest.config.json", ".eslintrc.json", ".prettierrc.json",
+ ".babelrc.json", "tslint.json", "angular.json",
+ "firebase.json", "renovate.json", "lerna.json",
+ "turbo.json", ".stylelintrc.json", "pnpm-lock.json",
+ "deno.json", "biome.json", "devcontainer.json",
+ ".devcontainer.json", "launch.json", "settings.json",
+ "extensions.json", "tasks.json", NULL};
+
+static bool lang_name_in(const char *name, const char *const *list) {
+ for (int i = 0; list[i]; i++) {
+ if (strcmp(name, list[i]) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* The content rule a name needs, or NULL. */
+static const char *lang_probe_extension(const char *filename) {
+ static const char *const PROBED[] = {".m", ".cls", ".inc", ".cfc", ".frm", ".res", NULL};
+ const char *dot = strrchr(filename, '.');
+ return (dot && lang_name_in(dot, PROBED)) ? dot : NULL;
+}
+
+/* "<Export generator=" in the first line-probe bytes: an ObjectScript Studio
+ * export, which is XML by name. */
+static bool lang_objectscript_export(const unsigned char *head, size_t n) {
+ char buf[LANG_PROBE_LINE + SKIP_ONE];
+ lang_head_text(buf, LANG_PROBE_LINE, head, n);
+ return strstr(buf, "<Export generator=") != NULL;
+}
+
+_Static_assert(LANG_PROBE_CFC == CBM_LANGUAGE_PROBE_MAX, "the longest probe is the public bound");
+
+size_t cbm_language_probe_bytes_with(const cbm_userconfig_t *config, const char *filename) {
+ if (!filename) {
+ return 0;
+ }
+ CBMLanguage lang = lang_for_filename(config, filename);
+ if (lang == CBM_LANG_COUNT) {
+ return LANG_PROBE_LINE; /* the shebang fallback */
+ }
+ const char *ext = lang_probe_extension(filename);
+ if (ext) {
+ return strcmp(ext, ".cfc") == 0 ? LANG_PROBE_CFC : LANG_PROBE_HEAD;
+ }
+ return lang == CBM_LANG_XML ? LANG_PROBE_LINE : 0;
+}
+
+CBMLanguage cbm_language_classify_with(const cbm_userconfig_t *config, const char *filename,
+ const unsigned char *head, size_t head_len, bool more,
+ bool readable) {
+ if (!filename) {
+ return CBM_LANG_COUNT;
+ }
+ if (!readable || !head) {
+ head = NULL;
+ head_len = 0;
+ }
+ CBMLanguage lang = lang_for_filename(config, filename);
+ if (lang == CBM_LANG_COUNT) {
+ /* The name says nothing: a conservative shebang probe, so extensionless
+ * scripts get indexed (#1199). The name stays authoritative otherwise. */
+ return readable ? lang_shebang(head, head_len, more) : CBM_LANG_COUNT;
+ }
+ const char *ext = lang_probe_extension(filename);
+ if (ext) {
+ char buf[LANG_PROBE_CFC + SKIP_ONE];
+ bool cfc = strcmp(ext, ".cfc") == 0;
+ lang_head_text(buf, cfc ? LANG_PROBE_CFC : LANG_PROBE_HEAD, head, head_len);
+ if (strcmp(ext, ".m") == 0) {
+ /* Objective-C, Magma or MATLAB */
+ lang = readable ? lang_m_text(buf) : CBM_LANG_MATLAB;
+ } else if (strcmp(ext, ".cls") == 0) {
+ /* ObjectScript UDL, Apex or a Visual Basic 6 class module */
+ lang = readable ? lang_cls_text(buf) : CBM_LANG_APEX;
+ } else if (strcmp(ext, ".inc") == 0) {
+ /* BitBake or an ObjectScript include */
+ lang = readable ? lang_inc_text(buf) : CBM_LANG_BITBAKE;
+ } else if (cfc) {
+ /* script or tag dialect */
+ lang = readable ? lang_cfc_text(buf) : CBM_LANG_CFSCRIPT;
+ } else if (strcmp(ext, ".frm") == 0) {
+ /* FORM or a Visual Basic 6 form (#721) */
+ lang = readable ? lang_frm_text(buf) : CBM_LANG_FORM;
+ } else {
+ /* .res: ReScript, or a binary Godot / Windows resource (#2176) */
+ lang = readable ? lang_res_bytes(head, head_len) : CBM_LANG_RESCRIPT;
+ }
+ }
+ if (lang == CBM_LANG_XML && readable && lang_objectscript_export(head, head_len)) {
+ return CBM_LANG_OBJECTSCRIPT_EXPORT;
+ }
+ if (lang == CBM_LANG_JSON && lang_name_in(filename, IGNORED_JSON_FILES)) {
+ return CBM_LANG_COUNT;
+ }
+ return lang;
+}
+
+size_t cbm_language_probe_bytes(const char *filename) {
+ return cbm_language_probe_bytes_with(cbm_get_user_lang_config(), filename);
+}
+
+CBMLanguage cbm_language_classify(const char *filename, const unsigned char *head, size_t head_len,
+ bool more, bool readable) {
+ return cbm_language_classify_with(cbm_get_user_lang_config(), filename, head, head_len, more,
+ readable);
+}
+
+CBMLanguage cbm_language_for_file(const char *filename, const char *path) {
+ size_t probe = cbm_language_probe_bytes(filename);
+ if (probe == 0) {
+ return cbm_language_classify(filename, NULL, 0, false, true);
+ }
+ /* One byte past the probe tells a file that ends there from a longer one. */
+ unsigned char head[LANG_PROBE_CFC + SKIP_ONE];
+ size_t n = 0;
+ FILE *f = path ? cbm_fopen(path, "rb") : NULL;
+ if (!f) {
+ return cbm_language_classify(filename, NULL, 0, false, false);
+ }
+ n = fread(head, SKIP_ONE, probe + SKIP_ONE, f);
+ bool failed = ferror(f) != 0;
+ (void)fclose(f);
+ bool more = n > probe;
+ return cbm_language_classify(filename, head, more ? probe : n, more, !failed);
+}
diff --git a/src/discover/userconfig.c b/src/discover/userconfig.c
index c2b45b788..8f906ef07 100644
--- a/src/discover/userconfig.c
+++ b/src/discover/userconfig.c
@@ -333,8 +333,8 @@ static int load_config_file(const char *path, cbm_userext_t **entries, int *coun
}
/* Retain the project input before parsing it; never reopen for declarations. */
-static int load_project_source(const char *path, cbm_userconfig_t *cfg,
- cbm_userext_t **entries, int *count) {
+static int load_project_source(const char *path, cbm_userconfig_t *cfg, cbm_userext_t **entries,
+ int *count) {
cbm_userconfig_source_t *source = cfg->project_source;
source->state = CBM_USERCONFIG_SOURCE_ERROR;
userconfig_source_digest("read-error", NULL, 0, cfg->project_source_sha256);
@@ -383,23 +383,25 @@ static int load_project_source(const char *path, cbm_userconfig_t *cfg,
/* ── Public API ──────────────────────────────────────────────────── */
static cbm_userconfig_t *userconfig_load(const char *repo_path, bool retain_source) {
- cbm_userconfig_t *cfg = calloc(CBM_ALLOC_ONE, sizeof(cbm_userconfig_t));
- if (!cfg) {
- return NULL;
- }
-
+ /* The retained source first: a failure here has nothing else to undo. */
+ cbm_userconfig_source_t *source = NULL;
if (retain_source) {
CBMArena arena;
cbm_arena_init(&arena);
- cfg->project_source = cbm_arena_calloc(&arena, sizeof(*cfg->project_source));
- if (!cfg->project_source) {
+ source = cbm_arena_calloc(&arena, sizeof(*source));
+ if (!source) {
cbm_arena_destroy(&arena);
- free(cfg);
return NULL;
}
- cfg->project_source->arena = arena;
- cfg->project_source->state = CBM_USERCONFIG_SOURCE_ABSENT;
+ source->arena = arena;
+ source->state = CBM_USERCONFIG_SOURCE_ABSENT;
+ }
+ cbm_userconfig_t *cfg = calloc(CBM_ALLOC_ONE, sizeof(cbm_userconfig_t));
+ if (!cfg) {
+ userconfig_source_free(source);
+ return NULL;
}
+ cfg->project_source = source;
cbm_userext_t *entries = NULL;
int count = 0;
@@ -427,8 +429,8 @@ static cbm_userconfig_t *userconfig_load(const char *repo_path, bool retain_sour
userconfig_source_digest("not-applicable", NULL, 0, cfg->project_source_sha256);
if (repo_path && repo_path[0]) {
char project_path[PATH_BUF_SZ];
- int path_len = snprintf(project_path, sizeof(project_path), "%s/.codebase-memory.json",
- repo_path);
+ int path_len =
+ snprintf(project_path, sizeof(project_path), "%s/.codebase-memory.json", repo_path);
int rc;
if (retain_source) {
if (path_len < 0 || (size_t)path_len >= sizeof(project_path)) {
@@ -499,7 +501,7 @@ cbm_userconfig_t *cbm_userconfig_load_with_source(const char *repo_path) {
}
cbm_userconfig_source_state_t cbm_userconfig_project_source(const cbm_userconfig_t *cfg,
- const char **bytes, size_t *len) {
+ const char **bytes, size_t *len) {
if (bytes)
*bytes = NULL;
if (len)
@@ -658,9 +660,8 @@ static cbm_userconfig_snapshot_status_t snapshot_input(cbm_userconfig_source_sta
return len > MAX_CONFIG_SIZE ? CBM_USERCONFIG_SNAPSHOT_LIMIT : CBM_USERCONFIG_SNAPSHOT_OK;
}
-cbm_userconfig_snapshot_status_t
-cbm_userconfig_from_project_bytes(cbm_userconfig_source_state_t state, const void *bytes,
- size_t len, cbm_userconfig_t **out) {
+cbm_userconfig_snapshot_status_t cbm_userconfig_from_project_bytes(
+ cbm_userconfig_source_state_t state, const void *bytes, size_t len, cbm_userconfig_t **out) {
if (!out)
return CBM_USERCONFIG_SNAPSHOT_INVALID;
*out = NULL;
diff --git a/src/discover/userconfig.h b/src/discover/userconfig.h
index cd946e4aa..7f6a15a29 100644
--- a/src/discover/userconfig.h
+++ b/src/discover/userconfig.h
@@ -35,8 +35,8 @@ typedef enum {
} cbm_userconfig_source_state_t;
typedef struct {
- cbm_userext_t *entries; /* heap-allocated array */
- int count; /* number of entries */
+ cbm_userext_t *entries; /* heap-allocated array */
+ int count; /* number of entries */
cbm_userconfig_source_t *project_source; /* optional owned project snapshot */
/* Digests of the exact bytes/state consumed by cbm_userconfig_load(). */
char global_source_sha256[CBM_SHA256_HEX_LEN + 1];
@@ -64,7 +64,7 @@ cbm_userconfig_t *cbm_userconfig_load_with_source(const char *repo_path);
/* The PRESENT byte view belongs to cfg and remains valid until free. Outputs
* are cleared for ABSENT/ERROR. A legacy loader result has no snapshot: ERROR. */
cbm_userconfig_source_state_t cbm_userconfig_project_source(const cbm_userconfig_t *cfg,
- const char **bytes, size_t *len);
+ const char **bytes, size_t *len);
/*
* Look up a file extension in the user config.
@@ -89,9 +89,8 @@ typedef enum {
CBM_USERCONFIG_SNAPSHOT_OOM
} cbm_userconfig_snapshot_status_t;
-cbm_userconfig_snapshot_status_t
-cbm_userconfig_from_project_bytes(cbm_userconfig_source_state_t state, const void *bytes,
- size_t len, cbm_userconfig_t **out);
+cbm_userconfig_snapshot_status_t cbm_userconfig_from_project_bytes(
+ cbm_userconfig_source_state_t state, const void *bytes, size_t len, cbm_userconfig_t **out);
/* ── Integration hook ───────────────────────────────────────────── */
diff --git a/src/foundation/subprocess.c b/src/foundation/subprocess.c
index 1d2f5ee89..16e8d78d6 100644
--- a/src/foundation/subprocess.c
+++ b/src/foundation/subprocess.c
@@ -679,7 +679,8 @@ static cbm_proc_poll_t cbm_subprocess_finish_failed(cbm_subprocess_t *process,
/* Match cbm_path_to_wide's file-path spelling using the process arena. Existing
* option conversions retain their legacy heap ownership. */
static wchar_t *cbm_win_stdin_path(cbm_subprocess_t *process) {
- int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, process->stdin_file, -1, NULL, 0);
+ int length =
+ MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, process->stdin_file, -1, NULL, 0);
if (length <= 0 || length > 32767) {
return NULL;
}
@@ -764,12 +765,19 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
if (!built) {
return -1;
}
+ /* Everything a failure must release, so every failure leaves through
+ * the one exit at the end. */
+ HANDLE job = NULL;
+ HANDLE nul = INVALID_HANDLE_VALUE;
+ HANDLE input = INVALID_HANDLE_VALUE;
+ HANDLE log = INVALID_HANDLE_VALUE;
+ HANDLE stdout_capture = INVALID_HANDLE_VALUE;
+ LPPROC_THREAD_ATTRIBUTE_LIST attrs = NULL;
+ bool attrs_init = false;
wchar_t *wbin = cbm_utf8_to_wide(process->bin);
wchar_t *wcmdline = cbm_utf8_to_wide(cmdline);
if (!wbin || !wcmdline) {
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;
@@ -779,31 +787,20 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
limits.JobMemoryLimit = (SIZE_T)process->memory_limit_bytes;
}
- HANDLE job = CreateJobObjectW(NULL, NULL);
+ job = CreateJobObjectW(NULL, NULL);
if (!job ||
!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof(limits))) {
- if (job) {
- CloseHandle(job);
- }
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
SECURITY_ATTRIBUTES security;
ZeroMemory(&security, sizeof(security));
security.nLength = sizeof(security);
security.bInheritHandle = TRUE;
- HANDLE nul = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE, &security, OPEN_EXISTING, 0, NULL);
- HANDLE input = INVALID_HANDLE_VALUE;
- HANDLE log = INVALID_HANDLE_VALUE;
- HANDLE stdout_capture = INVALID_HANDLE_VALUE;
+ nul = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ &security, OPEN_EXISTING, 0, NULL);
if (nul == INVALID_HANDLE_VALUE) {
- CloseHandle(job);
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
if (process->stdin_file) {
wchar_t *winput = cbm_win_stdin_path(process);
@@ -811,8 +808,8 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
* handle rather than relying only on path attributes. */
DWORD attributes = winput ? GetFileAttributesW(winput) : INVALID_FILE_ATTRIBUTES;
if (attributes != INVALID_FILE_ATTRIBUTES &&
- !(attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT |
- FILE_ATTRIBUTE_DEVICE))) {
+ !(attributes &
+ (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DEVICE))) {
input = CreateFileW(winput, GENERIC_READ, FILE_SHARE_READ, &security, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
}
@@ -821,11 +818,7 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
!GetFileInformationByHandle(input, &input_info) ||
(input_info.dwFileAttributes &
(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DEVICE))) {
- cbm_win_close_spawn_handles(nul, input, log, stdout_capture, NULL, false);
- CloseHandle(job);
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
}
if (process->log_file) {
@@ -841,11 +834,7 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
free(wlog);
}
if (log == INVALID_HANDLE_VALUE) {
- cbm_win_close_spawn_handles(nul, input, log, stdout_capture, NULL, false);
- CloseHandle(job);
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
}
@@ -857,11 +846,7 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
free(wstdout);
}
if (stdout_capture == INVALID_HANDLE_VALUE) {
- cbm_win_close_spawn_handles(nul, input, log, stdout_capture, NULL, false);
- CloseHandle(job);
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
}
@@ -879,17 +864,13 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
}
SIZE_T attrs_size = 0;
(void)InitializeProcThreadAttributeList(NULL, 1, 0, &attrs_size);
- LPPROC_THREAD_ATTRIBUTE_LIST attrs = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attrs_size);
- bool attrs_init = attrs && InitializeProcThreadAttributeList(attrs, 1, 0, &attrs_size);
+ attrs = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attrs_size);
+ attrs_init = attrs && InitializeProcThreadAttributeList(attrs, 1, 0, &attrs_size);
bool attrs_ready = attrs_init && UpdateProcThreadAttribute(
attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherit,
inherit_count * sizeof(inherit[0]), NULL, NULL);
if (!attrs_ready) {
- cbm_win_close_spawn_handles(nul, input, log, stdout_capture, attrs, attrs_init);
- CloseHandle(job);
- free(wbin);
- free(wcmdline);
- return -1;
+ goto fail;
}
STARTUPINFOEXW startup;
@@ -948,6 +929,15 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
process->process_id = child.dwProcessId;
process->job = job;
return 0;
+
+fail:
+ cbm_win_close_spawn_handles(nul, input, log, stdout_capture, attrs, attrs_init);
+ if (job) {
+ CloseHandle(job);
+ }
+ free(wbin);
+ free(wcmdline);
+ return -1;
}
static bool cbm_win_job_active(cbm_subprocess_t *process, bool *known) {
diff --git a/src/foundation/win_utf8.h b/src/foundation/win_utf8.h
index 2e187c028..756c1e558 100644
--- a/src/foundation/win_utf8.h
+++ b/src/foundation/win_utf8.h
@@ -10,7 +10,41 @@
#include <stdlib.h>
#include <wchar.h>
-static inline wchar_t *cbm_utf8_to_wide(const char *utf8) {
+#include "mem_core.h"
+
+/* Converter heaps. The `*_in(cls, ...)` forms allocate through the memory
+ * core and their result is released with cbm_free(cls, p). The legacy names
+ * allocate with the C library for the callers that still release with free();
+ * that route is the residual the memory-core ratchet drives down, so new
+ * callers use the `_in` forms. */
+typedef struct {
+ int core;
+ cbm_mem_class_t cls;
+} cbm_wide_heap_t;
+
+static inline cbm_wide_heap_t cbm_wide_heap_core(cbm_mem_class_t cls) {
+ cbm_wide_heap_t heap = {1, cls};
+ return heap;
+}
+
+static inline cbm_wide_heap_t cbm_wide_heap_libc(void) {
+ cbm_wide_heap_t heap = {0, CBM_MEM_CLASS_OTHER};
+ return heap;
+}
+
+static inline void *cbm_wide_heap_alloc(cbm_wide_heap_t heap, size_t bytes) {
+ return heap.core ? cbm_alloc(heap.cls, bytes) : malloc(bytes);
+}
+
+static inline void cbm_wide_heap_free(cbm_wide_heap_t heap, void *block) {
+ if (heap.core) {
+ cbm_free(heap.cls, block);
+ } else {
+ free(block);
+ }
+}
+
+static inline wchar_t *cbm_utf8_to_wide_heap(cbm_wide_heap_t heap, const char *utf8) {
if (!utf8) {
return NULL;
}
@@ -18,14 +52,22 @@ static inline wchar_t *cbm_utf8_to_wide(const char *utf8) {
if (len <= 0) {
return NULL;
}
- wchar_t *w = (wchar_t *)malloc((size_t)len * sizeof(wchar_t));
+ wchar_t *w = (wchar_t *)cbm_wide_heap_alloc(heap, (size_t)len * sizeof(wchar_t));
if (!w || MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, w, len) != len) {
- free(w);
+ cbm_wide_heap_free(heap, w);
return NULL;
}
return w;
}
+static inline wchar_t *cbm_utf8_to_wide(const char *utf8) {
+ return cbm_utf8_to_wide_heap(cbm_wide_heap_libc(), utf8);
+}
+
+static inline wchar_t *cbm_utf8_to_wide_in(cbm_mem_class_t cls, const char *utf8) {
+ return cbm_utf8_to_wide_heap(cbm_wide_heap_core(cls), utf8);
+}
+
static inline int cbm_win_path_separator(wchar_t value) {
return value == L'\\' || value == L'/';
}
@@ -54,7 +96,8 @@ static inline void cbm_win_path_normalize_wide_separators(wchar_t *path) {
* This makes behavior independent of the process manifest and LongPathsEnabled
* policy. Never use this for non-file strings (command lines, pipe names,
* registry paths). */
-static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {
+static inline wchar_t *cbm_wide_path_to_extended_heap(cbm_wide_heap_t heap,
+ const wchar_t *wide_path) {
if (!wide_path) {
return NULL;
}
@@ -62,7 +105,7 @@ static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {
if (input_length >= 32767U) {
return NULL;
}
- wchar_t *wide = (wchar_t *)malloc((input_length + 1U) * sizeof(*wide));
+ wchar_t *wide = (wchar_t *)cbm_wide_heap_alloc(heap, (input_length + 1U) * sizeof(*wide));
if (!wide) {
return NULL;
}
@@ -77,11 +120,12 @@ static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {
}
DWORD needed = GetFullPathNameW(wide, 0, NULL, NULL);
- wchar_t *full = needed > 0U ? (wchar_t *)malloc((size_t)needed * sizeof(wchar_t)) : NULL;
+ wchar_t *full =
+ needed > 0U ? (wchar_t *)cbm_wide_heap_alloc(heap, (size_t)needed * sizeof(wchar_t)) : NULL;
DWORD copied = full ? GetFullPathNameW(wide, needed, full, NULL) : 0U;
- free(wide);
+ cbm_wide_heap_free(heap, wide);
if (!full || copied == 0U || copied >= needed) {
- free(full);
+ cbm_wide_heap_free(heap, full);
return NULL;
}
cbm_win_path_normalize_wide_separators(full);
@@ -92,7 +136,7 @@ static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {
full[1] == L':' && full[2] == L'\\';
int unc_absolute = copied >= 5U && full[0] == L'\\' && full[1] == L'\\';
if (!drive_absolute && !unc_absolute) {
- free(full);
+ cbm_wide_heap_free(heap, full);
return NULL;
}
@@ -103,27 +147,40 @@ static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {
size_t extended_length = prefix_length + tail_length;
/* The documented extended-length limit includes the terminating NUL. */
if (extended_length >= 32767U) {
- free(full);
+ cbm_wide_heap_free(heap, full);
return NULL;
}
- wchar_t *prefixed = (wchar_t *)malloc((extended_length + 1U) * sizeof(wchar_t));
+ wchar_t *prefixed =
+ (wchar_t *)cbm_wide_heap_alloc(heap, (extended_length + 1U) * sizeof(wchar_t));
if (!prefixed) {
- free(full);
+ cbm_wide_heap_free(heap, full);
return NULL;
}
wmemcpy(prefixed, prefix, prefix_length);
wmemcpy(prefixed + prefix_length, full + tail_offset, tail_length + 1U);
- free(full);
+ cbm_wide_heap_free(heap, full);
return prefixed;
}
-static inline wchar_t *cbm_path_to_wide(const char *utf8_path) {
- wchar_t *wide = cbm_utf8_to_wide(utf8_path);
- wchar_t *extended = cbm_wide_path_to_extended(wide);
- free(wide);
+static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {
+ return cbm_wide_path_to_extended_heap(cbm_wide_heap_libc(), wide_path);
+}
+
+static inline wchar_t *cbm_path_to_wide_heap(cbm_wide_heap_t heap, const char *utf8_path) {
+ wchar_t *wide = cbm_utf8_to_wide_heap(heap, utf8_path);
+ wchar_t *extended = cbm_wide_path_to_extended_heap(heap, wide);
+ cbm_wide_heap_free(heap, wide);
return extended;
}
+static inline wchar_t *cbm_path_to_wide(const char *utf8_path) {
+ return cbm_path_to_wide_heap(cbm_wide_heap_libc(), utf8_path);
+}
+
+static inline wchar_t *cbm_path_to_wide_in(cbm_mem_class_t cls, const char *utf8_path) {
+ return cbm_path_to_wide_heap(cbm_wide_heap_core(cls), utf8_path);
+}
+
/* GetModuleFileNameW can preserve the \\?\ spelling used to launch a process.
* Internal UTF-8 paths use conventional DOS/UNC spelling and add the prefix
* only at the Win32 file-API boundary, so remove it before widening callers
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index fd3521b11..92460bf58 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -54,6 +54,7 @@ enum {
#include "mcp/mcp.h"
#include "mcp/mcp_internal.h"
#include "mcp/test_impact.h"
+#include "mcp/test_impact_engine.h"
#include "store/store.h"
#include "store/store_impact.h"
#include <sqlite3.h>
@@ -774,7 +775,7 @@ static const tool_def_t TOOLS[] = {
{"detect_changes", "Map a Git diff to files and impact. Page with snapshot cursors.",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"scope\":{\"type\":"
- "\"string\",\"enum\":[\"files\",\"impact\"],\"default\":\"impact\"},"
+ "\"string\",\"enum\":[\"files\",\"impact\",\"tests\"],\"default\":\"impact\"},"
"\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\",\"both\"],\"default\":"
"\"inbound\",\"description\":\"inbound=callers; outbound=dependencies; both=union.\"},"
"\"depth\":{\"type\":\"integer\",\"default\":2},"
@@ -16476,6 +16477,68 @@ static bool detect_snapshot_fingerprint(cbm_mcp_server_t *srv, const char *root_
return complete;
}
+/* scope:"tests": which tests the change needs (mcp/test_impact_engine.h). The
+ * answer is computed from a graph of exactly the pinned HEAD commit, built
+ * for this request; the live index is not consulted. Missing evidence is a
+ * run-all answer that names why; only a failed request is an error. */
+static char *detect_test_impact(const char *args, const char *root_path, const char *base_branch) {
+ detect_seed_request_t seed_req = {0};
+ char err[CBM_SZ_1K] = "";
+ detect_seed_parse(args, &seed_req, err, sizeof(err));
+ if (err[0]) {
+ return cbm_mcp_text_result(err, true);
+ }
+ char config_file[CBM_SZ_4K] = "";
+ if (seed_req.config_path[0]) {
+ if (repo_path_is_absolute(seed_req.config_path)) {
+ snprintf(config_file, sizeof(config_file), "%s", seed_req.config_path);
+ } else {
+ snprintf(config_file, sizeof(config_file), "%s/%s", root_path, seed_req.config_path);
+ }
+ }
+ char work[CBM_SZ_4K];
+ snprintf(work, sizeof(work), "%s/test-impact", cbm_resolve_cache_dir());
+ if (!cbm_mkdir_p(work, 0700)) {
+ return cbm_mcp_text_result("test_impact_failed: no private work directory", true);
+ }
+ cbm_test_impact_request_t request = {.repo_root = root_path,
+ .base_ref = base_branch,
+ .work_parent = work,
+ .config_path = config_file[0] ? config_file : NULL,
+ .deadline_ms = cbm_now_ms() + 30ULL * 60ULL * 1000ULL};
+ cbm_test_result_t *result = NULL;
+ char diagnostic[CBM_SZ_512] = "";
+ cbm_test_impact_status_t status =
+ cbm_test_impact_run(&request, &result, diagnostic, sizeof(diagnostic));
+ if (status != CBM_TEST_IMPACT_OK) {
+ char text[CBM_SZ_1K];
+ snprintf(text, sizeof(text), "test_impact_failed: status %d%s%s", (int)status,
+ diagnostic[0] ? ": " : "", diagnostic);
+ return cbm_mcp_text_result(text, true);
+ }
+ size_t length = 0;
+ const char *json = cbm_test_result_json(result, &length);
+ char *res = NULL;
+ size_t total = length + sizeof("{\"test_impact\":}");
+ char *text = json ? cbm_alloc(CBM_MEM_CLASS_OTHER, total) : NULL;
+ if (text) {
+ snprintf(text, total, "{\"test_impact\":%s}", json);
+ res = cbm_mcp_text_result(text, false);
+ cbm_free(CBM_MEM_CLASS_OTHER, text);
+ }
+ cbm_test_result_free(result);
+ return res ? res : cbm_mcp_text_result("test_impact_failed: out of memory", true);
+}
+
+/* The request strings handle_detect_changes owns, released on every early
+ * return (NULL is fine). */
+static void detect_release(char *root_path, char *project, char *base_branch, char *scope) {
+ free(root_path);
+ free(project);
+ free(base_branch);
+ free(scope);
+}
+
static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
char *project = get_project_arg(args);
char *base_branch = cbm_mcp_get_string_arg(args, "base_branch");
@@ -16530,23 +16593,23 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
if (!validate_search_path_arg(root_path) ||
!validate_windows_cmd_interpolation_arg(root_path)) {
- free(root_path);
- free(project);
- free(base_branch);
- free(scope);
+ detect_release(root_path, project, base_branch, scope);
return cbm_mcp_text_result("project path contains invalid characters", true);
}
+ if (scope && strcmp(scope, "tests") == 0) {
+ char *res = detect_test_impact(args, root_path, base_branch);
+ detect_release(root_path, project, base_branch, scope);
+ return res;
+ }
+
/* Every detect snapshot and cursor is generation-bound. Validate the
* metadata immediately after store resolution so fresh requests and
* cursor replays fail identically before Git work or cursor minting. */
cbm_store_t *store = srv->store;
char generation[96] = "";
if (cbm_store_generation(store, generation, sizeof(generation)) != CBM_STORE_OK) {
- free(root_path);
- free(project);
- free(base_branch);
- free(scope);
+ detect_release(root_path, project, base_branch, scope);
return cbm_mcp_text_result(
"index_metadata_error: generation metadata is unreadable; reindex before detecting "
"changes",
diff --git a/src/mcp/test_impact.c b/src/mcp/test_impact.c
index 6ad66adb4..fe678c5fd 100644
--- a/src/mcp/test_impact.c
+++ b/src/mcp/test_impact.c
@@ -46,7 +46,8 @@ struct cbm_test_model {
bool presets[CBM_TEST_PRESET_COUNT];
cbm_test_model_mapping_issue_t mapping;
bool finished;
- bool incomplete; /* sticky: a partial scan must never justify omission */
+ bool incomplete; /* sticky: a partial scan must never justify omission */
+ bool scoped_uncertain; /* some suite is `uncertain`; see tm_add_source */
};
const cbm_test_conventions_t *cbm_test_conventions_cbm(void) {
@@ -269,6 +270,7 @@ typedef struct {
const char *end;
int line;
bool line_start; /* only blanks so far on this line: a '#' opens a directive */
+ bool directive; /* lexing the text of one directive, continuations included */
bool *incomplete; /* shared by lookahead copies; restoring a cursor cannot erase an error */
} tm_lex_t;
@@ -286,6 +288,21 @@ static void tm_lex_uncertain(tm_lex_t *lx) {
}
}
+/* The length of a line splice (backslash, then LF or CRLF) at p, else 0. */
+static size_t tm_splice_len(const char *p, const char *end) {
+ if (p >= end || *p != '\\') {
+ return 0;
+ }
+ if (p + 1 < end && p[1] == '\n') {
+ return 2;
+ }
+ return p + 2 < end && p[1] == '\r' && p[2] == '\n' ? 3 : 0;
+}
+
+static bool tm_blank(char c) {
+ return c == ' ' || c == '\t';
+}
+
/* Raw strings need a delimiter-aware C++ lexer, which this model does not
* implement. Retain the old rows for diagnostics, but never certify them. */
static bool tm_raw_literal_starts(const char *p, const char *end) {
@@ -300,8 +317,7 @@ static void tm_skip_line_comment(tm_lex_t *lx) {
while (lx->p < lx->end && *lx->p != '\n') {
/* Translation-phase line splicing can extend this comment. The
* legacy lexer does not implement it, so its rows are uncertain. */
- if (*lx->p == '\\' && lx->p + 1 < lx->end &&
- (lx->p[1] == '\n' || (lx->p[1] == '\r' && lx->p + 2 < lx->end && lx->p[2] == '\n'))) {
+ if (tm_splice_len(lx->p, lx->end)) {
tm_lex_uncertain(lx);
}
lx->p++;
@@ -315,6 +331,9 @@ static void tm_skip_block_comment(tm_lex_t *lx) {
lx->p += 2;
return;
}
+ if (*lx->p == '*' && tm_splice_len(lx->p + 1, lx->end)) {
+ tm_lex_uncertain(lx); /* the splice may close the comment */
+ }
if (*lx->p == '\n') {
lx->line++;
}
@@ -360,9 +379,19 @@ static void tm_read_directive(tm_lex_t *lx, tm_tok_t *tok) {
tm_skip_literal(lx);
continue;
}
- if (*lx->p == '\\' && lx->p + 1 < lx->end && lx->p[1] == '\n') {
+ size_t splice = tm_splice_len(lx->p, lx->end);
+ if (splice) {
+ /* Next to a blank a continuation only separates tokens; with
+ * token characters on both sides it could join them, which the
+ * re-lexing of this text (tm_directive_word) does not do. The
+ * '#' precedes the text, so p[-1] is in bounds. */
+ const char *after = lx->p + splice;
+ if (!tm_blank(lx->p[-1]) && after < lx->end && !tm_blank(*after) && *after != '\n' &&
+ *after != '\r') {
+ tm_lex_uncertain(lx);
+ }
lx->line++;
- lx->p += 2;
+ lx->p = after;
continue;
}
if (*lx->p == '/' && lx->p + 1 < lx->end && lx->p[1] == '*') {
@@ -388,6 +417,10 @@ static void tm_next(tm_lex_t *lx, tm_tok_t *tok) {
tm_skip_line_comment(lx);
} else if (c == '/' && lx->p + 1 < lx->end && lx->p[1] == '*') {
tm_skip_block_comment(lx);
+ } else if (lx->directive && tm_splice_len(lx->p, lx->end)) {
+ /* A continuation tm_read_directive already followed and judged. */
+ lx->line++;
+ lx->p += tm_splice_len(lx->p, lx->end);
} else {
break;
}
@@ -400,6 +433,9 @@ static void tm_next(tm_lex_t *lx, tm_tok_t *tok) {
if (tm_raw_literal_starts(lx->p, lx->end)) {
tm_lex_uncertain(lx);
}
+ if (tm_splice_len(lx->p, lx->end)) {
+ tm_lex_uncertain(lx); /* a splice in plain code can join tokens */
+ }
bool line_start = lx->line_start;
lx->line_start = false;
if (c == '#' && line_start) {
@@ -594,7 +630,8 @@ static void tm_add_runner_suite(tm_scan_t *sc, const tm_tok_t *name, bool perf)
return;
}
m->runner = items;
- items[m->runner_count++] = (cbm_test_runner_suite_t){.name = copy, .perf = perf};
+ items[m->runner_count++] =
+ (cbm_test_runner_suite_t){.name = copy, .perf = perf, .file = sc->file, .line = name->line};
}
/* Virtual preset records are immutable. Original configured records are kept
@@ -816,6 +853,15 @@ static bool tm_descriptor_ident(tm_scan_t *sc, const tm_tok_t *tok) {
}
if (first == -2)
return false;
+ /* A function-like macro name not followed by '(' is not an invocation:
+ * the preprocessor leaves it alone (an array or variable that happens to
+ * carry the name), so it defines and registers nothing. An opened '('
+ * that does not close stays a malformed invocation below. */
+ tm_lex_t peek = sc->lx;
+ tm_tok_t next;
+ tm_next(&peek, &next);
+ if (!tm_tok_punct(&next, '('))
+ return false;
tm_invocation_t invocation = {0};
cbm_arena_init_sized(&invocation.arena, TM_INVOCATION_ARENA_BLOCK);
int parsed = tm_invocation_parse(sc, sc->lx, &invocation);
@@ -921,8 +967,11 @@ static void tm_descriptor_macro_body(tm_scan_t *sc, const tm_tok_t *word) {
/* The first word of a directive and what follows it. */
static void tm_directive_word(const tm_tok_t *tok, tm_tok_t *word, tm_lex_t *rest,
bool *incomplete) {
- *rest = (tm_lex_t){
- .p = tok->text, .end = tok->text + tok->len, .line = tok->line, .incomplete = incomplete};
+ *rest = (tm_lex_t){.p = tok->text,
+ .end = tok->text + tok->len,
+ .line = tok->line,
+ .directive = true,
+ .incomplete = incomplete};
tm_next(rest, word);
}
@@ -958,13 +1007,12 @@ static void tm_directive(tm_scan_t *sc, const tm_tok_t *tok) {
sc->m->incomplete = true;
}
if (tm_tok_is(&word, "ifndef")) {
- guard = condition.kind == TM_TOK_IDENT && tm_is_include_guard(sc, &condition);
- if (guard &&
- (sc->seen_token || sc->depth || sc->open != TM_OPEN_NONE || sc->cond_count)) {
- /* Keep the legacy diagnostic rows, but only certify a guard
- * that starts the file at outermost scope. */
- sc->m->incomplete = true;
- }
+ /* Only a guard that starts the file at outermost scope conditions
+ * nothing. The same pair anywhere else is the define-if-undefined
+ * idiom: an ordinary condition, so what it encloses is conditional. */
+ guard = condition.kind == TM_TOK_IDENT && !sc->seen_token && !sc->depth &&
+ sc->open == TM_OPEN_NONE && !sc->cond_count &&
+ tm_is_include_guard(sc, &condition);
}
if (sc->cond_count < TM_COND_MAX) {
sc->cond[sc->cond_count] = (tm_cond_t){.depth = sc->depth, .guard = guard};
@@ -1154,30 +1202,18 @@ static void tm_ident(tm_scan_t *sc, const tm_tok_t *tok) {
}
}
-static bool tm_add_source(cbm_test_model_t *m, const char *file, const char *text, size_t len,
- int language_kind) {
- if (!m || m->finished || !file || (!text && len > 0)) {
- if (m) {
- m->incomplete = true;
- }
- return false;
- }
+static bool tm_scan_source(cbm_test_model_t *m, const char *file, const char *text, size_t len,
+ int language_kind) {
if (!text) {
text = ""; /* (NULL, 0) is empty input, never NULL pointer arithmetic */
}
if (memchr(text, '\0', len)) {
m->incomplete = true;
}
- /* Translation-phase splicing can join identifiers, punctuators, or
- * comment delimiters before this lexer sees them. Without preprocessing,
- * even an otherwise handled directive/string splice prevents certainty. */
- for (size_t i = 0; i < len; i++) {
- if (text[i] == '\\' && len - i >= 2 &&
- (text[i + 1] == '\n' || (len - i >= 3 && text[i + 1] == '\r' && text[i + 2] == '\n'))) {
- m->incomplete = true;
- break;
- }
- }
+ /* Translation-phase line splicing is followed where the lexer reads it
+ * correctly (a directive's continuation lines, an escaped newline in a
+ * literal); a splice it cannot follow (in plain code, or extending a line
+ * comment) marks the file uncertain where it is met. */
tm_scan_t sc = {.m = m, .language_kind = language_kind, .ok = true};
int first_suite = m->suite_count;
sc.file = cbm_arena_strdup(&m->arena, file);
@@ -1224,6 +1260,44 @@ static bool tm_add_source(cbm_test_model_t *m, const char *file, const char *tex
return sc.ok;
}
+/* Scan one file and scope what it left uncertain. The uncertainty of a file
+ * that defines its own suite stays with those suites, which then run whole;
+ * a file that registers runner suites or defines no suite has nothing to
+ * scope it to, and a failure is never scoped. */
+static bool tm_add_source(cbm_test_model_t *m, const char *file, const char *text, size_t len,
+ int language_kind) {
+ if (!m || m->finished || !file || (!text && len > 0)) {
+ if (m) {
+ m->incomplete = true;
+ }
+ return false;
+ }
+ bool before = m->incomplete;
+ int first_suite = m->suite_count;
+ int first_runner = m->runner_count;
+ m->incomplete = false;
+ bool ok = tm_scan_source(m, file, text, len, language_kind);
+ bool uncertain = m->incomplete;
+ m->incomplete = before;
+ if (!ok) {
+ m->incomplete = true;
+ return false;
+ }
+ if (uncertain) {
+ bool own_suite = m->suite_count > first_suite;
+ bool registers_runner = m->runner_count > first_runner;
+ if (!own_suite || registers_runner) {
+ m->incomplete = true;
+ } else {
+ for (int i = first_suite; i < m->suite_count; i++) {
+ m->suites[i].uncertain = true;
+ }
+ m->scoped_uncertain = true;
+ }
+ }
+ return true;
+}
+
bool cbm_test_model_add_source(cbm_test_model_t *m, const char *file, const char *text,
size_t len) {
if (m && m->descriptor_mode) {
@@ -1355,6 +1429,10 @@ bool cbm_test_model_finish(cbm_test_model_t *m) {
/* ── Accessors ───────────────────────────────────────────────────── */
bool cbm_test_model_complete(const cbm_test_model_t *m) {
+ return m && m->finished && !m->incomplete && !m->scoped_uncertain;
+}
+
+bool cbm_test_model_narrowable(const cbm_test_model_t *m) {
return m && m->finished && !m->incomplete;
}
diff --git a/src/mcp/test_impact.h b/src/mcp/test_impact.h
index 87fd6983e..7153e0e8d 100644
--- a/src/mcp/test_impact.h
+++ b/src/mcp/test_impact.h
@@ -51,6 +51,10 @@ typedef struct {
/* The file defines a macro that registers tests. The suite may then run
* tests the model cannot name, so it can only be selected whole. */
bool macro_registrations;
+ /* The model could not read this suite's file with certainty (for
+ * example tests defined by a macro). The suite can only run whole; other
+ * suites stay narrowable (cbm_test_model_narrowable). */
+ bool uncertain;
} cbm_test_suite_t;
typedef struct {
@@ -65,6 +69,8 @@ typedef struct {
typedef struct {
const char *name;
bool perf;
+ const char *file; /* the runner file that registers it */
+ int line;
} cbm_test_runner_suite_t;
typedef struct cbm_test_model cbm_test_model_t;
@@ -91,6 +97,13 @@ void cbm_test_model_free(cbm_test_model_t *m);
* file/runner inventory is complete and conventions are applicable. */
bool cbm_test_model_complete(const cbm_test_model_t *m);
+/* True after finish when every uncertainty the model found is scoped to the
+ * suites of the file it was found in (those suites are marked `uncertain` and
+ * can only run whole). Uncertainty in a file that registers runner suites, in
+ * a file with no suite of its own, in the configuration, or a failure keeps
+ * this false, and nothing may be narrowed. complete() implies narrowable(). */
+bool cbm_test_model_narrowable(const cbm_test_model_t *m);
+
/* Descriptor mode is independent of the legacy six-spelling constructor.
* Copies every original record, ordered name_args, optional template and
* preset switch. NULL means invalid input or allocation failure. Unsupported
@@ -228,28 +241,28 @@ typedef struct {
} cbm_coverage_profile_binding_t;
typedef struct {
- int id; /* dense 0-based; row index */
+ int id; /* dense 0-based; row index */
const unsigned char *name; /* owned bytes; NOT a C-string contract */
- size_t name_length; /* positive; embedded NUL is representable */
- uint64_t function_hash; /* all 64 bits, without masking */
- uint64_t counter_count; /* positive shape; no counter values stored */
+ size_t name_length; /* positive; embedded NUL is representable */
+ uint64_t function_hash; /* all 64 bits, without masking */
+ uint64_t counter_count; /* positive shape; no counter values stored */
} cbm_coverage_profile_t;
typedef struct {
uint64_t max_input_bytes; /* profiles_len + tests_len; <= UINT64_MAX/8 */
- uint64_t max_items; /* exactly 1 header + profile rows + test rows + ID references */
- size_t max_alloc_bytes; /* cumulative logical allocation requests, including scratch */
- int max_ids; /* positive, <= INT_MAX; dense universe cardinality */
+ uint64_t max_items; /* exactly 1 header + profile rows + test rows + ID references */
+ size_t max_alloc_bytes; /* cumulative logical allocation requests, including scratch */
+ int max_ids; /* positive, <= INT_MAX; dense universe cardinality */
} cbm_coverage_parse_limits_t;
typedef bool (*cbm_coverage_parse_cancel_fn)(void *context);
typedef enum {
CBM_COVERAGE_PARSE_OK = 0,
- CBM_COVERAGE_PARSE_INVALID, /* bad pointers/limits, invalid C call */
- CBM_COVERAGE_PARSE_FORMAT, /* malformed/noncanonical identities or invalid test rows */
+ CBM_COVERAGE_PARSE_INVALID, /* bad pointers/limits, invalid C call */
+ CBM_COVERAGE_PARSE_FORMAT, /* malformed/noncanonical identities or invalid test rows */
CBM_COVERAGE_PARSE_UNSUPPORTED, /* well-formed recognized header, wire version != 2 */
- CBM_COVERAGE_PARSE_LIMIT, /* byte/item/ID/logical allocation/representation limit */
+ CBM_COVERAGE_PARSE_LIMIT, /* byte/item/ID/logical allocation/representation limit */
CBM_COVERAGE_PARSE_CANCELLED,
CBM_COVERAGE_PARSE_OOM
} cbm_coverage_parse_status_t;
@@ -266,12 +279,12 @@ typedef enum {
* OK owns all data in CBMArena storage and permits unobserved IDs explicitly.
* OK never establishes image/universe/row completeness or artifact admission.
* Use existing cbm_coverage_map_free; no shared mutable or cancellation state. */
-cbm_coverage_parse_status_t cbm_coverage_map_parse_v2(
- const void *profiles, size_t profiles_len,
- const char *tests, size_t tests_len,
- const cbm_coverage_parse_limits_t *limits,
- cbm_coverage_parse_cancel_fn cancelled, void *cancel_context,
- cbm_coverage_map_t **out);
+cbm_coverage_parse_status_t cbm_coverage_map_parse_v2(const void *profiles, size_t profiles_len,
+ const char *tests, size_t tests_len,
+ const cbm_coverage_parse_limits_t *limits,
+ cbm_coverage_parse_cancel_fn cancelled,
+ void *cancel_context,
+ cbm_coverage_map_t **out);
/* O(1) borrowed views until map_free. NULL map -> NONE / 0 / NULL.
* Generic count and exact digest work for formats 1 and 2. No reserialization:
@@ -286,8 +299,7 @@ const char *cbm_coverage_map_identity_sha256(const cbm_coverage_map_t *map);
* but binding remains available. Records remain in dense ID order. */
const cbm_coverage_profile_binding_t *cbm_coverage_map_profile_binding(
const cbm_coverage_map_t *map);
-const cbm_coverage_profile_t *cbm_coverage_map_profiles(
- const cbm_coverage_map_t *map, int *count);
+const cbm_coverage_profile_t *cbm_coverage_map_profiles(const cbm_coverage_map_t *map, int *count);
/* Existing test/find_test/intersection/free APIs retain their row semantics.
* On v2, old functions() returns NULL/count=0, find_function() returns NULL,
@@ -295,7 +307,6 @@ const cbm_coverage_profile_t *cbm_coverage_map_profiles(
* check_receipt() returns INVALID|METADATA before interpreting v1 evidence.
* All format-1 behavior, uniqueness and observed-ID guards stay unchanged. */
-
/* Explicit byte lengths; inputs need not be NUL-terminated. LF and CRLF are
* accepted. NULL means invalid/incomplete syntax, inconsistent references, or
* allocation failure; no partial map is returned. Does not read meta.json. */
diff --git a/src/mcp/test_impact_changes.c b/src/mcp/test_impact_changes.c
index 81a86a7e7..897701d2a 100644
--- a/src/mcp/test_impact_changes.c
+++ b/src/mcp/test_impact_changes.c
@@ -54,8 +54,8 @@ static bool changes_path_valid(const unsigned char *path, size_t length) {
return true;
}
-static bool changes_record(const unsigned char *bytes, size_t length, size_t *offset,
- char *status, changes_slice_t *path) {
+static bool changes_record(const unsigned char *bytes, size_t length, size_t *offset, char *status,
+ changes_slice_t *path) {
size_t at = *offset;
if (length - at < 4 || bytes[at + 1] != 0 ||
(bytes[at] != 'A' && bytes[at] != 'M' && bytes[at] != 'D' && bytes[at] != 'T')) {
@@ -76,8 +76,8 @@ static bool changes_record(const unsigned char *bytes, size_t length, size_t *of
return true;
}
-static int changes_path_compare(const unsigned char *a, size_t a_length,
- const unsigned char *b, size_t b_length) {
+static int changes_path_compare(const unsigned char *a, size_t a_length, const unsigned char *b,
+ size_t b_length) {
size_t common = a_length < b_length ? a_length : b_length;
int order = memcmp(a, b, common); /* specified unsigned-byte comparison */
return order ? order : (a_length > b_length) - (a_length < b_length);
@@ -94,9 +94,9 @@ static void changes_sort(cbm_change_file_t *files, cbm_change_file_t *scratch, s
size_t a = left;
size_t b = middle;
for (size_t i = left; i < right; i++) {
- if (b == right || (a < middle &&
- changes_path_compare(source[a].path, source[a].path_length,
- source[b].path, source[b].path_length) <= 0)) {
+ if (b == right || (a < middle && changes_path_compare(
+ source[a].path, source[a].path_length,
+ source[b].path, source[b].path_length) <= 0)) {
target[i] = source[a++];
} else {
target[i] = source[b++];
@@ -117,8 +117,7 @@ static void changes_sort(cbm_change_file_t *files, cbm_change_file_t *scratch, s
}
}
-static size_t changes_find(const cbm_changes_t *changes, const unsigned char *path,
- size_t length) {
+static size_t changes_find(const cbm_changes_t *changes, const unsigned char *path, size_t length) {
size_t low = 0;
size_t high = changes->count;
while (low < high) {
@@ -143,7 +142,7 @@ static bool changes_starts(changes_slice_t line, const char *prefix) {
}
static bool changes_line(const unsigned char *bytes, size_t length, size_t *offset,
- changes_slice_t *line) {
+ changes_slice_t *line) {
if (*offset == length) {
return false;
}
@@ -241,8 +240,7 @@ static bool changes_old_range_usable(changes_slice_t line) {
}
break;
}
- return offset < line.length && line.bytes[offset] == ' ' &&
- (values[1] == 0 || values[0] > 0);
+ return offset < line.length && line.bytes[offset] == ' ' && (values[1] == 0 || values[0] > 0);
}
/* The legacy file result does not retain old/new mode metadata or the old
@@ -286,13 +284,15 @@ static void changes_audit_headers(cbm_changes_t *changes) {
cbm_change_file_t *file = &changes->files[current];
if (changes_starts(line, "old mode ") || changes_starts(line, "new mode ")) {
file->reasons |= CBM_CHANGE_MODE;
- if (!changes_mode(line, changes_starts(line, "old mode ") ? "old mode " : "new mode ")) {
+ if (!changes_mode(line,
+ changes_starts(line, "old mode ") ? "old mode " : "new mode ")) {
changes->issues |= CBM_CHANGES_PATCH_INCOMPLETE;
}
} else if (changes_starts(line, "new file mode ") ||
changes_starts(line, "deleted file mode ")) {
- if (!changes_mode(line, changes_starts(line, "new file mode ") ?
- "new file mode " : "deleted file mode ")) {
+ if (!changes_mode(line, changes_starts(line, "new file mode ")
+ ? "new file mode "
+ : "deleted file mode ")) {
changes->issues |= CBM_CHANGES_PATCH_INCOMPLETE;
}
} else if (changes_starts(line, "--- ")) {
@@ -335,8 +335,9 @@ static void changes_reconcile(cbm_changes_t *changes, changes_match_t *matches)
for (int i = 0; i < patch_count; i++) {
const cbm_diff_file_t *file = &files[i];
size_t length = strlen(file->path);
- size_t index = changes_path_valid((const unsigned char *)file->path, length) ?
- changes_find(changes, (const unsigned char *)file->path, length) : SIZE_MAX;
+ size_t index = changes_path_valid((const unsigned char *)file->path, length)
+ ? changes_find(changes, (const unsigned char *)file->path, length)
+ : SIZE_MAX;
if (index == SIZE_MAX) {
changes->issues |= CBM_CHANGES_PATCH_EXTRA_PATH;
continue;
@@ -386,13 +387,15 @@ static void changes_reconcile(cbm_changes_t *changes, changes_match_t *matches)
file->patch_file = matches[i].file;
}
}
- changes->state = changes->count ? CBM_CHANGES_NONEMPTY :
- (changes->patch_length == 0 && changes->reconciled ? CBM_CHANGES_EMPTY : CBM_CHANGES_UNKNOWN);
+ changes->state =
+ changes->count ? CBM_CHANGES_NONEMPTY
+ : (changes->patch_length == 0 && changes->reconciled ? CBM_CHANGES_EMPTY
+ : CBM_CHANGES_UNKNOWN);
}
-cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status,
- size_t name_status_length, const unsigned char *patch,
- size_t patch_length, cbm_changes_t **out) {
+cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status, size_t name_status_length,
+ const unsigned char *patch, size_t patch_length,
+ cbm_changes_t **out) {
if (out) {
*out = NULL;
}
@@ -410,7 +413,8 @@ cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status,
}
count++;
}
- if (count > SIZE_MAX / sizeof(cbm_change_file_t) || count > SIZE_MAX / sizeof(changes_match_t)) {
+ if (count > SIZE_MAX / sizeof(cbm_change_file_t) ||
+ count > SIZE_MAX / sizeof(changes_match_t)) {
return CBM_CHANGES_OOM;
}
CBMArena arena;
@@ -449,7 +453,8 @@ cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status,
for (size_t i = 0; i < count; i++) {
changes_slice_t path;
char status;
- if (!changes_record(changes->name_status, name_status_length, &offset, &status, &path)) {
+ if (!changes_record(changes->name_status, name_status_length, &offset, &status,
+ &path)) {
cbm_changes_free(changes);
return CBM_CHANGES_INVALID;
}
@@ -470,7 +475,7 @@ cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status,
* C-string path consumer; retain the exact bytes and conservative inventory. */
bool binary_text = patch_length && memchr(changes->patch, 0, patch_length);
changes->diff = cbm_diff_parse(binary_text ? "" : (const char *)changes->patch,
- binary_text ? 0 : patch_length);
+ binary_text ? 0 : patch_length);
if (!changes->diff) {
goto oom;
}
diff --git a/src/mcp/test_impact_changes.h b/src/mcp/test_impact_changes.h
index e8553a176..2c923967b 100644
--- a/src/mcp/test_impact_changes.h
+++ b/src/mcp/test_impact_changes.h
@@ -10,11 +10,7 @@
* This is not a graph/coverage identity or provenance certificate. */
typedef struct cbm_changes cbm_changes_t;
-typedef enum {
- CBM_CHANGES_OK = 0,
- CBM_CHANGES_INVALID,
- CBM_CHANGES_OOM
-} cbm_changes_status_t;
+typedef enum { CBM_CHANGES_OK = 0, CBM_CHANGES_INVALID, CBM_CHANGES_OOM } cbm_changes_status_t;
typedef enum {
CBM_CHANGES_UNKNOWN = 0,
@@ -55,9 +51,9 @@ typedef struct {
* OOM/no owner. Legacy reader may mask header OOM as incomplete: such a result
* retains paths but no hunk pointers and requires outer broad/full fallback.
* NULL input is allowed only at zero length. No I/O, path expansion or recoding. */
-cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status,
- size_t name_status_length, const unsigned char *patch,
- size_t patch_length, cbm_changes_t **out);
+cbm_changes_status_t cbm_changes_parse(const unsigned char *name_status, size_t name_status_length,
+ const unsigned char *patch, size_t patch_length,
+ cbm_changes_t **out);
void cbm_changes_free(cbm_changes_t *changes);
/* Complete authoritative inventory, sorted by unsigned path bytes. Never
diff --git a/src/mcp/test_impact_classify.c b/src/mcp/test_impact_classify.c
new file mode 100644
index 000000000..df8e1ef37
--- /dev/null
+++ b/src/mcp/test_impact_classify.c
@@ -0,0 +1,363 @@
+/*
+ * test_impact_classify.c — the classified ledger of a pinned HEAD inventory
+ * (test_impact_classify.h).
+ */
+#include "mcp/test_impact_classify.h"
+
+#include "discover/discover.h"
+#include "foundation/arena.h"
+#include "foundation/mem_core.h"
+#include "mcp/test_impact_inventory_internal.h"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+struct cbm_test_impact_ledger {
+ CBMArena arena; /* owns this struct and the rows */
+ cbm_test_impact_classified_t *rows;
+ size_t count;
+ unsigned char manifest[32];
+ cbm_test_impact_classify_usage_t usage;
+};
+
+/* What the inventory's limits leave for this pass after the filter. */
+typedef struct {
+ uint64_t reads;
+ uint64_t content_bytes;
+ size_t arena_bytes;
+ size_t probe_bytes;
+} cls_budget_t;
+
+static bool cls_fail(cni_context *c, cbm_inventory_status_t status, const char *what) {
+ if (c->error.status == CBM_INVENTORY_OK) {
+ c->error.status = status;
+ c->error.file_index = c->file_index;
+ snprintf(c->error.diagnostic, sizeof(c->error.diagnostic), "%s", what);
+ }
+ return false;
+}
+
+static const char *cls_basename(const cbm_inventory_path_t *path) {
+ const char *name = (const char *)path->data;
+ const char *slash = strrchr(name, '/');
+ return slash ? slash + 1 : name;
+}
+
+static bool cls_budget(cni_context *c, const cbm_test_impact_inventory_t *inventory,
+ cls_budget_t *out) {
+ cbm_inventory_limits_t limits;
+ cbm_test_impact_inventory_usage_t usage;
+ if (!cbm_test_impact_inventory_limits(inventory, &limits) ||
+ !cbm_test_impact_inventory_usage(inventory, &usage)) {
+ return cls_fail(c, CBM_INVENTORY_STATE, "inventory has no limits");
+ }
+ if (usage.filter.verified_file_reads_reserved > limits.max_verified_file_reads ||
+ usage.filter.verified_content_bytes_reserved > limits.max_verified_content_bytes ||
+ usage.arena_budget_used_bytes > limits.max_arena_bytes) {
+ return cls_fail(c, CBM_INVENTORY_STATE, "inventory usage exceeds its limits");
+ }
+ out->reads = limits.max_verified_file_reads - usage.filter.verified_file_reads_reserved;
+ out->content_bytes =
+ limits.max_verified_content_bytes - usage.filter.verified_content_bytes_reserved;
+ out->arena_bytes = limits.max_arena_bytes - usage.arena_budget_used_bytes;
+ out->probe_bytes = limits.max_probe_prefix_bytes;
+ return true;
+}
+
+/* The inventory and the tree describe the same snapshot. */
+static bool cls_bound(cni_context *c, const cbm_inventory_filter_view_t *view,
+ cbm_pinned_tree_t *tree) {
+ const cbm_pinned_tree_view_t *native = cbm_pinned_tree_view(tree);
+ if (!native) {
+ return cls_fail(c, CBM_INVENTORY_STATE, "pinned tree is not ready");
+ }
+ if (native->file_count != view->file_count ||
+ memcmp(native->manifest_sha256, view->manifest_sha256, sizeof(view->manifest_sha256)) !=
+ 0) {
+ return cls_fail(c, CBM_INVENTORY_CHANGED, "pinned tree is not the inventory's snapshot");
+ }
+ return true;
+}
+
+static size_t cls_survivors(const cbm_inventory_filter_view_t *view) {
+ size_t n = 0;
+ for (size_t i = 0; i < view->file_count; i++) {
+ n += view->rows[i].disposition == CBM_INVENTORY_FILTER_NEEDS_LANGUAGE;
+ }
+ return n;
+}
+
+/* One survivor: the name, and the verified blob prefix where the name needs
+ * it. Charges the read to the budget. */
+static bool cls_one(cni_context *c, cni_reader *reader, const cbm_userconfig_t *config,
+ cls_budget_t *budget, cbm_test_impact_ledger_t *ledger, size_t index,
+ CBMLanguage *out) {
+ const cbm_inventory_file_t *file = &reader->files[index];
+ const char *name = cls_basename(&file->path);
+ size_t probe = cbm_language_probe_bytes_with(config, name);
+ if (probe == 0) {
+ *out = cbm_language_classify_with(config, name, NULL, 0, false, true);
+ return true;
+ }
+ if (probe > budget->probe_bytes || probe > CBM_LANGUAGE_PROBE_MAX) {
+ return cls_fail(c, CBM_INVENTORY_LIMIT, "language probe exceeds the probe limit");
+ }
+ if (budget->reads == 0 || file->content_length > budget->content_bytes) {
+ return cls_fail(c, CBM_INVENTORY_LIMIT, "language probe exceeds the read budget");
+ }
+ unsigned char head[CBM_LANGUAGE_PROBE_MAX];
+ size_t copied = 0;
+ reader->content_bound = budget->content_bytes;
+ cbm_inventory_error_t read_error;
+ if (cni_read(reader, index, head, probe, &copied, c->control, &read_error) !=
+ CBM_INVENTORY_OK) {
+ return false; /* cni_read recorded the error in c */
+ }
+ budget->reads--;
+ budget->content_bytes -= file->content_length;
+ ledger->usage.verified_file_reads++;
+ ledger->usage.verified_content_bytes += file->content_length;
+ *out =
+ cbm_language_classify_with(config, name, head, copied, file->content_length > copied, true);
+ return true;
+}
+
+static bool cls_run(cni_context *c, const cbm_inventory_filter_view_t *view,
+ cbm_pinned_tree_t *tree, const cbm_userconfig_t *config, cls_budget_t *budget,
+ cbm_test_impact_ledger_t *ledger) {
+ cni_reader reader = {
+ .context = c, .tree = tree, .files = view->files, .file_count = view->file_count};
+ for (size_t i = 0; i < view->file_count; i++) {
+ const cbm_inventory_filter_row_t *row = &view->rows[i];
+ if (row->disposition != CBM_INVENTORY_FILTER_NEEDS_LANGUAGE) {
+ continue;
+ }
+ c->file_index = row->file_index;
+ if (row->file_index >= view->file_count || !cni_event(c)) {
+ return c->error.status != CBM_INVENTORY_OK ||
+ cls_fail(c, CBM_INVENTORY_STATE, "inventory row names no file");
+ }
+ CBMLanguage language = CBM_LANG_COUNT;
+ if (!cls_one(c, &reader, config, budget, ledger, row->file_index, &language)) {
+ return false;
+ }
+ ledger->rows[ledger->count++] =
+ (cbm_test_impact_classified_t){.file_index = row->file_index, .language = language};
+ }
+ c->file_index = SIZE_MAX;
+ return cni_poll(c);
+}
+
+cbm_inventory_status_t cbm_test_impact_classify(const cbm_test_impact_inventory_t *inventory,
+ cbm_pinned_tree_t *tree,
+ const cbm_userconfig_t *config,
+ const cbm_inventory_control_t *control,
+ cbm_test_impact_ledger_t **out,
+ cbm_inventory_error_t *error) {
+ cbm_inventory_error_t initial = {.status = CBM_INVENTORY_OK, .file_index = SIZE_MAX};
+ if (out) {
+ *out = NULL;
+ }
+ if (error) {
+ *error = initial;
+ }
+ cni_context c = {.control = control, .error = initial, .file_index = SIZE_MAX};
+ const cbm_inventory_filter_view_t *view = cbm_test_impact_inventory_view(inventory);
+ cls_budget_t budget = {0};
+ cbm_test_impact_ledger_t *ledger = NULL;
+ if (!out || !inventory || !tree || !control || !control->deadline_ms) {
+ cls_fail(&c, CBM_INVENTORY_INVALID, "invalid classification arguments");
+ } else if (!view) {
+ cls_fail(&c, CBM_INVENTORY_STATE, "inventory has no view");
+ } else if (cni_poll(&c) && cls_bound(&c, view, tree) && cls_budget(&c, inventory, &budget)) {
+ size_t survivors = cls_survivors(view);
+ size_t need = sizeof(*ledger) + survivors * sizeof(*ledger->rows);
+ if (survivors > (SIZE_MAX - sizeof(*ledger)) / sizeof(*ledger->rows) ||
+ need > budget.arena_bytes) {
+ cls_fail(&c, CBM_INVENTORY_LIMIT, "classified ledger exceeds the arena budget");
+ } else {
+ CBMArena arena;
+ cbm_arena_init_exact(&arena, need);
+ ledger = cbm_arena_calloc(&arena, sizeof(*ledger));
+ cbm_test_impact_classified_t *rows =
+ survivors ? cbm_arena_calloc(&arena, survivors * sizeof(*rows)) : NULL;
+ if (!ledger || (survivors && !rows)) {
+ cbm_arena_destroy(&arena);
+ ledger = NULL;
+ cls_fail(&c, CBM_INVENTORY_OOM, "classified ledger allocation failed");
+ } else {
+ ledger->arena = arena; /* the ledger lives in its own arena */
+ ledger->rows = rows;
+ ledger->usage.arena_requested_bytes = need;
+ memcpy(ledger->manifest, view->manifest_sha256, sizeof(ledger->manifest));
+ if (cls_run(&c, view, tree, config, &budget, ledger)) {
+ *out = ledger;
+ return CBM_INVENTORY_OK;
+ }
+ }
+ }
+ }
+ cbm_test_impact_ledger_free(ledger);
+ if (error) {
+ *error = c.error;
+ }
+ return c.error.status;
+}
+
+const cbm_test_impact_classified_t *cbm_test_impact_ledger_rows(
+ const cbm_test_impact_ledger_t *ledger, size_t *count) {
+ if (count) {
+ *count = ledger ? ledger->count : 0;
+ }
+ return ledger ? ledger->rows : NULL;
+}
+
+const unsigned char *cbm_test_impact_ledger_manifest(const cbm_test_impact_ledger_t *ledger) {
+ return ledger ? ledger->manifest : NULL;
+}
+
+bool cbm_test_impact_ledger_usage(const cbm_test_impact_ledger_t *ledger,
+ cbm_test_impact_classify_usage_t *out) {
+ if (!out) {
+ return false;
+ }
+ memset(out, 0, sizeof(*out));
+ if (!ledger) {
+ return false;
+ }
+ *out = ledger->usage;
+ return true;
+}
+
+void cbm_test_impact_ledger_free(cbm_test_impact_ledger_t *ledger) {
+ if (ledger) {
+ CBMArena arena = ledger->arena; /* ledger itself is inside it */
+ cbm_arena_destroy(&arena);
+ }
+}
+
+/* ── The runnable registry of the same snapshot ─────────────────── */
+
+/* The ledger languages the declarations cover. The model reads C-family
+ * conventions only; a declared language it does not support is reported by
+ * the model itself and keeps it from being complete. */
+static void reg_languages(const cbm_test_declarations_t *declarations, bool *wanted) {
+ static const struct {
+ const char *name;
+ CBMLanguage language;
+ } NAMES[] = {{"c", CBM_LANG_C}, {"C", CBM_LANG_C}, {"cpp", CBM_LANG_CPP},
+ {"c++", CBM_LANG_CPP}, {"C++", CBM_LANG_CPP}, {"cuda", CBM_LANG_CUDA},
+ {"CUDA", CBM_LANG_CUDA}};
+ bool c_cbm = false;
+ if (cbm_test_declarations_preset(declarations, CBM_TEST_PRESET_C_CBM, &c_cbm) && c_cbm) {
+ wanted[CBM_LANG_C] = true;
+ }
+ int count = 0;
+ const cbm_test_declaration_t *items = cbm_test_declarations_items(declarations, &count);
+ for (int i = 0; i < count; i++) {
+ for (size_t j = 0; items[i].language && j < sizeof(NAMES) / sizeof(NAMES[0]); j++) {
+ if (strcmp(items[i].language, NAMES[j].name) == 0) {
+ wanted[NAMES[j].language] = true;
+ }
+ }
+ }
+}
+
+/* The full verified blob of one ledger file into the model. */
+static bool reg_add(cni_context *c, cni_reader *reader, cls_budget_t *budget,
+ cbm_test_model_t *model, const cbm_test_impact_classified_t *row) {
+ const cbm_inventory_file_t *file = &reader->files[row->file_index];
+ if (budget->reads == 0 || file->content_length > budget->content_bytes ||
+ file->content_length > (uint64_t)SIZE_MAX) {
+ return cls_fail(c, CBM_INVENTORY_LIMIT, "test registry exceeds the read budget");
+ }
+ size_t len = (size_t)file->content_length;
+ char *text = cbm_alloc(CBM_MEM_CLASS_EXTRACT, len ? len : 1);
+ if (!text) {
+ return cls_fail(c, CBM_INVENTORY_OOM, "test registry source allocation failed");
+ }
+ size_t copied = 0;
+ reader->content_bound = budget->content_bytes;
+ cbm_inventory_error_t read_error;
+ bool ok = cni_read(reader, row->file_index, (unsigned char *)text, len, &copied, c->control,
+ &read_error) == CBM_INVENTORY_OK;
+ if (ok && copied != len) {
+ ok = cls_fail(c, CBM_INVENTORY_CHANGED, "test registry source length changed");
+ }
+ if (ok) {
+ budget->reads--;
+ budget->content_bytes -= file->content_length;
+ if (!cbm_test_model_add_source_language(model, (const char *)file->path.data,
+ cbm_language_name(row->language), text, len)) {
+ ok = cls_fail(c, CBM_INVENTORY_OOM, "test registry source was not accepted");
+ }
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, text);
+ return ok;
+}
+
+cbm_inventory_status_t cbm_test_impact_registry(
+ const cbm_test_impact_ledger_t *ledger, const cbm_test_impact_inventory_t *inventory,
+ cbm_pinned_tree_t *tree, const cbm_test_declarations_t *declarations,
+ const cbm_inventory_control_t *control, cbm_test_model_t **out, cbm_inventory_error_t *error) {
+ cbm_inventory_error_t initial = {.status = CBM_INVENTORY_OK, .file_index = SIZE_MAX};
+ if (out) {
+ *out = NULL;
+ }
+ if (error) {
+ *error = initial;
+ }
+ cni_context c = {.control = control, .error = initial, .file_index = SIZE_MAX};
+ const cbm_inventory_filter_view_t *view = cbm_test_impact_inventory_view(inventory);
+ cls_budget_t budget = {0};
+ cbm_test_model_t *model = NULL;
+ if (!out || !ledger || !inventory || !tree || !declarations || !control ||
+ !control->deadline_ms) {
+ cls_fail(&c, CBM_INVENTORY_INVALID, "invalid registry arguments");
+ } else if (!view) {
+ cls_fail(&c, CBM_INVENTORY_STATE, "inventory has no view");
+ } else if (memcmp(ledger->manifest, view->manifest_sha256, sizeof(ledger->manifest)) != 0) {
+ cls_fail(&c, CBM_INVENTORY_CHANGED, "ledger is not the inventory's snapshot");
+ } else if (cni_poll(&c) && cls_bound(&c, view, tree) && cls_budget(&c, inventory, &budget)) {
+ /* What the ledger already read is spent. */
+ budget.reads -= budget.reads < ledger->usage.verified_file_reads
+ ? budget.reads
+ : ledger->usage.verified_file_reads;
+ budget.content_bytes -= budget.content_bytes < ledger->usage.verified_content_bytes
+ ? budget.content_bytes
+ : ledger->usage.verified_content_bytes;
+ model = cbm_test_model_new_declarations(declarations);
+ if (!model) {
+ cls_fail(&c, CBM_INVENTORY_OOM, "test registry could not start");
+ } else {
+ bool wanted[CBM_LANG_COUNT + 1] = {false};
+ reg_languages(declarations, wanted);
+ cni_reader reader = {
+ .context = &c, .tree = tree, .files = view->files, .file_count = view->file_count};
+ bool ok = true;
+ for (size_t i = 0; ok && i < ledger->count; i++) {
+ const cbm_test_impact_classified_t *row = &ledger->rows[i];
+ c.file_index = row->file_index;
+ if (row->language < 0 || row->language >= CBM_LANG_COUNT ||
+ !wanted[row->language]) {
+ continue;
+ }
+ ok = cni_event(&c) && reg_add(&c, &reader, &budget, model, row);
+ }
+ c.file_index = SIZE_MAX;
+ if (ok && !cbm_test_model_finish(model)) {
+ ok = cls_fail(&c, CBM_INVENTORY_OOM, "test registry could not finish");
+ }
+ if (ok && cni_poll(&c)) {
+ *out = model;
+ return CBM_INVENTORY_OK;
+ }
+ }
+ }
+ cbm_test_model_free(model);
+ if (error) {
+ *error = c.error;
+ }
+ return c.error.status;
+}
diff --git a/src/mcp/test_impact_classify.h b/src/mcp/test_impact_classify.h
new file mode 100644
index 000000000..198f5dd67
--- /dev/null
+++ b/src/mcp/test_impact_classify.h
@@ -0,0 +1,80 @@
+/*
+ * test_impact_classify.h — the classified ledger of a pinned HEAD inventory.
+ *
+ * The inventory filter leaves every file it keeps as "needs language". This
+ * pass gives each of them the language discovery gives the same file: the
+ * shared rule of cbm_language_classify, applied to the base name and, where
+ * the name is not enough, to the first bytes of the verified git blob. What
+ * the ledger holds is what a frozen build indexes and what the reconciliation
+ * compares against.
+ *
+ * A blob that cannot be read is an error of the whole pass, never a default
+ * language: a ledger that quietly classified a file as something else would
+ * index a different graph than the one the selection claims to use.
+ */
+#ifndef CBM_TEST_IMPACT_CLASSIFY_H
+#define CBM_TEST_IMPACT_CLASSIFY_H
+
+#include "discover/test_conventions.h"
+#include "discover/userconfig.h"
+#include "mcp/test_impact.h"
+#include "mcp/test_impact_inventory.h"
+#include "mcp/test_impact_tree.h"
+
+typedef struct {
+ size_t file_index; /* index in the pinned tree and the inventory view */
+ CBMLanguage language; /* CBM_LANG_COUNT: no supported language, not indexed */
+} cbm_test_impact_classified_t;
+
+typedef struct {
+ uint64_t verified_file_reads; /* blobs read by this pass */
+ uint64_t verified_content_bytes; /* their full lengths: each read verifies the whole blob */
+ size_t arena_requested_bytes; /* the ledger's own memory */
+} cbm_test_impact_classify_usage_t;
+
+typedef struct cbm_test_impact_ledger cbm_test_impact_ledger_t;
+
+/* Classify every "needs language" survivor of `inventory`, reading from
+ * `tree`, the READY pinned tree the inventory was prepared from, under the
+ * snapshot's language config `config` (NULL: no user overrides). Reads,
+ * content bytes and ledger memory are charged to what the inventory's limits
+ * leave after the filter; a probe longer than max_probe_prefix_bytes is a
+ * LIMIT. Clears *out and initializes *error first. On failure *out stays
+ * NULL; a started failed read may leave the tree disposal-only, exactly as
+ * for the filter's own reads. */
+cbm_inventory_status_t cbm_test_impact_classify(const cbm_test_impact_inventory_t *inventory,
+ cbm_pinned_tree_t *tree,
+ const cbm_userconfig_t *config,
+ const cbm_inventory_control_t *control,
+ cbm_test_impact_ledger_t **out,
+ cbm_inventory_error_t *error);
+
+/* Rows in file-index order, one per survivor. Borrowed until the ledger is
+ * freed. */
+const cbm_test_impact_classified_t *cbm_test_impact_ledger_rows(
+ const cbm_test_impact_ledger_t *ledger, size_t *count);
+
+/* The manifest the inventory was bound to, so a consumer can check that the
+ * ledger and a tree describe the same snapshot. */
+const unsigned char *cbm_test_impact_ledger_manifest(const cbm_test_impact_ledger_t *ledger);
+
+bool cbm_test_impact_ledger_usage(const cbm_test_impact_ledger_t *ledger,
+ cbm_test_impact_classify_usage_t *out);
+
+void cbm_test_impact_ledger_free(cbm_test_impact_ledger_t *ledger);
+
+/* The runnable test registry of the same snapshot: the finished test model
+ * (mcp/test_impact.h) built under `declarations` (the snapshot's config, as
+ * the frozen build was given it) from the full verified blobs of every ledger
+ * file in a language those declarations cover (C for the c-cbm preset). More
+ * files rather than fewer: no path filter narrows what is scanned. Blob reads
+ * are charged to what the inventory's limits leave after the filter and the
+ * ledger; a read that fails or does not fit is an error, never a smaller
+ * registry. The model may still report mapping uncertainty: callers must
+ * require cbm_test_model_complete() before narrowing anything with it. */
+cbm_inventory_status_t cbm_test_impact_registry(
+ const cbm_test_impact_ledger_t *ledger, const cbm_test_impact_inventory_t *inventory,
+ cbm_pinned_tree_t *tree, const cbm_test_declarations_t *declarations,
+ const cbm_inventory_control_t *control, cbm_test_model_t **out, cbm_inventory_error_t *error);
+
+#endif /* CBM_TEST_IMPACT_CLASSIFY_H */
diff --git a/src/mcp/test_impact_coverage.c b/src/mcp/test_impact_coverage.c
index 7ba7bf60d..aa76eae50 100644
--- a/src/mcp/test_impact_coverage.c
+++ b/src/mcp/test_impact_coverage.c
@@ -482,9 +482,8 @@ static cv_meta_suite_t *cv_meta_find_suite(cv_meta_suite_t *suites, int count, c
bool cbm_coverage_map_metadata_matches(const cbm_coverage_map_t *map, const char *metadata,
size_t len, const char *expected_commit) {
- if (!map || map->format != CBM_COVERAGE_FORMAT_FUNCTIONS || !metadata ||
- len == SIZE_MAX || !cv_meta_commit(expected_commit) ||
- memchr(metadata, '\0', len)) {
+ if (!map || map->format != CBM_COVERAGE_FORMAT_FUNCTIONS || !metadata || len == SIZE_MAX ||
+ !cv_meta_commit(expected_commit) || memchr(metadata, '\0', len)) {
return false;
}
yyjson_doc *doc = yyjson_read(metadata, len, 0);
@@ -747,8 +746,8 @@ static char *cv2_string(cv2_context_t *ctx, cv2_span_t span) {
return text;
}
-static bool cv2_line(cv2_context_t *ctx, cv2_span_t input, size_t *position,
- bool test_row, cv2_span_t *line) {
+static bool cv2_line(cv2_context_t *ctx, cv2_span_t input, size_t *position, bool test_row,
+ cv2_span_t *line) {
size_t start = *position;
while (*position < input.length) {
if (!cv2_step(ctx))
@@ -786,8 +785,8 @@ static bool cv2_fields(cv2_context_t *ctx, cv2_span_t line, cv2_span_t fields[4]
return true;
}
-static bool cv2_row(cv2_context_t *ctx, cv2_span_t input, size_t *position,
- bool test_row, cv2_span_t fields[4]) {
+static bool cv2_row(cv2_context_t *ctx, cv2_span_t input, size_t *position, bool test_row,
+ cv2_span_t fields[4]) {
cv2_span_t line;
return cv2_line(ctx, input, position, test_row, &line) && cv2_fields(ctx, line, fields);
}
@@ -796,8 +795,7 @@ static bool cv2_literal(cv2_span_t span, const char *literal, size_t length) {
return span.length == length && memcmp(span.data, literal, length) == 0;
}
-static bool cv2_decimal(cv2_context_t *ctx, cv2_span_t span, bool canonical,
- uint64_t *out) {
+static bool cv2_decimal(cv2_context_t *ctx, cv2_span_t span, bool canonical, uint64_t *out) {
if (!span.length || (canonical && span.length > 1 && span.data[0] == '0'))
return cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
uint64_t value = 0;
@@ -885,7 +883,9 @@ static bool cv2_profile_inventory(cv2_context_t *ctx, cv2_span_t profiles) {
if (!cv2_items(ctx, 1))
return false;
}
- return count == ctx->profile_count || cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ if (count != ctx->profile_count)
+ return cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ return true;
}
static bool cv2_id_count(cv2_context_t *ctx, cv2_span_t span, int *out) {
@@ -971,8 +971,8 @@ static bool cv2_profile_compare(cv2_context_t *ctx, const cbm_coverage_profile_t
*out = left->name_length < right->name_length ? -1 : 1;
return true;
}
- *out = (left->function_hash > right->function_hash) -
- (left->function_hash < right->function_hash);
+ *out =
+ (left->function_hash > right->function_hash) - (left->function_hash < right->function_hash);
return true;
}
@@ -1010,7 +1010,9 @@ static bool cv2_profiles(cv2_context_t *ctx, cv2_span_t profiles) {
!cv2_profile(ctx, fields, i))
return false;
}
- return position == profiles.length || cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ if (position != profiles.length)
+ return cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ return true;
}
static bool cv2_test_name(cv2_context_t *ctx, cv2_span_t field, cbm_coverage_test_t *row) {
@@ -1078,7 +1080,9 @@ static bool cv2_tests(cv2_context_t *ctx, cv2_span_t tests) {
!cv2_test_ids(ctx, fields[3], row))
return false;
}
- return position == tests.length || cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ if (position != tests.length)
+ return cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ return true;
}
static bool cv2_string_compare(cv2_context_t *ctx, const char *a, const char *b, int *out) {
@@ -1173,7 +1177,9 @@ static bool cv2_validate_tests(cv2_context_t *ctx) {
if (row->name[0] == '*' && row->name[1] == '\0')
setup = true;
}
- return !ctx->test_count || setup || cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ if (ctx->test_count && !setup)
+ return cv2_fail(ctx, CBM_COVERAGE_PARSE_FORMAT);
+ return true;
}
static bool cv2_hash(cv2_context_t *ctx, cv2_span_t span, char hex[CBM_SHA256_HEX_LEN + 1]) {
@@ -1203,8 +1209,8 @@ static bool cv2_hash(cv2_context_t *ctx, cv2_span_t span, char hex[CBM_SHA256_HE
}
static cbm_coverage_parse_status_t cv2_arguments(const void *profiles, size_t profiles_len,
- const char *tests, size_t tests_len,
- const cbm_coverage_parse_limits_t *limits) {
+ const char *tests, size_t tests_len,
+ const cbm_coverage_parse_limits_t *limits) {
if (!profiles || (!tests && tests_len) || !limits)
return CBM_COVERAGE_PARSE_INVALID;
if (!limits->max_input_bytes || limits->max_input_bytes > UINT64_MAX / 8 ||
@@ -1221,18 +1227,23 @@ static cbm_coverage_parse_status_t cv2_arguments(const void *profiles, size_t pr
return CBM_COVERAGE_PARSE_OK;
}
-cbm_coverage_parse_status_t cbm_coverage_map_parse_v2(
- const void *profiles, size_t profiles_len, const char *tests, size_t tests_len,
- const cbm_coverage_parse_limits_t *limits, cbm_coverage_parse_cancel_fn cancelled,
- void *cancel_context, cbm_coverage_map_t **out) {
+cbm_coverage_parse_status_t cbm_coverage_map_parse_v2(const void *profiles, size_t profiles_len,
+ const char *tests, size_t tests_len,
+ const cbm_coverage_parse_limits_t *limits,
+ cbm_coverage_parse_cancel_fn cancelled,
+ void *cancel_context,
+ cbm_coverage_map_t **out) {
if (!out)
return CBM_COVERAGE_PARSE_INVALID;
*out = NULL;
- cbm_coverage_parse_status_t status = cv2_arguments(profiles, profiles_len, tests, tests_len, limits);
+ cbm_coverage_parse_status_t status =
+ cv2_arguments(profiles, profiles_len, tests, tests_len, limits);
if (status != CBM_COVERAGE_PARSE_OK)
return status;
- cv2_context_t ctx = {.limits = limits, .cancelled = cancelled,
- .cancel_context = cancel_context, .status = CBM_COVERAGE_PARSE_OK};
+ cv2_context_t ctx = {.limits = limits,
+ .cancelled = cancelled,
+ .cancel_context = cancel_context,
+ .status = CBM_COVERAGE_PARSE_OK};
cbm_arena_init_lazy(&ctx.arena, 4096);
cv2_span_t profile_span = {profiles, profiles_len};
cv2_span_t test_span = {(const unsigned char *)tests, tests_len};
@@ -1264,7 +1275,8 @@ const char *cbm_coverage_map_identity_sha256(const cbm_coverage_map_t *map) {
return map ? map->functions_sha256 : NULL;
}
-const cbm_coverage_profile_binding_t *cbm_coverage_map_profile_binding(const cbm_coverage_map_t *map) {
+const cbm_coverage_profile_binding_t *cbm_coverage_map_profile_binding(
+ const cbm_coverage_map_t *map) {
return map && map->format == CBM_COVERAGE_FORMAT_PROFILES ? &map->profile_binding : NULL;
}
diff --git a/src/mcp/test_impact_engine.c b/src/mcp/test_impact_engine.c
new file mode 100644
index 000000000..39aece400
--- /dev/null
+++ b/src/mcp/test_impact_engine.c
@@ -0,0 +1,650 @@
+/*
+ * test_impact_engine.c — detect_changes scope:"tests", end to end: git, the
+ * merge base's rules, classification of every changed path, the HEAD
+ * snapshot, seeding, the walk, the selection and the answer.
+ */
+#include "mcp/test_impact_engine_internal.h"
+
+#include "foundation/compat.h"
+#include "foundation/compat_fs.h"
+#include "foundation/compat_thread.h"
+#include "foundation/mem_core.h"
+#include "foundation/platform.h"
+#include "foundation/sha256.h"
+#include "store/store_graph_digest.h"
+#include "store/store_impact.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+
+/* ── Shared helpers ──────────────────────────────────────────────── */
+
+bool te_grow(void **items, int *cap, int count, size_t size) {
+ if (count < *cap) {
+ return true;
+ }
+ int next = *cap ? *cap * 2 : 16;
+ void *grown = cbm_realloc(CBM_MEM_CLASS_EXTRACT, *items, (size_t)next * size);
+ if (!grown) {
+ return false;
+ }
+ *items = grown;
+ *cap = next;
+ return true;
+}
+
+bool te_oom(te_ctx_t *c) {
+ c->oom = true;
+ return false;
+}
+
+static void te_note(te_ctx_t *c, const char *text) {
+ if (c->diagnostic && c->diagnostic_len && !c->diagnostic[0] && text) {
+ snprintf(c->diagnostic, c->diagnostic_len, "%s", text);
+ }
+}
+
+bool te_fallback(te_ctx_t *c, cbm_test_result_fallback_t code, const char *diagnostic) {
+ te_note(c, diagnostic);
+ for (int i = 0; i < c->fallback_count; i++) {
+ if (c->fallbacks[i] == code) {
+ return true;
+ }
+ }
+ if (!te_grow((void **)&c->fallbacks, &c->fallback_cap, c->fallback_count,
+ sizeof(*c->fallbacks))) {
+ return te_oom(c);
+ }
+ c->fallbacks[c->fallback_count++] = code;
+ return true;
+}
+
+/* ── git ─────────────────────────────────────────────────────────── */
+
+bool cbm_test_impact_find_git(char *out, size_t out_len) {
+ const char *path = getenv("PATH");
+#ifdef _WIN32
+ const char sep = ';';
+ const char *exe = "git.exe";
+#else
+ const char sep = ':';
+ const char *exe = "git";
+#endif
+ if (!path || !out || out_len == 0) {
+ return false;
+ }
+ const char *p = path;
+ while (*p) {
+ const char *e = strchr(p, sep);
+ size_t len = e ? (size_t)(e - p) : strlen(p);
+ bool absolute = len > 0 && (p[0] == '/' || (len > 2 && p[1] == ':'));
+ if (absolute && len + 1 + strlen(exe) < out_len) {
+ snprintf(out, out_len, "%.*s/%s", (int)len, p, exe);
+ struct stat st;
+ if (stat(out, &st) == 0 && S_ISREG(st.st_mode)
+#ifndef _WIN32
+ && access(out, X_OK) == 0
+#endif
+ ) {
+ return true;
+ }
+ }
+ if (!e) {
+ break;
+ }
+ p = e + 1;
+ }
+ out[0] = '\0';
+ return false;
+}
+
+static bool te_git(te_ctx_t *c) {
+ char git[4096];
+ if (!cbm_test_impact_find_git(git, sizeof(git))) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GIT_UNAVAILABLE, "no git on PATH") && false;
+ }
+ cbm_git_facts_options_t options = {.root = c->rq->repo_root,
+ .base_ref = c->rq->base_ref,
+ .git_executable = git,
+ .deadline_ms = c->rq->deadline_ms,
+ .command_limit = 4096,
+ .stdout_limit = (size_t)512 << 20,
+ .stderr_limit = 65536,
+ .total_output_limit = (size_t)2048 << 20};
+ cbm_git_facts_error_t error;
+ c->facts = cbm_git_facts_open(&options, &error);
+ if (!c->facts || !cbm_git_facts_diff(c->facts, &c->diff, &error)) {
+ char text[700];
+ snprintf(text, sizeof(text), "git: %s", error.diagnostic);
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GIT_UNAVAILABLE, text) && false;
+ }
+ c->id = cbm_git_facts_identity(c->facts);
+ cbm_changes_status_t status =
+ cbm_changes_parse(c->diff.name_status.data, c->diff.name_status.length, c->diff.patch.data,
+ c->diff.patch.length, &c->changes);
+ if (status == CBM_CHANGES_OOM) {
+ return te_oom(c);
+ }
+ cbm_changes_state_t state = cbm_changes_state(c->changes);
+ c->diff_complete = status == CBM_CHANGES_OK && state != CBM_CHANGES_UNKNOWN &&
+ cbm_changes_patch_reconciled(c->changes);
+ c->has_changes = state != CBM_CHANGES_EMPTY;
+ return true;
+}
+
+/* ── Query-time configuration: the merge base's (M-4) ────────────── */
+
+static bool te_config(te_ctx_t *c) {
+ const char *path = c->rq->config_path;
+ char file[4200] = "";
+ bool optional = false;
+ if (!path) {
+ snprintf(file, sizeof(file), "%s/merge-base-config.json", c->work_dir);
+ path = file;
+ optional = true;
+ cbm_git_blob_t blob;
+ cbm_git_facts_error_t error;
+ static const char name[] = ".codebase-memory.json";
+ cbm_git_blob_status_t found = cbm_git_facts_read_blob(
+ c->facts, CBM_GIT_REV_MERGE_BASE, name, sizeof(name) - 1, &blob, &error);
+ if (found == CBM_GIT_BLOB_ERROR) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_CONFIG_INVALID,
+ "the merge base's .codebase-memory.json could not be read") &&
+ false;
+ }
+ if (found == CBM_GIT_BLOB_FOUND) {
+ FILE *f = cbm_fopen(file, "wb");
+ bool ok = f && fwrite(blob.bytes.data, 1, blob.bytes.length, f) == blob.bytes.length;
+ if (f) {
+ ok = fclose(f) == 0 && ok;
+ }
+ if (!ok) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_CONFIG_INVALID,
+ "the merge base's configuration could not be staged") &&
+ false;
+ }
+ }
+ }
+ c->config = cbm_test_config_load(path, optional);
+ if (optional) {
+ (void)cbm_unlink(file); /* only the merge-base copy staged above */
+ }
+ if (!c->config) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_CONFIG_INVALID,
+ "the test_impact configuration is invalid") &&
+ false;
+ }
+ c->policy = cbm_test_policy_new(c->config);
+ if (!c->policy) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_POLICY_UNAVAILABLE,
+ "the test_impact rules are invalid") &&
+ false;
+ }
+ return true;
+}
+
+/* ── Classification of the changed paths ─────────────────────────── */
+
+static bool te_match(te_ctx_t *c, int rule_index) {
+ for (int i = 0; i < c->match_count; i++) {
+ if (c->matches[i].rule_index == rule_index) {
+ return true;
+ }
+ }
+ if (!te_grow((void **)&c->matches, &c->match_cap, c->match_count, sizeof(*c->matches))) {
+ return te_oom(c);
+ }
+ c->matches[c->match_count++] = (te_match_t){.rule_index = rule_index, .resolved = true};
+ return true;
+}
+
+static bool te_fixture_path(te_ctx_t *c, const char *path, int rule_index) {
+ if (!te_grow((void **)&c->fixture_paths, &c->fixture_cap, c->fixture_count,
+ sizeof(*c->fixture_paths)) ||
+ !te_grow((void **)&c->fixture_rules, &c->fixture_rule_cap, c->fixture_count,
+ sizeof(*c->fixture_rules))) {
+ return te_oom(c);
+ }
+ c->fixture_paths[c->fixture_count] = path;
+ c->fixture_rules[c->fixture_count++] = rule_index;
+ return true;
+}
+
+static bool te_c_family(const char *path) {
+ static const char *const ext[] = {".c", ".h", ".cc", ".cpp", ".hpp",
+ ".m", ".mm", ".cxx", ".hh"};
+ size_t n = strlen(path);
+ for (size_t i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
+ size_t e = strlen(ext[i]);
+ if (n > e && strcmp(path + n - e, ext[i]) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* First pass: the rules. A path no rule matches is decided after the
+ * snapshot (te_classify_unmatched). Returns whether the snapshot is needed:
+ * a run-all rule decides everything without it. */
+static bool te_classify_rules(te_ctx_t *c, bool *need_snapshot, bool **unmatched) {
+ size_t count = 0;
+ const cbm_change_file_t *files = cbm_changes_files(c->changes, &count);
+ int rule_count = 0;
+ const cbm_test_rule_t *rules = cbm_test_policy_rules(c->policy, &rule_count);
+ *unmatched = cbm_arena_calloc(&c->arena, count + 1);
+ if (!*unmatched) {
+ return te_oom(c);
+ }
+ bool run_all = false;
+ c->activation_complete = true;
+ for (size_t i = 0; i < count; i++) {
+ const char *path = (const char *)files[i].path;
+ const cbm_test_rule_t *rule = NULL;
+ if (!cbm_test_policy_match_path(c->policy, path, &rule)) {
+ c->activation_complete = false;
+ if (!te_fallback(c, CBM_TEST_RESULT_FALLBACK_POLICY_EVALUATION_FAILED, path)) {
+ return false;
+ }
+ continue;
+ }
+ if (!rule) {
+ (*unmatched)[i] = true;
+ continue;
+ }
+ int index = (int)(rule - rules);
+ if (!te_match(c, index)) {
+ return false;
+ }
+ run_all = run_all || rule->action == CBM_TEST_RULE_RUN_ALL;
+ if (rule->action == CBM_TEST_RULE_REFERENCING_TESTS && !te_fixture_path(c, path, index)) {
+ return false;
+ }
+ }
+ *need_snapshot = !run_all && c->fallback_count == 0;
+ return true;
+}
+
+static bool te_in_ledger(te_ctx_t *c, const char *path) {
+ const cbm_pinned_tree_view_t *view = cbm_pinned_tree_view(c->tree);
+ size_t n = 0;
+ const cbm_test_impact_classified_t *rows = cbm_test_impact_ledger_rows(c->ledger, &n);
+ size_t lo = 0;
+ size_t hi = n;
+ /* Ledger rows follow the tree's raw-path order. */
+ while (lo < hi) {
+ size_t mid = lo + (hi - lo) / 2;
+ int cmp = strcmp((const char *)view->files[rows[mid].file_index].path, path);
+ if (cmp == 0) {
+ return true;
+ }
+ if (cmp < 0) {
+ lo = mid + 1;
+ } else {
+ hi = mid;
+ }
+ }
+ return false;
+}
+
+static bool te_add_seed_change(te_ctx_t *c, const cbm_change_file_t *f) {
+ if (!te_grow((void **)&c->seed_changes, &c->seed_change_cap, c->seed_change_count,
+ sizeof(*c->seed_changes))) {
+ return te_oom(c);
+ }
+ cbm_ti_change_t change = {.path = (const char *)f->path};
+ if (f->status == 'D') {
+ change.deleted = true;
+ cbm_git_blob_t blob;
+ cbm_git_facts_error_t error;
+ cbm_git_blob_status_t found = cbm_git_facts_read_blob(
+ c->facts, CBM_GIT_REV_MERGE_BASE, (const char *)f->path, f->path_length, &blob, &error);
+ if (found != CBM_GIT_BLOB_FOUND) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GIT_UNAVAILABLE,
+ "a deleted file's base text could not be read");
+ }
+ change.base_text = (const char *)blob.bytes.data;
+ change.base_len = blob.bytes.length;
+ } else if (f->evidence == CBM_CHANGE_HUNKS && f->patch_file) {
+ change.hunks = f->patch_file->hunks;
+ change.hunk_count = f->patch_file->hunk_count;
+ } else {
+ change.whole_file = true;
+ }
+ c->seed_changes[c->seed_change_count++] = change;
+ return true;
+}
+
+/* Second pass: a path no rule matched is read through the graph when it is
+ * a C-family source of the snapshot (or deleted from it); anything else is a
+ * change the test-runner lane cannot reason about (M-10): run everything. */
+static bool te_classify_unmatched(te_ctx_t *c, const bool *unmatched) {
+ size_t count = 0;
+ const cbm_change_file_t *files = cbm_changes_files(c->changes, &count);
+ for (size_t i = 0; i < count; i++) {
+ if (!unmatched[i]) {
+ continue;
+ }
+ const char *path = (const char *)files[i].path;
+ bool readable = te_c_family(path) && (files[i].status == 'D' || te_in_ledger(c, path));
+ bool ok = readable ? te_add_seed_change(c, &files[i])
+ : te_fallback(c, CBM_TEST_RESULT_FALLBACK_UNMAPPED_FILE, path);
+ if (!ok) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* ── Graph scope, seeding, selection ─────────────────────────────── */
+
+static bool te_open_scope(te_ctx_t *c) {
+ if (cbm_store_read_scope_open(c->store, NULL, NULL, &c->scope) != CBM_STORE_OK) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "the graph of HEAD could not be read") &&
+ false;
+ }
+ static const unsigned char project[] = "test-impact";
+ cbm_store_graph_digest_limits_t limits = {.max_rows = (uint64_t)1 << 32,
+ .max_framed_bytes = (uint64_t)1 << 40};
+ cbm_store_graph_digest_t digest;
+ if (cbm_store_graph_digest(c->scope, project, sizeof(project) - 1, &limits, &digest) !=
+ CBM_STORE_GRAPH_DIGEST_OK) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_REJECTED,
+ "the graph of HEAD could not be digested") &&
+ false;
+ }
+ memcpy(c->graph_sha256, digest.sha256, sizeof(c->graph_sha256));
+ c->graph_digest = true;
+ return true;
+}
+
+static bool te_seed(te_ctx_t *c) {
+ cbm_ti_seed_input_t in = {.changes = c->seed_changes,
+ .change_count = c->seed_change_count,
+ .model = c->model,
+ .graph = c->graph,
+ .source = c->source};
+ cbm_ti_seed_status_t status = cbm_ti_seed(&in, &c->seeds);
+ if (status == CBM_TI_SEED_OOM) {
+ return te_oom(c);
+ }
+ if (status != CBM_TI_SEED_OK) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "seeding the graph failed") &&
+ false;
+ }
+ return true;
+}
+
+static bool te_select(te_ctx_t *c) {
+ cbm_test_selection_input_t input = {.model = c->model,
+ .reach = c->reach,
+ .reach_count = c->reach_count,
+ .suite_triggers = c->triggers,
+ .suite_trigger_count = c->trigger_count,
+ .has_changes = c->has_changes,
+ .diff_complete = c->diff_complete,
+ .inventory_complete = c->snapshot_ok,
+ .static_complete = c->static_complete,
+ .coverage_admitted = false};
+ c->selection = cbm_test_select(&input);
+ if (!c->selection) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_SELECTION_UNAVAILABLE,
+ "the selection could not be computed");
+ }
+ return true;
+}
+
+/* ── The answer ──────────────────────────────────────────────────── */
+
+static bool te_hex_bytes(const char *hex, unsigned char *out, size_t count) {
+ if (!hex || strlen(hex) != count * 2) {
+ return false;
+ }
+ for (size_t i = 0; i < count; i++) {
+ unsigned v = 0;
+ for (int k = 0; k < 2; k++) {
+ char ch = hex[i * 2 + (size_t)k];
+ unsigned d = ch >= '0' && ch <= '9' ? (unsigned)(ch - '0')
+ : ch >= 'a' && ch <= 'f' ? (unsigned)(ch - 'a' + 10)
+ : ch >= 'A' && ch <= 'F' ? (unsigned)(ch - 'A' + 10)
+ : 16U;
+ if (d > 15) {
+ return false;
+ }
+ v = v * 16 + d;
+ }
+ out[i] = (unsigned char)v;
+ }
+ return true;
+}
+
+static cbm_test_result_oid_t te_oid(const te_ctx_t *c, const char *hex) {
+ cbm_test_result_oid_t oid = {0};
+ if (!c->id || !hex || !hex[0]) {
+ return oid;
+ }
+ size_t bytes = c->id->oid_hex_length == 64 ? 32 : 20;
+ if (te_hex_bytes(hex, oid.bytes, bytes)) {
+ oid.format = bytes == 32 ? CBM_TEST_RESULT_OBJECT_SHA256 : CBM_TEST_RESULT_OBJECT_SHA1;
+ } else {
+ memset(oid.bytes, 0, sizeof(oid.bytes));
+ }
+ return oid;
+}
+
+static cbm_test_result_digest_t te_digest_hex(const char *hex) {
+ cbm_test_result_digest_t d = {0};
+ d.present = te_hex_bytes(hex, d.bytes, 32);
+ if (!d.present) {
+ memset(d.bytes, 0, sizeof(d.bytes));
+ }
+ return d;
+}
+
+static cbm_test_result_digest_t te_digest_of(const cbm_git_bytes_t *b) {
+ cbm_test_result_digest_t d = {.present = true};
+ cbm_sha256_ctx ctx;
+ cbm_sha256_init(&ctx);
+ cbm_sha256_update(&ctx, b->data ? b->data : (const unsigned char *)"", b->length);
+ cbm_sha256_final(&ctx, d.bytes);
+ return d;
+}
+
+static void te_receipt(te_ctx_t *c, cbm_test_result_receipt_t *r,
+ cbm_test_result_evidence_reason_t *graph_reason) {
+ memset(r, 0, sizeof(*r));
+ r->routes = CBM_TEST_RESULT_ROUTES_FOLLOWED;
+ if (c->id) {
+ r->object_format = c->id->oid_hex_length == 64 ? CBM_TEST_RESULT_OBJECT_SHA256
+ : CBM_TEST_RESULT_OBJECT_SHA1;
+ r->base = te_oid(c, c->id->base);
+ r->head = te_oid(c, c->id->head);
+ r->merge_base = te_oid(c, c->id->merge_base);
+ }
+ if (c->changes) {
+ r->diff_sha256 = te_digest_of(&c->diff.patch);
+ r->name_status_sha256 = te_digest_of(&c->diff.name_status);
+ }
+ if (c->config) {
+ r->config_sha256 = te_digest_hex(cbm_test_config_digest(c->config));
+ }
+ if (c->policy) {
+ r->policy_sha256 = te_digest_hex(cbm_test_policy_digest(c->policy));
+ }
+ if (c->graph_digest) {
+ r->graph.state = CBM_TEST_RESULT_GRAPH_CERTIFIED;
+ r->graph.commit = r->head;
+ r->graph.sha256.present = true;
+ memcpy(r->graph.sha256.bytes, c->graph_sha256, 32);
+ } else if (c->tree) {
+ r->graph.state = CBM_TEST_RESULT_GRAPH_REJECTED;
+ *graph_reason = CBM_TEST_RESULT_EVIDENCE_DIAGNOSTICS_INCOMPLETE;
+ r->graph.rejection_reasons = (cbm_test_result_evidence_reasons_t){graph_reason, 1};
+ }
+ r->coverage.state = CBM_TEST_RESULT_COVERAGE_UNAVAILABLE;
+}
+
+static cbm_test_impact_status_t te_answer(te_ctx_t *c, cbm_test_result_t **out) {
+ cbm_test_result_rule_match_t *matches =
+ cbm_arena_calloc(&c->arena, (size_t)(c->match_count + 1) * sizeof(*matches));
+ if (!matches) {
+ return CBM_TEST_IMPACT_OOM;
+ }
+ for (int i = 0; i < c->match_count; i++) {
+ matches[i] = (cbm_test_result_rule_match_t){.rule_index = c->matches[i].rule_index,
+ .target_resolved = c->matches[i].resolved};
+ }
+ cbm_test_result_receipt_t receipt;
+ cbm_test_result_evidence_reason_t graph_reason = CBM_TEST_RESULT_EVIDENCE_PROVIDER_UNAVAILABLE;
+ te_receipt(c, &receipt, &graph_reason);
+ cbm_test_result_comparison_t comparison = !c->changes || !c->diff_complete
+ ? CBM_TEST_RESULT_COMPARISON_UNAVAILABLE
+ : c->has_changes ? CBM_TEST_RESULT_COMPARISON_CHANGED
+ : CBM_TEST_RESULT_COMPARISON_EMPTY;
+ if (comparison == CBM_TEST_RESULT_COMPARISON_UNAVAILABLE && c->fallback_count == 0 &&
+ !te_fallback(c, CBM_TEST_RESULT_FALLBACK_GIT_UNAVAILABLE, "the change is not complete")) {
+ return CBM_TEST_IMPACT_OOM;
+ }
+ bool with_selection = c->selection && comparison == CBM_TEST_RESULT_COMPARISON_CHANGED;
+ cbm_test_result_input_t input = {
+ .comparison = comparison,
+ .selection = with_selection ? c->selection : NULL,
+ .model = with_selection ? c->model : NULL,
+ .policy = comparison == CBM_TEST_RESULT_COMPARISON_EMPTY ? NULL : c->policy,
+ .inventory_complete = c->snapshot_ok,
+ .activation_complete = c->activation_complete,
+ .matched_rules = comparison == CBM_TEST_RESULT_COMPARISON_EMPTY ? NULL : matches,
+ .matched_rule_count =
+ comparison == CBM_TEST_RESULT_COMPARISON_EMPTY ? 0 : (size_t)c->match_count,
+ .fallbacks = c->fallbacks,
+ .fallback_count = (size_t)c->fallback_count,
+ .warnings = c->warnings,
+ .warning_count = (size_t)c->warning_count,
+ .receipt = &receipt};
+ cbm_test_result_limits_t limits = {.max_input_bytes = (uint64_t)1 << 30,
+ .max_items = (uint64_t)1 << 26,
+ .max_alloc_bytes = (size_t)1 << 30,
+ .max_output_bytes = (size_t)256 << 20};
+ cbm_test_result_status_t status = cbm_test_result_build(&input, &limits, NULL, NULL, out);
+ if (status == CBM_TEST_RESULT_OOM) {
+ return CBM_TEST_IMPACT_OOM;
+ }
+ if (status != CBM_TEST_RESULT_OK) {
+ char text[64];
+ snprintf(text, sizeof(text), "result codec status %d", (int)status);
+ te_note(c, text);
+ return CBM_TEST_IMPACT_INVALID;
+ }
+ return CBM_TEST_IMPACT_OK;
+}
+
+/* ── The request ─────────────────────────────────────────────────── */
+
+static void te_free(te_ctx_t *c) {
+ cbm_test_selection_free(c->selection);
+ cbm_ti_seeds_free(c->seeds);
+ if (c->scope) {
+ (void)cbm_store_read_scope_close(c->scope);
+ }
+ te_snapshot_free(c);
+ cbm_test_policy_free(c->policy);
+ cbm_test_config_free(c->config);
+ cbm_changes_free(c->changes);
+ cbm_git_facts_free(c->facts);
+ void *arrays[] = {c->matches, c->fallbacks, c->warnings, c->seed_changes,
+ c->fixture_paths, c->fixture_rules, c->triggers};
+ for (size_t i = 0; i < sizeof(arrays) / sizeof(arrays[0]); i++) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, arrays[i]);
+ }
+ cbm_arena_destroy(&c->arena);
+}
+
+static bool te_valid(const cbm_test_impact_request_t *rq) {
+ return rq && rq->repo_root && rq->repo_root[0] && rq->base_ref && rq->base_ref[0] &&
+ rq->work_parent && rq->work_parent[0] && rq->deadline_ms > 0;
+}
+
+/* The evidence steps. Each false is either a recorded run-all reason (the
+ * answer still comes) or exhausted memory (c->oom). */
+static void te_steps(te_ctx_t *c) {
+ if (!te_work_dir(c) || !te_git(c) || !te_config(c)) {
+ return;
+ }
+ if (!c->has_changes || !c->diff_complete) {
+ return; /* nothing changed, or the change is not known in full */
+ }
+ bool need_snapshot = false;
+ bool *unmatched = NULL;
+ if (!te_classify_rules(c, &need_snapshot, &unmatched) || !need_snapshot) {
+ return;
+ }
+ if (!te_snapshot(c) || !te_classify_unmatched(c, unmatched) || c->fallback_count) {
+ return;
+ }
+ if (!te_open_scope(c) || !te_seed(c) || !te_reach(c)) {
+ return;
+ }
+ (void)te_select(c);
+}
+
+typedef struct {
+ const cbm_test_impact_request_t *request;
+ cbm_test_result_t **out;
+ char *diagnostic;
+ size_t diagnostic_len;
+ cbm_test_impact_status_t status;
+} te_job_t;
+
+static void *te_job_main(void *arg) {
+ te_job_t *job = arg;
+ te_ctx_t c = {
+ .rq = job->request, .diagnostic = job->diagnostic, .diagnostic_len = job->diagnostic_len};
+ cbm_arena_init(&c.arena);
+ te_steps(&c);
+ cbm_test_impact_status_t status = c.oom ? CBM_TEST_IMPACT_OOM : te_answer(&c, job->out);
+ if (!c.oom && cbm_now_ms() > job->request->deadline_ms && status == CBM_TEST_IMPACT_OK) {
+ cbm_test_result_free(*job->out);
+ *job->out = NULL;
+ status = CBM_TEST_IMPACT_CANCELLED;
+ }
+ te_free(&c);
+ job->status = status;
+ return NULL;
+}
+
+cbm_test_impact_status_t cbm_test_impact_run(const cbm_test_impact_request_t *request,
+ cbm_test_result_t **out, char *diagnostic,
+ size_t diagnostic_len) {
+ if (diagnostic && diagnostic_len) {
+ diagnostic[0] = '\0';
+ }
+ if (!out) {
+ return CBM_TEST_IMPACT_INVALID;
+ }
+ *out = NULL;
+ if (!te_valid(request)) {
+ return CBM_TEST_IMPACT_INVALID;
+ }
+ te_job_t job = {.request = request,
+ .out = out,
+ .diagnostic = diagnostic,
+ .diagnostic_len = diagnostic_len,
+ .status = CBM_TEST_IMPACT_OOM};
+ /* The request runs a whole (frozen) index pipeline. Daemon tool calls run
+ * on 256 KiB application threads; the pipeline needs the stack every
+ * pipeline thread gets (cbm_thread_create's default), so the request runs
+ * on its own thread whoever calls it. On cbm, the in-daemon call died
+ * silently inside the pipeline without this. */
+ cbm_thread_t thread;
+ if (cbm_thread_create(&thread, 0, te_job_main, &job) != 0) {
+ return CBM_TEST_IMPACT_OOM;
+ }
+ (void)cbm_thread_join(&thread);
+ return job.status;
+}
diff --git a/src/mcp/test_impact_engine.h b/src/mcp/test_impact_engine.h
new file mode 100644
index 000000000..89cc50050
--- /dev/null
+++ b/src/mcp/test_impact_engine.h
@@ -0,0 +1,55 @@
+/*
+ * test_impact_engine.h — detect_changes scope:"tests", end to end.
+ *
+ * One request pins the change (merge base .. HEAD of a git worktree), builds
+ * the graph and the runnable test registry of exactly the HEAD snapshot,
+ * seeds the graph from the change, walks what depends on the seeds, maps
+ * reached tests to their suites and lanes, and returns the result codec's
+ * answer (cbm.test_impact). The selection rule is the measured rule B:
+ * a test runs when the static walk reaches it, when it changed, or when its
+ * recorded coverage meets the change.
+ *
+ * Missing or doubtful evidence never narrows: git, configuration, graph,
+ * registry or coverage that cannot be established turns into a run-all
+ * answer that names why. Only a malformed request, exhausted memory or the
+ * deadline end the request without an answer.
+ */
+#ifndef CBM_TEST_IMPACT_ENGINE_H
+#define CBM_TEST_IMPACT_ENGINE_H
+
+#include "mcp/test_impact_result.h"
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+typedef struct {
+ const char *repo_root; /* absolute top level of the git worktree */
+ const char *base_ref; /* commit-ish the change merges into */
+ /* A private directory (mode 0700) for the pinned snapshot and its graph;
+ * the request creates and removes its own entries inside. */
+ const char *work_parent;
+ /* NULL: the test_impact section of the merge base's .codebase-memory.json
+ * (a change cannot loosen its own selection). Otherwise that file. */
+ const char *config_path;
+ uint64_t deadline_ms; /* absolute cbm_now_ms() deadline */
+} cbm_test_impact_request_t;
+
+typedef enum {
+ CBM_TEST_IMPACT_OK = 0, /* an answer: selected, nothing, or run-all with reasons */
+ CBM_TEST_IMPACT_INVALID,
+ CBM_TEST_IMPACT_OOM,
+ CBM_TEST_IMPACT_CANCELLED
+} cbm_test_impact_status_t;
+
+/* *out owns the answer (cbm_test_result_json). diagnostic receives a short
+ * reason for a non-OK status and for every run-all fallback. */
+cbm_test_impact_status_t cbm_test_impact_run(const cbm_test_impact_request_t *request,
+ cbm_test_result_t **out, char *diagnostic,
+ size_t diagnostic_len);
+
+/* The absolute path of the `git` the engine runs: the first regular,
+ * executable `git` (`git.exe` on Windows) on PATH. false when none. */
+bool cbm_test_impact_find_git(char *out, size_t out_len);
+
+#endif /* CBM_TEST_IMPACT_ENGINE_H */
diff --git a/src/mcp/test_impact_engine_internal.h b/src/mcp/test_impact_engine_internal.h
new file mode 100644
index 000000000..2fae9eaf4
--- /dev/null
+++ b/src/mcp/test_impact_engine_internal.h
@@ -0,0 +1,115 @@
+/*
+ * test_impact_engine_internal.h — the state of one scope:"tests" request,
+ * shared by the engine's steps (test_impact_engine*.c).
+ */
+#ifndef CBM_TEST_IMPACT_ENGINE_INTERNAL_H
+#define CBM_TEST_IMPACT_ENGINE_INTERNAL_H
+
+#include "mcp/test_impact.h"
+#include "mcp/test_impact_changes.h"
+#include "mcp/test_impact_classify.h"
+#include "mcp/test_impact_engine.h"
+#include "mcp/test_impact_git.h"
+#include "mcp/test_impact_inventory.h"
+#include "mcp/test_impact_result.h"
+#include "mcp/test_impact_seed.h"
+#include "mcp/test_impact_source.h"
+#include "mcp/test_impact_tree.h"
+#include "discover/test_conventions.h"
+#include "foundation/arena.h"
+#include "store/store.h"
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+/* Every rule, fallback, warning and path the request records lives in the
+ * arena; dynamic arrays grow through the memory core. */
+typedef struct {
+ int rule_index;
+ bool resolved; /* every path it matched resolved its target */
+} te_match_t;
+
+typedef struct {
+ const cbm_test_impact_request_t *rq;
+ char *diagnostic;
+ size_t diagnostic_len;
+ CBMArena arena;
+ bool oom;
+
+ /* git */
+ cbm_git_facts_t *facts;
+ const cbm_git_facts_identity_t *id;
+ cbm_git_diff_t diff;
+ cbm_changes_t *changes;
+ bool diff_complete;
+ bool has_changes;
+
+ /* query-time configuration (the merge base's, M-4) */
+ cbm_test_config_t *config;
+ cbm_test_policy_t *policy;
+
+ /* the HEAD snapshot */
+ cbm_pinned_tree_t *tree;
+ cbm_test_impact_inventory_t *inventory;
+ cbm_test_impact_ledger_t *ledger;
+ cbm_test_declarations_t *declarations;
+ cbm_test_model_t *model;
+ char work_dir[4096];
+ char candidate_db[4096];
+ cbm_store_t *store;
+ cbm_store_read_scope_t *scope; /* one stable read of the candidate graph */
+ unsigned char graph_sha256[32];
+ bool graph_digest;
+ cbm_ti_graph_t *graph;
+ cbm_ti_source_t *source;
+ bool snapshot_ok;
+
+ /* classification of the changed paths */
+ te_match_t *matches;
+ int match_count;
+ int match_cap;
+ cbm_test_result_fallback_t *fallbacks;
+ int fallback_count;
+ int fallback_cap;
+ cbm_test_result_warning_t *warnings;
+ int warning_count;
+ int warning_cap;
+ cbm_ti_change_t *seed_changes; /* C-family paths the graph seeding reads */
+ int seed_change_count;
+ int seed_change_cap;
+ const char **fixture_paths; /* paths a `referencing_tests` rule matched */
+ int *fixture_rules; /* their rule index */
+ int fixture_rule_cap;
+ int fixture_count;
+ int fixture_cap;
+ bool activation_complete;
+
+ /* selection inputs */
+ cbm_ti_seeds_t *seeds;
+ cbm_test_reach_t *reach;
+ int reach_count;
+ cbm_test_suite_trigger_t *triggers;
+ int trigger_count;
+ int trigger_cap;
+ bool static_complete;
+
+ cbm_test_selection_t *selection;
+} te_ctx_t;
+
+/* Record a run-all reason once; the first diagnostic wins. false only when
+ * out of memory. */
+bool te_fallback(te_ctx_t *c, cbm_test_result_fallback_t code, const char *diagnostic);
+bool te_grow(void **items, int *cap, int count, size_t size);
+bool te_oom(te_ctx_t *c);
+
+/* test_impact_engine_snapshot.c */
+bool te_work_dir(te_ctx_t *c);
+bool te_snapshot(te_ctx_t *c);
+void te_snapshot_free(te_ctx_t *c);
+
+/* test_impact_engine_reach.c */
+bool te_fixtures(te_ctx_t *c, int64_t **extra_seeds, int *extra_count, bool **fixture_cases);
+bool te_reach(te_ctx_t *c);
+
+#endif /* CBM_TEST_IMPACT_ENGINE_INTERNAL_H */
diff --git a/src/mcp/test_impact_engine_reach.c b/src/mcp/test_impact_engine_reach.c
new file mode 100644
index 000000000..a3f96d0ba
--- /dev/null
+++ b/src/mcp/test_impact_engine_reach.c
@@ -0,0 +1,694 @@
+/*
+ * test_impact_engine_reach.c — from seeds to the selection's inputs: the
+ * fixture scan, the walk (rule B: the static walk without the process lift),
+ * reach rows for every registered test, and whole-suite triggers.
+ *
+ * Ports replay4.py run() 474-489 (cases, suites and runner as sinks), 584-615
+ * (fixtures by path literal) and 616-621 (header file-level escalation), and
+ * score4.py static_nolift (reached and changed suite bodies run whole; a
+ * reached runner main runs everything).
+ */
+#include "mcp/test_impact_engine_internal.h"
+
+#include "foundation/hash_table.h"
+#include "foundation/mem_core.h"
+#include "store/store_impact.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+/* The c-cbm runner's process-entry handlers: the runner re-executes itself
+ * with a role argument and these run product code in that child. They are
+ * reached, never expanded (their caller is the runner's main). */
+#define TE_RUNNER_ROLE_PREFIX "tf_maybe_run_"
+
+static const char *const te_walk_types[] = {"CALLS", "ASYNC_CALLS", "USAGE", "CALL_REFERENCE",
+ "READS"};
+
+typedef struct {
+ int64_t *items;
+ int count;
+ int cap;
+} te_ids_t;
+
+static bool te_ids_push(te_ctx_t *c, te_ids_t *a, int64_t id) {
+ if (!te_grow((void **)&a->items, &a->cap, a->count, sizeof(*a->items))) {
+ return te_oom(c);
+ }
+ a->items[a->count++] = id;
+ return true;
+}
+
+static bool te_is_function(const cbm_ti_node_t *n) {
+ return strcmp(n->label, "Function") == 0 || strcmp(n->label, "Method") == 0;
+}
+
+/* The function nodes of a test case or suite of `file`: those whose
+ * definition starts on the line of its TEST(...) / SUITE(...) — graphs name
+ * them differently (`x` without configured declarations, `TEST_x` with) —
+ * else every function named `name`. *count of them, ids appended. */
+static bool te_named(te_ctx_t *c, const char *file, const char *name, int line, te_ids_t *out,
+ int *count) {
+ bool ok = true;
+ int n = 0;
+ const cbm_ti_node_t *nodes = cbm_ti_graph_file(c->graph, file, &n, &ok);
+ if (!ok) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE, "graph read failed") &&
+ false;
+ }
+ *count = 0;
+ for (int pass = 0; pass < 2 && *count == 0; pass++) {
+ for (int i = 0; i < n; i++) {
+ bool match =
+ te_is_function(&nodes[i]) &&
+ (pass == 0 ? nodes[i].start_line == line : strcmp(nodes[i].name, name) == 0);
+ if (!match) {
+ continue;
+ }
+ (*count)++;
+ if (out && !te_ids_push(c, out, nodes[i].id)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+static bool te_is_runner_suite(te_ctx_t *c, const char *name) {
+ int n = 0;
+ const cbm_test_runner_suite_t *runner = cbm_test_model_runner_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (strcmp(runner[i].name, name) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* ── Fixtures (replay4 584-615) ──────────────────────────────────── */
+
+/* Test files: the files that define a suite. */
+static bool te_test_file(te_ctx_t *c, const char *path) {
+ int n = 0;
+ const cbm_test_suite_t *suites = cbm_test_model_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (strcmp(suites[i].file, path) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static int te_case_index(te_ctx_t *c, const char *file, const char *name) {
+ int n = 0;
+ const cbm_test_case_t *cases = cbm_test_model_cases(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (strcmp(cases[i].file, file) == 0 && strcmp(cases[i].name, name) == 0) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+/* Every line of a test file that contains `needle`: its enclosing
+ * definition is a fixture case or a seed. */
+static bool te_scan_literal(te_ctx_t *c, const char *needle, te_ids_t *seeds, bool *cases,
+ bool *hit) {
+ int files = cbm_ti_source_file_count(c->source);
+ size_t nlen = strlen(needle);
+ for (int f = 0; f < files; f++) {
+ const char *path = cbm_ti_source_path(c->source, f);
+ if (!te_test_file(c, path)) {
+ continue;
+ }
+ int lines = cbm_ti_source_line_count(c->source, f);
+ for (int line = 1; line <= lines; line++) {
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(c->source, f, line, &len);
+ bool found = false;
+ for (size_t i = 0; !found && nlen && i + nlen <= len; i++) {
+ found = memcmp(text + i, needle, nlen) == 0;
+ }
+ if (!found) {
+ continue;
+ }
+ bool ok = true;
+ const cbm_ti_node_t *d = cbm_ti_graph_enclosing(c->graph, path, line, &ok);
+ if (!ok) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "graph read failed") &&
+ false;
+ }
+ if (!d) {
+ continue;
+ }
+ *hit = true;
+ int ci = te_is_function(d) ? te_case_index(c, path, d->name) : -1;
+ if (ci >= 0) {
+ cases[ci] = true;
+ } else if (!te_ids_push(c, seeds, d->id)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/* One fixture path: the path itself, then each parent down to the rule's
+ * key segment; each with and without its first segment. The first key some
+ * test file mentions decides. */
+static bool te_fixture(te_ctx_t *c, const char *path, int min_segments, te_ids_t *seeds,
+ bool *cases, bool *hit) {
+ char key[4096];
+ size_t len = strlen(path);
+ if (len >= sizeof(key)) {
+ return true; /* unresolved: run-all through the rule */
+ }
+ memcpy(key, path, len + 1);
+ int segments = 1;
+ for (size_t i = 0; i < len; i++) {
+ segments += key[i] == '/';
+ }
+ *hit = false;
+ while (!*hit && segments >= min_segments) {
+ const char *rest = strchr(key, '/');
+ if (!te_scan_literal(c, key, seeds, cases, hit) ||
+ (rest && !te_scan_literal(c, rest + 1, seeds, cases, hit))) {
+ return false;
+ }
+ char *cut = strrchr(key, '/');
+ if (!cut) {
+ break;
+ }
+ *cut = '\0';
+ segments--;
+ }
+ return true;
+}
+
+bool te_fixtures(te_ctx_t *c, int64_t **extra_seeds, int *extra_count, bool **fixture_cases) {
+ int case_count = 0;
+ (void)cbm_test_model_cases(c->model, &case_count);
+ bool *cases = cbm_arena_calloc(&c->arena, (size_t)case_count + 1);
+ te_ids_t seeds = {0};
+ if (!cases) {
+ return te_oom(c);
+ }
+ int rule_count = 0;
+ const cbm_test_rule_t *rules = cbm_test_policy_rules(c->policy, &rule_count);
+ for (int i = 0; i < c->fixture_count; i++) {
+ int r = c->fixture_rules[i];
+ bool hit = false;
+ if (!te_fixture(c, c->fixture_paths[i], rules[r].key_segment + 1, &seeds, cases, &hit)) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, seeds.items);
+ return false;
+ }
+ for (int m = 0; !hit && m < c->match_count; m++) {
+ if (c->matches[m].rule_index == r) {
+ c->matches[m].resolved = false; /* no test names it: run-all */
+ }
+ }
+ }
+ *extra_seeds = seeds.items;
+ *extra_count = seeds.count;
+ *fixture_cases = cases;
+ return true;
+}
+
+/* ── The walk ────────────────────────────────────────────────────── */
+
+typedef struct {
+ te_ids_t sinks;
+ te_ids_t runner_main;
+} te_sinks_t;
+
+static bool te_runner_sinks(te_ctx_t *c, te_sinks_t *s) {
+ int n = 0;
+ const cbm_test_runner_suite_t *runner = cbm_test_model_runner_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (!runner[i].file ||
+ (i > 0 && runner[i - 1].file && strcmp(runner[i - 1].file, runner[i].file) == 0)) {
+ continue;
+ }
+ bool ok = true;
+ int count = 0;
+ const cbm_ti_node_t *nodes = cbm_ti_graph_file(c->graph, runner[i].file, &count, &ok);
+ if (!ok) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "graph read failed") &&
+ false;
+ }
+ for (int k = 0; k < count; k++) {
+ if (!te_is_function(&nodes[k])) {
+ continue;
+ }
+ bool main_fn = strcmp(nodes[k].name, "main") == 0;
+ bool role = strncmp(nodes[k].name, TE_RUNNER_ROLE_PREFIX,
+ sizeof(TE_RUNNER_ROLE_PREFIX) - 1) == 0;
+ if ((main_fn || role) && !te_ids_push(c, &s->sinks, nodes[k].id)) {
+ return false;
+ }
+ if (main_fn && !te_ids_push(c, &s->runner_main, nodes[k].id)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+static bool te_collect_sinks(te_ctx_t *c, te_sinks_t *s) {
+ int n = 0;
+ int count = 0;
+ const cbm_test_case_t *cases = cbm_test_model_cases(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (!te_named(c, cases[i].file, cases[i].name, cases[i].start_line, &s->sinks, &count)) {
+ return false;
+ }
+ }
+ const cbm_test_suite_t *suites = cbm_test_model_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (!te_named(c, suites[i].file, suites[i].name, suites[i].start_line, &s->sinks, &count)) {
+ return false;
+ }
+ }
+ return te_runner_sinks(c, s);
+}
+
+static bool te_walk(te_ctx_t *c, const te_sinks_t *sinks, const int64_t *extra, int extra_count,
+ cbm_impact_walk_t **out) {
+ cbm_impact_policy_t policy = {.project = "test-impact",
+ .edge_types = te_walk_types,
+ .edge_type_count =
+ (int)(sizeof(te_walk_types) / sizeof(te_walk_types[0])),
+ .follow_routes = true};
+ *out = NULL;
+ if (cbm_impact_walk_open_scoped(c->scope, &policy, out) != CBM_STORE_OK) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_ENGINE_SATURATED,
+ "the impact walk could not start") &&
+ false;
+ }
+ int seed_count = 0;
+ const int64_t *seeds = cbm_ti_seeds_nodes(c->seeds, &seed_count);
+ bool ok =
+ cbm_impact_walk_add_sinks(*out, sinks->sinks.items, sinks->sinks.count) == CBM_STORE_OK;
+ if (ok && seed_count) {
+ ok = cbm_impact_walk_run(*out, seeds, seed_count) == CBM_STORE_OK;
+ }
+ if (ok && extra_count) {
+ ok = cbm_impact_walk_run(*out, extra, extra_count) == CBM_STORE_OK;
+ }
+ if (!ok) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_ENGINE_SATURATED,
+ "the impact walk failed") &&
+ false;
+ }
+ return true;
+}
+
+/* ── Parse gaps (user decision 2026-10-04: handled per file) ────────
+ * A partial parse leaves a few lines (index_coverage `parse_partial`, detail
+ * "a-b,c-d") the graph has no edges from. A gap can only hide references
+ * written in its own lines, so when a gap's text names a definition the walk
+ * reached, the definition around the gap is reached too (its whole file when
+ * the gap lies outside every definition) and the walk goes on, to a
+ * fixpoint. Only C-family sources are read; tests are C. More, never fewer. */
+
+typedef struct {
+ const char *file;
+ int start;
+ int end;
+ bool fired;
+} te_gap_t;
+
+typedef struct {
+ te_gap_t *items;
+ int count;
+ int cap;
+} te_gaps_t;
+
+static bool te_gap_push(te_ctx_t *c, te_gaps_t *gaps, const char *file, int start, int end) {
+ if (!te_grow((void **)&gaps->items, &gaps->cap, gaps->count, sizeof(*gaps->items))) {
+ return te_oom(c);
+ }
+ gaps->items[gaps->count++] = (te_gap_t){.file = file, .start = start, .end = end};
+ return true;
+}
+
+/* "a-b,c-d,e" line ranges. */
+static bool te_parse_ranges(te_ctx_t *c, te_gaps_t *gaps, const char *file, const char *detail) {
+ const char *p = detail;
+ while (p && *p) {
+ char *end = NULL;
+ long a = strtol(p, &end, 10);
+ long b = a;
+ if (end == p) {
+ break;
+ }
+ if (*end == '-') {
+ p = end + 1;
+ b = strtol(p, &end, 10);
+ }
+ if (a > 0 && b >= a && b - a < 100000 && !te_gap_push(c, gaps, file, (int)a, (int)b)) {
+ return false;
+ }
+ p = *end == ',' ? end + 1 : NULL;
+ }
+ return true;
+}
+
+static bool te_load_gaps(te_ctx_t *c, te_gaps_t *gaps) {
+ cbm_coverage_row_t *rows = NULL;
+ int n = 0;
+ if (cbm_store_coverage_get(c->store, "test-impact", &rows, &n) != CBM_STORE_OK) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "the graph's parse gaps could not be read") &&
+ false;
+ }
+ bool ok = true;
+ for (int i = 0; ok && i < n; i++) {
+ if (!rows[i].kind || strcmp(rows[i].kind, "parse_partial") != 0 || !rows[i].rel_path ||
+ cbm_ti_source_find(c->source, rows[i].rel_path) < 0) {
+ continue;
+ }
+ const char *file = cbm_arena_strdup(&c->arena, rows[i].rel_path);
+ ok =
+ file ? te_parse_ranges(c, gaps, file, rows[i].detail ? rows[i].detail : "") : te_oom(c);
+ }
+ cbm_store_free_coverage(rows, n);
+ return ok;
+}
+
+/* The short names of everything the walk reached (last QN segment). */
+static bool te_reached_names(te_ctx_t *c, cbm_impact_walk_t *walk, CBMHashTable *names) {
+ const cbm_impact_hit_t *hits = cbm_impact_walk_hits(walk);
+ int n = cbm_impact_walk_count(walk);
+ for (int i = 0; i < n; i++) {
+ const char *qn = hits[i].qualified_name;
+ const char *dot = qn ? strrchr(qn, '.') : NULL;
+ const char *name = dot ? dot + 1 : qn;
+ if (!name || !*name || cbm_ht_get(names, name)) {
+ continue;
+ }
+ const char *owned = cbm_arena_strdup(&c->arena, name);
+ if (!owned) {
+ return te_oom(c);
+ }
+ cbm_ht_set(names, owned, (void *)1);
+ }
+ return true;
+}
+
+static bool te_gap_names_reached(te_ctx_t *c, const te_gap_t *g, CBMHashTable *names) {
+ int file = cbm_ti_source_find(c->source, g->file);
+ for (int line = g->start; line <= g->end; line++) {
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(c->source, file, line, &len);
+ for (size_t i = 0; text && i < len;) {
+ char ch = text[i];
+ bool start = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_';
+ if (!start) {
+ i++;
+ continue;
+ }
+ size_t e = i;
+ char word[256];
+ while (e < len &&
+ ((text[e] >= 'a' && text[e] <= 'z') || (text[e] >= 'A' && text[e] <= 'Z') ||
+ (text[e] >= '0' && text[e] <= '9') || text[e] == '_')) {
+ e++;
+ }
+ if (e - i < sizeof(word)) {
+ memcpy(word, text + i, e - i);
+ word[e - i] = '\0';
+ if (cbm_ht_get(names, word)) {
+ return true;
+ }
+ }
+ i = e;
+ }
+ }
+ return false;
+}
+
+/* Seeds for a gap that fired: the definition around it, else its file. */
+static bool te_gap_seeds(te_ctx_t *c, const te_gap_t *g, te_ids_t *out) {
+ bool ok = true;
+ const cbm_ti_node_t *d = cbm_ti_graph_enclosing(c->graph, g->file, g->start, &ok);
+ if (ok && d) {
+ return te_ids_push(c, out, d->id);
+ }
+ int n = 0;
+ const cbm_ti_node_t *nodes = ok ? cbm_ti_graph_file(c->graph, g->file, &n, &ok) : NULL;
+ for (int i = 0; ok && i < n; i++) {
+ ok = te_ids_push(c, out, nodes[i].id);
+ }
+ return ok || te_fallback(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE, "graph read failed");
+}
+
+static bool te_parse_gaps(te_ctx_t *c, cbm_impact_walk_t *walk) {
+ te_gaps_t gaps = {0};
+ CBMHashTable *names = NULL;
+ bool ok = te_load_gaps(c, &gaps);
+ bool grew = ok && gaps.count > 0;
+ while (ok && grew) {
+ grew = false;
+ if (names) {
+ cbm_ht_free(names);
+ }
+ names = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ te_ids_t seeds = {0};
+ ok = names && te_reached_names(c, walk, names);
+ for (int i = 0; ok && i < gaps.count; i++) {
+ if (!gaps.items[i].fired && te_gap_names_reached(c, &gaps.items[i], names)) {
+ gaps.items[i].fired = true;
+ ok = te_gap_seeds(c, &gaps.items[i], &seeds);
+ }
+ }
+ if (ok && seeds.count) {
+ ok = cbm_impact_walk_run(walk, seeds.items, seeds.count) == CBM_STORE_OK ||
+ (te_fallback(c, CBM_TEST_RESULT_FALLBACK_ENGINE_SATURATED,
+ "the impact walk failed") &&
+ false);
+ grew = ok;
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, seeds.items);
+ }
+ if (names) {
+ cbm_ht_free(names);
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, gaps.items);
+ return ok;
+}
+
+/* ── Reach rows and triggers ─────────────────────────────────────── */
+
+static bool te_trigger(te_ctx_t *c, const char *suite, bool reached, bool changed, bool rule);
+
+/* Whether a suite of `file` registers tests the model cannot name (a macro
+ * registers them) or is uncertain: its cases cannot be narrowed one by one. */
+static bool te_whole_only_file(te_ctx_t *c, const char *file) {
+ int n = 0;
+ const cbm_test_suite_t *suites = cbm_test_model_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if ((suites[i].macro_registrations || suites[i].uncertain) &&
+ strcmp(suites[i].file, file) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* A reached or changed case of such a file runs every suite of the file
+ * whole: a macro may register it in any of them (the reference walked on
+ * from such a case to its suite). */
+static bool te_trigger_file_suites(te_ctx_t *c, const char *file, bool reached, bool changed) {
+ int n = 0;
+ const cbm_test_suite_t *suites = cbm_test_model_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ if (strcmp(suites[i].file, file) == 0 &&
+ !te_trigger(c, suites[i].name, reached, changed, false)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool te_reach_rows(te_ctx_t *c, cbm_impact_walk_t *walk, const bool *fixture_cases) {
+ int n = 0;
+ const cbm_test_case_t *cases = cbm_test_model_cases(c->model, &n);
+ int changed_n = 0;
+ const int *changed = cbm_ti_seeds_changed_cases(c->seeds, &changed_n);
+ c->reach = cbm_arena_calloc(&c->arena, (size_t)(n ? n : 1) * sizeof(*c->reach));
+ if (!c->reach) {
+ return te_oom(c);
+ }
+ for (int i = 0; i < n; i++) {
+ int at = -1;
+ for (int k = 0; k < c->reach_count; k++) {
+ if (strcmp(c->reach[k].file, cases[i].file) == 0 &&
+ strcmp(c->reach[k].test, cases[i].name) == 0) {
+ at = k;
+ }
+ }
+ te_ids_t ids = {0};
+ int count = 0;
+ if (!te_named(c, cases[i].file, cases[i].name, cases[i].start_line, &ids, &count)) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, ids.items);
+ return false;
+ }
+ bool reached = false;
+ for (int k = 0; k < ids.count; k++) {
+ reached = reached || cbm_impact_walk_reached(walk, ids.items[k]);
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, ids.items);
+ bool was_changed = fixture_cases[i];
+ for (int k = 0; k < changed_n; k++) {
+ was_changed = was_changed || changed[k] == i;
+ }
+ if (te_whole_only_file(c, cases[i].file)) {
+ if ((reached || was_changed) &&
+ !te_trigger_file_suites(c, cases[i].file, reached, was_changed)) {
+ return false;
+ }
+ continue;
+ }
+ if (at >= 0) {
+ /* the same name twice in one file: ambiguous, never narrowed */
+ c->reach[at].mapped = false;
+ c->reach[at].reached = c->reach[at].reached || reached;
+ c->reach[at].changed = c->reach[at].changed || was_changed;
+ continue;
+ }
+ c->reach[c->reach_count++] = (cbm_test_reach_t){.file = cases[i].file,
+ .test = cases[i].name,
+ .mapped = count == 1,
+ .reached = reached,
+ .changed = was_changed};
+ }
+ return true;
+}
+
+static bool te_trigger(te_ctx_t *c, const char *suite, bool reached, bool changed, bool rule) {
+ if (!te_is_runner_suite(c, suite)) {
+ return true; /* outside this runner's selection */
+ }
+ if (!te_grow((void **)&c->triggers, &c->trigger_cap, c->trigger_count, sizeof(*c->triggers))) {
+ return te_oom(c);
+ }
+ c->triggers[c->trigger_count++] = (cbm_test_suite_trigger_t){
+ .suite = suite, .reached = reached, .changed = changed, .rule = rule};
+ return true;
+}
+
+static bool te_suite_triggers(te_ctx_t *c, cbm_impact_walk_t *walk) {
+ int n = 0;
+ const cbm_test_suite_t *suites = cbm_test_model_suites(c->model, &n);
+ int changed_n = 0;
+ const int *changed = cbm_ti_seeds_changed_suites(c->seeds, &changed_n);
+ for (int i = 0; i < n; i++) {
+ te_ids_t ids = {0};
+ int count = 0;
+ if (!te_named(c, suites[i].file, suites[i].name, suites[i].start_line, &ids, &count)) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, ids.items);
+ return false;
+ }
+ bool reached = false;
+ for (int k = 0; k < ids.count; k++) {
+ reached = reached || cbm_impact_walk_reached(walk, ids.items[k]);
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, ids.items);
+ bool was_changed = false;
+ for (int k = 0; k < changed_n; k++) {
+ was_changed = was_changed || changed[k] == i;
+ }
+ if ((reached || was_changed) &&
+ !te_trigger(c, suites[i].name, reached, was_changed, false)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* Suites a `suites` rule names, among the runner's. */
+static bool te_rule_triggers(te_ctx_t *c) {
+ int n = 0;
+ const cbm_test_runner_suite_t *runner = cbm_test_model_runner_suites(c->model, &n);
+ int rule_count = 0;
+ const cbm_test_rule_t *rules = cbm_test_policy_rules(c->policy, &rule_count);
+ for (int m = 0; m < c->match_count; m++) {
+ int r = c->matches[m].rule_index;
+ if (rules[r].action != CBM_TEST_RULE_SUITES) {
+ continue;
+ }
+ for (int i = 0; i < n; i++) {
+ bool selected = false;
+ if (!cbm_test_policy_rule_selects_suite(c->policy, r, runner[i].name, runner[i].perf,
+ &selected)) {
+ return te_fallback(c, CBM_TEST_RESULT_FALLBACK_POLICY_EVALUATION_FAILED,
+ "suite rule evaluation failed");
+ }
+ if (selected && !te_trigger(c, runner[i].name, false, false, true)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/* A header changed at file level: every suite of every file including it
+ * runs whole (replay4 616-621). */
+static bool te_header_triggers(te_ctx_t *c) {
+ int headers_n = 0;
+ const char *const *headers = cbm_ti_seeds_file_level_headers(c->seeds, &headers_n);
+ if (!headers_n) {
+ return true;
+ }
+ int files = cbm_ti_source_file_count(c->source);
+ bool *marked = cbm_arena_calloc(&c->arena, (size_t)files + 1);
+ if (!marked) {
+ return te_oom(c);
+ }
+ for (int h = 0; h < headers_n; h++) {
+ int at = cbm_ti_source_find(c->source, headers[h]);
+ if (at >= 0) {
+ marked[at] = true;
+ }
+ }
+ cbm_ti_source_include_closure(c->source, marked);
+ int n = 0;
+ const cbm_test_suite_t *suites = cbm_test_model_suites(c->model, &n);
+ for (int i = 0; i < n; i++) {
+ int at = cbm_ti_source_find(c->source, suites[i].file);
+ if (at >= 0 && marked[at] && !te_trigger(c, suites[i].name, true, false, false)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool te_reach(te_ctx_t *c) {
+ int64_t *extra = NULL;
+ int extra_count = 0;
+ bool *fixture_cases = NULL;
+ te_sinks_t sinks = {0};
+ cbm_impact_walk_t *walk = NULL;
+ bool ok = te_fixtures(c, &extra, &extra_count, &fixture_cases) && te_collect_sinks(c, &sinks) &&
+ te_walk(c, &sinks, extra, extra_count, &walk) && te_parse_gaps(c, walk);
+ if (ok) {
+ for (int i = 0; i < sinks.runner_main.count; i++) {
+ if (cbm_impact_walk_reached(walk, sinks.runner_main.items[i])) {
+ ok = te_fallback(c, CBM_TEST_RESULT_FALLBACK_RUNNER_REACHED,
+ "the change reaches the test runner's main");
+ break;
+ }
+ }
+ }
+ ok = ok && te_reach_rows(c, walk, fixture_cases) && te_suite_triggers(c, walk) &&
+ te_rule_triggers(c) && te_header_triggers(c);
+ c->static_complete = ok;
+ cbm_impact_walk_close(walk);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, extra);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, sinks.sinks.items);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, sinks.runner_main.items);
+ return ok;
+}
diff --git a/src/mcp/test_impact_engine_snapshot.c b/src/mcp/test_impact_engine_snapshot.c
new file mode 100644
index 000000000..0b5433774
--- /dev/null
+++ b/src/mcp/test_impact_engine_snapshot.c
@@ -0,0 +1,350 @@
+/*
+ * test_impact_engine_snapshot.c — the HEAD snapshot of one scope:"tests"
+ * request: the pinned tree, its classified ledger, the runnable registry, the
+ * frozen graph of exactly the ledger's files, and the text index of its
+ * C-family sources. All of it is a function of the pinned HEAD commit (D5):
+ * nothing reads the worktree.
+ */
+#include "mcp/test_impact_engine_internal.h"
+
+#include "discover/discover.h"
+#include "discover/userconfig.h"
+#include "foundation/compat.h"
+#include "foundation/compat_fs.h"
+#include "foundation/mem_core.h"
+#include "foundation/platform.h"
+#include "pipeline/pipeline.h"
+#include "pipeline/pipeline_internal.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+enum {
+ TE_MAX_FILES = 1000000,
+ TE_MAX_DIRECTORIES = 400000,
+ TE_MAX_CONFIG_BYTES = 65536,
+};
+
+static bool te_snapshot_fail(te_ctx_t *c, cbm_test_result_fallback_t code, const char *what,
+ const char *detail) {
+ char text[512];
+ snprintf(text, sizeof(text), "%s%s%s", what, detail && *detail ? ": " : "",
+ detail ? detail : "");
+ (void)te_fallback(c, code, text);
+ return false;
+}
+
+/* A private (0700) directory for this request under work_parent. */
+bool te_work_dir(te_ctx_t *c) {
+ snprintf(c->work_dir, sizeof(c->work_dir), "%s/ti-XXXXXX", c->rq->work_parent);
+ if (!cbm_mkdtemp(c->work_dir)) {
+ c->work_dir[0] = '\0';
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "no private work directory", c->rq->work_parent);
+ }
+ char sub[4200];
+ snprintf(sub, sizeof(sub), "%s/pin", c->work_dir);
+ bool ok = cbm_mkdir_p(sub, 0700);
+ snprintf(sub, sizeof(sub), "%s/graph", c->work_dir);
+ ok = ok && cbm_mkdir_p(sub, 0700);
+ snprintf(c->candidate_db, sizeof(c->candidate_db), "%s/graph/candidate.db", c->work_dir);
+ return ok || te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "work directory setup failed", c->work_dir);
+}
+
+static bool te_pin(te_ctx_t *c) {
+ char parent[4200];
+ snprintf(parent, sizeof(parent), "%s/pin", c->work_dir);
+ cbm_pinned_tree_options_t options = {
+ .facts = c->facts,
+ .revision = CBM_GIT_REV_HEAD,
+ .private_parent = parent,
+ .limits = {.max_files = TE_MAX_FILES,
+ .max_directories = TE_MAX_DIRECTORIES,
+ .max_total_content_bytes = (size_t)8 << 30,
+ .max_relative_path_bytes = 4095,
+ .max_arena_bytes = (size_t)2 << 30,
+ .blob_batch = {.max_entries = TE_MAX_FILES,
+ .max_input_bytes = (size_t)256 << 20,
+ .max_arena_bytes = (size_t)8 << 30}},
+ .control = {.deadline_ms = c->rq->deadline_ms}};
+ cbm_pinned_tree_error_t error;
+ cbm_pinned_tree_status_t status = cbm_pinned_tree_create(&options, &c->tree, &error);
+ if (status != CBM_PINNED_TREE_OK) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "pinning HEAD failed", error.diagnostic);
+ }
+ return true;
+}
+
+static bool te_inventory(te_ctx_t *c) {
+ cbm_inventory_limits_t limits = {.max_files = TE_MAX_FILES,
+ .max_directories = TE_MAX_DIRECTORIES,
+ .max_arena_bytes = (size_t)1 << 30,
+ .max_ignore_arena_bytes = (size_t)64 << 20,
+ .max_control_file_bytes = 1 << 20,
+ .max_control_total_bytes = 64u << 20,
+ .max_ignore_patterns = 100000,
+ .max_probe_prefix_bytes = CBM_LANGUAGE_PROBE_MAX,
+ .max_ignore_work = 1000000000ULL,
+ .max_verified_file_reads = TE_MAX_FILES,
+ .max_verified_content_bytes = (uint64_t)16 << 30};
+ cbm_inventory_control_t control = {.deadline_ms = c->rq->deadline_ms};
+ cbm_inventory_error_t error;
+ if (cbm_test_impact_inventory_prepare(c->tree, &limits, &control, &c->inventory, &error) !=
+ CBM_INVENTORY_OK) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "inventory of HEAD failed", error.diagnostic);
+ }
+ return true;
+}
+
+/* A configuration file's bytes, at most 64 KiB; absent leaves NULL. */
+static bool te_read_config(te_ctx_t *c, const char *path, char **bytes, size_t *len) {
+ *bytes = NULL;
+ *len = 0;
+ FILE *f = cbm_fopen(path, "rb");
+ if (!f) {
+ return true; /* absent */
+ }
+ char *buf = cbm_arena_alloc(&c->arena, TE_MAX_CONFIG_BYTES + 1);
+ size_t got = buf ? fread(buf, 1, TE_MAX_CONFIG_BYTES + 1, f) : 0;
+ bool err = ferror(f) != 0;
+ fclose(f);
+ if (!buf) {
+ return te_oom(c);
+ }
+ if (err || got > TE_MAX_CONFIG_BYTES) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_CONFIG_INVALID,
+ "configuration unreadable or over 64 KiB", path);
+ }
+ buf[got] = '\0';
+ *bytes = buf;
+ *len = got;
+ return true;
+}
+
+/* HEAD's own .codebase-memory.json: what the graph is built under. */
+static bool te_head_config(te_ctx_t *c, char **bytes, size_t *len) {
+ const cbm_pinned_tree_view_t *view = cbm_pinned_tree_view(c->tree);
+ char path[4200];
+ snprintf(path, sizeof(path), "%s/.codebase-memory.json", view->root);
+ return te_read_config(c, path, bytes, len);
+}
+
+/* The test declarations: the request's configuration when it names one
+ * (read in place of the project file, for replay), else HEAD's. */
+static bool te_ledger_and_registry(te_ctx_t *c, const char *config_bytes, size_t config_len) {
+ if (c->rq->config_path) {
+ char *override = NULL;
+ size_t override_len = 0;
+ if (!te_read_config(c, c->rq->config_path, &override, &override_len)) {
+ return false;
+ }
+ config_bytes = override;
+ config_len = override_len;
+ }
+ const cbm_pinned_tree_view_t *view = cbm_pinned_tree_view(c->tree);
+ cbm_userconfig_t *userconfig = cbm_userconfig_load(view->root);
+ cbm_inventory_control_t control = {.deadline_ms = c->rq->deadline_ms};
+ cbm_inventory_error_t error;
+ cbm_inventory_status_t status =
+ cbm_test_impact_classify(c->inventory, c->tree, userconfig, &control, &c->ledger, &error);
+ cbm_userconfig_free(userconfig);
+ if (status != CBM_INVENTORY_OK) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "classifying HEAD failed", error.diagnostic);
+ }
+ c->declarations = cbm_test_declarations_parse(config_bytes, config_len, config_bytes == NULL);
+ if (!c->declarations) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_CONFIG_INVALID,
+ "HEAD test declarations invalid", NULL);
+ }
+ status = cbm_test_impact_registry(c->ledger, c->inventory, c->tree, c->declarations, &control,
+ &c->model, &error);
+ if (status != CBM_INVENTORY_OK) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "test registry of HEAD failed", error.diagnostic);
+ }
+ return true;
+}
+
+static bool te_frozen_build(te_ctx_t *c, const char *config_bytes, size_t config_len) {
+ const cbm_pinned_tree_view_t *view = cbm_pinned_tree_view(c->tree);
+ size_t rows_n = 0;
+ const cbm_test_impact_classified_t *rows = cbm_test_impact_ledger_rows(c->ledger, &rows_n);
+ cbm_pipeline_frozen_file_t *list =
+ cbm_arena_alloc(&c->arena, (rows_n ? rows_n : 1) * sizeof(*list));
+ if (!list) {
+ return te_oom(c);
+ }
+ for (size_t i = 0; i < rows_n; i++) {
+ list[i] = (cbm_pipeline_frozen_file_t){
+ .rel_path = (const char *)view->files[rows[i].file_index].path,
+ .language = rows[i].language};
+ }
+ /* The context takes mutable strings; these are copies of the pinned facts. */
+ char root[4096];
+ char head[65];
+ char merge_base[65];
+ char empty[1] = "";
+ char branch[] = "pinned";
+ snprintf(root, sizeof(root), "%s", view->root);
+ snprintf(head, sizeof(head), "%s", c->id->head);
+ snprintf(merge_base, sizeof(merge_base), "%s", c->id->merge_base);
+ cbm_git_context_t git = {.is_git = true,
+ .is_detached = true,
+ .root_exists = true,
+ .input_path = root,
+ .worktree_root = root,
+ .git_dir = empty,
+ .git_common_dir = empty,
+ .canonical_root = root,
+ .branch = branch,
+ .branch_slug = branch,
+ .head_sha = head,
+ .base_sha = merge_base};
+ cbm_pipeline_frozen_inputs_t in = {.source_root = view->root,
+ .candidate_db_path = c->candidate_db,
+ .project = "test-impact",
+ .config_state = config_bytes ? CBM_USERCONFIG_SOURCE_PRESENT
+ : CBM_USERCONFIG_SOURCE_ABSENT,
+ .config_bytes = config_bytes,
+ .config_len = config_len,
+ .pinned_git = &git,
+ .files = list,
+ .file_count = rows_n};
+ cbm_pipeline_frozen_t *owner = NULL;
+ cbm_pipeline_frozen_status_t status = cbm_pipeline_frozen_create(&in, &owner);
+ if (status == CBM_PIPELINE_FROZEN_OK) {
+ status = cbm_pipeline_frozen_build(owner);
+ }
+ char detail[512] = "";
+ if (status != CBM_PIPELINE_FROZEN_OK) {
+ /* Name what refused the graph: the build's negative evidence and its
+ * first file error. */
+ unsigned flags = 0;
+ cbm_file_error_t *errors = NULL;
+ int error_count = 0;
+ (void)cbm_pipeline_frozen_negative_evidence(owner, &flags);
+ const cbm_pipeline_t *diagnostics = owner ? cbm_pipeline_frozen_diagnostics(owner) : NULL;
+ if (diagnostics) {
+ cbm_pipeline_get_file_errors(diagnostics, &errors, &error_count);
+ }
+ snprintf(detail, sizeof(detail), "frozen status %d, evidence %u, %d file error(s)%s%s%s%s",
+ (int)status, flags, error_count, error_count ? ": " : "",
+ error_count && errors[0].path ? errors[0].path : "", error_count ? " " : "",
+ error_count && errors[0].reason ? errors[0].reason : "");
+ }
+ cbm_pipeline_frozen_free(owner);
+ if (status != CBM_PIPELINE_FROZEN_OK) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_REJECTED,
+ "the graph of HEAD could not be built", detail);
+ }
+ c->store = cbm_store_open_path_query(c->candidate_db);
+ c->graph = c->store ? cbm_ti_graph_new(c->store, "test-impact") : NULL;
+ if (!c->graph) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "the graph of HEAD could not be opened", NULL);
+ }
+ return true;
+}
+
+/* The C-family files the reference reads (replay4 is_c: by extension). */
+static bool te_c_family_path(const char *path) {
+ static const char *const ext[] = {".c", ".h", ".cc", ".cpp", ".hpp",
+ ".m", ".mm", ".cxx", ".hh"};
+ size_t n = strlen(path);
+ for (size_t i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
+ size_t e = strlen(ext[i]);
+ if (n > e && strcmp(path + n - e, ext[i]) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool te_source_index(te_ctx_t *c) {
+ const cbm_pinned_tree_view_t *view = cbm_pinned_tree_view(c->tree);
+ size_t rows_n = 0;
+ const cbm_test_impact_classified_t *rows = cbm_test_impact_ledger_rows(c->ledger, &rows_n);
+ c->source = cbm_ti_source_new();
+ if (!c->source) {
+ return te_oom(c);
+ }
+ cbm_pinned_tree_control_t control = {.deadline_ms = c->rq->deadline_ms};
+ for (size_t i = 0; i < rows_n; i++) {
+ const cbm_pinned_tree_file_t *file = &view->files[rows[i].file_index];
+ const char *path = (const char *)file->path;
+ if (!te_c_family_path(path)) {
+ continue;
+ }
+ size_t len = (size_t)file->content_length;
+ unsigned char *text = cbm_alloc(CBM_MEM_CLASS_EXTRACT, len ? len : 1);
+ if (!text) {
+ return te_oom(c);
+ }
+ size_t copied = 0;
+ cbm_pinned_tree_error_t error;
+ cbm_pinned_tree_status_t status =
+ cbm_pinned_tree_read_prefix(c->tree, rows[i].file_index, file->content_length, text,
+ len, &copied, &control, &error);
+ bool ok = status == CBM_PINNED_TREE_OK && copied == len &&
+ cbm_ti_source_add(c->source, path, (const char *)text, len);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, text);
+ if (!ok) {
+ return te_snapshot_fail(c, CBM_TEST_RESULT_FALLBACK_GRAPH_UNAVAILABLE,
+ "reading HEAD sources failed", path);
+ }
+ }
+ return cbm_ti_source_finish(c->source) || te_oom(c);
+}
+
+bool te_snapshot(te_ctx_t *c) {
+ char *config_bytes = NULL;
+ size_t config_len = 0;
+ c->snapshot_ok = te_pin(c) && te_inventory(c) &&
+ te_head_config(c, &config_bytes, &config_len) &&
+ te_ledger_and_registry(c, config_bytes, config_len) &&
+ te_frozen_build(c, config_bytes, config_len) && te_source_index(c);
+ return c->snapshot_ok;
+}
+
+static void te_remove(const char *path) {
+ if (path && *path) {
+ (void)cbm_unlink(path);
+ }
+}
+
+void te_snapshot_free(te_ctx_t *c) {
+ cbm_ti_source_free(c->source);
+ cbm_ti_graph_free(c->graph);
+ if (c->store) {
+ cbm_store_close(c->store);
+ }
+ cbm_test_model_free(c->model);
+ cbm_test_declarations_free(c->declarations);
+ cbm_test_impact_ledger_free(c->ledger);
+ cbm_test_impact_inventory_free(c->inventory);
+ if (c->tree) {
+ cbm_pinned_tree_error_t error;
+ (void)cbm_pinned_tree_close(&c->tree, &error);
+ }
+ if (c->candidate_db[0]) {
+ char side[4200];
+ te_remove(c->candidate_db);
+ snprintf(side, sizeof(side), "%s-wal", c->candidate_db);
+ te_remove(side);
+ snprintf(side, sizeof(side), "%s-shm", c->candidate_db);
+ te_remove(side);
+ }
+ if (c->work_dir[0]) {
+ char sub[4200];
+ snprintf(sub, sizeof(sub), "%s/graph", c->work_dir);
+ (void)cbm_rmdir(sub);
+ snprintf(sub, sizeof(sub), "%s/pin", c->work_dir);
+ (void)cbm_rmdir(sub);
+ (void)cbm_rmdir(c->work_dir);
+ }
+}
diff --git a/src/mcp/test_impact_git.c b/src/mcp/test_impact_git.c
index 75620e2f8..299ae03f2 100644
--- a/src/mcp/test_impact_git.c
+++ b/src/mcp/test_impact_git.c
@@ -98,9 +98,7 @@ static bool gf_limit(cbm_git_facts_t *facts, cbm_git_facts_error_t *error, const
static size_t gf_input_length(const char *text) {
if (!text)
return SIZE_MAX;
- size_t n = 0;
- while (n <= GF_INPUT_MAX && text[n])
- n++;
+ size_t n = strnlen(text, (size_t)GF_INPUT_MAX + 1);
return n <= GF_INPUT_MAX ? n : SIZE_MAX;
}
@@ -171,8 +169,8 @@ static void *gf_allocate(cbm_git_facts_t *facts, CBMArena *arena, size_t size,
return out;
}
-static bool gf_metadata_equal(cbm_git_facts_t *facts, const char *a, const char *b,
- bool *equal, cbm_git_facts_error_t *error) {
+static bool gf_metadata_equal(cbm_git_facts_t *facts, const char *a, const char *b, bool *equal,
+ cbm_git_facts_error_t *error) {
if (!facts->batch_budget) {
*equal = strcmp(a, b) == 0;
return true;
@@ -287,12 +285,12 @@ static bool gf_private_directory(cbm_git_facts_t *facts, char path[GF_PATH_CAP],
int n = snprintf(path, GF_PATH_CAP, "%s/cbm-git-facts-%s", tmp, suffix);
if (n < 0 || n >= GF_PATH_CAP)
break;
- wchar_t *wide = cbm_path_to_wide(path);
+ wchar_t *wide = cbm_path_to_wide_in(CBM_MEM_CLASS_OTHER, path);
if (!wide)
break;
created = CreateDirectoryW(wide, &attributes) != 0;
DWORD why = GetLastError();
- free(wide); /* existing UTF-8 conversion helper owns this buffer */
+ cbm_free(CBM_MEM_CLASS_OTHER, wide);
if (created || (why != ERROR_ALREADY_EXISTS && why != ERROR_FILE_EXISTS))
break;
}
@@ -474,8 +472,8 @@ static void gf_command_diagnostic(cbm_git_facts_error_t *error, const gf_result_
/* Observed file-size limits request cancellation. They are not instantaneous
* disk quotas; final retained bytes are bounded independently after quiescence. */
static bool gf_run_input(cbm_git_facts_t *facts, const char *const *arguments, int count,
- bool allow_exit_one, const cbm_git_bytes_t *input,
- gf_result_t *out, cbm_git_facts_error_t *error) {
+ bool allow_exit_one, const cbm_git_bytes_t *input, gf_result_t *out,
+ cbm_git_facts_error_t *error) {
memset(out, 0, sizeof(*out));
out->exit_code = -1;
if (!gf_gate(facts, error))
@@ -572,8 +570,7 @@ static bool gf_run_input(cbm_git_facts_t *facts, const char *const *arguments, i
}
/* New batches classify a known command failure before cleanup. Cleanup
* must not replace an established error; legacy calls keep their ordering. */
- if (ok && facts->batch_budget &&
- !(result.outcome == CBM_PROC_CLEAN && result.exit_code == 0) &&
+ if (ok && facts->batch_budget && !(result.outcome == CBM_PROC_CLEAN && result.exit_code == 0) &&
!(allow_exit_one && result.outcome == CBM_PROC_EXIT_NONZERO && result.exit_code == 1)) {
ok = gf_error(error, CBM_GIT_FACTS_COMMAND, "Git command failed");
gf_command_diagnostic(error, &captured);
@@ -621,8 +618,8 @@ static bool gf_line(const cbm_git_bytes_t *bytes, const unsigned char **text, si
}
static bool gf_active_line(cbm_git_facts_t *facts, const cbm_git_bytes_t *bytes,
- const unsigned char **text, size_t *length,
- cbm_git_facts_error_t *error) {
+ const unsigned char **text, size_t *length,
+ cbm_git_facts_error_t *error) {
if (!facts->batch_budget)
return gf_line(bytes, text, length) ||
gf_error(error, CBM_GIT_FACTS_COMMAND, "Malformed Git metadata line");
@@ -754,14 +751,14 @@ static bool gf_topology_guard(cbm_git_facts_t *facts, cbm_git_facts_error_t *err
* No graft parsing or environment mutation; uncertain files block proof. */
static bool gf_history_file_absent_or_empty(const char *path, cbm_git_facts_error_t *error) {
#ifdef _WIN32
- wchar_t *wide = cbm_path_to_wide(path);
+ wchar_t *wide = cbm_path_to_wide_in(CBM_MEM_CLASS_OTHER, path);
if (!wide)
return gf_error(error, CBM_GIT_FACTS_IO, "Cannot inspect Git history override path");
HANDLE file =
CreateFileW(wide, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);
DWORD open_error = GetLastError();
- free(wide);
+ cbm_free(CBM_MEM_CLASS_OTHER, wide);
if (file == INVALID_HANDLE_VALUE) {
if (open_error == ERROR_FILE_NOT_FOUND || open_error == ERROR_PATH_NOT_FOUND)
return true;
@@ -804,8 +801,8 @@ static bool gf_history_guard(cbm_git_facts_t *facts, cbm_git_facts_error_t *erro
for (int i = 0; i < 2; i++) {
if (i == 1) {
bool equal;
- if (!gf_metadata_equal(facts, facts->graft_paths[0], facts->graft_paths[1],
- &equal, error))
+ if (!gf_metadata_equal(facts, facts->graft_paths[0], facts->graft_paths[1], &equal,
+ error))
return false;
if (equal)
continue;
@@ -1143,15 +1140,14 @@ static bool gf_inventory_compare(cbm_git_facts_t *facts, const cbm_git_tree_entr
}
at += chunk;
}
- *comparison = a->path_length < b->path_length ? -1 :
- a->path_length > b->path_length ? 1 : 0;
+ *comparison = a->path_length < b->path_length ? -1 : a->path_length > b->path_length ? 1 : 0;
return true;
}
/* In-place heapsort: deterministic byte order, no recursive stack or hidden
* allocation, and request gates during comparisons and each extraction. */
-static bool gf_inventory_sift(cbm_git_facts_t *facts, cbm_git_tree_entry_t *entries,
- size_t root, size_t count, cbm_git_facts_error_t *error) {
+static bool gf_inventory_sift(cbm_git_facts_t *facts, cbm_git_tree_entry_t *entries, size_t root,
+ size_t count, cbm_git_facts_error_t *error) {
while (root < count / 2) {
size_t child = root * 2 + 1;
int cmp;
@@ -1173,8 +1169,8 @@ static bool gf_inventory_sift(cbm_git_facts_t *facts, cbm_git_tree_entry_t *entr
return true;
}
-static bool gf_inventory_sort(cbm_git_facts_t *facts, cbm_git_tree_entry_t *entries,
- size_t count, cbm_git_facts_error_t *error) {
+static bool gf_inventory_sort(cbm_git_facts_t *facts, cbm_git_tree_entry_t *entries, size_t count,
+ cbm_git_facts_error_t *error) {
for (size_t i = count / 2; i > 0; i--)
if (!gf_inventory_sift(facts, entries, i - 1, count, error))
return false;
@@ -1198,7 +1194,7 @@ static bool gf_inventory_sort(cbm_git_facts_t *facts, cbm_git_tree_entry_t *entr
}
bool cbm_git_facts_inventory(cbm_git_facts_t *facts, cbm_git_revision_t revision,
- cbm_git_tree_inventory_t *out, cbm_git_facts_error_t *error) {
+ cbm_git_tree_inventory_t *out, cbm_git_facts_error_t *error) {
cbm_git_facts_error_t local;
if (!error)
error = &local;
@@ -1445,8 +1441,7 @@ static bool gf_ancestor_names_valid(cbm_git_facts_t *facts, const cbm_git_bytes_
if (!gf_gate(facts, error))
return false;
if (bytes->length - at < 3 || bytes->data[at + 1] != '\0')
- return gf_error(error, CBM_GIT_FACTS_COMMAND,
- "Malformed ancestor changed-path record");
+ return gf_error(error, CBM_GIT_FACTS_COMMAND, "Malformed ancestor changed-path record");
unsigned char status = bytes->data[at];
if (status != 'A' && status != 'M' && status != 'D' && status != 'T')
return gf_error(error, CBM_GIT_FACTS_COMMAND,
@@ -1471,8 +1466,7 @@ static bool gf_ancestor_names_valid(cbm_git_facts_t *facts, const cbm_git_bytes_
at += chunk;
}
if (!terminated)
- return gf_error(error, CBM_GIT_FACTS_COMMAND,
- "Truncated ancestor changed-path record");
+ return gf_error(error, CBM_GIT_FACTS_COMMAND, "Truncated ancestor changed-path record");
if (!gf_gate(facts, error) ||
!gf_inventory_path(facts, bytes->data + start, end - start, error))
return false;
@@ -1483,7 +1477,7 @@ static bool gf_ancestor_names_valid(cbm_git_facts_t *facts, const cbm_git_bytes_
/* merge-base accepts peeled tags. Check the object itself before ancestry so
* a full tag OID cannot silently stand in for the admitted artifact commit. */
static bool gf_ancestor_commit_type(cbm_git_facts_t *facts, const char *oid,
- cbm_git_facts_error_t *error) {
+ cbm_git_facts_error_t *error) {
const char *args[] = {"cat-file", "-t", oid};
gf_result_t result;
if (!gf_run(facts, args, 3, false, &result, error))
@@ -1493,8 +1487,7 @@ static bool gf_ancestor_commit_type(cbm_git_facts_t *facts, const char *oid,
/* The longest supported response is "commit\r\n". Reject a large malformed
* response without an unbounded scan through gf_line's line checks. */
if (result.out.length > 8 || !gf_line(&result.out, &type, &length))
- return gf_error(error, CBM_GIT_FACTS_COMMAND,
- "Malformed artifact object-type response");
+ return gf_error(error, CBM_GIT_FACTS_COMMAND, "Malformed artifact object-type response");
if (length == 6 && memcmp(type, "commit", 6) == 0)
return true;
if ((length == 4 && (memcmp(type, "tree", 4) == 0 || memcmp(type, "blob", 4) == 0)) ||
@@ -1504,11 +1497,11 @@ static bool gf_ancestor_commit_type(cbm_git_facts_t *facts, const char *oid,
return gf_error(error, CBM_GIT_FACTS_COMMAND, "Unknown artifact object-type response");
}
-cbm_git_ancestor_changes_status_t cbm_git_facts_ancestor_changes(
- cbm_git_facts_t *facts,
- const char *artifact_oid, size_t artifact_oid_length,
- cbm_git_bytes_t *name_status,
- cbm_git_facts_error_t *error) {
+cbm_git_ancestor_changes_status_t cbm_git_facts_ancestor_changes(cbm_git_facts_t *facts,
+ const char *artifact_oid,
+ size_t artifact_oid_length,
+ cbm_git_bytes_t *name_status,
+ cbm_git_facts_error_t *error) {
cbm_git_facts_error_t local;
if (!error)
error = &local;
@@ -1528,8 +1521,7 @@ cbm_git_ancestor_changes_status_t cbm_git_facts_ancestor_changes(
if (strcmp(ancestor, facts->identity.merge_base) != 0) {
if (!gf_ancestor_commit_type(facts, ancestor, error))
return CBM_GIT_ANCESTOR_CHANGES_ERROR;
- const char *args[] = {"merge-base", "--is-ancestor", ancestor,
- facts->identity.merge_base};
+ const char *args[] = {"merge-base", "--is-ancestor", ancestor, facts->identity.merge_base};
gf_result_t result;
if (!gf_run(facts, args, 4, true, &result, error))
return CBM_GIT_ANCESTOR_CHANGES_ERROR;
@@ -1558,8 +1550,8 @@ cbm_git_ancestor_changes_status_t cbm_git_facts_ancestor_changes(
"--"};
gf_result_t result;
if (!gf_run(facts, names, (int)(sizeof(names) / sizeof(names[0])), false, &result, error) ||
- !gf_ancestor_names_valid(facts, &result.out, error) ||
- !gf_history_guard(facts, error) || !gf_gate(facts, error))
+ !gf_ancestor_names_valid(facts, &result.out, error) || !gf_history_guard(facts, error) ||
+ !gf_gate(facts, error))
return CBM_GIT_ANCESTOR_CHANGES_ERROR;
*name_status = result.out;
return CBM_GIT_ANCESTOR_CHANGES_OK;
@@ -1604,8 +1596,7 @@ static bool gf_batch_gate(cbm_git_facts_t *facts, cbm_git_facts_error_t *error)
static bool gf_batch_limit(cbm_git_facts_t *facts, cbm_git_facts_error_t *error,
const char *message) {
- return facts ? gf_limit(facts, error, message) :
- gf_error(error, CBM_GIT_FACTS_LIMIT, message);
+ return facts ? gf_limit(facts, error, message) : gf_error(error, CBM_GIT_FACTS_LIMIT, message);
}
static bool gf_batch_canonical_oid(const char *oid, size_t width) {
@@ -1625,9 +1616,8 @@ typedef struct {
/* Continue validating digits after overflow so a malformed suffix is never
* mistaken for a valid huge size. Header length includes its terminal LF. */
-static bool gf_batch_header(cbm_git_facts_t *facts, cbm_git_bytes_t capture,
- const char *oid, size_t width, gf_batch_header_t *header,
- cbm_git_facts_error_t *error) {
+static bool gf_batch_header(cbm_git_facts_t *facts, cbm_git_bytes_t capture, const char *oid,
+ size_t width, gf_batch_header_t *header, cbm_git_facts_error_t *error) {
*header = (gf_batch_header_t){0};
if (!gf_batch_gate(facts, error))
return false;
@@ -1658,9 +1648,8 @@ static bool gf_batch_header(cbm_git_facts_t *facts, cbm_git_bytes_t capture,
return true;
}
-static bool gf_batch_payload(cbm_git_facts_t *facts, cbm_git_bytes_t capture,
- size_t *offset, size_t size, cbm_git_bytes_t *bytes,
- cbm_git_facts_error_t *error) {
+static bool gf_batch_payload(cbm_git_facts_t *facts, cbm_git_bytes_t capture, size_t *offset,
+ size_t size, cbm_git_bytes_t *bytes, cbm_git_facts_error_t *error) {
if (size >= capture.length - *offset)
return gf_error(error, CBM_GIT_FACTS_COMMAND, "Truncated Git batch payload");
size_t start = *offset;
@@ -1688,15 +1677,15 @@ static bool gf_batch_capture(cbm_git_facts_t *facts, cbm_git_bytes_t capture,
if (!gf_batch_gate(facts, error))
return false;
const char *oid = frames->objects ? frames->objects[i].oid : frames->oids[i];
- cbm_git_bytes_t remaining = {capture.data ? capture.data + at : NULL,
- capture.length - at};
+ cbm_git_bytes_t remaining = {capture.data ? capture.data + at : NULL, capture.length - at};
gf_batch_header_t header;
if (!gf_batch_header(facts, remaining, oid, frames->width, &header, error))
return false;
size_t size = header.size;
bool check_size = frames->sizes || (frames->objects && frames->has_payload);
- size_t expected = frames->sizes ? frames->sizes[i] :
- frames->objects ? frames->objects[i].size : 0;
+ size_t expected = frames->sizes ? frames->sizes[i]
+ : frames->objects ? frames->objects[i].size
+ : 0;
if (check_size && size != expected)
return gf_error(error, CBM_GIT_FACTS_COMMAND, "Git batch size changed after preflight");
at += header.length;
@@ -1740,8 +1729,8 @@ bool cbm_git_facts_test_batch_header(cbm_git_bytes_t capture, const char *expect
bool cbm_git_facts_test_batch_capture(cbm_git_bytes_t capture, size_t oid_hex_length,
const char *const *expected_oids,
- const size_t *expected_sizes, size_t count,
- bool has_payload, cbm_git_facts_error_t *error) {
+ const size_t *expected_sizes, size_t count, bool has_payload,
+ cbm_git_facts_error_t *error) {
cbm_git_facts_error_t local;
if (!error)
error = &local;
@@ -1753,8 +1742,10 @@ bool cbm_git_facts_test_batch_capture(cbm_git_bytes_t capture, size_t oid_hex_le
for (size_t i = 0; i < count; i++)
if (!gf_batch_canonical_oid(expected_oids[i], oid_hex_length))
return gf_error(error, CBM_GIT_FACTS_INVALID, "Invalid expected Git batch object ID");
- gf_batch_frames_t frames = {.width = oid_hex_length, .count = count,
- .oids = expected_oids, .sizes = expected_sizes,
+ gf_batch_frames_t frames = {.width = oid_hex_length,
+ .count = count,
+ .oids = expected_oids,
+ .sizes = expected_sizes,
.has_payload = has_payload};
return gf_batch_capture(NULL, capture, &frames, error);
}
@@ -1790,8 +1781,7 @@ static bool gf_batch_inventory(gf_batch_work_t *work, cbm_git_facts_error_t *err
return gf_error(error, CBM_GIT_FACTS_INVALID, "Invalid internal pinned inventory cache");
}
-static int gf_batch_pick_compare(const gf_batch_pick_t *a, const gf_batch_pick_t *b,
- size_t width) {
+static int gf_batch_pick_compare(const gf_batch_pick_t *a, const gf_batch_pick_t *b, size_t width) {
int cmp = memcmp(a->entry->oid, b->entry->oid, width);
if (cmp)
return cmp;
@@ -1844,7 +1834,8 @@ static bool gf_batch_selection(gf_batch_work_t *work, cbm_git_facts_error_t *err
return false;
size_t index = work->request->indices[i];
if (index >= work->inventory.count)
- return gf_error(error, CBM_GIT_FACTS_INVALID, "Git batch inventory index is out of range");
+ return gf_error(error, CBM_GIT_FACTS_INVALID,
+ "Git batch inventory index is out of range");
const cbm_git_tree_entry_t *entry = &work->inventory.entries[index];
if (entry->object_type != CBM_GIT_TREE_BLOB ||
(entry->mode != 0100644 && entry->mode != 0100755))
@@ -1857,8 +1848,8 @@ static bool gf_batch_selection(gf_batch_work_t *work, cbm_git_facts_error_t *err
if (!gf_gate(work->facts, error))
return false;
size_t index = work->request->indices[i];
- work->picks[i] = (gf_batch_pick_t){.entry = &work->inventory.entries[index],
- .inventory_index = index, .position = i};
+ work->picks[i] = (gf_batch_pick_t){
+ .entry = &work->inventory.entries[index], .inventory_index = index, .position = i};
}
return gf_batch_sort(work, error);
}
@@ -1908,16 +1899,19 @@ static size_t gf_batch_digits(size_t value) {
return digits;
}
-static bool gf_batch_command(gf_batch_work_t *work, size_t first, size_t count,
- bool payload, cbm_git_facts_error_t *error) {
- const char *args[] = {"cat-file", payload ? "--batch=%(objectname) %(objecttype) %(objectsize)" :
- "--batch-check=%(objectname) %(objecttype) %(objectsize)"};
+static bool gf_batch_command(gf_batch_work_t *work, size_t first, size_t count, bool payload,
+ cbm_git_facts_error_t *error) {
+ const char *args[] = {"cat-file",
+ payload ? "--batch=%(objectname) %(objecttype) %(objectsize)"
+ : "--batch-check=%(objectname) %(objecttype) %(objectsize)"};
cbm_git_bytes_t input = {work->lines + first * work->line_length, count * work->line_length};
gf_result_t result;
if (!gf_run_input(work->facts, args, 2, false, &input, &result, error))
return false;
- gf_batch_frames_t frames = {.width = work->facts->identity.oid_hex_length, .count = count,
- .objects = work->objects + first, .has_payload = payload};
+ gf_batch_frames_t frames = {.width = work->facts->identity.oid_hex_length,
+ .count = count,
+ .objects = work->objects + first,
+ .has_payload = payload};
return gf_batch_capture(work->facts, result.out, &frames, error);
}
@@ -1983,22 +1977,24 @@ static bool gf_batch_publish(gf_batch_work_t *work, cbm_git_blob_batch_t *out,
if (!gf_gate(work->facts, error))
return false;
const gf_batch_pick_t *pick = &work->picks[i];
- items[pick->position] = (cbm_git_blob_batch_item_t){
- .inventory_index = pick->inventory_index, .entry = pick->entry,
- .bytes = work->objects[pick->object_index].bytes};
+ items[pick->position] =
+ (cbm_git_blob_batch_item_t){.inventory_index = pick->inventory_index,
+ .entry = pick->entry,
+ .bytes = work->objects[pick->object_index].bytes};
}
}
if (!gf_history_guard(work->facts, error) || !gf_gate(work->facts, error))
return false;
*out = (cbm_git_blob_batch_t){.revision = work->request->revision,
.commit = gf_revision(work->facts, work->request->revision),
- .items = items, .count = count};
+ .items = items,
+ .count = count};
return true;
}
static bool gf_batch_execute(cbm_git_facts_t *facts, const cbm_git_blob_batch_request_t *request,
- const cbm_git_blob_batch_limits_t *limits,
- cbm_git_blob_batch_t *out, cbm_git_facts_error_t *error) {
+ const cbm_git_blob_batch_limits_t *limits, cbm_git_blob_batch_t *out,
+ cbm_git_facts_error_t *error) {
if (!gf_history_guard(facts, error))
return false;
if (request->count > limits->max_entries || request->count > SIZE_MAX / sizeof(size_t) ||
@@ -2025,8 +2021,8 @@ bool cbm_git_facts_read_blob_batch(cbm_git_facts_t *facts,
gf_error_clear(error);
if (out)
memset(out, 0, sizeof(*out));
- if (!facts || !request || !limits || !out || !limits->max_entries ||
- !limits->max_input_bytes || !limits->max_arena_bytes ||
+ if (!facts || !request || !limits || !out || !limits->max_entries || !limits->max_input_bytes ||
+ !limits->max_arena_bytes ||
(request->revision != CBM_GIT_REV_HEAD && request->revision != CBM_GIT_REV_MERGE_BASE) ||
(request->count && !request->indices) || facts->batch_budget)
return gf_error(error, CBM_GIT_FACTS_INVALID, "Invalid pinned Git blob batch request");
diff --git a/src/mcp/test_impact_git.h b/src/mcp/test_impact_git.h
index d0b5c9d33..b15523129 100644
--- a/src/mcp/test_impact_git.h
+++ b/src/mcp/test_impact_git.h
@@ -89,10 +89,7 @@ typedef struct {
size_t length;
} cbm_git_bytes_t;
-typedef enum {
- CBM_GIT_TREE_BLOB = 1,
- CBM_GIT_TREE_COMMIT = 2
-} cbm_git_tree_object_type_t;
+typedef enum { CBM_GIT_TREE_BLOB = 1, CBM_GIT_TREE_COMMIT = 2 } cbm_git_tree_object_type_t;
typedef struct {
const char *path; /* owned NUL-terminated bytes; path_length is authoritative */
@@ -117,7 +114,7 @@ typedef struct {
* Empty success is {NULL,0}; every failure clears out. All data lives until
* facts_free. Existing guards, cancellation/deadline and query budgets apply. */
bool cbm_git_facts_inventory(cbm_git_facts_t *facts, cbm_git_revision_t revision,
- cbm_git_tree_inventory_t *out, cbm_git_facts_error_t *error);
+ cbm_git_tree_inventory_t *out, cbm_git_facts_error_t *error);
typedef struct {
cbm_git_bytes_t bytes;
@@ -173,28 +170,29 @@ typedef enum {
CBM_GIT_ANCESTOR_CHANGES_OK = 1
} cbm_git_ancestor_changes_status_t;
-cbm_git_ancestor_changes_status_t cbm_git_facts_ancestor_changes(
- cbm_git_facts_t *facts,
- const char *artifact_oid, size_t artifact_oid_length,
- cbm_git_bytes_t *name_status,
- cbm_git_facts_error_t *error);
+cbm_git_ancestor_changes_status_t cbm_git_facts_ancestor_changes(cbm_git_facts_t *facts,
+ const char *artifact_oid,
+ size_t artifact_oid_length,
+ cbm_git_bytes_t *name_status,
+ cbm_git_facts_error_t *error);
typedef struct {
cbm_git_revision_t revision; /* HEAD or actual MERGE_BASE; BASE is INVALID */
- const size_t *indices; /* indices into that revision's canonical pinned inventory */
+ const size_t *indices; /* indices into that revision's canonical pinned inventory */
size_t count; /* duplicates allowed; NULL indices allowed exactly when count==0 */
} cbm_git_blob_batch_request_t;
typedef struct {
- size_t max_entries; /* positive; bounds request.count, including duplicates */
+ size_t max_entries; /* positive; bounds request.count, including duplicates */
size_t max_input_bytes; /* positive; cumulative OID+LF stdin bytes for this call */
- size_t max_arena_bytes; /* positive; all Git-facts-owned logical arena requests during this call */
+ size_t
+ max_arena_bytes; /* positive; all Git-facts-owned logical arena requests during this call */
} cbm_git_blob_batch_limits_t;
typedef struct {
size_t inventory_index;
const cbm_git_tree_entry_t *entry; /* facts-owned canonical path/mode/type/OID */
- cbm_git_bytes_t bytes; /* exact blob contents; NOT promised NUL-terminated */
+ cbm_git_bytes_t bytes; /* exact blob contents; NOT promised NUL-terminated */
} cbm_git_blob_batch_item_t;
typedef struct {
@@ -243,11 +241,9 @@ typedef struct {
* the whole capture directory, including stdin, under existing diagnostics.
* No legacy read_blob/inventory/diff/ancestor-change semantics are changed. */
bool cbm_git_facts_read_blob_batch(cbm_git_facts_t *facts,
- const cbm_git_blob_batch_request_t *request,
- const cbm_git_blob_batch_limits_t *limits,
- cbm_git_blob_batch_t *out,
- cbm_git_facts_error_t *error);
-
+ const cbm_git_blob_batch_request_t *request,
+ const cbm_git_blob_batch_limits_t *limits,
+ cbm_git_blob_batch_t *out, cbm_git_facts_error_t *error);
#ifdef CBM_ENABLE_TEST_SEAMS
/* Deterministic wrappers around the actual production header/frame parsers.
@@ -259,17 +255,15 @@ bool cbm_git_facts_read_blob_batch(cbm_git_facts_t *facts,
* be NULL (unknown); otherwise each parsed size must match expected_sizes[i].
* Payload mode requires expected_sizes for nonzero count. Empty capture/count
* is valid. Bad pointer/width arguments are INVALID. No partial output views. */
-bool cbm_git_facts_test_batch_header(cbm_git_bytes_t capture,
- const char *expected_oid, size_t oid_hex_length,
- size_t *object_size, size_t *header_length,
- cbm_git_facts_error_t *error);
+bool cbm_git_facts_test_batch_header(cbm_git_bytes_t capture, const char *expected_oid,
+ size_t oid_hex_length, size_t *object_size,
+ size_t *header_length, cbm_git_facts_error_t *error);
bool cbm_git_facts_test_batch_capture(cbm_git_bytes_t capture, size_t oid_hex_length,
- const char *const *expected_oids,
- const size_t *expected_sizes, size_t count,
- bool has_payload, cbm_git_facts_error_t *error);
+ const char *const *expected_oids,
+ const size_t *expected_sizes, size_t count, bool has_payload,
+ cbm_git_facts_error_t *error);
#endif
-
/* Local Git identity/content does not authenticate a coverage artifact or
* establish that any index/graph generation covers this snapshot. */
#endif
diff --git a/src/mcp/test_impact_inventory.c b/src/mcp/test_impact_inventory.c
index 5f853d456..eea5dbebd 100644
--- a/src/mcp/test_impact_inventory.c
+++ b/src/mcp/test_impact_inventory.c
@@ -137,6 +137,9 @@ static bool cni_delegate(cni_context *c, cbm_pinned_tree_t *tree, cbm_inventory_
cbm_inventory_error_t error;
cbm_inventory_status_t status =
cbm_inventory_filter_prepare(source, &limits, c->control, &owner->filter, &error);
+ /* The reader lives in this frame; the caller's source must not keep it. */
+ source->read = NULL;
+ source->read_context = NULL;
/* The filter owns all successful metadata; this release never refunds A. */
cbm_arena_destroy(&c->temporary);
if (status != CBM_INVENTORY_OK) {
diff --git a/src/mcp/test_impact_inventory.h b/src/mcp/test_impact_inventory.h
index 0f40a7d1e..8e275d8b8 100644
--- a/src/mcp/test_impact_inventory.h
+++ b/src/mcp/test_impact_inventory.h
@@ -13,8 +13,8 @@ typedef struct cbm_test_impact_inventory cbm_test_impact_inventory_t;
typedef struct {
size_t attachment_arena_requested_bytes; /* A, including freed temporary inputs. */
cbm_inventory_filter_usage_t filter; /* Existing D/C/I and read/work ledgers. */
- size_t arena_requested_bytes; /* A+D+C, actual logical requests. */
- size_t arena_budget_used_bytes; /* A+D+I, unavailable quota. */
+ size_t arena_requested_bytes; /* A+D+C, actual logical requests. */
+ size_t arena_budget_used_bytes; /* A+D+I, unavailable quota. */
} cbm_test_impact_inventory_usage_t;
/* Synchronous HEAD-only bridge from the complete READY native inventory.
@@ -26,10 +26,11 @@ typedef struct {
* Failure publishes NULL; native disposal remains caller-owned, including
* after a read makes the native owner disposal-only. No automatic retry.
*/
-cbm_inventory_status_t cbm_test_impact_inventory_prepare(
- cbm_pinned_tree_t *tree, const cbm_inventory_limits_t *limits,
- const cbm_inventory_control_t *control, cbm_test_impact_inventory_t **out,
- cbm_inventory_error_t *error);
+cbm_inventory_status_t cbm_test_impact_inventory_prepare(cbm_pinned_tree_t *tree,
+ const cbm_inventory_limits_t *limits,
+ const cbm_inventory_control_t *control,
+ cbm_test_impact_inventory_t **out,
+ cbm_inventory_error_t *error);
/* Existing filter view, borrowed until wrapper free; NULL for NULL owner.
* NEEDS_LANGUAGE survivors remain unfinished. No IO/poll/allocation.
@@ -42,9 +43,9 @@ const cbm_inventory_filter_view_t *cbm_test_impact_inventory_view(
* The wrapped filter privately received T-A with unchanged I exactly once.
*/
bool cbm_test_impact_inventory_usage(const cbm_test_impact_inventory_t *owner,
- cbm_test_impact_inventory_usage_t *out);
+ cbm_test_impact_inventory_usage_t *out);
bool cbm_test_impact_inventory_limits(const cbm_test_impact_inventory_t *owner,
- cbm_inventory_limits_t *out);
+ cbm_inventory_limits_t *out);
/* NULL-safe. Frees the wrapped filter, then wrapper arena. No native IO,
* callbacks or tree disposal. Cannot overlap getters or another operation.
diff --git a/src/mcp/test_impact_origins.c b/src/mcp/test_impact_origins.c
index 158137252..dc8f9d6f8 100644
--- a/src/mcp/test_impact_origins.c
+++ b/src/mcp/test_impact_origins.c
@@ -278,8 +278,9 @@ static bool or_path(or_work_t *work, cbm_coverage_origin_bytes_t path) {
}
if (path.data[offset] == '/') {
size_t length = offset - component;
- if (!length || (path.data[component] == '.' &&
- (length == 1 || (length == 2 && path.data[component + 1] == '.')))) {
+ if (!length ||
+ (path.data[component] == '.' &&
+ (length == 1 || (length == 2 && path.data[component + 1] == '.')))) {
return or_fail(work, CBM_COVERAGE_ORIGIN_FORMAT);
}
component = offset + 1;
@@ -299,11 +300,16 @@ static bool or_path(or_work_t *work, cbm_coverage_origin_bytes_t path) {
static unsigned or_edit(char status) {
switch (status) {
- case 'A': return CBM_COVERAGE_ORIGIN_EDIT_A;
- case 'M': return CBM_COVERAGE_ORIGIN_EDIT_M;
- case 'D': return CBM_COVERAGE_ORIGIN_EDIT_D;
- case 'T': return CBM_COVERAGE_ORIGIN_EDIT_T;
- default: return 0;
+ case 'A':
+ return CBM_COVERAGE_ORIGIN_EDIT_A;
+ case 'M':
+ return CBM_COVERAGE_ORIGIN_EDIT_M;
+ case 'D':
+ return CBM_COVERAGE_ORIGIN_EDIT_D;
+ case 'T':
+ return CBM_COVERAGE_ORIGIN_EDIT_T;
+ default:
+ return 0;
}
}
@@ -551,8 +557,8 @@ static bool or_change_sift(or_work_t *work, or_change_t *rows, size_t count, siz
return true;
}
-static bool or_changes(or_work_t *work, cbm_coverage_origin_bytes_t bytes,
- or_change_t **changes, size_t *change_count) {
+static bool or_changes(or_work_t *work, cbm_coverage_origin_bytes_t bytes, or_change_t **changes,
+ size_t *change_count) {
size_t count = 0, position = 0;
or_change_t ignored;
while (position < bytes.length) {
@@ -602,9 +608,9 @@ static bool or_changes(or_work_t *work, cbm_coverage_origin_bytes_t bytes,
}
static bool or_reconcile(or_work_t *work, const cbm_changes_t *request,
- const cbm_coverage_origin_binding_t *binding,
- const or_change_t *ah, size_t ah_count,
- const or_change_t *mh, size_t mh_count, cbm_changes_state_t *state) {
+ const cbm_coverage_origin_binding_t *binding, const or_change_t *ah,
+ size_t ah_count, const or_change_t *mh, size_t mh_count,
+ cbm_changes_state_t *state) {
size_t count;
const cbm_change_file_t *files = cbm_changes_files(request, &count);
if (count != mh_count || (count && !files)) {
@@ -768,9 +774,9 @@ static bool or_union_ids(or_work_t *work, cbm_coverage_origin_join_t *result) {
}
static bool or_join_paths(or_work_t *work, cbm_coverage_origin_join_t *result,
- const or_claim_t *claims, size_t claim_count,
- const or_change_t *ah, size_t ah_count,
- const or_change_t *mh, size_t mh_count, int function_count) {
+ const or_claim_t *claims, size_t claim_count, const or_change_t *ah,
+ size_t ah_count, const or_change_t *mh, size_t mh_count,
+ int function_count) {
if (ah_count > SIZE_MAX - mh_count) {
return or_fail(work, CBM_COVERAGE_ORIGIN_LIMIT);
}
@@ -785,8 +791,7 @@ static bool or_join_paths(or_work_t *work, cbm_coverage_origin_join_t *result,
return false;
}
int order = ai == ah_count ? 1 : mi == mh_count ? -1 : 0;
- if (ai < ah_count && mi < mh_count &&
- !or_compare(work, ah[ai].path, mh[mi].path, &order)) {
+ if (ai < ah_count && mi < mh_count && !or_compare(work, ah[ai].path, mh[mi].path, &order)) {
return false;
}
cbm_coverage_origin_path_t path = {0};
@@ -824,9 +829,8 @@ static bool or_join_paths(or_work_t *work, cbm_coverage_origin_join_t *result,
path.reasons |= CBM_COVERAGE_ORIGIN_PRESENCE_UNKNOWN;
} else {
bool present_at_a = claim->state >= 2;
- bool expected_present = path.artifact_status
- ? path.artifact_status != 'A'
- : path.merge_base_status != 'D';
+ bool expected_present = path.artifact_status ? path.artifact_status != 'A'
+ : path.merge_base_status != 'D';
if (present_at_a != expected_present) {
return or_fail(work, CBM_COVERAGE_ORIGIN_BINDING);
}
@@ -881,8 +885,8 @@ static int or_hex_digit(unsigned char ch) {
return ch >= 'a' && ch <= 'f' ? ch - 'a' + 10 : -1;
}
-static bool or_map(or_work_t *work, const cbm_coverage_map_t *map,
- const unsigned char expected[32], int *count) {
+static bool or_map(or_work_t *work, const cbm_coverage_map_t *map, const unsigned char expected[32],
+ int *count) {
cbm_coverage_format_t format = cbm_coverage_map_format(map);
if (format != CBM_COVERAGE_FORMAT_FUNCTIONS && format != CBM_COVERAGE_FORMAT_PROFILES) {
return or_fail(work, CBM_COVERAGE_ORIGIN_BINDING);
@@ -922,10 +926,11 @@ static bool or_span_valid(cbm_coverage_origin_bytes_t span) {
return span.data || !span.length;
}
-cbm_coverage_origin_status_t cbm_coverage_origin_join(
- const cbm_coverage_origin_input_t *input, const cbm_coverage_origin_limits_t *limits,
- cbm_coverage_origin_cancel_fn cancelled, void *cancel_context,
- cbm_coverage_origin_join_t **out) {
+cbm_coverage_origin_status_t cbm_coverage_origin_join(const cbm_coverage_origin_input_t *input,
+ const cbm_coverage_origin_limits_t *limits,
+ cbm_coverage_origin_cancel_fn cancelled,
+ void *cancel_context,
+ cbm_coverage_origin_join_t **out) {
if (out) {
*out = NULL;
}
@@ -968,8 +973,10 @@ cbm_coverage_origin_status_t cbm_coverage_origin_join(
}
total += (uint64_t)lengths[i];
}
- or_work_t work = {.limits = *limits, .cancelled = cancelled,
- .cancel_context = cancel_context, .status = CBM_COVERAGE_ORIGIN_OK};
+ or_work_t work = {.limits = *limits,
+ .cancelled = cancelled,
+ .cancel_context = cancel_context,
+ .status = CBM_COVERAGE_ORIGIN_OK};
cbm_arena_init_lazy(&work.arena, 1024);
cbm_coverage_origin_join_t *result;
cbm_coverage_origin_bytes_t manifest, ah_bytes, mh_bytes;
@@ -978,8 +985,7 @@ cbm_coverage_origin_status_t cbm_coverage_origin_join(
size_t claim_count, ah_count, mh_count;
unsigned reasons;
int function_count;
- if (!or_poll(&work) ||
- !or_hash_matches(&work, input->manifest, binding->manifest_sha256) ||
+ if (!or_poll(&work) || !or_hash_matches(&work, input->manifest, binding->manifest_sha256) ||
!or_hash_matches(&work, input->artifact_to_head, context->artifact_to_head_sha256) ||
!or_hash_matches(&work, input->merge_base_to_head, context->merge_base_to_head_sha256) ||
!or_map(&work, input->coverage, binding->functions_sha256, &function_count) ||
@@ -1013,7 +1019,8 @@ cbm_coverage_origin_status_t cbm_coverage_origin_join(
result->reasons |= CBM_COVERAGE_ORIGIN_REQUEST_UNKNOWN;
}
if (!or_join_paths(&work, result, claims, claim_count, ah, ah_count, mh, mh_count,
- function_count) || !or_poll(&work)) {
+ function_count) ||
+ !or_poll(&work)) {
goto failure;
}
result->arena = work.arena;
diff --git a/src/mcp/test_impact_origins.h b/src/mcp/test_impact_origins.h
index 3b19a52bb..754c4475a 100644
--- a/src/mcp/test_impact_origins.h
+++ b/src/mcp/test_impact_origins.h
@@ -49,9 +49,9 @@ typedef struct {
* map and its test observations. A v1 receipt cannot admit a v2 map;
* successful parsing supplies no admission evidence. */
bool artifact_admitted;
- bool origin_source_verified; /* authenticated repository/A/table/manifest tuple */
+ bool origin_source_verified; /* authenticated repository/A/table/manifest tuple */
bool origin_attestations_verified; /* supported producer claim/proof semantics */
- bool comparisons_verified; /* complete same-owner A ancestor of actual M, pinned H */
+ bool comparisons_verified; /* complete same-owner A ancestor of actual M, pinned H */
cbm_coverage_origin_binding_t binding;
unsigned char artifact_to_head_sha256[32];
unsigned char merge_base_to_head_sha256[32];
@@ -68,9 +68,9 @@ typedef struct {
typedef struct {
uint64_t max_input_bytes; /* manifest + AH + MH + context key; <= UINT64_MAX/8 */
- uint64_t max_items; /* decoded records, borrowed map checks and ID visits; see spec */
- size_t max_alloc_bytes; /* cumulative logical arena allocation requests */
- size_t max_result_ids; /* distinct final union cardinality; positive, <= INT_MAX */
+ uint64_t max_items; /* decoded records, borrowed map checks and ID visits; see spec */
+ size_t max_alloc_bytes; /* cumulative logical arena allocation requests */
+ size_t max_result_ids; /* distinct final union cardinality; positive, <= INT_MAX */
} cbm_coverage_origin_limits_t;
typedef bool (*cbm_coverage_origin_cancel_fn)(void *context);
@@ -99,10 +99,7 @@ enum {
CBM_COVERAGE_ORIGIN_EDIT_T = 1u << 3
};
-enum {
- CBM_COVERAGE_ORIGIN_FROM_ARTIFACT = 1u << 0,
- CBM_COVERAGE_ORIGIN_FROM_MERGE_BASE = 1u << 1
-};
+enum { CBM_COVERAGE_ORIGIN_FROM_ARTIFACT = 1u << 0, CBM_COVERAGE_ORIGIN_FROM_MERGE_BASE = 1u << 1 };
enum {
CBM_COVERAGE_ORIGIN_PROFILE_UNIVERSE_UNKNOWN = 1u << 0,
@@ -120,8 +117,8 @@ typedef struct {
char artifact_status; /* A/M/D/T or zero when absent from that comparison */
char merge_base_status;
cbm_coverage_origin_disposition_t disposition; /* UNKNOWN for missing row */
- unsigned supported_edits; /* zero for missing row */
- unsigned reasons; /* local gaps only; global gaps affect overall completeness */
+ unsigned supported_edits; /* zero for missing row */
+ unsigned reasons; /* local gaps only; global gaps affect overall completeness */
const int *function_ids; /* owned ascending unique positive evidence */
size_t function_count;
} cbm_coverage_origin_path_t;
@@ -139,11 +136,11 @@ typedef struct cbm_coverage_origin_join cbm_coverage_origin_join_t;
* owner. Missing evidence is OK/incomplete; malformed input, wrong binding,
* missing admission, cancel, limit and OOM are errors. No inferred identities.
* The adapter MUST use can_narrow, never complete alone. */
-cbm_coverage_origin_status_t cbm_coverage_origin_join(
- const cbm_coverage_origin_input_t *input,
- const cbm_coverage_origin_limits_t *limits,
- cbm_coverage_origin_cancel_fn cancelled, void *cancel_context,
- cbm_coverage_origin_join_t **out);
+cbm_coverage_origin_status_t cbm_coverage_origin_join(const cbm_coverage_origin_input_t *input,
+ const cbm_coverage_origin_limits_t *limits,
+ cbm_coverage_origin_cancel_fn cancelled,
+ void *cancel_context,
+ cbm_coverage_origin_join_t **out);
void cbm_coverage_origin_join_free(cbm_coverage_origin_join_t *join);
/* Views are immutable until join_free; path views may share one owned ALL ID
@@ -161,7 +158,6 @@ bool cbm_coverage_origin_join_broad_fallback_required(const cbm_coverage_origin_
bool cbm_coverage_origin_join_can_narrow(const cbm_coverage_origin_join_t *join);
unsigned cbm_coverage_origin_join_reasons(const cbm_coverage_origin_join_t *join);
/* Preserve cross-checked D4a M->H state. Never derive EMPTY from AH or ID count. */
-cbm_changes_state_t cbm_coverage_origin_join_request_state(
- const cbm_coverage_origin_join_t *join);
+cbm_changes_state_t cbm_coverage_origin_join_request_state(const cbm_coverage_origin_join_t *join);
#endif
diff --git a/src/mcp/test_impact_policy.c b/src/mcp/test_impact_policy.c
index aeb892894..a85cf5c7c 100644
--- a/src/mcp/test_impact_policy.c
+++ b/src/mcp/test_impact_policy.c
@@ -591,6 +591,9 @@ static const char *const tp_ci_paths[] = {".github/**", ".gitlab-ci.yml", ".ci
"Jenkinsfile*", ".buildkite/**", "azure-pipelines*.yml"};
static const char *const tp_vendor_paths[] = {"vendor*/**", "third_party/**"};
static const char *const tp_conftest_paths[] = {"conftest.py"};
+/* The selection's own configuration: a change to it may loosen what it
+ * selects, so it runs everything (smart-ci-design review M-4). */
+static const char *const tp_config_paths[] = {".codebase-memory.json"};
static const char *const tp_documentation_paths[] = {"docs/**", "**/*.md", "LICENSE*"};
typedef struct {
@@ -602,6 +605,8 @@ typedef struct {
#define TP_COUNT(array) (sizeof(array) / sizeof((array)[0]))
static const tp_builtin_t tp_builtins[] = {
+ {"builtin:test-impact-config", CBM_TEST_RULE_RUN_ALL, tp_config_paths,
+ TP_COUNT(tp_config_paths)},
{"builtin:build", CBM_TEST_RULE_RUN_ALL, tp_build_paths, TP_COUNT(tp_build_paths)},
{"builtin:ci", CBM_TEST_RULE_RUN_ALL, tp_ci_paths, TP_COUNT(tp_ci_paths)},
{"builtin:vendor", CBM_TEST_RULE_RUN_ALL, tp_vendor_paths, TP_COUNT(tp_vendor_paths)},
diff --git a/src/mcp/test_impact_result.h b/src/mcp/test_impact_result.h
index 25fcc6d64..f07beb447 100644
--- a/src/mcp/test_impact_result.h
+++ b/src/mcp/test_impact_result.h
@@ -44,6 +44,9 @@ typedef enum {
CBM_TEST_RESULT_FALLBACK_RULE_RUN_ALL,
CBM_TEST_RESULT_FALLBACK_POLICY_EVALUATION_FAILED,
CBM_TEST_RESULT_FALLBACK_TRAVERSAL_POLICY_UNKNOWN,
+ /* The walk reached the test runner's entry point: every suite may run
+ * changed code at start-up (smart-ci-design review M-3). */
+ CBM_TEST_RESULT_FALLBACK_RUNNER_REACHED,
CBM_TEST_RESULT_FALLBACK_COUNT
} cbm_test_result_fallback_t;
diff --git a/src/mcp/test_impact_result_project.c b/src/mcp/test_impact_result_project.c
index 21539432b..01cc334f9 100644
--- a/src/mcp/test_impact_result_project.c
+++ b/src/mcp/test_impact_result_project.c
@@ -82,7 +82,7 @@ static bool tir_lane_plan_build(tir_context *c, size_t index, tir_lane_plan *pla
if (!lane->source->narrow)
plan->reasons |= TIR_REASON(TIR_REASON_NARROW_DISABLED);
if (!c->input->inventory_complete || !c->input->model ||
- !cbm_test_model_complete(c->input->model)) {
+ !cbm_test_model_narrowable(c->input->model)) {
plan->suites = tir_null(c);
return plan->suites != NULL;
}
diff --git a/src/mcp/test_impact_result_rows.c b/src/mcp/test_impact_result_rows.c
index fccbd7d1c..67549df7f 100644
--- a/src/mcp/test_impact_result_rows.c
+++ b/src/mcp/test_impact_result_rows.c
@@ -68,8 +68,10 @@ static bool tir_normalize_suites(tir_context *c) {
if (!tir_sort(c, c->suites, c->suite_count, sizeof(*c->suites), tir_suite_compare))
return false;
size_t used = 0;
- bool known =
- c->input->inventory_complete && c->input->model && cbm_test_model_complete(c->input->model);
+ /* Narrowable, not complete: a suite the model is unsure of arrives whole
+ * in the selection, so only uncertainty it cannot scope is global. */
+ bool known = c->input->inventory_complete && c->input->model &&
+ cbm_test_model_narrowable(c->input->model);
for (size_t i = 0; i < c->suite_count; i++) {
if (!tir_step(c, 0, 1))
return false;
@@ -264,7 +266,7 @@ static void tir_global_floors(tir_context *c) {
c->global |= TIR_FALLBACK(CBM_TEST_RESULT_FALLBACK_ACTIVATION_UNKNOWN);
if (in->comparison != CBM_TEST_RESULT_COMPARISON_CHANGED)
return;
- if (!in->inventory_complete || !in->model || !cbm_test_model_complete(in->model))
+ if (!in->inventory_complete || !in->model || !cbm_test_model_narrowable(in->model))
c->global |= CBM_TEST_SELECT_INVENTORY_UNKNOWN;
if (!in->selection)
c->global |= TIR_FALLBACK(CBM_TEST_RESULT_FALLBACK_SELECTION_UNAVAILABLE);
diff --git a/src/mcp/test_impact_result_wire.c b/src/mcp/test_impact_result_wire.c
index 88d4c5ae8..e8e88f7c8 100644
--- a/src/mcp/test_impact_result_wire.c
+++ b/src/mcp/test_impact_result_wire.c
@@ -32,6 +32,7 @@ static const char *const tir_reason_names[TIR_REASON_COUNT] = {"CHANGED",
"RULE_RUN_ALL",
"POLICY_EVALUATION_FAILED",
"TRAVERSAL_POLICY_UNKNOWN",
+ "RUNNER_REACHED",
"POLICY_INACTIVE",
"NO_CHANGES",
"NO_SELECTED_TESTS",
diff --git a/src/mcp/test_impact_seed.c b/src/mcp/test_impact_seed.c
new file mode 100644
index 000000000..ccade1138
--- /dev/null
+++ b/src/mcp/test_impact_seed.c
@@ -0,0 +1,941 @@
+/*
+ * test_impact_seed.c — what a change seeds in the graph.
+ *
+ * Each step names the lines of the reference (scratchpad tia3/replay4.py) it
+ * ports, so a differential check can be read side by side.
+ */
+#include "mcp/test_impact_seed.h"
+
+#include "foundation/arena.h"
+#include "foundation/hash_table.h"
+#include "foundation/mem_core.h"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* ── Growable arrays (memory core) ───────────────────────────────── */
+
+static bool ts_grow(void **items, int *cap, int count, size_t size) {
+ if (count < *cap) {
+ return true;
+ }
+ int next = *cap ? *cap * 2 : 16;
+ void *grown = cbm_realloc(CBM_MEM_CLASS_EXTRACT, *items, (size_t)next * size);
+ if (!grown) {
+ return false;
+ }
+ *items = grown;
+ *cap = next;
+ return true;
+}
+
+typedef struct {
+ int64_t *items;
+ int count;
+ int cap;
+} ts_ids_t;
+
+typedef struct {
+ int *items;
+ int count;
+ int cap;
+} ts_ints_t;
+
+typedef struct {
+ const char **items;
+ int count;
+ int cap;
+} ts_strs_t;
+
+static bool ts_ids_push(ts_ids_t *a, int64_t v) {
+ if (!ts_grow((void **)&a->items, &a->cap, a->count, sizeof(*a->items))) {
+ return false;
+ }
+ a->items[a->count++] = v;
+ return true;
+}
+
+static bool ts_ints_push(ts_ints_t *a, int v) {
+ if (!ts_grow((void **)&a->items, &a->cap, a->count, sizeof(*a->items))) {
+ return false;
+ }
+ a->items[a->count++] = v;
+ return true;
+}
+
+static bool ts_strs_push(ts_strs_t *a, const char *v) {
+ if (!ts_grow((void **)&a->items, &a->cap, a->count, sizeof(*a->items))) {
+ return false;
+ }
+ a->items[a->count++] = v;
+ return true;
+}
+
+/* ── The graph, per file ─────────────────────────────────────────── */
+
+typedef struct {
+ cbm_ti_node_t *nodes;
+ int count;
+} ts_file_t;
+
+struct cbm_ti_graph {
+ cbm_store_t *store;
+ const char *project;
+ CBMArena arena;
+ CBMHashTable *files; /* path -> ts_file_t* (arena) */
+ CBMHashTable *names; /* name -> 1 present / 2 absent */
+};
+
+static bool ts_seedless(const char *label) {
+ static const char *const seedless[] = {"File", "Folder", "Project", "Module",
+ "Package", "Section", "Route", "Resource"};
+ for (size_t i = 0; i < sizeof(seedless) / sizeof(seedless[0]); i++) {
+ if (label && strcmp(label, seedless[i]) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+cbm_ti_graph_t *cbm_ti_graph_new(cbm_store_t *store, const char *project) {
+ if (!store || !project) {
+ return NULL;
+ }
+ cbm_ti_graph_t *g = cbm_alloc(CBM_MEM_CLASS_EXTRACT, sizeof(*g));
+ if (!g) {
+ return NULL;
+ }
+ memset(g, 0, sizeof(*g));
+ cbm_arena_init(&g->arena);
+ g->store = store;
+ g->project = cbm_arena_strdup(&g->arena, project);
+ g->files = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ g->names = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ if (!g->project || !g->files || !g->names) {
+ cbm_ti_graph_free(g);
+ return NULL;
+ }
+ return g;
+}
+
+void cbm_ti_graph_free(cbm_ti_graph_t *g) {
+ if (!g) {
+ return;
+ }
+ if (g->files) {
+ cbm_ht_free(g->files);
+ }
+ if (g->names) {
+ cbm_ht_free(g->names);
+ }
+ cbm_arena_destroy(&g->arena);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, g);
+}
+
+static int ts_node_compare(const void *left, const void *right) {
+ const cbm_ti_node_t *a = left;
+ const cbm_ti_node_t *b = right;
+ if (a->start_line != b->start_line) {
+ return a->start_line < b->start_line ? -1 : 1;
+ }
+ if (a->end_line != b->end_line) {
+ return a->end_line < b->end_line ? -1 : 1;
+ }
+ return a->id < b->id ? -1 : (a->id > b->id ? 1 : 0);
+}
+
+static ts_file_t *ts_load_file(cbm_ti_graph_t *g, const char *file) {
+ cbm_node_t *rows = NULL;
+ int count = 0;
+ if (cbm_store_find_nodes_by_file(g->store, g->project, file, &rows, &count) != CBM_STORE_OK) {
+ return NULL;
+ }
+ ts_file_t *f = cbm_arena_calloc(&g->arena, sizeof(*f));
+ cbm_ti_node_t *nodes = cbm_arena_alloc(&g->arena, (size_t)(count ? count : 1) * sizeof(*nodes));
+ const char *key = cbm_arena_strdup(&g->arena, file);
+ bool ok = f && nodes && key;
+ int kept = 0;
+ for (int i = 0; ok && i < count; i++) {
+ if (ts_seedless(rows[i].label)) {
+ continue;
+ }
+ cbm_ti_node_t *n = &nodes[kept++];
+ n->id = rows[i].id;
+ n->label = cbm_arena_strdup(&g->arena, rows[i].label ? rows[i].label : "");
+ n->name = cbm_arena_strdup(&g->arena, rows[i].name ? rows[i].name : "");
+ n->qualified_name =
+ cbm_arena_strdup(&g->arena, rows[i].qualified_name ? rows[i].qualified_name : "");
+ n->start_line = rows[i].start_line;
+ n->end_line = rows[i].end_line;
+ ok = n->label && n->name && n->qualified_name;
+ }
+ cbm_store_free_nodes(rows, count);
+ if (!ok) {
+ return NULL;
+ }
+ if (kept > 1) {
+ qsort(nodes, (size_t)kept, sizeof(*nodes), ts_node_compare);
+ }
+ f->nodes = nodes;
+ f->count = kept;
+ cbm_ht_set(g->files, key, f);
+ return f;
+}
+
+const cbm_ti_node_t *cbm_ti_graph_file(cbm_ti_graph_t *g, const char *file, int *count, bool *ok) {
+ *count = 0;
+ *ok = g && file;
+ if (!*ok) {
+ return NULL;
+ }
+ ts_file_t *f = cbm_ht_get(g->files, file);
+ if (!f) {
+ f = ts_load_file(g, file);
+ }
+ if (!f) {
+ *ok = false;
+ return NULL;
+ }
+ *count = f->count;
+ return f->nodes;
+}
+
+/* replay4 `_enclosing`: the smallest span containing the line; among equal
+ * spans the first in id order (the reference iterates the store's rows). */
+const cbm_ti_node_t *cbm_ti_graph_enclosing(cbm_ti_graph_t *g, const char *file, int line,
+ bool *ok) {
+ int count = 0;
+ const cbm_ti_node_t *nodes = cbm_ti_graph_file(g, file, &count, ok);
+ const cbm_ti_node_t *best = NULL;
+ for (int i = 0; i < count; i++) {
+ const cbm_ti_node_t *n = &nodes[i];
+ if (n->start_line > line || n->end_line < line) {
+ continue;
+ }
+ int span = n->end_line - n->start_line;
+ int best_span = best ? best->end_line - best->start_line : 0;
+ if (!best || span < best_span || (span == best_span && n->id < best->id)) {
+ best = n;
+ }
+ }
+ return best;
+}
+
+bool cbm_ti_graph_has_name(cbm_ti_graph_t *g, const char *name, bool *ok) {
+ *ok = g && name;
+ if (!*ok) {
+ return false;
+ }
+ intptr_t known = (intptr_t)cbm_ht_get(g->names, name);
+ if (known) {
+ return known == 1;
+ }
+ cbm_node_t *rows = NULL;
+ int count = 0;
+ if (cbm_store_find_nodes_by_name(g->store, g->project, name, &rows, &count) != CBM_STORE_OK) {
+ *ok = false;
+ return false;
+ }
+ cbm_store_free_nodes(rows, count);
+ const char *key = cbm_arena_strdup(&g->arena, name);
+ if (!key) {
+ *ok = false;
+ return false;
+ }
+ cbm_ht_set(g->names, key, (void *)(intptr_t)(count > 0 ? 1 : 2));
+ return count > 0;
+}
+
+/* ── The seeding state ───────────────────────────────────────────── */
+
+struct cbm_ti_seeds {
+ CBMArena arena;
+ ts_ids_t nodes;
+ ts_ints_t cases;
+ ts_ints_t suites;
+ ts_strs_t file_level;
+ ts_strs_t deleted;
+};
+
+typedef struct {
+ const cbm_ti_seed_input_t *in;
+ cbm_ti_seeds_t *out;
+ CBMHashTable *seen_nodes; /* "id" -> 1 */
+ CBMHashTable *whole; /* path -> 1 */
+ ts_strs_t whole_list; /* paths in insertion order */
+ CBMHashTable *deleted; /* name -> 1 */
+ CBMHashTable *case_index; /* "file\x1fname" -> case index + 1 */
+ CBMHashTable *suite_index; /* "file\x1fname" -> suite index + 1 */
+ CBMHashTable *changed_path; /* path -> 1 */
+ bool *case_changed;
+ bool *suite_changed;
+ int case_count;
+ int suite_count;
+ cbm_ti_seed_status_t status;
+} ts_state_t;
+
+static bool ts_fail(ts_state_t *st, cbm_ti_seed_status_t status) {
+ if (st->status == CBM_TI_SEED_OK) {
+ st->status = status;
+ }
+ return false;
+}
+
+static const char *ts_key(ts_state_t *st, const char *file, const char *name) {
+ size_t a = strlen(file);
+ size_t b = strlen(name);
+ char *key = cbm_arena_alloc(&st->out->arena, a + b + 2);
+ if (!key) {
+ return NULL;
+ }
+ memcpy(key, file, a);
+ key[a] = '\x1f';
+ memcpy(key + a + 1, name, b + 1);
+ return key;
+}
+
+static bool ts_add_node(ts_state_t *st, int64_t id) {
+ char key[32];
+ snprintf(key, sizeof(key), "%lld", (long long)id);
+ if (cbm_ht_get(st->seen_nodes, key)) {
+ return true;
+ }
+ const char *owned = cbm_arena_strdup(&st->out->arena, key);
+ if (!owned || !ts_ids_push(&st->out->nodes, id)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ cbm_ht_set(st->seen_nodes, owned, (void *)1);
+ return true;
+}
+
+static bool ts_add_whole(ts_state_t *st, const char *path) {
+ if (cbm_ht_get(st->whole, path)) {
+ return true;
+ }
+ const char *owned = cbm_arena_strdup(&st->out->arena, path);
+ if (!owned || !ts_strs_push(&st->whole_list, owned)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ cbm_ht_set(st->whole, owned, (void *)1);
+ return true;
+}
+
+static bool ts_add_deleted(ts_state_t *st, const char *line, cbm_ti_span_t span) {
+ char *name = cbm_arena_strndup(&st->out->arena, line + span.start, span.len);
+ if (!name) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ if (!cbm_ht_get(st->deleted, name)) {
+ cbm_ht_set(st->deleted, name, (void *)1);
+ if (!ts_strs_push(&st->out->deleted, name)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ }
+ return true;
+}
+
+/* A test case or suite body is reported, never seeded (replay4 558-566). */
+static int ts_case_of(ts_state_t *st, const char *file, const cbm_ti_node_t *n) {
+ if (strcmp(n->label, "Function") != 0 && strcmp(n->label, "Method") != 0) {
+ return -1;
+ }
+ char stack[512];
+ size_t a = strlen(file);
+ size_t b = strlen(n->name);
+ if (a + b + 2 > sizeof(stack)) {
+ return -1;
+ }
+ memcpy(stack, file, a);
+ stack[a] = '\x1f';
+ memcpy(stack + a + 1, n->name, b + 1);
+ return (int)(intptr_t)cbm_ht_get(st->case_index, stack) - 1;
+}
+
+static int ts_suite_of(ts_state_t *st, const char *file, const cbm_ti_node_t *n) {
+ if (strcmp(n->label, "Function") != 0 && strcmp(n->label, "Method") != 0) {
+ return -1;
+ }
+ char stack[512];
+ size_t a = strlen(file);
+ size_t b = strlen(n->name);
+ if (a + b + 2 > sizeof(stack)) {
+ return -1;
+ }
+ memcpy(stack, file, a);
+ stack[a] = '\x1f';
+ memcpy(stack + a + 1, n->name, b + 1);
+ return (int)(intptr_t)cbm_ht_get(st->suite_index, stack) - 1;
+}
+
+/* The names a removed line declared (replay4 548-552): define, tag
+ * declaration or prototype, when the line does not end in ';'. Every
+ * pattern that matches adds its name. */
+static bool ts_note_removed_line(ts_state_t *st, const char *line) {
+ size_t n = strlen(line);
+ size_t e = n;
+ while (e > 0 && (line[e - 1] == ' ' || line[e - 1] == '\t' || line[e - 1] == '\r' ||
+ line[e - 1] == '\f' || line[e - 1] == '\v')) {
+ e--;
+ }
+ if (e > 0 && line[e - 1] == ';') {
+ return true;
+ }
+ cbm_ti_span_t span;
+ if (cbm_ti_match_define(line, n, &span, NULL) && !ts_add_deleted(st, line, span)) {
+ return false;
+ }
+ if (cbm_ti_match_tag_declaration(line, n, &span) && !ts_add_deleted(st, line, span)) {
+ return false;
+ }
+ if (cbm_ti_match_prototype(line, n, &span) && !ts_add_deleted(st, line, span)) {
+ return false;
+ }
+ return true;
+}
+
+static bool ts_comment_only(const cbm_diff_hunk_t *h) {
+ for (int i = 0; i < h->added_count; i++) {
+ if (!cbm_ti_line_is_comment(h->added[i], strlen(h->added[i]))) {
+ return false;
+ }
+ }
+ for (int i = 0; i < h->removed_count; i++) {
+ if (!cbm_ti_line_is_comment(h->removed[i], strlen(h->removed[i]))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* A seed, or a changed case/suite (replay4 558-566). */
+static bool ts_take_definition(ts_state_t *st, const char *file, const cbm_ti_node_t *n) {
+ int c = ts_case_of(st, file, n);
+ if (c >= 0) {
+ st->case_changed[c] = true;
+ return true;
+ }
+ int s = ts_suite_of(st, file, n);
+ if (s >= 0) {
+ st->suite_changed[s] = true;
+ return true;
+ }
+ return ts_add_node(st, n->id);
+}
+
+/* The definition around a pure deletion: at the line the removal follows,
+ * else the next one (replay4 546). */
+static const cbm_ti_node_t *ts_around_deletion(ts_state_t *st, const char *file, int line,
+ bool *ok) {
+ const cbm_ti_node_t *d = cbm_ti_graph_enclosing(st->in->graph, file, line, ok);
+ if (!d && *ok) {
+ d = cbm_ti_graph_enclosing(st->in->graph, file, line + 1, ok);
+ }
+ return d;
+}
+
+/* One hunk of a source (not header) file (replay4 540-566). */
+static bool ts_source_hunk(ts_state_t *st, const char *file, const cbm_diff_hunk_t *h) {
+ if (ts_comment_only(h)) {
+ return true;
+ }
+ bool ok = true;
+ int overlapped = 0;
+ if (h->count > 0) {
+ int count = 0;
+ const cbm_ti_node_t *nodes = cbm_ti_graph_file(st->in->graph, file, &count, &ok);
+ int last = h->start + h->count - 1;
+ for (int i = 0; ok && i < count; i++) {
+ if (nodes[i].start_line <= last && nodes[i].end_line >= h->start) {
+ overlapped++;
+ ok = ts_take_definition(st, file, &nodes[i]);
+ }
+ }
+ } else {
+ const cbm_ti_node_t *d = ts_around_deletion(st, file, h->start, &ok);
+ if (d && ok) {
+ overlapped = 1;
+ ok = ts_take_definition(st, file, d);
+ }
+ }
+ if (!ok) {
+ return st->status == CBM_TI_SEED_OK ? ts_fail(st, CBM_TI_SEED_STORE) : false;
+ }
+ for (int i = 0; i < h->removed_count; i++) {
+ if (!ts_note_removed_line(st, h->removed[i])) {
+ return false;
+ }
+ }
+ return overlapped ? true : ts_add_whole(st, file);
+}
+
+/* The names a deleted file declared (replay4 521-528). */
+static bool ts_deleted_file(ts_state_t *st, const cbm_ti_change_t *c) {
+ const char *p = c->base_text ? c->base_text : "";
+ const char *end = p + c->base_len;
+ while (p <= end) {
+ const char *nl = memchr(p, '\n', (size_t)(end - p));
+ size_t len = nl ? (size_t)(nl - p) : (size_t)(end - p);
+ char *line = cbm_arena_strndup(&st->out->arena, p, len);
+ if (!line) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ if (!ts_note_removed_line(st, line)) {
+ return false;
+ }
+ if (!nl) {
+ break;
+ }
+ p = nl + 1;
+ }
+ return true;
+}
+
+/* ── Header symbol propagation (replay4 header_seeds, 290-374) ──── */
+
+typedef struct {
+ CBMHashTable *set; /* name -> 1 */
+ ts_strs_t list;
+} ts_names_t;
+
+static bool ts_names_add(ts_state_t *st, ts_names_t *names, const char *name, size_t len) {
+ char *copy = cbm_arena_strndup(&st->out->arena, name, len);
+ if (!copy) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ if (cbm_ht_get(names->set, copy)) {
+ return true;
+ }
+ if (!ts_strs_push(&names->list, copy)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ cbm_ht_set(names->set, copy, (void *)1);
+ return true;
+}
+
+static bool ts_names_has(const ts_names_t *names, const char *name) {
+ return cbm_ht_get(names->set, name) != NULL;
+}
+
+/* Classify the lines of one header hunk. false = error; *file_level set when
+ * a line cannot be classified or is a preprocessor conditional. */
+static bool ts_header_hunk(ts_state_t *st, const char *header, const cbm_diff_hunk_t *h,
+ ts_names_t *changed, bool *file_level) {
+ bool ok = true;
+ int overlap_count = 0;
+ if (h->count > 0) {
+ int count = 0;
+ const cbm_ti_node_t *nodes = cbm_ti_graph_file(st->in->graph, header, &count, &ok);
+ int last = h->start + h->count - 1;
+ for (int i = 0; ok && i < count; i++) {
+ if (nodes[i].start_line <= last && nodes[i].end_line >= h->start) {
+ overlap_count++;
+ ok = ts_names_add(st, changed, nodes[i].name, strlen(nodes[i].name));
+ }
+ }
+ }
+ int total = h->added_count + h->removed_count;
+ for (int k = 0; ok && k < total; k++) {
+ const char *ln = k < h->added_count ? h->added[k] : h->removed[k - h->added_count];
+ size_t len = strlen(ln);
+ if (cbm_ti_line_is_comment(ln, len)) {
+ continue;
+ }
+ if (cbm_ti_line_is_pp_condition(ln, len)) {
+ *file_level = true;
+ continue;
+ }
+ cbm_ti_span_t span;
+ if (cbm_ti_match_declaration(ln, len, &span)) {
+ ok = ts_names_add(st, changed, ln + span.start, span.len);
+ continue;
+ }
+ if (h->count > 0 && overlap_count > 0) {
+ continue; /* inside a definition at head: named by the overlap */
+ }
+ if (h->count == 0) {
+ const cbm_ti_node_t *d = ts_around_deletion(st, header, h->start, &ok);
+ if (d && ok) {
+ ok = ts_names_add(st, changed, d->name, strlen(d->name));
+ continue;
+ }
+ }
+ if (ok) {
+ *file_level = true;
+ }
+ }
+ if (!ok && st->status == CBM_TI_SEED_OK) {
+ ts_fail(st, CBM_TI_SEED_STORE);
+ }
+ return ok;
+}
+
+static bool ts_starts_with(const char *s, const char *prefix) {
+ return strncmp(s, prefix, strlen(prefix)) == 0;
+}
+
+static bool ts_ends_with(const char *s, const char *suffix) {
+ size_t a = strlen(s);
+ size_t b = strlen(suffix);
+ return a >= b && strcmp(s + a - b, suffix) == 0;
+}
+
+static bool ts_macro_hit(const cbm_ti_macro_t *m, const ts_names_t *changed) {
+ for (int i = 0; i < m->token_count; i++) {
+ if (ts_names_has(changed, m->tokens[i])) {
+ return true;
+ }
+ }
+ for (int k = 0; k < changed->list.count; k++) {
+ const char *c = changed->list.items[k];
+ for (int i = 0; i < m->paste_prefix_count; i++) {
+ if (ts_starts_with(c, m->paste_prefixes[i])) {
+ return true;
+ }
+ }
+ for (int i = 0; i < m->paste_suffix_count; i++) {
+ if (ts_ends_with(c, m->paste_suffixes[i])) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+/* Close the changed names over the headers' macros (replay4 328-345). */
+static bool ts_macro_fixpoint(ts_state_t *st, ts_names_t *changed) {
+ int count = 0;
+ const cbm_ti_macro_t *macros = cbm_ti_source_macros(st->in->source, &count);
+ bool grew = true;
+ while (grew) {
+ grew = false;
+ for (int i = 0; i < count; i++) {
+ if (ts_names_has(changed, macros[i].name) || !ts_macro_hit(&macros[i], changed)) {
+ continue;
+ }
+ if (!ts_names_add(st, changed, macros[i].name, strlen(macros[i].name))) {
+ return false;
+ }
+ grew = true;
+ }
+ }
+ return true;
+}
+
+static bool ts_is_function(const cbm_ti_node_t *n) {
+ return strcmp(n->label, "Function") == 0 || strcmp(n->label, "Method") == 0;
+}
+
+/* One occurrence of a propagated name in a file including the header
+ * (replay4 355-373). */
+static bool ts_header_occurrence(ts_state_t *st, int file, int line, ts_names_t *work) {
+ cbm_ti_source_t *src = st->in->source;
+ const char *path = cbm_ti_source_path(src, file);
+ bool ok = true;
+ const cbm_ti_node_t *d = cbm_ti_graph_enclosing(st->in->graph, path, line, &ok);
+ if (!ok) {
+ return ts_fail(st, CBM_TI_SEED_STORE);
+ }
+ if (d) {
+ if (!ts_add_node(st, d->id)) {
+ return false;
+ }
+ if (cbm_ti_source_is_header(src, file) && !ts_is_function(d) && d->name[0]) {
+ return ts_names_add(st, work, d->name, strlen(d->name));
+ }
+ return true;
+ }
+ if (!cbm_ti_source_is_header(src, file)) {
+ return ts_add_whole(st, path);
+ }
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(src, file, line, &len);
+ cbm_ti_span_t span;
+ if (text && cbm_ti_match_declaration(text, len, &span)) {
+ return ts_names_add(st, work, text + span.start, span.len);
+ }
+ return true;
+}
+
+/* Seed what mentions a propagated name inside the include closure; names
+ * found on the way join the work list (replay4 346-374). The work list is the
+ * set of names in insertion order, so each is scanned once. */
+static bool ts_header_scan(ts_state_t *st, const bool *closure, ts_names_t *work) {
+ cbm_ti_source_t *src = st->in->source;
+ if (!cbm_ti_source_build_occurrences(src)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ for (int k = 0; k < work->list.count; k++) {
+ const char *name = work->list.items[k];
+ int count = 0;
+ const cbm_ti_place_t *places = cbm_ti_source_occurrences(src, name, strlen(name), &count);
+ for (int i = 0; i < count; i++) {
+ if (closure[places[i].file] &&
+ !ts_header_occurrence(st, places[i].file, places[i].line, work)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+static bool ts_header(ts_state_t *st, const cbm_ti_change_t *c) {
+ ts_names_t changed = {.set = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0)};
+ bool *closure = NULL;
+ bool file_level = false;
+ bool ok = changed.set != NULL || ts_fail(st, CBM_TI_SEED_OOM);
+ for (int i = 0; ok && i < c->hunk_count; i++) {
+ ok = ts_header_hunk(st, c->path, &c->hunks[i], &changed, &file_level);
+ }
+ if (ok && (file_level || c->whole_file)) {
+ const char *owned = cbm_arena_strdup(&st->out->arena, c->path);
+ ok = (owned && ts_strs_push(&st->out->file_level, owned)) || ts_fail(st, CBM_TI_SEED_OOM);
+ } else if (ok) {
+ int files = cbm_ti_source_file_count(st->in->source);
+ int at = cbm_ti_source_find(st->in->source, c->path);
+ closure = cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)(files ? files : 1) * sizeof(bool));
+ ok = closure != NULL || ts_fail(st, CBM_TI_SEED_OOM);
+ if (ok) {
+ memset(closure, 0, (size_t)(files ? files : 1) * sizeof(bool));
+ if (at >= 0) {
+ closure[at] = true;
+ }
+ cbm_ti_source_include_closure(st->in->source, closure);
+ ok = ts_macro_fixpoint(st, &changed) && ts_header_scan(st, closure, &changed);
+ }
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, closure);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, changed.list.items);
+ if (changed.set) {
+ cbm_ht_free(changed.set);
+ }
+ return ok;
+}
+
+/* ── Deleted names (replay4 name_reference_seeds, 377-389) ────────── */
+
+static bool ts_name_references(ts_state_t *st) {
+ cbm_ti_source_t *src = st->in->source;
+ bool built = false;
+ for (int k = 0; k < st->out->deleted.count; k++) {
+ const char *name = st->out->deleted.items[k];
+ if (cbm_ti_is_keyword(name, strlen(name))) {
+ continue;
+ }
+ bool ok = true;
+ if (cbm_ti_graph_has_name(st->in->graph, name, &ok) || !ok) {
+ if (!ok) {
+ return ts_fail(st, CBM_TI_SEED_STORE);
+ }
+ continue; /* still defined at head: an ordinary seed already */
+ }
+ if (!built && !cbm_ti_source_build_occurrences(src)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ built = true;
+ int count = 0;
+ const cbm_ti_place_t *places = cbm_ti_source_occurrences(src, name, strlen(name), &count);
+ for (int i = 0; i < count; i++) {
+ const char *path = cbm_ti_source_path(src, places[i].file);
+ const cbm_ti_node_t *d =
+ cbm_ti_graph_enclosing(st->in->graph, path, places[i].line, &ok);
+ if (!ok) {
+ return ts_fail(st, CBM_TI_SEED_STORE);
+ }
+ if (d ? !ts_add_node(st, d->id)
+ : (!cbm_ti_source_is_header(src, places[i].file) && !ts_add_whole(st, path))) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/* Every definition of a whole file is a seed; a case in a changed file is a
+ * changed test (replay4 577-581). Suites and cases are seeded too: the walk
+ * holds them as reached sinks. */
+static bool ts_whole_files(ts_state_t *st) {
+ for (int k = 0; k < st->whole_list.count; k++) {
+ const char *path = st->whole_list.items[k];
+ bool ok = true;
+ int count = 0;
+ const cbm_ti_node_t *nodes = cbm_ti_graph_file(st->in->graph, path, &count, &ok);
+ if (!ok) {
+ return ts_fail(st, CBM_TI_SEED_STORE);
+ }
+ bool changed = cbm_ht_get(st->changed_path, path) != NULL;
+ for (int i = 0; i < count; i++) {
+ int c = ts_case_of(st, path, &nodes[i]);
+ if (c >= 0 && changed) {
+ st->case_changed[c] = true;
+ }
+ if (!ts_add_node(st, nodes[i].id)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/* ── Driver ──────────────────────────────────────────────────────── */
+
+static bool ts_index_model(ts_state_t *st) {
+ const cbm_test_case_t *cases = cbm_test_model_cases(st->in->model, &st->case_count);
+ const cbm_test_suite_t *suites = cbm_test_model_suites(st->in->model, &st->suite_count);
+ st->case_changed = cbm_arena_calloc(&st->out->arena, (size_t)st->case_count + 1);
+ st->suite_changed = cbm_arena_calloc(&st->out->arena, (size_t)st->suite_count + 1);
+ if (!st->case_changed || !st->suite_changed) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ for (int i = 0; i < st->case_count; i++) {
+ const char *key = ts_key(st, cases[i].file, cases[i].name);
+ if (!key) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ cbm_ht_set(st->case_index, key, (void *)(intptr_t)(i + 1));
+ }
+ for (int i = 0; i < st->suite_count; i++) {
+ const char *key = ts_key(st, suites[i].file, suites[i].name);
+ if (!key) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ cbm_ht_set(st->suite_index, key, (void *)(intptr_t)(i + 1));
+ }
+ for (int i = 0; i < st->in->change_count; i++) {
+ cbm_ht_set(st->changed_path, st->in->changes[i].path, (void *)1);
+ }
+ return true;
+}
+
+static bool ts_change(ts_state_t *st, const cbm_ti_change_t *c) {
+ if (c->deleted) {
+ return ts_deleted_file(st, c);
+ }
+ size_t n = strlen(c->path);
+ bool header = (n >= 2 && strcmp(c->path + n - 2, ".h") == 0) ||
+ (n >= 4 && strcmp(c->path + n - 4, ".hpp") == 0) ||
+ (n >= 3 && strcmp(c->path + n - 3, ".hh") == 0);
+ if (header) {
+ return ts_header(st, c);
+ }
+ if (c->whole_file) {
+ return ts_add_whole(st, c->path); /* no hunks to read: more, never fewer */
+ }
+ for (int i = 0; i < c->hunk_count; i++) {
+ if (!ts_source_hunk(st, c->path, &c->hunks[i])) {
+ return false;
+ }
+ }
+ return true;
+}
+
+static int ts_id_compare(const void *left, const void *right) {
+ int64_t a = *(const int64_t *)left;
+ int64_t b = *(const int64_t *)right;
+ return a < b ? -1 : (a > b ? 1 : 0);
+}
+
+static bool ts_collect(ts_state_t *st) {
+ if (st->out->nodes.count > 1) {
+ qsort(st->out->nodes.items, (size_t)st->out->nodes.count, sizeof(int64_t), ts_id_compare);
+ }
+ for (int i = 0; i < st->case_count; i++) {
+ if (st->case_changed[i] && !ts_ints_push(&st->out->cases, i)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ }
+ for (int i = 0; i < st->suite_count; i++) {
+ if (st->suite_changed[i] && !ts_ints_push(&st->out->suites, i)) {
+ return ts_fail(st, CBM_TI_SEED_OOM);
+ }
+ }
+ return true;
+}
+
+static void ts_state_free(ts_state_t *st) {
+ CBMHashTable *tables[] = {st->seen_nodes, st->whole, st->deleted,
+ st->case_index, st->suite_index, st->changed_path};
+ for (size_t i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
+ if (tables[i]) {
+ cbm_ht_free(tables[i]);
+ }
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, st->whole_list.items);
+}
+
+cbm_ti_seed_status_t cbm_ti_seed(const cbm_ti_seed_input_t *in, cbm_ti_seeds_t **out) {
+ if (!out) {
+ return CBM_TI_SEED_INVALID;
+ }
+ *out = NULL;
+ if (!in || !in->model || !in->graph || !in->source || (in->change_count && !in->changes)) {
+ return CBM_TI_SEED_INVALID;
+ }
+ cbm_ti_seeds_t *seeds = cbm_alloc(CBM_MEM_CLASS_EXTRACT, sizeof(*seeds));
+ if (!seeds) {
+ return CBM_TI_SEED_OOM;
+ }
+ memset(seeds, 0, sizeof(*seeds));
+ cbm_arena_init(&seeds->arena);
+ ts_state_t st = {.in = in, .out = seeds};
+ st.seen_nodes = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ st.whole = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ st.deleted = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ st.case_index = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ st.suite_index = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ st.changed_path = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ bool ok = (st.seen_nodes && st.whole && st.deleted && st.case_index && st.suite_index &&
+ st.changed_path) ||
+ ts_fail(&st, CBM_TI_SEED_OOM);
+ ok = ok && ts_index_model(&st);
+ for (int i = 0; ok && i < in->change_count; i++) {
+ ok = ts_change(&st, &in->changes[i]);
+ }
+ ok = ok && ts_name_references(&st) && ts_whole_files(&st) && ts_collect(&st);
+ ts_state_free(&st);
+ if (!ok) {
+ cbm_ti_seeds_free(seeds);
+ return st.status == CBM_TI_SEED_OK ? CBM_TI_SEED_OOM : st.status;
+ }
+ *out = seeds;
+ return CBM_TI_SEED_OK;
+}
+
+void cbm_ti_seeds_free(cbm_ti_seeds_t *s) {
+ if (!s) {
+ return;
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->nodes.items);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->cases.items);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->suites.items);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->file_level.items);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->deleted.items);
+ cbm_arena_destroy(&s->arena);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s);
+}
+
+const int64_t *cbm_ti_seeds_nodes(const cbm_ti_seeds_t *s, int *count) {
+ *count = s ? s->nodes.count : 0;
+ return s ? s->nodes.items : NULL;
+}
+
+const int *cbm_ti_seeds_changed_cases(const cbm_ti_seeds_t *s, int *count) {
+ *count = s ? s->cases.count : 0;
+ return s ? s->cases.items : NULL;
+}
+
+const int *cbm_ti_seeds_changed_suites(const cbm_ti_seeds_t *s, int *count) {
+ *count = s ? s->suites.count : 0;
+ return s ? s->suites.items : NULL;
+}
+
+const char *const *cbm_ti_seeds_file_level_headers(const cbm_ti_seeds_t *s, int *count) {
+ *count = s ? s->file_level.count : 0;
+ return s ? s->file_level.items : NULL;
+}
+
+const char *const *cbm_ti_seeds_deleted_names(const cbm_ti_seeds_t *s, int *count) {
+ *count = s ? s->deleted.count : 0;
+ return s ? s->deleted.items : NULL;
+}
diff --git a/src/mcp/test_impact_seed.h b/src/mcp/test_impact_seed.h
new file mode 100644
index 000000000..23e97114b
--- /dev/null
+++ b/src/mcp/test_impact_seed.h
@@ -0,0 +1,104 @@
+/*
+ * test_impact_seed.h — what a change seeds in the graph (smart-ci-design 5.1,
+ * 5.8), for detect_changes scope:"tests".
+ *
+ * A port of the measured reference (scratchpad tia3/replay4.py, seeding and
+ * header symbol propagation), rule for rule:
+ * - a hunk with lines at head seeds the definitions it overlaps; a hunk of
+ * comment lines only seeds nothing; a pure deletion seeds the definition
+ * around the deletion point; a hunk that overlaps no definition seeds its
+ * whole file;
+ * - the names a `-` line declared and head no longer defines are looked up
+ * by text: every definition whose lines mention one is a seed
+ * (NAME_REFERENCE), and a mention outside any definition of a source file
+ * seeds that file whole; a deleted file contributes every name it had;
+ * - a header change names what it changes (declared names, overlapped
+ * definitions), closes those names over the headers' macros (pastes
+ * included), and seeds every definition that mentions one in a file
+ * including the header; a line it cannot classify, or any preprocessor
+ * conditional, makes the header "file level": every test file including it
+ * runs its suites whole;
+ * - a changed test case or suite body is reported as such, never seeded.
+ * Every approximation selects more tests, never fewer.
+ */
+#ifndef CBM_TEST_IMPACT_SEED_H
+#define CBM_TEST_IMPACT_SEED_H
+
+#include "mcp/test_impact.h"
+#include "mcp/test_impact_source.h"
+#include "store/store.h"
+
+#include <stdbool.h>
+#include <stdint.h>
+
+/* The graph of the snapshot, as the seeding reads it. */
+typedef struct cbm_ti_graph cbm_ti_graph_t;
+
+typedef struct {
+ int64_t id;
+ const char *label;
+ const char *name;
+ const char *qualified_name;
+ int start_line;
+ int end_line;
+} cbm_ti_node_t;
+
+/* Borrows the store until free. Nodes of a file are read once, on first use. */
+cbm_ti_graph_t *cbm_ti_graph_new(cbm_store_t *store, const char *project);
+void cbm_ti_graph_free(cbm_ti_graph_t *g);
+/* The seedable definitions of a file (every label but File, Folder, Project,
+ * Module, Package, Section, Route, Resource), ordered by (start, end, id).
+ * NULL with *ok=false when the store failed: a failed read is never "none". */
+const cbm_ti_node_t *cbm_ti_graph_file(cbm_ti_graph_t *g, const char *file, int *count, bool *ok);
+/* The innermost definition containing the line: smallest span, then the
+ * earliest start, then the smallest id. NULL when none (or *ok=false). */
+const cbm_ti_node_t *cbm_ti_graph_enclosing(cbm_ti_graph_t *g, const char *file, int line,
+ bool *ok);
+/* Whether any node of the snapshot has this name (deleted-name check). */
+bool cbm_ti_graph_has_name(cbm_ti_graph_t *g, const char *name, bool *ok);
+
+/* One changed path the seeding reads: C-family, with its hunks unless the
+ * change has no usable text (then whole_file). */
+typedef struct {
+ const char *path;
+ bool deleted; /* gone at head: only its base names matter */
+ bool whole_file; /* no hunks to read: seed the whole file */
+ const cbm_diff_hunk_t *hunks;
+ int hunk_count;
+ /* For a deleted file: its text at the merge base (names it declared). */
+ const char *base_text;
+ size_t base_len;
+} cbm_ti_change_t;
+
+typedef struct {
+ const cbm_ti_change_t *changes;
+ int change_count;
+ const cbm_test_model_t *model; /* cases and suites at head */
+ cbm_ti_graph_t *graph;
+ cbm_ti_source_t *source; /* finished; occurrences built on demand */
+} cbm_ti_seed_input_t;
+
+typedef struct cbm_ti_seeds cbm_ti_seeds_t;
+
+typedef enum {
+ CBM_TI_SEED_OK = 0,
+ CBM_TI_SEED_INVALID,
+ CBM_TI_SEED_STORE, /* the graph could not be read */
+ CBM_TI_SEED_OOM
+} cbm_ti_seed_status_t;
+
+cbm_ti_seed_status_t cbm_ti_seed(const cbm_ti_seed_input_t *in, cbm_ti_seeds_t **out);
+void cbm_ti_seeds_free(cbm_ti_seeds_t *seeds);
+
+/* Seed node ids, ascending, unique. */
+const int64_t *cbm_ti_seeds_nodes(const cbm_ti_seeds_t *s, int *count);
+/* Model cases whose definition a hunk touched (indices into the model's
+ * cases), and suites whose body a hunk touched (indices into its suites). */
+const int *cbm_ti_seeds_changed_cases(const cbm_ti_seeds_t *s, int *count);
+const int *cbm_ti_seeds_changed_suites(const cbm_ti_seeds_t *s, int *count);
+/* Headers changed at file level (paths). */
+const char *const *cbm_ti_seeds_file_level_headers(const cbm_ti_seeds_t *s, int *count);
+/* Names head no longer defines that were looked up by text. */
+const char *const *cbm_ti_seeds_deleted_names(const cbm_ti_seeds_t *s, int *count);
+
+#endif /* CBM_TEST_IMPACT_SEED_H */
diff --git a/src/mcp/test_impact_select.c b/src/mcp/test_impact_select.c
index e88d2ff99..44e423f99 100644
--- a/src/mcp/test_impact_select.c
+++ b/src/mcp/test_impact_select.c
@@ -135,7 +135,7 @@ cbm_test_selection_t *cbm_test_select(const cbm_test_selection_input_t *input) {
if (!input->has_changes)
return result;
unsigned incomplete = 0;
- if (!input->inventory_complete || !cbm_test_model_complete(input->model))
+ if (!input->inventory_complete || !cbm_test_model_narrowable(input->model))
incomplete |= CBM_TEST_SELECT_INVENTORY_UNKNOWN;
if (!input->static_complete)
incomplete |= CBM_TEST_SELECT_STATIC_INCOMPLETE;
@@ -207,7 +207,7 @@ cbm_test_selection_t *cbm_test_select(const cbm_test_selection_input_t *input) {
int at = sl_suite_find(result->suites, runner_count, definitions[i].name);
if (at >= 0) {
definition_counts[at]++;
- if (definitions[i].macro_registrations)
+ if (definitions[i].macro_registrations || definitions[i].uncertain)
sl_whole(&result->suites[at], CBM_TEST_SELECT_INVENTORY_UNKNOWN);
}
}
@@ -235,13 +235,16 @@ cbm_test_selection_t *cbm_test_select(const cbm_test_selection_input_t *input) {
for (int i = 0; i < registration_count; i++) {
const cbm_test_registration_t *reg = order[i];
int at = sl_suite_find(result->suites, runner_count, reg->suite);
- if (at < 0)
- return sl_full(result, CBM_TEST_SELECT_INVENTORY_UNKNOWN);
- cbm_test_selected_suite_t *suite = &result->suites[at];
- registration_counts[at]++;
sl_reach_t *evidence = sl_reach_find(reach, input->reach_count, reg->file, reg->test);
if (evidence)
evidence->registered = true;
+ if (at < 0)
+ /* A suite this runner never registers runs elsewhere (another
+ * runner's list) or not at all: its tests are outside this
+ * selection, and a change to one is no unregistered change. */
+ continue;
+ cbm_test_selected_suite_t *suite = &result->suites[at];
+ registration_counts[at]++;
const cbm_test_case_t *test = sl_case_find(case_order, case_count, reg->file, reg->test);
if (!reg->resolved || !test)
sl_whole(suite, CBM_TEST_SELECT_INVENTORY_UNKNOWN);
diff --git a/src/mcp/test_impact_source.c b/src/mcp/test_impact_source.c
new file mode 100644
index 000000000..25a1ffca8
--- /dev/null
+++ b/src/mcp/test_impact_source.c
@@ -0,0 +1,965 @@
+/*
+ * test_impact_source.c — text facts about the C-family sources of one snapshot.
+ *
+ * Each line pattern reproduces one regular expression of the measured
+ * reference (replay4.py) by hand, so its matches are the same without a regex
+ * engine on any platform. The comment above each function quotes the
+ * expression it reproduces.
+ */
+#include "mcp/test_impact_source.h"
+
+#include "foundation/arena.h"
+#include "foundation/hash_table.h"
+#include "foundation/mem_core.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* ── Characters ───────────────────────────────────────────────────── */
+
+static bool ti_space(char c) {
+ return c == ' ' || c == '\t' || c == '\r' || c == '\f' || c == '\v' || c == '\n';
+}
+
+static bool ti_word(char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
+}
+
+static bool ti_start(char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
+}
+
+static size_t ti_skip_space(const char *s, size_t i, size_t n) {
+ while (i < n && ti_space(s[i])) {
+ i++;
+ }
+ return i;
+}
+
+/* The end of s[from..n) without its trailing whitespace. */
+static size_t ti_trim_end(const char *s, size_t from, size_t n) {
+ while (n > from && ti_space(s[n - 1])) {
+ n--;
+ }
+ return n;
+}
+
+static size_t ti_word_end(const char *s, size_t i, size_t n) {
+ while (i < n && ti_word(s[i])) {
+ i++;
+ }
+ return i;
+}
+
+static bool ti_at(const char *s, size_t i, size_t n, const char *word) {
+ size_t len = strlen(word);
+ return i + len <= n && memcmp(s + i, word, len) == 0;
+}
+
+/* `word` at i followed by a word boundary. */
+static bool ti_keyword_at(const char *s, size_t i, size_t n, const char *word) {
+ size_t len = strlen(word);
+ return ti_at(s, i, n, word) && (i + len == n || !ti_word(s[i + len]));
+}
+
+/* `word` at i followed by at least one blank: `word\s+`. */
+static bool ti_word_then_space(const char *s, size_t i, size_t n, const char *word) {
+ size_t len = strlen(word);
+ return ti_at(s, i, n, word) && i + len < n && ti_space(s[i + len]);
+}
+
+/* An identifier may start at i: `\b[A-Za-z_]`. */
+static bool ti_identifier_at(const char *s, size_t i) {
+ return ti_start(s[i]) && (i == 0 || !ti_word(s[i - 1]));
+}
+
+/* After an identifier ending at e: `\s*(?:\[[^\]]*\])?\s*;`. */
+static bool ti_array_then_semicolon(const char *s, size_t e, size_t n) {
+ size_t j = ti_skip_space(s, e, n);
+ if (j < n && s[j] == ';') {
+ return true;
+ }
+ if (j >= n || s[j] != '[') {
+ return false;
+ }
+ const char *close = memchr(s + j + 1, ']', n - j - 1);
+ if (!close) {
+ return false;
+ }
+ j = ti_skip_space(s, (size_t)(close - s) + 1, n);
+ return j < n && s[j] == ';';
+}
+
+/* ── Keywords (replay4 C_KEYWORDS), sorted for bsearch ───────────────── */
+
+static const char *const ti_keywords[] = {
+ "NULL", "auto", "bool", "break", "case", "char", "const", "continue",
+ "default", "define", "defined", "do", "double", "elif", "else", "endif",
+ "enum", "extern", "false", "float", "for", "goto", "if", "ifdef",
+ "ifndef", "include", "inline", "int", "int16_t", "int32_t", "int64_t", "int8_t",
+ "long", "pragma", "register", "restrict", "return", "short", "signed", "size_t",
+ "sizeof", "static", "struct", "switch", "true", "typedef", "uint16_t", "uint32_t",
+ "uint64_t", "uint8_t", "union", "unsigned", "void", "volatile", "while"};
+
+bool cbm_ti_is_keyword(const char *word, size_t len) {
+ size_t lo = 0;
+ size_t hi = sizeof(ti_keywords) / sizeof(ti_keywords[0]);
+ while (lo < hi) {
+ size_t mid = lo + (hi - lo) / 2;
+ const char *k = ti_keywords[mid];
+ size_t klen = strlen(k);
+ int c = memcmp(word, k, len < klen ? len : klen);
+ if (c == 0) {
+ c = len < klen ? -1 : (len > klen ? 1 : 0);
+ }
+ if (c == 0) {
+ return true;
+ }
+ if (c < 0) {
+ hi = mid;
+ } else {
+ lo = mid + 1;
+ }
+ }
+ return false;
+}
+
+/* ── Line patterns ─────────────────────────────────────────────────── */
+
+/* `^\s*(//.*|/\*.*|\*.*|.*\*\/\s*)?$` */
+bool cbm_ti_line_is_comment(const char *s, size_t n) {
+ size_t i = ti_skip_space(s, 0, n);
+ if (i == n || s[i] == '*') {
+ return true;
+ }
+ if (s[i] == '/' && i + 1 < n && (s[i + 1] == '/' || s[i + 1] == '*')) {
+ return true;
+ }
+ size_t e = ti_trim_end(s, i, n);
+ return e - i >= 2 && s[e - 2] == '*' && s[e - 1] == '/';
+}
+
+/* `^\s*#\s*(if|ifdef|ifndef|elif|else|endif|undef|include)\b` */
+bool cbm_ti_line_is_pp_condition(const char *s, size_t n) {
+ static const char *const words[] = {"if", "ifdef", "ifndef", "elif",
+ "else", "endif", "undef", "include"};
+ size_t i = ti_skip_space(s, 0, n);
+ if (i >= n || s[i] != '#') {
+ return false;
+ }
+ i = ti_skip_space(s, i + 1, n);
+ size_t e = ti_word_end(s, i, n);
+ for (size_t k = 0; k < sizeof(words) / sizeof(words[0]); k++) {
+ if (e - i == strlen(words[k]) && memcmp(s + i, words[k], e - i) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* `^\s*#\s*define\s+([A-Za-z_]\w*)(\()?` */
+bool cbm_ti_match_define(const char *s, size_t n, cbm_ti_span_t *name, size_t *body) {
+ size_t i = ti_skip_space(s, 0, n);
+ if (i >= n || s[i] != '#') {
+ return false;
+ }
+ i = ti_skip_space(s, i + 1, n);
+ if (!ti_word_then_space(s, i, n, "define")) {
+ return false;
+ }
+ i = ti_skip_space(s, i + 6, n);
+ if (i >= n || !ti_start(s[i])) {
+ return false;
+ }
+ size_t e = ti_word_end(s, i, n);
+ *name = (cbm_ti_span_t){i, e - i};
+ if (body) {
+ *body = e < n && s[e] == '(' ? e + 1 : e;
+ }
+ return true;
+}
+
+/* `\btypedef\b.*?\b([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*;`, searched */
+bool cbm_ti_match_typedef(const char *s, size_t n, cbm_ti_span_t *name) {
+ for (size_t p = 0; p + 7 <= n; p++) {
+ if (!ti_keyword_at(s, p, n, "typedef") || (p > 0 && ti_word(s[p - 1]))) {
+ continue;
+ }
+ for (size_t q = p + 7; q < n; q++) {
+ if (!ti_identifier_at(s, q)) {
+ continue;
+ }
+ size_t e = ti_word_end(s, q, n);
+ if (ti_array_then_semicolon(s, e, n)) {
+ *name = (cbm_ti_span_t){q, e - q};
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+/* `^\s*(?:typedef\s+)?(?:struct|union|enum)\s+([A-Za-z_]\w*)\s*\{` */
+bool cbm_ti_match_tag_declaration(const char *s, size_t n, cbm_ti_span_t *name) {
+ size_t i = ti_skip_space(s, 0, n);
+ if (ti_word_then_space(s, i, n, "typedef")) {
+ i = ti_skip_space(s, i + 7, n);
+ }
+ size_t kw = ti_word_then_space(s, i, n, "struct") ? 6
+ : ti_word_then_space(s, i, n, "union") ? 5
+ : ti_word_then_space(s, i, n, "enum") ? 4
+ : 0;
+ if (!kw) {
+ return false;
+ }
+ i = ti_skip_space(s, i + kw, n);
+ if (i >= n || !ti_start(s[i])) {
+ return false;
+ }
+ size_t e = ti_word_end(s, i, n);
+ size_t j = ti_skip_space(s, e, n);
+ if (j >= n || s[j] != '{') {
+ return false;
+ }
+ *name = (cbm_ti_span_t){i, e - i};
+ return true;
+}
+
+/* `^\s*extern\b[^;(]*?\b([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*;` */
+bool cbm_ti_match_extern(const char *s, size_t n, cbm_ti_span_t *name) {
+ size_t i = ti_skip_space(s, 0, n);
+ if (!ti_keyword_at(s, i, n, "extern")) {
+ return false;
+ }
+ for (size_t q = i + 6; q < n && s[q] != ';' && s[q] != '('; q++) {
+ if (!ti_identifier_at(s, q)) {
+ continue;
+ }
+ size_t e = ti_word_end(s, q, n);
+ if (ti_array_then_semicolon(s, e, n)) {
+ *name = (cbm_ti_span_t){q, e - q};
+ return true;
+ }
+ }
+ return false;
+}
+
+/* `^[A-Za-z_][\w \t\*]*?\b([A-Za-z_]\w*)\s*\(` */
+bool cbm_ti_match_prototype(const char *s, size_t n, cbm_ti_span_t *name) {
+ if (n == 0 || !ti_start(s[0])) {
+ return false;
+ }
+ for (size_t k = 1; k < n; k++) {
+ if (ti_identifier_at(s, k)) {
+ size_t e = ti_word_end(s, k, n);
+ size_t j = ti_skip_space(s, e, n);
+ if (j < n && s[j] == '(') {
+ *name = (cbm_ti_span_t){k, e - k};
+ return true;
+ }
+ }
+ if (!ti_word(s[k]) && s[k] != ' ' && s[k] != '\t' && s[k] != '*') {
+ return false;
+ }
+ }
+ return false;
+}
+
+bool cbm_ti_match_declaration(const char *s, size_t n, cbm_ti_span_t *name) {
+ return cbm_ti_match_define(s, n, name, NULL) || cbm_ti_match_typedef(s, n, name) ||
+ cbm_ti_match_tag_declaration(s, n, name) || cbm_ti_match_extern(s, n, name) ||
+ cbm_ti_match_prototype(s, n, name);
+}
+
+/* `^\s*#\s*include\s+"([^"]+)"` */
+bool cbm_ti_match_include(const char *s, size_t n, cbm_ti_span_t *path) {
+ size_t i = ti_skip_space(s, 0, n);
+ if (i >= n || s[i] != '#') {
+ return false;
+ }
+ i = ti_skip_space(s, i + 1, n);
+ if (!ti_word_then_space(s, i, n, "include")) {
+ return false;
+ }
+ i = ti_skip_space(s, i + 7, n);
+ if (i >= n || s[i] != '"') {
+ return false;
+ }
+ const char *close = memchr(s + i + 1, '"', n - i - 1);
+ if (!close || close == s + i + 1) {
+ return false;
+ }
+ *path = (cbm_ti_span_t){i + 1, (size_t)(close - s) - i - 1};
+ return true;
+}
+
+/* ── The index ─────────────────────────────────────────────────────── */
+
+typedef struct {
+ int *items;
+ int count;
+ int cap;
+} ti_ints_t;
+
+typedef struct {
+ cbm_ti_place_t *items;
+ int count;
+ int cap;
+} ti_places_t;
+
+typedef struct {
+ const char *path;
+ const char *text;
+ size_t len;
+ size_t *line_starts; /* line i (0-based) starts at line_starts[i] */
+ int line_count;
+ bool header;
+ ti_ints_t includers; /* files that include this one */
+} ti_file_t;
+
+struct cbm_ti_source {
+ CBMArena arena;
+ ti_file_t *files;
+ int file_count;
+ int file_cap;
+ bool finished;
+ bool failed;
+ CBMHashTable *by_path; /* path -> file index + 1 */
+ cbm_ti_macro_t *macros;
+ int macro_count;
+ int macro_cap;
+ CBMHashTable *occurrences; /* token -> ti_places_t* */
+ bool occurrences_built;
+};
+
+static bool ti_grow(void **items, int *cap, int count, size_t size) {
+ if (count < *cap) {
+ return true;
+ }
+ int next = *cap ? *cap * 2 : 8;
+ void *grown = cbm_realloc(CBM_MEM_CLASS_EXTRACT, *items, (size_t)next * size);
+ if (!grown) {
+ return false;
+ }
+ *items = grown;
+ *cap = next;
+ return true;
+}
+
+static bool ti_ints_push(ti_ints_t *a, int v) {
+ if (!ti_grow((void **)&a->items, &a->cap, a->count, sizeof(*a->items))) {
+ return false;
+ }
+ a->items[a->count++] = v;
+ return true;
+}
+
+cbm_ti_source_t *cbm_ti_source_new(void) {
+ cbm_ti_source_t *s = cbm_alloc(CBM_MEM_CLASS_EXTRACT, sizeof(*s));
+ if (!s) {
+ return NULL;
+ }
+ memset(s, 0, sizeof(*s));
+ cbm_arena_init(&s->arena);
+ s->by_path = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ s->occurrences = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ if (!s->by_path || !s->occurrences) {
+ cbm_ti_source_free(s);
+ return NULL;
+ }
+ return s;
+}
+
+static void ti_free_places(const char *key, void *value, void *userdata) {
+ (void)key;
+ (void)userdata;
+ ti_places_t *places = value;
+ cbm_free(CBM_MEM_CLASS_EXTRACT, places->items);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, places);
+}
+
+void cbm_ti_source_free(cbm_ti_source_t *s) {
+ if (!s) {
+ return;
+ }
+ for (int i = 0; i < s->file_count; i++) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->files[i].line_starts);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->files[i].includers.items);
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->files);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s->macros);
+ if (s->occurrences) {
+ cbm_ht_foreach(s->occurrences, ti_free_places, NULL);
+ cbm_ht_free(s->occurrences);
+ }
+ if (s->by_path) {
+ cbm_ht_free(s->by_path);
+ }
+ cbm_arena_destroy(&s->arena);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, s);
+}
+
+static bool ti_is_header_path(const char *path) {
+ size_t n = strlen(path);
+ return (n >= 2 && strcmp(path + n - 2, ".h") == 0) ||
+ (n >= 4 && strcmp(path + n - 4, ".hpp") == 0) ||
+ (n >= 3 && strcmp(path + n - 3, ".hh") == 0);
+}
+
+bool cbm_ti_source_add(cbm_ti_source_t *s, const char *path, const char *text, size_t len) {
+ if (!s || s->finished || !path || (!text && len) || cbm_ht_has(s->by_path, path)) {
+ return false;
+ }
+ if (!ti_grow((void **)&s->files, &s->file_cap, s->file_count, sizeof(*s->files))) {
+ return false;
+ }
+ char *own_text = cbm_arena_alloc(&s->arena, len + 1);
+ char *own_path = cbm_arena_strdup(&s->arena, path);
+ if (!own_text || !own_path) {
+ return false;
+ }
+ if (len) {
+ memcpy(own_text, text, len);
+ }
+ own_text[len] = '\0';
+ s->files[s->file_count] = (ti_file_t){
+ .path = own_path, .text = own_text, .len = len, .header = ti_is_header_path(own_path)};
+ s->file_count++;
+ return true;
+}
+
+/* Lines as the reference splits them (`text.split('\n')`): a final newline
+ * leaves one more, empty line. */
+static bool ti_split_lines(ti_file_t *f) {
+ int count = 1;
+ for (size_t i = 0; i < f->len; i++) {
+ count += f->text[i] == '\n';
+ }
+ f->line_starts = cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)count * sizeof(size_t));
+ if (!f->line_starts) {
+ return false;
+ }
+ int at = 0;
+ f->line_starts[at++] = 0;
+ for (size_t i = 0; i < f->len; i++) {
+ if (f->text[i] == '\n') {
+ f->line_starts[at++] = i + 1;
+ }
+ }
+ f->line_count = count;
+ return true;
+}
+
+static int ti_path_compare(const void *left, const void *right) {
+ return strcmp(((const ti_file_t *)left)->path, ((const ti_file_t *)right)->path);
+}
+
+int cbm_ti_source_file_count(const cbm_ti_source_t *s) {
+ return s ? s->file_count : 0;
+}
+
+const char *cbm_ti_source_path(const cbm_ti_source_t *s, int file) {
+ return s && file >= 0 && file < s->file_count ? s->files[file].path : NULL;
+}
+
+int cbm_ti_source_find(const cbm_ti_source_t *s, const char *path) {
+ if (!s || !path) {
+ return -1;
+ }
+ intptr_t at = (intptr_t)cbm_ht_get(s->by_path, path);
+ return at > 0 ? (int)at - 1 : -1;
+}
+
+bool cbm_ti_source_is_header(const cbm_ti_source_t *s, int file) {
+ return s && file >= 0 && file < s->file_count && s->files[file].header;
+}
+
+int cbm_ti_source_line_count(const cbm_ti_source_t *s, int file) {
+ return s && file >= 0 && file < s->file_count ? s->files[file].line_count : 0;
+}
+
+const char *cbm_ti_source_line(const cbm_ti_source_t *s, int file, int line, size_t *len) {
+ if (!s || file < 0 || file >= s->file_count || line < 1 || line > s->files[file].line_count) {
+ if (len) {
+ *len = 0;
+ }
+ return NULL;
+ }
+ const ti_file_t *f = &s->files[file];
+ size_t start = f->line_starts[line - 1];
+ size_t end = line < f->line_count ? f->line_starts[line] - 1 : f->len;
+ if (len) {
+ *len = end - start;
+ }
+ return f->text + start;
+}
+
+/* ── Includes ──────────────────────────────────────────────────────── */
+
+/* os.path.normpath(os.path.join(dirname(from), inc)) for '/' paths. */
+static char *ti_normalize_join(CBMArena *arena, const char *from, const char *inc, size_t inc_len) {
+ size_t from_len = strlen(from);
+ const char *slash = NULL;
+ for (size_t i = 0; i < from_len; i++) {
+ if (from[i] == '/') {
+ slash = from + i;
+ }
+ }
+ size_t dir_len = inc_len && inc[0] == '/' ? 0 : (slash ? (size_t)(slash - from) : 0);
+ size_t total = dir_len + 1 + inc_len;
+ char *joined = cbm_arena_alloc(arena, total + 1);
+ char *out = cbm_arena_alloc(arena, total + 2);
+ if (!joined || !out) {
+ return NULL;
+ }
+ memcpy(joined, from, dir_len);
+ joined[dir_len] = '/';
+ memcpy(joined + dir_len + 1, inc, inc_len);
+ joined[total] = '\0';
+ bool absolute = inc_len && inc[0] == '/';
+ size_t used = 0;
+ size_t depth = 0; /* segments that can be removed by a later ".." */
+ const char *p = dir_len ? joined : joined + 1;
+ while (*p) {
+ const char *e = strchr(p, '/');
+ size_t seg = e ? (size_t)(e - p) : strlen(p);
+ if (seg == 0 || (seg == 1 && p[0] == '.')) {
+ /* skip */
+ } else if (seg == 2 && p[0] == '.' && p[1] == '.' && depth > 0) {
+ while (used > 0 && out[used - 1] != '/') {
+ used--;
+ }
+ if (used > 0) {
+ used--;
+ }
+ depth--;
+ } else if (!(seg == 2 && p[0] == '.' && p[1] == '.' && absolute)) {
+ if (used) {
+ out[used++] = '/';
+ }
+ memcpy(out + used, p, seg);
+ used += seg;
+ depth += !(seg == 2 && p[0] == '.' && p[1] == '.');
+ }
+ p += seg + (e ? 1 : 0);
+ }
+ out[used] = '\0';
+ return out;
+}
+
+/* Every segment suffix of every path, for includes that do not resolve from
+ * the including file's directory. */
+static bool ti_add_suffixes(cbm_ti_source_t *s, CBMHashTable *suffixes, ti_ints_t **lists,
+ int *list_count, int *list_cap) {
+ for (int f = 0; f < s->file_count; f++) {
+ const char *path = s->files[f].path;
+ for (const char *p = path; p; p = strchr(p, '/') ? strchr(p, '/') + 1 : NULL) {
+ intptr_t at = (intptr_t)cbm_ht_get(suffixes, p);
+ if (!at) {
+ if (!ti_grow((void **)lists, list_cap, *list_count, sizeof(**lists))) {
+ return false;
+ }
+ (*lists)[*list_count] = (ti_ints_t){0};
+ at = ++*list_count;
+ cbm_ht_set(suffixes, p, (void *)at);
+ }
+ if (!ti_ints_push(&(*lists)[at - 1], f)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+static bool ti_add_includer(cbm_ti_source_t *s, int target, int from) {
+ ti_ints_t *in = &s->files[target].includers;
+ if (in->count && in->items[in->count - 1] == from) {
+ return true;
+ }
+ for (int i = 0; i < in->count; i++) {
+ if (in->items[i] == from) {
+ return true;
+ }
+ }
+ return ti_ints_push(in, from);
+}
+
+static bool ti_resolve_include(cbm_ti_source_t *s, CBMHashTable *suffixes, const ti_ints_t *lists,
+ int from, const char *inc, size_t inc_len) {
+ char *normal = ti_normalize_join(&s->arena, s->files[from].path, inc, inc_len);
+ if (!normal) {
+ return false;
+ }
+ int direct = cbm_ti_source_find(s, normal);
+ if (direct >= 0) {
+ return ti_add_includer(s, direct, from);
+ }
+ size_t skip = 0;
+ while (skip < inc_len && (inc[skip] == '.' || inc[skip] == '/')) {
+ skip++;
+ }
+ char *key = cbm_arena_strndup(&s->arena, inc + skip, inc_len - skip);
+ if (!key) {
+ return false;
+ }
+ intptr_t at = (intptr_t)cbm_ht_get(suffixes, key);
+ for (int i = 0; at && i < lists[at - 1].count; i++) {
+ if (!ti_add_includer(s, lists[at - 1].items[i], from)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool ti_build_includes(cbm_ti_source_t *s) {
+ CBMHashTable *suffixes = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 0);
+ ti_ints_t *lists = NULL;
+ int list_count = 0;
+ int list_cap = 0;
+ bool ok = suffixes && ti_add_suffixes(s, suffixes, &lists, &list_count, &list_cap);
+ for (int f = 0; ok && f < s->file_count; f++) {
+ for (int line = 1; ok && line <= s->files[f].line_count; line++) {
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(s, f, line, &len);
+ cbm_ti_span_t inc;
+ if (cbm_ti_match_include(text, len, &inc)) {
+ ok = ti_resolve_include(s, suffixes, lists, f, text + inc.start, inc.len);
+ }
+ }
+ }
+ for (int i = 0; i < list_count; i++) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, lists[i].items);
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, lists);
+ if (suffixes) {
+ cbm_ht_free(suffixes);
+ }
+ return ok;
+}
+
+void cbm_ti_source_include_closure(const cbm_ti_source_t *s, bool *marked) {
+ if (!s || !marked || !s->finished) {
+ return;
+ }
+ int *stack = cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)(s->file_count + 1) * sizeof(int));
+ if (!stack) {
+ /* Out of memory: mark everything, which can only select more. */
+ for (int i = 0; i < s->file_count; i++) {
+ marked[i] = true;
+ }
+ return;
+ }
+ int top = 0;
+ for (int i = 0; i < s->file_count; i++) {
+ if (marked[i]) {
+ stack[top++] = i;
+ }
+ }
+ while (top > 0) {
+ const ti_ints_t *in = &s->files[stack[--top]].includers;
+ for (int i = 0; i < in->count; i++) {
+ if (!marked[in->items[i]]) {
+ marked[in->items[i]] = true;
+ stack[top++] = in->items[i];
+ }
+ }
+ }
+ cbm_free(CBM_MEM_CLASS_EXTRACT, stack);
+}
+
+/* ── Header macros ─────────────────────────────────────────────────── */
+
+typedef struct {
+ const char **items;
+ int count;
+ int cap;
+} ti_strs_t;
+
+static bool ti_strs_add_unique(CBMArena *arena, ti_strs_t *list, const char *word, size_t len) {
+ for (int i = 0; i < list->count; i++) {
+ if (strlen(list->items[i]) == len && memcmp(list->items[i], word, len) == 0) {
+ return true;
+ }
+ }
+ char *copy = cbm_arena_strndup(arena, word, len);
+ if (!copy || !ti_grow((void **)&list->items, &list->cap, list->count, sizeof(*list->items))) {
+ return false;
+ }
+ list->items[list->count++] = copy;
+ return true;
+}
+
+static int ti_str_compare(const void *left, const void *right) {
+ return strcmp(*(const char *const *)left, *(const char *const *)right);
+}
+
+/* `re.findall(r'([A-Za-z_]\w*)\s*##|##\s*([A-Za-z_]\w*)', text)` */
+static bool ti_scan_pastes(CBMArena *arena, const char *t, size_t n, ti_strs_t *pre,
+ ti_strs_t *suf) {
+ size_t i = 0;
+ while (i < n) {
+ if (ti_start(t[i])) {
+ size_t e = ti_word_end(t, i, n);
+ size_t j = ti_skip_space(t, e, n);
+ if (j + 1 < n && t[j] == '#' && t[j + 1] == '#') {
+ if (!ti_strs_add_unique(arena, pre, t + i, e - i)) {
+ return false;
+ }
+ i = j + 2;
+ continue;
+ }
+ }
+ if (i + 1 < n && t[i] == '#' && t[i + 1] == '#') {
+ size_t j = ti_skip_space(t, i + 2, n);
+ if (j < n && ti_start(t[j])) {
+ size_t e = ti_word_end(t, j, n);
+ if (!ti_strs_add_unique(arena, suf, t + j, e - j)) {
+ return false;
+ }
+ i = e;
+ continue;
+ }
+ }
+ i++;
+ }
+ return true;
+}
+
+/* `set(TOKEN_RX.findall(text)) - C_KEYWORDS - {name}` */
+static bool ti_scan_tokens(CBMArena *arena, const char *t, size_t n, const char *name,
+ ti_strs_t *out) {
+ size_t i = 0;
+ while (i < n) {
+ if (!ti_start(t[i])) {
+ i++;
+ continue;
+ }
+ size_t e = ti_word_end(t, i, n);
+ bool own = strlen(name) == e - i && memcmp(name, t + i, e - i) == 0;
+ if (!own && !cbm_ti_is_keyword(t + i, e - i) &&
+ !ti_strs_add_unique(arena, out, t + i, e - i)) {
+ return false;
+ }
+ i = e;
+ }
+ return true;
+}
+
+static bool ti_line_continues(const char *line, size_t len) {
+ while (len > 0 && ti_space(line[len - 1])) {
+ len--;
+ }
+ return len > 0 && line[len - 1] == '\\';
+}
+
+/* One `#define` starting at *line; *line ends on its last continuation line.
+ * The body is the text after the name (and '('), then each continuation
+ * line, joined with one blank. */
+static bool ti_read_macro(cbm_ti_source_t *s, int file, int *line, cbm_ti_span_t name,
+ size_t body) {
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(s, file, *line, &len);
+ size_t cap = len - body + 1;
+ int last = *line;
+ const char *tail = text + body;
+ size_t tail_len = len - body;
+ while (ti_line_continues(tail, tail_len) && last < s->files[file].line_count) {
+ last++;
+ tail = cbm_ti_source_line(s, file, last, &tail_len);
+ cap += tail_len + 1;
+ }
+ char *joined = cbm_arena_alloc(&s->arena, cap + 1);
+ char *macro_name = cbm_arena_strndup(&s->arena, text + name.start, name.len);
+ if (!joined || !macro_name) {
+ return false;
+ }
+ size_t used = len - body;
+ memcpy(joined, text + body, used);
+ for (int l = *line + 1; l <= last; l++) {
+ const char *more = cbm_ti_source_line(s, file, l, &tail_len);
+ joined[used++] = ' ';
+ memcpy(joined + used, more, tail_len);
+ used += tail_len;
+ }
+ joined[used] = '\0';
+ ti_strs_t tokens = {0};
+ ti_strs_t pre = {0};
+ ti_strs_t suf = {0};
+ bool ok = ti_scan_tokens(&s->arena, joined, used, macro_name, &tokens) &&
+ ti_scan_pastes(&s->arena, joined, used, &pre, &suf) &&
+ ti_grow((void **)&s->macros, &s->macro_cap, s->macro_count, sizeof(*s->macros));
+ if (ok && tokens.count > 1) {
+ qsort(tokens.items, (size_t)tokens.count, sizeof(*tokens.items), ti_str_compare);
+ }
+ const char **kept[3] = {NULL, NULL, NULL};
+ ti_strs_t *lists[3] = {&tokens, &pre, &suf};
+ for (int k = 0; ok && k < 3; k++) {
+ size_t bytes = (size_t)(lists[k]->count ? lists[k]->count : 1) * sizeof(char *);
+ kept[k] = cbm_arena_alloc(&s->arena, bytes);
+ ok = kept[k] != NULL;
+ if (ok && lists[k]->count) {
+ memcpy(kept[k], lists[k]->items, (size_t)lists[k]->count * sizeof(char *));
+ }
+ }
+ if (ok) {
+ s->macros[s->macro_count++] = (cbm_ti_macro_t){.name = macro_name,
+ .file = file,
+ .tokens = kept[0],
+ .token_count = tokens.count,
+ .paste_prefixes = kept[1],
+ .paste_prefix_count = pre.count,
+ .paste_suffixes = kept[2],
+ .paste_suffix_count = suf.count};
+ }
+ for (int k = 0; k < 3; k++) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, lists[k]->items);
+ }
+ *line = last;
+ return ok;
+}
+
+static bool ti_build_macros(cbm_ti_source_t *s) {
+ for (int f = 0; f < s->file_count; f++) {
+ if (!s->files[f].header) {
+ continue;
+ }
+ for (int line = 1; line <= s->files[f].line_count; line++) {
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(s, f, line, &len);
+ cbm_ti_span_t name;
+ size_t body = 0;
+ if (cbm_ti_match_define(text, len, &name, &body) &&
+ !ti_read_macro(s, f, &line, name, body)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+const cbm_ti_macro_t *cbm_ti_source_macros(const cbm_ti_source_t *s, int *count) {
+ if (count) {
+ *count = s ? s->macro_count : 0;
+ }
+ return s ? s->macros : NULL;
+}
+
+bool cbm_ti_source_finish(cbm_ti_source_t *s) {
+ if (!s || s->finished) {
+ return false;
+ }
+ if (s->file_count > 1) {
+ qsort(s->files, (size_t)s->file_count, sizeof(*s->files), ti_path_compare);
+ }
+ for (int f = 0; f < s->file_count; f++) {
+ if (!ti_split_lines(&s->files[f])) {
+ return false;
+ }
+ cbm_ht_set(s->by_path, s->files[f].path, (void *)(intptr_t)(f + 1));
+ }
+ s->finished = true;
+ return ti_build_includes(s) && ti_build_macros(s);
+}
+
+/* ── Occurrences ───────────────────────────────────────────────────── */
+
+static bool ti_note_occurrence(cbm_ti_source_t *s, const char *word, size_t len, int file,
+ int line) {
+ char key[256];
+ const char *lookup;
+ char *heap_key = NULL;
+ if (len < sizeof(key)) {
+ memcpy(key, word, len);
+ key[len] = '\0';
+ lookup = key;
+ } else {
+ heap_key = cbm_arena_strndup(&s->arena, word, len);
+ if (!heap_key) {
+ return false;
+ }
+ lookup = heap_key;
+ }
+ ti_places_t *places = cbm_ht_get(s->occurrences, lookup);
+ if (!places) {
+ places = cbm_alloc(CBM_MEM_CLASS_EXTRACT, sizeof(*places));
+ const char *owned = heap_key ? heap_key : cbm_arena_strndup(&s->arena, word, len);
+ if (!places || !owned) {
+ cbm_free(CBM_MEM_CLASS_EXTRACT, places);
+ return false;
+ }
+ *places = (ti_places_t){0};
+ cbm_ht_set(s->occurrences, owned, places);
+ }
+ if (places->count && places->items[places->count - 1].file == file &&
+ places->items[places->count - 1].line == line) {
+ return true; /* one place per line */
+ }
+ if (!ti_grow((void **)&places->items, &places->cap, places->count, sizeof(*places->items))) {
+ return false;
+ }
+ places->items[places->count++] = (cbm_ti_place_t){file, line};
+ return true;
+}
+
+/* `for t in set(TOKEN_RX.findall(ln))` on lines not starting `//` or `*`. */
+static bool ti_scan_line(cbm_ti_source_t *s, int file, int line) {
+ size_t len = 0;
+ const char *text = cbm_ti_source_line(s, file, line, &len);
+ size_t i = ti_skip_space(text, 0, len);
+ if (i < len && (text[i] == '*' || (text[i] == '/' && i + 1 < len && text[i + 1] == '/'))) {
+ return true;
+ }
+ while (i < len) {
+ if (!ti_start(text[i])) {
+ i++;
+ continue;
+ }
+ size_t e = ti_word_end(text, i, len);
+ if (!cbm_ti_is_keyword(text + i, e - i) &&
+ !ti_note_occurrence(s, text + i, e - i, file, line)) {
+ return false;
+ }
+ i = e;
+ }
+ return true;
+}
+
+bool cbm_ti_source_build_occurrences(cbm_ti_source_t *s) {
+ if (!s || !s->finished || s->failed) {
+ return false;
+ }
+ if (s->occurrences_built) {
+ return true;
+ }
+ for (int f = 0; f < s->file_count; f++) {
+ for (int line = 1; line <= s->files[f].line_count; line++) {
+ if (!ti_scan_line(s, f, line)) {
+ s->failed = true;
+ return false;
+ }
+ }
+ }
+ s->occurrences_built = true;
+ return true;
+}
+
+const cbm_ti_place_t *cbm_ti_source_occurrences(const cbm_ti_source_t *s, const char *token,
+ size_t len, int *count) {
+ *count = 0;
+ if (!s || !s->occurrences_built || !token) {
+ return NULL;
+ }
+ char key[256];
+ if (len >= sizeof(key)) {
+ return NULL; /* never indexed under a stack key; looked up below */
+ }
+ memcpy(key, token, len);
+ key[len] = '\0';
+ const ti_places_t *places = cbm_ht_get(s->occurrences, key);
+ if (!places) {
+ return NULL;
+ }
+ *count = places->count;
+ return places->items;
+}
diff --git a/src/mcp/test_impact_source.h b/src/mcp/test_impact_source.h
new file mode 100644
index 000000000..37cdbd65f
--- /dev/null
+++ b/src/mcp/test_impact_source.h
@@ -0,0 +1,117 @@
+/*
+ * test_impact_source.h — text facts about the C-family sources of one snapshot.
+ *
+ * Some seeding rules of the test-impact engine (smart-ci-design 5.1 and 5.8)
+ * ask questions the graph cannot answer: which files include a header,
+ * directly or not; where an identifier is written; which macros the headers
+ * define and what their bodies name; what a changed line declares. This index
+ * answers them from the exact bytes of the snapshot's C-family files.
+ *
+ * It ports the measured reference (scratchpad tia3/replay4.py: build_occ,
+ * include_closure, header_macros and its line patterns) rule for rule,
+ * including where the rules over-approximate: identifiers inside strings and
+ * block comments count as occurrences. Every rule here can only add seeds, so
+ * an approximation selects more tests, never fewer. Identifiers are ASCII
+ * ([A-Za-z_][A-Za-z0-9_]*); a byte outside ASCII ends one.
+ */
+#ifndef CBM_TEST_IMPACT_SOURCE_H
+#define CBM_TEST_IMPACT_SOURCE_H
+
+#include <stdbool.h>
+#include <stddef.h>
+
+/* ── Line patterns ─────────────────────────────────────────────────
+ * Each takes one line without its newline (a trailing '\r' is blank space)
+ * and reports the declared name as an offset and length into the line. */
+
+typedef struct {
+ size_t start;
+ size_t len;
+} cbm_ti_span_t;
+
+/* Blank, or a comment line: starts with `//`, `/ *` or `*`, or ends with the
+ * close of a block comment. */
+bool cbm_ti_line_is_comment(const char *line, size_t len);
+/* `#if`, `#ifdef`, `#ifndef`, `#elif`, `#else`, `#endif`, `#undef` or
+ * `#include`. */
+bool cbm_ti_line_is_pp_condition(const char *line, size_t len);
+/* `#define NAME`; *body is where the replacement text starts (after the
+ * parameter list's '(' for a function-like macro, as the reference reads it). */
+bool cbm_ti_match_define(const char *line, size_t len, cbm_ti_span_t *name, size_t *body);
+/* The name a `typedef ... NAME [N];` introduces, anywhere on the line. */
+bool cbm_ti_match_typedef(const char *line, size_t len, cbm_ti_span_t *name);
+/* `[typedef] struct|union|enum NAME {` at the start of the line. */
+bool cbm_ti_match_tag_declaration(const char *line, size_t len, cbm_ti_span_t *name);
+/* `extern ... NAME [N];` at the start of the line. */
+bool cbm_ti_match_extern(const char *line, size_t len, cbm_ti_span_t *name);
+/* A function name followed by '(' on a line that starts with an identifier
+ * character, not the first word: `int f(`, `static T *g (`. */
+bool cbm_ti_match_prototype(const char *line, size_t len, cbm_ti_span_t *name);
+/* The name a changed header line declares, trying define, typedef, tag
+ * declaration, extern and prototype in that order (replay4 header_seeds). */
+bool cbm_ti_match_declaration(const char *line, size_t len, cbm_ti_span_t *name);
+/* `#include "PATH"`: the quoted path. */
+bool cbm_ti_match_include(const char *line, size_t len, cbm_ti_span_t *path);
+bool cbm_ti_is_keyword(const char *word, size_t len);
+
+/* ── The index ─────────────────────────────────────────────────────── */
+
+typedef struct cbm_ti_source cbm_ti_source_t;
+
+typedef struct {
+ int file; /* index in path order */
+ int line; /* 1-based */
+} cbm_ti_place_t;
+
+typedef struct {
+ const char *name;
+ int file;
+ /* Identifiers of the replacement text, keywords and the macro's own name
+ * removed. Sorted, unique. */
+ const char *const *tokens;
+ int token_count;
+ /* `X ##` and `## X` operands: a changed name that starts with a prefix or
+ * ends with a suffix may be what the paste builds. */
+ const char *const *paste_prefixes;
+ int paste_prefix_count;
+ const char *const *paste_suffixes;
+ int paste_suffix_count;
+} cbm_ti_macro_t;
+
+/* NULL when out of memory. */
+cbm_ti_source_t *cbm_ti_source_new(void);
+/* Add one file: its repository-relative path and exact bytes (both copied).
+ * false on a repeated path, after finish, or when out of memory. */
+bool cbm_ti_source_add(cbm_ti_source_t *s, const char *path, const char *text, size_t len);
+/* Split lines, resolve includes and read the headers' macros. Files are then
+ * in path order. false when out of memory. */
+bool cbm_ti_source_finish(cbm_ti_source_t *s);
+void cbm_ti_source_free(cbm_ti_source_t *s);
+
+int cbm_ti_source_file_count(const cbm_ti_source_t *s);
+const char *cbm_ti_source_path(const cbm_ti_source_t *s, int file);
+/* -1 when the snapshot has no such C-family file. */
+int cbm_ti_source_find(const cbm_ti_source_t *s, const char *path);
+/* .h, .hpp, .hh */
+bool cbm_ti_source_is_header(const cbm_ti_source_t *s, int file);
+int cbm_ti_source_line_count(const cbm_ti_source_t *s, int file);
+/* Line text without its newline; NULL outside the file. */
+const char *cbm_ti_source_line(const cbm_ti_source_t *s, int file, int line, size_t *len);
+
+/* Mark every file that includes a marked file, directly or through other
+ * files. `marked` holds one entry per file. A quoted include names the file
+ * it resolves to from the including file's directory when that file exists,
+ * otherwise every file whose path ends with the included path. */
+void cbm_ti_source_include_closure(const cbm_ti_source_t *s, bool *marked);
+
+/* The `#define`s of the header files, in (file, line) order. */
+const cbm_ti_macro_t *cbm_ti_source_macros(const cbm_ti_source_t *s, int *count);
+
+/* Where an identifier is written, in (file, line) order, one place per line.
+ * Lines whose first non-blank text is `//` or `*` hold none, nor do keywords.
+ * The index is built on the first call: false from build means out of memory. */
+bool cbm_ti_source_build_occurrences(cbm_ti_source_t *s);
+const cbm_ti_place_t *cbm_ti_source_occurrences(const cbm_ti_source_t *s, const char *token,
+ size_t len, int *count);
+
+#endif /* CBM_TEST_IMPACT_SOURCE_H */
diff --git a/src/mcp/test_impact_tree.c b/src/mcp/test_impact_tree.c
index ed3f64ca0..6f3437623 100644
--- a/src/mcp/test_impact_tree.c
+++ b/src/mcp/test_impact_tree.c
@@ -27,14 +27,57 @@ static cbm_pinned_tree_t *tpt_owner(tpt_context *c, const cbm_pinned_tree_option
return t;
}
+/* The entries the tree materializes: everything but symlinks and submodule
+ * links, which are counted instead. Other non-regular kinds stay in, so the
+ * plan still refuses them. Entries borrow the facts' strings, which outlive
+ * the create call. */
+static bool tpt_without_links(tpt_context *c, const cbm_git_tree_inventory_t *all,
+ cbm_git_tree_inventory_t *kept, size_t **original) {
+ *kept = (cbm_git_tree_inventory_t){0};
+ *original = NULL;
+ if (all->count == 0)
+ return true;
+ cbm_git_tree_entry_t *entries = tpt_alloc(c, all->count, sizeof(*entries));
+ size_t *positions = tpt_alloc(c, all->count, sizeof(*positions));
+ if (!entries || !positions)
+ return false;
+ size_t n = 0;
+ size_t skipped = 0;
+ for (size_t i = 0; i < all->count; i++) {
+ if (!tpt_poll(c))
+ return false;
+ const cbm_git_tree_entry_t *entry = &all->entries[i];
+ bool link = (entry->mode == 0120000 && entry->object_type == CBM_GIT_TREE_BLOB) ||
+ (entry->mode == 0160000 && entry->object_type == CBM_GIT_TREE_COMMIT);
+ if (link) {
+ skipped++;
+ } else {
+ positions[n] = i;
+ entries[n++] = *entry;
+ }
+ }
+ kept->entries = entries;
+ kept->count = n;
+ *original = positions;
+ c->tree->view.skipped_link_count = skipped;
+ return true;
+}
+
static bool tpt_load(tpt_context *c, const cbm_pinned_tree_options_t *o) {
if (!tpt_identity_copy(c, o) || !tpt_poll(c))
return false;
cbm_git_tree_inventory_t inventory = {0};
+ cbm_git_tree_inventory_t regular = {0};
+ size_t *original = NULL;
cbm_git_facts_error_t error = {0};
bool ok = cbm_git_facts_inventory(o->facts, o->revision, &inventory, &error);
- if (!tpt_after_facts(c, ok, &error) || !tpt_plan(c, o, &inventory))
+ if (!tpt_after_facts(c, ok, &error) || !tpt_without_links(c, &inventory, &regular, &original) ||
+ !tpt_plan(c, o, &regular))
return false;
+ /* The plan numbered the kept entries; the blob batch names positions in
+ * the facts' own inventory. */
+ for (size_t i = 0; original && i < c->tree->view.file_count; i++)
+ c->tree->indices[i] = original[c->tree->indices[i]];
cbm_git_blob_batch_t batch = {0};
return tpt_batch(c, o, &batch) && tpt_native_prepare(c) && tpt_build(c, &batch) &&
tpt_audit(c) && tpt_manifest(c) && tpt_poll(c);
diff --git a/src/mcp/test_impact_tree.h b/src/mcp/test_impact_tree.h
index 34895a9a1..b3e579ca2 100644
--- a/src/mcp/test_impact_tree.h
+++ b/src/mcp/test_impact_tree.h
@@ -80,6 +80,11 @@ typedef struct {
size_t file_count;
size_t directory_count; /* root plus unique proper path prefixes */
uint64_t total_content_bytes;
+ /* Symlink (0120000) and submodule (0160000) entries of the revision. They
+ * are not materialized and not in `files`: discovery never indexes a
+ * symlink, and a submodule's content is not in this repository. Any other
+ * non-regular entry still fails the pin. */
+ size_t skipped_link_count;
unsigned char manifest_sha256[32]; /* exact framing in normative text */
} cbm_pinned_tree_view_t;
diff --git a/src/mcp/test_impact_tree_batch.c b/src/mcp/test_impact_tree_batch.c
index 37a2c2f31..695421eb1 100644
--- a/src/mcp/test_impact_tree_batch.c
+++ b/src/mcp/test_impact_tree_batch.c
@@ -4,9 +4,9 @@ static bool tpt_batch_row(tpt_context *c, const cbm_git_blob_batch_item_t *item,
cbm_pinned_tree_t *t = c->tree;
cbm_pinned_tree_file_t *file = &t->files[index];
const cbm_git_tree_entry_t *e = item->entry;
- if (!e || !e->path || item->inventory_index != index || e->object_type != CBM_GIT_TREE_BLOB ||
- e->mode != file->git_mode || e->path_length != file->path_length ||
- !tpt_oid(c, e->oid, t->identity.oid_hex_length))
+ if (!e || !e->path || item->inventory_index != t->indices[index] ||
+ e->object_type != CBM_GIT_TREE_BLOB || e->mode != file->git_mode ||
+ e->path_length != file->path_length || !tpt_oid(c, e->oid, t->identity.oid_hex_length))
return tpt_fail(c, CBM_PINNED_TREE_GIT, "batch row identity");
if (!tpt_equal(c, e->path, file->path, file->path_length) ||
!tpt_equal(c, e->oid, file->oid, t->identity.oid_hex_length + 1) ||
diff --git a/src/mcp/test_impact_tree_digest.c b/src/mcp/test_impact_tree_digest.c
index 51f6c7b31..df0812ba7 100644
--- a/src/mcp/test_impact_tree_digest.c
+++ b/src/mcp/test_impact_tree_digest.c
@@ -1,7 +1,7 @@
#include "mcp/test_impact_tree_internal.h"
static bool tpt_number(tpt_context *c, cbm_sha256_ctx *h, uint64_t number, size_t width) {
- unsigned char bytes[8];
+ unsigned char bytes[8] = {0};
for (size_t i = 0; i < width; i++)
bytes[width - 1 - i] = (unsigned char)(number >> (i * 8));
return tpt_hash(c, h, bytes, width);
diff --git a/src/mcp/test_impact_tree_internal.h b/src/mcp/test_impact_tree_internal.h
index ab32f2f8a..d481b6a59 100644
--- a/src/mcp/test_impact_tree_internal.h
+++ b/src/mcp/test_impact_tree_internal.h
@@ -1,6 +1,13 @@
#ifndef CBM_TEST_IMPACT_TREE_INTERNAL_H
#define CBM_TEST_IMPACT_TREE_INTERNAL_H
+#ifdef _WIN32
+/* FILE_ID_INFO (stable 128-bit file identity) is a Windows 8 API; pin it
+ * before any system header so toolchains with an older default see it. */
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0602
+#endif
+#endif
#ifndef _WIN32
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.c
index e5092e356..b9f78045c 100644
--- a/src/pipeline/pass_calls.c
+++ b/src/pipeline/pass_calls.c
@@ -1013,10 +1013,12 @@ static CBMFileResult *calls_get_or_extract(cbm_pipeline_ctx_t *ctx, int idx,
}
return NULL;
}
- CBMFileResult *r = cbm_pipeline_test_force_extract_null(ctx, fi->language) ? NULL :
- cbm_extract_file_ex_with_tests(
- src, slen, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET,
- NULL, NULL, ctx->macro_table, ctx->return_type_table, ctx->test_declarations);
+ CBMFileResult *r =
+ cbm_pipeline_test_force_extract_null(ctx, fi->language)
+ ? NULL
+ : cbm_extract_file_ex_with_tests(
+ src, slen, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET,
+ NULL, NULL, ctx->macro_table, ctx->return_type_table, ctx->test_declarations);
free(src);
(void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r);
if (r) {
diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.c
index f0673c9e9..291da2da0 100644
--- a/src/pipeline/pass_definitions.c
+++ b/src/pipeline/pass_definitions.c
@@ -25,6 +25,7 @@ enum { PD_JSON_FIELD_OVERHEAD = 6 };
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/limits.h"
+#include "foundation/mem_core.h"
#include "foundation/str_util.h"
#include "cbm.h"
#include "arena.h"
@@ -256,9 +257,9 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
* dump. Gate the block to functions; other labels keep the lean base. */
const bool is_fn =
def->label && (strcmp(def->label, "Function") == 0 || strcmp(def->label, "Method") == 0);
- const char *test_role = def->test_role == CBM_TEST_ROLE_CASE ? ",\"test_role\":\"case\""
+ const char *test_role = def->test_role == CBM_TEST_ROLE_CASE ? ",\"test_role\":\"case\""
: def->test_role == CBM_TEST_ROLE_SUITE ? ",\"test_role\":\"suite\""
- : "";
+ : "";
int n;
if (is_fn) {
n = snprintf(buf, bufsize,
@@ -279,7 +280,8 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
"{\"complexity\":%d,\"lines\":%d,\"is_exported\":%s,\"is_test\":%s,"
"\"is_entry_point\":%s%s",
def->complexity, def->lines, def->is_exported ? "true" : "false",
- def->is_test ? "true" : "false", def->is_entry_point ? "true" : "false", test_role);
+ def->is_test ? "true" : "false", def->is_entry_point ? "true" : "false",
+ test_role);
}
if (n <= 0 || (size_t)n >= bufsize) {
@@ -754,7 +756,8 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
CBMFileResult **local_cache = ctx->result_cache;
bool owns_local_cache = false;
if (!local_cache) {
- local_cache = (CBMFileResult **)calloc((size_t)file_count, sizeof(CBMFileResult *));
+ local_cache = (CBMFileResult **)cbm_calloc(CBM_MEM_CLASS_EXTRACT,
+ (size_t)file_count * sizeof(CBMFileResult *));
owns_local_cache = (local_cache != NULL);
}
@@ -773,7 +776,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
cbm_free_result(local_cache[j]);
}
}
- free(local_cache);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, local_cache);
}
return CBM_NOT_FOUND;
}
@@ -839,14 +842,14 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
/* Studio Export XML is transformed to one cacheable aggregate so later
* passes see the same calls/usages/semantic carriers as native UDL. */
CBMFileResult *result =
- cbm_pipeline_test_force_extract_null(ctx, lang) ? NULL :
- lang == CBM_LANG_OBJECTSCRIPT_EXPORT
+ cbm_pipeline_test_force_extract_null(ctx, lang) ? NULL
+ : lang == CBM_LANG_OBJECTSCRIPT_EXPORT
? cbm_pipeline_extract_objectscript_export(source, source_len, ctx->project_name,
rel, ctx->macro_table, NULL)
- : cbm_extract_file_ex_with_tests(
- source, source_len, lang, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL,
- NULL /* no extra defines or include paths */, ctx->macro_table, NULL,
- ctx->test_declarations);
+ : cbm_extract_file_ex_with_tests(source, source_len, lang, ctx->project_name, rel,
+ CBM_EXTRACT_BUDGET, NULL,
+ NULL /* no extra defines or include paths */,
+ ctx->macro_table, NULL, ctx->test_declarations);
free(source);
if (!cbm_pipeline_test_extraction_ok(ctx, lang, result)) {
@@ -881,6 +884,14 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
ctx->pipeline, rel, result->error_ranges ? result->error_ranges : "unknown",
result->parse_unusable ? "parse_unusable" : "parse_partial");
}
+ if (result->test_declarations_degraded) {
+ /* Its configured test forms could not be mapped: indexed without
+ * configured test roles (degraded per file, not the index). */
+ cbm_pipeline_add_file_error(
+ ctx->pipeline, rel,
+ cbm_test_extract_status_message(result->test_declarations_degraded_status),
+ "test_declarations");
+ }
/* Create nodes for each definition */
for (int d = 0; d < result->defs.count; d++) {
@@ -943,7 +954,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
cbm_free_result(local_cache[i]);
}
}
- free(local_cache);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, local_cache);
}
}
@@ -957,7 +968,7 @@ configured_failure:
for (int j = 0; j < file_count; j++) {
cbm_free_result(local_cache[j]);
}
- free(local_cache);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, local_cache);
}
return CBM_PIPELINE_ABORT_PRESERVE_DB;
}
diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c
index 5b63ec871..a3c891276 100644
--- a/src/pipeline/pass_lsp_cross.c
+++ b/src/pipeline/pass_lsp_cross.c
@@ -16,6 +16,7 @@
#include "pipeline/pass_lsp_cross.h"
#include "pipeline/lsp_surface.h"
+#include "foundation/mem_core.h"
#include "result_spill.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/lsp_resolve.h"
@@ -613,7 +614,7 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are
* first actual collector spilled-load boundary, without timing. */
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
bool force_null = owner_walk_required && ctx &&
- (ctx->test_fault_mask & CBM_PIPELINE_TEST_FAULT_COLLECT_SPILL_NULL);
+ (ctx->test_fault_mask & CBM_PIPELINE_TEST_FAULT_COLLECT_SPILL_NULL);
fr = force_null ? NULL : cbm_result_spill_load(spill, fi);
#else
fr = cbm_result_spill_load(spill, fi);
@@ -1332,9 +1333,9 @@ void cbm_pxc_run_one(CBMLanguage lang, CBMFileResult *r, const char *source, int
* resolution as a separate map, so pass NULL/0 and let the LSP
* fall back to its own #include scan. */
if (r->has_test_definition_owners) {
- if (!cbm_run_c_lsp_cross_with_test_owners(
- &scratch, source, source_len, module_qn, cpp_mode, defs, def_count,
- NULL, NULL, 0, tree, &out, CBM_SOURCE_ORIGIN_RAW, r)) {
+ if (!cbm_run_c_lsp_cross_with_test_owners(&scratch, source, source_len, module_qn,
+ cpp_mode, defs, def_count, NULL, NULL, 0,
+ tree, &out, CBM_SOURCE_ORIGIN_RAW, r)) {
cbm_pipeline_test_owner_error(r);
pxc_scratch_give(PXC_SCRATCH_DISPATCH, &scratch);
return; /* out may be partial: never append it */
@@ -1510,17 +1511,17 @@ void cbm_pxc_dispatch_file(CBMLanguage lang, CBMFileResult *result, const char *
case CBM_LANG_CUDA:
if (result->has_test_definition_owners) {
if (!cbm_run_c_lsp_cross_with_registry_with_test_owners(
- &scratch, source, source_len, def_module, (lang != CBM_LANG_C),
- &overlay, imp_keys, imp_vals, imp_count, result->cached_tree,
- &out, CBM_SOURCE_ORIGIN_RAW, result)) {
+ &scratch, source, source_len, def_module, (lang != CBM_LANG_C), &overlay,
+ imp_keys, imp_vals, imp_count, result->cached_tree, &out,
+ CBM_SOURCE_ORIGIN_RAW, result)) {
cbm_pipeline_test_owner_error(result);
pxc_scratch_give(PXC_SCRATCH_DISPATCH, &scratch);
return; /* no append and no fallback on an invalid proof */
}
} else {
cbm_run_c_lsp_cross_with_registry(&scratch, source, source_len, def_module,
- (lang != CBM_LANG_C), &overlay, imp_keys, imp_vals,
- imp_count, result->cached_tree, &out);
+ (lang != CBM_LANG_C), &overlay, imp_keys,
+ imp_vals, imp_count, result->cached_tree, &out);
}
used_prebuilt = true;
break;
@@ -1692,9 +1693,8 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
}
bool owner_walk_required = atomic_load(&ctx->test_definition_owners_seen) != 0;
char cross_disabled[CBM_SZ_16];
- if (owner_walk_required &&
- cbm_safe_getenv("CBM_DISABLE_LSP_CROSS", cross_disabled,
- sizeof(cross_disabled), NULL) != NULL) {
+ if (owner_walk_required && cbm_safe_getenv("CBM_DISABLE_LSP_CROSS", cross_disabled,
+ sizeof(cross_disabled), NULL) != NULL) {
atomic_store(&ctx->test_declarations_failed, 1);
return CBM_PIPELINE_ABORT_PRESERVE_DB;
}
@@ -1709,8 +1709,9 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
/* Per-file module QN cache so we don't recompute it once per def + once
* per call. cbm_pipeline_fqn_module mallocs; freed at end. */
- char **def_modules = cbm_pipeline_test_force_def_modules_null(ctx) ? NULL :
- (char **)calloc((size_t)file_count, sizeof(char *));
+ char **def_modules = cbm_pipeline_test_force_def_modules_null(ctx)
+ ? NULL
+ : (char **)calloc((size_t)file_count, sizeof(char *));
if (!def_modules) {
cbm_log_error("pass.err", "pass", "lsp_cross", "phase", "alloc");
if (have_rust) {
@@ -1725,7 +1726,8 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
}
int def_count = 0;
- int *def_starts = (int *)calloc((size_t)file_count + 1, sizeof(int));
+ int *def_starts =
+ (int *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, ((size_t)file_count + 1) * sizeof(int));
/* The defs own their strings in the caller-owned seq_cross_arena, which
* the registries and later passes already borrow from (see below). */
if (!ctx->seq_cross_arena_live) {
@@ -1737,7 +1739,7 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
ctx->project_name, def_modules, &def_count, def_starts);
if (def_count < 0 || (owner_walk_required && (!all_defs || def_count <= 0))) {
atomic_store(&ctx->test_declarations_failed, 1);
- free(def_starts);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, def_starts);
free(all_defs);
for (int i = 0; i < file_count; i++) {
free(def_modules[i]);
@@ -1760,7 +1762,7 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
cbm_pipeline_set_lsp_surfaces(ctx->pipeline, surface_rows, surface_count);
}
}
- free(def_starts);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, def_starts);
/* Shared prepare (mirrors run_parallel_pipeline): inverted module-def
* index + per-language shared registries, built ONCE for the whole pass.
@@ -1882,8 +1884,7 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
"files_skipped_no_lsp", itoa_buf(skipped_no_lsp), "files_skipped_no_source",
itoa_buf(skipped_no_source), "defs_total", itoa_buf(def_count), "lsp_calls",
itoa_buf(per_lang_calls));
- return atomic_load(&ctx->test_declarations_failed)
- ? CBM_PIPELINE_ABORT_PRESERVE_DB : 0;
+ return atomic_load(&ctx->test_declarations_failed) ? CBM_PIPELINE_ABORT_PRESERVE_DB : 0;
}
/* ── Per-module def index (gopls "package summary" pattern) ──── */
@@ -2129,7 +2130,8 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
return NULL;
}
- bool *selected = (bool *)calloc((size_t)idx->def_count, sizeof(*selected));
+ bool *selected =
+ (bool *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)idx->def_count * sizeof(*selected));
if (!selected) {
return NULL;
}
@@ -2146,14 +2148,14 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
}
if (total == 0) {
- free(selected);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, selected);
*out_success = true;
return NULL;
}
CBMLSPDef *out = (CBMLSPDef *)malloc((size_t)total * sizeof(CBMLSPDef));
if (!out) {
- free(selected);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, selected);
return NULL;
}
@@ -2165,6 +2167,6 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
}
*out_count = n;
*out_success = true;
- free(selected);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, selected);
return out;
}
diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c
index 0332b41c3..0180364b8 100644
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@ -485,9 +485,9 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
* pass_definitions.c::build_def_props — keep both in sync. */
const bool is_fn =
def->label && (strcmp(def->label, "Function") == 0 || strcmp(def->label, "Method") == 0);
- const char *test_role = def->test_role == CBM_TEST_ROLE_CASE ? ",\"test_role\":\"case\""
+ const char *test_role = def->test_role == CBM_TEST_ROLE_CASE ? ",\"test_role\":\"case\""
: def->test_role == CBM_TEST_ROLE_SUITE ? ",\"test_role\":\"suite\""
- : "";
+ : "";
int n;
if (is_fn) {
n = snprintf(buf, bufsize,
@@ -508,7 +508,8 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
"{\"complexity\":%d,\"lines\":%d,\"is_exported\":%s,\"is_test\":%s,"
"\"is_entry_point\":%s%s",
def->complexity, def->lines, def->is_exported ? "true" : "false",
- def->is_test ? "true" : "false", def->is_entry_point ? "true" : "false", test_role);
+ def->is_test ? "true" : "false", def->is_entry_point ? "true" : "false",
+ test_role);
}
if (n <= 0 || (size_t)n >= bufsize) {
buf[0] = '\0';
@@ -1249,15 +1250,15 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
* generated classes are composed before entering the common registry
* and resolution lifecycle. */
CBMFileResult *result =
- cbm_pipeline_test_force_extract_null(ec->pctx, fi->language) ? NULL :
- fi->language == CBM_LANG_OBJECTSCRIPT_EXPORT
+ cbm_pipeline_test_force_extract_null(ec->pctx, fi->language) ? NULL
+ : fi->language == CBM_LANG_OBJECTSCRIPT_EXPORT
? cbm_pipeline_extract_objectscript_export(source, source_len, ec->project_name,
fi->rel_path, ec->macro_table,
ec->return_type_table)
- : cbm_extract_file_ex_with_tests(
- source, source_len, fi->language, ec->project_name, fi->rel_path,
- CBM_EXTRACT_BUDGET, NULL, NULL, ec->macro_table,
- ec->return_type_table, ec->pctx->test_declarations);
+ : cbm_extract_file_ex_with_tests(source, source_len, fi->language, ec->project_name,
+ fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL,
+ ec->macro_table, ec->return_type_table,
+ ec->pctx->test_declarations);
uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / PP_USEC_PER_MS;
@@ -1307,6 +1308,12 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
pp_err_add(errs, fi->rel_path, result->error_ranges ? result->error_ranges : "unknown",
result->parse_unusable ? "parse_unusable" : "parse_partial");
}
+ if (result->test_declarations_degraded) {
+ /* Degraded per file, not the index; see pass_definitions.c. */
+ pp_err_add(errs, fi->rel_path,
+ cbm_test_extract_status_message(result->test_declarations_degraded_status),
+ "test_declarations");
+ }
/* A truncated walk is a coverage gap like a partial parse, and until now
* it was the only one we kept to ourselves: result->walk_truncated was
* set and never read by anything, so a file the walk abandoned halfway
@@ -3854,8 +3861,8 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
}
if (result->has_test_definition_owners &&
- (!rc->all_defs || rc->def_count <= 0 || !cbm_pxc_has_cross_lsp(lang) ||
- is_generated || result->lsp_skipped)) {
+ (!rc->all_defs || rc->def_count <= 0 || !cbm_pxc_has_cross_lsp(lang) || is_generated ||
+ result->lsp_skipped)) {
cbm_pipeline_test_owner_error(result);
(void)cbm_pipeline_test_result_ok(rc->pctx, result);
continue;
@@ -3884,7 +3891,8 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
(jvm_cross_lsp || rust_workspace_cross_lsp || pending_lsp_site ||
qualified_lsp_sites < semantic_sites)) ||
unowned_c_member) &&
- !is_generated) || result->has_test_definition_owners;
+ !is_generated) ||
+ result->has_test_definition_owners;
/* Skip files with nothing else to resolve and no cross-LSP work. */
if (result->calls.count == 0 && result->usages.count == 0 && result->throws.count == 0 &&
@@ -4047,7 +4055,7 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
atomic_fetch_add_explicit(&rc->time_ns_semantic, extract_now_ns() - _ph_t0,
memory_order_relaxed);
-resolve_file_cleanup:
+ resolve_file_cleanup:
cbm_registry_reach_cache_end();
cbm_registry_import_map_cache_end();
cbm_registry_resolve_cache_end();
diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.c
index b9782a983..b3fdbb68b 100644
--- a/src/pipeline/pass_semantic.c
+++ b/src/pipeline/pass_semantic.c
@@ -670,10 +670,12 @@ static CBMFileResult *sem_get_or_extract(cbm_pipeline_ctx_t *ctx, int file_idx,
}
return NULL;
}
- CBMFileResult *r = cbm_pipeline_test_force_extract_null(ctx, fi->language) ? NULL :
- cbm_extract_file_ex_with_tests(
- source, source_len, fi->language, ctx->project_name, fi->rel_path,
- CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations);
+ CBMFileResult *r =
+ cbm_pipeline_test_force_extract_null(ctx, fi->language)
+ ? NULL
+ : cbm_extract_file_ex_with_tests(source, source_len, fi->language, ctx->project_name,
+ fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, NULL,
+ NULL, ctx->test_declarations);
cbm_free(CBM_MEM_CLASS_SEMANTIC, source);
(void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r);
if (r) {
diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.c
index 169dbeffc..f60378ff2 100644
--- a/src/pipeline/pass_usages.c
+++ b/src/pipeline/pass_usages.c
@@ -437,10 +437,11 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
errors++;
continue;
}
- result = cbm_pipeline_test_force_extract_null(ctx, files[i].language) ? NULL :
- cbm_extract_file_ex_with_tests(
- source, source_len, files[i].language, ctx->project_name, rel,
- CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations);
+ result = cbm_pipeline_test_force_extract_null(ctx, files[i].language)
+ ? NULL
+ : cbm_extract_file_ex_with_tests(
+ source, source_len, files[i].language, ctx->project_name, rel,
+ CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations);
free(source);
if (!cbm_pipeline_test_extraction_ok(ctx, files[i].language, result)) {
cbm_free_result(result);
diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c
index 21d8b5541..5aebed6c0 100644
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@ -286,6 +286,11 @@ struct cbm_pipeline_frozen {
cbm_pipeline_frozen_status_t failure;
cbm_file_hash_t *baseline;
int baseline_count;
+ /* The classified file list, owned by the arena, sorted by path; has_list
+ * false: discover the source root. */
+ bool has_list;
+ cbm_pipeline_frozen_file_t *listed;
+ size_t listed_count;
char canonical_root[CBM_SZ_4K];
char canonical_parent[CBM_SZ_4K];
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
@@ -295,7 +300,9 @@ struct cbm_pipeline_frozen {
#endif
};
-bool cbm_pipeline_is_frozen(const cbm_pipeline_t *p) { return p && p->frozen; }
+bool cbm_pipeline_is_frozen(const cbm_pipeline_t *p) {
+ return p && p->frozen;
+}
int cbm_pipeline_frozen_checkpoint(cbm_pipeline_t *p) {
if (!p || !p->frozen)
@@ -401,11 +408,136 @@ static bool frozen_config_span_valid(const cbm_pipeline_frozen_inputs_t *in) {
return in->config_state == CBM_USERCONFIG_SOURCE_PRESENT && in->config_bytes;
}
+/* A relative path made of non-empty segments other than "." and "..", with
+ * '/' as the only separator. */
+static bool frozen_rel_path_valid(const char *rel) {
+ if (!rel || !rel[0] || strlen(rel) >= CBM_SZ_4K || strchr(rel, '\\')) {
+ return false;
+ }
+ const char *segment = rel;
+ for (;;) {
+ const char *slash = strchr(segment, '/');
+ size_t len = slash ? (size_t)(slash - segment) : strlen(segment);
+ if (len == 0 || (len == 1 && segment[0] == '.') ||
+ (len == 2 && segment[0] == '.' && segment[1] == '.')) {
+ return false;
+ }
+ if (!slash) {
+ return true;
+ }
+ segment = slash + 1;
+ }
+}
+
+static bool frozen_files_valid(const cbm_pipeline_frozen_inputs_t *in) {
+ if (!in->files) {
+ return in->file_count == 0;
+ }
+ if (in->file_count > (size_t)INT_MAX) {
+ return false;
+ }
+ for (size_t i = 0; i < in->file_count; i++) {
+ if (!frozen_rel_path_valid(in->files[i].rel_path) || in->files[i].language < 0 ||
+ in->files[i].language > CBM_LANG_COUNT) {
+ return false;
+ }
+ }
+ return true;
+}
+
static bool frozen_inputs_valid(const cbm_pipeline_frozen_inputs_t *in) {
return in && frozen_absolute(in->source_root) && frozen_absolute(in->candidate_db_path) &&
frozen_string(in->project, true) && cbm_validate_project_name(in->project) &&
frozen_git_valid(in->pinned_git) && frozen_policy_valid(&in->resource_policy) &&
- frozen_config_span_valid(in);
+ frozen_config_span_valid(in) && frozen_files_valid(in);
+}
+
+static int frozen_listed_cmp(const void *left, const void *right) {
+ const cbm_pipeline_frozen_file_t *a = left;
+ const cbm_pipeline_frozen_file_t *b = right;
+ return strcmp(a->rel_path, b->rel_path);
+}
+
+/* Copy the list into the owner's arena, sorted; a path listed twice is
+ * INVALID (two languages for one file have no single meaning). */
+static cbm_pipeline_frozen_status_t frozen_copy_list(cbm_pipeline_frozen_t *owner,
+ const cbm_pipeline_frozen_inputs_t *in) {
+ owner->has_list = in->files != NULL;
+ if (!owner->has_list || in->file_count == 0) {
+ return CBM_PIPELINE_FROZEN_OK;
+ }
+ owner->listed = cbm_arena_calloc(&owner->arena, in->file_count * sizeof(*owner->listed));
+ if (!owner->listed) {
+ return CBM_PIPELINE_FROZEN_OOM;
+ }
+ for (size_t i = 0; i < in->file_count; i++) {
+ owner->listed[i].language = in->files[i].language;
+ owner->listed[i].rel_path = cbm_arena_strdup(&owner->arena, in->files[i].rel_path);
+ if (!owner->listed[i].rel_path) {
+ return CBM_PIPELINE_FROZEN_OOM;
+ }
+ }
+ owner->listed_count = in->file_count;
+ qsort(owner->listed, owner->listed_count, sizeof(*owner->listed), frozen_listed_cmp);
+ for (size_t i = 1; i < owner->listed_count; i++) {
+ if (strcmp(owner->listed[i - 1].rel_path, owner->listed[i].rel_path) == 0) {
+ return CBM_PIPELINE_FROZEN_INVALID;
+ }
+ }
+ return CBM_PIPELINE_FROZEN_OK;
+}
+
+bool cbm_pipeline_frozen_has_file_list(const cbm_pipeline_t *p) {
+ return cbm_pipeline_is_frozen(p) && p->frozen->has_list;
+}
+
+int cbm_pipeline_frozen_listed_files(cbm_pipeline_t *p, cbm_file_info_t **out, int *count) {
+ *out = NULL;
+ *count = 0;
+ if (!cbm_pipeline_frozen_has_file_list(p)) {
+ return CBM_NOT_FOUND;
+ }
+ cbm_pipeline_frozen_t *owner = p->frozen;
+ cbm_file_info_t *files =
+ owner->listed_count ? calloc(owner->listed_count, sizeof(*files)) : NULL;
+ if (owner->listed_count && !files) {
+ owner->failure = CBM_PIPELINE_FROZEN_OOM;
+ return CBM_NOT_FOUND;
+ }
+ int n = 0;
+ for (size_t i = 0; i < owner->listed_count; i++) {
+ const cbm_pipeline_frozen_file_t *listed = &owner->listed[i];
+ if (listed->language == CBM_LANG_COUNT) {
+ continue; /* no supported language: discovery does not index it either */
+ }
+ char path[CBM_SZ_4K];
+ int len = snprintf(path, sizeof(path), "%s/%s", p->repo_path, listed->rel_path);
+ /* The UTF-8-safe size probe; a directory is not a listed file. */
+ int64_t size =
+ len > 0 && (size_t)len < sizeof(path) && !cbm_is_dir(path) ? cbm_file_size(path) : -1;
+ bool regular = size >= 0;
+ if (!regular || cbm_pipeline_frozen_checkpoint(p)) {
+ if (!regular && owner->failure == CBM_PIPELINE_FROZEN_OK) {
+ owner->failure = CBM_PIPELINE_FROZEN_INPUT_CHANGED;
+ }
+ cbm_discover_free(files, n);
+ return CBM_NOT_FOUND;
+ }
+ files[n].path = strdup(path);
+ files[n].rel_path = strdup(listed->rel_path);
+ files[n].language = listed->language;
+ files[n].size = size;
+ if (!files[n].path || !files[n].rel_path) {
+ n++;
+ cbm_discover_free(files, n);
+ owner->failure = CBM_PIPELINE_FROZEN_OOM;
+ return CBM_NOT_FOUND;
+ }
+ n++;
+ }
+ *out = files;
+ *count = n;
+ return 0;
}
static bool frozen_copy_git(cbm_git_context_t *to, const cbm_git_context_t *from) {
@@ -480,8 +612,8 @@ static cbm_pipeline_frozen_status_t frozen_git_props(cbm_pipeline_frozen_t *owne
return CBM_PIPELINE_FROZEN_OK;
}
-static cbm_pipeline_frozen_status_t
-frozen_allocate_pipeline(cbm_pipeline_frozen_t *owner, const cbm_pipeline_frozen_inputs_t *in) {
+static cbm_pipeline_frozen_status_t frozen_allocate_pipeline(
+ cbm_pipeline_frozen_t *owner, const cbm_pipeline_frozen_inputs_t *in) {
cbm_pipeline_t *p = calloc(1, sizeof(*p));
if (!p)
return CBM_PIPELINE_FROZEN_OOM;
@@ -523,7 +655,10 @@ cbm_pipeline_frozen_status_t cbm_pipeline_frozen_create(const cbm_pipeline_froze
}
owner->arena = arena;
owner->external_cancelled = inputs->cancelled;
- cbm_pipeline_frozen_status_t status = frozen_allocate_pipeline(owner, inputs);
+ cbm_pipeline_frozen_status_t status = frozen_copy_list(owner, inputs);
+ if (status == CBM_PIPELINE_FROZEN_OK) {
+ status = frozen_allocate_pipeline(owner, inputs);
+ }
if (status != CBM_PIPELINE_FROZEN_OK) {
cbm_pipeline_frozen_free(owner);
return status;
@@ -785,11 +920,11 @@ void cbm_pipeline_free(cbm_pipeline_t *p) {
p->ignored_count = 0;
p->ignored_total = 0;
for (int i = 0; i < p->file_errors_count; i++) {
- free(p->file_errors[i].path);
- free(p->file_errors[i].reason);
- free(p->file_errors[i].phase);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->file_errors[i].path);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->file_errors[i].reason);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->file_errors[i].phase);
}
- free(p->file_errors);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->file_errors);
p->file_errors = NULL;
p->file_errors_count = 0;
p->file_errors_cap = 0;
@@ -855,8 +990,7 @@ const cbm_test_declarations_t *cbm_pipeline_test_declarations(const cbm_pipeline
return p ? p->test_declarations : NULL;
}
-bool cbm_pipeline_project_source_matches(const cbm_pipeline_t *p,
- const cbm_userconfig_t *fresh) {
+bool cbm_pipeline_project_source_matches(const cbm_pipeline_t *p, const cbm_userconfig_t *fresh) {
const char *current = NULL;
size_t current_len = 0;
cbm_userconfig_source_state_t current_state =
@@ -885,8 +1019,8 @@ static bool pipeline_load_test_config(cbm_pipeline_t *p) {
if (state == CBM_USERCONFIG_SOURCE_ERROR) {
return false;
}
- p->test_declarations = cbm_test_declarations_parse(
- bytes, len, state == CBM_USERCONFIG_SOURCE_ABSENT);
+ p->test_declarations =
+ cbm_test_declarations_parse(bytes, len, state == CBM_USERCONFIG_SOURCE_ABSENT);
if (!p->test_declarations) {
return false;
}
@@ -934,7 +1068,7 @@ static char *fe_strdup(const char *s) {
return NULL;
}
size_t n = strlen(s) + 1;
- char *d = (char *)malloc(n);
+ char *d = (char *)cbm_alloc(CBM_MEM_CLASS_OTHER, n);
if (d) {
memcpy(d, s, n);
}
@@ -983,10 +1117,10 @@ static bool frozen_diag_reserve(cbm_pipeline_t *p) {
frozen_diag_incomplete(p, false);
return false;
}
- cbm_file_error_t *grown =
- frozen_diag_fail_allocation(p, FROZEN_DIAG_GROW)
- ? NULL
- : realloc(p->file_errors, (size_t)capacity * sizeof(*p->file_errors));
+ cbm_file_error_t *grown = frozen_diag_fail_allocation(p, FROZEN_DIAG_GROW)
+ ? NULL
+ : cbm_realloc(CBM_MEM_CLASS_OTHER, p->file_errors,
+ (size_t)capacity * sizeof(*p->file_errors));
if (!grown) {
frozen_diag_incomplete(p, true);
return false;
@@ -1002,7 +1136,9 @@ static char *frozen_diag_copy(cbm_pipeline_t *p, const char *source, unsigned al
frozen_diag_incomplete(p, false);
return NULL;
}
- char *copy = frozen_diag_fail_allocation(p, allocation) ? NULL : malloc(length + 1);
+ char *copy = frozen_diag_fail_allocation(p, allocation)
+ ? NULL
+ : cbm_alloc(CBM_MEM_CLASS_OTHER, length + 1);
if (!copy) {
frozen_diag_incomplete(p, true);
return NULL;
@@ -1012,8 +1148,16 @@ static char *frozen_diag_copy(cbm_pipeline_t *p, const char *source, unsigned al
}
static void frozen_add_file_error(cbm_pipeline_t *p, const char *path, const char *reason,
- const char *phase) {
- p->frozen->diagnostic_flags |= CBM_PIPELINE_FROZEN_FILE_DIAGNOSTIC;
+ const char *phase) {
+ /* A partial parse is a parse gap the selection handles per file (user
+ * decision 2026-10-04); every other file diagnostic refuses the candidate. */
+ bool parse_gap = phase && strcmp(phase, "parse_partial") == 0;
+ /* A file indexed without configured test roles is not refused either
+ * (user decision 2026-10-04): the selection reads tests by its own model. */
+ bool test_gap = phase && strcmp(phase, "test_declarations") == 0;
+ p->frozen->diagnostic_flags |= parse_gap ? CBM_PIPELINE_FROZEN_PARSE_GAP
+ : test_gap ? CBM_PIPELINE_FROZEN_TEST_DECLARATION_GAP
+ : CBM_PIPELINE_FROZEN_FILE_DIAGNOSTIC;
if (!path || !reason || !phase) {
frozen_diag_incomplete(p, false);
return;
@@ -1026,9 +1170,9 @@ static void frozen_add_file_error(cbm_pipeline_t *p, const char *path, const cha
for (unsigned i = 0; i < 3; i++) {
*copies[i] = frozen_diag_copy(p, sources[i], FROZEN_DIAG_PATH + i);
if (!*copies[i]) {
- free(row.path);
- free(row.reason);
- free(row.phase);
+ cbm_free(CBM_MEM_CLASS_OTHER, row.path);
+ cbm_free(CBM_MEM_CLASS_OTHER, row.reason);
+ cbm_free(CBM_MEM_CLASS_OTHER, row.phase);
return;
}
}
@@ -1046,8 +1190,8 @@ void cbm_pipeline_add_file_error(cbm_pipeline_t *p, const char *path, const char
}
if (p->file_errors_count >= p->file_errors_cap) {
int ncap = p->file_errors_cap ? p->file_errors_cap * 2 : 16;
- cbm_file_error_t *grown =
- (cbm_file_error_t *)realloc(p->file_errors, (size_t)ncap * sizeof(*grown));
+ cbm_file_error_t *grown = (cbm_file_error_t *)cbm_realloc(
+ CBM_MEM_CLASS_OTHER, p->file_errors, (size_t)ncap * sizeof(*grown));
if (!grown) {
/* Never abort indexing just to record a skip — drop this record. */
return;
@@ -1951,8 +2095,7 @@ static int run_sequential_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
for (int si = 0; si < PL_SEQ_PASSES && rc == 0; si++) {
cbm_clock_gettime(CLOCK_MONOTONIC, t);
int pr = seq_passes[si].fn(ctx, files, file_count);
- if (pr == CBM_PIPELINE_ABORT_PRESERVE_DB ||
- atomic_load(&ctx->test_declarations_failed)) {
+ if (pr == CBM_PIPELINE_ABORT_PRESERVE_DB || atomic_load(&ctx->test_declarations_failed)) {
rc = CBM_PIPELINE_ABORT_PRESERVE_DB;
} else if (pr != 0 && !seq_passes[si].ignore_err) {
rc = pr;
@@ -2467,7 +2610,7 @@ static char *stage_lock_sidecar_path(const char *stage_path) {
if (len > SIZE_MAX - sizeof(suffix)) {
return NULL;
}
- char *sidecar = (char *)malloc(len + sizeof(suffix));
+ char *sidecar = (char *)cbm_alloc(CBM_MEM_CLASS_OTHER, len + sizeof(suffix));
if (!sidecar) {
return NULL;
}
@@ -2485,7 +2628,7 @@ int cbm_pipeline_stage_lock_hold(const char *stage_path) {
return -1;
}
int fd = cbm_lockfile_open(sidecar, true);
- free(sidecar);
+ cbm_free(CBM_MEM_CLASS_OTHER, sidecar);
return fd;
}
@@ -2501,7 +2644,7 @@ void cbm_pipeline_stage_lock_drop(const char *stage_path, int lock_fd) {
cbm_lockfile_close(lock_fd);
if (sidecar) {
(void)cbm_unlink(sidecar);
- free(sidecar);
+ cbm_free(CBM_MEM_CLASS_OTHER, sidecar);
}
}
@@ -2512,7 +2655,7 @@ static int stage_lock_drop_checked(const char *path, int fd) {
return CBM_NOT_FOUND;
cbm_path_info_t info;
bool absent = cbm_path_info_utf8(sidecar, &info) == CBM_PATH_INFO_ABSENT;
- free(sidecar);
+ cbm_free(CBM_MEM_CLASS_OTHER, sidecar);
return absent ? 0 : CBM_NOT_FOUND;
}
@@ -3341,9 +3484,12 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
p->ignored_files = NULL;
p->ignored_count = 0;
p->ignored_total = 0;
- int rc = cbm_discover_ex2(p->repo_path, &opts, &files, &file_count, &p->excluded_dirs,
- &p->excluded_count, &p->ignored_files, &p->ignored_count,
- &p->ignored_total);
+ /* A frozen build with a classified file list walks no directory. */
+ int rc = cbm_pipeline_frozen_has_file_list(p)
+ ? cbm_pipeline_frozen_listed_files(p, &files, &file_count)
+ : cbm_discover_ex2(p->repo_path, &opts, &files, &file_count, &p->excluded_dirs,
+ &p->excluded_count, &p->ignored_files, &p->ignored_count,
+ &p->ignored_total);
if (rc != 0) {
cbm_log_error("pipeline.err", "phase", "discover", "rc", itoa_buf(rc));
}
@@ -3409,9 +3555,11 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
p->ignored_total = 0;
opts.mode = p->mode;
- rc = cbm_discover_ex2(p->repo_path, &opts, &files, &file_count, &p->excluded_dirs,
- &p->excluded_count, &p->ignored_files, &p->ignored_count,
- &p->ignored_total);
+ rc = cbm_pipeline_frozen_has_file_list(p)
+ ? cbm_pipeline_frozen_listed_files(p, &files, &file_count)
+ : cbm_discover_ex2(p->repo_path, &opts, &files, &file_count, &p->excluded_dirs,
+ &p->excluded_count, &p->ignored_files, &p->ignored_count,
+ &p->ignored_total);
cbm_log_info("pipeline.rediscover", "requested_mode", pipeline_mode_name(p->requested_mode),
"effective_mode", pipeline_mode_name(p->mode), "files", itoa_buf(file_count));
if (rc != 0 || check_cancel(p)) {
@@ -3891,7 +4039,7 @@ static void sweep_one_stage(const char *stage_path) {
errno = 0;
int lock_fd = cbm_lockfile_open(sidecar, false);
int probe_errno = errno;
- free(sidecar);
+ cbm_free(CBM_MEM_CLASS_OTHER, sidecar);
if (lock_fd < 0 && probe_errno != ENOENT) {
bool live = probe_errno == EAGAIN || probe_errno == EACCES;
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
@@ -4244,7 +4392,9 @@ static cbm_pipeline_frozen_status_t frozen_diagnostic_status(const cbm_pipeline_
unsigned flags = p->frozen->diagnostic_flags;
if (flags & CBM_PIPELINE_FROZEN_DIAGNOSTIC_OOM)
return CBM_PIPELINE_FROZEN_OOM;
- return flags ? CBM_PIPELINE_FROZEN_PIPELINE_ERROR : CBM_PIPELINE_FROZEN_OK;
+ unsigned recorded = (unsigned)CBM_PIPELINE_FROZEN_PARSE_GAP |
+ (unsigned)CBM_PIPELINE_FROZEN_TEST_DECLARATION_GAP;
+ return (flags & ~recorded) ? CBM_PIPELINE_FROZEN_PIPELINE_ERROR : CBM_PIPELINE_FROZEN_OK;
}
static cbm_pipeline_frozen_status_t frozen_run_status(cbm_pipeline_t *p, int rc) {
@@ -4263,7 +4413,7 @@ static cbm_pipeline_frozen_status_t frozen_run_status(cbm_pipeline_t *p, int rc)
static cbm_pipeline_frozen_status_t frozen_run_stage(cbm_pipeline_t *p, const char *stage) {
char *destination = p->db_path;
- char *stage_copy = strdup(stage);
+ char *stage_copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, stage);
if (!stage_copy)
return CBM_PIPELINE_FROZEN_OOM;
p->db_path = stage_copy;
@@ -4271,7 +4421,7 @@ static cbm_pipeline_frozen_status_t frozen_run_stage(cbm_pipeline_t *p, const ch
p->final_existed = false;
int rc = cbm_pipeline_run_staged(p);
p->db_path = destination;
- free(stage_copy);
+ cbm_free(CBM_MEM_CLASS_OTHER, stage_copy);
return frozen_run_status(p, rc);
}
diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c
index 7be2c88d6..3aae16c25 100644
--- a/src/pipeline/pipeline_incremental.c
+++ b/src/pipeline/pipeline_incremental.c
@@ -16,6 +16,7 @@ enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24 };
#include <stdio.h>
#include <time.h>
#include "pipeline/lsp_surface.h"
+#include "foundation/mem_core.h"
#include "pipeline/pass_lsp_cross.h"
#include "sqlite3.h"
#include "yyjson/yyjson.h"
@@ -778,8 +779,13 @@ static int frozen_fresh_manifest(cbm_pipeline_t *p, cbm_file_hash_t **out, int *
int ignored_total = 0;
const cbm_userconfig_t *previous = cbm_get_user_lang_config();
cbm_set_user_lang_config(cbm_pipeline_frozen_config(p));
- int rc = cbm_discover_ex2(cbm_pipeline_repo_path(p), &opts, &files, &count, &excluded,
- &excluded_count, &ignored, &ignored_count, &ignored_total);
+ /* With a classified file list the reconciliation re-hashes exactly the
+ * listed files: a file added to the source root since is not compared,
+ * because it is not indexed either. */
+ int rc = cbm_pipeline_frozen_has_file_list(p)
+ ? cbm_pipeline_frozen_listed_files(p, &files, &count)
+ : cbm_discover_ex2(cbm_pipeline_repo_path(p), &opts, &files, &count, &excluded,
+ &excluded_count, &ignored, &ignored_count, &ignored_total);
if (rc == 0)
rc = cbm_pipeline_build_frozen_manifest(p, files, count, excluded, excluded_count, out,
out_count);
@@ -1476,9 +1482,8 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
bool legacy_cross_arena_live = false;
bool owner_walk_required = atomic_load(&ctx->test_definition_owners_seen) != 0;
char cross_disabled[CBM_SZ_16];
- if (owner_walk_required &&
- cbm_safe_getenv("CBM_DISABLE_LSP_CROSS", cross_disabled,
- sizeof(cross_disabled), NULL) != NULL) {
+ if (owner_walk_required && cbm_safe_getenv("CBM_DISABLE_LSP_CROSS", cross_disabled,
+ sizeof(cross_disabled), NULL) != NULL) {
atomic_store(&ctx->test_declarations_failed, 1);
rc = CBM_PIPELINE_ABORT_PRESERVE_DB;
goto cross_resolve_cleanup;
@@ -1486,9 +1491,11 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
if (closure) {
/* Fresh surfaces for the re-parsed files, from the same collect
* path a full build uses; then registries over stored + fresh. */
- def_modules = cbm_pipeline_test_force_def_modules_null(ctx) ? NULL :
- (char **)calloc((size_t)ci, sizeof(char *));
- int *def_starts = (int *)calloc((size_t)ci + 1, sizeof(int));
+ def_modules = cbm_pipeline_test_force_def_modules_null(ctx)
+ ? NULL
+ : (char **)calloc((size_t)ci, sizeof(char *));
+ int *def_starts =
+ (int *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, ((size_t)ci + 1) * sizeof(int));
int fresh_count = 0;
CBMLSPDef *fresh_defs =
def_modules && def_starts
@@ -1499,7 +1506,7 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
if (fresh_count < 0 || (owner_walk_required && (!fresh_defs || fresh_count <= 0))) {
/* Do not substitute the previous generation's definitions for
* configured owners that failed fresh preparation. */
- free(def_starts);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, def_starts);
free(fresh_defs);
closure->def_modules = def_modules;
closure->def_module_count = def_modules ? ci : 0;
@@ -1515,7 +1522,7 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
closure->fresh_rows = NULL;
closure->fresh_count = 0;
}
- free(def_starts);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, def_starts);
all_def_count = closure->base_def_count + fresh_count;
if (all_def_count > 0) {
all_defs = (CBMLSPDef *)cbm_arena_alloc(&closure->arena,
@@ -1571,13 +1578,12 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
* Only configured owners require this additional cross walk. */
cbm_arena_init(&legacy_cross_arena);
legacy_cross_arena_live = true;
- def_modules = cbm_arena_alloc(&legacy_cross_arena,
- (size_t)ci * sizeof(*def_modules));
+ def_modules = cbm_arena_alloc(&legacy_cross_arena, (size_t)ci * sizeof(*def_modules));
if (def_modules) {
memset(def_modules, 0, (size_t)ci * sizeof(*def_modules));
- all_defs = cbm_pxc_collect_all_defs(
- ctx, &legacy_cross_arena, cache, changed_files, ci,
- ctx->project_name, def_modules, &all_def_count, NULL);
+ all_defs =
+ cbm_pxc_collect_all_defs(ctx, &legacy_cross_arena, cache, changed_files, ci,
+ ctx->project_name, def_modules, &all_def_count, NULL);
}
if (!all_defs || all_def_count <= 0) {
atomic_store(&ctx->test_declarations_failed, 1);
@@ -1587,12 +1593,11 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
module_def_index = cbm_pxc_build_module_def_index(all_defs, all_def_count);
}
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- rc = cbm_parallel_resolve(ctx, changed_files, ci, cache, &shared_ids, worker_count,
- all_defs, all_def_count,
- closure ? closure->def_modules : def_modules,
- module_def_index, registries_arg);
+ rc = cbm_parallel_resolve(
+ ctx, changed_files, ci, cache, &shared_ids, worker_count, all_defs, all_def_count,
+ closure ? closure->def_modules : def_modules, module_def_index, registries_arg);
-cross_resolve_cleanup:
+ cross_resolve_cleanup:
if (module_def_index) {
cbm_pxc_free_module_def_index(module_def_index);
}
@@ -1867,8 +1872,10 @@ static int closure_probe_surfaces(cbm_pipeline_t *p, const char *project,
cbm_default_worker_count(true));
}
if (rc == 0) {
- char **def_modules = (char **)calloc((size_t)probe_count, sizeof(char *));
- int *def_starts = (int *)calloc((size_t)probe_count + 1, sizeof(int));
+ char **def_modules =
+ (char **)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)probe_count * sizeof(char *));
+ int *def_starts =
+ (int *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, ((size_t)probe_count + 1) * sizeof(int));
int def_count = 0;
CBMLSPDef *defs = NULL;
CBMArena probe_arena;
@@ -1885,12 +1892,12 @@ static int closure_probe_surfaces(cbm_pipeline_t *p, const char *project,
}
free(defs);
cbm_arena_destroy(&probe_arena);
- free(def_starts);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, def_starts);
if (def_modules) {
for (int i = 0; i < probe_count; i++) {
free(def_modules[i]);
}
- free(def_modules);
+ cbm_free(CBM_MEM_CLASS_EXTRACT, def_modules);
}
}
if (cache) {
@@ -2086,10 +2093,9 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
}
probe_files[i] = *info;
}
- int probe_rc = n_changed > 0
- ? closure_probe_surfaces(p, project, probe_files, n_changed,
- &probe_rows, &probe_count)
- : 0;
+ int probe_rc = n_changed > 0 ? closure_probe_surfaces(p, project, probe_files, n_changed,
+ &probe_rows, &probe_count)
+ : 0;
if (probe_rc != 0) {
cbm_ht_free(rows_by_path);
if (probe_rc == CBM_PIPELINE_ABORT_PRESERVE_DB) {
diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h
index 0f96c0b19..7186fd345 100644
--- a/src/pipeline/pipeline_internal.h
+++ b/src/pipeline/pipeline_internal.h
@@ -39,6 +39,15 @@ typedef enum {
CBM_PIPELINE_FROZEN_PIPELINE_ERROR
} cbm_pipeline_frozen_status_t;
+/* One file of a classified pinned ledger: a path relative to source_root
+ * ('/'-separated; no empty, "." or ".." segment) and the language the ledger
+ * gave it. CBM_LANG_COUNT: the file has no supported language and is not
+ * indexed, as discovery does not index it. */
+typedef struct {
+ const char *rel_path;
+ CBMLanguage language;
+} cbm_pipeline_frozen_file_t;
+
typedef struct {
/* Explicit native absolute paths. Source root and destination parent are
* private, caller-owned directories for the entire owner lifetime.
@@ -72,6 +81,15 @@ typedef struct {
* consumers may see only the internal latch until the next such sample.
*/
atomic_int *cancelled;
+
+ /* Optional: the files to index, from a classified pinned ledger (see
+ * test_impact_classify.h). With a list the build walks no directory: it
+ * indexes exactly these files under these languages, and the pre-commit
+ * reconciliation re-hashes exactly them, so a file added to source_root
+ * after the ledger was made is never indexed and a listed file that is not
+ * there is INPUT_CHANGED. NULL with 0 discovers source_root. Copied. */
+ const cbm_pipeline_frozen_file_t *files;
+ size_t file_count;
} cbm_pipeline_frozen_inputs_t;
/* Clear *out first. Deep-copy/validate all input; no Git/config filesystem
@@ -92,6 +110,14 @@ cbm_pipeline_frozen_status_t cbm_pipeline_frozen_create(const cbm_pipeline_froze
*/
cbm_pipeline_frozen_status_t cbm_pipeline_frozen_build(cbm_pipeline_frozen_t *owner);
+/* Inside a frozen build: whether the owner was given a file list, and that
+ * list as discovery records (absolute path under the source root, the listed
+ * language, the size on disk), sorted by relative path, files without a
+ * language left out. A listed file that is not a regular file records
+ * INPUT_CHANGED and returns CBM_NOT_FOUND. Free with cbm_discover_free. */
+bool cbm_pipeline_frozen_has_file_list(const cbm_pipeline_t *p);
+int cbm_pipeline_frozen_listed_files(cbm_pipeline_t *p, cbm_file_info_t **out, int *count);
+
/* Thread-safe while owner is alive; sets the internal atomic immediately.
* No concurrent free. This does not await a sample of the external flag. */
void cbm_pipeline_frozen_cancel(cbm_pipeline_frozen_t *owner);
@@ -103,19 +129,25 @@ void cbm_pipeline_frozen_cancel(cbm_pipeline_frozen_t *owner);
*/
const cbm_pipeline_t *cbm_pipeline_frozen_diagnostics(const cbm_pipeline_frozen_t *owner);
-/* Monotone negative observations; zero is NOT a completeness certificate. */
+/* Monotone negative observations; zero is NOT a completeness certificate.
+ * PARSE_GAP alone does not refuse the candidate: a file that parsed only
+ * partially stays in the graph with its unparsed ranges recorded, and the
+ * selection treats a change to it as a parse gap (the file is seeded whole and
+ * its language's lane runs whole). Every other bit refuses publication. */
enum {
CBM_PIPELINE_FROZEN_FILE_DIAGNOSTIC = 1,
CBM_PIPELINE_FROZEN_DIAGNOSTIC_INCOMPLETE = 2,
- CBM_PIPELINE_FROZEN_DIAGNOSTIC_OOM = 4
+ CBM_PIPELINE_FROZEN_DIAGNOSTIC_OOM = 4,
+ CBM_PIPELINE_FROZEN_PARSE_GAP = 8,
+ /* A file indexed without configured test roles (degraded per file). */
+ CBM_PIPELINE_FROZEN_TEST_DECLARATION_GAP = 16
};
/* Clears supplied output first. Returns false for NULL owner/output or while
* BUILDING; otherwise copies the mask. No overlap with build is permitted.
* Evidence survives failed/invalid retries until owner free; no reset API.
*/
-bool cbm_pipeline_frozen_negative_evidence(const cbm_pipeline_frozen_t *owner,
- unsigned *out_flags);
+bool cbm_pipeline_frozen_negative_evidence(const cbm_pipeline_frozen_t *owner, unsigned *out_flags);
/* Borrowed copied path only after build returned OK; otherwise NULL. */
const char *cbm_pipeline_frozen_candidate_path(const cbm_pipeline_frozen_t *owner);
@@ -354,16 +386,20 @@ static inline void cbm_pipeline_test_owner_error(CBMFileResult *result) {
result->test_declarations_status = CBM_TEST_EXTRACT_UNSUPPORTED_FORM;
result->test_declaration_index = -1;
result->test_declaration_line = 0;
+ if (!result->has_error) {
+ result->test_error_only = true;
+ }
result->has_error = true;
- result->error_msg = cbm_arena_strdup(&result->arena,
- "configured test body ownership could not be verified");
+ result->error_msg =
+ cbm_arena_strdup(&result->arena, "configured test body ownership could not be verified");
if (!result->error_msg) {
result->test_declarations_status = CBM_TEST_EXTRACT_OOM;
}
+ cbm_test_declarations_degrade(result); /* per file, not the index */
}
static inline bool cbm_pipeline_test_result_ok(cbm_pipeline_ctx_t *ctx,
- const CBMFileResult *result) {
+ const CBMFileResult *result) {
if (result && result->test_declarations_status != CBM_TEST_EXTRACT_OK) {
atomic_store(&ctx->test_declarations_failed, 1);
return false;
@@ -380,8 +416,8 @@ static inline bool cbm_pipeline_test_result_ok(cbm_pipeline_ctx_t *ctx,
static inline bool cbm_pipeline_test_definitions_apply(const cbm_pipeline_ctx_t *ctx,
CBMLanguage language) {
const cbm_test_declarations_t *snapshot = ctx ? ctx->test_declarations : NULL;
- if (!snapshot || (language != CBM_LANG_C && language != CBM_LANG_CPP &&
- language != CBM_LANG_CUDA)) {
+ if (!snapshot ||
+ (language != CBM_LANG_C && language != CBM_LANG_CPP && language != CBM_LANG_CUDA)) {
return false;
}
bool enabled = false;
@@ -396,21 +432,19 @@ static inline bool cbm_pipeline_test_definitions_apply(const cbm_pipeline_ctx_t
continue;
}
const char *name = items[i].language;
- if (name && ((language == CBM_LANG_C &&
- (strcmp(name, "c") == 0 || strcmp(name, "C") == 0)) ||
- (language == CBM_LANG_CPP &&
- (strcmp(name, "cpp") == 0 || strcmp(name, "c++") == 0 ||
- strcmp(name, "C++") == 0)) ||
- (language == CBM_LANG_CUDA &&
- (strcmp(name, "cuda") == 0 || strcmp(name, "CUDA") == 0)))) {
+ if (name &&
+ ((language == CBM_LANG_C && (strcmp(name, "c") == 0 || strcmp(name, "C") == 0)) ||
+ (language == CBM_LANG_CPP &&
+ (strcmp(name, "cpp") == 0 || strcmp(name, "c++") == 0 || strcmp(name, "C++") == 0)) ||
+ (language == CBM_LANG_CUDA &&
+ (strcmp(name, "cuda") == 0 || strcmp(name, "CUDA") == 0)))) {
return true;
}
}
return false;
}
-static inline bool cbm_pipeline_test_extraction_ok(cbm_pipeline_ctx_t *ctx,
- CBMLanguage language,
+static inline bool cbm_pipeline_test_extraction_ok(cbm_pipeline_ctx_t *ctx, CBMLanguage language,
const CBMFileResult *result) {
if (!result && cbm_pipeline_test_definitions_apply(ctx, language)) {
atomic_store(&ctx->test_declarations_failed, 1);
@@ -1190,8 +1224,7 @@ void cbm_pipeline_set_lsp_surfaces(cbm_pipeline_t *p, cbm_lsp_surface_row_t *row
const char *cbm_pipeline_repo_path(const cbm_pipeline_t *p);
const cbm_test_declarations_t *cbm_pipeline_test_declarations(const cbm_pipeline_t *p);
/* Without an active run snapshot this only validates fresh's source state. */
-bool cbm_pipeline_project_source_matches(const cbm_pipeline_t *p,
- const cbm_userconfig_t *fresh);
+bool cbm_pipeline_project_source_matches(const cbm_pipeline_t *p, const cbm_userconfig_t *fresh);
const cbm_index_resource_policy_t *cbm_pipeline_resource_policy(const cbm_pipeline_t *p);
cbm_index_resource_violation_t *cbm_pipeline_resource_violation(cbm_pipeline_t *p);
atomic_int *cbm_pipeline_cancelled_ptr(cbm_pipeline_t *p);
diff --git a/src/store/store.c b/src/store/store.c
index 19ff6ac01..ae7c06b16 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -115,7 +115,7 @@ static int bind_text(sqlite3_stmt *s, int col, const char *v) {
struct cbm_store {
sqlite3 *db;
const void *progress_owner; /* exclusive native progress guard token */
- const char *db_path; /* heap-allocated, or NULL for :memory: */
+ const char *db_path; /* heap-allocated, or NULL for :memory: */
char errbuf[CBM_SZ_512];
/* Prepared statements (lazily initialized, cached for lifetime) */
@@ -1342,7 +1342,7 @@ int cbm_store_rollback(cbm_store_t *s) {
* for an externally installed handler; direct replacement during this borrow
* is outside the request-owned connection contract. */
static bool store_progress_acquire(cbm_store_t *s, const void *owner, int interval,
- int (*callback)(void *), void *context) {
+ int (*callback)(void *), void *context) {
if (!s || !s->db || !owner || s->progress_owner) {
return false;
}
@@ -1460,7 +1460,8 @@ static int store_scope_cleanup(cbm_store_read_scope_t *scope) {
scope->transaction = false;
}
if (scope->query_only_changed && scope->query_only_saved) {
- const char *sql = scope->saved_query_only ? "PRAGMA query_only=ON;" : "PRAGMA query_only=OFF;";
+ const char *sql =
+ scope->saved_query_only ? "PRAGMA query_only=ON;" : "PRAGMA query_only=OFF;";
int restored = -1;
if (exec_sql(s, sql) != CBM_STORE_OK ||
!store_scope_pragma_get(s, "PRAGMA query_only;", &restored) ||
@@ -1548,8 +1549,8 @@ int cbm_store_read_scope_open(cbm_store_t *s, cbm_store_cancel_fn cancel, void *
}
/* BEGIN alone is not a snapshot. This real main-table read opens one even
* for an empty graph; finalizing the statement retains the transaction. */
- if (sqlite3_prepare_v2(s->db, "SELECT id FROM main.nodes LIMIT 1;", CBM_NOT_FOUND,
- &scope->pin, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, "SELECT id FROM main.nodes LIMIT 1;", CBM_NOT_FOUND, &scope->pin,
+ NULL) != SQLITE_OK) {
goto fail;
}
int step = sqlite3_step(scope->pin);
@@ -1985,12 +1986,12 @@ int cbm_store_compare_graphs(cbm_store_t *base_store, const char *base_project,
bool base_transaction = false;
bool target_transaction = false;
int progress_interval = graph_compare_progress_interval();
- if (!store_progress_acquire(base_store, &progress, progress_interval,
- graph_compare_progress, &progress)) {
+ if (!store_progress_acquire(base_store, &progress, progress_interval, graph_compare_progress,
+ &progress)) {
return CBM_STORE_ERR;
}
- if (!store_progress_acquire(target_store, &progress, progress_interval,
- graph_compare_progress, &progress)) {
+ if (!store_progress_acquire(target_store, &progress, progress_interval, graph_compare_progress,
+ &progress)) {
store_progress_release(base_store, &progress);
return CBM_STORE_ERR;
}
diff --git a/src/store/store_graph_digest.c b/src/store/store_graph_digest.c
index 48f4ac76f..9baac3c39 100644
--- a/src/store/store_graph_digest.c
+++ b/src/store/store_graph_digest.c
@@ -44,51 +44,55 @@ typedef struct {
#define GD_B GD_ALLOW_BLOB
static const gd_column_t gd_projects[] = {
- {"name", GD_T, 0, 1}, {"indexed_at", GD_T, 0, 0}, {"root_path", GD_T, 0, 0}
-};
-static const gd_column_t gd_file_hashes[] = {
- {"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"sha256", GD_T, 0, 0},
- {"mtime_ns", GD_I, 0, 0}, {"size", GD_I, 0, 0}
-};
-static const gd_column_t gd_nodes[] = {
- {"id", GD_I, 0, 1}, {"project", GD_T, 0, 0}, {"label", GD_T, 0, 0},
- {"name", GD_T, 0, 0}, {"qualified_name", GD_T, 0, 0},
- {"file_path", GD_T | GD_N, 0, 0}, {"start_line", GD_I | GD_N, 0, 0},
- {"end_line", GD_I | GD_N, 0, 0}, {"properties", GD_T | GD_N, 0, 0}
-};
-static const gd_column_t gd_edges[] = {
- {"id", GD_I, 0, 1}, {"project", GD_T, 0, 0}, {"source_id", GD_I, 0, 0},
- {"target_id", GD_I, 0, 0}, {"type", GD_T, 0, 0},
- {"properties", GD_T | GD_N, 0, 0}, {"url_path_gen", GD_T | GD_N, 2, 0},
- {"local_name_gen", GD_T | GD_N, 2, 0}
-};
-static const gd_column_t gd_project_summaries[] = {
- {"project", GD_T, 0, 1}, {"summary", GD_T, 0, 0}, {"source_hash", GD_T, 0, 0},
- {"created_at", GD_T, 0, 0}, {"updated_at", GD_T, 0, 0}
-};
+ {"name", GD_T, 0, 1}, {"indexed_at", GD_T, 0, 0}, {"root_path", GD_T, 0, 0}};
+static const gd_column_t gd_file_hashes[] = {{"project", GD_T, 0, 1},
+ {"rel_path", GD_T, 0, 2},
+ {"sha256", GD_T, 0, 0},
+ {"mtime_ns", GD_I, 0, 0},
+ {"size", GD_I, 0, 0}};
+static const gd_column_t gd_nodes[] = {{"id", GD_I, 0, 1},
+ {"project", GD_T, 0, 0},
+ {"label", GD_T, 0, 0},
+ {"name", GD_T, 0, 0},
+ {"qualified_name", GD_T, 0, 0},
+ {"file_path", GD_T | GD_N, 0, 0},
+ {"start_line", GD_I | GD_N, 0, 0},
+ {"end_line", GD_I | GD_N, 0, 0},
+ {"properties", GD_T | GD_N, 0, 0}};
+static const gd_column_t gd_edges[] = {{"id", GD_I, 0, 1},
+ {"project", GD_T, 0, 0},
+ {"source_id", GD_I, 0, 0},
+ {"target_id", GD_I, 0, 0},
+ {"type", GD_T, 0, 0},
+ {"properties", GD_T | GD_N, 0, 0},
+ {"url_path_gen", GD_T | GD_N, 2, 0},
+ {"local_name_gen", GD_T | GD_N, 2, 0}};
+static const gd_column_t gd_project_summaries[] = {{"project", GD_T, 0, 1},
+ {"summary", GD_T, 0, 0},
+ {"source_hash", GD_T, 0, 0},
+ {"created_at", GD_T, 0, 0},
+ {"updated_at", GD_T, 0, 0}};
static const gd_column_t gd_lsp_surface[] = {
- {"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"surface_sha", GD_T, 0, 0},
- {"defs_json", GD_T, 0, 0}, {"ref_bloom", GD_B | GD_N, 0, 0},
- {"config_ctx", GD_T, 0, 0}
-};
-static const gd_column_t gd_index_coverage[] = {
- {"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"kind", GD_T, 0, 3},
- {"detail", GD_T | GD_N, 0, 0}
-};
-static const gd_column_t gd_index_coverage_meta[] = {
- {"project", GD_T, 0, 1}, {"generation", GD_T, 0, 0}, {"index_mode", GD_T, 0, 0},
- {"recorded_at", GD_T, 0, 0}, {"recording_status", GD_T, 0, 0},
- {"ignored_files_stored", GD_I, 0, 0}, {"ignored_files_total", GD_I, 0, 0},
- {"coverage_version", GD_I, 0, 0}, {"hash_records_complete", GD_I, 0, 0}
-};
-static const gd_column_t gd_store_meta[] = {
- {"k", GD_T, 0, 1}, {"v", GD_T, 0, 0}
-};
+ {"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"surface_sha", GD_T, 0, 0},
+ {"defs_json", GD_T, 0, 0}, {"ref_bloom", GD_B | GD_N, 0, 0}, {"config_ctx", GD_T, 0, 0}};
+static const gd_column_t gd_index_coverage[] = {{"project", GD_T, 0, 1},
+ {"rel_path", GD_T, 0, 2},
+ {"kind", GD_T, 0, 3},
+ {"detail", GD_T | GD_N, 0, 0}};
+static const gd_column_t gd_index_coverage_meta[] = {{"project", GD_T, 0, 1},
+ {"generation", GD_T, 0, 0},
+ {"index_mode", GD_T, 0, 0},
+ {"recorded_at", GD_T, 0, 0},
+ {"recording_status", GD_T, 0, 0},
+ {"ignored_files_stored", GD_I, 0, 0},
+ {"ignored_files_total", GD_I, 0, 0},
+ {"coverage_version", GD_I, 0, 0},
+ {"hash_records_complete", GD_I, 0, 0}};
+static const gd_column_t gd_store_meta[] = {{"k", GD_T, 0, 1}, {"v", GD_T, 0, 0}};
/* These descriptors and SQL strings are immutable; all other state is local. */
static const gd_table_t gd_tables[GD_TABLE_COUNT] = {
- {"projects", gd_projects, GD_COLUMNS(gd_projects),
- "PRAGMA main.table_xinfo('projects');",
+ {"projects", gd_projects, GD_COLUMNS(gd_projects), "PRAGMA main.table_xinfo('projects');",
"SELECT name,indexed_at,root_path FROM main.projects ORDER BY CAST(name AS BLOB) ASC;"},
{"file_hashes", gd_file_hashes, GD_COLUMNS(gd_file_hashes),
"PRAGMA main.table_xinfo('file_hashes');",
@@ -119,8 +123,7 @@ static const gd_table_t gd_tables[GD_TABLE_COUNT] = {
"ORDER BY CAST(project AS BLOB) ASC;"},
{"store_meta", gd_store_meta, GD_COLUMNS(gd_store_meta),
"PRAGMA main.table_xinfo('store_meta');",
- "SELECT k,v FROM main.store_meta ORDER BY CAST(k AS BLOB) ASC;"}
-};
+ "SELECT k,v FROM main.store_meta ORDER BY CAST(k AS BLOB) ASC;"}};
#undef GD_B
#undef GD_N
@@ -150,9 +153,9 @@ static bool gd_fail(gd_context_t *g, cbm_store_graph_digest_status_t status) {
if (g->status == CBM_STORE_GRAPH_DIGEST_OK) {
g->status = status;
if (g->scope) {
- (void)cbm_store_read_scope_fail(
- g->scope, status == CBM_STORE_GRAPH_DIGEST_CANCELLED ?
- CBM_STORE_CANCELLED : CBM_STORE_ERR);
+ (void)cbm_store_read_scope_fail(g->scope, status == CBM_STORE_GRAPH_DIGEST_CANCELLED
+ ? CBM_STORE_CANCELLED
+ : CBM_STORE_ERR);
}
}
return false;
@@ -162,8 +165,8 @@ static bool gd_check(gd_context_t *g) {
if (g->scope) {
int status = cbm_store_read_scope_check(g->scope);
if (status != CBM_STORE_OK) {
- return gd_fail(g, status == CBM_STORE_CANCELLED ?
- CBM_STORE_GRAPH_DIGEST_CANCELLED : CBM_STORE_GRAPH_DIGEST_ERROR);
+ return gd_fail(g, status == CBM_STORE_CANCELLED ? CBM_STORE_GRAPH_DIGEST_CANCELLED
+ : CBM_STORE_GRAPH_DIGEST_ERROR);
}
}
return g->status == CBM_STORE_GRAPH_DIGEST_OK;
@@ -486,8 +489,7 @@ static bool gd_table_header(gd_context_t *g, int index, bool present) {
}
for (int i = 0; i < table->column_count; i++) {
const gd_column_t *column = &table->columns[i];
- if (!gd_literal(g, column->name) || !gd_u8(g, column->types) ||
- !gd_u8(g, column->kind)) {
+ if (!gd_literal(g, column->name) || !gd_u8(g, column->types) || !gd_u8(g, column->kind)) {
return false;
}
}
@@ -506,8 +508,7 @@ static bool gd_table_header(gd_context_t *g, int index, bool present) {
return gd_fail(g, CBM_STORE_GRAPH_DIGEST_SCHEMA);
}
gd_text_t name, type, sql;
- if (!gd_read_text(g, 0, &name) || !gd_read_text(g, 1, &type) ||
- !gd_read_text(g, 2, &sql)) {
+ if (!gd_read_text(g, 0, &name) || !gd_read_text(g, 1, &type) || !gd_read_text(g, 2, &sql)) {
return false;
}
if (!gd_text_eq(name, table->name) || !gd_text_eq(type, "table")) {
@@ -564,11 +565,20 @@ static bool gd_column_value(gd_context_t *g, int index, const gd_column_t *colum
int sql_type = sqlite3_column_type(g->stmt, index);
unsigned char tag;
switch (sql_type) {
- case SQLITE_NULL: tag = GD_NULL; break;
- case SQLITE_INTEGER: tag = GD_INTEGER; break;
- case SQLITE_TEXT: tag = GD_TEXT; break;
- case SQLITE_BLOB: tag = GD_BLOB; break;
- default: return gd_fail(g, CBM_STORE_GRAPH_DIGEST_SCHEMA);
+ case SQLITE_NULL:
+ tag = GD_NULL;
+ break;
+ case SQLITE_INTEGER:
+ tag = GD_INTEGER;
+ break;
+ case SQLITE_TEXT:
+ tag = GD_TEXT;
+ break;
+ case SQLITE_BLOB:
+ tag = GD_BLOB;
+ break;
+ default:
+ return gd_fail(g, CBM_STORE_GRAPH_DIGEST_SCHEMA);
}
if (!(column->types & (1u << tag))) {
return gd_fail(g, CBM_STORE_GRAPH_DIGEST_SCHEMA);
@@ -583,8 +593,7 @@ static bool gd_column_value(gd_context_t *g, int index, const gd_column_t *colum
}
if (tag == GD_TEXT) {
gd_text_t value;
- return gd_read_text(g, index, &value) &&
- gd_value(g, tag, value.data, value.length);
+ return gd_read_text(g, index, &value) && gd_value(g, tag, value.data, value.length);
}
const void *blob = sqlite3_column_blob(g->stmt, index);
int length = sqlite3_column_bytes(g->stmt, index);
@@ -655,10 +664,8 @@ static bool gd_project_argument(gd_context_t *g, const unsigned char *project, s
}
cbm_store_graph_digest_status_t cbm_store_graph_digest(
- cbm_store_read_scope_t *scope,
- const unsigned char *project, size_t project_len,
- const cbm_store_graph_digest_limits_t *limits,
- cbm_store_graph_digest_t *out) {
+ cbm_store_read_scope_t *scope, const unsigned char *project, size_t project_len,
+ const cbm_store_graph_digest_limits_t *limits, cbm_store_graph_digest_t *out) {
if (out) {
memset(out, 0, sizeof(*out));
}
diff --git a/src/store/store_graph_digest.h b/src/store/store_graph_digest.h
index 545086473..004ed7840 100644
--- a/src/store/store_graph_digest.h
+++ b/src/store/store_graph_digest.h
@@ -52,9 +52,7 @@ typedef struct {
* authenticity, source identity, extraction completeness or permission to
* narrow selection. Do not reuse it as certification for another read scope. */
cbm_store_graph_digest_status_t cbm_store_graph_digest(
- cbm_store_read_scope_t *scope,
- const unsigned char *project, size_t project_len,
- const cbm_store_graph_digest_limits_t *limits,
- cbm_store_graph_digest_t *out);
+ cbm_store_read_scope_t *scope, const unsigned char *project, size_t project_len,
+ const cbm_store_graph_digest_limits_t *limits, cbm_store_graph_digest_t *out);
#endif /* CBM_STORE_GRAPH_DIGEST_H */
diff --git a/src/store/store_impact.c b/src/store/store_impact.c
index a0e32c898..40c3f75a9 100644
--- a/src/store/store_impact.c
+++ b/src/store/store_impact.c
@@ -31,21 +31,21 @@ enum {
static const char IMPACT_HANDLES[] = "HANDLES";
static const char IMPACT_ROUTE_LABEL[] = "Route";
static const char *const IMPACT_ROUTE_IN[IMPACT_ROUTE_IN_COUNT] = {"HTTP_CALLS", "ASYNC_CALLS",
- "GRPC_CALLS"};
+ "GRPC_CALLS"};
struct cbm_impact_walk {
sqlite3 *db;
cbm_store_read_scope_t *scope; /* borrowed; NULL preserves legacy path */
- int status; /* sticky, keep count intact for allocated-row cleanup */
+ int status; /* sticky, keep count intact for allocated-row cleanup */
char *project;
char **edge_types; /* owned copies: a hit's via_edge points into these */
int edge_type_count;
bool follow_routes;
int max_hops; /* 0 = fixpoint */
- int64_t max_id; /* largest node id when the walk opened */
- int32_t *slot; /* [max_id + 1]: index into hits + 1; 0 = not reached */
- uint8_t *sink; /* [max_id + 1]: reached, never expanded */
+ int64_t max_id; /* largest node id when the walk opened */
+ int32_t *slot; /* [max_id + 1]: index into hits + 1; 0 = not reached */
+ uint8_t *sink; /* [max_id + 1]: reached, never expanded */
cbm_impact_hit_t *hits;
int count;
@@ -91,8 +91,9 @@ static int impact_fail(cbm_impact_walk_t *w, int status) {
return CBM_STORE_ERR;
}
if (w->status == CBM_STORE_OK) {
- w->status = w->scope ? cbm_store_read_scope_fail(w->scope, status) :
- (status == CBM_STORE_CANCELLED ? CBM_STORE_CANCELLED : CBM_STORE_ERR);
+ w->status = w->scope
+ ? cbm_store_read_scope_fail(w->scope, status)
+ : (status == CBM_STORE_CANCELLED ? CBM_STORE_CANCELLED : CBM_STORE_ERR);
}
sqlite3_reset(w->stmt_node);
sqlite3_reset(w->stmt_in);
@@ -120,8 +121,8 @@ static bool impact_visible(const cbm_impact_walk_t *w) {
/* Scoped sorting polls inside comparisons and heap work. Each swap is atomic
* with respect to cancellation so the array remains a permutation for cleanup.
* The legacy path retains its existing qsort and comparators exactly. */
-static bool impact_sort_compare(cbm_impact_walk_t *w, const void *a, const void *b,
- bool hits, int *order) {
+static bool impact_sort_compare(cbm_impact_walk_t *w, const void *a, const void *b, bool hits,
+ int *order) {
if (!impact_check(w)) {
return false;
}
@@ -165,8 +166,8 @@ static void impact_sort_swap(unsigned char *a, unsigned char *b, size_t size) {
}
}
-static bool impact_sift(cbm_impact_walk_t *w, unsigned char *items, size_t count,
- size_t root, size_t size, bool hits) {
+static bool impact_sift(cbm_impact_walk_t *w, unsigned char *items, size_t count, size_t root,
+ size_t size, bool hits) {
while (root < count / 2) {
if (!impact_check(w)) {
return false;
@@ -174,8 +175,8 @@ static bool impact_sift(cbm_impact_walk_t *w, unsigned char *items, size_t count
size_t child = root * 2 + 1;
int order;
if (child + 1 < count) {
- if (!impact_sort_compare(w, items + child * size, items + (child + 1) * size,
- hits, &order)) {
+ if (!impact_sort_compare(w, items + child * size, items + (child + 1) * size, hits,
+ &order)) {
return false;
}
if (order < 0) {
@@ -314,8 +315,8 @@ static impact_add_t impact_add_hit(cbm_impact_walk_t *w, impact_frontier_list_t
/* Follow one edge type from `from` (a frontier hit) to every neighbour not
* reached yet. stmt selects the far end of the edges of that type. */
-static bool impact_expand(cbm_impact_walk_t *w, sqlite3_stmt *stmt, int from,
- const char *edge_type, impact_frontier_list_t *next) {
+static bool impact_expand(cbm_impact_walk_t *w, sqlite3_stmt *stmt, int from, const char *edge_type,
+ impact_frontier_list_t *next) {
if (!impact_check(w) || w->hits[from].hop == INT_MAX) {
return false;
}
@@ -323,7 +324,8 @@ static bool impact_expand(cbm_impact_walk_t *w, sqlite3_stmt *stmt, int from,
int hop = w->hits[from].hop + SKIP_ONE;
if (sqlite3_reset(stmt) != SQLITE_OK ||
sqlite3_bind_int64(stmt, IMPACT_BIND_ID, from_id) != SQLITE_OK ||
- sqlite3_bind_text(stmt, IMPACT_BIND_TYPE, edge_type, CBM_NOT_FOUND, SQLITE_STATIC) != SQLITE_OK) {
+ sqlite3_bind_text(stmt, IMPACT_BIND_TYPE, edge_type, CBM_NOT_FOUND, SQLITE_STATIC) !=
+ SQLITE_OK) {
return false;
}
int rc;
@@ -379,8 +381,7 @@ static bool impact_expand_level(cbm_impact_walk_t *w, const impact_frontier_list
return false;
}
int hit = frontier->items[f].hit;
- if (w->sink[w->hits[hit].id] ||
- strcmp(w->hits[hit].label, IMPACT_ROUTE_LABEL) != 0) {
+ if (w->sink[w->hits[hit].id] || strcmp(w->hits[hit].label, IMPACT_ROUTE_LABEL) != 0) {
continue;
}
if (!impact_expand(w, w->stmt_in, hit, IMPACT_ROUTE_IN[t], next)) {
@@ -419,8 +420,8 @@ void cbm_impact_walk_close(cbm_impact_walk_t *w) {
static bool impact_copy_policy(cbm_impact_walk_t *w, const cbm_impact_policy_t *policy) {
w->project = cbm_mem_strdup(CBM_MEM_CLASS_STORE, policy->project);
- w->edge_types = (char **)cbm_calloc(CBM_MEM_CLASS_STORE,
- (size_t)policy->edge_type_count * sizeof(char *));
+ w->edge_types =
+ (char **)cbm_calloc(CBM_MEM_CLASS_STORE, (size_t)policy->edge_type_count * sizeof(char *));
if (!w->project || !w->edge_types) {
return false;
}
@@ -444,9 +445,8 @@ static bool impact_copy_policy(cbm_impact_walk_t *w, const cbm_impact_policy_t *
static bool impact_prepare(cbm_impact_walk_t *w) {
sqlite3_stmt *max_stmt = NULL;
- if (!impact_check(w) ||
- sqlite3_prepare_v2(w->db, "SELECT COALESCE(MAX(id), 0) FROM nodes", CBM_NOT_FOUND,
- &max_stmt, NULL) != SQLITE_OK) {
+ if (!impact_check(w) || sqlite3_prepare_v2(w->db, "SELECT COALESCE(MAX(id), 0) FROM nodes",
+ CBM_NOT_FOUND, &max_stmt, NULL) != SQLITE_OK) {
return false;
}
bool have_max = sqlite3_step(max_stmt) == SQLITE_ROW;
@@ -454,8 +454,8 @@ static bool impact_prepare(cbm_impact_walk_t *w) {
w->max_id = sqlite3_column_int64(max_stmt, 0);
}
int finalized = sqlite3_finalize(max_stmt);
- if (!have_max || finalized != SQLITE_OK || !impact_check(w) ||
- w->max_id < 0 || w->max_id >= INT32_MAX) {
+ if (!have_max || finalized != SQLITE_OK || !impact_check(w) || w->max_id < 0 ||
+ w->max_id >= INT32_MAX) {
return false;
}
/* The whole per-node state, sized once from the graph: whether the walk
@@ -466,18 +466,22 @@ static bool impact_prepare(cbm_impact_walk_t *w) {
if (!w->slot || !w->sink) {
return false;
}
- if (!impact_check(w) || sqlite3_prepare_v2(w->db,
+ if (!impact_check(w) ||
+ sqlite3_prepare_v2(w->db,
"SELECT qualified_name, label FROM nodes WHERE id = ?1 AND project = ?2",
CBM_NOT_FOUND, &w->stmt_node, NULL) != SQLITE_OK ||
- !impact_check(w) || sqlite3_prepare_v2(w->db, "SELECT source_id FROM edges WHERE target_id = ?1 AND type = ?2",
+ !impact_check(w) ||
+ sqlite3_prepare_v2(w->db, "SELECT source_id FROM edges WHERE target_id = ?1 AND type = ?2",
CBM_NOT_FOUND, &w->stmt_in, NULL) != SQLITE_OK ||
- !impact_check(w) || sqlite3_prepare_v2(w->db, "SELECT target_id FROM edges WHERE source_id = ?1 AND type = ?2",
+ !impact_check(w) ||
+ sqlite3_prepare_v2(w->db, "SELECT target_id FROM edges WHERE source_id = ?1 AND type = ?2",
CBM_NOT_FOUND, &w->stmt_out, NULL) != SQLITE_OK) {
return false;
}
/* The project never changes for the life of the walk. */
return sqlite3_bind_text(w->stmt_node, IMPACT_BIND_TYPE, w->project, CBM_NOT_FOUND,
- SQLITE_STATIC) == SQLITE_OK && impact_check(w);
+ SQLITE_STATIC) == SQLITE_OK &&
+ impact_check(w);
}
static int impact_open(cbm_store_t *s, cbm_store_read_scope_t *scope,
@@ -492,8 +496,8 @@ static int impact_open(cbm_store_t *s, cbm_store_read_scope_t *scope,
}
}
sqlite3 *db = cbm_store_get_db(s);
- if (!db || !out || !policy || !policy->project || !policy->project[0] ||
- !policy->edge_types || policy->edge_type_count <= 0) {
+ if (!db || !out || !policy || !policy->project || !policy->project[0] || !policy->edge_types ||
+ policy->edge_type_count <= 0) {
return scope ? cbm_store_read_scope_fail(scope, CBM_STORE_ERR) : CBM_STORE_ERR;
}
cbm_impact_walk_t *w = (cbm_impact_walk_t *)cbm_calloc(CBM_MEM_CLASS_STORE, sizeof(*w));
@@ -516,8 +520,8 @@ int cbm_impact_walk_open(cbm_store_t *s, const cbm_impact_policy_t *policy,
return impact_open(s, NULL, policy, out);
}
-int cbm_impact_walk_open_scoped(cbm_store_read_scope_t *scope,
- const cbm_impact_policy_t *policy, cbm_impact_walk_t **out) {
+int cbm_impact_walk_open_scoped(cbm_store_read_scope_t *scope, const cbm_impact_policy_t *policy,
+ cbm_impact_walk_t **out) {
if (!scope) {
if (out) {
*out = NULL;
@@ -529,8 +533,7 @@ int cbm_impact_walk_open_scoped(cbm_store_read_scope_t *scope,
/* True when `id` names a node of the walk's project. */
static bool impact_node_exists(cbm_impact_walk_t *w, int64_t id) {
- if (!impact_check(w) || !impact_known_id(w, id) ||
- sqlite3_reset(w->stmt_node) != SQLITE_OK ||
+ if (!impact_check(w) || !impact_known_id(w, id) || sqlite3_reset(w->stmt_node) != SQLITE_OK ||
sqlite3_bind_int64(w->stmt_node, IMPACT_BIND_ID, id) != SQLITE_OK) {
return false;
}
diff --git a/src/store/store_impact.h b/src/store/store_impact.h
index fce10bd84..a32f8aa32 100644
--- a/src/store/store_impact.h
+++ b/src/store/store_impact.h
@@ -61,8 +61,8 @@ int cbm_impact_walk_open(cbm_store_t *s, const cbm_impact_policy_t *policy,
/* Same walk within a pinned read scope, borrowed until close. All work,
* including ordering, checks cancellation. The first walk error invalidates
* this walk and its scope. Close the walk before closing the scope. */
-int cbm_impact_walk_open_scoped(cbm_store_read_scope_t *scope,
- const cbm_impact_policy_t *policy, cbm_impact_walk_t **out);
+int cbm_impact_walk_open_scoped(cbm_store_read_scope_t *scope, const cbm_impact_policy_t *policy,
+ cbm_impact_walk_t **out);
/* Nodes that are reached but never expanded: a test case that reaches the
* change is selected, and what calls the test case is not impacted by it. May
diff --git a/tests/test_language.c b/tests/test_language.c
index dc2bcf7d3..286733c7f 100644
--- a/tests/test_language.c
+++ b/tests/test_language.c
@@ -1314,6 +1314,180 @@ TEST(lang_all_have_names) {
PASS();
}
+/* ── One classifier for a name plus its first bytes ─────────────────
+ * Discovery reads files from disk; the pinned test-impact inventory reads git
+ * blobs. Both must give every file the same language, so both go through
+ * cbm_language_classify with the bytes cbm_language_probe_bytes asks for. */
+
+/* The file `name` with `content`, written byte for byte (no text-mode
+ * conversion on any platform). */
+static bool write_exact(const char *path, const char *content, size_t len) {
+ FILE *f = fopen(path, "wb");
+ if (!f) {
+ return false;
+ }
+ bool ok = fwrite(content, 1, len, f) == len;
+ return fclose(f) == 0 && ok;
+}
+
+/* The classifier on the first probe_bytes(name) bytes of `content`, as the
+ * pinned inventory calls it. */
+static CBMLanguage classify_content(const char *name, const char *content, size_t len) {
+ size_t probe = cbm_language_probe_bytes(name);
+ size_t head = len < probe ? len : probe;
+ return cbm_language_classify(name, (const unsigned char *)content, head, len > head, true);
+}
+
+typedef CBMLanguage (*path_probe_fn)(const char *path);
+
+TEST(lang_probe_bytes_follow_the_name) {
+ ASSERT_EQ(cbm_language_probe_bytes("main.go"), 0);
+ ASSERT_EQ(cbm_language_probe_bytes("Makefile"), 0);
+ ASSERT_EQ(cbm_language_probe_bytes("Foo.m"), 4096);
+ ASSERT_EQ(cbm_language_probe_bytes("Foo.cls"), 4096);
+ ASSERT_EQ(cbm_language_probe_bytes("foo.inc"), 4096);
+ ASSERT_EQ(cbm_language_probe_bytes("Form1.frm"), 4096);
+ ASSERT_EQ(cbm_language_probe_bytes("App.res"), 4096);
+ ASSERT_EQ(cbm_language_probe_bytes("Widget.cfc"), 16384);
+ ASSERT_EQ(cbm_language_probe_bytes("pom.xml"), 255);
+ /* An unknown name falls back to a shebang probe of the first line. */
+ ASSERT_EQ(cbm_language_probe_bytes("run-tests"), 255);
+ ASSERT_EQ(cbm_language_probe_bytes("package.json"), 0);
+ PASS();
+}
+
+/* Every content rule, through the classifier and through the path probe
+ * discovery used before: both must agree, and agree with the expectation. */
+TEST(lang_classify_matches_every_content_rule) {
+ static const struct {
+ const char *name;
+ const char *content;
+ CBMLanguage expect;
+ path_probe_fn path_probe; /* NULL: no public path probe for this rule */
+ } cases[] = {
+ {"a.m", "#import <Foundation/Foundation.h>\n@interface A\n@end\n", CBM_LANG_OBJC,
+ cbm_disambiguate_m},
+ {"b.m", "function f(x)\n return x;\nend function;\n", CBM_LANG_MAGMA, cbm_disambiguate_m},
+ {"c.m", "intrinsic Foo(x) -> RngIntElt\n{}\n", CBM_LANG_MAGMA, cbm_disambiguate_m},
+ {"d.m", "% a comment\nx = 1;\n", CBM_LANG_MATLAB, cbm_disambiguate_m},
+ {"e.cls", "VERSION 1.0 CLASS\r\nAttribute VB_Name = \"W\"\r\n", CBM_LANG_COUNT,
+ cbm_disambiguate_cls},
+ {"f.cls", "/// doc\nClass Demo.Person Extends %Persistent\n{\n}\n",
+ CBM_LANG_OBJECTSCRIPT_UDL, cbm_disambiguate_cls},
+ {"g.cls", "public class Account { }\n", CBM_LANG_APEX, cbm_disambiguate_cls},
+ {"h.inc", "ROUTINE MyMacros [Type=INC]\n", CBM_LANG_OBJECTSCRIPT_ROUTINE,
+ cbm_disambiguate_inc},
+ {"i.inc", "#define Max 10\n", CBM_LANG_OBJECTSCRIPT_ROUTINE, cbm_disambiguate_inc},
+ {"j.inc", "# a BitBake comment\nSRC_URI = \"x\"\n", CBM_LANG_BITBAKE, cbm_disambiguate_inc},
+ {"k.cfc", "<!--- header --->\n<cfcomponent>\n</cfcomponent>\n", CBM_LANG_CFML,
+ cbm_disambiguate_cfc},
+ {"l.cfc", "<!--- header --->\n<cfscript>component {}</cfscript>\n", CBM_LANG_CFSCRIPT,
+ cbm_disambiguate_cfc},
+ {"m.cfc", "<cfquery name=\"q\">select 1</cfquery>\n", CBM_LANG_CFML, cbm_disambiguate_cfc},
+ {"n.cfc", "component {\n function f() {}\n}\n", CBM_LANG_CFSCRIPT, cbm_disambiguate_cfc},
+ {"o.frm", "VERSION 5.00\r\nBegin VB.Form Form1\r\n", CBM_LANG_COUNT, cbm_disambiguate_frm},
+ {"p.frm", "#procedure foo\nLocal F = a;\n", CBM_LANG_FORM, cbm_disambiguate_frm},
+ {"q.res", "RSRC\0\0\0\1binary", CBM_LANG_COUNT, cbm_disambiguate_res},
+ {"r.res", "let x = 1\n", CBM_LANG_RESCRIPT, cbm_disambiguate_res},
+ {"s.xml", "<?xml version=\"1.0\"?>\n<Export generator=\"IRIS\" version=\"26\">\n",
+ CBM_LANG_OBJECTSCRIPT_EXPORT, NULL},
+ {"t.xml", "<?xml version=\"1.0\"?>\n<project/>\n", CBM_LANG_XML, NULL},
+ {"package.json", "{}\n", CBM_LANG_COUNT, NULL},
+ {"data.json", "{}\n", CBM_LANG_JSON, NULL},
+ {"u", "#!/usr/bin/env python3\nprint(1)\n", CBM_LANG_PYTHON, cbm_language_from_shebang},
+ {"v", "#!/bin/sh\r\necho hi\r\n", CBM_LANG_BASH, cbm_language_from_shebang},
+ {"w", "#!/usr/bin/env -S node --no-warnings\n", CBM_LANG_JAVASCRIPT,
+ cbm_language_from_shebang},
+ {"x", "#!/usr/bin/env PYTHON=/usr/bin/python python\n", CBM_LANG_COUNT,
+ cbm_language_from_shebang},
+ {"y", "plain text, no shebang\n", CBM_LANG_COUNT, cbm_language_from_shebang},
+ };
+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
+ /* q.res holds NULs: its length is the literal's, not strlen. */
+ size_t len = strcmp(cases[i].name, "q.res") == 0 ? 15 : strlen(cases[i].content);
+ CBMLanguage got = classify_content(cases[i].name, cases[i].content, len);
+ if (got != cases[i].expect) {
+ printf(" %s: classifier %d, expected %d\n", cases[i].name, (int)got,
+ (int)cases[i].expect);
+ }
+ ASSERT_EQ(got, cases[i].expect);
+ if (cases[i].path_probe) {
+ char path[512];
+ snprintf(path, sizeof(path), "%s/cbm_lang_classify_%s", cbm_tmpdir(), cases[i].name);
+ ASSERT_TRUE(write_exact(path, cases[i].content, len));
+ CBMLanguage by_path = cases[i].path_probe(path);
+ remove(path);
+ if (by_path != cases[i].expect) {
+ printf(" %s: path probe %d, expected %d\n", cases[i].name, (int)by_path,
+ (int)cases[i].expect);
+ }
+ ASSERT_EQ(by_path, cases[i].expect);
+ }
+ }
+ PASS();
+}
+
+/* Content that cannot be read gets what a failed open gave before: the
+ * name's default, and no language for a name that needed a shebang. */
+TEST(lang_classify_unreadable_content_keeps_the_name_default) {
+ ASSERT_EQ(cbm_language_classify("a.m", NULL, 0, false, false), CBM_LANG_MATLAB);
+ ASSERT_EQ(cbm_language_classify("a.cls", NULL, 0, false, false), CBM_LANG_APEX);
+ ASSERT_EQ(cbm_language_classify("a.inc", NULL, 0, false, false), CBM_LANG_BITBAKE);
+ ASSERT_EQ(cbm_language_classify("a.cfc", NULL, 0, false, false), CBM_LANG_CFSCRIPT);
+ ASSERT_EQ(cbm_language_classify("a.frm", NULL, 0, false, false), CBM_LANG_FORM);
+ ASSERT_EQ(cbm_language_classify("a.res", NULL, 0, false, false), CBM_LANG_RESCRIPT);
+ ASSERT_EQ(cbm_language_classify("a.xml", NULL, 0, false, false), CBM_LANG_XML);
+ ASSERT_EQ(cbm_language_classify("run-tests", NULL, 0, false, false), CBM_LANG_COUNT);
+ ASSERT_EQ(cbm_language_classify("main.go", NULL, 0, false, false), CBM_LANG_GO);
+ ASSERT_EQ(cbm_language_classify("package.json", NULL, 0, false, false), CBM_LANG_COUNT);
+ PASS();
+}
+
+/* A shebang counts only when the whole first line was seen: a first line that
+ * runs past the probe is cut, and a cut line names no interpreter. */
+TEST(lang_classify_shebang_needs_the_whole_first_line) {
+ char line[300];
+ memset(line, ' ', sizeof(line));
+ memcpy(line, "#!/bin/sh", 9);
+ /* 255 bytes of first line, and more bytes follow: cut. */
+ ASSERT_EQ(cbm_language_classify("tool", (const unsigned char *)line, 255, true, true),
+ CBM_LANG_COUNT);
+ /* The same 255 bytes are the whole file: the line is complete. */
+ ASSERT_EQ(cbm_language_classify("tool", (const unsigned char *)line, 255, false, true),
+ CBM_LANG_BASH);
+ /* The path probe agrees on both shapes. */
+ char path[512];
+ snprintf(path, sizeof(path), "%s/cbm_lang_classify_long_shebang", cbm_tmpdir());
+ ASSERT_TRUE(write_exact(path, line, sizeof(line)));
+ ASSERT_EQ(cbm_language_from_shebang(path), CBM_LANG_COUNT);
+ ASSERT_TRUE(write_exact(path, line, 255));
+ ASSERT_EQ(cbm_language_from_shebang(path), CBM_LANG_BASH);
+ remove(path);
+ PASS();
+}
+
+/* A probe reads a fixed number of leading bytes and nothing beyond: a marker
+ * past the probe does not count, on either path. */
+TEST(lang_classify_reads_only_its_probe) {
+ static char content[5000];
+ memset(content, ' ', sizeof(content));
+ content[sizeof(content) - 1] = '\0';
+ memcpy(content + 4500, "@interface", 10);
+ size_t len = strlen(content);
+ ASSERT_EQ(classify_content("late.m", content, len), CBM_LANG_MATLAB);
+ char path[512];
+ snprintf(path, sizeof(path), "%s/cbm_lang_classify_late.m", cbm_tmpdir());
+ ASSERT_TRUE(write_exact(path, content, len));
+ ASSERT_EQ(cbm_disambiguate_m(path), CBM_LANG_MATLAB);
+ /* Moved inside the probe it counts. */
+ memcpy(content + 100, "@interface", 10);
+ ASSERT_EQ(classify_content("late.m", content, len), CBM_LANG_OBJC);
+ ASSERT_TRUE(write_exact(path, content, len));
+ ASSERT_EQ(cbm_disambiguate_m(path), CBM_LANG_OBJC);
+ remove(path);
+ PASS();
+}
+
/* ── Suite ─────────────────────────────────────────────────────── */
SUITE(language) {
@@ -1577,4 +1751,9 @@ SUITE(language) {
RUN_TEST(lang_ext_sosl);
RUN_TEST(lang_all_have_names);
+ RUN_TEST(lang_probe_bytes_follow_the_name);
+ RUN_TEST(lang_classify_matches_every_content_rule);
+ RUN_TEST(lang_classify_unreadable_content_keeps_the_name_default);
+ RUN_TEST(lang_classify_shebang_needs_the_whole_first_line);
+ RUN_TEST(lang_classify_reads_only_its_probe);
}
diff --git a/tests/test_main.c b/tests/test_main.c
index d96ef9347..c2a09e4be 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -1730,6 +1730,10 @@ extern void suite_test_impact_git(void);
extern void suite_test_impact_tree(void);
extern void suite_test_impact_tree_read(void);
extern void suite_test_impact_inventory(void);
+extern void suite_test_impact_classify(void);
+extern void suite_test_impact_source(void);
+extern void suite_test_impact_seed(void);
+extern void suite_test_impact_engine(void);
extern void suite_test_impact_runner_filter(void);
extern void suite_store_search(void);
extern void suite_cypher(void);
@@ -2116,6 +2120,10 @@ int main(int argc, char **argv) {
RUN_SELECTED_SUITE(test_impact_tree);
RUN_SELECTED_SUITE(test_impact_tree_read);
RUN_SELECTED_SUITE(test_impact_inventory);
+ RUN_SELECTED_SUITE(test_impact_classify);
+ RUN_SELECTED_SUITE(test_impact_source);
+ RUN_SELECTED_SUITE(test_impact_seed);
+ RUN_SELECTED_SUITE(test_impact_engine);
RUN_SELECTED_SUITE(test_impact_runner_filter);
RUN_SELECTED_SUITE(store_search);
RUN_SELECTED_SUITE(store_bulk);
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 5daae1c00..e6e057d06 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -15871,6 +15871,30 @@ TEST(detect_changes_product_filter_uses_project_config_and_override) {
PASS();
}
+/* scope:"tests" answers with the test_impact object (mcp/test_impact_engine.h).
+ * The selection reads committed changes only: the fixture's edit is in the
+ * worktree, so against main nothing changed. A config_path that does not
+ * exist is evidence missing, never a narrower answer: everything runs. */
+TEST(detect_changes_scope_tests_answers_test_impact) {
+ dc_walk_fixture_t fx;
+ ASSERT_TRUE(dc_walk_fixture_open(&fx));
+ char *text = dc_walk_call(&fx, ",\"scope\":\"tests\"");
+ ASSERT_NOT_NULL(text);
+ if (!strstr(text, "\"decision\":\"nothing\"")) {
+ printf(" %.400s\n", text);
+ }
+ ASSERT_TRUE(strncmp(text, "{\"test_impact\":{", 16) == 0);
+ ASSERT_NOT_NULL(strstr(text, "\"decision\":\"nothing\""));
+ free(text);
+ text = dc_walk_call(&fx, ",\"scope\":\"tests\",\"config_path\":\"missing/config.json\"");
+ ASSERT_NOT_NULL(text);
+ ASSERT_NOT_NULL(strstr(text, "\"decision\":\"run_all\""));
+ ASSERT_NOT_NULL(strstr(text, "CONFIG_INVALID"));
+ free(text);
+ dc_walk_fixture_close(&fx);
+ PASS();
+}
+
TEST(detect_changes_fixpoint_walks_past_depth) {
dc_walk_fixture_t fx;
if (!dc_walk_fixture_open(&fx)) {
@@ -21890,6 +21914,7 @@ SUITE(mcp) {
RUN_TEST(detect_changes_product_filter_does_not_inflate_fallback);
RUN_TEST(detect_changes_seed_params_reject_misuse);
RUN_TEST(detect_changes_product_filter_uses_project_config_and_override);
+ RUN_TEST(detect_changes_scope_tests_answers_test_impact);
RUN_TEST(detect_changes_fixpoint_walks_past_depth);
RUN_TEST(detect_changes_edge_types_reach_references);
RUN_TEST(detect_changes_via_names_the_parent);
diff --git a/tests/test_pipeline_conventions.c b/tests/test_pipeline_conventions.c
index a851dbfda..ff8d73653 100644
--- a/tests/test_pipeline_conventions.c
+++ b/tests/test_pipeline_conventions.c
@@ -320,24 +320,38 @@ TEST(pipeline_conventions_absent_and_default_omit_role_properties) {
ASSERT_TRUE(setup); ASSERT_TRUE(absent); ASSERT_TRUE(configured); ASSERT_TRUE(cleanup);
ASSERT_EQ(rc, 0); ASSERT_TRUE(defaults); PASS();
}
-static int pc_typed_failure(bool legacy) {
+static bool pc_coverage_kind(const char *db, const char *path, const char *kind) {
+ cbm_store_t *s = cbm_store_open_path_query(db);
+ cbm_coverage_row_t *rows = NULL; int count = 0; bool found = false;
+ if (s && cbm_store_coverage_get_path(s, PC_PROJECT, path, &rows, &count) == CBM_STORE_OK)
+ for (int i = 0; i < count; i++) found = found || pc_text(rows[i].kind, kind);
+ cbm_store_free_coverage(rows, count); cbm_store_close(s); return found;
+}
+/* A configured form that cannot be mapped degrades its FILE, not the index
+ * (user decision 2026-10-04): the run publishes, the file is indexed without
+ * configured test roles, and it carries a test_declarations diagnostic. Before,
+ * one such file aborted the whole index (cbm's own repro matrices did). */
+static int pc_typed_degrade(bool legacy) {
pc_env_t env; pc_fixture_t f = {0}; pc_snapshot_t snapshot;
bool setup = pc_env_begin(&env, legacy) && pc_fixture_open(&f, legacy);
bool control = setup && pc_seed(&f, pc_config0) && pc_snapshot(&f, &snapshot);
bool changed = control && pc_source_write(&f, "unit.c", pc_bad_source);
cbm_incremental_route_t route = CBM_INCREMENTAL_ROUTE_NONE;
int rc = changed ? pc_run(&f, legacy ? CBM_MODE_FULL : CBM_MODE_FAST, legacy, 0, NULL, NULL, &route) : -999;
- bool preserved = changed && pc_preserved(&f, &snapshot);
+ char now[128];
+ bool published = changed && pc_generation(f.db, now) && strcmp(now, snapshot.generation) != 0 &&
+ pc_ordinary_graph(f.db, "preserved") && pc_no_roles(f.db) &&
+ pc_coverage_kind(f.db, "unit.c", "test_declarations");
bool cleanup = pc_close(&f, &env);
ASSERT_TRUE(setup); ASSERT_TRUE(control); ASSERT_TRUE(changed); ASSERT_TRUE(cleanup);
ASSERT_EQ(route, legacy ? CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL : CBM_INCREMENTAL_ROUTE_FORCED_FULL);
- ASSERT_EQ(rc, CBM_PIPELINE_ABORT_PRESERVE_DB); ASSERT_TRUE(preserved); PASS();
+ ASSERT_EQ(rc, 0); ASSERT_TRUE(published); PASS();
}
-TEST(pipeline_conventions_typed_failure_full_preserves_generation) {
- ASSERT_EQ(pc_init_status, 0); return pc_typed_failure(false);
+TEST(pipeline_conventions_typed_failure_full_degrades_the_file) {
+ ASSERT_EQ(pc_init_status, 0); return pc_typed_degrade(false);
}
-TEST(pipeline_conventions_typed_failure_incremental_preserves_generation) {
- ASSERT_EQ(pc_init_status, 0); return pc_typed_failure(true);
+TEST(pipeline_conventions_typed_failure_incremental_degrades_the_file) {
+ ASSERT_EQ(pc_init_status, 0); return pc_typed_degrade(true);
}
typedef struct { pc_fixture_t *fixture; int called; bool staged, written; } pc_hook_t;
@@ -610,8 +624,8 @@ SUITE(pipeline_conventions) {
RUN_TEST(pipeline_conventions_parallel_roles_qns_and_calls);
RUN_TEST(pipeline_conventions_config_only_change_rebuilds_same_source);
RUN_TEST(pipeline_conventions_absent_and_default_omit_role_properties);
- RUN_TEST(pipeline_conventions_typed_failure_full_preserves_generation);
- RUN_TEST(pipeline_conventions_typed_failure_incremental_preserves_generation);
+ RUN_TEST(pipeline_conventions_typed_failure_full_degrades_the_file);
+ RUN_TEST(pipeline_conventions_typed_failure_incremental_degrades_the_file);
RUN_TEST(pipeline_conventions_publication_config_mutation_preserves_generation);
RUN_TEST(pipeline_conventions_published_owners_survive_join_and_config_edit);
RUN_TEST(pipeline_conventions_disabled_required_parallel_crosswalk_preserves_generation);
diff --git a/tests/test_pipeline_frozen.c b/tests/test_pipeline_frozen.c
index d48338a09..028856d7c 100644
--- a/tests/test_pipeline_frozen.c
+++ b/tests/test_pipeline_frozen.c
@@ -1264,7 +1264,8 @@ static void pf_diag_before_publish(cbm_pipeline_t *pipeline, const char *stage,
unsigned flags = 123;
hook->building_getter =
!cbm_pipeline_frozen_negative_evidence(hook->owner, &flags) && flags == 0;
- char path[] = "ordinary.c", reason[] = "observed fixture diagnostic", phase[] = "parse_partial";
+ /* A blocking phase: a partial parse alone no longer refuses publication. */
+ char path[] = "ordinary.c", reason[] = "observed fixture diagnostic", phase[] = "extract";
cbm_pipeline_add_file_error(pipeline, path, hook->incomplete ? NULL : reason, phase);
memset(path, 'x', sizeof(path) - 1);
memset(reason, 'y', sizeof(reason) - 1);
@@ -1337,7 +1338,7 @@ static bool pf_diag_run(pf_fixture_t *f, cbm_pipeline_frozen_diag_fault_t fault,
pf_text(rows[0].path, hook.followup ? "followup.c" : "ordinary.c") &&
pf_text(rows[0].reason, hook.followup ? "retained later diagnostic"
: "observed fixture diagnostic") &&
- pf_text(rows[0].phase, hook.followup ? "extract" : "parse_partial");
+ pf_text(rows[0].phase, "extract");
bool failed_state =
!cbm_pipeline_frozen_candidate_path(owner) &&
cbm_pipeline_frozen_build(owner) == CBM_PIPELINE_FROZEN_INVALID &&
@@ -1451,10 +1452,11 @@ TEST(pipeline_frozen_diagnostic_state_and_cancel_precedence) {
PASS();
}
-/* The recovered one-line macro retains a real parse-coverage diagnostic.
- * Keep it as a publication-rejection case while the positive owner/config
- * cases use multiline recovered definitions with unambiguous body ranges. */
-TEST(pipeline_frozen_real_parse_diagnostic_blocks_publication) {
+/* The recovered one-line macro retains a real parse-coverage diagnostic. A
+ * partial parse is a parse gap (user decision 2026-10-04): the candidate is
+ * published, the row is kept, and only the non-blocking PARSE_GAP bit is set,
+ * so the selection can treat a change to this file as a parse gap. */
+TEST(pipeline_frozen_real_parse_gap_is_recorded_not_refused) {
ASSERT_EQ(pf_init_status, 0);
static const char one_line[] =
"void case_sink(void) {}\nvoid suite_sink(void) {}\n"
@@ -1472,12 +1474,12 @@ TEST(pipeline_frozen_real_parse_diagnostic_blocks_publication) {
cbm_file_error_t *rows = NULL;
int count = 0;
cbm_pipeline_get_file_errors(cbm_pipeline_frozen_diagnostics(owner), &rows, &count);
- bool recorded = evidence && flags == CBM_PIPELINE_FROZEN_FILE_DIAGNOSTIC && rows &&
- count == 1 && pf_text(rows[0].path, "unit.pfsource") &&
+ bool recorded = evidence && flags == CBM_PIPELINE_FROZEN_PARSE_GAP && rows && count == 1 &&
+ pf_text(rows[0].path, "unit.pfsource") &&
pf_text(rows[0].phase, "parse_partial") && pf_text(rows[0].reason, "3-3");
- bool rejected = status == CBM_PIPELINE_FROZEN_PIPELINE_ERROR &&
- !cbm_pipeline_frozen_candidate_path(owner) && pf_absent(f.db) &&
- pf_directory_only(f.destination, NULL) && pf_files_equal(f.control, f.saved);
+ const char *candidate = cbm_pipeline_frozen_candidate_path(owner);
+ bool published = status == CBM_PIPELINE_FROZEN_OK && candidate && pf_text(candidate, f.db) &&
+ !pf_absent(f.db) && pf_files_equal(f.control, f.saved);
cbm_pipeline_frozen_free(owner);
bool cleanup = pf_close(&f);
ASSERT_TRUE(setup);
@@ -1486,12 +1488,144 @@ TEST(pipeline_frozen_real_parse_diagnostic_blocks_publication) {
ASSERT_TRUE(ready);
ASSERT_TRUE(cleanup);
ASSERT_TRUE(recorded);
- ASSERT_TRUE(rejected);
+ ASSERT_TRUE(published);
+ PASS();
+}
+
+/* ── A classified file list instead of discovery ──────────────────── */
+
+static bool pf_has_qn(const char *db, const char *qn) {
+ cbm_store_t *store = cbm_store_open_path_query(db);
+ if (!store)
+ return false;
+ cbm_node_t node = {0};
+ bool found = cbm_store_find_node_by_qn(store, PF_PROJECT, qn, &node) == CBM_STORE_OK;
+ cbm_node_free_fields(&node);
+ cbm_store_close(store);
+ return found;
+}
+
+static cbm_pipeline_frozen_status_t pf_create_listed(pf_fixture_t *f,
+ const cbm_pipeline_frozen_file_t *files,
+ size_t count, cbm_pipeline_frozen_t **out) {
+ cbm_git_context_t git = pf_git(f);
+ cbm_pipeline_frozen_inputs_t in = pf_inputs(f, NULL, &git, NULL);
+ in.files = files;
+ in.file_count = count;
+ return cbm_pipeline_frozen_create(&in, out);
+}
+
+/* The build indexes exactly the listed files, under the listed languages: a
+ * file on disk that is not listed is not indexed, and a listed language wins
+ * over what the name alone would give. */
+TEST(pipeline_frozen_indexes_exactly_the_listed_files) {
+ pf_fixture_t f;
+ cbm_pipeline_frozen_t *owner = NULL;
+ ASSERT_TRUE(pf_open(&f));
+ bool ok = pf_source_write(&f, "listed.c", pf_ordinary) &&
+ pf_source_write(&f, "unlisted.c", "void stray(void) {}\n") &&
+ pf_source_write(&f, "script.foo", "def py_fn():\n return 1\n") &&
+ pf_source_write(&f, "README.md", "# readme\n");
+ static const cbm_pipeline_frozen_file_t files[] = {
+ {"script.foo", CBM_LANG_PYTHON},
+ {"listed.c", CBM_LANG_C},
+ {"README.md", CBM_LANG_COUNT},
+ };
+ ok = ok && pf_create_listed(&f, files, 3, &owner) == CBM_PIPELINE_FROZEN_OK &&
+ cbm_pipeline_frozen_build(owner) == CBM_PIPELINE_FROZEN_OK;
+ bool listed = ok && pf_has_qn(f.db, PF_PROJECT ".listed.ordinary") &&
+ pf_has_qn(f.db, PF_PROJECT ".listed.sink");
+ bool unlisted_absent = ok && !pf_has_qn(f.db, PF_PROJECT ".unlisted.stray");
+ bool language_from_list = ok && pf_has_qn(f.db, PF_PROJECT ".script.py_fn");
+ cbm_pipeline_frozen_free(owner);
+ ASSERT_TRUE(pf_close(&f));
+ ASSERT_TRUE(ok);
+ ASSERT_TRUE(listed);
+ ASSERT_TRUE(unlisted_absent);
+ ASSERT_TRUE(language_from_list);
+ PASS();
+}
+
+/* A listed file that is not in the source root means the root is not the
+ * snapshot the list came from. */
+TEST(pipeline_frozen_missing_listed_file_is_input_changed) {
+ pf_fixture_t f;
+ cbm_pipeline_frozen_t *owner = NULL;
+ ASSERT_TRUE(pf_open(&f));
+ bool ok = pf_source_write(&f, "listed.c", pf_ordinary);
+ static const cbm_pipeline_frozen_file_t files[] = {{"listed.c", CBM_LANG_C},
+ {"gone.c", CBM_LANG_C}};
+ ok = ok && pf_create_listed(&f, files, 2, &owner) == CBM_PIPELINE_FROZEN_OK;
+ cbm_pipeline_frozen_status_t status =
+ ok ? cbm_pipeline_frozen_build(owner) : CBM_PIPELINE_FROZEN_INVALID;
+ bool no_candidate = ok && cbm_pipeline_frozen_candidate_path(owner) == NULL && pf_absent(f.db);
+ cbm_pipeline_frozen_free(owner);
+ ASSERT_TRUE(pf_close(&f));
+ ASSERT_TRUE(ok);
+ ASSERT_EQ(status, CBM_PIPELINE_FROZEN_INPUT_CHANGED);
+ ASSERT_TRUE(no_candidate);
+ PASS();
+}
+
+/* A list that cannot name files in the source root is refused at create. */
+TEST(pipeline_frozen_rejects_malformed_file_lists) {
+ pf_fixture_t f;
+ ASSERT_TRUE(pf_open(&f));
+ static const struct {
+ cbm_pipeline_frozen_file_t file;
+ } bad[] = {
+ {{"../escape.c", CBM_LANG_C}},
+ {{"/abs.c", CBM_LANG_C}},
+ {{"", CBM_LANG_C}},
+ {{"a//b.c", CBM_LANG_C}},
+ {{"./a.c", CBM_LANG_C}},
+ {{"a/../b.c", CBM_LANG_C}},
+ {{"a\\b.c", CBM_LANG_C}},
+ {{NULL, CBM_LANG_C}},
+ {{"a.c", (CBMLanguage)-1}},
+ {{"a.c", (CBMLanguage)(CBM_LANG_COUNT + 1)}},
+ };
+ bool all_invalid = true;
+ for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
+ cbm_pipeline_frozen_t *owner = NULL;
+ cbm_pipeline_frozen_status_t status = pf_create_listed(&f, &bad[i].file, 1, &owner);
+ if (status != CBM_PIPELINE_FROZEN_INVALID || owner) {
+ printf(" case %zu: status %d\n", i, (int)status);
+ all_invalid = false;
+ }
+ cbm_pipeline_frozen_free(owner);
+ }
+ /* The same path twice. */
+ static const cbm_pipeline_frozen_file_t twice[] = {{"a.c", CBM_LANG_C}, {"a.c", CBM_LANG_CPP}};
+ cbm_pipeline_frozen_t *owner = NULL;
+ bool twice_invalid =
+ pf_create_listed(&f, twice, 2, &owner) == CBM_PIPELINE_FROZEN_INVALID && owner == NULL;
+ cbm_pipeline_frozen_free(owner);
+ /* A count without a list. */
+ cbm_git_context_t git = pf_git(&f);
+ cbm_pipeline_frozen_inputs_t in = pf_inputs(&f, NULL, &git, NULL);
+ in.file_count = 3;
+ owner = NULL;
+ bool count_invalid =
+ cbm_pipeline_frozen_create(&in, &owner) == CBM_PIPELINE_FROZEN_INVALID && owner == NULL;
+ cbm_pipeline_frozen_free(owner);
+ /* An empty list is a valid list: it indexes nothing. */
+ static const cbm_pipeline_frozen_file_t one[] = {{"a.c", CBM_LANG_C}};
+ in.files = one;
+ in.file_count = 0;
+ owner = NULL;
+ bool empty_ok = cbm_pipeline_frozen_create(&in, &owner) == CBM_PIPELINE_FROZEN_OK && owner;
+ cbm_pipeline_frozen_free(owner);
+ ASSERT_TRUE(pf_close(&f));
+ ASSERT_TRUE(all_invalid);
+ ASSERT_TRUE(twice_invalid);
+ ASSERT_TRUE(count_invalid);
+ ASSERT_TRUE(empty_ok);
PASS();
}
SUITE(pipeline_frozen) {
- RUN_TEST(pipeline_frozen_real_parse_diagnostic_blocks_publication);
+ RUN_TEST(pipeline_frozen_real_parse_gap_is_recorded_not_refused);
pf_init_status = cbm_init();
RUN_TEST(pipeline_frozen_config_snapshot_contract);
RUN_TEST(pipeline_frozen_detached_graph_and_owned_context);
@@ -1504,5 +1638,8 @@ SUITE(pipeline_frozen) {
RUN_TEST(pipeline_frozen_incomplete_diagnostic_is_sticky);
RUN_TEST(pipeline_frozen_diagnostic_allocation_failures);
RUN_TEST(pipeline_frozen_diagnostic_state_and_cancel_precedence);
+ RUN_TEST(pipeline_frozen_indexes_exactly_the_listed_files);
+ RUN_TEST(pipeline_frozen_missing_listed_file_is_input_changed);
+ RUN_TEST(pipeline_frozen_rejects_malformed_file_lists);
cbm_work_arena_release();
}
diff --git a/tests/test_test_conventions.c b/tests/test_test_conventions.c
index 13a52062b..79862da18 100644
--- a/tests/test_test_conventions.c
+++ b/tests/test_test_conventions.c
@@ -149,14 +149,23 @@ static bool tc_body_owner(const CBMFileResult *result, const char *source,
return calls > 0 && usages > 0;
}
+/* A configured form the extractor cannot map is detected with its exact
+ * status and location, then degrades the FILE (user decision 2026-10-04):
+ * the result reads OK, carries no configured roles, and keeps the issue. */
static bool tc_issue(const CBMFileResult *result, CBMTestExtractStatus status,
int index, uint32_t line) {
- return result && result->has_error && result->error_msg && result->error_msg[0] &&
- result->test_declarations_status == status &&
+ return result && result->test_declarations_degraded &&
+ result->test_declarations_degraded_status == status &&
+ result->test_declarations_status == CBM_TEST_EXTRACT_OK && !result->has_error &&
(index == -2 ? result->test_declaration_index >= 0 :
result->test_declaration_index == index) &&
result->test_declaration_line == line;
}
+static bool tc_degraded(const CBMFileResult *result) {
+ return result && result->test_declarations_degraded &&
+ result->test_declarations_degraded_status != CBM_TEST_EXTRACT_OK &&
+ result->test_declarations_status == CBM_TEST_EXTRACT_OK;
+}
TEST(conventions_null_absent_and_defaults_preserve_legacy) {
ASSERT_EQ(tc_init_status, 0);
@@ -241,7 +250,7 @@ TEST(conventions_duplicates_coalesce_and_conflicts_fail_typed) {
"src/conflict.c", config) : NULL;
bool bound = tc_issue(first, CBM_TEST_EXTRACT_AMBIGUOUS, -2, 1) &&
first->test_declaration_index < 2 && tc_issue(again, CBM_TEST_EXTRACT_AMBIGUOUS,
- first->test_declaration_index, 1) && tc_text(first->error_msg, again->error_msg);
+ first->test_declaration_index, 1);
if (!bound) fprintf(stderr, "convention conflict fixture %zu failed\n", i);
rejected = bound && rejected;
cbm_free_result(first); cbm_free_result(again); cbm_test_declarations_free(config);
@@ -415,15 +424,12 @@ TEST(conventions_roles_and_errors_survive_compaction_and_spill) {
CBMFileResult *bad = config ? tc_extract("CHECK(only) {}\n", CBM_LANG_C,
"src/spill_error.c", config) : NULL;
cbm_test_declarations_free(config);
- char error_copy[1024] = {0};
bool before = tc_ok(good) && tc_role(good, "CHECK_alive", CBM_TEST_ROLE_CASE) &&
- tc_issue(bad, CBM_TEST_EXTRACT_MISSING_ARGUMENT, 0, 1) &&
- strlen(bad->error_msg) < sizeof(error_copy);
- if (before) memcpy(error_copy, bad->error_msg, strlen(bad->error_msg) + 1);
+ tc_issue(bad, CBM_TEST_EXTRACT_MISSING_ARGUMENT, 0, 1);
if (good) cbm_result_compact(good);
if (bad) cbm_result_compact(bad);
bool compacted = tc_ok(good) && tc_role(good, "CHECK_alive", CBM_TEST_ROLE_CASE) &&
- tc_issue(bad, CBM_TEST_EXTRACT_MISSING_ARGUMENT, 0, 1) && tc_text(bad->error_msg, error_copy);
+ tc_issue(bad, CBM_TEST_EXTRACT_MISSING_ARGUMENT, 0, 1);
const char *temporary = th_mktempdir("cbm-test-conventions");
char directory[512] = {0};
bool dir_ok = temporary && strlen(temporary) < sizeof(directory);
@@ -436,15 +442,16 @@ TEST(conventions_roles_and_errors_survive_compaction_and_spill) {
if (parked_bad) bad = NULL;
CBMFileResult header = {0};
bool header_ok = parked_bad && cbm_result_spill_peek_header(spill, 1, &header) &&
- header.test_declarations_status == CBM_TEST_EXTRACT_MISSING_ARGUMENT &&
- header.test_declaration_index == 0 && header.test_declaration_line == 1 && header.has_error;
+ header.test_declarations_degraded &&
+ header.test_declarations_degraded_status == CBM_TEST_EXTRACT_MISSING_ARGUMENT &&
+ header.test_declarations_status == CBM_TEST_EXTRACT_OK &&
+ header.test_declaration_index == 0 && header.test_declaration_line == 1 && !header.has_error;
CBMFileResult *loaded_good = parked_good ? cbm_result_spill_load(spill, 0) : NULL;
CBMFileResult *loaded_bad = parked_bad ? cbm_result_spill_load(spill, 1) : NULL;
if (spill) cbm_result_spill_close(spill);
bool reloaded = tc_ok(loaded_good) && tc_role(loaded_good, "CHECK_alive", CBM_TEST_ROLE_CASE) &&
tc_def(loaded_good, "CHECK_alive")->is_test &&
- tc_issue(loaded_bad, CBM_TEST_EXTRACT_MISSING_ARGUMENT, 0, 1) &&
- tc_text(loaded_bad->error_msg, error_copy);
+ tc_issue(loaded_bad, CBM_TEST_EXTRACT_MISSING_ARGUMENT, 0, 1);
cbm_free_result(good); cbm_free_result(bad);
cbm_free_result(loaded_good); cbm_free_result(loaded_bad);
int cleanup = dir_ok ? th_rmtree(directory) : -1;
@@ -734,8 +741,7 @@ TEST(conventions_cpp_digit_separator_does_not_hide_mapping) {
CBMFileResult *bad = config ? tc_extract("int n=1'000;\nCHECK(alpha);\n",
CBM_LANG_CPP, "src/digits.cpp", config) : NULL;
bool control = tc_ok(good) && tc_only_case(good, "CHECK_alpha");
- bool rejected = bad && bad->has_error && bad->test_declarations_status != CBM_TEST_EXTRACT_OK &&
- bad->error_msg && bad->error_msg[0] && bad->test_declaration_index == 0 &&
+ bool rejected = tc_degraded(bad) && bad->test_declaration_index == 0 &&
bad->test_declaration_line == 2;
cbm_free_result(good); cbm_free_result(bad); cbm_test_declarations_free(config);
ASSERT_TRUE(parsed); ASSERT_TRUE(control); ASSERT_TRUE(rejected);
@@ -753,8 +759,7 @@ TEST(conventions_define_multiline_comment_preserves_complete_audit) {
"#define N 1 /* ordinary\ncomment\nCHECK(ok) {}\n",
CBM_LANG_C, "src/comments.c", config) : NULL;
bool control = tc_ok(good) && tc_only_case(good, "CHECK_ok");
- bool rejected = bad && bad->has_error && bad->test_declarations_status != CBM_TEST_EXTRACT_OK &&
- bad->error_msg && bad->error_msg[0];
+ bool rejected = tc_degraded(bad);
cbm_free_result(good); cbm_free_result(bad); cbm_test_declarations_free(config);
ASSERT_TRUE(parsed); ASSERT_TRUE(control); ASSERT_TRUE(rejected);
PASS();
diff --git a/tests/test_test_impact.c b/tests/test_test_impact.c
index 596621f42..18f649456 100644
--- a/tests/test_test_impact.c
+++ b/tests/test_test_impact.c
@@ -10,6 +10,7 @@
#include "test_helpers.h"
#include <foundation/subprocess.h>
#include <mcp/test_impact.h>
+#include <mcp/test_impact_result.h>
#include <discover/test_conventions.h>
#include <foundation/mem_core.h>
#include <stdio.h>
@@ -1686,7 +1687,228 @@ TEST(test_selection_inventory_ambiguity_and_conditionals_use_whole_suite) {
PASS();
}
-TEST(test_selection_unregistered_changes_and_unknown_runner_membership_run_all) {
+/* Uncertainty is scoped to the file it was found in. A file the model cannot
+ * read with certainty, but which defines its own suite, makes that suite
+ * uncertain (it can only run whole) and leaves every other suite narrowable.
+ * The same uncertainty in the runner's file (the list of runnable suites) or
+ * in a file with no suite of its own stays global. cbm has such a file:
+ * tests/repro/repro_call_argument_matrix_a.c defines its tests by macro. */
+static const char *scoped_main =
+ "void main(void) { RUN_SELECTED_SUITE(alpha); RUN_SELECTED_SUITE(beta); }\n";
+static const char *scoped_cases = "TEST(stat) {}\nSUITE(alpha) { RUN_TEST(stat); }\n";
+static const char *scoped_macro =
+ "#define MAKE(n) \\\n TEST(n) {}\nTEST(other) {}\nSUITE(beta) { RUN_TEST(other); }\n";
+
+TEST(test_model_uncertainty_is_scoped_to_the_suites_of_its_file) {
+ tm_source_t scoped[] = {{"tests/cases.c", scoped_cases},
+ {"tests/macro.c", scoped_macro},
+ {"tests/main.c", scoped_main}};
+ cbm_test_model_t *model = model_of(scoped, 3);
+ ASSERT_NOT_NULL(model);
+ ASSERT_FALSE(cbm_test_model_complete(model));
+ ASSERT_TRUE(cbm_test_model_narrowable(model));
+ int n = 0;
+ const cbm_test_suite_t *suites = cbm_test_model_suites(model, &n);
+ ASSERT_EQ(n, 2);
+ ASSERT_STR_EQ(suites[0].name, "alpha");
+ ASSERT_FALSE(suites[0].uncertain);
+ ASSERT_STR_EQ(suites[1].name, "beta");
+ ASSERT_TRUE(suites[1].uncertain);
+ cbm_test_model_free(model);
+
+ /* The runner's file is uncertain: some runnable suite may be missing. */
+ tm_source_t runner[] = {{"tests/cases.c", scoped_cases},
+ {"tests/main.c", "int all = 1; \\\n int more = 2;\n"
+ "void main(void) { RUN_SELECTED_SUITE(alpha); }\n"}};
+ model = model_of(runner, 2);
+ ASSERT_NOT_NULL(model);
+ ASSERT_FALSE(cbm_test_model_narrowable(model));
+ cbm_test_model_free(model);
+
+ /* An uncertain file with no suite of its own: nothing to scope it to. */
+ tm_source_t loose[] = {{"tests/cases.c", scoped_cases},
+ {"tests/helper.c", "int helper = 1; \\\n int more = 2;\n"},
+ {"tests/main.c", "void main(void) { RUN_SELECTED_SUITE(alpha); }\n"}};
+ model = model_of(loose, 3);
+ ASSERT_NOT_NULL(model);
+ ASSERT_FALSE(cbm_test_model_narrowable(model));
+ cbm_test_model_free(model);
+
+ /* No uncertainty at all: complete and narrowable. */
+ tm_source_t clean[] = {{"tests/cases.c", scoped_cases},
+ {"tests/main.c", "void main(void) { RUN_SELECTED_SUITE(alpha); }\n"}};
+ model = model_of(clean, 2);
+ ASSERT_NOT_NULL(model);
+ ASSERT_TRUE(cbm_test_model_complete(model));
+ ASSERT_TRUE(cbm_test_model_narrowable(model));
+ cbm_test_model_free(model);
+ PASS();
+}
+
+/* A line continuation the lexer reads correctly is no uncertainty: inside a
+ * preprocessor directive (LF and CRLF) or a string literal. Only one in plain
+ * code, which can splice tokens, makes the file uncertain. Before this rule,
+ * any continuation anywhere did, and every cbm test file with a multi-line
+ * #define (cli, mcp, daemon_runtime, extraction, test_main.c) could never be
+ * narrowed. */
+TEST(test_model_only_code_continuations_are_uncertain) {
+ static const struct {
+ const char *text;
+ bool complete;
+ } cases[] = {
+ {"#define MULTI(x) \\\n do { x; } while (0)\n"
+ "TEST(a) {}\nSUITE(s) { RUN_TEST(a); }\n"
+ "void main(void) { RUN_SELECTED_SUITE(s); }\n",
+ true},
+ {"#define MULTI(x) \\\r\n (x)\r\n"
+ "TEST(a) {}\r\nSUITE(s) { RUN_TEST(a); }\r\n"
+ "void main(void) { RUN_SELECTED_SUITE(s); }\r\n",
+ true},
+ {"static const char *text = \"a\\\nb\";\n"
+ "TEST(a) {}\nSUITE(s) { RUN_TEST(a); }\n"
+ "void main(void) { RUN_SELECTED_SUITE(s); }\n",
+ true},
+ {"TE\\\nST(a) {}\nSUITE(s) { RUN_TEST(a); }\n"
+ "void main(void) { RUN_SELECTED_SUITE(s); }\n",
+ false},
+ /* a splice that joins a directive word */
+ {"#def\\\nine X 1\nTEST(a) {}\nSUITE(s) { RUN_TEST(a); }\n"
+ "void main(void) { RUN_SELECTED_SUITE(s); }\n",
+ false},
+ /* `*` + splice + `/` closes a block comment, which hides nothing then */
+ {"/* note *\\\n/\nTEST(a) {}\n/* end */\nSUITE(s) { RUN_TEST(a); }\n"
+ "void main(void) { RUN_SELECTED_SUITE(s); }\n",
+ false},
+ };
+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
+ tm_source_t one[] = {{"tests/one.c", cases[i].text}};
+ cbm_test_model_t *model = model_of(one, 1);
+ ASSERT_NOT_NULL(model);
+ if (cbm_test_model_complete(model) != cases[i].complete) {
+ printf(" case %zu: complete %d\n", i, (int)cbm_test_model_complete(model));
+ }
+ ASSERT_EQ(cbm_test_model_complete(model), cases[i].complete);
+ if (cases[i].complete) {
+ int n = 0;
+ (void)cbm_test_model_registrations(model, &n);
+ ASSERT_EQ(n, 1);
+ }
+ cbm_test_model_free(model);
+ }
+ PASS();
+}
+
+/* The selection runs the uncertain suite whole and still narrows the others. */
+TEST(test_selection_scoped_uncertainty_runs_only_its_suite_whole) {
+ tm_source_t scoped[] = {{"tests/cases.c", scoped_cases},
+ {"tests/macro.c", scoped_macro},
+ {"tests/main.c", scoped_main}};
+ cbm_test_model_t *model = model_of(scoped, 3);
+ static const char *rows = "alpha:*\tcomplete\t\t1\nalpha:stat\tcomplete\t\t1\n"
+ "beta:*\tcomplete\t\t1\nbeta:other\tcomplete\t\t0\n";
+ cbm_coverage_map_t *map = selection_map(rows);
+ ASSERT_NOT_NULL(model);
+ ASSERT_NOT_NULL(map);
+ cbm_test_reach_t reach[] = {{"tests/cases.c", "stat", true, true, false}};
+ int changed[] = {0};
+ cbm_test_selection_input_t input = selection_input(model, map, reach, changed);
+ input.reach_count = 1;
+ cbm_test_selection_t *result = cbm_test_select(&input);
+ ASSERT_NOT_NULL(result);
+ ASSERT_EQ(cbm_test_selection_run_all(result), 0);
+ int count = 0;
+ const cbm_test_selected_suite_t *suites = cbm_test_selection_suites(result, &count);
+ ASSERT_EQ(count, 2);
+ ASSERT_STR_EQ(suites[0].name, "alpha");
+ ASSERT_FALSE(suites[0].whole);
+ ASSERT_STR_EQ(suites[1].name, "beta");
+ ASSERT_TRUE(suites[1].whole);
+ ASSERT_TRUE(suites[1].reasons & CBM_TEST_SELECT_INVENTORY_UNKNOWN);
+ ASSERT_EQ(selection_case_reasons(result, "alpha", "stat"), CBM_TEST_SELECT_STATIC);
+ cbm_test_selection_free(result);
+ cbm_coverage_map_free(map);
+ cbm_test_model_free(model);
+ PASS();
+}
+
+/* A changed test no suite registers runs everything; a runner suite the
+ * model finds no definition for runs whole (its tests are unknown). */
+/* The answer follows the selection: a model whose uncertainty is scoped to
+ * some suites (narrowable, not complete) carries those suites whole and
+ * narrows the rest. Before, the codec demanded a complete model and ran
+ * everything whenever any suite was uncertain (on cbm: always). */
+TEST(test_result_scoped_uncertainty_is_not_a_global_run_all) {
+ tm_source_t scoped[] = {{"tests/cases.c", scoped_cases},
+ {"tests/macro.c", scoped_macro},
+ {"tests/main.c", scoped_main}};
+ cbm_test_model_t *model = model_of(scoped, 3);
+ static const char *rows = "alpha:*\tcomplete\t\t1\nalpha:stat\tcomplete\t\t1\n"
+ "beta:*\tcomplete\t\t1\nbeta:other\tcomplete\t\t0\n";
+ cbm_coverage_map_t *map = selection_map(rows);
+ ASSERT_NOT_NULL(model);
+ ASSERT_NOT_NULL(map);
+ ASSERT_TRUE(cbm_test_model_narrowable(model));
+ ASSERT_FALSE(cbm_test_model_complete(model));
+ cbm_test_reach_t reach[] = {{"tests/cases.c", "stat", true, true, false}};
+ int changed[] = {0};
+ cbm_test_selection_input_t input = selection_input(model, map, reach, changed);
+ input.reach_count = 1;
+ cbm_test_selection_t *selection = cbm_test_select(&input);
+ ASSERT_NOT_NULL(selection);
+ char dir[512], path[600];
+ snprintf(dir, sizeof(dir), "%s/cbm-impact-result-XXXXXX", cbm_tmpdir());
+ ASSERT_NOT_NULL(cbm_mkdtemp(dir));
+ snprintf(path, sizeof(path), "%s/absent.json", dir);
+ cbm_test_config_t *config = cbm_test_config_load(path, true);
+ cbm_test_policy_t *policy = config ? cbm_test_policy_new(config) : NULL;
+ ASSERT_NOT_NULL(policy);
+ cbm_test_result_receipt_t receipt = {0};
+ receipt.object_format = CBM_TEST_RESULT_OBJECT_SHA1;
+ receipt.base.format = CBM_TEST_RESULT_OBJECT_SHA1;
+ receipt.head.format = CBM_TEST_RESULT_OBJECT_SHA1;
+ receipt.merge_base.format = CBM_TEST_RESULT_OBJECT_SHA1;
+ receipt.diff_sha256.present = true;
+ receipt.name_status_sha256.present = true;
+ const char *hex = cbm_test_policy_digest(policy);
+ ASSERT_NOT_NULL(hex);
+ for (size_t i = 0; i < 32; i++) {
+ unsigned v = 0;
+ ASSERT_EQ(sscanf(hex + i * 2, "%2x", &v), 1);
+ receipt.policy_sha256.bytes[i] = (unsigned char)v;
+ }
+ receipt.policy_sha256.present = true;
+ cbm_test_result_input_t in = {.comparison = CBM_TEST_RESULT_COMPARISON_CHANGED,
+ .selection = selection,
+ .model = model,
+ .policy = policy,
+ .inventory_complete = true,
+ .activation_complete = true,
+ .receipt = &receipt};
+ cbm_test_result_limits_t limits = {.max_input_bytes = 1048576,
+ .max_items = 100000,
+ .max_alloc_bytes = 16777216,
+ .max_output_bytes = 1048576};
+ cbm_test_result_t *result = NULL;
+ ASSERT_EQ(cbm_test_result_build(&in, &limits, NULL, NULL, &result), CBM_TEST_RESULT_OK);
+ size_t len = 0;
+ const char *json = cbm_test_result_json(result, &len);
+ ASSERT_NOT_NULL(json);
+ if (!strstr(json, "\"decision\":\"selected\"")) {
+ printf(" %.300s\n", json);
+ }
+ ASSERT_NOT_NULL(strstr(json, "\"decision\":\"selected\""));
+ ASSERT_NOT_NULL(strstr(json, "\"run_all_reasons\":[]"));
+ cbm_test_result_free(result);
+ cbm_test_policy_free(policy);
+ cbm_test_config_free(config);
+ cbm_test_selection_free(selection);
+ cbm_coverage_map_free(map);
+ cbm_test_model_free(model);
+ th_rmtree(dir);
+ PASS();
+}
+
+TEST(test_selection_unregistered_changes_run_all_and_undefined_runner_suites_run_whole) {
const char *sources[] = {
"TEST(changed) {}\nTEST(stat) {}\nSUITE(alpha) { RUN_TEST(stat); }\n"
"void main(void) { RUN_SELECTED_SUITE(alpha); }\n",
@@ -1705,8 +1927,17 @@ TEST(test_selection_unregistered_changes_and_unknown_runner_membership_run_all)
reach[2].changed = false;
cbm_test_selection_t *result = cbm_test_select(&input);
ASSERT_NOT_NULL(result);
- ASSERT_TRUE(cbm_test_selection_run_all(result) &
- (i ? CBM_TEST_SELECT_INVENTORY_UNKNOWN : CBM_TEST_SELECT_CHANGED_UNREGISTERED));
+ if (i == 0) {
+ ASSERT_TRUE(cbm_test_selection_run_all(result) & CBM_TEST_SELECT_CHANGED_UNREGISTERED);
+ } else {
+ ASSERT_EQ(cbm_test_selection_run_all(result), 0);
+ int count = 0;
+ const cbm_test_selected_suite_t *suites = cbm_test_selection_suites(result, &count);
+ ASSERT_EQ(count, 1);
+ ASSERT_STR_EQ(suites[0].name, "alpha");
+ ASSERT_TRUE(suites[0].whole);
+ ASSERT_TRUE(suites[0].reasons & CBM_TEST_SELECT_INVENTORY_UNKNOWN);
+ }
cbm_test_selection_free(result);
cbm_test_model_free(model);
}
@@ -1714,6 +1945,42 @@ TEST(test_selection_unregistered_changes_and_unknown_runner_membership_run_all)
PASS();
}
+/* A suite this runner never registers (another runner's, like the repro
+ * board's RUN_SUITE list, or one not built into it) is outside its universe:
+ * its tests are neither selected nor a reason to run everything, even when
+ * one of them changed. On cbm, 49 defined suites are such suites; treating
+ * them as unknown made every selection run everything. */
+TEST(test_selection_other_runners_suites_are_outside_the_selection) {
+ const char *source = "TEST(stat) {}\nTEST(elsewhere) {}\n"
+ "SUITE(alpha) { RUN_TEST(stat); }\n"
+ "SUITE(board) { RUN_TEST(elsewhere); }\n"
+ "void main(void) { RUN_SELECTED_SUITE(alpha); }\n";
+ cbm_test_model_t *model = selection_model(source);
+ static const char *rows = "alpha:*\tcomplete\t\t1\nalpha:stat\tcomplete\t\t0\n";
+ cbm_coverage_map_t *map = selection_map(rows);
+ ASSERT_NOT_NULL(model);
+ ASSERT_NOT_NULL(map);
+ cbm_test_reach_t reach[] = {{"tests/cases.c", "elsewhere", true, true, true},
+ {"tests/cases.c", "stat", true, true, false}};
+ int changed[] = {0};
+ cbm_test_selection_input_t input = selection_input(model, map, reach, changed);
+ input.reach_count = 2;
+ cbm_test_selection_t *result = cbm_test_select(&input);
+ ASSERT_NOT_NULL(result);
+ ASSERT_EQ(cbm_test_selection_run_all(result), 0);
+ int count = 0;
+ const cbm_test_selected_suite_t *suites = cbm_test_selection_suites(result, &count);
+ ASSERT_EQ(count, 1);
+ ASSERT_STR_EQ(suites[0].name, "alpha");
+ ASSERT_FALSE(suites[0].whole);
+ ASSERT_EQ(selection_case_reasons(result, "alpha", "stat"),
+ CBM_TEST_SELECT_STATIC | CBM_TEST_SELECT_COVERAGE);
+ cbm_test_selection_free(result);
+ cbm_coverage_map_free(map);
+ cbm_test_model_free(model);
+ PASS();
+}
+
TEST(test_selection_invalid_evidence_cannot_produce_a_partial_result) {
cbm_test_model_t *model = selection_model(selection_source);
cbm_coverage_map_t *map = selection_map(selection_rows);
@@ -2231,6 +2498,22 @@ TEST(test_policy_defaults_and_first_match_before_target_resolution) {
PASS();
}
+/* A change to the selection's own configuration runs everything, in every
+ * repository, before any project rule could ignore it (review M-4). */
+TEST(test_policy_config_change_runs_all) {
+ cbm_test_policy_t *policy =
+ policy_of("{\"test_impact\":{\"version\":1,\"rules\":[{\"id\":\"late\","
+ "\"paths\":[\"src/**\"],\"action\":\"ignore\"}]}}");
+ ASSERT_NOT_NULL(policy);
+ ASSERT_TRUE(policy_matches(policy, ".codebase-memory.json", "builtin:test-impact-config"));
+ ASSERT_TRUE(policy_matches(policy, "sub/.codebase-memory.json", "builtin:test-impact-config"));
+ const cbm_test_rule_t *rule = NULL;
+ ASSERT_TRUE(cbm_test_policy_match_path(policy, ".codebase-memory.json", &rule));
+ ASSERT_EQ(rule->action, CBM_TEST_RULE_RUN_ALL);
+ cbm_test_policy_free(policy);
+ PASS();
+}
+
TEST(test_policy_lanes_and_semantic_perf_membership) {
cbm_test_policy_t *policy = policy_of(
"{\"test_impact\":{\"version\":1,"
@@ -2962,6 +3245,30 @@ TEST(test_model_guard_like_conditions_cannot_certify_unconditional_cases) {
PASS();
}
+/* `#ifndef X` + `#define X` that does not start the file is the
+ * define-if-undefined idiom (`WIN32_LEAN_AND_MEAN` in 23 cbm source files),
+ * not an include guard: an ordinary condition whose contents are conditional.
+ * It made those files uncertain, and every cbm registry unnarrowable. */
+TEST(test_model_define_if_undefined_is_an_ordinary_condition) {
+ const char *source = "#include <stdio.h>\n"
+ "#ifndef LEAN\n#define LEAN\n#endif\n"
+ "TEST(plain) {}\n"
+ "#ifndef FEATURE\n#define FEATURE\nTEST(gated) {}\n#endif\n"
+ "SUITE(alpha) { RUN_TEST(plain); RUN_TEST(gated); }\n";
+ cbm_test_model_t *model = selection_model(source);
+ ASSERT_NOT_NULL(model);
+ ASSERT_TRUE(cbm_test_model_complete(model));
+ int count = 0;
+ const cbm_test_case_t *cases = cbm_test_model_cases(model, &count);
+ ASSERT_EQ(count, 2);
+ ASSERT_STR_EQ(cases[0].name, "plain");
+ ASSERT_FALSE(cases[0].conditional);
+ ASSERT_STR_EQ(cases[1].name, "gated");
+ ASSERT_TRUE(cases[1].conditional);
+ cbm_test_model_free(model);
+ PASS();
+}
+
TEST(test_model_empty_elif_is_not_certified) {
const char *branches[] = {"#elif\n", "#elif /* no expression */\n", "#elif // empty\n"};
for (size_t i = 0; i < sizeof(branches) / sizeof(branches[0]); i++) {
@@ -3171,6 +3478,39 @@ TEST(test_model_descriptors_argument_failures_have_owned_source_diagnostics) {
PASS();
}
+/* A function-like macro name that is not followed by '(' is not an invocation:
+ * the preprocessor leaves it alone, so it can define or register nothing. An
+ * array or variable that happens to carry a convention's name (cbm itself has
+ * `static const char *const TEST[]` in src/pipeline/pass_semantic_edges.c)
+ * must not make the whole registry uncertain. An opened '(' that never closes
+ * still does. */
+TEST(test_model_descriptors_plain_identifier_with_a_macro_name_is_no_invocation) {
+ cbm_test_model_t *model = descriptor_model(descriptor_config);
+ ASSERT_NOT_NULL(model);
+ const char *source = "static const char *const CASE_AT[] = {\"test\", NULL};\n"
+ "int USE_AT = 3;\n"
+ "void *p = &ENTER_AT;\n"
+ "OTHER_CASE(real) {}\n";
+ ASSERT_TRUE(
+ cbm_test_model_add_source_language(model, "src/not_a_test.c", "c", source, strlen(source)));
+ ASSERT_TRUE(cbm_test_model_finish(model));
+ ASSERT_TRUE(cbm_test_model_complete(model));
+ ASSERT_EQ(cbm_test_model_mapping_status(model, NULL), CBM_TEST_MODEL_MAPPING_OK);
+ ASSERT_EQ(count_cases(model), 1);
+ cbm_test_model_free(model);
+
+ model = descriptor_model(descriptor_config);
+ ASSERT_NOT_NULL(model);
+ const char *open = "CASE_AT(ignore,";
+ ASSERT_TRUE(cbm_test_model_add_source_language(model, "tests/open.c", "c", open, strlen(open)));
+ ASSERT_TRUE(cbm_test_model_finish(model));
+ ASSERT_FALSE(cbm_test_model_complete(model));
+ ASSERT_EQ(cbm_test_model_mapping_status(model, NULL),
+ CBM_TEST_MODEL_MAPPING_MALFORMED_INVOCATION);
+ cbm_test_model_free(model);
+ PASS();
+}
+
TEST(test_model_descriptors_registration_links_stay_in_their_source_file) {
cbm_test_model_t *model = descriptor_model(descriptor_config);
ASSERT_NOT_NULL(model);
@@ -3328,6 +3668,7 @@ SUITE(test_impact) {
RUN_TEST(test_model_descriptors_keep_unrenderable_names_and_templates_explicit);
RUN_TEST(test_model_descriptors_duplicates_are_idempotent_and_conflicts_never_narrow);
RUN_TEST(test_model_descriptors_argument_failures_have_owned_source_diagnostics);
+ RUN_TEST(test_model_descriptors_plain_identifier_with_a_macro_name_is_no_invocation);
RUN_TEST(test_model_descriptors_registration_links_stay_in_their_source_file);
RUN_TEST(test_model_descriptors_presets_are_explicit_and_native_gaps_are_visible);
RUN_TEST(test_model_descriptors_hidden_configured_macros_cannot_certify_inventory);
@@ -3341,6 +3682,7 @@ SUITE(test_impact) {
RUN_TEST(test_selection_cannot_override_partial_model_with_complete_input_flag);
RUN_TEST(test_model_split_identifiers_cannot_hide_registrations);
RUN_TEST(test_model_guard_like_conditions_cannot_certify_unconditional_cases);
+ RUN_TEST(test_model_define_if_undefined_is_an_ordinary_condition);
RUN_TEST(test_model_empty_elif_is_not_certified);
RUN_TEST(test_model_null_empty_source_is_safe);
@@ -3355,6 +3697,7 @@ SUITE(test_impact) {
RUN_TEST(test_policy_embedded_stars_do_not_cross_or_remove_separators);
RUN_TEST(test_policy_retains_exact_snapshot_and_owns_result);
RUN_TEST(test_policy_defaults_and_first_match_before_target_resolution);
+ RUN_TEST(test_policy_config_change_runs_all);
RUN_TEST(test_policy_lanes_and_semantic_perf_membership);
RUN_TEST(test_policy_globs_braces_escapes_and_directory_boundaries);
RUN_TEST(test_policy_rejects_invalid_consumed_fields_without_changing_seed_loader);
@@ -3374,7 +3717,12 @@ SUITE(test_impact) {
RUN_TEST(test_selection_setup_and_rejected_artifacts_select_whole_suites);
RUN_TEST(test_selection_incomplete_global_evidence_never_narrows);
RUN_TEST(test_selection_inventory_ambiguity_and_conditionals_use_whole_suite);
- RUN_TEST(test_selection_unregistered_changes_and_unknown_runner_membership_run_all);
+ RUN_TEST(test_model_uncertainty_is_scoped_to_the_suites_of_its_file);
+ RUN_TEST(test_model_only_code_continuations_are_uncertain);
+ RUN_TEST(test_selection_scoped_uncertainty_runs_only_its_suite_whole);
+ RUN_TEST(test_result_scoped_uncertainty_is_not_a_global_run_all);
+ RUN_TEST(test_selection_unregistered_changes_run_all_and_undefined_runner_suites_run_whole);
+ RUN_TEST(test_selection_other_runners_suites_are_outside_the_selection);
RUN_TEST(test_selection_invalid_evidence_cannot_produce_a_partial_result);
RUN_TEST(test_selection_is_deterministic_deduplicated_and_owns_strings);
RUN_TEST(test_selection_proven_empty_diff_is_distinct_from_unresolved_changes);
diff --git a/tests/test_test_impact_classify.c b/tests/test_test_impact_classify.c
new file mode 100644
index 000000000..bda9a5632
--- /dev/null
+++ b/tests/test_test_impact_classify.c
@@ -0,0 +1,388 @@
+/*
+ * test_test_impact_classify.c — the classified ledger of a pinned HEAD
+ * inventory (src/mcp/test_impact_classify.c), on real git snapshots.
+ *
+ * The ledger must give every kept file the language discovery gives the same
+ * bytes; a read it cannot make is an error, never a default language.
+ */
+#include "test_test_impact_inventory_internal.h"
+
+#include "discover/discover.h"
+#include "discover/userconfig.h"
+#include "mcp/test_impact_classify.h"
+
+typedef struct {
+ const char *path;
+ const char *content;
+} tic_file_t;
+
+/* A HEAD commit holding exactly `files`, its pinned tree and its inventory. */
+static bool tic_snapshot(if_native *n, const tic_file_t *files, size_t count,
+ cbm_test_impact_inventory_t **inventory) {
+ if (!ni_start(n) || !ni_reset_input(n)) {
+ return false;
+ }
+ for (size_t i = 0; i < count; i++) {
+ if (!if_text(&n->input, files[i].path, files[i].content)) {
+ return false;
+ }
+ }
+ n->input.limits.max_probe_prefix_bytes = CBM_LANGUAGE_PROBE_MAX;
+ return ni_commit_input(n) && ni_prepare(n, inventory);
+}
+
+static const cbm_test_impact_classified_t *tic_row(const cbm_test_impact_ledger_t *ledger,
+ const if_native *n, const char *path) {
+ size_t count = 0;
+ const cbm_test_impact_classified_t *rows = cbm_test_impact_ledger_rows(ledger, &count);
+ for (size_t i = 0; i < count; i++) {
+ if (strcmp(n->input.paths[rows[i].file_index], path) == 0) {
+ return &rows[i];
+ }
+ }
+ return NULL;
+}
+
+/* The language discovery's rule gives the same bytes. */
+static CBMLanguage tic_expected(const char *path, const char *content) {
+ const char *slash = strrchr(path, '/');
+ const char *name = slash ? slash + 1 : path;
+ size_t len = strlen(content);
+ size_t probe = cbm_language_probe_bytes(name);
+ size_t head = len < probe ? len : probe;
+ return cbm_language_classify(name, (const unsigned char *)content, head, len > head, true);
+}
+
+static const tic_file_t TIC_FILES[] = {
+ {".gitignore", "drop.c\n"},
+ {"a.m", "#import <Foundation/Foundation.h>\n@interface A\n@end\n"},
+ {"b.m", "% matlab\nx = 1;\n"},
+ {"c.cls", "Class Demo.Person Extends %Persistent\n{\n}\n"},
+ {"d.xml", "<?xml version=\"1.0\"?>\n<Export generator=\"IRIS\">\n"},
+ {"drop.c", "int dropped;\n"},
+ {"package.json", "{}\n"},
+ {"plain", "no shebang here\n"},
+ {"sub/data.json", "{\"k\": 1}\n"},
+ {"tool", "#!/usr/bin/env python3\nprint(1)\n"},
+ {"x.go", "package x\n"},
+};
+
+TEST(test_impact_classify_gives_discovery_languages) {
+ if_native n = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_ledger_t *ledger = NULL;
+ int result = 1;
+ size_t nfiles = sizeof(TIC_FILES) / sizeof(TIC_FILES[0]);
+ NI_CHECK(tic_snapshot(&n, TIC_FILES, nfiles, &inventory));
+ cbm_inventory_error_t error;
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_OK);
+ NI_CHECK(ledger && error.status == CBM_INVENTORY_OK);
+ size_t count = 0;
+ const cbm_test_impact_classified_t *rows = cbm_test_impact_ledger_rows(ledger, &count);
+ /* Every kept file once, in file-index order; the ignored one is absent. */
+ NI_CHECK(count == nfiles - 1);
+ for (size_t i = 1; i < count; i++) {
+ NI_CHECK(rows[i - 1].file_index < rows[i].file_index);
+ }
+ NI_CHECK(tic_row(ledger, &n, "drop.c") == NULL);
+ for (size_t i = 0; i < nfiles; i++) {
+ if (strcmp(TIC_FILES[i].path, "drop.c") == 0) {
+ continue;
+ }
+ const cbm_test_impact_classified_t *row = tic_row(ledger, &n, TIC_FILES[i].path);
+ NI_CHECK(row != NULL);
+ NI_CHECK(row->language == tic_expected(TIC_FILES[i].path, TIC_FILES[i].content));
+ }
+ /* Spot values, so a wrong shared rule cannot pass by agreeing with itself. */
+ NI_CHECK(tic_row(ledger, &n, "a.m")->language == CBM_LANG_OBJC);
+ NI_CHECK(tic_row(ledger, &n, "b.m")->language == CBM_LANG_MATLAB);
+ NI_CHECK(tic_row(ledger, &n, "c.cls")->language == CBM_LANG_OBJECTSCRIPT_UDL);
+ NI_CHECK(tic_row(ledger, &n, "d.xml")->language == CBM_LANG_OBJECTSCRIPT_EXPORT);
+ NI_CHECK(tic_row(ledger, &n, "package.json")->language == CBM_LANG_COUNT);
+ NI_CHECK(tic_row(ledger, &n, "plain")->language == CBM_LANG_COUNT);
+ NI_CHECK(tic_row(ledger, &n, "sub/data.json")->language == CBM_LANG_JSON);
+ NI_CHECK(tic_row(ledger, &n, "tool")->language == CBM_LANG_PYTHON);
+ NI_CHECK(tic_row(ledger, &n, "x.go")->language == CBM_LANG_GO);
+ /* Only names that need content were read: a.m b.m c.cls d.xml, and the
+ * shebang probe for the names without a language (.gitignore plain tool). */
+ cbm_test_impact_classify_usage_t usage;
+ NI_CHECK(cbm_test_impact_ledger_usage(ledger, &usage));
+ NI_CHECK(usage.verified_file_reads == 7);
+ NI_CHECK(memcmp(cbm_test_impact_ledger_manifest(ledger),
+ cbm_test_impact_inventory_view(inventory)->manifest_sha256, 32) == 0);
+ result = 0;
+done:
+ cbm_test_impact_ledger_free(ledger);
+ return ni_finish(&n, inventory, result);
+}
+
+/* Reads and the probe length are charged to what the inventory's limits leave
+ * after the filter. Running out is a LIMIT for the whole pass, with no ledger,
+ * and never a default language for the files that were not read. */
+TEST(test_impact_classify_limits_are_errors_not_defaults) {
+ if_native n = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_ledger_t *ledger = (cbm_test_impact_ledger_t *)(uintptr_t)1;
+ int result = 1;
+ NI_CHECK(tic_snapshot(&n, TIC_FILES, sizeof(TIC_FILES) / sizeof(TIC_FILES[0]), &inventory));
+ cbm_test_impact_inventory_usage_t used;
+ NI_CHECK(cbm_test_impact_inventory_usage(inventory, &used));
+ cbm_inventory_error_t error;
+
+ /* One read fewer than the seven probes need. The limits live in the
+ * inventory, so a tighter one needs a fresh inventory. */
+ cbm_test_impact_inventory_free(inventory);
+ inventory = NULL;
+ n.input.limits.max_verified_file_reads = used.filter.verified_file_reads_reserved + 6;
+ NI_CHECK(ni_prepare(&n, &inventory));
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_LIMIT);
+ NI_CHECK(ledger == NULL && error.status == CBM_INVENTORY_LIMIT);
+ /* Exactly enough is fine. */
+ cbm_test_impact_inventory_free(inventory);
+ inventory = NULL;
+ n.input.limits.max_verified_file_reads = used.filter.verified_file_reads_reserved + 7;
+ NI_CHECK(ni_prepare(&n, &inventory));
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_OK);
+ cbm_test_impact_ledger_free(ledger);
+ ledger = NULL;
+
+ /* A probe longer than the probe limit: the shebang probe needs 255. */
+ cbm_test_impact_inventory_free(inventory);
+ inventory = NULL;
+ n.input.limits.max_probe_prefix_bytes = 254;
+ NI_CHECK(ni_prepare(&n, &inventory));
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_LIMIT);
+ NI_CHECK(ledger == NULL);
+
+ /* Arguments. */
+ NI_CHECK(cbm_test_impact_classify(NULL, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_INVALID);
+ NI_CHECK(cbm_test_impact_classify(inventory, NULL, NULL, &n.input.control, &ledger, &error) ==
+ CBM_INVENTORY_INVALID);
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, NULL,
+ &error) == CBM_INVENTORY_INVALID);
+ result = 0;
+done:
+ if (ledger != (cbm_test_impact_ledger_t *)(uintptr_t)1) {
+ cbm_test_impact_ledger_free(ledger);
+ }
+ return ni_finish(&n, inventory, result);
+}
+
+/* The snapshot's language config decides, passed explicitly: the process-wide
+ * config another index may have installed takes no part. */
+TEST(test_impact_classify_uses_the_given_config) {
+ if_native n = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_ledger_t *with = NULL;
+ cbm_test_impact_ledger_t *without = NULL;
+ cbm_userconfig_t *config = NULL;
+ int result = 1;
+ static const tic_file_t files[] = {{"script.foo", "x = 1\n"}};
+ NI_CHECK(tic_snapshot(&n, files, 1, &inventory));
+ /* A config that maps .foo to Python, from a project file in a scratch dir. */
+ char dir[512];
+ snprintf(dir, sizeof(dir), "%s/cbm-classify-config-XXXXXX", cbm_tmpdir());
+ NI_CHECK(cbm_mkdtemp(dir) != NULL);
+ char file[600];
+ snprintf(file, sizeof(file), "%s/.codebase-memory.json", dir);
+ static const char project[] = "{\"extra_extensions\":{\".foo\":\"python\"}}";
+ NI_CHECK(ni_write(&n, file, project, sizeof(project) - 1));
+ config = cbm_userconfig_load(dir);
+ remove(file);
+ th_rmtree(dir);
+ NI_CHECK(config != NULL);
+ NI_CHECK(cbm_userconfig_lookup(config, ".foo") == CBM_LANG_PYTHON);
+ const cbm_userconfig_t *installed = cbm_get_user_lang_config();
+ cbm_inventory_error_t error;
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, config, &n.input.control, &with,
+ &error) == CBM_INVENTORY_OK);
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &without,
+ &error) == CBM_INVENTORY_OK);
+ NI_CHECK(cbm_get_user_lang_config() == installed);
+ NI_CHECK(tic_row(with, &n, "script.foo")->language == CBM_LANG_PYTHON);
+ NI_CHECK(tic_row(without, &n, "script.foo")->language == CBM_LANG_COUNT);
+ result = 0;
+done:
+ cbm_test_impact_ledger_free(with);
+ cbm_test_impact_ledger_free(without);
+ cbm_userconfig_free(config);
+ return ni_finish(&n, inventory, result);
+}
+
+/* A blob that cannot be read fails the pass: no ledger, the native error, and
+ * the index of the file. A default language here would index a different
+ * graph than the one the selection claims to use. */
+TEST(test_impact_classify_read_failure_is_an_error) {
+ if_native n = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_ledger_t *ledger = (cbm_test_impact_ledger_t *)(uintptr_t)1;
+ int result = 1;
+ NI_CHECK(tic_snapshot(&n, TIC_FILES, sizeof(TIC_FILES) / sizeof(TIC_FILES[0]), &inventory));
+#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
+ NI_CHECK(cbm_pinned_tree_test_set_read_fault(n.input.tree, CBM_PINNED_TREE_READ_FAULT_READ));
+ cbm_inventory_error_t error;
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_IO);
+ NI_CHECK(ledger == NULL && error.status == CBM_INVENTORY_IO);
+ /* The first survivor that needs its content is .gitignore, file 0. */
+ NI_CHECK(error.file_index == 0);
+ /* A started failed read leaves the tree disposal-only, as for the filter. */
+ NI_CHECK(!cbm_pinned_tree_view(n.input.tree));
+ result = 0;
+#else
+ fprintf(stderr, "classification read faults require canonical CBM_ENABLE_TEST_SEAMS\n");
+#endif
+done:
+ if (ledger != (cbm_test_impact_ledger_t *)(uintptr_t)1) {
+ cbm_test_impact_ledger_free(ledger);
+ }
+ return ni_finish(&n, inventory, result);
+}
+
+/* The inventory and the tree must describe the same snapshot. */
+TEST(test_impact_classify_refuses_another_snapshot) {
+ if_native first = {0};
+ if_native second = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_inventory_t *other = NULL;
+ cbm_test_impact_ledger_t *ledger = (cbm_test_impact_ledger_t *)(uintptr_t)1;
+ int result = 1;
+ static const tic_file_t files[] = {{"x.go", "package x\n"}};
+ NI_CHECK(tic_snapshot(&first, TIC_FILES, sizeof(TIC_FILES) / sizeof(TIC_FILES[0]), &inventory));
+ NI_CHECK(tic_snapshot(&second, files, 1, &other));
+ cbm_inventory_error_t error;
+ NI_CHECK(cbm_test_impact_classify(inventory, second.input.tree, NULL, &first.input.control,
+ &ledger, &error) == CBM_INVENTORY_CHANGED);
+ NI_CHECK(ledger == NULL);
+ /* Each with its own tree is fine. */
+ NI_CHECK(cbm_test_impact_classify(other, second.input.tree, NULL, &second.input.control,
+ &ledger, &error) == CBM_INVENTORY_OK);
+ result = 0;
+done:
+ if (ledger != (cbm_test_impact_ledger_t *)(uintptr_t)1) {
+ cbm_test_impact_ledger_free(ledger);
+ }
+ result = ni_finish(&second, other, result);
+ return ni_finish(&first, inventory, result);
+}
+
+/* ── The runnable registry of the same snapshot ─────────────────── */
+
+static const tic_file_t TIC_SUITE_FILES[] = {
+ {"README.md", "# readme\n"},
+ {"src/x.c", "int x(void) { return 1; }\n"},
+ {"tests/test_alpha.c", "TEST(a1) {\n PASS();\n}\nSUITE(alpha) {\n RUN_TEST(a1);\n}\n"},
+ {"tests/test_main.c", "int main(void) {\n RUN_SELECTED_SUITE(alpha);\n return 0;\n}\n"},
+};
+
+static const char TIC_C_CBM[] = "{\"test_impact\":{\"version\":1,\"tests\":{\"presets\":"
+ "{\"c-cbm\":true}}}}";
+
+/* The registry reads the snapshot's own test sources under the snapshot's
+ * declarations: the runner suite, the case and its registration. */
+TEST(test_impact_registry_reads_the_snapshot_tests) {
+ if_native n = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_ledger_t *ledger = NULL;
+ cbm_test_declarations_t *declarations = NULL;
+ cbm_test_model_t *model = NULL;
+ int result = 1;
+ NI_CHECK(tic_snapshot(&n, TIC_SUITE_FILES, sizeof(TIC_SUITE_FILES) / sizeof(TIC_SUITE_FILES[0]),
+ &inventory));
+ cbm_inventory_error_t error;
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_OK);
+ declarations = cbm_test_declarations_parse(TIC_C_CBM, sizeof(TIC_C_CBM) - 1, false);
+ NI_CHECK(declarations != NULL);
+ NI_CHECK(cbm_test_impact_registry(ledger, inventory, n.input.tree, declarations,
+ &n.input.control, &model, &error) == CBM_INVENTORY_OK);
+ NI_CHECK(model && error.status == CBM_INVENTORY_OK);
+ NI_CHECK(cbm_test_model_complete(model));
+ int count = 0;
+ const cbm_test_runner_suite_t *runner = cbm_test_model_runner_suites(model, &count);
+ NI_CHECK(count == 1 && strcmp(runner[0].name, "alpha") == 0);
+ const cbm_test_case_t *cases = cbm_test_model_cases(model, &count);
+ NI_CHECK(count == 1 && strcmp(cases[0].name, "a1") == 0 &&
+ strcmp(cases[0].file, "tests/test_alpha.c") == 0);
+ const cbm_test_registration_t *regs = cbm_test_model_registrations(model, &count);
+ NI_CHECK(count == 1 && strcmp(regs[0].suite, "alpha") == 0 && strcmp(regs[0].test, "a1") == 0 &&
+ regs[0].resolved);
+ result = 0;
+done:
+ cbm_test_model_free(model);
+ cbm_test_declarations_free(declarations);
+ cbm_test_impact_ledger_free(ledger);
+ return ni_finish(&n, inventory, result);
+}
+
+/* Without conventions the registry names no test at all, and a registry that
+ * cannot read every source it needs is an error, never a smaller registry. */
+TEST(test_impact_registry_names_nothing_it_cannot_read) {
+ if_native n = {0};
+ cbm_test_impact_inventory_t *inventory = NULL;
+ cbm_test_impact_ledger_t *ledger = NULL;
+ cbm_test_declarations_t *absent = NULL;
+ cbm_test_declarations_t *c_cbm = NULL;
+ cbm_test_model_t *model = NULL;
+ int result = 1;
+ size_t nfiles = sizeof(TIC_SUITE_FILES) / sizeof(TIC_SUITE_FILES[0]);
+ NI_CHECK(tic_snapshot(&n, TIC_SUITE_FILES, nfiles, &inventory));
+ cbm_inventory_error_t error;
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_OK);
+ absent = cbm_test_declarations_parse(NULL, 0, true);
+ NI_CHECK(absent != NULL);
+ NI_CHECK(cbm_test_impact_registry(ledger, inventory, n.input.tree, absent, &n.input.control,
+ &model, &error) == CBM_INVENTORY_OK);
+ int count = -1;
+ (void)cbm_test_model_cases(model, &count);
+ NI_CHECK(count == 0);
+ cbm_test_model_free(model);
+ model = NULL;
+
+ /* Three C sources to read; the reads the filter and the ledger left over
+ * are cut to two. The limits live in the inventory, so a fresh one. */
+ cbm_test_impact_classify_usage_t spent;
+ NI_CHECK(cbm_test_impact_ledger_usage(ledger, &spent));
+ cbm_test_impact_inventory_usage_t used;
+ NI_CHECK(cbm_test_impact_inventory_usage(inventory, &used));
+ cbm_test_impact_ledger_free(ledger);
+ ledger = NULL;
+ cbm_test_impact_inventory_free(inventory);
+ inventory = NULL;
+ n.input.limits.max_verified_file_reads =
+ used.filter.verified_file_reads_reserved + spent.verified_file_reads + 2;
+ NI_CHECK(ni_prepare(&n, &inventory));
+ NI_CHECK(cbm_test_impact_classify(inventory, n.input.tree, NULL, &n.input.control, &ledger,
+ &error) == CBM_INVENTORY_OK);
+ c_cbm = cbm_test_declarations_parse(TIC_C_CBM, sizeof(TIC_C_CBM) - 1, false);
+ NI_CHECK(c_cbm != NULL);
+ model = (cbm_test_model_t *)(uintptr_t)1;
+ NI_CHECK(cbm_test_impact_registry(ledger, inventory, n.input.tree, c_cbm, &n.input.control,
+ &model, &error) == CBM_INVENTORY_LIMIT);
+ NI_CHECK(model == NULL && error.status == CBM_INVENTORY_LIMIT);
+ result = 0;
+done:
+ if (model != (cbm_test_model_t *)(uintptr_t)1) {
+ cbm_test_model_free(model);
+ }
+ cbm_test_declarations_free(absent);
+ cbm_test_declarations_free(c_cbm);
+ cbm_test_impact_ledger_free(ledger);
+ return ni_finish(&n, inventory, result);
+}
+
+SUITE(test_impact_classify) {
+ RUN_TEST(test_impact_registry_reads_the_snapshot_tests);
+ RUN_TEST(test_impact_registry_names_nothing_it_cannot_read);
+ RUN_TEST(test_impact_classify_gives_discovery_languages);
+ RUN_TEST(test_impact_classify_limits_are_errors_not_defaults);
+ RUN_TEST(test_impact_classify_uses_the_given_config);
+ RUN_TEST(test_impact_classify_read_failure_is_an_error);
+ RUN_TEST(test_impact_classify_refuses_another_snapshot);
+}
diff --git a/tests/test_test_impact_engine.c b/tests/test_test_impact_engine.c
new file mode 100644
index 000000000..8dbaa2d14
--- /dev/null
+++ b/tests/test_test_impact_engine.c
@@ -0,0 +1,305 @@
+/*
+ * test_test_impact_engine.c — detect_changes scope:"tests" end to end
+ * (src/mcp/test_impact_engine*.c) on small real git repositories: a base
+ * commit, a change, and the answer for it.
+ *
+ * Without an admitted coverage map every runner suite runs whole by design;
+ * what the static walk found shows in each suite's reasons ("STATIC" for a
+ * reached suite, "CHANGED" for a changed one).
+ */
+#include "test_framework.h"
+#include "test_helpers.h"
+
+#include "cli/cli.h"
+#include "foundation/compat.h"
+#include "foundation/platform.h"
+#include "foundation/subprocess.h"
+#include "mcp/test_impact_engine.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct {
+ char git[1024];
+ char home[1024];
+ char repo[1100];
+ char work[1100];
+ char log[1100];
+} tie_fixture_t;
+
+static bool tie_git(tie_fixture_t *fx, const char *const *tail) {
+ const char *argv[32] = {fx->git,
+ "-C",
+ fx->repo,
+ "-c",
+ "commit.gpgSign=false",
+ "-c",
+ "core.autocrlf=false",
+ "-c",
+ "user.name=t",
+ "-c",
+ size_t n = 11;
+ for (size_t i = 0; tail[i] && n + 1 < sizeof(argv) / sizeof(argv[0]); i++) {
+ argv[n++] = tail[i];
+ }
+ argv[n] = NULL;
+ cbm_proc_opts_t opts = {.bin = fx->git,
+ .argv = argv,
+ .log_file = fx->log,
+ .strip_git_repo_env = true,
+ .quiet_timeout_ms = 20000};
+ cbm_proc_result_t result = {0};
+ return cbm_subprocess_run(&opts, &result) == 0 && result.outcome == CBM_PROC_CLEAN &&
+ result.exit_code == 0;
+}
+
+static bool tie_write(tie_fixture_t *fx, const char *rel, const char *content) {
+ return th_write_file(TH_PATH(fx->repo, rel), content) == 0;
+}
+
+static bool tie_commit(tie_fixture_t *fx, const char *message) {
+ const char *add[] = {"add", "-A", NULL};
+ const char *commit[] = {"commit", "--quiet", "-m", message, NULL};
+ return tie_git(fx, add) && tie_git(fx, commit);
+}
+
+static const char tie_config[] =
+ "{\"test_impact\":{\"version\":1,\"tests\":{\"presets\":{\"c-cbm\":true}},"
+ "\"rules\":[{\"id\":\"build\",\"paths\":[\"Makefile\"],\"action\":\"run_all\"}]}}\n";
+
+static const char tie_main[] = "#include \"test_framework.h\"\n"
+ "int main(int argc, char **argv) {\n"
+ " RUN_SELECTED_SUITE(alpha);\n"
+ " RUN_SELECTED_SUITE(beta);\n"
+ " RUN_SELECTED_SUITE(matrix);\n"
+ " return 0;\n"
+ "}\n";
+
+static const char tie_alpha[] = "int lib_value(void);\n"
+ "TEST(alpha_uses_lib) {\n"
+ " return lib_value() == 1 ? 0 : 1;\n"
+ "}\n"
+ "TEST(alpha_plain) {\n"
+ " return 0;\n"
+ "}\n"
+ "SUITE(alpha) {\n"
+ " RUN_TEST(alpha_uses_lib);\n"
+ " RUN_TEST(alpha_plain);\n"
+ "}\n";
+
+static const char tie_beta[] = "TEST(beta_alone) {\n"
+ " return 0;\n"
+ "}\n"
+ "SUITE(beta) {\n"
+ " RUN_TEST(beta_alone);\n"
+ "}\n";
+
+/* Tests registered by a macro, as the cbm repro matrices do. */
+static const char tie_matrix[] = "int lib_other(void);\n"
+ "TEST(matrix_one) {\n"
+ " return lib_other() == 2 ? 0 : 1;\n"
+ "}\n"
+ "#define MATRIX_CASES(X) X(matrix_one)\n"
+ "#define RUN_ONE(n) RUN_TEST(n);\n"
+ "SUITE(matrix) {\n"
+ " MATRIX_CASES(RUN_ONE)\n"
+ "}\n";
+
+static const char tie_lib[] = "int lib_value(void) {\n"
+ " return 1;\n"
+ "}\n"
+ "int lib_other(void) {\n"
+ " return 2;\n"
+ "}\n";
+
+static bool tie_open_with(tie_fixture_t *fx, const char *extra_path, const char *extra);
+
+static bool tie_open(tie_fixture_t *fx) {
+ return tie_open_with(fx, NULL, NULL);
+}
+
+/* The fixture, plus one more file in the base commit. */
+static bool tie_open_with(tie_fixture_t *fx, const char *extra_path, const char *extra) {
+ memset(fx, 0, sizeof(*fx));
+ const char *git = cbm_find_cli("git", cbm_get_home_dir());
+ const char *home = th_mktempdir("cbm-ti-engine");
+ char real[1024];
+ if (!git || !home || !realpath(home, real) || strlen(git) >= sizeof(fx->git)) {
+ return false;
+ }
+ snprintf(fx->git, sizeof(fx->git), "%s", git);
+ snprintf(fx->home, sizeof(fx->home), "%s", real);
+ snprintf(fx->repo, sizeof(fx->repo), "%s/repo", real);
+ snprintf(fx->work, sizeof(fx->work), "%s/work", real);
+ snprintf(fx->log, sizeof(fx->log), "%s/git.log", real);
+ const char *init[] = {"-c", "init.templateDir=", "init",
+ "--quiet", "--initial-branch=main", NULL};
+ const char *topic[] = {"checkout", "--quiet", "-b", "topic", NULL};
+ return th_mkdir_p(fx->repo) == 0 && th_mkdir_p(fx->work) == 0 && chmod(fx->work, 0700) == 0 &&
+ tie_git(fx, init) && tie_write(fx, ".codebase-memory.json", tie_config) &&
+ tie_write(fx, "tests/test_main.c", tie_main) &&
+ tie_write(fx, "tests/test_alpha.c", tie_alpha) &&
+ tie_write(fx, "tests/test_beta.c", tie_beta) &&
+ tie_write(fx, "tests/test_matrix.c", tie_matrix) &&
+ tie_write(fx, "src/lib.c", tie_lib) && tie_write(fx, "Makefile", "all:\n") &&
+ (!extra_path || tie_write(fx, extra_path, extra)) && tie_commit(fx, "base") &&
+ tie_git(fx, topic);
+}
+
+static void tie_close(tie_fixture_t *fx) {
+ (void)th_rmtree(fx->home);
+}
+
+/* The answer for the topic branch against main, as JSON (owned). */
+static char *tie_answer(tie_fixture_t *fx) {
+ cbm_test_impact_request_t rq = {.repo_root = fx->repo,
+ .base_ref = "main",
+ .work_parent = fx->work,
+ .deadline_ms = cbm_now_ms() + 120000U};
+ cbm_test_result_t *out = NULL;
+ char diagnostic[512];
+ if (cbm_test_impact_run(&rq, &out, diagnostic, sizeof(diagnostic)) != CBM_TEST_IMPACT_OK) {
+ printf(" engine: %s\n", diagnostic);
+ return NULL;
+ }
+ if (diagnostic[0]) {
+ printf(" engine note: %s\n", diagnostic);
+ }
+ size_t len = 0;
+ const char *json = cbm_test_result_json(out, &len);
+ char *copy = json ? strdup(json) : NULL;
+ cbm_test_result_free(out);
+ return copy;
+}
+
+/* The "reasons" array of one suite's entry in the answer. */
+static bool tie_suite_has(const char *json, const char *suite, const char *reason) {
+ char key[128];
+ snprintf(key, sizeof(key), "\"suite\":\"%s\"", suite);
+ const char *at = strstr(json, key);
+ if (!at) {
+ return false;
+ }
+ const char *end = strstr(at, "\"suite\":\"");
+ end = end && end != at ? end : strstr(at + strlen(key), "\"suite\":\"");
+ char want[128];
+ snprintf(want, sizeof(want), "\"%s\"", reason);
+ const char *hit = strstr(at, want);
+ return hit && (!end || hit < end);
+}
+
+/* A change the walk follows to one test's suite marks that suite reached;
+ * a suite it does not reach is not. */
+TEST(test_impact_engine_reached_suites_carry_static) {
+ tie_fixture_t fx;
+ ASSERT_TRUE(tie_open(&fx));
+ ASSERT_TRUE(tie_write(&fx, "src/lib.c",
+ "int lib_value(void) {\n return 1 + 0;\n}\n"
+ "int lib_other(void) {\n return 2;\n}\n"));
+ ASSERT_TRUE(tie_commit(&fx, "change lib_value"));
+ char *json = tie_answer(&fx);
+ ASSERT_NOT_NULL(json);
+ if (!tie_suite_has(json, "alpha", "STATIC")) {
+ printf(" %.600s\n", json);
+ }
+ ASSERT_TRUE(tie_suite_has(json, "alpha", "STATIC"));
+ ASSERT_FALSE(tie_suite_has(json, "beta", "STATIC"));
+ ASSERT_FALSE(tie_suite_has(json, "matrix", "STATIC"));
+ free(json);
+ tie_close(&fx);
+ PASS();
+}
+
+/* A test a macro registers has no explicit registration: reaching it must
+ * still select its suite (whole), as the measured reference does. */
+TEST(test_impact_engine_macro_registered_tests_select_their_suite) {
+ tie_fixture_t fx;
+ ASSERT_TRUE(tie_open(&fx));
+ ASSERT_TRUE(tie_write(&fx, "src/lib.c",
+ "int lib_value(void) {\n return 1;\n}\n"
+ "int lib_other(void) {\n return 2 + 0;\n}\n"));
+ ASSERT_TRUE(tie_commit(&fx, "change lib_other"));
+ char *json = tie_answer(&fx);
+ ASSERT_NOT_NULL(json);
+ if (!tie_suite_has(json, "matrix", "STATIC")) {
+ printf(" %.900s\n", json);
+ }
+ ASSERT_TRUE(tie_suite_has(json, "matrix", "STATIC"));
+ ASSERT_FALSE(tie_suite_has(json, "alpha", "STATIC"));
+ free(json);
+ tie_close(&fx);
+ PASS();
+}
+
+/* A path a run-all rule matches runs everything; so does a change the
+ * test-runner lane cannot read (M-10); an empty change selects nothing. */
+TEST(test_impact_engine_rules_unmapped_and_empty) {
+ tie_fixture_t fx;
+ ASSERT_TRUE(tie_open(&fx));
+ char *json = tie_answer(&fx);
+ ASSERT_NOT_NULL(json);
+ ASSERT_NOT_NULL(strstr(json, "\"decision\":\"nothing\""));
+ free(json);
+
+ ASSERT_TRUE(tie_write(&fx, "Makefile", "all:\n\techo\n"));
+ ASSERT_TRUE(tie_commit(&fx, "build change"));
+ json = tie_answer(&fx);
+ ASSERT_NOT_NULL(json);
+ ASSERT_NOT_NULL(strstr(json, "\"decision\":\"run_all\""));
+ ASSERT_NOT_NULL(strstr(json, "RULE_RUN_ALL"));
+ free(json);
+
+ const char *reset[] = {"reset", "--quiet", "--hard", "main", NULL};
+ ASSERT_TRUE(tie_git(&fx, reset));
+ ASSERT_TRUE(tie_write(&fx, "data/table.csv", "a,b\n1,2\n"));
+ ASSERT_TRUE(tie_commit(&fx, "runtime data"));
+ json = tie_answer(&fx);
+ ASSERT_NOT_NULL(json);
+ ASSERT_NOT_NULL(strstr(json, "UNMAPPED_FILE"));
+ free(json);
+ tie_close(&fx);
+ PASS();
+}
+
+/* A parse gap hides the edges written in its lines: a helper whose broken
+ * line calls the changed function has no CALLS edge to it. The gap's text
+ * still names the function, so the helper is reached, and with it the test
+ * that calls the helper (per-file PARSE_GAP rule, user decision 2026-10-04). */
+TEST(test_impact_engine_parse_gaps_reach_what_they_name) {
+ static const char gapped[] = "int lib_value(void);\n"
+ "static int helper(void) {\n"
+ " int x = 0;\n"
+ " x = (lib_value() ;\n"
+ " return x;\n"
+ "}\n"
+ "TEST(gap_case) {\n"
+ " return helper();\n"
+ "}\n"
+ "SUITE(beta) {\n"
+ " RUN_TEST(gap_case);\n"
+ "}\n";
+ tie_fixture_t fx;
+ ASSERT_TRUE(tie_open_with(&fx, "tests/test_beta.c", gapped));
+ ASSERT_TRUE(tie_write(&fx, "src/lib.c",
+ "int lib_value(void) {\n return 1 + 0;\n}\n"
+ "int lib_other(void) {\n return 2;\n}\n"));
+ ASSERT_TRUE(tie_commit(&fx, "change lib_value"));
+ char *json = tie_answer(&fx);
+ ASSERT_NOT_NULL(json);
+ if (!tie_suite_has(json, "beta", "STATIC")) {
+ printf(" %.900s\n", json);
+ }
+ ASSERT_TRUE(tie_suite_has(json, "beta", "STATIC"));
+ free(json);
+ tie_close(&fx);
+ PASS();
+}
+
+SUITE(test_impact_engine) {
+ RUN_TEST(test_impact_engine_reached_suites_carry_static);
+ RUN_TEST(test_impact_engine_macro_registered_tests_select_their_suite);
+ RUN_TEST(test_impact_engine_rules_unmapped_and_empty);
+ RUN_TEST(test_impact_engine_parse_gaps_reach_what_they_name);
+}
diff --git a/tests/test_test_impact_inventory_internal.h b/tests/test_test_impact_inventory_internal.h
index dac0055a4..d1f85d20a 100644
--- a/tests/test_test_impact_inventory_internal.h
+++ b/tests/test_test_impact_inventory_internal.h
@@ -15,6 +15,8 @@
bool ni_write(if_native *n, const char *path, const void *bytes, size_t size);
bool ni_ambient_change(if_native *n);
bool ni_replace_snapshot(if_native *n, bool empty_controls);
+bool ni_reset_input(if_native *n);
+bool ni_commit_input(if_native *n);
bool ni_tree(if_native *n, cbm_git_revision_t revision);
bool ni_dependency(if_native *n, cbm_git_revision_t revision);
bool ni_start(if_native *n);
diff --git a/tests/test_test_impact_inventory_support.c b/tests/test_test_impact_inventory_support.c
index 88924cbed..f77579290 100644
--- a/tests/test_test_impact_inventory_support.c
+++ b/tests/test_test_impact_inventory_support.c
@@ -128,16 +128,28 @@ bool ni_start(if_native *n) {
return if_native_start(n) && ni_dependency(n, CBM_GIT_REV_HEAD);
}
-bool ni_replace_snapshot(if_native *n, bool empty_controls) {
+bool ni_reset_input(if_native *n) {
if (!if_native_close(n))
return false;
cbm_git_facts_free(n->facts);
n->facts = NULL;
if_init(&n->input);
+ return true;
+}
+
+bool ni_replace_snapshot(if_native *n, bool empty_controls) {
+ if (!ni_reset_input(n))
+ return false;
if (empty_controls &&
(!if_text(&n->input, ".cbmignore", "") || !if_text(&n->input, ".gitignore", "") ||
!if_text(&n->input, "source.c", "int source;\n")))
return false;
+ return ni_commit_input(n);
+}
+
+/* Commit exactly n->input's files as HEAD, then open its facts, pinned tree
+ * and dependency. Mode 100755 for the third file, as the default fixture. */
+bool ni_commit_input(if_native *n) {
const char *clear[] = {"read-tree", "--empty", NULL};
if (!if_native_git(n, clear, NULL, 0))
return false;
diff --git a/tests/test_test_impact_seed.c b/tests/test_test_impact_seed.c
new file mode 100644
index 000000000..97dd62b73
--- /dev/null
+++ b/tests/test_test_impact_seed.c
@@ -0,0 +1,295 @@
+/*
+ * test_test_impact_seed.c — what a change seeds (src/mcp/test_impact_seed.c),
+ * one test per rule of the measured reference (replay4.py seeding and header
+ * symbol propagation), on a small in-memory graph with its sources.
+ */
+#include "test_framework.h"
+
+#include "mcp/test_impact.h"
+#include "mcp/test_impact_seed.h"
+#include "mcp/test_impact_source.h"
+#include "store/store.h"
+
+#include <stdio.h>
+#include <string.h>
+
+typedef struct {
+ cbm_store_t *store;
+ cbm_ti_graph_t *graph;
+ cbm_ti_source_t *source;
+ cbm_test_model_t *model;
+} tsd_fixture_t;
+
+static int64_t tsd_node(tsd_fixture_t *f, const char *label, const char *name, const char *file,
+ int start, int end) {
+ char qn[256];
+ snprintf(qn, sizeof(qn), "p.%s.%s.%d", file, name, start);
+ cbm_node_t node = {.project = "p",
+ .label = label,
+ .name = name,
+ .qualified_name = qn,
+ .file_path = file,
+ .start_line = start,
+ .end_line = end};
+ return cbm_store_upsert_node(f->store, &node);
+}
+
+/* Sources: pairs of (path, text). Model: the test sources among them. */
+static bool tsd_open(tsd_fixture_t *f, const char *const *files, int count) {
+ memset(f, 0, sizeof(*f));
+ f->store = cbm_store_open_memory();
+ if (!f->store || cbm_store_upsert_project(f->store, "p", "/tmp/p") != CBM_STORE_OK) {
+ return false;
+ }
+ f->graph = cbm_ti_graph_new(f->store, "p");
+ f->source = cbm_ti_source_new();
+ f->model = cbm_test_model_new(cbm_test_conventions_cbm());
+ if (!f->graph || !f->source || !f->model) {
+ return false;
+ }
+ for (int i = 0; i < count; i += 2) {
+ size_t len = strlen(files[i + 1]);
+ if (!cbm_ti_source_add(f->source, files[i], files[i + 1], len)) {
+ return false;
+ }
+ if (strncmp(files[i], "tests/", 6) == 0 &&
+ !cbm_test_model_add_source(f->model, files[i], files[i + 1], len)) {
+ return false;
+ }
+ }
+ return cbm_ti_source_finish(f->source) && cbm_test_model_finish(f->model);
+}
+
+static void tsd_close(tsd_fixture_t *f) {
+ cbm_test_model_free(f->model);
+ cbm_ti_source_free(f->source);
+ cbm_ti_graph_free(f->graph);
+ if (f->store) {
+ cbm_store_close(f->store);
+ }
+}
+
+static cbm_ti_seeds_t *tsd_seed(tsd_fixture_t *f, const cbm_ti_change_t *changes, int count) {
+ cbm_ti_seed_input_t in = {.changes = changes,
+ .change_count = count,
+ .model = f->model,
+ .graph = f->graph,
+ .source = f->source};
+ cbm_ti_seeds_t *out = NULL;
+ return cbm_ti_seed(&in, &out) == CBM_TI_SEED_OK ? out : NULL;
+}
+
+static bool tsd_seeded(const cbm_ti_seeds_t *s, int64_t id) {
+ int count = 0;
+ const int64_t *ids = cbm_ti_seeds_nodes(s, &count);
+ for (int i = 0; i < count; i++) {
+ if (ids[i] == id) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static int tsd_seed_count(const cbm_ti_seeds_t *s) {
+ int count = 0;
+ (void)cbm_ti_seeds_nodes(s, &count);
+ return count;
+}
+
+/* A hunk at head seeds the definitions it overlaps; a comment-only hunk seeds
+ * nothing; a pure deletion seeds the definition around it; a hunk outside
+ * every definition seeds its whole file. */
+TEST(test_impact_seed_hunks_follow_the_reference) {
+ const char *files[] = {"src/a.c", "int g;\nint f(void) {\n return g;\n}\n"
+ "int h(void) {\n return 1;\n}\n"};
+ tsd_fixture_t f;
+ ASSERT_TRUE(tsd_open(&f, files, 2));
+ int64_t g = tsd_node(&f, "Variable", "g", "src/a.c", 1, 1);
+ int64_t fn = tsd_node(&f, "Function", "f", "src/a.c", 2, 4);
+ int64_t h = tsd_node(&f, "Function", "h", "src/a.c", 5, 7);
+ (void)tsd_node(&f, "Module", "a", "src/a.c", 1, 7);
+
+ static const char *const body[] = {" return g + 1;"};
+ static const char *const old_body[] = {" return g;"};
+ cbm_diff_hunk_t edit = {.start = 3,
+ .count = 1,
+ .added = body,
+ .added_count = 1,
+ .removed = old_body,
+ .removed_count = 1};
+ cbm_ti_change_t change = {.path = "src/a.c", .hunks = &edit, .hunk_count = 1};
+ cbm_ti_seeds_t *s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(tsd_seed_count(s), 1);
+ ASSERT_TRUE(tsd_seeded(s, fn));
+ cbm_ti_seeds_free(s);
+
+ static const char *const comment[] = {" // why"};
+ cbm_diff_hunk_t note = {.start = 6, .count = 1, .added = comment, .added_count = 1};
+ change.hunks = &note;
+ s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(tsd_seed_count(s), 0);
+ cbm_ti_seeds_free(s);
+
+ static const char *const removed[] = {" h_extra();"};
+ cbm_diff_hunk_t cut = {.start = 5, .count = 0, .removed = removed, .removed_count = 1};
+ change.hunks = &cut;
+ s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(tsd_seed_count(s), 1);
+ ASSERT_TRUE(tsd_seeded(s, h));
+ cbm_ti_seeds_free(s);
+
+ static const char *const include[] = {"#include \"b.h\""};
+ cbm_diff_hunk_t top = {.start = 8, .count = 1, .added = include, .added_count = 1};
+ change.hunks = &top;
+ s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(tsd_seed_count(s), 3); /* g, f, h: the Module is no definition */
+ ASSERT_TRUE(tsd_seeded(s, g) && tsd_seeded(s, fn) && tsd_seeded(s, h));
+ cbm_ti_seeds_free(s);
+ tsd_close(&f);
+ PASS();
+}
+
+/* A changed test case or suite body is reported, never seeded. */
+TEST(test_impact_seed_changed_cases_and_suites_are_reported) {
+ const char *files[] = {"tests/t.c", "TEST(alpha) {\n PASS();\n}\n"
+ "SUITE(s) {\n RUN_TEST(alpha);\n}\n"};
+ tsd_fixture_t f;
+ ASSERT_TRUE(tsd_open(&f, files, 2));
+ (void)tsd_node(&f, "Function", "alpha", "tests/t.c", 1, 3);
+ (void)tsd_node(&f, "Function", "s", "tests/t.c", 4, 6);
+ static const char *const line[] = {" ASSERT_TRUE(1);"};
+ cbm_diff_hunk_t hunks[] = {{.start = 2, .count = 1, .added = line, .added_count = 1},
+ {.start = 5, .count = 1, .added = line, .added_count = 1}};
+ cbm_ti_change_t change = {.path = "tests/t.c", .hunks = hunks, .hunk_count = 2};
+ cbm_ti_seeds_t *s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(tsd_seed_count(s), 0);
+ int count = 0;
+ const int *cases = cbm_ti_seeds_changed_cases(s, &count);
+ ASSERT_EQ(count, 1);
+ ASSERT_EQ(cases[0], 0);
+ const int *suites = cbm_ti_seeds_changed_suites(s, &count);
+ ASSERT_EQ(count, 1);
+ ASSERT_EQ(suites[0], 0);
+ cbm_ti_seeds_free(s);
+ tsd_close(&f);
+ PASS();
+}
+
+/* A name a removed line declared that head no longer defines: every
+ * definition mentioning it is a seed, a mention at file scope of a source
+ * file seeds that file whole, and one in a header outside a definition adds
+ * nothing. A deleted file contributes every name it declared. */
+TEST(test_impact_seed_deleted_names_are_found_by_text) {
+ const char *files[] = {
+ "src/a.c", "int user(void) {\n return gone();\n}\n",
+ "src/b.c", "static void *table[] = {gone};\nint b(void) { return 0; }\n",
+ "inc/x.h", "int gone(void);\n",
+ "src/old.c", "int unrelated(void) { return 1; }\n"};
+ tsd_fixture_t f;
+ ASSERT_TRUE(tsd_open(&f, files, 8));
+ int64_t user = tsd_node(&f, "Function", "user", "src/a.c", 1, 3);
+ int64_t b = tsd_node(&f, "Function", "b", "src/b.c", 2, 2);
+ (void)tsd_node(&f, "Function", "unrelated", "src/old.c", 1, 1);
+ static const char *const removed[] = {"int gone(void) {", " return 0;", "}"};
+ cbm_diff_hunk_t cut = {.start = 1, .count = 0, .removed = removed, .removed_count = 3};
+ cbm_ti_change_t change = {.path = "src/old.c", .hunks = &cut, .hunk_count = 1};
+ cbm_ti_seeds_t *s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ int count = 0;
+ const char *const *names = cbm_ti_seeds_deleted_names(s, &count);
+ ASSERT_EQ(count, 1);
+ ASSERT_STR_EQ(names[0], "gone");
+ ASSERT_TRUE(tsd_seeded(s, user)); /* mentions gone inside a definition */
+ ASSERT_TRUE(tsd_seeded(s, b)); /* b.c mentions it at file scope: whole file */
+ cbm_ti_seeds_free(s);
+
+ cbm_ti_change_t deleted = {.path = "src/gone.c",
+ .deleted = true,
+ .base_text = "int gone(void) {\n return 0;\n}\n",
+ .base_len = strlen("int gone(void) {\n return 0;\n}\n")};
+ s = tsd_seed(&f, &deleted, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_TRUE(tsd_seeded(s, user));
+ cbm_ti_seeds_free(s);
+ tsd_close(&f);
+ PASS();
+}
+
+/* A header change names what it changes, closes the names over the headers'
+ * macros, and seeds what mentions them in files that include the header. */
+TEST(test_impact_seed_header_names_propagate_through_includes_and_macros) {
+ const char *files[] = {"inc/h.h", "#define LIMIT 4\n#define TWICE (LIMIT * 2)\n",
+ "src/a.c", "#include \"../inc/h.h\"\nint a(void) { return LIMIT; }\n",
+ "src/c.c", "#include \"inc/h.h\"\nint c(void) { return TWICE; }\n",
+ "src/far.c", "int far(void) { return LIMIT; }\n"};
+ tsd_fixture_t f;
+ ASSERT_TRUE(tsd_open(&f, files, 8));
+ int64_t limit = tsd_node(&f, "Macro", "LIMIT", "inc/h.h", 1, 1);
+ int64_t twice = tsd_node(&f, "Macro", "TWICE", "inc/h.h", 2, 2);
+ int64_t a = tsd_node(&f, "Function", "a", "src/a.c", 2, 2);
+ int64_t c = tsd_node(&f, "Function", "c", "src/c.c", 2, 2);
+ int64_t far = tsd_node(&f, "Function", "far", "src/far.c", 1, 1);
+ static const char *const added[] = {"#define LIMIT 8"};
+ static const char *const removed[] = {"#define LIMIT 4"};
+ cbm_diff_hunk_t edit = {.start = 1,
+ .count = 1,
+ .added = added,
+ .added_count = 1,
+ .removed = removed,
+ .removed_count = 1};
+ cbm_ti_change_t change = {.path = "inc/h.h", .hunks = &edit, .hunk_count = 1};
+ cbm_ti_seeds_t *s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ ASSERT_TRUE(tsd_seeded(s, limit));
+ ASSERT_TRUE(tsd_seeded(s, twice)); /* the macro whose body names LIMIT */
+ ASSERT_TRUE(tsd_seeded(s, a)); /* includes h.h, mentions LIMIT */
+ ASSERT_TRUE(tsd_seeded(s, c)); /* includes h.h, mentions TWICE */
+ ASSERT_FALSE(tsd_seeded(s, far)); /* mentions LIMIT, never includes h.h */
+ int count = 0;
+ (void)cbm_ti_seeds_file_level_headers(s, &count);
+ ASSERT_EQ(count, 0);
+ cbm_ti_seeds_free(s);
+ tsd_close(&f);
+ PASS();
+}
+
+/* A preprocessor conditional, or a line the patterns cannot classify outside
+ * any definition, makes the header file level: no seeds, an escalation. */
+TEST(test_impact_seed_unclassified_header_lines_escalate_the_file) {
+ const char *files[] = {"inc/h.h", "#define LIMIT 4\n\n"};
+ tsd_fixture_t f;
+ ASSERT_TRUE(tsd_open(&f, files, 2));
+ (void)tsd_node(&f, "Macro", "LIMIT", "inc/h.h", 1, 1);
+ static const char *const conditional[] = {"#ifdef FEATURE"};
+ static const char *const odd[] = {" LIMIT_PLUS_ONE,"};
+ cbm_diff_hunk_t cases[] = {
+ {.start = 2, .count = 1, .added = conditional, .added_count = 1},
+ {.start = 2, .count = 1, .added = odd, .added_count = 1},
+ };
+ for (int i = 0; i < 2; i++) {
+ cbm_ti_change_t change = {.path = "inc/h.h", .hunks = &cases[i], .hunk_count = 1};
+ cbm_ti_seeds_t *s = tsd_seed(&f, &change, 1);
+ ASSERT_NOT_NULL(s);
+ int count = 0;
+ const char *const *headers = cbm_ti_seeds_file_level_headers(s, &count);
+ ASSERT_EQ(count, 1);
+ ASSERT_STR_EQ(headers[0], "inc/h.h");
+ ASSERT_EQ(tsd_seed_count(s), 0);
+ cbm_ti_seeds_free(s);
+ }
+ tsd_close(&f);
+ PASS();
+}
+
+SUITE(test_impact_seed) {
+ RUN_TEST(test_impact_seed_hunks_follow_the_reference);
+ RUN_TEST(test_impact_seed_changed_cases_and_suites_are_reported);
+ RUN_TEST(test_impact_seed_deleted_names_are_found_by_text);
+ RUN_TEST(test_impact_seed_header_names_propagate_through_includes_and_macros);
+ RUN_TEST(test_impact_seed_unclassified_header_lines_escalate_the_file);
+}
diff --git a/tests/test_test_impact_source.c b/tests/test_test_impact_source.c
new file mode 100644
index 000000000..e76cd0d38
--- /dev/null
+++ b/tests/test_test_impact_source.c
@@ -0,0 +1,325 @@
+/*
+ * test_test_impact_source.c — text facts about a snapshot's C-family sources
+ * (src/mcp/test_impact_source.c).
+ *
+ * The line patterns are a hand port of the regular expressions of the
+ * measured reference (replay4.py). The expected values in the table below are
+ * what those expressions return for each line (computed with Python's `re`),
+ * quirks included: a port that disagrees seeds differently from what was
+ * measured.
+ */
+#include "test_framework.h"
+
+#include "mcp/test_impact_source.h"
+
+#include <stdbool.h>
+#include <string.h>
+
+typedef struct {
+ const char *line;
+ bool comment;
+ bool pp;
+ const char *define_name;
+ const char *typedef_name;
+ const char *tag_name;
+ const char *extern_name;
+ const char *proto_name;
+ const char *include_path;
+} tis_line_t;
+
+static const tis_line_t tis_lines[] = {
+ {"", true, false, "", "", "", "", "", ""},
+ {" ", true, false, "", "", "", "", "", ""},
+ {"// x", true, false, "", "", "", "", "", ""},
+ {" /* x", true, false, "", "", "", "", "", ""},
+ {" * x", true, false, "", "", "", "", "", ""},
+ {"int x; /* c */", true, false, "", "", "", "", "", ""},
+ {"int x;", false, false, "", "", "", "", "", ""},
+ {"x */ ", true, false, "", "", "", "", "", ""},
+ {"*/", true, false, "", "", "", "", "", ""},
+ {"a*/b", false, false, "", "", "", "", "", ""},
+ {"\t\r", true, false, "", "", "", "", "", ""},
+ {"#if X", false, true, "", "", "", "", "", ""},
+ {"#ifdef X", false, true, "", "", "", "", "", ""},
+ {" # ifndef X", false, true, "", "", "", "", "", ""},
+ {"#elif", false, true, "", "", "", "", "", ""},
+ {"#else", false, true, "", "", "", "", "", ""},
+ {"#endif", false, true, "", "", "", "", "", ""},
+ {"#undef X", false, true, "", "", "", "", "", ""},
+ {"#include <x>", false, true, "", "", "", "", "", ""},
+ {"#include\"x\"", false, true, "", "", "", "", "", ""},
+ {"#define X", false, false, "X", "", "", "", "", ""},
+ {"#iffy", false, false, "", "", "", "", "", ""},
+ {"#if(x)", false, true, "", "", "", "", "", ""},
+ {"#pragma once", false, false, "", "", "", "", "", ""},
+ {"#includes", false, false, "", "", "", "", "", ""},
+ {"#define X 1", false, false, "X", "", "", "", "", ""},
+ {" # define F(a, b) a##b", false, false, "F", "", "", "", "", ""},
+ {"#define", false, false, "", "", "", "", "", ""},
+ {"#definex", false, false, "", "", "", "", "", ""},
+ {"#define(X)", false, false, "", "", "", "", "", ""},
+ {"#define 1X", false, false, "", "", "", "", "", ""},
+ {"#define\tX", false, false, "X", "", "", "", "", ""},
+ {"#define F(x) f(x)", false, false, "F", "", "", "", "", ""},
+ {"typedef int myint;", false, false, "", "myint", "", "", "", ""},
+ {"typedef struct foo bar;", false, false, "", "bar", "", "", "", ""},
+ {"typedef int arr[3][4];", false, false, "", "", "", "", "", ""},
+ {"typedef int arr[3];", false, false, "", "arr", "", "", "", ""},
+ {"typedef void (*fn)(int);", false, false, "", "", "", "", "void", ""},
+ {"x typedef y;", false, false, "", "y", "", "", "", ""},
+ {"typedefs x;", false, false, "", "", "", "", "", ""},
+ {"typedef int a, b;", false, false, "", "b", "", "", "", ""},
+ {"int typedef_x;", false, false, "", "", "", "", "", ""},
+ {"typedef int x ;", false, false, "", "x", "", "", "", ""},
+ {"typedef struct { int a; } s_t;", false, false, "", "a", "", "", "", ""},
+ {"typedef unsigned long ulong_t [ 8 ] ;", false, false, "", "ulong_t", "", "", "", ""},
+ {"struct foo {", false, false, "", "", "foo", "", "", ""},
+ {"typedef struct foo {", false, false, "", "", "foo", "", "", ""},
+ {" union u{", false, false, "", "", "u", "", "", ""},
+ {"enum e {", false, false, "", "", "e", "", "", ""},
+ {"struct foo;", false, false, "", "", "", "", "", ""},
+ {"structfoo {", false, false, "", "", "", "", "", ""},
+ {"struct {", false, false, "", "", "", "", "", ""},
+ {"typedef enum color {", false, false, "", "", "color", "", "", ""},
+ {"extern int x;", false, false, "", "", "", "x", "", ""},
+ {"extern const char *names[];", false, false, "", "", "", "names", "", ""},
+ {"extern int f(void);", false, false, "", "", "", "", "f", ""},
+ {"extern int a, b;", false, false, "", "", "", "b", "", ""},
+ {" extern T x [N] ;", false, false, "", "", "", "x", "", ""},
+ {"externs int x;", false, false, "", "", "", "", "", ""},
+ {"extern \"C\" {", false, false, "", "", "", "", "", ""},
+ {"int foo(void)", false, false, "", "", "", "", "foo", ""},
+ {"foo(x)", false, false, "", "", "", "", "", ""},
+ {"static void foo (int a)", false, false, "", "", "", "", "foo", ""},
+ {" int foo(void)", false, false, "", "", "", "", "", ""},
+ {"int *bar(void)", false, false, "", "", "", "", "bar", ""},
+ {"a.b(c)", false, false, "", "", "", "", "", ""},
+ {"int foo\t(x)", false, false, "", "", "", "", "foo", ""},
+ {"return foo(x);", false, false, "", "", "", "", "foo", ""},
+ {"static inline T *g (void) {", false, false, "", "", "", "", "g", ""},
+ {"#include \"a/b.h\"", false, true, "", "", "", "", "", "a/b.h"},
+ {" # include \"x.h\"", false, true, "", "", "", "", "", "x.h"},
+ {"#include <x.h>", false, true, "", "", "", "", "", ""},
+ {"#include\"\"", false, true, "", "", "", "", "", ""},
+ {"#include \"../up/y.h\" // c", false, true, "", "", "", "", "", "../up/y.h"},
+};
+
+static bool tis_same(const char *line, bool matched, cbm_ti_span_t span, const char *expected) {
+ if (!*expected) {
+ return !matched;
+ }
+ return matched && span.len == strlen(expected) &&
+ memcmp(line + span.start, expected, span.len) == 0;
+}
+
+/* Every pattern gives on every line what the reference expression gives. */
+TEST(test_impact_source_line_patterns_match_the_reference) {
+ for (size_t i = 0; i < sizeof(tis_lines) / sizeof(tis_lines[0]); i++) {
+ const tis_line_t *c = &tis_lines[i];
+ const char *s = c->line;
+ size_t n = strlen(s);
+ cbm_ti_span_t span = {0};
+ size_t body = 0;
+ bool ok = cbm_ti_line_is_comment(s, n) == c->comment &&
+ cbm_ti_line_is_pp_condition(s, n) == c->pp &&
+ tis_same(s, cbm_ti_match_define(s, n, &span, &body), span, c->define_name) &&
+ tis_same(s, cbm_ti_match_typedef(s, n, &span), span, c->typedef_name) &&
+ tis_same(s, cbm_ti_match_tag_declaration(s, n, &span), span, c->tag_name) &&
+ tis_same(s, cbm_ti_match_extern(s, n, &span), span, c->extern_name) &&
+ tis_same(s, cbm_ti_match_prototype(s, n, &span), span, c->proto_name) &&
+ tis_same(s, cbm_ti_match_include(s, n, &span), span, c->include_path);
+ if (!ok) {
+ printf(" line %zu: \"%s\"\n", i, s);
+ }
+ ASSERT_TRUE(ok);
+ }
+ PASS();
+}
+
+/* The declaration of a changed header line tries define, typedef, tag,
+ * extern, prototype in that order. */
+TEST(test_impact_source_declaration_tries_the_patterns_in_order) {
+ static const struct {
+ const char *line;
+ const char *name;
+ } cases[] = {{"#define F(x) f(x)", "F"},
+ {"typedef void (*fn)(int);", "void"},
+ {"extern int f(void);", "f"},
+ {"typedef struct foo {", "foo"},
+ {"int x;", ""}};
+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
+ cbm_ti_span_t span = {0};
+ const char *s = cases[i].line;
+ ASSERT_TRUE(
+ tis_same(s, cbm_ti_match_declaration(s, strlen(s), &span), span, cases[i].name));
+ }
+ PASS();
+}
+
+static cbm_ti_source_t *tis_build(const char *const *files, int count) {
+ cbm_ti_source_t *s = cbm_ti_source_new();
+ if (!s) {
+ return NULL;
+ }
+ for (int i = 0; i < count; i += 2) {
+ if (!cbm_ti_source_add(s, files[i], files[i + 1], strlen(files[i + 1]))) {
+ cbm_ti_source_free(s);
+ return NULL;
+ }
+ }
+ if (!cbm_ti_source_finish(s)) {
+ cbm_ti_source_free(s);
+ return NULL;
+ }
+ return s;
+}
+
+static bool tis_has(const char *const *list, int count, const char *word) {
+ for (int i = 0; i < count; i++) {
+ if (strcmp(list[i], word) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* A header's macros carry the identifiers of their body (keywords and the
+ * macro's own name removed, continuation lines included) and the operands of
+ * `##`, as the reference collects them. */
+TEST(test_impact_source_macros_carry_body_names_and_pastes) {
+ const char *files[] = {"inc/m.h",
+ "#define CASE(tag_) \\\n"
+ " static int CASE_##tag_ = helper(x2y, 0x1F); \\\n"
+ " int tag_ ## _end;\n"
+ "#define PLAIN return NULL\n",
+ "src/a.c", "#define NOT_A_HEADER helper\n"};
+ cbm_ti_source_t *s = tis_build(files, 4);
+ ASSERT_NOT_NULL(s);
+ int count = 0;
+ const cbm_ti_macro_t *macros = cbm_ti_source_macros(s, &count);
+ ASSERT_EQ(count, 2);
+ ASSERT_STR_EQ(macros[0].name, "CASE");
+ /* `tag_` is the parameter: the reference keeps it, as it keeps `x1F` */
+ const char *want[] = {"CASE_", "_end", "helper", "tag_", "x1F", "x2y"};
+ ASSERT_EQ(macros[0].token_count, 6);
+ for (int i = 0; i < 6; i++) {
+ ASSERT_STR_EQ(macros[0].tokens[i], want[i]);
+ }
+ ASSERT_EQ(macros[0].paste_prefix_count, 2);
+ ASSERT_TRUE(tis_has(macros[0].paste_prefixes, 2, "CASE_"));
+ ASSERT_TRUE(tis_has(macros[0].paste_prefixes, 2, "tag_"));
+ ASSERT_EQ(macros[0].paste_suffix_count, 0);
+ ASSERT_STR_EQ(macros[1].name, "PLAIN");
+ ASSERT_EQ(macros[1].token_count, 0);
+ cbm_ti_source_free(s);
+ PASS();
+}
+
+/* `x ## y ## z`: the reference reads x and y as prefixes and never z (the
+ * second `##` was taken by y); `## q` alone is a suffix. */
+TEST(test_impact_source_paste_scan_follows_the_reference) {
+ const char *files[] = {"p.h", "#define A x ## y ## z\n#define B ## q\n"};
+ cbm_ti_source_t *s = tis_build(files, 2);
+ ASSERT_NOT_NULL(s);
+ int count = 0;
+ const cbm_ti_macro_t *macros = cbm_ti_source_macros(s, &count);
+ ASSERT_EQ(count, 2);
+ ASSERT_EQ(macros[0].paste_prefix_count, 2);
+ ASSERT_TRUE(tis_has(macros[0].paste_prefixes, 2, "x"));
+ ASSERT_TRUE(tis_has(macros[0].paste_prefixes, 2, "y"));
+ ASSERT_EQ(macros[0].paste_suffix_count, 0);
+ ASSERT_EQ(macros[1].paste_prefix_count, 0);
+ ASSERT_EQ(macros[1].paste_suffix_count, 1);
+ ASSERT_STR_EQ(macros[1].paste_suffixes[0], "q");
+ cbm_ti_source_free(s);
+ PASS();
+}
+
+/* An include names the file it resolves to from the including directory
+ * when that file exists, otherwise every file whose path ends with it
+ * (leading `.` and `/` removed). The closure follows includers transitively. */
+TEST(test_impact_source_include_closure_follows_the_reference) {
+ const char *files[] = {"src/core/x.h", "int x;\n",
+ "src/core/y.h", "#include \"x.h\"\n",
+ "src/app/main.c", "#include \"core/y.h\"\n",
+ "src/app/other.c", "#include \"../core/x.h\"\n",
+ "lib/x.h", "int other_x;\n",
+ "tests/t.c", "#include \"../../x.h\"\n",
+ "tests/u.c", "#include <x.h>\n"};
+ cbm_ti_source_t *s = tis_build(files, 14);
+ ASSERT_NOT_NULL(s);
+ int n = cbm_ti_source_file_count(s);
+ ASSERT_EQ(n, 7);
+ bool marked[7] = {false};
+ marked[cbm_ti_source_find(s, "src/core/x.h")] = true;
+ cbm_ti_source_include_closure(s, marked);
+ /* y.h resolves x.h beside it; main.c reaches y.h through the suffix
+ * "core/y.h"; other.c through ../core/x.h; t.c's "../../x.h" does not
+ * exist relative to tests/, so its key "x.h" names BOTH x.h files. */
+ ASSERT_TRUE(marked[cbm_ti_source_find(s, "src/core/y.h")]);
+ ASSERT_TRUE(marked[cbm_ti_source_find(s, "src/app/main.c")]);
+ ASSERT_TRUE(marked[cbm_ti_source_find(s, "src/app/other.c")]);
+ ASSERT_TRUE(marked[cbm_ti_source_find(s, "tests/t.c")]);
+ ASSERT_FALSE(marked[cbm_ti_source_find(s, "lib/x.h")]);
+ ASSERT_FALSE(marked[cbm_ti_source_find(s, "tests/u.c")]);
+ cbm_ti_source_free(s);
+ PASS();
+}
+
+/* One place per line; comment-led lines and keywords hold none; identifiers
+ * in strings and trailing comments count (an over-approximation that only
+ * adds seeds); `0x1F` holds `x1F` as the reference's token pattern reads it. */
+TEST(test_impact_source_occurrences_follow_the_reference) {
+ const char *files[] = {"b.c",
+ "int f(void) { return f2(f); }\n"
+ "// f in a comment line\n"
+ " * f in a block comment line\n"
+ "const char *s = \"f\"; /* f */\n"
+ "int y = 0x1F;\n",
+ "a.c", "void g(void) { f(); }\n"};
+ cbm_ti_source_t *s = tis_build(files, 4);
+ ASSERT_NOT_NULL(s);
+ ASSERT_TRUE(cbm_ti_source_build_occurrences(s));
+ int count = 0;
+ const cbm_ti_place_t *places = cbm_ti_source_occurrences(s, "f", 1, &count);
+ ASSERT_EQ(count, 3);
+ ASSERT_STR_EQ(cbm_ti_source_path(s, places[0].file), "a.c");
+ ASSERT_EQ(places[0].line, 1);
+ ASSERT_STR_EQ(cbm_ti_source_path(s, places[1].file), "b.c");
+ ASSERT_EQ(places[1].line, 1);
+ ASSERT_EQ(places[2].line, 4);
+ (void)cbm_ti_source_occurrences(s, "x1F", 3, &count);
+ ASSERT_EQ(count, 1);
+ (void)cbm_ti_source_occurrences(s, "int", 3, &count);
+ ASSERT_EQ(count, 0);
+ cbm_ti_source_free(s);
+ PASS();
+}
+
+/* Lines split as `text.split('\n')`: a final newline leaves an empty line. */
+TEST(test_impact_source_lines_split_like_the_reference) {
+ const char *files[] = {"x.c", "a\r\nb\n"};
+ cbm_ti_source_t *s = tis_build(files, 2);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(cbm_ti_source_line_count(s, 0), 3);
+ size_t len = 0;
+ const char *line = cbm_ti_source_line(s, 0, 1, &len);
+ ASSERT_EQ(len, 2);
+ ASSERT_TRUE(memcmp(line, "a\r", 2) == 0);
+ (void)cbm_ti_source_line(s, 0, 3, &len);
+ ASSERT_EQ(len, 0);
+ ASSERT_NULL(cbm_ti_source_line(s, 0, 4, &len));
+ ASSERT_FALSE(cbm_ti_source_add(s, "late.c", "", 0));
+ cbm_ti_source_free(s);
+ PASS();
+}
+
+SUITE(test_impact_source) {
+ RUN_TEST(test_impact_source_line_patterns_match_the_reference);
+ RUN_TEST(test_impact_source_declaration_tries_the_patterns_in_order);
+ RUN_TEST(test_impact_source_macros_carry_body_names_and_pastes);
+ RUN_TEST(test_impact_source_paste_scan_follows_the_reference);
+ RUN_TEST(test_impact_source_include_closure_follows_the_reference);
+ RUN_TEST(test_impact_source_occurrences_follow_the_reference);
+ RUN_TEST(test_impact_source_lines_split_like_the_reference);
+}
diff --git a/tests/test_test_impact_tree.c b/tests/test_test_impact_tree.c
index 15765cf46..2a77026b6 100644
--- a/tests/test_test_impact_tree.c
+++ b/tests/test_test_impact_tree.c
@@ -1135,15 +1135,23 @@ TEST(tree_c_complete_inventory_and_native_names) {
PT_CHECK(cbm_pinned_tree_create(&options, &fx.tree, &error) == CBM_PINNED_TREE_OK);
PT_CHECK(pt_close_one(&fx.tree));
pt_row rows[2] = {fx.rows[0], fx.rows[0]};
- rows[0].path = "good";
- rows[1].path = "unsupported";
+ /* A symlink or a submodule link is left out and counted, as discovery
+ * never indexes a symlink; the regular file beside it is pinned. The link
+ * sorts first (rows are in git's order), so the pinned file is not at its
+ * position in git's own list. */
+ rows[0].path = "a-link";
+ rows[1].path = "good";
const uint32_t modes[] = {0120000, 0160000};
for (size_t i = 0; i < 2; i++) {
- rows[1].mode = modes[i];
- strcpy(rows[1].oid, i == 0 ? fx.rows[0].oid : fx.a);
+ rows[0].mode = modes[i];
+ strcpy(rows[0].oid, i == 0 ? fx.rows[0].oid : fx.a);
PT_CHECK(pt_replace_tree(&fx, rows, 2));
options = pt_options(&fx, CBM_GIT_REV_HEAD);
- PT_CHECK(pt_clean_failure(&fx, &options, CBM_PINNED_TREE_UNSUPPORTED));
+ PT_CHECK(cbm_pinned_tree_create(&options, &fx.tree, &error) == CBM_PINNED_TREE_OK);
+ const cbm_pinned_tree_view_t *linked = cbm_pinned_tree_view(fx.tree);
+ PT_CHECK(linked && linked->file_count == 1 && linked->skipped_link_count == 1 &&
+ strcmp((const char *)linked->files[0].path, "good") == 0);
+ PT_CHECK(pt_close_one(&fx.tree));
}
rows[1] = fx.rows[0];
#ifdef _WIN32
@@ -2533,7 +2541,6 @@ SUITE(test_impact_tree) {
RUN_TEST(tree_h_cleanup_owner_and_unrelated_resources);
}
-
/* Independent prefix-read acceptance: no publisher/admission claims. All
* mutations are synchronous and restricted to the fixture's owned namespace. */
static bool ptr_setup(pt_fixture *fx, unsigned width) {