mirror of
https://github.com/DeusData/codebase-memory-mcp.git
synced 2026-12-02 04:17:04 +08:00
Merge branch 'main' into feat/ruby-lsp-per-file
This commit is contained in:
@@ -10,7 +10,11 @@ permissions:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
# Pinned, not ubuntu-latest: the LLVM install below adds an
|
||||
# apt.llvm.org llvm-toolchain-NOBLE repo, which is 24.04 by name. When
|
||||
# GitHub moves ubuntu-latest to the next LTS this job breaks on a day
|
||||
# nobody chose. Pin the runner to the release the repo line already names.
|
||||
runs-on: ubuntu-24.04
|
||||
# 15 min proved too tight on a slow runner day and a timed-out lint reads
|
||||
# as "cancelled", which the release graph must treat as a hard stop; keep
|
||||
# a bound, but one only a genuine hang can hit (normal runtime ~5 min).
|
||||
@@ -60,7 +64,8 @@ jobs:
|
||||
# provability (never suppressed — the NOLINT ban applies here too).
|
||||
# Vendored-tree diagnostics are path-filtered, mirroring .cppcheck.
|
||||
lint-mem:
|
||||
runs-on: ubuntu-latest
|
||||
# Pinned for the same reason as `lint`: llvm-toolchain-noble-21 below.
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
@@ -245,7 +245,9 @@ jobs:
|
||||
# parallel suite — catches what an older compiler-rt can miss. Same
|
||||
# canonical scripts/test.sh wave as every other leg.
|
||||
test-diag:
|
||||
runs-on: ubuntu-latest
|
||||
# Pinned for the same reason as the lint jobs: the pinned diagnostic
|
||||
# toolchain below installs from llvm-toolchain-noble-21.
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
@@ -236,8 +236,20 @@ jobs:
|
||||
- name: Generate SBOM
|
||||
run: python3 scripts/ci/generate-sbom.py "${{ inputs.version }}"
|
||||
|
||||
# actions/attest-sbom is deprecated. What it does now is emit
|
||||
# "::warning::actions/attest-sbom has been deprecated" and forward to
|
||||
# actions/attest with NODE_OPTIONS set, passing sbom-path straight
|
||||
# through. Calling attest directly produces the same attestation without
|
||||
# the wrapper, and sbom-path is a first-class input there (verified
|
||||
# against the action definition at this exact SHA, which is tag v4.1.0).
|
||||
#
|
||||
# This step deliberately carries no continue-on-error: a release must
|
||||
# fail if its SBOM cannot be attested. An unattested SBOM is worse than
|
||||
# an absent one, because the artifact still ships looking complete.
|
||||
- name: Attest SBOM
|
||||
uses: actions/attest-sbom@c604332985a26aa8cf1bdc465b92731239ec6b9e # v4.1.0
|
||||
uses: actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26 # v4.1.0
|
||||
env:
|
||||
NODE_OPTIONS: '--max-http-header-size=32768'
|
||||
with:
|
||||
subject-path: '*.tar.gz'
|
||||
sbom-path: 'sbom.json'
|
||||
|
||||
+28
-11
@@ -327,6 +327,7 @@ FOUNDATION_SRCS = \
|
||||
src/foundation/limits.c \
|
||||
src/foundation/index_policy.c \
|
||||
src/foundation/subprocess.c \
|
||||
src/foundation/git_env.c \
|
||||
src/foundation/sha256.c \
|
||||
src/foundation/secure_random.c \
|
||||
src/foundation/macos_acl.c \
|
||||
@@ -832,8 +833,14 @@ BUILD_DIR = build/c
|
||||
# ── Object file compilation (grammars need relaxed warnings) ─────
|
||||
|
||||
# Grammar + tree-sitter runtime: compiled without -Werror (upstream code has warnings)
|
||||
# $(TEST_SEAM_DEFINE): these prod objects (grammars, ts_runtime, lsp_all) are
|
||||
# linked into the same binary as the CFLAGS_PROD sources, so both halves must
|
||||
# agree on the seam switch. lsp_all holds seam code of its own (ts_lsp.c's
|
||||
# budget probes, any seam counter a resolver defines): without the define a
|
||||
# TEST_SEAMS=1 binary silently lacks those seams, and a seam symbol that cbm.c
|
||||
# references fails to link. GRAMMAR_CFLAGS_TEST always carries the define.
|
||||
GRAMMAR_CFLAGS = -std=c11 -D_DEFAULT_SOURCE -O2 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \
|
||||
$(MEMWASTE_VENDOR_CFLAGS)
|
||||
$(TEST_SEAM_DEFINE) $(MEMWASTE_VENDOR_CFLAGS)
|
||||
GRAMMAR_CFLAGS_TEST = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \
|
||||
-DCBM_ENABLE_TEST_SEAMS=1 $(SANITIZED_DEFINE) $(SANITIZE)
|
||||
GRAMMAR_CFLAGS_TSAN = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \
|
||||
@@ -941,7 +948,9 @@ $(BUILD_DIR)/sqlite3.o: $(SQLITE3_SRC) | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/tsan_sqlite3.o: $(SQLITE3_SRC) | $(BUILD_DIR)
|
||||
$(CC) $(SQLITE3_CFLAGS_TEST) $(TSAN_SANITIZE) -c -o $@ $<
|
||||
|
||||
$(BUILD_DIR)/prod_sqlite3.o: $(SQLITE3_SRC) Makefile.cbm | $(BUILD_DIR)
|
||||
# .build-config: SQLITE3_CFLAGS carries MEMWASTE_VENDOR_CFLAGS (see the stamp
|
||||
# under "Production binary").
|
||||
$(BUILD_DIR)/prod_sqlite3.o: $(SQLITE3_SRC) Makefile.cbm $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) $(SQLITE3_CFLAGS) -c -o $@ $<
|
||||
|
||||
# TRE regex (only compiled on Windows — POSIX uses system <regex.h>)
|
||||
@@ -971,7 +980,7 @@ $(BUILD_DIR)/tre.o: $(TRE_SRC) | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/tsan_tre.o: $(TRE_SRC) | $(BUILD_DIR)
|
||||
$(CC) $(TRE_CFLAGS) $(TSAN_SANITIZE) -c -o $@ $<
|
||||
|
||||
$(BUILD_DIR)/prod_tre.o: $(TRE_SRC) | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_tre.o: $(TRE_SRC) $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) $(TRE_CFLAGS) -O2 $(MEMWASTE_VENDOR_CFLAGS) -c -o $@ $<
|
||||
endif
|
||||
|
||||
@@ -1125,28 +1134,35 @@ TS_RUNTIME_OBJ_PROD = $(BUILD_DIR)/prod_ts_runtime.o
|
||||
LSP_OBJ_PROD = $(BUILD_DIR)/prod_lsp_all.o
|
||||
PP_OBJ_PROD = $(BUILD_DIR)/prod_preprocessor.o
|
||||
|
||||
$(BUILD_DIR)/prod_%.o: $(CBM_DIR)/%.c $(GRAMMAR_UNITY_DEPS) | $(BUILD_DIR)
|
||||
# Every prod object whose flags carry a BUILD_CONFIG_SIG variable
|
||||
# (TEST_SEAM_DEFINE via GRAMMAR_CFLAGS, MEMWASTE_VENDOR_CFLAGS) depends on the
|
||||
# $(BUILD_DIR)/.build-config stamp. These objects are compiled once and linked
|
||||
# into every later binary, so without the stamp a TEST_SEAMS or MEMWASTE flip
|
||||
# relinks the PREVIOUS flavour: a release binary keeps seam code compiled into
|
||||
# lsp_all, or a seams binary misses it. prod_mimalloc.o and the unixcoder blob
|
||||
# take no config variable and stay off the stamp.
|
||||
$(BUILD_DIR)/prod_%.o: $(CBM_DIR)/%.c $(GRAMMAR_UNITY_DEPS) $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) $(GRAMMAR_CFLAGS) -c -o $@ $<
|
||||
|
||||
$(BUILD_DIR)/prod_ts_runtime.o: $(TS_RUNTIME_DEPS) | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_ts_runtime.o: $(TS_RUNTIME_DEPS) $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) $(GRAMMAR_CFLAGS) -c -o $@ $<
|
||||
|
||||
$(BUILD_DIR)/prod_lsp_all.o: $(LSP_UNITY_DEPS) | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_lsp_all.o: $(LSP_UNITY_DEPS) $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) $(GRAMMAR_CFLAGS) -c -o $@ $<
|
||||
|
||||
$(BUILD_DIR)/prod_preprocessor.o: $(CBM_DIR)/preprocessor.cpp | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_preprocessor.o: $(CBM_DIR)/preprocessor.cpp $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CXX) $(CXXFLAGS_PROD) -w -I$(CBM_DIR)/vendored -c -o $@ $<
|
||||
|
||||
# Vendored LZ4 (compiled separately, not unity-built via lz4_store.c)
|
||||
LZ4_OBJ_PROD = $(BUILD_DIR)/prod_lz4.o $(BUILD_DIR)/prod_lz4hc.o
|
||||
$(BUILD_DIR)/prod_lz4.o: $(CBM_DIR)/vendored/lz4/lz4.c | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_lz4.o: $(CBM_DIR)/vendored/lz4/lz4.c $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) -std=c11 -D_DEFAULT_SOURCE -O2 -w $(MEMWASTE_VENDOR_CFLAGS) -I$(CBM_DIR) -c -o $@ $<
|
||||
$(BUILD_DIR)/prod_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) -std=c11 -D_DEFAULT_SOURCE -O2 -w $(MEMWASTE_VENDOR_CFLAGS) -I$(CBM_DIR)/vendored/lz4 -c -o $@ $<
|
||||
|
||||
# Vendored zstd (compiled separately, not unity-built via zstd_store.c)
|
||||
ZSTD_OBJ_PROD = $(BUILD_DIR)/prod_zstd.o
|
||||
$(BUILD_DIR)/prod_zstd.o: $(CBM_DIR)/vendored/zstd/zstd.c | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/prod_zstd.o: $(CBM_DIR)/vendored/zstd/zstd.c $(BUILD_DIR)/.build-config | $(BUILD_DIR)
|
||||
$(CC) -std=c11 -D_DEFAULT_SOURCE -O2 -w $(MEMWASTE_VENDOR_CFLAGS) -I$(CBM_DIR)/vendored/zstd -c -o $@ $<
|
||||
|
||||
OBJS_VENDORED_PROD = $(MIMALLOC_OBJ_PROD) $(SQLITE3_OBJ_PROD) $(TRE_OBJ_PROD) $(GRAMMAR_OBJS_PROD) $(TS_RUNTIME_OBJ_PROD) $(LSP_OBJ_PROD) $(PP_OBJ_PROD) $(LZ4_OBJ_PROD) $(ZSTD_OBJ_PROD) $(UNIXCODER_OBJ)
|
||||
@@ -1162,7 +1178,8 @@ MAIN_SRC = src/main.c
|
||||
# configuration and it is rewritten only when that content changes, so ordinary
|
||||
# incremental builds are unaffected. (Single-quoted: the signature may contain
|
||||
# the escaped quotes of -DCBM_VERSION, which are literal inside '', but must not
|
||||
# contain a literal single quote.)
|
||||
# contain a literal single quote.) The config-flavoured prod objects above
|
||||
# depend on the stamp for the same reason as the binary.
|
||||
# SANITIZE belongs here: it changes the instrumentation compiled into every
|
||||
# object, so a build that only changes it MUST rebuild. Its absence made
|
||||
# `scripts/test.sh SANITIZE= ...` -- the documented way to get a plain build
|
||||
|
||||
@@ -129,7 +129,7 @@ The native `install`, `update`, and `uninstall` commands are the deliberate exce
|
||||
|
||||
Package-manager setup (npm, PyPI, or Go) verifies and publishes a coherent private cached runtime set. Sidecars are replaced before the executable with per-file atomic renames; an interrupted multi-file publication is detected and repaired on the next launch rather than being described as one crash-atomic filesystem transaction. It does not replace the active native installation and therefore does not stop running CBM sessions. When that cached binary is executed, it still enters the same exact-build admission barrier. The shell and PowerShell installers invoke the verified candidate's native `install` command, so they do receive the full account-wide activation guarantee.
|
||||
|
||||
The ordinary `cli` mode is intentionally separate: it runs one command locally and never starts or connects to the coordination daemon, registers a daemon session, or starts watchers/UI. Its only shared state is the OS admission barrier plus per-project locks for graph mutations. While the command is running, a temporary monitor lets activation cancel that operation and its supervised worker safely; the monitor exits with the command and never becomes a standing daemon. See [CLI Mode](#cli-mode) for details.
|
||||
The ordinary `cli` mode runs one command locally, but it is not disconnected from the daemon above: it connects to the shared coordination daemon — starting one if none is already running — for that same admission barrier plus per-project locks on graph mutations. Its connection is a `cli_session`: it never registers with the background watcher and never starts a UI, and it holds the admission lease only for the command's lifetime. If the command's own connection is what started the daemon, that daemon exits again once the command closes and no other session is attached; if a daemon was already running, the command simply joins and leaves it exactly as found. While the command is running, a temporary monitor separately lets activation cancel that operation and its supervised worker safely; the monitor exits with the command and never becomes a standing daemon. See [CLI Mode](#cli-mode) for details.
|
||||
|
||||
### Graph Visualization UI
|
||||
|
||||
@@ -199,7 +199,7 @@ The install script placed beside the binary is **reported, not deleted** — uni
|
||||
- **Cypher-like queries**: `MATCH (f:Function)-[:CALLS]->(g) WHERE f.name = 'main' RETURN g.name`
|
||||
|
||||
### Search
|
||||
- **Semantic search** (`semantic_query`): vector search across the entire graph, powered by bundled Nomic `nomic-embed-code` embeddings (40K tokens, 768d int8) compiled into the binary — no API key, no Ollama, no Docker. 11-signal combined scoring (TF-IDF, RRI, API/Type/Decorator signatures, AST profiles, data flow, Halstead-lite, MinHash, module proximity, graph diffusion).
|
||||
- **Semantic search** (the `semantic_query` parameter of `search_graph`, not a separate tool): vector search across the entire graph, powered by bundled Nomic `nomic-embed-code` embeddings (40K tokens, 768d int8) compiled into the binary — no API key, no Ollama, no Docker. 11-signal combined scoring (TF-IDF, RRI, API/Type/Decorator signatures, AST profiles, data flow, Halstead-lite, MinHash, module proximity, graph diffusion).
|
||||
- **BM25 full-text search** via SQLite FTS5 with `cbm_camel_split` tokenizer (camelCase / snake_case aware)
|
||||
- **Structural search** (`search_graph`): regex name patterns, label filters, min/max degree, file scoping
|
||||
- **Code search** (`search_code`): graph-augmented grep over indexed files only
|
||||
@@ -243,12 +243,12 @@ The install script placed beside the binary is **reported, not deleted** — uni
|
||||
|
||||
Commit a single compressed file to your repo and your teammates skip the reindex.
|
||||
|
||||
`.codebase-memory/graph.db.zst` is a zstd-compressed snapshot of the knowledge graph that lives next to your source. When you index, the artifact is written or refreshed; when a teammate clones the repo and runs `codebase-memory-mcp` for the first time, the artifact is decompressed and incremental indexing fills in their local diff.
|
||||
`.codebase-memory/graph.db.zst` is a zstd-compressed snapshot of the knowledge graph that lives next to your source. The artifact is opt-in: `index_repository` writes it only with `persistence: true` (the default is `false`), and once it exists later indexes refresh it; when a teammate clones the repo and runs `codebase-memory-mcp` for the first time, the artifact is decompressed and incremental indexing fills in their local diff.
|
||||
|
||||
- **Format**: SQLite database, indexes stripped, `VACUUM INTO` compacted, then zstd 1.5.7 compressed (8–13:1 ratio typical)
|
||||
- **Two tiers**:
|
||||
- **Best** (`zstd -9` + index strip + `VACUUM INTO`) — written on explicit `index_repository`
|
||||
- **Fast** (`zstd -3`) — written by the watcher for low-latency incremental updates
|
||||
- **Best** (`zstd -9` + index strip + `VACUUM INTO`) — written by `index_repository` with `persistence: true`
|
||||
- **Fast** (`zstd -3`) — refreshes an existing artifact on every other index (including the watcher's low-latency incremental updates)
|
||||
- **Bootstrap**: when no local DB exists but the artifact is present, `index_repository` imports the artifact first, then runs incremental indexing — avoiding the full reindex cost
|
||||
- **No merge pain**: a `.codebase-memory/.gitattributes` line with `merge=ours` is auto-created on first export, so concurrent edits don't produce conflicts on the binary artifact
|
||||
- **Commit it deliberately**: the artifact is rewritten on every index, including the watcher's Fast tier, and git stores each rewrite as a full new blob. Committing every refresh is what turns a 20 MB file into gigabytes of history — one team reached ~6 GB across ~350 commits of this single path. Pick a cadence (a release, a milestone, a nightly job) rather than committing every save.
|
||||
@@ -630,7 +630,7 @@ no longer a suitable automatic global target.
|
||||
|
||||
## CLI Mode
|
||||
|
||||
Every MCP tool can be invoked as a local, one-shot command. CLI tools neither start nor connect to the coordination daemon and leave no standing process behind. They hold a crash-safe exact-build admission lease only for the command lifetime. `index_repository` is the only exception internally: it starts a temporary, exact-build supervised worker for the index, then stops that worker before the CLI command exits; the worker holds its own lease until exit.
|
||||
Every MCP tool can be invoked as a local, one-shot command. CLI tools connect to the shared coordination daemon — starting one if none is already running — to get a crash-safe exact-build admission lease for the command's lifetime; they never register with the background watcher, and a daemon a command had to start itself exits again once the command's connection closes and no other session is using it. `index_repository` is the only exception internally: it starts a temporary, exact-build supervised worker for the index, then stops that worker before the CLI command exits; the worker holds its own lease until exit.
|
||||
|
||||
Commands that mutate graph data use shared OS-backed, per-project locks. This serializes conflicting work from CLI and MCP sessions on the same project while allowing unrelated projects to proceed independently.
|
||||
|
||||
@@ -669,12 +669,39 @@ JSON arguments can also be piped on stdin, for tools that take arguments. A tool
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `index_repository` | Index a repository into the graph. Auto-sync keeps it fresh after that. |
|
||||
| `index_repository` | Index a repository into the graph. Auto-sync keeps it fresh after that. Waits for the whole index by default; pass `async: true` to start it in the daemon and return at once, then poll with `status: true` (see below). |
|
||||
| `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. |
|
||||
|
||||
**Long indexes and client call deadlines.** A synchronous `index_repository` on a large
|
||||
repository can take longer than an MCP client allows one tool call (some IDE clients give up
|
||||
after a fixed deadline). When a client cancels or disconnects, the daemon cancels an index that
|
||||
nobody else is waiting for, so retrying the same blocking call never finishes. Use the async
|
||||
mode instead:
|
||||
|
||||
1. `index_repository(repo_path="/abs/path", async: true)` starts the index in the daemon (or
|
||||
joins the one already running for that project) and returns immediately with
|
||||
`state` (`queued`/`running`). The job keeps running even if the client cancels, times out or
|
||||
disconnects; only stopping the daemon ends it.
|
||||
2. `index_repository(repo_path="/abs/path", status: true)` reports `state`
|
||||
(`queued`, `running`, `cancelling`, `succeeded`, `failed`, `cancelled`), `started_at`,
|
||||
`finished_at` and an `error` summary. Poll it until the state is `succeeded`, `failed` or
|
||||
`cancelled`. Pass the same `repo_path` (and `name`, if the index call used one).
|
||||
|
||||
`async` and `status` are exclusive; `async` does not apply to `cross-repo-intelligence`. Both
|
||||
need the daemon-backed server (the default `codebase-memory-mcp` entry point). A temporary
|
||||
daemon (started on demand rather than by `codebase-memory-mcp daemon start`) stops, and
|
||||
cancels its jobs, when its last client disconnects. A connected MCP session keeps it alive, so
|
||||
async from your editor works. A one-shot `codebase-memory-mcp cli index_repository --async`
|
||||
that is the daemon's only client is refused with a clear error, because the job would die the
|
||||
moment the command exits: run `codebase-memory-mcp daemon start` first, keep an MCP session
|
||||
open, or call without `--async`. `status` works everywhere. When a synchronous call was cut
|
||||
short, the next
|
||||
`index_repository` or `status` call for that project carries a `notice` suggesting the async
|
||||
mode. `index_status` keeps describing the published graph and its freshness.
|
||||
|
||||
### Querying
|
||||
|
||||
| Tool | Description |
|
||||
@@ -758,7 +785,7 @@ is preserved. See [Index resource limits](docs/INDEX_RESOURCE_LIMITS.md).
|
||||
| `CBM_MEM_BUDGET_MB` | *(detected)* | Override the in-memory graph budget with an explicit cap in MiB, taking precedence over the `ram_fraction × total_RAM` default. Useful on bare-metal hosts without a cgroup limit, or to pin a budget *below* the cgroup limit so headroom is left for sibling processes. Must be a positive integer; it is clamped to detected total RAM (logged as `mem.budget.clamped`), and non-numeric or non-positive values are ignored with a warning (`mem.budget.env.invalid`). |
|
||||
| `CBM_DUMP_VERIFY_MIN_RATIO` | `0.5` | After indexing, compare persisted SQLite node count to the in-memory dump count. When persisted nodes fall below this fraction of committed nodes (and committed > 50), `index_repository` returns `status:"degraded"` instead of silent `indexed`. Range 0–1; set `0` to disable. Invalid values are ignored with a warning. |
|
||||
|
||||
Environment used by daemon-owned components—such as diagnostics, daemon logging, and process-wide indexing resource limits—is captured from the first daemon-backed session that starts the daemon. Later sessions join that process and cannot replace those values. To change them, close all daemon-backed sessions, update the relevant agent configurations consistently, and restart a session. `CBM_ALLOWED_ROOT` remains session-specific, a conflicting `CBM_CACHE_DIR` is rejected, and one-shot CLI commands read their own environment without starting the daemon.
|
||||
Environment used by daemon-owned components—such as diagnostics, daemon logging, and process-wide indexing resource limits—is captured from the first daemon-backed session that starts the daemon. Later sessions join that process and cannot replace those values. To change them, close all daemon-backed sessions, update the relevant agent configurations consistently, and restart a session. `CBM_ALLOWED_ROOT` remains session-specific, a conflicting `CBM_CACHE_DIR` is rejected, and a one-shot CLI command is not exempt from the rule above: it connects to the coordination daemon like any other session, starting one if none is running, so its own environment becomes the captured daemon-owned environment only when its invocation is the one that starts the daemon — joining an already-running daemon, it inherits that daemon's already-captured values instead.
|
||||
|
||||
```bash
|
||||
# Store indexes in a custom directory
|
||||
@@ -799,6 +826,7 @@ SQLite databases stored at `~/.cache/codebase-memory-mcp/`. Persists across rest
|
||||
|---------|-----|
|
||||
| `/mcp` doesn't show the server | Check `.mcp.json` path is absolute. Restart agent. Test: `echo '{}' \| /path/to/binary` should output JSON. |
|
||||
| `index_repository` fails | Pass absolute path: `index_repository(repo_path="/absolute/path")` |
|
||||
| `index_repository` times out in the client | Start it with `async: true`, then poll with `status: true` (see [Indexing](#indexing)). |
|
||||
| `trace_path` returns 0 results | Use `search_graph(name_pattern=".*PartialName.*")` first to find the exact name. |
|
||||
| Queries return wrong project results | Add `project="name"` parameter. Use `list_projects` to see names. |
|
||||
| Binary not found after install | Add to PATH: `export PATH="$HOME/.local/bin:$PATH"` |
|
||||
|
||||
+12
-5
@@ -60,15 +60,22 @@ License summary:
|
||||
smart-coin language, written for this project because no usable public
|
||||
grammar exists; its source and corpus tests live in
|
||||
`tools/tree-sitter-chialisp/`.
|
||||
- Seven further grammars (`arkts`, `assembly`, `cfml`,
|
||||
`cfscript`, `dotenv`, `pine`, `qml`) are self-maintained forks that retain
|
||||
their original upstream authors' licenses — see the manifest for per-grammar
|
||||
provenance. `arkts` is a first-party derivative of
|
||||
- Nine further grammars (`arkts`, `assembly`, `cfml`,
|
||||
`cfscript`, `dotenv`, `javascript`, `pine`, `qml`, `tsx`) are self-maintained
|
||||
forks that retain their original upstream authors' licenses — see the manifest
|
||||
for per-grammar provenance. `arkts` is a first-party derivative of
|
||||
[tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)
|
||||
(MIT, (c) 2017 Max Brunsfeld; on the
|
||||
[tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript)
|
||||
base, MIT, (c) 2014 Max Brunsfeld) with (c) 2026 DeusData ArkTS additions;
|
||||
its grammar source lives in `tools/tree-sitter-arkts/`.
|
||||
its grammar source lives in `tools/tree-sitter-arkts/`. `javascript`
|
||||
([tree-sitter/tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript),
|
||||
MIT, (c) 2014 Max Brunsfeld) and `tsx`
|
||||
([tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)'s
|
||||
`tsx` dialect, MIT, (c) 2017 Max Brunsfeld, on the same javascript base) are
|
||||
the upstream grammars with one (c) 2026 DeusData patch that lets a lone `&`
|
||||
appear in JSX strings and text; their grammar sources live in
|
||||
`tools/tree-sitter-javascript/` and `tools/tree-sitter-tsx/`.
|
||||
|
||||
### tree-sitter-plsql
|
||||
|
||||
|
||||
+15
-1
@@ -200,7 +200,21 @@ process that should share one daemon must see the same value — set it in the
|
||||
environment of your MCP client and your shell alike, or a CLI invocation without
|
||||
it will coordinate through the default location instead.
|
||||
|
||||
Environment used by daemon-owned components—such as diagnostics, daemon logging, and process-wide indexing resource limits—is captured from the first daemon-backed session that starts the daemon. Later sessions join the existing process and cannot replace those values. To change them, close every daemon-backed session, update the relevant agent configurations consistently, and restart a session. `CBM_ALLOWED_ROOT` remains session-specific, a conflicting `CBM_CACHE_DIR` is rejected, and one-shot CLI commands use their own current environment without starting the daemon.
|
||||
**WSL2 and Windows drives (`/mnt/c`, `/mnt/e`, ...).** `CBM_CACHE_DIR` goes through
|
||||
the same private-directory check. With WSL's default automount options, DrvFs
|
||||
reports every directory as `0777` and ignores `chmod`, so a cache under
|
||||
`/mnt/<drive>` is refused, and the refusal names this remedy. Either turn on
|
||||
permission metadata in `/etc/wsl.conf`, then run `wsl --shutdown` and reopen WSL:
|
||||
|
||||
```ini
|
||||
[automount]
|
||||
options = "metadata,umask=22,fmask=11"
|
||||
```
|
||||
|
||||
or keep the cache on the Linux filesystem (the default `~/.cache/codebase-memory-mcp`),
|
||||
which is also much faster than a 9p-mounted Windows drive.
|
||||
|
||||
Environment used by daemon-owned components—such as diagnostics, daemon logging, and process-wide indexing resource limits—is captured from the first daemon-backed session that starts the daemon. Later sessions join the existing process and cannot replace those values. To change them, close every daemon-backed session, update the relevant agent configurations consistently, and restart a session. `CBM_ALLOWED_ROOT` remains session-specific, a conflicting `CBM_CACHE_DIR` is rejected, and a one-shot CLI command is not exempt from the rule above: it connects to the coordination daemon like any other session, starting one if none is running, so its own environment becomes the captured daemon-owned environment only when its invocation is the one that starts the daemon — joining an already-running daemon, it inherits that daemon's already-captured values instead.
|
||||
|
||||
|
||||
### Roots that are always refused
|
||||
|
||||
+6
-1
@@ -70,7 +70,12 @@ For directories:
|
||||
|
||||
1. **Built-in skip list** — `.git`, `node_modules`, `dist`, `target`,
|
||||
`vendor`, tool caches, etc. (60+ names; the fast/moderate index modes add
|
||||
more, e.g. `docs`, `examples`, `testdata`). A `.cbmignore` negation
|
||||
more, e.g. `docs`, `examples`, `testdata`). Generated output whose
|
||||
folder name alone is too common to skip everywhere is matched by path
|
||||
suffix instead: Laravel's compiled Blade view cache
|
||||
`storage/framework/views/` (at any depth) is skipped even without
|
||||
Laravel's stock `.gitignore` there, while other `views/` folders stay
|
||||
indexed. A `.cbmignore` negation
|
||||
(for example `!target/`) can un-skip these directories, except the
|
||||
non-negatable safety core: `.git`, `node_modules`, `.worktrees`, and
|
||||
`.claude-worktrees`.
|
||||
|
||||
+14
-3
@@ -238,6 +238,14 @@ typedef struct {
|
||||
* that declared this method. Kept at the tail so zero-initialised
|
||||
* callers in every other language remain ABI/source compatible. */
|
||||
const char *impl_trait;
|
||||
/* JS/TS only (#1916): a module-level binding initialised by
|
||||
* `axios.create(...)` records the client library here ("axios"), and the
|
||||
* literal `baseURL` string (or NULL when absent / not a string literal).
|
||||
* The Module def carries the pair when its default export is such a
|
||||
* client. The call resolver composes `<binding>.get('/p')` into an
|
||||
* HTTP_CALLS edge to base + path. Tail fields: zero-init stays valid. */
|
||||
const char *http_client;
|
||||
const char *http_base_url;
|
||||
} CBMDefinition;
|
||||
|
||||
/* Argument captured from a call expression */
|
||||
@@ -299,6 +307,7 @@ typedef struct {
|
||||
typedef struct {
|
||||
const char *local_name; // local alias or name
|
||||
const char *module_path; // resolved module path / QN
|
||||
bool is_default; // ES default import (`import X from "Y"`), JS/TS only (#1916)
|
||||
} CBMImport;
|
||||
|
||||
typedef enum {
|
||||
@@ -729,9 +738,6 @@ const char *cbm_index_quarantine_phase(const char *rel_path);
|
||||
void cbm_index_mark_start(const char *rel_path);
|
||||
void cbm_index_mark_done(const char *rel_path);
|
||||
|
||||
// Extract all data from one file. Caller must call cbm_free_result().
|
||||
// source must remain valid for the duration of the call.
|
||||
// timeout_micros: per-file parse timeout in microseconds (0 = no timeout).
|
||||
/* Compact a finished result: copy everything reachable from it -- every
|
||||
* record array at exact count, every string once (interned by content within
|
||||
* the file), the retained source -- into one exact-size arena, and destroy the
|
||||
@@ -767,6 +773,11 @@ void cbm_work_arena_keep_begin(void);
|
||||
/* Free the compaction scratch this thread kept (cbm_work_arena_release calls it). */
|
||||
void cbm_result_compact_release_thread(void);
|
||||
|
||||
// Extract all data from one file. Caller must call cbm_free_result().
|
||||
// source must remain valid for the duration of the call.
|
||||
// timeout_micros: per-file tree-sitter parse budget in microseconds of the
|
||||
// calling thread's CPU time, with a wall-clock backstop of
|
||||
// CBM_PARSE_WALL_CEILING_FACTOR x the budget (0 = no budget).
|
||||
CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage language,
|
||||
const char *project, const char *rel_path, int64_t timeout_micros,
|
||||
const char **extra_defines, // NULL-terminated, or NULL
|
||||
|
||||
@@ -2105,6 +2105,56 @@ static void process_keyword_arg(CBMExtractCtx *ctx, TSNode arg_node, CBMCallArg
|
||||
}
|
||||
}
|
||||
|
||||
static const char *extract_string_value(CBMExtractCtx *ctx, TSNode val_node);
|
||||
|
||||
/* A JS/TS request-config object -- `http({url: `/users/${id}`, method: 'GET'})`,
|
||||
* `axios({url: '/orders'})`, the shape Orval and similar generators emit -- names
|
||||
* its request URL in the `url` property. Return that URL (template literals
|
||||
* flattened to the canonical "{}" form, like a bare template argument), or NULL.
|
||||
* Only the `url` key counts: `path`/`endpoint` in an options object name other
|
||||
* things too often. Route registrations are excluded: an object there is the
|
||||
* route definition (Fastify `route({url, handler})`), not a client request, and
|
||||
* its handler lives inside the object where the route pass cannot read it. So is
|
||||
* axios `getUri(config)`: it takes the same config but only formats the URL and
|
||||
* sends nothing (Orval's `get<Op>Url` helpers). (#2235) */
|
||||
static bool config_object_callee_eligible(const CBMExtractCtx *ctx, const char *callee_name) {
|
||||
if (ctx->language != CBM_LANG_JAVASCRIPT && ctx->language != CBM_LANG_TYPESCRIPT &&
|
||||
ctx->language != CBM_LANG_TSX && ctx->language != CBM_LANG_ARKTS) {
|
||||
return false;
|
||||
}
|
||||
if (!callee_name || cbm_service_pattern_route_method(callee_name) != NULL) {
|
||||
return false;
|
||||
}
|
||||
static const char get_uri[] = "getUri";
|
||||
size_t clen = strlen(callee_name);
|
||||
size_t glen = sizeof(get_uri) - 1;
|
||||
return !(clen >= glen && strcmp(callee_name + clen - glen, get_uri) == 0);
|
||||
}
|
||||
|
||||
static const char *js_config_object_url(CBMExtractCtx *ctx, TSNode obj, const char *callee_name) {
|
||||
if (strcmp(ts_node_type(obj), "object") != 0 ||
|
||||
!config_object_callee_eligible(ctx, callee_name)) {
|
||||
return NULL;
|
||||
}
|
||||
uint32_t n = ts_node_named_child_count(obj);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode pair = ts_node_named_child(obj, i);
|
||||
if (strcmp(ts_node_type(pair), "pair") != 0) {
|
||||
continue;
|
||||
}
|
||||
TSNode key_n = ts_node_child_by_field_name(pair, TS_FIELD("key"));
|
||||
TSNode val_n = ts_node_child_by_field_name(pair, TS_FIELD("value"));
|
||||
if (ts_node_is_null(key_n) || ts_node_is_null(val_n)) {
|
||||
continue;
|
||||
}
|
||||
const char *key = strip_quotes(ctx->arena, cbm_node_text(ctx->arena, key_n, ctx->source));
|
||||
if (key && strcmp(key, "url") == 0) {
|
||||
return extract_string_value(ctx, val_n);
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Extract all arguments from a call expression into call->args[]. */
|
||||
static void extract_call_args(CBMExtractCtx *ctx, TSNode args, CBMCall *call) {
|
||||
uint32_t argc = ts_node_named_child_count(args);
|
||||
@@ -2147,6 +2197,10 @@ static void extract_call_args(CBMExtractCtx *ctx, TSNode args, CBMCall *call) {
|
||||
ca->value = cbm_template_string_text(ctx->arena, arg_node, ctx->source);
|
||||
} else if (strcmp(ak, "identifier") == 0 && ca->expr) {
|
||||
ca->value = lookup_string_constant(ctx, ca->expr);
|
||||
} else if (strcmp(ak, "object") == 0) {
|
||||
/* Request-config object: its `url` is what the arg-url
|
||||
* heuristic reads for a local fetch wrapper (#2235). */
|
||||
ca->value = js_config_object_url(ctx, arg_node, call->callee_name);
|
||||
} else if (strcmp(ak, "call_expression") == 0) {
|
||||
/* URL-builder helper call (issue #1009): resolve
|
||||
* client(buildPath(id)) through the per-file builder map. */
|
||||
@@ -2411,7 +2465,8 @@ static const char *extract_positional_url(CBMExtractCtx *ctx, TSNode arg, const
|
||||
}
|
||||
|
||||
// Extract URL/topic from keyword or positional args.
|
||||
static const char *extract_url_or_topic_arg(CBMExtractCtx *ctx, TSNode args) {
|
||||
static const char *extract_url_or_topic_arg(CBMExtractCtx *ctx, TSNode args,
|
||||
const char *callee_name) {
|
||||
uint32_t nc = ts_node_named_child_count(args);
|
||||
for (uint32_t ai = 0; ai < nc; ai++) {
|
||||
TSNode arg = ts_node_named_child(args, ai);
|
||||
@@ -2439,6 +2494,15 @@ static const char *extract_url_or_topic_arg(CBMExtractCtx *ctx, TSNode args) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/* JS/TS request-config object: `axios({url: '/orders'})` (#2235). */
|
||||
if (strcmp(ak, "object") == 0) {
|
||||
const char *val = js_config_object_url(ctx, arg, callee_name);
|
||||
if (val) {
|
||||
return val;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Cloud SDK dispatch via input struct: the queue/topic target is a field
|
||||
* of a composite literal (Go `&sqs.SendMessageInput{QueueUrl: ...}`), not
|
||||
* a bare string arg. Recover it so the async edge forms. */
|
||||
@@ -3876,7 +3940,7 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
|
||||
args = swift_call_args(node);
|
||||
}
|
||||
if (!ts_node_is_null(args)) {
|
||||
call.first_string_arg = extract_url_or_topic_arg(ctx, args);
|
||||
call.first_string_arg = extract_url_or_topic_arg(ctx, args, call.callee_name);
|
||||
/* #952: routes registered inside Laravel `prefix()->group()`
|
||||
* closures must carry the composed path — the resolve passes
|
||||
* only see the flat CBMCall, so the enclosing chain can only
|
||||
|
||||
@@ -1650,6 +1650,141 @@ static bool try_route_from_decorator_call(CBMArena *a, TSNode dchild, const char
|
||||
return true;
|
||||
}
|
||||
|
||||
/* NestJS (and routing-controllers) method decorators: the verb is the bare,
|
||||
* capitalized decorator name — @Get, @Post, ... @All. Returns NULL otherwise. */
|
||||
static const char *nest_decorator_method(const char *name) {
|
||||
static const struct {
|
||||
const char *decorator;
|
||||
const char *method;
|
||||
} verbs[] = {{"Get", "GET"}, {"Post", "POST"}, {"Put", "PUT"}, {"Delete", "DELETE"},
|
||||
{"Patch", "PATCH"}, {"Head", "HEAD"}, {"Options", "OPTIONS"}, {"All", "ANY"}};
|
||||
for (size_t i = 0; name && i < sizeof(verbs) / sizeof(verbs[0]); i++) {
|
||||
if (strcmp(name, verbs[i].decorator) == 0) {
|
||||
return verbs[i].method;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Unquote a TS `string` literal node and root it at "/": Nest writes route
|
||||
* segments without a leading slash (@Get(':id'), @Controller('users')). */
|
||||
static const char *nest_path_from_string(CBMArena *a, TSNode node, const char *source) {
|
||||
if (ts_node_is_null(node) || strcmp(ts_node_type(node), "string") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
char *text = cbm_node_text(a, node, source);
|
||||
size_t len = text ? strlen(text) : 0;
|
||||
if (len < PAIR_CHARS) {
|
||||
return NULL;
|
||||
}
|
||||
const char *inner = cbm_arena_strndup(a, text + SKIP_CHAR, len - PAIR_CHARS);
|
||||
if (!inner) {
|
||||
return NULL;
|
||||
}
|
||||
return inner[0] == '/' ? inner : cbm_arena_sprintf(a, "/%s", inner);
|
||||
}
|
||||
|
||||
/* The route path a Nest decorator's argument list carries. Accepted shapes:
|
||||
* () -> "/"
|
||||
* ('users') / (['a', 'b']) -> the (first) string literal
|
||||
* ({ path: 'users', ... }) -> the `path` property (Nest's options form)
|
||||
* Any other first argument (a constant, a template) has no statically known
|
||||
* path: NULL, so no Route is invented for it. */
|
||||
static const char *nest_path_from_args(CBMArena *a, TSNode args, const char *source) {
|
||||
if (ts_node_is_null(args) || ts_node_named_child_count(args) == 0) {
|
||||
return "/";
|
||||
}
|
||||
TSNode arg = ts_node_named_child(args, 0);
|
||||
const char *kind = ts_node_type(arg);
|
||||
if (strcmp(kind, "array") == 0 && ts_node_named_child_count(arg) > 0) {
|
||||
return nest_path_from_string(a, ts_node_named_child(arg, 0), source);
|
||||
}
|
||||
if (strcmp(kind, "object") != 0) {
|
||||
return nest_path_from_string(a, arg, source);
|
||||
}
|
||||
uint32_t nc = ts_node_named_child_count(arg);
|
||||
for (uint32_t i = 0; i < nc; i++) {
|
||||
TSNode pair = ts_node_named_child(arg, i);
|
||||
if (strcmp(ts_node_type(pair), "pair") != 0) {
|
||||
continue;
|
||||
}
|
||||
TSNode key = ts_node_child_by_field_name(pair, TS_FIELD("key"));
|
||||
char *key_text = ts_node_is_null(key) ? NULL : cbm_node_text(a, key, source);
|
||||
if (key_text && strcmp(key_text, "path") == 0) {
|
||||
return nest_path_from_string(a, ts_node_child_by_field_name(pair, TS_FIELD("value")),
|
||||
source);
|
||||
}
|
||||
}
|
||||
return "/"; /* options object without `path` (e.g. only `host`) */
|
||||
}
|
||||
|
||||
/* A TS decorator's call_expression as (bare name, argument list). Returns the
|
||||
* name, or NULL when the callee is not a plain identifier. */
|
||||
static const char *ts_decorator_call_name(CBMArena *a, TSNode call, const char *source,
|
||||
TSNode *out_args) {
|
||||
if (ts_node_is_null(call) || strcmp(ts_node_type(call), "call_expression") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
TSNode fn = ts_node_child_by_field_name(call, TS_FIELD("function"));
|
||||
if (ts_node_is_null(fn) || strcmp(ts_node_type(fn), "identifier") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
*out_args = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
|
||||
return cbm_node_text(a, fn, source);
|
||||
}
|
||||
|
||||
/* NestJS method route: @Get(':id') on a TS class method. The class-level
|
||||
* @Controller prefix is composed by the caller (nest_class_route_prefix). */
|
||||
static bool try_route_from_ts_decorator_call(CBMArena *a, TSNode dchild, const char *source,
|
||||
const char **out_path, const char **out_method) {
|
||||
TSNode args = {0};
|
||||
const char *method = nest_decorator_method(ts_decorator_call_name(a, dchild, source, &args));
|
||||
if (!method) {
|
||||
return false;
|
||||
}
|
||||
const char *path = nest_path_from_args(a, args, source);
|
||||
if (!path) {
|
||||
return false;
|
||||
}
|
||||
*out_path = path;
|
||||
*out_method = method;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The @Controller('users') prefix of a NestJS controller, from `decorator`
|
||||
* nodes that are children of the class node (`@X class C`) or its preceding
|
||||
* siblings (`@X export class C`: the decorator belongs to export_statement).
|
||||
* NULL when the class is not a controller. */
|
||||
static const char *nest_prefix_from_decorator(CBMArena *a, TSNode dec, const char *source) {
|
||||
if (strcmp(ts_node_type(dec), "decorator") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
TSNode args = {0};
|
||||
const char *name = ts_decorator_call_name(a, ts_node_named_child(dec, 0), source, &args);
|
||||
if (!name || (strcmp(name, "Controller") != 0 && strcmp(name, "JsonController") != 0)) {
|
||||
return NULL;
|
||||
}
|
||||
return nest_path_from_args(a, args, source);
|
||||
}
|
||||
|
||||
static const char *nest_class_route_prefix(CBMArena *a, TSNode class_node, const char *source) {
|
||||
uint32_t cc = ts_node_named_child_count(class_node);
|
||||
for (uint32_t i = 0; i < cc; i++) {
|
||||
const char *p = nest_prefix_from_decorator(a, ts_node_named_child(class_node, i), source);
|
||||
if (p) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
for (TSNode prev = ts_node_prev_named_sibling(class_node); !ts_node_is_null(prev);
|
||||
prev = ts_node_prev_named_sibling(prev)) {
|
||||
const char *p = nest_prefix_from_decorator(a, prev, source);
|
||||
if (p) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Resolve an annotation's name node across grammars. Java exposes a `name`
|
||||
* field; tree-sitter-kotlin does not — its annotation name lives in a nested
|
||||
* type_identifier:
|
||||
@@ -1822,6 +1957,9 @@ static void extract_route_from_decorators(CBMArena *a, TSNode func_node, const c
|
||||
uint32_t dc = ts_node_named_child_count(prev);
|
||||
for (uint32_t di = 0; di < dc; di++) {
|
||||
TSNode dchild = ts_node_named_child(prev, di);
|
||||
if (try_route_from_ts_decorator_call(a, dchild, source, out_path, out_method)) {
|
||||
return;
|
||||
}
|
||||
if (strcmp(ts_node_type(dchild), "call") != 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -5180,6 +5318,12 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node,
|
||||
const char *prefix = spring_class_route_prefix(a, class_node, ctx->source, spec);
|
||||
def.route_path = join_route_paths(a, prefix, def.route_path);
|
||||
}
|
||||
if (def.route_path && (ctx->language == CBM_LANG_TYPESCRIPT || ctx->language == CBM_LANG_TSX)) {
|
||||
/* NestJS: a verb decorator only routes inside a @Controller class. */
|
||||
const char *prefix = nest_class_route_prefix(a, class_node, ctx->source);
|
||||
def.route_path = prefix ? join_route_paths(a, prefix, def.route_path) : NULL;
|
||||
def.route_method = prefix ? def.route_method : NULL;
|
||||
}
|
||||
def.docstring = extract_docstring(a, child, ctx->source, ctx->language);
|
||||
|
||||
if (spec->branching_node_types && spec->branching_node_types[0]) {
|
||||
@@ -5773,6 +5917,123 @@ static bool is_require_import_call(TSNode value, const char *source, CBMArena *a
|
||||
return false;
|
||||
}
|
||||
|
||||
/* True when text of `node` equals `want` exactly (no arena allocation). */
|
||||
static bool js_node_text_is(TSNode node, const char *source, const char *want) {
|
||||
if (ts_node_is_null(node)) {
|
||||
return false;
|
||||
}
|
||||
uint32_t start = ts_node_start_byte(node);
|
||||
uint32_t end = ts_node_end_byte(node);
|
||||
size_t len = strlen(want);
|
||||
return end >= start && (size_t)(end - start) == len && memcmp(source + start, want, len) == 0;
|
||||
}
|
||||
|
||||
/* #1916: `axios.create(...)` — the factory of a configured axios instance
|
||||
* (the vue-element-admin / RuoYi `request.js` wrapper). Only the literal
|
||||
* `axios` receiver is recognised: a look-alike `factory.create(...)` is not
|
||||
* an HTTP client and must not turn its binding into one. */
|
||||
static bool js_is_axios_create_call(TSNode value, const char *source) {
|
||||
if (ts_node_is_null(value) || strcmp(ts_node_type(value), "call_expression") != 0) {
|
||||
return false;
|
||||
}
|
||||
TSNode fn = ts_node_child_by_field_name(value, TS_FIELD("function"));
|
||||
if (ts_node_is_null(fn) || strcmp(ts_node_type(fn), "member_expression") != 0) {
|
||||
return false;
|
||||
}
|
||||
TSNode obj = ts_node_child_by_field_name(fn, TS_FIELD("object"));
|
||||
TSNode prop = ts_node_child_by_field_name(fn, TS_FIELD("property"));
|
||||
return !ts_node_is_null(obj) && strcmp(ts_node_type(obj), "identifier") == 0 &&
|
||||
js_node_text_is(obj, source, "axios") && js_node_text_is(prop, source, "create");
|
||||
}
|
||||
|
||||
/* The literal `baseURL` of `axios.create({ baseURL: '<lit>' })`, or NULL when
|
||||
* the config is absent, not an object literal, or the value is not a plain
|
||||
* string literal (process.env.X, a template with substitutions, an escape):
|
||||
* an unknown base is never guessed. */
|
||||
static const char *js_axios_create_base_url(CBMArena *a, TSNode call, const char *source) {
|
||||
TSNode args = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
|
||||
if (ts_node_is_null(args) || ts_node_named_child_count(args) == 0) {
|
||||
return NULL;
|
||||
}
|
||||
TSNode cfg = ts_node_named_child(args, 0);
|
||||
if (strcmp(ts_node_type(cfg), "object") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
uint32_t n = ts_node_named_child_count(cfg);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode pair = ts_node_named_child(cfg, i);
|
||||
if (strcmp(ts_node_type(pair), "pair") != 0) {
|
||||
continue;
|
||||
}
|
||||
TSNode key = ts_node_child_by_field_name(pair, TS_FIELD("key"));
|
||||
if (!js_node_text_is(key, source, "baseURL") &&
|
||||
!js_node_text_is(key, source, "'baseURL'") &&
|
||||
!js_node_text_is(key, source, "\"baseURL\"")) {
|
||||
continue;
|
||||
}
|
||||
TSNode val = ts_node_child_by_field_name(pair, TS_FIELD("value"));
|
||||
if (ts_node_is_null(val) || strcmp(ts_node_type(val), "string") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
char *text = cbm_node_text(a, val, source);
|
||||
size_t len = text ? strlen(text) : 0;
|
||||
if (len < PAIR_LEN || strchr(text, '\\') != NULL) {
|
||||
return NULL;
|
||||
}
|
||||
text[len - SKIP_ONE] = '\0';
|
||||
return text + SKIP_ONE;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Mark `def` as an axios client instance created by `call` (#1916). */
|
||||
static void js_mark_axios_client(CBMArena *a, CBMDefinition *def, TSNode call, const char *source) {
|
||||
def->http_client = "axios";
|
||||
def->http_base_url = js_axios_create_base_url(a, call, source);
|
||||
}
|
||||
|
||||
/* #1916: `export default api;` (api an axios instance declared above) or
|
||||
* `export default axios.create({...})` makes the MODULE's default export the
|
||||
* client — record it on the Module def so a default import can find it. */
|
||||
static void js_mark_default_export_client(CBMExtractCtx *ctx, int mod_idx) {
|
||||
if (mod_idx < 0 || mod_idx >= ctx->result->defs.count) {
|
||||
return;
|
||||
}
|
||||
TSTreeCursor cursor = ts_tree_cursor_new(ctx->root);
|
||||
if (!ts_tree_cursor_goto_first_child(&cursor)) {
|
||||
ts_tree_cursor_delete(&cursor);
|
||||
return;
|
||||
}
|
||||
do {
|
||||
TSNode stmt = ts_tree_cursor_current_node(&cursor);
|
||||
if (strcmp(ts_node_type(stmt), "export_statement") != 0) {
|
||||
continue;
|
||||
}
|
||||
TSNode val = ts_node_child_by_field_name(stmt, TS_FIELD("value"));
|
||||
if (ts_node_is_null(val)) {
|
||||
continue;
|
||||
}
|
||||
CBMDefinition *mod = &ctx->result->defs.items[mod_idx];
|
||||
if (js_is_axios_create_call(val, ctx->source)) {
|
||||
js_mark_axios_client(ctx->arena, mod, val, ctx->source);
|
||||
continue;
|
||||
}
|
||||
if (strcmp(ts_node_type(val), "identifier") != 0) {
|
||||
continue;
|
||||
}
|
||||
for (int d = 0; d < ctx->result->defs.count; d++) {
|
||||
const CBMDefinition *v = &ctx->result->defs.items[d];
|
||||
if (v->http_client && v->label && strcmp(v->label, "Variable") == 0 && v->name &&
|
||||
!v->parent_class && js_node_text_is(val, ctx->source, v->name)) {
|
||||
mod->http_client = v->http_client;
|
||||
mod->http_base_url = v->http_base_url;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} while (ts_tree_cursor_goto_next_sibling(&cursor));
|
||||
ts_tree_cursor_delete(&cursor);
|
||||
}
|
||||
|
||||
// JS/TS variable extraction: skip function-assigned declarators.
|
||||
static void extract_js_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
|
||||
uint32_t n = ts_node_named_child_count(node);
|
||||
@@ -5808,7 +6069,12 @@ static void extract_js_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
|
||||
if (is_require) {
|
||||
continue;
|
||||
}
|
||||
int before = ctx->result->defs.count;
|
||||
push_var_def(ctx, cbm_node_text(a, vname, ctx->source), child);
|
||||
if (ctx->result->defs.count > before &&
|
||||
js_is_axios_create_call(value, ctx->source)) {
|
||||
js_mark_axios_client(a, &ctx->result->defs.items[before], value, ctx->source);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7484,6 +7750,38 @@ static void extract_typescript_namespace_def(CBMExtractCtx *ctx, TSNode node,
|
||||
cbm_defs_push(&ctx->result->defs, ctx->arena, def);
|
||||
}
|
||||
|
||||
/* Dart `extension on T { ... }` has no name: there is no container def to hang
|
||||
* its members on, and extract_class_def would bail before extract_class_methods,
|
||||
* dropping every member (#1457). */
|
||||
static bool is_dart_unnamed_extension(const CBMExtractCtx *ctx, TSNode node) {
|
||||
return ctx->language == CBM_LANG_DART &&
|
||||
strcmp(ts_node_type(node), "extension_declaration") == 0 &&
|
||||
ts_node_is_null(ts_node_child_by_field_name(node, TS_FIELD("name")));
|
||||
}
|
||||
|
||||
/* Walk an unnamed Dart extension's members as file-level functions. A member is
|
||||
* `method_signature > function_signature`; the wrapper carries no name of its
|
||||
* own, so push the inner function_signature (which does) for the generic walk. */
|
||||
static void push_dart_unnamed_extension_members(TSNode node, wd_stack_t *s,
|
||||
const char *enclosing_qn) {
|
||||
TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
|
||||
if (ts_node_is_null(body)) {
|
||||
return;
|
||||
}
|
||||
uint32_t nc = ts_node_named_child_count(body);
|
||||
for (int i = (int)nc - 1; i >= 0; i--) {
|
||||
TSNode child = ts_node_named_child(body, (uint32_t)i);
|
||||
if (strcmp(ts_node_type(child), "method_signature") == 0) {
|
||||
TSNode sig = cbm_find_child_by_kind(child, "function_signature");
|
||||
if (!ts_node_is_null(sig)) {
|
||||
wd_push(s, sig, enclosing_qn);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
wd_push(s, child, enclosing_qn);
|
||||
}
|
||||
}
|
||||
|
||||
// Push nested class children from a class body container onto the walk stack.
|
||||
static void push_class_body_children(TSNode node, const CBMLangSpec *spec, wd_stack_t *s,
|
||||
const char *new_enclosing, const CBMExtractCtx *ctx) {
|
||||
@@ -8086,6 +8384,11 @@ static void walk_defs(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec,
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_dart_unnamed_extension(ctx, node)) {
|
||||
push_dart_unnamed_extension_members(node, &s, frame.enclosing_class_qn);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cbm_kind_in_set(node, spec->class_node_types)) {
|
||||
extract_class_def(ctx, node, spec);
|
||||
const char *new_enclosing = compute_class_qn(ctx, node, frame.enclosing_class_qn);
|
||||
@@ -8246,7 +8549,14 @@ void cbm_extract_definitions(CBMExtractCtx *ctx) {
|
||||
mod.route_method = "GET"; /* a routable page is reached by navigation */
|
||||
}
|
||||
}
|
||||
int mod_idx = ctx->result->defs.count;
|
||||
cbm_defs_push(&ctx->result->defs, a, mod);
|
||||
|
||||
cbm_extract_definitions_without_module(ctx);
|
||||
|
||||
if (ctx->language == CBM_LANG_JAVASCRIPT || ctx->language == CBM_LANG_TYPESCRIPT ||
|
||||
ctx->language == CBM_LANG_TSX || ctx->language == CBM_LANG_ARKTS) {
|
||||
/* Same language set as extract_js_vars, which marks the bindings. */
|
||||
js_mark_default_export_client(ctx, mod_idx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,7 +394,7 @@ static bool process_import_clause(CBMExtractCtx *ctx, TSNode clause, const char
|
||||
const char *sk = ts_node_type(sub);
|
||||
if (strcmp(sk, "identifier") == 0) {
|
||||
char *name = cbm_node_text(a, sub, ctx->source);
|
||||
CBMImport imp = {.local_name = name, .module_path = path};
|
||||
CBMImport imp = {.local_name = name, .module_path = path, .is_default = true};
|
||||
cbm_imports_push(&ctx->result->imports, a, imp);
|
||||
found = true;
|
||||
} else if (strcmp(sk, "namespace_import") == 0) {
|
||||
|
||||
@@ -594,8 +594,9 @@ static const char *swift_decorator_types[] = {"attribute", NULL};
|
||||
// ==================== DART ====================
|
||||
static const char *dart_func_types[] = {"function_signature", "method_signature",
|
||||
"lambda_expression", NULL};
|
||||
static const char *dart_class_types[] = {"class_definition", "enum_declaration",
|
||||
"mixin_declaration", "type_alias", NULL};
|
||||
static const char *dart_class_types[] = {"class_definition", "enum_declaration",
|
||||
"mixin_declaration", "extension_declaration",
|
||||
"type_alias", NULL};
|
||||
static const char *dart_field_types[] = {"declaration", NULL};
|
||||
static const char *dart_module_types[] = {"program", NULL};
|
||||
static const char *dart_call_types[] = {"selector", "new_expression", NULL};
|
||||
|
||||
@@ -2880,6 +2880,23 @@ static bool c_base_declares_member(CLSPContext *ctx, const char *type_qn, const
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Type of the idx-th declared field, for structured-binding decomposition.
|
||||
* field_types[] is parallel to field_names[] and may hold NULL entries, so
|
||||
* only field_names[] bounds it: a binding list longer than the field list
|
||||
* (ill-formed, but present in compiler test suites) must yield NULL, never
|
||||
* read past the array into the next arena object (#1743). */
|
||||
static const CBMType *c_struct_field_type_at(const CBMRegisteredType *rt, int idx) {
|
||||
if (!rt || !rt->field_names || !rt->field_types || idx < 0) {
|
||||
return NULL;
|
||||
}
|
||||
for (int i = 0; i < idx; i++) {
|
||||
if (!rt->field_names[i]) {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
return rt->field_names[idx] ? rt->field_types[idx] : NULL;
|
||||
}
|
||||
|
||||
// Field type lookup
|
||||
static const CBMType *c_lookup_field_type(CLSPContext *ctx, const char *type_qn,
|
||||
const char *field_name, int depth) {
|
||||
@@ -3055,9 +3072,10 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
|
||||
ctx->registry,
|
||||
cbm_arena_sprintf(ctx->arena, "%s.%s",
|
||||
ctx->module_qn, rhs_qn));
|
||||
if (rt && rt->field_types &&
|
||||
rt->field_types[binding_idx])
|
||||
elem_type = rt->field_types[binding_idx];
|
||||
const CBMType *ft =
|
||||
c_struct_field_type_at(rt, binding_idx);
|
||||
if (ft)
|
||||
elem_type = ft;
|
||||
}
|
||||
cbm_scope_bind(ctx->current_scope, bname, elem_type);
|
||||
binding_idx++;
|
||||
@@ -3140,8 +3158,9 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
|
||||
ctx->registry,
|
||||
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn,
|
||||
rhs_qn));
|
||||
if (rt && rt->field_types && rt->field_types[binding_idx]) {
|
||||
elem_type = rt->field_types[binding_idx];
|
||||
const CBMType *ft = c_struct_field_type_at(rt, binding_idx);
|
||||
if (ft) {
|
||||
elem_type = ft;
|
||||
}
|
||||
}
|
||||
cbm_scope_bind(ctx->current_scope, bname, elem_type);
|
||||
@@ -3551,8 +3570,9 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
|
||||
rt = cbm_registry_lookup_type(
|
||||
ctx->registry,
|
||||
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, eq));
|
||||
if (rt && rt->field_types && rt->field_types[binding_idx])
|
||||
bt = rt->field_types[binding_idx];
|
||||
const CBMType *ft = c_struct_field_type_at(rt, binding_idx);
|
||||
if (ft)
|
||||
bt = ft;
|
||||
}
|
||||
cbm_scope_bind(ctx->current_scope, bname, bt);
|
||||
binding_idx++;
|
||||
|
||||
@@ -631,7 +631,18 @@ void cbm_rust_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
|
||||
|
||||
/* ── std::path ─────────────────────────────────────────────── */
|
||||
ADD_TYPE("std.path.Path", "Path", false);
|
||||
ADD_TYPE("std.path.PathBuf", "PathBuf", false);
|
||||
{
|
||||
/* PathBuf derefs to Path (#2053): `buf.join(..)` dispatches through
|
||||
* rust_deref_step's DerefTarget entry to std.path.Path.join instead of
|
||||
* leaving the receiver's method unknown. */
|
||||
static const char *pathbuf_deref[] = {"DerefTarget:std.path.Path", NULL};
|
||||
CBMRegisteredType _rt;
|
||||
memset(&_rt, 0, sizeof(_rt));
|
||||
_rt.qualified_name = "std.path.PathBuf";
|
||||
_rt.short_name = "PathBuf";
|
||||
_rt.embedded_types = pathbuf_deref;
|
||||
cbm_registry_add_type(reg, _rt);
|
||||
}
|
||||
ADD_TYPE("std.path.Component", "Component", false);
|
||||
ADD_TYPE("std.path.Components", "Components", false);
|
||||
ADD_TYPE("std.path.Iter", "Iter", false);
|
||||
@@ -639,6 +650,9 @@ void cbm_rust_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
|
||||
|
||||
{
|
||||
const char* T = "std.path.Path";
|
||||
/* Owned-path producers return PathBuf (#2053), so a chained call
|
||||
* (`root.to_path_buf().join(..)`) keeps a typed receiver. */
|
||||
const CBMType* t_pathbuf = cbm_type_named(arena, "std.path.PathBuf");
|
||||
ADD_FUNC(T, "new", "std.path.Path.new", cbm_type_unknown());
|
||||
ADD_FUNC(T, "exists", "std.path.Path.exists", t_bool);
|
||||
ADD_FUNC(T, "try_exists", "std.path.Path.try_exists", cbm_type_unknown());
|
||||
@@ -656,16 +670,16 @@ void cbm_rust_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
|
||||
ADD_FUNC(T, "parent", "std.path.Path.parent", cbm_type_unknown());
|
||||
ADD_FUNC(T, "components", "std.path.Path.components", cbm_type_unknown());
|
||||
ADD_FUNC(T, "iter", "std.path.Path.iter", cbm_type_unknown());
|
||||
ADD_FUNC(T, "join", "std.path.Path.join", cbm_type_unknown());
|
||||
ADD_FUNC(T, "join", "std.path.Path.join", t_pathbuf);
|
||||
ADD_FUNC(T, "display", "std.path.Path.display", cbm_type_unknown());
|
||||
ADD_FUNC(T, "canonicalize", "std.path.Path.canonicalize", cbm_type_unknown());
|
||||
ADD_FUNC(T, "to_path_buf", "std.path.Path.to_path_buf", cbm_type_unknown());
|
||||
ADD_FUNC(T, "to_path_buf", "std.path.Path.to_path_buf", t_pathbuf);
|
||||
ADD_FUNC(T, "to_str", "std.path.Path.to_str", cbm_type_unknown());
|
||||
ADD_FUNC(T, "to_string_lossy", "std.path.Path.to_string_lossy", cbm_type_unknown());
|
||||
ADD_FUNC(T, "metadata", "std.path.Path.metadata", cbm_type_unknown());
|
||||
ADD_FUNC(T, "read_dir", "std.path.Path.read_dir", cbm_type_unknown());
|
||||
ADD_FUNC(T, "with_extension", "std.path.Path.with_extension", cbm_type_unknown());
|
||||
ADD_FUNC(T, "with_file_name", "std.path.Path.with_file_name", cbm_type_unknown());
|
||||
ADD_FUNC(T, "with_extension", "std.path.Path.with_extension", t_pathbuf);
|
||||
ADD_FUNC(T, "with_file_name", "std.path.Path.with_file_name", t_pathbuf);
|
||||
}
|
||||
{
|
||||
const char* T = "std.path.PathBuf";
|
||||
@@ -676,7 +690,7 @@ void cbm_rust_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
|
||||
ADD_FUNC(T, "pop", "std.path.PathBuf.pop", t_bool);
|
||||
ADD_FUNC(T, "set_file_name", "std.path.PathBuf.set_file_name",t_unit);
|
||||
ADD_FUNC(T, "set_extension", "std.path.PathBuf.set_extension",t_bool);
|
||||
ADD_FUNC(T, "as_path", "std.path.PathBuf.as_path", cbm_type_unknown());
|
||||
ADD_FUNC(T, "as_path", "std.path.PathBuf.as_path", cbm_type_named(arena, "std.path.Path"));
|
||||
ADD_FUNC(T, "into_os_string", "std.path.PathBuf.into_os_string",cbm_type_unknown());
|
||||
ADD_FUNC(T, "clear", "std.path.PathBuf.clear", t_unit);
|
||||
}
|
||||
|
||||
+57
-17
@@ -1406,17 +1406,30 @@ static bool ts_scope_has_binding(const CBMScope *scope, const char *name) {
|
||||
return ts_scope_binding_owner(scope, name) != NULL;
|
||||
}
|
||||
|
||||
/* Full QN of an imported symbol. An import value is normally the module QN
|
||||
* (symbol = module + "." + name), but may already be the symbol QN. When the
|
||||
* module QN ends in ".name" the spelling is ambiguous: `Foo.ts` exporting
|
||||
* `Foo` (module `x.Foo`, symbol `x.Foo.Foo`) looks exactly like an
|
||||
* already-qualified value. Treating it as the symbol typed every imported
|
||||
* same-name class as its module (#1354), so the registry decides: a
|
||||
* registered `module.name` wins, else the value is the symbol. Two hashed
|
||||
* lookups on a finalized/sealed registry, only in the ambiguous case. */
|
||||
static const char *ts_import_symbol_qn(TSLSPContext *ctx, const char *module_qn, const char *name) {
|
||||
if (!ctx || !module_qn || !name) {
|
||||
return NULL;
|
||||
}
|
||||
const char *appended = cbm_arena_sprintf(ctx->arena, "%s.%s", module_qn, name);
|
||||
size_t module_len = strlen(module_qn);
|
||||
size_t name_len = strlen(name);
|
||||
if (module_len > name_len + 1 && module_qn[module_len - name_len - 1] == '.' &&
|
||||
strcmp(module_qn + module_len - name_len, name) == 0) {
|
||||
if (appended && (cbm_registry_lookup_type(ctx->registry, appended) ||
|
||||
cbm_registry_lookup_func(ctx->registry, appended))) {
|
||||
return appended;
|
||||
}
|
||||
return module_qn;
|
||||
}
|
||||
return cbm_arena_sprintf(ctx->arena, "%s.%s", module_qn, name);
|
||||
return appended;
|
||||
}
|
||||
|
||||
/* Same-file function values use only the exact current-module QN. No short-name,
|
||||
@@ -1785,9 +1798,28 @@ static const CBMType *eval_indexed_access(TSLSPContext *ctx, const CBMType *obj,
|
||||
return cbm_type_unknown();
|
||||
}
|
||||
|
||||
// Look up a method on a receiver type — returns the registered func.
|
||||
static const CBMRegisteredFunc *lookup_method_inner(TSLSPContext *ctx, const CBMType *recv,
|
||||
const char *method_name);
|
||||
|
||||
/* Depth-guarded entry, same contract as lookup_member_type: the method walk
|
||||
* recurses through wrapper classes, union members and the extends/implements
|
||||
* chain. A cyclic chain (#1743: the Effect idiom `class Service extends
|
||||
* Context.Service<Service, I>()(...)` whose base resolved to the class itself)
|
||||
* recursed without bound and overflowed the resolver thread's stack. Past the
|
||||
* cap the method is simply not found. */
|
||||
static const CBMRegisteredFunc *lookup_method(TSLSPContext *ctx, const CBMType *recv,
|
||||
const char *method_name) {
|
||||
if (!ctx || ctx->method_depth >= TS_LSP_MAX_MEMBER_DEPTH)
|
||||
return NULL;
|
||||
ctx->method_depth++;
|
||||
const CBMRegisteredFunc *f = lookup_method_inner(ctx, recv, method_name);
|
||||
ctx->method_depth--;
|
||||
return f;
|
||||
}
|
||||
|
||||
// Look up a method on a receiver type — returns the registered func.
|
||||
static const CBMRegisteredFunc *lookup_method_inner(TSLSPContext *ctx, const CBMType *recv,
|
||||
const char *method_name) {
|
||||
if (!ctx || !recv || !method_name)
|
||||
return NULL;
|
||||
const CBMType *base = simplify_type(ctx, recv);
|
||||
@@ -1946,6 +1978,26 @@ static const char *ts_import_module_for_local(const TSLSPContext *ctx, const cha
|
||||
return matched;
|
||||
}
|
||||
|
||||
/* Type of `new C()` for a bare class name, in TS scoping order: a class
|
||||
* declared in this module, else the class an unambiguous import binding
|
||||
* names, else the historical current-module spelling. Without the import
|
||||
* step (#1354) `new ImportedClass()` was typed as a phantom current-module
|
||||
* class, so every method call on the instance missed the registry and the
|
||||
* cross-file edge was lost while the same code in the class's own file
|
||||
* resolved. One hashed type lookup; the registry is only read. */
|
||||
static const CBMType *ts_new_bare_class_type(TSLSPContext *ctx, const char *cname) {
|
||||
if (!ctx->module_qn)
|
||||
return cbm_type_named(ctx->arena, cname);
|
||||
const char *local_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cname);
|
||||
if (cbm_registry_lookup_type(ctx->registry, local_qn))
|
||||
return cbm_type_named(ctx->arena, local_qn);
|
||||
bool import_matched = false;
|
||||
const char *import_module = ts_import_module_for_local(ctx, cname, &import_matched);
|
||||
if (import_module)
|
||||
return cbm_type_named(ctx->arena, ts_import_symbol_qn(ctx, import_module, cname));
|
||||
return cbm_type_named(ctx->arena, local_qn);
|
||||
}
|
||||
|
||||
static const CBMRegisteredFunc *ts_lookup_namespace_call(TSLSPContext *ctx, const char *object_name,
|
||||
const char *method_name, TSNode args,
|
||||
bool *out_is_import) {
|
||||
@@ -2176,13 +2228,8 @@ const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {
|
||||
if (!ts_node_is_null(ctor)) {
|
||||
char *cname = node_text(ctx, ctor);
|
||||
if (cname) {
|
||||
// Bare class name → qualify against module.
|
||||
if (strchr(cname, '.') == NULL && ctx->module_qn) {
|
||||
const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cname);
|
||||
result = cbm_type_named(ctx->arena, qn);
|
||||
} else {
|
||||
result = cbm_type_named(ctx->arena, cname);
|
||||
}
|
||||
result = strchr(cname, '.') == NULL ? ts_new_bare_class_type(ctx, cname)
|
||||
: cbm_type_named(ctx->arena, cname);
|
||||
}
|
||||
}
|
||||
} else if (strcmp(kind, "call_expression") == 0) {
|
||||
@@ -2416,14 +2463,7 @@ static const CBMType *resolve_type_with_imports(TSLSPContext *ctx, const CBMType
|
||||
continue;
|
||||
if (strcmp(lname, bare) != 0)
|
||||
continue;
|
||||
// Heuristic: if mqn already ends in ".bare" use as-is; otherwise append.
|
||||
size_t mqn_len = strlen(mqn);
|
||||
size_t bare_len = strlen(bare);
|
||||
if (mqn_len > bare_len + 1 && mqn[mqn_len - bare_len - 1] == '.' &&
|
||||
strcmp(mqn + mqn_len - bare_len, bare) == 0) {
|
||||
return cbm_type_named(ctx->arena, mqn);
|
||||
}
|
||||
return cbm_type_named(ctx->arena, cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, bare));
|
||||
return cbm_type_named(ctx->arena, ts_import_symbol_qn(ctx, mqn, bare));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@@ -69,6 +69,9 @@ typedef struct {
|
||||
// recursive unions/wrappers across registered types) otherwise recurse
|
||||
// without bound — stack overflow on real repos.
|
||||
int member_depth;
|
||||
// Same guard for lookup_method: its extends/implements walk recursed
|
||||
// without bound on a cyclic heritage chain (#1743).
|
||||
int method_depth;
|
||||
} TSLSPContext;
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
|
||||
@@ -273,6 +273,8 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) {
|
||||
cr_str(c, &d->structural_profile);
|
||||
cr_str(c, &d->body_tokens);
|
||||
cr_str(c, &d->impl_trait);
|
||||
cr_str(c, &d->http_client);
|
||||
cr_str(c, &d->http_base_url);
|
||||
}
|
||||
|
||||
static void cr_walk_call(cr_ctx_t *c, CBMCall *call) {
|
||||
|
||||
@@ -106,6 +106,31 @@ struct cbm_result_spill {
|
||||
* target to race against, and a failed write stays handled underneath. */
|
||||
enum { SPILL_FREE_FLOOR_GB = 10, SPILL_FREE_SHARE_DIV = 2 };
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* Set by the test's main thread before any worker exists; atomic so a reading
|
||||
* worker and a restoring test can never race under TSan. */
|
||||
static _Atomic size_t g_free_bytes_pin;
|
||||
|
||||
size_t cbm_result_spill_pin_free_bytes_for_tests(size_t bytes) {
|
||||
return atomic_exchange_explicit(&g_free_bytes_pin, bytes, memory_order_relaxed);
|
||||
}
|
||||
|
||||
size_t cbm_result_spill_free_floor_bytes_for_tests(void) {
|
||||
return (size_t)SPILL_FREE_FLOOR_GB * 1024 * 1024 * 1024;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Free space under the spill directory. Production always asks the disk. */
|
||||
static size_t spill_free_bytes(const char *spill_dir) {
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
size_t pinned = atomic_load_explicit(&g_free_bytes_pin, memory_order_relaxed);
|
||||
if (pinned > 0) {
|
||||
return pinned;
|
||||
}
|
||||
#endif
|
||||
return cbm_fs_free_bytes(spill_dir);
|
||||
}
|
||||
|
||||
/* Remove spill files left by runs that are no longer here. Only files this
|
||||
* module names (spill-<pid>-<writer>.bin) are touched, and on Windows an open
|
||||
* file refuses deletion, which is exactly the liveness check we want: a running
|
||||
@@ -164,7 +189,7 @@ cbm_result_spill_t *cbm_result_spill_open(const char *dir, int writers, int slot
|
||||
* caller in the memory path it was already in (back-pressure, then its own
|
||||
* budget decision) — the same outcome as a disk that fills mid-run, minus
|
||||
* the filled disk. */
|
||||
size_t free_bytes = cbm_fs_free_bytes(spill_dir);
|
||||
size_t free_bytes = spill_free_bytes(spill_dir);
|
||||
int64_t byte_cap = 0;
|
||||
if (free_bytes > 0) {
|
||||
size_t floor_bytes = (size_t)SPILL_FREE_FLOOR_GB * 1024 * 1024 * 1024;
|
||||
|
||||
@@ -70,4 +70,15 @@ void cbm_result_spill_close(cbm_result_spill_t *sp);
|
||||
* `new_base`. Exposed for tests. */
|
||||
void cbm_result_relocate(CBMFileResult *result, const char *old_base, size_t len, char *new_base);
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* Test builds only: open's free-space reading (and so its low-disk refusal and
|
||||
* its disk-share cap) answers `bytes` instead of asking the disk; 0 asks the
|
||||
* disk again. Returns the previous pin. A test's verdict must not depend on how
|
||||
* full the machine's disk happens to be, so the test runner pins ample space
|
||||
* for the whole process and the refusal test pins a low value on purpose. */
|
||||
size_t cbm_result_spill_pin_free_bytes_for_tests(size_t bytes);
|
||||
/* The production floor: below this much free space, open refuses. */
|
||||
size_t cbm_result_spill_free_floor_bytes_for_tests(void);
|
||||
#endif
|
||||
|
||||
#endif /* CBM_RESULT_SPILL_H */
|
||||
|
||||
@@ -747,6 +747,20 @@ static void free_children(PageRef *children, int child_count, const PageRef *lea
|
||||
}
|
||||
}
|
||||
|
||||
// Take the most recently placed cell back off an interior page (it is always
|
||||
// the lowest one in the content area) and zero its bytes, so the page is
|
||||
// byte-identical to one that never held it. Requires cell_count >= 2.
|
||||
static void unplace_last_interior_cell(uint8_t *page, int *cell_count, int *content_offset,
|
||||
int *ptr_offset) {
|
||||
const uint8_t *prev_ptr = page + *ptr_offset - (2 * CELL_PTR_SIZE);
|
||||
int prev_offset = (prev_ptr[0] << 8) | prev_ptr[1];
|
||||
memset(page + *content_offset, 0, (size_t)(prev_offset - *content_offset));
|
||||
*ptr_offset -= CELL_PTR_SIZE;
|
||||
memset(page + *ptr_offset, 0, CELL_PTR_SIZE);
|
||||
*content_offset = prev_offset;
|
||||
(*cell_count)--;
|
||||
}
|
||||
|
||||
// Fill an interior page with cells from children[*idx..child_count-2].
|
||||
// Updates cell_count, content_offset, ptr_offset, and *idx.
|
||||
static void fill_interior_page(uint8_t *page, const PageRef *children, int child_count,
|
||||
@@ -761,6 +775,17 @@ static void fill_interior_page(uint8_t *page, const PageRef *children, int child
|
||||
int available = *content_offset - *ptr_offset - CELL_PTR_SIZE;
|
||||
if (clen > available && *cell_count > 0) {
|
||||
free(heap_cell);
|
||||
/* Full with children[*idx] as this page's right child. If that
|
||||
* leaves exactly ONE child (the last), the next page would hold
|
||||
* zero cells and only a right-child pointer — SQLite reports
|
||||
* SQLITE_CORRUPT when a cursor descends into such a page (the
|
||||
* rightmost path, which a key sorting after every row takes;
|
||||
* #1783). Give the last cell back so the next page gets one
|
||||
* cell plus the last child as its right child. */
|
||||
if (*idx == child_count - 2 && *cell_count > SKIP_ONE) {
|
||||
unplace_last_interior_cell(page, cell_count, content_offset, ptr_offset);
|
||||
(*idx)--;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,9 @@ The grammars were originally vendored as bare `parser.c`+`scanner.c` with **no r
|
||||
|
||||
## Summary
|
||||
|
||||
- Grammars: **162** — vendored-from-upstream: **143**, first-party/self-maintained: **14**, registry-disagreement: **5** (nim removed 2026-06-12; objectscript_udl + objectscript_routine added 2026-06-24; mojo added 2026-07-01; arkts added 2026-08-26; plsql added 2026-08-27; chialisp added 2026-08-28 — see notes below)
|
||||
- ABI distribution: **9×** ABI-13 **79×** ABI-14 **74×** ABI-15 (runtime ceiling is ABI 15; never vendor ABI 16 without a runtime upgrade)
|
||||
- Grammars: **162** — vendored-from-upstream: **141**, first-party/self-maintained: **16**, registry-disagreement: **5** (nim removed 2026-06-12; objectscript_udl + objectscript_routine added 2026-06-24; mojo added 2026-07-01; arkts added 2026-08-26; plsql added 2026-08-27; chialisp added 2026-08-28; javascript + tsx became self-maintained forks 2026-09-25 — see notes below)
|
||||
- ABI distribution: **9×** ABI-13 **78×** ABI-14 **75×** ABI-15 (runtime ceiling is ABI 15; never vendor ABI 16 without a runtime upgrade)
|
||||
— recounted from the tree 2026-09-25 after the tsx fork was regenerated with tree-sitter-cli 0.25.10, moving `tsx` from ABI 14 to ABI 15 (was `9×/79×/74×`).
|
||||
— recounted from the tree 2026-08-30 after the perl v1.2.1 refresh moved `perl` from ABI 14 to ABI 15 (was `9×/80×/73×`). Neither side of the rebase had this right: main's line was correct for main, and this branch still carried the pre-2026-08-28 `7×/84×/65×`. Regenerate, never increment.
|
||||
— recounted from the tree 2026-08-28. This line had drifted: it read `7×/86×/65×`, which sums to 158 against 161 vendored grammars, so it was wrong before Chialisp was added and incrementing it would have carried the error forward. Regenerate with:
|
||||
`grep -h '#define LANGUAGE_VERSION' internal/cbm/vendored/grammars/*/parser.c | sort | uniq -c`
|
||||
@@ -32,6 +33,7 @@ The grammars were originally vendored as bare `parser.c`+`scanner.c` with **no r
|
||||
- **objectscript_udl / objectscript_routine** (added 2026-06-24): vendored from [intersystems/tree-sitter-objectscript](https://github.com/intersystems/tree-sitter-objectscript) @ `a7ffcdf` — MIT, the InterSystems-official grammars (a niche vendor language, hence `vendor-maintained`, not in nvim-treesitter/Helix). **Re-vendor note:** each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` (a verbatim copy of upstream `common/scanner.h`), because this repo's shared `vendored/common/scanner.h` belongs to the cfml/fsharp grammars and differs. The generated `parser.c`/`scanner.c` are otherwise byte-for-byte upstream — on re-vendor, re-apply only that single include rename. **Local modification (2026-07-16):** in `objectscript_common.h`, two loop counters `uint8_t i` were widened to `int i` (the `reverse_marker` scan and the `html_marker_buffer` reversal) to clear CodeQL `cpp/comparison-with-wider-type` — a false positive in practice (both lengths are hard-bounded by `MARKER_BUFFER_MAX_LEN = 30`, so `uint8_t` could never wrap), fixed for cleanliness. On re-vendor, re-apply this widening too (or upstream it at intersystems/tree-sitter-objectscript).
|
||||
- **mojo** (added 2026-07-01): vendored from [lsh/tree-sitter-mojo](https://github.com/lsh/tree-sitter-mojo) @ `33193a99afe6` — MIT, ABI 15. Helix tracks `lsh/tree-sitter-mojo` as its Mojo grammar source, but the Helix-pinned commit (`3d7c53b8038f`) no longer resolves in the upstream repository after a force-push, so this vendor uses current upstream `main` rather than the stale registry SHA. Security review covered only the vendored C surface (`parser.c`, `scanner.c`, `tree_sitter/*.h`) plus upstream license/provenance metadata; no package manager hooks, workflow files, prompt/agent instruction files, or generated lockfiles were vendored.
|
||||
- **arkts** (added 2026-08-26): **first-party derivative** — a fork of [tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)'s `typescript` dialect pinned @ `75b3874edb2d` (v0.23.2, the same commit our vendored typescript/tsx come from), on the tree-sitter-javascript base @ `3a837b6f3658` (v0.23.1, the version upstream's own package-lock pins), extended with ArkTS/ArkUI syntax (`@Component struct` declarations, UI-DSL trailing-closure calls with post-block attribute chains, decorated function declarations, `import lazy`, `@Extend`/`@Styles` leading-dot attribute chains, anonymous `stateStyles` style blocks). Grammar source + corpus tests live in `tools/tree-sitter-arkts/`; regenerate with `npx tree-sitter-cli@0.25.10 generate` (ABI 15). **External scanner:** `scanner.c` is a symbol-rename trampoline; `_common_scanner.h` is byte-identical (same SHA-256) to the reviewed `typescript/_common_scanner.h` already shipped. **LICENSE:** tree-sitter-typescript's MIT text **verbatim and byte-identical** (© 2017 Max Brunsfeld) — which is what MIT requires of a derivative work, and what lets the provenance audit byte-verify it against upstream rather than take a note on trust. The fork is registered in the audit's `FORKS` map. Our own copyright for the ArkTS additions, and the tree-sitter-javascript attribution (© 2014 Max Brunsfeld), live with the SOURCE in `tools/tree-sitter-arkts/grammar.js` and in `THIRD_PARTY.md`, which is what ships in the release archives.
|
||||
- **javascript + tsx** (forked 2026-09-25, #1736): **self-maintained forks** of the pins we already vendored — [tree-sitter/tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript) @ `58404d8cf191` and [tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)'s `tsx` dialect @ `75b3874edb2d` (javascript base @ `3a837b6f3658`, the version upstream's package-lock pins, as for arkts). **Why:** upstream accepts a `&` inside a JSX string only before a space/digit or as a complete character reference, and never inside JSX text, so a plain URL query (`href="…?a=1&b=2"`, Google Fonts `&display=swap`) or `<p>Tom & Jerry</p>` produced an ERROR node — a `parse_partial` flag, plus false USAGE edges from identifiers the error recovery pulled out of the URL (on vercel/next.js `examples/`: 45 of 92 flagged files, 115 false cross-example USAGE edges). **The change** is one patch, `tools/tree-sitter-javascript/patches/jsx-lone-ampersand.patch`, applied to both javascript bases: a lone `&` that does not begin a complete `html_character_reference` is a one-character token (lexical precedence -1, so `&`/`&` still lex as references) aliased to the EXISTING `string_fragment` / `jsx_text` nodes, and the string-fragment regexes stop before a `&` that directly precedes the closing quote. Node types are unchanged (same type/named set; `node-types.json` only gains an empty `fields` map on those two entries). Without the patch both directories regenerate upstream exactly (javascript: byte-identical `parser.c` apart from the generator-version comment; tsx: identical state/symbol counts, ABI 14 → 15 from the newer CLI). **External scanners** are unchanged: `javascript/scanner.c` and `tsx/scanner.c` + `_common_scanner.h` stay the reviewed upstream bytes. Regenerate with `npx tree-sitter-cli@0.25.10 generate` in `tools/tree-sitter-{javascript,tsx}/` (ABI 15) and copy `src/parser.c` (tsx: also `src/tree_sitter/*.h`) here. **On an upstream bump:** re-fetch the new pins, re-apply the patch, regenerate, re-run `test/corpus/jsx_ampersand.txt` — and drop the fork if upstream fixes it. **LICENSE:** upstream's MIT text byte-identical (registered in the audit's `FORKS` map); our copyright for the patch lives in the fork `grammar.js` headers and `THIRD_PARTY.md`.
|
||||
- **plsql** (added 2026-08-27): vendored from [AndreasMaierDe/tree-sitter-plsql](https://github.com/AndreasMaierDe/tree-sitter-plsql) @ `28aebef209be` (full: `28aebef209be57169600e1aa41ca1431cc6c916f`, upstream tip; repo dormant since 2023-02) — MIT, ABI 14, **no external scanner** (`EXTERNAL_TOKEN_COUNT 0`). Not listed in nvim-treesitter/Helix (`community-niche`, an individual-maintained grammar); provenance verified directly against upstream (pin = `git ls-remote` HEAD; vendored `parser.c` byte-identical to the pinned clone apart from the include-quote local patch below; 0 non-ASCII bytes; 0 dangerous calls). Security review covered only the vendored C surface (`parser.c`, `tree_sitter/parser.h`) plus upstream license/provenance metadata; no package manager hooks, workflow files, prompt/agent instruction files, or generated lockfiles were vendored. Known upstream limitation: `CREATE TYPE ... AS OBJECT` currently yields ERROR nodes (pinned by `plsql_create_type_as_object_limitation` in `tests/test_extraction.c` + `tests/fixtures/plsql/create_type_as_object_limitation.tps`). Originally contributed as PR #1033 by Oğuz (@ouzsrcm); re-vendored from upstream per vendoring policy with the PR's language wiring distilled on top.
|
||||
|
||||
- **chialisp** (added 2026-08-28): **first-party** — authored in this repository, not vendored from anywhere. Grammar source + corpus tests live in `tools/tree-sitter-chialisp/`; regenerate with `npx tree-sitter-cli@0.25.10 generate --abi 14` and copy `src/parser.c` + `src/tree_sitter/*.h` here. ABI 14, **no external scanner** (`EXTERNAL_TOKEN_COUNT 0`), 0 non-ASCII bytes. It is a deliberately GENERIC s-expression grammar (`source_file`/`list`/`symbol`/`string`/`number`/`hex`/`dot`/`comment`) modelling the clvm_tools reader rather than the Chialisp form vocabulary: `mod`/`defun`/`defconstant`/`include` are ordinary head symbols, and which lists are definitions is decided in `internal/cbm/extract_defs.c`, so a dialect that adds a form does not need a regenerated parser. Written because the only public grammar (`Quexington/tree-sitter-chialisp`) cannot parse the language: it required CRLF to terminate a comment (`/;.*\r\n/`) while real files are LF, rejected the `.` in `(include foo.clib)`, and accepted only a primitive after `(defconstant NAME …)` — each of which desynchronised the rest of the file. Acceptance gate: all five `chia-blockchain@main` reference files parse with **zero ERROR and zero MISSING nodes**. **LICENSE:** the project's own LICENSE, byte-identical to the repository root — no third-party copyright is carried, because there is no third party.
|
||||
@@ -152,7 +154,6 @@ row instead.
|
||||
| ini | 15 | justinmk/tree-sitter-ini | `e4018b517613` | VERIFIED-BOTH | ✅ |
|
||||
| ispc | 14 | tree-sitter-grammars/tree-sitter-ispc | `9b2f9aec2106` | VERIFIED-NVIM | ✅ |
|
||||
| java | 14 | tree-sitter/tree-sitter-java | `e10607b45ff7` | VERIFIED-BOTH | ✅ |
|
||||
| javascript | 15 | tree-sitter/tree-sitter-javascript | `58404d8cf191` | VERIFIED-BOTH | ✅ |
|
||||
| jsdoc | 15 | tree-sitter/tree-sitter-jsdoc | `658d18dcdddb` | VERIFIED-BOTH | ✅ |
|
||||
| json | 14 | tree-sitter/tree-sitter-json | `001c28d7a298` | VERIFIED-BOTH | ✅ |
|
||||
| json5 | 15 | Joakker/tree-sitter-json5 | `aa630ef48903` | VERIFIED-BOTH | ✅ |
|
||||
@@ -226,7 +227,6 @@ row instead.
|
||||
| thrift | 14 | tree-sitter-grammars/tree-sitter-thrift | `68fd0d80943a` | VERIFIED-BOTH | ✅ |
|
||||
| tlaplus | 14 | tlaplus-community/tree-sitter-tlaplus | `add40814fda3` | VERIFIED-BOTH | ✅ |
|
||||
| toml | 14 | tree-sitter-grammars/tree-sitter-toml | `64b56832c2cf` | MISMATCH | ✅ |
|
||||
| tsx | 14 | tree-sitter/tree-sitter-typescript | `75b3874edb2d` | VERIFIED-BOTH | ✅ |
|
||||
| typescript | 14 | tree-sitter/tree-sitter-typescript | `75b3874edb2d` | VERIFIED-BOTH | ✅ |
|
||||
| typst | 14 | uben0/tree-sitter-typst | `46cf4ded12ee` | VERIFIED-BOTH | ✅ |
|
||||
| verilog | 14 | tree-sitter/tree-sitter-verilog | `4457145e795b` | VERIFIED-HELIX | ✅ |
|
||||
@@ -265,6 +265,8 @@ upstream author (correctly retained). The table now records the true origin.
|
||||
| grammar | cur ABI | original upstream | license |
|
||||
|---|:---:|---|---|
|
||||
| arkts | 15 | **self-maintained fork** of tree-sitter/tree-sitter-typescript @ `75b3874edb2d` (v0.23.2; javascript base @ `3a837b6f3658` v0.23.1); grammar source in `tools/tree-sitter-arkts/` | MIT, (c) 2017 Max Brunsfeld — byte-identical to upstream; ArkTS additions (c) 2026 DeusData, see grammar.js + THIRD_PARTY.md |
|
||||
| javascript | 15 | **self-maintained fork** of tree-sitter/tree-sitter-javascript @ `58404d8cf191` (the previously vendored pin, VERIFIED-BOTH) + the JSX lone-ampersand patch (#1736); grammar source in `tools/tree-sitter-javascript/` | MIT, (c) 2014 Max Brunsfeld — byte-identical to upstream; patch (c) 2026 DeusData, see grammar.js + THIRD_PARTY.md |
|
||||
| tsx | 15 | **self-maintained fork** of tree-sitter/tree-sitter-typescript's `tsx` dialect @ `75b3874edb2d` (v0.23.2, the previously vendored pin, VERIFIED-BOTH; javascript base @ `3a837b6f3658` v0.23.1) + the same JSX lone-ampersand patch (#1736); grammar source in `tools/tree-sitter-tsx/` | MIT, (c) 2017 Max Brunsfeld — byte-identical to upstream; patch (c) 2026 DeusData, see grammar.js + THIRD_PARTY.md |
|
||||
| assembly | 14 | RubixDev/tree-sitter-assembly (**repo deleted from GitHub** — our retained MIT copy, (c) 2023 RubixDev, is the surviving grant) | MIT |
|
||||
| cfml | 15 | cfmleditor/tree-sitter-cfml | MIT, (c) 2014 Gareth Edwards & Gavin Baumanis — byte-identical |
|
||||
| cfscript | 15 | cfmleditor/tree-sitter-cfml | MIT, same — byte-identical |
|
||||
|
||||
+21319
-21147
File diff suppressed because it is too large
Load Diff
+229219
-228882
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ extern "C" {
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4101)
|
||||
#elif defined(__GNUC__) || defined(__clang__)
|
||||
#pragma GCC diagnostic push
|
||||
@@ -278,7 +279,7 @@ static inline void _array__splice(Array *self, size_t element_size,
|
||||
#define _compare_int(a, b) ((int)*(a) - (int)(b))
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(default : 4101)
|
||||
#pragma warning(pop)
|
||||
#elif defined(__GNUC__) || defined(__clang__)
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
@@ -18,6 +18,11 @@ typedef uint16_t TSStateId;
|
||||
typedef uint16_t TSSymbol;
|
||||
typedef uint16_t TSFieldId;
|
||||
typedef struct TSLanguage TSLanguage;
|
||||
typedef struct TSLanguageMetadata {
|
||||
uint8_t major_version;
|
||||
uint8_t minor_version;
|
||||
uint8_t patch_version;
|
||||
} TSLanguageMetadata;
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
@@ -26,10 +31,11 @@ typedef struct {
|
||||
bool inherited;
|
||||
} TSFieldMapEntry;
|
||||
|
||||
// Used to index the field and supertype maps.
|
||||
typedef struct {
|
||||
uint16_t index;
|
||||
uint16_t length;
|
||||
} TSFieldMapSlice;
|
||||
} TSMapSlice;
|
||||
|
||||
typedef struct {
|
||||
bool visible;
|
||||
@@ -79,6 +85,12 @@ typedef struct {
|
||||
uint16_t external_lex_state;
|
||||
} TSLexMode;
|
||||
|
||||
typedef struct {
|
||||
uint16_t lex_state;
|
||||
uint16_t external_lex_state;
|
||||
uint16_t reserved_word_set_id;
|
||||
} TSLexerMode;
|
||||
|
||||
typedef union {
|
||||
TSParseAction action;
|
||||
struct {
|
||||
@@ -93,7 +105,7 @@ typedef struct {
|
||||
} TSCharacterRange;
|
||||
|
||||
struct TSLanguage {
|
||||
uint32_t version;
|
||||
uint32_t abi_version;
|
||||
uint32_t symbol_count;
|
||||
uint32_t alias_count;
|
||||
uint32_t token_count;
|
||||
@@ -109,13 +121,13 @@ struct TSLanguage {
|
||||
const TSParseActionEntry *parse_actions;
|
||||
const char * const *symbol_names;
|
||||
const char * const *field_names;
|
||||
const TSFieldMapSlice *field_map_slices;
|
||||
const TSMapSlice *field_map_slices;
|
||||
const TSFieldMapEntry *field_map_entries;
|
||||
const TSSymbolMetadata *symbol_metadata;
|
||||
const TSSymbol *public_symbol_map;
|
||||
const uint16_t *alias_map;
|
||||
const TSSymbol *alias_sequences;
|
||||
const TSLexMode *lex_modes;
|
||||
const TSLexerMode *lex_modes;
|
||||
bool (*lex_fn)(TSLexer *, TSStateId);
|
||||
bool (*keyword_lex_fn)(TSLexer *, TSStateId);
|
||||
TSSymbol keyword_capture_token;
|
||||
@@ -129,15 +141,23 @@ struct TSLanguage {
|
||||
void (*deserialize)(void *, const char *, unsigned);
|
||||
} external_scanner;
|
||||
const TSStateId *primary_state_ids;
|
||||
const char *name;
|
||||
const TSSymbol *reserved_words;
|
||||
uint16_t max_reserved_word_set_size;
|
||||
uint32_t supertype_count;
|
||||
const TSSymbol *supertype_symbols;
|
||||
const TSMapSlice *supertype_map_slices;
|
||||
const TSSymbol *supertype_map_entries;
|
||||
TSLanguageMetadata metadata;
|
||||
};
|
||||
|
||||
static inline bool set_contains(TSCharacterRange *ranges, uint32_t len, int32_t lookahead) {
|
||||
static inline bool set_contains(const TSCharacterRange *ranges, uint32_t len, int32_t lookahead) {
|
||||
uint32_t index = 0;
|
||||
uint32_t size = len - index;
|
||||
while (size > 1) {
|
||||
uint32_t half_size = size / 2;
|
||||
uint32_t mid_index = index + half_size;
|
||||
TSCharacterRange *range = &ranges[mid_index];
|
||||
const TSCharacterRange *range = &ranges[mid_index];
|
||||
if (lookahead >= range->start && lookahead <= range->end) {
|
||||
return true;
|
||||
} else if (lookahead > range->end) {
|
||||
@@ -145,7 +165,7 @@ static inline bool set_contains(TSCharacterRange *ranges, uint32_t len, int32_t
|
||||
}
|
||||
size -= half_size;
|
||||
}
|
||||
TSCharacterRange *range = &ranges[index];
|
||||
const TSCharacterRange *range = &ranges[index];
|
||||
return (lookahead >= range->start && lookahead <= range->end);
|
||||
}
|
||||
|
||||
|
||||
@@ -354,6 +354,6 @@ secretstorage==3.5.0 \
|
||||
twine==7.0.0 \
|
||||
--hash=sha256:85cdb29c518efef867360ae4acd4b0dfd61c8654a22fca08e6f8539f05022177 \
|
||||
--hash=sha256:b854164df26db268af05f49aa5c0344b10e27a494343ff05b1e0bad3b135f5a7
|
||||
urllib3==2.7.0 \
|
||||
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
|
||||
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
|
||||
urllib3==2.8.0 \
|
||||
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
|
||||
--hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
|
||||
|
||||
@@ -36,7 +36,11 @@ FORKS = { # self-maintained forks: vendored LICENSE must match the original ups
|
||||
"cfml": "cfmleditor/tree-sitter-cfml",
|
||||
"cfscript": "cfmleditor/tree-sitter-cfml",
|
||||
"dotenv": "pnx/tree-sitter-dotenv",
|
||||
# javascript / tsx: our JSX lone-ampersand forks (#1736) of the pins we vendored
|
||||
# before; same routing rule as arkts -- upstream's MIT verbatim, byte-verified.
|
||||
"javascript": "tree-sitter/tree-sitter-javascript",
|
||||
"qml": "yuja/tree-sitter-qmljs",
|
||||
"tsx": "tree-sitter/tree-sitter-typescript",
|
||||
}
|
||||
SPECIAL_NOTICE = {
|
||||
"assembly": "RETAINED-MIT (upstream RubixDev/tree-sitter-assembly deleted from GitHub)",
|
||||
|
||||
@@ -57,7 +57,7 @@ src/pipeline/artifact.c 38
|
||||
src/pipeline/fqn.c 23
|
||||
src/pipeline/lsp_resolve.h 4
|
||||
src/pipeline/lsp_surface.c 5
|
||||
src/pipeline/pass_calls.c 23
|
||||
src/pipeline/pass_calls.c 22
|
||||
src/pipeline/pass_compile_commands.c 17
|
||||
src/pipeline/pass_complexity.c 15
|
||||
src/pipeline/pass_configlink.c 3
|
||||
|
||||
+32
-18
@@ -55,6 +55,16 @@ POLL_SECONDS = 0.05
|
||||
WINDOWS_DESCENDANT_PROBE_SECONDS = 15
|
||||
WINDOWS_DESCENDANT_PROBE_ATTEMPTS = 2
|
||||
|
||||
# WHY: the same defect as the probe above, one call earlier. `taskkill /F`
|
||||
# cannot be resisted -- a live tree is terminated as soon as the tool runs --
|
||||
# so what bounding it measures is taskkill.exe's own cold start on the runner,
|
||||
# not the tree. Timed with --kill-grace (1s in the harness contract), a slow
|
||||
# start was reported as "taskkill could not prove process-tree cleanup" for an
|
||||
# ordinary hung suite (#2345). The tree does not change while the tool starts,
|
||||
# so this is a stable-state budget; --kill-grace keeps bounding what it names:
|
||||
# how long the leader may take to be reaped once taskkill has succeeded.
|
||||
WINDOWS_TASKKILL_SECONDS = 15
|
||||
|
||||
|
||||
@dataclass
|
||||
class ActiveSuite:
|
||||
@@ -225,6 +235,27 @@ def windows_tree_cleanup_blocker(pid: int) -> str | None:
|
||||
return unproven
|
||||
|
||||
|
||||
def windows_taskkill_tree(pid: int) -> bool:
|
||||
"""Force-terminate `pid` and its whole tree; True only on proven success.
|
||||
|
||||
A tool that cannot start, cannot finish within its own budget, or reports
|
||||
failure is never read as success -- the caller refuses to call the tree
|
||||
clean.
|
||||
"""
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["taskkill.exe", "/PID", str(pid), "/T", "/F"],
|
||||
check=False,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=WINDOWS_TASKKILL_SECONDS,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return completed.returncode == 0
|
||||
|
||||
|
||||
def terminate_process_tree(active: ActiveSuite, kill_grace: int) -> None:
|
||||
process = active.process
|
||||
leader_exited = process.poll() is not None
|
||||
@@ -243,24 +274,7 @@ def terminate_process_tree(active: ActiveSuite, kill_grace: int) -> None:
|
||||
f"could not be proven: {blocker}"
|
||||
)
|
||||
return
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[
|
||||
"taskkill.exe",
|
||||
"/PID",
|
||||
str(process.pid),
|
||||
"/T",
|
||||
"/F",
|
||||
],
|
||||
check=False,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=kill_grace,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
completed = None
|
||||
if completed is None or completed.returncode != 0:
|
||||
if not windows_taskkill_tree(process.pid):
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
try:
|
||||
|
||||
@@ -5,7 +5,7 @@ c5cfb43042b6b72045f4ba997834d0a7786d2793d91680868b5815b39f14fc78 internal/cbm/v
|
||||
b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/common/tree_sitter/alloc.h
|
||||
31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/common/tree_sitter/array.h
|
||||
180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/common/tree_sitter/parser.h
|
||||
9fe439eff24b2a474618f2cb75cbeb06074840f0396fbeb1d2503e668a5d056a internal/cbm/vendored/grammars/MANIFEST.md
|
||||
6cb436878b820c14e97c7ea80fbf8c91f037c140c3bce283c6eedd724dbebd99 internal/cbm/vendored/grammars/MANIFEST.md
|
||||
ad8425038de519f8c4e3e9339feebf99dfad8a6002dcf79227d91402780a32cc internal/cbm/vendored/grammars/ada/LICENSE
|
||||
02805ec13939b749c891567be36bf024b09034e04c80683a1ae667272458d549 internal/cbm/vendored/grammars/ada/parser.c
|
||||
115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/ada/tree_sitter/alloc.h
|
||||
@@ -371,7 +371,7 @@ b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/v
|
||||
02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/java/tree_sitter/array.h
|
||||
2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/java/tree_sitter/parser.h
|
||||
2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/javascript/LICENSE
|
||||
5bfb18365de4d5ff04a3a0d2ff8e5379d1a5c2a94f3b7b4622eea6886975215a internal/cbm/vendored/grammars/javascript/parser.c
|
||||
c61b6b3d52ce1d13f5ab3f8b35c61bffa447b96a35e91885e2228d5be28f2f69 internal/cbm/vendored/grammars/javascript/parser.c
|
||||
1a5ab5c7a9a75d78d1bd36856e01efb186b2f4f6a261947bbb733aa4878b09b2 internal/cbm/vendored/grammars/javascript/scanner.c
|
||||
115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/javascript/tree_sitter/alloc.h
|
||||
02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/javascript/tree_sitter/array.h
|
||||
@@ -843,11 +843,11 @@ b727eee929bee836e8102cecf749a795b199f291b58c885bcd81cae727ac5a46 internal/cbm/v
|
||||
2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/toml/tree_sitter/parser.h
|
||||
49bf33cf78ef5897e4e161ce1517df7de1ae5042a65b6bcfd44401e0fc606559 internal/cbm/vendored/grammars/tsx/LICENSE
|
||||
da66ef2bd14a3f7ea743e25ba068c6c9aae2c3509db200ff80c4a0e6116e564c internal/cbm/vendored/grammars/tsx/_common_scanner.h
|
||||
1902cb53fa7ff5179df89b2eea863165e84c8cc866226419dc26921d8c055885 internal/cbm/vendored/grammars/tsx/parser.c
|
||||
d7d95b604965a6ad5cf10eb2c852a5dc7273f9d04dd7db14541c2593ab3691c0 internal/cbm/vendored/grammars/tsx/parser.c
|
||||
7a2fe1ae9928ef0ac74dae3a9d02c85b6be31f08d65f0e9697d215b62c991ec2 internal/cbm/vendored/grammars/tsx/scanner.c
|
||||
b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/tsx/tree_sitter/alloc.h
|
||||
4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/tsx/tree_sitter/array.h
|
||||
a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/tsx/tree_sitter/parser.h
|
||||
5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/tsx/tree_sitter/array.h
|
||||
180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/tsx/tree_sitter/parser.h
|
||||
49bf33cf78ef5897e4e161ce1517df7de1ae5042a65b6bcfd44401e0fc606559 internal/cbm/vendored/grammars/typescript/LICENSE
|
||||
da66ef2bd14a3f7ea743e25ba068c6c9aae2c3509db200ff80c4a0e6116e564c internal/cbm/vendored/grammars/typescript/_common_scanner.h
|
||||
74fe453edd70f4eae9af0a1050cbd7943d8971d59165b6aaebbaa0a0b716d1aa internal/cbm/vendored/grammars/typescript/parser.c
|
||||
|
||||
+66
-21
@@ -23,6 +23,7 @@
|
||||
#include "foundation/constants.h"
|
||||
#include "foundation/log.h"
|
||||
#include "foundation/sha256.h"
|
||||
#include "foundation/str_util.h"
|
||||
#include "cli/client_adapter.h"
|
||||
#include "mcp/mcp.h" // cbm_mcp_tool_input_schema — CLI flag parser + per-tool --help
|
||||
#include "mcp/index_supervisor.h"
|
||||
@@ -62,7 +63,6 @@ enum {
|
||||
SQL_PARAM_1 = 1, /* sqlite3_bind parameter index 1 */
|
||||
SQL_PARAM_2 = 2,
|
||||
SEMVER_PARTS = 3, /* major.minor.patch */
|
||||
DB_EXT_LEN = 3, /* strlen(".db") */
|
||||
MIN_ARGC_CMD = 3,
|
||||
/* minimum argc for subcommand with arg */ /* sqlite3_bind parameter index 2 */ /* 10 MB cap
|
||||
factor */
|
||||
@@ -226,6 +226,7 @@ typedef struct {
|
||||
static cbm_cli_activation_ops_t g_cli_activation_test_ops;
|
||||
static bool g_cli_activation_test_ops_set = false;
|
||||
static const char *g_cli_activation_runtime_parent_for_test = NULL;
|
||||
static bool g_cli_activation_scope_cache_unreadable_for_test = false;
|
||||
|
||||
static void cli_activation_diagnostic(const cbm_cli_activation_ops_t *ops, const char *message) {
|
||||
const char *diagnostic = message ? message : CLI_ACTIVATION_REFUSED_MESSAGE;
|
||||
@@ -335,6 +336,10 @@ const char *cbm_cli_activation_runtime_parent_for_test(void) {
|
||||
return g_cli_activation_runtime_parent_for_test;
|
||||
}
|
||||
|
||||
void cbm_cli_set_activation_scope_cache_unreadable_for_test(bool unreadable) {
|
||||
g_cli_activation_scope_cache_unreadable_for_test = unreadable;
|
||||
}
|
||||
|
||||
static const char *cli_activation_action_text(cbm_daemon_runtime_activation_action_t action) {
|
||||
switch (action) {
|
||||
case CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL:
|
||||
@@ -541,6 +546,7 @@ typedef enum {
|
||||
CLI_ACTIVATION_SCOPE_ACTIVE = 0,
|
||||
CLI_ACTIVATION_SCOPE_NOTHING_TO_REPLACE,
|
||||
CLI_ACTIVATION_SCOPE_FOREIGN_COHORT,
|
||||
CLI_ACTIVATION_SCOPE_UNCONFIRMED,
|
||||
CLI_ACTIVATION_SCOPE_ERROR,
|
||||
} cli_activation_scope_t;
|
||||
|
||||
@@ -566,9 +572,43 @@ static void cli_activation_log_guard_decision(const cli_activation_production_co
|
||||
* anything at all (a --skip-binary install without an index reset publishes
|
||||
* nothing), and whose cohort is active. Admission with an immediate deadline
|
||||
* is the cheapest authoritative read of the active lifetime record: OK means
|
||||
* the cohort is ours or empty, CONFLICT names the active identity (its cache
|
||||
* fingerprint is filled for every conflict kind), BUSY means another
|
||||
* activation holds maintenance and the barrier waits for it as before. */
|
||||
* the cohort shares this exact identity (cache included) or is empty,
|
||||
* CONFLICT names the active identity (its cache fingerprint is filled for
|
||||
* every conflict kind), BUSY means another activation or a session start held
|
||||
* the group, so the active identity was never read.
|
||||
*
|
||||
* Only a POSITIVE match may drain (user decision 2026-09-28, "unknown =
|
||||
* foreign, keep it"): the daemon's activation-shutdown handler verifies the
|
||||
* requester's build, never its cache, so this decision is the only thing
|
||||
* that keeps another HOME's install/update from stopping the account's live
|
||||
* daemon. A busy group or an unreadable active cache used to fall through to
|
||||
* "ours" and stop every session behind that daemon. */
|
||||
static cli_activation_scope_t cli_activation_scope_unconfirmed(
|
||||
cli_activation_production_context_t *context, const char *scope, const char *reason) {
|
||||
const char *action = cli_activation_action_text(context->action);
|
||||
(void)snprintf(context->scope_detail, sizeof(context->scope_detail),
|
||||
"active cohort ownership unconfirmed (%s); scope=%s; nothing stopped", reason,
|
||||
scope);
|
||||
cli_activation_log_guard_decision(context, "unconfirmed_cohort", NULL);
|
||||
/* Name the daemon being left: a read-only status probe (no cohort, no
|
||||
* HELLO, no admission) that works across build skew. */
|
||||
cbm_daemon_runtime_status_t daemon;
|
||||
if (cbm_daemon_runtime_request_status(context->endpoint, &context->identity,
|
||||
CLI_ACTIVATION_CONTROL_TIMEOUT_MS, &daemon)) {
|
||||
printf("Leaving the running CBM daemon untouched (pid %lu, version %s): this %s could "
|
||||
"not confirm that it serves the cache this %s targets (%s).\n",
|
||||
(unsigned long)daemon.daemon_pid, daemon.semantic_version, action, action, reason);
|
||||
} else {
|
||||
printf("Leaving active CBM sessions untouched: this %s could not confirm that they "
|
||||
"serve the cache it targets (%s).\n",
|
||||
action, reason);
|
||||
}
|
||||
printf("If it is yours, close its CBM sessions and run `codebase-memory-mcp daemon stop` "
|
||||
"to stop it yourself.\n");
|
||||
(void)fflush(stdout);
|
||||
return CLI_ACTIVATION_SCOPE_UNCONFIRMED;
|
||||
}
|
||||
|
||||
static cli_activation_scope_t cli_activation_resolve_scope(
|
||||
cli_activation_production_context_t *context) {
|
||||
const char *runtime_dir = cbm_daemon_ipc_endpoint_runtime_dir(context->endpoint);
|
||||
@@ -594,20 +634,27 @@ static cli_activation_scope_t cli_activation_resolve_scope(
|
||||
if (lease) {
|
||||
return CLI_ACTIVATION_SCOPE_ERROR;
|
||||
}
|
||||
if (g_cli_activation_scope_cache_unreadable_for_test) {
|
||||
conflict.active_cache_fingerprint[0] = '\0';
|
||||
}
|
||||
switch (status) {
|
||||
case CBM_VERSION_COHORT_OK:
|
||||
case CBM_VERSION_COHORT_BUSY:
|
||||
return CLI_ACTIVATION_SCOPE_ACTIVE;
|
||||
case CBM_VERSION_COHORT_BUSY:
|
||||
return cli_activation_scope_unconfirmed(
|
||||
context, scope, "the session group was busy, so its cache identity could not be read");
|
||||
case CBM_VERSION_COHORT_CONFLICT:
|
||||
break;
|
||||
default:
|
||||
return CLI_ACTIVATION_SCOPE_ERROR;
|
||||
}
|
||||
if (!conflict.active_cache_fingerprint[0] ||
|
||||
strcmp(conflict.active_cache_fingerprint, context->cache_fingerprint) == 0) {
|
||||
/* Same cache namespace, another build or version: that IS the daemon
|
||||
* this activation replaces. An unreadable active cache stays in scope
|
||||
* rather than silently exempting a same-namespace daemon. */
|
||||
if (!conflict.active_cache_fingerprint[0]) {
|
||||
return cli_activation_scope_unconfirmed(context, scope,
|
||||
"its cache identity could not be read");
|
||||
}
|
||||
if (strcmp(conflict.active_cache_fingerprint, context->cache_fingerprint) == 0) {
|
||||
/* Positively confirmed: same cache namespace, another build or
|
||||
* version. That IS the daemon this activation replaces. */
|
||||
return CLI_ACTIVATION_SCOPE_ACTIVE;
|
||||
}
|
||||
(void)snprintf(context->scope_detail, sizeof(context->scope_detail),
|
||||
@@ -636,9 +683,10 @@ static int cli_activation_production_reserve(void *opaque, cbm_cli_activation_lo
|
||||
}
|
||||
if (scope != CLI_ACTIVATION_SCOPE_ACTIVE) {
|
||||
/* Nothing in the target namespace is being replaced, or the only
|
||||
* active cohort serves another namespace: hold no maintenance,
|
||||
* admission, lifetime or startup lock (each wakes or blocks the other
|
||||
* namespace's sessions) and send no drain request. */
|
||||
* active cohort serves another namespace, or its ownership could not
|
||||
* be confirmed: hold no maintenance, admission, lifetime or startup
|
||||
* lock (each wakes or blocks the other namespace's sessions) and
|
||||
* send no drain request. */
|
||||
if (!cli_activation_log_event(context, "quiesce_skipped", context->scope_detail)) {
|
||||
return CLI_ERR;
|
||||
}
|
||||
@@ -7207,8 +7255,7 @@ int cbm_list_indexes(const char *home_dir) {
|
||||
int count = 0;
|
||||
cbm_dirent_t *ent;
|
||||
while ((ent = cbm_readdir(d)) != NULL) {
|
||||
size_t len = strlen(ent->name);
|
||||
if (len > DB_EXT_LEN && strcmp(ent->name + len - DB_EXT_LEN, ".db") == 0) {
|
||||
if (cbm_is_project_index_db(ent->name)) {
|
||||
printf(" %s/%s\n", cache_dir, ent->name);
|
||||
count++;
|
||||
}
|
||||
@@ -7231,8 +7278,7 @@ int cbm_remove_indexes(const char *home_dir) {
|
||||
int count = 0;
|
||||
cbm_dirent_t *ent;
|
||||
while ((ent = cbm_readdir(d)) != NULL) {
|
||||
size_t len = strlen(ent->name);
|
||||
if (len > DB_EXT_LEN && strcmp(ent->name + len - DB_EXT_LEN, ".db") == 0) {
|
||||
if (cbm_is_project_index_db(ent->name)) {
|
||||
char path[CLI_BUF_1K];
|
||||
snprintf(path, sizeof(path), "%s/%s", cache_dir, ent->name);
|
||||
/* Also remove .db.tmp if present */
|
||||
@@ -7268,7 +7314,7 @@ cbm_config_t *cbm_config_open(const char *cache_dir) {
|
||||
}
|
||||
|
||||
char dbpath[CLI_BUF_1K];
|
||||
snprintf(dbpath, sizeof(dbpath), "%s/_config.db", cache_dir);
|
||||
snprintf(dbpath, sizeof(dbpath), "%s/" CBM_CONFIG_DB_FILENAME, cache_dir);
|
||||
|
||||
/* Ensure directory exists */
|
||||
mkdirp(cache_dir, DIR_PERMS);
|
||||
@@ -10437,7 +10483,7 @@ static int cbm_install_agent_configs_with_previous(const char *home, const char
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Count .db files in the cache directory. */
|
||||
/* Count project index .db files in the cache directory (internal stores excluded). */
|
||||
static int count_db_indexes(const char *home) {
|
||||
const char *cache_dir = get_cache_dir(home);
|
||||
if (!cache_dir) {
|
||||
@@ -10450,8 +10496,7 @@ static int count_db_indexes(const char *home) {
|
||||
int count = 0;
|
||||
cbm_dirent_t *ent;
|
||||
while ((ent = cbm_readdir(d)) != NULL) {
|
||||
size_t len = strlen(ent->name);
|
||||
if (len > DB_EXT_LEN && strcmp(ent->name + len - DB_EXT_LEN, ".db") == 0) {
|
||||
if (cbm_is_project_index_db(ent->name)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
+8
-1
@@ -404,7 +404,8 @@ unsigned char *cbm_extract_binary_from_zip(const unsigned char *data, int data_l
|
||||
* Prints each file path to stdout. Returns count of .db files found. */
|
||||
int cbm_list_indexes(const char *home_dir);
|
||||
|
||||
/* Remove all .db files in the cache directory. Returns count removed. */
|
||||
/* Remove every project index .db (and its sidecars) in the cache directory.
|
||||
* Internal stores (_config.db, _cross_repo.db) are kept. Returns count removed. */
|
||||
int cbm_remove_indexes(const char *home_dir);
|
||||
|
||||
/* ── Config store (persistent key-value, backed by _config.db) ── */
|
||||
@@ -504,6 +505,12 @@ void cbm_cli_set_activation_ops_for_test(const cbm_cli_activation_ops_t *ops);
|
||||
void cbm_cli_set_activation_runtime_parent_for_test(const char *runtime_parent);
|
||||
const char *cbm_cli_activation_runtime_parent_for_test(void);
|
||||
|
||||
/* Internal integration-test seam: the activation scope read reports the active
|
||||
* cohort's cache fingerprint as unreadable (blank), exactly what the scope
|
||||
* decision sees when that field cannot be recovered. false restores the real
|
||||
* read. Not a command-line or environment override. */
|
||||
void cbm_cli_set_activation_scope_cache_unreadable_for_test(bool unreadable);
|
||||
|
||||
/* ── Subcommands (wired from main.c) ─────────────────────────── */
|
||||
|
||||
/* install: copy binary, install skills, install editor MCP configs, ensure PATH.
|
||||
|
||||
+237
-150
@@ -2516,10 +2516,205 @@ static int toml_legacy_args_are_empty(const char *data, const toml_assignment_t
|
||||
return pos == end;
|
||||
}
|
||||
|
||||
static int toml_legacy_schema_is_owned(int command_count, int command_owned, int args_count,
|
||||
int args_empty) {
|
||||
return command_count == 1 && command_owned && args_count <= 1 &&
|
||||
(args_count == 0 || args_empty);
|
||||
/* #1720: the only names cbm has ever listed in env_vars (#1562, #1664). */
|
||||
static int toml_legacy_env_name_is_owned(const toml_string_t *name) {
|
||||
static const char *const owned[] = {"CBM_CACHE_DIR", "CBM_RUNTIME_DIR"};
|
||||
for (size_t i = 0U; i < sizeof(owned) / sizeof(owned[0]); ++i) {
|
||||
size_t owned_len = strlen(owned[i]);
|
||||
if (name->len == owned_len && memcmp(name->data, owned[i], owned_len) == 0) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void toml_skip_blanks(const char *data, size_t end, size_t *pos) {
|
||||
while (*pos < end && (data[*pos] == ' ' || data[*pos] == '\t')) {
|
||||
++*pos;
|
||||
}
|
||||
}
|
||||
|
||||
/* A single-line array of strings naming only variables cbm forwards: the
|
||||
* value cbm writes, as Codex re-serializes it when it rewrites the table. */
|
||||
static int toml_legacy_env_vars_are_owned(const char *data, const toml_assignment_t *assignment) {
|
||||
if (!assignment->present || assignment->multiline_value) {
|
||||
return 0;
|
||||
}
|
||||
size_t pos = assignment->value_start;
|
||||
size_t end = assignment->value_end;
|
||||
if (pos >= end || data[pos++] != '[') {
|
||||
return 0;
|
||||
}
|
||||
for (;;) {
|
||||
toml_skip_blanks(data, end, &pos);
|
||||
if (pos < end && data[pos] == ']') {
|
||||
pos++;
|
||||
break;
|
||||
}
|
||||
toml_string_t name = {0};
|
||||
if (pos >= end || toml_parse_string(data + pos, end - pos, &name) != TOML_EDIT_OK) {
|
||||
return 0;
|
||||
}
|
||||
int owned = toml_legacy_env_name_is_owned(&name);
|
||||
pos += name.consumed;
|
||||
toml_string_dispose(&name);
|
||||
toml_skip_blanks(data, end, &pos);
|
||||
if (!owned || pos >= end || (data[pos] != ',' && data[pos] != ']')) {
|
||||
return 0;
|
||||
}
|
||||
if (data[pos] == ',') {
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
toml_skip_blanks(data, end, &pos);
|
||||
return pos == end;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
int command_count;
|
||||
int command_owned;
|
||||
int args_count;
|
||||
int args_empty;
|
||||
int env_vars_count;
|
||||
int env_vars_owned;
|
||||
} toml_legacy_shape_t;
|
||||
|
||||
static int toml_legacy_schema_is_owned(const toml_legacy_shape_t *shape) {
|
||||
return shape->command_count == 1 && shape->command_owned && shape->args_count <= 1 &&
|
||||
(shape->args_count == 0 || shape->args_empty) && shape->env_vars_count <= 1 &&
|
||||
(shape->env_vars_count == 0 || shape->env_vars_owned);
|
||||
}
|
||||
|
||||
/* Classify one assignment inside the target table. Returns TOML_EDIT_ERR for
|
||||
* a duplicated key or an unparsable command, otherwise TOML_EDIT_OK with
|
||||
* *foreign set when the assignment is not part of the owned schema. */
|
||||
static int toml_legacy_classify_assignment(const char *data, const toml_assignment_t *assignment,
|
||||
toml_legacy_shape_t *shape, int *foreign) {
|
||||
if (assignment->key.count != 1U) {
|
||||
*foreign = 1;
|
||||
} else if (toml_key_path_is_single(&assignment->key, "command")) {
|
||||
if (++shape->command_count > 1 ||
|
||||
toml_legacy_command_is_owned(data, assignment, &shape->command_owned) != TOML_EDIT_OK) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (!shape->command_owned) {
|
||||
*foreign = 1;
|
||||
}
|
||||
} else if (toml_key_path_is_single(&assignment->key, "args")) {
|
||||
shape->args_empty = toml_legacy_args_are_empty(data, assignment);
|
||||
if (++shape->args_count > 1) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (!shape->args_empty) {
|
||||
*foreign = 1;
|
||||
}
|
||||
} else if (toml_key_path_is_single(&assignment->key, "env_vars")) {
|
||||
shape->env_vars_owned = toml_legacy_env_vars_are_owned(data, assignment);
|
||||
if (++shape->env_vars_count > 1) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (!shape->env_vars_owned) {
|
||||
*foreign = 1;
|
||||
}
|
||||
} else {
|
||||
*foreign = 1;
|
||||
}
|
||||
return TOML_EDIT_OK;
|
||||
}
|
||||
|
||||
/* Copy existing into output without the one owned legacy table. Returns
|
||||
* TOML_EDIT_OK (output holds the result, unchanged when the table is absent),
|
||||
* TOML_EDIT_FOREIGN for a same-name table that is not ours, or TOML_EDIT_ERR. */
|
||||
static int toml_strip_legacy_table(const char *existing, size_t existing_len,
|
||||
const toml_key_path_t *desired, toml_buffer_t *output) {
|
||||
size_t cursor = 0U;
|
||||
toml_line_t line;
|
||||
int multiline_state = TOML_STRING_NONE;
|
||||
int target_active = 0;
|
||||
int target_count = 0;
|
||||
int target_foreign = 0;
|
||||
int target_array_seen = 0;
|
||||
int target_regular_seen = 0;
|
||||
toml_legacy_shape_t shape = {0};
|
||||
size_t edit_start = SIZE_MAX;
|
||||
size_t edit_end = existing_len;
|
||||
while (toml_next_line(existing, existing_len, &cursor, &line)) {
|
||||
int line_in_multiline = multiline_state != TOML_STRING_NONE;
|
||||
int handled_header = 0;
|
||||
if (!line_in_multiline) {
|
||||
toml_header_t header;
|
||||
if (toml_parse_header(existing, &line, "", &header) != TOML_EDIT_OK) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (header.present) {
|
||||
handled_header = 1;
|
||||
int exact = toml_key_path_equal(&header.path, desired);
|
||||
int descendant = header.path.count > desired->count &&
|
||||
toml_key_path_has_prefix(&header.path, desired);
|
||||
if (exact) {
|
||||
if (header.array) {
|
||||
if (target_regular_seen) {
|
||||
toml_header_dispose(&header);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
target_array_seen = 1;
|
||||
target_foreign = 1;
|
||||
target_count++;
|
||||
} else if (target_array_seen || target_regular_seen) {
|
||||
toml_header_dispose(&header);
|
||||
return TOML_EDIT_ERR;
|
||||
} else {
|
||||
target_regular_seen = 1;
|
||||
target_count = 1;
|
||||
}
|
||||
target_active = 1;
|
||||
memset(&shape, 0, sizeof(shape));
|
||||
edit_start = header.edit_start;
|
||||
} else if (target_active) {
|
||||
if (descendant || !toml_legacy_schema_is_owned(&shape)) {
|
||||
target_foreign = 1;
|
||||
}
|
||||
edit_end = header.edit_start;
|
||||
target_active = 0;
|
||||
}
|
||||
}
|
||||
toml_header_dispose(&header);
|
||||
}
|
||||
if (target_active && !handled_header && !line_in_multiline &&
|
||||
!toml_line_is_blank_or_comment(existing, &line)) {
|
||||
toml_assignment_t assignment;
|
||||
int classified = TOML_EDIT_ERR;
|
||||
if (toml_parse_assignment(existing, &line, &assignment) == TOML_EDIT_OK &&
|
||||
assignment.present) {
|
||||
classified =
|
||||
toml_legacy_classify_assignment(existing, &assignment, &shape, &target_foreign);
|
||||
}
|
||||
toml_assignment_dispose(&assignment);
|
||||
if (classified != TOML_EDIT_OK) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
}
|
||||
if (toml_scan_line_strings(existing, &line, &multiline_state) != TOML_EDIT_OK) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
}
|
||||
if (multiline_state != TOML_STRING_NONE) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (target_active && !toml_legacy_schema_is_owned(&shape)) {
|
||||
target_foreign = 1;
|
||||
}
|
||||
if (target_foreign) {
|
||||
return TOML_EDIT_FOREIGN;
|
||||
}
|
||||
if (target_count == 0) {
|
||||
return toml_buffer_append(output, existing, existing_len);
|
||||
}
|
||||
if (toml_buffer_append(output, existing, edit_start) != TOML_EDIT_OK ||
|
||||
toml_buffer_append(output, existing + edit_end, existing_len - edit_end) != TOML_EDIT_OK) {
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
return TOML_EDIT_OK;
|
||||
}
|
||||
|
||||
int cbm_toml_remove_legacy_table(const char *file_path, const char *table_name,
|
||||
@@ -2546,159 +2741,46 @@ int cbm_toml_remove_legacy_table(const char *file_path, const char *table_name,
|
||||
toml_line_t begin_line = {0};
|
||||
toml_line_t end_line = {0};
|
||||
int has_managed_pair = 0;
|
||||
if (toml_find_markers(existing, existing_len, begin_marker, end_marker, &begin_line, &end_line,
|
||||
&has_managed_pair) != TOML_EDIT_OK) {
|
||||
int find_rc = toml_find_markers(existing, existing_len, begin_marker, end_marker, &begin_line,
|
||||
&end_line, &has_managed_pair);
|
||||
/* #1720: Codex rewrites the whole [mcp_servers] table when it edits MCP
|
||||
* servers itself and drops comment decor on the way, so our begin marker
|
||||
* vanishes while the end marker survives below whatever table follows.
|
||||
* The stray line is ours (#1558) and removing it guesses nothing; the
|
||||
* table it used to bracket is then judged by its shape like any other
|
||||
* unmarked table, so a foreign one still fails closed untouched. */
|
||||
toml_buffer_t healed = {0};
|
||||
const char *scan = existing;
|
||||
size_t scan_len = existing_len;
|
||||
int result = TOML_EDIT_OK;
|
||||
if (find_rc == TOML_EDIT_ORPHAN_MARKER) {
|
||||
const toml_line_t *stray = begin_line.full_end > 0U ? &begin_line : &end_line;
|
||||
if (toml_buffer_append(&healed, existing, stray->start) != TOML_EDIT_OK ||
|
||||
toml_buffer_append(&healed, existing + stray->full_end,
|
||||
existing_len - stray->full_end) != TOML_EDIT_OK) {
|
||||
result = TOML_EDIT_ERR;
|
||||
}
|
||||
scan = healed.data ? healed.data : "";
|
||||
scan_len = healed.len;
|
||||
} else if (find_rc != TOML_EDIT_OK) {
|
||||
result = TOML_EDIT_ERR;
|
||||
} else if (has_managed_pair) {
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (has_managed_pair) {
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_OK;
|
||||
}
|
||||
|
||||
size_t cursor = 0U;
|
||||
toml_line_t line;
|
||||
int multiline_state = TOML_STRING_NONE;
|
||||
int target_active = 0;
|
||||
int target_count = 0;
|
||||
int target_foreign = 0;
|
||||
int target_array_seen = 0;
|
||||
int target_regular_seen = 0;
|
||||
int command_count = 0;
|
||||
int command_owned = 0;
|
||||
int args_count = 0;
|
||||
int args_empty = 0;
|
||||
size_t edit_start = SIZE_MAX;
|
||||
size_t edit_end = existing_len;
|
||||
while (toml_next_line(existing, existing_len, &cursor, &line)) {
|
||||
int line_in_multiline = multiline_state != TOML_STRING_NONE;
|
||||
int handled_header = 0;
|
||||
if (!line_in_multiline) {
|
||||
toml_header_t header;
|
||||
if (toml_parse_header(existing, &line, "", &header) != TOML_EDIT_OK) {
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (header.present) {
|
||||
handled_header = 1;
|
||||
int exact = toml_key_path_equal(&header.path, &desired);
|
||||
int descendant = header.path.count > desired.count &&
|
||||
toml_key_path_has_prefix(&header.path, &desired);
|
||||
if (exact) {
|
||||
if (header.array) {
|
||||
if (target_regular_seen) {
|
||||
toml_header_dispose(&header);
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
target_array_seen = 1;
|
||||
target_foreign = 1;
|
||||
target_count++;
|
||||
} else if (target_array_seen || target_regular_seen) {
|
||||
toml_header_dispose(&header);
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
} else {
|
||||
target_regular_seen = 1;
|
||||
target_count = 1;
|
||||
}
|
||||
target_active = 1;
|
||||
command_count = 0;
|
||||
command_owned = 0;
|
||||
args_count = 0;
|
||||
args_empty = 0;
|
||||
edit_start = header.edit_start;
|
||||
} else if (target_active) {
|
||||
if (descendant || !toml_legacy_schema_is_owned(command_count, command_owned,
|
||||
args_count, args_empty)) {
|
||||
target_foreign = 1;
|
||||
}
|
||||
edit_end = header.edit_start;
|
||||
target_active = 0;
|
||||
}
|
||||
}
|
||||
toml_header_dispose(&header);
|
||||
}
|
||||
if (target_active && !handled_header && !line_in_multiline &&
|
||||
!toml_line_is_blank_or_comment(existing, &line)) {
|
||||
toml_assignment_t assignment;
|
||||
if (toml_parse_assignment(existing, &line, &assignment) != TOML_EDIT_OK ||
|
||||
!assignment.present) {
|
||||
toml_assignment_dispose(&assignment);
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (assignment.key.count != 1U) {
|
||||
target_foreign = 1;
|
||||
} else if (toml_key_path_is_single(&assignment.key, "command")) {
|
||||
if (++command_count > 1 ||
|
||||
toml_legacy_command_is_owned(existing, &assignment, &command_owned) !=
|
||||
TOML_EDIT_OK) {
|
||||
toml_assignment_dispose(&assignment);
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (!command_owned) {
|
||||
target_foreign = 1;
|
||||
}
|
||||
} else if (toml_key_path_is_single(&assignment.key, "args")) {
|
||||
args_count++;
|
||||
args_empty = toml_legacy_args_are_empty(existing, &assignment);
|
||||
if (args_count > 1) {
|
||||
toml_assignment_dispose(&assignment);
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (!args_empty) {
|
||||
target_foreign = 1;
|
||||
}
|
||||
} else {
|
||||
target_foreign = 1;
|
||||
}
|
||||
toml_assignment_dispose(&assignment);
|
||||
}
|
||||
if (toml_scan_line_strings(existing, &line, &multiline_state) != TOML_EDIT_OK) {
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
}
|
||||
toml_key_path_dispose(&desired);
|
||||
if (multiline_state != TOML_STRING_NONE) {
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
}
|
||||
if (target_active &&
|
||||
!toml_legacy_schema_is_owned(command_count, command_owned, args_count, args_empty)) {
|
||||
target_foreign = 1;
|
||||
}
|
||||
if (target_foreign) {
|
||||
free(existing);
|
||||
return TOML_EDIT_FOREIGN;
|
||||
}
|
||||
if (target_count == 0) {
|
||||
free(existing);
|
||||
return TOML_EDIT_OK;
|
||||
}
|
||||
|
||||
toml_buffer_t output = {0};
|
||||
if (toml_buffer_append(&output, existing, edit_start) != TOML_EDIT_OK ||
|
||||
toml_buffer_append(&output, existing + edit_end, existing_len - edit_end) != TOML_EDIT_OK) {
|
||||
toml_buffer_dispose(&output);
|
||||
free(existing);
|
||||
return TOML_EDIT_ERR;
|
||||
if (result == TOML_EDIT_OK) {
|
||||
result = toml_strip_legacy_table(scan, scan_len, &desired, &output);
|
||||
}
|
||||
if (result == TOML_EDIT_OK) {
|
||||
result = toml_write_atomic(file_path, existing, existing_len,
|
||||
output.data ? output.data : "", output.len, &snapshot);
|
||||
}
|
||||
int result =
|
||||
toml_write_atomic(file_path, existing, existing_len, output.data, output.len, &snapshot);
|
||||
toml_buffer_dispose(&output);
|
||||
toml_buffer_dispose(&healed);
|
||||
toml_key_path_dispose(&desired);
|
||||
free(existing);
|
||||
return result;
|
||||
}
|
||||
@@ -2774,9 +2856,14 @@ static int toml_codex_executable_is_safe(const char *encoded, size_t len, size_t
|
||||
*end = *start && len >= 2U && encoded[len - 1U] == '\'' ? len - 1U : len;
|
||||
if (*start && *end == len)
|
||||
return 0;
|
||||
/* #2044: inside the single-quoted form a space is literal in sh and
|
||||
* PowerShell alike, and cbm_shell_quote_word/cbm_powershell_quote_word
|
||||
* emit it for a profile such as C:\Users\First Last. Only an unquoted
|
||||
* word must be free of spaces, since the shell would split it. */
|
||||
unsigned char lowest = *start ? 0x20U : 0x21U;
|
||||
for (size_t pos = *start; pos < *end;) {
|
||||
unsigned char ch = (unsigned char)encoded[pos++];
|
||||
if (ch < 0x21U || ch == 0x7fU || (!*start && strchr("\"'`$;&|<>(){}[]*?!", ch))) {
|
||||
if (ch < lowest || ch == 0x7fU || (!*start && strchr("\"'`$;&|<>(){}[]*?!", ch))) {
|
||||
return 0;
|
||||
}
|
||||
if (*start && ch == '\'') {
|
||||
|
||||
@@ -31,11 +31,14 @@ int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marke
|
||||
const char *end_marker);
|
||||
|
||||
/* Remove one pre-marker codebase-memory-mcp table only when it has the known
|
||||
* historical schema: one owned command basename, optional empty args, and no
|
||||
* unknown assignments or descendant tables. Returns 1 for a syntactically
|
||||
* valid same-name foreign table and leaves it byte-identical, 0 for removed or
|
||||
* absent owned state, and -1 for malformed input or I/O failure. A supplied
|
||||
* managed-marker pair makes this a successful no-op. */
|
||||
* historical schema: one owned command basename, optional empty args, optional
|
||||
* env_vars naming only CBM_CACHE_DIR/CBM_RUNTIME_DIR, and no unknown
|
||||
* assignments or descendant tables. A lone orphaned managed marker (left when
|
||||
* a client rewrote the table and dropped its comments, #1720) is dropped in
|
||||
* the same write. Returns 1 for a syntactically valid same-name foreign table
|
||||
* and leaves the file byte-identical, 0 for removed or absent owned state, and
|
||||
* -1 for malformed input or I/O failure. A supplied managed-marker pair makes
|
||||
* this a successful no-op. */
|
||||
int cbm_toml_remove_legacy_table(const char *file_path, const char *table_name,
|
||||
const char *begin_marker, const char *end_marker);
|
||||
|
||||
|
||||
@@ -2698,8 +2698,28 @@ static int yaml_sequence_line_has_unsupported(const yaml_doc_t *doc, const yaml_
|
||||
return quote != '\0' ? YAML_MATCH : 0;
|
||||
}
|
||||
|
||||
static int yaml_sequence_validate_document(const yaml_doc_t *doc) {
|
||||
for (size_t i = 0U; i < doc->line_count; i++) {
|
||||
/* Validates only the top-level section the edit descends into. The root
|
||||
* mapping itself was already validated when the document was parsed, so the
|
||||
* section boundaries are sound; every OTHER top-level section is opaque user
|
||||
* content, the same contract the mapping-entry editor applies. Validating the
|
||||
* whole document refused the stock Hermes config for flow sequences such as
|
||||
* `cli: [hermes-cli]` under `platform_toolsets:`, which the hook edit never
|
||||
* reads or rewrites (#2209). An absent root key means the sequence is appended
|
||||
* as a new top-level section, which touches no existing line. */
|
||||
static int yaml_sequence_validate_document(const yaml_doc_t *doc, const char *root_key,
|
||||
size_t root_key_len) {
|
||||
bool found = false;
|
||||
size_t section_line = 0U;
|
||||
size_t section_colon = 0U;
|
||||
if (yaml_find_unique_key(doc, 0U, root_key, root_key_len, &found, §ion_line,
|
||||
§ion_colon) != 0) {
|
||||
return YAML_ERROR;
|
||||
}
|
||||
if (!found) {
|
||||
return 0;
|
||||
}
|
||||
size_t section_end = yaml_top_level_section_end(doc, section_line);
|
||||
for (size_t i = section_line; i < section_end; i++) {
|
||||
const yaml_line_t *line = &doc->lines[i];
|
||||
if (line->blank || line->comment || line->dquote_cont) {
|
||||
continue;
|
||||
@@ -2947,7 +2967,7 @@ static int yaml_sequence_analyze(const yaml_doc_t *doc, const char *const *seque
|
||||
const char *identity_key, const char *identity_value,
|
||||
yaml_mapping_sequence_target_t *target) {
|
||||
memset(target, 0, sizeof(*target));
|
||||
if (yaml_sequence_validate_document(doc) != 0) {
|
||||
if (yaml_sequence_validate_document(doc, sequence_path[0], path_lengths[0]) != 0) {
|
||||
return YAML_ERROR;
|
||||
}
|
||||
size_t parent_begin = 0U;
|
||||
|
||||
+79
-65
@@ -2300,7 +2300,6 @@ static const char *node_string_field(const cbm_node_t *n, const char *prop) {
|
||||
/* Get node property by name.
|
||||
* store may be NULL; only needed for virtual degree properties. */
|
||||
static const char *json_extract_prop(const char *json, const char *key, char *buf, size_t buf_sz);
|
||||
static void node_fields_free(cbm_node_t *n); /* defined below; used by the stub re-fetch */
|
||||
|
||||
static const char *node_prop(const cbm_node_t *n, const char *prop, cbm_store_t *store) {
|
||||
if (!n || !prop) {
|
||||
@@ -2310,8 +2309,6 @@ static const char *node_prop(const cbm_node_t *n, const char *prop, cbm_store_t
|
||||
if (str && str[0]) {
|
||||
return str;
|
||||
}
|
||||
/* Note: a string field that exists but is empty ("") falls through here so a
|
||||
* WITH-aggregation node stub (below) can re-fetch it. */
|
||||
/* Computed and JSON-derived values live in rotating thread-local buffers:
|
||||
* a single row (or an ORDER-BY comparison) reads several of these before any
|
||||
* of them is copied out, so returning one shared static buffer would alias
|
||||
@@ -2349,40 +2346,6 @@ static const char *node_prop(const cbm_node_t *n, const char *prop, cbm_store_t
|
||||
return v;
|
||||
}
|
||||
}
|
||||
/* WITH aggregation carries a node group var by id + name only (the group key
|
||||
* is the node name), so every other property is absent on the stub. Detect
|
||||
* the stub (id set, but the full string fields were never populated) and
|
||||
* re-fetch the node so RETURN g.file_path / g.label / g.<metric> project
|
||||
* correctly instead of returning blank. The gate is heuristic, not an exact
|
||||
* stub discriminator: a real bound node with NULL label AND file_path would
|
||||
* also match, but in that case the worst case is one redundant indexed fetch
|
||||
* that returns the same value — never a wrong result. */
|
||||
if (store && n->id > 0 && !n->file_path && !n->label) {
|
||||
cbm_node_t full = {0};
|
||||
if (cbm_store_find_node_by_id(store, n->id, &full) == CBM_STORE_OK) {
|
||||
const char *res = NULL;
|
||||
const char *rv = node_string_field(&full, prop);
|
||||
if (rv && rv[0]) {
|
||||
snprintf(out, CBM_SZ_512, "%s", rv);
|
||||
res = out;
|
||||
} else if (strcmp(prop, "start_line") == 0) {
|
||||
snprintf(out, CBM_SZ_512, "%d", full.start_line);
|
||||
res = out;
|
||||
} else if (strcmp(prop, "end_line") == 0) {
|
||||
snprintf(out, CBM_SZ_512, "%d", full.end_line);
|
||||
res = out;
|
||||
} else if (full.properties_json && full.properties_json[0] == '{') {
|
||||
const char *jv = json_extract_prop(full.properties_json, prop, out, CBM_SZ_512);
|
||||
if (jv && jv[0]) {
|
||||
res = out;
|
||||
}
|
||||
}
|
||||
node_fields_free(&full);
|
||||
if (res) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -3842,6 +3805,30 @@ static void distinct_list_add(char ***list, int *count, const char *val) {
|
||||
(*list)[idx] = heap_strdup(val);
|
||||
}
|
||||
|
||||
/* Resolve one WITH ORDER BY key on a projected binding. The key is either a
|
||||
* projected name (`c`, or an unaliased `f.name`) or a property of a carried
|
||||
* node (`g.start_line` after `WITH f AS g`, #2208): an exact projected name
|
||||
* wins, otherwise `var.prop` is split and resolved on the carried node. */
|
||||
static const char *order_key_value(binding_t *b, const char *key) {
|
||||
const char *dot = strchr(key, '.');
|
||||
if (!dot) {
|
||||
return binding_get_virtual(b, key, NULL);
|
||||
}
|
||||
for (int i = 0; i < b->var_count; i++) {
|
||||
if (strcmp(b->var_names[i], key) == 0) {
|
||||
return binding_get_virtual(b, key, NULL);
|
||||
}
|
||||
}
|
||||
char var[CBM_SZ_256];
|
||||
size_t vlen = (size_t)(dot - key);
|
||||
if (vlen >= sizeof(var)) {
|
||||
return "";
|
||||
}
|
||||
memcpy(var, key, vlen);
|
||||
var[vlen] = '\0';
|
||||
return binding_get_virtual(b, var, dot + SKIP_ONE);
|
||||
}
|
||||
|
||||
/* Sort bindings by the ORDER BY key list (virtual variables) using bubble
|
||||
* sort; later keys break ties, direction is per key (#1334). */
|
||||
static void sort_bindings(binding_t *vbindings, int count, const cbm_return_clause_t *wc) {
|
||||
@@ -3849,9 +3836,8 @@ static void sort_bindings(binding_t *vbindings, int count, const cbm_return_clau
|
||||
for (int j = 0; j < count - i - SKIP_ONE; j++) {
|
||||
int cmp = 0;
|
||||
for (int k = 0; k < wc->order_key_count && cmp == 0; k++) {
|
||||
const char *va = binding_get_virtual(&vbindings[j], wc->order_keys[k], NULL);
|
||||
const char *vb2 =
|
||||
binding_get_virtual(&vbindings[j + SKIP_ONE], wc->order_keys[k], NULL);
|
||||
const char *va = order_key_value(&vbindings[j], wc->order_keys[k]);
|
||||
const char *vb2 = order_key_value(&vbindings[j + SKIP_ONE], wc->order_keys[k]);
|
||||
char *ea = NULL;
|
||||
char *eb = NULL;
|
||||
double da = strtod(va, &ea);
|
||||
@@ -3925,9 +3911,28 @@ typedef struct {
|
||||
double *mins, *maxs;
|
||||
char ***distinct_lists; /* per-item set of seen values for COUNT(DISTINCT) */
|
||||
int *distinct_n; /* per-item distinct count (#239) */
|
||||
int64_t *group_node_ids; /* per-item node id when the group var is a node (0 = not) */
|
||||
cbm_node_t *group_nodes; /* per-item carried node (deep copy; id 0 = not a node) */
|
||||
} with_agg_t;
|
||||
|
||||
/* A WITH item that is a bare, bound node variable (`WITH f`, `WITH f AS g`)
|
||||
* carries the node itself, not a scalar: return that node, else NULL. Property
|
||||
* items, functions (labels/id/keys/...) and unbound OPTIONAL vars (id 0) stay
|
||||
* scalar. The carried node keeps every field, so a later g.<prop> resolves
|
||||
* exactly as it would without the WITH (#2208). */
|
||||
static const cbm_node_t *with_item_carried_node(const cbm_return_item_t *item, binding_t *b) {
|
||||
if (item->func || item->property || !item->variable) {
|
||||
return NULL;
|
||||
}
|
||||
const cbm_node_t *n = binding_get(b, item->variable);
|
||||
return (n && n->id > 0) ? n : NULL;
|
||||
}
|
||||
|
||||
/* Name a carried node is bound under: the AST-owned alias or variable, which
|
||||
* outlives every binding of the query (binding_set does not copy the name). */
|
||||
static const char *with_item_node_alias(const cbm_return_item_t *item) {
|
||||
return item->alias ? item->alias : item->variable;
|
||||
}
|
||||
|
||||
/* Build a group key from non-aggregate WITH items */
|
||||
static int with_agg_build_key(cbm_return_clause_t *wc, binding_t *b, char *key, size_t key_sz) {
|
||||
int kl = 0;
|
||||
@@ -3936,7 +3941,12 @@ static int with_agg_build_key(cbm_return_clause_t *wc, binding_t *b, char *key,
|
||||
continue;
|
||||
}
|
||||
char vbuf[CBM_SZ_512];
|
||||
const char *v = project_item(b, &wc->items[ci], vbuf, sizeof(vbuf));
|
||||
const cbm_node_t *gn = with_item_carried_node(&wc->items[ci], b);
|
||||
if (gn) {
|
||||
/* Group a node by identity, never by its (non-unique) name. */
|
||||
snprintf(vbuf, sizeof(vbuf), "#%lld", (long long)gn->id);
|
||||
}
|
||||
const char *v = gn ? vbuf : project_item(b, &wc->items[ci], vbuf, sizeof(vbuf));
|
||||
kl += snprintf(key + kl, key_sz - (size_t)kl, "%s|", v);
|
||||
if (kl >= (int)key_sz) {
|
||||
kl = (int)key_sz - SKIP_ONE;
|
||||
@@ -3966,7 +3976,7 @@ static int with_agg_find_or_create(with_agg_t **aggs, int *agg_cnt, int *agg_cap
|
||||
(*aggs)[found].maxs = calloc(wc->count, sizeof(double));
|
||||
(*aggs)[found].distinct_lists = calloc(wc->count, sizeof(char **));
|
||||
(*aggs)[found].distinct_n = calloc(wc->count, sizeof(int));
|
||||
(*aggs)[found].group_node_ids = calloc(wc->count, sizeof(int64_t));
|
||||
(*aggs)[found].group_nodes = calloc(wc->count, sizeof(cbm_node_t));
|
||||
for (int ci = 0; ci < wc->count; ci++) {
|
||||
(*aggs)[found].mins[ci] = CYP_DBL_MAX;
|
||||
(*aggs)[found].maxs[ci] = -CYP_DBL_MAX;
|
||||
@@ -3979,18 +3989,9 @@ static int with_agg_find_or_create(with_agg_t **aggs, int *agg_cnt, int *agg_cap
|
||||
char vbuf[CBM_SZ_512];
|
||||
const char *v = project_item(b, &wc->items[ci], vbuf, sizeof(vbuf));
|
||||
(*aggs)[found].group_vals[ci] = heap_strdup(v);
|
||||
/* If this group item is a bare node variable, remember its id so the
|
||||
* carried virtual var can re-fetch any property (group_vals holds only
|
||||
* the name). Excludes entity-introspection funcs (labels/id/keys/
|
||||
* properties): those project a scalar off the node (via project_item
|
||||
* above), not the node itself, so the carried id must not be set or a
|
||||
* later alias.property re-fetches the source node's real properties
|
||||
* instead of returning empty for the non-node alias. */
|
||||
if (!wc->items[ci].func && !wc->items[ci].property && wc->items[ci].variable) {
|
||||
cbm_node_t *gn = binding_get(b, wc->items[ci].variable);
|
||||
if (gn) {
|
||||
(*aggs)[found].group_node_ids[ci] = gn->id;
|
||||
}
|
||||
const cbm_node_t *gn = with_item_carried_node(&wc->items[ci], b);
|
||||
if (gn) {
|
||||
node_deep_copy(&(*aggs)[found].group_nodes[ci], gn);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
@@ -4033,11 +4034,14 @@ static void with_agg_format(const char *func, with_agg_t *agg, int ci, char *buf
|
||||
}
|
||||
}
|
||||
|
||||
/* Add a virtual variable binding for one WITH item */
|
||||
/* Add a scalar virtual variable binding for one WITH item. The value lives in
|
||||
* .name; the owned alias string (var_names points at it) lives in .project,
|
||||
* which no property accessor exposes. It used to live in .qualified_name, so
|
||||
* alias.qualified_name / keys(alias) returned the variable name as data (#2208). */
|
||||
static void with_add_vbinding_var(binding_t *vb, const char *alias, const char *val) {
|
||||
cbm_node_t vn = {.name = heap_strdup(val), .qualified_name = heap_strdup(alias)};
|
||||
cbm_node_t vn = {.name = heap_strdup(val), .project = heap_strdup(alias)};
|
||||
if (vb->var_count < CYP_BUF_16) {
|
||||
vb->var_names[vb->var_count] = vn.qualified_name;
|
||||
vb->var_names[vb->var_count] = vn.project;
|
||||
vb->var_nodes[vb->var_count] = vn;
|
||||
vb->var_count++;
|
||||
}
|
||||
@@ -4062,7 +4066,12 @@ static void with_agg_free(with_agg_t *aggs, int agg_cnt, int item_count) {
|
||||
free(aggs[a].maxs);
|
||||
free(aggs[a].distinct_lists);
|
||||
free(aggs[a].distinct_n);
|
||||
free(aggs[a].group_node_ids);
|
||||
if (aggs[a].group_nodes) {
|
||||
for (int ci = 0; ci < item_count; ci++) {
|
||||
node_fields_free(&aggs[a].group_nodes[ci]);
|
||||
}
|
||||
}
|
||||
free(aggs[a].group_nodes);
|
||||
}
|
||||
free(aggs);
|
||||
}
|
||||
@@ -4102,13 +4111,10 @@ static void execute_with_aggregate(cbm_return_clause_t *wc, binding_t *bindings,
|
||||
with_agg_format(wc->items[ci].func, &aggs[a], ci, vbuf, sizeof(vbuf));
|
||||
}
|
||||
with_add_vbinding_var(&vb, alias, vbuf);
|
||||
} else if (aggs[a].group_nodes[ci].id > 0) {
|
||||
binding_set(&vb, with_item_node_alias(&wc->items[ci]), &aggs[a].group_nodes[ci]);
|
||||
} else {
|
||||
with_add_vbinding_var(&vb, alias, aggs[a].group_vals[ci]);
|
||||
/* Tag the carried virtual var with the node id (when the group
|
||||
* var is a node) so node_prop can re-fetch its full properties. */
|
||||
if (aggs[a].group_node_ids[ci] > 0 && vb.var_count > 0) {
|
||||
vb.var_nodes[vb.var_count - 1].id = aggs[a].group_node_ids[ci];
|
||||
}
|
||||
}
|
||||
}
|
||||
(*vbindings)[(*vcount)++] = vb;
|
||||
@@ -4125,6 +4131,11 @@ static void execute_with_simple(cbm_return_clause_t *wc, binding_t *bindings, in
|
||||
for (int ci = 0; ci < wc->count; ci++) {
|
||||
char name_buf[CBM_SZ_256];
|
||||
const char *alias = resolve_item_alias(&wc->items[ci], name_buf, sizeof(name_buf));
|
||||
const cbm_node_t *carried = with_item_carried_node(&wc->items[ci], &bindings[bi]);
|
||||
if (carried) {
|
||||
binding_set(&vb, with_item_node_alias(&wc->items[ci]), carried);
|
||||
continue;
|
||||
}
|
||||
char func_buf[CBM_SZ_512];
|
||||
const char *val =
|
||||
project_item(&bindings[bi], &wc->items[ci], func_buf, sizeof(func_buf));
|
||||
@@ -4811,9 +4822,12 @@ static void cross_join_with_rels(cbm_store_t *store, cbm_pattern_t *patn, bindin
|
||||
free(tmp);
|
||||
}
|
||||
if (opt && extra_count == 0) {
|
||||
/* OPTIONAL with no start node: keep the row, pattern vars unbound.
|
||||
* The buffer was sized for a single row when extra_count == 0, so
|
||||
* this write must grow it like every other writer here. */
|
||||
binding_t nb = {0};
|
||||
binding_copy(&nb, &(*bindings)[bi]);
|
||||
new_bindings[new_count++] = nb;
|
||||
(void)binding_out_append(&new_bindings, &new_count, &new_cap, &nb);
|
||||
}
|
||||
}
|
||||
for (int bi = 0; bi < *bind_count; bi++) {
|
||||
|
||||
+429
-16
@@ -10,6 +10,7 @@
|
||||
#include "foundation/compat_thread.h"
|
||||
#include "foundation/log.h"
|
||||
#include "foundation/mem.h"
|
||||
#include "foundation/mem_core.h"
|
||||
#include "foundation/platform.h"
|
||||
#include "foundation/secure_random.h"
|
||||
#include "foundation/sha256.h"
|
||||
@@ -32,6 +33,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
@@ -127,6 +129,9 @@ struct cbm_daemon_application_session {
|
||||
bool update_notice_delivered;
|
||||
bool pending_background_initialize;
|
||||
bool pending_update_notice;
|
||||
/* #2144: the current request arrived on the one-shot tool channel (the
|
||||
* `cli` command path), whose client closes right after the reply. */
|
||||
bool one_shot_request;
|
||||
cbm_daemon_application_session_t *next;
|
||||
};
|
||||
|
||||
@@ -147,9 +152,32 @@ struct cbm_daemon_application_job {
|
||||
bool cancelled;
|
||||
bool cancel_requested;
|
||||
bool supervision_failed;
|
||||
/* #2144: an async index_repository holds one subscriber reference on
|
||||
* the application's behalf, released only at terminal publish, so the
|
||||
* job outlives the request and session that started it. */
|
||||
bool async_owned;
|
||||
bool worker_started;
|
||||
cbm_daemon_application_job_t *next;
|
||||
};
|
||||
|
||||
/* #2144: the last known index outcome per project, kept after the terminal
|
||||
* job itself is reaped so index_repository(status: true) can answer after
|
||||
* completion. sync_cut_short records that a synchronous caller gave up (client
|
||||
* cancel, deadline, disconnect) before its index finished; the next
|
||||
* index_repository or status call for that project carries the async advice.
|
||||
* This is job bookkeeping, not graph freshness (index_status owns that). */
|
||||
typedef struct cbm_daemon_application_index_record cbm_daemon_application_index_record_t;
|
||||
struct cbm_daemon_application_index_record {
|
||||
char *project_key;
|
||||
const char *state; /* static string: queued/succeeded/failed/cancelled */
|
||||
bool async;
|
||||
bool sync_cut_short;
|
||||
char started_at[32];
|
||||
char finished_at[32];
|
||||
char *error;
|
||||
cbm_daemon_application_index_record_t *next;
|
||||
};
|
||||
|
||||
/* A watcher-triggered physical job is owned by the exact live sessions that
|
||||
* currently subscribe to its project/root watch. The callback waiting for the
|
||||
* job is only a storage waiter; it is deliberately not an ownership
|
||||
@@ -177,6 +205,7 @@ struct cbm_daemon_application {
|
||||
cbm_daemon_application_job_t *jobs;
|
||||
cbm_daemon_application_watch_job_subscription_t *watch_job_subscriptions;
|
||||
cbm_daemon_application_mutation_t *mutations;
|
||||
cbm_daemon_application_index_record_t *index_records;
|
||||
cbm_daemon_application_worker_ops_t worker_ops;
|
||||
cbm_daemon_application_update_ops_t update_ops;
|
||||
cbm_project_lock_manager_t *project_locks;
|
||||
@@ -556,6 +585,131 @@ static void application_job_free(cbm_daemon_application_job_t *job) {
|
||||
free(job);
|
||||
}
|
||||
|
||||
enum { APPLICATION_RECORD_ERROR_CAP = 512 };
|
||||
|
||||
static void application_utc_now(char out[32]) {
|
||||
time_t now = time(NULL);
|
||||
struct tm parts;
|
||||
out[0] = '\0';
|
||||
if (cbm_gmtime_r(&now, &parts)) {
|
||||
(void)strftime(out, 32, "%Y-%m-%dT%H:%M:%SZ", &parts);
|
||||
}
|
||||
}
|
||||
|
||||
static cbm_daemon_application_index_record_t *application_index_record_find_locked(
|
||||
cbm_daemon_application_t *application, const char *project_key) {
|
||||
for (cbm_daemon_application_index_record_t *record = application->index_records; record;
|
||||
record = record->next) {
|
||||
if (strcmp(record->project_key, project_key) == 0) {
|
||||
return record;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Find or create; NULL only on allocation failure (bookkeeping is then
|
||||
* skipped, never the index itself). */
|
||||
static cbm_daemon_application_index_record_t *application_index_record_get_locked(
|
||||
cbm_daemon_application_t *application, const char *project_key) {
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_find_locked(application, project_key);
|
||||
if (record) {
|
||||
return record;
|
||||
}
|
||||
record = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*record));
|
||||
if (!record || !(record->project_key = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, project_key))) {
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, record);
|
||||
return NULL;
|
||||
}
|
||||
record->state = "queued";
|
||||
record->next = application->index_records;
|
||||
application->index_records = record;
|
||||
return record;
|
||||
}
|
||||
|
||||
static void application_index_records_free(cbm_daemon_application_index_record_t *record) {
|
||||
while (record) {
|
||||
cbm_daemon_application_index_record_t *next = record->next;
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, record->project_key);
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, record->error);
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, record);
|
||||
record = next;
|
||||
}
|
||||
}
|
||||
|
||||
/* A new physical job for the project begins a fresh attempt record. The
|
||||
* cut-short marker deliberately survives: it describes the caller, and the
|
||||
* advice stays pending until a later call has carried it. */
|
||||
static void application_index_record_begin_locked(cbm_daemon_application_job_t *job) {
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_get_locked(job->application, job->project_key);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
record->state = "queued";
|
||||
record->async = false;
|
||||
application_utc_now(record->started_at);
|
||||
record->finished_at[0] = '\0';
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, record->error);
|
||||
record->error = NULL;
|
||||
}
|
||||
|
||||
/* The first content text of a tool result, bounded for a status summary. */
|
||||
static char *application_tool_result_summary(const char *response) {
|
||||
yyjson_doc *doc = response ? yyjson_read(response, strlen(response), 0) : NULL;
|
||||
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
|
||||
yyjson_val *content = root && yyjson_is_obj(root) ? yyjson_obj_get(root, "content") : NULL;
|
||||
yyjson_val *first = content && yyjson_is_arr(content) ? yyjson_arr_get_first(content) : NULL;
|
||||
yyjson_val *text = first && yyjson_is_obj(first) ? yyjson_obj_get(first, "text") : NULL;
|
||||
char *summary = NULL;
|
||||
if (text && yyjson_is_str(text)) {
|
||||
const char *value = yyjson_get_str(text);
|
||||
size_t length = strlen(value);
|
||||
if (length >= APPLICATION_RECORD_ERROR_CAP) {
|
||||
length = APPLICATION_RECORD_ERROR_CAP - 1U;
|
||||
/* Never split a UTF-8 sequence. */
|
||||
while (length > 0 && ((unsigned char)value[length] & 0xC0U) == 0x80U) {
|
||||
length--;
|
||||
}
|
||||
}
|
||||
summary = cbm_alloc(CBM_MEM_CLASS_OTHER, length + 1U);
|
||||
if (summary) {
|
||||
memcpy(summary, value, length);
|
||||
summary[length] = '\0';
|
||||
}
|
||||
}
|
||||
yyjson_doc_free(doc);
|
||||
return summary;
|
||||
}
|
||||
|
||||
static void application_index_record_finish_locked(cbm_daemon_application_job_t *job) {
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_get_locked(job->application, job->project_key);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
record->state = job->successful ? "succeeded" : job->cancelled ? "cancelled" : "failed";
|
||||
application_utc_now(record->finished_at);
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, record->error);
|
||||
record->error = job->successful ? NULL : application_tool_result_summary(job->response);
|
||||
}
|
||||
|
||||
/* A synchronous caller stopped waiting before its index finished. */
|
||||
static void application_index_record_mark_cut_short_locked(cbm_daemon_application_t *application,
|
||||
const char *project_key) {
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_get_locked(application, project_key);
|
||||
if (record) {
|
||||
record->sync_cut_short = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void application_index_record_cut_short_locked(cbm_daemon_application_job_t *job) {
|
||||
if (job && !job->terminal) {
|
||||
application_index_record_mark_cut_short_locked(job->application, job->project_key);
|
||||
}
|
||||
}
|
||||
|
||||
/* Reap completed job threads only after every logical demand subscription and
|
||||
* watcher callback storage waiter has released the job. Exactly one caller
|
||||
* removes a job under the mutex. */
|
||||
@@ -1127,6 +1281,7 @@ static application_attempt_status_t application_job_run_attempt(cbm_daemon_appli
|
||||
|
||||
cbm_mutex_lock(&application->mutex);
|
||||
job->worker = worker;
|
||||
job->worker_started = true;
|
||||
bool cancel_now = job->cancel_requested || application->stopping;
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
if (cancel_now) {
|
||||
@@ -1187,7 +1342,9 @@ static char *application_job_failure_response(const cbm_index_worker_result_t *r
|
||||
char message[1024];
|
||||
if (result && result->cancellation_requested) {
|
||||
(void)snprintf(message, sizeof(message),
|
||||
"index operation cancelled after its final owning session disconnected");
|
||||
"index operation cancelled before completion (its last waiting "
|
||||
"client disconnected or the daemon stopped). %s",
|
||||
CBM_MCP_INDEX_ASYNC_HINT);
|
||||
} else if (result && (result->supervision_failed || !result->tree_quiesced)) {
|
||||
(void)snprintf(message, sizeof(message),
|
||||
"index worker containment failed (%s); inspect log: %s",
|
||||
@@ -1495,6 +1652,12 @@ static void application_job_publish(cbm_daemon_application_job_t *job,
|
||||
!execution->last_result.cancellation_requested);
|
||||
job->terminal = true;
|
||||
job->thread_done = true;
|
||||
application_index_record_finish_locked(job);
|
||||
if (job->async_owned) {
|
||||
/* The async reference ends with the job; terminal, so no cancel. */
|
||||
job->async_owned = false;
|
||||
application_job_unsubscribe_locked(job);
|
||||
}
|
||||
for (cbm_daemon_application_session_t *session = application->sessions; session;
|
||||
session = session->next) {
|
||||
if (session->auto_index_job != job || !session->auto_index_subscribed) {
|
||||
@@ -1733,6 +1896,8 @@ static cbm_daemon_application_job_t *application_job_subscribe_locked(
|
||||
application->jobs = job;
|
||||
if (application_job_thread_create(&job->thread, job) == 0) {
|
||||
job->thread_started = true;
|
||||
/* Still under the mutex, so this precedes the thread's publish. */
|
||||
application_index_record_begin_locked(job);
|
||||
} else {
|
||||
/* The job was linked only so a concurrently started thread could
|
||||
* observe its reservation. No thread exists on this path, so roll the
|
||||
@@ -2286,7 +2451,8 @@ static char *application_job_wait_for_session(cbm_daemon_application_session_t *
|
||||
cbm_mutex_lock(&application->mutex);
|
||||
if (session->active_job != job || !session->active_job_subscribed) {
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
return cbm_mcp_text_result("index operation cancelled for this session", true);
|
||||
return cbm_mcp_text_result(
|
||||
"index operation cancelled for this session. " CBM_MCP_INDEX_ASYNC_HINT, true);
|
||||
}
|
||||
if (job->terminal) {
|
||||
char *response = job->response ? strdup(job->response) : NULL;
|
||||
@@ -2303,12 +2469,20 @@ static char *application_job_wait_for_session(cbm_daemon_application_session_t *
|
||||
}
|
||||
}
|
||||
|
||||
static char *application_index_execute(void *context, const char *root_path,
|
||||
const char *args_json) {
|
||||
cbm_daemon_application_session_t *session = context;
|
||||
if (!session || !root_path || !args_json) {
|
||||
return NULL;
|
||||
static const char *application_index_admission_error(application_job_subscribe_status_t status) {
|
||||
if (status == APPLICATION_JOB_SUBSCRIBE_OPTIONS_CONFLICT) {
|
||||
return "another index operation for this project is active with different options";
|
||||
}
|
||||
if (status == APPLICATION_JOB_SUBSCRIBE_ALLOCATION_FAILED) {
|
||||
return "daemon index coordinator could not allocate an index job";
|
||||
}
|
||||
return "daemon index coordinator is stopping or unavailable";
|
||||
}
|
||||
|
||||
/* The synchronous contract: wait for the whole index (queueing behind the
|
||||
* physical job limit); a cancelled request drops only its own reference. */
|
||||
static char *application_index_execute_sync(cbm_daemon_application_session_t *session,
|
||||
const char *root_path, const char *args_json) {
|
||||
char *project_key = application_index_project_key(root_path, args_json);
|
||||
if (!project_key) {
|
||||
return cbm_mcp_text_result("failed to derive index project identity", true);
|
||||
@@ -2332,28 +2506,28 @@ static char *application_index_execute(void *context, const char *root_path,
|
||||
memory_order_release);
|
||||
cbm_mutex_lock(&session->application->mutex);
|
||||
bool queued_cancelled = application_request_cancelled_locked(session);
|
||||
if (queued_cancelled) {
|
||||
application_index_record_mark_cut_short_locked(session->application, project_key);
|
||||
}
|
||||
cbm_mutex_unlock(&session->application->mutex);
|
||||
if (queued_cancelled) {
|
||||
free(project_key);
|
||||
return cbm_mcp_text_result("index operation cancelled for this session", true);
|
||||
return cbm_mcp_text_result(
|
||||
"index operation cancelled for this session. " CBM_MCP_INDEX_ASYNC_HINT, true);
|
||||
}
|
||||
cbm_usleep(APPLICATION_JOB_POLL_US);
|
||||
}
|
||||
free(project_key);
|
||||
if (!job) {
|
||||
const char *message = "daemon index coordinator is stopping or unavailable";
|
||||
if (subscribe_status == APPLICATION_JOB_SUBSCRIBE_OPTIONS_CONFLICT) {
|
||||
message = "another index operation for this project is active with different options";
|
||||
} else if (subscribe_status == APPLICATION_JOB_SUBSCRIBE_ALLOCATION_FAILED) {
|
||||
message = "daemon index coordinator could not allocate an index job";
|
||||
}
|
||||
return cbm_mcp_text_result(message, true);
|
||||
return cbm_mcp_text_result(application_index_admission_error(subscribe_status), true);
|
||||
}
|
||||
cbm_mutex_lock(&session->application->mutex);
|
||||
if (application_request_cancelled_locked(session)) {
|
||||
application_index_record_cut_short_locked(job);
|
||||
application_job_unsubscribe_locked(job);
|
||||
cbm_mutex_unlock(&session->application->mutex);
|
||||
return cbm_mcp_text_result("index operation cancelled for this session", true);
|
||||
return cbm_mcp_text_result(
|
||||
"index operation cancelled for this session. " CBM_MCP_INDEX_ASYNC_HINT, true);
|
||||
}
|
||||
if (session->active_job) {
|
||||
application_job_unsubscribe_locked(job);
|
||||
@@ -2366,6 +2540,236 @@ static char *application_index_execute(void *context, const char *root_path,
|
||||
return application_job_wait_for_session(session, job);
|
||||
}
|
||||
|
||||
/* Take (and clear) the project's pending cut-short advice. Taken at the START
|
||||
* of a synchronous call: if this call is cut short too, its own cancel path
|
||||
* sets the marker again, so the advice is never consumed by a reply nobody
|
||||
* reads. */
|
||||
static bool application_index_take_cut_short(cbm_daemon_application_t *application,
|
||||
const char *project_key) {
|
||||
cbm_mutex_lock(&application->mutex);
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_find_locked(application, project_key);
|
||||
bool pending = record && record->sync_cut_short;
|
||||
if (pending) {
|
||||
record->sync_cut_short = false;
|
||||
}
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
return pending;
|
||||
}
|
||||
|
||||
#define APPLICATION_CUT_SHORT_NOTICE \
|
||||
"The previous synchronous index_repository call for this project was cut short before the " \
|
||||
"index finished (client cancel, call deadline or disconnect). " CBM_MCP_INDEX_ASYNC_HINT
|
||||
|
||||
static char *application_index_run_sync(cbm_daemon_application_session_t *session,
|
||||
const char *root_path, const char *args_json) {
|
||||
char *project_key = application_index_project_key(root_path, args_json);
|
||||
bool notice =
|
||||
project_key && application_index_take_cut_short(session->application, project_key);
|
||||
safe_free(project_key);
|
||||
char *response = application_index_execute_sync(session, root_path, args_json);
|
||||
return notice ? cbm_mcp_tool_result_add_notice(response, APPLICATION_CUT_SHORT_NOTICE)
|
||||
: response;
|
||||
}
|
||||
|
||||
static char *application_index_async_response(const char *project_key, const char *state,
|
||||
bool joined) {
|
||||
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
|
||||
yyjson_mut_val *root = doc ? yyjson_mut_obj(doc) : NULL;
|
||||
char *json = NULL;
|
||||
if (root) {
|
||||
yyjson_mut_doc_set_root(doc, root);
|
||||
yyjson_mut_obj_add_strcpy(doc, root, "project", project_key);
|
||||
yyjson_mut_obj_add_str(doc, root, "state", state);
|
||||
yyjson_mut_obj_add_bool(doc, root, "async", true);
|
||||
yyjson_mut_obj_add_bool(doc, root, "joined", joined);
|
||||
yyjson_mut_obj_add_str(doc, root, "poll",
|
||||
"call index_repository with the same repo_path and status: true "
|
||||
"until state is succeeded, failed or cancelled");
|
||||
json = yyjson_mut_write(doc, 0, NULL);
|
||||
}
|
||||
yyjson_mut_doc_free(doc);
|
||||
char *result = cbm_mcp_text_result(json ? json : "{}", false);
|
||||
safe_free(json);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* #2144 user decision: refuse async where the job would certainly die with its
|
||||
* requester. A temporary (non-permanent) daemon stops and cancels every job
|
||||
* when its final live session ends. The one-shot tool channel (`cli ...`)
|
||||
* closes its session right after the reply, so if it is the only live session
|
||||
* the job is doomed. A long-lived MCP session - the IDE case this exists for -
|
||||
* stays connected and is a valid host even when it is the only one, as is any
|
||||
* other live session and every permanent (`daemon start`) generation. */
|
||||
static bool application_async_host_missing(cbm_daemon_application_session_t *session) {
|
||||
cbm_daemon_application_t *application = session->application;
|
||||
cbm_mutex_lock(&application->mutex);
|
||||
bool other_live_session = false;
|
||||
for (cbm_daemon_application_session_t *other = application->sessions;
|
||||
other && !other_live_session; other = other->next) {
|
||||
other_live_session = other != session && !other->session_cancelled;
|
||||
}
|
||||
bool missing = !application->permanent && session->one_shot_request && !other_live_session;
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
return missing;
|
||||
}
|
||||
|
||||
/* index_repository(async: true) (#2144): start or join the project's job and
|
||||
* return at once. The application keeps one subscriber reference until the
|
||||
* terminal publish, so neither this request returning, nor its client
|
||||
* cancelling, nor this session closing cancels the job: only daemon shutdown
|
||||
* (or the final live session of a non-permanent generation) does. Never
|
||||
* queues behind the physical job limit: a full daemon answers busy. */
|
||||
#define APPLICATION_ASYNC_NEEDS_HOST \
|
||||
"async indexing needs a daemon that outlives this command: this one-shot call is the only " \
|
||||
"client of a temporary daemon, which stops (cancelling the job) when the command exits. Run " \
|
||||
"`codebase-memory-mcp daemon start` (or keep an MCP session open), then retry; or call " \
|
||||
"without async"
|
||||
|
||||
static char *application_index_start_async(cbm_daemon_application_session_t *session,
|
||||
const char *root_path, const char *args_json) {
|
||||
cbm_daemon_application_t *application = session->application;
|
||||
if (application_async_host_missing(session)) {
|
||||
return cbm_mcp_text_result(APPLICATION_ASYNC_NEEDS_HOST, true);
|
||||
}
|
||||
char *project_key = application_index_project_key(root_path, args_json);
|
||||
if (!project_key) {
|
||||
return cbm_mcp_text_result("failed to derive index project identity", true);
|
||||
}
|
||||
application_jobs_reap_completed(application);
|
||||
application_job_subscribe_status_t status = APPLICATION_JOB_SUBSCRIBE_UNAVAILABLE;
|
||||
cbm_mutex_lock(&application->mutex);
|
||||
/* Subscribe and claim in one critical section: the job cannot publish in
|
||||
* between, so the async reference is always released by its publish. */
|
||||
cbm_daemon_application_job_t *job =
|
||||
application_job_subscribe_locked(application, project_key, root_path, args_json, &status);
|
||||
bool joined = false;
|
||||
const char *state = "queued";
|
||||
if (job) {
|
||||
joined = job->async_owned || job->subscribers > 1;
|
||||
if (job->async_owned) {
|
||||
application_job_unsubscribe_locked(job); /* one async reference per job */
|
||||
} else {
|
||||
job->async_owned = true;
|
||||
}
|
||||
state = job->worker_started ? "running" : "queued";
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_get_locked(application, project_key);
|
||||
if (record) {
|
||||
record->async = true;
|
||||
record->sync_cut_short = false; /* the advice was taken */
|
||||
}
|
||||
}
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
char *result = NULL;
|
||||
if (job) {
|
||||
cbm_log_info("daemon.index.async", "project", project_key, "joined",
|
||||
joined ? "true" : "false");
|
||||
result = application_index_async_response(project_key, state, joined);
|
||||
} else if (status == APPLICATION_JOB_SUBSCRIBE_BUSY) {
|
||||
result = cbm_mcp_text_result(
|
||||
"daemon index job limit reached; async requests do not queue. Retry async later, or "
|
||||
"call without async to wait for a slot",
|
||||
true);
|
||||
} else if (status == APPLICATION_JOB_SUBSCRIBE_CANCELLING) {
|
||||
result = cbm_mcp_text_result(
|
||||
"the previous index of this project is still being cancelled; retry async shortly",
|
||||
true);
|
||||
} else {
|
||||
result = cbm_mcp_text_result(application_index_admission_error(status), true);
|
||||
}
|
||||
safe_free(project_key);
|
||||
return result;
|
||||
}
|
||||
|
||||
static char *application_index_execute(void *context, const char *root_path, const char *args_json,
|
||||
bool async) {
|
||||
cbm_daemon_application_session_t *session = context;
|
||||
if (!session || !root_path || !args_json) {
|
||||
return NULL;
|
||||
}
|
||||
return async ? application_index_start_async(session, root_path, args_json)
|
||||
: application_index_run_sync(session, root_path, args_json);
|
||||
}
|
||||
|
||||
static void application_status_add_record(yyjson_mut_doc *doc, yyjson_mut_val *root,
|
||||
const cbm_daemon_application_index_record_t *record) {
|
||||
yyjson_mut_obj_add_bool(doc, root, "async", record->async);
|
||||
if (record->started_at[0]) {
|
||||
yyjson_mut_obj_add_strcpy(doc, root, "started_at", record->started_at);
|
||||
}
|
||||
if (record->finished_at[0]) {
|
||||
yyjson_mut_obj_add_strcpy(doc, root, "finished_at", record->finished_at);
|
||||
}
|
||||
if (record->error) {
|
||||
yyjson_mut_obj_add_strcpy(doc, root, "error", record->error);
|
||||
}
|
||||
if (record->sync_cut_short) {
|
||||
yyjson_mut_obj_add_str(doc, root, "notice", APPLICATION_CUT_SHORT_NOTICE);
|
||||
}
|
||||
}
|
||||
|
||||
/* index_repository(status: true) (#2144). A live job reports queued, running
|
||||
* or cancelling; otherwise the last recorded outcome. A project with neither a
|
||||
* job record nor a database is an error; one indexed before this daemon
|
||||
* generation reports idle and points at index_status for graph freshness. */
|
||||
static char *application_index_status(void *context, const char *project) {
|
||||
cbm_daemon_application_session_t *session = context;
|
||||
if (!session || !project) {
|
||||
return NULL;
|
||||
}
|
||||
cbm_daemon_application_t *application = session->application;
|
||||
bool db_exists = application_regular_db_exists(project);
|
||||
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
|
||||
yyjson_mut_val *root = doc ? yyjson_mut_obj(doc) : NULL;
|
||||
if (!root) {
|
||||
yyjson_mut_doc_free(doc);
|
||||
return NULL;
|
||||
}
|
||||
yyjson_mut_doc_set_root(doc, root);
|
||||
yyjson_mut_obj_add_strcpy(doc, root, "project", project);
|
||||
cbm_mutex_lock(&application->mutex);
|
||||
cbm_daemon_application_job_t *job = application_find_active_job_locked(application, project);
|
||||
cbm_daemon_application_index_record_t *record =
|
||||
application_index_record_find_locked(application, project);
|
||||
bool known = job || record || db_exists;
|
||||
if (job) {
|
||||
yyjson_mut_obj_add_str(doc, root, "state",
|
||||
job->cancel_requested ? "cancelling"
|
||||
: job->worker_started ? "running"
|
||||
: "queued");
|
||||
} else if (record) {
|
||||
yyjson_mut_obj_add_str(doc, root, "state", record->state);
|
||||
} else {
|
||||
yyjson_mut_obj_add_str(doc, root, "state", "idle");
|
||||
yyjson_mut_obj_add_str(doc, root, "detail",
|
||||
"no index job has run for this project in this daemon generation; "
|
||||
"index_status describes the published graph");
|
||||
}
|
||||
if (record) {
|
||||
application_status_add_record(doc, root, record);
|
||||
}
|
||||
if (job && !job->cancel_requested) {
|
||||
yyjson_mut_obj_add_str(doc, root, "poll",
|
||||
"call again with status: true until state is succeeded, failed or "
|
||||
"cancelled");
|
||||
}
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
char *json = known ? yyjson_mut_write(doc, 0, NULL) : NULL;
|
||||
yyjson_mut_doc_free(doc);
|
||||
if (!known) {
|
||||
char message[APPLICATION_PATH_CAP];
|
||||
(void)snprintf(message, sizeof(message),
|
||||
"no index job or index is known for project '%s'; start one with "
|
||||
"index_repository(repo_path=..., async: true)",
|
||||
project);
|
||||
return cbm_mcp_text_result(message, true);
|
||||
}
|
||||
char *result = cbm_mcp_text_result(json ? json : "{}", false);
|
||||
safe_free(json);
|
||||
return result;
|
||||
}
|
||||
|
||||
static cbm_daemon_runtime_application_session_t *application_session_open(
|
||||
void *context, cbm_daemon_client_id_t client_id, uint64_t authenticated_process_id) {
|
||||
cbm_daemon_application_t *application = context;
|
||||
@@ -2386,6 +2790,7 @@ static cbm_daemon_runtime_application_session_t *application_session_open(
|
||||
cbm_mcp_server_set_background_tasks(session->mcp, false);
|
||||
cbm_mcp_server_set_config(session->mcp, application->config);
|
||||
cbm_mcp_server_set_index_executor(session->mcp, application_index_execute, session);
|
||||
cbm_mcp_server_set_index_status_provider(session->mcp, application_index_status, session);
|
||||
cbm_mcp_server_set_project_mutation_guard(session->mcp, application_session_mutation_begin,
|
||||
application_session_mutation_end, session);
|
||||
cbm_mcp_server_set_project_mutation_try_guard(session->mcp,
|
||||
@@ -2617,7 +3022,9 @@ static cbm_daemon_runtime_application_status_t application_tool_request(
|
||||
free(args);
|
||||
return CBM_DAEMON_RUNTIME_APPLICATION_REJECTED;
|
||||
}
|
||||
session->one_shot_request = true; /* only this request thread reads it */
|
||||
char *response = cbm_mcp_handle_tool(session->mcp, tool, args);
|
||||
session->one_shot_request = false;
|
||||
free(tool);
|
||||
free(args);
|
||||
if (!response) {
|
||||
@@ -2849,6 +3256,7 @@ static void application_request_cancel(void *context,
|
||||
cbm_daemon_application_job_t *job = session->active_job;
|
||||
session->active_job = NULL;
|
||||
session->active_job_subscribed = false;
|
||||
application_index_record_cut_short_locked(job);
|
||||
application_job_unsubscribe_locked(job);
|
||||
}
|
||||
if (active_match) {
|
||||
@@ -2881,6 +3289,7 @@ static void application_session_cancel(void *context,
|
||||
cbm_daemon_application_job_t *job = session->active_job;
|
||||
session->active_job = NULL;
|
||||
session->active_job_subscribed = false;
|
||||
application_index_record_cut_short_locked(job);
|
||||
application_job_unsubscribe_locked(job);
|
||||
}
|
||||
join_auto_index = application_auto_index_release_locked(session);
|
||||
@@ -2937,6 +3346,7 @@ static void application_session_close(void *context,
|
||||
*cursor = session->next;
|
||||
}
|
||||
if (session->active_job && session->active_job_subscribed) {
|
||||
application_index_record_cut_short_locked(session->active_job);
|
||||
application_job_unsubscribe_locked(session->active_job);
|
||||
session->active_job = NULL;
|
||||
session->active_job_subscribed = false;
|
||||
@@ -3148,7 +3558,10 @@ bool cbm_daemon_application_free_with_timeout(cbm_daemon_application_t *applicat
|
||||
application->watch_job_subscriptions = NULL;
|
||||
cbm_daemon_application_mutation_t *mutations = application->mutations;
|
||||
application->mutations = NULL;
|
||||
cbm_daemon_application_index_record_t *index_records = application->index_records;
|
||||
application->index_records = NULL;
|
||||
cbm_mutex_unlock(&application->mutex);
|
||||
application_index_records_free(index_records);
|
||||
while (sessions) {
|
||||
cbm_daemon_application_session_t *next = sessions->next;
|
||||
cbm_mcp_server_free(sessions->mcp);
|
||||
|
||||
+36
-8
@@ -241,21 +241,49 @@ static const char *bootstrap_runtime_parent_override(char *buffer, size_t capaci
|
||||
return value && value[0] != '\0' ? value : NULL;
|
||||
}
|
||||
|
||||
/* An explicit parent keeps precedence: it carries the compile-time test seam
|
||||
* and the lifecycle guards' isolated namespace. NULL means the account-wide
|
||||
* default rendezvous. */
|
||||
static const char *bootstrap_runtime_parent_resolve(const char *runtime_parent, char *buffer,
|
||||
size_t capacity) {
|
||||
return runtime_parent ? runtime_parent : bootstrap_runtime_parent_override(buffer, capacity);
|
||||
}
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* Armed once by a test runner before any suite starts its threads. */
|
||||
static bool g_bootstrap_default_runtime_forbidden = false;
|
||||
|
||||
void cbm_daemon_bootstrap_forbid_default_runtime_for_test(bool forbid) {
|
||||
g_bootstrap_default_runtime_forbidden = forbid;
|
||||
}
|
||||
|
||||
bool cbm_daemon_bootstrap_default_runtime_refused_for_test(const char *runtime_parent) {
|
||||
char override_parent[BOOTSTRAP_PATH_CAP];
|
||||
return g_bootstrap_default_runtime_forbidden &&
|
||||
!bootstrap_runtime_parent_resolve(runtime_parent, override_parent,
|
||||
sizeof(override_parent));
|
||||
}
|
||||
#endif
|
||||
|
||||
cbm_daemon_ipc_endpoint_t *cbm_daemon_bootstrap_endpoint_new(const char *runtime_parent) {
|
||||
char key[CBM_DAEMON_KEY_SIZE];
|
||||
if (!cbm_daemon_rendezvous_key(key)) {
|
||||
return NULL;
|
||||
}
|
||||
/* An explicit parent keeps precedence: it carries the compile-time test
|
||||
* seam and the lifecycle guards' isolated namespace. The override is
|
||||
* resolved HERE, the one function every product endpoint goes through
|
||||
* (daemon, MCP client, local CLI, index worker, activation), so no call
|
||||
* site can silently keep the default. */
|
||||
/* The override is resolved HERE, the one function every product endpoint
|
||||
* goes through (daemon, MCP client, local CLI, index worker, activation),
|
||||
* so no call site can silently keep the default. */
|
||||
char override_parent[BOOTSTRAP_PATH_CAP];
|
||||
const char *parent =
|
||||
runtime_parent
|
||||
? runtime_parent
|
||||
: bootstrap_runtime_parent_override(override_parent, sizeof(override_parent));
|
||||
bootstrap_runtime_parent_resolve(runtime_parent, override_parent, sizeof(override_parent));
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
if (!parent && g_bootstrap_default_runtime_forbidden) {
|
||||
(void)fprintf(stderr, "codebase-memory-mcp: test run refused the default daemon runtime "
|
||||
"directory (no explicit parent and CBM_RUNTIME_DIR unset): the "
|
||||
"developer's live daemon listens there\n");
|
||||
return NULL;
|
||||
}
|
||||
#endif
|
||||
return cbm_daemon_ipc_endpoint_new(key, parent);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,17 @@ bool cbm_daemon_process_role_requires_client(cbm_daemon_process_role_t role);
|
||||
* ABI values must never create parallel daemon namespaces. */
|
||||
cbm_daemon_ipc_endpoint_t *cbm_daemon_bootstrap_endpoint_new(const char *runtime_parent);
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* Test runners only; no product binary arms it. Once armed, an endpoint
|
||||
* request that names no runtime parent while CBM_RUNTIME_DIR is unset (one
|
||||
* that would resolve to the account-wide default rendezvous, where the
|
||||
* developer's live daemon listens) is refused with a diagnostic on stderr. */
|
||||
void cbm_daemon_bootstrap_forbid_default_runtime_for_test(bool forbid);
|
||||
/* The same decision cbm_daemon_bootstrap_endpoint_new makes, without
|
||||
* resolving anything: true when that call would be refused. */
|
||||
bool cbm_daemon_bootstrap_default_runtime_refused_for_test(const char *runtime_parent);
|
||||
#endif
|
||||
|
||||
/* Cross-platform launch policy for the daemon child. The child is invoked
|
||||
* directly (never through a shell), with exactly argv[0] plus the one hidden
|
||||
* internal argument. It is detached from the launching client's lifetime and
|
||||
|
||||
+19
-1
@@ -382,8 +382,26 @@ static bool frontend_write_response(FILE *out, const uint8_t *response, uint32_t
|
||||
return fflush(out) == 0 && written;
|
||||
}
|
||||
|
||||
const char *cbm_daemon_frontend_cancelled_error_message(const char *request_message) {
|
||||
static const char plain[] = "Request cancelled";
|
||||
static const char index_call[] = "Request cancelled. " CBM_MCP_INDEX_ASYNC_HINT;
|
||||
cbm_jsonrpc_request_t request = {0};
|
||||
if (!request_message || cbm_jsonrpc_parse(request_message, &request) != 0) {
|
||||
return plain;
|
||||
}
|
||||
char *tool = request.method && strcmp(request.method, "tools/call") == 0 && request.params_raw
|
||||
? cbm_mcp_get_string_arg(request.params_raw, "name")
|
||||
: NULL;
|
||||
bool index_repository = tool && strcmp(tool, "index_repository") == 0;
|
||||
safe_free(tool);
|
||||
cbm_jsonrpc_request_free(&request);
|
||||
return index_repository ? index_call : plain;
|
||||
}
|
||||
|
||||
static bool frontend_write_cancelled_response(FILE *out, const frontend_item_t *item) {
|
||||
static const char cancelled_error[] = "{\"code\":-32800,\"message\":\"Request cancelled\"}";
|
||||
char cancelled_error[512];
|
||||
(void)snprintf(cancelled_error, sizeof(cancelled_error), "{\"code\":-32800,\"message\":\"%s\"}",
|
||||
cbm_daemon_frontend_cancelled_error_message(item->message));
|
||||
cbm_jsonrpc_response_t response = {
|
||||
.id = item->id,
|
||||
.id_str = item->id_str,
|
||||
|
||||
@@ -29,6 +29,12 @@ bool cbm_daemon_frontend_is_cancellation_notification(const char *message);
|
||||
bool cbm_daemon_frontend_cancellation_matches_request(const char *message, int64_t active_id,
|
||||
const char *active_id_str);
|
||||
|
||||
/* The JSON-RPC error message answered for a cancelled request (#2144). A
|
||||
* cancelled index_repository call is usually a client deadline on a long
|
||||
* index, so its reply names the async alternative; every other request keeps
|
||||
* the plain message. Returns a static string free of JSON metacharacters. */
|
||||
const char *cbm_daemon_frontend_cancelled_error_message(const char *request_message);
|
||||
|
||||
/* Start a temporary observer for a one-shot local CLI command or physical
|
||||
* supervised worker. manager and cancel_context are borrowed until stop. On
|
||||
* maintenance intent the observer invokes cancel once, permits a fixed bounded
|
||||
|
||||
+69
-7
@@ -408,6 +408,9 @@ int cbm_daemon_ipc_wait_pending(const cbm_ipc_pending_ops_t *ops, uint32_t timeo
|
||||
#include <sys/un.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#if defined(__linux__)
|
||||
#include <sys/vfs.h>
|
||||
#endif
|
||||
|
||||
#ifndef O_CLOEXEC
|
||||
#define O_CLOEXEC 0
|
||||
@@ -1680,6 +1683,55 @@ static bool posix_ancestor_stat_ok(uid_t owner, mode_t mode, uid_t euid, uid_t o
|
||||
return true;
|
||||
}
|
||||
|
||||
/* #1687: WSL2 mounts Windows drives (/mnt/c, /mnt/e, ...) as DrvFs over 9p.
|
||||
* Without the `metadata` mount option such a mount reports 0777 for every
|
||||
* directory and ignores chmod, so both the ancestor rule (not world-writable)
|
||||
* and the leaf 0700 rule refuse it -- correctly: the 0777 is real. The gate
|
||||
* stays exactly as it is; this only lets the refusal name the remedy instead
|
||||
* of leaving a WSL user to guess. Detection is a statfs magic (9p) confirmed by
|
||||
* a WSL kernel release string, so plain 9p mounts elsewhere (QEMU virtfs) keep
|
||||
* the generic message. Diagnostic only: it never changes accept/refuse. */
|
||||
#define POSIX_WSL_DRVFS_REMEDY \
|
||||
"WSL DrvFs mount: set /etc/wsl.conf [automount] options = " \
|
||||
"\"metadata,umask=22,fmask=11\", then run `wsl --shutdown`; or keep the cache on the Linux " \
|
||||
"filesystem (e.g. ~/.cache)"
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
static bool g_posix_force_wsl_drvfs;
|
||||
void cbm_daemon_ipc_posix_force_wsl_drvfs_for_test(bool force) {
|
||||
g_posix_force_wsl_drvfs = force;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(__linux__)
|
||||
#define POSIX_V9FS_MAGIC 0x01021997UL
|
||||
|
||||
static bool posix_kernel_is_wsl(void) {
|
||||
char release[128];
|
||||
if (!posix_read_small_proc_file("/proc/sys/kernel/osrelease", release, sizeof(release))) {
|
||||
return false;
|
||||
}
|
||||
return strstr(release, "microsoft") != NULL || strstr(release, "Microsoft") != NULL ||
|
||||
strstr(release, "WSL") != NULL;
|
||||
}
|
||||
#endif
|
||||
|
||||
static bool posix_fd_on_wsl_drvfs(int directory_fd) {
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
if (g_posix_force_wsl_drvfs) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
#if defined(__linux__)
|
||||
struct statfs filesystem;
|
||||
return directory_fd >= 0 && fstatfs(directory_fd, &filesystem) == 0 &&
|
||||
(unsigned long)filesystem.f_type == POSIX_V9FS_MAGIC && posix_kernel_is_wsl();
|
||||
#else
|
||||
(void)directory_fd;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
static bool posix_directory_ancestor_owner_trusted(uid_t owner) {
|
||||
return posix_ancestor_owner_ok(owner, geteuid(), posix_ancestor_overflow_uid());
|
||||
}
|
||||
@@ -1796,11 +1848,18 @@ static int private_directory_tree_open(const char *directory_path) {
|
||||
* refusing, found it clean, and said so — correctly. Naming the
|
||||
* containing directory is the difference between a report we
|
||||
* can act on and weeks of talking past each other. */
|
||||
ipc_validation_detail_set(
|
||||
"%s: the directory CONTAINING '%s' is not a usable private-directory parent "
|
||||
"(it must be owned by you, not world-writable, and carry no allow-ACL). Check "
|
||||
"that containing directory, not '%s' itself",
|
||||
directory_path, component, component);
|
||||
if (posix_fd_on_wsl_drvfs(current_fd)) {
|
||||
/* #1687: shorter rule text so the remedy fits the buffer. */
|
||||
ipc_validation_detail_set("%s: the directory CONTAINING '%s' is not private "
|
||||
"(DrvFs reports 0777). " POSIX_WSL_DRVFS_REMEDY,
|
||||
directory_path, component);
|
||||
} else {
|
||||
ipc_validation_detail_set(
|
||||
"%s: the directory CONTAINING '%s' is not a usable private-directory "
|
||||
"parent (it must be owned by you, not world-writable, and carry no "
|
||||
"allow-ACL). Check that containing directory, not '%s' itself",
|
||||
directory_path, component, component);
|
||||
}
|
||||
}
|
||||
bool created = ok && mkdirat(current_fd, component, 0700) == 0;
|
||||
if (!created && errno != EEXIST) {
|
||||
@@ -1854,8 +1913,11 @@ static int private_directory_tree_open(const char *directory_path) {
|
||||
ok = false;
|
||||
}
|
||||
if (ok && (fstat(current_fd, &final_status) != 0 || (final_status.st_mode & 07777) != 0700)) {
|
||||
ipc_validation_detail_set("%s: mode 0%o survived chmod, expected 0700", directory_path,
|
||||
(unsigned)(final_status.st_mode & 07777));
|
||||
/* #1687: DrvFs without `metadata` ignores chmod; name the remedy. */
|
||||
bool drvfs = posix_fd_on_wsl_drvfs(current_fd);
|
||||
ipc_validation_detail_set("%s: mode 0%o survived chmod, expected 0700%s%s", directory_path,
|
||||
(unsigned)(final_status.st_mode & 07777), drvfs ? ". " : "",
|
||||
drvfs ? POSIX_WSL_DRVFS_REMEDY : "");
|
||||
ok = false;
|
||||
}
|
||||
if (ok && !cbm_macos_extended_acl_fd_is_empty(current_fd)) {
|
||||
|
||||
@@ -131,6 +131,9 @@ bool cbm_daemon_ipc_posix_uid_map_is_single_uid_for_test(const char *uid_map, un
|
||||
bool cbm_daemon_ipc_posix_ancestor_stat_ok_for_test(unsigned long owner, unsigned int mode,
|
||||
unsigned long euid, bool overflow_active,
|
||||
unsigned long overflow_uid);
|
||||
/* #1687: treat every directory as on a WSL DrvFs mount so the remedy text in
|
||||
* the private-directory refusal is testable off WSL. Diagnostic only. */
|
||||
void cbm_daemon_ipc_posix_force_wsl_drvfs_for_test(bool force);
|
||||
#if defined(__linux__)
|
||||
/* Number of REAL overflow-uid derivations so far. The value is meaningless on
|
||||
* its own; the point is that it must rise on every ancestor check, proving no
|
||||
|
||||
+145
-44
@@ -36,6 +36,23 @@ static atomic_bool runtime_force_peer_image_mismatch_seam;
|
||||
void cbm_daemon_runtime_force_peer_image_mismatch_for_testing(bool force) {
|
||||
atomic_store(&runtime_force_peer_image_mismatch_seam, force);
|
||||
}
|
||||
/* #1955 test seam: make the active-image comparison miss, exactly as when the
|
||||
* peer runs a DIFFERENT file with identical bytes (a second install path, a
|
||||
* package-manager cache copy). Everything after that comparison - the full
|
||||
* fingerprint fallback and the verified-image cache - still runs for real. The
|
||||
* counter records every full-image fingerprint the HELLO path computes, so a
|
||||
* test asserts how often the O(image size) hash runs instead of timing it. */
|
||||
static atomic_bool runtime_force_peer_image_distinct_copy_seam;
|
||||
static atomic_uint_fast64_t runtime_peer_image_hash_count_seam;
|
||||
void cbm_daemon_runtime_force_peer_image_distinct_copy_for_testing(bool force) {
|
||||
atomic_store(&runtime_force_peer_image_distinct_copy_seam, force);
|
||||
}
|
||||
uint64_t cbm_daemon_runtime_peer_image_hashes_for_testing(void) {
|
||||
return (uint64_t)atomic_load(&runtime_peer_image_hash_count_seam);
|
||||
}
|
||||
static void runtime_note_peer_image_hash(void) {
|
||||
(void)atomic_fetch_add(&runtime_peer_image_hash_count_seam, 1);
|
||||
}
|
||||
/* The abandoned-request containment path ends in process termination, which an
|
||||
* in-process harness cannot observe. The timeout override makes the ceiling
|
||||
* reachable in test time; the hook replaces termination with a recordable
|
||||
@@ -59,6 +76,8 @@ static _Atomic uint32_t runtime_ephemeral_linger_timeout_seam = UINT32_MAX;
|
||||
void cbm_daemon_runtime_service_set_ephemeral_linger_timeout_for_testing(uint32_t timeout_ms) {
|
||||
atomic_store(&runtime_ephemeral_linger_timeout_seam, timeout_ms);
|
||||
}
|
||||
#else
|
||||
static void runtime_note_peer_image_hash(void) {}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
@@ -88,6 +107,11 @@ enum {
|
||||
RUNTIME_ACCEPT_POLL_MS = 20,
|
||||
RUNTIME_WAIT_POLL_NS = 1000000,
|
||||
RUNTIME_WORKER_STACK_SIZE = 256 * 1024,
|
||||
/* Distinct peer image files (install paths / identical copies) whose full
|
||||
* fingerprint already matched this daemon. Each held entry pins one image
|
||||
* inode, so the bound is small; a full table only means later copies are
|
||||
* hashed per admission, exactly as before the table existed. */
|
||||
RUNTIME_VERIFIED_PEER_IMAGE_CAPACITY = 8,
|
||||
/* Bounds the drain-before-close wait for a peer consuming its final
|
||||
* response; interrupted or already-poisoned connections skip it. */
|
||||
RUNTIME_WORKER_DRAIN_TIMEOUT_MS = 2000,
|
||||
@@ -240,6 +264,10 @@ struct cbm_daemon_runtime_service {
|
||||
char build_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
|
||||
cbm_daemon_build_identity_t identity;
|
||||
runtime_process_image_reference_t active_image;
|
||||
/* Guarded by mutex. Retained references keep each verified inode alive,
|
||||
* so its stat identity cannot be reused by a different file. */
|
||||
runtime_process_image_reference_t verified_peer_images[RUNTIME_VERIFIED_PEER_IMAGE_CAPACITY];
|
||||
size_t verified_peer_image_count;
|
||||
char *conflict_log_path;
|
||||
size_t conflict_log_cap_bytes;
|
||||
uint64_t lease_timeout_ms;
|
||||
@@ -916,6 +944,35 @@ static bool runtime_process_image_reference_acquire(
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* True when a retained reference is still the unchanged image it captured AND
|
||||
* the freshly acquired peer maps that same image. Metadata only: no hashing. */
|
||||
static bool runtime_process_image_reference_same(const runtime_process_image_reference_t *held,
|
||||
const runtime_process_image_reference_t *peer) {
|
||||
if (!held || !held->held || !peer || !peer->held) {
|
||||
return false;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
BY_HANDLE_FILE_INFORMATION held_now;
|
||||
LARGE_INTEGER held_size_now;
|
||||
return runtime_windows_file_snapshot(held->file, &held_now, &held_size_now) &&
|
||||
runtime_windows_file_snapshot_same(&held->information, &held->size, &held_now,
|
||||
&held_size_now) &&
|
||||
runtime_windows_file_snapshot_same(&held->information, &held->size, &peer->information,
|
||||
&peer->size);
|
||||
#elif defined(__APPLE__)
|
||||
struct stat held_now;
|
||||
return fstat(held->fd, &held_now) == 0 && runtime_mac_stat_same(&held->status, &held_now) &&
|
||||
runtime_mac_stat_same(&held->status, &peer->status);
|
||||
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
|
||||
struct stat held_now;
|
||||
return fstat(held->fd, &held_now) == 0 &&
|
||||
runtime_posix_stat_same_image(&held->status, &held_now) &&
|
||||
runtime_posix_stat_same_image(&held->status, &peer->status);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* A false result means only "not proven identical". The caller must use the
|
||||
* full fingerprint fallback before rejecting the peer. */
|
||||
static bool runtime_process_image_reference_matches_process(
|
||||
@@ -923,43 +980,12 @@ static bool runtime_process_image_reference_matches_process(
|
||||
if (!active || !active->held || process_id == 0) {
|
||||
return false;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
runtime_process_image_reference_t peer;
|
||||
runtime_process_image_reference_init(&peer);
|
||||
bool same = runtime_process_image_reference_acquire(process_id, &peer, NULL);
|
||||
BY_HANDLE_FILE_INFORMATION active_now;
|
||||
LARGE_INTEGER active_size_now;
|
||||
same = same && runtime_windows_file_snapshot(active->file, &active_now, &active_size_now) &&
|
||||
runtime_windows_file_snapshot_same(&active->information, &active->size, &active_now,
|
||||
&active_size_now) &&
|
||||
runtime_windows_file_snapshot_same(&active->information, &active->size,
|
||||
&peer.information, &peer.size);
|
||||
bool same = runtime_process_image_reference_acquire(process_id, &peer, NULL) &&
|
||||
runtime_process_image_reference_same(active, &peer);
|
||||
bool released = runtime_process_image_reference_release(&peer);
|
||||
return same && released;
|
||||
#elif defined(__APPLE__)
|
||||
runtime_process_image_reference_t peer;
|
||||
runtime_process_image_reference_init(&peer);
|
||||
bool same = runtime_process_image_reference_acquire(process_id, &peer, NULL);
|
||||
struct stat active_now;
|
||||
same = same && fstat(active->fd, &active_now) == 0 &&
|
||||
runtime_mac_stat_same(&active->status, &active_now) &&
|
||||
runtime_mac_stat_same(&active->status, &peer.status);
|
||||
bool released = runtime_process_image_reference_release(&peer);
|
||||
return same && released;
|
||||
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
|
||||
runtime_process_image_reference_t peer;
|
||||
runtime_process_image_reference_init(&peer);
|
||||
bool same = runtime_process_image_reference_acquire(process_id, &peer, NULL);
|
||||
struct stat active_now;
|
||||
same = same && fstat(active->fd, &active_now) == 0 &&
|
||||
runtime_posix_stat_same_image(&active->status, &active_now) &&
|
||||
runtime_posix_stat_same_image(&active->status, &peer.status);
|
||||
bool released = runtime_process_image_reference_release(&peer);
|
||||
return same && released;
|
||||
#else
|
||||
(void)process_id;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool cbm_daemon_runtime_process_build_fingerprint(uint64_t process_id,
|
||||
@@ -980,6 +1006,86 @@ bool cbm_daemon_runtime_process_build_fingerprint(uint64_t process_id,
|
||||
return ok;
|
||||
}
|
||||
|
||||
typedef enum {
|
||||
RUNTIME_PEER_IMAGE_VERIFIED,
|
||||
RUNTIME_PEER_IMAGE_UNVERIFIABLE,
|
||||
RUNTIME_PEER_IMAGE_MISMATCH,
|
||||
} runtime_peer_image_verdict_t;
|
||||
|
||||
static bool runtime_verified_peer_image_known_locked(
|
||||
const cbm_daemon_runtime_service_t *service, const runtime_process_image_reference_t *peer) {
|
||||
for (size_t i = 0; i < service->verified_peer_image_count; i++) {
|
||||
if (runtime_process_image_reference_same(&service->verified_peer_images[i], peer)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* #1955: the HELLO must prove the peer runs this daemon's build. The cheap
|
||||
* proof is "same image file as the daemon"; a peer running a DIFFERENT file
|
||||
* with identical bytes (a second install path, a package-manager copy) needs
|
||||
* the full fingerprint, i.e. hashing the whole (~300 MB) image. That hash is
|
||||
* slower than the client's HELLO budget, so the client abandoned it and every
|
||||
* re-probe started it again - admission never completed against a healthy
|
||||
* daemon. A copy is now hashed once: its verified reference is retained and
|
||||
* later admissions of the same unchanged file match it by metadata, exactly
|
||||
* like the active image. The accepted set of images is unchanged. */
|
||||
static runtime_peer_image_verdict_t runtime_peer_image_verify(cbm_daemon_runtime_service_t *service,
|
||||
uint64_t process_id,
|
||||
const char *requested_build) {
|
||||
runtime_process_image_reference_t peer;
|
||||
runtime_process_image_reference_init(&peer);
|
||||
bool peer_held = runtime_process_image_reference_acquire(process_id, &peer, NULL);
|
||||
bool known = false;
|
||||
if (peer_held) {
|
||||
known = runtime_process_image_reference_same(&service->active_image, &peer);
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
if (atomic_load(&runtime_force_peer_image_distinct_copy_seam)) {
|
||||
known = false;
|
||||
}
|
||||
#endif
|
||||
if (!known) {
|
||||
cbm_mutex_lock(&service->mutex);
|
||||
known = runtime_verified_peer_image_known_locked(service, &peer);
|
||||
cbm_mutex_unlock(&service->mutex);
|
||||
}
|
||||
}
|
||||
bool released = runtime_process_image_reference_release(&peer);
|
||||
if (known && released) {
|
||||
return RUNTIME_PEER_IMAGE_VERIFIED;
|
||||
}
|
||||
|
||||
char fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
|
||||
runtime_process_image_reference_t hashed;
|
||||
runtime_process_image_reference_init(&hashed);
|
||||
runtime_note_peer_image_hash();
|
||||
bool fingerprinted = runtime_process_image_reference_acquire(process_id, &hashed, fingerprint);
|
||||
bool verified = fingerprinted && strcmp(fingerprint, requested_build) == 0 &&
|
||||
strcmp(fingerprint, service->identity.build_fingerprint) == 0;
|
||||
if (verified) {
|
||||
cbm_mutex_lock(&service->mutex);
|
||||
if (service->verified_peer_image_count < RUNTIME_VERIFIED_PEER_IMAGE_CAPACITY &&
|
||||
!runtime_verified_peer_image_known_locked(service, &hashed)) {
|
||||
service->verified_peer_images[service->verified_peer_image_count++] = hashed;
|
||||
runtime_process_image_reference_init(&hashed);
|
||||
}
|
||||
cbm_mutex_unlock(&service->mutex);
|
||||
}
|
||||
(void)runtime_process_image_reference_release(&hashed);
|
||||
if (verified) {
|
||||
return RUNTIME_PEER_IMAGE_VERIFIED;
|
||||
}
|
||||
return fingerprinted ? RUNTIME_PEER_IMAGE_MISMATCH : RUNTIME_PEER_IMAGE_UNVERIFIABLE;
|
||||
}
|
||||
|
||||
static void runtime_verified_peer_images_release(cbm_daemon_runtime_service_t *service) {
|
||||
for (size_t i = 0; i < service->verified_peer_image_count; i++) {
|
||||
(void)runtime_process_image_reference_release(&service->verified_peer_images[i]);
|
||||
}
|
||||
service->verified_peer_image_count = 0;
|
||||
}
|
||||
|
||||
static bool runtime_hello_response_encode(uint8_t out[CBM_DAEMON_RENDEZVOUS_RESPONSE_SIZE],
|
||||
const cbm_daemon_runtime_connect_result_t *result) {
|
||||
if (!out || !result) {
|
||||
@@ -1950,17 +2056,10 @@ static void *runtime_connection_worker(void *opaque) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool peer_image_verified = runtime_process_image_reference_matches_process(
|
||||
&service->active_image, worker->peer_process_id);
|
||||
bool peer_image_fingerprinted = false;
|
||||
if (!peer_image_verified) {
|
||||
char peer_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
|
||||
peer_image_fingerprinted =
|
||||
cbm_daemon_runtime_process_build_fingerprint(worker->peer_process_id, peer_fingerprint);
|
||||
peer_image_verified = peer_image_fingerprinted &&
|
||||
strcmp(peer_fingerprint, requested_build) == 0 &&
|
||||
strcmp(peer_fingerprint, service->identity.build_fingerprint) == 0;
|
||||
}
|
||||
runtime_peer_image_verdict_t peer_image =
|
||||
runtime_peer_image_verify(service, worker->peer_process_id, requested_build);
|
||||
bool peer_image_verified = peer_image == RUNTIME_PEER_IMAGE_VERIFIED;
|
||||
bool peer_image_fingerprinted = peer_image != RUNTIME_PEER_IMAGE_UNVERIFIABLE;
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
if (atomic_load(&runtime_force_peer_image_unverified_seam)) {
|
||||
peer_image_verified = false;
|
||||
@@ -2378,6 +2477,7 @@ static void runtime_service_destroy_unstarted(cbm_daemon_runtime_service_t *serv
|
||||
cbm_daemon_ipc_listener_close(service->listener);
|
||||
cbm_daemon_coordinator_free(service->coordinator);
|
||||
(void)runtime_process_image_reference_release(&service->active_image);
|
||||
runtime_verified_peer_images_release(service);
|
||||
free(service->conflict_log_path);
|
||||
for (size_t i = 0; i < service->worker_mutexes_initialized; i++) {
|
||||
cbm_mutex_destroy(&service->workers[i].send_mutex);
|
||||
@@ -2727,6 +2827,7 @@ bool cbm_daemon_runtime_service_free(cbm_daemon_runtime_service_t *service) {
|
||||
}
|
||||
cbm_daemon_coordinator_free(service->coordinator);
|
||||
(void)runtime_process_image_reference_release(&service->active_image);
|
||||
runtime_verified_peer_images_release(service);
|
||||
free(service->conflict_log_path);
|
||||
for (size_t i = 0; i < service->worker_mutexes_initialized; i++) {
|
||||
cbm_mutex_destroy(&service->workers[i].send_mutex);
|
||||
|
||||
@@ -450,6 +450,12 @@ void cbm_daemon_runtime_force_peer_image_unverified_for_testing(bool force);
|
||||
* i.e. the tamper case that must still be rejected after unverifiable images
|
||||
* became admissible. */
|
||||
void cbm_daemon_runtime_force_peer_image_mismatch_for_testing(bool force);
|
||||
/* #1955 test seam: make the peer look like a different file with identical
|
||||
* bytes (second install path, package-manager copy) so the fingerprint
|
||||
* fallback runs; the counter reports how many full-image fingerprints the
|
||||
* HELLO path has computed in this process. */
|
||||
void cbm_daemon_runtime_force_peer_image_distinct_copy_for_testing(bool force);
|
||||
uint64_t cbm_daemon_runtime_peer_image_hashes_for_testing(void);
|
||||
/* Abandoned-request containment seams (2026-08-29 zombie incident). The
|
||||
* timeout override shrinks the join ceiling to test scale; zero restores the
|
||||
* production constant. The hook replaces the terminal containment stop with a
|
||||
|
||||
+34
-2
@@ -2,7 +2,8 @@
|
||||
* discover.c — Recursive directory walk with filtering.
|
||||
*
|
||||
* Walks a repository directory tree, applying:
|
||||
* 1. Hardcoded directory skip patterns (60+ dirs like .git, node_modules)
|
||||
* 1. Hardcoded directory skip patterns (60+ dirs like .git, node_modules,
|
||||
* plus path-suffix rules such as Laravel's storage/framework/views)
|
||||
* 2. Hardcoded suffix filters (.pyc, .png, .wasm, etc.)
|
||||
* 3. Fast-mode additional filters (docs, examples, lock files, etc.)
|
||||
* 4. Gitignore-style pattern matching
|
||||
@@ -52,6 +53,17 @@ static const char *ALWAYS_SKIP_DIRS[] = {
|
||||
/* Misc */
|
||||
".codebase-memory", ".qdrant_code_embeddings", ".tmp", "vendor", "vendored", NULL};
|
||||
|
||||
/* Always-skip directories matched by relative-PATH suffix, not by basename:
|
||||
* generated build output whose last path component alone ("views") is far too
|
||||
* common to skip everywhere. A rule matches the whole relative path or a
|
||||
* '/'-aligned tail of it, so "storage/framework/views" and
|
||||
* "backend/storage/framework/views" match while "app/views",
|
||||
* "mystorage/framework/views" and "storage/framework/views_old" do not. */
|
||||
static const char *ALWAYS_SKIP_DIR_SUFFIXES[] = {
|
||||
/* Laravel's compiled Blade view cache (#1735): generated PHP with no source
|
||||
* value, skipped even when Laravel's stock .gitignore there is missing. */
|
||||
"storage/framework/views", NULL};
|
||||
|
||||
static const char *FAST_SKIP_DIRS[] = {
|
||||
"generated", "gen", "auto-generated", "fixtures", "testdata", "test_data",
|
||||
"__tests__", "__mocks__", "__snapshots__", "__fixtures__", "__test__", "docs",
|
||||
@@ -336,6 +348,25 @@ static bool resolve_global_excludes_path(char *out, size_t out_sz) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* True when rel_path equals a suffix rule or ends with "/" + the rule. */
|
||||
static bool rel_path_has_skip_suffix(const char *rel_path) {
|
||||
if (!rel_path) {
|
||||
return false;
|
||||
}
|
||||
size_t plen = strlen(rel_path);
|
||||
for (int i = 0; ALWAYS_SKIP_DIR_SUFFIXES[i]; i++) {
|
||||
const char *suffix = ALWAYS_SKIP_DIR_SUFFIXES[i];
|
||||
size_t slen = strlen(suffix);
|
||||
if (slen > plen || strcmp(rel_path + plen - slen, suffix) != 0) {
|
||||
continue;
|
||||
}
|
||||
if (slen == plen || rel_path[plen - slen - SKIP_ONE] == '/') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ── Public filter functions ─────────────────────── */
|
||||
|
||||
bool cbm_should_skip_dir(const char *dirname, cbm_index_mode_t mode) {
|
||||
@@ -727,7 +758,8 @@ static bool should_skip_directory(const char *entry_name, const char *rel_path,
|
||||
const gitignore_link_t *ignore_chain,
|
||||
const cbm_gitignore_t *global_gi,
|
||||
const cbm_gitignore_t *cbmignore) {
|
||||
if (cbm_should_skip_dir(entry_name, opts ? opts->mode : CBM_MODE_FULL)) {
|
||||
if (cbm_should_skip_dir(entry_name, opts ? opts->mode : CBM_MODE_FULL) ||
|
||||
rel_path_has_skip_suffix(rel_path)) {
|
||||
/* #500: a .cbmignore negation (e.g. "!obj/") whose rule is the last
|
||||
* match for this dir un-skips a built-in skip-list dir — except the
|
||||
* non-negatable safety core. Fall through so .gitignore/global/local
|
||||
|
||||
+153
-17
@@ -7,6 +7,7 @@
|
||||
#include "foundation/constants.h"
|
||||
#include "foundation/compat_fs.h"
|
||||
#include "foundation/compat_fs_internal.h"
|
||||
#include "foundation/git_env.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -236,7 +237,9 @@ static wchar_t *cbm_resolve_comspec(void) {
|
||||
|
||||
/* On failure returns NULL with *stage naming the failing step and *gle the
|
||||
* GetLastError value captured at that step (0 when errno is the signal). */
|
||||
static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle) {
|
||||
/* env: a CREATE_UNICODE_ENVIRONMENT block for the child, or NULL to inherit. */
|
||||
static FILE *cbm_popen_isolated(const char *cmd, const wchar_t *env, const char **stage,
|
||||
DWORD *gle) {
|
||||
*stage = "";
|
||||
*gle = 0;
|
||||
InitOnceExecuteOnce(&g_popen_once, cbm_popen_init, NULL, NULL);
|
||||
@@ -315,8 +318,11 @@ static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle)
|
||||
*stage = "cmdline";
|
||||
*gle = ERROR_NOT_ENOUGH_MEMORY;
|
||||
} else {
|
||||
created = CreateProcessW(app, wcmdline, NULL, NULL, TRUE,
|
||||
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, NULL, NULL,
|
||||
DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW;
|
||||
if (env) {
|
||||
flags |= CREATE_UNICODE_ENVIRONMENT;
|
||||
}
|
||||
created = CreateProcessW(app, wcmdline, NULL, NULL, TRUE, flags, (LPVOID)env, NULL,
|
||||
&si.StartupInfo, &pi);
|
||||
if (!created) {
|
||||
*stage = "spawn";
|
||||
@@ -372,29 +378,46 @@ static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static FILE *cbm_popen_read_isolated(const char *cmd, const wchar_t *env) {
|
||||
const char *stage = "";
|
||||
DWORD gle = 0;
|
||||
FILE *fp = cbm_popen_isolated(cmd, env, &stage, &gle);
|
||||
g_popen_last_isolated = (fp != NULL);
|
||||
if (!fp) {
|
||||
char glebuf[CBM_SZ_16];
|
||||
char errnobuf[CBM_SZ_16];
|
||||
snprintf(glebuf, sizeof(glebuf), "%lu", (unsigned long)gle);
|
||||
snprintf(errnobuf, sizeof(errnobuf), "%d", errno);
|
||||
cbm_log_warn("compat.popen_isolated_failed", "stage", stage, "gle", glebuf, "errno",
|
||||
errnobuf);
|
||||
}
|
||||
return fp;
|
||||
}
|
||||
|
||||
FILE *cbm_popen(const char *cmd, const char *mode) {
|
||||
/* Our git shell-outs are all read-mode; they MUST use the isolated
|
||||
* spawn. On failure, log and fail the call — never fall back to
|
||||
* _popen, whose full handle inheritance re-arms the UI hang (#798). */
|
||||
if (mode && mode[0] == 'r' && mode[1] == '\0') {
|
||||
const char *stage = "";
|
||||
DWORD gle = 0;
|
||||
FILE *fp = cbm_popen_isolated(cmd, &stage, &gle);
|
||||
g_popen_last_isolated = (fp != NULL);
|
||||
if (!fp) {
|
||||
char glebuf[CBM_SZ_16];
|
||||
char errnobuf[CBM_SZ_16];
|
||||
snprintf(glebuf, sizeof(glebuf), "%lu", (unsigned long)gle);
|
||||
snprintf(errnobuf, sizeof(errnobuf), "%d", errno);
|
||||
cbm_log_warn("compat.popen_isolated_failed", "stage", stage, "gle", glebuf, "errno",
|
||||
errnobuf);
|
||||
}
|
||||
return fp;
|
||||
return cbm_popen_read_isolated(cmd, NULL);
|
||||
}
|
||||
g_popen_last_isolated = 0;
|
||||
return _popen(cmd, mode);
|
||||
}
|
||||
|
||||
FILE *cbm_popen_git(const char *cmd) {
|
||||
/* Fail closed: without the scrubbed block the child would inherit a
|
||||
* caller's GIT_DIR and read the wrong repository (#2003). */
|
||||
wchar_t *env = cbm_git_child_env_block();
|
||||
if (!env) {
|
||||
cbm_log_warn("compat.popen_git_env_failed", "stage", "env_block");
|
||||
return NULL;
|
||||
}
|
||||
FILE *fp = cbm_popen_read_isolated(cmd, env);
|
||||
cbm_git_child_env_free(env); /* CreateProcessW copies the block into the child */
|
||||
return fp;
|
||||
}
|
||||
|
||||
int cbm_pclose(FILE *f) {
|
||||
InitOnceExecuteOnce(&g_popen_once, cbm_popen_init, NULL, NULL);
|
||||
|
||||
@@ -759,6 +782,8 @@ int cbm_exec_no_shell(const char *const *argv) {
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <spawn.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
@@ -863,8 +888,119 @@ FILE *cbm_popen(const char *cmd, const char *mode) {
|
||||
return popen(cmd, mode);
|
||||
}
|
||||
|
||||
/* Streams opened by cbm_popen_git: popen() cannot take an environment, so
|
||||
* those children are spawned here and reaped by cbm_pclose via this list. */
|
||||
typedef struct cbm_popen_git_entry {
|
||||
FILE *fp;
|
||||
pid_t pid;
|
||||
struct cbm_popen_git_entry *next;
|
||||
} cbm_popen_git_entry_t;
|
||||
|
||||
static cbm_popen_git_entry_t *g_popen_git_list = NULL;
|
||||
static pthread_mutex_t g_popen_git_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static bool cbm_fd_set_cloexec(int fd) {
|
||||
int flags = fcntl(fd, F_GETFD);
|
||||
return flags >= 0 && fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0;
|
||||
}
|
||||
|
||||
/* `/bin/sh -c cmd` with stdout on a pipe, stdin on /dev/null (never the MCP
|
||||
* transport), stderr inherited like popen(), and `envp` as the environment. */
|
||||
static pid_t cbm_popen_spawn_sh(const char *cmd, char **envp, int *read_fd) {
|
||||
int fds[2];
|
||||
if (pipe(fds) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (!cbm_fd_set_cloexec(fds[0]) || !cbm_fd_set_cloexec(fds[1])) {
|
||||
(void)close(fds[0]);
|
||||
(void)close(fds[1]);
|
||||
return -1;
|
||||
}
|
||||
posix_spawn_file_actions_t actions;
|
||||
if (posix_spawn_file_actions_init(&actions) != 0) {
|
||||
(void)close(fds[0]);
|
||||
(void)close(fds[1]);
|
||||
return -1;
|
||||
}
|
||||
/* dup2 clears close-on-exec on the child's stdout; both pipe ends
|
||||
* themselves stay close-on-exec, so no other child ever holds them. */
|
||||
bool configured =
|
||||
posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0) == 0 &&
|
||||
posix_spawn_file_actions_adddup2(&actions, fds[1], STDOUT_FILENO) == 0;
|
||||
char *const argv[] = {(char *)"sh", (char *)"-c", (char *)cmd, NULL};
|
||||
pid_t pid = -1;
|
||||
int rc = configured ? posix_spawn(&pid, "/bin/sh", &actions, NULL, argv, envp) : -1;
|
||||
(void)posix_spawn_file_actions_destroy(&actions);
|
||||
(void)close(fds[1]);
|
||||
if (rc != 0 || pid <= 0) {
|
||||
(void)close(fds[0]);
|
||||
return -1;
|
||||
}
|
||||
*read_fd = fds[0];
|
||||
return pid;
|
||||
}
|
||||
|
||||
static int cbm_popen_git_wait(pid_t pid) {
|
||||
int status = 0;
|
||||
while (waitpid(pid, &status, 0) < 0) {
|
||||
if (errno != EINTR) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
FILE *cbm_popen_git(const char *cmd) {
|
||||
if (!cmd) {
|
||||
return NULL;
|
||||
}
|
||||
/* Fail closed: without the scrubbed environment the child would inherit
|
||||
* a caller's GIT_DIR and read the wrong repository (#2003). */
|
||||
char **envp = cbm_git_child_envp();
|
||||
if (!envp) {
|
||||
return NULL;
|
||||
}
|
||||
int read_fd = -1;
|
||||
pid_t pid = cbm_popen_spawn_sh(cmd, envp, &read_fd);
|
||||
cbm_git_child_env_free(envp); /* posix_spawn copied it into the child */
|
||||
if (pid < 0) {
|
||||
return NULL;
|
||||
}
|
||||
cbm_popen_git_entry_t *entry = (cbm_popen_git_entry_t *)malloc(sizeof(*entry));
|
||||
FILE *fp = entry ? fdopen(read_fd, "r") : NULL;
|
||||
if (!fp) {
|
||||
free(entry);
|
||||
(void)close(read_fd);
|
||||
(void)cbm_popen_git_wait(pid);
|
||||
return NULL;
|
||||
}
|
||||
entry->fp = fp;
|
||||
entry->pid = pid;
|
||||
pthread_mutex_lock(&g_popen_git_lock);
|
||||
entry->next = g_popen_git_list;
|
||||
g_popen_git_list = entry;
|
||||
pthread_mutex_unlock(&g_popen_git_lock);
|
||||
return fp;
|
||||
}
|
||||
|
||||
int cbm_pclose(FILE *f) {
|
||||
return pclose(f);
|
||||
cbm_popen_git_entry_t *found = NULL;
|
||||
pthread_mutex_lock(&g_popen_git_lock);
|
||||
for (cbm_popen_git_entry_t **link = &g_popen_git_list; *link; link = &(*link)->next) {
|
||||
if ((*link)->fp == f) {
|
||||
found = *link;
|
||||
*link = found->next;
|
||||
break;
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&g_popen_git_lock);
|
||||
if (!found) {
|
||||
return pclose(f); /* opened by popen() */
|
||||
}
|
||||
pid_t pid = found->pid;
|
||||
free(found);
|
||||
(void)fclose(f);
|
||||
return cbm_popen_git_wait(pid); /* the raw wait status, as pclose() */
|
||||
}
|
||||
|
||||
FILE *cbm_fopen(const char *path, const char *mode) {
|
||||
|
||||
@@ -60,6 +60,13 @@ void cbm_closedir(cbm_dir_t *d);
|
||||
/* ── Portable popen/pclose ────────────────────────────────────── */
|
||||
|
||||
FILE *cbm_popen(const char *cmd, const char *mode);
|
||||
|
||||
/* Read-mode cbm_popen for a `git ...` command line: the child environment
|
||||
* omits git's repository-local variables (foundation/git_env.h), so an
|
||||
* inherited GIT_DIR/GIT_WORK_TREE/... can never override `git -C <repo>`.
|
||||
* The caller's own environment is untouched. Close with cbm_pclose. */
|
||||
FILE *cbm_popen_git(const char *cmd);
|
||||
|
||||
int cbm_pclose(FILE *f);
|
||||
|
||||
/* ── File operations ──────────────────────────────────────────── */
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* git_env.c — child environment for cbm's git spawns. See git_env.h.
|
||||
*/
|
||||
#include "foundation/git_env.h"
|
||||
#include "foundation/mem_core.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#else
|
||||
extern char **environ;
|
||||
#endif
|
||||
|
||||
const char *const cbm_git_repo_env_vars[CBM_GIT_REPO_ENV_VAR_COUNT] = {
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
"GIT_CONFIG",
|
||||
"GIT_CONFIG_PARAMETERS",
|
||||
"GIT_CONFIG_COUNT",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_DIR",
|
||||
"GIT_WORK_TREE",
|
||||
"GIT_IMPLICIT_WORK_TREE",
|
||||
"GIT_GRAFT_FILE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_NO_REPLACE_OBJECTS",
|
||||
"GIT_REPLACE_REF_BASE",
|
||||
"GIT_PREFIX",
|
||||
"GIT_SHALLOW_FILE",
|
||||
"GIT_COMMON_DIR",
|
||||
};
|
||||
|
||||
static char git_env_fold(char c) {
|
||||
#ifdef _WIN32
|
||||
return (c >= 'a' && c <= 'z') ? (char)(c - 'a' + 'A') : c;
|
||||
#else
|
||||
return c;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Does the name part of `entry` (up to '=' or `name_len` chars) equal `var`? */
|
||||
static bool git_env_name_equals(const char *entry, size_t name_len, const char *var) {
|
||||
size_t var_len = strlen(var);
|
||||
if (name_len != var_len) {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < var_len; i++) {
|
||||
if (git_env_fold(entry[i]) != var[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool git_env_name_is_repo_local(const char *name, size_t name_len) {
|
||||
for (size_t i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {
|
||||
if (git_env_name_equals(name, name_len, cbm_git_repo_env_vars[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool cbm_git_env_entry_is_repo_local(const char *entry) {
|
||||
if (!entry) {
|
||||
return false;
|
||||
}
|
||||
const char *eq = strchr(entry, '=');
|
||||
size_t name_len = eq ? (size_t)(eq - entry) : strlen(entry);
|
||||
return git_env_name_is_repo_local(entry, name_len);
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
/* Wide entry name → is it repository-local? Names we match are ASCII, so any
|
||||
* non-ASCII code unit is an immediate mismatch. Windows keeps per-drive cwd
|
||||
* entries ("=C:=C:\\dir") whose name starts with '='; the search for the
|
||||
* separator starts at index 1 so they are kept untouched. */
|
||||
static bool git_env_wide_entry_is_repo_local(const wchar_t *entry) {
|
||||
char name[64] = {0};
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; entry[i] && (i == 0 || entry[i] != L'='); i++) {
|
||||
if (entry[i] > 0x7F || n + 1 >= sizeof(name)) {
|
||||
return false;
|
||||
}
|
||||
name[n++] = (char)entry[i];
|
||||
}
|
||||
return git_env_name_is_repo_local(name, n);
|
||||
}
|
||||
|
||||
wchar_t *cbm_git_child_env_block(void) {
|
||||
wchar_t *current = GetEnvironmentStringsW();
|
||||
if (!current) {
|
||||
return NULL;
|
||||
}
|
||||
size_t kept = 0;
|
||||
for (const wchar_t *e = current; *e; e += wcslen(e) + 1) {
|
||||
if (!git_env_wide_entry_is_repo_local(e)) {
|
||||
kept += wcslen(e) + 1;
|
||||
}
|
||||
}
|
||||
/* +2: a block that keeps nothing still needs its double terminator. */
|
||||
wchar_t *block = (wchar_t *)cbm_alloc(CBM_MEM_CLASS_OTHER, (kept + 2) * sizeof(wchar_t));
|
||||
if (!block) {
|
||||
FreeEnvironmentStringsW(current);
|
||||
return NULL;
|
||||
}
|
||||
size_t pos = 0;
|
||||
for (const wchar_t *e = current; *e; e += wcslen(e) + 1) {
|
||||
if (!git_env_wide_entry_is_repo_local(e)) {
|
||||
size_t len = wcslen(e) + 1;
|
||||
memcpy(block + pos, e, len * sizeof(wchar_t));
|
||||
pos += len;
|
||||
}
|
||||
}
|
||||
block[pos] = L'\0';
|
||||
if (pos == 0) {
|
||||
block[1] = L'\0';
|
||||
}
|
||||
FreeEnvironmentStringsW(current);
|
||||
return block;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
char **cbm_git_child_envp(void) {
|
||||
size_t count = 0;
|
||||
size_t bytes = 0;
|
||||
for (char **e = environ; e && *e; e++) {
|
||||
if (!cbm_git_env_entry_is_repo_local(*e)) {
|
||||
count++;
|
||||
bytes += strlen(*e) + 1;
|
||||
}
|
||||
}
|
||||
size_t table = (count + 1) * sizeof(char *);
|
||||
char **envp = (char **)cbm_alloc(CBM_MEM_CLASS_OTHER, table + bytes);
|
||||
if (!envp) {
|
||||
return NULL;
|
||||
}
|
||||
char *strings = (char *)envp + table;
|
||||
size_t slot = 0;
|
||||
for (char **e = environ; e && *e && slot < count; e++) {
|
||||
if (!cbm_git_env_entry_is_repo_local(*e)) {
|
||||
size_t len = strlen(*e) + 1;
|
||||
memcpy(strings, *e, len);
|
||||
envp[slot++] = strings;
|
||||
strings += len;
|
||||
}
|
||||
}
|
||||
envp[slot] = NULL;
|
||||
return envp;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
void cbm_git_child_env_free(void *env) {
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, env);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* git_env.h — the environment cbm hands to its OWN git child processes.
|
||||
*
|
||||
* Git exports repository-local variables into hooks and some editors export
|
||||
* them into their terminals (GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, ...). They
|
||||
* take precedence over `git -C <dir>`: a cbm started from such an environment
|
||||
* would otherwise resolve every indexed project against the CALLER's repository
|
||||
* (a non-git directory reported as is_git=true, history and branch data from
|
||||
* the wrong repo). Every git spawn therefore gets a child environment with
|
||||
* exactly the variables `git rev-parse --local-env-vars` prints removed. The
|
||||
* scrub is per spawn: cbm's own environment is never modified (unsetenv in the
|
||||
* parent would race every other thread reading the environment).
|
||||
*/
|
||||
#ifndef CBM_GIT_ENV_H
|
||||
#define CBM_GIT_ENV_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <wchar.h>
|
||||
#endif
|
||||
|
||||
/* `git rev-parse --local-env-vars` (git 2.50) — the single source of truth. */
|
||||
enum { CBM_GIT_REPO_ENV_VAR_COUNT = 15 };
|
||||
extern const char *const cbm_git_repo_env_vars[CBM_GIT_REPO_ENV_VAR_COUNT];
|
||||
|
||||
/* True when a "NAME=value" environment entry names one of the variables above.
|
||||
* The name compare is case-insensitive on Windows (its environment is). */
|
||||
bool cbm_git_env_entry_is_repo_local(const char *entry);
|
||||
|
||||
#ifdef _WIN32
|
||||
/* A CREATE_UNICODE_ENVIRONMENT block: the current environment minus the
|
||||
* repository-local git variables. One allocation; release with cbm_git_child_env_free().
|
||||
* NULL on allocation/snapshot failure. */
|
||||
wchar_t *cbm_git_child_env_block(void);
|
||||
#else
|
||||
/* A NULL-terminated envp: the current environment minus the repository-local
|
||||
* git variables. Pointers and strings live in ONE allocation; release with
|
||||
* cbm_git_child_env_free(). NULL on allocation failure. */
|
||||
char **cbm_git_child_envp(void);
|
||||
#endif
|
||||
|
||||
/* Release a block from cbm_git_child_env_block / cbm_git_child_envp. NULL is a no-op. */
|
||||
void cbm_git_child_env_free(void *env);
|
||||
|
||||
#endif /* CBM_GIT_ENV_H */
|
||||
@@ -594,7 +594,15 @@ size_t cbm_mem_allocator_committed(void) {
|
||||
}
|
||||
|
||||
static _Atomic size_t g_peak_charged;
|
||||
static _Atomic size_t g_charged_for_tests; /* 0 = live reading */
|
||||
void cbm_mem_set_charged_for_tests(size_t bytes) {
|
||||
atomic_store_explicit(&g_charged_for_tests, bytes, memory_order_relaxed);
|
||||
}
|
||||
size_t cbm_mem_charged(void) {
|
||||
size_t pinned = atomic_load_explicit(&g_charged_for_tests, memory_order_relaxed);
|
||||
if (pinned != 0) {
|
||||
return pinned;
|
||||
}
|
||||
/* The OS number (phys_footprint on macOS, RSS elsewhere) is the charge for
|
||||
* everything the process maps, and the memory core's own live bytes are its
|
||||
* floor: macOS was measured under-reporting the OS number after
|
||||
|
||||
@@ -93,6 +93,14 @@ size_t cbm_mem_budget(void);
|
||||
* Never call from production code. */
|
||||
void cbm_mem_set_budget_for_tests(size_t bytes);
|
||||
|
||||
/* TEST HOOK: pin cbm_mem_charged() (and so cbm_mem_over_budget()) to `bytes`;
|
||||
* 0 restores the live reading. The charge is the process footprint, which a
|
||||
* test cannot steer, so a gate keyed to it ("extraction ended just under the
|
||||
* spill latch", #2184) is otherwise untestable. A pinned reading does not move
|
||||
* cbm_mem_peak_charged(). Callers restore 0 before their assertions. Never call
|
||||
* from production code. */
|
||||
void cbm_mem_set_charged_for_tests(size_t bytes);
|
||||
|
||||
/* Returns true if current RSS exceeds the budget. */
|
||||
bool cbm_mem_over_budget(void);
|
||||
|
||||
|
||||
@@ -310,6 +310,24 @@ bool cbm_validate_project_name(const char *name) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool cbm_is_internal_cache_db(const char *filename) {
|
||||
return filename && (strcmp(filename, CBM_CONFIG_DB_FILENAME) == 0 ||
|
||||
strcmp(filename, CBM_CROSS_REPO_DB_FILENAME) == 0);
|
||||
}
|
||||
|
||||
bool cbm_is_project_index_db(const char *filename) {
|
||||
static const char db_ext[] = ".db";
|
||||
const size_t ext_len = sizeof(db_ext) - 1;
|
||||
if (!filename) {
|
||||
return false;
|
||||
}
|
||||
size_t len = strlen(filename);
|
||||
if (len <= ext_len || strcmp(filename + len - ext_len, db_ext) != 0) {
|
||||
return false;
|
||||
}
|
||||
return !cbm_is_internal_cache_db(filename);
|
||||
}
|
||||
|
||||
int cbm_utf8_trim_partial(char *buf) {
|
||||
if (!buf) {
|
||||
return 0;
|
||||
|
||||
@@ -73,6 +73,22 @@ bool cbm_validate_shell_path_arg(const char *path);
|
||||
* Returns true if safe, false if the name could escape the cache directory. */
|
||||
bool cbm_validate_project_name(const char *name);
|
||||
|
||||
/* Internal stores that live next to the project indexes in the cache
|
||||
* directory. They are exact filenames: a project name may itself begin with
|
||||
* "_" or contain "config", so prefix/substring filters would hide real
|
||||
* projects. */
|
||||
#define CBM_CONFIG_DB_FILENAME "_config.db"
|
||||
#define CBM_CROSS_REPO_DB_FILENAME "_cross_repo.db"
|
||||
|
||||
/* True when a cache-directory entry is one of the internal stores above. */
|
||||
bool cbm_is_internal_cache_db(const char *filename);
|
||||
|
||||
/* True when a cache-directory entry is a project index: "<name>.db" with a
|
||||
* non-empty stem and not an internal store. The one predicate every
|
||||
* enumeration of the cache directory's .db files uses (list, count,
|
||||
* remove, cross-repo). */
|
||||
bool cbm_is_project_index_db(const char *filename);
|
||||
|
||||
/* Safe snprintf append: clamps offset to prevent buffer overflow on truncation.
|
||||
* When snprintf truncates, it returns what it WOULD have written, which can make
|
||||
* offset > bufsize. Next call: bufsize - offset wraps unsigned → huge → overflow.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include "compat.h" /* cbm_nanosleep */
|
||||
#include "compat_fs.h"
|
||||
#include "git_env.h" /* strip_git_repo_env: scrubbed child environment for git */
|
||||
#include "log.h"
|
||||
#include "platform.h" /* cbm_now_ms */
|
||||
#include "sanitized.h" /* CBM_SANITIZED — spawn-retry budget */
|
||||
@@ -27,8 +28,8 @@
|
||||
#include <signal.h>
|
||||
#ifdef __APPLE__
|
||||
#include <spawn.h>
|
||||
extern char **environ;
|
||||
#endif
|
||||
extern char **environ;
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
@@ -413,6 +414,10 @@ struct cbm_subprocess {
|
||||
int cancel_grace_ms;
|
||||
size_t memory_limit_bytes;
|
||||
bool delete_log_on_exit;
|
||||
bool strip_git_repo_env;
|
||||
#ifndef _WIN32
|
||||
char **envp; /* NULL => inherit environ; else the scrubbed git child env */
|
||||
#endif
|
||||
|
||||
long tail_pos;
|
||||
uint64_t last_activity_ms;
|
||||
@@ -463,6 +468,9 @@ static void cbm_subprocess_free_config(cbm_subprocess_t *process) {
|
||||
free(process->bin);
|
||||
free(process->windows_cmd_payload);
|
||||
free(process->log_file);
|
||||
#ifndef _WIN32
|
||||
cbm_git_child_env_free(process->envp);
|
||||
#endif
|
||||
free(process);
|
||||
}
|
||||
|
||||
@@ -531,6 +539,18 @@ static cbm_subprocess_t *cbm_subprocess_copy_opts(const cbm_proc_opts_t *opts) {
|
||||
}
|
||||
process->memory_limit_bytes = opts->memory_limit_bytes;
|
||||
process->delete_log_on_exit = opts->delete_log_on_exit;
|
||||
process->strip_git_repo_env = opts->strip_git_repo_env;
|
||||
#ifndef _WIN32
|
||||
/* Built before the spawn: the fork child may only assign it (malloc is
|
||||
* not async-signal-safe there). Fail closed rather than inherit GIT_DIR. */
|
||||
if (opts->strip_git_repo_env) {
|
||||
process->envp = cbm_git_child_envp();
|
||||
if (!process->envp) {
|
||||
cbm_subprocess_free_config(process);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
atomic_init(&process->lifecycle, CBM_SUBPROCESS_ACTIVE);
|
||||
cbm_subprocess_result_init(&process->result);
|
||||
return process;
|
||||
@@ -746,8 +766,15 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {
|
||||
ZeroMemory(&child, sizeof(child));
|
||||
DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP |
|
||||
CREATE_NO_WINDOW;
|
||||
BOOL created = CreateProcessW(wbin, wcmdline, NULL, NULL, TRUE, flags, NULL, NULL,
|
||||
/* Fail closed: a git child must never inherit a caller's GIT_DIR. */
|
||||
wchar_t *env = process->strip_git_repo_env ? cbm_git_child_env_block() : NULL;
|
||||
if (env) {
|
||||
flags |= CREATE_UNICODE_ENVIRONMENT;
|
||||
}
|
||||
BOOL created = (!process->strip_git_repo_env || env) &&
|
||||
CreateProcessW(wbin, wcmdline, NULL, NULL, TRUE, flags, (LPVOID)env, NULL,
|
||||
&startup.StartupInfo, &child);
|
||||
cbm_git_child_env_free(env); /* CreateProcessW copied the block into the child */
|
||||
cbm_win_close_spawn_handles(nul, log, attrs, attrs_init);
|
||||
free(wbin);
|
||||
free(wcmdline);
|
||||
@@ -1066,6 +1093,9 @@ static void cbm_posix_child_exec(cbm_subprocess_t *process, int input, int outpu
|
||||
for (int fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
|
||||
(void)close(fd);
|
||||
}
|
||||
if (process->envp) {
|
||||
environ = process->envp; /* execvp passes environ to the new image */
|
||||
}
|
||||
/* A fixed literal tool name (for example "git" or "curl") uses the
|
||||
* caller's normal PATH without introducing a shell. An explicit path
|
||||
* still has execvp's exact-path semantics because it contains '/'. */
|
||||
@@ -1143,8 +1173,9 @@ static int cbm_posix_spawn_apple(cbm_subprocess_t *process, int input, int outpu
|
||||
posix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO) == 0 &&
|
||||
posix_spawn_file_actions_adddup2(&actions, output, STDERR_FILENO) == 0;
|
||||
pid_t pid = -1;
|
||||
int rc =
|
||||
configured ? posix_spawnp(&pid, process->bin, &actions, &attr, process->argv, environ) : -1;
|
||||
int rc = configured ? posix_spawnp(&pid, process->bin, &actions, &attr, process->argv,
|
||||
process->envp ? process->envp : environ)
|
||||
: -1;
|
||||
(void)posix_spawn_file_actions_destroy(&actions);
|
||||
(void)posix_spawnattr_destroy(&attr);
|
||||
if (configured && rc == 0 && pid > 0) {
|
||||
|
||||
@@ -74,6 +74,9 @@ typedef struct {
|
||||
size_t memory_limit_bytes; /* Windows-only hard commit limit for the entire Job Object;
|
||||
* 0 => no OS-enforced memory limit */
|
||||
bool delete_log_on_exit; /* unlink log_file after reaping */
|
||||
bool strip_git_repo_env; /* child env omits git's repository-local variables
|
||||
* (foundation/git_env.h) — set for every git spawn so
|
||||
* an inherited GIT_DIR never overrides `git -C` */
|
||||
} cbm_proc_opts_t;
|
||||
|
||||
#define CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS 1000
|
||||
|
||||
@@ -65,7 +65,7 @@ static int git_capture(const char *repo_path, const char *git_args, char **out)
|
||||
return CBM_NOT_FOUND;
|
||||
}
|
||||
|
||||
FILE *fp = cbm_popen(cmd, "r");
|
||||
FILE *fp = cbm_popen_git(cmd);
|
||||
if (!fp) {
|
||||
return CBM_NOT_FOUND;
|
||||
}
|
||||
|
||||
+503
-67
@@ -428,6 +428,60 @@ char *cbm_mcp_text_result(const char *text, bool is_error) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Rebuild the payload text with the notice attached; NULL when the payload
|
||||
* cannot be rewritten. The result is a memory-core block (class other) on
|
||||
* both branches, so the caller has one release path. */
|
||||
static char *tool_result_payload_with_notice(const char *payload, const char *notice) {
|
||||
yyjson_doc *payload_doc = yyjson_read(payload, strlen(payload), 0);
|
||||
yyjson_val *payload_root = payload_doc ? yyjson_doc_get_root(payload_doc) : NULL;
|
||||
char *rewritten = NULL;
|
||||
if (payload_root && yyjson_is_obj(payload_root)) {
|
||||
yyjson_mut_doc *copy = yyjson_doc_mut_copy(payload_doc, NULL);
|
||||
yyjson_mut_val *copy_root = copy ? yyjson_mut_doc_get_root(copy) : NULL;
|
||||
char *written = copy_root && yyjson_mut_obj_add_strcpy(copy, copy_root, "notice", notice)
|
||||
? yy_doc_to_str(copy)
|
||||
: NULL;
|
||||
rewritten = written ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, written) : NULL;
|
||||
safe_free(written); /* yyjson's writer block, not a core block */
|
||||
yyjson_mut_doc_free(copy);
|
||||
} else {
|
||||
size_t payload_len = strlen(payload);
|
||||
size_t notice_len = strlen(notice);
|
||||
rewritten = cbm_alloc(CBM_MEM_CLASS_OTHER, payload_len + notice_len + 3U);
|
||||
if (rewritten) {
|
||||
memcpy(rewritten, payload, payload_len);
|
||||
memcpy(rewritten + payload_len, "\n\n", 2U);
|
||||
memcpy(rewritten + payload_len + 2U, notice, notice_len + 1U);
|
||||
}
|
||||
}
|
||||
yyjson_doc_free(payload_doc);
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
char *cbm_mcp_tool_result_add_notice(char *result, const char *notice) {
|
||||
if (!result || !notice || !notice[0]) {
|
||||
return result;
|
||||
}
|
||||
yyjson_doc *doc = yyjson_read(result, strlen(result), 0);
|
||||
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
|
||||
yyjson_val *content = root && yyjson_is_obj(root) ? yyjson_obj_get(root, "content") : NULL;
|
||||
yyjson_val *first = content && yyjson_is_arr(content) ? yyjson_arr_get_first(content) : NULL;
|
||||
yyjson_val *text = first && yyjson_is_obj(first) ? yyjson_obj_get(first, "text") : NULL;
|
||||
yyjson_val *is_error = root && yyjson_is_obj(root) ? yyjson_obj_get(root, "isError") : NULL;
|
||||
char *payload = text && yyjson_is_str(text)
|
||||
? tool_result_payload_with_notice(yyjson_get_str(text), notice)
|
||||
: NULL;
|
||||
char *rebuilt =
|
||||
payload ? cbm_mcp_text_result(payload, is_error && yyjson_get_bool(is_error)) : NULL;
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, payload);
|
||||
yyjson_doc_free(doc);
|
||||
if (!rebuilt) {
|
||||
return result;
|
||||
}
|
||||
safe_free(result); /* the caller's tool result, not a core block */
|
||||
return rebuilt;
|
||||
}
|
||||
|
||||
bool cbm_mcp_cancel_request_matches(const char *params_json, int64_t active_id,
|
||||
const char *active_id_str) {
|
||||
if (!params_json) {
|
||||
@@ -466,7 +520,11 @@ typedef struct {
|
||||
static const tool_def_t TOOLS[] = {
|
||||
{"index_repository",
|
||||
"Index a repository. full/moderate add semantics; fast omits them; cross-repo-intelligence "
|
||||
"links services. Reports coverage gaps.",
|
||||
"links services. Reports coverage gaps. Waits for the whole index by default; a large repo "
|
||||
"can exceed a client's per-call deadline. async:true starts (or joins) the index in the "
|
||||
"daemon and returns at once; poll with status:true (same repo_path) until state is "
|
||||
"succeeded, failed or cancelled. async needs a daemon that outlives the call: an MCP session "
|
||||
"or `daemon start`.",
|
||||
"{\"type\":\"object\",\"properties\":{\"repo_path\":{\"type\":\"string\",\"description\":"
|
||||
"\"Repository path\"},"
|
||||
"\"mode\":{\"type\":\"string\","
|
||||
@@ -478,7 +536,14 @@ static const tool_def_t TOOLS[] = {
|
||||
"\"name\":{\"type\":\"string\",\"description\":"
|
||||
"\"Name override; Non-ASCII bytes are encoded; unsafe characters normalized.\"},"
|
||||
"\"persistence\":{\"type\":\"boolean\",\"default\":false,\"description\":"
|
||||
"\"Write .codebase-memory/graph.db.zst.\"}"
|
||||
"\"Write .codebase-memory/graph.db.zst.\"},"
|
||||
"\"async\":{\"type\":\"boolean\",\"default\":false,\"description\":"
|
||||
"\"Start the index in the background and return immediately; it keeps running if this "
|
||||
"call is cancelled or times out. Not with status or cross-repo-intelligence. Refused for a "
|
||||
"one-shot cli call that is the only client of a temporary daemon (run daemon start).\"},"
|
||||
"\"status\":{\"type\":\"boolean\",\"default\":false,\"description\":"
|
||||
"\"Report the running or last index job (queued/running/succeeded/failed/cancelled) "
|
||||
"instead of indexing. Pass the same repo_path (and name, if any) as the index call.\"}"
|
||||
"},\"required\":[\"repo_path\"]}"},
|
||||
|
||||
{"search_graph",
|
||||
@@ -769,14 +834,19 @@ typedef struct {
|
||||
* left in place, never quarantined or rebuilt — quarantine/rebuild is reserved
|
||||
* for write-side opens (index_repository, manage_adr writes). That is what
|
||||
* makes readOnlyHint=true honest for them and lets plan-mode clients expose
|
||||
* them (the "read-only analysis tools" surface described in #1100). */
|
||||
* them (the "read-only analysis tools" surface described in #1100).
|
||||
* get_file_outline reads through the same resolve_store() path, and
|
||||
* ingest_traces only validates and counts its input (edge creation is not
|
||||
* implemented), so both are read-only too (#2118). Only handlers that write
|
||||
* user-visible state -- index_repository, manage_adr, delete_project -- may
|
||||
* clear readOnlyHint. */
|
||||
static const tool_annotation_def_t TOOL_ANNOTATIONS[] = {
|
||||
{"index_repository", false, false, true, false},
|
||||
{"search_graph", true, false, true, false},
|
||||
{"query_graph", true, false, true, false},
|
||||
{"trace_path", true, false, true, false},
|
||||
{"get_code_snippet", true, false, true, false},
|
||||
{"get_file_outline", false, true, true, false},
|
||||
{"get_file_outline", true, false, true, false},
|
||||
{"get_graph_schema", true, false, true, false},
|
||||
{"compare_graphs", true, false, true, false},
|
||||
{"get_architecture", true, false, true, false},
|
||||
@@ -787,7 +857,7 @@ static const tool_annotation_def_t TOOL_ANNOTATIONS[] = {
|
||||
{"check_index_coverage", true, false, true, false},
|
||||
{"detect_changes", true, false, true, false},
|
||||
{"manage_adr", false, true, false, false},
|
||||
{"ingest_traces", false, false, false, false},
|
||||
{"ingest_traces", true, false, true, false},
|
||||
};
|
||||
|
||||
static const tool_annotation_def_t *mcp_tool_annotations(const char *name) {
|
||||
@@ -1481,24 +1551,50 @@ static bool repo_path_is_absolute(const char *path) {
|
||||
#endif
|
||||
}
|
||||
|
||||
bool cbm_validate_project_name(const char *project);
|
||||
|
||||
static bool has_non_ascii_byte(const char *s) {
|
||||
for (; *s; s++) {
|
||||
if ((unsigned char)*s >= 0x80) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* #1827: a bare non-ASCII selector, typically the real folder name of a repo
|
||||
* under a CJK path, is encoded exactly like the path segment it came from
|
||||
* (non-ASCII bytes -> hex, #571), so the exact/tail lookup matches the stored
|
||||
* identity. Stored names never change; ASCII selectors keep their existing
|
||||
* validation; a selector that collapses to the "root" fallback is left alone
|
||||
* so it never selects the root project. */
|
||||
static bool bare_project_encoding_usable(const char *encoded) {
|
||||
return strcmp(encoded, "root") != 0 && cbm_validate_project_name(encoded);
|
||||
}
|
||||
|
||||
static char *normalize_project_arg(char *project) {
|
||||
if (!project || (!strchr(project, '/') && !strchr(project, '\\'))) {
|
||||
if (!project) {
|
||||
return project;
|
||||
}
|
||||
|
||||
project = canonicalize_repo_path_if_exists(project);
|
||||
char *normalized = cbm_project_name_from_path(project);
|
||||
if (normalized) {
|
||||
free(project);
|
||||
return normalized;
|
||||
char *normalized = NULL;
|
||||
bool bare = !strchr(project, '/') && !strchr(project, '\\');
|
||||
if (bare) {
|
||||
if (has_non_ascii_byte(project)) {
|
||||
normalized = cbm_project_name_sanitize(project);
|
||||
}
|
||||
} else {
|
||||
project = canonicalize_repo_path_if_exists(project);
|
||||
normalized = cbm_project_name_from_path(project);
|
||||
}
|
||||
return project;
|
||||
/* Keep exactly one of the two strings and release the other. */
|
||||
bool use_normalized = normalized && (!bare || bare_project_encoding_usable(normalized));
|
||||
free(use_normalized ? project : normalized);
|
||||
return use_normalized ? normalized : project;
|
||||
}
|
||||
|
||||
/* Forward decls — defined below alongside store resolution. */
|
||||
static const char *cache_dir(char *buf, size_t bufsz);
|
||||
static bool is_project_db_file(const char *name, size_t len);
|
||||
bool cbm_validate_project_name(const char *project);
|
||||
|
||||
/* #1025: agents naturally pass the repo FOLDER name ("codebase-memory-mcp"),
|
||||
* but indexed project names derive from the full path
|
||||
@@ -1660,6 +1756,8 @@ struct cbm_mcp_server {
|
||||
struct cbm_config *config; /* external config ref (not owned) */
|
||||
cbm_mcp_index_executor_fn index_executor;
|
||||
void *index_executor_context;
|
||||
cbm_mcp_index_status_fn index_status_provider; /* #2144; NULL outside the daemon */
|
||||
void *index_status_context;
|
||||
cbm_proc_log_cb index_log_callback;
|
||||
void *index_log_context;
|
||||
cbm_mcp_project_mutation_begin_fn mutation_begin;
|
||||
@@ -1815,6 +1913,14 @@ void cbm_mcp_server_set_index_executor(cbm_mcp_server_t *srv, cbm_mcp_index_exec
|
||||
}
|
||||
}
|
||||
|
||||
void cbm_mcp_server_set_index_status_provider(cbm_mcp_server_t *srv,
|
||||
cbm_mcp_index_status_fn provider, void *context) {
|
||||
if (srv) {
|
||||
srv->index_status_provider = provider;
|
||||
srv->index_status_context = context;
|
||||
}
|
||||
}
|
||||
|
||||
void cbm_mcp_server_set_index_log_callback(cbm_mcp_server_t *srv, cbm_proc_log_cb callback,
|
||||
void *context) {
|
||||
if (srv) {
|
||||
@@ -9178,6 +9284,9 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {
|
||||
if (node_count == 0) {
|
||||
cbm_node_t qn_node = {0};
|
||||
if (cbm_store_find_node_by_qn(store, project, func_name, &qn_node) == CBM_STORE_OK) {
|
||||
/* A zero-row name lookup still returns its allocated (empty)
|
||||
* array; release it before the fallback replaces the pointer. */
|
||||
cbm_store_free_nodes(nodes, 0);
|
||||
nodes = malloc(sizeof(cbm_node_t));
|
||||
if (nodes) {
|
||||
nodes[0] = qn_node;
|
||||
@@ -9947,10 +10056,16 @@ static char *handle_cross_repo_mode(cbm_mcp_server_t *srv, const char *repo_path
|
||||
free(lease_keys);
|
||||
yyjson_doc_free(jdoc);
|
||||
|
||||
if (result.failed) {
|
||||
if (result.no_targets || result.failed) {
|
||||
free(project);
|
||||
return cbm_mcp_text_result(
|
||||
"cross-repo source or target project is missing, invalid, or not indexed", true);
|
||||
result.no_targets
|
||||
? "cross-repo-intelligence resolved zero target projects: no indexed project "
|
||||
"other than the source matched target_projects. Index the other service first "
|
||||
"(run list_projects to see what is indexed); existing cross-repo edges were "
|
||||
"left unchanged."
|
||||
: "cross-repo source or target project is missing, invalid, or not indexed",
|
||||
true);
|
||||
}
|
||||
|
||||
int total = result.http_edges + result.async_edges + result.channel_edges + result.grpc_edges +
|
||||
@@ -10494,7 +10609,8 @@ static char *build_worker_unsafe_terminal_response(const char *args, cbm_proc_ou
|
||||
yyjson_mut_obj_add_str(
|
||||
doc, root, "hint",
|
||||
cancellation_requested
|
||||
? "Indexing worker was cancelled. No in-process retry was started."
|
||||
? "Indexing worker was cancelled. No in-process retry was "
|
||||
"started. " CBM_MCP_INDEX_ASYNC_HINT
|
||||
: "Indexing worker process-tree containment failed. No in-process retry was "
|
||||
"started; inspect daemon logs.");
|
||||
if (repo_path) {
|
||||
@@ -11044,8 +11160,12 @@ static bool resolve_session_repo_path(cbm_mcp_server_t *srv, char **repo_path) {
|
||||
}
|
||||
|
||||
/* Preserve every index option while replacing all caller-supplied repo_path
|
||||
* keys with the one canonical path that was actually authorized. */
|
||||
* keys with the one canonical path that was actually authorized. A non-empty
|
||||
* project_name likewise replaces any caller "name" (#2134: the project key the
|
||||
* parent resolved for this root travels to the daemon job / worker verbatim,
|
||||
* so lease key and written index cannot diverge). */
|
||||
static char *index_args_with_repo_path(const char *args, const char *canonical_repo_path,
|
||||
const char *project_name,
|
||||
const cbm_index_resource_policy_t *policy) {
|
||||
if (!args || !canonical_repo_path || !policy) {
|
||||
return NULL;
|
||||
@@ -11070,7 +11190,22 @@ static char *index_args_with_repo_path(const char *args, const char *canonical_r
|
||||
while (yyjson_mut_obj_get(copy_root, "_cbm_index_policy")) {
|
||||
(void)yyjson_mut_obj_remove_key(copy_root, "_cbm_index_policy");
|
||||
}
|
||||
if (!yyjson_mut_obj_add_strcpy(copy, copy_root, "repo_path", canonical_repo_path) ||
|
||||
/* #2144: async/status choose how the caller waits, not what is indexed.
|
||||
* They never reach the worker, and an async request coalesces with an
|
||||
* identical synchronous one instead of being refused as an options
|
||||
* conflict. */
|
||||
static const char *const call_mode_keys[] = {"async", "status"};
|
||||
for (size_t i = 0; i < sizeof(call_mode_keys) / sizeof(call_mode_keys[0]); i++) {
|
||||
while (yyjson_mut_obj_get(copy_root, call_mode_keys[i])) {
|
||||
(void)yyjson_mut_obj_remove_key(copy_root, call_mode_keys[i]);
|
||||
}
|
||||
}
|
||||
bool has_name = project_name && project_name[0];
|
||||
while (has_name && yyjson_mut_obj_get(copy_root, "name")) {
|
||||
(void)yyjson_mut_obj_remove_key(copy_root, "name");
|
||||
}
|
||||
if ((has_name && !yyjson_mut_obj_add_strcpy(copy, copy_root, "name", project_name)) ||
|
||||
!yyjson_mut_obj_add_strcpy(copy, copy_root, "repo_path", canonical_repo_path) ||
|
||||
!cbm_mcp_index_policy_add_to_args(copy, copy_root, policy)) {
|
||||
yyjson_mut_doc_free(copy);
|
||||
return NULL;
|
||||
@@ -11123,6 +11258,117 @@ static bool project_db_is_servable(const char *project, const char *db_path) {
|
||||
return servable;
|
||||
}
|
||||
|
||||
/* #2134: an index_repository call without `name` derived the project key from
|
||||
* the path alone, so re-indexing a root that was first indexed under an
|
||||
* explicit name silently forked a second index (same root_path, path-derived
|
||||
* name) and left the original stale while it kept being served. Resolve the
|
||||
* key from the indexes already on disk instead:
|
||||
* - the path-derived project exists -> keep it (unchanged path);
|
||||
* - exactly one other project owns this root -> adopt its name (update it);
|
||||
* - several other projects own this root -> ambiguous: fail loudly,
|
||||
* naming them, never guess;
|
||||
* - none -> first index, derived name.
|
||||
* Roots compare as stored: both sides are the canonical repo path. Returns
|
||||
* false only for the ambiguous / allocation-failure case, with *error_out set
|
||||
* to a heap message; *owner_out is a heap name or NULL. */
|
||||
static bool index_root_owner_append(char **list, size_t *len, size_t *cap, const char *name) {
|
||||
size_t need = *len + strlen(name) + 3;
|
||||
if (need > *cap) {
|
||||
size_t grown_cap = need * 2;
|
||||
char *grown = cbm_realloc(CBM_MEM_CLASS_OTHER, *list, grown_cap);
|
||||
if (!grown) {
|
||||
return false;
|
||||
}
|
||||
*list = grown;
|
||||
*cap = grown_cap;
|
||||
}
|
||||
*len += (size_t)snprintf(*list + *len, *cap - *len, "%s%s", *len ? ", " : "", name);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool index_root_owner_resolve(const char *repo_path, char **owner_out, char **error_out) {
|
||||
*owner_out = NULL;
|
||||
*error_out = NULL;
|
||||
char *derived = cbm_project_name_from_path(repo_path);
|
||||
if (!derived) {
|
||||
return true; /* the caller reports the derivation failure itself */
|
||||
}
|
||||
char derived_db[CBM_SZ_1K];
|
||||
project_db_path(derived, derived_db, sizeof(derived_db));
|
||||
if (derived_db[0] && cbm_file_exists(derived_db)) {
|
||||
safe_free(derived);
|
||||
return true; /* fast path: the path-derived project is already on disk */
|
||||
}
|
||||
char dir_path[CBM_SZ_1K];
|
||||
cache_dir(dir_path, sizeof(dir_path));
|
||||
cbm_dir_t *d = cbm_opendir(dir_path);
|
||||
if (!d) {
|
||||
safe_free(derived);
|
||||
return true;
|
||||
}
|
||||
char *owner = NULL;
|
||||
char *owners = NULL;
|
||||
size_t owners_len = 0;
|
||||
size_t owners_cap = 0;
|
||||
int owner_count = 0;
|
||||
bool derived_exists = false;
|
||||
bool ok = true;
|
||||
cbm_dirent_t *entry;
|
||||
while (ok && !derived_exists && (entry = cbm_readdir(d)) != NULL) {
|
||||
size_t len = strlen(entry->name);
|
||||
if (!is_project_db_file(entry->name, len)) {
|
||||
continue;
|
||||
}
|
||||
mcp_project_record_t record = {0};
|
||||
project_record_status_t status =
|
||||
read_project_record_identity(dir_path, entry->name, 0, &record);
|
||||
if (status == PROJECT_RECORD_OOM) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
if (status != PROJECT_RECORD_OK) {
|
||||
continue;
|
||||
}
|
||||
if (strcmp(record.name, derived) == 0) {
|
||||
derived_exists = true;
|
||||
} else if (strcmp(record.root_path, repo_path) == 0) {
|
||||
owner_count++;
|
||||
ok = index_root_owner_append(&owners, &owners_len, &owners_cap, record.name);
|
||||
if (owner_count == 1 && ok) {
|
||||
owner = heap_strdup(record.name);
|
||||
ok = owner != NULL;
|
||||
}
|
||||
}
|
||||
project_record_clear(&record);
|
||||
}
|
||||
cbm_closedir(d);
|
||||
safe_free(derived);
|
||||
|
||||
if (ok && !derived_exists && owner_count == 1) {
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, owners);
|
||||
*owner_out = owner;
|
||||
return true;
|
||||
}
|
||||
safe_free(owner);
|
||||
if (ok && (derived_exists || owner_count == 0)) {
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, owners);
|
||||
return true;
|
||||
}
|
||||
char msg[CBM_SZ_4K];
|
||||
if (ok) {
|
||||
snprintf(msg, sizeof(msg),
|
||||
"several indexed projects share root_path %s: %s. Pass name=<project> to "
|
||||
"choose which one to re-index (or delete_project the stale ones).",
|
||||
repo_path, owners);
|
||||
} else {
|
||||
snprintf(msg, sizeof(msg), "out of memory while resolving the project for root_path %s",
|
||||
repo_path);
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, owners);
|
||||
*error_out = heap_strdup(msg);
|
||||
return false;
|
||||
}
|
||||
|
||||
/* 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
|
||||
@@ -11133,7 +11379,122 @@ static void index_args_free(char *repo_path, char *mode_str, char *name_override
|
||||
free(name_override);
|
||||
}
|
||||
|
||||
/* #2144: async and status are strict booleans. A present non-boolean value is
|
||||
* refused rather than read as false, so "async":"true" never silently blocks
|
||||
* for the whole index. */
|
||||
static bool index_call_mode_arg(const char *args, const char *key, bool *value_out) {
|
||||
*value_out = false;
|
||||
yyjson_doc *doc = args ? yyjson_read(args, strlen(args), 0) : NULL;
|
||||
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
|
||||
yyjson_val *value = root && yyjson_is_obj(root) ? yyjson_obj_get(root, key) : NULL;
|
||||
bool valid = !value || yyjson_is_bool(value);
|
||||
*value_out = valid && value && yyjson_get_bool(value);
|
||||
yyjson_doc_free(doc);
|
||||
return valid;
|
||||
}
|
||||
|
||||
/* The project key a status query names: an explicit name override wins (the
|
||||
* key the index call used), then repo_path resolved exactly as for indexing
|
||||
* (session root, canonical form, workspace boundary, and the #2134 root owner
|
||||
* an unnamed start adopts), then a known project alias. NULL with *error_out
|
||||
* set when none identifies a project. */
|
||||
static char *index_status_project_key(cbm_mcp_server_t *srv, const char *args, char *error_out,
|
||||
size_t error_size) {
|
||||
char *name = cbm_mcp_get_string_arg(args, "name");
|
||||
if (name && name[0]) {
|
||||
char *key = cbm_project_name_from_path(name);
|
||||
safe_free(name);
|
||||
return key;
|
||||
}
|
||||
safe_free(name);
|
||||
char *repo_path = cbm_mcp_get_string_arg(args, "repo_path");
|
||||
if (!repo_path) {
|
||||
char *project = get_project_arg(args);
|
||||
if (!project) {
|
||||
(void)snprintf(error_out, error_size,
|
||||
"status needs the repo_path (or name) the index call used");
|
||||
}
|
||||
return project;
|
||||
}
|
||||
cbm_normalize_path_sep(repo_path);
|
||||
if (!resolve_session_repo_path(srv, &repo_path)) {
|
||||
safe_free(repo_path);
|
||||
(void)snprintf(error_out, error_size, "failed to resolve repo_path");
|
||||
return NULL;
|
||||
}
|
||||
repo_path = canonicalize_repo_path_if_exists(repo_path);
|
||||
const char *allowed_root =
|
||||
srv->allowed_root_policy_set ? srv->allowed_root : getenv("CBM_ALLOWED_ROOT");
|
||||
if (repo_path && repo_path[0] &&
|
||||
!cbm_workspace_root_allowed(repo_path, cbm_workspace_home_dir(), cbm_workspace_cache_dir(),
|
||||
allowed_root, error_out, error_size)) {
|
||||
safe_free(repo_path);
|
||||
return NULL;
|
||||
}
|
||||
/* An unnamed start of a root another project owns keys its job by that
|
||||
* owner (#2134), so the poll naming the same repo_path must resolve the
|
||||
* same owner, and fail on the same ambiguity, or it never finds the job. */
|
||||
char *owner = NULL;
|
||||
char *owner_error = NULL;
|
||||
if (repo_path && repo_path[0] && !index_root_owner_resolve(repo_path, &owner, &owner_error)) {
|
||||
(void)snprintf(error_out, error_size, "%s",
|
||||
owner_error ? owner_error : "could not resolve index project name");
|
||||
safe_free(owner_error);
|
||||
safe_free(repo_path);
|
||||
return NULL;
|
||||
}
|
||||
const char *key_source = owner ? owner : repo_path;
|
||||
char *key = key_source ? cbm_project_name_from_path(key_source) : NULL;
|
||||
safe_free(owner);
|
||||
safe_free(repo_path);
|
||||
if (!key) {
|
||||
(void)snprintf(error_out, error_size, "could not resolve index project name");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/* index_repository(status: true): report the project's running or most recent
|
||||
* index job without starting one. Job state lives in the daemon's job
|
||||
* registry; a server without one (CLI index worker, embedder) has no job that
|
||||
* could outlive a call, so it refuses instead of guessing. */
|
||||
static char *handle_index_repository_status(cbm_mcp_server_t *srv, const char *args) {
|
||||
if (!srv->index_status_provider) {
|
||||
return cbm_mcp_text_result("index_repository status needs the daemon-backed MCP server; "
|
||||
"this in-process server tracks no index jobs",
|
||||
true);
|
||||
}
|
||||
char error[CBM_SZ_4K] = {0}; /* the #2134 ambiguity error lists every owner */
|
||||
char *project = index_status_project_key(srv, args, error, sizeof(error));
|
||||
if (!project) {
|
||||
return cbm_mcp_text_result(error[0] ? error : "could not resolve index project name", true);
|
||||
}
|
||||
char *result = srv->index_status_provider(srv->index_status_context, project);
|
||||
safe_free(project);
|
||||
return result ? result : cbm_mcp_text_result("index job status is unavailable", true);
|
||||
}
|
||||
|
||||
static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
bool async_mode = false;
|
||||
bool status_mode = false;
|
||||
if (!index_call_mode_arg(args, "async", &async_mode) ||
|
||||
!index_call_mode_arg(args, "status", &status_mode)) {
|
||||
return cbm_mcp_text_result("async and status must be booleans", true);
|
||||
}
|
||||
if (async_mode && status_mode) {
|
||||
return cbm_mcp_text_result(
|
||||
"async and status are exclusive: start with async: true, then poll with status: true",
|
||||
true);
|
||||
}
|
||||
if (status_mode) {
|
||||
return handle_index_repository_status(srv, args);
|
||||
}
|
||||
if (async_mode && !srv->index_executor) {
|
||||
return cbm_mcp_text_result("index_repository async needs the daemon-backed MCP server: "
|
||||
"this in-process server has no process that outlives the call; "
|
||||
"call without async",
|
||||
true);
|
||||
}
|
||||
|
||||
char *repo_path = cbm_mcp_get_string_arg(args, "repo_path");
|
||||
char *mode_str = cbm_mcp_get_string_arg(args, "mode");
|
||||
char *name_override = cbm_mcp_get_string_arg(args, "name");
|
||||
@@ -11175,11 +11536,37 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
}
|
||||
|
||||
if (mode_str && strcmp(mode_str, "cross-repo-intelligence") == 0) {
|
||||
if (async_mode) {
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result(
|
||||
"async is not supported for mode cross-repo-intelligence (it runs no index job)",
|
||||
true);
|
||||
}
|
||||
char *result = handle_cross_repo_mode(srv, repo_path, name_override, args);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* #2134 applies to re-indexing only. Cross-repo mode reads an existing
|
||||
* source index and never writes one; adopting a root owner there could
|
||||
* turn one of its own named targets into the source. */
|
||||
if ((!name_override || !name_override[0]) && repo_path && repo_path[0]) {
|
||||
char *owner = NULL;
|
||||
char *owner_error = NULL;
|
||||
if (!index_root_owner_resolve(repo_path, &owner, &owner_error)) {
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
char *result = cbm_mcp_text_result(
|
||||
owner_error ? owner_error : "could not resolve index project name", true);
|
||||
safe_free(owner_error);
|
||||
return result;
|
||||
}
|
||||
if (owner) {
|
||||
cbm_log_info("index.root_owner_reused", "root", repo_path, "project", owner);
|
||||
safe_free(name_override);
|
||||
name_override = owner;
|
||||
}
|
||||
}
|
||||
|
||||
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))) {
|
||||
@@ -11190,10 +11577,11 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
/* A daemon session delegates the one physical write to its shared job
|
||||
* registry only after path canonicalization and workspace authorization. */
|
||||
if (srv->index_executor) {
|
||||
char *worker_args = index_args_with_repo_path(args, repo_path, &resource_policy);
|
||||
char *coordinated =
|
||||
worker_args ? srv->index_executor(srv->index_executor_context, repo_path, worker_args)
|
||||
: NULL;
|
||||
char *worker_args =
|
||||
index_args_with_repo_path(args, repo_path, name_override, &resource_policy);
|
||||
char *coordinated = worker_args ? srv->index_executor(srv->index_executor_context,
|
||||
repo_path, worker_args, async_mode)
|
||||
: NULL;
|
||||
free(worker_args);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return coordinated ? coordinated
|
||||
@@ -11218,7 +11606,8 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
* installs the same guard before running the in-process pipeline. A marked
|
||||
* host fails closed if preparation or worker startup cannot complete. */
|
||||
if (cbm_index_supervisor_should_wrap()) {
|
||||
char *worker_args = index_args_with_repo_path(args, repo_path, &resource_policy);
|
||||
char *worker_args =
|
||||
index_args_with_repo_path(args, repo_path, name_override, &resource_policy);
|
||||
if (!worker_args) {
|
||||
free(mutation_project);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
@@ -11249,7 +11638,8 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
|
||||
mcp_project_mutation_end(srv, mutation_project);
|
||||
free(mutation_project);
|
||||
index_args_free(repo_path, mode_str, name_override);
|
||||
return cbm_mcp_text_result("index operation cancelled for this request", true);
|
||||
return cbm_mcp_text_result(
|
||||
"index operation cancelled for this request. " CBM_MCP_INDEX_ASYNC_HINT, true);
|
||||
}
|
||||
|
||||
cbm_index_mode_t mode = CBM_MODE_FULL;
|
||||
@@ -14442,7 +14832,7 @@ static bool compile_path_filter(const char *filter, cbm_regex_t *re) {
|
||||
static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(
|
||||
cbm_mcp_server_t *srv, const char *command, char output_path[CBM_SZ_2K], size_t output_limit,
|
||||
uint64_t deadline_ms, bool deadline_enabled, bool deadline_latched, bool exit_one_is_no_match,
|
||||
cbm_proc_result_t *result_out);
|
||||
bool git_child, cbm_proc_result_t *result_out);
|
||||
|
||||
static char *search_code_timeout_result(void) {
|
||||
static const char message[] = "search_code scan exceeded its execution deadline";
|
||||
@@ -14783,7 +15173,8 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
|
||||
srv->search_scan_command_override ? srv->search_scan_command_override : cmd;
|
||||
mcp_scan_cause_t scan_cause = mcp_run_shell_command_cancellable_bounded(
|
||||
srv, scan_command, output_path, scan_output_limit, scan_deadline_ms, true,
|
||||
scan_deadline_latched, /*exit_one_is_no_match=*/false, &scan_result);
|
||||
scan_deadline_latched, /*exit_one_is_no_match=*/false, /*git_child=*/false,
|
||||
&scan_result);
|
||||
/* Both POSIX commands wrap grep and map its no-match status to 0, so any
|
||||
* non-zero exit (a failed find/sort, an unreadable operand, a broken
|
||||
* grep) is an incomplete scan and fails closed. */
|
||||
@@ -15143,7 +15534,7 @@ static mcp_scan_cause_t mcp_scan_pre_spawn_cause(cbm_mcp_server_t *srv, const ch
|
||||
static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(
|
||||
cbm_mcp_server_t *srv, const char *command, char output_path[CBM_SZ_2K], size_t output_limit,
|
||||
uint64_t deadline_ms, bool deadline_enabled, bool deadline_latched, bool exit_one_is_no_match,
|
||||
cbm_proc_result_t *result_out) {
|
||||
bool git_child, cbm_proc_result_t *result_out) {
|
||||
if (!srv || !command || !output_path || !result_out) {
|
||||
return MCP_SCAN_COMMAND_FAILURE;
|
||||
}
|
||||
@@ -15201,6 +15592,7 @@ static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(
|
||||
.quiet_timeout_ms = 0,
|
||||
.cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,
|
||||
.delete_log_on_exit = false,
|
||||
.strip_git_repo_env = git_child,
|
||||
};
|
||||
pre_spawn_cause =
|
||||
mcp_scan_pre_spawn_cause(srv, output_path, output_limit, deadline_ms, deadline_enabled,
|
||||
@@ -15278,11 +15670,14 @@ static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(
|
||||
: MCP_SCAN_CONTAINED_COMMAND_FAILURE;
|
||||
}
|
||||
|
||||
/* Every caller is a detect_changes git command: the child environment drops
|
||||
* git's repository-local variables so an inherited GIT_DIR cannot redirect
|
||||
* `git -C <root>` (#2003). */
|
||||
static int mcp_run_shell_command_cancellable(cbm_mcp_server_t *srv, const char *command,
|
||||
char output_path[CBM_SZ_2K],
|
||||
cbm_proc_result_t *result_out) {
|
||||
mcp_scan_cause_t cause = mcp_run_shell_command_cancellable_bounded(
|
||||
srv, command, output_path, 0, 0, false, false, false, result_out);
|
||||
srv, command, output_path, 0, 0, false, false, false, /*git_child=*/true, result_out);
|
||||
/* Legacy callers inspect result_out for cancellation/exit status. Preserve
|
||||
* their original contract: any contained terminal tree is transport
|
||||
* success; only spawn/rejection or failed supervision is a wrapper error. */
|
||||
@@ -15565,6 +15960,48 @@ static bool detect_add_changed_path(char ***files, int *file_count, int *file_ca
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Git status porcelain always reports paths relative to the Git ROOT, while
|
||||
* graph file_paths are relative to the indexed project root, which may be a
|
||||
* subdirectory of the repository (#1951). `prefix` is that subdirectory as
|
||||
* `git rev-parse --show-prefix` prints it ("" at the root, else "dir/").
|
||||
* Returns the project-relative tail, or NULL for a path outside the project. */
|
||||
static const char *detect_project_relative_path(const char *git_path, const char *prefix) {
|
||||
size_t prefix_length = strlen(prefix);
|
||||
if (strncmp(git_path, prefix, prefix_length) != 0) {
|
||||
return NULL;
|
||||
}
|
||||
return git_path + prefix_length;
|
||||
}
|
||||
|
||||
/* A `--show-prefix` answer: empty at the repository root, otherwise a
|
||||
* '/'-terminated relative directory. */
|
||||
static bool detect_valid_git_prefix(const char *value) {
|
||||
size_t length = strlen(value);
|
||||
return length == 0 || value[length - 1] == '/';
|
||||
}
|
||||
|
||||
/* Read one '\n'-terminated `git rev-parse` record (a trailing '\r' dropped)
|
||||
* into out when it is terminated, fits, and passes `valid`. Anything else is
|
||||
* a malformed answer and fails the request closed. */
|
||||
static bool detect_read_rev_parse_line(FILE *stream, bool *oom, char *out, size_t out_size,
|
||||
bool (*valid)(const char *)) {
|
||||
bool terminated = false;
|
||||
char *record = detect_read_record(stream, '\n', oom, &terminated);
|
||||
if (!record) {
|
||||
return false;
|
||||
}
|
||||
size_t length = strlen(record);
|
||||
if (length > 0 && record[length - 1] == '\r') {
|
||||
record[--length] = '\0';
|
||||
}
|
||||
bool ok = terminated && length < out_size && valid(record);
|
||||
if (ok) {
|
||||
memcpy(out, record, length + 1U);
|
||||
}
|
||||
free(record);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static int detect_changed_path_compare(const void *left, const void *right) {
|
||||
const char *const *left_path = left;
|
||||
const char *const *right_path = right;
|
||||
@@ -15915,15 +16352,20 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
|
||||
* HEAD advance cannot mix revisions within one answer. */
|
||||
char head_oid[65] = "";
|
||||
char base_oid[65] = "";
|
||||
/* The project root may be a subdirectory of the Git worktree (#1951);
|
||||
* --show-prefix names it so every changed path can be translated from the
|
||||
* Git-root coordinate system into the graph's project-relative one. */
|
||||
char git_prefix[CBM_SZ_4K] = "";
|
||||
bool git_prefix_valid = false;
|
||||
char resolve_cmd[CBM_SZ_2K];
|
||||
#ifdef _WIN32
|
||||
snprintf(resolve_cmd, sizeof(resolve_cmd),
|
||||
"git -C \"%s\" rev-parse \"HEAD^{commit}\" \"%s^{commit}\" 2>NUL", root_path,
|
||||
base_branch);
|
||||
"git -C \"%s\" rev-parse \"HEAD^{commit}\" \"%s^{commit}\" --show-prefix 2>NUL",
|
||||
root_path, base_branch);
|
||||
#else
|
||||
snprintf(resolve_cmd, sizeof(resolve_cmd),
|
||||
"git -C '%s' rev-parse 'HEAD^{commit}' '%s^{commit}' 2>/dev/null", root_path,
|
||||
base_branch);
|
||||
"git -C '%s' rev-parse 'HEAD^{commit}' '%s^{commit}' --show-prefix 2>/dev/null",
|
||||
root_path, base_branch);
|
||||
#endif
|
||||
char resolve_output_path[CBM_SZ_2K] = {0};
|
||||
cbm_proc_result_t resolve_result = {0};
|
||||
@@ -15931,43 +16373,24 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
|
||||
mcp_run_shell_command_cancellable(srv, resolve_cmd, resolve_output_path, &resolve_result);
|
||||
bool resolve_cancelled = resolve_result.cancellation_requested || mcp_request_cancelled(srv);
|
||||
bool resolve_oom = false;
|
||||
char *resolved_head = NULL;
|
||||
char *resolved_base = NULL;
|
||||
FILE *resolve_fp = resolve_run == 0 && resolve_result.exit_code == 0 && !resolve_cancelled
|
||||
? cbm_fopen(resolve_output_path, "rb")
|
||||
: NULL;
|
||||
if (resolve_fp) {
|
||||
bool head_terminated = false;
|
||||
bool base_terminated = false;
|
||||
resolved_head = detect_read_record(resolve_fp, '\n', &resolve_oom, &head_terminated);
|
||||
resolved_base = detect_read_record(resolve_fp, '\n', &resolve_oom, &base_terminated);
|
||||
if (resolved_head) {
|
||||
size_t length = strlen(resolved_head);
|
||||
if (length > 0 && resolved_head[length - 1] == '\r') {
|
||||
resolved_head[--length] = '\0';
|
||||
}
|
||||
if (head_terminated && detect_valid_object_id(resolved_head)) {
|
||||
memcpy(head_oid, resolved_head, length + 1U);
|
||||
}
|
||||
}
|
||||
if (resolved_base) {
|
||||
size_t length = strlen(resolved_base);
|
||||
if (length > 0 && resolved_base[length - 1] == '\r') {
|
||||
resolved_base[--length] = '\0';
|
||||
}
|
||||
if (base_terminated && detect_valid_object_id(resolved_base)) {
|
||||
memcpy(base_oid, resolved_base, length + 1U);
|
||||
}
|
||||
}
|
||||
/* Records in argument order: HEAD, base, then the --show-prefix line. */
|
||||
(void)detect_read_rev_parse_line(resolve_fp, &resolve_oom, head_oid, sizeof(head_oid),
|
||||
detect_valid_object_id);
|
||||
(void)detect_read_rev_parse_line(resolve_fp, &resolve_oom, base_oid, sizeof(base_oid),
|
||||
detect_valid_object_id);
|
||||
git_prefix_valid = detect_read_rev_parse_line(resolve_fp, &resolve_oom, git_prefix,
|
||||
sizeof(git_prefix), detect_valid_git_prefix);
|
||||
(void)fclose(resolve_fp);
|
||||
}
|
||||
free(resolved_head);
|
||||
free(resolved_base);
|
||||
if (resolve_output_path[0]) {
|
||||
(void)cbm_unlink(resolve_output_path);
|
||||
}
|
||||
if (resolve_cancelled || resolve_run != 0 || resolve_result.exit_code != 0 || resolve_oom ||
|
||||
!head_oid[0] || !base_oid[0]) {
|
||||
!head_oid[0] || !base_oid[0] || !git_prefix_valid) {
|
||||
free(direction);
|
||||
free(root_path);
|
||||
free(project);
|
||||
@@ -15980,6 +16403,12 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
|
||||
return cbm_mcp_text_result(
|
||||
"git revision resolution failed: the contained command could not complete", true);
|
||||
}
|
||||
if (head_oid[0] && base_oid[0] && !resolve_oom) {
|
||||
return cbm_mcp_text_result(
|
||||
"git revision resolution failed: the project root's path inside the Git "
|
||||
"worktree could not be determined",
|
||||
true);
|
||||
}
|
||||
return cbm_mcp_text_result(
|
||||
"git revision resolution failed: base_branch or HEAD is not a commit", true);
|
||||
}
|
||||
@@ -16079,7 +16508,9 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
|
||||
free(record);
|
||||
break;
|
||||
}
|
||||
if (!detect_add_changed_path(&files, &file_count, &file_cap, record)) {
|
||||
const char *project_path = detect_project_relative_path(record, git_prefix);
|
||||
if (project_path &&
|
||||
!detect_add_changed_path(&files, &file_count, &file_cap, project_path)) {
|
||||
changed_path_oom = true;
|
||||
free(record);
|
||||
break;
|
||||
@@ -16154,7 +16585,10 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
|
||||
free(record);
|
||||
break;
|
||||
}
|
||||
if (!detect_add_changed_path(&files, &file_count, &file_cap, record + PAIR_LEN + 1U)) {
|
||||
const char *project_path =
|
||||
detect_project_relative_path(record + PAIR_LEN + 1U, git_prefix);
|
||||
if (project_path &&
|
||||
!detect_add_changed_path(&files, &file_count, &file_cap, project_path)) {
|
||||
changed_path_oom = true;
|
||||
free(record);
|
||||
break;
|
||||
@@ -16271,20 +16705,22 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
|
||||
* index combined with insertions earlier in the file shifts the node lines
|
||||
* relative to the hunks and can mis-scope. The failure is bounded by
|
||||
* detect_collect_seeds' zero-overlap fallback: a file whose definitions all
|
||||
* miss reverts to whole-file seeding rather than dropping out. */
|
||||
* miss reverts to whole-file seeding rather than dropping out.
|
||||
* --relative keeps hunk paths in the same project-relative coordinates as
|
||||
* `files` when the project root is a repository subdirectory (#1951). */
|
||||
cbm_changed_hunk_t *hunks = NULL;
|
||||
int hunk_count = 0;
|
||||
if (want_symbols) {
|
||||
char hunk_cmd[CBM_SZ_2K];
|
||||
#ifdef _WIN32
|
||||
snprintf(hunk_cmd, sizeof(hunk_cmd),
|
||||
"git -C \"%s\" diff --unified=0 \"%s\" \"%s\" -- 2>NUL && "
|
||||
"git -C \"%s\" diff --unified=0 -- 2>NUL",
|
||||
"git -C \"%s\" diff --relative --unified=0 \"%s\" \"%s\" -- 2>NUL && "
|
||||
"git -C \"%s\" diff --relative --unified=0 -- 2>NUL",
|
||||
root_path, merge_base, head_oid, root_path);
|
||||
#else
|
||||
snprintf(hunk_cmd, sizeof(hunk_cmd),
|
||||
"git -C '%s' diff --unified=0 '%s' '%s' -- 2>/dev/null && "
|
||||
"git -C '%s' diff --unified=0 -- 2>/dev/null",
|
||||
"git -C '%s' diff --relative --unified=0 '%s' '%s' -- 2>/dev/null && "
|
||||
"git -C '%s' diff --relative --unified=0 -- 2>/dev/null",
|
||||
root_path, merge_base, head_oid, root_path);
|
||||
#endif
|
||||
char hunk_output_path[CBM_SZ_2K] = {0};
|
||||
|
||||
+29
-2
@@ -56,6 +56,22 @@ char *cbm_jsonrpc_format_error(int64_t id, int code, const char *message);
|
||||
/* Format an MCP tool result with text content. Returns heap-allocated JSON. */
|
||||
char *cbm_mcp_text_result(const char *text, bool is_error);
|
||||
|
||||
/* Attach a notice to a complete MCP tool result: a JSON-object payload gains a
|
||||
* "notice" key (content text and structuredContent stay in step), a text
|
||||
* payload gains a trailing paragraph. Takes
|
||||
* ownership of result and returns the rewritten result, or result unchanged
|
||||
* when it is not a tool-result object (never NULL for a non-NULL result). */
|
||||
char *cbm_mcp_tool_result_add_notice(char *result, const char *notice);
|
||||
|
||||
/* #2144: the advice every cut-short synchronous index_repository surfaces. A
|
||||
* long index can outlive a client's per-call deadline; the async flag lets the
|
||||
* daemon finish it while the client polls. */
|
||||
#define CBM_MCP_INDEX_ASYNC_HINT \
|
||||
"Long indexes can exceed an MCP client's per-call deadline: retry with " \
|
||||
"index_repository(repo_path=..., async: true), then poll " \
|
||||
"index_repository(repo_path=..., status: true) until state is succeeded, failed or " \
|
||||
"cancelled."
|
||||
|
||||
/* Return true when notifications/cancelled params target the active request. */
|
||||
bool cbm_mcp_cancel_request_matches(const char *params_json, int64_t active_id,
|
||||
const char *active_id_str);
|
||||
@@ -128,9 +144,17 @@ bool cbm_mcp_tool_profile_allows_http(cbm_mcp_tool_profile_t profile);
|
||||
* already authorized against this session; args_json contains that canonical
|
||||
* path plus all caller options. The callback returns a complete malloc-owned
|
||||
* MCP tool result. A NULL result is reported as an error and never degrades to
|
||||
* an uncoordinated in-process index. */
|
||||
* an uncoordinated in-process index. async (#2144) asks the executor to start
|
||||
* or join the project's job and return at once; the job must then outlive the
|
||||
* request and its session. */
|
||||
typedef char *(*cbm_mcp_index_executor_fn)(void *context, const char *repo_path,
|
||||
const char *args_json);
|
||||
const char *args_json, bool async);
|
||||
|
||||
/* Optional daemon-owned index job status (#2144): the state of the running or
|
||||
* most recent index job for one project key. Returns a malloc-owned tool
|
||||
* result. Servers without one (in-process CLI workers, embedders) refuse
|
||||
* index_repository's async and status modes. */
|
||||
typedef char *(*cbm_mcp_index_status_fn)(void *context, const char *project);
|
||||
|
||||
/* Daemon-owned exclusive lease for operations that mutate a published project
|
||||
* database. begin may wait, but must remain cancellable by its session owner;
|
||||
@@ -180,6 +204,9 @@ void cbm_mcp_server_set_background_tasks(cbm_mcp_server_t *srv, bool enabled);
|
||||
void cbm_mcp_server_set_index_executor(cbm_mcp_server_t *srv, cbm_mcp_index_executor_fn executor,
|
||||
void *context);
|
||||
|
||||
void cbm_mcp_server_set_index_status_provider(cbm_mcp_server_t *srv,
|
||||
cbm_mcp_index_status_fn provider, void *context);
|
||||
|
||||
/* Relay supervised worker logs to one local request (for CLI progress). The
|
||||
* callback/context are borrowed until the synchronous tool call returns. */
|
||||
void cbm_mcp_server_set_index_log_callback(cbm_mcp_server_t *srv, cbm_proc_log_cb callback,
|
||||
|
||||
@@ -255,7 +255,7 @@ static bool git_head_hash(const char *repo_path, char *buf, size_t bufsz) {
|
||||
git_context.c) */
|
||||
return false;
|
||||
}
|
||||
FILE *fp = cbm_popen(cmd, "r");
|
||||
FILE *fp = cbm_popen_git(cmd);
|
||||
if (!fp) {
|
||||
buf[0] = '\0';
|
||||
return false;
|
||||
@@ -397,7 +397,7 @@ static bool git_run_ok(const char *repo_path, const char *args) {
|
||||
if (!build_git_cmd(cmd, sizeof(cmd), repo_path, args)) {
|
||||
return false;
|
||||
}
|
||||
FILE *fp = cbm_popen(cmd, "r");
|
||||
FILE *fp = cbm_popen_git(cmd);
|
||||
if (!fp) {
|
||||
return false;
|
||||
}
|
||||
@@ -416,7 +416,7 @@ static int git_capture_full(const char *repo_path, const char *args, char **out,
|
||||
if (!build_git_cmd(cmd, sizeof(cmd), repo_path, args)) {
|
||||
return CBM_NOT_FOUND;
|
||||
}
|
||||
FILE *fp = cbm_popen(cmd, "r");
|
||||
FILE *fp = cbm_popen_git(cmd);
|
||||
if (!fp) {
|
||||
return CBM_NOT_FOUND;
|
||||
}
|
||||
@@ -813,7 +813,7 @@ static void ensure_gitattributes(const char *repo_path) {
|
||||
if (n < 0 || (size_t)n >= sizeof(cmd)) {
|
||||
return; /* truncated command → skip (parity with git_context.c) */
|
||||
}
|
||||
FILE *p = cbm_popen(cmd, "r");
|
||||
FILE *p = cbm_popen_git(cmd);
|
||||
if (p) {
|
||||
(void)cbm_pclose(p);
|
||||
}
|
||||
|
||||
+6
-2
@@ -428,9 +428,13 @@ char *cbm_project_name_from_path(const char *abs_path) {
|
||||
cbm_normalize_path_sep(real);
|
||||
name_path = real;
|
||||
}
|
||||
return cbm_project_name_sanitize(name_path);
|
||||
}
|
||||
|
||||
/* Work on mutable copy */
|
||||
char *path = strdup(name_path);
|
||||
char *cbm_project_name_sanitize(const char *name_path) {
|
||||
/* Work on mutable copy. NULL and "" map to "" and fall through to the
|
||||
* empty-after-trim "root" return below. */
|
||||
char *path = strdup(name_path ? name_path : "");
|
||||
if (!path) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -537,6 +537,47 @@ static inline bool cbm_pipeline_kotlin_external_target(CBMLanguage lang, const c
|
||||
strncmp(callee_qn, "javax.", strlen("javax.")) == 0;
|
||||
}
|
||||
|
||||
/* Rust (#2053): true when the Rust LSP positively resolved a call to a
|
||||
* registered symbol that lives OUTSIDE the project — a std/core/alloc seed
|
||||
* method (`root.join()` on `root: &Path` -> std.path.Path.join) or a seeded
|
||||
* crate API. Such a row has no graph node, and before this gate the callers
|
||||
* then fell back to the textual registry, which bound the call to whatever
|
||||
* project method shares the leaf name (EvidenceTier::join, unique_name).
|
||||
*
|
||||
* The evidence is the strategy plus the QN's namespace. The listed strategies
|
||||
* emit the QN of a function the LSP registry actually holds; project defs are
|
||||
* registered under their project-prefixed QNs, so a registered QN outside the
|
||||
* project prefix is an embedded seed by construction. A project-prefixed QN
|
||||
* that merely failed the gbuf lookup is NOT external and keeps the #1085
|
||||
* registry fallback, as does every unresolved/unknown-receiver row (those
|
||||
* never reach the callers: they sit below CBM_LSP_CONFIDENCE_FLOOR).
|
||||
* Rust-only: suppressors stay per-language. Pure; unit-tested. */
|
||||
static inline bool cbm_pipeline_rust_external_target(CBMLanguage lang, const char *strategy,
|
||||
const char *callee_qn,
|
||||
const char *project_name) {
|
||||
if (lang != CBM_LANG_RUST || !strategy || !callee_qn || !callee_qn[0] || !project_name ||
|
||||
!project_name[0]) {
|
||||
return false;
|
||||
}
|
||||
static const char *const registered_target_strategies[] = {
|
||||
"lsp_method_dispatch", "lsp_trait_dispatch", "lsp_deref_dispatch", "lsp_bound_dispatch",
|
||||
"lsp_direct", "lsp_ufcs", "lsp_constructor",
|
||||
};
|
||||
bool registered_target = false;
|
||||
for (size_t i = 0;
|
||||
i < sizeof(registered_target_strategies) / sizeof(registered_target_strategies[0]); i++) {
|
||||
if (strcmp(strategy, registered_target_strategies[i]) == 0) {
|
||||
registered_target = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!registered_target) {
|
||||
return false;
|
||||
}
|
||||
size_t proj_len = strlen(project_name);
|
||||
return !(strncmp(callee_qn, project_name, proj_len) == 0 && callee_qn[proj_len] == '.');
|
||||
}
|
||||
|
||||
/* Resolvers may report one graph target both project-relative and already
|
||||
* project-prefixed. Raw string inequality is not ambiguity when both spellings
|
||||
* resolve to the same materialized node; conversely, if both nodes exist they
|
||||
|
||||
@@ -125,6 +125,31 @@ static char *surface_file_to_json(const CBMFileResult *result, const CBMLSPDef *
|
||||
}
|
||||
yyjson_mut_obj_add_val(doc, root, "reg", reg);
|
||||
|
||||
/* #1916: an axios instance binding's baseURL is consumed by the files
|
||||
* that import it (their HTTP_CALLS compose base + path), so a changed
|
||||
* base must change the surface or those importers keep stale edges.
|
||||
* Written only when the file has such a binding: every other file's
|
||||
* surface bytes — and so its sha — stay exactly what they were. The
|
||||
* decoder ignores this key; it feeds the early-cutoff hash only. */
|
||||
yyjson_mut_val *http = NULL;
|
||||
for (int i = 0; result && i < result->defs.count; i++) {
|
||||
const CBMDefinition *d = &result->defs.items[i];
|
||||
if (!d->http_client || !d->qualified_name) {
|
||||
continue;
|
||||
}
|
||||
if (!http) {
|
||||
http = yyjson_mut_arr(doc);
|
||||
}
|
||||
yyjson_mut_val *o = yyjson_mut_obj(doc);
|
||||
yyjson_mut_obj_add_str(doc, o, "q", d->qualified_name);
|
||||
yyjson_mut_obj_add_str(doc, o, "c", d->http_client);
|
||||
add_str_or_null(doc, o, "b", d->http_base_url);
|
||||
yyjson_mut_arr_add_val(http, o);
|
||||
}
|
||||
if (http) {
|
||||
yyjson_mut_obj_add_val(doc, root, "http", http);
|
||||
}
|
||||
|
||||
char *json = yyjson_mut_write(doc, 0, out_len);
|
||||
yyjson_mut_doc_free(doc);
|
||||
return json;
|
||||
|
||||
+221
-16
@@ -107,6 +107,16 @@ static char *extract_local_name_from_json(const char *props_json) {
|
||||
return cbm_strndup(start, end - start);
|
||||
}
|
||||
|
||||
/* The graph node whose QN is cbm_pipeline_fqn_compute(project, rel_path, name),
|
||||
* or NULL. The one place this pass computes a transient QN for a lookup. */
|
||||
static const cbm_gbuf_node_t *pc_find_by_computed_qn(const cbm_gbuf_t *gbuf, const char *project,
|
||||
const char *rel_path, const char *name) {
|
||||
char *qn = cbm_pipeline_fqn_compute(project, rel_path, name);
|
||||
const cbm_gbuf_node_t *n = qn ? cbm_gbuf_find_by_qn(gbuf, qn) : NULL;
|
||||
free(qn);
|
||||
return n;
|
||||
}
|
||||
|
||||
static int build_import_map(cbm_pipeline_ctx_t *ctx, const char *rel_path,
|
||||
const CBMFileResult *result, const char ***out_keys,
|
||||
const char ***out_vals, int *out_count) {
|
||||
@@ -153,9 +163,8 @@ static int build_import_map(cbm_pipeline_ctx_t *ctx, const char *rel_path,
|
||||
}
|
||||
|
||||
/* Slow path: scan graph buffer IMPORTS edges + parse JSON properties */
|
||||
char *file_qn = cbm_pipeline_fqn_compute(ctx->project_name, rel_path, "__file__");
|
||||
const cbm_gbuf_node_t *file_node = cbm_gbuf_find_by_qn(ctx->gbuf, file_qn);
|
||||
free(file_qn);
|
||||
const cbm_gbuf_node_t *file_node =
|
||||
pc_find_by_computed_qn(ctx->gbuf, ctx->project_name, rel_path, "__file__");
|
||||
if (!file_node) {
|
||||
return 0;
|
||||
}
|
||||
@@ -204,6 +213,167 @@ static void free_import_map(const char **keys, const char **vals, int count) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ── #1916: axios client-instance calls ─────────────────────────── */
|
||||
|
||||
/* Copy the plain (unescaped) JSON string value of "key" in props into out.
|
||||
* False when absent, escaped, or too long — an unreadable base is unknown. */
|
||||
static bool pc_json_str_prop(const char *props, const char *key, char *out, size_t out_sz) {
|
||||
if (!props) {
|
||||
return false;
|
||||
}
|
||||
char pat[CBM_SZ_64];
|
||||
snprintf(pat, sizeof(pat), "\"%s\":\"", key);
|
||||
const char *p = strstr(props, pat);
|
||||
if (!p) {
|
||||
return false;
|
||||
}
|
||||
p += strlen(pat);
|
||||
const char *e = strchr(p, '"');
|
||||
if (!e) {
|
||||
return false;
|
||||
}
|
||||
size_t len = (size_t)(e - p);
|
||||
if (len >= out_sz || memchr(p, '\\', len) != NULL) {
|
||||
return false;
|
||||
}
|
||||
memcpy(out, p, len);
|
||||
out[len] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A node the extractor marked as an axios instance. `base` receives the
|
||||
* literal baseURL ("" when unknown). */
|
||||
static bool pc_node_is_http_client(const cbm_gbuf_node_t *n, char *base, size_t base_sz) {
|
||||
char client[CBM_SZ_32];
|
||||
if (!n || !pc_json_str_prop(n->properties_json, "http_client", client, sizeof(client))) {
|
||||
return false;
|
||||
}
|
||||
if (!pc_json_str_prop(n->properties_json, "http_base_url", base, base_sz)) {
|
||||
base[0] = '\0';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The module-level Variable `name` declared in file `file_rel`. */
|
||||
static const cbm_gbuf_node_t *pc_module_var(const cbm_gbuf_t *gbuf, const char *project,
|
||||
const char *file_rel, const char *name) {
|
||||
if (!file_rel) {
|
||||
return NULL;
|
||||
}
|
||||
const cbm_gbuf_node_t *n = pc_find_by_computed_qn(gbuf, project, file_rel, name);
|
||||
return (n && n->label && strcmp(n->label, "Variable") == 0) ? n : NULL;
|
||||
}
|
||||
|
||||
/* Resolve the binding `recv` names in the calling file to a client node:
|
||||
* a same-file declaration first, then its ES import (default import → the
|
||||
* module's default export; named import → that module's Variable). */
|
||||
static bool pc_receiver_client_base(const cbm_gbuf_t *gbuf, const char *project, const char *rel,
|
||||
const CBMFileResult *result, const char **imp_keys,
|
||||
const char **imp_vals, int imp_count, const char *recv,
|
||||
char *base, size_t base_sz) {
|
||||
if (pc_node_is_http_client(pc_module_var(gbuf, project, rel, recv), base, base_sz)) {
|
||||
return true;
|
||||
}
|
||||
const CBMImport *imp = NULL;
|
||||
for (int i = 0; result && i < result->imports.count; i++) {
|
||||
const CBMImport *it = &result->imports.items[i];
|
||||
if (it->local_name && strcmp(it->local_name, recv) == 0) {
|
||||
imp = it;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!imp) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < imp_count; i++) {
|
||||
if (!imp_keys[i] || strcmp(imp_keys[i], recv) != 0 || !imp_vals[i]) {
|
||||
continue;
|
||||
}
|
||||
const cbm_gbuf_node_t *t = cbm_gbuf_find_by_qn(gbuf, imp_vals[i]);
|
||||
if (!t || !t->label) {
|
||||
return false;
|
||||
}
|
||||
if (strcmp(t->label, "Variable") == 0) {
|
||||
return pc_node_is_http_client(t, base, base_sz);
|
||||
}
|
||||
if (strcmp(t->label, "Module") != 0) {
|
||||
return false;
|
||||
}
|
||||
if (imp->is_default) {
|
||||
return pc_node_is_http_client(t, base, base_sz);
|
||||
}
|
||||
return pc_node_is_http_client(pc_module_var(gbuf, project, t->file_path, recv), base,
|
||||
base_sz);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* axios instance request methods (the verb after the receiver). */
|
||||
static bool pc_is_axios_verb(const char *verb) {
|
||||
static const char *const verbs[] = {"get", "post", "put", "delete",
|
||||
"patch", "head", "options", NULL};
|
||||
for (int i = 0; verbs[i]; i++) {
|
||||
if (strcmp(verb, verbs[i]) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Copy the plain-identifier receiver of `callee` (text before `dot`) into
|
||||
* recv. False for `this.api.get`, `a().get` and other non-binding receivers. */
|
||||
static bool pc_plain_receiver(const char *callee, const char *dot, char *recv, size_t recv_sz) {
|
||||
size_t rlen = (size_t)(dot - callee);
|
||||
if (rlen == 0 || rlen >= recv_sz) {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < rlen; i++) {
|
||||
char c = callee[i];
|
||||
bool ident = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '$';
|
||||
if (!ident) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
memcpy(recv, callee, rlen);
|
||||
recv[rlen] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
bool cbm_pipeline_http_client_call_url(const cbm_gbuf_t *gbuf, const char *project, const char *rel,
|
||||
const CBMFileResult *result, const char **imp_keys,
|
||||
const char **imp_vals, int imp_count, const CBMCall *call,
|
||||
char *out, size_t out_sz) {
|
||||
const char *callee = call ? call->callee_name : NULL;
|
||||
const char *url = call ? call->first_string_arg : NULL;
|
||||
if (!gbuf || !project || !callee || !url || (url[0] != '/' && !strstr(url, "://"))) {
|
||||
return false;
|
||||
}
|
||||
const char *dot = strrchr(callee, '.');
|
||||
char recv[CBM_SZ_128];
|
||||
if (!dot || !pc_is_axios_verb(dot + SKIP_ONE) ||
|
||||
!pc_plain_receiver(callee, dot, recv, sizeof(recv))) {
|
||||
return false;
|
||||
}
|
||||
char base[CBM_SZ_256];
|
||||
if (!pc_receiver_client_base(gbuf, project, rel, result, imp_keys, imp_vals, imp_count, recv,
|
||||
base, sizeof(base))) {
|
||||
return false;
|
||||
}
|
||||
/* axios combineURLs: an absolute request URL ignores baseURL; otherwise
|
||||
* the base (trailing '/' trimmed) is joined with the '/'-leading path. */
|
||||
if (strstr(url, "://") || base[0] == '\0') {
|
||||
int n = snprintf(out, out_sz, "%s", url);
|
||||
return n > 0 && (size_t)n < out_sz;
|
||||
}
|
||||
size_t blen = strlen(base);
|
||||
while (blen > 0 && base[blen - SKIP_ONE] == '/') {
|
||||
base[--blen] = '\0';
|
||||
}
|
||||
int n = snprintf(out, out_sz, "%s%s", base, url);
|
||||
return n > 0 && (size_t)n < out_sz;
|
||||
}
|
||||
|
||||
/* Handle a route registration call: create Route node + HANDLES edge. */
|
||||
static void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *call,
|
||||
const cbm_gbuf_node_t *source_node, const char *module_qn,
|
||||
@@ -467,18 +637,17 @@ static const cbm_gbuf_node_t *calls_find_source(cbm_pipeline_ctx_t *ctx, const c
|
||||
}
|
||||
}
|
||||
if (!src) {
|
||||
char *fqn = cbm_pipeline_fqn_compute(ctx->project_name, rel, "__file__");
|
||||
src = cbm_gbuf_find_by_qn(ctx->gbuf, fqn);
|
||||
free(fqn);
|
||||
src = pc_find_by_computed_qn(ctx->gbuf, ctx->project_name, rel, "__file__");
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
/* Resolve one call and emit the appropriate edge. Returns 1 if resolved, 0 if not. */
|
||||
static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
|
||||
const CBMResolvedCallArray *lsp_calls, const char *rel,
|
||||
const char *module_qn, const char **imp_keys, const char **imp_vals,
|
||||
int imp_count, CBMLanguage lang) {
|
||||
static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBMFileResult *result,
|
||||
const char *rel, const char *module_qn, const char **imp_keys,
|
||||
const char **imp_vals, int imp_count, CBMLanguage lang,
|
||||
const CBMImportArray *imports) {
|
||||
const CBMResolvedCallArray *lsp_calls = &result->resolved_calls;
|
||||
const cbm_gbuf_node_t *source_node = calls_find_source(ctx, rel, call->enclosing_func_qn);
|
||||
if (!source_node) {
|
||||
return 0;
|
||||
@@ -527,7 +696,26 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
|
||||
* and not an HTTP pattern, so BOTH the empty-resolution and resolved-QN
|
||||
* service checks below miss it and the call is dropped. Detect it on the
|
||||
* callee_name FIRST so the HTTP_CALLS/ASYNC_CALLS edge is emitted regardless
|
||||
* (target is a synthesized route node, not the unindexed library). (#523) */
|
||||
* (target is a synthesized route node, not the unindexed library). (#523)
|
||||
*
|
||||
* First, though: `api.get('/orders')` on an axios.create() instance (#1916).
|
||||
* The receiver's binding decides, not its spelling — without this the
|
||||
* verb suffix made it an Express route REGISTRATION below (a CALLS edge
|
||||
* to a phantom server route), and a receiver spelled `axiosInstance`
|
||||
* substring-matches the #523 check and loses its baseURL. */
|
||||
char client_url[CBM_SZ_512];
|
||||
if (cbm_pipeline_http_client_call_url(ctx->gbuf, ctx->project_name, rel, result, imp_keys,
|
||||
imp_vals, imp_count, call, client_url,
|
||||
sizeof(client_url))) {
|
||||
CBMCall routed = *call;
|
||||
routed.first_string_arg = client_url;
|
||||
cbm_resolution_t svc_res = {.qualified_name = call->callee_name,
|
||||
.confidence = PC_SVC_PATTERN_CONF,
|
||||
.strategy = "http_client_instance",
|
||||
.candidate_count = 0};
|
||||
emit_http_async_edge(ctx, &routed, source_node, NULL, &svc_res, CBM_SVC_HTTP, false);
|
||||
return SKIP_ONE;
|
||||
}
|
||||
cbm_svc_kind_t csvc = cbm_service_pattern_match(call->callee_name);
|
||||
if (csvc == CBM_SVC_HTTP || csvc == CBM_SVC_ASYNC) {
|
||||
const char *cu = call->first_string_arg;
|
||||
@@ -544,8 +732,18 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
|
||||
}
|
||||
}
|
||||
|
||||
cbm_resolution_t res = cbm_registry_resolve(ctx->registry, call->callee_name, module_qn,
|
||||
imp_keys, imp_vals, imp_count);
|
||||
/* #2053: a Rust call the LSP placed on an EXTERNAL symbol (std's
|
||||
* Path::join, a seeded crate API) is resolved — it just has no graph node.
|
||||
* The textual registry would bind it to a same-named project method
|
||||
* instead, so skip it and let the empty-resolution service fallbacks below
|
||||
* classify the call. MUST match pass_parallel.c. */
|
||||
bool rust_external = lsp && cbm_pipeline_rust_external_target(
|
||||
lang, lsp->strategy, lsp->callee_qn, ctx->project_name);
|
||||
cbm_resolution_t res = {0};
|
||||
if (!rust_external) {
|
||||
res = cbm_registry_resolve(ctx->registry, call->callee_name, module_qn, imp_keys, imp_vals,
|
||||
imp_count);
|
||||
}
|
||||
if (!res.qualified_name || res.qualified_name[0] == '\0') {
|
||||
/* Resolution is empty when the callee belongs to an EXTERNAL client
|
||||
* library whose source is not in the indexed tree (e.g. `requests.get`,
|
||||
@@ -650,7 +848,14 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
|
||||
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);
|
||||
call->callee_is_locally_bound, res.strategy) ||
|
||||
/* Import-binding suppression (#2127): an external `from m import f`
|
||||
* binds `f` for the whole module, so a weak short-name match onto a
|
||||
* project `X.f` outside m is fabricated. Python-only (the import
|
||||
* paths are module chains) — MUST match pass_parallel.c exactly. */
|
||||
(lang == CBM_LANG_PYTHON && cbm_suppress_weak_import_bound_call(true, true, res.strategy) &&
|
||||
cbm_python_import_binding_contradicts(imports, call->callee_name, res.qualified_name,
|
||||
ctx->gbuf, ctx->project_name, rel));
|
||||
|
||||
/* Service-pattern HTTP/ASYNC calls to an EXTERNAL client library (e.g.
|
||||
* `requests.get("/api/orders/{id}")`) resolve to a QN containing the library
|
||||
@@ -841,8 +1046,8 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
|
||||
continue;
|
||||
}
|
||||
total_calls++;
|
||||
if (resolve_single_call(ctx, call, &result->resolved_calls, rel, module_qn, imp_keys,
|
||||
imp_vals, imp_count, files[i].language)) {
|
||||
if (resolve_single_call(ctx, call, result, rel, module_qn, imp_keys, imp_vals,
|
||||
imp_count, files[i].language, &result->imports)) {
|
||||
resolved++;
|
||||
} else {
|
||||
unresolved++;
|
||||
|
||||
+126
-36
@@ -153,6 +153,13 @@ static bool cr_store_has_exact_project(cbm_store_t *store, const char *project)
|
||||
return matches;
|
||||
}
|
||||
|
||||
/* True when `project` is a usable cross-repo input: its store holds exactly
|
||||
* that project AND carries the schema the read-write open in
|
||||
* cr_open_existing_project requires. Checking only the first let a pre-#768
|
||||
* store (still readable, so list_projects shows it) pass validation and the
|
||||
* ["*"] enumeration, then abort the whole run at its write open — after the
|
||||
* source's previous CROSS_* generation had already been deleted. The probe is
|
||||
* read-only, so the legacy store is left untouched for its reindex. (#2133) */
|
||||
static bool cr_project_exists(const char *project) {
|
||||
char path[CR_PATH_BUF];
|
||||
if (!cr_db_path(project, path, sizeof(path))) {
|
||||
@@ -160,6 +167,11 @@ static bool cr_project_exists(const char *project) {
|
||||
}
|
||||
cbm_store_t *store = cbm_store_open_path_query(path);
|
||||
bool exists = cr_store_has_exact_project(store, project);
|
||||
if (exists && !cbm_store_edges_schema_current(store)) {
|
||||
cbm_log_warn("cross_repo.project_unusable", "project", project, "reason",
|
||||
"pre_768_schema_reindex_required");
|
||||
exists = false;
|
||||
}
|
||||
cbm_store_close(store);
|
||||
return exists;
|
||||
}
|
||||
@@ -592,6 +604,80 @@ static bool emit_cross_route_bidirectional(
|
||||
return insert_cross_edge(tgt_store, tgt_project, handler_id, tgt_route_id, edge_type, rev, ctx);
|
||||
}
|
||||
|
||||
/* A resolved route: the matched Route QN plus its handler's name and file. */
|
||||
typedef struct {
|
||||
char qn[CR_QN_BUF];
|
||||
char name[CBM_SZ_256];
|
||||
char file[CBM_SZ_512];
|
||||
} cr_route_hit_t;
|
||||
|
||||
/* Resolve a client call (method + canonical path) to a handled Route in
|
||||
* store: exact method QN, then ANY, then segment-wise template matching,
|
||||
* since a concrete client path ("/v2/orders/123") never exact-matches a
|
||||
* templated route ("/v2/orders/{}") (#523). Returns the handler id, or 0. */
|
||||
static int64_t resolve_route_handler(cbm_store_t *store, const char *method, const char *curl,
|
||||
cr_route_hit_t *hit, bool *failed, cr_run_context_t *ctx) {
|
||||
snprintf(hit->qn, sizeof(hit->qn), "__route__%s__%s", method[0] ? method : "ANY", curl);
|
||||
int64_t handler_id = find_route_handler(store, hit->qn, hit->name, sizeof(hit->name), hit->file,
|
||||
sizeof(hit->file), failed);
|
||||
if (!*failed && handler_id == 0) {
|
||||
snprintf(hit->qn, sizeof(hit->qn), "__route__ANY__%s", curl);
|
||||
handler_id = find_route_handler(store, hit->qn, hit->name, sizeof(hit->name), hit->file,
|
||||
sizeof(hit->file), failed);
|
||||
}
|
||||
if (!*failed && handler_id == 0) {
|
||||
handler_id = find_route_handler_fuzzy(store, curl, method[0] ? method : NULL, hit->qn,
|
||||
sizeof(hit->qn), hit->name, sizeof(hit->name),
|
||||
hit->file, sizeof(hit->file), failed, ctx);
|
||||
}
|
||||
return *failed ? 0 : handler_id;
|
||||
}
|
||||
|
||||
/* True when the caller's own project has a HANDLES edge into the local Route
|
||||
* node its HTTP_CALLS points at. Sets *failed on a query error. (#1459) */
|
||||
static bool route_node_handled(struct sqlite3 *src_db, const char *src_project, int64_t route_id,
|
||||
bool *failed) {
|
||||
*failed = false;
|
||||
sqlite3_stmt *s = NULL;
|
||||
if (sqlite3_prepare_v2(src_db,
|
||||
"SELECT 1 FROM edges WHERE project = ?1 AND target_id = ?2 "
|
||||
"AND type = 'HANDLES' LIMIT 1",
|
||||
CBM_NOT_FOUND, &s, NULL) != SQLITE_OK) {
|
||||
*failed = true;
|
||||
return false;
|
||||
}
|
||||
if (sqlite3_bind_text(s, SKIP_ONE, src_project, CBM_NOT_FOUND, SQLITE_STATIC) != SQLITE_OK ||
|
||||
sqlite3_bind_int64(s, PAIR_LEN, route_id) != SQLITE_OK) {
|
||||
sqlite3_finalize(s);
|
||||
*failed = true;
|
||||
return false;
|
||||
}
|
||||
int step_rc = sqlite3_step(s);
|
||||
if (step_rc != SQLITE_ROW && step_rc != SQLITE_DONE) {
|
||||
*failed = true;
|
||||
}
|
||||
if (sqlite3_finalize(s) != SQLITE_OK) {
|
||||
*failed = true;
|
||||
}
|
||||
return !*failed && step_rc == SQLITE_ROW;
|
||||
}
|
||||
|
||||
/* Caller-local floor (#1459): a call the caller's own project serves is an
|
||||
* in-project call — another project exposing the same path is no evidence of
|
||||
* a cross-service call. "Served" is the HANDLES edge on the Route node the
|
||||
* HTTP_CALLS points at, or the same method/ANY/template resolution the target
|
||||
* lookup uses, applied to the caller's own store: a method-less fetch() points
|
||||
* at the ANY node while the local handler sits on the GET node. */
|
||||
static bool call_served_locally(cbm_store_t *src_store, struct sqlite3 *src_db,
|
||||
const char *src_project, int64_t route_id, const char *method,
|
||||
const char *curl, bool *failed, cr_run_context_t *ctx) {
|
||||
if (route_node_handled(src_db, src_project, route_id, failed) || *failed) {
|
||||
return !*failed;
|
||||
}
|
||||
cr_route_hit_t local;
|
||||
return resolve_route_handler(src_store, method, curl, &local, failed, ctx) != 0;
|
||||
}
|
||||
|
||||
static cr_match_result_t match_http_routes(cbm_store_t *src_store, const char *src_project,
|
||||
cbm_store_t *tgt_store, const char *tgt_project,
|
||||
cr_run_context_t *ctx) {
|
||||
@@ -632,35 +718,26 @@ static cr_match_result_t match_http_routes(cbm_store_t *src_store, const char *s
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Build the expected Route QN in the target project (authority-stripped
|
||||
* and param-canonicalized so client url_path matches the server handler
|
||||
* regardless of base URL and framework placeholder syntax). */
|
||||
char route_qn[CR_QN_BUF];
|
||||
/* Canonical client path: authority-stripped and param-canonicalized so
|
||||
* it matches a server handler regardless of base URL and framework
|
||||
* placeholder syntax. */
|
||||
char cpath[CBM_SZ_256];
|
||||
const char *curl = cbm_route_canon_path(cr_url_path(url_path), cpath, sizeof(cpath));
|
||||
snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", method[0] ? method : "ANY", curl);
|
||||
|
||||
char handler_name[CBM_SZ_256] = {0};
|
||||
char handler_file[CBM_SZ_512] = {0};
|
||||
bool query_failed = false;
|
||||
bool served_locally = call_served_locally(src_store, src_db, src_project, route_id, method,
|
||||
curl, &query_failed, ctx);
|
||||
if (query_failed) {
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
if (served_locally) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cr_route_hit_t hit;
|
||||
int64_t handler_id =
|
||||
find_route_handler(tgt_store, route_qn, handler_name, sizeof(handler_name),
|
||||
handler_file, sizeof(handler_file), &query_failed);
|
||||
if (!query_failed && handler_id == 0) {
|
||||
/* Try without method (ANY) */
|
||||
snprintf(route_qn, sizeof(route_qn), "__route__ANY__%s", curl);
|
||||
handler_id = find_route_handler(tgt_store, route_qn, handler_name, sizeof(handler_name),
|
||||
handler_file, sizeof(handler_file), &query_failed);
|
||||
}
|
||||
if (!query_failed && handler_id == 0) {
|
||||
/* Exact QN lookup missed. A concrete client path ("/v2/orders/123")
|
||||
* never exact-matches a templated route ("/v2/orders/{}"), so fall
|
||||
* back to segment-wise template matching. (#523) */
|
||||
handler_id =
|
||||
find_route_handler_fuzzy(tgt_store, curl, method[0] ? method : NULL, route_qn,
|
||||
sizeof(route_qn), handler_name, sizeof(handler_name),
|
||||
handler_file, sizeof(handler_file), &query_failed, ctx);
|
||||
}
|
||||
resolve_route_handler(tgt_store, method, curl, &hit, &query_failed, ctx);
|
||||
if (query_failed) {
|
||||
failed = true;
|
||||
break;
|
||||
@@ -674,9 +751,8 @@ static cr_match_result_t match_http_routes(cbm_store_t *src_store, const char *s
|
||||
}
|
||||
|
||||
if (!emit_cross_route_bidirectional(src_store, src_project, src_db, caller_id, route_id,
|
||||
tgt_store, tgt_project, handler_id, route_qn,
|
||||
handler_name, handler_file, url_path, method,
|
||||
"CROSS_HTTP_CALLS", ctx)) {
|
||||
tgt_store, tgt_project, handler_id, hit.qn, hit.name,
|
||||
hit.file, url_path, method, "CROSS_HTTP_CALLS", ctx)) {
|
||||
failed = !cr_cancel_requested(ctx);
|
||||
break;
|
||||
}
|
||||
@@ -1094,15 +1170,13 @@ static int collect_all_projects(char ***out, cr_run_context_t *ctx) {
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
/* Internal stores are exact filenames (cbm_is_internal_cache_db).
|
||||
* Substring filtering would hide legitimate projects such as
|
||||
* orders_config_service or api-wal. */
|
||||
if (!cbm_is_project_index_db(ent->name)) {
|
||||
continue;
|
||||
}
|
||||
size_t len = strlen(ent->name);
|
||||
if (len < CR_COL_4 || strcmp(ent->name + len - CR_DB_EXT_LEN, ".db") != 0) {
|
||||
continue;
|
||||
}
|
||||
/* Internal stores are exact filenames. Substring filtering would hide
|
||||
* legitimate projects such as orders_config_service or api-wal. */
|
||||
if (strcmp(ent->name, "_cross_repo.db") == 0 || strcmp(ent->name, "_config.db") == 0) {
|
||||
continue;
|
||||
}
|
||||
if (count >= CR_MAX_PROJECTS) {
|
||||
failed = true;
|
||||
break;
|
||||
@@ -1239,17 +1313,33 @@ cbm_cross_repo_result_t cbm_cross_repo_match_cancellable(const char *project,
|
||||
result.failed = !result.cancelled;
|
||||
return result;
|
||||
}
|
||||
int other_targets = 0;
|
||||
for (int i = 0; i < resolved_count; i++) {
|
||||
if (cr_cancel_requested(&run)) {
|
||||
result.cancelled = true;
|
||||
free_project_list(resolved, resolved_count);
|
||||
return result;
|
||||
}
|
||||
if (strcmp(resolved[i], project) != 0 && !cr_project_exists(resolved[i])) {
|
||||
if (strcmp(resolved[i], project) == 0) {
|
||||
continue;
|
||||
}
|
||||
if (!cr_project_exists(resolved[i])) {
|
||||
result.failed = true;
|
||||
free_project_list(resolved, resolved_count);
|
||||
return result;
|
||||
}
|
||||
other_targets++;
|
||||
}
|
||||
/* Nothing but the source itself to match against (a self-only list, or
|
||||
* ["*"] in a store holding only the source). Reporting that as success
|
||||
* with projects_scanned:0 is indistinguishable from "these services share
|
||||
* no routes", and the source's existing CROSS_* edges would be wiped below
|
||||
* with nothing to rebuild them. Fail before any write. (#1133) */
|
||||
if (other_targets == 0) {
|
||||
result.failed = true;
|
||||
result.no_targets = true;
|
||||
free_project_list(resolved, resolved_count);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Every input is known to exist before destructive source cleanup. The
|
||||
|
||||
@@ -20,6 +20,7 @@ typedef struct {
|
||||
int projects_scanned;
|
||||
double elapsed_ms;
|
||||
bool failed; /* source/target validation, open, or allocation failed */
|
||||
bool no_targets; /* failed: nothing but the source project resolved (#1133) */
|
||||
bool cancelled; /* stopped at a bounded cancellation checkpoint */
|
||||
bool partial_results; /* committed writes before cancellation were retained */
|
||||
} cbm_cross_repo_result_t;
|
||||
|
||||
@@ -294,6 +294,8 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
|
||||
append_json_str_array(buf, bufsize, &pos, "param_types", def->param_types);
|
||||
append_json_string(buf, bufsize, &pos, "route_path", def->route_path);
|
||||
append_json_string(buf, bufsize, &pos, "route_method", def->route_method);
|
||||
append_json_string(buf, bufsize, &pos, "http_client", def->http_client);
|
||||
append_json_string(buf, bufsize, &pos, "http_base_url", def->http_base_url);
|
||||
|
||||
/* MinHash fingerprint — append if present and buffer has room. */
|
||||
if (def->fingerprint && def->fingerprint_k > 0 &&
|
||||
|
||||
@@ -130,7 +130,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
|
||||
"--since=\"1 year ago\" --max-count=10000 2>%s",
|
||||
repo_path, null_dev);
|
||||
|
||||
FILE *fp = cbm_popen(cmd, "r");
|
||||
FILE *fp = cbm_popen_git(cmd);
|
||||
if (!fp) {
|
||||
return CBM_NOT_FOUND;
|
||||
}
|
||||
|
||||
@@ -522,6 +522,8 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
|
||||
append_json_str_array(buf, bufsize, &pos, "param_types", def->param_types);
|
||||
append_json_string(buf, bufsize, &pos, "route_path", def->route_path);
|
||||
append_json_string(buf, bufsize, &pos, "route_method", def->route_method);
|
||||
append_json_string(buf, bufsize, &pos, "http_client", def->http_client);
|
||||
append_json_string(buf, bufsize, &pos, "http_base_url", def->http_base_url);
|
||||
|
||||
/* MinHash fingerprint — append if present and buffer has room.
|
||||
* Hex-encoded K=64 uint32 = 512 chars + key/quotes ≈ 520 chars. */
|
||||
@@ -940,6 +942,88 @@ static int pp_spill_sweep(extract_ctx_t *ec, int worker_id) {
|
||||
return parked;
|
||||
}
|
||||
|
||||
/* ── Post-extraction projection (#2184) ───────────────────────────────
|
||||
* Spill is entered DURING extraction, when the charge crosses the latch below.
|
||||
* The phases after it -- registry build, cross-LSP prepare (all_defs, the
|
||||
* per-language registries, surface rows, the module index) and resolve (edges
|
||||
* into the graph buffer, cross-LSP appends into the cached results) -- cannot
|
||||
* spill, and they grow the charge by a sizeable fraction of what extraction
|
||||
* left. A run that ended extraction just under the latch therefore kept every
|
||||
* result in memory and went over the budget later: openclaw, 8 workers,
|
||||
* 4079 MB budget: 3678 MB charged at extraction end, 5829 MB in resolve.
|
||||
*
|
||||
* So extraction end projects that growth from the result counts and spills
|
||||
* before handing over when charged + growth would cross the latch. A pure
|
||||
* function of counts (O9): the same repo decides the same way on every run.
|
||||
* Per-unit costs fitted 2026-09-25 (M5 Pro, release build, 8 workers) on the
|
||||
* charge growth from the parallel_extract mark to the parallel_resolve mark:
|
||||
*
|
||||
* corpus files defs calls+usages growth model
|
||||
* go 21882 735895 5,504,282 1307 MB 1909 MB
|
||||
* django 4169 75419 591,350 231 MB 215 MB
|
||||
* kotlin 5247 49669 421,788 129 MB 166 MB
|
||||
* rust 818 23717 265,957 79 MB 76 MB
|
||||
* php 2435 14691 137,969 47 MB 58 MB
|
||||
* openclaw 48203 748829 >= 7,402,832 2151 MB >= 2419 MB
|
||||
*
|
||||
* It never under-reads by more than 7% (inside the budget/16 margin) and
|
||||
* over-reads Go by 46% -- the safe side: an unneeded spill costs disk reads,
|
||||
* never graph content (spilled and in-memory runs build the same graph). */
|
||||
enum {
|
||||
PP_POST_BYTES_PER_DEF = 1280, /* registry entry + LSP def + cross registries */
|
||||
PP_POST_BYTES_PER_REF = 160, /* per call / usage: resolved edge + appends */
|
||||
PP_POST_BYTES_PER_FILE = 8192, /* per-file tables: modules, surfaces, imports */
|
||||
};
|
||||
|
||||
static size_t pp_post_extract_growth(const extract_ctx_t *ec, int64_t *defs_out,
|
||||
int64_t *refs_out) {
|
||||
int64_t defs = 0;
|
||||
int64_t refs = 0;
|
||||
for (int i = 0; i < ec->file_count; i++) {
|
||||
const CBMFileResult *r = ec->result_cache[i];
|
||||
if (r) {
|
||||
defs += r->defs.count;
|
||||
refs += (int64_t)r->calls.count + r->usages.count;
|
||||
}
|
||||
}
|
||||
*defs_out = defs;
|
||||
*refs_out = refs;
|
||||
return (size_t)defs * PP_POST_BYTES_PER_DEF + (size_t)refs * PP_POST_BYTES_PER_REF +
|
||||
(size_t)ec->file_count * PP_POST_BYTES_PER_FILE;
|
||||
}
|
||||
|
||||
/* Enter spill mode at extraction end when the projected post-extraction growth
|
||||
* would carry the charge over the latch; the final sweep then parks every
|
||||
* cached result before registry build. No-op when spill is already on, not
|
||||
* allowed for this owner, or no budget is set. */
|
||||
static void pp_spill_if_projected_over(extract_ctx_t *ec) {
|
||||
size_t budget = cbm_mem_budget();
|
||||
if (budget == 0 || !ec->pctx || !ec->pctx->spill_allowed || !pp_spill_allowed(ec) ||
|
||||
pp_spill_active(ec) || atomic_load_explicit(&ec->over_budget_abort, memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
int64_t defs = 0;
|
||||
int64_t refs = 0;
|
||||
size_t growth = pp_post_extract_growth(ec, &defs, &refs);
|
||||
size_t charged = cbm_mem_charged();
|
||||
size_t line = budget - budget / PP_SPILL_EARLY_DIV;
|
||||
bool spill = growth > line || charged > line - growth;
|
||||
const size_t mb = (size_t)1024 * 1024;
|
||||
char v[6][CBM_SZ_32];
|
||||
snprintf(v[0], sizeof(v[0]), "%zu", charged / mb);
|
||||
snprintf(v[1], sizeof(v[1]), "%zu", growth / mb);
|
||||
snprintf(v[2], sizeof(v[2]), "%zu", line / mb);
|
||||
snprintf(v[3], sizeof(v[3]), "%lld", (long long)defs);
|
||||
snprintf(v[4], sizeof(v[4]), "%lld", (long long)refs);
|
||||
snprintf(v[5], sizeof(v[5]), "%d", ec->file_count);
|
||||
cbm_log_info("mem.post_extract.projection", "charged_mb", v[0], "growth_mb", v[1], "line_mb",
|
||||
v[2], "defs", v[3], "refs", v[4], "files", v[5], "decision",
|
||||
spill ? "spill" : "keep");
|
||||
if (spill) {
|
||||
pp_spill_enter(ec, "post_extract_projection");
|
||||
}
|
||||
}
|
||||
|
||||
/* Diagnostic (CBM_MEM_PHASES=1): where does the charge go between the
|
||||
* near-budget latch and the first over-budget observation? One line per
|
||||
* 256 MB step of the charge above its last logged value while spill mode is
|
||||
@@ -1485,6 +1569,7 @@ int cbm_parallel_extract_ex(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
|
||||
cbm_parallel_for_opts_t parallel_opts = {.max_workers = worker_count, .force_pthreads = false};
|
||||
cbm_scale_begin(&ec.scale, "parallel_extract", (long)file_count);
|
||||
cbm_parallel_for(worker_count, extract_worker, &ec, parallel_opts);
|
||||
pp_spill_if_projected_over(&ec);
|
||||
if (pp_spill_active(&ec) &&
|
||||
!atomic_load_explicit(&ec.over_budget_abort, memory_order_relaxed)) {
|
||||
/* Spill mode was entered, so results belong on disk: park every
|
||||
@@ -1493,7 +1578,9 @@ int cbm_parallel_extract_ex(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
|
||||
* run only on an over-budget observation; a run that latched early
|
||||
* and then stayed under budget through extraction (kernel, 15 GB,
|
||||
* 2026-09-14: 14,949 MB at this point, 44,797 results = 8 GB still
|
||||
* cached) reached resolve with no headroom and aborted there. */
|
||||
* cached) reached resolve with no headroom and aborted there.
|
||||
* The projection above enters spill mode here too when the phases
|
||||
* after extraction would carry the charge over the latch (#2184). */
|
||||
int parked = pp_spill_sweep(&ec, 0);
|
||||
cbm_log_info("mem.spill.final_sweep", "parked", itoa_log(parked), "charged_mb",
|
||||
itoa_log((int)(cbm_mem_charged() / ((size_t)1024 * 1024))));
|
||||
@@ -2895,7 +2982,15 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
|
||||
* semantic candidates are deliberately excluded: they require an
|
||||
* exact LSP target and must fail closed rather than accepting a textual
|
||||
* registry match. */
|
||||
if ((!res.qualified_name || !res.qualified_name[0]) && !call->requires_lsp_resolution) {
|
||||
/* #2053: a Rust call the LSP placed on an EXTERNAL symbol (std's
|
||||
* Path::join, a seeded crate API) is resolved — it just has no graph
|
||||
* node. The textual registry would bind it to a same-named project
|
||||
* method instead, so it must not run for such a row. Mirrors
|
||||
* pass_calls.c; the service fallbacks below still see the call. */
|
||||
bool rust_external = lsp && cbm_pipeline_rust_external_target(
|
||||
lang, lsp->strategy, lsp->callee_qn, rc->project_name);
|
||||
if ((!res.qualified_name || !res.qualified_name[0]) && !call->requires_lsp_resolution &&
|
||||
!rust_external) {
|
||||
res = cbm_registry_resolve(rc->registry, call->callee_name, module_qn, imp_keys,
|
||||
imp_vals, imp_count);
|
||||
}
|
||||
@@ -2957,7 +3052,14 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
|
||||
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);
|
||||
call->callee_is_locally_bound, res.strategy) ||
|
||||
/* Import-binding suppression (#2127) — see pass_calls.c; this gate
|
||||
* MUST stay identical to the one there. */
|
||||
(lang == CBM_LANG_PYTHON &&
|
||||
cbm_suppress_weak_import_bound_call(true, true, res.strategy) &&
|
||||
cbm_python_import_binding_contradicts(&result->imports, call->callee_name,
|
||||
res.qualified_name, rc->main_gbuf,
|
||||
rc->project_name, rel));
|
||||
|
||||
/* Service-pattern HTTP/ASYNC client call (`requests.get(url)`): the
|
||||
* service signal lives in the callee_name. The registry can mis-resolve
|
||||
@@ -2966,7 +3068,22 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
|
||||
* pattern, so the resolved-QN service checks below miss it and the call
|
||||
* is dropped. Detect it on the callee_name FIRST so the HTTP_CALLS/
|
||||
* ASYNC_CALLS edge is emitted regardless (target is a synthesized route
|
||||
* node, not the unindexed library). Mirrors pass_calls.c. (#523) */
|
||||
* node, not the unindexed library). Mirrors pass_calls.c. (#523)
|
||||
*
|
||||
* First: a call on an axios.create() instance (#1916) — decided by the
|
||||
* receiver's binding, before the #523 spelling check and the
|
||||
* route-registration suffix fallback. MUST match pass_calls.c. */
|
||||
char client_url[CBM_SZ_512];
|
||||
if (cbm_pipeline_http_client_call_url(rc->main_gbuf, rc->project_name, rel, result,
|
||||
imp_keys, imp_vals, imp_count, call, client_url,
|
||||
sizeof(client_url))) {
|
||||
cbm_resolution_t svc_res = {.qualified_name = call->callee_name,
|
||||
.confidence = PP_HALF_CONF,
|
||||
.strategy = "http_client_instance"};
|
||||
emit_http_async_service_edge(ws->local_edge_buf, source_node, call, &svc_res,
|
||||
CBM_SVC_HTTP, client_url);
|
||||
continue;
|
||||
}
|
||||
cbm_svc_kind_t csvc = cbm_service_pattern_match(call->callee_name);
|
||||
if (csvc == CBM_SVC_HTTP || csvc == CBM_SVC_ASYNC) {
|
||||
const char *cu = call->first_string_arg;
|
||||
@@ -2989,9 +3106,14 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
|
||||
cbm_resolution_t fake_res = {.qualified_name = call->callee_name,
|
||||
.confidence = PP_HALF_CONF,
|
||||
.strategy = "callee_suffix"};
|
||||
/* #2053: an LSP-external Rust call (`map.get(k)` on a std
|
||||
* HashMap) reaches this branch only because its registry
|
||||
* fallback was skipped. Without a route path the plain-CALLS
|
||||
* fall-through would bind source -> source, a fabricated
|
||||
* self-call, so it keeps only the route/service edges. */
|
||||
emit_service_edge(ws->local_edge_buf, source_node, source_node, call, &fake_res,
|
||||
module_qn, rc->registry, rc->main_gbuf, imp_keys, imp_vals,
|
||||
imp_count, false);
|
||||
imp_count, rust_external);
|
||||
} else if (cbm_service_pattern_is_global_fetch(call->callee_name)) {
|
||||
/* Native `fetch()` (#856): only the global API once resolution
|
||||
* has failed to find a local/imported `fetch`. Call the low-level
|
||||
|
||||
+217
-2
@@ -1543,6 +1543,213 @@ static bool import_targetable_label(const char *label) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* #2127: a Python import path spells the module chain that owns the imported
|
||||
* name (`from unittest.mock import patch` -> unittest, mock). Strategy 3 matches
|
||||
* the leaf name alone, so an EXTERNAL import (stdlib / third party: no project
|
||||
* module, Strategy 1 misses) bound to any same-named project definition -- a
|
||||
* REST view's `patch` handler became the target of every mock.patch call at
|
||||
* import_map confidence. For such an external import, accept a symbol hit only
|
||||
* when the module segments preceding `name` in the import path occur, in
|
||||
* order, among the hit's enclosing QN segments -- a src/ layout or sys.path
|
||||
* root the module resolver missed (`from template_tests.utils import setup` ->
|
||||
* proj.tests.template_tests.utils.setup) still qualifies. Relative prefixes
|
||||
* (leading dots) carry no segment and are skipped. Imports of project modules
|
||||
* are never judged by it (they may re-export from anywhere). Python only. */
|
||||
enum { PY_IMPORT_MAX_SEGS = 64 };
|
||||
bool cbm_python_import_path_matches_qn(const char *module_path, const char *name,
|
||||
const char *hit_qn) {
|
||||
if (!module_path || !name || !hit_qn) {
|
||||
return true;
|
||||
}
|
||||
char path[1024];
|
||||
snprintf(path, sizeof(path), "%s", module_path);
|
||||
char *as = strstr(path, " as ");
|
||||
if (as) {
|
||||
*as = '\0';
|
||||
}
|
||||
const char *p = path;
|
||||
while (*p == '.') {
|
||||
p++;
|
||||
}
|
||||
/* Segments of the import path; name_at = index of the LAST `name`. */
|
||||
const char *segs[PY_IMPORT_MAX_SEGS];
|
||||
size_t lens[PY_IMPORT_MAX_SEGS];
|
||||
int nseg = 0;
|
||||
int name_at = -1;
|
||||
size_t name_len = strlen(name);
|
||||
while (*p && nseg < PY_IMPORT_MAX_SEGS) {
|
||||
const char *dot = strchr(p, '.');
|
||||
size_t len = dot ? (size_t)(dot - p) : strlen(p);
|
||||
if (len == name_len && strncmp(p, name, len) == 0) {
|
||||
name_at = nseg;
|
||||
}
|
||||
segs[nseg] = p;
|
||||
lens[nseg] = len;
|
||||
nseg++;
|
||||
if (!dot) {
|
||||
break;
|
||||
}
|
||||
p = dot + SKIP_ONE;
|
||||
}
|
||||
if (name_at <= 0) {
|
||||
return true; /* no module chain before the name: nothing to check */
|
||||
}
|
||||
/* Ordered-subsequence match against the hit's enclosing segments (every
|
||||
* segment before the hit's own leaf). */
|
||||
const char *leaf = strrchr(hit_qn, '.');
|
||||
const char *q = hit_qn;
|
||||
int want = 0;
|
||||
while (want < name_at && leaf && q < leaf) {
|
||||
const char *dot = strchr(q, '.');
|
||||
size_t len = (size_t)(dot - q);
|
||||
if (len == lens[want] && strncmp(q, segs[want], len) == 0) {
|
||||
want++;
|
||||
}
|
||||
q = dot + SKIP_ONE;
|
||||
}
|
||||
return want == name_at;
|
||||
}
|
||||
|
||||
/* #2127, call side: an imported name binds the file's identifier to that
|
||||
* import for the whole module, exactly like a parameter binds it for a body.
|
||||
* When the import could not be materialized (external module) the resolver
|
||||
* falls through to project-wide short-name strategies and binds `patch(...)`
|
||||
* (or `mock.patch(...)`) to whatever project definition shares the leaf. True
|
||||
* when the callee's root identifier is bound by this file's Python imports and
|
||||
* EVERY such binding's module chain (`unittest.mock` for `from unittest.mock
|
||||
* import patch`; the callee's own dotted path for a root `import a.b`) is
|
||||
* absent from `resolved_qn`'s enclosing segments AND the binding is external
|
||||
* (no IMPORTS edge materialized it: the module is not in the project). An
|
||||
* internal binding is never judged here -- a project module can re-export a
|
||||
* name from anywhere -- and a chain consistent with the target (src/ layout)
|
||||
* keeps the edge. `gbuf` NULL means "no IMPORTS edges" (all external). */
|
||||
static bool python_import_local_materialized(const cbm_gbuf_t *gbuf, const char *project_name,
|
||||
const char *rel_path, const char *local_name) {
|
||||
if (!gbuf || !rel_path) {
|
||||
return false;
|
||||
}
|
||||
char *file_qn = cbm_pipeline_fqn_compute(project_name, rel_path, "__file__");
|
||||
const cbm_gbuf_node_t *file_node = file_qn ? cbm_gbuf_find_by_qn(gbuf, file_qn) : NULL;
|
||||
safe_free(file_qn);
|
||||
const cbm_gbuf_edge_t **edges = NULL;
|
||||
int edge_count = 0;
|
||||
if (!file_node || cbm_gbuf_find_edges_by_source_type(gbuf, file_node->id, "IMPORTS", &edges,
|
||||
&edge_count) != 0) {
|
||||
return false;
|
||||
}
|
||||
char needle[CBM_SZ_256];
|
||||
snprintf(needle, sizeof(needle), "\"local_name\":\"%s\"", local_name);
|
||||
for (int i = 0; i < edge_count; i++) {
|
||||
if (edges[i]->properties_json && strstr(edges[i]->properties_json, needle)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool cbm_python_import_binding_contradicts(const CBMImportArray *imports, const char *callee_name,
|
||||
const char *resolved_qn, const cbm_gbuf_t *gbuf,
|
||||
const char *project_name, const char *rel_path) {
|
||||
if (!imports || imports->count <= 0 || !callee_name || !callee_name[0] || !resolved_qn ||
|
||||
!resolved_qn[0]) {
|
||||
return false;
|
||||
}
|
||||
const char *root_end = strchr(callee_name, '.');
|
||||
size_t root_len = root_end ? (size_t)(root_end - callee_name) : strlen(callee_name);
|
||||
bool bound = false;
|
||||
for (int i = 0; i < imports->count; i++) {
|
||||
const CBMImport *imp = &imports->items[i];
|
||||
if (!imp->local_name || !imp->module_path || strlen(imp->local_name) != root_len ||
|
||||
strncmp(imp->local_name, callee_name, root_len) != 0) {
|
||||
continue;
|
||||
}
|
||||
char full[1024];
|
||||
snprintf(full, sizeof(full), "%s", imp->module_path);
|
||||
char *as = strstr(full, " as ");
|
||||
if (as) {
|
||||
*as = '\0';
|
||||
}
|
||||
const char *path_leaf_seg = strrchr(full, '.');
|
||||
bool from_import = path_leaf_seg && strcmp(path_leaf_seg + SKIP_ONE, imp->local_name) == 0;
|
||||
if (!as && !from_import && strncmp(full, callee_name, root_len) == 0 &&
|
||||
(full[root_len] == '.' || full[root_len] == '\0')) {
|
||||
/* `import a.b` binds the ROOT package `a`: the callee already
|
||||
* spells its own full dotted path (`a.b.f()`). */
|
||||
snprintf(full, sizeof(full), "%s", callee_name);
|
||||
}
|
||||
/* Otherwise (`from m import x [as y]`) only the import's own module
|
||||
* chain is evidence: members reached THROUGH x (`x.objects.create`)
|
||||
* may live on any type, so they are not compared. */
|
||||
const char *leaf = strrchr(full, '.');
|
||||
leaf = leaf ? leaf + SKIP_ONE : full;
|
||||
if (cbm_python_import_path_matches_qn(full, leaf, resolved_qn) ||
|
||||
python_import_local_materialized(gbuf, project_name, rel_path, imp->local_name)) {
|
||||
return false; /* consistent with the target, or a project import */
|
||||
}
|
||||
bound = true;
|
||||
}
|
||||
return bound;
|
||||
}
|
||||
|
||||
/* #2127: whether a Python import's module lives in this project. Relative
|
||||
* imports always do; otherwise the module part (the path minus the imported
|
||||
* name) must resolve to a graph node. Strategy 1 has already failed on the
|
||||
* full path when this is asked. */
|
||||
static bool python_import_module_in_project(const cbm_pipeline_ctx_t *ctx, const char *source_rel,
|
||||
const char *module_path) {
|
||||
if (!module_path || module_path[0] == '.') {
|
||||
return true;
|
||||
}
|
||||
char part[1024];
|
||||
snprintf(part, sizeof(part), "%s", module_path);
|
||||
char *as = strstr(part, " as ");
|
||||
if (as) {
|
||||
*as = '\0';
|
||||
}
|
||||
char *dot = strrchr(part, '.');
|
||||
if (!dot) {
|
||||
return false; /* `import x`: Strategy 1 already missed x itself */
|
||||
}
|
||||
*dot = '\0';
|
||||
char *qn = cbm_pipeline_resolve_module(ctx, source_rel, part);
|
||||
bool found = qn && cbm_gbuf_find_by_qn(ctx->gbuf, qn) != NULL;
|
||||
safe_free(qn);
|
||||
return found;
|
||||
}
|
||||
|
||||
/* `import a.b` / `import a` (as opposed to `from a import b`): every segment
|
||||
* names a module. The extractor binds the ROOT (`a`) for a dotted plain
|
||||
* import and the leaf for a from-import; a dot-less path is always a plain
|
||||
* import. An aliased form is ambiguous and reads as a from-import. */
|
||||
static bool python_is_plain_module_import(const CBMImport *imp) {
|
||||
const char *p = imp->module_path;
|
||||
if (!p || p[0] == '.' || strstr(p, " as ")) {
|
||||
return false;
|
||||
}
|
||||
const char *first_dot = strchr(p, '.');
|
||||
if (!first_dot) {
|
||||
return true;
|
||||
}
|
||||
const char *leaf = strrchr(p, '.') + SKIP_ONE;
|
||||
size_t root_len = (size_t)(first_dot - p);
|
||||
return imp->local_name && strlen(imp->local_name) == root_len &&
|
||||
strncmp(imp->local_name, p, root_len) == 0 && strcmp(leaf, imp->local_name) != 0;
|
||||
}
|
||||
|
||||
/* #2127: Strategy 3 hit filter for an EXTERNAL Python import. The hit must
|
||||
* spell the import's module chain (a src/ layout the module resolver missed
|
||||
* still does), and whatever names a module -- an enclosing path segment, or
|
||||
* any segment of a plain `import x` -- can only be a Module/File node (`import
|
||||
* copy` must not fall back to a project method called `copy`). */
|
||||
static bool python_external_hit_rejected(const CBMImport *imp, const char *name,
|
||||
bool enclosing_segment, const cbm_gbuf_node_t *hit) {
|
||||
if (!cbm_python_import_path_matches_qn(imp->module_path, name, hit->qualified_name)) {
|
||||
return true;
|
||||
}
|
||||
bool names_module = enclosing_segment || python_is_plain_module_import(imp);
|
||||
return names_module && strcmp(hit->label, "Module") != 0 && strcmp(hit->label, "File") != 0;
|
||||
}
|
||||
|
||||
/* #1934: whether the name-guess import fallbacks — Strategy 1b (sibling file,
|
||||
* whose label filter admits symbols) and Strategy 3 (symbol name) — may run
|
||||
* for imports from this language. A Go import path names a package — never a
|
||||
@@ -1882,8 +2089,8 @@ const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_t
|
||||
src_base = pb + SKIP_ONE;
|
||||
}
|
||||
}
|
||||
const bool symbol_fallback_allowed =
|
||||
cbm_import_symbol_fallback_allowed(cbm_language_for_filename(src_base));
|
||||
const CBMLanguage src_lang = cbm_language_for_filename(src_base);
|
||||
const bool symbol_fallback_allowed = cbm_import_symbol_fallback_allowed(src_lang);
|
||||
|
||||
/* Strategy 1b: sibling-file resolution for build/markup grammars whose
|
||||
* import string is a sibling filename or directory (SCSS partials, Just/
|
||||
@@ -2033,6 +2240,11 @@ const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_t
|
||||
*dot = '\0';
|
||||
end = dot;
|
||||
}
|
||||
/* #2127: a Python import whose module is not in the project (stdlib /
|
||||
* third party) may only fall back to a hit that spells its chain. */
|
||||
const bool py_external =
|
||||
symbol_fallback_allowed && src_lang == CBM_LANG_PYTHON &&
|
||||
!python_import_module_in_project(ctx, source_rel, imp->module_path);
|
||||
for (int ci = 0; symbol_fallback_allowed && ci < ncands; ci++) {
|
||||
const cbm_gbuf_node_t **hits = NULL;
|
||||
int n = 0;
|
||||
@@ -2054,6 +2266,9 @@ const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_t
|
||||
strcmp(cand->qualified_name, source_file_qn) == 0) {
|
||||
continue; /* self */
|
||||
}
|
||||
if (py_external && python_external_hit_rejected(imp, cands[ci], ci > 0, cand)) {
|
||||
continue; /* #2127: not the external module's symbol */
|
||||
}
|
||||
if (!best || (cand->qualified_name && best->qualified_name &&
|
||||
strcmp(cand->qualified_name, best->qualified_name) < 0)) {
|
||||
best = cand;
|
||||
|
||||
@@ -1194,7 +1194,7 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c
|
||||
}
|
||||
str_def_fp += def->fingerprint ? (size_t)def->fingerprint_k * sizeof(uint32_t) : 0;
|
||||
str_def_misc += census_len(def->route_path) + census_len(def->route_method) +
|
||||
census_len(def->impl_trait);
|
||||
census_len(def->impl_trait) + census_len(def->http_base_url);
|
||||
}
|
||||
for (int c = 0; c < r->calls.count; c++) {
|
||||
const CBMCall *call = &r->calls.items[c];
|
||||
|
||||
@@ -213,6 +213,13 @@ char *cbm_pipeline_resolve_relative_import(const char *source_rel, const char *m
|
||||
* Caller must free() the returned string. */
|
||||
char *cbm_project_name_from_path(const char *abs_path);
|
||||
|
||||
/* The name-mapping half of cbm_project_name_from_path, WITHOUT path
|
||||
* canonicalization: maps any string to the stored project-name form (unsafe
|
||||
* ASCII -> '-', non-ASCII bytes -> two hex digits, dash/dot collapse, trim,
|
||||
* #624 length cap). Lets a selector such as a bare non-ASCII folder name be
|
||||
* encoded exactly like the segment it came from (#1827). Caller frees. */
|
||||
char *cbm_project_name_sanitize(const char *name_path);
|
||||
|
||||
/* ── Function Registry ──────────────────────────────────────────── */
|
||||
|
||||
typedef struct cbm_registry cbm_registry_t;
|
||||
@@ -327,6 +334,16 @@ bool cbm_weak_member_unique_name_exempt(bool is_python, bool receiver_is_self_at
|
||||
bool cbm_suppress_weak_local_binding_call(bool enabled, bool callee_is_locally_bound,
|
||||
const char *strategy);
|
||||
|
||||
/* Import-binding counterpart (#2127). True when the callee's root identifier
|
||||
* is bound by an import of this file whose module chain contradicts the
|
||||
* resolved target (`from unittest.mock import patch; patch()` must not bind a
|
||||
* project `PkgConfigView.patch`), and the match came from a weak short-name
|
||||
* strategy. Same drop-list as the guards above; the language set lives at the
|
||||
* call sites and must be identical in pass_calls.c and pass_parallel.c.
|
||||
* Pure; unit-tested in test_registry.c. */
|
||||
bool cbm_suppress_weak_import_bound_call(bool enabled, bool import_binding_contradicts,
|
||||
const char *strategy);
|
||||
|
||||
/* #725: drop a suffix_match CALLS edge when the caller language and the
|
||||
* target file's language disagree. unique_name (candidates == 1) is #1572
|
||||
* and is left alone; same_module / import_map / lsp_* are kept. JS/TS/TSX
|
||||
|
||||
@@ -287,13 +287,25 @@ int64_t cbm_delta_preseed(cbm_store_t *store, const char *project, cbm_gbuf_t *g
|
||||
* UNIQUE violation the pre-remap patch would have raised. A resolver that
|
||||
* only LOOKS UP still needs its target resident, which is why the list
|
||||
* mirrors the registry's own membership rule instead of guessing. */
|
||||
/* The one property a resolver READS off a proxy: an axios instance
|
||||
* binding's client + baseURL (#1916). A caller re-resolved alone must
|
||||
* compose `api.get('/p')` against its unchanged wrapper exactly as a full
|
||||
* build does. Only the two keys, only on the rare Module/Variable rows
|
||||
* that carry them; every other proxy stays "{}". Proxies are never
|
||||
* written back (cbm_delta_patch skips id <= max_db_id). */
|
||||
sqlite3_stmt *stmt = NULL;
|
||||
if (sqlite3_prepare_v2(db,
|
||||
"SELECT id, label, name, qualified_name, file_path FROM nodes"
|
||||
" WHERE project = ?1 AND label NOT IN"
|
||||
" ('Macro','Comment','Section','Branch','Commit','Tag')"
|
||||
" ORDER BY id",
|
||||
CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
|
||||
if (sqlite3_prepare_v2(
|
||||
db,
|
||||
"SELECT id, label, name, qualified_name, file_path,"
|
||||
" CASE WHEN label IN ('Module','Variable')"
|
||||
" AND instr(properties, '\"http_client\"') > 0"
|
||||
" THEN json_object('http_client', json_extract(properties, '$.http_client'),"
|
||||
" 'http_base_url', json_extract(properties, '$.http_base_url')) END"
|
||||
" FROM nodes"
|
||||
" WHERE project = ?1 AND label NOT IN"
|
||||
" ('Macro','Comment','Section','Branch','Commit','Tag')"
|
||||
" ORDER BY id",
|
||||
CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
|
||||
return -1;
|
||||
}
|
||||
sqlite3_bind_text(stmt, 1, project, CBM_NOT_FOUND, SQLITE_TRANSIENT);
|
||||
@@ -305,9 +317,11 @@ int64_t cbm_delta_preseed(cbm_store_t *store, const char *project, cbm_gbuf_t *g
|
||||
const char *name = (const char *)sqlite3_column_text(stmt, 2);
|
||||
const char *qn = (const char *)sqlite3_column_text(stmt, 3);
|
||||
const char *fp = (const char *)sqlite3_column_text(stmt, 4);
|
||||
const char *client_props = (const char *)sqlite3_column_text(stmt, 5);
|
||||
/* Pin the gbuf id to the database id: proxies ARE their rows. */
|
||||
cbm_gbuf_set_next_id(gbuf, id);
|
||||
int64_t got = cbm_gbuf_upsert_node(gbuf, label, name, qn, fp ? fp : "", 0, 0, "{}");
|
||||
int64_t got = cbm_gbuf_upsert_node(gbuf, label, name, qn, fp ? fp : "", 0, 0,
|
||||
client_props ? client_props : "{}");
|
||||
if (got != id) {
|
||||
/* A QN collision inside the preseed set would silently split
|
||||
* identity between RAM and disk; the run cannot be trusted. */
|
||||
|
||||
@@ -23,7 +23,10 @@
|
||||
|
||||
/* ── Shared pipeline constants ─────────────────────────────────── */
|
||||
|
||||
/* Maximum byte budget for tree-sitter extraction per file */
|
||||
/* Per-file tree-sitter parse budget, in MICROSECONDS of this thread's CPU time
|
||||
* (5 s). Passed as cbm_extract_file*()'s timeout_micros; a generous wall-clock
|
||||
* ceiling (CBM_PARSE_WALL_CEILING_FACTOR x, ~60 s) backstops a stuck parse.
|
||||
* It is a time budget, not a byte budget. */
|
||||
#define CBM_EXTRACT_BUDGET 5000000
|
||||
|
||||
/* Route node QN buffer size (must fit __route__METHOD__/full/url/path) */
|
||||
@@ -211,6 +214,21 @@ void cbm_pipeline_set_pkgmap(CBMHashTable *map);
|
||||
char *cbm_pipeline_resolve_module(const cbm_pipeline_ctx_t *ctx, const char *source_rel,
|
||||
const char *module_path);
|
||||
|
||||
/* #1916: HTTP client-instance calls. When `call` is `<recv>.<verb>(url)` with
|
||||
* an HTTP verb suffix and a path/URL first argument, and `recv` is bound —
|
||||
* in the calling module itself, or via an ES import (named or default) — to a
|
||||
* binding the extractor marked as an `axios.create(...)` instance
|
||||
* (`http_client` node property), write the request URL to `out` (the
|
||||
* instance's literal `http_base_url` joined with a '/'-leading path, the path
|
||||
* unchanged when the base is unknown or the URL is absolute) and return true.
|
||||
* Both call resolvers (pass_calls.c, pass_parallel.c) call this before any
|
||||
* route-registration or registry fallback, so a wrapper client's `api.get`
|
||||
* is never mistaken for an Express `app.get` route registration. */
|
||||
bool cbm_pipeline_http_client_call_url(const cbm_gbuf_t *gbuf, const char *project, const char *rel,
|
||||
const CBMFileResult *result, const char **imp_keys,
|
||||
const char **imp_vals, int imp_count, const CBMCall *call,
|
||||
char *out, size_t out_sz);
|
||||
|
||||
/* Resolve an import to its in-graph target node, or NULL if unresolvable.
|
||||
*
|
||||
* Resolution order (first hit wins):
|
||||
@@ -282,6 +300,23 @@ static inline int cbm_pipeline_check_cancel(const cbm_pipeline_ctx_t *ctx) {
|
||||
* ei_go_import_never_binds_symbol. */
|
||||
bool cbm_import_symbol_fallback_allowed(CBMLanguage lang);
|
||||
|
||||
/* #2127: true when the module segments preceding `name` in a Python import
|
||||
* path (`unittest.mock.patch` -> unittest, mock) occur, in order, among the
|
||||
* enclosing segments of `hit_qn`. Leading relative dots and ` as alias` are
|
||||
* ignored; a path with no module chain before `name` always matches. Gates
|
||||
* the import resolver's symbol-name fallback for Python. */
|
||||
bool cbm_python_import_path_matches_qn(const char *module_path, const char *name,
|
||||
const char *hit_qn);
|
||||
|
||||
/* #2127: true when the callee's root identifier is bound by the file's Python
|
||||
* imports and every such binding is EXTERNAL (no IMPORTS edge from `rel_path`
|
||||
* in `gbuf` carries its local name; NULL gbuf = none) with a module chain that
|
||||
* contradicts `resolved_qn`. Feeds cbm_suppress_weak_import_bound_call at both
|
||||
* resolver call sites. */
|
||||
bool cbm_python_import_binding_contradicts(const CBMImportArray *imports, const char *callee_name,
|
||||
const char *resolved_qn, const cbm_gbuf_t *gbuf,
|
||||
const char *project_name, const char *rel_path);
|
||||
|
||||
/* Check if a file path is worth tracking for git history analysis. */
|
||||
bool cbm_is_trackable_file(const char *path);
|
||||
|
||||
|
||||
@@ -695,6 +695,22 @@ bool cbm_suppress_weak_local_binding_call(bool enabled, bool callee_is_locally_b
|
||||
return weak_short_name_strategy(strategy);
|
||||
}
|
||||
|
||||
/* Import-binding counterpart of the parameter guard above (#2127). An import
|
||||
* binds the identifier for the whole module; when that import is external it
|
||||
* never materializes, and the chain falls through to project-wide short-name
|
||||
* strategies (`from unittest.mock import patch; patch()` -> a REST view's
|
||||
* `PkgConfigView.patch`). The caller decides whether the binding contradicts
|
||||
* the target (cbm_python_import_binding_contradicts: a SCOPE FACT about this
|
||||
* file, not a spelling list); only weak strategies are dropped, so import_map /
|
||||
* same_module / lsp_* edges are untouched. Pure; unit-tested in test_registry.c. */
|
||||
bool cbm_suppress_weak_import_bound_call(bool enabled, bool import_binding_contradicts,
|
||||
const char *strategy) {
|
||||
if (!enabled || !import_binding_contradicts) {
|
||||
return false;
|
||||
}
|
||||
return weak_short_name_strategy(strategy);
|
||||
}
|
||||
|
||||
static bool js_ts_family(CBMLanguage lang) {
|
||||
return lang == CBM_LANG_JAVASCRIPT || lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX ||
|
||||
lang == CBM_LANG_ARKTS;
|
||||
|
||||
+15
-9
@@ -230,6 +230,18 @@ static void iso_now(char *buf, size_t sz) {
|
||||
|
||||
/* ── Schema ─────────────────────────────────────────────────────── */
|
||||
|
||||
bool cbm_store_edges_schema_current(cbm_store_t *s) {
|
||||
sqlite3_stmt *probe = NULL;
|
||||
if (!s || !s->db ||
|
||||
sqlite3_prepare_v2(s->db, "SELECT local_name_gen FROM edges LIMIT 0;", CBM_NOT_FOUND,
|
||||
&probe, NULL) != SQLITE_OK) {
|
||||
sqlite3_finalize(probe);
|
||||
return false;
|
||||
}
|
||||
sqlite3_finalize(probe);
|
||||
return true;
|
||||
}
|
||||
|
||||
static int init_schema(cbm_store_t *s) {
|
||||
const char *ddl =
|
||||
"CREATE TABLE IF NOT EXISTS projects ("
|
||||
@@ -357,15 +369,9 @@ static int init_schema(cbm_store_t *s) {
|
||||
* callers already treat an unopenable DB as incompatible (a full index
|
||||
* deletes + rebuilds it, artifact import refuses and falls back to a
|
||||
* reindex). Read-only query opens skip init_schema and keep working. */
|
||||
{
|
||||
sqlite3_stmt *probe = NULL;
|
||||
if (sqlite3_prepare_v2(s->db, "SELECT local_name_gen FROM edges LIMIT 0;", CBM_NOT_FOUND,
|
||||
&probe, NULL) != SQLITE_OK) {
|
||||
cbm_log_warn("store.schema", "result", "incompatible", "missing",
|
||||
"edges.local_name_gen");
|
||||
return CBM_STORE_ERR;
|
||||
}
|
||||
sqlite3_finalize(probe);
|
||||
if (!cbm_store_edges_schema_current(s)) {
|
||||
cbm_log_warn("store.schema", "result", "incompatible", "missing", "edges.local_name_gen");
|
||||
return CBM_STORE_ERR;
|
||||
}
|
||||
|
||||
/* FTS5 contentless virtual table for BM25 full-text search.
|
||||
|
||||
@@ -371,6 +371,11 @@ const char *cbm_store_db_path(const cbm_store_t *s);
|
||||
* (projects table has correct types, no corruption indicators).
|
||||
* Returns false if corruption is detected — caller should delete and re-index. */
|
||||
bool cbm_store_check_integrity(cbm_store_t *s);
|
||||
/* True when the edges table carries the #768 local_name_gen discriminator —
|
||||
* the schema a read-write open (cbm_store_open_path_existing) requires. A
|
||||
* pre-#768 store still serves read-only queries but refuses every write open
|
||||
* until it is reindexed. Read-only: safe on a store opened for query. */
|
||||
bool cbm_store_edges_schema_current(cbm_store_t *s);
|
||||
/* Shallow check + PRAGMA quick_check — catches page-level corruption.
|
||||
* O(db size); use on rare paths (artifact import), not hot opens. */
|
||||
bool cbm_store_check_integrity_deep(cbm_store_t *s);
|
||||
|
||||
@@ -2064,10 +2064,11 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,
|
||||
/* ── Public API ───────────────────────────────────────────────── */
|
||||
|
||||
static char *http_read_only_index_rejected(void *context, const char *repo_path,
|
||||
const char *args_json) {
|
||||
const char *args_json, bool async) {
|
||||
(void)context;
|
||||
(void)repo_path;
|
||||
(void)args_json;
|
||||
(void)async;
|
||||
return cbm_mcp_text_result("UI RPC indexing is disabled; use the coordinated /api/index route",
|
||||
true);
|
||||
}
|
||||
|
||||
@@ -393,6 +393,7 @@ static watcher_git_status_t watcher_git_run(cbm_watcher_t *w, project_state_t *s
|
||||
.quiet_timeout_ms = 0,
|
||||
.cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,
|
||||
.delete_log_on_exit = false,
|
||||
.strip_git_repo_env = true, /* #2003: an inherited GIT_DIR must not redirect -C */
|
||||
};
|
||||
cbm_subprocess_t *process = NULL;
|
||||
if (cbm_subprocess_spawn(&options, &process) != 0) {
|
||||
|
||||
@@ -28,6 +28,7 @@ int tf_skip_count = 0;
|
||||
#include "test_framework.h"
|
||||
#include "repro_runner.h"
|
||||
#include "foundation/compat.h" /* cbm_setenv — #845 supervisor kill switch */
|
||||
#include "daemon/bootstrap.h" /* refuse the developer's default daemon rendezvous */
|
||||
|
||||
/* Per-suite summary + filter. RUN_SUITE prints a one-line
|
||||
* "[SUITE] <name> P passed, F failed" report (greppable for which suites still
|
||||
@@ -131,6 +132,13 @@ int main(void) {
|
||||
* supervisor gate already ignores unmarked hosts; pin the kill switch too.
|
||||
* A test that exercises the supervisor must explicitly re-enable it. */
|
||||
cbm_setenv("CBM_INDEX_SUPERVISOR", "0", 1);
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* No reproduction needs the daemon rendezvous. Its default is the
|
||||
* developer's live daemon whatever HOME says, so a case that ever resolves
|
||||
* an endpoint without an explicit parent or CBM_RUNTIME_DIR is refused
|
||||
* loudly instead of reaching it. */
|
||||
cbm_daemon_bootstrap_forbid_default_runtime_for_test(true);
|
||||
#endif
|
||||
|
||||
/* Unbuffered: a reproduction may crash/_exit (or a sanitizer may _exit on a
|
||||
* leak) before stdio flushes — keep every printed line so the summary and the
|
||||
|
||||
@@ -2086,6 +2086,28 @@ TEST(clsp_structured_binding_struct) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1743: a structured binding with more names than the struct has fields
|
||||
* (ill-formed C++, but common in compiler test suites such as LLVM's
|
||||
* dcl.decomp tests) indexed field_types[] past its NULL terminator. The read
|
||||
* landed in the next arena object and bound a garbage pointer (0x9) as the
|
||||
* type, which decltype() then dereferenced: a deterministic SIGSEGV at
|
||||
* address 9 in c_resolve_name_to_type. Extra names must bind as unknown. */
|
||||
TEST(clsp_structured_binding_more_names_than_fields) {
|
||||
CBMFileResult *r = extract_cpp("struct A { int x, y; };\n"
|
||||
"const auto &[acr0, acr1, acr2] = A();\n"
|
||||
"using ConstFloatRef = decltype(acr2);\n"
|
||||
"void test() {\n"
|
||||
" auto [b0, b1, b2, b3] = A();\n"
|
||||
" using T = decltype(b3);\n"
|
||||
" for (auto [c0, c1, c2, c3] : (A *)0) {\n"
|
||||
" using U = decltype(c3);\n"
|
||||
" }\n"
|
||||
"}\n");
|
||||
ASSERT_NOT_NULL(r);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(clsp_ternary_type) {
|
||||
CBMFileResult *r = extract_cpp("\n"
|
||||
"class Widget {\n"
|
||||
@@ -16486,6 +16508,7 @@ SUITE(c_lsp) {
|
||||
RUN_TEST(clsp_tad_make_pair_like);
|
||||
RUN_TEST(clsp_structured_binding_pair);
|
||||
RUN_TEST(clsp_structured_binding_struct);
|
||||
RUN_TEST(clsp_structured_binding_more_names_than_fields);
|
||||
RUN_TEST(clsp_ternary_type);
|
||||
RUN_TEST(clsp_chained_method_calls);
|
||||
RUN_TEST(clsp_std_vector_push_back);
|
||||
|
||||
@@ -18,11 +18,13 @@
|
||||
#include <cli/cli.h>
|
||||
#include <cli/progress_sink.h>
|
||||
#include <daemon/bootstrap.h>
|
||||
#include <daemon/ipc.h>
|
||||
#include <daemon/runtime.h>
|
||||
#include <daemon/version_cohort.h>
|
||||
#include <foundation/constants.h>
|
||||
#include <foundation/log.h>
|
||||
#include <foundation/platform.h>
|
||||
#include <foundation/private_file_lock.h>
|
||||
#include <foundation/sha256.h>
|
||||
#include <mcp/mcp.h>
|
||||
#include <mcp/index_supervisor.h>
|
||||
@@ -2037,6 +2039,139 @@ TEST(cli_install_skip_binary_unchanged_in_host_namespace_quiesces_nothing) {
|
||||
ASSERT_TRUE(nothing_drained);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* cli_scope_install with the activation's stdout captured into out. */
|
||||
static int cli_scope_install_captured(cli_scope_fixture_t *fixture, const char *home,
|
||||
const char *cache, const char *bin_dir, bool skip_binary,
|
||||
char *out, size_t out_size) {
|
||||
out[0] = '\0';
|
||||
FILE *capture = tmpfile();
|
||||
int saved_stdout = capture ? dup(STDOUT_FILENO) : -1;
|
||||
bool redirected = false;
|
||||
if (capture && saved_stdout >= 0) {
|
||||
fflush(stdout);
|
||||
redirected = dup2(fileno(capture), STDOUT_FILENO) >= 0;
|
||||
}
|
||||
int rc = redirected ? cli_scope_install(fixture, home, cache, bin_dir, skip_binary) : -1;
|
||||
if (redirected) {
|
||||
fflush(stdout);
|
||||
(void)dup2(saved_stdout, STDOUT_FILENO);
|
||||
}
|
||||
if (saved_stdout >= 0) {
|
||||
close(saved_stdout);
|
||||
}
|
||||
if (capture) {
|
||||
rewind(capture);
|
||||
size_t count = fread(out, 1, out_size - 1U, capture);
|
||||
out[count] = '\0';
|
||||
fclose(capture);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* The notice an activation prints when it leaves a daemon it could not
|
||||
* confirm as its own: names the daemon by pid and tells the user how to stop
|
||||
* it themselves. Never the "Stopping ..." banner of a drain. */
|
||||
static bool cli_scope_kept_notice_names_host(const char *output, pid_t host) {
|
||||
char pid_text[48];
|
||||
snprintf(pid_text, sizeof(pid_text), "(pid %ld, version %s)", (long)host, CBM_VERSION);
|
||||
return strstr(output, "Leaving the running CBM daemon untouched") != NULL &&
|
||||
strstr(output, pid_text) != NULL &&
|
||||
strstr(output, "codebase-memory-mcp daemon stop") != NULL &&
|
||||
strstr(output, "Stopping active CBM sessions") == NULL;
|
||||
}
|
||||
|
||||
/* (e) USER DECISION 2026-09-28, "unknown = foreign, keep it": the scope read
|
||||
* reaches the active cohort but cannot read its cache identity. Ownership is
|
||||
* unconfirmed, so the sandbox install must leave the host daemon serving,
|
||||
* stop no session, and say which daemon it left and how to stop it. The
|
||||
* install publishes a binary (no --skip-binary): an activation that replaces
|
||||
* nothing never consults the cohort at all (test d). */
|
||||
TEST(cli_install_foreign_home_unreadable_cohort_cache_keeps_host_daemon) {
|
||||
cli_scope_fixture_t fixture;
|
||||
bool ready = cli_scope_fixture_start(&fixture, "unread");
|
||||
char foreign_home[512];
|
||||
char foreign_cache[576];
|
||||
char foreign_bin[640];
|
||||
char activation_log[704];
|
||||
cli_scope_foreign_paths(&fixture, foreign_home, foreign_cache, foreign_bin, activation_log);
|
||||
bool prepared = ready && cbm_mkdir_p(foreign_home, 0700);
|
||||
char output[16384];
|
||||
output[0] = '\0';
|
||||
cbm_cli_set_activation_scope_cache_unreadable_for_test(true);
|
||||
int install_rc = prepared
|
||||
? cli_scope_install_captured(&fixture, foreign_home, foreign_cache,
|
||||
foreign_bin, false, output, sizeof(output))
|
||||
: -1;
|
||||
cbm_cli_set_activation_scope_cache_unreadable_for_test(false);
|
||||
bool host_serving = prepared && cli_scope_host_serving(&fixture);
|
||||
bool notice = cli_scope_kept_notice_names_host(output, fixture.host);
|
||||
const char *events = read_test_file(activation_log);
|
||||
bool completed = events && strstr(events, "\"phase\":\"completed\"") != NULL;
|
||||
bool nothing_drained = events && strstr(events, "cohort drained") == NULL;
|
||||
int host_exit = cli_scope_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(ready);
|
||||
ASSERT_TRUE(host_serving);
|
||||
ASSERT_EQ(host_exit, 0);
|
||||
ASSERT_TRUE(nothing_drained);
|
||||
ASSERT_TRUE(notice);
|
||||
ASSERT_EQ(install_rc, 0);
|
||||
ASSERT_TRUE(completed);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* (f) Same decision, busy group: another activation holds the cohort
|
||||
* maintenance gate, so the scope read cannot reach the active identity at
|
||||
* all. Unconfirmed ownership keeps the host daemon; the sandbox install
|
||||
* completes without draining anyone. The gate is held through the product's
|
||||
* own lock-directory handle on the name version_cohort.c uses. */
|
||||
TEST(cli_install_foreign_home_busy_cohort_keeps_host_daemon) {
|
||||
cli_scope_fixture_t fixture;
|
||||
bool ready = cli_scope_fixture_start(&fixture, "busy");
|
||||
char foreign_home[512];
|
||||
char foreign_cache[576];
|
||||
char foreign_bin[640];
|
||||
char activation_log[704];
|
||||
cli_scope_foreign_paths(&fixture, foreign_home, foreign_cache, foreign_bin, activation_log);
|
||||
cbm_private_lock_directory_t *lock_directory = NULL;
|
||||
cbm_private_file_lock_t *maintenance = NULL;
|
||||
bool held = ready &&
|
||||
cbm_daemon_ipc_private_lock_directory_new(fixture.endpoint, &lock_directory) ==
|
||||
CBM_PRIVATE_FILE_LOCK_OK &&
|
||||
cbm_private_file_lock_try_acquire(
|
||||
lock_directory, "cbm-version-cohort-maintenance-v1.lock",
|
||||
CBM_PRIVATE_FILE_LOCK_EX, &maintenance) == CBM_PRIVATE_FILE_LOCK_OK;
|
||||
bool prepared = held && cbm_mkdir_p(foreign_home, 0700);
|
||||
char output[16384];
|
||||
output[0] = '\0';
|
||||
int install_rc = prepared
|
||||
? cli_scope_install_captured(&fixture, foreign_home, foreign_cache,
|
||||
foreign_bin, false, output, sizeof(output))
|
||||
: -1;
|
||||
bool host_serving = prepared && cli_scope_host_serving(&fixture);
|
||||
bool released =
|
||||
maintenance && cbm_private_file_lock_release(&maintenance) == CBM_PRIVATE_FILE_LOCK_OK;
|
||||
if (lock_directory) {
|
||||
cbm_private_lock_directory_close(lock_directory);
|
||||
}
|
||||
bool notice = cli_scope_kept_notice_names_host(output, fixture.host);
|
||||
const char *events = read_test_file(activation_log);
|
||||
bool completed = events && strstr(events, "\"phase\":\"completed\"") != NULL;
|
||||
bool nothing_drained = events && strstr(events, "cohort drained") == NULL;
|
||||
int host_exit = cli_scope_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(ready);
|
||||
ASSERT_TRUE(held);
|
||||
ASSERT_TRUE(host_serving);
|
||||
ASSERT_EQ(host_exit, 0);
|
||||
ASSERT_TRUE(nothing_drained);
|
||||
ASSERT_TRUE(notice);
|
||||
ASSERT_EQ(install_rc, 0);
|
||||
ASSERT_TRUE(completed);
|
||||
ASSERT_TRUE(released);
|
||||
PASS();
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(cli_install_force_quiesces_active_cohort_before_replacing_binary) {
|
||||
@@ -2286,6 +2421,71 @@ TEST(cli_remove_indexes_deletes_orphan_sqlite_sidecars_issue2054) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The cache directory also holds internal stores next to the project
|
||||
* indexes: the user's settings (_config.db) and the cross-repo store
|
||||
* (_cross_repo.db). Index enumeration treated every *.db as a project, so
|
||||
* install --reset-indexes / uninstall deleted the user's config along with
|
||||
* the indexes, and list/count over-reported. Internal stores are exact
|
||||
* filenames: a real project whose name starts with "_" is still an index. */
|
||||
TEST(cli_index_enumeration_skips_internal_cache_dbs) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-internal-dbs-XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir)) {
|
||||
FAIL("cbm_mkdtemp failed");
|
||||
}
|
||||
char *old_home = NULL;
|
||||
char *old_cache = NULL;
|
||||
cli_activation_save_env(&old_home, &old_cache);
|
||||
cbm_setenv("HOME", tmpdir, 1);
|
||||
char cache_dir[512];
|
||||
snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);
|
||||
cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);
|
||||
test_mkdirp(cache_dir);
|
||||
|
||||
cbm_config_t *cfg = cbm_config_open(cache_dir);
|
||||
int set_rc = cfg ? cbm_config_set(cfg, "auto_index", "true") : -1;
|
||||
cbm_config_close(cfg);
|
||||
|
||||
char config_path[640];
|
||||
char cross_path[640];
|
||||
char proj_path[640];
|
||||
char underscore_proj_path[640];
|
||||
snprintf(config_path, sizeof(config_path), "%s/_config.db", cache_dir);
|
||||
snprintf(cross_path, sizeof(cross_path), "%s/_cross_repo.db", cache_dir);
|
||||
snprintf(proj_path, sizeof(proj_path), "%s/proj.db", cache_dir);
|
||||
snprintf(underscore_proj_path, sizeof(underscore_proj_path), "%s/_work-api.db", cache_dir);
|
||||
write_test_file(cross_path, "cross");
|
||||
write_test_file(proj_path, "db");
|
||||
write_test_file(underscore_proj_path, "db");
|
||||
|
||||
int listed = cbm_list_indexes(tmpdir);
|
||||
int removed = cbm_remove_indexes(tmpdir);
|
||||
|
||||
struct stat st;
|
||||
bool config_kept = stat(config_path, &st) == 0;
|
||||
bool cross_kept = stat(cross_path, &st) == 0;
|
||||
bool proj_absent = stat(proj_path, &st) != 0;
|
||||
bool underscore_proj_absent = stat(underscore_proj_path, &st) != 0;
|
||||
char value[32] = "";
|
||||
cfg = cbm_config_open(cache_dir);
|
||||
if (cfg) {
|
||||
snprintf(value, sizeof(value), "%s", cbm_config_get(cfg, "auto_index", ""));
|
||||
cbm_config_close(cfg);
|
||||
}
|
||||
cli_activation_restore_env(old_home, old_cache);
|
||||
test_rmdir_r(tmpdir);
|
||||
|
||||
ASSERT_EQ(set_rc, 0);
|
||||
ASSERT_EQ(listed, 2);
|
||||
ASSERT_EQ(removed, 2);
|
||||
ASSERT_TRUE(config_kept);
|
||||
ASSERT_TRUE(cross_kept);
|
||||
ASSERT_TRUE(proj_absent);
|
||||
ASSERT_TRUE(underscore_proj_absent);
|
||||
ASSERT_STR_EQ(value, "true");
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(cli_install_config_only_waits_for_cohort_drain) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-daemon-install-config-race-XXXXXX");
|
||||
@@ -13604,6 +13804,57 @@ TEST(cli_codex_legacy_migration_ignores_header_text_in_multiline_string) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1720: Codex rewrites its own [mcp_servers] tables whenever it edits MCP
|
||||
* servers (`codex mcp add`, the app's MCP settings, wrappers that drive it).
|
||||
* The rewrite drops comment decor, so our begin marker vanishes, `args = []`
|
||||
* is omitted, and the end marker survives as an ORPHAN below the next table.
|
||||
* The config below is byte-for-byte what codex-cli 0.153.4 produced from our
|
||||
* managed block after `codex mcp add orca -- /bin/echo hi`. Every later
|
||||
* install then failed `op=mcp_install` on a table cbm itself had written. */
|
||||
TEST(cli_upsert_codex_mcp_adopts_codex_rewritten_table) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-codex-rewrite-XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir))
|
||||
FAIL("cbm_mkdtemp failed");
|
||||
char configpath[512];
|
||||
snprintf(configpath, sizeof(configpath), "%s/config.toml", tmpdir);
|
||||
write_test_file(configpath, "model = \"gpt-5\"\n"
|
||||
"\n"
|
||||
"[projects.\"/tmp/x\"]\n"
|
||||
"trust_level = \"trusted\"\n"
|
||||
"\n"
|
||||
"[mcp_servers.codebase-memory-mcp]\n"
|
||||
"command = \"/opt/cbm/codebase-memory-mcp\"\n"
|
||||
"env_vars = [\"CBM_CACHE_DIR\", \"CBM_RUNTIME_DIR\"]\n"
|
||||
"\n"
|
||||
"[mcp_servers.orca]\n"
|
||||
"command = \"/bin/echo\"\n"
|
||||
"args = [\"hi\"]\n"
|
||||
"# <<< codebase-memory-mcp MCP <<<\n"
|
||||
"\n"
|
||||
"[tui]\n"
|
||||
"theme = \"dark\"\n");
|
||||
|
||||
int rc = cbm_upsert_codex_mcp("/new/cbm/codebase-memory-mcp", configpath);
|
||||
char *data = read_test_file_alloc(configpath);
|
||||
int tables = 0;
|
||||
for (const char *p = data; p && (p = strstr(p, "[mcp_servers.codebase-memory-mcp]")); p++) {
|
||||
tables++;
|
||||
}
|
||||
bool ok = data && tables == 1 && strstr(data, "/opt/cbm/") == NULL &&
|
||||
strstr(data, "command = \"/new/cbm/codebase-memory-mcp\"") != NULL &&
|
||||
strstr(data, "[mcp_servers.orca]\ncommand = \"/bin/echo\"\nargs = [\"hi\"]\n") &&
|
||||
strstr(data, "trust_level = \"trusted\"") && strstr(data, "theme = \"dark\"") &&
|
||||
strstr(data, "# >>> codebase-memory-mcp MCP >>>\n[mcp_servers.codebase-memory-mcp]");
|
||||
free(data);
|
||||
test_rmdir_r(tmpdir);
|
||||
if (rc != 0)
|
||||
FAIL("install must adopt the owned table Codex rewrote (orphan end marker, no args)");
|
||||
if (!ok)
|
||||
FAIL("adoption must leave one managed cbm table and every other entry intact");
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════
|
||||
* Group B: MCP Config Upsert — Zed (corrected format)
|
||||
* ═══════════════════════════════════════════════════════════════════ */
|
||||
@@ -15501,6 +15752,28 @@ TEST(cli_build_args_json_array_flag_accepts_json_literal) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1133: `index_repository --target-projects '["*"]'` (the form the help
|
||||
* documents) must reach the cross-repo matcher as a one-element array, not as
|
||||
* a single string holding the literal text -- that shape resolved to zero
|
||||
* targets and returned a silent "success" with projects_scanned:0. */
|
||||
TEST(cli_build_args_json_target_projects_literal_issue1133) {
|
||||
char *err = NULL;
|
||||
char *argv[] = {"--repo-path", "/r", "--mode", "cross-repo-intelligence",
|
||||
"--target-projects", "[\"*\"]"};
|
||||
char *json = cbm_cli_build_args_json("index_repository", 6, argv, &err);
|
||||
ASSERT_NOT_NULL(json);
|
||||
ASSERT_NULL(err);
|
||||
ASSERT(strstr(json, "\"target_projects\":[\"*\"]") != NULL);
|
||||
free(json);
|
||||
|
||||
char *argv2[] = {"--repo-path", "/r", "--target-projects", "[\"svc-a\",\"svc-b\"]"};
|
||||
json = cbm_cli_build_args_json("index_repository", 4, argv2, &err);
|
||||
ASSERT_NOT_NULL(json);
|
||||
ASSERT(strstr(json, "\"target_projects\":[\"svc-a\",\"svc-b\"]") != 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
|
||||
@@ -16313,6 +16586,60 @@ TEST(cli_update_only_names_an_installer_that_exists_issue1632) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2200: on 0.9.0, `update -y` in a non-interactive shell auto-confirmed
|
||||
* "Delete these indexes and continue with update?", removed every project
|
||||
* index, and THEN failed at the variant chooser -- no binary, no indexes.
|
||||
* The release dispatch now hands off to install.sh (which keeps indexes by
|
||||
* default, #607) and never asks a variant question. Pin that on every
|
||||
* platform: `update -y` and `update -y --standard`, with the activation seam
|
||||
* OFF (the exact path a release binary ships), exit 0 and leave every .db in
|
||||
* the cache byte-for-byte intact. A generic -y must never be read as consent
|
||||
* to delete indexes. */
|
||||
TEST(cli_update_yes_keeps_every_index_issue2200) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-update-2200-XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir)) {
|
||||
FAIL("cbm_mkdtemp failed");
|
||||
}
|
||||
char *old_home = NULL;
|
||||
char *old_cache = NULL;
|
||||
cli_activation_save_env(&old_home, &old_cache);
|
||||
cbm_setenv("HOME", tmpdir, 1);
|
||||
char cache_dir[512];
|
||||
snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);
|
||||
cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);
|
||||
test_mkdirp(cache_dir);
|
||||
|
||||
static const char *const projects[] = {"alpha", "beta", "gamma"};
|
||||
enum { PROJECT_COUNT = 3 };
|
||||
char db_paths[PROJECT_COUNT][640];
|
||||
for (int i = 0; i < PROJECT_COUNT; i++) {
|
||||
snprintf(db_paths[i], sizeof(db_paths[i]), "%s/%s.db", cache_dir, projects[i]);
|
||||
write_test_file(db_paths[i], projects[i]);
|
||||
}
|
||||
|
||||
char *yes_argv[] = {"-y"};
|
||||
char *legacy_argv[] = {"-y", "--standard"};
|
||||
int yes_rc = cbm_cmd_update(1, yes_argv);
|
||||
int legacy_rc = cbm_cmd_update(2, legacy_argv);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
|
||||
int kept = 0;
|
||||
for (int i = 0; i < PROJECT_COUNT; i++) {
|
||||
const char *content = read_test_file(db_paths[i]);
|
||||
if (content && strcmp(content, projects[i]) == 0) {
|
||||
kept++;
|
||||
}
|
||||
}
|
||||
cli_activation_restore_env(old_home, old_cache);
|
||||
test_rmdir_r(tmpdir);
|
||||
|
||||
ASSERT_EQ(yes_rc, 0);
|
||||
ASSERT_EQ(legacy_rc, 0);
|
||||
ASSERT_EQ(kept, PROJECT_COUNT);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(cli) {
|
||||
if (!th_secure_runtime_parent_new(g_cli_suite_runtime_parent,
|
||||
sizeof(g_cli_suite_runtime_parent), "cli-suite")) {
|
||||
@@ -16325,6 +16652,7 @@ SUITE(cli) {
|
||||
|
||||
RUN_TEST(cli_suite_uses_private_activation_runtime);
|
||||
RUN_TEST(cli_update_only_names_an_installer_that_exists_issue1632);
|
||||
RUN_TEST(cli_update_yes_keeps_every_index_issue2200);
|
||||
#ifndef _WIN32
|
||||
RUN_TEST(cli_hook_deadline_ignores_an_unreadable_value);
|
||||
#endif
|
||||
@@ -16362,12 +16690,15 @@ SUITE(cli) {
|
||||
RUN_TEST(cli_install_binary_into_foreign_home_never_drains_host_cohort);
|
||||
RUN_TEST(cli_install_into_host_namespace_still_drains_host_cohort);
|
||||
RUN_TEST(cli_install_skip_binary_unchanged_in_host_namespace_quiesces_nothing);
|
||||
RUN_TEST(cli_install_foreign_home_unreadable_cohort_cache_keeps_host_daemon);
|
||||
RUN_TEST(cli_install_foreign_home_busy_cohort_keeps_host_daemon);
|
||||
#endif
|
||||
RUN_TEST(cli_install_force_quiesces_active_cohort_before_replacing_binary);
|
||||
RUN_TEST(cli_install_dir_and_skip_config_stage_first_install_safely);
|
||||
RUN_TEST(cli_activation_commands_reject_malformed_and_unknown_flags);
|
||||
RUN_TEST(cli_install_reset_deletion_waits_for_final_activation_guard);
|
||||
RUN_TEST(cli_remove_indexes_deletes_orphan_sqlite_sidecars_issue2054);
|
||||
RUN_TEST(cli_index_enumeration_skips_internal_cache_dbs);
|
||||
RUN_TEST(cli_install_config_only_waits_for_cohort_drain);
|
||||
RUN_TEST(cli_install_config_and_path_finish_before_guard_release);
|
||||
RUN_TEST(cli_install_config_failure_keeps_published_binary);
|
||||
@@ -16662,6 +16993,7 @@ SUITE(cli) {
|
||||
RUN_TEST(cli_upsert_codex_mcp_existing);
|
||||
RUN_TEST(cli_upsert_codex_mcp_replace);
|
||||
RUN_TEST(cli_codex_legacy_migration_ignores_header_text_in_multiline_string);
|
||||
RUN_TEST(cli_upsert_codex_mcp_adopts_codex_rewritten_table);
|
||||
|
||||
/* Zed MCP format fix (1 test — group B) */
|
||||
RUN_TEST(cli_zed_mcp_uses_args_format);
|
||||
@@ -16738,6 +17070,7 @@ SUITE(cli) {
|
||||
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_target_projects_literal_issue1133);
|
||||
RUN_TEST(cli_build_args_json_unknown_flag_rejected);
|
||||
RUN_TEST(cli_build_args_json_repeated_array_issue680);
|
||||
RUN_TEST(cli_build_args_json_array_literal);
|
||||
|
||||
+44
-39
@@ -435,36 +435,58 @@ static double cx_ratio(double num, double den) {
|
||||
return den > 0.0 ? num / den : 0.0;
|
||||
}
|
||||
|
||||
typedef int (*CxCorpusBuilder)(const char *root, int k);
|
||||
|
||||
static void cx_remove_corpus(const char *root) {
|
||||
if (th_rmtree(root) != 0) {
|
||||
fprintf(stderr, " [complexity] WARN: could not remove temp corpus %s\n", root);
|
||||
}
|
||||
}
|
||||
|
||||
/* Build one corpus shape at k and 2k in two fresh temp dirs, run the pipeline
|
||||
* on both, and remove both dirs before returning — on success and on every
|
||||
* failure path. Only the metrics outlive the call; the corpora used to stay
|
||||
* behind in the temp root, four per suite run. Only dirs this call created
|
||||
* are removed (the temp root is shared with concurrent runs). */
|
||||
static int cx_measure(CxCorpusBuilder build, const char *prefix_a, const char *prefix_b,
|
||||
CxMetrics *out_a, CxMetrics *out_b) {
|
||||
const char *tmp = cbm_tmpdir();
|
||||
char root_a[512];
|
||||
char root_b[512];
|
||||
snprintf(root_a, sizeof(root_a), "%s/%s_XXXXXX", tmp, prefix_a);
|
||||
snprintf(root_b, sizeof(root_b), "%s/%s_XXXXXX", tmp, prefix_b);
|
||||
bool made_a = cbm_mkdtemp(root_a) != NULL;
|
||||
bool made_b = made_a && cbm_mkdtemp(root_b) != NULL;
|
||||
int rc = -1;
|
||||
if (made_b && build(root_a, CX_K_BASE) == 0 && build(root_b, CX_K_BASE * 2) == 0) {
|
||||
char db_a[600];
|
||||
char db_b[600];
|
||||
snprintf(db_a, sizeof(db_a), "%s/cx.db", root_a);
|
||||
snprintf(db_b, sizeof(db_b), "%s/cx.db", root_b);
|
||||
if (cx_run(root_a, db_a, out_a) == 0 && cx_run(root_b, db_b, out_b) == 0) {
|
||||
rc = 0;
|
||||
}
|
||||
}
|
||||
if (made_b) {
|
||||
cx_remove_corpus(root_b);
|
||||
}
|
||||
if (made_a) {
|
||||
cx_remove_corpus(root_a);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Shared across the suite so the report test reuses the measured pair instead
|
||||
* of paying two more pipeline runs. */
|
||||
static CxMetrics g_cx_base;
|
||||
static CxMetrics g_cx_doubled;
|
||||
static bool g_cx_measured = false;
|
||||
static char g_cx_root_base[512];
|
||||
static char g_cx_root_doubled[512];
|
||||
|
||||
static int cx_measure_pair(void) {
|
||||
if (g_cx_measured) {
|
||||
return 0;
|
||||
}
|
||||
const char *tmp = cbm_tmpdir();
|
||||
snprintf(g_cx_root_base, sizeof(g_cx_root_base), "%s/cbm_cx_base_XXXXXX", tmp);
|
||||
snprintf(g_cx_root_doubled, sizeof(g_cx_root_doubled), "%s/cbm_cx_dbl_XXXXXX", tmp);
|
||||
if (!cbm_mkdtemp(g_cx_root_base) || !cbm_mkdtemp(g_cx_root_doubled)) {
|
||||
return -1;
|
||||
}
|
||||
if (cx_build_corpus(g_cx_root_base, CX_K_BASE) != 0 ||
|
||||
cx_build_corpus(g_cx_root_doubled, CX_K_BASE * 2) != 0) {
|
||||
return -1;
|
||||
}
|
||||
char db1[600];
|
||||
char db2[600];
|
||||
snprintf(db1, sizeof(db1), "%s/cx.db", g_cx_root_base);
|
||||
snprintf(db2, sizeof(db2), "%s/cx.db", g_cx_root_doubled);
|
||||
if (cx_run(g_cx_root_base, db1, &g_cx_base) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (cx_run(g_cx_root_doubled, db2, &g_cx_doubled) != 0) {
|
||||
if (cx_measure(cx_build_corpus, "cbm_cx_base", "cbm_cx_dbl", &g_cx_base, &g_cx_doubled) != 0) {
|
||||
return -1;
|
||||
}
|
||||
g_cx_measured = true;
|
||||
@@ -555,25 +577,8 @@ static int cx_measure_bigpkg_pair(void) {
|
||||
if (g_cx_big_measured) {
|
||||
return 0;
|
||||
}
|
||||
const char *tmp = cbm_tmpdir();
|
||||
char ra[512];
|
||||
char rb[512];
|
||||
snprintf(ra, sizeof(ra), "%s/cbm_cxbig_a_XXXXXX", tmp);
|
||||
snprintf(rb, sizeof(rb), "%s/cbm_cxbig_b_XXXXXX", tmp);
|
||||
if (!cbm_mkdtemp(ra) || !cbm_mkdtemp(rb)) {
|
||||
return -1;
|
||||
}
|
||||
if (cx_build_bigpkg(ra, CX_K_BASE) != 0 || cx_build_bigpkg(rb, CX_K_BASE * 2) != 0) {
|
||||
return -1;
|
||||
}
|
||||
char db1[600];
|
||||
char db2[600];
|
||||
snprintf(db1, sizeof(db1), "%s/cx.db", ra);
|
||||
snprintf(db2, sizeof(db2), "%s/cx.db", rb);
|
||||
if (cx_run(ra, db1, &g_cx_big_base) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (cx_run(rb, db2, &g_cx_big_doubled) != 0) {
|
||||
if (cx_measure(cx_build_bigpkg, "cbm_cxbig_a", "cbm_cxbig_b", &g_cx_big_base,
|
||||
&g_cx_big_doubled) != 0) {
|
||||
return -1;
|
||||
}
|
||||
g_cx_big_measured = true;
|
||||
|
||||
@@ -566,6 +566,41 @@ TEST(config_toml_legacy_remove_reports_foreign_table_without_mutation) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1720: `env_vars` naming only the variables cbm itself forwards is part of
|
||||
* the owned shape (#1562/#1664), so a table Codex rewrote without markers is
|
||||
* adopted; any other forwarded name keeps the table foreign. */
|
||||
TEST(config_toml_legacy_remove_adopts_owned_env_vars_only) {
|
||||
char dir[CTE_PATH_CAP];
|
||||
char path[CTE_PATH_CAP];
|
||||
char actual[CTE_FILE_CAP];
|
||||
ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);
|
||||
ASSERT_EQ(th_write_file(path, "theme = \"dark\"\n"
|
||||
"[mcp_servers.codebase-memory-mcp]\n"
|
||||
"command = 'C:\\cbm\\codebase-memory-mcp.exe'\n"
|
||||
"env_vars = [\"CBM_CACHE_DIR\"]\n"
|
||||
"\n"
|
||||
"[tui]\n"
|
||||
"keep = true\n"),
|
||||
0);
|
||||
ASSERT_EQ(
|
||||
cbm_toml_remove_legacy_table(path, "mcp_servers.codebase-memory-mcp", CTE_BEGIN, CTE_END),
|
||||
0);
|
||||
ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);
|
||||
ASSERT_STR_EQ(actual, "theme = \"dark\"\n[tui]\nkeep = true\n");
|
||||
|
||||
const char *foreign = "[mcp_servers.codebase-memory-mcp]\n"
|
||||
"command = \"/opt/codebase-memory-mcp\"\n"
|
||||
"env_vars = [\"CBM_CACHE_DIR\", \"HOME\"]\n";
|
||||
ASSERT_EQ(th_write_file(path, foreign), 0);
|
||||
ASSERT_EQ(
|
||||
cbm_toml_remove_legacy_table(path, "mcp_servers.codebase-memory-mcp", CTE_BEGIN, CTE_END),
|
||||
1);
|
||||
ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);
|
||||
ASSERT_STR_EQ(actual, foreign);
|
||||
th_cleanup(dir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(config_toml_vibe_non_array_and_dotted_conflicts_fail_closed) {
|
||||
char dir[CTE_PATH_CAP];
|
||||
char path[CTE_PATH_CAP];
|
||||
@@ -1391,6 +1426,55 @@ TEST(config_toml_codex_reports_stable_failure_reasons) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2044: an installed binary under a profile with a space (C:\Users\First Last)
|
||||
* is rendered single-quoted by cbm_shell_quote_word / cbm_powershell_quote_word.
|
||||
* The hook block must accept exactly what those writers emit, read it back as
|
||||
* owned, and still refuse an unquoted word that the shell would split. */
|
||||
TEST(config_toml_codex_accepts_quoted_binary_path_with_spaces) {
|
||||
static const char command[] = "'/Users/First Last/.local/bin/codebase-memory-mcp' hook-augment";
|
||||
static const char command_windows[] = "& 'C:/Users/First Last/AppData/Local/Programs/"
|
||||
"codebase-memory-mcp/codebase-memory-mcp.exe' "
|
||||
"hook-augment";
|
||||
char dir[CTE_PATH_CAP];
|
||||
char path[CTE_PATH_CAP];
|
||||
char first[CTE_FILE_CAP];
|
||||
char actual[CTE_FILE_CAP];
|
||||
ASSERT_EQ(cte_fixture(dir, sizeof(dir), path, sizeof(path)), 0);
|
||||
ASSERT_EQ(th_write_file(path, "keep = true\n"), 0);
|
||||
|
||||
cbm_toml_codex_hook_failure_t failure = CBM_TOML_CODEX_HOOK_FAILURE_INVALID_ARGUMENT;
|
||||
ASSERT_EQ(cte_codex_edit_commands_detailed(path, command, command_windows,
|
||||
CBM_TOML_CODEX_HOOK_UPSERT, 1, &failure),
|
||||
0);
|
||||
ASSERT_STR_EQ(cbm_toml_codex_hook_failure_name(failure), "none");
|
||||
ASSERT_EQ(cte_codex_edit_commands_detailed(path, command, command_windows,
|
||||
CBM_TOML_CODEX_HOOK_UPSERT, 0, &failure),
|
||||
0);
|
||||
ASSERT_EQ(cte_read(path, first, sizeof(first)), 0);
|
||||
ASSERT(strstr(first, "First Last/.local/bin/codebase-memory-mcp' hook-augment") != NULL);
|
||||
|
||||
/* The written block is recognised as ours: a second upsert is a no-op. */
|
||||
ASSERT_EQ(cte_codex_edit_commands_detailed(path, command, command_windows,
|
||||
CBM_TOML_CODEX_HOOK_UPSERT, 0, &failure),
|
||||
0);
|
||||
ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);
|
||||
ASSERT_STR_EQ(actual, first);
|
||||
ASSERT_EQ(cte_codex_edit_commands_detailed(path, command, command_windows,
|
||||
CBM_TOML_CODEX_HOOK_REMOVE, 0, &failure),
|
||||
0);
|
||||
ASSERT_EQ(cte_read(path, actual, sizeof(actual)), 0);
|
||||
ASSERT_STR_EQ(actual, "keep = true\n");
|
||||
|
||||
/* Unquoted, the space splits the executable word: still refused. */
|
||||
ASSERT_EQ(cte_codex_edit_commands_detailed(
|
||||
path, "/Users/First Last/.local/bin/codebase-memory-mcp hook-augment",
|
||||
command_windows, CBM_TOML_CODEX_HOOK_UPSERT, 1, &failure),
|
||||
-1);
|
||||
ASSERT_STR_EQ(cbm_toml_codex_hook_failure_name(failure), "command_render");
|
||||
th_cleanup(dir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(config_toml_codex_preserves_bom_crlf_and_foreign_aot) {
|
||||
char dir[CTE_PATH_CAP];
|
||||
char path[CTE_PATH_CAP];
|
||||
@@ -1506,6 +1590,8 @@ SUITE(config_toml_edit) {
|
||||
RUN_TEST(config_toml_codex_accepts_v0102_managed_windows_crlf);
|
||||
RUN_TEST(config_toml_codex_rejects_ambiguous_inline_byte_identically);
|
||||
RUN_TEST(config_toml_codex_reports_stable_failure_reasons);
|
||||
RUN_TEST(config_toml_codex_accepts_quoted_binary_path_with_spaces);
|
||||
RUN_TEST(config_toml_codex_preserves_bom_crlf_and_foreign_aot);
|
||||
RUN_TEST(config_toml_legacy_remove_reports_foreign_table_without_mutation);
|
||||
RUN_TEST(config_toml_legacy_remove_adopts_owned_env_vars_only);
|
||||
}
|
||||
|
||||
@@ -1228,12 +1228,14 @@ TEST(config_yaml_edit_hermes_accepts_interior_brackets_in_plain_scalar_issue1924
|
||||
|
||||
TEST(config_yaml_edit_hermes_hook_still_refuses_block_scalar_value_issue1924) {
|
||||
/* A `>` or `|` that BEGINS a value is a real block scalar whose
|
||||
* indentation contract this editor does not model: the fail-closed
|
||||
* refusal stays, and the file stays byte-identical. */
|
||||
* indentation contract this editor does not model: inside the `hooks`
|
||||
* subtree the edit descends into, the fail-closed refusal stays and the
|
||||
* file stays byte-identical. The same construct in an untouched section
|
||||
* is opaque user content (#2209). */
|
||||
static const char *const initials[] = {
|
||||
"agent:\n personalities:\n probe: >\n folded face\n",
|
||||
"agent:\n personalities:\n probe: |\n literal face\n",
|
||||
"agent:\n personalities:\n probe: >-\n chomped face\n",
|
||||
"hooks:\n probe: >\n folded face\n",
|
||||
"hooks:\n probe: |\n literal face\n",
|
||||
"hooks:\n probe: >-\n chomped face\n",
|
||||
};
|
||||
for (size_t i = 0U; i < sizeof(initials) / sizeof(initials[0]); i++) {
|
||||
yaml_fixture_t fixture;
|
||||
@@ -1250,10 +1252,10 @@ TEST(config_yaml_edit_hermes_hook_still_refuses_block_scalar_value_issue1924) {
|
||||
|
||||
TEST(config_yaml_edit_hermes_hook_still_refuses_nonempty_flow_sequence_value_issue1924) {
|
||||
/* Pins the #1631 line: exact `[]` is accepted, a non-empty flow sequence
|
||||
* value is still unsupported in the sequence-document scan. */
|
||||
const char *initial = "agent:\n"
|
||||
" personalities:\n"
|
||||
" probe: [a, b]\n";
|
||||
* value inside the edited `hooks` subtree is still unsupported. Outside
|
||||
* it, the value is opaque user content (#2209). */
|
||||
const char *initial = "hooks:\n"
|
||||
" probe: [a, b]\n";
|
||||
yaml_fixture_t fixture;
|
||||
ASSERT_EQ(yaml_fixture_init(&fixture, initial), 0);
|
||||
ASSERT_EQ(yaml_hermes_hook_upsert(&fixture), CBM_YAML_IDENTITY_EDIT_ERROR);
|
||||
@@ -2027,6 +2029,57 @@ TEST(config_yaml_edit_remove_on_absent_config_is_a_no_op) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2209: the stock Hermes config carries flow sequences and block scalars in
|
||||
* sections the hook edit never touches (`platform_toolsets:` -> `cli:
|
||||
* [hermes-cli]`, `plugins:` -> `enabled: [...]`, `|` prompts). They are opaque
|
||||
* user content, exactly as for the mapping-entry editor that writes
|
||||
* `mcp_servers` into the same file; only the `hooks` subtree is validated. */
|
||||
TEST(config_yaml_edit_nested_sequence_ignores_foreign_flow_and_block_scalars_issue2209) {
|
||||
const char *initial = "plugins:\n"
|
||||
" enabled: [disk-cleanup]\n"
|
||||
"platform_toolsets:\n"
|
||||
" cli: [hermes-cli]\n"
|
||||
" telegram: [hermes-telegram]\n"
|
||||
"toolsets: [all]\n"
|
||||
"agent:\n"
|
||||
" system_prompt: |\n"
|
||||
" You are helpful.\n"
|
||||
" - keep: [this, text]\n"
|
||||
" note: >\n"
|
||||
" folded\n"
|
||||
"model:\n"
|
||||
" default: \"anthropic/claude-opus-4.6\"\n";
|
||||
yaml_fixture_t fixture;
|
||||
ASSERT_EQ(yaml_fixture_init(&fixture, initial), 0);
|
||||
ASSERT_EQ(cbm_yaml_upsert_mapping_sequence_item(fixture.path, yaml_hook_sequence_path, 2U, "id",
|
||||
yaml_hook_identity, yaml_hook_canonical_item),
|
||||
CBM_YAML_IDENTITY_EDIT_OK);
|
||||
char *installed = yaml_read_alloc(fixture.path);
|
||||
ASSERT_NOT_NULL(installed);
|
||||
ASSERT_EQ(strncmp(installed, initial, strlen(initial)), 0);
|
||||
ASSERT_NOT_NULL(strstr(installed, "hooks:\n"
|
||||
" pre_llm_call:\n"
|
||||
" - id: \"codebase-memory-mcp\"\n"));
|
||||
ASSERT_EQ(cbm_yaml_upsert_mapping_sequence_item(fixture.path, yaml_hook_sequence_path, 2U, "id",
|
||||
yaml_hook_identity, yaml_hook_canonical_item),
|
||||
CBM_YAML_IDENTITY_EDIT_OK);
|
||||
char *second = yaml_read_alloc(fixture.path);
|
||||
ASSERT_NOT_NULL(second);
|
||||
ASSERT_STR_EQ(second, installed);
|
||||
free(second);
|
||||
free(installed);
|
||||
ASSERT_EQ(cbm_yaml_remove_mapping_sequence_item(fixture.path, yaml_hook_sequence_path, 2U, "id",
|
||||
yaml_hook_identity, yaml_hook_canonical_item),
|
||||
CBM_YAML_IDENTITY_EDIT_OK);
|
||||
char *removed = yaml_read_alloc(fixture.path);
|
||||
ASSERT_NOT_NULL(removed);
|
||||
ASSERT_NULL(strstr(removed, "codebase-memory-mcp"));
|
||||
ASSERT_EQ(strncmp(removed, initial, strlen(initial)), 0);
|
||||
free(removed);
|
||||
th_cleanup(fixture.dir);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(config_yaml_edit_nested_sequence_ambiguity_fails_byte_identically) {
|
||||
const char *cases[] = {
|
||||
"hooks:\n pre_llm_call:\n - id: \"bad-indent\"\n",
|
||||
@@ -2192,6 +2245,7 @@ SUITE(config_yaml_edit) {
|
||||
RUN_TEST(config_yaml_edit_nested_sequence_preserves_crlf);
|
||||
RUN_TEST(config_yaml_edit_nested_sequence_foreign_identity_is_preserved);
|
||||
RUN_TEST(config_yaml_edit_nested_sequence_removes_only_exact_canonical_item);
|
||||
RUN_TEST(config_yaml_edit_nested_sequence_ignores_foreign_flow_and_block_scalars_issue2209);
|
||||
RUN_TEST(config_yaml_edit_nested_sequence_ambiguity_fails_byte_identically);
|
||||
RUN_TEST(config_yaml_edit_remove_on_absent_config_is_a_no_op);
|
||||
#ifndef _WIN32
|
||||
|
||||
@@ -147,6 +147,84 @@ static bool cross_repo_seed_http_pair(const cross_repo_fixture_t *fixture,
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* Give the source project its own handler for the local Route the seeded
|
||||
* HTTP_CALLS edge points at (caller-local HANDLES), as when a monorepo's
|
||||
* client code calls the API the same repo serves. (#1459) */
|
||||
static bool cross_repo_seed_local_handler(const cross_repo_fixture_t *fixture,
|
||||
const char *source_project, const char *suffix) {
|
||||
char source_path[512];
|
||||
if (!cross_repo_project_path(fixture, source_project, source_path, sizeof(source_path))) {
|
||||
return false;
|
||||
}
|
||||
cbm_store_t *source = cbm_store_open_path(source_path);
|
||||
if (!source) {
|
||||
return false;
|
||||
}
|
||||
char local_route_qn[256];
|
||||
char handler_qn[256];
|
||||
snprintf(local_route_qn, sizeof(local_route_qn), "%s.local-route.%s", source_project, suffix);
|
||||
snprintf(handler_qn, sizeof(handler_qn), "%s.local-handle.%s", source_project, suffix);
|
||||
cbm_node_t route = {0};
|
||||
bool ok =
|
||||
cbm_store_find_node_by_qn(source, source_project, local_route_qn, &route) == CBM_STORE_OK;
|
||||
int64_t route_id = ok ? route.id : 0;
|
||||
if (ok) {
|
||||
cbm_node_free_fields(&route);
|
||||
}
|
||||
cbm_node_t handler = {.project = source_project,
|
||||
.label = "Function",
|
||||
.name = "handle_local",
|
||||
.qualified_name = handler_qn,
|
||||
.file_path = "server.c"};
|
||||
int64_t handler_id = ok ? cbm_store_upsert_node(source, &handler) : 0;
|
||||
cbm_edge_t handles = {.project = source_project,
|
||||
.source_id = handler_id,
|
||||
.target_id = route_id,
|
||||
.type = "HANDLES"};
|
||||
ok = ok && route_id > 0 && handler_id > 0 && cbm_store_insert_edge(source, &handles) > 0;
|
||||
cbm_store_close(source);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* Give the source project a canonical "__route__GET__<path>" Route with its
|
||||
* own handler, distinct from the node the seeded HTTP_CALLS points at — the
|
||||
* shape extraction produces for a method-less fetch() against a local
|
||||
* app.get() route. (#1459) */
|
||||
static bool cross_repo_seed_local_get_route(const cross_repo_fixture_t *fixture,
|
||||
const char *source_project, const char *route_path) {
|
||||
char source_path[512];
|
||||
if (!cross_repo_project_path(fixture, source_project, source_path, sizeof(source_path))) {
|
||||
return false;
|
||||
}
|
||||
cbm_store_t *source = cbm_store_open_path(source_path);
|
||||
if (!source) {
|
||||
return false;
|
||||
}
|
||||
char route_qn[256];
|
||||
char handler_qn[256];
|
||||
snprintf(route_qn, sizeof(route_qn), "__route__GET__%s", route_path);
|
||||
snprintf(handler_qn, sizeof(handler_qn), "%s.local-get-handler", source_project);
|
||||
cbm_node_t route = {.project = source_project,
|
||||
.label = "Route",
|
||||
.name = route_path,
|
||||
.qualified_name = route_qn,
|
||||
.file_path = "server.c"};
|
||||
cbm_node_t handler = {.project = source_project,
|
||||
.label = "Function",
|
||||
.name = "handle_local_get",
|
||||
.qualified_name = handler_qn,
|
||||
.file_path = "server.c"};
|
||||
int64_t route_id = cbm_store_upsert_node(source, &route);
|
||||
int64_t handler_id = cbm_store_upsert_node(source, &handler);
|
||||
cbm_edge_t handles = {.project = source_project,
|
||||
.source_id = handler_id,
|
||||
.target_id = route_id,
|
||||
.type = "HANDLES"};
|
||||
bool ok = route_id > 0 && handler_id > 0 && cbm_store_insert_edge(source, &handles) > 0;
|
||||
cbm_store_close(source);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static bool cross_repo_exec(const cross_repo_fixture_t *fixture, const char *project,
|
||||
const char *sql) {
|
||||
char path[512];
|
||||
@@ -236,6 +314,93 @@ TEST(cross_repo_wildcard_keeps_projects_containing_internal_tokens) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A project store written before the #768 edges.local_name_gen column: it
|
||||
* still answers read-only queries (list_projects shows it), but the
|
||||
* read-write open every cross-repo target needs refuses it until a reindex. */
|
||||
static bool cross_repo_create_pre768_project(const cross_repo_fixture_t *fixture,
|
||||
const char *project) {
|
||||
char path[512];
|
||||
if (!cross_repo_project_path(fixture, project, path, sizeof(path))) {
|
||||
return false;
|
||||
}
|
||||
sqlite3 *db = NULL;
|
||||
if (sqlite3_open(path, &db) != SQLITE_OK) {
|
||||
sqlite3_close(db);
|
||||
return false;
|
||||
}
|
||||
char sql[1024];
|
||||
snprintf(sql, sizeof(sql),
|
||||
"CREATE TABLE projects(name TEXT PRIMARY KEY, indexed_at TEXT NOT NULL,"
|
||||
" root_path TEXT NOT NULL);"
|
||||
"CREATE TABLE nodes(id INTEGER PRIMARY KEY AUTOINCREMENT, project TEXT NOT NULL,"
|
||||
" label TEXT NOT NULL, name TEXT NOT NULL, qualified_name TEXT NOT NULL,"
|
||||
" file_path TEXT DEFAULT '', start_line INTEGER DEFAULT 0,"
|
||||
" end_line INTEGER DEFAULT 0, properties TEXT DEFAULT '{}',"
|
||||
" UNIQUE(project, qualified_name));"
|
||||
"CREATE TABLE edges(id INTEGER PRIMARY KEY AUTOINCREMENT, project TEXT NOT NULL,"
|
||||
" source_id INTEGER NOT NULL, target_id INTEGER NOT NULL, type TEXT NOT NULL,"
|
||||
" properties TEXT DEFAULT '{}', UNIQUE(source_id, target_id, type));"
|
||||
"INSERT INTO projects VALUES('%s', '2026-06-01T00:00:00Z', '/pre768');",
|
||||
project);
|
||||
bool ok = sqlite3_exec(db, sql, NULL, NULL, NULL) == SQLITE_OK;
|
||||
sqlite3_close(db);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* #2133: ["*"] enumerated every store a read-only open accepts, then aborted
|
||||
* the whole run on the first one the matcher's read-write open refused — a
|
||||
* single pre-#768 index anywhere in the cache made the wildcard fail with
|
||||
* "missing, invalid, or not indexed" while naming the same live targets
|
||||
* worked. A store the matcher cannot use is not a wildcard target. */
|
||||
TEST(cross_repo_wildcard_skips_pre768_store_issue2133) {
|
||||
cross_repo_fixture_t fixture;
|
||||
bool setup = cross_repo_fixture_begin(&fixture) &&
|
||||
cross_repo_seed_http_pair(&fixture, "wild-src", "wild-api", "/orders", "w") &&
|
||||
cross_repo_create_pre768_project(&fixture, "aa-pre768-store");
|
||||
if (!setup) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to seed pre-#768 wildcard fixture");
|
||||
}
|
||||
|
||||
const char *targets[] = {"*"};
|
||||
cbm_cross_repo_result_t result = cbm_cross_repo_match("wild-src", targets, 1);
|
||||
int edges = cross_repo_count_edges(&fixture, "wild-src", "CROSS_HTTP_CALLS");
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_FALSE(result.failed);
|
||||
ASSERT_EQ(result.projects_scanned, 1);
|
||||
ASSERT_EQ(result.http_edges, 1);
|
||||
ASSERT_EQ(edges, 1);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Naming an unusable store stays an error, but it must be refused during
|
||||
* validation, before the source's previous CROSS_* generation is deleted. */
|
||||
TEST(cross_repo_named_pre768_target_fails_before_cleanup_issue2133) {
|
||||
cross_repo_fixture_t fixture;
|
||||
bool setup = cross_repo_fixture_begin(&fixture) &&
|
||||
cross_repo_seed_http_pair(&fixture, "named-src", "named-api", "/orders", "n") &&
|
||||
cross_repo_create_pre768_project(&fixture, "aa-pre768-store");
|
||||
if (!setup) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to seed pre-#768 named fixture");
|
||||
}
|
||||
|
||||
const char *live[] = {"named-api"};
|
||||
cbm_cross_repo_result_t initial = cbm_cross_repo_match("named-src", live, 1);
|
||||
int before = cross_repo_count_edges(&fixture, "named-src", "CROSS_HTTP_CALLS");
|
||||
const char *with_pre768[] = {"named-api", "aa-pre768-store"};
|
||||
cbm_cross_repo_result_t result = cbm_cross_repo_match("named-src", with_pre768, 2);
|
||||
int after = cross_repo_count_edges(&fixture, "named-src", "CROSS_HTTP_CALLS");
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_FALSE(initial.failed);
|
||||
ASSERT_EQ(before, 1);
|
||||
ASSERT_TRUE(result.failed);
|
||||
ASSERT_EQ(after, before);
|
||||
PASS();
|
||||
}
|
||||
|
||||
static bool cross_repo_seed_bounded_scan(const cross_repo_fixture_t *fixture,
|
||||
const char *source_project, const char *target_project) {
|
||||
enum { TEST_SCAN_ROWS = 4097 };
|
||||
@@ -469,6 +634,58 @@ TEST(cross_repo_pre_cancel_preserves_existing_cross_edges) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1133: a run whose targets resolve to nothing but the source project must
|
||||
* fail explicitly. It used to report "success" with projects_scanned:0 --
|
||||
* indistinguishable from "these services share no routes" -- and, worse, it
|
||||
* had already wiped the source's existing CROSS_* edges before noticing there
|
||||
* was nothing to match against. */
|
||||
TEST(cross_repo_self_only_target_fails_and_keeps_edges_issue1133) {
|
||||
cross_repo_fixture_t fixture;
|
||||
bool setup =
|
||||
cross_repo_fixture_begin(&fixture) &&
|
||||
cross_repo_seed_http_pair(&fixture, "self-source", "self-target", "/self-only", "self");
|
||||
if (!setup) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to seed self-only fixture");
|
||||
}
|
||||
|
||||
const char *target = "self-target";
|
||||
cbm_cross_repo_result_t initial = cbm_cross_repo_match("self-source", &target, 1);
|
||||
int before = cross_repo_count_edges(&fixture, "self-source", "CROSS_HTTP_CALLS");
|
||||
const char *self = "self-source";
|
||||
cbm_cross_repo_result_t result = cbm_cross_repo_match("self-source", &self, 1);
|
||||
int after = cross_repo_count_edges(&fixture, "self-source", "CROSS_HTTP_CALLS");
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_FALSE(initial.failed);
|
||||
ASSERT_TRUE(before > 0);
|
||||
ASSERT_TRUE(result.failed);
|
||||
ASSERT_TRUE(result.no_targets);
|
||||
ASSERT_EQ(result.projects_scanned, 0);
|
||||
ASSERT_EQ(after, before);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1133: ["*"] in a store that holds only the source project resolves to zero
|
||||
* targets -- same contract as an explicit self-only list. */
|
||||
TEST(cross_repo_wildcard_with_no_other_project_fails_issue1133) {
|
||||
cross_repo_fixture_t fixture;
|
||||
if (!cross_repo_fixture_begin(&fixture) ||
|
||||
!cross_repo_create_project(&fixture, "lonely-source")) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to create isolated source project");
|
||||
}
|
||||
|
||||
const char *targets[] = {"*"};
|
||||
cbm_cross_repo_result_t result = cbm_cross_repo_match("lonely-source", targets, 1);
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_TRUE(result.failed);
|
||||
ASSERT_TRUE(result.no_targets);
|
||||
ASSERT_EQ(result.projects_scanned, 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Add the internal "<name>::missed" miss-graph row that indexing writes into
|
||||
* the SAME db whenever a file parses partially. */
|
||||
static bool cross_repo_add_missed_shadow(const cross_repo_fixture_t *fixture, const char *project) {
|
||||
@@ -519,13 +736,111 @@ TEST(cross_repo_accepts_project_with_missed_shadow_row_issue1609) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1459 floor: a caller whose own project handles the route it calls is
|
||||
* calling itself — another project exposing the same path is not evidence of
|
||||
* a cross-service call. Neither direction of the pass may link it. */
|
||||
TEST(cross_repo_caller_local_handler_blocks_cross_http_issue1459) {
|
||||
cross_repo_fixture_t fixture;
|
||||
bool setup =
|
||||
cross_repo_fixture_begin(&fixture) &&
|
||||
cross_repo_seed_http_pair(&fixture, "mono-1459", "api-1459", "/api/users", "mono") &&
|
||||
cross_repo_seed_local_handler(&fixture, "mono-1459", "mono");
|
||||
if (!setup) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to seed caller-local route fixture");
|
||||
}
|
||||
const char *target = "api-1459";
|
||||
cbm_cross_repo_result_t fwd = cbm_cross_repo_match("mono-1459", &target, 1);
|
||||
const char *consumer = "mono-1459";
|
||||
cbm_cross_repo_result_t rev = cbm_cross_repo_match("api-1459", &consumer, 1);
|
||||
int mono_edges = cross_repo_count_edges(&fixture, "mono-1459", "CROSS_HTTP_CALLS");
|
||||
int api_edges = cross_repo_count_edges(&fixture, "api-1459", "CROSS_HTTP_CALLS");
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_FALSE(fwd.failed);
|
||||
ASSERT_FALSE(rev.failed);
|
||||
ASSERT_EQ(fwd.http_edges, 0);
|
||||
ASSERT_EQ(rev.http_edges, 0);
|
||||
ASSERT_EQ(mono_edges, 0);
|
||||
ASSERT_EQ(api_edges, 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1459 floor, real-world shape: a method-less client call points at the ANY
|
||||
* Route node, while the caller's own handler sits on the GET node for the same
|
||||
* path. The call is still served in-project and must not cross. */
|
||||
TEST(cross_repo_methodless_call_to_local_get_route_blocks_cross_http_issue1459) {
|
||||
cross_repo_fixture_t fixture;
|
||||
bool setup =
|
||||
cross_repo_fixture_begin(&fixture) &&
|
||||
cross_repo_seed_http_pair(&fixture, "mono2-1459", "api3-1459", "/api/users", "mono2") &&
|
||||
cross_repo_exec(&fixture, "mono2-1459",
|
||||
"UPDATE edges SET properties = '{\"url_path\":\"/api/users\"}' "
|
||||
"WHERE type = 'HTTP_CALLS';") &&
|
||||
cross_repo_seed_local_get_route(&fixture, "mono2-1459", "/api/users");
|
||||
if (!setup) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to seed method-less caller-local fixture");
|
||||
}
|
||||
const char *target = "api3-1459";
|
||||
cbm_cross_repo_result_t fwd = cbm_cross_repo_match("mono2-1459", &target, 1);
|
||||
const char *consumer = "mono2-1459";
|
||||
cbm_cross_repo_result_t rev = cbm_cross_repo_match("api3-1459", &consumer, 1);
|
||||
int mono_edges = cross_repo_count_edges(&fixture, "mono2-1459", "CROSS_HTTP_CALLS");
|
||||
int api_edges = cross_repo_count_edges(&fixture, "api3-1459", "CROSS_HTTP_CALLS");
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_FALSE(fwd.failed);
|
||||
ASSERT_FALSE(rev.failed);
|
||||
ASSERT_EQ(fwd.http_edges, 0);
|
||||
ASSERT_EQ(rev.http_edges, 0);
|
||||
ASSERT_EQ(mono_edges, 0);
|
||||
ASSERT_EQ(api_edges, 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Control for the #1459 floor: without a caller-local handler the path match
|
||||
* still links the caller to the remote handler, in both run directions. */
|
||||
TEST(cross_repo_caller_without_local_handler_keeps_cross_http_issue1459) {
|
||||
cross_repo_fixture_t fixture;
|
||||
bool setup =
|
||||
cross_repo_fixture_begin(&fixture) &&
|
||||
cross_repo_seed_http_pair(&fixture, "client-1459", "api2-1459", "/api/users", "client");
|
||||
if (!setup) {
|
||||
cross_repo_fixture_end(&fixture);
|
||||
FAIL("failed to seed remote-only route fixture");
|
||||
}
|
||||
const char *target = "api2-1459";
|
||||
cbm_cross_repo_result_t fwd = cbm_cross_repo_match("client-1459", &target, 1);
|
||||
int client_edges = cross_repo_count_edges(&fixture, "client-1459", "CROSS_HTTP_CALLS");
|
||||
int api_edges = cross_repo_count_edges(&fixture, "api2-1459", "CROSS_HTTP_CALLS");
|
||||
const char *consumer = "client-1459";
|
||||
cbm_cross_repo_result_t rev = cbm_cross_repo_match("api2-1459", &consumer, 1);
|
||||
cross_repo_fixture_end(&fixture);
|
||||
|
||||
ASSERT_FALSE(fwd.failed);
|
||||
ASSERT_FALSE(rev.failed);
|
||||
ASSERT_EQ(fwd.http_edges, 1);
|
||||
ASSERT_EQ(rev.http_edges, 1);
|
||||
ASSERT_EQ(client_edges, 1);
|
||||
ASSERT_EQ(api_edges, 1);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(cross_repo) {
|
||||
RUN_TEST(cross_repo_caller_local_handler_blocks_cross_http_issue1459);
|
||||
RUN_TEST(cross_repo_methodless_call_to_local_get_route_blocks_cross_http_issue1459);
|
||||
RUN_TEST(cross_repo_caller_without_local_handler_keeps_cross_http_issue1459);
|
||||
RUN_TEST(cross_repo_accepts_project_with_missed_shadow_row_issue1609);
|
||||
RUN_TEST(cross_repo_null_target_fails_without_dereference);
|
||||
RUN_TEST(cross_repo_wildcard_keeps_projects_containing_internal_tokens);
|
||||
RUN_TEST(cross_repo_wildcard_skips_pre768_store_issue2133);
|
||||
RUN_TEST(cross_repo_named_pre768_target_fails_before_cleanup_issue2133);
|
||||
RUN_TEST(cross_repo_scan_bound_counts_examined_rows_not_matches);
|
||||
RUN_TEST(cross_repo_propagates_delete_failure);
|
||||
RUN_TEST(cross_repo_failed_bidirectional_insert_is_not_counted);
|
||||
RUN_TEST(cross_repo_cancel_mid_run_keeps_completed_target_and_stops_before_later_target);
|
||||
RUN_TEST(cross_repo_pre_cancel_preserves_existing_cross_edges);
|
||||
RUN_TEST(cross_repo_self_only_target_fails_and_keeps_edges_issue1133);
|
||||
RUN_TEST(cross_repo_wildcard_with_no_other_project_fails_issue1133);
|
||||
}
|
||||
|
||||
@@ -715,6 +715,45 @@ TEST(cypher_exec_optional_empty_label_no_overflow) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Regression: the relationship variant of the test above. An OPTIONAL MATCH
|
||||
* with a relationship whose start AND terminal are both unbound, and whose
|
||||
* start matches zero nodes, drove cross_join_with_rels with extra_count == 0.
|
||||
* That sized its output for a single binding, and the OPTIONAL fallback then
|
||||
* wrote one row per existing binding without growing the buffer: a heap
|
||||
* buffer overflow once the first MATCH bound more than one node (ASan:
|
||||
* heap-buffer-overflow). The query text reaches this from the MCP query tool. */
|
||||
TEST(cypher_exec_optional_empty_label_rel_no_overflow) {
|
||||
cbm_store_t *s = setup_cypher_store(); /* 4 Function nodes */
|
||||
cbm_cypher_result_t r = {0};
|
||||
|
||||
int rc = cbm_cypher_execute(s,
|
||||
"MATCH (a:Function) OPTIONAL MATCH (x:NoSuchLabel)-[:CALLS]->(y) "
|
||||
"RETURN a.name, x.name, y.name",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.col_count, 3);
|
||||
/* One row per Function, each with x and y left unbound (""). */
|
||||
ASSERT_EQ(r.row_count, 4);
|
||||
const char *want[] = {"HandleOrder", "ValidateOrder", "SubmitOrder", "LogError"};
|
||||
for (int w = 0; w < 4; w++) {
|
||||
int seen = 0;
|
||||
for (int i = 0; i < r.row_count; i++) {
|
||||
if (strcmp(r.rows[i][0], want[w]) == 0) {
|
||||
seen++;
|
||||
}
|
||||
}
|
||||
ASSERT_EQ(seen, 1);
|
||||
}
|
||||
for (int i = 0; i < r.row_count; i++) {
|
||||
ASSERT_STR_EQ(r.rows[i][1], "");
|
||||
ASSERT_STR_EQ(r.rows[i][2], "");
|
||||
}
|
||||
|
||||
cbm_cypher_result_free(&r);
|
||||
cbm_store_close(s);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Regression: expand_pattern_rels sized its OPTIONAL-expansion output buffer as
|
||||
* bind_cap*10 + 1 — room for the bounded expansion (max_new = bind_cap*10) plus
|
||||
* a SINGLE OPTIONAL fallback row. When one source saturated the expansion to
|
||||
@@ -3937,6 +3976,202 @@ TEST(cypher_exec_with_rename) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2208: a node carried IN SCOPE through WITH must project every property
|
||||
* exactly as the same node does without the WITH. The carried var used to be a
|
||||
* name-only stub whose qualified_name slot held the variable name and whose
|
||||
* start_line was 0, so f.qualified_name returned "f" and f.start_line "0". */
|
||||
static int64_t issue2208_id_of(cbm_store_t *s, const char *qn) {
|
||||
cbm_node_t n = {0};
|
||||
int64_t id = 0;
|
||||
if (cbm_store_find_node_by_qn(s, "test", qn, &n) == CBM_STORE_OK) {
|
||||
id = n.id;
|
||||
cbm_node_free_fields(&n);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
static cbm_store_t *setup_issue2208_store(void) {
|
||||
cbm_store_t *s = setup_cypher_store();
|
||||
cbm_node_t twins[] = {
|
||||
{.project = "test",
|
||||
.label = "Function",
|
||||
.name = "ProjectionTwin",
|
||||
.qualified_name = "test.ProjectionA",
|
||||
.file_path = "projection_a.go",
|
||||
.start_line = 30,
|
||||
.end_line = 40,
|
||||
.properties_json = "{\"marker\":\"alpha\"}"},
|
||||
{.project = "test",
|
||||
.label = "Function",
|
||||
.name = "ProjectionTwin",
|
||||
.qualified_name = "test.ProjectionB",
|
||||
.file_path = "projection_b.go",
|
||||
.start_line = 10,
|
||||
.end_line = 20,
|
||||
.properties_json = "{\"marker\":\"beta\"}"},
|
||||
{.project = "test",
|
||||
.label = "Function",
|
||||
.name = "ProjectionTwin",
|
||||
.qualified_name = "test.ProjectionC",
|
||||
.file_path = "projection_c.go",
|
||||
.start_line = 20,
|
||||
.end_line = 30,
|
||||
.properties_json = "{\"marker\":\"gamma\"}"},
|
||||
};
|
||||
int64_t ids[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ids[i] = cbm_store_upsert_node(s, &twins[i]);
|
||||
}
|
||||
/* Callers: A has 2 (HandleOrder, ValidateOrder), B has 1 (HandleOrder), C none. */
|
||||
int64_t handle = issue2208_id_of(s, "test.HandleOrder");
|
||||
int64_t validate = issue2208_id_of(s, "test.ValidateOrder");
|
||||
cbm_edge_t e1 = {.project = "test", .source_id = handle, .target_id = ids[0], .type = "CALLS"};
|
||||
cbm_edge_t e2 = {
|
||||
.project = "test", .source_id = validate, .target_id = ids[0], .type = "CALLS"};
|
||||
cbm_edge_t e3 = {.project = "test", .source_id = handle, .target_id = ids[1], .type = "CALLS"};
|
||||
cbm_store_insert_edge(s, &e1);
|
||||
cbm_store_insert_edge(s, &e2);
|
||||
cbm_store_insert_edge(s, &e3);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The reporter's exact shape: aggregate WITH carrying the node beside count(). */
|
||||
TEST(cypher_issue2208_with_agg_carried_node_props) {
|
||||
cbm_store_t *s = setup_issue2208_store();
|
||||
cbm_cypher_result_t r = {0};
|
||||
int rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function {qualified_name: 'test.ProjectionA'}) "
|
||||
"OPTIONAL MATCH (caller)-[r:CALLS]->(f) "
|
||||
"WITH f, count(r) AS refs "
|
||||
"RETURN f.qualified_name, f.file_path, f.start_line, "
|
||||
"f.end_line, f.label, f.marker, f.name, refs",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 1);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "test.ProjectionA");
|
||||
ASSERT_STR_EQ(r.rows[0][1], "projection_a.go");
|
||||
ASSERT_STR_EQ(r.rows[0][2], "30");
|
||||
ASSERT_STR_EQ(r.rows[0][3], "40");
|
||||
ASSERT_STR_EQ(r.rows[0][4], "Function");
|
||||
ASSERT_STR_EQ(r.rows[0][5], "alpha");
|
||||
ASSERT_STR_EQ(r.rows[0][6], "ProjectionTwin");
|
||||
ASSERT_STR_EQ(r.rows[0][7], "2");
|
||||
cbm_cypher_result_free(&r);
|
||||
cbm_store_close(s);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Aggregate WITH groups by node IDENTITY, not display name: three same-named
|
||||
* functions stay three rows, each with its own properties and caller count
|
||||
* (they used to collapse into one row with one node's props and summed refs). */
|
||||
TEST(cypher_issue2208_with_agg_groups_by_node_identity) {
|
||||
cbm_store_t *s = setup_issue2208_store();
|
||||
cbm_cypher_result_t r = {0};
|
||||
int rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function {name: 'ProjectionTwin'}) "
|
||||
"OPTIONAL MATCH (caller)-[r:CALLS]->(f) "
|
||||
"WITH f, count(r) AS refs "
|
||||
"RETURN f.qualified_name, f.start_line, refs "
|
||||
"ORDER BY f.qualified_name",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 3);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "test.ProjectionA");
|
||||
ASSERT_STR_EQ(r.rows[0][1], "30");
|
||||
ASSERT_STR_EQ(r.rows[0][2], "2");
|
||||
ASSERT_STR_EQ(r.rows[1][0], "test.ProjectionB");
|
||||
ASSERT_STR_EQ(r.rows[1][1], "10");
|
||||
ASSERT_STR_EQ(r.rows[1][2], "1");
|
||||
ASSERT_STR_EQ(r.rows[2][0], "test.ProjectionC");
|
||||
ASSERT_STR_EQ(r.rows[2][1], "20");
|
||||
/* rows[2][2] (count(r) for the caller-less C) is not asserted here: count()
|
||||
* of an unbound OPTIONAL var is a separate, pre-existing defect. */
|
||||
cbm_cypher_result_free(&r);
|
||||
cbm_store_close(s);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Simple (non-aggregate) WITH: a bare node stays a node (renamed or not);
|
||||
* scalar items stay scalars; OPTIONAL null stays null; post-WITH WHERE and
|
||||
* WITH ... ORDER BY see the real node properties. */
|
||||
TEST(cypher_issue2208_with_simple_carried_node_props) {
|
||||
cbm_store_t *s = setup_issue2208_store();
|
||||
cbm_cypher_result_t r = {0};
|
||||
int rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function) WHERE f.qualified_name = 'test.ProjectionA' "
|
||||
"WITH f "
|
||||
"RETURN f.name, f.qualified_name, f.file_path, f.label, "
|
||||
"f.start_line, f.marker",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 1);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "ProjectionTwin");
|
||||
ASSERT_STR_EQ(r.rows[0][1], "test.ProjectionA");
|
||||
ASSERT_STR_EQ(r.rows[0][2], "projection_a.go");
|
||||
ASSERT_STR_EQ(r.rows[0][3], "Function");
|
||||
ASSERT_STR_EQ(r.rows[0][4], "30");
|
||||
ASSERT_STR_EQ(r.rows[0][5], "alpha");
|
||||
cbm_cypher_result_free(&r);
|
||||
|
||||
memset(&r, 0, sizeof(r));
|
||||
rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function) WHERE f.qualified_name = 'test.ProjectionA' "
|
||||
"WITH f AS g, f.name AS n, labels(f) AS ls "
|
||||
"RETURN g.qualified_name, g.file_path, n, ls, n.file_path, "
|
||||
"ls.file_path",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 1);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "test.ProjectionA");
|
||||
ASSERT_STR_EQ(r.rows[0][1], "projection_a.go");
|
||||
ASSERT_STR_EQ(r.rows[0][2], "ProjectionTwin");
|
||||
ASSERT_STR_EQ(r.rows[0][3], "[\"Function\"]");
|
||||
ASSERT_STR_EQ(r.rows[0][4], "");
|
||||
ASSERT_STR_EQ(r.rows[0][5], "");
|
||||
cbm_cypher_result_free(&r);
|
||||
|
||||
/* OPTIONAL null carried through WITH stays null (no fabricated node). */
|
||||
memset(&r, 0, sizeof(r));
|
||||
rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function) WHERE f.name = 'LogError' "
|
||||
"OPTIONAL MATCH (f)-[:CALLS]->(g:Function) "
|
||||
"WITH g AS projected "
|
||||
"RETURN projected, projected.file_path, projected.qualified_name",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 1);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "");
|
||||
ASSERT_STR_EQ(r.rows[0][1], "");
|
||||
ASSERT_STR_EQ(r.rows[0][2], "");
|
||||
cbm_cypher_result_free(&r);
|
||||
|
||||
memset(&r, 0, sizeof(r));
|
||||
rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function) WITH f AS g "
|
||||
"WHERE g.file_path = 'projection_b.go' "
|
||||
"RETURN g.qualified_name",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 1);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "test.ProjectionB");
|
||||
cbm_cypher_result_free(&r);
|
||||
|
||||
/* A(30), B(10), C(20): ascending then SKIP 1 LIMIT 1 selects C. */
|
||||
memset(&r, 0, sizeof(r));
|
||||
rc = cbm_cypher_execute(s,
|
||||
"MATCH (f:Function) WHERE f.name = 'ProjectionTwin' "
|
||||
"WITH f AS g ORDER BY g.start_line ASC SKIP 1 LIMIT 1 "
|
||||
"RETURN g.qualified_name, g.start_line",
|
||||
"test", 0, &r);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(r.row_count, 1);
|
||||
ASSERT_STR_EQ(r.rows[0][0], "test.ProjectionC");
|
||||
ASSERT_STR_EQ(r.rows[0][1], "20");
|
||||
cbm_cypher_result_free(&r);
|
||||
cbm_store_close(s);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(cypher_exec_with_count) {
|
||||
cbm_store_t *s = setup_cypher_store();
|
||||
cbm_cypher_result_t r = {0};
|
||||
@@ -4673,6 +4908,7 @@ SUITE(cypher) {
|
||||
RUN_TEST(cypher_deep_nesting_rejected_not_crash);
|
||||
RUN_TEST(cypher_exec_match_all_functions);
|
||||
RUN_TEST(cypher_exec_optional_empty_label_no_overflow);
|
||||
RUN_TEST(cypher_exec_optional_empty_label_rel_no_overflow);
|
||||
RUN_TEST(cypher_cross_join_alloc_rejects_overflow);
|
||||
RUN_TEST(cypher_exec_optional_rel_saturated_no_overflow);
|
||||
RUN_TEST(cypher_exec_optional_saturated_does_not_fabricate_no_match);
|
||||
@@ -4822,6 +5058,9 @@ SUITE(cypher) {
|
||||
RUN_TEST(cypher_parse_case);
|
||||
/* Phase 6: WITH clause */
|
||||
RUN_TEST(cypher_exec_with_rename);
|
||||
RUN_TEST(cypher_issue2208_with_agg_carried_node_props);
|
||||
RUN_TEST(cypher_issue2208_with_agg_groups_by_node_identity);
|
||||
RUN_TEST(cypher_issue2208_with_simple_carried_node_props);
|
||||
RUN_TEST(cypher_exec_with_count);
|
||||
RUN_TEST(cypher_issue1111_with_type_count_group);
|
||||
RUN_TEST(cypher_issue1111_with_scalar_func_alias_no_node_leak);
|
||||
|
||||
@@ -5681,6 +5681,735 @@ TEST(daemon_application_index_args_compare_repo_path_separator_equivalently) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── #2144: async index_repository + status polling ─────────────────────────
|
||||
*
|
||||
* A client with a per-call deadline (Copilot for IntelliJ) gives up on a long
|
||||
* synchronous index; its cancel makes the daemon drop the job's last
|
||||
* subscriber and cancel the worker, so every retry starts over and a large
|
||||
* repository never finishes. async:true starts the job detached from the
|
||||
* request and session; status:true polls it. Every wait below is a bounded
|
||||
* observation of a held fake worker (never a timing assertion). */
|
||||
|
||||
typedef struct {
|
||||
app_fake_worker_context_t fake;
|
||||
cbm_daemon_application_worker_ops_t ops;
|
||||
cbm_daemon_application_t *application;
|
||||
cbm_daemon_runtime_application_callbacks_t callbacks;
|
||||
char root[APP_TEST_PATH_CAP];
|
||||
char *project;
|
||||
uint8_t *context;
|
||||
uint32_t context_length;
|
||||
} app_async_fixture_t;
|
||||
|
||||
static bool app_async_fixture_init(app_async_fixture_t *fixture, const char *label,
|
||||
bool permanent) {
|
||||
memset(fixture, 0, sizeof(*fixture));
|
||||
app_fake_worker_context_init(&fixture->fake);
|
||||
fixture->ops = (cbm_daemon_application_worker_ops_t){
|
||||
.context = &fixture->fake,
|
||||
.start = app_fake_worker_start,
|
||||
.poll = app_fake_worker_poll,
|
||||
.cancel = app_fake_worker_cancel,
|
||||
.log_path = app_fake_worker_log_path,
|
||||
.destroy = app_fake_worker_destroy,
|
||||
};
|
||||
cbm_daemon_application_config_t config = {.worker_ops = &fixture->ops};
|
||||
fixture->application = cbm_daemon_application_new(&config);
|
||||
if (!fixture->application) {
|
||||
return false;
|
||||
}
|
||||
/* permanent mirrors `daemon start`; false is the temporary generation an
|
||||
* MCP client or one-shot command spawns. */
|
||||
cbm_daemon_application_set_permanent(fixture->application, permanent);
|
||||
fixture->callbacks = cbm_daemon_application_runtime_callbacks(fixture->application);
|
||||
(void)snprintf(fixture->root, sizeof(fixture->root), "%s/cbm-app-%s-XXXXXX", cbm_tmpdir(),
|
||||
label);
|
||||
if (!cbm_mkdtemp(fixture->root)) {
|
||||
fixture->root[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
fixture->project = cbm_project_name_from_path(fixture->root);
|
||||
return fixture->project &&
|
||||
app_test_context_request(fixture->root, fixture->root, &fixture->context,
|
||||
&fixture->context_length);
|
||||
}
|
||||
|
||||
static cbm_daemon_runtime_application_session_t *app_async_session(app_async_fixture_t *fixture,
|
||||
cbm_daemon_client_id_t id) {
|
||||
cbm_daemon_runtime_application_session_t *session = app_test_open(&fixture->callbacks, id);
|
||||
uint8_t *empty = NULL;
|
||||
uint32_t empty_length = 0;
|
||||
bool ok = session && app_test_request(&fixture->callbacks, session, fixture->context,
|
||||
fixture->context_length, &empty,
|
||||
&empty_length) == CBM_DAEMON_RUNTIME_APPLICATION_OK;
|
||||
free(empty);
|
||||
if (!ok && session) {
|
||||
fixture->callbacks.session_close(fixture->callbacks.context, session);
|
||||
session = NULL;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
/* One index_repository request on its own thread, so a call that (wrongly)
|
||||
* blocks for the whole index cannot hang the suite: the caller observes
|
||||
* `done` within the hang-detector budget, then always releases the worker
|
||||
* before joining. */
|
||||
typedef struct {
|
||||
app_request_thread_t request;
|
||||
uint8_t *tool;
|
||||
cbm_thread_t thread;
|
||||
bool started;
|
||||
} app_async_call_t;
|
||||
|
||||
static bool app_async_call_start(app_async_fixture_t *fixture, app_async_call_t *call,
|
||||
cbm_daemon_runtime_application_session_t *session,
|
||||
cbm_daemon_runtime_application_token_t token,
|
||||
const char *extra_args) {
|
||||
memset(call, 0, sizeof(*call));
|
||||
char args[APP_TEST_PATH_CAP + 128];
|
||||
(void)snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"%s}", fixture->root,
|
||||
extra_args ? extra_args : "");
|
||||
uint32_t tool_length = 0;
|
||||
if (!app_test_tool_request("index_repository", args, &call->tool, &tool_length)) {
|
||||
return false;
|
||||
}
|
||||
call->request.callbacks = fixture->callbacks;
|
||||
call->request.session = session;
|
||||
call->request.request_token = token;
|
||||
call->request.request = call->tool;
|
||||
call->request.request_length = tool_length;
|
||||
atomic_init(&call->request.done, false);
|
||||
call->started = cbm_thread_create(&call->thread, 0, app_request_thread, &call->request) == 0;
|
||||
return call->started;
|
||||
}
|
||||
|
||||
static const char *app_async_call_response(app_async_call_t *call) {
|
||||
return call->request.response ? (const char *)call->request.response : "";
|
||||
}
|
||||
|
||||
static void app_async_call_join(app_async_call_t *call) {
|
||||
if (call->started) {
|
||||
(void)cbm_thread_join(&call->thread);
|
||||
call->started = false;
|
||||
}
|
||||
}
|
||||
|
||||
static void app_async_call_free(app_async_call_t *call) {
|
||||
app_async_call_join(call);
|
||||
free(call->request.response);
|
||||
free(call->tool);
|
||||
memset(call, 0, sizeof(*call));
|
||||
}
|
||||
|
||||
/* A request that must return promptly (status, validation, async start). */
|
||||
static char *app_async_call_now(app_async_fixture_t *fixture,
|
||||
cbm_daemon_runtime_application_session_t *session,
|
||||
const char *extra_args) {
|
||||
app_async_call_t call;
|
||||
memset(&call, 0, sizeof(call));
|
||||
char *response = NULL;
|
||||
if (app_async_call_start(fixture, &call, session, CBM_DAEMON_RUNTIME_APPLICATION_TOKEN_INVALID,
|
||||
extra_args) &&
|
||||
app_wait_for_atomic_bool(&call.request.done, true)) {
|
||||
response = strdup(app_async_call_response(&call));
|
||||
}
|
||||
/* Never strand a request thread that blocked on the held worker. */
|
||||
if (call.started && !atomic_load(&call.request.done)) {
|
||||
atomic_store(&fixture->fake.allow_completion, true);
|
||||
}
|
||||
app_async_call_free(&call);
|
||||
return response;
|
||||
}
|
||||
|
||||
static bool app_async_fixture_finish(app_async_fixture_t *fixture) {
|
||||
atomic_store(&fixture->fake.allow_completion, true);
|
||||
bool stopped = fixture->application &&
|
||||
cbm_daemon_application_shutdown(fixture->application, APP_TEST_TIMEOUT_MS);
|
||||
cbm_daemon_application_free(fixture->application);
|
||||
free(fixture->context);
|
||||
free(fixture->project);
|
||||
if (fixture->root[0]) {
|
||||
(void)cbm_rmdir(fixture->root);
|
||||
}
|
||||
return stopped;
|
||||
}
|
||||
|
||||
static bool app_async_contains(const char *text, const char *needle) {
|
||||
return text && strstr(text, needle) != NULL;
|
||||
}
|
||||
|
||||
TEST(daemon_application_async_index_returns_before_completion_and_status_polls) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "async-poll", true);
|
||||
cbm_daemon_runtime_application_session_t *session =
|
||||
setup ? app_async_session(&fixture, 7101) : NULL;
|
||||
|
||||
/* The worker is held: a blocking call cannot return until it is released. */
|
||||
char *started = session ? app_async_call_now(&fixture, session, ",\"async\":true") : NULL;
|
||||
bool worker_running = started && app_wait_for_atomic_int(&fixture.fake.starts, 1);
|
||||
char *running =
|
||||
worker_running ? app_async_call_now(&fixture, session, ",\"status\":true") : NULL;
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
bool drained = running && app_wait_for_active_jobs(fixture.application, 0);
|
||||
char *finished = drained ? app_async_call_now(&fixture, session, ",\"status\":true") : NULL;
|
||||
int cancels = atomic_load(&fixture.fake.cancels);
|
||||
if (session) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, session);
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_NOT_NULL(session);
|
||||
ASSERT_NOT_NULL(started);
|
||||
ASSERT_TRUE(app_async_contains(started, "\"async\":true"));
|
||||
ASSERT_FALSE(app_async_contains(started, "\"isError\":true"));
|
||||
ASSERT_TRUE(worker_running);
|
||||
ASSERT_NOT_NULL(running);
|
||||
ASSERT_TRUE(app_async_contains(running, "\"state\":\"running\""));
|
||||
ASSERT_TRUE(drained);
|
||||
ASSERT_NOT_NULL(finished);
|
||||
ASSERT_TRUE(app_async_contains(finished, "\"state\":\"succeeded\""));
|
||||
ASSERT_TRUE(app_async_contains(finished, "\"finished_at\""));
|
||||
ASSERT_EQ(cancels, 0);
|
||||
ASSERT_EQ(atomic_load(&fixture.fake.starts), 1);
|
||||
ASSERT_TRUE(stopped);
|
||||
free(started);
|
||||
free(running);
|
||||
free(finished);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The async job belongs to the daemon, not to the session that started it:
|
||||
* closing that session (the client gave up and went away) leaves the worker
|
||||
* running while another session still keeps this daemon generation alive. */
|
||||
TEST(daemon_application_async_index_survives_requesting_session_close) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "async-survive", false);
|
||||
cbm_daemon_runtime_application_session_t *starter =
|
||||
setup ? app_async_session(&fixture, 7201) : NULL;
|
||||
cbm_daemon_runtime_application_session_t *observer =
|
||||
starter ? app_async_session(&fixture, 7202) : NULL;
|
||||
char *started = observer ? app_async_call_now(&fixture, starter, ",\"async\":true") : NULL;
|
||||
bool worker_running = started && app_wait_for_atomic_int(&fixture.fake.starts, 1);
|
||||
if (worker_running) {
|
||||
fixture.callbacks.session_cancel(fixture.callbacks.context, starter);
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, starter);
|
||||
starter = NULL;
|
||||
}
|
||||
int cancels_after_close = atomic_load(&fixture.fake.cancels);
|
||||
size_t jobs_after_close = cbm_daemon_application_active_jobs(fixture.application);
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
bool drained = worker_running && app_wait_for_active_jobs(fixture.application, 0);
|
||||
char *finished = drained ? app_async_call_now(&fixture, observer, ",\"status\":true") : NULL;
|
||||
if (starter) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, starter);
|
||||
}
|
||||
if (observer) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, observer);
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_NOT_NULL(observer);
|
||||
ASSERT_TRUE(app_async_contains(started, "\"async\":true"));
|
||||
ASSERT_TRUE(worker_running);
|
||||
ASSERT_EQ(cancels_after_close, 0);
|
||||
ASSERT_EQ(jobs_after_close, 1);
|
||||
ASSERT_TRUE(drained);
|
||||
ASSERT_TRUE(app_async_contains(finished, "\"state\":\"succeeded\""));
|
||||
ASSERT_EQ(atomic_load(&fixture.fake.cancels), 0);
|
||||
ASSERT_TRUE(stopped);
|
||||
free(started);
|
||||
free(finished);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Regression guard for the unchanged synchronous contract, in the exact
|
||||
* shape of the test above: the same close with a SYNC caller still cancels
|
||||
* the worker once its last subscriber is gone, even though another session
|
||||
* keeps the daemon generation alive. */
|
||||
TEST(daemon_application_sync_index_still_cancels_on_last_subscriber_close) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "sync-cancel", false);
|
||||
cbm_daemon_runtime_application_session_t *starter =
|
||||
setup ? app_async_session(&fixture, 7301) : NULL;
|
||||
cbm_daemon_runtime_application_session_t *observer =
|
||||
starter ? app_async_session(&fixture, 7302) : NULL;
|
||||
app_async_call_t call;
|
||||
memset(&call, 0, sizeof(call));
|
||||
bool call_started =
|
||||
observer && app_async_call_start(&fixture, &call, starter, UINT64_C(7303), NULL);
|
||||
bool worker_running = call_started && app_wait_for_atomic_int(&fixture.fake.starts, 1);
|
||||
if (worker_running) {
|
||||
fixture.callbacks.session_cancel(fixture.callbacks.context, starter);
|
||||
}
|
||||
bool cancelled = worker_running && app_wait_for_atomic_int(&fixture.fake.cancels, 1);
|
||||
if (call_started) {
|
||||
if (!atomic_load(&call.request.done)) {
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
}
|
||||
app_async_call_join(&call);
|
||||
}
|
||||
cbm_daemon_runtime_application_status_t status = call.request.status;
|
||||
if (call_started) {
|
||||
app_async_call_free(&call);
|
||||
}
|
||||
if (starter) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, starter);
|
||||
}
|
||||
if (observer) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, observer);
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_TRUE(call_started);
|
||||
ASSERT_TRUE(worker_running);
|
||||
ASSERT_TRUE(cancelled);
|
||||
ASSERT_EQ(status, CBM_DAEMON_RUNTIME_APPLICATION_CANCELLED);
|
||||
ASSERT_TRUE(stopped);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(daemon_application_async_and_status_validation_errors) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "async-validate", false);
|
||||
cbm_daemon_runtime_application_session_t *session =
|
||||
setup ? app_async_session(&fixture, 7401) : NULL;
|
||||
char *both =
|
||||
session ? app_async_call_now(&fixture, session, ",\"async\":true,\"status\":true") : NULL;
|
||||
char *not_bool = session ? app_async_call_now(&fixture, session, ",\"async\":\"yes\"") : NULL;
|
||||
char *cross = session
|
||||
? app_async_call_now(&fixture, session,
|
||||
",\"async\":true,\"mode\":\"cross-repo-intelligence\"")
|
||||
: NULL;
|
||||
/* Nothing was ever indexed here and no job ran: status must say so, not
|
||||
* report an empty success. */
|
||||
char *unknown = session ? app_async_call_now(&fixture, session, ",\"status\":true") : NULL;
|
||||
int starts = atomic_load(&fixture.fake.starts);
|
||||
if (session) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, session);
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_TRUE(app_async_contains(both, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(both, "exclusive"));
|
||||
ASSERT_TRUE(app_async_contains(not_bool, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(not_bool, "must be booleans"));
|
||||
ASSERT_TRUE(app_async_contains(cross, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(cross, "cross-repo-intelligence"));
|
||||
ASSERT_TRUE(app_async_contains(unknown, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(unknown, "no index job or index is known"));
|
||||
ASSERT_EQ(starts, 0);
|
||||
ASSERT_TRUE(stopped);
|
||||
free(both);
|
||||
free(not_bool);
|
||||
free(cross);
|
||||
free(unknown);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Cut-short advice (a): a synchronous caller whose job is cancelled out from
|
||||
* under it (here: the daemon stops) receives the async alternative in the
|
||||
* cancellation text it is actually delivered. */
|
||||
TEST(daemon_application_cancelled_sync_index_reply_offers_async) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "sync-hint", false);
|
||||
cbm_daemon_runtime_application_session_t *session =
|
||||
setup ? app_async_session(&fixture, 7501) : NULL;
|
||||
app_async_call_t call;
|
||||
memset(&call, 0, sizeof(call));
|
||||
bool call_started =
|
||||
session && app_async_call_start(&fixture, &call, session, UINT64_C(7502), NULL);
|
||||
bool worker_running = call_started && app_wait_for_atomic_int(&fixture.fake.starts, 1);
|
||||
/* Shutdown cancels the job but not the waiting request, so the waiter is
|
||||
* handed the job's cancellation reply. */
|
||||
bool stopped =
|
||||
worker_running && cbm_daemon_application_shutdown(fixture.application, APP_TEST_TIMEOUT_MS);
|
||||
if (call_started && !atomic_load(&call.request.done)) {
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
}
|
||||
if (call_started) {
|
||||
app_async_call_join(&call);
|
||||
}
|
||||
cbm_daemon_runtime_application_status_t status = call.request.status;
|
||||
char *reply = call_started ? strdup(app_async_call_response(&call)) : NULL;
|
||||
if (call_started) {
|
||||
app_async_call_free(&call);
|
||||
}
|
||||
if (session) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, session);
|
||||
}
|
||||
(void)app_async_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_TRUE(worker_running);
|
||||
ASSERT_TRUE(stopped);
|
||||
ASSERT_EQ(status, CBM_DAEMON_RUNTIME_APPLICATION_OK);
|
||||
ASSERT_TRUE(app_async_contains(reply, "cancelled"));
|
||||
ASSERT_TRUE(app_async_contains(reply, "async: true"));
|
||||
ASSERT_TRUE(app_async_contains(reply, "status: true"));
|
||||
free(reply);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Cut-short advice (b): the Copilot-deadline case. The client cancels its
|
||||
* synchronous call, which never sees a reply; the NEXT status call and the
|
||||
* NEXT index_repository call for that project carry the advice, once. */
|
||||
TEST(daemon_application_cut_short_sync_index_advice_reaches_next_call) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "sync-next", false);
|
||||
cbm_daemon_runtime_application_session_t *session =
|
||||
setup ? app_async_session(&fixture, 7601) : NULL;
|
||||
app_async_call_t call;
|
||||
memset(&call, 0, sizeof(call));
|
||||
cbm_daemon_runtime_application_token_t token = UINT64_C(7602);
|
||||
bool call_started = session && app_async_call_start(&fixture, &call, session, token, NULL);
|
||||
bool worker_running = call_started && app_wait_for_atomic_int(&fixture.fake.starts, 1);
|
||||
if (worker_running) {
|
||||
fixture.callbacks.request_cancel(fixture.callbacks.context, session, token);
|
||||
}
|
||||
bool cancelled_returned = worker_running && app_wait_for_atomic_bool(&call.request.done, true);
|
||||
if (call_started && !atomic_load(&call.request.done)) {
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
}
|
||||
if (call_started) {
|
||||
app_async_call_free(&call);
|
||||
}
|
||||
bool drained = cancelled_returned && app_wait_for_active_jobs(fixture.application, 0);
|
||||
char *status = drained ? app_async_call_now(&fixture, session, ",\"status\":true") : NULL;
|
||||
/* Every later worker completes at once. */
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
char *next = status ? app_async_call_now(&fixture, session, NULL) : NULL;
|
||||
char *after = next ? app_async_call_now(&fixture, session, NULL) : NULL;
|
||||
if (session) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, session);
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_TRUE(worker_running);
|
||||
ASSERT_TRUE(cancelled_returned);
|
||||
ASSERT_TRUE(drained);
|
||||
ASSERT_TRUE(app_async_contains(status, "\"state\":\"cancelled\""));
|
||||
ASSERT_TRUE(app_async_contains(status, "\"notice\""));
|
||||
ASSERT_TRUE(app_async_contains(status, "async: true"));
|
||||
ASSERT_TRUE(app_async_contains(next, "indexed"));
|
||||
ASSERT_TRUE(app_async_contains(next, "\"notice\""));
|
||||
ASSERT_TRUE(app_async_contains(next, "cut short"));
|
||||
ASSERT_TRUE(app_async_contains(after, "indexed"));
|
||||
ASSERT_FALSE(app_async_contains(after, "\"notice\""));
|
||||
ASSERT_TRUE(stopped);
|
||||
free(status);
|
||||
free(next);
|
||||
free(after);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2144 user decision: on a temporary daemon, a one-shot `cli` request that is
|
||||
* the daemon's only live session is refused async (the daemon would stop and
|
||||
* cancel the job as soon as the command exits), while status stays allowed and
|
||||
* a long-lived MCP session on the same temporary daemon remains a valid host. */
|
||||
TEST(daemon_application_async_refused_for_lone_one_shot_client_of_temporary_daemon) {
|
||||
app_async_fixture_t fixture;
|
||||
bool setup = app_async_fixture_init(&fixture, "async-refuse", false);
|
||||
cbm_daemon_runtime_application_session_t *session =
|
||||
setup ? app_async_session(&fixture, 7701) : NULL;
|
||||
char *refused = session ? app_async_call_now(&fixture, session, ",\"async\":true") : NULL;
|
||||
int starts_after_refusal = atomic_load(&fixture.fake.starts);
|
||||
char *status = refused ? app_async_call_now(&fixture, session, ",\"status\":true") : NULL;
|
||||
|
||||
/* Same temporary daemon, same lone session, but the MCP channel. */
|
||||
char message[APP_TEST_PATH_CAP + 256];
|
||||
(void)snprintf(message, sizeof(message),
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":7702,\"method\":\"tools/call\",\"params\":{"
|
||||
"\"name\":\"index_repository\",\"arguments\":{\"repo_path\":\"%s\","
|
||||
"\"async\":true}}}",
|
||||
fixture.root);
|
||||
uint8_t *mcp_request = NULL;
|
||||
uint32_t mcp_request_length = 0;
|
||||
uint8_t *mcp_response = NULL;
|
||||
uint32_t mcp_response_length = 0;
|
||||
cbm_daemon_runtime_application_status_t mcp_status =
|
||||
status && app_test_text_request(CBM_DAEMON_APPLICATION_REQUEST_MCP, message, &mcp_request,
|
||||
&mcp_request_length)
|
||||
? app_test_request(&fixture.callbacks, session, mcp_request, mcp_request_length,
|
||||
&mcp_response, &mcp_response_length)
|
||||
: CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;
|
||||
bool worker_started = mcp_status == CBM_DAEMON_RUNTIME_APPLICATION_OK &&
|
||||
app_wait_for_atomic_int(&fixture.fake.starts, 1);
|
||||
int cancels_while_hosted = atomic_load(&fixture.fake.cancels);
|
||||
atomic_store(&fixture.fake.allow_completion, true);
|
||||
bool drained = worker_started && app_wait_for_active_jobs(fixture.application, 0);
|
||||
if (session) {
|
||||
fixture.callbacks.session_close(fixture.callbacks.context, session);
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&fixture);
|
||||
char *mcp_text = mcp_response ? strdup((const char *)mcp_response) : NULL;
|
||||
free(mcp_response);
|
||||
free(mcp_request);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_NOT_NULL(session);
|
||||
ASSERT_TRUE(app_async_contains(refused, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(refused, "daemon start"));
|
||||
ASSERT_EQ(starts_after_refusal, 0);
|
||||
ASSERT_NOT_NULL(status);
|
||||
ASSERT_FALSE(app_async_contains(status, "daemon start"));
|
||||
ASSERT_EQ(mcp_status, CBM_DAEMON_RUNTIME_APPLICATION_OK);
|
||||
ASSERT_TRUE(app_async_contains(mcp_text, "\\\"async\\\":true"));
|
||||
ASSERT_FALSE(app_async_contains(mcp_text, "daemon start"));
|
||||
ASSERT_TRUE(worker_started);
|
||||
ASSERT_EQ(cancels_while_hosted, 0);
|
||||
ASSERT_TRUE(drained);
|
||||
ASSERT_TRUE(stopped);
|
||||
free(refused);
|
||||
free(status);
|
||||
free(mcp_text);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── #2134 x #2144: the unnamed status poll resolves the start's key ────────
|
||||
*
|
||||
* An unnamed index_repository of a root that another indexed project already
|
||||
* owns adopts that owner's name (#2134), so the daemon keys the async job by
|
||||
* it. The async reply tells the client to poll "with the same repo_path and
|
||||
* status: true"; that unnamed poll must resolve the same key (owner first,
|
||||
* then path-derived; several owners fail loudly), or it never finds the job
|
||||
* it just started. Owners are real project databases in a private cache; the
|
||||
* held fake worker never writes one, so the seeded state is all there is. */
|
||||
|
||||
enum { APP_OWNER_CANONICAL_CAP = 4096 }; /* cbm_canonical_path needs >= 4096 */
|
||||
|
||||
typedef struct {
|
||||
char cache[APP_TEST_PATH_CAP];
|
||||
char canonical_root[APP_OWNER_CANONICAL_CAP];
|
||||
char *saved_cache;
|
||||
bool had_cache;
|
||||
bool cache_set;
|
||||
app_async_fixture_t fixture;
|
||||
cbm_daemon_runtime_application_session_t *session;
|
||||
} app_owner_fixture_t;
|
||||
|
||||
typedef struct {
|
||||
char *started;
|
||||
char *running;
|
||||
char *finished;
|
||||
bool worker_running;
|
||||
bool drained;
|
||||
} app_owner_run_t;
|
||||
|
||||
static bool app_owner_fixture_init(app_owner_fixture_t *owner, const char *label) {
|
||||
memset(owner, 0, sizeof(*owner));
|
||||
const char *old_cache = getenv("CBM_CACHE_DIR");
|
||||
owner->had_cache = old_cache != NULL;
|
||||
owner->saved_cache = old_cache ? strdup(old_cache) : NULL;
|
||||
(void)snprintf(owner->cache, sizeof(owner->cache), "%s/cbm-app-owner-cache-XXXXXX",
|
||||
cbm_tmpdir());
|
||||
if ((owner->had_cache && !owner->saved_cache) || !cbm_mkdtemp(owner->cache)) {
|
||||
owner->cache[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
owner->cache_set = cbm_setenv("CBM_CACHE_DIR", owner->cache, 1) == 0;
|
||||
if (!owner->cache_set || !app_async_fixture_init(&owner->fixture, label, true) ||
|
||||
!cbm_canonical_path(owner->fixture.root, owner->canonical_root,
|
||||
sizeof(owner->canonical_root))) {
|
||||
return false;
|
||||
}
|
||||
/* Stored root_path values use forward slashes on every platform. */
|
||||
cbm_normalize_path_sep(owner->canonical_root);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* One indexed project whose stored root is this fixture's root. */
|
||||
static bool app_owner_seed(const app_owner_fixture_t *owner, const char *project) {
|
||||
char path[APP_TEST_PATH_CAP];
|
||||
int written = snprintf(path, sizeof(path), "%s/%s.db", owner->cache, project);
|
||||
if (written <= 0 || (size_t)written >= sizeof(path)) {
|
||||
return false;
|
||||
}
|
||||
cbm_store_t *store = cbm_store_open_path(path);
|
||||
bool seeded =
|
||||
store && cbm_store_upsert_project(store, project, owner->canonical_root) == CBM_STORE_OK;
|
||||
cbm_store_close(store);
|
||||
return seeded;
|
||||
}
|
||||
|
||||
/* An unnamed async start, then unnamed status polls naming the same
|
||||
* repo_path: one while the held worker runs, one after it drained. */
|
||||
static void app_owner_run(app_owner_fixture_t *owner, app_owner_run_t *run) {
|
||||
memset(run, 0, sizeof(*run));
|
||||
app_async_fixture_t *fixture = &owner->fixture;
|
||||
run->started = app_async_call_now(fixture, owner->session, ",\"async\":true");
|
||||
run->worker_running = run->started && !app_async_contains(run->started, "\"isError\":true") &&
|
||||
app_wait_for_atomic_int(&fixture->fake.starts, 1);
|
||||
run->running = app_async_call_now(fixture, owner->session, ",\"status\":true");
|
||||
atomic_store(&fixture->fake.allow_completion, true);
|
||||
run->drained = run->worker_running && app_wait_for_active_jobs(fixture->application, 0);
|
||||
run->finished =
|
||||
run->drained ? app_async_call_now(fixture, owner->session, ",\"status\":true") : NULL;
|
||||
}
|
||||
|
||||
static void app_owner_run_free(app_owner_run_t *run) {
|
||||
free(run->started);
|
||||
free(run->running);
|
||||
free(run->finished);
|
||||
memset(run, 0, sizeof(*run));
|
||||
}
|
||||
|
||||
static bool app_owner_fixture_finish(app_owner_fixture_t *owner) {
|
||||
if (owner->session) {
|
||||
owner->fixture.callbacks.session_close(owner->fixture.callbacks.context, owner->session);
|
||||
owner->session = NULL;
|
||||
}
|
||||
bool stopped = app_async_fixture_finish(&owner->fixture);
|
||||
if (owner->cache_set) {
|
||||
if (owner->had_cache) {
|
||||
(void)cbm_setenv("CBM_CACHE_DIR", owner->saved_cache, 1);
|
||||
} else {
|
||||
(void)cbm_unsetenv("CBM_CACHE_DIR");
|
||||
}
|
||||
}
|
||||
free(owner->saved_cache);
|
||||
owner->saved_cache = NULL;
|
||||
if (owner->cache[0]) {
|
||||
(void)th_rmtree(owner->cache);
|
||||
}
|
||||
return stopped;
|
||||
}
|
||||
|
||||
static bool app_owner_names_project(const char *response, const char *project) {
|
||||
char needle[APP_TEST_PATH_CAP];
|
||||
int written = snprintf(needle, sizeof(needle), "\"project\":\"%s\"", project);
|
||||
return written > 0 && (size_t)written < sizeof(needle) && app_async_contains(response, needle);
|
||||
}
|
||||
|
||||
TEST(daemon_application_unnamed_status_finds_async_job_of_root_owner_issue2134) {
|
||||
app_owner_fixture_t owner;
|
||||
bool setup =
|
||||
app_owner_fixture_init(&owner, "owner-poll") && app_owner_seed(&owner, "owned-2134s");
|
||||
owner.session = setup ? app_async_session(&owner.fixture, 7801) : NULL;
|
||||
bool session_opened = owner.session != NULL;
|
||||
app_owner_run_t run;
|
||||
memset(&run, 0, sizeof(run));
|
||||
if (session_opened) {
|
||||
app_owner_run(&owner, &run);
|
||||
}
|
||||
int cancels = atomic_load(&owner.fixture.fake.cancels);
|
||||
bool stopped = app_owner_fixture_finish(&owner);
|
||||
if (!app_async_contains(run.running, "\"state\":\"running\"")) {
|
||||
fprintf(stderr, " [2134x2144] unnamed status missed the owner's job: %.400s\n",
|
||||
run.running ? run.running : "(null)");
|
||||
}
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_TRUE(session_opened);
|
||||
/* #2134: the unnamed start adopted the owner; the daemon keyed its job so. */
|
||||
ASSERT_TRUE(app_owner_names_project(run.started, "owned-2134s"));
|
||||
ASSERT_TRUE(run.worker_running);
|
||||
/* The unnamed poll with the same repo_path reports that live job ... */
|
||||
ASSERT_FALSE(app_async_contains(run.running, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_owner_names_project(run.running, "owned-2134s"));
|
||||
ASSERT_TRUE(app_async_contains(run.running, "\"state\":\"running\""));
|
||||
/* ... and, once drained, the outcome recorded under the same key. */
|
||||
ASSERT_TRUE(run.drained);
|
||||
ASSERT_TRUE(app_owner_names_project(run.finished, "owned-2134s"));
|
||||
ASSERT_TRUE(app_async_contains(run.finished, "\"state\":\"succeeded\""));
|
||||
ASSERT_EQ(cancels, 0);
|
||||
ASSERT_TRUE(stopped);
|
||||
app_owner_run_free(&run);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Control: the path-derived key is untouched where #2134 keeps it - a root no
|
||||
* other project owns, and a root whose path-derived project exists even though
|
||||
* a named twin shares it. Start and poll name the same project either way. */
|
||||
TEST(daemon_application_unnamed_status_keeps_path_derived_key_issue2134) {
|
||||
app_owner_fixture_t fresh;
|
||||
bool fresh_setup = app_owner_fixture_init(&fresh, "owner-fresh");
|
||||
fresh.session = fresh_setup ? app_async_session(&fresh.fixture, 7811) : NULL;
|
||||
char *fresh_project = fresh.fixture.project ? strdup(fresh.fixture.project) : NULL;
|
||||
app_owner_run_t fresh_run;
|
||||
memset(&fresh_run, 0, sizeof(fresh_run));
|
||||
if (fresh.session) {
|
||||
app_owner_run(&fresh, &fresh_run);
|
||||
}
|
||||
bool fresh_stopped = app_owner_fixture_finish(&fresh);
|
||||
|
||||
app_owner_fixture_t twin;
|
||||
bool twin_setup = app_owner_fixture_init(&twin, "owner-twin") && twin.fixture.project &&
|
||||
app_owner_seed(&twin, twin.fixture.project) &&
|
||||
app_owner_seed(&twin, "twin-2134s");
|
||||
twin.session = twin_setup ? app_async_session(&twin.fixture, 7812) : NULL;
|
||||
char *twin_project = twin.fixture.project ? strdup(twin.fixture.project) : NULL;
|
||||
app_owner_run_t twin_run;
|
||||
memset(&twin_run, 0, sizeof(twin_run));
|
||||
if (twin.session) {
|
||||
app_owner_run(&twin, &twin_run);
|
||||
}
|
||||
bool twin_stopped = app_owner_fixture_finish(&twin);
|
||||
|
||||
ASSERT_TRUE(fresh_setup);
|
||||
ASSERT_NOT_NULL(fresh_project);
|
||||
ASSERT_TRUE(app_owner_names_project(fresh_run.started, fresh_project));
|
||||
ASSERT_TRUE(fresh_run.worker_running);
|
||||
ASSERT_TRUE(app_owner_names_project(fresh_run.running, fresh_project));
|
||||
ASSERT_TRUE(app_async_contains(fresh_run.running, "\"state\":\"running\""));
|
||||
ASSERT_TRUE(app_async_contains(fresh_run.finished, "\"state\":\"succeeded\""));
|
||||
ASSERT_TRUE(fresh_stopped);
|
||||
|
||||
ASSERT_TRUE(twin_setup);
|
||||
ASSERT_NOT_NULL(twin_project);
|
||||
ASSERT_TRUE(app_owner_names_project(twin_run.started, twin_project));
|
||||
ASSERT_FALSE(app_owner_names_project(twin_run.started, "twin-2134s"));
|
||||
ASSERT_TRUE(twin_run.worker_running);
|
||||
ASSERT_TRUE(app_owner_names_project(twin_run.running, twin_project));
|
||||
ASSERT_TRUE(app_async_contains(twin_run.running, "\"state\":\"running\""));
|
||||
ASSERT_TRUE(app_async_contains(twin_run.finished, "\"state\":\"succeeded\""));
|
||||
ASSERT_TRUE(twin_stopped);
|
||||
free(fresh_project);
|
||||
free(twin_project);
|
||||
app_owner_run_free(&fresh_run);
|
||||
app_owner_run_free(&twin_run);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Control: several owners and no path-derived project is ambiguous. The start
|
||||
* still refuses and names them without spawning a worker, and the poll gives
|
||||
* the same loud error instead of guessing (or pointing at a path-derived
|
||||
* project nobody indexes). */
|
||||
TEST(daemon_application_unnamed_async_and_status_refuse_ambiguous_root_issue2134) {
|
||||
app_owner_fixture_t owner;
|
||||
bool setup = app_owner_fixture_init(&owner, "owner-ambiguous") &&
|
||||
app_owner_seed(&owner, "first-2134s") && app_owner_seed(&owner, "second-2134s");
|
||||
owner.session = setup ? app_async_session(&owner.fixture, 7821) : NULL;
|
||||
bool session_opened = owner.session != NULL;
|
||||
app_owner_run_t run;
|
||||
memset(&run, 0, sizeof(run));
|
||||
if (session_opened) {
|
||||
app_owner_run(&owner, &run);
|
||||
}
|
||||
int starts = atomic_load(&owner.fixture.fake.starts);
|
||||
bool stopped = app_owner_fixture_finish(&owner);
|
||||
|
||||
ASSERT_TRUE(setup);
|
||||
ASSERT_TRUE(session_opened);
|
||||
ASSERT_TRUE(app_async_contains(run.started, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(run.started, "several indexed projects share root_path"));
|
||||
ASSERT_TRUE(app_async_contains(run.started, "first-2134s"));
|
||||
ASSERT_TRUE(app_async_contains(run.started, "second-2134s"));
|
||||
ASSERT_FALSE(run.worker_running);
|
||||
ASSERT_EQ(starts, 0);
|
||||
ASSERT_TRUE(app_async_contains(run.running, "\"isError\":true"));
|
||||
ASSERT_TRUE(app_async_contains(run.running, "several indexed projects share root_path"));
|
||||
ASSERT_TRUE(app_async_contains(run.running, "first-2134s"));
|
||||
ASSERT_TRUE(app_async_contains(run.running, "second-2134s"));
|
||||
ASSERT_TRUE(stopped);
|
||||
app_owner_run_free(&run);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(daemon_application) {
|
||||
RUN_TEST(daemon_application_oversized_reply_is_a_jsonrpc_error_not_a_death);
|
||||
RUN_TEST(daemon_application_new_session_does_not_retain_initial_store);
|
||||
@@ -5701,6 +6430,16 @@ SUITE(daemon_application) {
|
||||
RUN_TEST(daemon_application_sensitive_root_blocks_watch_but_preserves_controls);
|
||||
RUN_TEST(daemon_application_ui_index_accepts_non_ascii_directory);
|
||||
RUN_TEST(daemon_application_index_args_compare_repo_path_separator_equivalently);
|
||||
RUN_TEST(daemon_application_async_index_returns_before_completion_and_status_polls);
|
||||
RUN_TEST(daemon_application_async_index_survives_requesting_session_close);
|
||||
RUN_TEST(daemon_application_sync_index_still_cancels_on_last_subscriber_close);
|
||||
RUN_TEST(daemon_application_async_and_status_validation_errors);
|
||||
RUN_TEST(daemon_application_cancelled_sync_index_reply_offers_async);
|
||||
RUN_TEST(daemon_application_cut_short_sync_index_advice_reaches_next_call);
|
||||
RUN_TEST(daemon_application_async_refused_for_lone_one_shot_client_of_temporary_daemon);
|
||||
RUN_TEST(daemon_application_unnamed_status_finds_async_job_of_root_owner_issue2134);
|
||||
RUN_TEST(daemon_application_unnamed_status_keeps_path_derived_key_issue2134);
|
||||
RUN_TEST(daemon_application_unnamed_async_and_status_refuse_ambiguous_root_issue2134);
|
||||
RUN_TEST(daemon_application_programmatic_index_injects_resource_policy);
|
||||
RUN_TEST(daemon_application_auto_index_honors_tracked_file_limit);
|
||||
RUN_TEST(daemon_application_auto_index_file_count_handles_literal_metacharacter_path);
|
||||
|
||||
@@ -400,6 +400,11 @@ TEST(daemon_bootstrap_runtime_dir_env_relocates_rendezvous) {
|
||||
char relocated_runtime[BOOTSTRAP_TEST_PATH_CAP] = {0};
|
||||
char explicit_runtime[BOOTSTRAP_TEST_PATH_CAP] = {0};
|
||||
char unusable[BOOTSTRAP_TEST_PATH_CAP] = {0};
|
||||
/* The runner isolates the rendezvous for the whole run through this same
|
||||
* variable, so the test must hand back exactly what it found. */
|
||||
char previous_value[BOOTSTRAP_TEST_PATH_CAP] = {0};
|
||||
const char *previous =
|
||||
cbm_safe_getenv("CBM_RUNTIME_DIR", previous_value, sizeof(previous_value), NULL);
|
||||
int written = snprintf(override_parent, sizeof(override_parent),
|
||||
"%s/cbm-bootstrap-runtime-env-XXXXXX", cbm_tmpdir());
|
||||
if (written <= 0 || written >= (int)sizeof(override_parent) || !cbm_mkdtemp(override_parent)) {
|
||||
@@ -436,8 +441,10 @@ TEST(daemon_bootstrap_runtime_dir_env_relocates_rendezvous) {
|
||||
unusable_set ? cbm_daemon_bootstrap_endpoint_new(NULL) : NULL;
|
||||
|
||||
/* Restore before asserting: a failed assertion returns immediately, and a
|
||||
* leaked CBM_RUNTIME_DIR would follow every later suite in this process. */
|
||||
(void)cbm_unsetenv("CBM_RUNTIME_DIR");
|
||||
* leaked override, or a dropped run value, would follow every later suite
|
||||
* in this process. */
|
||||
bool restored = previous ? cbm_setenv("CBM_RUNTIME_DIR", previous_value, 1) == 0
|
||||
: cbm_unsetenv("CBM_RUNTIME_DIR") == 0;
|
||||
cbm_daemon_ipc_endpoint_free(refused);
|
||||
cbm_daemon_ipc_endpoint_free(relocated);
|
||||
if (relocated_runtime[0] != '\0') {
|
||||
@@ -448,6 +455,7 @@ TEST(daemon_bootstrap_runtime_dir_env_relocates_rendezvous) {
|
||||
}
|
||||
(void)cbm_rmdir(override_parent);
|
||||
|
||||
ASSERT_TRUE(restored);
|
||||
ASSERT_TRUE(prepared);
|
||||
ASSERT_TRUE(explicit_started);
|
||||
ASSERT_TRUE(explicit_canonical);
|
||||
|
||||
@@ -1274,6 +1274,27 @@ TEST(daemon_frontend_correlates_cancellation_to_exact_request) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2144 (a): the -32800 reply to a cancelled index_repository call is the one
|
||||
* text a deadline-bound client can still read, so it names the async mode;
|
||||
* other requests and unparseable input keep the plain message. */
|
||||
TEST(daemon_frontend_cancelled_index_reply_offers_async_issue2144) {
|
||||
const char *index_reply = cbm_daemon_frontend_cancelled_error_message(
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\","
|
||||
"\"params\":{\"name\":\"index_repository\",\"arguments\":{\"repo_path\":\"/r\"}}}");
|
||||
ASSERT_NOT_NULL(strstr(index_reply, "Request cancelled"));
|
||||
ASSERT_NOT_NULL(strstr(index_reply, "async: true"));
|
||||
ASSERT_NOT_NULL(strstr(index_reply, "status: true"));
|
||||
ASSERT_NULL(strchr(index_reply, '"'));
|
||||
ASSERT_NULL(strchr(index_reply, '\\'));
|
||||
ASSERT_STR_EQ(cbm_daemon_frontend_cancelled_error_message(
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"tools/call\","
|
||||
"\"params\":{\"name\":\"search_graph\",\"arguments\":{}}}"),
|
||||
"Request cancelled");
|
||||
ASSERT_STR_EQ(cbm_daemon_frontend_cancelled_error_message("not json"), "Request cancelled");
|
||||
ASSERT_STR_EQ(cbm_daemon_frontend_cancelled_error_message(NULL), "Request cancelled");
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(daemon_frontend_ignores_cancellation_text_in_string_content) {
|
||||
ASSERT_FALSE(cbm_daemon_frontend_is_cancellation_notification(
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","
|
||||
@@ -1659,6 +1680,7 @@ TEST(daemon_local_participant_monitor_joins_before_manager_teardown) {
|
||||
SUITE(daemon_frontend) {
|
||||
RUN_TEST(daemon_frontend_recognizes_exact_cancellation_notification);
|
||||
RUN_TEST(daemon_frontend_correlates_cancellation_to_exact_request);
|
||||
RUN_TEST(daemon_frontend_cancelled_index_reply_offers_async_issue2144);
|
||||
RUN_TEST(daemon_frontend_ignores_cancellation_text_in_string_content);
|
||||
RUN_TEST(daemon_frontend_rejects_non_notification_cancellation_shapes);
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
|
||||
+102
-20
@@ -401,6 +401,7 @@ static int ipc_test_win_lock_child(const char *kind, const char *key, const char
|
||||
typedef struct {
|
||||
const cbm_daemon_ipc_endpoint_t *endpoint;
|
||||
int result;
|
||||
atomic_bool finished; /* set once the startup call has fully returned */
|
||||
} ipc_test_win_startup_call_t;
|
||||
|
||||
typedef struct {
|
||||
@@ -421,16 +422,22 @@ static void ipc_test_startup_gate(void *context) {
|
||||
}
|
||||
}
|
||||
|
||||
static bool ipc_test_startup_gate_wait_acquired(ipc_test_startup_gate_t *gate) {
|
||||
/* `acquired` never clears, so this wait cannot miss the event; the bound
|
||||
* only catches a thread that never started at all. */
|
||||
for (size_t attempt = 0; attempt < 50000U; attempt++) {
|
||||
if (atomic_load(&gate->acquired)) {
|
||||
return true;
|
||||
}
|
||||
/* Waits until the startup thread has either parked in the gate or returned
|
||||
* without reaching it. Both flags only ever go false -> true, and one of them
|
||||
* is always eventually set: before the gate the startup path only try-acquires
|
||||
* (no blocking wait on anything this test holds), and a thread parked in the
|
||||
* gate cannot return until the test releases it. So no attempt or time bound
|
||||
* is needed, and none may decide the verdict: the previous 50000 x
|
||||
* cbm_usleep(200) budget meant ~10 s on POSIX but, since cbm_usleep(200) is
|
||||
* Sleep(0) on Windows, only 50000 bare yields there -- a loaded CI runner
|
||||
* exhausted them before the thread reached the gate. A thread that never
|
||||
* started is caught by the caller's thread_started check. */
|
||||
static bool ipc_test_startup_gate_wait_acquired(ipc_test_startup_gate_t *gate,
|
||||
ipc_test_win_startup_call_t *call) {
|
||||
while (!atomic_load(&gate->acquired) && !atomic_load(&call->finished)) {
|
||||
cbm_usleep(200);
|
||||
}
|
||||
return false;
|
||||
return atomic_load(&gate->acquired);
|
||||
}
|
||||
|
||||
static void *ipc_test_win_startup_call(void *opaque) {
|
||||
@@ -441,6 +448,7 @@ static void *ipc_test_win_startup_call(void *opaque) {
|
||||
call->result = 0;
|
||||
}
|
||||
cbm_daemon_ipc_startup_lock_release(&startup);
|
||||
atomic_store(&call->finished, true);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -1395,6 +1403,7 @@ TEST(daemon_ipc_windows_startup_retries_transient_rendezvous_reader) {
|
||||
bool startup_observed = false;
|
||||
int join_status = -1;
|
||||
ipc_test_win_startup_call_t call = {.result = -1};
|
||||
atomic_init(&call.finished, false);
|
||||
ipc_test_startup_gate_t gate;
|
||||
atomic_init(&gate.acquired, false);
|
||||
atomic_init(&gate.may_proceed, false);
|
||||
@@ -1420,7 +1429,7 @@ TEST(daemon_ipc_windows_startup_retries_transient_rendezvous_reader) {
|
||||
thread_started = cbm_thread_create(&thread, 0, ipc_test_win_startup_call, &call) == 0;
|
||||
}
|
||||
if (thread_started) {
|
||||
startup_observed = ipc_test_startup_gate_wait_acquired(&gate);
|
||||
startup_observed = ipc_test_startup_gate_wait_acquired(&gate, &call);
|
||||
}
|
||||
ipc_test_win_lock_release(&record_reader);
|
||||
atomic_store(&gate.may_proceed, true);
|
||||
@@ -1441,7 +1450,14 @@ TEST(daemon_ipc_windows_startup_retries_transient_rendezvous_reader) {
|
||||
ASSERT_EQ(directory_status, CBM_PRIVATE_FILE_LOCK_OK);
|
||||
ASSERT_EQ(record_status, CBM_PRIVATE_FILE_LOCK_OK);
|
||||
ASSERT_TRUE(thread_started);
|
||||
ASSERT_TRUE(startup_observed);
|
||||
if (!startup_observed) {
|
||||
/* The startup thread returned without reaching the gate; its
|
||||
* try-acquire status is the true reason. */
|
||||
char reason[96];
|
||||
(void)snprintf(reason, sizeof(reason), "startup call returned %d without reaching the gate",
|
||||
call.result);
|
||||
FAIL(reason);
|
||||
}
|
||||
ASSERT_EQ(join_status, 0);
|
||||
ASSERT_EQ(call.result, 1);
|
||||
ASSERT_TRUE(address[0] != '\0');
|
||||
@@ -1464,6 +1480,7 @@ TEST(daemon_ipc_windows_rendezvous_bridges_concurrent_lifetime_owner) {
|
||||
bool startup_observed = false;
|
||||
int join_status = -1;
|
||||
ipc_test_win_startup_call_t call = {.result = -1};
|
||||
atomic_init(&call.finished, false);
|
||||
|
||||
bool parent_ok = ipc_test_parent_new(parent, "win-lifetime-bridge");
|
||||
if (parent_ok) {
|
||||
@@ -1501,7 +1518,7 @@ TEST(daemon_ipc_windows_rendezvous_bridges_concurrent_lifetime_owner) {
|
||||
thread_started = cbm_thread_create(&thread, 0, ipc_test_win_startup_call, &call) == 0;
|
||||
}
|
||||
if (thread_started) {
|
||||
startup_observed = ipc_test_startup_gate_wait_acquired(&gate);
|
||||
startup_observed = ipc_test_startup_gate_wait_acquired(&gate, &call);
|
||||
}
|
||||
/* Claim the lifetime lock while startup is parked in the gate, so the
|
||||
* concurrent-owner bridge under test is exercised deterministically. */
|
||||
@@ -1534,7 +1551,14 @@ TEST(daemon_ipc_windows_rendezvous_bridges_concurrent_lifetime_owner) {
|
||||
ASSERT_EQ(directory_status, CBM_PRIVATE_FILE_LOCK_OK);
|
||||
ASSERT_EQ(record_status, CBM_PRIVATE_FILE_LOCK_OK);
|
||||
ASSERT_TRUE(thread_started);
|
||||
ASSERT_TRUE(startup_observed);
|
||||
if (!startup_observed) {
|
||||
/* The startup thread returned without reaching the gate; its
|
||||
* try-acquire status is the true reason. */
|
||||
char reason[96];
|
||||
(void)snprintf(reason, sizeof(reason), "startup call returned %d without reaching the gate",
|
||||
call.result);
|
||||
FAIL(reason);
|
||||
}
|
||||
ASSERT_EQ(lifetime_status, CBM_PRIVATE_FILE_LOCK_OK);
|
||||
ASSERT_EQ(join_status, 0);
|
||||
ASSERT_EQ(call.result, 0);
|
||||
@@ -2442,6 +2466,7 @@ typedef struct {
|
||||
cbm_daemon_ipc_listener_t *listener;
|
||||
cbm_daemon_ipc_connection_t *connection;
|
||||
atomic_bool waiting;
|
||||
atomic_bool finished; /* set once the server thread has returned */
|
||||
int receive_result;
|
||||
} ipc_forever_wait_server_t;
|
||||
|
||||
@@ -2464,6 +2489,7 @@ static void *ipc_forever_wait_server(void *opaque) {
|
||||
server->connection, CBM_DAEMON_IPC_WAIT_FOREVER, &frame, &payload);
|
||||
}
|
||||
free(payload);
|
||||
atomic_store_explicit(&server->finished, true, memory_order_release);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -2480,6 +2506,7 @@ TEST(daemon_ipc_wait_forever_is_interruptible) {
|
||||
int join_result = -1;
|
||||
ipc_forever_wait_server_t server = {0};
|
||||
atomic_init(&server.waiting, false);
|
||||
atomic_init(&server.finished, false);
|
||||
|
||||
if (ipc_test_parent_new(parent, "wait-forever")) {
|
||||
endpoint = cbm_daemon_ipc_endpoint_new(key, parent);
|
||||
@@ -2495,9 +2522,11 @@ TEST(daemon_ipc_wait_forever_is_interruptible) {
|
||||
if (thread_started) {
|
||||
client = cbm_daemon_ipc_connect(endpoint, 2000);
|
||||
}
|
||||
uint64_t deadline = cbm_now_ms() + 2000;
|
||||
while (client && cbm_now_ms() < deadline &&
|
||||
!atomic_load_explicit(&server.waiting, memory_order_acquire)) {
|
||||
/* Wait for the event itself, never a deadline: the server either enters
|
||||
* its forever-wait or returns (its accept is bounded by the call's own
|
||||
* timeout), and both flags only ever go false -> true. */
|
||||
while (client && !atomic_load_explicit(&server.waiting, memory_order_acquire) &&
|
||||
!atomic_load_explicit(&server.finished, memory_order_acquire)) {
|
||||
cbm_usleep(1000);
|
||||
}
|
||||
reached_wait = atomic_load_explicit(&server.waiting, memory_order_acquire);
|
||||
@@ -2561,14 +2590,13 @@ TEST(daemon_ipc_connect_waits_for_delayed_listener) {
|
||||
thread_started = cbm_thread_create(&thread, 0, ipc_delayed_listener_start, &delayed) == 0;
|
||||
}
|
||||
if (thread_started) {
|
||||
/* `delay_started` is the thread's first store, so it cannot return
|
||||
* without setting it: wait for that event with no attempt bound. */
|
||||
struct timespec poll_delay = {.tv_sec = 0, .tv_nsec = 1000000};
|
||||
for (size_t i = 0; i < 2000; i++) {
|
||||
if (atomic_load_explicit(&delayed.delay_started, memory_order_acquire)) {
|
||||
delay_observed = true;
|
||||
break;
|
||||
}
|
||||
while (!atomic_load_explicit(&delayed.delay_started, memory_order_acquire)) {
|
||||
(void)cbm_nanosleep(&poll_delay, NULL);
|
||||
}
|
||||
delay_observed = true;
|
||||
}
|
||||
if (delay_observed) {
|
||||
client = cbm_daemon_ipc_connect(endpoint, 1500);
|
||||
@@ -5193,6 +5221,59 @@ TEST(daemon_ipc_posix_world_writable_ancestor_still_refused_issue1537) {
|
||||
}
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* #1687: on a WSL DrvFs mount (/mnt/e, default 0777) the ancestor refusal is
|
||||
* correct but used to leave the user guessing. The gate must still refuse, and
|
||||
* the detail must now name the containing directory AND the WSL remedy. */
|
||||
TEST(daemon_ipc_posix_wsl_drvfs_refusal_names_remedy_issue1687) {
|
||||
char parent[TEST_PATH_CAP];
|
||||
char ancestor[TEST_PATH_CAP];
|
||||
char cache[TEST_PATH_CAP];
|
||||
char detail[512] = {0};
|
||||
char plain_detail[512] = {0};
|
||||
bool paths_ok = false;
|
||||
bool ancestor_ready = false;
|
||||
bool refused = false;
|
||||
bool plain_refused = false;
|
||||
|
||||
if (ipc_test_parent_new(parent, "posix-wsl-drvfs")) {
|
||||
int a = snprintf(ancestor, sizeof(ancestor), "%s/e", parent);
|
||||
int c = snprintf(cache, sizeof(cache), "%s/codebase_memory_cache", ancestor);
|
||||
paths_ok = a > 0 && a < (int)sizeof(ancestor) && c > 0 && c < (int)sizeof(cache);
|
||||
}
|
||||
if (paths_ok) {
|
||||
ancestor_ready = mkdir(ancestor, 0777) == 0 && chmod(ancestor, 0777) == 0;
|
||||
}
|
||||
if (ancestor_ready) {
|
||||
cbm_daemon_ipc_posix_force_wsl_drvfs_for_test(true);
|
||||
refused = !cbm_daemon_ipc_private_directory_secure(cache);
|
||||
cbm_daemon_ipc_posix_force_wsl_drvfs_for_test(false);
|
||||
(void)snprintf(detail, sizeof(detail), "%s", cbm_daemon_ipc_validation_detail());
|
||||
plain_refused = !cbm_daemon_ipc_private_directory_secure(cache);
|
||||
(void)snprintf(plain_detail, sizeof(plain_detail), "%s",
|
||||
cbm_daemon_ipc_validation_detail());
|
||||
}
|
||||
|
||||
(void)rmdir(cache);
|
||||
(void)rmdir(ancestor);
|
||||
ipc_test_remove_flat_dir(parent);
|
||||
|
||||
ASSERT_TRUE(paths_ok);
|
||||
ASSERT_TRUE(ancestor_ready);
|
||||
ASSERT_TRUE(refused); /* policy unchanged: still refused */
|
||||
ASSERT_NOT_NULL(strstr(detail, "CONTAINING 'codebase_memory_cache'"));
|
||||
ASSERT_NOT_NULL(strstr(detail, "/etc/wsl.conf"));
|
||||
ASSERT_NOT_NULL(strstr(detail, "metadata,umask=22,fmask=11"));
|
||||
ASSERT_NOT_NULL(strstr(detail, "wsl --shutdown"));
|
||||
ASSERT_NOT_NULL(strstr(detail, "~/.cache"));
|
||||
/* The remedy must fit whole, not be clipped by the detail buffer. */
|
||||
ASSERT_NOT_NULL(strstr(detail, "(e.g. ~/.cache)"));
|
||||
/* Off DrvFs the generic message stays and carries no WSL advice. */
|
||||
ASSERT_TRUE(plain_refused);
|
||||
ASSERT_NOT_NULL(strstr(plain_detail, "CONTAINING 'codebase_memory_cache'"));
|
||||
ASSERT_NULL(strstr(plain_detail, "wsl.conf"));
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1830: /proc/self/uid_map single-uid detection. A single-uid map is exactly
|
||||
* one line "<inside> <outside> 1" whose inside id is our euid; anything else —
|
||||
* the init map, a count other than 1, a foreign inside id, extra lines, or junk
|
||||
@@ -5517,6 +5598,7 @@ SUITE(daemon_ipc) {
|
||||
RUN_TEST(daemon_ipc_posix_group_writable_ancestor_is_admitted_issue1537);
|
||||
RUN_TEST(daemon_ipc_posix_world_writable_ancestor_still_refused_issue1537);
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
RUN_TEST(daemon_ipc_posix_wsl_drvfs_refusal_names_remedy_issue1687);
|
||||
RUN_TEST(daemon_ipc_posix_uid_map_single_uid_parse_issue1830);
|
||||
RUN_TEST(daemon_ipc_posix_overflow_ancestor_tolerated_only_in_single_uid_ns_issue1830);
|
||||
RUN_TEST(daemon_ipc_posix_overflow_uid_is_never_cached_issue1830);
|
||||
|
||||
@@ -1918,6 +1918,59 @@ TEST(daemon_runtime_unverifiable_image_is_admitted_issue1539) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1955: a client whose binary is a DIFFERENT file with identical bytes (a
|
||||
* second install path, a package-manager copy) misses the active-image
|
||||
* comparison, so the daemon proves it by hashing the peer's whole image. With
|
||||
* a ~300 MB release binary that hash costs more than the client's 1000 ms
|
||||
* HELLO budget: the client gave up, re-probed, and every re-probe started the
|
||||
* same hash again on a fresh worker, so such a client waited out the full
|
||||
* 30 s startup deadline against a healthy daemon (worse under indexing load).
|
||||
* A verified image must be remembered: repeated admissions of the same copy
|
||||
* hash it once. Asserted on the hash count, never on time. */
|
||||
TEST(daemon_runtime_verified_peer_copy_is_hashed_once_issue1955) {
|
||||
/* The first admission really hashes the test binary (hundreds of MB,
|
||||
* slower still under sanitizers), so its HELLO gets a hang-guard ceiling,
|
||||
* not a budget: the verdict is the hash count below. */
|
||||
enum { ADMISSIONS = 3, HASHED_HELLO_CEILING_MS = 120000 };
|
||||
cbm_daemon_build_identity_t identity =
|
||||
runtime_test_identity("2.4.0", runtime_test_self_build());
|
||||
runtime_test_fixture_t fixture;
|
||||
bool started = runtime_test_fixture_start(&fixture, "image-copy-cache", &identity);
|
||||
int admitted = 0;
|
||||
/* An owner session keeps the ephemeral generation alive across the
|
||||
* sequential admissions below (the last committed client leaving retires
|
||||
* it). It connects before the seam, through the active-image fast path. */
|
||||
cbm_daemon_runtime_connect_result_t owner_result = {0};
|
||||
cbm_daemon_runtime_client_t *owner =
|
||||
started ? cbm_daemon_runtime_client_connect(fixture.endpoint, &identity,
|
||||
RUNTIME_TEST_TIMEOUT_MS, &owner_result)
|
||||
: NULL;
|
||||
uint64_t hashes_before = cbm_daemon_runtime_peer_image_hashes_for_testing();
|
||||
|
||||
cbm_daemon_runtime_force_peer_image_distinct_copy_for_testing(true);
|
||||
for (int i = 0; owner && i < ADMISSIONS; i++) {
|
||||
cbm_daemon_runtime_connect_result_t result = {0};
|
||||
cbm_daemon_runtime_client_t *client = cbm_daemon_runtime_client_connect(
|
||||
fixture.endpoint, &identity, HASHED_HELLO_CEILING_MS, &result);
|
||||
if (client && result.status == CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED &&
|
||||
cbm_daemon_runtime_client_close(client, RUNTIME_TEST_TIMEOUT_MS)) {
|
||||
admitted++;
|
||||
} else if (client) {
|
||||
(void)cbm_daemon_runtime_client_close(client, RUNTIME_TEST_TIMEOUT_MS);
|
||||
}
|
||||
}
|
||||
cbm_daemon_runtime_force_peer_image_distinct_copy_for_testing(false);
|
||||
uint64_t hashes = cbm_daemon_runtime_peer_image_hashes_for_testing() - hashes_before;
|
||||
bool owner_closed = owner && cbm_daemon_runtime_client_close(owner, RUNTIME_TEST_TIMEOUT_MS);
|
||||
runtime_test_fixture_finish(&fixture);
|
||||
|
||||
ASSERT_TRUE(started);
|
||||
ASSERT_TRUE(owner_closed);
|
||||
ASSERT_EQ(admitted, ADMISSIONS);
|
||||
ASSERT_EQ(hashes, 1);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(daemon_runtime_unexpected_frame_payload_is_freed_once) {
|
||||
static const uint8_t unexpected_payload[] = {0xde, 0xad, 0xbe, 0xef};
|
||||
cbm_daemon_build_identity_t identity =
|
||||
@@ -5119,6 +5172,7 @@ SUITE(daemon_runtime) {
|
||||
RUN_TEST(daemon_runtime_exact_hello_issues_connection_bound_identity);
|
||||
RUN_TEST(daemon_runtime_image_rejection_reaches_client_issue1383);
|
||||
RUN_TEST(daemon_runtime_unverifiable_image_is_admitted_issue1539);
|
||||
RUN_TEST(daemon_runtime_verified_peer_copy_is_hashed_once_issue1955);
|
||||
RUN_TEST(daemon_runtime_unexpected_frame_payload_is_freed_once);
|
||||
RUN_TEST(daemon_runtime_activation_rejects_forged_and_malformed_without_stop);
|
||||
RUN_TEST(daemon_runtime_activation_ack_snapshots_then_interrupts_all_clients);
|
||||
|
||||
@@ -1258,6 +1258,82 @@ TEST(discover_cbmignore_negates_always_skip_dir) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── Laravel compiled Blade view cache (issue #1735) ─────────────── */
|
||||
|
||||
/* storage/framework/views/ holds Laravel's compiled Blade templates: generated
|
||||
* PHP with no source value that the php_only grammar flags as parse damage.
|
||||
* It is skipped by default even when Laravel's stock .gitignore in that folder
|
||||
* is missing. The match is on the path suffix, component-aligned, so ordinary
|
||||
* views/ dirs (resources/views, app/views, app/framework/views) and look-alike
|
||||
* prefixes (mystorage/...) stay indexed. */
|
||||
TEST(discover_skips_laravel_compiled_views_issue1735) {
|
||||
char *base = th_mktempdir("cbm_disc_laravel_views");
|
||||
ASSERT(base != NULL);
|
||||
|
||||
/* No .gitignore anywhere: the skip must come from the built-in rule. */
|
||||
th_write_file(TH_PATH(base, "storage/framework/views/abc123.php"),
|
||||
"<?php $__env->startSection('title'); ?>\n"
|
||||
"<?php echo e($title); ?>\n"
|
||||
"<?php $__env->stopSection(); ?>\n");
|
||||
th_write_file(TH_PATH(base, "backend/storage/framework/views/def456.php"),
|
||||
"<?php echo e($x); ?>\n");
|
||||
th_write_file(TH_PATH(base, "resources/views/welcome.blade.php"), "<h1>{{ $title }}</h1>\n");
|
||||
th_write_file(TH_PATH(base, "app/views/x.php"), "<?php function x() { return 1; }\n");
|
||||
th_write_file(TH_PATH(base, "app/framework/views/y.php"), "<?php function y() {}\n");
|
||||
th_write_file(TH_PATH(base, "mystorage/framework/views/z.php"), "<?php function z() {}\n");
|
||||
th_write_file(TH_PATH(base, "storage/framework/views_old/w.php"), "<?php function w() {}\n");
|
||||
|
||||
cbm_discover_opts_t opts = {0};
|
||||
cbm_file_info_t *files = NULL;
|
||||
int count = 0;
|
||||
char **excluded = NULL;
|
||||
int excluded_count = 0;
|
||||
|
||||
int rc = cbm_discover_ex(base, &opts, &files, &count, &excluded, &excluded_count);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_FALSE(discover_has_rel_path(files, count, "storage/framework/views/abc123.php"));
|
||||
ASSERT_FALSE(discover_has_rel_path(files, count, "backend/storage/framework/views/def456.php"));
|
||||
ASSERT_TRUE(discover_has_rel_path(files, count, "resources/views/welcome.blade.php"));
|
||||
ASSERT_TRUE(discover_has_rel_path(files, count, "app/views/x.php"));
|
||||
ASSERT_TRUE(discover_has_rel_path(files, count, "app/framework/views/y.php"));
|
||||
ASSERT_TRUE(discover_has_rel_path(files, count, "mystorage/framework/views/z.php"));
|
||||
ASSERT_TRUE(discover_has_rel_path(files, count, "storage/framework/views_old/w.php"));
|
||||
ASSERT_EQ(count, 5);
|
||||
/* Reported as an excluded subtree (#411), like every built-in skip dir. */
|
||||
ASSERT_TRUE(discover_excluded_contains(excluded, excluded_count, "storage/framework/views"));
|
||||
ASSERT_TRUE(
|
||||
discover_excluded_contains(excluded, excluded_count, "backend/storage/framework/views"));
|
||||
ASSERT_FALSE(discover_excluded_contains(excluded, excluded_count, "app/views"));
|
||||
ASSERT_FALSE(discover_excluded_contains(excluded, excluded_count, "resources/views"));
|
||||
|
||||
cbm_discover_free_excluded(excluded, excluded_count);
|
||||
cbm_discover_free(files, count);
|
||||
th_cleanup(base);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Like the other ordinary built-in skip dirs (#500), a .cbmignore negation
|
||||
* un-skips the compiled-view cache for a user who really wants it indexed. */
|
||||
TEST(discover_cbmignore_negates_laravel_compiled_views_issue1735) {
|
||||
char *base = th_mktempdir("cbm_disc_laravel_views_neg");
|
||||
ASSERT(base != NULL);
|
||||
|
||||
th_write_file(TH_PATH(base, ".cbmignore"), "!storage/framework/views/\n");
|
||||
th_write_file(TH_PATH(base, "storage/framework/views/abc123.php"), "<?php echo 1; ?>\n");
|
||||
|
||||
cbm_discover_opts_t opts = {0};
|
||||
cbm_file_info_t *files = NULL;
|
||||
int count = 0;
|
||||
|
||||
int rc = cbm_discover(base, &opts, &files, &count);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_TRUE(discover_has_rel_path(files, count, "storage/framework/views/abc123.php"));
|
||||
|
||||
cbm_discover_free(files, count);
|
||||
th_cleanup(base);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* An anchored negation ("!src/target/") un-skips only that nested dir; other
|
||||
* dirs with the same basename stay built-in-skipped. */
|
||||
TEST(discover_cbmignore_negates_only_nested_skip_dir) {
|
||||
@@ -2330,6 +2406,10 @@ SUITE(discover) {
|
||||
RUN_TEST(discover_cbmignore_negation_last_match_wins);
|
||||
RUN_TEST(discover_cbmignore_negation_cannot_unskip_safety_core);
|
||||
|
||||
/* Laravel compiled Blade view cache (issue #1735) */
|
||||
RUN_TEST(discover_skips_laravel_compiled_views_issue1735);
|
||||
RUN_TEST(discover_cbmignore_negates_laravel_compiled_views_issue1735);
|
||||
|
||||
/* .git/info/exclude support (issue #489) */
|
||||
RUN_TEST(discover_git_info_exclude);
|
||||
RUN_TEST(discover_git_info_exclude_stacks_with_gitignore);
|
||||
|
||||
@@ -645,6 +645,113 @@ TEST(ei_go_import_never_binds_symbol) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2127 helper: inbound edges of `edge_type` onto the (single) node named
|
||||
* `name` with label `label`; -1 when that node is missing. */
|
||||
static int ei_inbound_edges_on(cbm_store_t *store, const char *project, const char *name,
|
||||
const char *label, const char *edge_type) {
|
||||
cbm_node_t *nodes = NULL;
|
||||
int count = 0;
|
||||
if (cbm_store_find_nodes_by_name(store, project, name, &nodes, &count) != CBM_STORE_OK) {
|
||||
return -1;
|
||||
}
|
||||
int64_t id = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (nodes[i].label && strcmp(nodes[i].label, label) == 0) {
|
||||
id = nodes[i].id;
|
||||
}
|
||||
}
|
||||
cbm_store_free_nodes(nodes, count);
|
||||
if (id == 0) {
|
||||
return -1;
|
||||
}
|
||||
cbm_edge_t *edges = NULL;
|
||||
int n = 0;
|
||||
if (cbm_store_find_edges_by_target_type(store, id, edge_type, &edges, &n) != CBM_STORE_OK) {
|
||||
return -1;
|
||||
}
|
||||
cbm_store_free_edges(edges, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* #2127: `from unittest.mock import patch` names an EXTERNAL module. Strategy
|
||||
* 1 cannot resolve it, and Strategy 3's symbol-name fallback bound the import
|
||||
* to the only project definition named `patch` — an unrelated REST view's
|
||||
* HTTP handler — so every patch(...) call became an import_map CALLS edge at
|
||||
* confidence 0.95 (and, once the import edge is gone, a unique_name edge; the
|
||||
* member form `mock.patch(...)` a suffix_match edge). A Python import path
|
||||
* names its module chain, so a symbol hit whose QN does not contain the chain
|
||||
* of an EXTERNAL import is not the imported thing. The true project import
|
||||
* (`from app.util import helper`) must keep both its IMPORTS and its CALLS
|
||||
* edge. `pad` > MIN_FILES_FOR_PARALLEL(50) runs the
|
||||
* same fixture through the parallel pipeline, so both drivers are covered. */
|
||||
static int ei_py_external_import_case(int pad) {
|
||||
enum { EI_2127_BASE = 5, EI_2127_MAX = EI_2127_BASE + 64 };
|
||||
static char names[EI_2127_MAX][32];
|
||||
EILangFile f[EI_2127_MAX];
|
||||
int n = 0;
|
||||
f[n++] = (EILangFile){"app/views.py", "class PkgConfigView:\n"
|
||||
" def get(self, request):\n return 1\n\n"
|
||||
" def patch(self, request):\n return 2\n\n"
|
||||
" def copy(self):\n return 3\n"};
|
||||
f[n++] = (EILangFile){"app/util.py", "def helper():\n return 1\n"};
|
||||
/* Recall pin: a PROJECT module re-exporting a name defined elsewhere
|
||||
* (`app.base` re-exports `app.errors.BoomError`) is an internal import;
|
||||
* its weak resolution is never judged by the #2127 guard. */
|
||||
f[n++] = (EILangFile){"app/errors.py", "class BoomError(Exception):\n pass\n"};
|
||||
f[n++] = (EILangFile){"app/base.py", "from app.errors import BoomError\n"};
|
||||
f[n++] = (EILangFile){"tests/test_views.py", "import copy\n"
|
||||
"from unittest import mock\n"
|
||||
"from unittest.mock import patch\n"
|
||||
"from app.base import BoomError\n"
|
||||
"from app.util import helper\n\n\n"
|
||||
"def test_something():\n"
|
||||
" mock.patch(\"app.views.other\")\n"
|
||||
" copy.copy(helper)\n"
|
||||
" if helper() > 1:\n"
|
||||
" raise BoomError()\n"
|
||||
" with patch(\"app.views.thing\"):\n"
|
||||
" return helper()\n"};
|
||||
for (int i = 0; i < pad && n < EI_2127_MAX; i++) {
|
||||
snprintf(names[n], sizeof(names[n]), "pad/mod_%02d.py", i);
|
||||
f[n] = (EILangFile){names[n], "def filler():\n return 0\n"};
|
||||
n++;
|
||||
}
|
||||
EILangProj lp;
|
||||
cbm_store_t *store = ei_index_files(&lp, f, n);
|
||||
int bad_imports =
|
||||
store ? ei_inbound_edges_on(store, lp.project, "patch", "Method", "IMPORTS") : -1;
|
||||
int bad_calls = store ? ei_inbound_edges_on(store, lp.project, "patch", "Method", "CALLS") : -1;
|
||||
/* `import copy` (a plain module import of stdlib `copy`) is no project
|
||||
* method: neither the import nor `copy.copy(...)` may bind it. */
|
||||
bad_imports += store ? ei_inbound_edges_on(store, lp.project, "copy", "Method", "IMPORTS") : 0;
|
||||
bad_calls += store ? ei_inbound_edges_on(store, lp.project, "copy", "Method", "CALLS") : 0;
|
||||
int good_imports =
|
||||
store ? ei_inbound_edges_on(store, lp.project, "helper", "Function", "IMPORTS") : -1;
|
||||
int good_calls =
|
||||
store ? ei_inbound_edges_on(store, lp.project, "helper", "Function", "CALLS") : -1;
|
||||
int reexport_calls =
|
||||
store ? ei_inbound_edges_on(store, lp.project, "BoomError", "Class", "CALLS") : -1;
|
||||
int ok = bad_imports == 0 && bad_calls == 0 && good_imports >= 1 && good_calls >= 1 &&
|
||||
reexport_calls >= 1;
|
||||
if (!ok) {
|
||||
fprintf(stderr,
|
||||
" [#2127 pad=%d] PkgConfigView.patch+copy IMPORTS=%d CALLS=%d (want 0/0); "
|
||||
"helper IMPORTS=%d CALLS=%d (want >=1/>=1); BoomError CALLS=%d (want >=1)\n",
|
||||
pad, bad_imports, bad_calls, good_imports, good_calls, reexport_calls);
|
||||
}
|
||||
ei_cleanup(&lp, store);
|
||||
return ok;
|
||||
}
|
||||
|
||||
TEST(ei_py_external_import_never_binds_project_symbol) {
|
||||
/* Both legs run before asserting so a failure diagnoses both drivers. */
|
||||
int sequential_ok = ei_py_external_import_case(0);
|
||||
int parallel_ok = ei_py_external_import_case(60);
|
||||
ASSERT_TRUE(sequential_ok);
|
||||
ASSERT_TRUE(parallel_ok);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* C++: header include should resolve to the header file node, not the same-stem
|
||||
* source node. Also exercises angle-bracket include resolution. */
|
||||
TEST(ei_cpp_header_include_targets_header_file) {
|
||||
@@ -1171,6 +1278,7 @@ SUITE(edge_imports) {
|
||||
RUN_TEST(ei_go_blank_import);
|
||||
RUN_TEST(ei_go_two_consumers_same_package);
|
||||
RUN_TEST(ei_go_import_never_binds_symbol);
|
||||
RUN_TEST(ei_py_external_import_never_binds_project_symbol);
|
||||
RUN_TEST(ei_cpp_header_include_targets_header_file);
|
||||
|
||||
/* ── RED REPRODUCTIONS — Rust (expected to FAIL until pipeline fixed) ── */
|
||||
|
||||
+185
-5
@@ -183,11 +183,12 @@ TEST(extract_ts_factory_object_methods_issue341) {
|
||||
*
|
||||
* The bound is derived, not tuned. Measured on this source, total_alloc was
|
||||
* 365984 before the scratch arena and is 87456 after, exactly that difference.
|
||||
* Of the 87456 that remain, 7680 is the defs item array at GROW_ARRAY's
|
||||
* starting capacity of 32 times sizeof(CBMDefinition) 240, and the other 79776
|
||||
* is everything else this file's extraction interns; none of it is traversal
|
||||
* scratch. So the bound sits above 87456 with room and a factor of four below
|
||||
* 365984.
|
||||
* #1916 added two pointers to CBMDefinition (240 -> 256 bytes), so it now
|
||||
* measures 87968: 8192 is the defs item array at GROW_ARRAY's starting
|
||||
* capacity of 32 times sizeof(CBMDefinition) 256, and the other 79776 is
|
||||
* everything else this file's extraction interns; none of it is traversal
|
||||
* scratch. So the bound sits above 87968 with room and a factor of four below
|
||||
* the 365984 the scratch stacks cost.
|
||||
*
|
||||
* It is a byte budget, not a proof of lifetime; that is
|
||||
* extract_traversal_stacks_come_from_ctx_scratch_issue2010 in test_mem.c. */
|
||||
@@ -916,6 +917,43 @@ TEST(dart_class) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* --- Dart extension members (#1457) --- */
|
||||
TEST(dart_extension_members) {
|
||||
CBMFileResult *r =
|
||||
extract("class Holder {\n final int value;\n const Holder(this.value);\n}\n\n"
|
||||
"extension HolderMath on Holder {\n int doubled() => value + value;\n"
|
||||
" int tripled() => value + value + value;\n"
|
||||
" String describeHolder() => 'holder';\n}\n\n"
|
||||
"int topLevelHelper(int x) => x + 1;\n",
|
||||
CBM_LANG_DART, "t", "a.dart");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT(has_def(r, "Class", "Holder"));
|
||||
ASSERT(has_def(r, "Function", "topLevelHelper"));
|
||||
ASSERT(has_def(r, "Class", "HolderMath"));
|
||||
ASSERT(has_def(r, "Method", "doubled"));
|
||||
ASSERT(has_def(r, "Method", "tripled"));
|
||||
ASSERT(has_def(r, "Method", "describeHolder"));
|
||||
/* Members hang off the extension (DEFINES_METHOD source), not the file. */
|
||||
for (int i = 0; i < r->defs.count; i++) {
|
||||
const CBMDefinition *d = &r->defs.items[i];
|
||||
if (d->name && strcmp(d->name, "doubled") == 0) {
|
||||
ASSERT_NOT_NULL(d->parent_class);
|
||||
ASSERT_STR_EQ(d->parent_class, "t.a.HolderMath");
|
||||
}
|
||||
}
|
||||
cbm_free_result(r);
|
||||
|
||||
/* Unnamed extension: its members are still indexed. */
|
||||
r = extract("extension on String {\n bool isShout() => this == toUpperCase();\n}\n",
|
||||
CBM_LANG_DART, "t", "b.dart");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT(has_def_any(r, "isShout"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* --- Groovy --- */
|
||||
TEST(groovy_class) {
|
||||
CBMFileResult *r =
|
||||
@@ -4631,6 +4669,57 @@ TEST(extract_java_spring_relative_string_not_route_path) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Issue #1428: NestJS routes are TypeScript decorators — the class-level
|
||||
* @Controller('users') prefix composes with the method-level @Get(':id')
|
||||
* verb + path. Nest paths carry no leading slash, and the decorator's call is
|
||||
* a `call_expression` (not Python's `call`), so no Route was ever formed. */
|
||||
TEST(extract_ts_nestjs_controller_routes_issue1428) {
|
||||
CBMFileResult *r =
|
||||
extract("import { Controller, Get, Post, Patch, Delete, Param } from '@nestjs/common';\n"
|
||||
"@Controller({ path: 'users', version: '1' })\n"
|
||||
"export class UsersController {\n"
|
||||
" @Get() findAll() { return []; }\n"
|
||||
" @Get(':id') findOne(@Param('id') id: string) { return id; }\n"
|
||||
" @Post() create() { return 1; }\n"
|
||||
" @Patch(':id') update(@Param('id') id: string) { return id; }\n"
|
||||
" @Delete('/:id') remove(@Param('id') id: string) { return id; }\n"
|
||||
" helper() { return 0; }\n"
|
||||
"}\n"
|
||||
"@Controller('health')\n"
|
||||
"export class HealthController {\n"
|
||||
" @Get() check() { return { status: 'ok' }; }\n"
|
||||
"}\n"
|
||||
"@Controller()\n"
|
||||
"export class RootController {\n"
|
||||
" @Get('ping') ping() { return 'pong'; }\n"
|
||||
"}\n",
|
||||
CBM_LANG_TYPESCRIPT, "t", "src/users/users.controller.ts");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
static const struct {
|
||||
const char *name;
|
||||
const char *method;
|
||||
const char *path;
|
||||
} want[] = {
|
||||
{"findAll", "GET", "/users"}, {"findOne", "GET", "/users/:id"},
|
||||
{"create", "POST", "/users"}, {"update", "PATCH", "/users/:id"},
|
||||
{"remove", "DELETE", "/users/:id"}, {"check", "GET", "/health"},
|
||||
{"ping", "GET", "/ping"},
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(want) / sizeof(want[0]); i++) {
|
||||
const CBMDefinition *d = find_def_by_name(r, want[i].name);
|
||||
ASSERT_NOT_NULL(d);
|
||||
ASSERT_NOT_NULL(d->route_path);
|
||||
ASSERT_STR_EQ(d->route_path, want[i].path);
|
||||
ASSERT_STR_EQ(d->route_method, want[i].method);
|
||||
}
|
||||
const CBMDefinition *helper = find_def_by_name(r, "helper");
|
||||
ASSERT_NOT_NULL(helper);
|
||||
ASSERT_NULL(helper->route_path);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Return the file's Module definition (extraction pushes it first), or NULL. */
|
||||
static const CBMDefinition *find_module_def(CBMFileResult *r) {
|
||||
for (int i = 0; i < r->defs.count; i++) {
|
||||
@@ -5108,6 +5197,62 @@ TEST(extract_ts_template_string_url_issue1006) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Issue #2235: a request-config object argument carries the URL in its `url`
|
||||
* property (Orval/axios style: `http({url: `/x/${id}`, method: 'GET'})`).
|
||||
* The property's template literal flattens to the canonical "{}" form both on
|
||||
* the argument (read by the arg-url heuristic for local helpers) and as the
|
||||
* call's URL (read by HTTP-client classification, e.g. `axios({url})`). Other
|
||||
* keys never stand in for the URL, and a route registration keeps its own
|
||||
* (object-free) handling. */
|
||||
TEST(extract_ts_config_object_url_issue2235) {
|
||||
CBMFileResult *r =
|
||||
extract("export const get1 = (id: string) => {\n"
|
||||
" return http<Customer>({url: `/api/customers/${id}`, method: 'GET'});\n"
|
||||
"};\n"
|
||||
"export const load = () => axios({method: 'POST', 'url': '/api/orders'});\n"
|
||||
"export const other = () => http({path: '/api/ignored/x'});\n"
|
||||
"export const reg = () => fastify.route({url: '/srv/x', handler: h});\n"
|
||||
"export const u = () => axiosInstance.getUri({url: `/pets`});\n",
|
||||
CBM_LANG_TYPESCRIPT, "t", "client.ts");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
const CBMCall *c = NULL;
|
||||
const CBMCall *o = NULL;
|
||||
for (int i = 0; i < r->calls.count; i++) {
|
||||
const CBMCall *k = &r->calls.items[i];
|
||||
if (k->callee_name && strcmp(k->callee_name, "http") == 0 && k->arg_count > 0) {
|
||||
if (k->args[0].expr && strstr(k->args[0].expr, "customers")) {
|
||||
c = k;
|
||||
} else {
|
||||
o = k;
|
||||
}
|
||||
}
|
||||
}
|
||||
ASSERT_NOT_NULL(c);
|
||||
ASSERT_NOT_NULL(c->args[0].value);
|
||||
ASSERT_STR_EQ(c->args[0].value, "/api/customers/{}");
|
||||
ASSERT_NOT_NULL(c->first_string_arg);
|
||||
ASSERT_STR_EQ(c->first_string_arg, "/api/customers/{}");
|
||||
const CBMCall *a = find_call_by_callee(r, "axios");
|
||||
ASSERT_NOT_NULL(a);
|
||||
ASSERT_NOT_NULL(a->first_string_arg);
|
||||
ASSERT_STR_EQ(a->first_string_arg, "/api/orders");
|
||||
ASSERT_NOT_NULL(o);
|
||||
ASSERT_NULL(o->args[0].value);
|
||||
ASSERT_NULL(o->first_string_arg);
|
||||
const CBMCall *g = find_call_by_callee(r, "fastify.route");
|
||||
ASSERT_NOT_NULL(g);
|
||||
ASSERT_NULL(g->first_string_arg);
|
||||
ASSERT(g->arg_count == 0 || g->args[0].value == NULL);
|
||||
/* getUri only formats the URL; it sends no request. */
|
||||
const CBMCall *gu = find_call_by_callee(r, "axiosInstance.getUri");
|
||||
ASSERT_NOT_NULL(gu);
|
||||
ASSERT_NULL(gu->first_string_arg);
|
||||
ASSERT(gu->arg_count == 0 || gu->args[0].value == NULL);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Issue #1249: a mux route built as `configVar + "/literal"` (Go's idiomatic
|
||||
* configurable-base-path pattern) must index the literal suffix, both for a
|
||||
* route registration and for an outbound URL built the same way. A real BFF
|
||||
@@ -8632,6 +8777,37 @@ TEST(extract_spill_round_trip_keeps_every_field) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The low-disk guard, pinned through the free-space seam rather than the host
|
||||
* disk: one byte under the floor refuses (spilling onto a nearly full disk is
|
||||
* a worse failure than the memory pressure it relieves), the floor itself
|
||||
* opens. The runner pins ample space everywhere else; restored before asserts. */
|
||||
TEST(extract_spill_refuses_below_the_free_disk_floor) {
|
||||
char dir[512];
|
||||
snprintf(dir, sizeof(dir), "%s/cbm_spill_XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(dir));
|
||||
|
||||
size_t floor_bytes = cbm_result_spill_free_floor_bytes_for_tests();
|
||||
size_t saved = cbm_result_spill_pin_free_bytes_for_tests(floor_bytes - 1);
|
||||
cbm_result_spill_t *below = cbm_result_spill_open(dir, 1, 1);
|
||||
(void)cbm_result_spill_pin_free_bytes_for_tests(floor_bytes);
|
||||
cbm_result_spill_t *at = cbm_result_spill_open(dir, 1, 1);
|
||||
(void)cbm_result_spill_pin_free_bytes_for_tests(saved);
|
||||
|
||||
bool refused = below == NULL;
|
||||
bool opened = at != NULL;
|
||||
cbm_result_spill_close(below);
|
||||
cbm_result_spill_close(at);
|
||||
char spill_sub[600];
|
||||
snprintf(spill_sub, sizeof(spill_sub), "%s/spill", dir);
|
||||
cbm_rmdir(spill_sub);
|
||||
cbm_rmdir(dir);
|
||||
|
||||
ASSERT_EQ(floor_bytes, (size_t)10 * 1024 * 1024 * 1024);
|
||||
ASSERT_TRUE(refused);
|
||||
ASSERT_TRUE(opened);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── A skipped file gets no LSP walk, per-file or cross-file ── */
|
||||
|
||||
/* CBM_TEST_LSP_SKIP_ON names the file: the result carries lsp_skipped, the
|
||||
@@ -8691,6 +8867,7 @@ SUITE(extraction) {
|
||||
RUN_TEST(extract_compact_keeps_every_field_and_shrinks_the_arena);
|
||||
RUN_TEST(extract_compact_is_idempotent_and_survives_empty_results);
|
||||
RUN_TEST(extract_spill_round_trip_keeps_every_field);
|
||||
RUN_TEST(extract_spill_refuses_below_the_free_disk_floor);
|
||||
RUN_TEST(extract_lsp_skipped_file_gets_no_walk);
|
||||
RUN_TEST(extract_walk_truncated_when_a_node_budget_is_set);
|
||||
/* Initialize extraction library */
|
||||
@@ -8794,6 +8971,7 @@ SUITE(extraction) {
|
||||
RUN_TEST(scala_function);
|
||||
RUN_TEST(scala_class);
|
||||
RUN_TEST(dart_class);
|
||||
RUN_TEST(dart_extension_members);
|
||||
RUN_TEST(groovy_class);
|
||||
|
||||
/* Systems */
|
||||
@@ -9043,11 +9221,13 @@ SUITE(extraction) {
|
||||
RUN_TEST(extract_java_jaxrs_relative_path_templates);
|
||||
RUN_TEST(extract_java_jaxrs_empty_path_means_class_path);
|
||||
RUN_TEST(extract_java_spring_relative_string_not_route_path);
|
||||
RUN_TEST(extract_ts_nestjs_controller_routes_issue1428);
|
||||
RUN_TEST(extract_blazor_page_directive_routes_component);
|
||||
RUN_TEST(extract_blazor_component_without_page_has_no_route);
|
||||
RUN_TEST(extract_razor_page_directive_routes_cshtml_view);
|
||||
RUN_TEST(extract_razor_layout_without_page_has_no_route);
|
||||
RUN_TEST(extract_ts_template_string_url_issue1006);
|
||||
RUN_TEST(extract_ts_config_object_url_issue2235);
|
||||
RUN_TEST(extract_go_binary_concat_url_issue1249);
|
||||
RUN_TEST(extract_go_binary_concat_url_no_literal_suffix_issue1249);
|
||||
RUN_TEST(extract_ts_url_builder_issue1009);
|
||||
|
||||
@@ -27,6 +27,11 @@
|
||||
#include "test_framework.h"
|
||||
#include "test_helpers.h"
|
||||
#include "git/git_context.h"
|
||||
#include "foundation/compat.h"
|
||||
#include "foundation/git_env.h"
|
||||
#include "pipeline/pipeline_internal.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
@@ -82,6 +87,94 @@ static int make_git_repo(const char *dir) {
|
||||
}
|
||||
#endif /* _WIN32 */
|
||||
|
||||
#ifndef _WIN32
|
||||
/* ── Inherited repository-local git environment (#2003) ────────────
|
||||
* A cbm started from a git hook (or an editor that exports GIT_DIR) inherits
|
||||
* GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE/..., which override `git -C <dir>`.
|
||||
* Production must clear them for its own git children (per spawn). These
|
||||
* tests set the hook set explicitly (the runner may clear it at startup) and
|
||||
* restore the caller's values before asserting, so a failure never leaks the
|
||||
* decoy environment into later tests. */
|
||||
|
||||
typedef struct {
|
||||
char *saved[CBM_GIT_REPO_ENV_VAR_COUNT];
|
||||
bool present[CBM_GIT_REPO_ENV_VAR_COUNT];
|
||||
} git_env_snapshot_t;
|
||||
|
||||
static void git_env_hook_enter(git_env_snapshot_t *snap, const char *decoy) {
|
||||
for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {
|
||||
const char *v = getenv(cbm_git_repo_env_vars[i]);
|
||||
snap->present[i] = v != NULL;
|
||||
snap->saved[i] = v ? strdup(v) : NULL;
|
||||
}
|
||||
char buf[1024];
|
||||
snprintf(buf, sizeof(buf), "%s/.git", decoy);
|
||||
cbm_setenv("GIT_DIR", buf, 1);
|
||||
cbm_setenv("GIT_COMMON_DIR", buf, 1);
|
||||
cbm_setenv("GIT_WORK_TREE", decoy, 1);
|
||||
snprintf(buf, sizeof(buf), "%s/.git/index", decoy);
|
||||
cbm_setenv("GIT_INDEX_FILE", buf, 1);
|
||||
snprintf(buf, sizeof(buf), "%s/.git/objects", decoy);
|
||||
cbm_setenv("GIT_OBJECT_DIRECTORY", buf, 1);
|
||||
cbm_setenv("GIT_PREFIX", "", 1);
|
||||
}
|
||||
|
||||
static void git_env_hook_leave(git_env_snapshot_t *snap) {
|
||||
for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {
|
||||
if (snap->present[i]) {
|
||||
cbm_setenv(cbm_git_repo_env_vars[i], snap->saved[i], 1);
|
||||
} else {
|
||||
cbm_unsetenv(cbm_git_repo_env_vars[i]);
|
||||
}
|
||||
free(snap->saved[i]);
|
||||
snap->saved[i] = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/* First output line of `git -C dir <args>` (run with the test's clean env). */
|
||||
static void git_read_line(const char *dir, const char *args, char *out, size_t out_sz) {
|
||||
char cmd[1024];
|
||||
out[0] = '\0';
|
||||
snprintf(cmd, sizeof(cmd), "git -C \"%s\" %s 2>/dev/null", dir, args);
|
||||
FILE *fp = popen(cmd, "r");
|
||||
if (!fp)
|
||||
return;
|
||||
if (fgets(out, (int)out_sz, fp)) {
|
||||
out[strcspn(out, "\r\n")] = '\0';
|
||||
}
|
||||
pclose(fp);
|
||||
}
|
||||
|
||||
/* root/decoy: a repo on branch decoy-branch with coupled a.go+b.go commits;
|
||||
* root/fixture: a repo on branch fixture-branch; root/plain: not a repo. */
|
||||
static int make_env_isolation_tree(const char *root) {
|
||||
char decoy[512], fixture[512], plain[512], path[600];
|
||||
snprintf(decoy, sizeof(decoy), "%s/decoy", root);
|
||||
snprintf(fixture, sizeof(fixture), "%s/fixture", root);
|
||||
snprintf(plain, sizeof(plain), "%s/plain", root);
|
||||
if (make_git_repo(decoy) != 0 || make_git_repo(fixture) != 0)
|
||||
return -1;
|
||||
if (git_run(decoy, "checkout -q -b decoy-branch") != 0)
|
||||
return -1;
|
||||
if (git_run(fixture, "checkout -q -b fixture-branch") != 0)
|
||||
return -1;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
char content[32];
|
||||
snprintf(content, sizeof(content), "package a // %d\n", i);
|
||||
snprintf(path, sizeof(path), "%s/a.go", decoy);
|
||||
th_write_file(path, content);
|
||||
snprintf(path, sizeof(path), "%s/b.go", decoy);
|
||||
th_write_file(path, content);
|
||||
if (git_run(decoy, "add a.go b.go") != 0)
|
||||
return -1;
|
||||
if (git_run(decoy, "commit -q -m decoy") != 0)
|
||||
return -1;
|
||||
}
|
||||
return th_mkdir_p(plain);
|
||||
}
|
||||
|
||||
#endif /* _WIN32 */
|
||||
|
||||
/* ── canonical_root: normal repo indexed from its root ──────────── */
|
||||
|
||||
TEST(canonical_root_repo_root) {
|
||||
@@ -253,6 +346,100 @@ TEST(canonical_root_linked_worktree) {
|
||||
#endif /* _WIN32 */
|
||||
}
|
||||
|
||||
TEST(git_context_ignores_inherited_repo_env) {
|
||||
#ifdef _WIN32
|
||||
SKIP_PLATFORM("git-based env-isolation test not supported on Windows CI");
|
||||
#else
|
||||
char root[256];
|
||||
char *raw = th_mktempdir("cbm_gitenv");
|
||||
if (!raw)
|
||||
FAIL("th_mktempdir returned NULL");
|
||||
snprintf(root, sizeof(root), "%s", raw);
|
||||
if (make_env_isolation_tree(root) != 0) {
|
||||
th_rmtree(root);
|
||||
SKIP_PLATFORM("git not available to init a repo");
|
||||
}
|
||||
char decoy[512], fixture[512], plain[512];
|
||||
snprintf(decoy, sizeof(decoy), "%s/decoy", root);
|
||||
snprintf(fixture, sizeof(fixture), "%s/fixture", root);
|
||||
snprintf(plain, sizeof(plain), "%s/plain", root);
|
||||
|
||||
char decoy_head[128], decoy_branch[128], fixture_head[128];
|
||||
git_read_line(decoy, "rev-parse HEAD", decoy_head, sizeof(decoy_head));
|
||||
git_read_line(decoy, "rev-parse --abbrev-ref HEAD", decoy_branch, sizeof(decoy_branch));
|
||||
git_read_line(fixture, "rev-parse HEAD", fixture_head, sizeof(fixture_head));
|
||||
|
||||
git_env_snapshot_t snap;
|
||||
git_env_hook_enter(&snap, decoy);
|
||||
cbm_git_context_t plain_ctx = {0};
|
||||
int plain_rc = cbm_git_context_resolve(plain, &plain_ctx);
|
||||
cbm_git_context_t fix_ctx = {0};
|
||||
int fix_rc = cbm_git_context_resolve(fixture, &fix_ctx);
|
||||
git_env_hook_leave(&snap);
|
||||
|
||||
bool plain_is_git = plain_ctx.is_git;
|
||||
char fix_head[128], fix_branch[128];
|
||||
snprintf(fix_head, sizeof(fix_head), "%s", fix_ctx.head_sha ? fix_ctx.head_sha : "");
|
||||
snprintf(fix_branch, sizeof(fix_branch), "%s", fix_ctx.branch ? fix_ctx.branch : "");
|
||||
bool fix_is_git = fix_ctx.is_git;
|
||||
cbm_git_context_free(&plain_ctx);
|
||||
cbm_git_context_free(&fix_ctx);
|
||||
|
||||
char decoy_head_after[128], decoy_branch_after[128];
|
||||
git_read_line(decoy, "rev-parse HEAD", decoy_head_after, sizeof(decoy_head_after));
|
||||
git_read_line(decoy, "rev-parse --abbrev-ref HEAD", decoy_branch_after,
|
||||
sizeof(decoy_branch_after));
|
||||
th_rmtree(root);
|
||||
|
||||
ASSERT_EQ(plain_rc, 0);
|
||||
ASSERT_FALSE(plain_is_git); /* a plain dir is not the decoy's repo */
|
||||
ASSERT_EQ(fix_rc, 0);
|
||||
ASSERT_TRUE(fix_is_git);
|
||||
ASSERT_STR_EQ(fix_head, fixture_head); /* the fixture's HEAD, not the decoy's */
|
||||
ASSERT_STR_EQ(fix_branch, "fixture-branch");
|
||||
ASSERT_STR_EQ(decoy_head_after, decoy_head); /* the decoy is untouched */
|
||||
ASSERT_STR_EQ(decoy_branch_after, decoy_branch);
|
||||
PASS();
|
||||
#endif /* _WIN32 */
|
||||
}
|
||||
|
||||
TEST(githistory_ignores_inherited_repo_env) {
|
||||
#ifdef _WIN32
|
||||
SKIP_PLATFORM("git-based env-isolation test not supported on Windows CI");
|
||||
#else
|
||||
char root[256];
|
||||
char *raw = th_mktempdir("cbm_gitenv_hist");
|
||||
if (!raw)
|
||||
FAIL("th_mktempdir returned NULL");
|
||||
snprintf(root, sizeof(root), "%s", raw);
|
||||
if (make_env_isolation_tree(root) != 0) {
|
||||
th_rmtree(root);
|
||||
SKIP_PLATFORM("git not available to init a repo");
|
||||
}
|
||||
char decoy[512], plain[512];
|
||||
snprintf(decoy, sizeof(decoy), "%s/decoy", root);
|
||||
snprintf(plain, sizeof(plain), "%s/plain", root);
|
||||
|
||||
git_env_snapshot_t snap;
|
||||
git_env_hook_enter(&snap, decoy);
|
||||
cbm_githistory_result_t result = {0};
|
||||
(void)cbm_pipeline_githistory_compute(plain, &result);
|
||||
git_env_hook_leave(&snap);
|
||||
|
||||
int commits = result.commit_count;
|
||||
int couplings = result.count;
|
||||
free(result.couplings);
|
||||
free(result.file_temporal);
|
||||
th_rmtree(root);
|
||||
|
||||
/* A non-git directory has no history: the decoy's 3 coupled commits
|
||||
* must not be attributed to it. */
|
||||
ASSERT_EQ(commits, 0);
|
||||
ASSERT_EQ(couplings, 0);
|
||||
PASS();
|
||||
#endif /* _WIN32 */
|
||||
}
|
||||
|
||||
/* ── Suite ──────────────────────────────────────────────────────── */
|
||||
|
||||
SUITE(git_context) {
|
||||
@@ -260,4 +447,6 @@ SUITE(git_context) {
|
||||
RUN_TEST(canonical_root_repo_root);
|
||||
RUN_TEST(canonical_root_subdir);
|
||||
RUN_TEST(canonical_root_linked_worktree);
|
||||
RUN_TEST(git_context_ignores_inherited_repo_env);
|
||||
RUN_TEST(githistory_ignores_inherited_repo_env);
|
||||
}
|
||||
|
||||
@@ -180,15 +180,19 @@ static inline char *th_mktempdir(const char *prefix) {
|
||||
* leaf made by cbm_mkdtemp() has a private DACL. Keep these security-sensitive
|
||||
* fixtures under LocalAppData on Windows; preserve the ordinary temporary-root
|
||||
* behavior on POSIX. */
|
||||
static inline const char *th_secure_runtime_base(void) {
|
||||
#ifdef _WIN32
|
||||
return cbm_app_local_dir();
|
||||
#else
|
||||
return cbm_tmpdir();
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline bool th_secure_runtime_parent_new(char *out, size_t out_cap, const char *tag) {
|
||||
if (!out || out_cap == 0 || !tag || !tag[0]) {
|
||||
return false;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
const char *base = cbm_app_local_dir();
|
||||
#else
|
||||
const char *base = cbm_tmpdir();
|
||||
#endif
|
||||
const char *base = th_secure_runtime_base();
|
||||
if (!base || !base[0]) {
|
||||
out[0] = '\0';
|
||||
return false;
|
||||
|
||||
+117
-1
@@ -18,12 +18,14 @@ int tf_skip_count = 0;
|
||||
#include "foundation/mem.h" /* cbm_mem_init — worker budget */
|
||||
#include "foundation/log.h" /* worker liveness heartbeat probe */
|
||||
#include "foundation/platform.h" /* cbm_file_exists — blocking-git marker */
|
||||
#include "daemon/bootstrap.h" /* runner rendezvous isolation */
|
||||
#include "daemon/runtime.h" /* bounded worker response probe */
|
||||
#include "daemon/ipc.h" /* Windows private-lock re-exec probe */
|
||||
#include "daemon/version_cohort.h" /* Windows crash-turnover re-exec probe */
|
||||
#include "mcp/index_supervisor.h" /* cbm_index_set_worker_role */
|
||||
#include "mcp/mcp.h" /* cbm_mcp_handle_tool — act as a real worker */
|
||||
#include "ui/http_server.h" /* deleted-self executable probe */
|
||||
#include "result_spill.h" /* pinned free disk: spill verdicts ignore the host disk */
|
||||
#include <sqlite3.h>
|
||||
#include <errno.h>
|
||||
#include <stdbool.h>
|
||||
@@ -186,11 +188,15 @@ static int tf_maybe_run_blocking_git_probe(int argc, char **argv) {
|
||||
* this sentinel and restore it; atexit removes anything left behind by an
|
||||
* assertion that returns before fixture cleanup. */
|
||||
static char tf_home_sentinel[512];
|
||||
static char tf_runtime_sentinel[512];
|
||||
|
||||
static void tf_cleanup_cache_sentinel(void) {
|
||||
if (tf_home_sentinel[0]) {
|
||||
th_rmtree(tf_home_sentinel);
|
||||
}
|
||||
if (tf_runtime_sentinel[0]) {
|
||||
th_rmtree(tf_runtime_sentinel);
|
||||
}
|
||||
}
|
||||
|
||||
/* Client home overrides the CLI honours BEFORE $HOME, so redirecting HOME alone
|
||||
@@ -242,9 +248,108 @@ static bool tf_setup_cache_sentinel(void) {
|
||||
cbm_unsetenv(tf_client_home_overrides[i]);
|
||||
}
|
||||
atexit(tf_cleanup_cache_sentinel);
|
||||
/* HOME and CBM_CACHE_DIR do not move the daemon rendezvous: its key is a
|
||||
* constant product hash under the system temp root. Without this, an
|
||||
* install/uninstall/update test or any endpoint resolved with no explicit
|
||||
* parent reaches the developer's live daemon. The run always gets a fresh
|
||||
* private directory; an inherited value is replaced, never reused (the
|
||||
* rule scripts/test-runtime.sh applies to the shell harness).
|
||||
* th_secure_runtime_parent_new anchors it where the IPC ancestry check
|
||||
* accepts it (LocalAppData on Windows). */
|
||||
if (!th_secure_runtime_parent_new(tf_runtime_sentinel, sizeof(tf_runtime_sentinel), "run")) {
|
||||
tf_runtime_sentinel[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
if (cbm_setenv("CBM_RUNTIME_DIR", tf_runtime_sentinel, 1) != 0) {
|
||||
return false;
|
||||
}
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* Belt and braces: a fixture that later drops the variable gets a loud
|
||||
* refusal instead of the default rendezvous. */
|
||||
cbm_daemon_bootstrap_forbid_default_runtime_for_test(true);
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool tf_path_has_parent(const char *path, const char *parent) {
|
||||
size_t length = parent ? strlen(parent) : 0;
|
||||
return path && length > 0 && strncmp(path, parent, length) == 0 &&
|
||||
(path[length] == '/' || path[length] == '\\');
|
||||
}
|
||||
|
||||
/* The daemon rendezvous is not derived from HOME or the cache: its key is a
|
||||
* constant product hash and its default parent is the system temp root. With
|
||||
* CBM_RUNTIME_DIR unset, every endpoint a test resolves is therefore the
|
||||
* developer's live daemon socket (<tmp>/cbm-daemon-<uid>/cbm-<key>.sock).
|
||||
* Every check runs before anything is resolved, so a run without isolation
|
||||
* fails here and this test never reaches that socket itself. */
|
||||
TEST(runner_isolation_daemon_runtime_dir_is_private) {
|
||||
char runtime_env[sizeof(tf_runtime_sentinel)] = {0};
|
||||
const char *value = cbm_safe_getenv("CBM_RUNTIME_DIR", runtime_env, sizeof(runtime_env), NULL);
|
||||
ASSERT_NOT_NULL(value);
|
||||
ASSERT_TRUE(value[0] != '\0');
|
||||
/* The fresh per-run directory, never a value inherited from the caller. */
|
||||
ASSERT_STR_EQ(value, tf_runtime_sentinel);
|
||||
|
||||
const char *root = th_secure_runtime_base();
|
||||
ASSERT_NOT_NULL(root);
|
||||
char canonical_root[CBM_SZ_4K] = {0};
|
||||
char canonical_run[CBM_SZ_4K] = {0};
|
||||
ASSERT_TRUE(cbm_canonical_path(root, canonical_root, sizeof(canonical_root)) != 0);
|
||||
ASSERT_TRUE(cbm_canonical_path(value, canonical_run, sizeof(canonical_run)) != 0);
|
||||
/* Strictly below the temp root: the root itself is the default rendezvous
|
||||
* parent (/tmp on POSIX, LocalAppData on Windows). */
|
||||
ASSERT_TRUE(tf_path_has_parent(canonical_run, canonical_root));
|
||||
|
||||
/* Only now resolve through the product resolver. A NULL parent is what
|
||||
* every product call site passes: daemon, MCP client, CLI, activation. */
|
||||
cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_bootstrap_endpoint_new(NULL);
|
||||
const char *resolved = endpoint ? cbm_daemon_ipc_endpoint_runtime_dir(endpoint) : NULL;
|
||||
char canonical_resolved[CBM_SZ_4K] = {0};
|
||||
bool resolved_ok = resolved && cbm_canonical_path(resolved, canonical_resolved,
|
||||
sizeof(canonical_resolved)) != 0;
|
||||
cbm_daemon_ipc_endpoint_free(endpoint);
|
||||
ASSERT_TRUE(resolved_ok);
|
||||
ASSERT_TRUE(tf_path_has_parent(canonical_resolved, canonical_run));
|
||||
#ifndef _WIN32
|
||||
char live_default[CBM_SZ_4K];
|
||||
(void)snprintf(live_default, sizeof(live_default), "%s/cbm-daemon-%lu", canonical_root,
|
||||
(unsigned long)geteuid());
|
||||
ASSERT_TRUE(strcmp(canonical_resolved, live_default) != 0);
|
||||
#endif
|
||||
PASS();
|
||||
}
|
||||
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
/* The runner arms the bootstrap guard, so a fixture that drops the variable
|
||||
* gets a refusal instead of the default rendezvous. Only the decision is
|
||||
* exercised: no endpoint is ever built while the variable is absent. */
|
||||
TEST(runner_isolation_refuses_default_daemon_runtime) {
|
||||
ASSERT_TRUE(tf_runtime_sentinel[0] != '\0');
|
||||
bool allowed_with_run_dir = !cbm_daemon_bootstrap_default_runtime_refused_for_test(NULL);
|
||||
|
||||
(void)cbm_unsetenv("CBM_RUNTIME_DIR");
|
||||
bool refused_without = cbm_daemon_bootstrap_default_runtime_refused_for_test(NULL);
|
||||
bool explicit_allowed =
|
||||
!cbm_daemon_bootstrap_default_runtime_refused_for_test(tf_runtime_sentinel);
|
||||
/* Restore before asserting: a failed assertion returns immediately. */
|
||||
bool restored = cbm_setenv("CBM_RUNTIME_DIR", tf_runtime_sentinel, 1) == 0;
|
||||
|
||||
ASSERT_TRUE(restored);
|
||||
ASSERT_TRUE(allowed_with_run_dir);
|
||||
ASSERT_TRUE(refused_without);
|
||||
ASSERT_TRUE(explicit_allowed);
|
||||
PASS();
|
||||
}
|
||||
#endif
|
||||
|
||||
SUITE(runner_isolation) {
|
||||
RUN_TEST(runner_isolation_daemon_runtime_dir_is_private);
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
RUN_TEST(runner_isolation_refuses_default_daemon_runtime);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Fast real-process probes for the async index-supervisor contract. They run
|
||||
* only in a child admitted by the exact build-bound worker grammar. */
|
||||
static void tf_index_worker_probe(const char *args_json, const char *response_out) {
|
||||
@@ -958,6 +1063,14 @@ int main(int argc, char **argv) {
|
||||
(void)printf("sanitized=%d test_seams=%d\n", sanitized, test_seams);
|
||||
return 0;
|
||||
}
|
||||
/* A test's verdict is a pure function of code, test, platform and seed --
|
||||
* never of how full this machine's disk is. The spill store refuses to open
|
||||
* below 10 GB free, so without this pin every spill test failed, and every
|
||||
* budget-driven pipeline test silently took the no-store path, on a host
|
||||
* with less free space. Pin ample space for this process and every worker
|
||||
* it re-execs; the refusal itself is pinned on purpose by
|
||||
* extraction::extract_spill_refuses_below_the_free_disk_floor. */
|
||||
(void)cbm_result_spill_pin_free_bytes_for_tests((size_t)64 * 1024 * 1024 * 1024);
|
||||
/* Skip the multi-hundred-MB executable-image hash that computes the exact
|
||||
* build fingerprint: it is tens of seconds per spawned worker/daemon under
|
||||
* ASan on constrained CI runners and the sole cause of the daemon-family
|
||||
@@ -1048,7 +1161,7 @@ int main(int argc, char **argv) {
|
||||
* A test that exercises the supervisor must explicitly re-enable it. */
|
||||
cbm_setenv("CBM_INDEX_SUPERVISOR", "0", 1);
|
||||
if (!tf_setup_cache_sentinel()) {
|
||||
fprintf(stderr, "failed to create isolated test cache\n");
|
||||
fprintf(stderr, "failed to create isolated test cache and daemon runtime\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
@@ -1072,6 +1185,9 @@ int main(int argc, char **argv) {
|
||||
printf("\n codebase-memory-mcp C test suite\n");
|
||||
}
|
||||
|
||||
/* Runner isolation first: nothing below may reach the developer's daemon. */
|
||||
RUN_SELECTED_SUITE(runner_isolation);
|
||||
|
||||
/* Foundation */
|
||||
RUN_SELECTED_SUITE(arena);
|
||||
RUN_SELECTED_SUITE(hash_table);
|
||||
|
||||
+541
-4
@@ -1397,13 +1397,13 @@ TEST(mcp_tools_have_behavior_annotations) {
|
||||
* left in place, never quarantined or rebuilt. Quarantine/rebuild is
|
||||
* a write-side job (index_repository, manage_adr writes), so the
|
||||
* read-only annotations are honest and plan-mode clients can expose
|
||||
* these tools. get_file_outline arrived after this split and keeps
|
||||
* its upstream conservative annotation. */
|
||||
* these tools. get_file_outline reads through the same resolve_store
|
||||
* path and is annotated the same way (#2118). */
|
||||
{"search_graph", true, false, true, false},
|
||||
{"query_graph", true, false, true, false},
|
||||
{"trace_path", true, false, true, false},
|
||||
{"get_code_snippet", true, false, true, false},
|
||||
{"get_file_outline", false, true, true, false},
|
||||
{"get_file_outline", true, false, true, false},
|
||||
{"get_graph_schema", true, false, true, false},
|
||||
{"compare_graphs", true, false, true, false},
|
||||
{"get_architecture", true, false, true, false},
|
||||
@@ -1414,7 +1414,10 @@ TEST(mcp_tools_have_behavior_annotations) {
|
||||
{"check_index_coverage", true, false, true, false},
|
||||
{"detect_changes", true, false, true, false},
|
||||
{"manage_adr", false, true, false, false},
|
||||
{"ingest_traces", false, false, false, false},
|
||||
/* ingest_traces only validates and counts its input; it writes
|
||||
* nothing, so it is read-only and idempotent until edge creation
|
||||
* actually lands (#2118). */
|
||||
{"ingest_traces", true, false, true, false},
|
||||
};
|
||||
|
||||
char *json = cbm_mcp_tools_list();
|
||||
@@ -1467,6 +1470,80 @@ TEST(mcp_tools_have_behavior_annotations) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2118: annotations drive client auto-approval, so a mis-stamped read tool
|
||||
* is a real integration bug. Walk the REGISTERED tool list (not a mirrored
|
||||
* table) so a newly added tool cannot slip through: every tool must carry
|
||||
* annotations, a read-only tool can never be destructive, and only the tools
|
||||
* whose handlers actually mutate state may be non-read-only. */
|
||||
static yyjson_val *find_tool_json(yyjson_val *tools, const char *name) {
|
||||
yyjson_arr_iter iter;
|
||||
yyjson_arr_iter_init(tools, &iter);
|
||||
yyjson_val *tool;
|
||||
while ((tool = yyjson_arr_iter_next(&iter)) != NULL) {
|
||||
const char *tool_name = yyjson_get_str(yyjson_obj_get(tool, "name"));
|
||||
if (tool_name && strcmp(tool_name, name) == 0) {
|
||||
return tool;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static bool tool_in_list(const char *name, const char *const *list, size_t count) {
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
if (strcmp(name, list[i]) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
TEST(mcp_tool_annotations_only_mutators_are_writable_issue2118) {
|
||||
/* Handlers that write user-visible state: index_repository (builds the
|
||||
* index), manage_adr (writes/overwrites ADR sections), delete_project
|
||||
* (removes the index). Everything else must be read-only. */
|
||||
static const char *const mutating[] = {"index_repository", "manage_adr", "delete_project"};
|
||||
/* Of those, only the ones that can remove/overwrite existing data. */
|
||||
static const char *const destructive[] = {"manage_adr", "delete_project"};
|
||||
const size_t n_mut = sizeof(mutating) / sizeof(mutating[0]);
|
||||
const size_t n_des = sizeof(destructive) / sizeof(destructive[0]);
|
||||
|
||||
char *json = cbm_mcp_tools_list();
|
||||
ASSERT_NOT_NULL(json);
|
||||
yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
|
||||
ASSERT_NOT_NULL(doc);
|
||||
yyjson_val *tools = yyjson_obj_get(yyjson_doc_get_root(doc), "tools");
|
||||
ASSERT_NOT_NULL(tools);
|
||||
|
||||
int count = cbm_mcp_tool_count();
|
||||
ASSERT_GT(count, 0);
|
||||
ASSERT_EQ(yyjson_arr_size(tools), (size_t)count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
const char *name = cbm_mcp_tool_name(i);
|
||||
ASSERT_NOT_NULL(name);
|
||||
yyjson_val *tool = find_tool_json(tools, name);
|
||||
ASSERT_NOT_NULL(tool);
|
||||
yyjson_val *annotations = yyjson_obj_get(tool, "annotations");
|
||||
ASSERT_NOT_NULL(annotations);
|
||||
yyjson_val *read_only = yyjson_obj_get(annotations, "readOnlyHint");
|
||||
yyjson_val *destr = yyjson_obj_get(annotations, "destructiveHint");
|
||||
ASSERT_TRUE(yyjson_is_bool(read_only));
|
||||
ASSERT_TRUE(yyjson_is_bool(destr));
|
||||
bool is_mut = tool_in_list(name, mutating, n_mut);
|
||||
bool is_des = tool_in_list(name, destructive, n_des);
|
||||
if (yyjson_get_bool(read_only) == is_mut || yyjson_get_bool(destr) != is_des) {
|
||||
printf(" tool %s: readOnlyHint=%d destructiveHint=%d (want %d/%d)\n", name,
|
||||
(int)yyjson_get_bool(read_only), (int)yyjson_get_bool(destr), (int)!is_mut,
|
||||
(int)is_des);
|
||||
}
|
||||
ASSERT_EQ(yyjson_get_bool(read_only), !is_mut);
|
||||
ASSERT_EQ(yyjson_get_bool(destr), is_des);
|
||||
}
|
||||
|
||||
yyjson_doc_free(doc);
|
||||
free(json);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(mcp_index_repository_declares_name_override_issue571) {
|
||||
char *json = cbm_mcp_tools_list();
|
||||
ASSERT_NOT_NULL(json);
|
||||
@@ -7187,6 +7264,67 @@ TEST(tool_trace_call_path_prefers_definition) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Leak regression: trace_path by a qualified name resolves only through the
|
||||
* qualified_name fallback. The bare-name lookup that precedes it returns a
|
||||
* heap array even for zero rows (find_nodes_generic allocates its initial
|
||||
* capacity up front), and the fallback used to overwrite that pointer —
|
||||
* leaking ~1 KB per call for the daemon's lifetime. The sanitizer lanes
|
||||
* (LSan: default-on under Linux ASan, `make -f Makefile.cbm test-lsan` on
|
||||
* macOS) report the leak at exit; the assertions pin that this test really
|
||||
* takes the fallback path. */
|
||||
TEST(tool_trace_call_path_qn_fallback_frees_name_miss) {
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
cbm_store_t *st = cbm_mcp_server_store(srv);
|
||||
const char *proj = "qnfb-proj";
|
||||
const char *qn = "qnfb-proj.src.qnfb_entry";
|
||||
cbm_mcp_server_set_project(srv, proj);
|
||||
cbm_store_upsert_project(st, proj, "/tmp/qnfb");
|
||||
cbm_node_t entry = {.project = proj,
|
||||
.label = "Function",
|
||||
.name = "qnfb_entry",
|
||||
.qualified_name = qn,
|
||||
.file_path = "src/qnfb.c",
|
||||
.start_line = 1,
|
||||
.end_line = 10};
|
||||
cbm_node_t callee = {.project = proj,
|
||||
.label = "Function",
|
||||
.name = "qnfb_callee",
|
||||
.qualified_name = "qnfb-proj.src.qnfb_callee",
|
||||
.file_path = "src/qnfb.c",
|
||||
.start_line = 20,
|
||||
.end_line = 30};
|
||||
int64_t id_entry = cbm_store_upsert_node(st, &entry);
|
||||
int64_t id_callee = cbm_store_upsert_node(st, &callee);
|
||||
ASSERT_GT(id_entry, 0);
|
||||
ASSERT_GT(id_callee, 0);
|
||||
cbm_edge_t e = {
|
||||
.project = proj, .source_id = id_entry, .target_id = id_callee, .type = "CALLS"};
|
||||
cbm_store_insert_edge(st, &e);
|
||||
|
||||
/* Precondition: the qualified name is NOT a bare name, so the handler's
|
||||
* first lookup misses and the fallback is the only way to resolve it. */
|
||||
cbm_node_t *by_name = NULL;
|
||||
int by_name_count = -1;
|
||||
ASSERT_EQ(cbm_store_find_nodes_by_name(st, proj, qn, &by_name, &by_name_count), CBM_STORE_OK);
|
||||
ASSERT_EQ(by_name_count, 0);
|
||||
cbm_store_free_nodes(by_name, by_name_count);
|
||||
|
||||
char *resp = cbm_mcp_server_handle(
|
||||
srv, "{\"jsonrpc\":\"2.0\",\"id\":63,\"method\":\"tools/call\","
|
||||
"\"params\":{\"name\":\"trace_call_path\",\"arguments\":{\"function_name\":"
|
||||
"\"qnfb-proj.src.qnfb_entry\",\"project\":\"qnfb-proj\",\"direction\":\"outbound\"}}}");
|
||||
ASSERT_NOT_NULL(resp);
|
||||
char *inner = extract_text_content(resp);
|
||||
ASSERT_NOT_NULL(inner);
|
||||
ASSERT_NULL(strstr(inner, "function not found"));
|
||||
/* resolved through the fallback -> its outbound CALLS edge shows */
|
||||
ASSERT_NOT_NULL(strstr(inner, "qnfb_callee"));
|
||||
free(inner);
|
||||
free(resp);
|
||||
cbm_mcp_server_free(srv);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* CONTRACT PIN for the closed strategy vocabulary published by
|
||||
* trace_path(include_evidence:true).
|
||||
*
|
||||
@@ -8439,6 +8577,197 @@ TEST(tool_project_arg_resolves_unique_tail_issue1025) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1827: a repo under a non-ASCII folder ("中文测试仓库") gets a project name
|
||||
* whose non-ASCII bytes are hex-transliterated (#571), e.g.
|
||||
* "...-e4b8ade69687e6b58be8af95e4bb93e5ba93". That stored identity stays
|
||||
* stable (it is the cache DB file name), but the project must stay reachable
|
||||
* by what the user actually knows: the real path (already normalized) AND the
|
||||
* real folder name, which the #1025 tail match skipped because the raw
|
||||
* non-ASCII name fails the project-name validator before any lookup. */
|
||||
TEST(tool_project_arg_resolves_non_ascii_folder_issue1827) {
|
||||
char parent[CBM_SZ_256];
|
||||
char cache[CBM_SZ_256];
|
||||
snprintf(parent, sizeof(parent), "/tmp/cbm-i1827a-XXXXXX");
|
||||
snprintf(cache, sizeof(cache), "/tmp/cbm-i1827c-XXXXXX");
|
||||
if (!cbm_mkdtemp(parent) || !cbm_mkdtemp(cache)) {
|
||||
FAIL("mkdtemp failed");
|
||||
}
|
||||
const char *folder = "\xe4\xb8\xad\xe6\x96\x87\xe6\xb5\x8b\xe8\xaf\x95\xe4\xbb\x93\xe5\xba\x93";
|
||||
char repo[CBM_SZ_512];
|
||||
snprintf(repo, sizeof(repo), "%s/%s", parent, folder);
|
||||
ASSERT_TRUE(cbm_mkdir_p(repo, 0755));
|
||||
char file[CBM_SZ_1K];
|
||||
snprintf(file, sizeof(file), "%s/hello.js", repo);
|
||||
FILE *f = cbm_fopen(file, "w");
|
||||
ASSERT_NOT_NULL(f);
|
||||
fprintf(f, "function greet_1827(){return 'hi';}\n");
|
||||
fclose(f);
|
||||
|
||||
const char *saved_cache = getenv("CBM_CACHE_DIR");
|
||||
char *saved_cache_copy = saved_cache ? cbm_strdup(saved_cache) : NULL;
|
||||
cbm_setenv("CBM_CACHE_DIR", cache, 1);
|
||||
cbm_setenv("CBM_INDEX_SUPERVISOR", "0", 1);
|
||||
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
ASSERT_NOT_NULL(srv);
|
||||
char args[CBM_SZ_2K];
|
||||
snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", repo);
|
||||
char *r = cbm_mcp_handle_tool(srv, "index_repository", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
free(r);
|
||||
|
||||
/* The stored identity keeps its existing hex form (no DB rename). */
|
||||
char *stored = cbm_project_name_from_path(repo);
|
||||
ASSERT_NOT_NULL(stored);
|
||||
ASSERT_NOT_NULL(strstr(stored, "-e4b8ade69687e6b58be8af95e4bb93e5ba93"));
|
||||
free(stored);
|
||||
|
||||
/* 1. The real folder name resolves (RED before: "project not found"). */
|
||||
snprintf(args, sizeof(args), "{\"project\":\"%s\",\"name_pattern\":\".*greet_1827.*\"}",
|
||||
folder);
|
||||
r = cbm_mcp_handle_tool(srv, "search_graph", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
if (strstr(r, "project not found")) {
|
||||
fprintf(stderr, " [1827] FAIL folder name did not resolve: %.200s\n", r);
|
||||
}
|
||||
ASSERT_NULL(strstr(r, "project not found"));
|
||||
ASSERT_NOT_NULL(strstr(r, "greet_1827"));
|
||||
free(r);
|
||||
|
||||
/* 2. The real path keeps resolving. */
|
||||
snprintf(args, sizeof(args), "{\"project\":\"%s\",\"name_pattern\":\".*greet_1827.*\"}", repo);
|
||||
r = cbm_mcp_handle_tool(srv, "search_graph", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NULL(strstr(r, "project not found"));
|
||||
ASSERT_NOT_NULL(strstr(r, "greet_1827"));
|
||||
free(r);
|
||||
|
||||
/* 3. A non-ASCII name matching nothing stays a not-found error. */
|
||||
r = cbm_mcp_handle_tool(srv, "search_graph",
|
||||
"{\"project\":\"\xe4\xb8\x8d\xe5\xad\x98\xe5\x9c\xa8\","
|
||||
"\"name_pattern\":\".*\"}");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(strstr(r, "project not found"));
|
||||
free(r);
|
||||
|
||||
cbm_mcp_server_free(srv);
|
||||
if (saved_cache_copy) {
|
||||
cbm_setenv("CBM_CACHE_DIR", saved_cache_copy, 1);
|
||||
free(saved_cache_copy);
|
||||
} else {
|
||||
cbm_unsetenv("CBM_CACHE_DIR");
|
||||
}
|
||||
th_rmtree(parent);
|
||||
th_rmtree(cache);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2134: re-indexing a root WITHOUT `name` must update the project that
|
||||
* already owns that root_path, not fork a second index under the
|
||||
* path-derived name (both then list the same root_path and the stale one
|
||||
* keeps being read as fresh). Several owners of one root are ambiguous: the
|
||||
* call must fail loudly and name them instead of guessing or forking. */
|
||||
static int i2134_count_occurrences(const char *haystack, const char *needle) {
|
||||
int count = 0;
|
||||
for (const char *p = haystack ? strstr(haystack, needle) : NULL; p; p = strstr(p + 1, needle)) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
TEST(tool_index_repository_reuses_existing_project_for_root_issue2134) {
|
||||
char repo[CBM_SZ_256];
|
||||
char cache[CBM_SZ_256];
|
||||
snprintf(repo, sizeof(repo), "/tmp/cbm-i2134r-XXXXXX");
|
||||
snprintf(cache, sizeof(cache), "/tmp/cbm-i2134c-XXXXXX");
|
||||
if (!cbm_mkdtemp(repo) || !cbm_mkdtemp(cache)) {
|
||||
FAIL("mkdtemp failed");
|
||||
}
|
||||
char canonical_repo[CBM_SZ_4K]; /* cbm_canonical_path needs >= 4096 bytes */
|
||||
if (!cbm_canonical_path(repo, canonical_repo, sizeof(canonical_repo))) {
|
||||
FAIL("cbm_canonical_path failed");
|
||||
}
|
||||
/* Stored root_path values use forward slashes on every platform. */
|
||||
cbm_normalize_path_sep(canonical_repo);
|
||||
const char *saved_cache = getenv("CBM_CACHE_DIR");
|
||||
char *saved_cache_copy = saved_cache ? cbm_strdup(saved_cache) : NULL;
|
||||
const char *saved_sup = getenv("CBM_INDEX_SUPERVISOR");
|
||||
char *saved_sup_copy = saved_sup ? cbm_strdup(saved_sup) : NULL;
|
||||
cbm_setenv("CBM_CACHE_DIR", cache, 1);
|
||||
cbm_setenv("CBM_INDEX_SUPERVISOR", "0", 1);
|
||||
i1025_write_repo(repo, "root_owner_2134");
|
||||
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
ASSERT_NOT_NULL(srv);
|
||||
|
||||
/* 1. Index once under an explicit name. */
|
||||
char args[CBM_SZ_1K];
|
||||
snprintf(args, sizeof(args), "{\"repo_path\":\"%s\",\"name\":\"named-2134\"}", repo);
|
||||
char *r = cbm_mcp_handle_tool(srv, "index_repository", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(strstr(r, "named-2134"));
|
||||
free(r);
|
||||
|
||||
/* 2. Re-index the same root without a name: must update named-2134. */
|
||||
snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", repo);
|
||||
r = cbm_mcp_handle_tool(srv, "index_repository", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
if (!strstr(r, "named-2134")) {
|
||||
fprintf(stderr, " [2134] reindex without name forked: %.300s\n", r);
|
||||
}
|
||||
ASSERT_NOT_NULL(strstr(r, "named-2134"));
|
||||
free(r);
|
||||
|
||||
/* Every listed project carries its root_path once in structuredContent,
|
||||
* so the canonical root occurring once there means exactly one owner. */
|
||||
r = cbm_mcp_handle_tool(srv, "list_projects", "{\"format\":\"json\"}");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(strstr(r, "\"structuredContent\""));
|
||||
int owners = i2134_count_occurrences(strstr(r, "\"structuredContent\""), canonical_repo);
|
||||
if (owners != 1) {
|
||||
fprintf(stderr, " [2134] %d projects share root %s: %.400s\n", owners, canonical_repo, r);
|
||||
}
|
||||
ASSERT_EQ(owners, 1);
|
||||
free(r);
|
||||
|
||||
/* 3. An explicit second name is the caller's choice; afterwards the root
|
||||
* has two owners, so an unnamed re-index must refuse and list both. */
|
||||
snprintf(args, sizeof(args), "{\"repo_path\":\"%s\",\"name\":\"other-2134\"}", repo);
|
||||
r = cbm_mcp_handle_tool(srv, "index_repository", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(strstr(r, "other-2134"));
|
||||
free(r);
|
||||
snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", repo);
|
||||
r = cbm_mcp_handle_tool(srv, "index_repository", args);
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(strstr(r, "named-2134"));
|
||||
ASSERT_NOT_NULL(strstr(r, "other-2134"));
|
||||
ASSERT_NOT_NULL(strstr(r, "\"isError\":true"));
|
||||
free(r);
|
||||
r = cbm_mcp_handle_tool(srv, "list_projects", "{\"format\":\"json\"}");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_NOT_NULL(strstr(r, "\"structuredContent\""));
|
||||
ASSERT_EQ(i2134_count_occurrences(strstr(r, "\"structuredContent\""), canonical_repo), 2);
|
||||
free(r);
|
||||
|
||||
cbm_mcp_server_free(srv);
|
||||
if (saved_cache_copy) {
|
||||
cbm_setenv("CBM_CACHE_DIR", saved_cache_copy, 1);
|
||||
free(saved_cache_copy);
|
||||
} else {
|
||||
cbm_unsetenv("CBM_CACHE_DIR");
|
||||
}
|
||||
if (saved_sup_copy) {
|
||||
cbm_setenv("CBM_INDEX_SUPERVISOR", saved_sup_copy, 1);
|
||||
free(saved_sup_copy);
|
||||
} else {
|
||||
cbm_unsetenv("CBM_INDEX_SUPERVISOR");
|
||||
}
|
||||
th_rmtree(repo);
|
||||
th_rmtree(cache);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Regression for #604: path scopes architecture totals and content. */
|
||||
TEST(tool_get_architecture_path_scoping) {
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
@@ -14184,6 +14513,146 @@ TEST(tool_detect_changes_finds_nested_untracked_file_and_impact_seed) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Issue #1951: the indexed project root is a SUBDIRECTORY of a normal Git
|
||||
* repository. Git reports changed paths relative to the Git root
|
||||
* ("game/src/math.c"), while graph file_paths are relative to the project
|
||||
* root ("src/math.c"). detect_changes must translate Git-root paths into the
|
||||
* project's coordinate system (diff, hunk and status records alike) and leave
|
||||
* changes outside the project out, or the seed lookup finds nothing. */
|
||||
TEST(tool_detect_changes_subdirectory_project_translates_git_root_paths_issue1951) {
|
||||
char repo[CBM_SZ_4K];
|
||||
snprintf(repo, sizeof(repo), "%s/cbm-detect-subdir-XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(repo));
|
||||
char cache[CBM_SZ_4K];
|
||||
snprintf(cache, sizeof(cache), "%s/cbm-detect-subdir-cache-XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(cache));
|
||||
|
||||
char project_root[CBM_SZ_4K];
|
||||
snprintf(project_root, sizeof(project_root), "%s/game", repo);
|
||||
ASSERT_EQ(cbm_mkdir(project_root), 0);
|
||||
char source_dir[CBM_SZ_4K];
|
||||
snprintf(source_dir, sizeof(source_dir), "%s/src", project_root);
|
||||
ASSERT_EQ(cbm_mkdir(source_dir), 0);
|
||||
char math_source[CBM_SZ_4K];
|
||||
snprintf(math_source, sizeof(math_source), "%s/math.c", source_dir);
|
||||
ASSERT_EQ(th_write_file(math_source, "int add_one(int x) { return x + 1; }\n"
|
||||
"int untouched(void) { return 0; }\n"),
|
||||
0);
|
||||
char use_source[CBM_SZ_4K];
|
||||
snprintf(use_source, sizeof(use_source), "%s/use.c", source_dir);
|
||||
ASSERT_EQ(
|
||||
th_write_file(use_source, "int add_one(int x);\nint use_it(void) { return add_one(4); }\n"),
|
||||
0);
|
||||
char outside_source[CBM_SZ_4K];
|
||||
snprintf(outside_source, sizeof(outside_source), "%s/outside.c", repo);
|
||||
ASSERT_EQ(th_write_file(outside_source, "int outside(void) { return 0; }\n"), 0);
|
||||
|
||||
const char *const init_args[] = {"init", "-q", NULL};
|
||||
const char *const add_args[] = {"add", "-A", NULL};
|
||||
const char *const commit_args[] = {
|
||||
"-c", "user.name=cbm-test",
|
||||
"-c", "user.email=cbm-test@example.invalid",
|
||||
"-c", "commit.gpgsign=false",
|
||||
"commit", "-q",
|
||||
"-m", "fixture",
|
||||
NULL,
|
||||
};
|
||||
ASSERT_EQ(mcp_test_git(repo, init_args), 0);
|
||||
ASSERT_EQ(mcp_test_git(repo, add_args), 0);
|
||||
ASSERT_EQ(mcp_test_git(repo, commit_args), 0);
|
||||
|
||||
/* Worktree edits: a tracked change inside the project (diff + hunk path),
|
||||
* an untracked file inside it (status path) and a change outside it. */
|
||||
ASSERT_EQ(th_write_file(math_source, "int add_one(int x) { return x + 2; }\n"
|
||||
"int untouched(void) { return 0; }\n"),
|
||||
0);
|
||||
char fresh_source[CBM_SZ_4K];
|
||||
snprintf(fresh_source, sizeof(fresh_source), "%s/fresh.c", source_dir);
|
||||
ASSERT_EQ(th_write_file(fresh_source, "int fresh(void) { return 1; }\n"), 0);
|
||||
ASSERT_EQ(th_write_file(outside_source, "int outside(void) { return 1; }\n"), 0);
|
||||
|
||||
const char *saved_cache = getenv("CBM_CACHE_DIR");
|
||||
char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;
|
||||
ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR", cache, 1), 0);
|
||||
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 = "detect-subdir-project";
|
||||
ASSERT_EQ(cbm_store_upsert_project(store, project, project_root), CBM_STORE_OK);
|
||||
cbm_mcp_server_set_project(srv, project);
|
||||
|
||||
cbm_node_t seed = {.project = project,
|
||||
.label = "Function",
|
||||
.name = "add_one",
|
||||
.qualified_name = "fixture.src.math.add_one",
|
||||
.file_path = "src/math.c",
|
||||
.start_line = 1,
|
||||
.end_line = 1};
|
||||
int64_t seed_id = cbm_store_upsert_node(store, &seed);
|
||||
ASSERT_GT(seed_id, 0);
|
||||
/* Same file, untouched line: only hunk scoping (project-relative hunk
|
||||
* paths) keeps it out of the seeds; whole-file fallback would add it. */
|
||||
cbm_node_t untouched = {.project = project,
|
||||
.label = "Function",
|
||||
.name = "untouched",
|
||||
.qualified_name = "fixture.src.math.untouched",
|
||||
.file_path = "src/math.c",
|
||||
.start_line = 2,
|
||||
.end_line = 2};
|
||||
ASSERT_GT(cbm_store_upsert_node(store, &untouched), 0);
|
||||
cbm_node_t caller = {.project = project,
|
||||
.label = "Function",
|
||||
.name = "use_it",
|
||||
.qualified_name = "fixture.src.use.use_it",
|
||||
.file_path = "src/use.c",
|
||||
.start_line = 2,
|
||||
.end_line = 2};
|
||||
int64_t caller_id = cbm_store_upsert_node(store, &caller);
|
||||
ASSERT_GT(caller_id, 0);
|
||||
cbm_edge_t edge = {
|
||||
.project = project, .source_id = caller_id, .target_id = seed_id, .type = "CALLS"};
|
||||
ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);
|
||||
|
||||
char *response =
|
||||
cbm_mcp_handle_tool(srv, "detect_changes",
|
||||
"{\"project\":\"detect-subdir-project\",\"base_branch\":\"HEAD\","
|
||||
"\"scope\":\"impact\",\"depth\":2,\"max_output_tokens\":10000,"
|
||||
"\"format\":\"json\"}");
|
||||
char *inner = extract_text_content(response);
|
||||
yyjson_doc *doc = inner ? yyjson_read(inner, strlen(inner), 0) : NULL;
|
||||
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
|
||||
yyjson_val *changed_files = root ? yyjson_obj_get(root, "changed_files") : NULL;
|
||||
yyjson_val *first_path = changed_files ? yyjson_arr_get(changed_files, 0) : NULL;
|
||||
yyjson_val *second_path = changed_files ? yyjson_arr_get(changed_files, 1) : NULL;
|
||||
yyjson_val *impacted = root ? yyjson_obj_get(root, "impacted") : NULL;
|
||||
yyjson_val *first_impact = impacted ? yyjson_arr_get(impacted, 0) : NULL;
|
||||
bool project_relative_paths =
|
||||
root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 2 && first_path &&
|
||||
second_path && strcmp(yyjson_get_str(first_path), "src/fresh.c") == 0 &&
|
||||
strcmp(yyjson_get_str(second_path), "src/math.c") == 0;
|
||||
bool seed_found = root && yyjson_get_int(yyjson_obj_get(root, "seed_symbols")) == 1;
|
||||
bool impact_found = first_impact && strcmp(yyjson_get_str(yyjson_obj_get(first_impact, "qn")),
|
||||
"fixture.src.use.use_it") == 0;
|
||||
if (!project_relative_paths || !seed_found || !impact_found) {
|
||||
fprintf(stderr, " issue1951 response: %s\n", inner ? inner : "(null)");
|
||||
}
|
||||
|
||||
yyjson_doc_free(doc);
|
||||
free(inner);
|
||||
free(response);
|
||||
cbm_mcp_server_free(srv);
|
||||
restore_cache_dir(saved_cache_copy);
|
||||
free(saved_cache_copy);
|
||||
ASSERT_EQ(th_rmtree(cache), 0);
|
||||
ASSERT_EQ(th_rmtree(repo), 0);
|
||||
|
||||
ASSERT_TRUE(project_relative_paths);
|
||||
ASSERT_TRUE(seed_found);
|
||||
ASSERT_TRUE(impact_found);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(tool_detect_changes_escapes_newline_path_in_tree_and_round_trips_json) {
|
||||
#ifdef _WIN32
|
||||
/* Win32 rejects control characters in filenames, so Windows cannot create
|
||||
@@ -20454,7 +20923,70 @@ TEST(bm25_searches_legacy_four_column_fts_without_error_issue518) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2144: async/status need the daemon's job registry. An in-process server
|
||||
* (index worker, embedder) has no process that outlives the call, so it must
|
||||
* refuse both modes instead of silently running a blocking index. */
|
||||
TEST(index_repository_async_and_status_refused_without_daemon_issue2144) {
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
ASSERT_NOT_NULL(srv);
|
||||
char *async_reply = cbm_mcp_handle_tool(srv, "index_repository",
|
||||
"{\"repo_path\":\"/nonexistent-2144\","
|
||||
"\"async\":true}");
|
||||
char *status_reply = cbm_mcp_handle_tool(srv, "index_repository",
|
||||
"{\"repo_path\":\"/nonexistent-2144\","
|
||||
"\"status\":true}");
|
||||
cbm_mcp_server_free(srv);
|
||||
ASSERT_NOT_NULL(async_reply);
|
||||
ASSERT_NOT_NULL(strstr(async_reply, "\"isError\":true"));
|
||||
ASSERT_NOT_NULL(strstr(async_reply, "daemon"));
|
||||
ASSERT_NOT_NULL(status_reply);
|
||||
ASSERT_NOT_NULL(strstr(status_reply, "\"isError\":true"));
|
||||
ASSERT_NOT_NULL(strstr(status_reply, "daemon"));
|
||||
free(async_reply);
|
||||
free(status_reply);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2144: the tool schema advertises both flags and the description explains
|
||||
* the deadline problem and the polling pattern. */
|
||||
TEST(index_repository_schema_documents_async_polling_issue2144) {
|
||||
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
|
||||
ASSERT_NOT_NULL(srv);
|
||||
char *resp =
|
||||
cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":2144,\"method\":\"tools/list\"}");
|
||||
cbm_mcp_server_free(srv);
|
||||
ASSERT_NOT_NULL(resp);
|
||||
ASSERT_NOT_NULL(strstr(resp, "\"async\":{\"type\":\"boolean\""));
|
||||
ASSERT_NOT_NULL(strstr(resp, "\"status\":{\"type\":\"boolean\""));
|
||||
ASSERT_NOT_NULL(strstr(resp, "per-call deadline"));
|
||||
ASSERT_NOT_NULL(strstr(resp, "poll with status:true"));
|
||||
free(resp);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2144: a notice rides on a JSON payload as a key (content text and
|
||||
* structuredContent together) and on a text payload as a paragraph. */
|
||||
TEST(tool_result_add_notice_keeps_payload_shape_issue2144) {
|
||||
char *object = cbm_mcp_tool_result_add_notice(
|
||||
cbm_mcp_text_result("{\"status\":\"indexed\"}", false), "retry async");
|
||||
char *text =
|
||||
cbm_mcp_tool_result_add_notice(cbm_mcp_text_result("plain failure", true), "retry async");
|
||||
ASSERT_NOT_NULL(object);
|
||||
ASSERT_NOT_NULL(strstr(object, "\"structuredContent\":{\"status\":\"indexed\","
|
||||
"\"notice\":\"retry async\"}"));
|
||||
ASSERT_NOT_NULL(strstr(object, "\"isError\":false"));
|
||||
ASSERT_NOT_NULL(text);
|
||||
ASSERT_NOT_NULL(strstr(text, "plain failure\\n\\nretry async"));
|
||||
ASSERT_NOT_NULL(strstr(text, "\"isError\":true"));
|
||||
free(object);
|
||||
free(text);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(mcp) {
|
||||
RUN_TEST(index_repository_async_and_status_refused_without_daemon_issue2144);
|
||||
RUN_TEST(index_repository_schema_documents_async_polling_issue2144);
|
||||
RUN_TEST(tool_result_add_notice_keeps_payload_shape_issue2144);
|
||||
/* #518/#519 — BM25 prose search */
|
||||
RUN_TEST(bm25_finds_section_by_its_prose_issue518);
|
||||
RUN_TEST(bm25_finds_module_by_promoted_description_issue519);
|
||||
@@ -20503,6 +21035,7 @@ SUITE(mcp) {
|
||||
RUN_TEST(mcp_discovery_defaults_match_runtime_contract);
|
||||
RUN_TEST(mcp_metadata_byte_budget);
|
||||
RUN_TEST(mcp_tools_have_behavior_annotations);
|
||||
RUN_TEST(mcp_tool_annotations_only_mutators_are_writable_issue2118);
|
||||
RUN_TEST(mcp_index_repository_declares_name_override_issue571);
|
||||
RUN_TEST(mcp_tools_array_schemas_have_items);
|
||||
RUN_TEST(mcp_ingest_traces_items_disallow_additional_properties_issue731);
|
||||
@@ -20638,6 +21171,7 @@ SUITE(mcp) {
|
||||
RUN_TEST(tool_trace_reports_engine_saturation_as_lower_bound);
|
||||
RUN_TEST(store_bfs_edge_data_is_skippable_and_bounded);
|
||||
RUN_TEST(tool_trace_call_path_prefers_definition);
|
||||
RUN_TEST(tool_trace_call_path_qn_fallback_frees_name_miss);
|
||||
RUN_TEST(trace_evidence_strategy_class_vocabulary_is_closed);
|
||||
RUN_TEST(tool_trace_path_evidence_is_opt_in_and_class_mapped);
|
||||
RUN_TEST(tool_trace_path_evidence_columns_match_header_issue1542);
|
||||
@@ -20655,6 +21189,8 @@ SUITE(mcp) {
|
||||
RUN_TEST(tool_get_architecture_accepts_project_name_alias_issue640);
|
||||
RUN_TEST(tool_search_graph_accepts_project_name_alias_issue640);
|
||||
RUN_TEST(tool_project_arg_resolves_unique_tail_issue1025);
|
||||
RUN_TEST(tool_project_arg_resolves_non_ascii_folder_issue1827);
|
||||
RUN_TEST(tool_index_repository_reuses_existing_project_for_root_issue2134);
|
||||
RUN_TEST(tool_get_architecture_path_scoping);
|
||||
RUN_TEST(tool_query_graph_missing_query);
|
||||
|
||||
@@ -20755,6 +21291,7 @@ SUITE(mcp) {
|
||||
RUN_TEST(tool_detect_changes_invalid_base_is_an_error);
|
||||
RUN_TEST(tool_detect_changes_preserves_utf8_git_path_and_impact_seed);
|
||||
RUN_TEST(tool_detect_changes_finds_nested_untracked_file_and_impact_seed);
|
||||
RUN_TEST(tool_detect_changes_subdirectory_project_translates_git_root_paths_issue1951);
|
||||
RUN_TEST(tool_detect_changes_escapes_newline_path_in_tree_and_round_trips_json);
|
||||
RUN_TEST(tool_detect_changes_staged_rename_uses_exact_destination_record);
|
||||
RUN_TEST(tool_detect_changes_contained_commands_clean_up_error_and_success);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user