mirror of
https://github.com/DeusData/codebase-memory-mcp.git
synced 2026-11-04 10:48:20 +00:00
Merge branch 'main' into fix/smoke-tool-inventory
This commit is contained in:
52 files changed
+4523
-252
No files matched your search
@@ -64,9 +64,29 @@ jobs:
|
||||
run: |
|
||||
# The full .diff endpoint rejects large-but-valid PRs at 20k lines.
|
||||
# The paginated files endpoint remains filename-only for this gate.
|
||||
FILES=$(gh api --paginate "repos/$REPO/pulls/$PR/files?per_page=100" --jq '.[].filename')
|
||||
if FILES=$(gh api --paginate "repos/$REPO/pulls/$PR/files?per_page=100" --jq '.[].filename'); then
|
||||
echo "file list: pulls/files API"
|
||||
else
|
||||
# The files endpoint renders the diff server-side too, and answers
|
||||
# 422 "this diff is taking too long to generate" for a PR that
|
||||
# regenerates a vendored parser (#2246: a 42 MB sql/parser.c) --
|
||||
# so does the compare endpoint. The PR merge ref's first parent is
|
||||
# the base, so a name-only diff across it is the same file list.
|
||||
# depth 2 + blob:none fetches commits and trees only (well under
|
||||
# 1 MB, under a second); nothing from the PR is checked out or run.
|
||||
echo "::notice::pulls/files API failed; file list taken from refs/pull/$PR/merge"
|
||||
CHANGES_GIT="$RUNNER_TEMP/changes.git"
|
||||
git init -q --bare "$CHANGES_GIT"
|
||||
git --git-dir="$CHANGES_GIT" fetch -q --depth=2 --filter=blob:none \
|
||||
"https://github.com/$REPO" "refs/pull/$PR/merge"
|
||||
FILES=$(git --git-dir="$CHANGES_GIT" diff --name-only --no-renames FETCH_HEAD^1 FETCH_HEAD)
|
||||
fi
|
||||
printf '%s\n' "$FILES"
|
||||
if printf '%s\n' "$FILES" | grep -qE '^(src/|internal/|install\.(sh|ps1)|scripts/build\.sh|scripts/smoke-test\.sh|scripts/smoke-local\.sh|scripts/smoke-fixture-server\.py|scripts/gen-third-party-notices\.sh|scripts/env\.sh|test-infrastructure/vm/(vm-smoke\.sh|windows-user-path-guard\.ps1)|Makefile\.cbm)'; then
|
||||
# A here-string, not a pipe: under this shell's pipefail, grep -q
|
||||
# exits on its first match, printf dies of SIGPIPE once the list
|
||||
# outgrows the pipe buffer, and the MATCH is then reported as a
|
||||
# failure -- product=false, smoke skipped, on the largest PRs.
|
||||
if grep -qE '^(src/|internal/|install\.(sh|ps1)|scripts/build\.sh|scripts/smoke-test\.sh|scripts/smoke-local\.sh|scripts/smoke-fixture-server\.py|scripts/gen-third-party-notices\.sh|scripts/env\.sh|test-infrastructure/vm/(vm-smoke\.sh|windows-user-path-guard\.ps1)|Makefile\.cbm)' <<<"$FILES"; then
|
||||
echo "product=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "product=false" >> "$GITHUB_OUTPUT"
|
||||
|
||||
+20
-1
@@ -55,7 +55,7 @@ src/
|
||||
foundation/ Arena allocator, hash table, string utils, platform compat
|
||||
store/ SQLite graph storage (WAL mode, FTS5)
|
||||
cypher/ Cypher query → SQL translation
|
||||
mcp/ MCP server (JSON-RPC 2.0 over stdio, 14 tools)
|
||||
mcp/ MCP server (JSON-RPC 2.0 over stdio, 17 tools)
|
||||
pipeline/ Multi-pass indexing pipeline
|
||||
pass_*.c Individual pipeline passes (definitions, calls, usages, etc.)
|
||||
httplink.c HTTP route extraction (Go/Express/Laravel/Ktor/Python)
|
||||
@@ -149,6 +149,25 @@ If in doubt, open an issue and ask.
|
||||
- Run `scripts/test.sh` and `scripts/lint.sh` before submitting
|
||||
- Keep PRs focused — avoid unrelated reformatting or refactoring
|
||||
|
||||
## AI-assisted and AI-authored contributions
|
||||
|
||||
Contributions written with the help of an AI tool, or written by an AI agent acting for a person, are welcome here on the same terms as any other. What we review is the change, not who or what typed it. Three things make that work:
|
||||
|
||||
- **Say so.** If an agent wrote the PR or is answering in the thread, disclose it — a line in the PR description or at the top of a comment is enough ("written with X", "this account is operated by an AI agent on behalf of Y"). Disclosure is never held against a contribution. Finding out later is.
|
||||
- **A person is accountable.** The [DCO sign-off](#license-and-sign-off-dco--required-on-every-commit) is a legal certification, and only a person can make it. The human behind the account certifies every commit, answers for it, and is who we talk to if something goes wrong. An agent may carry the conversation; it cannot carry the responsibility.
|
||||
- **The bar does not move.** Every claim in a PR must be something a reviewer can check: the failing test, the command that was run, the numbers and the machine they came from. "The model says it works" is not evidence, and a confident description does not replace a test that fails without the fix. We read AI-written PRs exactly as carefully as human-written ones — no more suspiciously, and no less.
|
||||
|
||||
Two practical notes:
|
||||
|
||||
- `Co-authored-by:` trailers naming a tool are fine. Links to private chat or agent sessions are not — they are dead to everyone else and do not belong in permanent history; we will ask you to remove them.
|
||||
- High-volume, low-effort submissions — many near-identical PRs, changes nobody ran, replies that do not engage with the review — will be closed, whoever or whatever produced them. One careful PR is worth more than twenty generated ones.
|
||||
|
||||
### Who speaks for the project
|
||||
|
||||
Only the maintainer account ([@DeusData](https://github.com/DeusData)) speaks for this project. A review, an approval, a "this will be merged" or a "this is a duplicate" from any other account is that person's opinion, however official it sounds — helpful reviews from the community are very welcome, and that is what they are.
|
||||
|
||||
**Impersonating a maintainer is not acceptable**, by a person or by an agent: presenting yourself as part of the maintainer team, posting approvals or change requests styled as maintainer decisions, or telling other contributors what the project has decided. We dismiss such reviews, hide the comments, say publicly in the affected threads that they were not ours, and report and block the account. If you are unsure whether a response you received is from the project, check the account name — and ask.
|
||||
|
||||
## Security
|
||||
|
||||
We take security seriously. All PRs go through:
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. Ships as a native executable with a small verified runtime-asset set for macOS, Linux, and Windows — download, run `install`, done.
|
||||
|
||||
High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across all 162 languages, enhanced with [**Hybrid LSP** semantic type resolution](#hybrid-lsp) for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 15 MCP tools. No language runtime, hosted service, or API key. Plug and play across 45 supported automatic/conditional client surfaces.
|
||||
High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across all 162 languages, enhanced with [**Hybrid LSP** semantic type resolution](#hybrid-lsp) for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 17 MCP tools. No language runtime, hosted service, or API key. Plug and play across 45 supported automatic/conditional client surfaces.
|
||||
|
||||
> **Research** — The design and benchmarks behind this project are described in the preprint [*Codebase-Memory: Tree-Sitter-Based Knowledge Graphs for LLM Code Exploration via MCP*](https://arxiv.org/abs/2603.27277) (arXiv:2603.27277). Evaluated across 31 real-world repositories: 83% answer quality, 10× fewer tokens, 2.1× fewer tool calls vs. file-by-file exploration.
|
||||
|
||||
@@ -37,7 +37,7 @@ High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-si
|
||||
- **45 supported automatic/conditional client surfaces** — `install` configures detected clients and safely activates conditional clients only when their documented platform, marker, or explicit existing config path is present. See [Multi-Agent Support](#multi-agent-support) for the complete matrix and manual/UI-only boundaries.
|
||||
- **Built-in graph visualization** — 3D interactive UI at `localhost:9749`, served from the binary itself.
|
||||
- **Infrastructure-as-code indexing** — Dockerfiles, Kubernetes manifests, and Kustomize overlays indexed as graph nodes with cross-references. `Resource` nodes for K8s kinds, `Module` nodes for Kustomize overlays with `IMPORTS` edges to referenced resources.
|
||||
- **15 MCP tools** — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
|
||||
- **17 MCP tools** — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -461,7 +461,7 @@ Add to `~/.claude.json` (user scope) or project `.mcp.json`:
|
||||
}
|
||||
```
|
||||
|
||||
Restart your agent. Verify with `/mcp` — you should see `codebase-memory-mcp` with 15 tools.
|
||||
Restart your agent. Verify with `/mcp` — you should see `codebase-memory-mcp` with 17 tools.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -673,6 +673,7 @@ JSON arguments can also be piped on stdin, for tools that take arguments. A tool
|
||||
| `list_projects` | List all indexed projects with node/edge counts. |
|
||||
| `delete_project` | Remove a project and all its graph data. |
|
||||
| `index_status` | Check indexing status of a project. |
|
||||
| `check_index_coverage` | Check whether exact paths or a scope are indexed and fresh. A clean result means no recorded gap, not proof of completeness. |
|
||||
|
||||
### Querying
|
||||
|
||||
@@ -683,7 +684,9 @@ JSON arguments can also be piped on stdin, for tools that take arguments. A tool
|
||||
| `detect_changes` | Map git diff to affected symbols + blast radius with risk classification. |
|
||||
| `query_graph` | Execute Cypher-like graph queries (read-only). |
|
||||
| `get_graph_schema` | Node/edge counts, relationship patterns, property definitions per label. Run this first. |
|
||||
| `compare_graphs` | Compare two indexed snapshots: node/edge additions and removals between a base and a target. |
|
||||
| `get_code_snippet` | Read source code for a function by qualified name. |
|
||||
| `get_file_outline` | Declaration outline of one repository-relative file in source order, with optional label filter and paging. |
|
||||
| `get_architecture` | Codebase overview: languages, packages, routes, hotspots, clusters, ADR. |
|
||||
| `search_code` | Grep-like text search within indexed project files. |
|
||||
| `manage_adr` | CRUD for Architecture Decision Records (`get` reads, `update` replaces the whole document, `set_sections` rewrites only the named sections and leaves every other byte untouched, `sections` lists headings). Query modes do not wait behind a same-project reindex; writes remain serialized. |
|
||||
@@ -849,7 +852,7 @@ Also supported (not yet benchmarked): Ada, Agda, Apex, Assembly (NASM), Astro, A
|
||||
src/
|
||||
main.c Entry point (MCP stdio server + CLI + install/update/config)
|
||||
daemon/ Per-account session coordination, IPC, lifecycle, shared jobs/watchers
|
||||
mcp/ MCP server (15 tools, JSON-RPC 2.0, session detection, auto-index)
|
||||
mcp/ MCP server (17 tools, JSON-RPC 2.0, session detection, auto-index)
|
||||
cli/ Install/uninstall/update/config (45 client surfaces, hooks, instructions)
|
||||
store/ SQLite graph storage (nodes, edges, traversal, search, Louvain)
|
||||
pipeline/ Multi-pass indexing (structure → definitions → calls → HTTP links → config → tests)
|
||||
|
||||
+3
-3
@@ -56,7 +56,7 @@
|
||||
"featureList": [
|
||||
"Indexes 158 programming languages via vendored tree-sitter grammars",
|
||||
"Hybrid LSP semantic type resolution for Python, TypeScript/JavaScript, PHP, C#, Go, C/C++, Java, Kotlin, and Rust",
|
||||
"15 MCP tools for structural search, call-path tracing, targeted coverage checks, and Cypher graph queries",
|
||||
"17 MCP tools for structural search, call-path tracing, targeted coverage checks, and Cypher graph queries",
|
||||
"Semantic vector code search via bundled nomic-embed-code embeddings (no API key, fully local)",
|
||||
"Semantic graph edges (SEMANTICALLY_RELATED) and near-clone detection (SIMILAR_TO, MinHash + LSH)",
|
||||
"Cross-service linking for HTTP, gRPC, GraphQL, tRPC, and pub/sub channels with confidence scoring",
|
||||
@@ -739,8 +739,8 @@
|
||||
<p>The optional UI variant adds one verified, content-addressed frontend pack and serves an interactive 3D graph at <code>localhost:9749</code> to explore nodes, edges, and clusters visually.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<h3>15 MCP tools</h3>
|
||||
<p><code>search_graph</code>, <code>trace_path</code>, <code>detect_changes</code>, <code>query_graph</code> (Cypher), <code>get_architecture</code>, <code>get_code_snippet</code>, <code>check_index_coverage</code>, <code>manage_adr</code>, and 7 more.</p>
|
||||
<h3>17 MCP tools</h3>
|
||||
<p><code>search_graph</code>, <code>trace_path</code>, <code>detect_changes</code>, <code>query_graph</code> (Cypher), <code>get_architecture</code>, <code>get_code_snippet</code>, <code>check_index_coverage</code>, <code>manage_adr</code>, and 9 more.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<h3>Cypher graph queries</h3>
|
||||
|
||||
+435
-36
@@ -125,7 +125,79 @@ void cbm_reset_profile(void) {
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* A definition name never spans lines. Config extractors hand over a node's
|
||||
* whole text — a YAML block key, a Makefile recipe (`endif\n\n$(obj)/x.h`), a
|
||||
* ktest .conf directive — and the line break rode into the graph (2026-09-16
|
||||
* probe: 8,301 Field nodes on elastic/elasticsearch, 91 kernel nodes). Cut at
|
||||
* the first line break and drop trailing blanks; the qualified name carries
|
||||
* the same text as its last segment and is cut the same way. */
|
||||
static const char *cbm_first_line(CBMArena *a, const char *text) {
|
||||
if (!text) {
|
||||
return text;
|
||||
}
|
||||
const char *nl = strpbrk(text, "\r\n");
|
||||
if (!nl) {
|
||||
return text;
|
||||
}
|
||||
size_t n = (size_t)(nl - text);
|
||||
while (n > 0 && (text[n - 1] == ' ' || text[n - 1] == '\t')) {
|
||||
n--;
|
||||
}
|
||||
char *cut = (char *)cbm_arena_alloc(a, n + 1);
|
||||
if (!cut) {
|
||||
return text;
|
||||
}
|
||||
memcpy(cut, text, n);
|
||||
cut[n] = '\0';
|
||||
return cut;
|
||||
}
|
||||
|
||||
/* JS/TS files: a definition named by a literal token is the walker naming a
|
||||
* function or variable from an object key or a numeric pattern element —
|
||||
* `{}` (1,534 incoming CALLS on microsoft/TypeScript's test baselines), `1`
|
||||
* (38 nodes), a quoted string. An identifier starts with a letter, `_`, `$`,
|
||||
* `#` (private members) or a non-ASCII byte; anything else is not a name. */
|
||||
static bool cbm_js_family_path(const char *path) {
|
||||
if (!path) {
|
||||
return false;
|
||||
}
|
||||
const char *dot = strrchr(path, '.');
|
||||
if (!dot) {
|
||||
return false;
|
||||
}
|
||||
static const char *const exts[] = {".js", ".mjs", ".cjs", ".jsx", ".ts",
|
||||
".mts", ".cts", ".tsx", ".ets", NULL};
|
||||
for (int i = 0; exts[i]; i++) {
|
||||
if (strcmp(dot, exts[i]) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool cbm_js_name_is_junk(const char *name) {
|
||||
if (!name || !name[0]) {
|
||||
return false; /* empty names are handled by the callers' own rules */
|
||||
}
|
||||
unsigned char c = (unsigned char)name[0];
|
||||
bool identifier_start = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' ||
|
||||
c == '$' || c == '#' || c >= 0x80;
|
||||
/* Member names JS spells without an identifier start are still names:
|
||||
* computed keys (`[Symbol.iterator]`), string-literal keys (`"my-key"`,
|
||||
* `'x'`) and escaped identifiers (`А`). Measured on the TypeScript
|
||||
* corpus: 1,531 `[…]` members, 97 quoted members, 154 escaped
|
||||
* identifiers — all real definitions. What remains ({…} patterns, numeric
|
||||
* literals, parenthesised types, `...rest`) is a token, not a name. */
|
||||
bool member_key_start = c == '[' || c == '"' || c == '\'' || c == '\\';
|
||||
return !identifier_start && !member_key_start;
|
||||
}
|
||||
|
||||
void cbm_defs_push(CBMDefArray *arr, CBMArena *a, CBMDefinition def) {
|
||||
def.name = cbm_first_line(a, def.name);
|
||||
def.qualified_name = cbm_first_line(a, def.qualified_name);
|
||||
if (cbm_js_family_path(def.file_path) && cbm_js_name_is_junk(def.name)) {
|
||||
return;
|
||||
}
|
||||
GROW_ARRAY(arr, a);
|
||||
arr->items[arr->count++] = def;
|
||||
}
|
||||
@@ -1358,14 +1430,89 @@ static void cbm_mark_pp_error_rows(TSNode n, uint8_t *rows, uint32_t row_count,
|
||||
/* Recovery subtraction (#963): tree-sitter error recovery plus the
|
||||
* ERROR-descending def walker often still extract constructs INSIDE a failed
|
||||
* region (verified: a function in an #ifdef-split ERROR region and even a
|
||||
* `def broken(:` both came back as defs). A region whose every line is
|
||||
* covered by definitions that START inside it is definitely recovered — its
|
||||
* constructs ARE in the graph — so flagging it would be a false miss.
|
||||
* Container defs (Module/Package) are ignored: a file-spanning Module node is
|
||||
* not evidence the region's constructs survived. Conservative: partially
|
||||
* covered regions stay flagged. */
|
||||
static bool cbm_region_is_recovered(uint32_t rs, uint32_t re, const CBMDefArray *defs) {
|
||||
enum { MAX_COVER_DEFS = 256 };
|
||||
* `def broken(:` both came back as defs). The lines a definition that STARTS
|
||||
* inside the region covers are therefore in the graph, and only the lines no
|
||||
* definition covers can honestly be called missed. Container defs
|
||||
* (Module/Package) are ignored: a file-spanning Module node is not evidence
|
||||
* the region's constructs survived.
|
||||
*
|
||||
* This used to be all-or-nothing — a region stayed flagged whole unless every
|
||||
* line was covered. On torvalds/linux (2026-09-16 probe) one ERROR node that
|
||||
* swallowed the second half of kernel/sched/core.c (lines 5522–11284) survived
|
||||
* because of the comment and macro lines between its 286 extracted functions,
|
||||
* and the coverage report told a reader 68 % of the scheduler was unindexed.
|
||||
* Now the uncovered gaps are reported instead, and a gap holding only blank,
|
||||
* comment or preprocessor lines is not a miss at all. */
|
||||
static uint32_t *cbm_line_offsets(const char *src, int src_len, uint32_t *out_lines) {
|
||||
uint32_t lines = 1;
|
||||
for (int i = 0; i < src_len; i++) {
|
||||
if (src[i] == '\n') {
|
||||
lines++;
|
||||
}
|
||||
}
|
||||
uint32_t *offs =
|
||||
(uint32_t *)cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)(lines + 1) * sizeof(uint32_t));
|
||||
if (!offs) {
|
||||
*out_lines = 0;
|
||||
return NULL;
|
||||
}
|
||||
uint32_t n = 0;
|
||||
offs[n++] = 0;
|
||||
for (int i = 0; i < src_len && n < lines; i++) {
|
||||
if (src[i] == '\n') {
|
||||
offs[n++] = (uint32_t)i + 1;
|
||||
}
|
||||
}
|
||||
offs[n] = (uint32_t)src_len;
|
||||
*out_lines = n;
|
||||
return offs;
|
||||
}
|
||||
|
||||
/* A 1-based line that holds nothing a reader would call missed code: blank,
|
||||
* a comment line, or a preprocessor directive (the import pass owns #include;
|
||||
* #if/#endif carry no construct of their own). */
|
||||
static bool cbm_line_is_inert(const char *src, const uint32_t *offs, uint32_t nlines,
|
||||
uint32_t line) {
|
||||
if (!src || !offs || line == 0 || line > nlines) {
|
||||
return true;
|
||||
}
|
||||
const char *p = src + offs[line - 1];
|
||||
const char *end = src + offs[line];
|
||||
while (p < end && (*p == ' ' || *p == '\t' || *p == '\r')) {
|
||||
p++;
|
||||
}
|
||||
if (p >= end || *p == '\n') {
|
||||
return true;
|
||||
}
|
||||
if (p[0] == '/' && p + 1 < end && (p[1] == '/' || p[1] == '*')) {
|
||||
return true;
|
||||
}
|
||||
return p[0] == '*' || p[0] == '#';
|
||||
}
|
||||
|
||||
static void cbm_regions_emit_gap(cbm_error_regions_t *out, uint32_t gs, uint32_t ge,
|
||||
const char *src, const uint32_t *offs, uint32_t nlines) {
|
||||
bool live = false;
|
||||
for (uint32_t l = gs; l <= ge && !live; l++) {
|
||||
live = !cbm_line_is_inert(src, offs, nlines, l);
|
||||
}
|
||||
if (!live) {
|
||||
return;
|
||||
}
|
||||
if (out->count < CBM_MAX_ERROR_REGIONS) {
|
||||
out->starts[out->count] = gs;
|
||||
out->ends[out->count] = ge;
|
||||
out->count++;
|
||||
} else {
|
||||
out->dropped++;
|
||||
}
|
||||
}
|
||||
|
||||
/* Replace [rs, re] by the sub-ranges no in-region definition covers. */
|
||||
static void cbm_region_uncovered_gaps(uint32_t rs, uint32_t re, const CBMDefArray *defs,
|
||||
const char *src, const uint32_t *offs, uint32_t nlines,
|
||||
cbm_error_regions_t *out) {
|
||||
enum { MAX_COVER_DEFS = 1024 };
|
||||
uint32_t starts[MAX_COVER_DEFS];
|
||||
uint32_t ends[MAX_COVER_DEFS];
|
||||
int n = 0;
|
||||
@@ -1377,14 +1524,25 @@ static bool cbm_region_is_recovered(uint32_t rs, uint32_t re, const CBMDefArray
|
||||
if (d->start_line < rs || d->start_line > re) {
|
||||
continue; /* recovery evidence must originate inside the region */
|
||||
}
|
||||
/* A one-line definition salvaged from inside an error region is the
|
||||
* walker's guess at broken text (`def x(:` comes back as a def, a
|
||||
* mis-parsed `static _Thread_local int x` as a Variable named `int`,
|
||||
* and Python's synthetic builtins all sit on line 1); only a construct
|
||||
* whose body spans lines proves it was understood. Conservative: real
|
||||
* one-line variables and macros inside a failed region keep their line
|
||||
* flagged. */
|
||||
if (d->end_line <= d->start_line) {
|
||||
continue;
|
||||
}
|
||||
starts[n] = d->start_line;
|
||||
ends[n] = d->end_line < d->start_line ? d->start_line : d->end_line;
|
||||
ends[n] = d->end_line;
|
||||
n++;
|
||||
}
|
||||
if (n == 0) {
|
||||
return false;
|
||||
cbm_regions_emit_gap(out, rs, re, src, offs, nlines);
|
||||
return;
|
||||
}
|
||||
/* Insertion-sort by start, then sweep for gaps in [rs, re]. */
|
||||
/* Insertion-sort by start, then sweep and emit the gaps in [rs, re]. */
|
||||
for (int i = 1; i < n; i++) {
|
||||
uint32_t s = starts[i];
|
||||
uint32_t e = ends[i];
|
||||
@@ -1397,16 +1555,18 @@ static bool cbm_region_is_recovered(uint32_t rs, uint32_t re, const CBMDefArray
|
||||
starts[j + 1] = s;
|
||||
ends[j + 1] = e;
|
||||
}
|
||||
uint32_t covered_to = rs - 1;
|
||||
uint32_t cursor = rs;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (starts[i] > covered_to + 1) {
|
||||
return false; /* uncovered gap */
|
||||
if (starts[i] > cursor) {
|
||||
cbm_regions_emit_gap(out, cursor, starts[i] - 1, src, offs, nlines);
|
||||
}
|
||||
if (ends[i] > covered_to) {
|
||||
covered_to = ends[i];
|
||||
if (ends[i] + 1 > cursor) {
|
||||
cursor = ends[i] + 1;
|
||||
}
|
||||
}
|
||||
return covered_to >= re;
|
||||
if (cursor <= re) {
|
||||
cbm_regions_emit_gap(out, cursor, re, src, offs, nlines);
|
||||
}
|
||||
}
|
||||
|
||||
/* #961: true when 1-based `line` of `src` contains `name` (used to verify a
|
||||
@@ -1514,6 +1674,63 @@ static bool cbm_span_contains_callable_def(const char *src, int src_len, uint32_
|
||||
return false;
|
||||
}
|
||||
|
||||
/* #1989: type-def counterpart of cbm_span_contains_callable_def. A rescued
|
||||
* class/struct/enum definition has its name followed by a base clause (':') or
|
||||
* a body ('{'), not a parameter list, so the callable validator would reject
|
||||
* every type def pulled from the expanded tree. */
|
||||
static bool cbm_span_contains_type_def(const char *src, int src_len, uint32_t start_line,
|
||||
uint32_t end_line, const char *name) {
|
||||
if (!src || src_len <= 0 || !name || !name[0] || start_line == 0 || end_line < start_line) {
|
||||
return false;
|
||||
}
|
||||
int span_start = 0;
|
||||
uint32_t line = 1;
|
||||
while (span_start < src_len && line < start_line) {
|
||||
if (src[span_start++] == '\n') {
|
||||
line++;
|
||||
}
|
||||
}
|
||||
if (line != start_line) {
|
||||
return false;
|
||||
}
|
||||
int span_end = span_start;
|
||||
while (span_end < src_len && line <= end_line) {
|
||||
if (src[span_end++] == '\n') {
|
||||
line++;
|
||||
}
|
||||
}
|
||||
size_t name_len = strlen(name);
|
||||
for (int pos = span_start; pos + (int)name_len <= span_end; pos++) {
|
||||
if (strncmp(src + pos, name, name_len) != 0 ||
|
||||
(pos > 0 && cbm_identifier_char(src[pos - 1])) ||
|
||||
(pos + (int)name_len < src_len && cbm_identifier_char(src[pos + name_len]))) {
|
||||
continue;
|
||||
}
|
||||
int open = pos + (int)name_len;
|
||||
while (open < span_end && isspace((unsigned char)src[open])) {
|
||||
open++;
|
||||
}
|
||||
// Base clause (": public B"), body ("{"), or template args ("<...").
|
||||
if (open < span_end && (src[open] == ':' || src[open] == '{' || src[open] == '<')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* #1989: label buckets for the misparse-correction gates. A raw def extracted
|
||||
* from a broken `class MOD_API Foo` shape lands under a callable label while
|
||||
* the expanded tree yields a proper type label for the same name. */
|
||||
static bool cbm_def_label_is_type(const char *label) {
|
||||
return label != NULL && (strcmp(label, "Class") == 0 || strcmp(label, "Enum") == 0 ||
|
||||
strcmp(label, "Interface") == 0 || strcmp(label, "Type") == 0 ||
|
||||
strcmp(label, "Struct") == 0 || strcmp(label, "Union") == 0);
|
||||
}
|
||||
|
||||
static bool cbm_def_label_is_callable(const char *label) {
|
||||
return label != NULL && (strcmp(label, "Function") == 0 || strcmp(label, "Method") == 0);
|
||||
}
|
||||
|
||||
/* Remap an expanded-source definition back to the original input file. Every
|
||||
* line in the definition must be attributable to the main file; generated
|
||||
* macro bodies, included headers, and ambiguous spans fail closed. */
|
||||
@@ -1541,16 +1758,19 @@ static bool cbm_remap_preprocessed_def(CBMDefinition *def, const CBMPreprocessed
|
||||
return true;
|
||||
}
|
||||
|
||||
static void cbm_subtract_recovered_regions(cbm_error_regions_t *regs, const CBMDefArray *defs) {
|
||||
int kept = 0;
|
||||
for (int i = 0; i < regs->count; i++) {
|
||||
if (!cbm_region_is_recovered(regs->starts[i], regs->ends[i], defs)) {
|
||||
regs->starts[kept] = regs->starts[i];
|
||||
regs->ends[kept] = regs->ends[i];
|
||||
kept++;
|
||||
}
|
||||
static void cbm_subtract_recovered_regions(cbm_error_regions_t *regs, const CBMDefArray *defs,
|
||||
const char *src, int src_len) {
|
||||
if (regs->count <= 0) {
|
||||
return;
|
||||
}
|
||||
regs->count = kept;
|
||||
uint32_t nlines = 0;
|
||||
uint32_t *offs = cbm_line_offsets(src, src_len, &nlines);
|
||||
cbm_error_regions_t out = {{0}, {0}, 0, regs->dropped};
|
||||
for (int i = 0; i < regs->count; i++) {
|
||||
cbm_region_uncovered_gaps(regs->starts[i], regs->ends[i], defs, src, offs, nlines, &out);
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, offs);
|
||||
*regs = out;
|
||||
}
|
||||
|
||||
/* #1071: a function-like macro invocation whose argument is a type token
|
||||
@@ -1962,6 +2182,9 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
|
||||
|
||||
TSTree *tree = ts_parser_parse_with_options(parser, NULL, ts_input, opts);
|
||||
uint64_t t1 = now_ns();
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
t1 += tl_parse_wall_seam_offset_ns; /* the stall seam inflates every wall reading */
|
||||
#endif
|
||||
|
||||
if (!tree) {
|
||||
result->has_error = true;
|
||||
@@ -2133,6 +2356,14 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
|
||||
// Defs keep original-source line numbers; only CALLS are extracted from expanded source.
|
||||
if (language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA) {
|
||||
uint64_t pp_start = now_ns();
|
||||
/* #1989: collect build-system export-macro candidates from the raw
|
||||
* source. They are predefined empty in the expanded buffer (see
|
||||
* preprocessor.cpp) so `class MOD_API Foo` parses with its real name,
|
||||
* and the rescue loop below can adopt corrected type defs. Bounded:
|
||||
* at most CBM_EXPORT_MACRO_MAX names per file. */
|
||||
char export_cands[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int export_cand_count =
|
||||
cbm_export_macro_candidates(source, source_len, export_cands, CBM_EXPORT_MACRO_MAX);
|
||||
CBMPreprocessedSource *preprocessed = cbm_preprocess_with_map(
|
||||
source, source_len, rel_path, extra_defines, include_paths, language != CBM_LANG_C);
|
||||
if (preprocessed && preprocessed->source) {
|
||||
@@ -2213,17 +2444,52 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
|
||||
* recover defs from it — adopting ONLY those that
|
||||
* intersect a raw ERROR region, whose name is visible on
|
||||
* the raw source line, and whose QN the raw pass did not
|
||||
* already extract. */
|
||||
if (ts_node_has_error(root)) {
|
||||
* already extract.
|
||||
*
|
||||
* #1989: build-system export macros (<MOD>_API,
|
||||
* <lib>_EXPORT, ...) are empty on the real compile line but
|
||||
* opaque to tree-sitter, so `class MOD_API Foo` misparses
|
||||
* with the macro as the type name — often with NO raw ERROR
|
||||
* region at all (the class_specifier "succeeds" with the
|
||||
* wrong name; enums and free functions do error out). When
|
||||
* export-macro candidates were collected for this file, also
|
||||
* adopt expanded defs that replace a raw def literally named
|
||||
* as a candidate, or that correct a raw misparse label (the
|
||||
* raw pass extracted the same name as Function/Method from
|
||||
* the broken function_definition shape; the expanded tree
|
||||
* yields a proper type def). Superseded raw defs are
|
||||
* dropped so the corrected definition is not shadowed by
|
||||
* the qualified-name dedup. With no candidates the block
|
||||
* reduces to the original #961 behavior. */
|
||||
if (ts_node_has_error(root) || export_cand_count > 0) {
|
||||
cbm_error_regions_t raw_regs = {{0}, {0}, 0, 0};
|
||||
cbm_collect_error_regions(root, &raw_regs, source, source_len);
|
||||
if (raw_regs.count > 0) {
|
||||
if (raw_regs.count > 0 || export_cand_count > 0) {
|
||||
int defs_before = result->defs.count;
|
||||
cbm_extract_definitions(&pp_ctx);
|
||||
int w = defs_before;
|
||||
char *superseded = NULL;
|
||||
if (export_cand_count > 0 && defs_before > 0) {
|
||||
superseded =
|
||||
(char *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)defs_before);
|
||||
}
|
||||
/* #1989: spans of defs already adopted from the
|
||||
* expanded tree. A def nested inside one of these
|
||||
* (an inline method of a rescued class) was dropped
|
||||
* by the raw pass — the misparsed
|
||||
* `class MOD_API Foo {...}` parsed as a
|
||||
* function_definition, and nested defs in its body
|
||||
* are never walked. Bounded: one span per adopted
|
||||
* def, capped at 64. */
|
||||
struct {
|
||||
uint32_t start;
|
||||
uint32_t end;
|
||||
} rescued_spans[64];
|
||||
int rescued_count = 0;
|
||||
for (int i = defs_before; i < result->defs.count; i++) {
|
||||
CBMDefinition *d = &result->defs.items[i];
|
||||
bool adopt = false;
|
||||
int supersede_j = -1;
|
||||
if (cbm_remap_preprocessed_def(d, preprocessed)) {
|
||||
for (int rj = 0; rj < raw_regs.count && !adopt; rj++) {
|
||||
if (d->start_line <= raw_regs.ends[rj] &&
|
||||
@@ -2231,26 +2497,159 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
|
||||
adopt = true;
|
||||
}
|
||||
}
|
||||
if (!adopt && export_cand_count > 0 && d->name) {
|
||||
for (int ci = 0; ci < export_cand_count && !adopt; ci++) {
|
||||
for (int j = 0; j < defs_before && !adopt; j++) {
|
||||
CBMDefinition *r = &result->defs.items[j];
|
||||
if (!r->name ||
|
||||
strcmp(r->name, export_cands[ci]) != 0) {
|
||||
continue;
|
||||
}
|
||||
if (r->start_line <= d->end_line &&
|
||||
d->start_line <= r->end_line &&
|
||||
cbm_span_contains_type_def(
|
||||
source, source_len, d->start_line,
|
||||
d->end_line, d->name)) {
|
||||
adopt = true;
|
||||
supersede_j = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!adopt && d->label && cbm_def_label_is_type(d->label)) {
|
||||
for (int j = 0; j < defs_before && !adopt; j++) {
|
||||
CBMDefinition *r = &result->defs.items[j];
|
||||
/* Widened past callables (#1989): the
|
||||
* misparse also mints value-label raw
|
||||
* defs for types (`class X_API FEmpty {}`
|
||||
* -> Variable FEmpty). Same name,
|
||||
* overlapping span, raw label is NOT a
|
||||
* type => raw is the misparse artifact. */
|
||||
if (!r->name || !r->label || !d->name ||
|
||||
strcmp(r->name, d->name) != 0 ||
|
||||
cbm_def_label_is_type(r->label)) {
|
||||
continue;
|
||||
}
|
||||
if (r->start_line <= d->end_line &&
|
||||
d->start_line <= r->end_line) {
|
||||
adopt = true;
|
||||
supersede_j = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Nested rescue (#1989): a def nested inside
|
||||
* an already-adopted def's span — the inline
|
||||
* method of a rescued class, dropped by the
|
||||
* raw pass because the class parsed as a
|
||||
* function body. The same validation gates
|
||||
* (name-on-line, shape, QN dedup) still run
|
||||
* below before it lands. */
|
||||
if (!adopt && rescued_count > 0) {
|
||||
for (int k = 0; k < rescued_count && !adopt; k++) {
|
||||
if (d->start_line >= rescued_spans[k].start &&
|
||||
d->end_line <= rescued_spans[k].end) {
|
||||
adopt = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (adopt && (!d->name ||
|
||||
!cbm_line_contains(source, source_len, d->start_line,
|
||||
d->name) ||
|
||||
!cbm_span_contains_callable_def(
|
||||
source, source_len, d->start_line, d->end_line,
|
||||
d->name))) {
|
||||
if (adopt &&
|
||||
(!d->name ||
|
||||
!cbm_line_contains(source, source_len, d->start_line,
|
||||
d->name) ||
|
||||
(!cbm_span_contains_callable_def(source, source_len,
|
||||
d->start_line, d->end_line,
|
||||
d->name) &&
|
||||
!cbm_span_contains_type_def(source, source_len, d->start_line,
|
||||
d->end_line, d->name)))) {
|
||||
adopt = false;
|
||||
}
|
||||
for (int j = 0; j < defs_before && adopt; j++) {
|
||||
if (j == supersede_j || (superseded && superseded[j])) {
|
||||
continue; // being replaced by this very def
|
||||
}
|
||||
const char *q = result->defs.items[j].qualified_name;
|
||||
if (q && d->qualified_name &&
|
||||
strcmp(q, d->qualified_name) == 0) {
|
||||
/* #1989: a raw def holding the same QN is
|
||||
* usually a reject — unless it is the
|
||||
* misparse artifact this very def came to
|
||||
* replace (raw "Function FCalc" from the
|
||||
* broken `class MOD_API FCalc` shape vs the
|
||||
* rescued "Class FCalc"). Same name, same
|
||||
* span, raw label is not a type: supersede
|
||||
* instead of dropping the correction. */
|
||||
CBMDefinition *r = &result->defs.items[j];
|
||||
if (d->label && cbm_def_label_is_type(d->label) &&
|
||||
r->label && r->name && d->name &&
|
||||
strcmp(r->name, d->name) == 0 &&
|
||||
!cbm_def_label_is_type(r->label) &&
|
||||
r->start_line == d->start_line &&
|
||||
r->end_line == d->end_line && superseded) {
|
||||
superseded[j] = 1;
|
||||
continue;
|
||||
}
|
||||
adopt = false;
|
||||
}
|
||||
}
|
||||
if (adopt) {
|
||||
if (supersede_j >= 0 && supersede_j < defs_before &&
|
||||
superseded) {
|
||||
superseded[supersede_j] = 1;
|
||||
}
|
||||
/* Phantom-artifact suppression (#1989): on the
|
||||
* raw tree `class MOD_API Foo : public Base
|
||||
* {...}` parses as a function_definition whose
|
||||
* declarator is the BASE-CLASS name, so the raw
|
||||
* pass mints a bogus Function def named after
|
||||
* the base spanning the whole class. Fingerprint:
|
||||
* a raw callable def with an IDENTICAL span to
|
||||
* the adopted type def whose name is one of the
|
||||
* adopted def's base classes. A real method is
|
||||
* a strict subset of the class span and never
|
||||
* carries a base-class name. */
|
||||
if (d->label && cbm_def_label_is_type(d->label) && superseded &&
|
||||
d->base_classes) {
|
||||
for (int j = 0; j < defs_before; j++) {
|
||||
CBMDefinition *r = &result->defs.items[j];
|
||||
if (!r->label || !r->name ||
|
||||
!cbm_def_label_is_callable(r->label) ||
|
||||
r->start_line != d->start_line ||
|
||||
r->end_line != d->end_line) {
|
||||
continue;
|
||||
}
|
||||
for (const char **b = d->base_classes; *b; b++) {
|
||||
if (strcmp(*b, r->name) == 0) {
|
||||
superseded[j] = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rescued_count < 64) {
|
||||
rescued_spans[rescued_count].start = d->start_line;
|
||||
rescued_spans[rescued_count].end = d->end_line;
|
||||
rescued_count++;
|
||||
}
|
||||
result->defs.items[w++] = *d;
|
||||
}
|
||||
}
|
||||
if (superseded) {
|
||||
int rw = 0;
|
||||
for (int j = 0; j < defs_before; j++) {
|
||||
if (!superseded[j]) {
|
||||
result->defs.items[rw++] = result->defs.items[j];
|
||||
}
|
||||
}
|
||||
int shift = defs_before - rw;
|
||||
if (shift > 0 && w > defs_before) {
|
||||
memmove(&result->defs.items[rw],
|
||||
&result->defs.items[defs_before],
|
||||
(size_t)(w - defs_before) * sizeof(CBMDefinition));
|
||||
}
|
||||
w -= shift;
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, superseded);
|
||||
}
|
||||
result->defs.count = w;
|
||||
}
|
||||
}
|
||||
@@ -2436,7 +2835,7 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
|
||||
* splitting a brace inside a recovered function looks unrecovered:
|
||||
* the refinement keeps only the discarded branch, the function starts
|
||||
* above it, and the evidence falls outside the range. */
|
||||
cbm_subtract_recovered_regions(®s, &result->defs);
|
||||
cbm_subtract_recovered_regions(®s, &result->defs, source, source_len);
|
||||
/* Phase 2: cut what is left down to the lines the preprocessed parse
|
||||
* could not explain. */
|
||||
if (pp_line_map) {
|
||||
|
||||
+25
-20
@@ -269,26 +269,31 @@ typedef struct {
|
||||
* calls at 251 MB with most of that empty slots. Readers index it exactly
|
||||
* as before; only `sizeof` changed. */
|
||||
CBMCallArg *args;
|
||||
int arg_count; // number of captured arguments (<= CBM_MAX_CALL_ARGS)
|
||||
int loop_depth; // enclosing loop nesting at the call site
|
||||
int branch_depth; // enclosing branch nesting at the call site
|
||||
int start_line; // 1-based source line of the call (for def range-match)
|
||||
uint32_t site_start_byte; // exact AST occurrence span; end > start when present
|
||||
uint32_t site_end_byte; // exclusive byte offset in the source file
|
||||
CBMSourceOrigin source_origin; // raw source or C-family preprocessed buffer
|
||||
bool is_method; // method/member call with an UNRESOLVED receiver. Perl:
|
||||
// arrow/method call ($obj->m). TS/JS/TSX: member call
|
||||
// x.foo() whose receiver is not this/super. Python:
|
||||
// x.foo() where x is not self/cls/super() and is not
|
||||
// rooted in an imported name. Read by the weak-member
|
||||
// guard and by the pxc synthetic-carrier dedup key in
|
||||
// pass_lsp_cross.c. Default false.
|
||||
bool requires_lsp_resolution; // synthetic semantic candidate (for example an implicit
|
||||
// C++ operator). Never fall back to textual resolution.
|
||||
bool callee_is_locally_bound; // bare call foo() whose callee identifier is bound as a
|
||||
// parameter of an enclosing function, so it cannot be the
|
||||
// module-level foo. Python only today. Read by the
|
||||
// weak-local-binding guard. Default false.
|
||||
int arg_count; // number of captured arguments (<= CBM_MAX_CALL_ARGS)
|
||||
int loop_depth; // enclosing loop nesting at the call site
|
||||
int branch_depth; // enclosing branch nesting at the call site
|
||||
int start_line; // 1-based source line of the call (for def range-match)
|
||||
uint32_t site_start_byte; // exact AST occurrence span; end > start when present
|
||||
uint32_t site_end_byte; // exclusive byte offset in the source file
|
||||
CBMSourceOrigin source_origin; // raw source or C-family preprocessed buffer
|
||||
bool is_method; // method/member call with an UNRESOLVED receiver. Perl:
|
||||
// arrow/method call ($obj->m). TS/JS/TSX: member call
|
||||
// x.foo() whose receiver is not this/super. Python:
|
||||
// x.foo() where x is not self/cls/super() and is not
|
||||
// rooted in an imported name. Read by the weak-member
|
||||
// guard and by the pxc synthetic-carrier dedup key in
|
||||
// pass_lsp_cross.c. Default false.
|
||||
bool requires_lsp_resolution; // synthetic semantic candidate (for example an implicit
|
||||
// C++ operator). Never fall back to textual resolution.
|
||||
bool callee_is_locally_bound; // bare call foo() whose callee identifier is bound as a
|
||||
// parameter of an enclosing function, so it cannot be the
|
||||
// module-level foo. Python only today. Read by the
|
||||
// weak-local-binding guard. Default false.
|
||||
bool receiver_is_self_attribute; // Python member call whose receiver is an attribute
|
||||
// chain rooted at self/cls but not self/cls itself
|
||||
// (self.compiler.apply_converters()). An object the
|
||||
// class owns, not a parameter: read by the weak-member
|
||||
// guard's unique-name exemption. Default false.
|
||||
} CBMCall;
|
||||
|
||||
typedef struct {
|
||||
|
||||
@@ -2068,6 +2068,14 @@ static void extract_call_args(CBMExtractCtx *ctx, TSNode args, CBMCall *call) {
|
||||
for (uint32_t ai = 0; ai < argc && call->arg_count < CBM_MAX_CALL_ARGS; ai++) {
|
||||
TSNode arg_node = ts_node_named_child(args, ai);
|
||||
const char *ak = ts_node_type(arg_node);
|
||||
/* tree-sitter lists a comment inside the argument list as a named
|
||||
* child (Java block_comment/line_comment, C-family comment). It is
|
||||
* not an argument: taken as one, a leading block comment became
|
||||
* args[0] and the Route pass read its text as a URL. */
|
||||
if (strcmp(ak, "comment") == 0 || strcmp(ak, "line_comment") == 0 ||
|
||||
strcmp(ak, "block_comment") == 0) {
|
||||
continue;
|
||||
}
|
||||
if (!call->args) {
|
||||
call->args = cbm_arena_calloc(ctx->arena, CBM_MAX_CALL_ARGS * sizeof(CBMCallArg));
|
||||
if (!call->args) {
|
||||
@@ -2272,6 +2280,61 @@ static const char *extract_binary_concat_suffix(CBMExtractCtx *ctx, TSNode node)
|
||||
}
|
||||
|
||||
// Try to extract URL/topic from a positional argument (string or constant).
|
||||
/* Swift names its call arguments, so each one is a value_argument that may lead
|
||||
* with a value_argument_label — the `from:` in `data(from: url)`. Return the
|
||||
* value itself, and leave any other node exactly as it came in. */
|
||||
static TSNode swift_argument_value(TSNode arg) {
|
||||
if (strcmp(ts_node_type(arg), "value_argument") != 0 || ts_node_named_child_count(arg) == 0) {
|
||||
return arg;
|
||||
}
|
||||
TSNode val = ts_node_named_child(arg, 0);
|
||||
if (strcmp(ts_node_type(val), "value_argument_label") == 0 &&
|
||||
ts_node_named_child_count(arg) > 1) {
|
||||
val = ts_node_named_child(arg, 1);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Swift has no URL literal, so almost no real code passes a bare string to a
|
||||
* request. It writes `URL(string: "https://…")!` instead, and the literal then
|
||||
* sits two levels down: past the trailing `!`, which the grammar models as a
|
||||
* postfix_expression, and inside the constructor's own argument list.
|
||||
*
|
||||
* Unwrap both so that literal is as reachable as a bare one. Only the three
|
||||
* Foundation types that take a URL string are unwrapped — any other call keeps
|
||||
* its own meaning, and a non-literal argument such as `URL(string: base + path)`
|
||||
* falls through to the ordinary handling unchanged. */
|
||||
static TSNode swift_unwrap_url_constructor(CBMExtractCtx *ctx, TSNode arg) {
|
||||
/* Step past a trailing "!" or "?". */
|
||||
if (strcmp(ts_node_type(arg), "postfix_expression") == 0) {
|
||||
TSNode target = ts_node_child_by_field_name(arg, TS_FIELD("target"));
|
||||
if (!ts_node_is_null(target)) {
|
||||
arg = target;
|
||||
}
|
||||
}
|
||||
if (strcmp(ts_node_type(arg), "call_expression") != 0) {
|
||||
return arg;
|
||||
}
|
||||
TSNode callee = ts_node_named_child(arg, 0);
|
||||
if (ts_node_is_null(callee) || strcmp(ts_node_type(callee), "simple_identifier") != 0) {
|
||||
return arg;
|
||||
}
|
||||
const char *name = cbm_node_text(ctx->arena, callee, ctx->source);
|
||||
if (!name || (strcmp(name, "URL") != 0 && strcmp(name, "URLComponents") != 0 &&
|
||||
strcmp(name, "URLRequest") != 0)) {
|
||||
return arg;
|
||||
}
|
||||
TSNode suffix = cbm_find_child_by_kind(arg, "call_suffix");
|
||||
if (ts_node_is_null(suffix)) {
|
||||
return arg;
|
||||
}
|
||||
TSNode inner = cbm_find_child_by_kind(suffix, "value_arguments");
|
||||
if (ts_node_is_null(inner) || ts_node_named_child_count(inner) == 0) {
|
||||
return arg;
|
||||
}
|
||||
return swift_argument_value(ts_node_named_child(inner, 0));
|
||||
}
|
||||
|
||||
static const char *extract_positional_url(CBMExtractCtx *ctx, TSNode arg, const char *ak) {
|
||||
/* JS/TS template literals: `/things/${id}` normalizes to "/things/{}" so the
|
||||
* client URL joins the server route's canonical placeholder (issue #1006). */
|
||||
@@ -2315,15 +2378,12 @@ static const char *extract_url_or_topic_arg(CBMExtractCtx *ctx, TSNode args) {
|
||||
}
|
||||
/* Swift wraps each argument in a value_argument that may lead with its
|
||||
* label, so `data(from: url)` would otherwise yield the label `from`
|
||||
* rather than the value. Step past a leading value_argument_label. */
|
||||
if (strcmp(ts_node_type(arg), "value_argument") == 0 &&
|
||||
ts_node_named_child_count(arg) > 0) {
|
||||
TSNode val = ts_node_named_child(arg, 0);
|
||||
if (strcmp(ts_node_type(val), "value_argument_label") == 0 &&
|
||||
ts_node_named_child_count(arg) > 1) {
|
||||
val = ts_node_named_child(arg, 1);
|
||||
}
|
||||
arg = val;
|
||||
* rather than the value. */
|
||||
arg = swift_argument_value(arg);
|
||||
/* A Swift URL is usually built rather than written bare, and the
|
||||
* literal then sits inside that constructor. */
|
||||
if (ctx->language == CBM_LANG_SWIFT) {
|
||||
arg = swift_unwrap_url_constructor(ctx, arg);
|
||||
}
|
||||
const char *ak = ts_node_type(arg);
|
||||
|
||||
@@ -2965,6 +3025,28 @@ static char *resolve_objectscript_instance_call(CBMArena *a, TSNode node, const
|
||||
* statically-known type here, so the call must not bind by short name alone.
|
||||
* Note `self.client.send()` is NOT exempt: the receiver is `self.client`, an
|
||||
* attribute of unknown type, not `self` itself. */
|
||||
/* True when a Python attribute-call receiver is an attribute chain ROOTED at
|
||||
* self/cls but is not self/cls itself: `self.compiler.apply_converters()` has
|
||||
* receiver `self.compiler`, an object the class owns. The weak-member guard's
|
||||
* unique-name exemption keys on this shape (see cbm_weak_member_unique_name_
|
||||
* exempt): a bare parameter (`accelerator.backward()`) carries no ownership
|
||||
* evidence and stays suppressed. Direct `self.m()` is already exempt via
|
||||
* python_receiver_is_exempt and is deliberately NOT flagged here. */
|
||||
static bool python_receiver_rooted_at_self(CBMExtractCtx *ctx, TSNode receiver) {
|
||||
if (ts_node_is_null(receiver) || strcmp(ts_node_type(receiver), "attribute") != 0) {
|
||||
return false;
|
||||
}
|
||||
TSNode root = receiver;
|
||||
while (!ts_node_is_null(root) && strcmp(ts_node_type(root), "attribute") == 0) {
|
||||
root = ts_node_child_by_field_name(root, TS_FIELD("object"));
|
||||
}
|
||||
if (ts_node_is_null(root) || strcmp(ts_node_type(root), "identifier") != 0) {
|
||||
return false;
|
||||
}
|
||||
char *name = cbm_node_text(ctx->arena, root, ctx->source);
|
||||
return name && (strcmp(name, "self") == 0 || strcmp(name, "cls") == 0);
|
||||
}
|
||||
|
||||
static bool python_receiver_is_exempt(CBMExtractCtx *ctx, TSNode receiver) {
|
||||
if (ts_node_is_null(receiver)) {
|
||||
return false;
|
||||
@@ -3695,6 +3777,7 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
|
||||
if (!ts_node_is_null(fn) && strcmp(ts_node_type(fn), "attribute") == 0) {
|
||||
TSNode obj = ts_node_child_by_field_name(fn, TS_FIELD("object"));
|
||||
call.is_method = !python_receiver_is_exempt(ctx, obj);
|
||||
call.receiver_is_self_attribute = python_receiver_rooted_at_self(ctx, obj);
|
||||
} else if (!ts_node_is_null(fn) && strcmp(ts_node_type(fn), "identifier") == 0) {
|
||||
call.callee_is_locally_bound = python_callee_is_bound_parameter(ctx, state, fn);
|
||||
}
|
||||
|
||||
+155
-2
@@ -3477,6 +3477,159 @@ static TSNode find_function_params(TSNode func_node, CBMLanguage lang) {
|
||||
return params;
|
||||
}
|
||||
|
||||
/* ── C-family declared return type ──────────────────────────────────
|
||||
* The C-family grammars split a declared return type three ways: the `type`
|
||||
* field (`char`), sibling type_qualifier nodes (`const`), and the
|
||||
* pointer/reference declarators wrapping the function declarator (`*`). Taking
|
||||
* only the `type` field published `const char *get_name(void)` as "char".
|
||||
*
|
||||
* Canonical spelling: leading cv-qualifiers in source order, the base type text
|
||||
* verbatim, then one space and the declarator markers outermost-first with no
|
||||
* space between them — `const char *`, `char **`, `Text &`, `Text *&`. A
|
||||
* qualifier on a pointer level follows its `*` and is separated from the next
|
||||
* marker by a space: `char *const *`. A qualifier written after the base type
|
||||
* (`char const *`) is normalized to the leading position. */
|
||||
|
||||
/* Output sink: measures when buf is NULL, writes otherwise. Rendering twice
|
||||
* sizes the arena allocation exactly without a second copy of the logic. */
|
||||
typedef struct {
|
||||
char *buf;
|
||||
size_t len;
|
||||
} c_rt_out_t;
|
||||
|
||||
static void c_rt_put(c_rt_out_t *out, const char *text, size_t n) {
|
||||
if (out->buf) {
|
||||
memcpy(out->buf + out->len, text, n);
|
||||
}
|
||||
out->len += n;
|
||||
}
|
||||
|
||||
static void c_rt_put_str(c_rt_out_t *out, const char *text) {
|
||||
c_rt_put(out, text, strlen(text));
|
||||
}
|
||||
|
||||
static void c_rt_put_node(c_rt_out_t *out, TSNode node, const char *source) {
|
||||
uint32_t start = ts_node_start_byte(node);
|
||||
uint32_t end = ts_node_end_byte(node);
|
||||
if (end > start) {
|
||||
c_rt_put(out, source + start, (size_t)(end - start));
|
||||
}
|
||||
}
|
||||
|
||||
/* type_qualifier also covers keywords that are not part of the type
|
||||
* (`constexpr`, `_Noreturn`, `mutable`, `__extension__`, …). Keep only the ones
|
||||
* that are, so `constexpr int f()` still returns "int". */
|
||||
static bool is_c_return_cv_qualifier(TSNode node, const char *source) {
|
||||
static const char *const kept[] = {"const", "volatile", "restrict", "__restrict",
|
||||
"__restrict__", "_Atomic", NULL};
|
||||
if (strcmp(ts_node_type(node), "type_qualifier") != 0) {
|
||||
return false;
|
||||
}
|
||||
uint32_t start = ts_node_start_byte(node);
|
||||
uint32_t end = ts_node_end_byte(node);
|
||||
size_t len = end > start ? (size_t)(end - start) : 0;
|
||||
for (const char *const *k = kept; *k; k++) {
|
||||
if (strlen(*k) == len && memcmp(source + start, *k, len) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool is_c_declarator_lang(CBMLanguage lang) {
|
||||
return lang == CBM_LANG_C || lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA ||
|
||||
lang == CBM_LANG_GLSL || lang == CBM_LANG_HLSL || lang == CBM_LANG_ISPC ||
|
||||
lang == CBM_LANG_SLANG || lang == CBM_LANG_OBJC;
|
||||
}
|
||||
|
||||
/* Render the canonical return type into `out`; returns how many qualifiers and
|
||||
* markers were added around the base type (0 = the base text alone is already
|
||||
* the whole type). The declarator walk is one strict child chain, so it is
|
||||
* O(depth) with no recursion and needs no depth cap. It stops at the first node
|
||||
* that is neither a pointer nor a reference declarator: for a function returning
|
||||
* a function pointer (`int (*f(void))(int)`) that is the outer
|
||||
* function_declarator, which leaves the base type as it was. */
|
||||
static size_t c_rt_render(c_rt_out_t *out, TSNode func_node, TSNode type_node, TSNode declarator,
|
||||
const char *source) {
|
||||
size_t added = 0;
|
||||
uint32_t decl_start = ts_node_start_byte(declarator);
|
||||
uint32_t nc = ts_node_named_child_count(func_node);
|
||||
for (uint32_t i = 0; i < nc; i++) {
|
||||
TSNode ch = ts_node_named_child(func_node, i);
|
||||
if (ts_node_start_byte(ch) >= decl_start) {
|
||||
break;
|
||||
}
|
||||
if (is_c_return_cv_qualifier(ch, source)) {
|
||||
c_rt_put_node(out, ch, source);
|
||||
c_rt_put_str(out, " ");
|
||||
added++;
|
||||
}
|
||||
}
|
||||
c_rt_put_node(out, type_node, source);
|
||||
|
||||
bool need_space = true;
|
||||
TSNode decl = declarator;
|
||||
while (!ts_node_is_null(decl)) {
|
||||
const char *dk = ts_node_type(decl);
|
||||
bool is_ref = strcmp(dk, "reference_declarator") == 0;
|
||||
if (!is_ref && strcmp(dk, "pointer_declarator") != 0) {
|
||||
break;
|
||||
}
|
||||
if (need_space) {
|
||||
c_rt_put_str(out, " ");
|
||||
need_space = false;
|
||||
}
|
||||
/* A reference_declarator opens with its `&` / `&&` token. */
|
||||
TSNode marker = ts_node_child(decl, 0);
|
||||
if (is_ref && !ts_node_is_null(marker) && !ts_node_is_named(marker)) {
|
||||
c_rt_put_node(out, marker, source);
|
||||
} else {
|
||||
c_rt_put_str(out, is_ref ? "&" : "*");
|
||||
}
|
||||
added++;
|
||||
uint32_t dn = ts_node_named_child_count(decl);
|
||||
for (uint32_t i = 0; i < dn; i++) {
|
||||
TSNode q = ts_node_named_child(decl, i);
|
||||
if (is_c_return_cv_qualifier(q, source)) {
|
||||
c_rt_put_node(out, q, source);
|
||||
need_space = true;
|
||||
added++;
|
||||
}
|
||||
}
|
||||
/* tree-sitter-cpp/-cuda give a reference_declarator's inner declarator no
|
||||
* `declarator` field (see find_c_params); it is the one named child. */
|
||||
TSNode inner = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
|
||||
if (ts_node_is_null(inner) && is_ref && dn > 0) {
|
||||
inner = ts_node_named_child(decl, 0);
|
||||
}
|
||||
decl = inner;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
/* Declared return type of a C-family function/method node whose `type` field is
|
||||
* `type_node`. Any other language, and any type with nothing around its base
|
||||
* type, gets the base type text exactly as before. */
|
||||
static char *c_declared_return_type(CBMExtractCtx *ctx, TSNode func_node, TSNode type_node) {
|
||||
CBMArena *a = ctx->arena;
|
||||
TSNode declarator = ts_node_child_by_field_name(func_node, TS_FIELD("declarator"));
|
||||
if (!is_c_declarator_lang(ctx->language) || ts_node_is_null(declarator)) {
|
||||
return cbm_node_text(a, type_node, ctx->source);
|
||||
}
|
||||
c_rt_out_t out = {NULL, 0};
|
||||
if (c_rt_render(&out, func_node, type_node, declarator, ctx->source) == 0) {
|
||||
return cbm_node_text(a, type_node, ctx->source);
|
||||
}
|
||||
out.buf = (char *)cbm_arena_alloc(a, out.len + NULL_TERM);
|
||||
if (!out.buf) {
|
||||
return cbm_node_text(a, type_node, ctx->source);
|
||||
}
|
||||
out.len = 0;
|
||||
(void)c_rt_render(&out, func_node, type_node, declarator, ctx->source);
|
||||
out.buf[out.len] = '\0';
|
||||
return out.buf;
|
||||
}
|
||||
|
||||
// C++: resolve trailing return type (auto f() -> Type) on a declarator node.
|
||||
// Updates def->return_type and def->return_types if trailing type found.
|
||||
static void resolve_cpp_trailing_return(CBMArena *a, TSNode func_node, const char *source,
|
||||
@@ -3712,7 +3865,7 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
|
||||
for (const char **f = rt_fields; *f; f++) {
|
||||
TSNode rt = ts_node_child_by_field_name(func_node, *f, (uint32_t)strlen(*f));
|
||||
if (!ts_node_is_null(rt)) {
|
||||
def.return_type = cbm_node_text(a, rt, ctx->source);
|
||||
def.return_type = c_declared_return_type(ctx, func_node, rt);
|
||||
def.return_types = extract_return_types(a, rt, ctx->source, ctx->language);
|
||||
break;
|
||||
}
|
||||
@@ -4964,7 +5117,7 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node,
|
||||
for (const char **f = rt_fields; *f; f++) {
|
||||
TSNode rt = ts_node_child_by_field_name(child, *f, (uint32_t)strlen(*f));
|
||||
if (!ts_node_is_null(rt)) {
|
||||
def.return_type = cbm_node_text(a, rt, ctx->source);
|
||||
def.return_type = c_declared_return_type(ctx, child, rt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +133,19 @@ static void parse_go_import_spec(CBMExtractCtx *ctx, TSNode spec) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* cgo: `import "C"` names the cgo PSEUDO-package, not a real one — "C" is
|
||||
* reserved by go/build and no package with that import path can exist.
|
||||
* Emitting it as an ordinary import makes the import resolver fall through
|
||||
* to its symbol-name fallback (cbm_pipeline_resolve_import_node Strategy 3,
|
||||
* pass_pkgmap.c), which matches the literal name "C" against every project
|
||||
* node called C and picks the lexicographically smallest: on a real Go repo
|
||||
* all 27 cgo files pointed their IMPORTS edge at the same unrelated `C`
|
||||
* member of a test helper. Drop it — the C side is not a graph package, and
|
||||
* the file's remaining imports are unaffected. */
|
||||
if (strcmp(path, "C") == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
TSNode name_node = ts_node_child_by_field_name(spec, TS_FIELD("name"));
|
||||
const char *local_name =
|
||||
!ts_node_is_null(name_node) ? cbm_node_text(a, name_node, ctx->source) : path_last(a, path);
|
||||
|
||||
@@ -42,6 +42,283 @@ static bool has_preprocessor_work(const char *source, int source_len) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Export-macro candidates (#1989) ─────────────────────────────────────────
|
||||
// Build systems define symbol-export macros empty on the compiler command line
|
||||
// (UE's UBT: `/D "MODULE_API="`; CMake generate_export_header: `<lib>_EXPORT`),
|
||||
// so they never appear as #define lines in the source. tree-sitter has no
|
||||
// preprocessor state either, and `class MODULE_API Foo` misparses with the
|
||||
// macro token as the type name (worse: enums and free functions are lost to
|
||||
// ERROR regions entirely). To mirror the real compile line, the preprocessed
|
||||
// second pass predefines the conventional export-macro-shaped identifiers found
|
||||
// in the file as empty. The shape is deliberately narrow — ALL_CAPS identifier
|
||||
// ending in a known export suffix, with a non-trivial prefix — and the list is
|
||||
// capped, so ordinary all-caps identifiers cannot be swept in wholesale.
|
||||
static const char *kExportMacroSuffixes[] = {"_API", "_EXPORT", "_IMPORT",
|
||||
"_DLLEXPORT", "_DEPRECATED", NULL};
|
||||
|
||||
static bool is_export_macro_shape(const char *id, size_t len) {
|
||||
if (id[0] < 'A' || id[0] > 'Z') {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
char c = id[i];
|
||||
bool upper = c >= 'A' && c <= 'Z';
|
||||
bool digit = c >= '0' && c <= '9';
|
||||
if (!upper && !digit && c != '_') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (int s = 0; kExportMacroSuffixes[s]; s++) {
|
||||
size_t slen = strlen(kExportMacroSuffixes[s]);
|
||||
// Require at least two prefix characters before the suffix so a bare
|
||||
// "X_API"-style token (single-letter, easily a genuine symbol) stays out.
|
||||
if (len >= slen + 2 && strncmp(id + len - slen, kExportMacroSuffixes[s], slen) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool is_identifier_start(char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
|
||||
}
|
||||
|
||||
static bool is_identifier_char(char c) {
|
||||
return is_identifier_start(c) || (c >= '0' && c <= '9');
|
||||
}
|
||||
|
||||
// C++ raw string literals (R"delim(...)delim"). Returns the index one past
|
||||
// the closing quote, or -1 when the form cannot be confidently recognized
|
||||
// (unterminated, malformed delimiter) — the caller then STOPS collecting so
|
||||
// the mis-modeled literal cannot poison the scan state of the rest of the
|
||||
// file (#1989 review).
|
||||
static int skip_raw_string(const char *source, int source_len, int quote) {
|
||||
int j = quote + 1;
|
||||
int delim_start = j;
|
||||
while (j < source_len) {
|
||||
char c = source[j];
|
||||
if (c == '(') {
|
||||
break;
|
||||
}
|
||||
// Delimiter chars: the standard d-char set excludes space, parens,
|
||||
// backslash, and the line breaks — a double quote IS a legal d-char
|
||||
// (R"""(...)""" compiles), so it must not end the delimiter (#1989
|
||||
// review round 3).
|
||||
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ')' || c == '\\' ||
|
||||
j - delim_start >= 16) {
|
||||
return -1;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
if (j >= source_len || source[j] != '(') {
|
||||
return -1;
|
||||
}
|
||||
int delim_len = j - delim_start;
|
||||
j++; // past the opening "("
|
||||
while (j < source_len) {
|
||||
if (source[j] == ')') {
|
||||
int k = j + 1;
|
||||
int m = 0;
|
||||
while (m < delim_len && k + m < source_len &&
|
||||
source[k + m] == source[delim_start + m]) {
|
||||
m++;
|
||||
}
|
||||
if (m == delim_len && k + m < source_len && source[k + m] == '"') {
|
||||
return k + m + 1;
|
||||
}
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1; // unterminated raw string: uncertain
|
||||
}
|
||||
|
||||
// If the identifier just scanned is a raw-string prefix (R, LR, uR, UR, u8R)
|
||||
// immediately followed by a quote, return skip_raw_string(...). Returns 0 for
|
||||
// an ordinary identifier (including an identifier merely ENDING in R — only a
|
||||
// standalone prefix token starts a raw string) and -1 on an unrecognizable
|
||||
// raw form.
|
||||
static int raw_string_after_prefix(const char *source, int source_len, int start, int end) {
|
||||
static const char *prefixes[] = {"R", "LR", "uR", "UR", "u8R", NULL};
|
||||
size_t idlen = (size_t)(end - start);
|
||||
bool is_prefix = false;
|
||||
for (int p = 0; prefixes[p]; p++) {
|
||||
if (idlen == strlen(prefixes[p]) && strncmp(source + start, prefixes[p], idlen) == 0) {
|
||||
is_prefix = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!is_prefix || end >= source_len || source[end] != '"') {
|
||||
return 0;
|
||||
}
|
||||
return skip_raw_string(source, source_len, end);
|
||||
}
|
||||
|
||||
// Advance past comments and string/char literals so only real code tokens
|
||||
// consume the candidate budget (#1989 review). Handles line-spliced //
|
||||
// comments (a backslash before the newline continues the comment — line
|
||||
// splicing happens before comment recognition) and, via the identifier-scan
|
||||
// hook in the callers, C++ raw string literals. A digit separator (1'000'000)
|
||||
// can still over-skip — that fails safe, toward NOT collecting a candidate.
|
||||
static int skip_non_code(const char *source, int source_len, int i) {
|
||||
while (i < source_len) {
|
||||
char c = source[i];
|
||||
if (c == '/' && i + 1 < source_len && source[i + 1] == '/') {
|
||||
i += 2;
|
||||
for (;;) {
|
||||
while (i < source_len && source[i] != '\n') {
|
||||
i++;
|
||||
}
|
||||
if (i >= source_len) {
|
||||
break;
|
||||
}
|
||||
// Line splice: a backslash right before the newline (allowing
|
||||
// \r\n) means the comment continues on the next line.
|
||||
int back = i - 1;
|
||||
if (back >= 0 && source[back] == '\r') {
|
||||
back--;
|
||||
}
|
||||
if (back >= 0 && source[back] == '\\') {
|
||||
i++; // spliced: keep consuming inside the comment
|
||||
continue;
|
||||
}
|
||||
i++; // real end-of-comment newline
|
||||
break;
|
||||
}
|
||||
} else if (c == '/' && i + 1 < source_len && source[i + 1] == '*') {
|
||||
i += 2;
|
||||
while (i + 1 < source_len && !(source[i] == '*' && source[i + 1] == '/')) {
|
||||
i++;
|
||||
}
|
||||
if (i + 1 < source_len) {
|
||||
i += 2; // past the closing "*/"
|
||||
} else {
|
||||
i = source_len; // unterminated comment runs to EOF
|
||||
}
|
||||
} else if (c == '"' || c == '\'') {
|
||||
char quote = c;
|
||||
i++;
|
||||
while (i < source_len) {
|
||||
if (source[i] == '\\') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (source[i] == quote) {
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
// Count-only scan used by the early gate (no storage).
|
||||
static bool has_export_macro_candidates(const char *source, int source_len) {
|
||||
if (!source || source_len <= 0) {
|
||||
return false;
|
||||
}
|
||||
int i = 0;
|
||||
while (i < source_len) {
|
||||
i = skip_non_code(source, source_len, i);
|
||||
if (i >= source_len) {
|
||||
break;
|
||||
}
|
||||
if (!is_identifier_start(source[i])) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
int start = i;
|
||||
while (i < source_len && is_identifier_char(source[i])) {
|
||||
i++;
|
||||
}
|
||||
// A raw-string prefix consumes everything up to its closing quote;
|
||||
// an unrecognizable raw form poisons the scan state, so fail toward
|
||||
// NOT running the second pass (raw behavior preserved).
|
||||
int raw = raw_string_after_prefix(source, source_len, start, i);
|
||||
if (raw < 0) {
|
||||
return false;
|
||||
}
|
||||
if (raw > 0) {
|
||||
i = raw;
|
||||
continue;
|
||||
}
|
||||
if (is_export_macro_shape(source + start, (size_t)(i - start))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static int collect_export_macro_candidates(const char *source, int source_len,
|
||||
char (*out)[CBM_EXPORT_MACRO_NAME_MAX], int max_out) {
|
||||
if (!source || source_len <= 0 || !out || max_out <= 0) {
|
||||
return 0;
|
||||
}
|
||||
int stored = 0;
|
||||
int i = 0;
|
||||
while (i < source_len) {
|
||||
i = skip_non_code(source, source_len, i);
|
||||
if (i >= source_len) {
|
||||
break;
|
||||
}
|
||||
if (!is_identifier_start(source[i])) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
int start = i;
|
||||
while (i < source_len && is_identifier_char(source[i])) {
|
||||
i++;
|
||||
}
|
||||
// Raw string (see has_export_macro_candidates): skip its body, or stop
|
||||
// collecting entirely when the form cannot be confidently recognized —
|
||||
// continuing would mis-tokenize the rest of the file and could both
|
||||
// mint phantom candidates and mask real ones (#1989 review).
|
||||
int raw = raw_string_after_prefix(source, source_len, start, i);
|
||||
if (raw < 0) {
|
||||
break;
|
||||
}
|
||||
if (raw > 0) {
|
||||
i = raw;
|
||||
continue;
|
||||
}
|
||||
size_t len = (size_t)(i - start);
|
||||
/* Length gate FIRST: the dedup below reads out[k][0..len] against rows
|
||||
* of CBM_EXPORT_MACRO_NAME_MAX bytes — an over-long candidate must be
|
||||
* rejected before any compare touches them. */
|
||||
if (len >= CBM_EXPORT_MACRO_NAME_MAX) {
|
||||
continue;
|
||||
}
|
||||
if (!is_export_macro_shape(source + start, len)) {
|
||||
continue;
|
||||
}
|
||||
bool dup = false;
|
||||
for (int k = 0; k < stored; k++) {
|
||||
if (strncmp(out[k], source + start, len) == 0 && out[k][len] == '\0') {
|
||||
dup = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (dup) {
|
||||
continue;
|
||||
}
|
||||
if (stored >= max_out) {
|
||||
break; // bounded: stop collecting once the cap is reached
|
||||
}
|
||||
memcpy(out[stored], source + start, len);
|
||||
out[stored][len] = '\0';
|
||||
stored++;
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
int cbm_export_macro_candidates(const char *source, int source_len,
|
||||
char (*out)[CBM_EXPORT_MACRO_NAME_MAX], int max_out) {
|
||||
return collect_export_macro_candidates(source, source_len, out, max_out);
|
||||
}
|
||||
|
||||
static int count_expanded_lines(const std::string &text) {
|
||||
int count = 1;
|
||||
for (char c : text) {
|
||||
@@ -146,7 +423,11 @@ static bool build_line_map(const std::string &expanded, const std::string &main_
|
||||
CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_len,
|
||||
const char *filename, const char **extra_defines,
|
||||
const char **include_paths, int cpp_mode) {
|
||||
if (!has_preprocessor_work(source, source_len)) {
|
||||
// Run the second pass when there are directives to evaluate OR when the file
|
||||
// carries export-macro-shaped identifiers to predefine empty (#1989) — a UE
|
||||
// plugin header with only `#pragma once` + `#include` lines still needs it.
|
||||
if (!has_preprocessor_work(source, source_len) &&
|
||||
!has_export_macro_candidates(source, source_len)) {
|
||||
return NULL; // NULL = no expansion needed, use original
|
||||
}
|
||||
|
||||
@@ -156,6 +437,28 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le
|
||||
for (int i = 0; extra_defines[i]; i++)
|
||||
dui.defines.push_back(extra_defines[i]);
|
||||
}
|
||||
// Predefine collected export-macro candidates as empty, mirroring the
|
||||
// real compile command line (`/D "MODULE_API="`). Names already provided
|
||||
// by the caller win — never override an explicit define.
|
||||
char export_cands[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int export_cand_count =
|
||||
collect_export_macro_candidates(source, source_len, export_cands, CBM_EXPORT_MACRO_MAX);
|
||||
for (int i = 0; i < export_cand_count; i++) {
|
||||
bool provided = false;
|
||||
for (std::list<std::string>::const_iterator it = dui.defines.begin();
|
||||
it != dui.defines.end(); ++it) {
|
||||
const std::string &def = *it;
|
||||
size_t eq = def.find('=');
|
||||
std::string name = (eq == std::string::npos) ? def : def.substr(0, eq);
|
||||
if (name == export_cands[i]) {
|
||||
provided = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!provided) {
|
||||
dui.defines.push_back(std::string(export_cands[i]) + "=");
|
||||
}
|
||||
}
|
||||
if (include_paths) {
|
||||
for (int i = 0; include_paths[i]; i++)
|
||||
dui.includePaths.push_back(include_paths[i]);
|
||||
|
||||
@@ -4,6 +4,15 @@
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* #1989: build-system export macros (UE "<MOD>_API", CMake generate_export_header
|
||||
* "<lib>_EXPORT", ...) are defined empty on the real compile command line but are
|
||||
* invisible to tree-sitter, so `class MOD_API Foo` misparses with the macro token
|
||||
* as the type name. The preprocessed second pass predefines the conventional
|
||||
* export-macro-shaped identifiers found in a source file as empty, mirroring the
|
||||
* real build line. The candidate list is bounded. */
|
||||
#define CBM_EXPORT_MACRO_MAX 32
|
||||
#define CBM_EXPORT_MACRO_NAME_MAX 96
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
@@ -15,6 +24,12 @@ typedef struct {
|
||||
int expanded_line_count;
|
||||
} CBMPreprocessedSource;
|
||||
|
||||
// Collect conventional export-macro-shaped identifiers (ALL_CAPS ending in
|
||||
// _API/_EXPORT/_IMPORT/_DLLEXPORT/_DEPRECATED) from the source, up to max_out
|
||||
// unique names. Returns the number of names stored in out.
|
||||
int cbm_export_macro_candidates(const char *source, int source_len,
|
||||
char (*out)[CBM_EXPORT_MACRO_NAME_MAX], int max_out);
|
||||
|
||||
// Preprocess C/C++ source: expand macros, evaluate #ifdef, resolve #include.
|
||||
// Returns malloc-allocated expanded source, or NULL if no expansion needed/on failure.
|
||||
// extra_defines: NULL-terminated array of "NAME=VALUE" strings (can be NULL).
|
||||
|
||||
+136
-10
@@ -140,6 +140,20 @@ static const lib_pattern_t http_libraries[] = {
|
||||
{"socket.http", CBM_SVC_HTTP, NULL},
|
||||
{"resty.http", CBM_SVC_HTTP, NULL},
|
||||
|
||||
/* Glued-name libraries. match_qn needs an identifier boundary around an
|
||||
* id, so a library whose own name glues a lowercase prefix/suffix onto
|
||||
* another id ("grequests", "curlpp") is listed explicitly: no boundary
|
||||
* rule can tell "grequests" from "myrequests". */
|
||||
{"grequests", CBM_SVC_HTTP, NULL}, /* Python: gevent + requests */
|
||||
{"txrequests", CBM_SVC_HTTP, NULL}, /* Python: Twisted + requests */
|
||||
{"redaxios", CBM_SVC_HTTP, NULL}, /* JS: axios-compatible fetch client */
|
||||
{"gaxios", CBM_SVC_HTTP, NULL}, /* JS: Google's axios-style client */
|
||||
{"libcurl", CBM_SVC_HTTP, NULL}, /* C, node-libcurl */
|
||||
{"curlpp", CBM_SVC_HTTP, NULL}, /* C++ libcurl wrapper */
|
||||
{"curlcpp", CBM_SVC_HTTP, NULL}, /* C++ libcurl wrapper */
|
||||
{"hyperlocal", CBM_SVC_HTTP, NULL}, /* Rust: hyper over unix sockets */
|
||||
{"guzzlehttp", CBM_SVC_HTTP, NULL}, /* PHP: Guzzle's composer vendor */
|
||||
|
||||
{NULL, CBM_SVC_NONE, NULL},
|
||||
};
|
||||
|
||||
@@ -263,6 +277,33 @@ static const lib_pattern_t async_libraries[] = {
|
||||
{"dapr.clients.grpc", CBM_SVC_ASYNC, "dapr"},
|
||||
{"DaprClient", CBM_SVC_ASYNC, "dapr"},
|
||||
|
||||
/* Glued-name libraries (see the note in http_libraries). */
|
||||
{"aiokafka", CBM_SVC_ASYNC, "kafka"},
|
||||
{"pykafka", CBM_SVC_ASYNC, "kafka"},
|
||||
{"librdkafka", CBM_SVC_ASYNC, "kafka"},
|
||||
{"rdkafkacpp", CBM_SVC_ASYNC, "kafka"},
|
||||
{"rskafka", CBM_SVC_ASYNC, "kafka"},
|
||||
{"aioamqp", CBM_SVC_ASYNC, "rabbitmq"},
|
||||
{"amqpstorm", CBM_SVC_ASYNC, "rabbitmq"},
|
||||
{"pamqp", CBM_SVC_ASYNC, "rabbitmq"},
|
||||
{"pyamqp", CBM_SVC_ASYNC, "rabbitmq"},
|
||||
{"amqprs", CBM_SVC_ASYNC, "rabbitmq"},
|
||||
{"amqpcpp", CBM_SVC_ASYNC, "rabbitmq"},
|
||||
{"pynats", CBM_SVC_ASYNC, "nats"},
|
||||
{"jnats", CBM_SVC_ASYNC, "nats"},
|
||||
{"aiomqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"amqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"hbmqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"umqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"mqttools", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"emqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"rumqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"gomqtt", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"libmosquitto", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"mosquittopp", CBM_SVC_ASYNC, "mqtt"},
|
||||
{"pubsublite", CBM_SVC_ASYNC, "pubsub"},
|
||||
{"gocelery", CBM_SVC_ASYNC, "celery"},
|
||||
|
||||
{NULL, CBM_SVC_NONE, NULL},
|
||||
};
|
||||
|
||||
@@ -308,6 +349,13 @@ static const lib_pattern_t config_libraries[] = {
|
||||
{"Application.get_env", CBM_SVC_CONFIG, NULL},
|
||||
{"Application.fetch_env", CBM_SVC_CONFIG, NULL},
|
||||
|
||||
/* Glued-name accessors (see the note in http_libraries). */
|
||||
{"wgetenv", CBM_SVC_CONFIG, NULL}, /* Windows CRT: _wgetenv, _wgetenv_s */
|
||||
{"getenvb", CBM_SVC_CONFIG, NULL}, /* Python: os.getenvb */
|
||||
{"qgetenv", CBM_SVC_CONFIG, NULL}, /* Qt */
|
||||
{"dotenvx", CBM_SVC_CONFIG, NULL}, /* JS: @dotenvx/dotenvx */
|
||||
{"phpdotenv", CBM_SVC_CONFIG, NULL}, /* PHP: vlucas/phpdotenv */
|
||||
|
||||
{NULL, CBM_SVC_NONE, NULL},
|
||||
};
|
||||
|
||||
@@ -377,6 +425,11 @@ static const lib_pattern_t route_reg_libraries[] = {
|
||||
{"akka.http.scaladsl.server", CBM_SVC_ROUTE_REG, NULL},
|
||||
{"play.api.routing", CBM_SVC_ROUTE_REG, NULL},
|
||||
|
||||
/* Glued-name frameworks (see the note in http_libraries). */
|
||||
{"apiflask", CBM_SVC_ROUTE_REG, NULL}, /* Python: Flask-based */
|
||||
{"honox", CBM_SVC_ROUTE_REG, NULL}, /* JS: Hono meta-framework */
|
||||
{"fasthttprouter", CBM_SVC_ROUTE_REG, NULL}, /* Go: httprouter for fasthttp */
|
||||
|
||||
{NULL, CBM_SVC_NONE, NULL},
|
||||
};
|
||||
|
||||
@@ -448,6 +501,11 @@ static const lib_pattern_t graphql_libraries[] = {
|
||||
{"async-graphql", CBM_SVC_GRAPHQL, NULL},
|
||||
{"juniper", CBM_SVC_GRAPHQL, NULL},
|
||||
|
||||
/* Glued-name libraries (see the note in http_libraries). */
|
||||
{"gqlparser", CBM_SVC_GRAPHQL, NULL}, /* Go: vektah/gqlparser */
|
||||
{"gqlgenc", CBM_SVC_GRAPHQL, NULL}, /* Go: gqlgen client generator */
|
||||
{"aiogqlc", CBM_SVC_GRAPHQL, NULL}, /* Python: asyncio GraphQL client */
|
||||
|
||||
{NULL, CBM_SVC_NONE, NULL},
|
||||
};
|
||||
|
||||
@@ -534,17 +592,67 @@ static const method_suffix_t method_suffixes[] = {
|
||||
|
||||
/* ── Matching implementation ───────────────────────────────────── */
|
||||
|
||||
/* Check if any library identifier appears as a substring in the QN.
|
||||
* Case-sensitive: "requests" matches "project.venv.requests.api.get"
|
||||
* but not "Requests". Library names are specific enough to avoid
|
||||
* false positives even with substring matching. */
|
||||
static bool qn_is_lower(char ch) {
|
||||
return ch >= 'a' && ch <= 'z';
|
||||
}
|
||||
|
||||
static bool is_digit_char(char ch) {
|
||||
return ch >= '0' && ch <= '9';
|
||||
}
|
||||
|
||||
static bool qn_is_alnum(char ch) {
|
||||
return qn_is_lower(ch) || is_digit_char(ch) || (ch >= 'A' && ch <= 'Z');
|
||||
}
|
||||
|
||||
/* True when the occurrence of `id` at `hit` sits on identifier boundaries.
|
||||
*
|
||||
* A raw substring match let short ids fire inside unrelated words: "gin."
|
||||
* in "plugin.", "dio" in "studio", "surf" in "surface", "express" in
|
||||
* "expression". Every character that is not an ASCII letter or digit is a
|
||||
* separator ('.', '/', '\\', ':', '_', '-', '$', '@', ...).
|
||||
*
|
||||
* BEFORE: start of string, a separator, an id that itself starts with a
|
||||
* separator ("@trpc/server"), or an id that starts with an
|
||||
* uppercase letter — a capital opens a new CamelCase word whatever
|
||||
* precedes it ("AsyncHttpClient", "IHttpClientFactory",
|
||||
* "NSURLSession"). Rejected: a lowercase/digit-initial id glued to
|
||||
* a letter or digit ("plugin." / "studio" / "myrequests").
|
||||
* AFTER: end of string, a separator, an id that itself ends in a
|
||||
* separator ("gin."), an uppercase letter (CamelCase glue:
|
||||
* "GuzzleHttp", "FeignClient", "KafkaProducer", "kafkaProducer")
|
||||
* or a digit (version suffix: "urllib2", "amqp091-go").
|
||||
* Rejected: a lowercase letter continuing the word ("surface",
|
||||
* "curly", "expression"). */
|
||||
static bool qn_hit_on_boundary(const char *qn, const char *hit, const char *id, size_t id_len) {
|
||||
char first = id[0];
|
||||
char last = id[id_len - 1];
|
||||
if (hit > qn && qn_is_alnum(hit[-1]) && (qn_is_lower(first) || is_digit_char(first))) {
|
||||
return false;
|
||||
}
|
||||
if (qn_is_alnum(last) && qn_is_lower(hit[id_len])) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Check if any library identifier appears in the QN on identifier
|
||||
* boundaries (see qn_hit_on_boundary). Case-sensitive: "requests" matches
|
||||
* "project.venv.requests.api.get" and "svc.requests_get" but neither
|
||||
* "Requests" nor "myrequests". */
|
||||
static const lib_pattern_t *match_qn(const char *qn, const lib_pattern_t *patterns) {
|
||||
if (!qn || !qn[0]) {
|
||||
return NULL;
|
||||
}
|
||||
for (int i = 0; patterns[i].library_id != NULL; i++) {
|
||||
if (strstr(qn, patterns[i].library_id) != NULL) {
|
||||
return &patterns[i];
|
||||
const char *id = patterns[i].library_id;
|
||||
size_t id_len = strlen(id);
|
||||
if (id_len == 0) {
|
||||
continue;
|
||||
}
|
||||
for (const char *hit = strstr(qn, id); hit != NULL; hit = strstr(hit + 1, id)) {
|
||||
if (qn_hit_on_boundary(qn, hit, id, id_len)) {
|
||||
return &patterns[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
@@ -574,10 +682,6 @@ static bool contains_segment(const char *path, const char *segment) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool is_digit_char(char ch) {
|
||||
return ch >= '0' && ch <= '9';
|
||||
}
|
||||
|
||||
static bool has_http_route_marker(const char *path) {
|
||||
if (starts_with_segment(path, "api") || starts_with_segment(path, "apis") ||
|
||||
starts_with_segment(path, "graphql") || starts_with_segment(path, "health") ||
|
||||
@@ -714,6 +818,25 @@ static const char *strip_string_delimiters(const char *literal, char *buf, size_
|
||||
return buf;
|
||||
}
|
||||
|
||||
/* A comment opens with the slash a route opens with, and an argument list
|
||||
* that starts with one handed three Java block comments to the Route pass as
|
||||
* URLs (elasticsearch, 2026-09-16). The wildcard route (slash-star alone) is a
|
||||
* path, so the block-comment shape needs its closing star-slash; a route
|
||||
* literal never holds a line break. */
|
||||
bool cbm_service_pattern_is_comment_text(const char *text) {
|
||||
if (!text || text[0] != '/') {
|
||||
return false;
|
||||
}
|
||||
if (strchr(text, '\n') != NULL || strchr(text, '\r') != NULL) {
|
||||
return true;
|
||||
}
|
||||
size_t n = strlen(text);
|
||||
if (text[1] == '*' && n >= 4 && text[n - 2] == '*' && text[n - 1] == '/') {
|
||||
return true;
|
||||
}
|
||||
return text[1] == '/' && (text[2] == ' ' || text[2] == '\t');
|
||||
}
|
||||
|
||||
bool cbm_service_pattern_is_http_route_literal(const char *literal, const char *callee_name) {
|
||||
char path_buf[1024];
|
||||
const char *path = strip_string_delimiters(literal, path_buf, sizeof(path_buf));
|
||||
@@ -729,6 +852,9 @@ bool cbm_service_pattern_is_http_route_literal(const char *literal, const char *
|
||||
if (path[0] != '/') {
|
||||
return false;
|
||||
}
|
||||
if (cbm_service_pattern_is_comment_text(path)) {
|
||||
return false;
|
||||
}
|
||||
if (callee_is_delimiter_or_filesystem_builder(callee_name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -48,6 +48,12 @@ bool cbm_service_pattern_is_global_fetch(const char *callee_name);
|
||||
* Rejects filesystem paths and non-HTTP string consumers. */
|
||||
bool cbm_service_pattern_is_http_route_literal(const char *literal, const char *callee_name);
|
||||
|
||||
/* True when text that reached a path slot is a source comment rather than a
|
||||
* path: a block comment (slash-star … star-slash), a line comment (slash-slash
|
||||
* followed by a space), or any text with a line break. The wildcard route
|
||||
* (slash-star alone) is a path. */
|
||||
bool cbm_service_pattern_is_comment_text(const char *text);
|
||||
|
||||
/* Per-worker TLS cache for cbm_service_pattern_match results. The
|
||||
* pattern matcher runs once per resolved CALL edge in emit_service_
|
||||
* edge — that's 6 pattern lists × ~30 patterns × strstr per call ≈
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <errno.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <io.h>
|
||||
@@ -1777,6 +1778,10 @@ static int sync_writer_output(FILE *fp) {
|
||||
}
|
||||
|
||||
static int discard_writer_output(write_db_ctx_t *w, int rc) {
|
||||
/* Cleanup runs after the failure that brought us here, and a library
|
||||
* call may set errno even when it succeeds. Carry the reason across it
|
||||
* so the caller can report WHY the publish failed. */
|
||||
int failure_errno = errno;
|
||||
if (w->fp) {
|
||||
(void)fclose(w->fp);
|
||||
w->fp = NULL;
|
||||
@@ -1784,6 +1789,7 @@ static int discard_writer_output(write_db_ctx_t *w, int rc) {
|
||||
if (w->temp_path[0]) {
|
||||
(void)cbm_unlink(w->temp_path);
|
||||
}
|
||||
errno = failure_errno;
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -1792,10 +1798,12 @@ static int publish_writer_output(write_db_ctx_t *w) {
|
||||
return discard_writer_output(w, ERR_WRITE_FAILED);
|
||||
}
|
||||
if (fclose(w->fp) != 0) {
|
||||
int failure_errno = errno;
|
||||
w->fp = NULL;
|
||||
if (w->temp_path[0]) {
|
||||
(void)cbm_unlink(w->temp_path);
|
||||
}
|
||||
errno = failure_errno;
|
||||
return ERR_WRITE_FAILED;
|
||||
}
|
||||
w->fp = NULL;
|
||||
@@ -1803,7 +1811,12 @@ static int publish_writer_output(write_db_ctx_t *w) {
|
||||
return 0;
|
||||
}
|
||||
if (cbm_rename_replace(w->temp_path, w->final_path) != 0) {
|
||||
/* cbm_rename_replace translated the platform error into errno so the
|
||||
* caller can say what denied the publish (#1620). Preserve it across
|
||||
* the cleanup unlink. */
|
||||
int rename_errno = errno;
|
||||
(void)cbm_unlink(w->temp_path);
|
||||
errno = rename_errno;
|
||||
return ERR_WRITE_FAILED;
|
||||
}
|
||||
/* Sidecars are removed only after the replacement succeeds. On POSIX,
|
||||
@@ -2303,13 +2316,22 @@ cbm_db_writer_t *cbm_writer_open(const char *path) {
|
||||
int n = snprintf(w->wc.final_path, sizeof(w->wc.final_path), "%s", path);
|
||||
if (n < 0 || (size_t)n >= sizeof(w->wc.final_path) ||
|
||||
make_writer_temp_path(path, w, w->wc.temp_path, sizeof(w->wc.temp_path)) != 0) {
|
||||
/* Both conditions are truncation and neither sets errno; name the
|
||||
* reason rather than let the caller report a stale one. */
|
||||
free(w);
|
||||
errno = ENAMETOOLONG;
|
||||
return NULL;
|
||||
}
|
||||
FILE *fp = cbm_fopen(w->wc.temp_path, "wb");
|
||||
if (!fp) {
|
||||
/* The cleanup below unlinks a file that was never created, so it
|
||||
* fails and leaves ENOENT behind — which reads as a missing path
|
||||
* when the real answer is that the directory refused the create.
|
||||
* That is the #1620 case, so carry the open's reason across it. */
|
||||
int open_errno = errno;
|
||||
(void)cbm_unlink(w->wc.temp_path);
|
||||
free(w);
|
||||
errno = open_errno;
|
||||
return NULL;
|
||||
}
|
||||
w->wc.fp = fp;
|
||||
@@ -2377,6 +2399,10 @@ int cbm_writer_finalize(cbm_db_writer_t *w, const char *project, const char *roo
|
||||
write_db_ctx_t wc = w->wc; /* value copy survives free(w) */
|
||||
free(w);
|
||||
if (err != 0) {
|
||||
/* A sticky append failure: errno belongs to whatever call failed
|
||||
* many calls ago, not to the publish. Clear it so the caller does
|
||||
* not attach a reason this path does not have. */
|
||||
errno = 0;
|
||||
return discard_writer_output(&wc, err);
|
||||
}
|
||||
return write_db_after_nodes(&wc, nodes_root);
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@
|
||||
|
||||
**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. This npm wrapper downloads, verifies, and caches the selected native runtime set: the executable, its authenticated integration asset, and—when requested—the content-addressed UI pack.
|
||||
|
||||
High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across 162 languages — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 15 MCP tools. No hosted service or API key; this package requires Node.js to manage and launch the cached native runtime set. Plug and play across 45 automatic/conditional client surfaces.
|
||||
High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across 162 languages — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 17 MCP tools. No hosted service or API key; this package requires Node.js to manage and launch the cached native runtime set. Plug and play across 45 automatic/conditional client surfaces.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -38,7 +38,7 @@ Restart your agent. Say **"Index this project"** — done.
|
||||
- **Lifecycle hooks stay conservative** — Kimi uses `UserPromptSubmit`; on macOS/Linux, GitLab Duo gets a fail-open user `SessionStart`, while Devin gets `UserPromptSubmit`, `PostCompaction`, and a deduplicated `SessionStart` when Claude does not already provide it. Qoder, GitLab Duo, Devin, and Factory hooks are withheld on Windows without a documented shell/executor contract. Cline's auto-activating file hooks are withheld because their context output is not reliably consumed, CodeBuddy beta hooks are not auto-installed, and Cursor context hooks remain withheld.
|
||||
- **Subagent access is explicit** — Claude, Gemini, Kiro, Qwen, CodeBuddy, KiloCode, Mistral Vibe, Grok Build, Qoder, Junie, and Factory get documented graph profiles with the narrowest tool/server filters their schemas support. KiloCode and Vibe enumerate read-only query tools rather than using server wildcards. Cursor, Rovo, Pochi, and Cline use explicit parent handoff where child MCP is unavailable or unsafe; IBM Bob receives no invented hook or agent.
|
||||
- **Manual, UI, cloud, or repository-managed (not counted)** — Qodo, Warp MCP, JetBrains AI/ACP, GitHub Copilot coding agent, Jules, CodeRabbit, Replit, BLACKBOX AI, Plandex, and SWE-agent. Warp is counted above for its detected skill installation; its MCP connection remains manual.
|
||||
- **15 MCP tools** — search, trace, architecture, impact analysis, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
|
||||
- **17 MCP tools** — search, trace, architecture, impact analysis, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
|
||||
@@ -17,4 +17,13 @@ echo "pre-commit: security audit (source-level)..."
|
||||
scripts/security-audit.sh
|
||||
|
||||
echo "pre-commit: building and running tests..."
|
||||
make -j$(sysctl -n hw.ncpu 2>/dev/null || nproc) -f Makefile.cbm test
|
||||
(
|
||||
# Git exports repository-local variables to hooks. The test suite creates
|
||||
# independent repositories and linked worktrees, so keep the commit's
|
||||
# index and object paths out of those fixtures.
|
||||
while IFS= read -r variable; do
|
||||
unset "$variable"
|
||||
done < <(git rev-parse --local-env-vars)
|
||||
|
||||
make -j"$(sysctl -n hw.ncpu 2>/dev/null || nproc)" -f Makefile.cbm test
|
||||
)
|
||||
@@ -52,7 +52,7 @@ 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 814
|
||||
src/mcp/mcp.c 784
|
||||
src/pipeline/artifact.c 38
|
||||
src/pipeline/fqn.c 23
|
||||
src/pipeline/lsp_resolve.h 4
|
||||
|
||||
@@ -13752,6 +13752,32 @@ static void cli_add_typed(yyjson_mut_doc *out, yyjson_mut_val *obj, const char *
|
||||
arr = yyjson_mut_arr(out);
|
||||
yyjson_mut_obj_add(obj, yyjson_mut_strcpy(out, key), arr);
|
||||
}
|
||||
/* The help prints `--paths <array>`, and a caller who writes the
|
||||
* array literally — `--paths '["lib","t"]'` — used to get ONE element
|
||||
* holding that literal text (2026-09-16 probe: check_index_coverage
|
||||
* reported the fake path `["lib","t"]`). A value that parses as a JSON
|
||||
* array contributes its elements; anything else is one element. */
|
||||
if (have_value && value && value[0] == '[') {
|
||||
yyjson_doc *lit = yyjson_read(value, strlen(value), 0);
|
||||
yyjson_val *lit_root = lit ? yyjson_doc_get_root(lit) : NULL;
|
||||
if (lit_root && yyjson_is_arr(lit_root)) {
|
||||
size_t idx;
|
||||
size_t max;
|
||||
yyjson_val *elem;
|
||||
yyjson_arr_foreach(lit_root, idx, max, elem) {
|
||||
if (yyjson_is_str(elem)) {
|
||||
yyjson_mut_arr_add_strcpy(out, arr, yyjson_get_str(elem));
|
||||
} else {
|
||||
yyjson_mut_arr_add_val(arr, yyjson_val_mut_copy(out, elem));
|
||||
}
|
||||
}
|
||||
yyjson_doc_free(lit);
|
||||
return;
|
||||
}
|
||||
if (lit) {
|
||||
yyjson_doc_free(lit);
|
||||
}
|
||||
}
|
||||
yyjson_mut_arr_add_strcpy(out, arr, have_value ? value : "");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,18 @@ const char *cbm_cli_get_version(void);
|
||||
|
||||
/* ── CLI tool arguments (flags / --args-file / --help) ────────── */
|
||||
|
||||
/* Top-level `cli --help` text printed by run_cli() in src/main.c.
|
||||
* Documents tool-level --format without adding a session-wide flag (#2102). */
|
||||
#define CBM_CLI_USAGE \
|
||||
"Usage: codebase-memory-mcp cli [--quiet] [--progress] [--verbose] [--json] <tool_name> " \
|
||||
"[json_args]\n" \
|
||||
" --quiet Show errors only; cannot combine with --progress or outer --verbose\n" \
|
||||
" --progress Show lifecycle progress even when stderr is redirected\n" \
|
||||
" --verbose Include informational logs (preserves CBM_LOG_LEVEL=debug)\n" \
|
||||
" --json Print the raw MCP result envelope\n" \
|
||||
" Tools that accept format support --format tree|json (default: tree).\n" \
|
||||
" --format json prints payload JSON; outer --json prints the full MCP envelope.\n"
|
||||
|
||||
/* Convert `--flag value` / `--flag=value` / bare-boolean `--flag` arguments for
|
||||
* a tool into a JSON arguments object string, using the tool's input_schema to
|
||||
* type values (string/integer/boolean) and to collect repeated flags into
|
||||
|
||||
+166
-5
@@ -7,6 +7,7 @@
|
||||
|
||||
#include "foundation/constants.h"
|
||||
#include "mcp/mcp.h"
|
||||
#include "yyjson/yyjson.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
@@ -138,6 +139,167 @@ static void emit_header(adapter_sb_t *sb, const char *client) {
|
||||
"// are overwritten; edit outside it, or remove the markers to take ownership.\n");
|
||||
}
|
||||
|
||||
static void append_typebox_type(adapter_sb_t *sb, yyjson_val *val, const char *description,
|
||||
bool include_description) {
|
||||
yyjson_val *type_val = yyjson_obj_get(val, "type");
|
||||
yyjson_val *enum_val = yyjson_obj_get(val, "enum");
|
||||
yyjson_val *items_val = yyjson_obj_get(val, "items");
|
||||
const char *type_str = yyjson_get_str(type_val);
|
||||
|
||||
if (type_str && strcmp(type_str, "string") == 0 && enum_val && yyjson_is_arr(enum_val) &&
|
||||
yyjson_arr_size(enum_val) > 0) {
|
||||
sb_append(sb, "Type.Union([");
|
||||
size_t enum_idx = 0;
|
||||
size_t enum_max = yyjson_arr_size(enum_val);
|
||||
bool first_enum = true;
|
||||
for (enum_idx = 0; enum_idx < enum_max; enum_idx++) {
|
||||
yyjson_val *enum_item = yyjson_arr_get(enum_val, enum_idx);
|
||||
const char *enum_str = yyjson_get_str(enum_item);
|
||||
if (!enum_str) {
|
||||
continue;
|
||||
}
|
||||
if (!first_enum) {
|
||||
sb_append(sb, ", ");
|
||||
}
|
||||
first_enum = false;
|
||||
sb_append(sb, "Type.Literal(");
|
||||
sb_append_js_string(sb, enum_str);
|
||||
sb_append(sb, ")");
|
||||
}
|
||||
if (first_enum) {
|
||||
sb_append(sb, "Type.String()");
|
||||
} else {
|
||||
sb_append(sb, "]");
|
||||
if (include_description && description) {
|
||||
sb_append(sb, ", { description: ");
|
||||
sb_append_js_string(sb, description);
|
||||
sb_append(sb, " }");
|
||||
}
|
||||
sb_append(sb, ")");
|
||||
return;
|
||||
}
|
||||
sb_append(sb, ")");
|
||||
return;
|
||||
}
|
||||
|
||||
const char *typebox_name = "Any";
|
||||
if (type_str && strcmp(type_str, "string") == 0) {
|
||||
typebox_name = "String";
|
||||
} else if (type_str && strcmp(type_str, "integer") == 0) {
|
||||
typebox_name = "Integer";
|
||||
} else if (type_str && strcmp(type_str, "number") == 0) {
|
||||
typebox_name = "Number";
|
||||
} else if (type_str && strcmp(type_str, "boolean") == 0) {
|
||||
typebox_name = "Boolean";
|
||||
}
|
||||
|
||||
if (type_str && strcmp(type_str, "array") == 0) {
|
||||
sb_append(sb, "Type.Array(");
|
||||
if (items_val) {
|
||||
append_typebox_type(sb, items_val, NULL, false);
|
||||
} else {
|
||||
sb_append(sb, "Type.Any()");
|
||||
}
|
||||
if (include_description && description) {
|
||||
sb_append(sb, ", { description: ");
|
||||
sb_append_js_string(sb, description);
|
||||
sb_append(sb, " }");
|
||||
}
|
||||
sb_append(sb, ")");
|
||||
return;
|
||||
}
|
||||
|
||||
sb_append(sb, "Type.");
|
||||
sb_append(sb, typebox_name);
|
||||
sb_append(sb, "(");
|
||||
if (include_description && description) {
|
||||
sb_append(sb, "{ description: ");
|
||||
sb_append_js_string(sb, description);
|
||||
sb_append(sb, " }");
|
||||
}
|
||||
sb_append(sb, ")");
|
||||
}
|
||||
|
||||
static bool typebox_property_is_required(yyjson_val *required, const char *prop_name) {
|
||||
if (!required || !yyjson_is_arr(required)) {
|
||||
return false;
|
||||
}
|
||||
size_t idx = 0;
|
||||
size_t max = yyjson_arr_size(required);
|
||||
for (idx = 0; idx < max; idx++) {
|
||||
const char *required_name = yyjson_get_str(yyjson_arr_get(required, idx));
|
||||
if (required_name && strcmp(required_name, prop_name) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void convert_json_schema_to_typebox(adapter_sb_t *sb, const char *schema_str) {
|
||||
if (!schema_str) {
|
||||
sb_append(sb, "Type.Object({})");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Parse the JSON schema to extract properties and convert to TypeBox */
|
||||
yyjson_doc *doc = yyjson_read(schema_str, strlen(schema_str), 0);
|
||||
if (!doc) {
|
||||
sb_append(sb, "Type.Object({})");
|
||||
return;
|
||||
}
|
||||
|
||||
yyjson_val *root = yyjson_doc_get_root(doc);
|
||||
if (!root) {
|
||||
sb_append(sb, "Type.Object({})");
|
||||
yyjson_doc_free(doc);
|
||||
return;
|
||||
}
|
||||
|
||||
yyjson_val *properties = yyjson_obj_get(root, "properties");
|
||||
yyjson_val *required = yyjson_obj_get(root, "required");
|
||||
if (!properties) {
|
||||
sb_append(sb, "Type.Object({})");
|
||||
yyjson_doc_free(doc);
|
||||
return;
|
||||
}
|
||||
|
||||
sb_append(sb, "Type.Object({\n");
|
||||
|
||||
bool first_prop = true;
|
||||
size_t idx = 0, max = 0;
|
||||
yyjson_val *key = NULL, *val = NULL;
|
||||
|
||||
yyjson_obj_foreach(properties, idx, max, key, val) {
|
||||
const char *prop_name = yyjson_get_str(key);
|
||||
if (!prop_name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!first_prop) {
|
||||
sb_append(sb, ",\n");
|
||||
}
|
||||
first_prop = false;
|
||||
|
||||
sb_append(sb, " ");
|
||||
sb_append(sb, prop_name);
|
||||
sb_append(sb, ": ");
|
||||
|
||||
yyjson_val *description_val = yyjson_obj_get(val, "description");
|
||||
const char *description = yyjson_get_str(description_val);
|
||||
bool is_required = typebox_property_is_required(required, prop_name);
|
||||
if (!is_required) {
|
||||
sb_append(sb, "Type.Optional(");
|
||||
}
|
||||
append_typebox_type(sb, val, description, true);
|
||||
if (!is_required) {
|
||||
sb_append(sb, ")");
|
||||
}
|
||||
}
|
||||
|
||||
sb_append(sb, "\n })");
|
||||
yyjson_doc_free(doc);
|
||||
}
|
||||
|
||||
char *cbm_client_adapter_pi(const char *binary_path) {
|
||||
if (!binary_path || !binary_path[0]) {
|
||||
return NULL;
|
||||
@@ -157,7 +319,8 @@ char *cbm_client_adapter_pi(const char *binary_path) {
|
||||
* (pods CLI) or an old AgentTool arity cannot be mistaken for this file. */
|
||||
sb_append(&sb, "// Target: @earendil-works/pi-coding-agent >= 0.74.0 (verified 0.84.2)\n"
|
||||
"// ToolDefinition.execute(toolCallId, params, signal, onUpdate, ctx)\n");
|
||||
sb_append(&sb, "import { spawn } from 'node:child_process';\n\n");
|
||||
sb_append(&sb, "import { spawn } from 'node:child_process';\n");
|
||||
sb_append(&sb, "import { Type } from 'typebox';\n\n");
|
||||
sb_append(&sb, "const BIN = '");
|
||||
sb_append(&sb, bin);
|
||||
sb_append(&sb, "';\n\n");
|
||||
@@ -224,10 +387,8 @@ char *cbm_client_adapter_pi(const char *binary_path) {
|
||||
sb_append(&sb, ",\n description: ");
|
||||
sb_append_js_string(&sb, description ? description : "");
|
||||
sb_append(&sb, ",\n parameters: ");
|
||||
/* input_schema is compact JSON, which is a valid JavaScript object
|
||||
* literal; embedding it directly keeps the generated module free of a
|
||||
* JSON.parse indirection and of any escaping drift. */
|
||||
sb_append(&sb, schema ? schema : "{}");
|
||||
/* Convert JSON schema to TypeBox format */
|
||||
convert_json_schema_to_typebox(&sb, schema);
|
||||
/* 0.84.2 calls execute(toolCallId, params, signal, onUpdate, ctx).
|
||||
* The previous (args, ctx) shape bound the call id as the MCP args. */
|
||||
sb_append(&sb, ",\n execute: async (toolCallId, params, signal, _onUpdate, ctx) => {\n");
|
||||
|
||||
@@ -5014,8 +5014,107 @@ static void execute_return_clause(cbm_query_t *q, cbm_return_clause_t *ret, bind
|
||||
limit_is_engine_budget);
|
||||
}
|
||||
|
||||
/* ── Planner: seed a single-hop pattern from its selective end ──────────────
|
||||
*
|
||||
* The executor scans pattern node 0 and expands from there. Written as
|
||||
* `MATCH (a)-[:CALLS]->(b) WHERE b.name = '_printk'`, that scans every node
|
||||
* in the store before the filter on `b` can discard any — on an 8.5 M node
|
||||
* kernel graph the query hit the execution-time limit while the anchored
|
||||
* spelling `MATCH (b:Function {name:'_printk'})<-[:CALLS]-(a)` answered in
|
||||
* seconds (2026-09-16 probe). A reader should not have to know which end to
|
||||
* write first: when the far node carries an equality on name/qualified_name,
|
||||
* an inline property, or a label and the near node carries less, the pattern
|
||||
* is walked from the far end with the relationship direction inverted. The
|
||||
* result set is identical; only the enumeration order changes. Restricted to
|
||||
* one single-relationship pattern with an explicit RETURN, and never to an
|
||||
* OPTIONAL MATCH, whose anchor is part of its meaning. */
|
||||
static int cypher_cond_selectivity(const cbm_condition_t *c, const char *var) {
|
||||
if (!c || !c->variable || !var || strcmp(c->variable, var) != 0 || c->negated) {
|
||||
return 0;
|
||||
}
|
||||
if (!c->op || strcmp(c->op, "=") != 0 || !c->property) {
|
||||
return 0;
|
||||
}
|
||||
return (strcmp(c->property, "name") == 0 || strcmp(c->property, "qualified_name") == 0) ? 3 : 2;
|
||||
}
|
||||
|
||||
static int cypher_expr_selectivity(const cbm_expr_t *e, const char *var) {
|
||||
if (!e) {
|
||||
return 0;
|
||||
}
|
||||
if (e->type == EXPR_CONDITION) {
|
||||
return cypher_cond_selectivity(&e->cond, var);
|
||||
}
|
||||
if (e->type == EXPR_AND) {
|
||||
int l = cypher_expr_selectivity(e->left, var);
|
||||
int r = cypher_expr_selectivity(e->right, var);
|
||||
return l > r ? l : r;
|
||||
}
|
||||
return 0; /* OR / NOT / XOR: no single equality to seed from */
|
||||
}
|
||||
|
||||
static int cypher_node_selectivity(const cbm_node_pattern_t *n, const cbm_where_clause_t *w) {
|
||||
int s = 0;
|
||||
for (int i = 0; i < n->prop_count; i++) {
|
||||
const char *k = n->props[i].key;
|
||||
int v = (k && (strcmp(k, "name") == 0 || strcmp(k, "qualified_name") == 0)) ? 3 : 2;
|
||||
if (v > s) {
|
||||
s = v;
|
||||
}
|
||||
}
|
||||
if (w && n->variable) {
|
||||
int v = 0;
|
||||
if (w->root) {
|
||||
v = cypher_expr_selectivity(w->root, n->variable);
|
||||
} else if (!w->op || strcmp(w->op, "AND") == 0) {
|
||||
for (int i = 0; i < w->count; i++) {
|
||||
int c = cypher_cond_selectivity(&w->conditions[i], n->variable);
|
||||
if (c > v) {
|
||||
v = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (v > s) {
|
||||
s = v;
|
||||
}
|
||||
}
|
||||
if (s == 0 && n->label) {
|
||||
s = 1;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
static void cypher_plan_seed_from_selective_end(cbm_query_t *q) {
|
||||
if (!q || q->pattern_count != 1 || !q->ret || (q->pattern_optional && q->pattern_optional[0])) {
|
||||
return;
|
||||
}
|
||||
cbm_pattern_t *p = &q->patterns[0];
|
||||
if (p->rel_count != 1 || p->node_count != 2) {
|
||||
return;
|
||||
}
|
||||
if (cypher_node_selectivity(&p->nodes[1], q->where) <=
|
||||
cypher_node_selectivity(&p->nodes[0], q->where)) {
|
||||
return;
|
||||
}
|
||||
cbm_node_pattern_t tmp = p->nodes[0];
|
||||
p->nodes[0] = p->nodes[1];
|
||||
p->nodes[1] = tmp;
|
||||
cbm_rel_pattern_t *r = &p->rels[0];
|
||||
const char *inverted = NULL;
|
||||
if (r->direction && strcmp(r->direction, "outbound") == 0) {
|
||||
inverted = "inbound";
|
||||
} else if (r->direction && strcmp(r->direction, "inbound") == 0) {
|
||||
inverted = "outbound";
|
||||
}
|
||||
if (inverted) {
|
||||
safe_str_free(&r->direction);
|
||||
r->direction = heap_strdup(inverted);
|
||||
}
|
||||
}
|
||||
|
||||
static int execute_single(cbm_store_t *store, cbm_query_t *q, const char *project, int max_rows,
|
||||
result_builder_t *rb) {
|
||||
cypher_plan_seed_from_selective_end(q);
|
||||
cbm_pattern_t *pat0 = &q->patterns[0];
|
||||
|
||||
/* Step 1: Scan initial nodes */
|
||||
|
||||
+81
-7
@@ -214,6 +214,31 @@ static void ipc_startup_gate_run(void) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
static cbm_daemon_ipc_win_directory_create_hook_fn g_win_directory_create_hook_for_test;
|
||||
static void *g_win_directory_create_hook_context_for_test;
|
||||
#endif
|
||||
|
||||
void cbm_daemon_ipc_win_directory_create_hook_set_for_test(
|
||||
cbm_daemon_ipc_win_directory_create_hook_fn hook, void *context) {
|
||||
#ifdef _WIN32
|
||||
g_win_directory_create_hook_context_for_test = context;
|
||||
g_win_directory_create_hook_for_test = hook;
|
||||
#else
|
||||
(void)hook;
|
||||
(void)context;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
static void ipc_win_directory_create_hook_run(const wchar_t *path) {
|
||||
cbm_daemon_ipc_win_directory_create_hook_fn hook = g_win_directory_create_hook_for_test;
|
||||
if (hook) {
|
||||
hook(path, g_win_directory_create_hook_context_for_test);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
bool cbm_daemon_ipc_windows_legacy_names(const char *canonical_runtime_parent,
|
||||
const char *instance_key,
|
||||
char pipe_out[CBM_DAEMON_IPC_WINDOWS_NAME_CAP],
|
||||
@@ -3994,6 +4019,16 @@ static char *wide_to_utf8(const wchar_t *value) {
|
||||
return utf8;
|
||||
}
|
||||
|
||||
/* Record "<path>: <message>" as the validation detail, with the wide path
|
||||
* rendered as UTF-8. One place owns the conversion buffer, so every refusal on
|
||||
* the directory walk can name its component without each call site carrying
|
||||
* its own allocation. */
|
||||
static void ipc_validation_detail_set_for_path(const wchar_t *path, const char *message) {
|
||||
char *path_utf8 = wide_to_utf8(path);
|
||||
ipc_validation_detail_set("%s: %s", path_utf8 ? path_utf8 : "<path>", message);
|
||||
free(path_utf8);
|
||||
}
|
||||
|
||||
static wchar_t *wide_copy(const wchar_t *value) {
|
||||
if (!value) {
|
||||
return NULL;
|
||||
@@ -4861,13 +4896,28 @@ static bool win_runtime_directory_secure(const wchar_t *runtime_dir) {
|
||||
return false;
|
||||
}
|
||||
bool created = CreateDirectoryW(runtime_dir, &security.directory_attributes) != 0;
|
||||
if (!created && GetLastError() != ERROR_ALREADY_EXISTS) {
|
||||
DWORD create_error = created ? ERROR_SUCCESS : GetLastError();
|
||||
if (!created && create_error != ERROR_ALREADY_EXISTS) {
|
||||
char message[96];
|
||||
(void)snprintf(message, sizeof(message),
|
||||
"could not create the directory (Windows error %lu)",
|
||||
(unsigned long)create_error);
|
||||
ipc_validation_detail_set_for_path(runtime_dir, message);
|
||||
win_security_destroy(&security);
|
||||
return false;
|
||||
}
|
||||
DWORD attributes = GetFileAttributesW(runtime_dir);
|
||||
if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0 ||
|
||||
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
|
||||
/* What already exists at this path is adopted only if it is a plain
|
||||
* directory. Say which rule refused it: the walk in front of this
|
||||
* function tolerates losing a creation race, so this check is what
|
||||
* stands between that tolerance and a planted file or junction. */
|
||||
const char *rule = attributes == INVALID_FILE_ATTRIBUTES ? "cannot be inspected"
|
||||
: (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0
|
||||
? "exists but is not a directory"
|
||||
: "is a reparse point (junction or symlink)";
|
||||
ipc_validation_detail_set_for_path(runtime_dir, rule);
|
||||
win_security_destroy(&security);
|
||||
return false;
|
||||
}
|
||||
@@ -5021,8 +5071,35 @@ static bool win_private_directory_tree_secure(const wchar_t *directory_path) {
|
||||
DWORD attributes = GetFileAttributesW(path);
|
||||
if (attributes == INVALID_FILE_ATTRIBUTES) {
|
||||
DWORD error = GetLastError();
|
||||
ok = (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) &&
|
||||
CreateDirectoryW(path, &security.directory_attributes) != 0;
|
||||
bool absent = error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND;
|
||||
if (absent) {
|
||||
ipc_win_directory_create_hook_run(path);
|
||||
/* Several processes first-starting together all observe
|
||||
* this component absent; one CreateDirectoryW wins and
|
||||
* the rest get ERROR_ALREADY_EXISTS. Losing that race is
|
||||
* not a failure -- the directory this process wanted now
|
||||
* exists, exactly as if it had been there all along. It
|
||||
* is NOT trusted for that: an ancestor still goes through
|
||||
* win_directory_component_secure() below, and the final
|
||||
* component through win_runtime_directory_secure(), which
|
||||
* refuses a non-directory or reparse point and enforces
|
||||
* owner and DACL. The POSIX walk tolerates EEXIST at the
|
||||
* same point for the same reason. */
|
||||
if (CreateDirectoryW(path, &security.directory_attributes) == 0) {
|
||||
error = GetLastError();
|
||||
absent = error == ERROR_ALREADY_EXISTS;
|
||||
}
|
||||
}
|
||||
ok = absent;
|
||||
if (!ok) {
|
||||
/* Never a bare "(endpoint)": name the component and the
|
||||
* Windows error that refused it. */
|
||||
char message[96];
|
||||
(void)snprintf(message, sizeof(message),
|
||||
"could not create or inspect the directory (Windows error %lu)",
|
||||
(unsigned long)error);
|
||||
ipc_validation_detail_set_for_path(path, message);
|
||||
}
|
||||
}
|
||||
/* Ancestors are observe-only and must already be secure. The
|
||||
* final current-user directory is intentionally handled below by
|
||||
@@ -5034,10 +5111,7 @@ static bool win_private_directory_tree_secure(const wchar_t *directory_path) {
|
||||
* at this walk position; the helper set the inner rule. */
|
||||
char inner[384];
|
||||
(void)snprintf(inner, sizeof(inner), "%s", ipc_validation_detail_buffer);
|
||||
char *component_utf8 = wide_to_utf8(path);
|
||||
ipc_validation_detail_set(
|
||||
"%s: %s", component_utf8 ? component_utf8 : "<component>", inner);
|
||||
free(component_utf8);
|
||||
ipc_validation_detail_set_for_path(path, inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,4 +110,15 @@ void cbm_daemon_ipc_posix_record_write_failure_set_for_test(int errno_value);
|
||||
typedef void (*cbm_daemon_ipc_startup_gate_fn)(void *context);
|
||||
void cbm_daemon_ipc_startup_gate_set_for_test(cbm_daemon_ipc_startup_gate_fn gate, void *context);
|
||||
|
||||
/* Deterministic-interleaving seam for the Windows private-directory walk:
|
||||
* fires after a path component was observed ABSENT and before this process
|
||||
* tries to create it. A test plays the concurrent process that wins that
|
||||
* creation, which pins the cold-start race (N processes first-starting
|
||||
* against a runtime directory that does not exist yet) by construction
|
||||
* instead of by thread timing. `path` is the NUL-terminated component path at
|
||||
* the walk position. No-op off Windows. */
|
||||
typedef void (*cbm_daemon_ipc_win_directory_create_hook_fn)(const wchar_t *path, void *context);
|
||||
void cbm_daemon_ipc_win_directory_create_hook_set_for_test(
|
||||
cbm_daemon_ipc_win_directory_create_hook_fn hook, void *context);
|
||||
|
||||
#endif /* CBM_DAEMON_IPC_INTERNAL_H */
|
||||
@@ -2,7 +2,7 @@
|
||||
* compat_thread.c — Portable thread, mutex, and aligned allocation.
|
||||
*
|
||||
* POSIX: thin wrappers around pthreads and posix_memalign.
|
||||
* Windows: CreateThread, CRITICAL_SECTION, _aligned_malloc.
|
||||
* Windows: CreateThread, CRITICAL_SECTION, aligned allocation.
|
||||
*/
|
||||
#include "foundation/mem_events.h"
|
||||
#include "foundation/constants.h"
|
||||
@@ -279,12 +279,20 @@ void cbm_mutex_destroy(cbm_mutex_t *m) {
|
||||
#ifdef _WIN32
|
||||
|
||||
int cbm_aligned_alloc(void **ptr, size_t alignment, size_t size) {
|
||||
#if defined(CBM_MEM_GLOBAL_OVERRIDE) && CBM_MEM_GLOBAL_OVERRIDE
|
||||
*ptr = mi_malloc_aligned(size, alignment);
|
||||
#else
|
||||
*ptr = _aligned_malloc(size, alignment);
|
||||
#endif
|
||||
return *ptr ? 0 : -1;
|
||||
}
|
||||
|
||||
void cbm_aligned_free(void *ptr) {
|
||||
#if defined(CBM_MEM_GLOBAL_OVERRIDE) && CBM_MEM_GLOBAL_OVERRIDE
|
||||
mi_free(ptr);
|
||||
#else
|
||||
_aligned_free(ptr);
|
||||
#endif
|
||||
}
|
||||
|
||||
#else /* POSIX */
|
||||
|
||||
@@ -310,6 +310,33 @@ bool cbm_validate_project_name(const char *name) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int cbm_utf8_trim_partial(char *buf) {
|
||||
if (!buf) {
|
||||
return 0;
|
||||
}
|
||||
int pos = (int)strlen(buf);
|
||||
if (pos == 0) {
|
||||
return 0;
|
||||
}
|
||||
/* Walk back over continuation bytes to the lead byte; drop the sequence
|
||||
* when fewer continuation bytes follow it than its lead byte announces. */
|
||||
int back = pos - 1;
|
||||
int cont = 0;
|
||||
while (back >= 0 && ((unsigned char)buf[back] & 0xC0) == 0x80) {
|
||||
back--;
|
||||
cont++;
|
||||
}
|
||||
if (back >= 0) {
|
||||
unsigned char lead = (unsigned char)buf[back];
|
||||
int need = lead >= 0xF0 ? 3 : lead >= 0xE0 ? 2 : lead >= 0xC0 ? 1 : 0;
|
||||
if (need > cont) {
|
||||
pos = back;
|
||||
buf[pos] = '\0';
|
||||
}
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
int cbm_json_escape(char *buf, int bufsize, const char *src) {
|
||||
if (!buf || bufsize <= 0) {
|
||||
return 0;
|
||||
@@ -319,7 +346,8 @@ int cbm_json_escape(char *buf, int bufsize, const char *src) {
|
||||
return 0;
|
||||
}
|
||||
int pos = 0;
|
||||
for (int i = 0; src[i] && pos < bufsize - JSON_NUL_RESERVE; i++) {
|
||||
int i = 0;
|
||||
for (; src[i] && pos < bufsize - JSON_NUL_RESERVE; i++) {
|
||||
unsigned char c = (unsigned char)src[i];
|
||||
if (c == '"' || c == '\\') {
|
||||
if (pos + JSON_ESC_LEN > bufsize - JSON_NUL_RESERVE) {
|
||||
@@ -356,5 +384,11 @@ int cbm_json_escape(char *buf, int bufsize, const char *src) {
|
||||
}
|
||||
}
|
||||
buf[pos] = '\0';
|
||||
/* A truncated output must never end inside a multibyte UTF-8 sequence: a
|
||||
* callee cut mid-character persisted bytes SQLite cannot decode as text
|
||||
* (2026-09-16 probe: nine CALLS rows across rust, java and typescript). */
|
||||
if (src[i] != '\0') {
|
||||
pos = cbm_utf8_trim_partial(buf);
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
@@ -91,9 +91,16 @@ bool cbm_validate_project_name(const char *name);
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* Drop a trailing INCOMPLETE UTF-8 sequence from a NUL-terminated buffer in
|
||||
* place (a lead byte whose continuation bytes were cut off). Returns the new
|
||||
* length. Complete sequences and ASCII are left untouched. Use after any
|
||||
* byte-count truncation of text that will be stored or serialised. */
|
||||
int cbm_utf8_trim_partial(char *buf);
|
||||
|
||||
/* Escape a string for safe embedding in JSON: escapes " \ and control chars.
|
||||
* Writes into buf (including NUL). Returns number of chars written (excl NUL).
|
||||
* If buf is too small, output is truncated but always NUL-terminated. */
|
||||
* If buf is too small, output is truncated but always NUL-terminated, and it
|
||||
* never ends inside a multibyte UTF-8 sequence. */
|
||||
int cbm_json_escape(char *buf, int bufsize, const char *src);
|
||||
|
||||
#endif /* CBM_STR_UTIL_H */
|
||||
@@ -39,6 +39,7 @@ enum {
|
||||
#include "foundation/mem_core.h"
|
||||
#include <sqlite3.h>
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h> // int64_t
|
||||
#include <stdio.h>
|
||||
@@ -1841,6 +1842,32 @@ static void log_dump_summary(int node_count, int edge_count) {
|
||||
cbm_log_info("gbuf.dump", "nodes", b1, "edges", b2);
|
||||
}
|
||||
|
||||
/* A dump that published nothing gets exactly one signature in the log.
|
||||
* Without it the writer's return code is the only evidence, and it reaches
|
||||
* the user as a generic pipeline failure that blames their repository
|
||||
* (#1620, #2001).
|
||||
*
|
||||
* failure_errno is read by the caller at the point of failure: the value is
|
||||
* only meaningful before the next library call. Zero means the failure did
|
||||
* not originate at the publish boundary — an append that failed many calls
|
||||
* earlier — and the field is omitted rather than claim a reason this record
|
||||
* does not have. */
|
||||
static void log_dump_failed(int rc, int failure_errno, int node_count, int edge_count) {
|
||||
char b1[CBM_SZ_16];
|
||||
char b3[CBM_SZ_16];
|
||||
char b4[CBM_SZ_16];
|
||||
snprintf(b1, sizeof(b1), "%d", rc);
|
||||
snprintf(b3, sizeof(b3), "%d", node_count);
|
||||
snprintf(b4, sizeof(b4), "%d", edge_count);
|
||||
if (failure_errno == 0) {
|
||||
cbm_log_error("gbuf.dump_failed", "rc", b1, "nodes", b3, "edges", b4);
|
||||
return;
|
||||
}
|
||||
char b2[CBM_SZ_16];
|
||||
snprintf(b2, sizeof(b2), "%d", failure_errno);
|
||||
cbm_log_error("gbuf.dump_failed", "rc", b1, "errno", b2, "nodes", b3, "edges", b4);
|
||||
}
|
||||
|
||||
static void free_dump_resources(char **url_paths, char **local_names, int edge_count,
|
||||
CBMDumpEdge *dump_edges, CBMDumpNode *dump_nodes,
|
||||
int64_t *temp_to_final) {
|
||||
@@ -1896,6 +1923,7 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
|
||||
int64_t max_temp_id = gb->next_id;
|
||||
int64_t *temp_to_final = cbm_calloc(CBM_MEM_CLASS_DUMP, (size_t)max_temp_id * sizeof(int64_t));
|
||||
if (!temp_to_final) {
|
||||
log_dump_failed(CBM_NOT_FOUND, errno, 0, 0);
|
||||
return CBM_NOT_FOUND;
|
||||
}
|
||||
|
||||
@@ -1926,6 +1954,7 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
|
||||
* uninitialized budget from ever triggering the free). */
|
||||
cbm_db_writer_t *w = cbm_writer_open(path);
|
||||
if (!w) {
|
||||
log_dump_failed(CBM_NOT_FOUND, errno, node_idx, 0);
|
||||
cbm_free(CBM_MEM_CLASS_DUMP, src_nodes);
|
||||
cbm_free(CBM_MEM_CLASS_DUMP, dump_nodes);
|
||||
cbm_free(CBM_MEM_CLASS_DUMP, temp_to_final);
|
||||
@@ -1980,12 +2009,19 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
|
||||
int frc = cbm_writer_finalize(w, gb->project, gb->root_path, indexed_at, dump_nodes, node_idx,
|
||||
dump_edges, edge_idx, gb->dump_vectors, gb->dump_vector_count,
|
||||
gb->dump_token_vecs, gb->dump_token_vec_count);
|
||||
/* Read errno before anything else can touch it: the profiling macro
|
||||
* below is already one library call away from losing the reason. */
|
||||
int finalize_errno = errno;
|
||||
CBM_PROF_END_N("dump", "6_write_db_finalize", t_finalize, node_idx + edge_idx);
|
||||
if (rc == 0) {
|
||||
rc = frc;
|
||||
}
|
||||
|
||||
log_dump_summary(node_idx, edge_idx);
|
||||
if (rc != 0) {
|
||||
log_dump_failed(rc, finalize_errno, node_idx, edge_idx);
|
||||
} else {
|
||||
log_dump_summary(node_idx, edge_idx);
|
||||
}
|
||||
free_dump_resources(url_paths, local_names, edge_idx, dump_edges, dump_nodes, temp_to_final);
|
||||
cbm_free(CBM_MEM_CLASS_DUMP, src_nodes);
|
||||
return rc;
|
||||
|
||||
+1
-7
@@ -675,13 +675,7 @@ static bool client_start_parent_watchdog(DWORD initial_ppid) {
|
||||
|
||||
/* ── CLI mode ───────────────────────────────────────────────────── */
|
||||
|
||||
#define CLI_USAGE \
|
||||
"Usage: codebase-memory-mcp cli [--quiet] [--progress] [--verbose] [--json] <tool_name> " \
|
||||
"[json_args]\n" \
|
||||
" --quiet Show errors only; cannot combine with --progress or outer --verbose\n" \
|
||||
" --progress Show lifecycle progress even when stderr is redirected\n" \
|
||||
" --verbose Include informational logs (preserves CBM_LOG_LEVEL=debug)\n" \
|
||||
" --json Print the raw MCP result envelope\n"
|
||||
#define CLI_USAGE CBM_CLI_USAGE /* `cli --help`; wording lives in cli.h (#2102) */
|
||||
|
||||
/* Extract text content from MCP tool result envelope and print it.
|
||||
* MCP results: {"content":[{"type":"text","text":"..."}],"isError":...}
|
||||
|
||||
+61
-42
@@ -63,6 +63,7 @@ enum {
|
||||
#include "cli/cli.h"
|
||||
#include "watcher/watcher.h"
|
||||
#include "foundation/mem.h"
|
||||
#include "foundation/mem_core.h"
|
||||
#include "foundation/diagnostics.h"
|
||||
#include "foundation/platform.h"
|
||||
#include "foundation/compat.h"
|
||||
@@ -3762,6 +3763,8 @@ enum {
|
||||
BM25_BIND_OFFSET = 4,
|
||||
BM25_BIND_INNER = 5,
|
||||
BM25_BIND_FILE = 6,
|
||||
BM25_BIND_LABEL = 7,
|
||||
BM25_BIND_EXACT = 8,
|
||||
BM25_SQL_AUTO_LEN = -1,
|
||||
/* Inner FTS5 candidate cap. SQLite can early-terminate a plain FTS5 query
|
||||
* (no JOIN/WHERE on outer table) of the form:
|
||||
@@ -3878,7 +3881,7 @@ static void bm25_output_rows_free(bm25_output_row_t *rows, int count) {
|
||||
free(rows[i].label);
|
||||
free(rows[i].file_path);
|
||||
}
|
||||
free(rows);
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, rows);
|
||||
}
|
||||
|
||||
static void bm25_lines_str(char *out, size_t size, int start, int end) {
|
||||
@@ -4019,8 +4022,8 @@ static char *bm25_render(const bm25_output_row_t *rows, int returned, int total,
|
||||
* Returns NULL if FTS5 is unavailable or the query produced no usable tokens,
|
||||
* in which case the caller falls back to the regex-based search path. */
|
||||
static char *bm25_search(cbm_store_t *store, const char *project, const char *query,
|
||||
const char *file_pattern, int limit, int offset, bool tree_format,
|
||||
size_t max_output_bytes) {
|
||||
const char *file_pattern, const char *label, int limit, int offset,
|
||||
bool tree_format, size_t max_output_bytes) {
|
||||
sqlite3 *db = cbm_store_get_db(store);
|
||||
if (!db) {
|
||||
return NULL;
|
||||
@@ -4046,9 +4049,18 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu
|
||||
* because no outer predicate blocks it. We fetch BM25_INNER_LIMIT top candidates
|
||||
* from the FTS5 index, then join/filter/boost only those rows. bm25() returns a
|
||||
* NEGATIVE score (lower = more relevant). */
|
||||
/* Exact-name tier (2026-09-16 probe): a definition whose NAME is the query
|
||||
* outranks every partial hit. BM25 term frequency otherwise rewards a long
|
||||
* test-method name that repeats the token — `table references table with
|
||||
* same name` — over the `Table` class itself, and the label tiers below
|
||||
* then push the class's own methods above it (Method 10 > Class 5). The
|
||||
* definition the reader asked for by name comes first; case-insensitive
|
||||
* exact spelling comes next; everything else keeps its BM25 order. */
|
||||
const char *sql =
|
||||
"SELECT n.id, n.label, n.name, n.qualified_name, n.file_path, n.start_line, n.end_line, "
|
||||
" (fts.base_rank "
|
||||
" - CASE WHEN n.name = ?8 THEN 30.0 "
|
||||
" WHEN lower(n.name) = lower(?8) THEN 20.0 ELSE 0.0 END "
|
||||
" - CASE WHEN n.label IN ('Function','Method') THEN 10.0 "
|
||||
" WHEN n.label = 'Route' THEN 8.0 "
|
||||
" WHEN n.label IN (" CBM_SQL_TYPE_LIKE_LABELS ") THEN 5.0 "
|
||||
@@ -4070,6 +4082,10 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu
|
||||
* must be changed together or results desynchronise from counts. */
|
||||
" AND n.label NOT IN ('File','Folder','Variable','Project') "
|
||||
" AND (?6 IS NULL OR n.file_path LIKE ?6) "
|
||||
/* The caller's label filter applies in query mode exactly as it does
|
||||
* in the structural mode (2026-09-16 probe: `label=Class` was ignored
|
||||
* here and five Methods came back). MIRRORED in the count query. */
|
||||
" AND (?7 IS NULL OR n.label = ?7) "
|
||||
/* rank ties are common (boosted floats) — the id tie-break makes
|
||||
* offset pages contractually stable across calls. */
|
||||
"ORDER BY rank, n.id "
|
||||
@@ -4090,6 +4106,12 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu
|
||||
} else {
|
||||
sqlite3_bind_null(stmt, BM25_BIND_FILE);
|
||||
}
|
||||
if (label && label[0]) {
|
||||
sqlite3_bind_text(stmt, BM25_BIND_LABEL, label, BM25_SQL_AUTO_LEN, MCP_SQLITE_TRANSIENT);
|
||||
} else {
|
||||
sqlite3_bind_null(stmt, BM25_BIND_LABEL);
|
||||
}
|
||||
sqlite3_bind_text(stmt, BM25_BIND_EXACT, query, BM25_SQL_AUTO_LEN, MCP_SQLITE_TRANSIENT);
|
||||
|
||||
/* Count hits within the same inner-limit window — capped at BM25_INNER_LIMIT.
|
||||
* Uses the identical subquery structure so the FTS5 early-exit applies here too. */
|
||||
@@ -4107,6 +4129,7 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu
|
||||
* not describe the rows returned. */
|
||||
" AND n.label NOT IN ('File','Folder','Variable','Project')"
|
||||
" AND (?6 IS NULL OR n.file_path LIKE ?6)"
|
||||
" AND (?7 IS NULL OR n.label = ?7)"
|
||||
")";
|
||||
sqlite3_stmt *cs = NULL;
|
||||
if (sqlite3_prepare_v2(db, count_sql, BM25_SQL_AUTO_LEN, &cs, NULL) == SQLITE_OK) {
|
||||
@@ -4121,6 +4144,12 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu
|
||||
} else {
|
||||
sqlite3_bind_null(cs, BM25_BIND_FILE);
|
||||
}
|
||||
if (label && label[0]) {
|
||||
sqlite3_bind_text(cs, BM25_BIND_LABEL, label, BM25_SQL_AUTO_LEN,
|
||||
MCP_SQLITE_TRANSIENT);
|
||||
} else {
|
||||
sqlite3_bind_null(cs, BM25_BIND_LABEL);
|
||||
}
|
||||
if (sqlite3_step(cs) == SQLITE_ROW) {
|
||||
total = sqlite3_column_int(cs, 0);
|
||||
}
|
||||
@@ -4149,14 +4178,15 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu
|
||||
}
|
||||
|
||||
int row_cap = limit > 0 ? limit : BM25_DEFAULT_LIMIT;
|
||||
bm25_output_row_t *rows = calloc((size_t)row_cap, sizeof(*rows));
|
||||
bm25_output_row_t *rows =
|
||||
(bm25_output_row_t *)cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)row_cap * sizeof(*rows));
|
||||
int row_count = 0;
|
||||
while (rows && row_count < row_cap && sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
const char *qn = (const char *)sqlite3_column_text(stmt, BM25_COL_QN);
|
||||
const char *label = (const char *)sqlite3_column_text(stmt, BM25_COL_LABEL);
|
||||
const char *row_label = (const char *)sqlite3_column_text(stmt, BM25_COL_LABEL);
|
||||
const char *file = (const char *)sqlite3_column_text(stmt, BM25_COL_FILE);
|
||||
rows[row_count].qualified_name = heap_strdup(qn ? qn : "");
|
||||
rows[row_count].label = heap_strdup(label ? label : "");
|
||||
rows[row_count].label = heap_strdup(row_label ? row_label : "");
|
||||
rows[row_count].file_path = heap_strdup(file ? file : "");
|
||||
rows[row_count].start_line = sqlite3_column_int(stmt, BM25_COL_START);
|
||||
rows[row_count].end_line = sqlite3_column_int(stmt, BM25_COL_END);
|
||||
@@ -5089,9 +5119,11 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
|
||||
}
|
||||
if (query && query[0]) {
|
||||
char *q_file_pattern = cbm_mcp_get_string_arg(args, "file_pattern");
|
||||
char *bm25_json = bm25_search(store, project, query, q_file_pattern, limit, offset,
|
||||
char *q_label = cbm_mcp_get_string_arg(args, "label");
|
||||
char *bm25_json = bm25_search(store, project, query, q_file_pattern, q_label, limit, offset,
|
||||
!json_format, max_output_bytes);
|
||||
free(q_file_pattern);
|
||||
free(q_label);
|
||||
if (bm25_json) {
|
||||
free(query);
|
||||
free(project);
|
||||
@@ -11062,6 +11094,16 @@ static bool project_db_is_servable(const char *project, const char *db_path) {
|
||||
return servable;
|
||||
}
|
||||
|
||||
/* The three heap strings handle_index_repository owns from
|
||||
* cbm_mcp_get_string_arg / resolved_repo_path_from_project_arg. One release
|
||||
* point keeps the dozen early-return paths in step; free(NULL) is a no-op, so
|
||||
* a path may pass NULL for an argument it never obtained. */
|
||||
static void index_args_free(char *repo_path, char *mode_str, char *name_override) {
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
}
|
||||
|
||||
static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
char *repo_path = cbm_mcp_get_string_arg(args, "repo_path");
|
||||
char *mode_str = cbm_mcp_get_string_arg(args, "mode");
|
||||
@@ -11074,15 +11116,12 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
}
|
||||
|
||||
if (!repo_path) {
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(NULL, mode_str, name_override);
|
||||
return cbm_mcp_text_result("repo_path is required", true);
|
||||
}
|
||||
|
||||
if (!resolve_session_repo_path(srv, &repo_path)) {
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
free(repo_path);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result("failed to resolve repo_path", true);
|
||||
}
|
||||
|
||||
@@ -11102,26 +11141,20 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
if (repo_path && repo_path[0] &&
|
||||
!cbm_workspace_root_allowed(repo_path, cbm_workspace_home_dir(), cbm_workspace_cache_dir(),
|
||||
allowed_root, boundary_err, sizeof(boundary_err))) {
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
free(repo_path);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result(boundary_err, true);
|
||||
}
|
||||
|
||||
if (mode_str && strcmp(mode_str, "cross-repo-intelligence") == 0) {
|
||||
free(mode_str);
|
||||
char *result = handle_cross_repo_mode(srv, repo_path, name_override, args);
|
||||
free(name_override);
|
||||
free(repo_path);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return result;
|
||||
}
|
||||
|
||||
cbm_index_resource_policy_t resource_policy;
|
||||
char policy_error[CBM_SZ_256] = {0};
|
||||
if (!load_index_policy(srv, args, &resource_policy, policy_error, sizeof(policy_error))) {
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
free(repo_path);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result(policy_error, true);
|
||||
}
|
||||
|
||||
@@ -11133,9 +11166,7 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
worker_args ? srv->index_executor(srv->index_executor_context, repo_path, worker_args)
|
||||
: NULL;
|
||||
free(worker_args);
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return coordinated ? coordinated
|
||||
: cbm_mcp_text_result(
|
||||
"daemon index coordinator could not start the operation", true);
|
||||
@@ -11148,9 +11179,7 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
char *mutation_project =
|
||||
cbm_project_name_from_path(name_override && name_override[0] ? name_override : repo_path);
|
||||
if (!mutation_project) {
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result("could not resolve index project name", true);
|
||||
}
|
||||
|
||||
@@ -11163,24 +11192,18 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
char *worker_args = index_args_with_repo_path(args, repo_path, &resource_policy);
|
||||
if (!worker_args) {
|
||||
free(mutation_project);
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result("failed to prepare supervised index request", true);
|
||||
}
|
||||
char *supervised = index_run_supervised(srv, worker_args);
|
||||
free(worker_args);
|
||||
if (supervised) {
|
||||
free(mutation_project);
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return supervised;
|
||||
}
|
||||
free(mutation_project);
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result(
|
||||
"index supervision failed before a contained worker could start; no "
|
||||
"in-process fallback was attempted",
|
||||
@@ -11189,18 +11212,14 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
|
||||
if (!mcp_project_mutation_begin(srv, mutation_project)) {
|
||||
free(mutation_project);
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result("index operation blocked by another mutation for this project",
|
||||
true);
|
||||
}
|
||||
if (mcp_request_cancelled(srv)) {
|
||||
mcp_project_mutation_end(srv, mutation_project);
|
||||
free(mutation_project);
|
||||
free(repo_path);
|
||||
free(mode_str);
|
||||
free(name_override);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result("index operation cancelled for this request", true);
|
||||
}
|
||||
|
||||
|
||||
@@ -626,15 +626,29 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
|
||||
* reintroduce the #592/#606 false-edge class for .ets files. */
|
||||
bool suppress_weak_member = lang == CBM_LANG_PYTHON || lang == CBM_LANG_JAVASCRIPT ||
|
||||
lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX ||
|
||||
lang == CBM_LANG_ARKTS;
|
||||
lang == CBM_LANG_ARKTS ||
|
||||
/* Files whose calls are embedded JS/TS (<script>
|
||||
* bodies): the calls carry the JS receiver flag
|
||||
* but the FILE language gated them out, so
|
||||
* generated Dokka pages bound localStorage.getItem
|
||||
* to a docs bundle (2026-09-16 probe: 4,207 junk
|
||||
* edges on JetBrains/Exposed). */
|
||||
lang == CBM_LANG_HTML || lang == CBM_LANG_VUE ||
|
||||
lang == CBM_LANG_SVELTE || lang == CBM_LANG_ASTRO;
|
||||
/* Bare-call local-binding suppression. A member call has a receiver the
|
||||
* guard above can reason about; a bare `run()` has none, so that guard
|
||||
* cannot see this class at all. Python-only today because the extraction
|
||||
* flag is set only for Python — this gate MUST match pass_parallel.c's
|
||||
* exactly, for the same divergence reason noted above. */
|
||||
bool suppress_weak_local_binding = lang == CBM_LANG_PYTHON;
|
||||
/* The member guard's one exemption (Python, self/cls-rooted receiver,
|
||||
* unique_name, not a builtin type's method) — see
|
||||
* cbm_weak_member_unique_name_exempt. MUST match pass_parallel.c exactly. */
|
||||
bool drop_plain_call =
|
||||
cbm_suppress_weak_member_match(suppress_weak_member, call->is_method, res.strategy) ||
|
||||
(cbm_suppress_weak_member_match(suppress_weak_member, call->is_method, res.strategy) &&
|
||||
!cbm_weak_member_unique_name_exempt(lang == CBM_LANG_PYTHON,
|
||||
call->receiver_is_self_attribute, call->callee_name,
|
||||
res.strategy)) ||
|
||||
cbm_suppress_weak_local_binding_call(suppress_weak_local_binding,
|
||||
call->callee_is_locally_bound, res.strategy);
|
||||
|
||||
|
||||
@@ -1874,6 +1874,10 @@ typedef struct {
|
||||
static void sanitize_expr(char *expr_buf, const char *expr) {
|
||||
if (expr) {
|
||||
snprintf(expr_buf, 128, "%.*s", 120, expr);
|
||||
/* The 120-byte cut can land inside a multibyte character; a torn
|
||||
* sequence persisted as invalid UTF-8 in edge properties (2026-09-16
|
||||
* probe: rust, java, typescript stores). */
|
||||
cbm_utf8_trim_partial(expr_buf);
|
||||
for (char *p = expr_buf; *p; p++) {
|
||||
if (*p == '"') {
|
||||
*p = '\'';
|
||||
@@ -1960,10 +1964,18 @@ static bool is_path_keyword(const char *keyword) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* A route path is one line that opens with a slash. A block or line comment
|
||||
* opens with a slash too, and an argument list that starts with one used to
|
||||
* hand the comment text to the Route pass (three Java block comments became
|
||||
* Route nodes on elasticsearch, 2026-09-16). */
|
||||
static bool is_route_path_shaped(const char *val) {
|
||||
return val && val[0] == '/' && !cbm_service_pattern_is_comment_text(val);
|
||||
}
|
||||
|
||||
static const char *find_route_path_in_args(const CBMCall *call, const char **out_handler) {
|
||||
*out_handler = NULL;
|
||||
/* 1. First string arg starting with / */
|
||||
if (call->first_string_arg && call->first_string_arg[0] == '/') {
|
||||
if (is_route_path_shaped(call->first_string_arg)) {
|
||||
*out_handler = call->second_arg_name;
|
||||
return call->first_string_arg;
|
||||
}
|
||||
@@ -1972,7 +1984,7 @@ static const char *find_route_path_in_args(const CBMCall *call, const char **out
|
||||
for (int ai = 0; ai < call->arg_count && !found; ai++) {
|
||||
const CBMCallArg *ca = &call->args[ai];
|
||||
const char *val = ca->value ? ca->value : ca->expr;
|
||||
if (!val || val[0] != '/') {
|
||||
if (!is_route_path_shaped(val)) {
|
||||
continue;
|
||||
}
|
||||
if ((ca->keyword && is_path_keyword(ca->keyword)) || (!ca->keyword && ca->index == 0)) {
|
||||
@@ -2931,12 +2943,19 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
|
||||
* note there. ArkTS belongs to the JS/TS family (#1842). */
|
||||
bool suppress_weak_member = lang == CBM_LANG_PYTHON || lang == CBM_LANG_JAVASCRIPT ||
|
||||
lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX ||
|
||||
lang == CBM_LANG_ARKTS;
|
||||
lang == CBM_LANG_ARKTS ||
|
||||
/* embedded-script hosts — see pass_calls.c */
|
||||
lang == CBM_LANG_HTML || lang == CBM_LANG_VUE ||
|
||||
lang == CBM_LANG_SVELTE || lang == CBM_LANG_ASTRO;
|
||||
/* Bare-call local-binding suppression — see the note in pass_calls.c.
|
||||
* This gate MUST stay identical to the one there. */
|
||||
bool suppress_weak_local_binding = lang == CBM_LANG_PYTHON;
|
||||
/* The member guard's one exemption — MUST match pass_calls.c exactly. */
|
||||
bool drop_plain_call =
|
||||
cbm_suppress_weak_member_match(suppress_weak_member, call->is_method, res.strategy) ||
|
||||
(cbm_suppress_weak_member_match(suppress_weak_member, call->is_method, res.strategy) &&
|
||||
!cbm_weak_member_unique_name_exempt(lang == CBM_LANG_PYTHON,
|
||||
call->receiver_is_self_attribute,
|
||||
call->callee_name, res.strategy)) ||
|
||||
cbm_suppress_weak_local_binding_call(suppress_weak_local_binding,
|
||||
call->callee_is_locally_bound, res.strategy);
|
||||
|
||||
|
||||
@@ -1599,6 +1599,49 @@ static bool is_c_family_source(const char *source_rel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Directory depth of a repo-relative path: how many directories sit above it. */
|
||||
static int include_path_depth(const char *path) {
|
||||
int depth = 0;
|
||||
for (const char *p = path; *p; p++) {
|
||||
if (*p == '/' || *p == '\\') {
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
/* Total order among nodes whose file path ends with the include path. The
|
||||
* by-name hits arrive in node-registration order, which under parallel
|
||||
* extraction is the workers' merge order and differs run to run; taking the
|
||||
* first hit made `#include <linux/device.h>` target include/linux/device.h in
|
||||
* one index of the kernel and tools/virtio/linux/device.h in the next (5,821
|
||||
* IMPORTS edges moved, and every CALLS edge resolved through those files'
|
||||
* import maps moved with them). The include names a file, so a File node
|
||||
* outranks a symbol declared in it; among files the least nested path wins
|
||||
* (include/ over tools/virtio/), then the smaller path, then the smaller QN
|
||||
* — a function of the candidate set alone (O9). */
|
||||
static bool include_target_outranks(const cbm_gbuf_node_t *cand, const cbm_gbuf_node_t *best) {
|
||||
if (!best) {
|
||||
return true;
|
||||
}
|
||||
bool cand_file = strcmp(cand->label, "File") == 0;
|
||||
bool best_file = strcmp(best->label, "File") == 0;
|
||||
if (cand_file != best_file) {
|
||||
return cand_file;
|
||||
}
|
||||
int cd = include_path_depth(cand->file_path);
|
||||
int bd = include_path_depth(best->file_path);
|
||||
if (cd != bd) {
|
||||
return cd < bd;
|
||||
}
|
||||
int by_path = strcmp(cand->file_path, best->file_path);
|
||||
if (by_path != 0) {
|
||||
return by_path < 0;
|
||||
}
|
||||
return cand->qualified_name && best->qualified_name &&
|
||||
strcmp(cand->qualified_name, best->qualified_name) < 0;
|
||||
}
|
||||
|
||||
static const cbm_gbuf_node_t *resolve_exact_file_node(const cbm_pipeline_ctx_t *ctx,
|
||||
const char *file_path,
|
||||
const char *source_file_qn) {
|
||||
@@ -1651,18 +1694,12 @@ static const cbm_gbuf_node_t *resolve_exact_file_node(const cbm_pipeline_ctx_t *
|
||||
strcmp(cand->qualified_name, source_file_qn) == 0) {
|
||||
continue;
|
||||
}
|
||||
if (strcmp(cand->label, "File") == 0) {
|
||||
return cand;
|
||||
}
|
||||
if (!best) {
|
||||
if (include_target_outranks(cand, best)) {
|
||||
best = cand;
|
||||
}
|
||||
}
|
||||
if (best) {
|
||||
return best;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
return best;
|
||||
}
|
||||
|
||||
static const cbm_gbuf_node_t *resolve_header_include(const cbm_pipeline_ctx_t *ctx,
|
||||
|
||||
@@ -294,6 +294,20 @@ bool cbm_perl_suppress_generic_match(bool is_perl, bool is_method, const char *c
|
||||
* Pure; unit-tested in test_registry.c. */
|
||||
bool cbm_suppress_weak_member_match(bool enabled, bool is_method, const char *strategy);
|
||||
|
||||
/* True if `name` is a method of a Python builtin type (str/bytes/list/dict/set/
|
||||
* file) or a builtin function seen as an attribute call. A language fact, kept
|
||||
* as a sorted table like the Perl builtins. */
|
||||
bool cbm_python_is_builtin_member(const char *name);
|
||||
|
||||
/* The member guard's exemption: a Python member call whose receiver is an
|
||||
* attribute chain rooted at self/cls (an object the class owns), whose callee has
|
||||
* exactly one project definition (strategy unique_name) and is not a builtin
|
||||
* type's own method keeps its edge. Combine at the call sites as
|
||||
* `suppress && !exempt`; both pass_calls.c and pass_parallel.c must do the same.
|
||||
* Pure; unit-tested in test_registry.c. */
|
||||
bool cbm_weak_member_unique_name_exempt(bool is_python, bool receiver_is_self_attribute,
|
||||
const char *callee_name, const char *strategy);
|
||||
|
||||
/* Bare-call counterpart of the guard above. True when a resolved BARE call edge
|
||||
* binds a callee that is shadowed by an enclosing parameter, and the match came
|
||||
* from a weak short-name strategy — so the edge is fabricated by construction
|
||||
|
||||
+150
-13
@@ -229,6 +229,37 @@ static int candidate_score(const char *candidate_qn, const char *module_qn, int
|
||||
return score;
|
||||
}
|
||||
|
||||
/* Number of '.'-separated segments in a QN: how deeply the definition is
|
||||
* nested (file depth + enclosing types). */
|
||||
static int qn_depth(const char *qn) {
|
||||
int depth = 1;
|
||||
for (const char *p = qn; *p; p++) {
|
||||
if (*p == '.') {
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
/* Total order among candidates that tie on candidate_score. The registry's
|
||||
* by-name bucket is in registration order, which follows the file list; a
|
||||
* tie broken by bucket position made the resolved target a function of
|
||||
* that order (kernel: 632 CALLS edges differed between two indexes of the
|
||||
* same tree, `dev_name` flipping between twenty same-named struct fields
|
||||
* and unresolved, `sg_set_buf` between include/linux and tools/virtio).
|
||||
* The rule: the least nested definition wins (a top-level function over a
|
||||
* same-named member two types deep, include/linux over tools/virtio/linux),
|
||||
* then the lexicographically smaller QN — a pure function of the candidate
|
||||
* set, never of the order it was built in (O9). */
|
||||
static bool candidate_outranks_on_tie(const char *candidate, const char *best) {
|
||||
int cd = qn_depth(candidate);
|
||||
int bd = qn_depth(best);
|
||||
if (cd != bd) {
|
||||
return cd < bd;
|
||||
}
|
||||
return strcmp(candidate, best) < 0;
|
||||
}
|
||||
|
||||
/* Pick candidate with highest composite score (test-deprioritization + namespace
|
||||
* proximity). `is_test_flags` is the candidates' cached test verdicts, or NULL
|
||||
* when the caller has none (a filtered subset carries its own copy). */
|
||||
@@ -239,7 +270,8 @@ static const char *best_by_import_distance(const char **candidates, const uint8_
|
||||
for (int i = 0; i < count; i++) {
|
||||
int score =
|
||||
candidate_score(candidates[i], module_qn, is_test_flags ? (int)is_test_flags[i] : -1);
|
||||
if (score > best_score) {
|
||||
if (score > best_score ||
|
||||
(score == best_score && best && candidate_outranks_on_tie(candidates[i], best))) {
|
||||
best_score = score;
|
||||
best = candidates[i];
|
||||
}
|
||||
@@ -559,6 +591,84 @@ bool cbm_suppress_weak_member_match(bool enabled, bool is_method, const char *st
|
||||
return weak_short_name_strategy(strategy);
|
||||
}
|
||||
|
||||
/* ── Python builtin-type members ─────────────────────────────────────────
|
||||
* Methods of Python's builtin types (str, bytes, list, dict, set, file objects)
|
||||
* plus the builtin functions that appear as attribute calls. Like PERL_BUILTINS
|
||||
* this is a fact about the LANGUAGE, not about corpus fashion: a member call
|
||||
* whose name is a builtin's own method — `parts.extend(...)`, `line.strip()`,
|
||||
* `d.items()` — is that builtin's method whenever the receiver is untyped, so a
|
||||
* project symbol that merely shares the spelling must not bind. MUST stay
|
||||
* sorted ASCII-ascending for bsearch. */
|
||||
static const char *const PYTHON_BUILTIN_MEMBERS[] = {
|
||||
"add", "append", "capitalize",
|
||||
"casefold", "center", "clear",
|
||||
"close", "copy", "count",
|
||||
"decode", "difference", "discard",
|
||||
"encode", "endswith", "expandtabs",
|
||||
"extend", "fileno", "find",
|
||||
"flush", "format", "get",
|
||||
"index", "insert", "intersection",
|
||||
"isalnum", "isalpha", "isdecimal",
|
||||
"isdigit", "isidentifier", "islower",
|
||||
"isnumeric", "isprintable", "isspace",
|
||||
"istitle", "isupper", "issubset",
|
||||
"issuperset", "items", "join",
|
||||
"keys", "ljust", "lower",
|
||||
"lstrip", "partition", "pop",
|
||||
"popitem", "print", "read",
|
||||
"readable", "readline", "readlines",
|
||||
"remove", "replace", "reverse",
|
||||
"rfind", "rindex", "rjust",
|
||||
"rpartition", "rsplit", "rstrip",
|
||||
"seek", "setdefault", "sort",
|
||||
"split", "splitlines", "startswith",
|
||||
"strip", "swapcase", "symmetric_difference",
|
||||
"tell", "title", "truncate",
|
||||
"union", "update", "upper",
|
||||
"values", "writable", "write",
|
||||
"writelines", "zfill",
|
||||
};
|
||||
|
||||
static int python_builtin_member_cmp(const void *key, const void *elem) {
|
||||
return strcmp((const char *)key, *(const char *const *)elem);
|
||||
}
|
||||
|
||||
bool cbm_python_is_builtin_member(const char *name) {
|
||||
if (!name || !name[0]) {
|
||||
return false;
|
||||
}
|
||||
return bsearch(name, PYTHON_BUILTIN_MEMBERS,
|
||||
sizeof(PYTHON_BUILTIN_MEMBERS) / sizeof(PYTHON_BUILTIN_MEMBERS[0]),
|
||||
sizeof(PYTHON_BUILTIN_MEMBERS[0]), python_builtin_member_cmp) != NULL;
|
||||
}
|
||||
|
||||
/* The member guard's one exemption. A Python member call whose receiver could
|
||||
* not be typed still carries real evidence when three facts line up: the callee
|
||||
* name has exactly ONE definition in the whole project (strategy unique_name),
|
||||
* the receiver is an attribute chain rooted at self/cls — an object the class
|
||||
* owns, not a parameter handed in — and the name is not a builtin type's own
|
||||
* method. `self.compiler.apply_converters()` names the only apply_converters in
|
||||
* django and nothing else it could mean exists. Measured on django/django
|
||||
* (v0.10.8 → v0.11.0 A/B, 2026-09-16): the unconditional guard dropped 800 such
|
||||
* self-rooted edges, every sampled one a real call in the source. A bare
|
||||
* parameter receiver (`accelerator.backward()`, #1276's own case) carries no
|
||||
* ownership evidence and stays suppressed, as does every builtin-member name
|
||||
* (`self.parts.extend()`). Python only: the JS/TS family keeps the TS-LSP trade
|
||||
* recorded in the resolution probe. Pure; unit-tested in test_registry.c. */
|
||||
bool cbm_weak_member_unique_name_exempt(bool is_python, bool receiver_is_self_attribute,
|
||||
const char *callee_name, const char *strategy) {
|
||||
if (!is_python || !receiver_is_self_attribute) {
|
||||
return false;
|
||||
}
|
||||
if (!strategy || strcmp(strategy, "unique_name") != 0) {
|
||||
return false;
|
||||
}
|
||||
if (!callee_name || !callee_name[0]) {
|
||||
return false;
|
||||
}
|
||||
return !cbm_python_is_builtin_member(simple_name(callee_name));
|
||||
}
|
||||
|
||||
/* Bare-call counterpart of the member guard above. A Python call `foo()` whose
|
||||
* callee identifier is bound as a parameter of an enclosing scope cannot be the
|
||||
* module-level `foo`: the parameter shadows it for the whole body. Binding such
|
||||
@@ -611,13 +721,30 @@ static const char *path_basename(const char *path) {
|
||||
return slash ? slash + 1 : path;
|
||||
}
|
||||
|
||||
/* Build and configuration languages have no cross-language call semantics: a
|
||||
* Makefile's `$(eval ...)` or a CMake `function(...)` names nothing in a C
|
||||
* file, so a bare-name bind into another language is always a collision
|
||||
* (2026-09-16 probe: kernel Makefile targets bound to `sk_psock.eval`). */
|
||||
static bool build_config_language(CBMLanguage lang) {
|
||||
return lang == CBM_LANG_MAKEFILE || lang == CBM_LANG_CMAKE || lang == CBM_LANG_YAML ||
|
||||
lang == CBM_LANG_TOML || lang == CBM_LANG_JSON || lang == CBM_LANG_INI ||
|
||||
lang == CBM_LANG_DOCKERFILE;
|
||||
}
|
||||
|
||||
bool cbm_suppress_cross_language_suffix_match(CBMLanguage caller_lang, const char *target_file_path,
|
||||
const char *strategy) {
|
||||
/* Two same-named symbols in different languages: suffix_match picks one
|
||||
* winner by import-distance and attaches every bare-name call to it
|
||||
* (#725, Bash/Python main, JS/Python commit). unique_name is the
|
||||
* candidates==1 case (#1572) and is not this guard. */
|
||||
if (!strategy || strcmp(strategy, "suffix_match") != 0) {
|
||||
* candidates==1 case (#1572) and is not this guard — except for a build
|
||||
* or configuration caller, where even a unique match into another
|
||||
* language is a collision by construction. */
|
||||
if (!strategy) {
|
||||
return false;
|
||||
}
|
||||
bool config_caller = build_config_language(caller_lang);
|
||||
if (strcmp(strategy, "suffix_match") != 0 &&
|
||||
!(config_caller && strcmp(strategy, "unique_name") == 0)) {
|
||||
return false;
|
||||
}
|
||||
if (caller_lang == CBM_LANG_COUNT || !target_file_path || !target_file_path[0]) {
|
||||
@@ -1088,27 +1215,37 @@ static bool receiver_chain_admits(const char *callee_name, const char *candidate
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The candidate's parent segment: the one before its final name. */
|
||||
/* The candidate's ancestry: every segment before its final name. */
|
||||
const char *cand_last = strrchr(candidate_qn, '.');
|
||||
if (!cand_last || cand_last == candidate_qn) {
|
||||
return true; /* top-level candidate — no parent to look for */
|
||||
return true; /* top-level candidate — no ancestry to look for */
|
||||
}
|
||||
const char *parent = cand_last;
|
||||
while (parent > candidate_qn && parent[-1] != '.') {
|
||||
parent--;
|
||||
}
|
||||
size_t parent_len = (size_t)(cand_last - parent);
|
||||
|
||||
/* Walk the chain — every segment before the final callee name. A trailing
|
||||
* "()" is dropped so JSONEncoder().encode reads as JSONEncoder. */
|
||||
* "()" is dropped so JSONEncoder().encode reads as JSONEncoder. A chain
|
||||
* segment admits the candidate when it names ANY segment of the candidate's
|
||||
* ancestry, not only the immediate parent: Settings.builder().putList binds
|
||||
* settings.Settings.Builder.putList because Settings owns Builder, and
|
||||
* RequestOptions.DEFAULT.toBuilder().setWarningsHandler binds
|
||||
* RequestOptions.Builder.setWarningsHandler the same way. Measured on
|
||||
* elastic/elasticsearch: the parent-only rule refused 9,473 unique-name
|
||||
* calls, most of them exactly these factory chains into a nested Builder.
|
||||
* A foreign root still finds nothing in the ancestry — Base64.getEncoder
|
||||
* does not admit DocOffsetsCodec.getEncoder, URLSession.shared.data does
|
||||
* not admit PickedFile.data — so the #1893 refusals hold. */
|
||||
for (const char *seg = dotted; seg < last_dot;) {
|
||||
const char *end = strchr(seg, '.');
|
||||
size_t len = (size_t)(end - seg);
|
||||
if (len >= 2 && seg[len - 2] == '(' && seg[len - 1] == ')') {
|
||||
len -= 2; /* an empty "()" — JSONEncoder().encode names JSONEncoder */
|
||||
}
|
||||
if (len == parent_len && strncmp(seg, parent, parent_len) == 0) {
|
||||
return true;
|
||||
for (const char *anc = candidate_qn; anc < cand_last;) {
|
||||
const char *anc_end = strchr(anc, '.');
|
||||
size_t anc_len = (size_t)(anc_end - anc);
|
||||
if (anc_len == len && len > 0 && strncmp(seg, anc, len) == 0) {
|
||||
return true;
|
||||
}
|
||||
anc = anc_end + SKIP_ONE;
|
||||
}
|
||||
seg = end + SKIP_ONE;
|
||||
}
|
||||
|
||||
+70
-2
@@ -76,6 +76,14 @@ typedef struct {
|
||||
uint64_t last_dirty_sig; /* committed dirty-state signature */
|
||||
uint64_t pending_dirty_sig; /* observed at check time */
|
||||
char pending_head[CBM_SZ_128]; /* HEAD observed at check time */
|
||||
/* Consecutive hard index failures (index_fn < 0). A hard error is
|
||||
* usually persistent — a poisoned coordination endpoint, an unreadable
|
||||
* DB — so retrying it at the plain poll interval re-forks a worker that
|
||||
* fails identically, for as long as the daemon lives. #937 deliberately
|
||||
* leaves the baseline uncommitted so the change is never lost; this
|
||||
* decays the retry cadence so "never lost" does not also mean "retried
|
||||
* forever". Reset to 0 by any successful reindex. */
|
||||
int index_failures;
|
||||
/* Hop from root_path up to the repository root ("" when they are the same),
|
||||
* from `rev-parse --show-cdup`. Porcelain paths are repository-relative, so
|
||||
* the signature needs this to stat them. Resolved once at baseline. */
|
||||
@@ -115,6 +123,16 @@ struct cbm_watcher {
|
||||
#define POLL_FILE_STEP 500 /* add 1s per this many files */
|
||||
#define POLL_MAX_MS 60000
|
||||
|
||||
/* Hard index-failure backoff. Doubling per consecutive failure, capped, so a
|
||||
* persistently failing project costs ~12 attempts/hour instead of ~480 while
|
||||
* still recovering on its own within the ceiling once the cause clears. The
|
||||
* shift cap keeps the intermediate value well inside int64 for any interval. */
|
||||
#define INDEX_FAIL_SHIFT_MAX 6
|
||||
#define INDEX_FAIL_CEILING_MS 300000 /* 5 min */
|
||||
/* Log a distinct line once the failures are clearly not transient, so the
|
||||
* daemon log names the stuck project instead of only repeating the warning. */
|
||||
#define INDEX_FAIL_SUSTAINED 10
|
||||
|
||||
/* Stale-root pruning (#286): a watched project whose root directory stays
|
||||
* missing is pruned — its cached DB is deleted and the watch entry removed.
|
||||
* Deletion is destructive (the DB can hold user-authored data such as the
|
||||
@@ -144,6 +162,27 @@ static int64_t now_ns(void) {
|
||||
|
||||
/* ── Adaptive interval ──────────────────────────────────────────── */
|
||||
|
||||
int cbm_watcher_index_backoff_ms(int interval_ms, int consecutive_failures) {
|
||||
if (interval_ms < 0) {
|
||||
interval_ms = 0;
|
||||
}
|
||||
if (consecutive_failures <= 0) {
|
||||
return interval_ms;
|
||||
}
|
||||
int shift =
|
||||
consecutive_failures < INDEX_FAIL_SHIFT_MAX ? consecutive_failures : INDEX_FAIL_SHIFT_MAX;
|
||||
int64_t delay = (int64_t)interval_ms << shift;
|
||||
if (delay > INDEX_FAIL_CEILING_MS) {
|
||||
delay = INDEX_FAIL_CEILING_MS;
|
||||
}
|
||||
/* Backing off must never schedule SOONER than the project's own cadence.
|
||||
* Unreachable today (POLL_MAX_MS < the ceiling), but clamping here keeps
|
||||
* the function monotonic for every input rather than only for the inputs
|
||||
* the current constants can produce — the caller's contract is "a delay
|
||||
* that never shrinks as failures accumulate". */
|
||||
return (int)(delay < interval_ms ? interval_ms : delay);
|
||||
}
|
||||
|
||||
int cbm_watcher_poll_interval_ms(int file_count) {
|
||||
int ms = POLL_BASE_MS + ((file_count / POLL_FILE_STEP) * CBM_MSEC_PER_SEC);
|
||||
if (ms > POLL_MAX_MS) {
|
||||
@@ -1150,6 +1189,17 @@ void cbm_watcher_touch(cbm_watcher_t *w, const char *project_name) {
|
||||
cbm_mutex_unlock(&w->projects_lock);
|
||||
}
|
||||
|
||||
int cbm_watcher_index_failure_count(cbm_watcher_t *w, const char *project_name) {
|
||||
if (!w || !project_name) {
|
||||
return -1;
|
||||
}
|
||||
cbm_mutex_lock(&w->projects_lock);
|
||||
project_state_t *s = cbm_ht_get(w->projects, project_name);
|
||||
int failures = s ? s->index_failures : -1;
|
||||
cbm_mutex_unlock(&w->projects_lock);
|
||||
return failures;
|
||||
}
|
||||
|
||||
int cbm_watcher_watch_count(cbm_watcher_t *w) {
|
||||
if (!w) {
|
||||
return 0;
|
||||
@@ -1449,6 +1499,7 @@ static void poll_project(const char *key, void *val, void *ud) {
|
||||
int rc = ctx->w->index_fn(s->project_name, s->root_path, ctx->w->user_data);
|
||||
if (rc == 0) {
|
||||
ctx->reindexed++;
|
||||
s->index_failures = 0;
|
||||
/* Commit the baselines OBSERVED AT CHECK TIME — the state whose
|
||||
* reindex just succeeded. A commit/edit landing during the
|
||||
* reindex is deliberately not absorbed: the next poll sees it
|
||||
@@ -1467,11 +1518,28 @@ static void poll_project(const char *key, void *val, void *ud) {
|
||||
/* Busy-skip: baseline stays uncommitted, next poll retries. */
|
||||
cbm_log_info("watcher.index.retry", "project", s->project_name);
|
||||
} else {
|
||||
cbm_log_warn("watcher.index.err", "project", s->project_name);
|
||||
/* itoa_buf returns one shared per-thread buffer, so two of them
|
||||
* in one call would print the same value twice. */
|
||||
char rc_text[CBM_SZ_32];
|
||||
char streak_text[CBM_SZ_32];
|
||||
if (s->index_failures < INT_MAX) {
|
||||
s->index_failures++;
|
||||
}
|
||||
snprintf(rc_text, sizeof(rc_text), "%d", rc);
|
||||
snprintf(streak_text, sizeof(streak_text), "%d", s->index_failures);
|
||||
cbm_log_warn("watcher.index.err", "project", s->project_name, "rc", rc_text,
|
||||
"consecutive", streak_text);
|
||||
if (s->index_failures == INDEX_FAIL_SUSTAINED) {
|
||||
cbm_log_warn("watcher.index.sustained_failure", "project", s->project_name,
|
||||
"consecutive", streak_text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s->next_poll_ns = ctx->now + ((int64_t)s->interval_ms * US_PER_MS);
|
||||
/* Failures back off; success and busy-skip keep the adaptive cadence. */
|
||||
s->next_poll_ns =
|
||||
ctx->now +
|
||||
((int64_t)cbm_watcher_index_backoff_ms(s->interval_ms, s->index_failures) * US_PER_MS);
|
||||
}
|
||||
|
||||
/* Callback to snapshot project state pointers into an array. */
|
||||
|
||||
@@ -91,9 +91,53 @@ void cbm_watcher_stop(cbm_watcher_t *w);
|
||||
/* Return the number of projects in the watch list. */
|
||||
int cbm_watcher_watch_count(cbm_watcher_t *w);
|
||||
|
||||
/* Return a watched project's consecutive hard-index-failure count, or -1 when
|
||||
* it is not watched. Exposed so the failure state machine (increment on a
|
||||
* hard error, reset on success) can be asserted directly rather than inferred
|
||||
* from the poll deadline it feeds.
|
||||
*
|
||||
* Memory visibility: this reads under projects_lock, but poll_project WRITES
|
||||
* the counter outside that lock — it runs against a state snapshot taken
|
||||
* while the lock was held, which is the same discipline the other
|
||||
* poll-mutated fields here already follow (last_head, last_dirty_sig,
|
||||
* interval_ms, next_poll_ns, missing_root_count). It is NOT the discipline of
|
||||
* every field: active_git is serialized by projects_lock and registered is an
|
||||
* atomic_bool. Reading concurrently with a live poll is therefore formally a
|
||||
* data race and may observe a stale value; it is a diagnostic and test
|
||||
* accessor, not a synchronisation point.
|
||||
* Single-threaded callers (the tests, and any caller between poll cycles)
|
||||
* always see the current value. Do not build scheduling decisions on it
|
||||
* without first giving the counter atomic accessors. */
|
||||
int cbm_watcher_index_failure_count(cbm_watcher_t *w, const char *project_name);
|
||||
|
||||
/* Return the adaptive poll interval (ms) for a given file count. */
|
||||
int cbm_watcher_poll_interval_ms(int file_count);
|
||||
|
||||
/* Return the delay (ms) before the next index attempt for a project with
|
||||
* `consecutive_failures` consecutive hard index failures. Zero failures
|
||||
* yields `interval_ms` unchanged; each further failure doubles the delay, so
|
||||
* a permanently failing project stops re-forking a worker at the poll cadence
|
||||
* without ever being abandoned.
|
||||
*
|
||||
* Doubling stops at a fixed shift cap, so the delay plateaus at
|
||||
* `interval_ms << INDEX_FAIL_SHIFT_MAX` — which is the ceiling only when
|
||||
* `interval_ms` is large enough to reach it (>= 4688 ms for the current cap
|
||||
* and ceiling). Below that the plateau sits strictly under the ceiling. Every
|
||||
* interval this watcher generates is >= POLL_BASE_MS, so in practice the
|
||||
* ceiling is always reached; the distinction is stated because this is an
|
||||
* exported function and a caller may pass a smaller interval.
|
||||
*
|
||||
* The result is clamped at BOTH ends: never above the ceiling, and never
|
||||
* below `interval_ms`, so backing off can only ever delay the next attempt,
|
||||
* never bring it forward. That lower clamp matters only for an `interval_ms`
|
||||
* already above the ceiling, which the current constants cannot produce
|
||||
* (POLL_MAX_MS < the ceiling) — it is stated because this is an exported
|
||||
* function and the guarantee should hold for any argument a caller passes,
|
||||
* not only for the ones today's constants generate.
|
||||
*
|
||||
* Negative inputs are treated as zero. */
|
||||
int cbm_watcher_index_backoff_ms(int interval_ms, int consecutive_failures);
|
||||
|
||||
/* Classify a stat() errno observed on a watched project root: returns true
|
||||
* only for values that mean the root itself is gone (ENOENT, ENOTDIR) and
|
||||
* may count toward stale-root pruning (#286). Any other failure (EACCES,
|
||||
|
||||
@@ -1174,8 +1174,13 @@ TEST(client_adapter_pi_emits_parameters_and_execute) {
|
||||
ASSERT_NOT_NULL(strstr(js, "result.content"));
|
||||
ASSERT_NULL(strstr(js, "run: (args, ctx)"));
|
||||
ASSERT_NOT_NULL(strstr(js, "parameters:"));
|
||||
/* The registry input_schema is embedded as a JSON object literal. */
|
||||
ASSERT_NOT_NULL(strstr(js, "\"type\":\"object\""));
|
||||
/* TypeBox parameters schema is embedded with Type.Object syntax. */
|
||||
ASSERT_NOT_NULL(strstr(js, "Type.Object("));
|
||||
ASSERT_NOT_NULL(strstr(js, "Type.String("));
|
||||
/* A numeric registry property must remain numeric in the generated schema. */
|
||||
ASSERT_NOT_NULL(strstr(js, "depth: Type.Optional(Type.Integer("));
|
||||
/* TypeBox import should be present. */
|
||||
ASSERT_NOT_NULL(strstr(js, "import { Type } from 'typebox';"));
|
||||
/* Raw JSON output is required so the bridge can parse the MCP result; the
|
||||
* human-readable path would leave `call` with nothing to JSON.parse. */
|
||||
ASSERT_NOT_NULL(strstr(js, "'cli', '--json'"));
|
||||
|
||||
+65
-26
@@ -1837,8 +1837,7 @@ static bool cli_scope_fixture_start(cli_scope_fixture_t *fixture, const char *ta
|
||||
return fixture->client != NULL;
|
||||
}
|
||||
|
||||
static bool cli_scope_host_serving_within(const cli_scope_fixture_t *fixture,
|
||||
uint32_t timeout_ms) {
|
||||
static bool cli_scope_host_serving_within(const cli_scope_fixture_t *fixture, uint32_t timeout_ms) {
|
||||
cbm_daemon_runtime_status_t status = {0};
|
||||
return fixture->endpoint &&
|
||||
cbm_daemon_runtime_request_status(fixture->endpoint, &fixture->identity, timeout_ms,
|
||||
@@ -1994,8 +1993,8 @@ TEST(cli_install_into_host_namespace_still_drains_host_cohort) {
|
||||
: -1;
|
||||
/* Negative probe: see CLI_SCOPE_HOST_DRAINED_PROBE_MS. The drain itself is
|
||||
* asserted positively below via host_exit == CLI_SCOPE_HOST_DRAINED. */
|
||||
bool host_serving = ready && cli_scope_host_serving_within(&fixture,
|
||||
CLI_SCOPE_HOST_DRAINED_PROBE_MS);
|
||||
bool host_serving =
|
||||
ready && cli_scope_host_serving_within(&fixture, CLI_SCOPE_HOST_DRAINED_PROBE_MS);
|
||||
const char *events = read_test_file(activation_log);
|
||||
bool drained_in_log = events && strstr(events, "cohort drained") != NULL &&
|
||||
strstr(events, "\"daemon_active_clients\":1") != NULL;
|
||||
@@ -9384,8 +9383,8 @@ TEST(cli_codex_respects_codex_home) {
|
||||
snprintf(expected_config, sizeof(expected_config), "%s/config.toml", codex_home);
|
||||
yyjson_doc *plan_doc = json ? yyjson_read(json, strlen(json), 0) : NULL;
|
||||
yyjson_val *plan_root = plan_doc ? yyjson_doc_get_root(plan_doc) : NULL;
|
||||
bool plans_config = test_json_string_array_contains(plan_root, "config_files_planned",
|
||||
expected_config);
|
||||
bool plans_config =
|
||||
test_json_string_array_contains(plan_root, "config_files_planned", expected_config);
|
||||
bool plans_instructions = test_json_string_array_contains(
|
||||
plan_root, "instruction_files_planned", expected_instructions);
|
||||
bool plans_cleanup = json && strstr(json, "remove_managed_block_if_present") != NULL;
|
||||
@@ -9441,8 +9440,8 @@ TEST(cli_codex_install_uses_global_activation_pointer_issue1689) {
|
||||
struct stat state;
|
||||
int fresh_rc = cbm_install_agent_configs(tmpdir, binary_path, false, false);
|
||||
char *fresh_agents = read_test_file_alloc(agents_path);
|
||||
bool fresh_pointer_installed = fresh_rc == 0 && fresh_agents &&
|
||||
strcmp(fresh_agents, test_codex_activation_block) == 0;
|
||||
bool fresh_pointer_installed =
|
||||
fresh_rc == 0 && fresh_agents && strcmp(fresh_agents, test_codex_activation_block) == 0;
|
||||
char *config = read_test_file_alloc(config_path);
|
||||
bool other_surfaces_installed =
|
||||
fresh_rc == 0 && config && strstr(config, "[mcp_servers.codebase-memory-mcp]") &&
|
||||
@@ -9463,8 +9462,7 @@ TEST(cli_codex_install_uses_global_activation_pointer_issue1689) {
|
||||
bool unowned_preserved =
|
||||
user_pointer_written > 0 && (size_t)user_pointer_written < sizeof(expected_user_pointer) &&
|
||||
dry_rc == 0 && unowned_rc == 0 && after_dry && after_unowned &&
|
||||
strcmp(after_dry, user_only) == 0 &&
|
||||
strcmp(after_unowned, expected_user_pointer) == 0;
|
||||
strcmp(after_dry, user_only) == 0 && strcmp(after_unowned, expected_user_pointer) == 0;
|
||||
free(after_dry);
|
||||
free(after_unowned);
|
||||
|
||||
@@ -9509,11 +9507,10 @@ TEST(cli_codex_install_uses_global_activation_pointer_issue1689) {
|
||||
int malformed_rc = cbm_install_agent_configs(tmpdir, binary_path, false, false);
|
||||
char *after_malformed = read_test_file_alloc(agents_path);
|
||||
config = read_test_file_alloc(config_path);
|
||||
bool malformed_preserved = malformed_rc != 0 && after_malformed &&
|
||||
strcmp(after_malformed, malformed) == 0 && config &&
|
||||
strstr(config, "[mcp_servers.codebase-memory-mcp]") &&
|
||||
strstr(config, "SessionStart") && stat(skill_path, &state) == 0 &&
|
||||
stat(profile_path, &state) == 0;
|
||||
bool malformed_preserved =
|
||||
malformed_rc != 0 && after_malformed && strcmp(after_malformed, malformed) == 0 && config &&
|
||||
strstr(config, "[mcp_servers.codebase-memory-mcp]") && strstr(config, "SessionStart") &&
|
||||
stat(skill_path, &state) == 0 && stat(profile_path, &state) == 0;
|
||||
free(config);
|
||||
free(after_malformed);
|
||||
|
||||
@@ -9521,8 +9518,8 @@ TEST(cli_codex_install_uses_global_activation_pointer_issue1689) {
|
||||
char *uninstall_argv[] = {"uninstall", "--yes"};
|
||||
int uninstall_rc = cli_test_cmd_uninstall(2, uninstall_argv);
|
||||
char *after_uninstall = read_test_file_alloc(agents_path);
|
||||
bool uninstall_preserved_foreign = uninstall_rc == 0 && after_uninstall &&
|
||||
strcmp(after_uninstall, user_only) == 0;
|
||||
bool uninstall_preserved_foreign =
|
||||
uninstall_rc == 0 && after_uninstall && strcmp(after_uninstall, user_only) == 0;
|
||||
free(after_uninstall);
|
||||
|
||||
restore_test_env("HOME", saved_home);
|
||||
@@ -11803,8 +11800,7 @@ TEST(cli_codex_migrates_to_single_hook_representation) {
|
||||
restore_test_env("PATH", saved_path);
|
||||
restore_test_env("CODEX_HOME", saved_codex);
|
||||
test_rmdir_r(tmpdir);
|
||||
if (!lifecycle_ok || !migrated || !independent_cleanup ||
|
||||
!pointer_only_on_preflight_failure)
|
||||
if (!lifecycle_ok || !migrated || !independent_cleanup || !pointer_only_on_preflight_failure)
|
||||
FAIL("Codex lifecycle preflight must be idempotent, preserve the activation pointer "
|
||||
"contract, and independently clean owned side files");
|
||||
PASS();
|
||||
@@ -11844,8 +11840,7 @@ TEST(cli_codex_pointer_migration_precedes_hook_preflight_issue1689) {
|
||||
test_rmdir_r(tmpdir);
|
||||
FAIL("failed to build expected Codex pointer migration");
|
||||
}
|
||||
if (write_test_file(config_path, ambiguous) != 0 ||
|
||||
write_test_file(agents_path, legacy) != 0) {
|
||||
if (write_test_file(config_path, ambiguous) != 0 || write_test_file(agents_path, legacy) != 0) {
|
||||
test_rmdir_r(tmpdir);
|
||||
FAIL("failed to write Codex cleanup preflight fixture");
|
||||
}
|
||||
@@ -11868,14 +11863,13 @@ TEST(cli_codex_pointer_migration_precedes_hook_preflight_issue1689) {
|
||||
strcmp(config_after_plan, ambiguous) == 0 &&
|
||||
strcmp(agents_after_plan, legacy) == 0;
|
||||
|
||||
int install_rc =
|
||||
cbm_install_agent_configs(tmpdir, "/opt/codebase-memory-mcp", false, false);
|
||||
int install_rc = cbm_install_agent_configs(tmpdir, "/opt/codebase-memory-mcp", false, false);
|
||||
char *config_after_install = read_test_file_alloc(config_path);
|
||||
char *agents_after_install = read_test_file_alloc(agents_path);
|
||||
struct stat state;
|
||||
bool preflight_failed_closed =
|
||||
install_rc != 0 && config_after_install && strcmp(config_after_install, ambiguous) == 0 &&
|
||||
stat(skill_path, &state) != 0 && stat(profile_path, &state) != 0;
|
||||
bool preflight_failed_closed = install_rc != 0 && config_after_install &&
|
||||
strcmp(config_after_install, ambiguous) == 0 &&
|
||||
stat(skill_path, &state) != 0 && stat(profile_path, &state) != 0;
|
||||
bool pointer_migrated =
|
||||
agents_after_install && strcmp(agents_after_install, legacy_migrated) == 0;
|
||||
|
||||
@@ -15206,6 +15200,34 @@ TEST(cli_build_args_json_bare_boolean_issue680) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* An array-typed flag given a JSON array literal — the shape the help's
|
||||
* `<array>` invites — contributes the literal's elements, not one element
|
||||
* holding the literal text (2026-09-16 probe: check_index_coverage reported
|
||||
* the fake path `["lib","t"]`). Repeated plain values still accumulate. */
|
||||
TEST(cli_build_args_json_array_flag_accepts_json_literal) {
|
||||
char *err = NULL;
|
||||
char *argv[] = {"--project", "p", "--paths", "[\"lib\",\"t\"]"};
|
||||
char *json = cbm_cli_build_args_json("check_index_coverage", 4, argv, &err);
|
||||
ASSERT_NOT_NULL(json);
|
||||
ASSERT_NULL(err);
|
||||
ASSERT(strstr(json, "\"paths\":[\"lib\",\"t\"]") != NULL);
|
||||
free(json);
|
||||
|
||||
char *argv2[] = {"--project", "p", "--paths", "lib", "--paths", "t"};
|
||||
json = cbm_cli_build_args_json("check_index_coverage", 6, argv2, &err);
|
||||
ASSERT_NOT_NULL(json);
|
||||
ASSERT(strstr(json, "\"paths\":[\"lib\",\"t\"]") != NULL);
|
||||
free(json);
|
||||
|
||||
/* A value that merely starts with '[' but is not JSON stays one element. */
|
||||
char *argv3[] = {"--project", "p", "--paths", "[weird"};
|
||||
json = cbm_cli_build_args_json("check_index_coverage", 4, argv3, &err);
|
||||
ASSERT_NOT_NULL(json);
|
||||
ASSERT(strstr(json, "\"paths\":[\"[weird\"]") != NULL);
|
||||
free(json);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* An unknown flag for a KNOWN tool must be rejected loudly, not silently
|
||||
* typed as a string and dropped server-side (#997). GF1 eval: `trace_path
|
||||
* --max-depth 1` was accepted, the real --depth stayed at default 3, and
|
||||
@@ -15314,6 +15336,21 @@ TEST(cli_print_tool_help_issue680) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2102: top-level `cli --help` (CLI_USAGE) must point at tool-level
|
||||
* `--format json` and distinguish it from outer `--json`. This is help-only:
|
||||
* the usage synopsis still has no session-wide --format / CBM_CLI_FORMAT. */
|
||||
TEST(cli_usage_points_to_tool_format_json_issue2102) {
|
||||
ASSERT_NOT_NULL(strstr(CBM_CLI_USAGE, "--format tree|json"));
|
||||
ASSERT_NOT_NULL(strstr(CBM_CLI_USAGE, "payload JSON"));
|
||||
ASSERT_NOT_NULL(strstr(CBM_CLI_USAGE, "full MCP envelope"));
|
||||
ASSERT_NOT_NULL(strstr(CBM_CLI_USAGE, "--json Print the raw MCP result envelope"));
|
||||
ASSERT_NOT_NULL(strstr(CBM_CLI_USAGE, "cli [--quiet] [--progress] [--verbose] [--json] "
|
||||
"<tool_name>"));
|
||||
ASSERT_NULL(strstr(CBM_CLI_USAGE, "[--format"));
|
||||
ASSERT_NULL(strstr(CBM_CLI_USAGE, "CBM_CLI_FORMAT"));
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1359: `cli <tool>` with no argument-bearing token used to slurp stdin to EOF
|
||||
* for ANY non-terminal stdin. The ordinary automation caller never sends that
|
||||
* EOF — Node's child_process.spawn defaults to stdio:['pipe','pipe','pipe'] and
|
||||
@@ -16347,12 +16384,14 @@ SUITE(cli) {
|
||||
RUN_TEST(cli_build_args_json_string_flag_issue680);
|
||||
RUN_TEST(cli_build_args_json_integer_flag_issue680);
|
||||
RUN_TEST(cli_build_args_json_bare_boolean_issue680);
|
||||
RUN_TEST(cli_build_args_json_array_flag_accepts_json_literal);
|
||||
RUN_TEST(cli_build_args_json_unknown_flag_rejected);
|
||||
RUN_TEST(cli_build_args_json_repeated_array_issue680);
|
||||
RUN_TEST(cli_build_args_json_kebab_to_snake_issue680);
|
||||
RUN_TEST(cli_build_args_json_key_equals_value_issue680);
|
||||
RUN_TEST(cli_build_args_json_bad_positional_errors_issue680);
|
||||
RUN_TEST(cli_print_tool_help_issue680);
|
||||
RUN_TEST(cli_usage_points_to_tool_format_json_issue2102);
|
||||
|
||||
/* Stdin argument gate (#1359) */
|
||||
RUN_TEST(cli_zero_argument_tool_never_reads_stdin_issue1359);
|
||||
|
||||
@@ -4468,6 +4468,63 @@ TEST(cypher_exec_prop_array_with_internal_commas) {
|
||||
|
||||
/* A string property must not end at an ESCAPED quote: the scan stopped at the
|
||||
* first '"' regardless of a preceding backslash, cutting the value short. */
|
||||
/* Planner (2026-09-16): a single-hop pattern whose FAR node carries the
|
||||
* selective filter is walked from that end. `MATCH (a)-[:CALLS]->(b) WHERE
|
||||
* b.name = 'X'` used to scan every node before the filter on b could act — on
|
||||
* the 8.5 M node kernel graph it hit the execution-time limit while the
|
||||
* anchored spelling answered in seconds. The rows must be the same in every
|
||||
* spelling, including the inline-property and inbound-direction forms, and
|
||||
* the caller-side variable must still bind the right nodes after the swap. */
|
||||
TEST(cypher_single_hop_seeds_from_selective_far_node) {
|
||||
cbm_store_t *s = setup_cypher_store();
|
||||
|
||||
cbm_cypher_result_t where_form = {0};
|
||||
ASSERT_EQ(cbm_cypher_execute(s,
|
||||
"MATCH (a)-[:CALLS]->(b) WHERE b.name = 'ValidateOrder' "
|
||||
"RETURN a.name ORDER BY a.name",
|
||||
"test", 0, &where_form),
|
||||
0);
|
||||
ASSERT_EQ(where_form.row_count, 1);
|
||||
ASSERT_STR_EQ(where_form.rows[0][0], "HandleOrder");
|
||||
cbm_cypher_result_free(&where_form);
|
||||
|
||||
cbm_cypher_result_t inline_form = {0};
|
||||
ASSERT_EQ(cbm_cypher_execute(s,
|
||||
"MATCH (a)-[:CALLS]->(b {name: 'SubmitOrder'}) "
|
||||
"RETURN a.name",
|
||||
"test", 0, &inline_form),
|
||||
0);
|
||||
ASSERT_EQ(inline_form.row_count, 1);
|
||||
ASSERT_STR_EQ(inline_form.rows[0][0], "ValidateOrder");
|
||||
cbm_cypher_result_free(&inline_form);
|
||||
|
||||
/* Inbound spelling: the far node is now the CALLER; direction inverts back. */
|
||||
cbm_cypher_result_t inbound_form = {0};
|
||||
ASSERT_EQ(cbm_cypher_execute(s,
|
||||
"MATCH (callee)<-[:CALLS]-(caller) WHERE caller.name = "
|
||||
"'HandleOrder' RETURN callee.name ORDER BY callee.name",
|
||||
"test", 0, &inbound_form),
|
||||
0);
|
||||
ASSERT_EQ(inbound_form.row_count, 2);
|
||||
ASSERT_STR_EQ(inbound_form.rows[0][0], "LogError");
|
||||
ASSERT_STR_EQ(inbound_form.rows[1][0], "ValidateOrder");
|
||||
cbm_cypher_result_free(&inbound_form);
|
||||
|
||||
/* Count aggregation through the swapped seed. */
|
||||
cbm_cypher_result_t count_form = {0};
|
||||
ASSERT_EQ(cbm_cypher_execute(s,
|
||||
"MATCH (a)-[:CALLS]->(b) WHERE b.name = 'LogError' "
|
||||
"RETURN count(a) AS callers",
|
||||
"test", 0, &count_form),
|
||||
0);
|
||||
ASSERT_EQ(count_form.row_count, 1);
|
||||
ASSERT_STR_EQ(count_form.rows[0][0], "1");
|
||||
cbm_cypher_result_free(&count_form);
|
||||
|
||||
cbm_store_close(s);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(cypher_exec_prop_string_with_escaped_quote) {
|
||||
cbm_store_t *s = cbm_store_open_memory();
|
||||
cbm_store_upsert_project(s, "test", "/tmp/test");
|
||||
@@ -4792,4 +4849,5 @@ SUITE(cypher) {
|
||||
/* Composite property projection (arrays/objects, escaped quotes) */
|
||||
RUN_TEST(cypher_exec_prop_array_with_internal_commas);
|
||||
RUN_TEST(cypher_exec_prop_string_with_escaped_quote);
|
||||
RUN_TEST(cypher_single_hop_seeds_from_selective_far_node);
|
||||
}
|
||||
@@ -882,6 +882,129 @@ TEST(daemon_ipc_windows_private_directory_ace_is_inheritable) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
int calls;
|
||||
bool plant_file; /* false: play a racer that creates the DIRECTORY first */
|
||||
bool planted;
|
||||
} ipc_test_win_create_racer_t;
|
||||
|
||||
/* Plays the concurrent process that wins the creation of a path component the
|
||||
* walk has just observed absent. Runs inside the walk, at the exact point the
|
||||
* race lives, so the interleaving is pinned by construction: no threads, no
|
||||
* timing. */
|
||||
static void ipc_test_win_create_racer(const wchar_t *path, void *context) {
|
||||
ipc_test_win_create_racer_t *racer = context;
|
||||
racer->calls++;
|
||||
if (racer->calls != 1) {
|
||||
return;
|
||||
}
|
||||
if (racer->plant_file) {
|
||||
HANDLE file =
|
||||
CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
racer->planted = file != INVALID_HANDLE_VALUE;
|
||||
if (racer->planted) {
|
||||
(void)CloseHandle(file);
|
||||
}
|
||||
} else {
|
||||
racer->planted = CreateDirectoryW(path, NULL) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Cold-start race (test-windows-guards section_cold_storm, 2026-09-21; the
|
||||
* same thing a user gets when a host launches several MCP servers on its very
|
||||
* first run): N processes first-start against a runtime directory that does
|
||||
* not exist yet. All of them observe the final component absent, one
|
||||
* CreateDirectoryW wins, and every other process gets ERROR_ALREADY_EXISTS.
|
||||
* The walk treated that as a failure and recorded no detail, so the losers
|
||||
* exited with a bare "secure CLI coordination could not be created
|
||||
* (endpoint)". Losing the creation race is not a failure: the directory this
|
||||
* process wanted now exists, and the owner / DACL / not-a-reparse-point checks
|
||||
* that follow are exactly the ones a pre-existing directory gets. The POSIX
|
||||
* walk has always tolerated EEXIST here. */
|
||||
TEST(daemon_ipc_windows_private_directory_survives_lost_creation_race) {
|
||||
char parent[TEST_PATH_CAP] = {0};
|
||||
char cache[TEST_PATH_CAP] = {0};
|
||||
bool paths_ok = false;
|
||||
bool secured = false;
|
||||
bool owner_only = false;
|
||||
ipc_test_win_create_racer_t racer = {0};
|
||||
|
||||
if (ipc_test_parent_new(parent, "win-create-race")) {
|
||||
int written = snprintf(cache, sizeof(cache), "%s/cache", parent);
|
||||
paths_ok = written > 0 && written < (int)sizeof(cache);
|
||||
}
|
||||
if (paths_ok) {
|
||||
cbm_daemon_ipc_win_directory_create_hook_set_for_test(ipc_test_win_create_racer, &racer);
|
||||
secured = cbm_daemon_ipc_private_directory_secure(cache);
|
||||
cbm_daemon_ipc_win_directory_create_hook_set_for_test(NULL, NULL);
|
||||
}
|
||||
if (secured) {
|
||||
/* The racer created the directory with an inherited DACL; the winner's
|
||||
* directory must still end up owner-only, like any adopted one. */
|
||||
PACL dacl = NULL;
|
||||
PSECURITY_DESCRIPTOR descriptor = NULL;
|
||||
ACL_SIZE_INFORMATION information;
|
||||
memset(&information, 0, sizeof(information));
|
||||
if (GetNamedSecurityInfoA(cache, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL,
|
||||
&dacl, NULL, &descriptor) == ERROR_SUCCESS &&
|
||||
dacl &&
|
||||
GetAclInformation(dacl, &information, sizeof(information), AclSizeInformation)) {
|
||||
owner_only = information.AceCount == 1;
|
||||
}
|
||||
if (descriptor) {
|
||||
(void)LocalFree(descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
(void)RemoveDirectoryA(cache);
|
||||
ipc_test_remove_flat_dir(parent);
|
||||
|
||||
ASSERT_TRUE(paths_ok);
|
||||
/* The seam sat on the path and the racer really won: without these two the
|
||||
* test could pass without ever exercising the race. */
|
||||
ASSERT_EQ(racer.calls, 1);
|
||||
ASSERT_TRUE(racer.planted);
|
||||
ASSERT_TRUE(secured);
|
||||
ASSERT_TRUE(owner_only);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The tolerance above must not admit anything: when what appeared at the path
|
||||
* is NOT a directory, the walk still refuses -- and it says why. A bare
|
||||
* "(endpoint)" is what four reporters in #1533/#1574 were left with; every
|
||||
* refusal on this path names the component and the rule. */
|
||||
TEST(daemon_ipc_windows_private_directory_refuses_and_names_a_planted_file) {
|
||||
char parent[TEST_PATH_CAP] = {0};
|
||||
char cache[TEST_PATH_CAP] = {0};
|
||||
char detail[512] = {0};
|
||||
bool paths_ok = false;
|
||||
bool refused = false;
|
||||
ipc_test_win_create_racer_t racer = {.plant_file = true};
|
||||
|
||||
if (ipc_test_parent_new(parent, "win-create-race-file")) {
|
||||
int written = snprintf(cache, sizeof(cache), "%s/cache", parent);
|
||||
paths_ok = written > 0 && written < (int)sizeof(cache);
|
||||
}
|
||||
if (paths_ok) {
|
||||
cbm_daemon_ipc_win_directory_create_hook_set_for_test(ipc_test_win_create_racer, &racer);
|
||||
refused = !cbm_daemon_ipc_private_directory_secure(cache);
|
||||
cbm_daemon_ipc_win_directory_create_hook_set_for_test(NULL, NULL);
|
||||
const char *why = cbm_daemon_ipc_validation_detail();
|
||||
(void)snprintf(detail, sizeof(detail), "%s", why ? why : "");
|
||||
}
|
||||
|
||||
(void)DeleteFileA(cache);
|
||||
ipc_test_remove_flat_dir(parent);
|
||||
|
||||
ASSERT_TRUE(paths_ok);
|
||||
ASSERT_EQ(racer.calls, 1);
|
||||
ASSERT_TRUE(racer.planted);
|
||||
ASSERT_TRUE(refused);
|
||||
ASSERT_NOT_NULL(strstr(detail, "cache"));
|
||||
ASSERT_NOT_NULL(strstr(detail, "not a directory"));
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(daemon_ipc_windows_private_directory_allows_add_subdirectory_only_ancestor) {
|
||||
char parent[TEST_PATH_CAP] = {0};
|
||||
char add_only[TEST_PATH_CAP] = {0};
|
||||
@@ -5361,6 +5484,8 @@ SUITE(daemon_ipc) {
|
||||
RUN_TEST(daemon_ipc_windows_default_endpoint_ignores_temp_environment);
|
||||
RUN_TEST(daemon_ipc_windows_private_directory_rejects_untrusted_ancestor_acl);
|
||||
RUN_TEST(daemon_ipc_windows_private_directory_ace_is_inheritable);
|
||||
RUN_TEST(daemon_ipc_windows_private_directory_survives_lost_creation_race);
|
||||
RUN_TEST(daemon_ipc_windows_private_directory_refuses_and_names_a_planted_file);
|
||||
RUN_TEST(daemon_ipc_windows_private_directory_allows_add_subdirectory_only_ancestor);
|
||||
RUN_TEST(daemon_ipc_windows_sid_trust_accepts_local_admin_rejects_foreign_500);
|
||||
RUN_TEST(daemon_ipc_windows_legacy_bridge_covers_handoff_and_lifetime);
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include "foundation/compat_thread.h"
|
||||
#include "foundation/log.h"
|
||||
#include "foundation/platform.h"
|
||||
#include "foundation/sanitized.h"
|
||||
#include "pipeline/pipeline.h"
|
||||
#include "store/store.h"
|
||||
|
||||
@@ -3676,10 +3677,18 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_oth
|
||||
SKIP_PLATFORM("requires a queryable copied process image");
|
||||
#else
|
||||
enum {
|
||||
#if CBM_SANITIZED
|
||||
/* This readiness wait is a liveness backstop, not the behavior under
|
||||
* test. The copied instrumented runner can take several seconds to
|
||||
* reach main on macOS, especially while the parallel gate is busy. */
|
||||
CHILD_READY_BOUND_MS = 60000,
|
||||
REQUEST_TIMEOUT_MS = 90000,
|
||||
#else
|
||||
CHILD_READY_BOUND_MS = 5000,
|
||||
REQUEST_TIMEOUT_MS = 15000,
|
||||
#endif
|
||||
CHILD_CANCEL_BOUND_MS = 3000,
|
||||
CHILD_CLEANUP_BOUND_MS = 5000,
|
||||
REQUEST_TIMEOUT_MS = 15000,
|
||||
};
|
||||
const char *old_cache = getenv("CBM_CACHE_DIR");
|
||||
const char *old_path = getenv("PATH");
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "test_framework.h"
|
||||
#include "cbm.h"
|
||||
#include "foundation/constants.h" /* CBM_SZ_* */
|
||||
#include "preprocessor.h" /* cbm_export_macro_candidates (#1989) */
|
||||
#include "../src/foundation/compat.h" /* cbm_clock_gettime (wide-flat scaling guard) */
|
||||
#include "../src/foundation/compat_fs.h"
|
||||
#include <time.h>
|
||||
@@ -976,6 +977,65 @@ TEST(c_struct) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* return_type of the first definition named `name`; NULL when there is no such
|
||||
* definition or it carries no return type. */
|
||||
static const char *def_return_type(CBMFileResult *r, const char *name) {
|
||||
for (int i = 0; i < r->defs.count; i++) {
|
||||
if (strcmp(r->defs.items[i].name, name) == 0) {
|
||||
return r->defs.items[i].return_type;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* PR #1245: the C grammar splits a declared return type across the `type` node,
|
||||
* sibling type_qualifier nodes and the pointer_declarator chain wrapping the
|
||||
* function declarator. Taking only the `type` node published `const char *` as
|
||||
* "char". Canonical spelling: qualifiers, base type, one space, then the
|
||||
* declarator markers unspaced (`const char *`, `char **`). */
|
||||
TEST(c_function_return_type_preserves_pointer_and_qualifier) {
|
||||
CBMFileResult *r = extract("static const char *text_end(const char *text) { return text; }\n"
|
||||
"char **table(void) { return 0; }\n"
|
||||
"char const *east_const(void) { return 0; }\n"
|
||||
"const struct Point *find_point(void) { return 0; }\n"
|
||||
"volatile unsigned long *reg(void) { return 0; }\n"
|
||||
"char *const *frozen(void) { return 0; }\n",
|
||||
CBM_LANG_C, "t", "returns.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT_STR_EQ(def_return_type(r, "text_end"), "const char *");
|
||||
ASSERT_STR_EQ(def_return_type(r, "table"), "char **");
|
||||
ASSERT_STR_EQ(def_return_type(r, "east_const"), "const char *");
|
||||
ASSERT_STR_EQ(def_return_type(r, "find_point"), "const struct Point *");
|
||||
ASSERT_STR_EQ(def_return_type(r, "reg"), "volatile unsigned long *");
|
||||
ASSERT_STR_EQ(def_return_type(r, "frozen"), "char *const *");
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Guard for the fix above: a return type with no qualifier and no declarator
|
||||
* marker is already correct and must come out byte-identical. */
|
||||
TEST(c_function_return_type_plain_unchanged) {
|
||||
CBMFileResult *r = extract("int scalar(void) { return 0; }\n"
|
||||
"void nothing(void) {}\n"
|
||||
"unsigned long wide(void) { return 0; }\n"
|
||||
"struct Point make_point(void) { struct Point p; return p; }\n"
|
||||
"static inline size_t count(void) { return 0; }\n"
|
||||
"_Noreturn void die(void) { for (;;) {} }\n",
|
||||
CBM_LANG_C, "t", "plain.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT_STR_EQ(def_return_type(r, "scalar"), "int");
|
||||
ASSERT_STR_EQ(def_return_type(r, "nothing"), "void");
|
||||
ASSERT_STR_EQ(def_return_type(r, "wide"), "unsigned long");
|
||||
ASSERT_STR_EQ(def_return_type(r, "make_point"), "struct Point");
|
||||
ASSERT_STR_EQ(def_return_type(r, "count"), "size_t");
|
||||
/* _Noreturn parses as a type_qualifier but is not part of the type. */
|
||||
ASSERT_STR_EQ(def_return_type(r, "die"), "void");
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* --- C++ --- */
|
||||
TEST(cpp_class) {
|
||||
CBMFileResult *r = extract(
|
||||
@@ -989,6 +1049,42 @@ TEST(cpp_class) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* PR #1245, C++ side: in-class methods go through a separate extraction path
|
||||
* from free functions, and C++ adds reference markers (`&`, `&&`) whose
|
||||
* reference_declarator carries no `declarator` field. */
|
||||
TEST(cpp_method_return_type_preserves_pointer_and_qualifier) {
|
||||
CBMFileResult *r = extract("class Text {\n"
|
||||
"public:\n"
|
||||
" const char *end() { return nullptr; }\n"
|
||||
" char **table() { return nullptr; }\n"
|
||||
" Text &self() { return *this; }\n"
|
||||
" const Text &cself() const { return *this; }\n"
|
||||
" Text *&slot() { return next_; }\n"
|
||||
" Text *next_;\n"
|
||||
" int width() const { return 0; }\n"
|
||||
" constexpr int square(int x) const { return x * x; }\n"
|
||||
"};\n"
|
||||
"const Text &shared() { static Text t; return t; }\n"
|
||||
"Text &&moved(Text &t) { return static_cast<Text &&>(t); }\n"
|
||||
"const char *Text::c_str() const { return nullptr; }\n",
|
||||
CBM_LANG_CPP, "t", "text.cpp");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT_STR_EQ(def_return_type(r, "end"), "const char *");
|
||||
ASSERT_STR_EQ(def_return_type(r, "table"), "char **");
|
||||
ASSERT_STR_EQ(def_return_type(r, "self"), "Text &");
|
||||
ASSERT_STR_EQ(def_return_type(r, "cself"), "const Text &");
|
||||
ASSERT_STR_EQ(def_return_type(r, "slot"), "Text *&");
|
||||
ASSERT_STR_EQ(def_return_type(r, "width"), "int");
|
||||
/* constexpr parses as a type_qualifier but is not part of the type. */
|
||||
ASSERT_STR_EQ(def_return_type(r, "square"), "int");
|
||||
ASSERT_STR_EQ(def_return_type(r, "shared"), "const Text &");
|
||||
ASSERT_STR_EQ(def_return_type(r, "moved"), "Text &&");
|
||||
ASSERT_STR_EQ(def_return_type(r, "c_str"), "const char *");
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════
|
||||
* Group C: Scripting / Dynamic Languages
|
||||
* ═══════════════════════════════════════════════════════════════════ */
|
||||
@@ -2940,6 +3036,106 @@ TEST(commonlisp_defmacro) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* 2026-09-16 probe: config extractors handed multi-line node text over as a
|
||||
* name (8,301 elasticsearch YAML Fields, 91 kernel Makefile/.conf nodes with a
|
||||
* line break inside), and JS/TS baselines named functions `{}` and variables
|
||||
* `1`. The definition push is the one place every extractor goes through. */
|
||||
TEST(defs_push_cuts_multiline_names_and_rejects_js_literal_names) {
|
||||
CBMArena a;
|
||||
cbm_arena_init(&a);
|
||||
CBMDefArray defs = {0};
|
||||
|
||||
CBMDefinition make = {0};
|
||||
make.name = "endif\n\n$(obj)/pm_data-offsets.h";
|
||||
make.qualified_name = "proj.arch.arm.mach-at91.Makefile.endif\n\n$(obj)/pm_data-offsets.h";
|
||||
make.label = "Function";
|
||||
make.file_path = "arch/arm/mach-at91/Makefile";
|
||||
cbm_defs_push(&defs, &a, make);
|
||||
ASSERT_EQ(defs.count, 1);
|
||||
ASSERT_STR_EQ(defs.items[0].name, "endif");
|
||||
ASSERT_STR_EQ(defs.items[0].qualified_name, "proj.arch.arm.mach-at91.Makefile.endif");
|
||||
|
||||
CBMDefinition yaml = {0};
|
||||
yaml.name = "Test get datafeed stats given missing datafeed_id \r\n - do:";
|
||||
yaml.qualified_name =
|
||||
"proj.spec.Test get datafeed stats given missing datafeed_id \r\n - do:";
|
||||
yaml.label = "Field";
|
||||
yaml.file_path = "rest-api-spec/test/ml/get_datafeed_stats.yml";
|
||||
cbm_defs_push(&defs, &a, yaml);
|
||||
ASSERT_EQ(defs.count, 2);
|
||||
ASSERT_STR_EQ(defs.items[1].name, "Test get datafeed stats given missing datafeed_id");
|
||||
|
||||
/* JS/TS: a literal token is not a name. */
|
||||
CBMDefinition brace = {0};
|
||||
brace.name = "{}";
|
||||
brace.qualified_name = "proj.tests.baselines.x.{}";
|
||||
brace.label = "Function";
|
||||
brace.file_path = "tests/baselines/reference/x.js";
|
||||
cbm_defs_push(&defs, &a, brace);
|
||||
CBMDefinition one = {0};
|
||||
one.name = "1";
|
||||
one.qualified_name = "proj.tests.cases.y.1";
|
||||
one.label = "Variable";
|
||||
one.file_path = "tests/cases/y.ts";
|
||||
cbm_defs_push(&defs, &a, one);
|
||||
ASSERT_EQ(defs.count, 2);
|
||||
|
||||
/* Real JS names, including private members and `$`-prefixed ones, stay. */
|
||||
CBMDefinition priv = {0};
|
||||
priv.name = "#secret";
|
||||
priv.qualified_name = "proj.src.a.Klass.#secret";
|
||||
priv.label = "Method";
|
||||
priv.file_path = "src/a.ts";
|
||||
cbm_defs_push(&defs, &a, priv);
|
||||
CBMDefinition dollar = {0};
|
||||
dollar.name = "$scope";
|
||||
dollar.qualified_name = "proj.src.b.$scope";
|
||||
dollar.label = "Variable";
|
||||
dollar.file_path = "src/b.js";
|
||||
cbm_defs_push(&defs, &a, dollar);
|
||||
ASSERT_EQ(defs.count, 4);
|
||||
|
||||
/* Member keys JS spells without an identifier start are names too:
|
||||
* computed, string-literal and escaped (1,782 real definitions in the
|
||||
* TypeScript corpus wore these spellings). */
|
||||
const char *member_keys[] = {"[Symbol.iterator]", "\"my-key\"", "'x'", "\\u0410"};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
CBMDefinition member = {0};
|
||||
member.name = member_keys[i];
|
||||
member.qualified_name = member_keys[i];
|
||||
member.label = "Method";
|
||||
member.file_path = "src/c.ts";
|
||||
cbm_defs_push(&defs, &a, member);
|
||||
}
|
||||
ASSERT_EQ(defs.count, 8);
|
||||
|
||||
/* Tokens that are not names in any spelling: patterns, numeric literals,
|
||||
* parenthesised types, rest elements. */
|
||||
const char *tokens[] = {"{ b11 } = { b11: \"string\" }", "0x0", "3.2e1",
|
||||
"(x: number) => string", "...a", "?"};
|
||||
for (int i = 0; i < 6; i++) {
|
||||
CBMDefinition token = {0};
|
||||
token.name = tokens[i];
|
||||
token.qualified_name = tokens[i];
|
||||
token.label = "Variable";
|
||||
token.file_path = "tests/cases/z.js";
|
||||
cbm_defs_push(&defs, &a, token);
|
||||
}
|
||||
ASSERT_EQ(defs.count, 8);
|
||||
|
||||
/* Other languages may legitimately name operators: untouched. */
|
||||
CBMDefinition op = {0};
|
||||
op.name = "<$>";
|
||||
op.qualified_name = "proj.Data.Functor.<$>";
|
||||
op.label = "Function";
|
||||
op.file_path = "src/Data/Functor.hs";
|
||||
cbm_defs_push(&defs, &a, op);
|
||||
ASSERT_EQ(defs.count, 9);
|
||||
|
||||
cbm_arena_destroy(&a);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(makefile_rule_as_function) {
|
||||
CBMFileResult *r = extract("all:\n\t@echo hello\n", CBM_LANG_MAKEFILE, "test", "Makefile");
|
||||
ASSERT_NOT_NULL(r);
|
||||
@@ -3114,6 +3310,25 @@ TEST(go_imports) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* cgo's `import "C"` is a pseudo-package, not a real import: keeping it lets the
|
||||
* import resolver name-match "C" onto an arbitrary project symbol called C. The
|
||||
* real imports of the same file must survive. */
|
||||
TEST(go_cgo_pseudo_import_dropped) {
|
||||
CBMFileResult *r = extract("package m\n\n/*\nstatic int helper(void) { return 1; }\n*/\n"
|
||||
"import \"C\"\n\nimport \"fmt\"\n\n"
|
||||
"func Run() { fmt.Println(C.helper()) }\n",
|
||||
CBM_LANG_GO, "t", "cgo.go");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT(has_import(r, "fmt"));
|
||||
for (int i = 0; i < r->imports.count; i++) {
|
||||
ASSERT_NOT_NULL(r->imports.items[i].module_path);
|
||||
ASSERT_TRUE(strcmp(r->imports.items[i].module_path, "C") != 0);
|
||||
}
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1935: Go struct fields were never extracted — find_class_body() returns the
|
||||
* struct_type node, whose only named child is a field_declaration_list, so the
|
||||
* member loop matched nothing and every field was silently skipped (0 Field
|
||||
@@ -4358,6 +4573,52 @@ TEST(swift_labeled_call_string_arg_issue1892) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Swift has no URL literal, so real code builds one and force-unwraps it. The
|
||||
* string then sits two levels below the argument list. */
|
||||
TEST(swift_nested_url_constructor_issue1892) {
|
||||
CBMFileResult *r = extract("func fetch() { URLSession.shared.dataTask(with: URL(string: "
|
||||
"\"https://example.com/api/v1/widgets\")!) }\n",
|
||||
CBM_LANG_SWIFT, "t", "Fetch.swift");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
const CBMCall *c = find_call_by_callee(r, "URLSession.shared.dataTask");
|
||||
ASSERT_NOT_NULL(c);
|
||||
ASSERT_NOT_NULL(c->first_string_arg);
|
||||
ASSERT_STR_EQ(c->first_string_arg, "https://example.com/api/v1/widgets");
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Without the trailing "!" the constructor is not wrapped in a
|
||||
* postfix_expression, so this covers the other shape. */
|
||||
TEST(swift_nested_url_no_bang_issue1892) {
|
||||
CBMFileResult *r =
|
||||
extract("func fetch() { client.send(to: URLRequest(url: \"/api/v1/widgets/1\")) }\n",
|
||||
CBM_LANG_SWIFT, "t", "Send.swift");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
const CBMCall *c = find_call_by_callee(r, "client.send");
|
||||
ASSERT_NOT_NULL(c);
|
||||
ASSERT_NOT_NULL(c->first_string_arg);
|
||||
ASSERT_STR_EQ(c->first_string_arg, "/api/v1/widgets/1");
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A constructor that is not one of the three URL types keeps its own meaning:
|
||||
* the outer call must not borrow the inner call's string. */
|
||||
TEST(swift_non_url_constructor_untouched_issue1892) {
|
||||
CBMFileResult *r = extract("func f() { log.write(to: Formatter(pattern: \"%s-%d\")) }\n",
|
||||
CBM_LANG_SWIFT, "t", "Log.swift");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
const CBMCall *c = find_call_by_callee(r, "log.write");
|
||||
ASSERT_NOT_NULL(c);
|
||||
ASSERT_NULL(c->first_string_arg);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Issue #1009: URL-builder helper pattern — a function returning a URL-shaped
|
||||
* literal, consumed as client(buildPath(id)). The builder's URL is recorded in
|
||||
* the per-file constant map and resolved at the call site, for both return
|
||||
@@ -5751,6 +6012,370 @@ TEST(extract_c_clean_file_no_recovery_duplicates_issue961) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989: build-system export macros (UE "<MOD>_API", CMake generate_export_header
|
||||
* "<lib>_EXPORT") are empty on the real compile line but opaque to tree-sitter,
|
||||
* so `class MOD_API Foo` misparses. The preprocessed second pass predefines the
|
||||
* conventional export-macro-shaped identifiers found in the file as empty, and
|
||||
* the recovery loop adopts the corrected type defs (superseding the raw
|
||||
* misparse artifacts). */
|
||||
TEST(extract_cpp_export_macro_class_recovery_issue1989) {
|
||||
CBMFileResult *r = extract("#pragma once\n"
|
||||
"UCLASS()\n"
|
||||
"class DUMMY_API UFoo : public UObject\n"
|
||||
"{\n"
|
||||
" GENERATED_BODY()\n"
|
||||
"public:\n"
|
||||
" int32 X = 0;\n"
|
||||
"};\n",
|
||||
CBM_LANG_CPP, "p", "ue.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "UFoo");
|
||||
ASSERT_NOT_NULL(cls); /* was missing entirely before the fix */
|
||||
ASSERT_EQ(cls->start_line, 3u);
|
||||
ASSERT_NULL(find_def(r, "DUMMY_API")); /* macro-as-name artifact superseded */
|
||||
/* The raw misparse also mints a phantom Function def NAMED AFTER THE BASE
|
||||
* CLASS spanning the whole class ("UObject" from the declarator of the
|
||||
* broken function_definition shape) — it must be suppressed, not just the
|
||||
* macro-named artifact. */
|
||||
ASSERT_NULL(find_def(r, "UObject"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(extract_cpp_export_macro_struct_recovery_issue1989) {
|
||||
/* The struct case is the SILENT failure: the raw tree parses "successfully"
|
||||
* with the macro token as the name and raises no error flag at all. */
|
||||
CBMFileResult *r = extract("#pragma once\n"
|
||||
"USTRUCT()\n"
|
||||
"struct DUMMY_API FBar\n"
|
||||
"{\n"
|
||||
" int32 Y;\n"
|
||||
"};\n",
|
||||
CBM_LANG_CPP, "p", "ue_struct.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *st = find_def(r, "FBar");
|
||||
ASSERT_NOT_NULL(st);
|
||||
ASSERT(st->label && strcmp(st->label, "Class") == 0); /* struct_specifier -> Class */
|
||||
ASSERT_NULL(find_def(r, "DUMMY_API"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(extract_cpp_export_macro_enum_recovery_issue1989) {
|
||||
/* `enum class MOD_API EKind` is lost to an ERROR region entirely. */
|
||||
CBMFileResult *r = extract("#pragma once\n"
|
||||
"UENUM()\n"
|
||||
"enum class DUMMY_API EKind : uint8\n"
|
||||
"{\n"
|
||||
" A,\n"
|
||||
" B\n"
|
||||
"};\n",
|
||||
CBM_LANG_CPP, "p", "ue_enum.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(find_def(r, "EKind"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(extract_cpp_export_macro_free_function_recovery_issue1989) {
|
||||
/* A free function DEFINED with the export macro is lost to an ERROR region
|
||||
* on the raw tree (prototypes never mint defs — same as clean code). */
|
||||
CBMFileResult *r = extract("#pragma once\n"
|
||||
"DUMMY_API int Add(int a, int b)\n"
|
||||
"{\n"
|
||||
" return a + b;\n"
|
||||
"}\n",
|
||||
CBM_LANG_CPP, "p", "ue_fn.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(find_def(r, "Add"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(extract_cpp_export_macro_inline_method_recovery_issue1989) {
|
||||
/* The misparsed class parsed as a function body on the raw tree, so the
|
||||
* raw walk never extracted its inline methods — the rescued class def must
|
||||
* carry them in via the nested-span adoption. */
|
||||
CBMFileResult *r = extract("#pragma once\n"
|
||||
"class DUMMY_API FCalc\n"
|
||||
"{\n"
|
||||
"public:\n"
|
||||
" int Add(int a, int b) { return a + b; }\n"
|
||||
"};\n",
|
||||
CBM_LANG_CPP, "p", "ue_inline.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "FCalc");
|
||||
ASSERT_NOT_NULL(cls);
|
||||
ASSERT(cls->label && strcmp(cls->label, "Class") == 0); /* not the raw "Function" mislabel */
|
||||
const CBMDefinition *m = find_def(r, "Add");
|
||||
ASSERT_NOT_NULL(m);
|
||||
ASSERT(m->label && strcmp(m->label, "Method") == 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Negative control the maintainer asked for: ordinary ALL_CAPS identifiers
|
||||
* (constants, enum values) must NOT be swept in as export-macro candidates and
|
||||
* stripped from the graph. Only the narrow _API/_EXPORT/... suffix shape is. */
|
||||
TEST(extract_cpp_export_macro_negative_control_ordinary_caps_issue1989) {
|
||||
CBMFileResult *r = extract("#pragma once\n"
|
||||
"#define MAX_CONNECTIONS 16\n"
|
||||
"const int TIMEOUT_MS = 250;\n"
|
||||
"enum class State { IDLE, RUNNING };\n"
|
||||
"struct Config { int MAX_RETRIES; };\n",
|
||||
CBM_LANG_CPP, "p", "caps.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(find_def(r, "Config"));
|
||||
ASSERT_TRUE(has_def(r, "Variable", "TIMEOUT_MS"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* C files get the same rescue (SQLITE_API-style prefixes are C, not C++). */
|
||||
TEST(extract_c_export_macro_recovery_issue1989) {
|
||||
CBMFileResult *r = extract("typedef struct sqlite3 sqlite3;\n"
|
||||
"SQLITE_API int sqlite3_open(const char *path)\n"
|
||||
"{\n"
|
||||
" return 0;\n"
|
||||
"}\n",
|
||||
CBM_LANG_C, "p", "db.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(find_def(r, "sqlite3_open"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review (P1): an over-long candidate-shaped identifier (>= 96 chars)
|
||||
* arriving AFTER a stored candidate must be rejected BEFORE the dedup
|
||||
* compares — the pre-fix dedup ran strncmp(out[k], src, len) with
|
||||
* len >= CBM_EXPORT_MACRO_NAME_MAX against 96-byte rows (out-of-bounds read;
|
||||
* sanitizer lanes crash). Locally unsanitized, so this pins the behavior
|
||||
* (normal candidate still recovers, no crash); CI's sanitized lanes guard
|
||||
* the memory error itself. */
|
||||
TEST(extract_cpp_export_macro_overlong_candidate_safe_issue1989) {
|
||||
char src[4096];
|
||||
int off = snprintf(src, sizeof(src), "class MOD_API First { int v; };\nclass ");
|
||||
ASSERT_GTE(off, 0);
|
||||
memset(src + off, 'A', 100);
|
||||
off += 100;
|
||||
ASSERT_GTE(snprintf(src + off, sizeof(src) - (size_t)off, "_API Long { int w; };\n"), 0);
|
||||
CBMFileResult *r = extract(src, CBM_LANG_CPP, "p", "overlong.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *first = find_def(r, "First");
|
||||
ASSERT_NOT_NULL(first);
|
||||
ASSERT(first->label && strcmp(first->label, "Class") == 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review (P2): candidate-shaped tokens inside comments and string
|
||||
* literals must NOT consume the bounded budget — 32 of them ahead of the real
|
||||
* class would otherwise exhaust the cap and leave the real macro undefined. */
|
||||
TEST(extract_cpp_export_macro_comment_string_budget_issue1989) {
|
||||
char src[8192];
|
||||
int off = 0;
|
||||
for (int n = 0; n < 31; n++) {
|
||||
ASSERT_GTE(snprintf(src + off, sizeof(src) - (size_t)off, "// see DOC%02d_API notes\n", n),
|
||||
0);
|
||||
off += (int)strlen(src + off);
|
||||
}
|
||||
ASSERT_GTE(snprintf(src + off, sizeof(src) - (size_t)off,
|
||||
"static const char *kRef = \"STRING_DOC_API\";\n"
|
||||
"class REALMOD_API Real { int v; };\n"),
|
||||
0);
|
||||
CBMFileResult *r = extract(src, CBM_LANG_CPP, "p", "budget.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "Real");
|
||||
ASSERT_NOT_NULL(cls);
|
||||
ASSERT(cls->label && strcmp(cls->label, "Class") == 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review: the bounded-budget contract — 33 distinct candidates collect
|
||||
* only the first CBM_EXPORT_MACRO_MAX (32, in source order); the 33rd stays
|
||||
* unpredefined and its class keeps the raw misparse (value label, not Class). */
|
||||
TEST(extract_cpp_export_macro_candidate_cap_issue1989) {
|
||||
char src[8192];
|
||||
int off = 0;
|
||||
for (int n = 0; n < 33; n++) {
|
||||
ASSERT_GTE(
|
||||
snprintf(src + off, sizeof(src) - (size_t)off, "class CAP%02d_API K%02d {};\n", n, n),
|
||||
0);
|
||||
off += (int)strlen(src + off);
|
||||
}
|
||||
CBMFileResult *r = extract(src, CBM_LANG_CPP, "p", "cap.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
int recovered = 0;
|
||||
for (int n = 0; n < 33; n++) {
|
||||
char name[8];
|
||||
snprintf(name, sizeof(name), "K%02d", n);
|
||||
const CBMDefinition *d = find_def(r, name);
|
||||
if (d && d->label && strcmp(d->label, "Class") == 0) {
|
||||
recovered++;
|
||||
}
|
||||
}
|
||||
ASSERT_EQ(recovered, 32);
|
||||
/* The cap contract's other half: the 33rd candidate (K32) must STILL be
|
||||
* present with its raw misparse — dropping the def entirely would be a
|
||||
* regression, not a graceful cap. */
|
||||
const CBMDefinition *cap_tail = find_def(r, "K32");
|
||||
ASSERT_NOT_NULL(cap_tail);
|
||||
ASSERT_TRUE(!cap_tail->label || strcmp(cap_tail->label, "Class") != 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review round 2: line-spliced // comments. A backslash before the
|
||||
* newline continues the comment (splicing happens before comment
|
||||
* recognition), so "FAKE_API" below is comment text and must NOT consume
|
||||
* budget. 32 spliced fake comments would otherwise exhaust the cap and leave
|
||||
* the real class unrecovered. */
|
||||
TEST(extract_cpp_export_macro_spliced_comment_budget_issue1989) {
|
||||
char src[8192];
|
||||
int off = 0;
|
||||
for (int n = 0; n < 31; n++) {
|
||||
ASSERT_GTE(
|
||||
snprintf(src + off, sizeof(src) - (size_t)off, "// fake \\\nFAKE%02d_API notes\n", n),
|
||||
0);
|
||||
off += (int)strlen(src + off);
|
||||
}
|
||||
ASSERT_GTE(snprintf(src + off, sizeof(src) - (size_t)off,
|
||||
"// last \\\r\nSPLICEFAKE_API notes\n"
|
||||
"class REALMOD_API Real { int v; };\n"),
|
||||
0);
|
||||
CBMFileResult *r = extract(src, CBM_LANG_CPP, "p", "spliced.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "Real");
|
||||
ASSERT_NOT_NULL(cls);
|
||||
ASSERT(cls->label && strcmp(cls->label, "Class") == 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review round 2: C++ raw string literals. Tokens inside R"(...)"
|
||||
* must not be collected, and code after the literal must still be scanned —
|
||||
* an unmodeled raw string previously let "BAR_API" leak in AND masked the
|
||||
* real candidate after the literal's closing quote. An unrecognizable raw
|
||||
* form (unterminated/malformed delimiter) stops collection entirely so scan
|
||||
* state cannot be poisoned. */
|
||||
TEST(extract_cpp_export_macro_raw_string_issue1989) {
|
||||
CBMFileResult *r = extract("const char *s = R\"(foo \" BAR_API)\";\n"
|
||||
"class REALMOD_API Real { int v; };\n",
|
||||
CBM_LANG_CPP, "p", "raw.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "Real");
|
||||
ASSERT_NOT_NULL(cls);
|
||||
ASSERT(cls->label && strcmp(cls->label, "Class") == 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(extract_cpp_export_macro_raw_string_delimited_issue1989) {
|
||||
CBMFileResult *r = extract("auto log = R\"log(FOO_API \"quote\")log\";\n"
|
||||
"class DELIMMOD_API Delim { int v; };\n",
|
||||
CBM_LANG_CPP, "p", "raw_delim.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "Delim");
|
||||
ASSERT_NOT_NULL(cls);
|
||||
ASSERT(cls->label && strcmp(cls->label, "Class") == 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review: every conventional suffix variant must be collected and
|
||||
* recovered, not just _API. */
|
||||
TEST(extract_cpp_export_macro_suffix_variants_issue1989) {
|
||||
CBMFileResult *r = extract("class LIB_EXPORT A1 { int v; };\n"
|
||||
"class LIB_IMPORT B2 { int v; };\n"
|
||||
"class LIB_DLLEXPORT C3 { int v; };\n"
|
||||
"class LIB_DEPRECATED D4 { int v; };\n",
|
||||
CBM_LANG_CPP, "p", "suffix.h");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const char *names[] = {"A1", "B2", "C3", "D4"};
|
||||
for (int n = 0; n < 4; n++) {
|
||||
const CBMDefinition *d = find_def(r, names[n]);
|
||||
ASSERT_NOT_NULL(d);
|
||||
ASSERT(d->label && strcmp(d->label, "Class") == 0);
|
||||
}
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review: caller-provided defines win — the collector must not push a
|
||||
* define for a name the caller already provided (a duplicate could flip the
|
||||
* expansion and silently change what parses). With an explicit empty define
|
||||
* the class still recovers; with a caller define that corrupts the header,
|
||||
* the injected empty define must NOT clobber it back into parsing. */
|
||||
TEST(extract_cpp_export_macro_explicit_define_priority_issue1989) {
|
||||
const char *src = "class MYMOD_API Foo { int v; };\n";
|
||||
|
||||
const char *empty_defines[] = {"MYMOD_API=", NULL};
|
||||
CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_CPP, "p", "prio_empty.h", 0,
|
||||
empty_defines, NULL);
|
||||
ASSERT_NOT_NULL(r);
|
||||
const CBMDefinition *cls = find_def(r, "Foo");
|
||||
ASSERT_NOT_NULL(cls);
|
||||
ASSERT(cls->label && strcmp(cls->label, "Class") == 0);
|
||||
cbm_free_result(r);
|
||||
|
||||
const char *body_defines[] = {"MYMOD_API=Junk", NULL};
|
||||
CBMFileResult *r2 = cbm_extract_file(src, (int)strlen(src), CBM_LANG_CPP, "p", "prio_body.h", 0,
|
||||
body_defines, NULL);
|
||||
ASSERT_NOT_NULL(r2);
|
||||
const CBMDefinition *foo2 = find_def(r2, "Foo");
|
||||
ASSERT_TRUE(foo2 == NULL || (foo2->label && strcmp(foo2->label, "Class") != 0));
|
||||
cbm_free_result(r2);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1989 review round 2: the collector CONTRACT itself, called directly (the
|
||||
* reviewer's method): the raw string's inner token is not a candidate and the
|
||||
* code after the literal IS. */
|
||||
TEST(extract_cpp_export_macro_collector_raw_string_contract_issue1989) {
|
||||
const char *src = "const char *s = R\"(foo \" BAR_API)\";\n"
|
||||
"class REALMOD_API Real { int v; };\n";
|
||||
char out[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int n = cbm_export_macro_candidates(src, (int)strlen(src), out, CBM_EXPORT_MACRO_MAX);
|
||||
ASSERT_EQ(n, 1);
|
||||
ASSERT(strcmp(out[0], "REALMOD_API") == 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Delimiter form R"log(...)log" works the same way. */
|
||||
TEST(extract_cpp_export_macro_collector_raw_string_delim_contract_issue1989) {
|
||||
const char *src = "auto log = R\"log(FOO_API \"q\")log\";\n"
|
||||
"class DELIMMOD_API Delim { int v; };\n";
|
||||
char out[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int n = cbm_export_macro_candidates(src, (int)strlen(src), out, CBM_EXPORT_MACRO_MAX);
|
||||
ASSERT_EQ(n, 1);
|
||||
ASSERT(strcmp(out[0], "DELIMMOD_API") == 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A double quote is a legal raw-string delimiter character. Keep scanning
|
||||
* after R"""(...)""" so a later export macro is still collected. */
|
||||
TEST(extract_cpp_export_macro_collector_raw_string_quote_delim_issue1989) {
|
||||
const char *src = "const char *s = R\"\"\"(FOO_API)\"\"\";\n"
|
||||
"class QUOTEMOD_API Quoted { int v; };\n";
|
||||
char out[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int n = cbm_export_macro_candidates(src, (int)strlen(src), out, CBM_EXPORT_MACRO_MAX);
|
||||
ASSERT_EQ(n, 1);
|
||||
ASSERT(strcmp(out[0], "QUOTEMOD_API") == 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Unterminated raw literal: the scan stops rather than mis-tokenizing the
|
||||
* rest of the file (uncertain state -> fail toward raw behavior). */
|
||||
TEST(extract_cpp_export_macro_collector_raw_string_unterminated_issue1989) {
|
||||
const char *src = "const char *s = R\"(never closed BAR_API\n"
|
||||
"class REALMOD_API Real { int v; };\n";
|
||||
char out[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int n = cbm_export_macro_candidates(src, (int)strlen(src), out, CBM_EXPORT_MACRO_MAX);
|
||||
ASSERT_EQ(n, 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #668: walk_defs used a fixed `walk_defs_frame_t stack[4096]` — a ~160 KB
|
||||
* C-stack frame that overflowed small thread stacks (the reporter's crash was in
|
||||
* the "definitions pass" on a large SQL file), and whose `top < 4096` push guards
|
||||
@@ -6780,6 +7405,38 @@ static int find_call_args(const CBMFileResult *r, const char *callee, const char
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* tree-sitter lists a comment inside an argument list as a named child; it is
|
||||
* not an argument. A Java constructor call whose argument list opened with a
|
||||
* slash-star comment handed the comment text to the Route pass as a URL
|
||||
* (three Route nodes named by comments on elasticsearch, 2026-09-16). */
|
||||
TEST(call_args_skip_comments_between_arguments) {
|
||||
CBMFileResult *r = extract("class A {\n"
|
||||
" void f() {\n"
|
||||
" app.get(/* the orders listing */ \"/orders\", handler);\n"
|
||||
" new TestCase(\n"
|
||||
" /*\n"
|
||||
" * a multi-line note\n"
|
||||
" */\n"
|
||||
" \"x\", // trailing\n"
|
||||
" 1);\n"
|
||||
" }\n"
|
||||
"}\n",
|
||||
CBM_LANG_JAVA, "t", "A.java");
|
||||
ASSERT_NOT_NULL(r);
|
||||
const char *arg0 = NULL;
|
||||
const char *arg1 = NULL;
|
||||
int argc = find_call_args(r, "get", &arg0, &arg1);
|
||||
ASSERT_EQ(argc, 2);
|
||||
ASSERT_STR_EQ(arg0, "\"/orders\"");
|
||||
ASSERT_STR_EQ(arg1, "handler");
|
||||
argc = find_call_args(r, "TestCase", &arg0, &arg1);
|
||||
ASSERT_EQ(argc, 2);
|
||||
ASSERT_STR_EQ(arg0, "\"x\"");
|
||||
ASSERT_STR_EQ(arg1, "1");
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(objectscript_data_flows_class_method_args) {
|
||||
CBMFileResult *r = extract("Class MyApp.Caller Extends %RegisteredObject\n"
|
||||
"{\n"
|
||||
@@ -7649,6 +8306,7 @@ SUITE(extraction) {
|
||||
RUN_TEST(objectscript_macro_constant_no_extra_call);
|
||||
RUN_TEST(objectscript_udl_method_return_type);
|
||||
RUN_TEST(objectscript_udl_scalar_return_type_not_resolved);
|
||||
RUN_TEST(call_args_skip_comments_between_arguments);
|
||||
RUN_TEST(objectscript_data_flows_class_method_args);
|
||||
RUN_TEST(objectscript_data_flows_instance_method_args);
|
||||
RUN_TEST(iris_export_xml_simple_class);
|
||||
@@ -7708,8 +8366,11 @@ SUITE(extraction) {
|
||||
RUN_TEST(go_interface);
|
||||
RUN_TEST(zig_function);
|
||||
RUN_TEST(c_function);
|
||||
RUN_TEST(c_function_return_type_preserves_pointer_and_qualifier);
|
||||
RUN_TEST(c_function_return_type_plain_unchanged);
|
||||
RUN_TEST(c_struct);
|
||||
RUN_TEST(cpp_class);
|
||||
RUN_TEST(cpp_method_return_type_preserves_pointer_and_qualifier);
|
||||
|
||||
/* Scripting */
|
||||
RUN_TEST(python_function);
|
||||
@@ -7782,6 +8443,9 @@ SUITE(extraction) {
|
||||
RUN_TEST(swift_chained_call);
|
||||
RUN_TEST(swift_force_unwrap_scanner_shift);
|
||||
RUN_TEST(swift_call_string_arg_issue1892);
|
||||
RUN_TEST(swift_nested_url_constructor_issue1892);
|
||||
RUN_TEST(swift_nested_url_no_bang_issue1892);
|
||||
RUN_TEST(swift_non_url_constructor_untouched_issue1892);
|
||||
RUN_TEST(swift_labeled_call_string_arg_issue1892);
|
||||
RUN_TEST(objc_interface);
|
||||
RUN_TEST(objc_implementation);
|
||||
@@ -7859,6 +8523,7 @@ SUITE(extraction) {
|
||||
RUN_TEST(commonlisp_defun);
|
||||
RUN_TEST(commonlisp_multiple_functions);
|
||||
RUN_TEST(commonlisp_defmacro);
|
||||
RUN_TEST(defs_push_cuts_multiline_names_and_rejects_js_literal_names);
|
||||
RUN_TEST(makefile_rule_as_function);
|
||||
RUN_TEST(makefile_multiple_targets);
|
||||
RUN_TEST(makefile_variable_extraction);
|
||||
@@ -7874,6 +8539,7 @@ SUITE(extraction) {
|
||||
RUN_TEST(python_imports);
|
||||
RUN_TEST(js_imports);
|
||||
RUN_TEST(go_imports);
|
||||
RUN_TEST(go_cgo_pseudo_import_dropped);
|
||||
RUN_TEST(extract_go_struct_fields_have_nodes);
|
||||
RUN_TEST(java_imports);
|
||||
RUN_TEST(rust_imports);
|
||||
@@ -7974,6 +8640,25 @@ SUITE(extraction) {
|
||||
RUN_TEST(extract_cpp_preproc_macro_generated_callable_skipped_issue949);
|
||||
RUN_TEST(extract_c_ifdef_split_brace_after_include_remapped_issue949);
|
||||
RUN_TEST(extract_c_clean_file_no_recovery_duplicates_issue961);
|
||||
RUN_TEST(extract_cpp_export_macro_class_recovery_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_struct_recovery_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_enum_recovery_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_free_function_recovery_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_inline_method_recovery_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_negative_control_ordinary_caps_issue1989);
|
||||
RUN_TEST(extract_c_export_macro_recovery_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_overlong_candidate_safe_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_comment_string_budget_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_candidate_cap_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_spliced_comment_budget_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_raw_string_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_raw_string_delimited_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_collector_raw_string_contract_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_collector_raw_string_delim_contract_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_collector_raw_string_quote_delim_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_collector_raw_string_unterminated_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_suffix_variants_issue1989);
|
||||
RUN_TEST(extract_cpp_export_macro_explicit_define_priority_issue1989);
|
||||
RUN_TEST(walk_defs_no_truncation_over_4096_issue668);
|
||||
RUN_TEST(extract_rust_test_attr_marks_is_test_issue855);
|
||||
RUN_TEST(extract_c_test_dir_marks_is_test_issue1294);
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
#include "foundation/mem_core.h"
|
||||
#include <stdatomic.h>
|
||||
#include "store/store.h"
|
||||
#include "../src/foundation/compat.h"
|
||||
#include "foundation/compat_fs.h"
|
||||
#include "foundation/log.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
/* ── Node operations ───────────────────────────────────────────── */
|
||||
@@ -1120,6 +1124,72 @@ TEST(gbuf_flush_skips_orphan_edges) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── Publish failure reporting ───────────────────────────────── */
|
||||
|
||||
static char g_log_capture[4096];
|
||||
static CBMLogLevel g_prev_log_level;
|
||||
static CBMLogFormat g_prev_log_format;
|
||||
|
||||
static void capture_log_sink(const char *line) {
|
||||
size_t used = strlen(g_log_capture);
|
||||
size_t avail = sizeof(g_log_capture) - used;
|
||||
if (avail <= 1) {
|
||||
return;
|
||||
}
|
||||
int n = snprintf(g_log_capture + used, avail, "%s\n", line);
|
||||
if (n < 0 || (size_t)n >= avail) {
|
||||
g_log_capture[sizeof(g_log_capture) - 1] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
static void capture_logs_start(void) {
|
||||
g_log_capture[0] = '\0';
|
||||
g_prev_log_level = cbm_log_get_level();
|
||||
g_prev_log_format = cbm_log_get_format();
|
||||
cbm_log_set_level(CBM_LOG_DEBUG);
|
||||
/* The assertions below read the text encoding, so pin it rather than
|
||||
* inherit whatever CBM_LOG_FORMAT left set. */
|
||||
cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
|
||||
cbm_log_set_sink(capture_log_sink);
|
||||
}
|
||||
|
||||
static const char *capture_logs_end(void) {
|
||||
cbm_log_set_sink(NULL);
|
||||
cbm_log_set_level(g_prev_log_level);
|
||||
cbm_log_set_format(g_prev_log_format);
|
||||
return g_log_capture;
|
||||
}
|
||||
|
||||
/* A dump that publishes nothing has to say so, and say why. Renaming onto an
|
||||
* existing directory is how test_sqlite_writer already forces the publish to
|
||||
* fail; here it stands in for any host that denies the rename (#1620). */
|
||||
TEST(gbuf_dump_failure_logs_reason) {
|
||||
char dir[256];
|
||||
snprintf(dir, sizeof(dir), "/tmp/cbm_gbuf_pub_XXXXXX");
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(dir));
|
||||
|
||||
cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp/repo");
|
||||
ASSERT_NOT_NULL(gb);
|
||||
int64_t id = cbm_gbuf_upsert_node(gb, "Function", "main", "pkg.main", "main.go", 1, 10, "{}");
|
||||
ASSERT_GT(id, 0);
|
||||
|
||||
capture_logs_start();
|
||||
int rc = cbm_gbuf_dump_to_sqlite(gb, dir);
|
||||
const char *logs = capture_logs_end();
|
||||
|
||||
ASSERT(rc != 0);
|
||||
ASSERT_NOT_NULL(strstr(logs, "gbuf.dump_failed"));
|
||||
/* The reason survived the cleanup unlink. */
|
||||
ASSERT_NOT_NULL(strstr(logs, "errno="));
|
||||
ASSERT(strstr(logs, "errno=0 ") == NULL);
|
||||
/* And the run is not also reported as a successful dump. */
|
||||
ASSERT(strstr(logs, "msg=gbuf.dump ") == NULL);
|
||||
|
||||
cbm_gbuf_free(gb);
|
||||
cbm_rmdir(dir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── Suite ─────────────────────────────────────────────────────── */
|
||||
|
||||
/* A worker buffer draws ids from the shared counter, so a dense id -> node
|
||||
@@ -1221,4 +1291,7 @@ SUITE(graph_buffer) {
|
||||
RUN_TEST(gbuf_shared_ids_null_fallback);
|
||||
RUN_TEST(gbuf_next_id_set_next_id_roundtrip);
|
||||
RUN_TEST(gbuf_next_id_null_safe);
|
||||
|
||||
/* Publish failure reporting */
|
||||
RUN_TEST(gbuf_dump_failure_logs_reason);
|
||||
}
|
||||
+194
-2
@@ -1,11 +1,11 @@
|
||||
#include "test_framework.h"
|
||||
#include "graph_buffer/graph_buffer.h"
|
||||
#include "pipeline/pipeline_internal.h"
|
||||
#include "service_patterns.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
bool cbm_service_pattern_is_http_route_literal(const char *literal, const char *callee_name);
|
||||
#include <stdio.h>
|
||||
|
||||
static int has_data_flow(cbm_gbuf_t *gb, int64_t source_id, int64_t target_id) {
|
||||
const cbm_gbuf_edge_t **edges = NULL;
|
||||
@@ -32,6 +32,196 @@ TEST(infrascan_http_route_literal_guard_rejects_filesystem_paths) {
|
||||
ASSERT_TRUE(cbm_service_pattern_is_http_route_literal("/api/orders", "requests.get"));
|
||||
ASSERT_TRUE(cbm_service_pattern_is_http_route_literal("https://orders.example/api/orders",
|
||||
"requests.get"));
|
||||
/* A comment that leads an argument list is not a route (elasticsearch
|
||||
* RestHandler routes: three Java block comments became Route nodes). */
|
||||
ASSERT_FALSE(cbm_service_pattern_is_http_route_literal(
|
||||
"/*\n * Deprecated in #64227, 7.12/8.0.\n */",
|
||||
"Route.builder"));
|
||||
ASSERT_FALSE(cbm_service_pattern_is_http_route_literal("// legacy path", "Route.builder"));
|
||||
ASSERT_FALSE(cbm_service_pattern_is_http_route_literal("/_cat\n/indices", "Route.builder"));
|
||||
ASSERT_FALSE(cbm_service_pattern_is_http_route_literal("/* all */", "Route.builder"));
|
||||
ASSERT_TRUE(cbm_service_pattern_is_http_route_literal("/_cat/indices", "Route.builder"));
|
||||
/* The wildcard path (slash-star alone) is a route, not a comment:
|
||||
* elasticsearch's RestClient.buildUri(null, wildcard) registers one. */
|
||||
ASSERT_TRUE(cbm_service_pattern_is_http_route_literal("/*", "RestClient.buildUri"));
|
||||
ASSERT_TRUE(cbm_service_pattern_is_http_route_literal("/api/*", "app.get"));
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── Service-pattern QN boundaries (distilled from PR #1245) ─────────
|
||||
* A library id must sit on an identifier boundary inside the QN. A raw
|
||||
* substring match classified "proj.plugin.loader" as gin ("gin.") and
|
||||
* "proj.studio.x" as Dio ("dio"), which minted bogus Route / HTTP_CALLS
|
||||
* edges. The rule must stay open for CamelCase glue ("GuzzleHttp",
|
||||
* "FeignClient", "KafkaProducer", "IHttpClientFactory") and for version
|
||||
* suffixes ("urllib2", "amqp091-go"). */
|
||||
typedef struct {
|
||||
const char *qn;
|
||||
cbm_svc_kind_t want;
|
||||
} svc_case_t;
|
||||
|
||||
static int svc_case_mismatches(const svc_case_t *cases) {
|
||||
int bad = 0;
|
||||
for (int i = 0; cases[i].qn != NULL; i++) {
|
||||
cbm_svc_kind_t got = cbm_service_pattern_match(cases[i].qn);
|
||||
if (got != cases[i].want) {
|
||||
printf(" service-pattern mismatch: \"%s\" -> %d, expected %d\n", cases[i].qn, (int)got,
|
||||
(int)cases[i].want);
|
||||
bad++;
|
||||
}
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
TEST(infrascan_service_pattern_match_rejects_ids_inside_words) {
|
||||
static const svc_case_t cases[] = {
|
||||
/* "gin." inside plugin. */
|
||||
{"proj.plugins.autorun.tests.test_plugin._dispatch", CBM_SVC_NONE},
|
||||
{"proj.plugin.loader", CBM_SVC_NONE},
|
||||
/* "chi." / "echo." / "fiber." */
|
||||
{"proj.hibachi.grill", CBM_SVC_NONE},
|
||||
{"sound.reecho.apply", CBM_SVC_NONE},
|
||||
{"textile.microfiber.weave", CBM_SVC_NONE},
|
||||
/* "dio" inside studio / radio */
|
||||
{"proj.studio.x", CBM_SVC_NONE},
|
||||
{"radio.tune", CBM_SVC_NONE},
|
||||
/* "surf" / "resty" / "curl" / "phin" / "hyper" / "sling" / "needle" / "treq" */
|
||||
{"app.surface.draw", CBM_SVC_NONE},
|
||||
{"ui.restyle.apply", CBM_SVC_NONE},
|
||||
/* control: "forestry" spells "restr", never contained "resty" */
|
||||
{"pkg.forestry.trees", CBM_SVC_NONE},
|
||||
{"util.curly.brace", CBM_SVC_NONE},
|
||||
{"sea.dolphin.swim", CBM_SVC_NONE},
|
||||
{"math.hyperbolic.tanh", CBM_SVC_NONE},
|
||||
{"farm.gosling.walk", CBM_SVC_NONE},
|
||||
{"sewing.needles.sort", CBM_SVC_NONE},
|
||||
{"util.streq", CBM_SVC_NONE},
|
||||
/* "requests" glued to a lowercase prefix (upstream's case) */
|
||||
{"proj.myrequests.client.get", CBM_SVC_NONE},
|
||||
/* "express" / "rocket" / "tonic" / "nconf" */
|
||||
{"ast.expression.eval", CBM_SVC_NONE},
|
||||
{"mq.rocketmq.send", CBM_SVC_NONE},
|
||||
{"geo.tectonic.plates", CBM_SVC_NONE},
|
||||
{"app.unconfigured.warn", CBM_SVC_NONE},
|
||||
{"cli.runconfig.load", CBM_SVC_NONE},
|
||||
{"aws.s3express.session", CBM_SVC_NONE},
|
||||
/* not clients of the id they contain: ASGI server, URL library,
|
||||
* nginx platform, Memgraph OGM, Celery settings module, a word */
|
||||
{"hypercorn.run.serve", CBM_SVC_NONE},
|
||||
{"hyperlink.URL.from_text", CBM_SVC_NONE},
|
||||
{"openresty.core.request", CBM_SVC_NONE},
|
||||
{"gqlalchemy.Memgraph.execute", CBM_SVC_NONE},
|
||||
{"celeryconfig.broker_url", CBM_SVC_NONE},
|
||||
{"kafkaesque.story.tell", CBM_SVC_NONE},
|
||||
{NULL, CBM_SVC_NONE},
|
||||
};
|
||||
ASSERT_EQ(svc_case_mismatches(cases), 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(infrascan_service_pattern_match_keeps_real_library_qns) {
|
||||
static const svc_case_t cases[] = {
|
||||
/* Route registration: ids that end in a separator, own segment */
|
||||
{"github.com/gin-gonic/gin.Default", CBM_SVC_ROUTE_REG},
|
||||
{"proj.gin.router.GET", CBM_SVC_ROUTE_REG},
|
||||
{"gin.GET", CBM_SVC_ROUTE_REG},
|
||||
{"chi.NewRouter", CBM_SVC_ROUTE_REG},
|
||||
{"github.com/labstack/echo.New", CBM_SVC_ROUTE_REG},
|
||||
{"fiber.New", CBM_SVC_ROUTE_REG},
|
||||
{"proj.express.router.get", CBM_SVC_ROUTE_REG},
|
||||
{"@hapi/hapi.server.route", CBM_SVC_ROUTE_REG},
|
||||
/* HTTP: own segment / separator-joined wrapper */
|
||||
{"proj.venv.requests.api.get", CBM_SVC_HTTP},
|
||||
{"proj.service.requests_get", CBM_SVC_HTTP},
|
||||
{"package:dio/dio.dart", CBM_SVC_HTTP},
|
||||
{"dio.Dio.get", CBM_SVC_HTTP},
|
||||
{"pkg.net.curl.get", CBM_SVC_HTTP},
|
||||
{"curl_exec", CBM_SVC_HTTP},
|
||||
{"surf.get", CBM_SVC_HTTP},
|
||||
{"hyper.Client.request", CBM_SVC_HTTP},
|
||||
{"phin.promisified", CBM_SVC_HTTP},
|
||||
{"needle.get", CBM_SVC_HTTP},
|
||||
{"github.com/go-resty/resty.New", CBM_SVC_HTTP},
|
||||
{"github.com/dghubble/sling.New", CBM_SVC_HTTP},
|
||||
/* HTTP: CamelCase glue after the id */
|
||||
{"GuzzleHttp\\Client", CBM_SVC_HTTP},
|
||||
{"proj.GuzzleHttp.Client.get", CBM_SVC_HTTP},
|
||||
{"org.springframework.cloud.openfeign.FeignClientBuilder.build", CBM_SVC_HTTP},
|
||||
{"com.acme.net.HttpClientFactory.create", CBM_SVC_HTTP},
|
||||
/* HTTP: CamelCase glue before the id */
|
||||
{"System.Net.Http.IHttpClientFactory.CreateClient", CBM_SVC_HTTP},
|
||||
{"org.asynchttpclient.AsyncHttpClient.prepareGet", CBM_SVC_HTTP},
|
||||
{"Foundation.NSURLSession.dataTask", CBM_SVC_HTTP},
|
||||
/* HTTP: version suffix after the id */
|
||||
{"urllib2.urlopen", CBM_SVC_HTTP},
|
||||
{"Mint.HTTP2.request", CBM_SVC_HTTP},
|
||||
/* Async */
|
||||
{"com.acme.events.KafkaProducer.send", CBM_SVC_ASYNC},
|
||||
{"this.kafkaProducer.send", CBM_SVC_ASYNC},
|
||||
{"org.apache.kafka.clients.producer.KafkaProducer.send", CBM_SVC_ASYNC},
|
||||
{"github.com/rabbitmq/amqp091-go.Channel.Publish", CBM_SVC_ASYNC},
|
||||
{"github.com/nats-io/nats.go.Conn.Publish", CBM_SVC_ASYNC},
|
||||
/* Config */
|
||||
{"os.getenv", CBM_SVC_CONFIG},
|
||||
{"os.Getenv", CBM_SVC_CONFIG},
|
||||
/* Glued-name libraries: the library's own name glues a lowercase
|
||||
* prefix/suffix onto another id, so each has an explicit table entry.
|
||||
* Every QN below contains NO other id — only the entry can match. */
|
||||
{"grequests.map", CBM_SVC_HTTP},
|
||||
{"txrequests.Session.send", CBM_SVC_HTTP},
|
||||
{"redaxios.create", CBM_SVC_HTTP},
|
||||
{"gaxios.request", CBM_SVC_HTTP},
|
||||
{"libcurl.version", CBM_SVC_HTTP},
|
||||
{"node-libcurl.Easy.perform", CBM_SVC_HTTP},
|
||||
{"curlpp.Easy.perform", CBM_SVC_HTTP},
|
||||
{"curlcpp.easy.perform", CBM_SVC_HTTP},
|
||||
{"hyperlocal.UnixConnector.call", CBM_SVC_HTTP},
|
||||
{"guzzlehttp/psr7.Utils.streamFor", CBM_SVC_HTTP},
|
||||
{"aiokafka.helpers.create_ssl_context", CBM_SVC_ASYNC},
|
||||
{"pykafka.topic.Topic.get_producer", CBM_SVC_ASYNC},
|
||||
{"librdkafka.rd_version", CBM_SVC_ASYNC},
|
||||
{"rdkafkacpp.version", CBM_SVC_ASYNC},
|
||||
{"rskafka.client.partition.write", CBM_SVC_ASYNC},
|
||||
{"aioamqp.connect", CBM_SVC_ASYNC},
|
||||
{"amqpstorm.Connection.channel", CBM_SVC_ASYNC},
|
||||
{"pamqp.frame.marshal", CBM_SVC_ASYNC},
|
||||
{"kombu.transport.pyamqp.Transport.establish_connection", CBM_SVC_ASYNC},
|
||||
{"amqprs.channel.basic_publish", CBM_SVC_ASYNC},
|
||||
{"amqpcpp.TcpChannel.publish", CBM_SVC_ASYNC},
|
||||
{"pynats.client.send", CBM_SVC_ASYNC},
|
||||
{"jnats.options.build", CBM_SVC_ASYNC},
|
||||
{"aiomqtt.client.publish", CBM_SVC_ASYNC},
|
||||
{"amqtt.session.deliver", CBM_SVC_ASYNC},
|
||||
{"hbmqtt.session.deliver", CBM_SVC_ASYNC},
|
||||
{"umqtt.simple.publish", CBM_SVC_ASYNC},
|
||||
{"mqttools.client.publish", CBM_SVC_ASYNC},
|
||||
{"emqtt.publish", CBM_SVC_ASYNC},
|
||||
{"rumqtt.client.publish", CBM_SVC_ASYNC},
|
||||
{"github.com/256dpi/gomqtt/client.Publish", CBM_SVC_ASYNC},
|
||||
{"libmosquitto.publish", CBM_SVC_ASYNC},
|
||||
{"mosquittopp.publish", CBM_SVC_ASYNC},
|
||||
{"google.cloud.pubsublite.admin.create_topic", CBM_SVC_ASYNC},
|
||||
{"gocelery.client.delay", CBM_SVC_ASYNC},
|
||||
{"_wgetenv", CBM_SVC_CONFIG},
|
||||
{"_wgetenv_s", CBM_SVC_CONFIG},
|
||||
{"os.getenvb", CBM_SVC_CONFIG},
|
||||
{"qgetenv", CBM_SVC_CONFIG},
|
||||
{"@dotenvx/dotenvx.config", CBM_SVC_CONFIG},
|
||||
{"vlucas/phpdotenv.load", CBM_SVC_CONFIG},
|
||||
{"apiflask.scaffold.get", CBM_SVC_ROUTE_REG},
|
||||
{"honox.factory.createRoute", CBM_SVC_ROUTE_REG},
|
||||
{"fasthttprouter.Router.GET", CBM_SVC_ROUTE_REG},
|
||||
{"github.com/vektah/gqlparser/v2.LoadSchema", CBM_SVC_GRAPHQL},
|
||||
{"github.com/Yamashou/gqlgenc.client.Post", CBM_SVC_GRAPHQL},
|
||||
{"aiogqlc.client.execute", CBM_SVC_GRAPHQL},
|
||||
{NULL, CBM_SVC_NONE},
|
||||
};
|
||||
ASSERT_EQ(svc_case_mismatches(cases), 0);
|
||||
ASSERT_STR_EQ(cbm_service_pattern_broker("aiokafka.helpers.create_ssl_context"), "kafka");
|
||||
ASSERT_STR_EQ(cbm_service_pattern_broker("umqtt.simple.publish"), "mqtt");
|
||||
ASSERT_STR_EQ(cbm_service_pattern_broker("com.acme.events.KafkaProducer.send"), "kafka");
|
||||
ASSERT_STR_EQ(cbm_service_pattern_broker("github.com/rabbitmq/amqp091-go.Channel.Publish"),
|
||||
"rabbitmq");
|
||||
PASS();
|
||||
}
|
||||
|
||||
@@ -115,6 +305,8 @@ TEST(infrascan_http_calls_join_matching_handler_route) {
|
||||
|
||||
SUITE(infrascan) {
|
||||
RUN_TEST(infrascan_http_route_literal_guard_rejects_filesystem_paths);
|
||||
RUN_TEST(infrascan_service_pattern_match_rejects_ids_inside_words);
|
||||
RUN_TEST(infrascan_service_pattern_match_keeps_real_library_qns);
|
||||
RUN_TEST(infrascan_route_nodes_skip_bad_http_url_paths);
|
||||
RUN_TEST(infrascan_http_calls_join_matching_handler_route);
|
||||
}
|
||||
+129
-9
@@ -3786,6 +3786,124 @@ TEST(tool_search_graph_bm25_reports_candidate_saturation) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Shared fixture for the two BM25 findability probes (2026-09-16, measured on
|
||||
* JetBrains/Exposed and django/django): a Class named exactly like the query,
|
||||
* that class's own Methods, and test Methods whose long names repeat the
|
||||
* query token — the shapes that outranked the class and hid it entirely. */
|
||||
static void bm25_findability_fixture(cbm_store_t *store, const char *project) {
|
||||
cbm_store_upsert_project(store, project, "/tmp/bm25-findability");
|
||||
struct {
|
||||
const char *label, *name, *qn, *file;
|
||||
} rows[] = {
|
||||
{"Class", "Table", "bm25-find.core.Table.Table", "core/Table.kt"},
|
||||
{"Method", "unquoted", "bm25-find.core.Table.Table.unquoted", "core/Table.kt"},
|
||||
{"Method", "describe", "bm25-find.core.Table.Table.describe", "core/Table.kt"},
|
||||
{"Method", "table references table with same name in other database",
|
||||
"bm25-find.tests.SchemaTests.table_references_table_with_same_name", "tests/Schema.kt"},
|
||||
{"Method", "table references table with same name in mysql",
|
||||
"bm25-find.tests.SchemaTests.table_references_table_with_same_name_mysql",
|
||||
"tests/Schema.kt"},
|
||||
{"Function", "get_object_or_404", "bm25-find.shortcuts.get_object_or_404", "shortcuts.py"},
|
||||
{"Method", "test_get_object_or_404",
|
||||
"bm25-find.tests.GetObjectOr404Tests.test_get_object_or_404", "tests/tests.py"},
|
||||
{"Method", "test_get_object_or_404_queryset_attribute_error",
|
||||
"bm25-find.tests.GetObjectOr404Tests.test_get_object_or_404_queryset_attribute_error",
|
||||
"tests/tests.py"},
|
||||
{"Method", "test_get_object_or_404_bad_class",
|
||||
"bm25-find.tests.GetListObjectOr404Test.test_get_object_or_404_bad_class",
|
||||
"tests/async.py"},
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(rows) / sizeof(rows[0]); i++) {
|
||||
cbm_node_t node = {.project = project,
|
||||
.label = rows[i].label,
|
||||
.name = rows[i].name,
|
||||
.qualified_name = rows[i].qn,
|
||||
.file_path = rows[i].file,
|
||||
.start_line = (int)i + 1,
|
||||
.end_line = (int)i + 2};
|
||||
cbm_store_upsert_node(store, &node);
|
||||
}
|
||||
cbm_store_exec(store, "INSERT INTO nodes_fts(nodes_fts) VALUES('delete-all');");
|
||||
cbm_store_exec(store, "INSERT INTO nodes_fts(rowid, name, qualified_name, label, "
|
||||
"file_path) SELECT id, cbm_camel_split(name), qualified_name, "
|
||||
"label, file_path FROM nodes;");
|
||||
}
|
||||
|
||||
/* The label filter must apply in query (BM25) mode exactly as in structural
|
||||
* mode: `query=Table label=Class` returns the class, and no Method. */
|
||||
TEST(tool_search_graph_bm25_applies_label_filter) {
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
ASSERT_NOT_NULL(srv);
|
||||
cbm_store_t *store = cbm_mcp_server_store(srv);
|
||||
ASSERT_NOT_NULL(store);
|
||||
const char *project = "bm25-find";
|
||||
cbm_mcp_server_set_project(srv, project);
|
||||
bm25_findability_fixture(store, project);
|
||||
|
||||
char *resp = cbm_mcp_server_handle(
|
||||
srv, "{\"jsonrpc\":\"2.0\",\"id\":554,\"method\":\"tools/call\","
|
||||
"\"params\":{\"name\":\"search_graph\",\"arguments\":{"
|
||||
"\"project\":\"bm25-find\",\"query\":\"Table\",\"label\":\"Class\","
|
||||
"\"limit\":5,\"format\":\"json\"}}}");
|
||||
ASSERT_NOT_NULL(resp);
|
||||
char *inner = extract_text_content(resp);
|
||||
ASSERT_NOT_NULL(inner);
|
||||
ASSERT_NOT_NULL(strstr(inner, "\"bm25-find.core.Table.Table\",\"Class\""));
|
||||
ASSERT_NULL(strstr(inner, "\"Method\""));
|
||||
/* The reported total describes the filtered rows, not the unfiltered window. */
|
||||
ASSERT_NOT_NULL(strstr(inner, "\"total\":1"));
|
||||
free(inner);
|
||||
free(resp);
|
||||
cbm_mcp_server_free(srv);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The definition whose NAME is the query ranks first: the `Table` class above
|
||||
* its own methods and above test methods that repeat "table" three times; the
|
||||
* `get_object_or_404` function above the test methods that contain it. */
|
||||
TEST(tool_search_graph_bm25_ranks_exact_name_first) {
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
ASSERT_NOT_NULL(srv);
|
||||
cbm_store_t *store = cbm_mcp_server_store(srv);
|
||||
ASSERT_NOT_NULL(store);
|
||||
const char *project = "bm25-find";
|
||||
cbm_mcp_server_set_project(srv, project);
|
||||
bm25_findability_fixture(store, project);
|
||||
|
||||
char *resp = cbm_mcp_server_handle(
|
||||
srv, "{\"jsonrpc\":\"2.0\",\"id\":555,\"method\":\"tools/call\","
|
||||
"\"params\":{\"name\":\"search_graph\",\"arguments\":{"
|
||||
"\"project\":\"bm25-find\",\"query\":\"Table\",\"limit\":5,\"format\":\"json\"}}}");
|
||||
ASSERT_NOT_NULL(resp);
|
||||
char *inner = extract_text_content(resp);
|
||||
ASSERT_NOT_NULL(inner);
|
||||
const char *rows = strstr(inner, "\"rows\":[");
|
||||
ASSERT_NOT_NULL(rows);
|
||||
const char *first_qn = strstr(rows, "[\"");
|
||||
ASSERT_NOT_NULL(first_qn);
|
||||
ASSERT_EQ(strncmp(first_qn, "[\"bm25-find.core.Table.Table\"", 29), 0);
|
||||
free(inner);
|
||||
free(resp);
|
||||
|
||||
resp = cbm_mcp_server_handle(
|
||||
srv, "{\"jsonrpc\":\"2.0\",\"id\":556,\"method\":\"tools/call\","
|
||||
"\"params\":{\"name\":\"search_graph\",\"arguments\":{"
|
||||
"\"project\":\"bm25-find\",\"query\":\"get_object_or_404\",\"limit\":5,"
|
||||
"\"format\":\"json\"}}}");
|
||||
ASSERT_NOT_NULL(resp);
|
||||
inner = extract_text_content(resp);
|
||||
ASSERT_NOT_NULL(inner);
|
||||
rows = strstr(inner, "\"rows\":[");
|
||||
ASSERT_NOT_NULL(rows);
|
||||
first_qn = strstr(rows, "[\"");
|
||||
ASSERT_NOT_NULL(first_qn);
|
||||
ASSERT_EQ(strncmp(first_qn, "[\"bm25-find.shortcuts.get_object_or_404\"", 40), 0);
|
||||
free(inner);
|
||||
free(resp);
|
||||
cbm_mcp_server_free(srv);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* `query` selects the BM25 fast path, which returns before semantic_query is
|
||||
* evaluated. Accepting both therefore used to report success while silently
|
||||
* discarding one of the caller's two requested result sets. The contract is
|
||||
@@ -5583,9 +5701,9 @@ TEST(tool_check_index_coverage_reports_truncation_marker_issue963) {
|
||||
|
||||
/* The marked file: both real ranges survive, the marker is flagged, and the
|
||||
* "12" from the marker never becomes a range of its own. */
|
||||
char *marked =
|
||||
cbm_mcp_handle_tool(srv, "check_index_coverage",
|
||||
"{\"project\":\"coverage-marker\",\"paths\":[\"src/marked.c\"],\"format\":\"json\"}");
|
||||
char *marked = cbm_mcp_handle_tool(
|
||||
srv, "check_index_coverage",
|
||||
"{\"project\":\"coverage-marker\",\"paths\":[\"src/marked.c\"],\"format\":\"json\"}");
|
||||
ASSERT_NOT_NULL(marked);
|
||||
char *marked_inner = extract_text_content(marked);
|
||||
ASSERT_NOT_NULL(marked_inner);
|
||||
@@ -5597,9 +5715,9 @@ TEST(tool_check_index_coverage_reports_truncation_marker_issue963) {
|
||||
free(marked);
|
||||
|
||||
/* The same ranges without a marker must NOT be reported as truncated. */
|
||||
char *plain =
|
||||
cbm_mcp_handle_tool(srv, "check_index_coverage",
|
||||
"{\"project\":\"coverage-marker\",\"paths\":[\"src/plain.c\"],\"format\":\"json\"}");
|
||||
char *plain = cbm_mcp_handle_tool(
|
||||
srv, "check_index_coverage",
|
||||
"{\"project\":\"coverage-marker\",\"paths\":[\"src/plain.c\"],\"format\":\"json\"}");
|
||||
ASSERT_NOT_NULL(plain);
|
||||
char *plain_inner = extract_text_content(plain);
|
||||
ASSERT_NOT_NULL(plain_inner);
|
||||
@@ -5610,9 +5728,9 @@ TEST(tool_check_index_coverage_reports_truncation_marker_issue963) {
|
||||
|
||||
/* The reader's own limit stops the list early, so it must say so even
|
||||
* though the producer sent no marker. */
|
||||
char *widest =
|
||||
cbm_mcp_handle_tool(srv, "check_index_coverage",
|
||||
"{\"project\":\"coverage-marker\",\"paths\":[\"src/wide.c\"],\"format\":\"json\"}");
|
||||
char *widest = cbm_mcp_handle_tool(
|
||||
srv, "check_index_coverage",
|
||||
"{\"project\":\"coverage-marker\",\"paths\":[\"src/wide.c\"],\"format\":\"json\"}");
|
||||
ASSERT_NOT_NULL(widest);
|
||||
char *wide_inner = extract_text_content(widest);
|
||||
ASSERT_NOT_NULL(wide_inner);
|
||||
@@ -20418,6 +20536,8 @@ SUITE(mcp) {
|
||||
RUN_TEST(tool_output_byte_budgets);
|
||||
RUN_TEST(tool_search_graph_query_honors_file_pattern_issue552);
|
||||
RUN_TEST(tool_search_graph_bm25_reports_candidate_saturation);
|
||||
RUN_TEST(tool_search_graph_bm25_applies_label_filter);
|
||||
RUN_TEST(tool_search_graph_bm25_ranks_exact_name_first);
|
||||
RUN_TEST(tool_search_graph_rejects_bm25_and_semantic_query_together);
|
||||
RUN_TEST(tool_search_graph_semantic_ceiling_never_emits_unusable_continuation);
|
||||
RUN_TEST(tool_search_graph_semantic_pagination_is_lossless_and_independent);
|
||||
|
||||
+130
-24
@@ -112,21 +112,21 @@ static const char *PY_CLEAN = "def ok():\n"
|
||||
* Guards against over-suppression: the preprocessor explains the guarded
|
||||
* region but explains nothing about the garbage, so BOTH must stay flagged
|
||||
* and they must be reported as two separate ranges, not one big one. */
|
||||
static const char *C_IFDEF_SPLIT_PLUS_GARBAGE = "#include <stdio.h>\n" /* 1 */
|
||||
"\n" /* 2 */
|
||||
"void ok_before(void) { }\n" /* 3 */
|
||||
"\n" /* 4 */
|
||||
"#ifdef FEATURE_A\n" /* 5 */
|
||||
"static int guarded(int x) {\n" /* 6 */
|
||||
"#else\n" /* 7 */
|
||||
static const char *C_IFDEF_SPLIT_PLUS_GARBAGE = "#include <stdio.h>\n" /* 1 */
|
||||
"\n" /* 2 */
|
||||
"void ok_before(void) { }\n" /* 3 */
|
||||
"\n" /* 4 */
|
||||
"#ifdef FEATURE_A\n" /* 5 */
|
||||
"static int guarded(int x) {\n" /* 6 */
|
||||
"#else\n" /* 7 */
|
||||
"static int guarded_alt(int x) {\n" /* 8 */
|
||||
"#endif\n" /* 9 */
|
||||
" return x + 1;\n" /* 10 */
|
||||
"}\n" /* 11 */
|
||||
"\n" /* 12 */
|
||||
"%%% ((( &&& ))) %%%\n" /* 13 */
|
||||
"\n" /* 14 */
|
||||
"void ok_after(void) { }\n"; /* 15 */
|
||||
"#endif\n" /* 9 */
|
||||
" return x + 1;\n" /* 10 */
|
||||
"}\n" /* 11 */
|
||||
"\n" /* 12 */
|
||||
"%%% ((( &&& ))) %%%\n" /* 13 */
|
||||
"\n" /* 14 */
|
||||
"void ok_after(void) { }\n"; /* 15 */
|
||||
|
||||
/* Perl formats have a line-oriented body terminated by a lone dot. The
|
||||
* following named sub pins the important recovery boundary: a grammar must
|
||||
@@ -494,7 +494,8 @@ TEST(real_error_before_eof_still_flagged_without_final_newline_issue1610) {
|
||||
bool has_ranges = r->error_ranges != NULL;
|
||||
cbm_free_result(r);
|
||||
if (!flagged) {
|
||||
FAIL("a real mid-file parse failure must still be reported when the file also lacks its final newline");
|
||||
FAIL("a real mid-file parse failure must still be reported when the file also lacks its "
|
||||
"final newline");
|
||||
}
|
||||
if (!has_ranges) {
|
||||
FAIL("a reported failure must still name its line range");
|
||||
@@ -529,11 +530,8 @@ TEST(perl_format_followed_by_named_sub_is_complete_issue1838) {
|
||||
bool has_error_ranges = r->error_ranges != NULL;
|
||||
bool has_following_sub = has_def(r, "after_format");
|
||||
if (partial || error_regions != 0 || has_error_ranges || !has_following_sub) {
|
||||
fprintf(stderr,
|
||||
" Perl format result: partial=%d regions=%d ranges=%s following_sub=%d\n",
|
||||
partial,
|
||||
error_regions,
|
||||
r->error_ranges ? r->error_ranges : "(none)",
|
||||
fprintf(stderr, " Perl format result: partial=%d regions=%d ranges=%s following_sub=%d\n",
|
||||
partial, error_regions, r->error_ranges ? r->error_ranges : "(none)",
|
||||
has_following_sub);
|
||||
cbm_free_result(r);
|
||||
FAIL("a valid Perl format and its following named sub must parse completely");
|
||||
@@ -619,7 +617,8 @@ TEST(width_bearing_error_at_eof_still_flagged_with_trailing_blank_issue1746) {
|
||||
bool flagged = r->parse_incomplete;
|
||||
cbm_free_result(r);
|
||||
if (!flagged) {
|
||||
FAIL("a width-bearing parse failure at EOF must still be reported when the file ends in blanks");
|
||||
FAIL("a width-bearing parse failure at EOF must still be reported when the file ends in "
|
||||
"blanks");
|
||||
}
|
||||
PASS();
|
||||
}
|
||||
@@ -734,7 +733,6 @@ TEST(c_clean_file_stays_unflagged_after_refinement) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
|
||||
/* The whole-file class, and the reason the parse_unusable kind exists.
|
||||
*
|
||||
* The Phase 2 refinement that narrows a whole-file range using the
|
||||
@@ -806,18 +804,31 @@ TEST(c_ifdef_split_is_partial_never_unusable) {
|
||||
* says so, instead of leaving a wrong note in the plan. (The plan's Phase 0
|
||||
* also listed the pointer form as failing. It does not fail today.) */
|
||||
TEST(c_thread_local_grammar_limit_is_pinned_issue963) {
|
||||
/* The init form used to read as "parses clean", but that was a masking
|
||||
* effect, not a clean parse: the grammar leaves an ERROR on line 1 and
|
||||
* salvages a one-line Variable named `int` from it, which the old
|
||||
* all-or-nothing recovery rule accepted as evidence the line was
|
||||
* understood. Since 2026-09-16 a one-line salvage is not evidence, so the
|
||||
* line is flagged — honest, because `x` is what the graph lacks. */
|
||||
CBMFileResult *ok = do_extract("static _Thread_local int x = 0;\n"
|
||||
"void f(void) { x = 1; }\n",
|
||||
CBM_LANG_C, "tls_init.c");
|
||||
ASSERT_NOT_NULL(ok);
|
||||
ASSERT_FALSE(ok->parse_incomplete);
|
||||
ASSERT_TRUE(ok->parse_incomplete);
|
||||
ASSERT_NOT_NULL(ok->error_ranges);
|
||||
ASSERT_STR_EQ("1-1", ok->error_ranges);
|
||||
ASSERT_TRUE(has_def(ok, "f"));
|
||||
cbm_free_result(ok);
|
||||
|
||||
/* The pointer form: the same masking, the same honest answer now. */
|
||||
CBMFileResult *ptr = do_extract("static _Thread_local int *p;\n"
|
||||
"void f(void) { p = 0; }\n",
|
||||
CBM_LANG_C, "tls_ptr.c");
|
||||
ASSERT_NOT_NULL(ptr);
|
||||
ASSERT_FALSE(ptr->parse_incomplete);
|
||||
ASSERT_TRUE(ptr->parse_incomplete);
|
||||
ASSERT_NOT_NULL(ptr->error_ranges);
|
||||
ASSERT_STR_EQ("1-1", ptr->error_ranges);
|
||||
ASSERT_TRUE(has_def(ptr, "f"));
|
||||
cbm_free_result(ptr);
|
||||
|
||||
CBMFileResult *arr = do_extract("static _Thread_local char b[8];\n"
|
||||
@@ -879,6 +890,99 @@ TEST(coverage_range_never_ends_past_the_last_line_issue963) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── Residual ranges (2026-09-16) ─────────────────────────────────────────
|
||||
* The recovery subtraction used to be all-or-nothing: a region stayed flagged
|
||||
* whole unless every one of its lines was covered by a definition that started
|
||||
* inside it. On torvalds/linux one ERROR node that swallowed the second half of
|
||||
* kernel/sched/core.c (lines 5522-11284) survived on the strength of the
|
||||
* comment and macro lines BETWEEN its 286 extracted functions, and
|
||||
* check_index_coverage told a reader 68 % of the scheduler was unindexed. The
|
||||
* ranges must now name only the lines no extracted definition covers. */
|
||||
|
||||
/* A brace-unbalanced junk line between two clean functions: the recovery
|
||||
* walker still extracts both functions, so the reported range must not cover
|
||||
* either of them, only the junk. */
|
||||
static const char *C_JUNK_BETWEEN_FUNCTIONS = "int alpha(void) {\n" /* 1 */
|
||||
" return 1;\n" /* 2 */
|
||||
"}\n" /* 3 */
|
||||
"\n" /* 4 */
|
||||
"} ] junk ( {\n" /* 5 */
|
||||
"\n" /* 6 */
|
||||
"int beta(void) {\n" /* 7 */
|
||||
" return 2;\n" /* 8 */
|
||||
"}\n" /* 9 */
|
||||
"\n" /* 10 */
|
||||
"int gamma(void) {\n" /* 11 */
|
||||
" return 3;\n" /* 12 */
|
||||
"}\n"; /* 13 */
|
||||
|
||||
static int range_covers_line(const char *ranges, unsigned int line) {
|
||||
const char *p = ranges;
|
||||
while (p && *p) {
|
||||
unsigned int s = 0;
|
||||
unsigned int e = 0;
|
||||
if (sscanf(p, "%u-%u", &s, &e) == 2 && s <= line && line <= e) {
|
||||
return 1;
|
||||
}
|
||||
p = strchr(p, ',');
|
||||
if (p) {
|
||||
p++;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
TEST(coverage_range_never_covers_an_extracted_definition) {
|
||||
CBMFileResult *r = do_extract(C_JUNK_BETWEEN_FUNCTIONS, CBM_LANG_C, "junk.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_TRUE(has_def(r, "alpha"));
|
||||
ASSERT_TRUE(has_def(r, "beta"));
|
||||
ASSERT_TRUE(has_def(r, "gamma"));
|
||||
ASSERT_TRUE(r->parse_incomplete);
|
||||
ASSERT_NOT_NULL(r->error_ranges);
|
||||
/* Every extracted definition's own lines are in the graph, so no reported
|
||||
* range may cover its start line. */
|
||||
for (int i = 0; i < r->defs.count; i++) {
|
||||
const CBMDefinition *d = &r->defs.items[i];
|
||||
if (!d->label || strcmp(d->label, "Module") == 0) {
|
||||
continue;
|
||||
}
|
||||
ASSERT_FALSE(range_covers_line(r->error_ranges, d->start_line));
|
||||
}
|
||||
/* And the junk line itself is still reported. */
|
||||
ASSERT_TRUE(range_covers_line(r->error_ranges, 5u));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The lines between recovered definitions are comments and blanks here: a gap
|
||||
* with no code in it is not a miss, so nothing may be reported for it. The
|
||||
* junk line stays reported. */
|
||||
static const char *C_JUNK_WITH_COMMENT_GAPS = "int alpha(void) {\n" /* 1 */
|
||||
" return 1;\n" /* 2 */
|
||||
"}\n" /* 3 */
|
||||
"/* between alpha and the junk */\n" /* 4 */
|
||||
"} ] junk ( {\n" /* 5 */
|
||||
"// trailing note\n" /* 6 */
|
||||
"int beta(void) {\n" /* 7 */
|
||||
" return 2;\n" /* 8 */
|
||||
"}\n"; /* 9 */
|
||||
|
||||
TEST(coverage_gap_of_only_comments_is_not_a_miss) {
|
||||
CBMFileResult *r = do_extract(C_JUNK_WITH_COMMENT_GAPS, CBM_LANG_C, "gaps.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_TRUE(has_def(r, "alpha"));
|
||||
ASSERT_TRUE(has_def(r, "beta"));
|
||||
ASSERT_TRUE(r->parse_incomplete);
|
||||
ASSERT_NOT_NULL(r->error_ranges);
|
||||
ASSERT_TRUE(range_covers_line(r->error_ranges, 5u));
|
||||
ASSERT_FALSE(range_covers_line(r->error_ranges, 1u));
|
||||
ASSERT_FALSE(range_covers_line(r->error_ranges, 7u));
|
||||
ASSERT_FALSE(range_covers_line(r->error_ranges, 9u));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(parse_coverage) {
|
||||
RUN_TEST(c_ifdef_split_brace_sets_parse_incomplete);
|
||||
RUN_TEST(c_ifdef_split_brace_neighbors_still_extracted);
|
||||
@@ -917,4 +1021,6 @@ SUITE(parse_coverage) {
|
||||
RUN_TEST(c_thread_local_grammar_limit_is_pinned_issue963);
|
||||
RUN_TEST(coverage_repeated_error_line_reports_one_range_issue963);
|
||||
RUN_TEST(coverage_range_never_ends_past_the_last_line_issue963);
|
||||
RUN_TEST(coverage_range_never_covers_an_extracted_definition);
|
||||
RUN_TEST(coverage_gap_of_only_comments_is_not_a_miss);
|
||||
}
|
||||
@@ -5710,6 +5710,123 @@ TEST(pipeline_python_receiver_suppresses_weak_method_edge) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The member guard's one exemption (2026-09-16, v0.10.8 → v0.11.0 A/B on
|
||||
* django/django): a member call whose receiver is an attribute chain rooted at
|
||||
* self/cls, whose callee has exactly ONE definition in the project and is not a
|
||||
* builtin type's own method keeps its unique_name edge —
|
||||
* `self.compiler.apply_converters()` names the only apply_converters there is.
|
||||
* A bare parameter receiver and the builtin-member class the guard was built
|
||||
* for (`parts.extend()` -> a project ListMixin.extend) stay suppressed.
|
||||
* Fewer than 50 files exercises pass_calls.c. */
|
||||
TEST(pipeline_python_receiver_keeps_specific_unique_name_member_call) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "/tmp/cbm_python_uniq_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmp)) {
|
||||
FAIL("tmpdir");
|
||||
}
|
||||
|
||||
write_temp_file(tmp, "compiler.py",
|
||||
"class SQLCompiler:\n"
|
||||
" def apply_converters(self, rows):\n"
|
||||
" return rows\n");
|
||||
write_temp_file(tmp, "mixin.py",
|
||||
"class ListMixin:\n"
|
||||
" def extend(self, other):\n"
|
||||
" return other\n");
|
||||
write_temp_file(tmp, "caller.py",
|
||||
"class RawIterable:\n"
|
||||
" def __init__(self, compiler):\n"
|
||||
" self.compiler = compiler\n"
|
||||
"\n"
|
||||
" def iterate(self):\n"
|
||||
" return self.compiler.apply_converters([])\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def collect(parts):\n"
|
||||
" parts.extend([1])\n"
|
||||
" return parts\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def handed_in(compiler):\n"
|
||||
" return compiler.apply_converters([])\n");
|
||||
|
||||
char db_path[512];
|
||||
snprintf(db_path, sizeof(db_path), "%s/python_uniq.db", tmp);
|
||||
cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
|
||||
ASSERT_NOT_NULL(p);
|
||||
ASSERT_EQ(cbm_pipeline_run(p), 0);
|
||||
const char *project = cbm_pipeline_project_name(p);
|
||||
|
||||
cbm_store_t *s = cbm_store_open_path(db_path);
|
||||
ASSERT_NOT_NULL(s);
|
||||
|
||||
/* POSITIVE: the only apply_converters in the project binds through
|
||||
* self.compiler, an object the class owns. */
|
||||
ASSERT_TRUE(cross_file_call_exists(s, project, "iterate", "apply_converters"));
|
||||
/* NEGATIVE: the same unique name through a bare parameter carries no
|
||||
* ownership evidence and stays suppressed (#1276's own shape). */
|
||||
ASSERT_FALSE(cross_file_call_exists(s, project, "handed_in", "apply_converters"));
|
||||
/* NEGATIVE: list.extend on a parameter must not bind ListMixin.extend. */
|
||||
ASSERT_FALSE(cross_file_call_exists(s, project, "collect", "extend"));
|
||||
/* Tripwire against a vacuous run. */
|
||||
ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 1);
|
||||
|
||||
cbm_store_close(s);
|
||||
cbm_pipeline_free(p);
|
||||
th_rmtree(tmp);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Embedded-script hosts (2026-09-16 probe on JetBrains/Exposed): a member call
|
||||
* inside an HTML <script> body is extracted as JavaScript and carries the JS
|
||||
* receiver flag, but the weak-member guard was gated on the FILE language, so
|
||||
* 4,207 generated Dokka pages bound `localStorage.getItem` to a docs bundle
|
||||
* function through unique_name. HTML (and Vue/Svelte/Astro) join the gate.
|
||||
* POSITIVE tripwire: a bare project call in a plain .js file still resolves. */
|
||||
TEST(pipeline_html_embedded_member_call_stays_unbound) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "/tmp/cbm_html_member_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmp)) {
|
||||
FAIL("tmpdir");
|
||||
}
|
||||
|
||||
/* One directory level each: write_temp_file creates a single parent. */
|
||||
write_temp_file(tmp, "scripts/storage.js",
|
||||
"function getItem(key) {\n"
|
||||
" return key;\n"
|
||||
"}\n");
|
||||
write_temp_file(tmp, "scripts/theme.js",
|
||||
"import { getItem } from './storage.js';\n"
|
||||
"\n"
|
||||
"function loadTheme() {\n"
|
||||
" return getItem('theme');\n"
|
||||
"}\n");
|
||||
write_temp_file(tmp, "docs/index.html",
|
||||
"<html><head><script>\n"
|
||||
"var mode = localStorage.getItem('dokka-dark-mode');\n"
|
||||
"</script></head><body></body></html>\n");
|
||||
|
||||
char db_path[512];
|
||||
snprintf(db_path, sizeof(db_path), "%s/html_member.db", tmp);
|
||||
cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
|
||||
ASSERT_NOT_NULL(p);
|
||||
ASSERT_EQ(cbm_pipeline_run(p), 0);
|
||||
const char *project = cbm_pipeline_project_name(p);
|
||||
|
||||
cbm_store_t *s = cbm_store_open_path(db_path);
|
||||
ASSERT_NOT_NULL(s);
|
||||
|
||||
/* NEGATIVE: localStorage's own method must not bind the docs bundle. */
|
||||
ASSERT_FALSE(cross_file_call_exists(s, project, "index", "getItem"));
|
||||
/* POSITIVE: the bare project call in storage.js resolves as before. */
|
||||
ASSERT_TRUE(cross_file_call_exists(s, project, "loadTheme", "getItem"));
|
||||
|
||||
cbm_store_close(s);
|
||||
cbm_pipeline_free(p);
|
||||
th_rmtree(tmp);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Fixture for the #1928 cross-language reference-guard probes (sequential and
|
||||
* parallel twins). pad_files > 0 adds filler files to push the index over the
|
||||
* parallel-pipeline threshold, since USAGE/WRITES/READS have one resolver per
|
||||
@@ -6628,6 +6745,55 @@ TEST(pipeline_native_fetch_classified_as_http_calls) {
|
||||
* no call arguments at all. Alamofire/URLSession were already in the service
|
||||
* pattern table; the URL simply never reached it. This is the Swift twin of
|
||||
* the TypeScript fetch case above. */
|
||||
/* The shape real Swift actually writes: the URL is built by a constructor and
|
||||
* force-unwrapped, so the literal is two levels below the argument list. This
|
||||
* is what issue #1892 reported from a real project. */
|
||||
TEST(pipeline_swift_nested_url_makes_route_issue1892) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "/tmp/cbm_swiftnested_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmp)) {
|
||||
FAIL("tmpdir");
|
||||
}
|
||||
|
||||
write_temp_file(tmp, "Sources/Client.swift",
|
||||
"import Foundation\n"
|
||||
"final class Client {\n"
|
||||
" func listWidgets() {\n"
|
||||
" URLSession.shared.dataTask(with: "
|
||||
"URL(string: \"/api/v1/widgets\")!)\n"
|
||||
" }\n"
|
||||
"}\n");
|
||||
|
||||
char db_path[512];
|
||||
snprintf(db_path, sizeof(db_path), "%s/swiftnested.db", tmp);
|
||||
cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
|
||||
ASSERT_NOT_NULL(p);
|
||||
ASSERT_EQ(cbm_pipeline_run(p), 0);
|
||||
const char *project = cbm_pipeline_project_name(p);
|
||||
|
||||
cbm_store_t *s = cbm_store_open_path(db_path);
|
||||
ASSERT_NOT_NULL(s);
|
||||
|
||||
ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 1);
|
||||
|
||||
cbm_node_t *routes = NULL;
|
||||
int route_count = 0;
|
||||
cbm_store_find_nodes_by_label(s, project, "Route", &routes, &route_count);
|
||||
int widget_routes = 0;
|
||||
for (int i = 0; i < route_count; i++) {
|
||||
if (routes[i].qualified_name && strstr(routes[i].qualified_name, "/api/v1/widgets")) {
|
||||
widget_routes++;
|
||||
}
|
||||
}
|
||||
cbm_store_free_nodes(routes, route_count);
|
||||
ASSERT_GTE(widget_routes, 1);
|
||||
|
||||
cbm_store_close(s);
|
||||
cbm_pipeline_free(p);
|
||||
th_rmtree(tmp);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(pipeline_swift_http_call_makes_route_issue1892) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "/tmp/cbm_swifthttp_XXXXXX");
|
||||
@@ -7589,6 +7755,60 @@ TEST(pipeline_python_project) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* `#include <linux/device.h>` from arch/x/bugs.c: two headers end with the
|
||||
* include path (include/linux/device.h, tools/virtio/linux/device.h) and each
|
||||
* declares `struct device`. The exact-file lookup returned the first matching
|
||||
* node in by-name bucket order — the workers' merge order, different run to
|
||||
* run: 5,821 kernel IMPORTS edges moved between two indexes of one tree and
|
||||
* the CALLS resolved through their import maps moved with them. The target is
|
||||
* the least nested File node, whichever order the nodes were registered in. */
|
||||
static void add_device_header(cbm_gbuf_t *gb, const char *rel, const char *qn_stem) {
|
||||
char fqn[256];
|
||||
snprintf(fqn, sizeof(fqn), "%s.h.__file__", qn_stem);
|
||||
cbm_gbuf_upsert_node(gb, "File", "device.h", fqn, rel, 0, 0, "{}");
|
||||
char cqn[256];
|
||||
snprintf(cqn, sizeof(cqn), "%s.device", qn_stem);
|
||||
cbm_gbuf_upsert_node(gb, "Class", "device", cqn, rel, 10, 40, "{}");
|
||||
}
|
||||
|
||||
static const cbm_gbuf_node_t *resolve_device_h_from(cbm_gbuf_t *gb) {
|
||||
atomic_int cancelled = 0;
|
||||
cbm_pipeline_ctx_t ctx = {
|
||||
.project_name = "p",
|
||||
.repo_path = "/tmp/p",
|
||||
.gbuf = gb,
|
||||
.registry = NULL,
|
||||
.cancelled = &cancelled,
|
||||
};
|
||||
CBMImport imp = {0};
|
||||
imp.module_path = "linux/device.h";
|
||||
imp.local_name = "h";
|
||||
return cbm_pipeline_resolve_import_node(&ctx, "arch/x/bugs.c", "p.arch.x.bugs.c.__file__", &imp,
|
||||
NULL);
|
||||
}
|
||||
|
||||
TEST(pipeline_header_include_target_is_independent_of_registration_order) {
|
||||
cbm_gbuf_t *a = cbm_gbuf_new("p", "/tmp/cbm_include_order_a");
|
||||
cbm_gbuf_t *b = cbm_gbuf_new("p", "/tmp/cbm_include_order_b");
|
||||
ASSERT_NOT_NULL(a);
|
||||
ASSERT_NOT_NULL(b);
|
||||
add_device_header(a, "include/linux/device.h", "p.include.linux.device");
|
||||
add_device_header(a, "tools/virtio/linux/device.h", "p.tools.virtio.linux.device");
|
||||
add_device_header(b, "tools/virtio/linux/device.h", "p.tools.virtio.linux.device");
|
||||
add_device_header(b, "include/linux/device.h", "p.include.linux.device");
|
||||
|
||||
const cbm_gbuf_node_t *ta = resolve_device_h_from(a);
|
||||
const cbm_gbuf_node_t *tb = resolve_device_h_from(b);
|
||||
ASSERT_NOT_NULL(ta);
|
||||
ASSERT_NOT_NULL(tb);
|
||||
ASSERT_STR_EQ(ta->qualified_name, "p.include.linux.device.h.__file__");
|
||||
ASSERT_STR_EQ(tb->qualified_name, "p.include.linux.device.h.__file__");
|
||||
|
||||
cbm_gbuf_free(a);
|
||||
cbm_gbuf_free(b);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #768 end-to-end: `import { A, B } from './lib'` must survive the REAL
|
||||
* pipeline (extract -> gbuf dedup -> raw SQLite dump) as TWO IMPORTS edges
|
||||
* with distinct local_name — and the dumped DB must satisfy its own schema.
|
||||
@@ -10517,6 +10737,61 @@ TEST(registry_receiver_chain_keeps_project_extension_issue1893) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A factory chain into a nested type: Settings.builder().putList names the only
|
||||
* putList in the project, Settings.Builder.putList, and Settings — the chain's
|
||||
* root — is in the candidate's ancestry even though the candidate's immediate
|
||||
* parent (Builder) is not spelled in the chain. The parent-only rule refused
|
||||
* 9,473 such unique-name calls on elastic/elasticsearch (v0.10.8 → v0.11.0 A/B,
|
||||
* 2026-09-16). */
|
||||
TEST(registry_receiver_chain_admits_factory_chain_into_nested_type) {
|
||||
cbm_registry_t *reg = cbm_registry_new();
|
||||
cbm_registry_add(reg, "putList", "org.elasticsearch.common.settings.Settings.Builder.putList",
|
||||
"Method");
|
||||
|
||||
cbm_resolution_t r = cbm_registry_resolve(
|
||||
reg, "Settings.builder().putList", "org.elasticsearch.index.IndexSettings", NULL, NULL, 0);
|
||||
ASSERT_STR_EQ(r.qualified_name, "org.elasticsearch.common.settings.Settings.Builder.putList");
|
||||
ASSERT_STR_EQ(r.strategy, "unique_name");
|
||||
|
||||
/* The same shape through a value in between: RequestOptions.DEFAULT
|
||||
* .toBuilder().setWarningsHandler -> RequestOptions.Builder.setWarningsHandler. */
|
||||
cbm_registry_add(reg, "setWarningsHandler",
|
||||
"org.elasticsearch.client.RequestOptions.Builder.setWarningsHandler",
|
||||
"Method");
|
||||
r = cbm_registry_resolve(reg, "RequestOptions.DEFAULT.toBuilder().setWarningsHandler",
|
||||
"org.elasticsearch.client.Rest", NULL, NULL, 0);
|
||||
ASSERT_STR_EQ(r.qualified_name,
|
||||
"org.elasticsearch.client.RequestOptions.Builder.setWarningsHandler");
|
||||
|
||||
cbm_registry_free(reg);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The ancestry rule must not widen the gate to foreign roots: Base64 is the
|
||||
* JDK's, so the project's DocOffsetsCodec.getEncoder stays refused, exactly as
|
||||
* #1893's URLSession case above. */
|
||||
TEST(registry_receiver_chain_still_refuses_foreign_root_with_ancestry_rule) {
|
||||
cbm_registry_t *reg = cbm_registry_new();
|
||||
cbm_registry_add(reg, "getEncoder", "org.elasticsearch.index.codec.DocOffsetsCodec.getEncoder",
|
||||
"Method");
|
||||
|
||||
cbm_resolution_t r = cbm_registry_resolve(
|
||||
reg, "Base64.getEncoder", "org.elasticsearch.index.IndexSettings", NULL, NULL, 0);
|
||||
ASSERT_NULL(r.qualified_name);
|
||||
|
||||
/* Nor may a package segment admit it: Math.toIntExact must not bind
|
||||
* org.elasticsearch.common.Math.toIntExact through "Math" appearing as an
|
||||
* ancestry segment ONLY IF that segment really is the type — here it is, and
|
||||
* that is the correct outcome (the project's own Math.toIntExact). */
|
||||
cbm_registry_add(reg, "toIntExact", "org.elasticsearch.common.Math.toIntExact", "Method");
|
||||
r = cbm_registry_resolve(reg, "Math.toIntExact", "org.elasticsearch.index.IndexSettings", NULL,
|
||||
NULL, 0);
|
||||
ASSERT_STR_EQ(r.qualified_name, "org.elasticsearch.common.Math.toIntExact");
|
||||
|
||||
cbm_registry_free(reg);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A lower-case root names a value, whose type the chain does not show. The gate
|
||||
* must not look at it, or every ordinary vm.load style call would be refused. */
|
||||
TEST(registry_receiver_chain_ignores_lowercase_root_issue1893) {
|
||||
@@ -14841,6 +15116,8 @@ SUITE(pipeline) {
|
||||
#endif
|
||||
RUN_TEST(pipeline_tsjs_receiver_suppresses_weak_method_edge);
|
||||
RUN_TEST(pipeline_python_receiver_suppresses_weak_method_edge);
|
||||
RUN_TEST(pipeline_python_receiver_keeps_specific_unique_name_member_call);
|
||||
RUN_TEST(pipeline_html_embedded_member_call_stays_unbound);
|
||||
RUN_TEST(pipeline_go_rw_usage_never_cross_into_c);
|
||||
RUN_TEST(pipeline_go_rw_usage_never_cross_into_c_parallel);
|
||||
RUN_TEST(pipeline_go_bare_ref_never_binds_field);
|
||||
@@ -14853,6 +15130,7 @@ SUITE(pipeline) {
|
||||
RUN_TEST(pipeline_parallel_rust_cross_only_macro_hidden_gets_synthetic_carrier);
|
||||
RUN_TEST(pipeline_arg_url_rejects_non_http_slash_arguments);
|
||||
RUN_TEST(pipeline_native_fetch_classified_as_http_calls);
|
||||
RUN_TEST(pipeline_swift_nested_url_makes_route_issue1892);
|
||||
RUN_TEST(pipeline_swift_http_call_makes_route_issue1892);
|
||||
RUN_TEST(pipeline_native_fetch_parallel_classified_as_http_calls);
|
||||
RUN_TEST(pipeline_local_fetch_shadow_not_classified_as_http);
|
||||
@@ -14876,6 +15154,7 @@ SUITE(pipeline) {
|
||||
RUN_TEST(usages_kotlin_no_duplicate_calls);
|
||||
/* Language integration tests */
|
||||
RUN_TEST(pipeline_python_project);
|
||||
RUN_TEST(pipeline_header_include_target_is_independent_of_registration_order);
|
||||
RUN_TEST(pipeline_imports_multi_symbol_edges);
|
||||
RUN_TEST(pipeline_go_cross_package_call);
|
||||
RUN_TEST(pipeline_swift_cross_package_import);
|
||||
@@ -15019,6 +15298,8 @@ SUITE(pipeline) {
|
||||
RUN_TEST(registry_receiver_chain_refuses_library_unique_name_issue1893);
|
||||
RUN_TEST(registry_receiver_chain_refuses_library_suffix_match_issue1893);
|
||||
RUN_TEST(registry_receiver_chain_keeps_project_extension_issue1893);
|
||||
RUN_TEST(registry_receiver_chain_admits_factory_chain_into_nested_type);
|
||||
RUN_TEST(registry_receiver_chain_still_refuses_foreign_root_with_ancestry_rule);
|
||||
RUN_TEST(registry_receiver_chain_ignores_lowercase_root_issue1893);
|
||||
RUN_TEST(registry_receiver_chain_ignores_bare_name_issue1893);
|
||||
RUN_TEST(registry_fuzzy_confidence_single);
|
||||
|
||||
@@ -820,6 +820,96 @@ TEST(perl_suppress_keeps_high_confidence_and_genuine_calls) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* 2026-09-16 probe on torvalds/linux: a Makefile target bound the C function
|
||||
* `sk_psock.eval` through unique_name. Build and configuration languages have
|
||||
* no cross-language call semantics, so for them a unique match into another
|
||||
* language is a collision by construction; a code caller keeps #1572. */
|
||||
TEST(cross_language_config_caller_drops_unique_name_too) {
|
||||
ASSERT_TRUE(cbm_suppress_cross_language_suffix_match(CBM_LANG_MAKEFILE, "include/linux/skmsg.h",
|
||||
"unique_name"));
|
||||
ASSERT_TRUE(
|
||||
cbm_suppress_cross_language_suffix_match(CBM_LANG_CMAKE, "src/main.c", "unique_name"));
|
||||
ASSERT_TRUE(
|
||||
cbm_suppress_cross_language_suffix_match(CBM_LANG_YAML, "app/models.py", "unique_name"));
|
||||
/* A code caller's unique_name into another language is still #1572. */
|
||||
ASSERT_FALSE(cbm_suppress_cross_language_suffix_match(
|
||||
CBM_LANG_PYTHON, "web/src/pages/Editor.js", "unique_name"));
|
||||
/* Same-language config targets are untouched. */
|
||||
ASSERT_FALSE(
|
||||
cbm_suppress_cross_language_suffix_match(CBM_LANG_MAKEFILE, "lib/Makefile", "unique_name"));
|
||||
/* Receiver-aware strategies are never this guard's business. */
|
||||
ASSERT_FALSE(
|
||||
cbm_suppress_cross_language_suffix_match(CBM_LANG_MAKEFILE, "src/main.c", "same_module"));
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Same-named candidates that tie on test-status and namespace proximity used
|
||||
* to be settled by bucket position, i.e. by the order files were registered:
|
||||
* two indexes of one kernel tree differed by 632 CALLS edges, `dev_name`
|
||||
* landing on any of twenty same-named struct fields or on nothing at all.
|
||||
* The tie is now a function of the candidate set: the least nested
|
||||
* definition, then the smaller QN — whichever order the registry was built
|
||||
* in (O9). */
|
||||
TEST(registry_tie_break_is_independent_of_registration_order) {
|
||||
const char *cands[] = {
|
||||
"proj.drivers.media.cec.i2c.ch7322.ch7322_conn_match.dev_name", /* struct field */
|
||||
"proj.sound.soc.codecs.tas2783-sdw.tas2783_prv.dev_name", /* struct field */
|
||||
"proj.include.linux.device.dev_name", /* the function */
|
||||
"proj.arch.um.drivers.pty.pty_chan.dev_name", /* struct field */
|
||||
};
|
||||
const char *labels[] = {"Field", "Field", "Function", "Field"};
|
||||
const int n = 4;
|
||||
|
||||
cbm_registry_t *forward = cbm_registry_new();
|
||||
cbm_registry_t *backward = cbm_registry_new();
|
||||
for (int i = 0; i < n; i++) {
|
||||
cbm_registry_add(forward, "dev_name", cands[i], labels[i]);
|
||||
cbm_registry_add(backward, "dev_name", cands[n - 1 - i], labels[n - 1 - i]);
|
||||
}
|
||||
|
||||
/* A far-away caller with no imports: every candidate scores the same. */
|
||||
cbm_resolution_t f =
|
||||
cbm_registry_resolve(forward, "dev_name", "proj.kernel.irq.msi", NULL, NULL, 0);
|
||||
cbm_resolution_t b =
|
||||
cbm_registry_resolve(backward, "dev_name", "proj.kernel.irq.msi", NULL, NULL, 0);
|
||||
ASSERT_NOT_NULL(f.qualified_name);
|
||||
ASSERT_NOT_NULL(b.qualified_name);
|
||||
ASSERT_STR_EQ(f.qualified_name, "proj.include.linux.device.dev_name");
|
||||
ASSERT_STR_EQ(b.qualified_name, "proj.include.linux.device.dev_name");
|
||||
ASSERT_STR_EQ(f.strategy, "suffix_match");
|
||||
ASSERT_STR_EQ(b.strategy, "suffix_match");
|
||||
|
||||
/* Equal depth: the smaller QN, from either order. */
|
||||
cbm_registry_t *lex_a = cbm_registry_new();
|
||||
cbm_registry_t *lex_b = cbm_registry_new();
|
||||
cbm_registry_add(lex_a, "sg_next", "proj.tools.virtio.scatterlist.sg_next", "Function");
|
||||
cbm_registry_add(lex_a, "sg_next", "proj.include.linux.scatterlist.sg_next", "Function");
|
||||
cbm_registry_add(lex_b, "sg_next", "proj.include.linux.scatterlist.sg_next", "Function");
|
||||
cbm_registry_add(lex_b, "sg_next", "proj.tools.virtio.scatterlist.sg_next", "Function");
|
||||
cbm_resolution_t la =
|
||||
cbm_registry_resolve(lex_a, "sg_next", "proj.drivers.scsi.arm_scsi", NULL, NULL, 0);
|
||||
cbm_resolution_t lb =
|
||||
cbm_registry_resolve(lex_b, "sg_next", "proj.drivers.scsi.arm_scsi", NULL, NULL, 0);
|
||||
ASSERT_STR_EQ(la.qualified_name, "proj.include.linux.scatterlist.sg_next");
|
||||
ASSERT_STR_EQ(lb.qualified_name, "proj.include.linux.scatterlist.sg_next");
|
||||
|
||||
/* Proximity still outranks depth: the sibling wins over a shallower stranger. */
|
||||
cbm_registry_t *near = cbm_registry_new();
|
||||
cbm_registry_add(near, "vnic_rq_free", "proj.lib.vnic_rq_free", "Function");
|
||||
cbm_registry_add(near, "vnic_rq_free", "proj.drivers.scsi.fnic.vnic_rq.vnic_rq_free",
|
||||
"Function");
|
||||
cbm_resolution_t nr = cbm_registry_resolve(near, "vnic_rq_free",
|
||||
"proj.drivers.scsi.fnic.fnic_res", NULL, NULL, 0);
|
||||
ASSERT_STR_EQ(nr.qualified_name, "proj.drivers.scsi.fnic.vnic_rq.vnic_rq_free");
|
||||
|
||||
cbm_registry_free(forward);
|
||||
cbm_registry_free(backward);
|
||||
cbm_registry_free(lex_a);
|
||||
cbm_registry_free(lex_b);
|
||||
cbm_registry_free(near);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(cross_language_suffix_match_drops_py_vs_js) {
|
||||
/* #725: two same-named symbols in different languages. suffix_match is the
|
||||
* strategy that collapses them; unique_name is #1572 and must stay. */
|
||||
@@ -939,6 +1029,53 @@ TEST(dynamic_suppress_keeps_high_confidence_and_non_methods) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(python_builtin_member_table_matches_builtin_type_methods) {
|
||||
/* Ends and middle of the sorted table, so a mis-sorted insert shows up. */
|
||||
ASSERT_TRUE(cbm_python_is_builtin_member("add"));
|
||||
ASSERT_TRUE(cbm_python_is_builtin_member("extend"));
|
||||
ASSERT_TRUE(cbm_python_is_builtin_member("items"));
|
||||
ASSERT_TRUE(cbm_python_is_builtin_member("print"));
|
||||
ASSERT_TRUE(cbm_python_is_builtin_member("startswith"));
|
||||
ASSERT_TRUE(cbm_python_is_builtin_member("zfill"));
|
||||
/* Project-specific spellings are not builtin members. */
|
||||
ASSERT_FALSE(cbm_python_is_builtin_member("apply_converters"));
|
||||
ASSERT_FALSE(cbm_python_is_builtin_member("lazy_model_operation"));
|
||||
ASSERT_FALSE(cbm_python_is_builtin_member("describe"));
|
||||
ASSERT_FALSE(cbm_python_is_builtin_member(NULL));
|
||||
ASSERT_FALSE(cbm_python_is_builtin_member(""));
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(weak_member_unique_name_exempt_is_python_self_rooted_unique_and_specific_only) {
|
||||
/* The exemption: Python, self/cls-rooted receiver, unique_name, callee not
|
||||
* a builtin member. */
|
||||
ASSERT_TRUE(cbm_weak_member_unique_name_exempt(true, true, "self.compiler.apply_converters",
|
||||
"unique_name"));
|
||||
ASSERT_TRUE(cbm_weak_member_unique_name_exempt(true, true, "cls.registry.lazy_model_operation",
|
||||
"unique_name"));
|
||||
/* A bare parameter/local receiver carries no ownership evidence: #1276's
|
||||
* accelerator.backward() and c.describe() stay suppressed. */
|
||||
ASSERT_FALSE(
|
||||
cbm_weak_member_unique_name_exempt(true, false, "accelerator.backward", "unique_name"));
|
||||
/* A builtin type's own method stays suppressed even on self. */
|
||||
ASSERT_FALSE(
|
||||
cbm_weak_member_unique_name_exempt(true, true, "self.parts.extend", "unique_name"));
|
||||
ASSERT_FALSE(cbm_weak_member_unique_name_exempt(true, true, "self.out.print", "unique_name"));
|
||||
/* Only unique_name carries the one-definition evidence. */
|
||||
ASSERT_FALSE(cbm_weak_member_unique_name_exempt(true, true, "self.compiler.apply_converters",
|
||||
"suffix_match"));
|
||||
ASSERT_FALSE(cbm_weak_member_unique_name_exempt(true, true, "self.compiler.apply_converters",
|
||||
"field_type_hint"));
|
||||
/* Python only: the JS/TS family keeps its recorded trade. */
|
||||
ASSERT_FALSE(
|
||||
cbm_weak_member_unique_name_exempt(false, true, "this.compiler.apply", "unique_name"));
|
||||
/* Degenerate inputs never exempt. */
|
||||
ASSERT_FALSE(cbm_weak_member_unique_name_exempt(true, true, NULL, "unique_name"));
|
||||
ASSERT_FALSE(cbm_weak_member_unique_name_exempt(true, true, "", "unique_name"));
|
||||
ASSERT_FALSE(cbm_weak_member_unique_name_exempt(true, true, "self.x.y", NULL));
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(local_binding_suppress_drops_weak_shadowed_bare_calls) {
|
||||
/* A bare `run()` whose callee is a parameter of an enclosing scope cannot be
|
||||
* the module-level `run`, so a weak short-name match fabricates the edge. */
|
||||
@@ -1103,10 +1240,14 @@ SUITE(registry) {
|
||||
RUN_TEST(perl_suppress_drops_weak_builtin_and_method_matches);
|
||||
RUN_TEST(perl_suppress_keeps_high_confidence_and_genuine_calls);
|
||||
RUN_TEST(cross_language_suffix_match_drops_py_vs_js);
|
||||
RUN_TEST(cross_language_config_caller_drops_unique_name_too);
|
||||
RUN_TEST(registry_tie_break_is_independent_of_registration_order);
|
||||
RUN_TEST(cross_language_ref_drops_go_vs_c);
|
||||
RUN_TEST(go_bare_ref_never_binds_field);
|
||||
RUN_TEST(dynamic_suppress_drops_weak_method_matches);
|
||||
RUN_TEST(dynamic_suppress_keeps_high_confidence_and_non_methods);
|
||||
RUN_TEST(python_builtin_member_table_matches_builtin_type_methods);
|
||||
RUN_TEST(weak_member_unique_name_exempt_is_python_self_rooted_unique_and_specific_only);
|
||||
RUN_TEST(local_binding_suppress_drops_weak_shadowed_bare_calls);
|
||||
RUN_TEST(local_binding_suppress_keeps_unshadowed_and_strong_strategies);
|
||||
RUN_TEST(weak_call_guards_share_one_drop_list);
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
/* sqlite_writer.h is at internal/cbm/ — Makefile adds -Iinternal/cbm */
|
||||
#include "sqlite_writer.h" /* CBMDumpNode, CBMDumpEdge, cbm_write_db */
|
||||
#include "sqlite3.h" /* vendored/sqlite3/ via -Ivendored/sqlite3 */
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ── Helper: create temp file path ─────────────────────────────── */
|
||||
@@ -101,6 +102,45 @@ static int count_temp_outputs_for(const char *path) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Locate the writer's temp output for `path`. Same naming rule as
|
||||
* count_temp_outputs_for, but returns the full path of the first match. */
|
||||
static int find_temp_output_for(const char *path, char *out, size_t out_size) {
|
||||
char dir[256];
|
||||
char base[256];
|
||||
const char *slash = strrchr(path, '/');
|
||||
if (slash) {
|
||||
size_t dir_len = (size_t)(slash - path);
|
||||
if (dir_len == 0 || dir_len >= sizeof(dir)) {
|
||||
return -1;
|
||||
}
|
||||
memcpy(dir, path, dir_len);
|
||||
dir[dir_len] = '\0';
|
||||
snprintf(base, sizeof(base), "%s", slash + 1);
|
||||
} else {
|
||||
snprintf(dir, sizeof(dir), ".");
|
||||
snprintf(base, sizeof(base), "%s", path);
|
||||
}
|
||||
|
||||
cbm_dir_t *d = cbm_opendir(dir);
|
||||
if (!d) {
|
||||
return -1;
|
||||
}
|
||||
size_t base_len = strlen(base);
|
||||
int found = -1;
|
||||
cbm_dirent_t *ent;
|
||||
while ((ent = cbm_readdir(d)) != NULL) {
|
||||
size_t name_len = strlen(ent->name);
|
||||
if (name_len > base_len + 5 && strncmp(ent->name, base, base_len) == 0 &&
|
||||
strncmp(ent->name + base_len, ".tmp.", 5) == 0) {
|
||||
snprintf(out, out_size, "%s/%s", dir, ent->name);
|
||||
found = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
cbm_closedir(d);
|
||||
return found;
|
||||
}
|
||||
|
||||
/* ── Tests ─────────────────────────────────────────────────────── */
|
||||
|
||||
TEST(sw_minimal_data) {
|
||||
@@ -877,6 +917,61 @@ TEST(sw_publish_preserves_live_reader) {
|
||||
|
||||
/* ── Suite ─────────────────────────────────────────────────────── */
|
||||
|
||||
TEST(sw_open_truncated_path_names_its_reason) {
|
||||
/* final_path is a fixed 4K buffer and make_writer_temp_path only fails by
|
||||
* truncation. Neither sets an errno of its own, so without naming one the
|
||||
* caller reports whatever was left behind by an unrelated call. */
|
||||
char longpath[5000];
|
||||
memset(longpath, 'a', sizeof(longpath) - 1);
|
||||
longpath[sizeof(longpath) - 1] = '\0';
|
||||
longpath[0] = '/';
|
||||
|
||||
errno = 0;
|
||||
cbm_db_writer_t *w = cbm_writer_open(longpath);
|
||||
ASSERT(w == NULL);
|
||||
ASSERT_EQ(errno, ENAMETOOLONG);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(sw_publish_failure_reports_the_rename_not_the_cleanup) {
|
||||
#ifdef _WIN32
|
||||
SKIP_PLATFORM("removing a still-open file to make the cleanup unlink fail");
|
||||
#endif
|
||||
char dir[256];
|
||||
snprintf(dir, sizeof(dir), "/tmp/cbm_sw_cleanup_XXXXXX");
|
||||
ASSERT(cbm_mkdtemp(dir) != NULL);
|
||||
|
||||
char final_path[320];
|
||||
snprintf(final_path, sizeof(final_path), "%s/db.sqlite", dir);
|
||||
ASSERT_EQ(write_fixture_file(final_path, "destination"), 0);
|
||||
|
||||
cbm_db_writer_t *w = cbm_writer_open(final_path);
|
||||
ASSERT(w != NULL);
|
||||
|
||||
/* Turn the still-open temp into a directory. The publish rename then fails
|
||||
* with ENOTDIR (directory onto a file), and the cleanup unlink fails too
|
||||
* (EISDIR on Linux, EPERM on macOS) — so only a saved errno still carries
|
||||
* the rename's reason out to the caller. */
|
||||
char temp[512];
|
||||
ASSERT_EQ(find_temp_output_for(final_path, temp, sizeof(temp)), 0);
|
||||
ASSERT_EQ(cbm_unlink(temp), 0);
|
||||
ASSERT(cbm_mkdir_p(temp, 0700));
|
||||
|
||||
errno = 0;
|
||||
int rc = cbm_writer_finalize(w, "test", "/tmp/test", "2026-07-07T00:00:00Z", NULL, 0, NULL, 0,
|
||||
NULL, 0, NULL, 0);
|
||||
int publish_errno = errno;
|
||||
ASSERT(rc != 0);
|
||||
ASSERT_EQ(publish_errno, ENOTDIR);
|
||||
/* The destination is intact: a failed publish never replaces it. */
|
||||
ASSERT(fixture_file_equals(final_path, "destination"));
|
||||
|
||||
cbm_rmdir(temp);
|
||||
cbm_unlink(final_path);
|
||||
cbm_rmdir(dir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(sqlite_writer) {
|
||||
RUN_TEST(sw_minimal_data);
|
||||
RUN_TEST(sw_imports_local_name_unique);
|
||||
@@ -890,4 +985,6 @@ SUITE(sqlite_writer) {
|
||||
RUN_TEST(sw_publish_failure_preserves_destination_sidecars);
|
||||
RUN_TEST(sw_publish_supports_non_ascii_path);
|
||||
RUN_TEST(sw_publish_preserves_live_reader);
|
||||
RUN_TEST(sw_open_truncated_path_names_its_reason);
|
||||
RUN_TEST(sw_publish_failure_reports_the_rename_not_the_cleanup);
|
||||
}
|
||||
@@ -436,6 +436,30 @@ TEST(json_escape_control_chars) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A truncated escape must never end inside a multibyte UTF-8 sequence: the
|
||||
* callee text of a CALLS edge is escaped into a fixed buffer, and a cut umlaut
|
||||
* persisted bytes SQLite could not decode as text (2026-09-16 probe: rust,
|
||||
* java and typescript stores). "aé" is a, 0xC3, 0xA9. */
|
||||
TEST(json_escape_never_splits_utf8) {
|
||||
char buf[3]; /* room for two payload bytes + NUL: the lead byte would fit, its continuation not
|
||||
*/
|
||||
int len = cbm_json_escape(buf, sizeof(buf), "a\xC3\xA9");
|
||||
ASSERT_STR_EQ(buf, "a");
|
||||
ASSERT_EQ(len, 1);
|
||||
|
||||
char whole[4];
|
||||
len = cbm_json_escape(whole, sizeof(whole), "a\xC3\xA9");
|
||||
ASSERT_STR_EQ(whole, "a\xC3\xA9");
|
||||
ASSERT_EQ(len, 3);
|
||||
|
||||
/* A four-byte sequence cut after two bytes is dropped whole. */
|
||||
char emoji[3];
|
||||
len = cbm_json_escape(emoji, sizeof(emoji), "\xF0\x9F\x98\x80z");
|
||||
ASSERT_STR_EQ(emoji, "");
|
||||
ASSERT_EQ(len, 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── SNPRINTF_APPEND tests ────────────────────────────────────── */
|
||||
|
||||
TEST(snprintf_append_basic) {
|
||||
@@ -547,6 +571,7 @@ SUITE(str_util) {
|
||||
RUN_TEST(validate_shell_arg_spaces);
|
||||
/* JSON Escaping */
|
||||
RUN_TEST(json_escape_control_chars);
|
||||
RUN_TEST(json_escape_never_splits_utf8);
|
||||
/* SNPRINTF_APPEND */
|
||||
RUN_TEST(snprintf_append_basic);
|
||||
RUN_TEST(snprintf_append_fills_exactly);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "../src/foundation/compat.h"
|
||||
#include "../src/foundation/compat_thread.h"
|
||||
#include "../src/foundation/constants.h"
|
||||
#include "../src/foundation/log.h"
|
||||
#include "../src/foundation/platform.h"
|
||||
#include "test_framework.h"
|
||||
#include "test_helpers.h"
|
||||
@@ -15,6 +16,7 @@
|
||||
#include <pipeline/artifact.h>
|
||||
#include <store/store.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <stdatomic.h>
|
||||
#include <signal.h>
|
||||
#include <string.h>
|
||||
@@ -86,6 +88,71 @@ TEST(poll_interval_small) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════
|
||||
* HARD INDEX-FAILURE BACKOFF
|
||||
* ══════════════════════════════════════════════════════════════════ */
|
||||
|
||||
TEST(index_backoff_no_failures_keeps_interval) {
|
||||
/* The success and busy-skip paths must be completely unaffected. */
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 0), 5000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(60000, 0), 60000);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(index_backoff_doubles_per_failure) {
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 1), 10000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 2), 20000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 3), 40000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 4), 80000);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(index_backoff_reaches_ceiling_and_stays) {
|
||||
/* 5000 << 6 = 320000, above the 5-minute ceiling. The shift is capped
|
||||
* too, so an arbitrarily long failure streak cannot overflow the
|
||||
* intermediate value or wrap back to a short delay. */
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 6), 300000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, 100), 300000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, INT_MAX), 300000);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(60000, INT_MAX), 300000);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(index_backoff_is_monotonic_and_bounded) {
|
||||
/* The property that actually matters: the delay never decreases as the
|
||||
* streak grows, and never exceeds the ceiling. This is what bounds the
|
||||
* fork rate of a permanently failing project. */
|
||||
int previous = cbm_watcher_index_backoff_ms(5000, 0);
|
||||
for (int failures = 1; failures < 200; failures++) {
|
||||
int delay = cbm_watcher_index_backoff_ms(5000, failures);
|
||||
ASSERT_TRUE(delay >= previous);
|
||||
ASSERT_TRUE(delay <= 300000);
|
||||
previous = delay;
|
||||
}
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(index_backoff_degenerate_inputs) {
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(0, 5), 0);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(-1, 0), 0);
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(5000, -1), 5000);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(index_backoff_never_schedules_sooner_than_the_interval) {
|
||||
/* An interval above the ceiling must not be SHORTENED by backing off:
|
||||
* the clamp is a floor as well as a cap. Not reachable while
|
||||
* POLL_MAX_MS < the ceiling, but the helper is exported, so its contract
|
||||
* has to hold for what a caller can pass, not only for what today's
|
||||
* constants produce. */
|
||||
int over = 400000; /* > INDEX_FAIL_CEILING_MS */
|
||||
ASSERT_EQ(cbm_watcher_index_backoff_ms(over, 0), over);
|
||||
for (int failures = 1; failures < 20; failures++) {
|
||||
ASSERT_TRUE(cbm_watcher_index_backoff_ms(over, failures) >= over);
|
||||
}
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════
|
||||
* LIFECYCLE
|
||||
* ══════════════════════════════════════════════════════════════════ */
|
||||
@@ -1864,6 +1931,243 @@ TEST(watcher_failed_reindex_retries_issue937) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The failure state machine the backoff feeds (#2015): the streak must count
|
||||
* consecutive HARD failures and reset the moment one reindex succeeds. The
|
||||
* delay it computes is covered by the index_backoff_* unit tests; what is
|
||||
* covered here is the counter that selects which delay applies, because a
|
||||
* streak that never increments — or never resets — silently reverts the
|
||||
* backoff to the unbounded retry it exists to prevent, with every other test
|
||||
* still green. Each poll is preceded by cbm_watcher_touch, which zeroes
|
||||
* next_poll_ns, so this exercises the counter without depending on a clock. */
|
||||
TEST(watcher_index_failure_streak_increments_and_resets_issue2015) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_strk_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir))
|
||||
FAIL("cbm_mkdtemp failed");
|
||||
|
||||
if (wt_git(tmpdir, "init -q") != 0) {
|
||||
th_rmtree(tmpdir);
|
||||
FAIL("git init failed");
|
||||
}
|
||||
{
|
||||
char p[300];
|
||||
th_write_file(wt_path(p, sizeof(p), tmpdir, "file.txt"), "hello\n");
|
||||
}
|
||||
wt_git(tmpdir, "add file.txt");
|
||||
wt_git(tmpdir, "commit -q -m init");
|
||||
|
||||
cbm_store_t *store = cbm_store_open_memory();
|
||||
cbm_watcher_t *w = cbm_watcher_new(store, failing_index_callback, NULL);
|
||||
|
||||
cbm_watcher_watch(w, "strk-repo", tmpdir);
|
||||
failing_index_calls = 0;
|
||||
failing_index_fail_first_n = 2; /* first TWO reindex attempts fail hard */
|
||||
|
||||
/* Baseline (clean tree): no reindex, so no failures yet. */
|
||||
cbm_watcher_poll_once(w);
|
||||
ASSERT_EQ(failing_index_calls, 0);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "strk-repo"), 0);
|
||||
|
||||
/* HEAD moves. */
|
||||
{
|
||||
char p[300];
|
||||
th_append_file(wt_path(p, sizeof(p), tmpdir, "file.txt"), "world\n");
|
||||
}
|
||||
wt_git(tmpdir, "add file.txt");
|
||||
wt_git(tmpdir, "commit -q -m add-world");
|
||||
|
||||
/* First hard failure → streak 1. */
|
||||
cbm_watcher_touch(w, "strk-repo");
|
||||
cbm_watcher_poll_once(w);
|
||||
ASSERT_EQ(failing_index_calls, 1);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "strk-repo"), 1);
|
||||
|
||||
/* Second consecutive hard failure → streak 2 (it accumulates; it is not
|
||||
* a boolean, which is what makes the delay grow). */
|
||||
cbm_watcher_touch(w, "strk-repo");
|
||||
cbm_watcher_poll_once(w);
|
||||
ASSERT_EQ(failing_index_calls, 2);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "strk-repo"), 2);
|
||||
|
||||
/* Third attempt succeeds → streak resets, so a project that recovers
|
||||
* returns to its normal cadence instead of staying backed off. */
|
||||
cbm_watcher_touch(w, "strk-repo");
|
||||
cbm_watcher_poll_once(w);
|
||||
ASSERT_EQ(failing_index_calls, 3);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "strk-repo"), 0);
|
||||
|
||||
cbm_watcher_free(w);
|
||||
cbm_store_close(store);
|
||||
th_rmtree(tmpdir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The delay WIRE-UP (#2015): a hard failure must leave SOME deadline behind,
|
||||
* so the failing project is not re-polled on the very next cycle. Observable
|
||||
* without a clock by simply not calling cbm_watcher_touch between polls —
|
||||
* touch zeroes next_poll_ns, so a wire-up that never assigns one leaves it at
|
||||
* 0 and the callback fires on every poll.
|
||||
*
|
||||
* Be precise about what this does NOT prove, because it is less than it looks.
|
||||
* The code before this change also assigned a deadline here (the plain
|
||||
* adaptive interval), so this test passes against the unfixed tree: it is a
|
||||
* regression guard on the assignment existing, NOT a demonstration of the
|
||||
* backoff.
|
||||
*
|
||||
* Measured, not assumed: replacing the backoff call with the pre-change
|
||||
* `ctx->now + interval_ms * US_PER_MS` leaves this whole suite green at 82/82.
|
||||
* No test in this file fails when the behavioural change is removed — the
|
||||
* index_backoff_* tests still pass because they exercise the pure function
|
||||
* directly, and the streak tests still pass because the counter is unaffected.
|
||||
* What distinguishes backed-off from plain cadence is the delay's MAGNITUDE,
|
||||
* and observing that needs a controllable clock the watcher does not have, or
|
||||
* a further accessor exposing next_poll_ns. Both were judged out of scope; the
|
||||
* gap is recorded here rather than papered over. */
|
||||
TEST(watcher_index_failure_backoff_gates_repolling_issue2015) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_gate_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir))
|
||||
FAIL("cbm_mkdtemp failed");
|
||||
|
||||
if (wt_git(tmpdir, "init -q") != 0) {
|
||||
th_rmtree(tmpdir);
|
||||
FAIL("git init failed");
|
||||
}
|
||||
{
|
||||
char p[300];
|
||||
th_write_file(wt_path(p, sizeof(p), tmpdir, "file.txt"), "hello\n");
|
||||
}
|
||||
wt_git(tmpdir, "add file.txt");
|
||||
wt_git(tmpdir, "commit -q -m init");
|
||||
|
||||
cbm_store_t *store = cbm_store_open_memory();
|
||||
cbm_watcher_t *w = cbm_watcher_new(store, failing_index_callback, NULL);
|
||||
|
||||
cbm_watcher_watch(w, "gate-repo", tmpdir);
|
||||
failing_index_calls = 0;
|
||||
failing_index_fail_first_n = 100; /* never succeeds */
|
||||
|
||||
cbm_watcher_poll_once(w); /* baseline */
|
||||
|
||||
{
|
||||
char p[300];
|
||||
th_append_file(wt_path(p, sizeof(p), tmpdir, "file.txt"), "world\n");
|
||||
}
|
||||
wt_git(tmpdir, "add file.txt");
|
||||
wt_git(tmpdir, "commit -q -m add-world");
|
||||
|
||||
/* One failure, forced by touch. */
|
||||
cbm_watcher_touch(w, "gate-repo");
|
||||
cbm_watcher_poll_once(w);
|
||||
ASSERT_EQ(failing_index_calls, 1);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "gate-repo"), 1);
|
||||
|
||||
/* Now poll repeatedly WITHOUT touching. The change is still pending (the
|
||||
* baseline stays uncommitted per #937), so the ONLY thing that can stop a
|
||||
* re-fork is the deadline the failure just scheduled. Before the backoff
|
||||
* wire-up existed this project was re-forked at the poll cadence; with no
|
||||
* deadline set at all it would fire on every one of these iterations. */
|
||||
for (int i = 0; i < 5; i++) {
|
||||
cbm_watcher_poll_once(w);
|
||||
}
|
||||
ASSERT_EQ(failing_index_calls, 1);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "gate-repo"), 1);
|
||||
|
||||
/* Control: the watcher is not simply dead — clearing the deadline lets the
|
||||
* retry through, which is what keeps #937's at-least-once guarantee. */
|
||||
cbm_watcher_touch(w, "gate-repo");
|
||||
cbm_watcher_poll_once(w);
|
||||
ASSERT_EQ(failing_index_calls, 2);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "gate-repo"), 2);
|
||||
|
||||
cbm_watcher_free(w);
|
||||
cbm_store_close(store);
|
||||
th_rmtree(tmpdir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The sustained-failure line must fire EXACTLY once, at the threshold — the
|
||||
* other single-token mutation round 1 named (`==` widened to `>=`) would emit
|
||||
* it on every failure from the threshold onward and turn a one-shot signal
|
||||
* into the log spam the whole change is meant to avoid. */
|
||||
static int sustained_log_hits = 0;
|
||||
static void sustained_log_sink(const char *line) {
|
||||
if (line && strstr(line, "watcher.index.sustained_failure") != NULL) {
|
||||
sustained_log_hits++;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(watcher_sustained_failure_logs_once_issue2015) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_sust_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir))
|
||||
FAIL("cbm_mkdtemp failed");
|
||||
|
||||
if (wt_git(tmpdir, "init -q") != 0) {
|
||||
th_rmtree(tmpdir);
|
||||
FAIL("git init failed");
|
||||
}
|
||||
{
|
||||
char p[300];
|
||||
th_write_file(wt_path(p, sizeof(p), tmpdir, "file.txt"), "hello\n");
|
||||
}
|
||||
wt_git(tmpdir, "add file.txt");
|
||||
wt_git(tmpdir, "commit -q -m init");
|
||||
|
||||
cbm_store_t *store = cbm_store_open_memory();
|
||||
cbm_watcher_t *w = cbm_watcher_new(store, failing_index_callback, NULL);
|
||||
|
||||
cbm_watcher_watch(w, "sust-repo", tmpdir);
|
||||
failing_index_calls = 0;
|
||||
failing_index_fail_first_n = 100; /* never succeeds */
|
||||
|
||||
cbm_watcher_poll_once(w); /* baseline */
|
||||
|
||||
{
|
||||
char p[300];
|
||||
th_append_file(wt_path(p, sizeof(p), tmpdir, "file.txt"), "world\n");
|
||||
}
|
||||
wt_git(tmpdir, "add file.txt");
|
||||
wt_git(tmpdir, "commit -q -m add-world");
|
||||
|
||||
sustained_log_hits = 0;
|
||||
cbm_log_set_sink(sustained_log_sink);
|
||||
|
||||
/* Drive well past the threshold (10). touch clears the deadline each time
|
||||
* so every iteration actually attempts a reindex. */
|
||||
for (int i = 0; i < 14; i++) {
|
||||
cbm_watcher_touch(w, "sust-repo");
|
||||
cbm_watcher_poll_once(w);
|
||||
}
|
||||
|
||||
cbm_log_set_sink(NULL);
|
||||
|
||||
ASSERT_EQ(failing_index_calls, 14);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "sust-repo"), 14);
|
||||
/* Exactly one, not four (11..14) and not zero. */
|
||||
ASSERT_EQ(sustained_log_hits, 1);
|
||||
|
||||
cbm_watcher_free(w);
|
||||
cbm_store_close(store);
|
||||
th_rmtree(tmpdir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(watcher_index_failure_count_unknown_project) {
|
||||
cbm_store_t *store = cbm_store_open_memory();
|
||||
cbm_watcher_t *w = cbm_watcher_new(store, index_callback, NULL);
|
||||
|
||||
/* Unwatched and NULL inputs report -1, distinct from a watched project
|
||||
* sitting at a legitimate 0. */
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, "never-watched"), -1);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(w, NULL), -1);
|
||||
ASSERT_EQ(cbm_watcher_index_failure_count(NULL, "x"), -1);
|
||||
|
||||
cbm_watcher_free(w);
|
||||
cbm_store_close(store);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(watcher_multiple_projects) {
|
||||
/* Create two temporary git repos */
|
||||
char tmpdirA[256];
|
||||
@@ -3271,6 +3575,16 @@ SUITE(watcher) {
|
||||
RUN_TEST(poll_interval_scaling);
|
||||
RUN_TEST(poll_interval_cap);
|
||||
RUN_TEST(poll_interval_small);
|
||||
RUN_TEST(index_backoff_no_failures_keeps_interval);
|
||||
RUN_TEST(index_backoff_doubles_per_failure);
|
||||
RUN_TEST(index_backoff_reaches_ceiling_and_stays);
|
||||
RUN_TEST(index_backoff_is_monotonic_and_bounded);
|
||||
RUN_TEST(index_backoff_degenerate_inputs);
|
||||
RUN_TEST(index_backoff_never_schedules_sooner_than_the_interval);
|
||||
RUN_TEST(watcher_index_failure_streak_increments_and_resets_issue2015);
|
||||
RUN_TEST(watcher_index_failure_backoff_gates_repolling_issue2015);
|
||||
RUN_TEST(watcher_sustained_failure_logs_once_issue2015);
|
||||
RUN_TEST(watcher_index_failure_count_unknown_project);
|
||||
|
||||
/* Lifecycle */
|
||||
RUN_TEST(watcher_create_free);
|
||||
|
||||
@@ -70,8 +70,15 @@ run_worker() {
|
||||
--response-out "${response}" >"${out}" 2>"${err}"
|
||||
}
|
||||
|
||||
# A worker never reads the resource policy from config or environment: the
|
||||
# supervisor resolves it and sends it inside the request, and a request
|
||||
# without one is refused ("missing or incomplete trusted worker policy").
|
||||
# This script plays the supervisor, so it sends what the supervisor sends --
|
||||
# both limits off, the default.
|
||||
policy='"_cbm_index_policy":{"index_max_files":"off","index_max_source_mb":"off"}'
|
||||
|
||||
response="${tmpdir}/scoped.response"
|
||||
if ! run_worker "{\"repo_path\":\"${repo}\",\"mode\":\"fast\"}" "${response}" \
|
||||
if ! run_worker "{\"repo_path\":\"${repo}\",\"mode\":\"fast\",${policy}}" "${response}" \
|
||||
"${tmpdir}/scoped.out" "${tmpdir}/scoped.err"; then
|
||||
echo "worker exited nonzero for an admitted request" >&2
|
||||
cat "${tmpdir}/scoped.err" >&2
|
||||
@@ -94,7 +101,7 @@ fi
|
||||
|
||||
# Fail closed: no repo_path means no request scope, so no indexing at all.
|
||||
unscoped="${tmpdir}/unscoped.response"
|
||||
if run_worker '{"mode":"fast"}' "${unscoped}" "${tmpdir}/unscoped.out" "${tmpdir}/unscoped.err"; then
|
||||
if run_worker "{\"mode\":\"fast\",${policy}}" "${unscoped}" "${tmpdir}/unscoped.out" "${tmpdir}/unscoped.err"; then
|
||||
echo "worker ran without a request workspace scope" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
Reference in new issue
Block a user