Merge branch 'main' into fix/home-user-symlink-alias

This commit is contained in:
BumaldaOverTheWater94
2026-10-06 13:18:27 -07:00
committed by GitHub
155 changed files with 1303070 additions and 862769 deletions
+7 -2
View File
@@ -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
+3 -1
View File
@@ -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
+2 -2
View File
@@ -29,7 +29,7 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y zlib1g-dev
- name: Initialize CodeQL
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
uses: github/codeql-action/init@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1
with:
languages: c-cpp
build-mode: manual
@@ -38,6 +38,6 @@ jobs:
run: scripts/build.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
uses: github/codeql-action/analyze@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1
with:
category: "/language:c-cpp"
+13 -1
View File
@@ -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'
+1 -1
View File
@@ -27,6 +27,6 @@ jobs:
publish_results: true
- name: Upload SARIF results
uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4
uses: github/codeql-action/upload-sarif@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4
with:
sarif_file: results.sarif
+30 -11
View File
@@ -338,6 +338,7 @@ FOUNDATION_SRCS = \
EXTRACTION_SRCS = \
$(CBM_DIR)/cbm.c \
$(CBM_DIR)/extract_defs.c \
$(CBM_DIR)/callable_sig.c \
$(CBM_DIR)/extract_calls.c \
$(CBM_DIR)/extract_imports.c \
$(CBM_DIR)/extract_usages.c \
@@ -436,6 +437,7 @@ PIPELINE_SRCS = \
src/pipeline/lsp_surface.c \
src/pipeline/pipeline_delta.c \
src/pipeline/path_alias.c \
src/pipeline/laravel_routing.c \
src/pipeline/registry.c \
src/pipeline/pipeline.c \
src/pipeline/pipeline_incremental.c \
@@ -633,6 +635,7 @@ TEST_FOUNDATION_SRCS = \
TEST_EXTRACTION_SRCS = \
tests/test_extraction.c \
tests/test_callable_sig.c \
tests/test_extraction_inheritance.c \
tests/test_extraction_imports.c \
tests/test_parse_coverage.c \
@@ -832,8 +835,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 +950,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 +982,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 +1136,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 +1180,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
+14 -4
View File
@@ -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
@@ -155,6 +155,8 @@ Watcher registration is controlled separately by `auto_watch` (default `true`).
To turn the watcher off entirely, set `config set watcher_enabled false` (default `true`): the background poll thread never starts and no project is registered, while `auto_index` and manual `index_repository` keep working. Unlike `auto_watch` — which is consulted per session — `watcher_enabled` is read once when the background daemon starts, so run `codebase-memory-mcp daemon stop` after changing it; reconnecting your MCP client alone will not restart the daemon. See [docs/CONFIGURATION.md](docs/CONFIGURATION.md#2-cli-managed-runtime-settings).
The watcher follows **git** projects only by default: a project indexed from a directory that is not a git repository is not watched and stays at its last index until you run `index_repository` again. To have such roots polled too, set `config set watch_non_git true` (default `false`, read when the daemon starts): they are then checked on the same cadence with a file-tree scan that uses the indexer's own ignore rules.
### Keeping Up to Date
**Updates run from the install script on every platform, not from inside the running binary.** `codebase-memory-mcp update` validates your flags and then prints the exact command to run:
@@ -183,7 +185,14 @@ Installed through **npm or pip**? Update with your package manager on every plat
codebase-memory-mcp uninstall
```
Removes owned agent config entries, skills, hooks, instructions, and the installed binary. Existing graph indexes are listed and deleted only after confirmation.
Removes owned agent config entries, skills, hooks, instructions, and the installed binary. Existing graph indexes are listed and **kept by default**. `-y`/`--yes`, `-n`/`--no`, and noninteractive input keep them unless `--delete-indexes` is explicitly given. An interactive terminal without that flag is asked separately; the default answer is to keep them.
```bash
codebase-memory-mcp uninstall -y --delete-indexes # also delete every project index
codebase-memory-mcp uninstall --dry-run --delete-indexes # preview; change nothing
```
`--delete-indexes` is explicit consent and takes precedence over `--no`; `--dry-run` always preserves the files. When indexes are kept, uninstall prints their cache directory (`${CBM_CACHE_DIR:-~/.cache/codebase-memory-mcp}`) and how to remove them.
The install script placed beside the binary is **reported, not deleted** — uninstall prints its path and the `rm` command for it. It is left alone on purpose: it may be your own copy, a symlink into a checkout, or managed by a package manager, and an uninstaller should not delete a file it cannot prove it owns.
@@ -630,7 +639,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.
@@ -763,6 +772,7 @@ codebase-memory-mcp config set auto_index true # auto-index on session
codebase-memory-mcp config set auto_index_limit 50000 # max files for auto-index
codebase-memory-mcp config set auto_watch false # don't register background git watcher (default: true)
codebase-memory-mcp config set watcher_enabled false # stop the watcher thread entirely (default: true)
codebase-memory-mcp config set watch_non_git true # also poll non-git project roots (default: false)
codebase-memory-mcp config set index_max_files 250000 # optional per-index source-file limit
codebase-memory-mcp config set index_max_source_mb 16384 # optional per-index source-size limit
codebase-memory-mcp config reset auto_index # reset to default
@@ -785,7 +795,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
+12 -5
View File
@@ -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
+2 -1
View File
@@ -89,6 +89,7 @@ Current keys:
| `auto_index_limit` | `50000` | Maximum file count allowed for automatic indexing of a new project. |
| `auto_watch` | `true` | Register the session's project with the background git watcher on connect. Set `false` to keep a session from registering its project (the watcher still runs for other projects). |
| `watcher_enabled` | `true` | Master switch for the background watcher subsystem. Set `false` to stop the watcher from starting at all — no poll thread and no project registration. Reindex manually with `index_repository` when disabled. |
| `watch_non_git` | `false` | Also poll project roots that are **not git repositories**. By default the watcher only follows git projects, so a project indexed from a plain directory is never refreshed after its first index — reindex it manually with `index_repository`. Set `true` to poll such roots on the same adaptive cadence with a file-tree scan: the indexer's own discovery walk (same skip lists, `.gitignore` and `.cbmignore` rules) hashed over each file's path, size and mtime. Any change reindexes once; paths the indexer skips (including cbm's own `.codebase-memory/` output) never trigger. The first poll after the daemon starts reindexes each such project once, since nothing records which tree state the index holds. The scan walks the whole tree every poll, so it costs more than git polling on very large trees. Read once when the daemon starts, like `watcher_enabled`. |
| `index_max_files` | `off` | Optional maximum number of accepted source files in one discovery run. |
| `index_max_source_mb` | `off` | Optional maximum accepted source size in MiB in one discovery run. |
@@ -214,7 +215,7 @@ 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 one-shot CLI commands use their own current 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 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
File diff suppressed because it is too large Load Diff
+83
View File
@@ -0,0 +1,83 @@
/*
* callable_sig.h — signature-qualified callable identity (#2061).
*
* A callable's graph identity is
*
* callable_qn := base_qn [<tparams>] (params) [cvref]
*
* so overloads that share a base QN (Java/C#/C++/Kotlin/Swift/Scala/ObjC)
* become distinct nodes instead of merging into one node that collects every
* overload's CALLS edges. The `name` column stays the bare name.
*
* Every language selects a mode (cbm_callable_identity). A language whose
* mode is CBM_CALLABLE_ID_NONE keeps its historical QN byte for byte; the
* suffix is applied only where a mode is enabled, and the SAME builder
* (cbm_callable_sig) serves the definition QN and the call-scope QN so the two
* can never disagree.
*
* Suffix contract (what cbm_qn_callable_base_len inverts):
* - it never contains '.', "::" or "->" — the separators every QN leaf
* splitter uses — so a splitter that first strips the suffix finds the
* same leaf as before;
* - it is whitespace-normalized: one space only between two identifier
* characters ("unsigned long", "const T&"), none elsewhere;
* - type spelling: comments, annotations and attributes are dropped;
* qualified type paths keep their last segment (java.util.List -> List,
* std::vector -> vector); "->" in function types is spelled "=>"; a
* variadic/rest marker is "[]" for Java (the JVM array it is) and "~"
* everywhere else; C++ top-level cv-qualifiers are dropped and array
* parameters decay to pointers, as the language itself does;
* - it is at most CBM_CALLABLE_SIG_MAX bytes. A longer signature keeps the
* leading whole parameter entries that fit and ends in "#<16 hex>)", the
* FNV-1a 64 of the full uncapped suffix, so identity is preserved.
*/
#ifndef CBM_CALLABLE_SIG_H
#define CBM_CALLABLE_SIG_H
#include "cbm.h"
#include "arena.h"
#include "tree_sitter/api.h"
#include <stddef.h>
typedef enum {
CBM_CALLABLE_ID_NONE = 0, /* historical base QN, no suffix */
CBM_CALLABLE_ID_TYPED, /* (int,String) */
CBM_CALLABLE_ID_LABELED_TYPED, /* (_:Data,to:URL) Swift */
CBM_CALLABLE_ID_LABELED, /* (_:style:) ObjC selector */
CBM_CALLABLE_ID_ARITY, /* (2) dynamic langs */
} CBMCallableIdentity;
enum { CBM_CALLABLE_SIG_MAX = 200 };
/* The identity mode a language uses for callable QNs. Every language is
* CBM_CALLABLE_ID_NONE until its enable change lands (with its index-format
* bump). Kept as a side table, like cbm_string_dispatch_suffixes, rather than
* a CBMLangSpec field: the ~160 positional lang_specs rows would all have to
* spell the new member under -Wmissing-field-initializers. */
CBMCallableIdentity cbm_callable_identity(CBMLanguage lang);
/* The identity suffix for the callable at `func_node` in the language's own
* mode, or NULL when that mode is NONE (or the node carries no parameter
* information the mode can use). Arena-owned. */
const char *cbm_callable_sig(CBMArena *a, TSNode func_node, const char *source, CBMLanguage lang);
/* Same, with an explicit mode — the builder the enable changes and the golden
* tables exercise before a language is switched on. */
const char *cbm_callable_sig_mode(CBMArena *a, TSNode func_node, const char *source,
CBMLanguage lang, CBMCallableIdentity mode);
/* Length of the base QN, i.e. `qn` without its callable identity suffix; equal
* to strlen(qn) when there is none. Purely syntactic (the inverse of the
* builder's contract above); a bare C++ `operator()` leaf is recognised as a
* name, not a suffix. NULL -> 0. */
size_t cbm_qn_callable_base_len(const char *qn);
/* The inverse anchored to the callable's bare `name` (the node's name
* column): the suffix is stripped only when the base QN is `name` or ends in
* "." / "::" + `name`. Other QN text can end in ')' as well — a Java field
* whose name is its declarator `X = f()`, a make `$(VAR)` target — and only
* the anchor makes the inverse exact on it. Use this form wherever the name
* is known; NULL name -> the unanchored form. */
size_t cbm_qn_callable_base_len_named(const char *qn, const char *name);
#endif /* CBM_CALLABLE_SIG_H */
+5
View File
@@ -243,6 +243,11 @@ void cbm_typeassign_push(CBMTypeAssignArray *arr, CBMArena *a, CBMTypeAssign ta)
arr->items[arr->count++] = ta;
}
void cbm_fieldtype_push(CBMFieldTypeArray *arr, CBMArena *a, CBMFieldType ft) {
GROW_ARRAY(arr, a);
arr->items[arr->count++] = ft;
}
void cbm_stringref_push(CBMStringRefArray *arr, CBMArena *a, CBMStringRef sr) {
GROW_ARRAY(arr, a);
arr->items[arr->count++] = sr;
+47
View File
@@ -246,6 +246,10 @@ typedef struct {
* HTTP_CALLS edge to base + path. Tail fields: zero-init stays valid. */
const char *http_client;
const char *http_base_url;
/* Callable identity (#2061): offset of the signature suffix inside
* qualified_name (base QN = the first qn_sig_off bytes); 0 = no suffix.
* Always 0 until a language enables its callable_identity mode. */
uint32_t qn_sig_off;
} CBMDefinition;
/* Argument captured from a call expression */
@@ -304,10 +308,20 @@ typedef struct {
// guard's unique-name exemption. Default false.
} CBMCall;
// What an import statement names, when the syntax says so. Only PHP's
// `use function` / `use const` set a non-default kind today: they name a
// namespace MEMBER, so they must never be mapped to a class file (#1186).
typedef enum {
CBM_IMPORT_KIND_DEFAULT = 0, // module / class / namespace (language default)
CBM_IMPORT_KIND_FUNCTION, // PHP `use function A\b`
CBM_IMPORT_KIND_CONST, // PHP `use const A\B`
} CBMImportKind;
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)
CBMImportKind kind; // CBM_IMPORT_KIND_DEFAULT unless the syntax names a member kind
} CBMImport;
typedef enum {
@@ -405,6 +419,17 @@ typedef struct {
CBMChannelDirection direction;
} CBMChannel;
/* Python: one annotated instance field of a class -- `x: T` or `x: T = v` in
* the class body, `self.x: T = v` in __init__, or `self.x = p` where `p` is an
* annotated __init__ parameter. Not a graph node: it only carries the field's
* declared type to the cross-file LSP, so `obj.x.m()` on a class imported
* from another file can be typed (#1277). */
typedef struct {
const char *class_qn; // QN of the owning class
const char *field_name; // attribute name
const char *type_text; // raw annotation text, resolved later per file
} CBMFieldType;
// Rust: impl Trait for Struct
typedef struct {
const char *trait_name; // trait name (raw text)
@@ -431,6 +456,10 @@ typedef struct {
uint32_t site_start_byte; // exact source occurrence; end > start when present
uint32_t site_end_byte; // exclusive byte offset in the source file
CBMSourceOrigin source_origin; // raw source or C-family preprocessed buffer
/* Callable identity (#2061): the resolved overload's signature suffix,
* appended to callee_qn when the edge is written; NULL = none (always,
* until a language enables its callable_identity mode). */
const char *callee_sig;
} CBMResolvedCall;
typedef struct {
@@ -518,6 +547,12 @@ typedef struct {
int cap;
} CBMChannelArray;
typedef struct {
CBMFieldType *items;
int count;
int cap;
} CBMFieldTypeArray;
// Full extraction result for one file.
typedef struct CBMFileResult {
CBMArena arena; // owns local memory; composites may also retain child arenas below
@@ -536,6 +571,7 @@ typedef struct CBMFileResult {
CBMStringRefArray string_refs; // URL/config string literals from AST
CBMInfraBindingArray infra_bindings; // topic→URL pairs from IaC configs
CBMChannelArray channels; // Socket.IO / EventEmitter pub/sub participation
CBMFieldTypeArray field_types; // Python: annotated instance fields (#1277)
const char *module_qn; // module qualified name
const char *namespace_name; // declared namespace/package (Java/Kotlin/C#/PHP), NULL if none
@@ -606,6 +642,11 @@ typedef struct CBMFileResult {
// by cbm_free_result(); ordinary single-file results leave these zeroed.
struct CBMFileResult **owned_results;
int owned_result_count;
/* The file's own doc, set on its File node: the Go package comment or
* the Rust inner docs (//!). NULL for other languages and undocumented
* files. */
const char *module_doc;
} CBMFileResult;
// --- Enclosing function cache ---
@@ -692,6 +733,11 @@ typedef struct {
/* How many nodes the unified walk actually visited (whether or not it ran
* out of budget) — the measurement the budget has to be expressed in. */
uint32_t walk_nodes_visited;
/* Doc-comment lookup state (extract_defs.c), NULL until first used and
* allocated in `scratch`: the memo of parents' child arrays and the Perl
* POD section index. */
void *doc_memo;
void *doc_pod_index;
} CBMExtractCtx;
// --- Public API ---
@@ -892,6 +938,7 @@ void cbm_rw_push(CBMRWArray *arr, CBMArena *a, CBMReadWrite rw);
void cbm_typerefs_push(CBMTypeRefArray *arr, CBMArena *a, CBMTypeRef tr);
void cbm_envaccess_push(CBMEnvAccessArray *arr, CBMArena *a, CBMEnvAccess ea);
void cbm_typeassign_push(CBMTypeAssignArray *arr, CBMArena *a, CBMTypeAssign ta);
void cbm_fieldtype_push(CBMFieldTypeArray *arr, CBMArena *a, CBMFieldType ft);
void cbm_stringref_push(CBMStringRefArray *arr, CBMArena *a, CBMStringRef sr);
void cbm_infrabinding_push(CBMInfraBindingArray *arr, CBMArena *a, CBMInfraBinding ib);
void cbm_impltrait_push(CBMImplTraitArray *arr, CBMArena *a, CBMImplTrait it);
File diff suppressed because it is too large Load Diff
+29 -5
View File
@@ -1205,7 +1205,29 @@ static void parse_wolfram_imports(CBMExtractCtx *ctx) {
// require/include forms remain `expression_statement`s and are still handled by
// the text fallback. Take the first qualified_name/name descendant of each
// clause as the module path.
static void emit_php_use_clause(CBMExtractCtx *ctx, TSNode clause, const char *group_prefix) {
// `use function` / `use const` carry the keyword as an anonymous direct child
// of the declaration (flat form) or of the clause (grouped form
// `use A\{function f, const C, K}`). DEFAULT when neither is present.
static CBMImportKind php_use_kind(TSNode node) {
uint32_t n = ts_node_child_count(node);
for (uint32_t i = 0; i < n; i++) {
TSNode c = ts_node_child(node, i);
if (ts_node_is_named(c)) {
continue;
}
const char *k = ts_node_type(c);
if (strcmp(k, "function") == 0) {
return CBM_IMPORT_KIND_FUNCTION;
}
if (strcmp(k, "const") == 0) {
return CBM_IMPORT_KIND_CONST;
}
}
return CBM_IMPORT_KIND_DEFAULT;
}
static void emit_php_use_clause(CBMExtractCtx *ctx, TSNode clause, const char *group_prefix,
CBMImportKind decl_kind) {
CBMArena *a = ctx->arena;
// The path node is the qualified_name / namespace_name / name child.
TSNode path_node = clause;
@@ -1230,12 +1252,14 @@ static void emit_php_use_clause(CBMExtractCtx *ctx, TSNode clause, const char *g
TSNode alias = ts_node_child_by_field_name(clause, TS_FIELD("alias"));
const char *local =
!ts_node_is_null(alias) ? cbm_node_text(a, alias, ctx->source) : path_last(a, path);
CBMImport imp = {.local_name = local, .module_path = path};
CBMImportKind kind = decl_kind != CBM_IMPORT_KIND_DEFAULT ? decl_kind : php_use_kind(clause);
CBMImport imp = {.local_name = local, .module_path = path, .kind = kind};
cbm_imports_push(&ctx->result->imports, a, imp);
}
static void emit_php_use_decl(CBMExtractCtx *ctx, TSNode decl) {
CBMArena *a = ctx->arena;
const CBMImportKind decl_kind = php_use_kind(decl);
// Grouped form: namespace_use_group with a leading prefix qualified_name.
TSNode group = decl;
if (find_first_descendant_of(decl, "namespace_use_group", &group)) {
@@ -1257,7 +1281,7 @@ static void emit_php_use_decl(CBMExtractCtx *ctx, TSNode decl) {
const char *ck = ts_node_type(clause);
if (strcmp(ck, "namespace_use_group_clause") == 0 ||
strcmp(ck, "namespace_use_clause") == 0) {
emit_php_use_clause(ctx, clause, prefix);
emit_php_use_clause(ctx, clause, prefix, decl_kind);
}
}
return;
@@ -1268,13 +1292,13 @@ static void emit_php_use_decl(CBMExtractCtx *ctx, TSNode decl) {
for (uint32_t i = 0; i < dc; i++) {
TSNode clause = ts_node_named_child(decl, i);
if (strcmp(ts_node_type(clause), "namespace_use_clause") == 0) {
emit_php_use_clause(ctx, clause, NULL);
emit_php_use_clause(ctx, clause, NULL, decl_kind);
any = true;
}
}
if (!any) {
// Some grammar versions inline the path directly under the declaration.
emit_php_use_clause(ctx, decl, NULL);
emit_php_use_clause(ctx, decl, NULL, decl_kind);
}
}
+84
View File
@@ -1025,6 +1025,53 @@ static const CBMType *c_resolve_name_to_type(CLSPContext *ctx, const char *name)
return cbm_type_named(ctx->arena, name);
}
/* Resolve the class of a qualified member `Scope::member` -- scope_qn is the
* dotted scope ("SecdManager", "ns.Widget") -- to the QN of ONE registered
* class, or NULL. The bare and caller-module spellings come first. A class
* declared in another file is registered under that file's module
* ("<proj>.app.src.SecdManager.SecdManager"), which neither spelling reaches,
* so then every registered type whose QN ends in ".<scope_qn>" at a segment
* boundary is a candidate. More than one distinct candidate (two libraries
* each declaring `Twin`) names no single class: the call stays unresolved
* rather than bind one of them by guess. */
static const char *c_resolve_scope_class_qn(CLSPContext *ctx, const char *scope_qn) {
if (!ctx->registry || !scope_qn || !scope_qn[0]) {
return NULL;
}
if (cbm_registry_lookup_type(ctx->registry, scope_qn)) {
return scope_qn;
}
if (ctx->module_qn) {
const char *mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, scope_qn);
if (cbm_registry_lookup_type(ctx->registry, mod_qn)) {
return mod_qn;
}
}
const char *last_dot = strrchr(scope_qn, '.');
const char *short_name = last_dot ? last_dot + 1 : scope_qn;
size_t scope_len = strlen(scope_qn);
const char *found = NULL;
CBMTypeShortIter it;
cbm_registry_types_by_short_name_chain(ctx->registry, short_name, &it);
int i;
while ((i = cbm_type_short_iter_next(&it)) >= 0) {
const char *q = it.reg->types[i].qualified_name;
size_t qlen = q ? strlen(q) : 0;
if (qlen <= scope_len || q[qlen - scope_len - 1] != '.' ||
strcmp(q + qlen - scope_len, scope_qn) != 0) {
continue;
}
if (found && strcmp(found, q) != 0) {
return NULL;
}
found = q;
}
return found;
}
static const CBMRegisteredFunc *c_lookup_scope_member(CLSPContext *ctx, const char *class_qn,
const char *member_name);
// ============================================================================
// c_parse_type_node: AST type node -> CBMType
// ============================================================================
@@ -1821,6 +1868,16 @@ static const CBMType *c_eval_expr_type_inner(CLSPContext *ctx, TSNode node) {
}
}
}
// Class::member of a class declared in another file: its signature
// carries the return type a chained or auto receiver dispatches on.
const char *scope_class =
c_resolve_scope_class_qn(ctx, cbm_arena_strndup(ctx->arena, qn, prefix_len));
const CBMRegisteredFunc *sm =
scope_class ? c_lookup_scope_member(ctx, scope_class, dot + 1) : NULL;
if (sm && sm->signature) {
return sm->signature;
}
}
return cbm_type_unknown();
@@ -2860,6 +2917,15 @@ const CBMRegisteredFunc *c_lookup_member(CLSPContext *ctx, const char *type_qn,
return c_lookup_member_depth(ctx, type_qn, member_name, 0);
}
/* A member of a class c_resolve_scope_class_qn already pinned down: direct,
* then through its aliases and base classes. Entering below depth 0 skips the
* short-name fallback, which would re-anchor the lookup onto a same-named
* class elsewhere -- the scope names exactly this class. */
static const CBMRegisteredFunc *c_lookup_scope_member(CLSPContext *ctx, const char *class_qn,
const char *member_name) {
return c_lookup_member_depth(ctx, class_qn, member_name, 1);
}
// True if any BASE class of type_qn (not type_qn itself) declares member_name —
// i.e. a method found directly on type_qn is an OVERRIDE of an inherited method.
// This mirrors the existing virtual-dispatch notion (a derived override of a base
@@ -4142,6 +4208,24 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
goto recurse;
}
}
// Class::method of a class declared in another file (#1153).
if (dot) {
const char *scope_class = c_resolve_scope_class_qn(
ctx, cbm_arena_strndup(ctx->arena, qn, (size_t)(dot - qn)));
const CBMRegisteredFunc *sm = NULL;
if (scope_class) {
sm = cbm_registry_lookup_method_by_types(ctx->registry, scope_class,
dot + 1, arg_types, arg_count);
if (!sm) {
sm = c_lookup_scope_member(ctx, scope_class, dot + 1);
}
}
if (sm) {
c_emit_resolved_call_at(ctx, sm->qualified_name, "lsp_scoped", 0.95f,
node);
goto recurse;
}
}
c_emit_unresolved_call(ctx, qn, "scoped_not_in_registry");
}
goto recurse;
+3
View File
@@ -99,6 +99,9 @@ typedef struct {
* a decorator rebinds the function name, so the undecorated definition is
* not automatically an exact callable-value target. */
const char **decorators;
/* Callable identity (#2061): signature suffix of this def's graph QN;
* qualified_name stays the base QN. NULL = none (always, until enabled). */
const char *sig;
} CBMLSPDef;
// Parse source, build registry from defs + stdlib, run LSP.
+42
View File
@@ -4965,6 +4965,47 @@ static const char **py_split_pipe(CBMArena *arena, const char *text) {
return out;
}
/* Split a class def's field_defs ("name:QN|name:QN", built by the Python
* field fold in pass_lsp_cross.c) into the parallel NULL-terminated arrays a
* CBMRegisteredType carries. The types are already project QNs, so each one
* becomes a NAMED type verbatim. Without this, `obj.field.method()` on a class
* from another file lost the field's type (#1277); same-file classes get their
* fields from the per-file walk instead. Pure string work: no registry lookup
* happens here, so it is safe inside the type-registration pass. */
static void py_split_field_defs(CBMArena *arena, const char *field_defs, const char ***names_out,
const CBMType ***types_out) {
*names_out = NULL;
*types_out = NULL;
const char **pairs = py_split_pipe(arena, field_defs);
if (!pairs)
return;
int n = 0;
while (pairs[n])
n++;
const char **names =
(const char **)cbm_arena_alloc(arena, (size_t)(n + 1) * sizeof(const char *));
const CBMType **types =
(const CBMType **)cbm_arena_alloc(arena, (size_t)(n + 1) * sizeof(const CBMType *));
if (!names || !types)
return;
int kept = 0;
for (int i = 0; i < n; i++) {
char *colon = strchr(pairs[i], ':');
if (!colon || colon == pairs[i] || !colon[1])
continue;
*colon = '\0'; /* pairs[i] is this call's own arena copy */
names[kept] = pairs[i];
types[kept] = cbm_type_named(arena, colon + 1);
kept++;
}
if (kept == 0)
return;
names[kept] = NULL;
types[kept] = NULL;
*names_out = names;
*types_out = types;
}
/* Build a registry from CBMLSPDef[] supplied by the caller — covers both
* the source file's own defs and cross-file referenced defs. */
static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRegistry *reg,
@@ -4990,6 +5031,7 @@ static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe
if (d->method_names_str && d->method_names_str[0]) {
rt.method_names = py_split_pipe(arena, d->method_names_str);
}
py_split_field_defs(arena, d->field_defs, &rt.field_names, &rt.field_types);
cbm_registry_add_type(reg, rt);
}
}
+132 -31
View File
@@ -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,
@@ -1965,6 +1978,42 @@ 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);
}
/* Type of a `new_expression`: a bare constructor name follows TS scoping
* (ts_new_bare_class_type), a dotted one is taken as spelled. NULL when the
* node carries no constructor. Shared by expression evaluation and by the
* field-initializer inference in ast_sweep_shapes, so `const t = new C()`
* and `private t = new C()` type the instance identically. */
static const CBMType *ts_new_expression_type(TSLSPContext *ctx, TSNode node) {
TSNode ctor = ts_node_child_by_field_name(node, "constructor", TS_LSP_FIELD_LEN("constructor"));
if (ts_node_is_null(ctor))
return NULL;
char *cname = node_text(ctx, ctor);
if (!cname)
return NULL;
return strchr(cname, '.') == NULL ? ts_new_bare_class_type(ctx, cname)
: cbm_type_named(ctx->arena, cname);
}
static const CBMRegisteredFunc *ts_lookup_namespace_call(TSLSPContext *ctx, const char *object_name,
const char *method_name, TSNode args,
bool *out_is_import) {
@@ -2190,20 +2239,9 @@ const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {
result = lookup_member_type(ctx, recv, pname);
}
} else if (strcmp(kind, "new_expression") == 0) {
TSNode ctor =
ts_node_child_by_field_name(node, "constructor", TS_LSP_FIELD_LEN("constructor"));
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);
}
}
}
const CBMType *nt = ts_new_expression_type(ctx, node);
if (nt)
result = nt;
} else if (strcmp(kind, "call_expression") == 0) {
TSNode fn = ts_node_child_by_field_name(node, "function", TS_LSP_FIELD_LEN("function"));
if (!ts_node_is_null(fn)) {
@@ -2435,14 +2473,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;
}
@@ -5336,6 +5367,76 @@ static const CBMType *interface_method_signature_from_ast(TSLSPContext *ctx, TSN
return cbm_type_func(ctx->arena, NULL, param_count ? param_types : NULL, return_types);
}
/* Parsed type of a `type_annotation` field (`: T`), or unknown. */
static const CBMType *ts_annotation_field_type(TSLSPContext *ctx, TSNode owner) {
TSNode tann = ts_node_child_by_field_name(owner, "type", TS_LSP_FIELD_LEN("type"));
if (ts_node_is_null(tann))
return cbm_type_unknown();
TSNode tn =
strcmp(ts_node_type(tann), "type_annotation") == 0 ? ts_node_named_child(tann, 0) : tann;
return ts_node_is_null(tn) ? cbm_type_unknown() : ts_parse_type_node(ctx, tn);
}
/* Declared type of a class field (`public_field_definition`) or interface
* property: the annotation when present, else, for an unannotated field
* initialised with `new C()`, the type of that instance (#514). No other
* initializer is inferred: `new` names its type exactly, arbitrary
* expressions do not. */
static const CBMType *ts_field_decl_type(TSLSPContext *ctx, TSNode m) {
if (!ts_node_is_null(ts_node_child_by_field_name(m, "type", TS_LSP_FIELD_LEN("type"))))
return ts_annotation_field_type(ctx, m);
TSNode val = ts_node_child_by_field_name(m, "value", TS_LSP_FIELD_LEN("value"));
if (ts_node_is_null(val) || strcmp(ts_node_type(val), "new_expression") != 0)
return cbm_type_unknown();
const CBMType *nt = ts_new_expression_type(ctx, val);
return nt ? nt : cbm_type_unknown();
}
/* A constructor parameter is a TS parameter property, i.e. also declares a
* class field, iff it carries an accessibility modifier, `readonly` or
* `override`. */
static bool ts_param_is_property(TSNode p) {
uint32_t pc = ts_node_child_count(p);
for (uint32_t ci = 0; ci < pc; ci++) {
const char *ck = ts_node_type(ts_node_child(p, ci));
if (strcmp(ck, "accessibility_modifier") == 0 || strcmp(ck, "readonly") == 0 ||
strcmp(ck, "override_modifier") == 0)
return true;
}
return false;
}
/* Append the parameter properties of a `constructor` method_definition to
* the field arrays (#514): `constructor(private readonly svc: Svc)` declares
* field `svc: Svc`, the dominant NestJS injection shape. Any other member is
* ignored. Returns the new field count. */
static int ts_collect_param_properties(TSLSPContext *ctx, TSNode m, const char **names,
const CBMType **types, int count, int cap) {
TSNode mname = ts_node_child_by_field_name(m, "name", TS_LSP_FIELD_LEN("name"));
char *mnm = ts_node_is_null(mname) ? NULL : node_text(ctx, mname);
if (!mnm || strcmp(mnm, "constructor") != 0)
return count;
TSNode params = ts_node_child_by_field_name(m, "parameters", TS_LSP_FIELD_LEN("parameters"));
uint32_t pnc = ts_node_is_null(params) ? 0 : ts_node_named_child_count(params);
for (uint32_t pi = 0; pi < pnc && count < cap; pi++) {
TSNode p = ts_node_named_child(params, pi);
const char *pk = ts_node_type(p);
if ((strcmp(pk, "required_parameter") != 0 && strcmp(pk, "optional_parameter") != 0) ||
!ts_param_is_property(p))
continue;
TSNode pat = ts_node_child_by_field_name(p, "pattern", TS_LSP_FIELD_LEN("pattern"));
if (ts_node_is_null(pat) || strcmp(ts_node_type(pat), "identifier") != 0)
continue;
char *pnm = node_text(ctx, pat);
if (!pnm)
continue;
names[count] = pnm;
types[count] = ts_annotation_field_type(ctx, p);
count++;
}
return count;
}
// AST sweep: walk class/interface bodies to collect field names+types and refine
// embedded_types / type_param_names.
static void ast_sweep_shapes(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *reg) {
@@ -5448,24 +5549,24 @@ static void ast_sweep_shapes(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *re
if (strcmp(mk, "public_field_definition") == 0 ||
strcmp(mk, "property_signature") == 0) {
TSNode fname = ts_node_child_by_field_name(m, "name", TS_LSP_FIELD_LEN("name"));
TSNode ftype = ts_node_child_by_field_name(m, "type", TS_LSP_FIELD_LEN("type"));
if (ts_node_is_null(fname))
continue;
char *fnm = node_text(ctx, fname);
if (!fnm)
continue;
const CBMType *ft = cbm_type_unknown();
if (!ts_node_is_null(ftype)) {
TSNode tch = ts_node_named_child(ftype, 0);
if (!ts_node_is_null(tch))
ft = ts_parse_type_node(ctx, tch);
}
field_names[field_count] = fnm;
field_types[field_count] = ft;
field_types[field_count] = ts_field_decl_type(ctx, m);
field_count++;
continue;
}
// Constructor parameter properties are class fields too (#514).
if (!is_interface && strcmp(mk, "method_definition") == 0) {
field_count =
ts_collect_param_properties(ctx, m, field_names, field_types, field_count, 63);
continue;
}
// Interface method signature: `methodName(params): ReturnType;`
// Or class method declaration in `.d.ts` ambient mode.
if (is_interface && (strcmp(mk, "method_signature") == 0)) {
+21 -1
View File
@@ -677,8 +677,28 @@ CBMRegisteredType *cbm_registry_type_for_update(CBMTypeRegistry *head, const cha
for (const CBMTypeRegistry *r = head->fallback; r; r = r->fallback) {
const CBMRegisteredType *base = lookup_type_self(r, qualified_name);
if (base) {
CBMRegisteredType copy = *base;
/* Field refinements overwrite entries in this array. The type
* objects remain immutable, but the writable overlay must own
* the pointer array rather than mutate its shared fallback. */
if (base->field_types) {
size_t count = 0;
/* Types are parallel to names; a named field may have no
* type, so an interior NULL does not terminate that array. */
while (base->field_names ? base->field_names[count] != NULL
: base->field_types[count] != NULL) {
count++;
}
const CBMType **field_types = (const CBMType **)cbm_arena_alloc(
head->arena, (count + 1) * sizeof(*field_types));
if (!field_types) {
return NULL;
}
memcpy(field_types, base->field_types, (count + 1) * sizeof(*field_types));
copy.field_types = field_types;
}
int before = head->type_count;
cbm_registry_add_type(head, *base);
cbm_registry_add_type(head, copy);
if (head->type_count == before + 1) {
return &head->types[before];
}
+3
View File
@@ -40,6 +40,9 @@ typedef struct {
* remain NULL when raw cross-file provenance is ambiguous; the Rust trait
* flag still prevents that method from being mistaken for inherent. */
const char *impl_trait_qn;
/* Callable identity (#2061): this overload's signature suffix; its graph
* QN is qualified_name + sig. NULL = none (always, until enabled). */
const char *sig;
} CBMRegisteredFunc;
// Registered type with fields and method names.
+9
View File
@@ -357,6 +357,7 @@ static void cr_walk(cr_ctx_t *c, CBMFileResult *r) {
cr_str(c, &r->resolved_calls.items[i].callee_qn);
cr_str(c, &r->resolved_calls.items[i].strategy);
cr_str(c, &r->resolved_calls.items[i].reason);
cr_str(c, &r->resolved_calls.items[i].callee_sig);
}
cr_array(c, (void **)&r->string_refs.items, r->string_refs.count, sizeof(CBMStringRef));
for (int i = 0; i < r->string_refs.count && r->string_refs.items; i++) {
@@ -377,6 +378,12 @@ static void cr_walk(cr_ctx_t *c, CBMFileResult *r) {
cr_str(c, &r->channels.items[i].transport);
cr_str(c, &r->channels.items[i].enclosing_func_qn);
}
cr_array(c, (void **)&r->field_types.items, r->field_types.count, sizeof(CBMFieldType));
for (int i = 0; i < r->field_types.count && r->field_types.items; i++) {
cr_str(c, &r->field_types.items[i].class_qn);
cr_str(c, &r->field_types.items[i].field_name);
cr_str(c, &r->field_types.items[i].type_text);
}
cr_str(c, &r->module_qn);
cr_str(c, &r->namespace_name);
cr_list(c, &r->exports);
@@ -385,6 +392,7 @@ static void cr_walk(cr_ctx_t *c, CBMFileResult *r) {
cr_list(c, &r->macros);
cr_str(c, &r->error_msg);
cr_str(c, &r->error_ranges);
cr_str(c, &r->module_doc);
cr_blob(c, (const void **)&r->source, r->source ? (size_t)r->source_len + SKIP_ONE : 0);
}
@@ -523,6 +531,7 @@ void cbm_result_compact(CBMFileResult *result) {
tmp.string_refs.cap = tmp.string_refs.count;
tmp.infra_bindings.cap = tmp.infra_bindings.count;
tmp.channels.cap = tmp.channels.count;
tmp.field_types.cap = tmp.field_types.count;
/* A composite kept its per-unit results only so shallow-copied strings
* stayed valid; every string is now a copy of its own. */
+141 -3
View File
@@ -41,6 +41,11 @@ static const lib_pattern_t http_libraries[] = {
/* JavaScript / TypeScript */
{"axios", CBM_SVC_HTTP, NULL},
/* `import Axios from "axios"`: the capitalized default-import binding
* (also axios's own Axios / AxiosInstance types). Matching is
* case-sensitive, so without this entry `Axios.get(url)` fell through to
* the `.get` route-suffix fallback and became a route registration. */
{"Axios", CBM_SVC_HTTP, NULL},
{"superagent", CBM_SVC_HTTP, NULL},
{"needle", CBM_SVC_HTTP, NULL},
{"node-fetch", CBM_SVC_HTTP, NULL},
@@ -752,9 +757,9 @@ static bool has_filesystem_extension(const char *path) {
ext[ext_len] = '\0';
static const char *const hard_file_exts[] = {
".cfg", ".conf", ".credentials", ".crt", ".db", ".env",
".ini", ".key", ".pem", ".pid", ".properties", ".service",
".sock", ".socket", ".sqlite", ".toml", NULL};
".cfg", ".conf", ".credentials", ".crt", ".db", ".env", ".ini", ".key",
".log", ".md", ".pdf", ".pem", ".pid", ".properties", ".rst", ".service",
".sock", ".socket", ".sqlite", ".toml", ".txt", NULL};
for (int i = 0; hard_file_exts[i]; i++) {
if (path_ext_matches(ext, hard_file_exts[i])) {
return true;
@@ -865,6 +870,139 @@ bool cbm_service_pattern_is_http_route_literal(const char *literal, const char *
return true;
}
/* ── GraphQL operation identity (#598) ─────────────────────────── */
static bool gql_name_start(unsigned char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static bool gql_name_char(unsigned char c) {
return gql_name_start(c) || (c >= '0' && c <= '9');
}
/* Skip one lexical unit whose braces are not structure: a # comment, a "..."
* or """...""" string, or a JS ${...} template interpolation. Returns p
* unchanged when p starts none of them. */
static const char *gql_skip_opaque(const char *p) {
if (*p == '#') {
while (*p && *p != '\n' && *p != '\r') {
p++;
}
return p;
}
if (strncmp(p, "\"\"\"", 3) == 0) {
const char *end = strstr(p + 3, "\"\"\"");
return end ? end + 3 : p + strlen(p);
}
if (*p == '"') {
p++;
while (*p && *p != '"') {
p += (*p == '\\' && p[1]) ? 2 : 1;
}
return *p ? p + 1 : p;
}
if (p[0] == '$' && p[1] == '{') {
int depth = 1;
p += 2;
while (*p && depth > 0) {
depth += (*p == '{') - (*p == '}');
p++;
}
return p;
}
return p;
}
/* Skip GraphQL "ignored tokens" (whitespace, commas, comments). */
static const char *gql_skip_ignored(const char *p) {
for (;;) {
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || *p == ',') {
p++;
}
if (*p != '#') {
return p;
}
p = gql_skip_opaque(p);
}
}
/* Copy the Name token at p (bounded). Returns false when p is not a Name. */
static bool gql_copy_name(const char *p, char *name_buf, size_t name_sz) {
if (!gql_name_start((unsigned char)*p) || !name_buf || name_sz == 0) {
return false;
}
size_t n = 0;
while (gql_name_char((unsigned char)p[n]) && n + 1 < name_sz) {
name_buf[n] = p[n];
n++;
}
name_buf[n] = '\0';
return true;
}
static const char *gql_operation_keyword(const char *tok, size_t len) {
static const char *const kws[] = {"query", "mutation", "subscription", NULL};
for (int i = 0; kws[i]; i++) {
if (strlen(kws[i]) == len && strncmp(tok, kws[i], len) == 0) {
return kws[i];
}
}
return NULL;
}
bool cbm_service_pattern_graphql_operation(const char *doc, const char **op_type, char *name_buf,
size_t name_sz) {
*op_type = "operation";
if (name_buf && name_sz > 0) {
name_buf[0] = '\0';
}
if (!doc) {
return false;
}
int depth = 0;
bool in_fragment = false;
const char *p = doc;
while (*p) {
const char *q = gql_skip_opaque(p);
if (q != p) {
p = q;
continue;
}
unsigned char c = (unsigned char)*p;
if (c == '{' && depth == 0 && !in_fragment) {
*op_type = "query"; /* `{ ... }` shorthand is an anonymous query */
return false;
}
if (c == '{' || c == '}') {
depth += (c == '{') ? 1 : -1;
depth = depth < 0 ? 0 : depth;
in_fragment = in_fragment && depth > 0;
p++;
continue;
}
if (depth > 0 || in_fragment || !gql_name_start(c)) {
p++;
continue;
}
const char *tok = p;
while (gql_name_char((unsigned char)*p)) {
p++;
}
size_t len = (size_t)(p - tok);
if (len == strlen("fragment") && strncmp(tok, "fragment", len) == 0) {
in_fragment = true;
continue;
}
const char *kw = gql_operation_keyword(tok, len);
if (!kw) {
return false; /* not a GraphQL document (URL, dict key, variable ...) */
}
*op_type = kw;
return gql_copy_name(gql_skip_ignored(p), name_buf, name_sz);
}
return false;
}
/* ── Public API ────────────────────────────────────────────────── */
/* Per-worker TLS cache of cbm_service_pattern_match results.
+14
View File
@@ -12,6 +12,7 @@
#define CBM_SERVICE_PATTERNS_H
#include <stdbool.h>
#include <stddef.h>
/* Edge type returned by pattern match. */
typedef enum {
@@ -77,4 +78,17 @@ const char *cbm_service_pattern_route_method(const char *callee_name);
* Returns NULL if not an async pattern. */
const char *cbm_service_pattern_broker(const char *resolved_qn);
/* GraphQL operation identity of a client call argument (#598).
* Scans `doc` as a GraphQL document (skipping comments, strings, `${...}`
* template interpolations and leading fragment definitions) and reports the
* first operation: *op_type is "query", "mutation" or "subscription" ("query"
* for the `{ ... }` shorthand). Returns true and writes the operation name to
* name_buf when the operation is named. Returns false for an anonymous
* operation, or with *op_type = "operation" when `doc` is not a GraphQL
* document (NULL, a URL, a bare word such as a dict key ...). The operation
* text itself is never copied, so callers can key Routes on a bounded
* identity. */
bool cbm_service_pattern_graphql_operation(const char *doc, const char **op_type, char *name_buf,
size_t name_sz);
#endif /* CBM_SERVICE_PATTERNS_H */
+27 -5
View File
@@ -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`
@@ -29,9 +30,30 @@ The grammars were originally vendored as bare `parser.c`+`scanner.c` with **no r
The table uses `UPSTREAM-RELEASE` because this refresh verified the tagged
upstream release itself but did not independently verify a current registry
pin; it intentionally does not claim `VERIFIED-NVIM` or `VERIFIED-BOTH`.
- **c_sharp** (refreshed 2026-09-25, #1748): byte-for-byte generated bundle
(`parser.c`, `scanner.c`, `tree_sitter/{alloc,array,parser}.h`) from
[tree-sitter/tree-sitter-c-sharp](https://github.com/tree-sitter/tree-sitter-c-sharp)
tag `v0.23.5`, full commit `cac6d5fb595f5811a076336682d5d595ac1c9e85` (ABI 15,
unchanged), replacing `88366631d598`. The refresh picks up upstream's C# 12
collection-expression support (#402, first released in v0.23.4): new named
nodes `collection_expression`, `collection_element`, `expression_element`,
`spread_element` (purely additive; no node type was removed or renamed, and
`scanner.c` is content-identical). Before it, `[...]` literals only parsed as
`element_binding_expression`, so `c ? [] : x` and similar conditionals were
reported as parse_partial. Upstream HEAD (`9150f7d56bb4`, C# 14 support) was
checked and gives identical results on the #1748 cases and the dotnet/runtime
corpus residuals, so the release tag was taken. Upstream's generated files
were copied from the tag checkout; no upstream JS/build code was run. The
existing MIT `LICENSE` is byte-identical to upstream at the tag (SHA-256
`778fb7d63b8c1844da315648c02f325c4713a6f4a5d19644fd413421422776d3`).
Previous vendored copies differed from the pin only by stripped trailing
newlines; the new files keep upstream's bytes exactly. Per-file SHA-256
values are pinned in `scripts/vendored-checksums.txt`. Regression coverage:
the `cs_*_issue1748` tests in `tests/test_parse_coverage.c`.
- **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 `&amp;`/`&#38;` 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.
@@ -107,7 +129,7 @@ row instead.
| bitbake | 14 | tree-sitter-grammars/tree-sitter-bitbake | `a5d04fdb5a69` | VERIFIED-BOTH | ✅ |
| blade | 15 | EmranMR/tree-sitter-blade | `b9436b7b9369` | VERIFIED-BOTH | ✅ |
| c | 15 | tree-sitter/tree-sitter-c | `ae19b676b13b` | VERIFIED-BOTH | ✅ |
| c_sharp | 15 | tree-sitter/tree-sitter-c-sharp | `88366631d598` | VERIFIED-BOTH | ✅ |
| c_sharp | 15 | tree-sitter/tree-sitter-c-sharp | `cac6d5fb595f` | UPSTREAM-RELEASE | ✅ |
| cairo | 14 | tree-sitter-grammars/tree-sitter-cairo | `6238f609bea2` | VERIFIED-NVIM | ✅ |
| capnp | 14 | tree-sitter-grammars/tree-sitter-capnp | `7b0883c03e5e` | VERIFIED-BOTH | ✅ |
| clojure | 14 | sogaiu/tree-sitter-clojure | `e43eff80d17c` | VERIFIED-BOTH | ✅ |
@@ -152,7 +174,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 +247,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 +285,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 |
+620788 -611671
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -418,4 +418,4 @@ bool tree_sitter_c_sharp_external_scanner_scan(void *payload, TSLexer *lexer, co
}
return false;
}
}
@@ -51,4 +51,4 @@ extern void (*ts_current_free)(void *ptr);
}
#endif
#endif // TREE_SITTER_ALLOC_H_
#endif // TREE_SITTER_ALLOC_H_
@@ -60,7 +60,13 @@ extern "C" {
/// Free any memory allocated for this array. Note that this does not free any
/// memory allocated for the array's contents.
#define array_delete(self) _array__delete((self), (void *)(self)->contents, sizeof(*self))
#define array_delete(self) \
do { \
if ((self)->contents) ts_free((self)->contents); \
(self)->contents = NULL; \
(self)->size = 0; \
(self)->capacity = 0; \
} while (0)
/// Push a new `element` onto the end of the array.
#define array_push(self, element) \
@@ -130,12 +136,11 @@ extern "C" {
/// Swap one array with another
#define array_swap(self, other) \
do { \
struct Swap swapped_contents = _array__swap( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
(void *)(other)->contents, &(other)->size, &(other)->capacity \
); \
(self)->contents = swapped_contents.self_contents; \
(other)->contents = swapped_contents.other_contents; \
void *_array_swap_tmp = (void *)(self)->contents; \
(self)->contents = (other)->contents; \
(other)->contents = _array_swap_tmp; \
_array__swap(&(self)->size, &(self)->capacity, \
&(other)->size, &(other)->capacity); \
} while (0)
/// Get the size of the array contents
@@ -188,12 +193,6 @@ extern "C" {
// The `Array` type itself was not altered as a solution in order to avoid breakage
// with existing consumers (in particular, parsers with external scanners).
/// This is not what you're looking for, see `array_delete`.
static inline void _array__delete(void *self, void *contents, size_t self_size) {
if (contents) ts_free(contents);
if (self) memset(self, 0, self_size);
}
/// This is not what you're looking for, see `array_erase`.
static inline void _array__erase(void* self_contents, uint32_t *size,
size_t element_size, uint32_t index) {
@@ -228,31 +227,15 @@ static inline void *_array__assign(void* self_contents, uint32_t *self_size, uin
return new_contents;
}
struct Swap {
void *self_contents;
void *other_contents;
};
/// This is not what you're looking for, see `array_swap`.
// static inline void _array__swap(Array *self, Array *other) {
static inline struct Swap _array__swap(void *self_contents, uint32_t *self_size, uint32_t *self_capacity,
void *other_contents, uint32_t *other_size, uint32_t *other_capacity) {
void *new_self_contents = other_contents;
uint32_t new_self_size = *other_size;
uint32_t new_self_capacity = *other_capacity;
void *new_other_contents = self_contents;
*other_size = *self_size;
*other_capacity = *self_capacity;
*self_size = new_self_size;
*self_capacity = new_self_capacity;
struct Swap out = {
.self_contents = new_self_contents,
.other_contents = new_other_contents,
};
return out;
static inline void _array__swap(uint32_t *self_size, uint32_t *self_capacity,
uint32_t *other_size, uint32_t *other_capacity) {
uint32_t tmp_size = *self_size;
uint32_t tmp_capacity = *self_capacity;
*self_size = *other_size;
*self_capacity = *other_capacity;
*other_size = tmp_size;
*other_capacity = tmp_capacity;
}
/// This is not what you're looking for, see `array_push` or `array_grow_by`.
@@ -344,4 +327,4 @@ static inline void *_array__splice(void *self_contents, uint32_t *size, uint32_t
}
#endif
#endif // TREE_SITTER_ARRAY_H_
#endif // TREE_SITTER_ARRAY_H_
@@ -283,4 +283,4 @@ static inline bool set_contains(const TSCharacterRange *ranges, uint32_t len, in
}
#endif
#endif // TREE_SITTER_PARSER_H_
#endif // TREE_SITTER_PARSER_H_
File diff suppressed because it is too large Load Diff
+229219 -228882
View File
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);
}
+3 -1
View File
@@ -55,9 +55,11 @@ codebase-memory-mcp install # configure all detected coding agents
codebase-memory-mcp --version
codebase-memory-mcp --help
codebase-memory-mcp update # update to latest release
codebase-memory-mcp uninstall # remove agent configs
codebase-memory-mcp uninstall # remove agent configs; keep indexes by default
```
Uninstall keeps project indexes with `--yes`, `--no`, or noninteractive input unless you explicitly add `--delete-indexes`. An interactive terminal without the flag asks separately and defaults to keeping them. `--delete-indexes` overrides `--no`; add `--dry-run` to preview without changing files. Kept indexes remain in the cache directory printed by uninstall.
### CLI Mode
Every MCP tool is also available directly from the command line:
+231 -29
View File
@@ -8,7 +8,7 @@ const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execFileSync } = require('child_process');
const { execFileSync, spawn } = require('child_process');
const { pipeline } = require('stream');
const REPO = 'DeusData/codebase-memory-mcp';
@@ -18,6 +18,20 @@ const MAX_REDIRECTS = 5;
const DOWNLOAD_HOP_TIMEOUT_MS = 120_000;
const CANDIDATE_TIMEOUT_MS = 15_000;
const MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024;
// Release archive resource limits. Keep in sync with the Go wrapper
// (pkg/go/cmd/codebase-memory-mcp/main.go) and the PyPI wrapper (_cli.py).
const MAX_RELEASE_ARCHIVE_BYTES = 256 * 1024 * 1024;
const MAX_ARCHIVE_MEMBERS = 64;
const MAX_ARCHIVE_MEMBER_BYTES = 256 * 1024 * 1024;
const MAX_ARCHIVE_EXPANDED_BYTES = 512 * 1024 * 1024;
const DEFAULT_ARCHIVE_LIMITS = Object.freeze({
compressedBytes: MAX_RELEASE_ARCHIVE_BYTES,
members: MAX_ARCHIVE_MEMBERS,
memberBytes: MAX_ARCHIVE_MEMBER_BYTES,
expandedBytes: MAX_ARCHIVE_EXPANDED_BYTES,
});
// Bytes of tar's own diagnostics kept for the failure message.
const MAX_TAR_STDERR_CHARS = 4096;
const WINDOWS_BINARY_NAME = 'codebase-memory-mcp.exe';
const UNIX_ARCHIVE_NAMES = [
'codebase-memory-mcp',
@@ -90,21 +104,131 @@ function validateExactTarMemberListing(listing, expectedNames) {
}
}
function extractExactTarArchive(
archivePath, destPath, expectedNames, targetName, runFile = execFileSync,
function validateArchiveLimits(limits) {
if (!limits || !(limits.compressedBytes > 0) || !(limits.members > 0) ||
!(limits.memberBytes > 0) || !(limits.expandedBytes > 0)) {
throw new Error('invalid archive resource safety limits');
}
}
function requireCompressedArchiveWithinLimit(archivePath, limits) {
const status = fs.statSync(archivePath);
if (!status.isFile()) {
throw new Error('release archive is not a regular file');
}
if (status.size > limits.compressedBytes) {
throw new Error(
`release archive exceeds the ${limits.compressedBytes}-byte compressed safety limit`,
);
}
}
// Streams one member through `tar -xzOf` into a file this call creates,
// counting every byte against the per-member limit. The file is removed only
// when this call created it: a pre-existing target fails untouched.
function extractTarMemberWithLimit(
archivePath, target, memberName, limits, spawnFile = spawn,
) {
return new Promise((resolve, reject) => {
let fd;
try {
fd = fs.openSync(target, 'wx', 0o600);
} catch (err) {
reject(err);
return;
}
let written = 0;
let failure = null;
let settled = false;
let stderr = '';
const finish = (err) => {
if (settled) return;
settled = true;
try { fs.closeSync(fd); } catch (closeError) { err = err || closeError; }
if (err) {
try { fs.unlinkSync(target); } catch (_) { /* already gone */ }
reject(err);
return;
}
resolve(written);
};
const child = spawnFile('tar', ['-xzOf', archivePath, memberName], {
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
const fail = (err) => {
if (failure) return;
failure = err;
child.kill();
};
child.stdout.on('data', (chunk) => {
if (failure) return;
written += chunk.length;
if (written > limits.memberBytes) {
fail(new Error(
`archive member ${JSON.stringify(memberName)} exceeds the ${limits.memberBytes}-byte expanded safety limit`,
));
return;
}
try {
let offset = 0;
while (offset < chunk.length) {
offset += fs.writeSync(fd, chunk, offset, chunk.length - offset);
}
} catch (err) {
fail(err);
}
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (text) => {
if (stderr.length < MAX_TAR_STDERR_CHARS) stderr += text;
});
child.on('error', (err) => {
failure = failure || err;
// A process that never started (no tar on PATH) has no exit to wait for.
if (child.pid === undefined) finish(failure);
});
child.on('close', (code, signal) => {
const detail = stderr.trim();
let err = failure;
if (!err && signal) {
err = new Error(
`tar was terminated by ${signal} while extracting ${memberName}: ${detail}`,
);
} else if (!err && code !== 0) {
err = new Error(
`tar exited with status ${code} while extracting ${memberName}: ${detail}`,
);
} else if (!err && written === 0) {
err = new Error(`archive member ${memberName} is empty`);
}
finish(err);
});
});
}
async function extractExactTarArchive(
archivePath, destPath, expectedNames, targetName,
runFile = execFileSync, limits = DEFAULT_ARCHIVE_LIMITS, spawnFile = spawn,
) {
validateArchiveLimits(limits);
requireCompressedArchiveWithinLimit(archivePath, limits);
// The exact root namespace is the member bound: its four names lie well
// within MAX_ARCHIVE_MEMBERS, which the zip path enforces by count.
if (expectedNames.length > limits.members) {
throw new Error(`archive namespace exceeds the ${limits.members}-member safety limit`);
}
const listing = runFile('tar', ['-tzf', archivePath], {
encoding: 'utf8',
maxBuffer: MAX_CHECKSUM_MANIFEST_BYTES,
windowsHide: true,
});
validateExactTarMemberListing(listing, expectedNames);
// Extract only the fixed root executable. Even a malformed tar implementation
// cannot write an unvalidated companion member outside the private temp tree.
runFile('tar', ['-xzf', archivePath, '-C', destPath, targetName], {
stdio: 'inherit',
windowsHide: true,
});
// Only the fixed root executable is ever written, through the counted
// writer; the companions are listed but never extracted.
const target = path.join(destPath, targetName);
await extractTarMemberWithLimit(archivePath, target, targetName, limits, spawnFile);
fs.chmodSync(target, 0o755);
}
function downloadHop(url, dest, maxBytes) {
@@ -123,7 +247,11 @@ function downloadHop(url, dest, maxBytes) {
const req = https.get(url, (res) => {
response = res;
res.on('error', (err) => finish(err));
let piped = false;
// Before the body is piped, a response error ends the hop directly;
// afterwards the pipeline reports it, so the partial file is discarded
// before the hop settles.
res.on('error', (err) => { if (!piped) finish(err); });
const redirectCodes = new Set([301, 302, 303, 307, 308]);
if (redirectCodes.has(res.statusCode)) {
const location = res.headers.location;
@@ -149,6 +277,12 @@ function downloadHop(url, dest, maxBytes) {
finish(new Error(`HTTP ${res.statusCode} for ${url}`));
return;
}
const declared = Number(res.headers['content-length']);
if (maxBytes && Number.isFinite(declared) && declared > maxBytes) {
res.destroy();
finish(new Error(`Download exceeds the ${maxBytes}-byte safety limit`));
return;
}
let received = 0;
res.on('data', (chunk) => {
@@ -158,8 +292,20 @@ function downloadHop(url, dest, maxBytes) {
}
});
const file = fs.createWriteStream(dest, { flags: 'w' });
piped = true;
pipeline(res, file, (err) => {
finish(err, { redirect: null });
if (!err) {
finish(null, { redirect: null });
return;
}
// Discard the partial file once its handle is closed (Windows refuses
// to unlink an open file), then report the failure.
const discard = () => {
try { fs.unlinkSync(dest); } catch (_) { /* nothing was written */ }
finish(err);
};
if (file.closed) discard();
else file.once('close', discard);
});
});
req.on('error', (err) => finish(err));
@@ -457,19 +603,37 @@ function installWindowsBinaryAtomically(sourceDir, destDir, verifier = verifyCan
}
}
function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames) {
function extractZipOnWindows(
archivePath, destPath, requiredNames, extractNames,
limits = DEFAULT_ARCHIVE_LIMITS, shell = 'powershell',
) {
validateArchiveLimits(limits);
requireCompressedArchiveWithinLimit(archivePath, limits);
// -EncodedCommand is a constant program. Paths travel only through the child
// environment and are consumed with -LiteralPath, so PowerShell never parses
// user/TEMP path bytes as source code or wildcard syntax.
const script = [
"$ErrorActionPreference = 'Stop'",
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
'$maxMembers = [int]$env:CBM_NPM_MAX_MEMBERS',
'$maxMemberBytes = [long]$env:CBM_NPM_MAX_MEMBER_BYTES',
'$maxExpandedBytes = [long]$env:CBM_NPM_MAX_EXPANDED_BYTES',
'$memberCount = 0',
'$declaredExpanded = [long]0',
'$zip = [System.IO.Compression.ZipFile]::OpenRead($env:CBM_NPM_ARCHIVE_PATH)',
"$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)",
"$requiredNames = @($env:CBM_NPM_REQUIRED_NAMES.Split('|'))",
'$targetCounts = @{}',
'foreach ($requiredName in $requiredNames) { $targetCounts[$requiredName] = 0 }',
'try { foreach ($entry in $zip.Entries) { ' +
'$memberCount = $memberCount + 1; ' +
'if ($memberCount -gt $maxMembers) { ' +
'throw "archive exceeds the $maxMembers-member safety limit" }; ' +
'if ($entry.Length -gt $maxMemberBytes) { ' +
'throw "archive member $($entry.FullName) exceeds the $maxMemberBytes-byte expanded safety limit" }; ' +
'if ($declaredExpanded -gt ($maxExpandedBytes - $entry.Length)) { ' +
'throw "archive exceeds the $maxExpandedBytes-byte aggregate expanded safety limit" }; ' +
'$declaredExpanded = $declaredExpanded + $entry.Length; ' +
"$name = $entry.FullName.Replace('\\', '/'); " +
"$directory = $name.EndsWith('/'); " +
"$segmentsPath = if ($directory) { $name.TrimEnd('/') } else { $name }; " +
@@ -491,27 +655,61 @@ function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames)
'if ($seen.Count -ne $requiredNames.Count) { ' +
'throw "archive does not match the exact release root-file allowlist" }',
"$extractNames = @($env:CBM_NPM_EXTRACT_NAMES.Split('|'))",
'$actualExpanded = [long]0',
'$buffer = New-Object byte[] 65536',
'$extractZip = [System.IO.Compression.ZipFile]::OpenRead($env:CBM_NPM_ARCHIVE_PATH)',
// Copy by hand with a byte counter: ExtractToFile would write whatever the
// compressed stream yields, regardless of the declared size.
'try { foreach ($extractName in $extractNames) { ' +
'$entry = @($extractZip.Entries | Where-Object { $_.FullName -ceq $extractName })[0]; ' +
'[System.IO.Compression.ZipFileExtensions]::ExtractToFile(' +
'$entry, (Join-Path $env:CBM_NPM_DEST_PATH $extractName), $false) ' +
'$targetPath = Join-Path $env:CBM_NPM_DEST_PATH $extractName; ' +
'$remaining = $maxExpandedBytes - $actualExpanded; ' +
'$copied = [long]0; ' +
'$source = $entry.Open(); ' +
'$target = [System.IO.File]::Open($targetPath, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write); ' +
'try { while ($true) { ' +
'$count = $source.Read($buffer, 0, $buffer.Length); ' +
'if ($count -le 0) { break }; ' +
'$copied = $copied + $count; ' +
'if ($copied -gt $maxMemberBytes) { ' +
'throw "archive member $extractName exceeds the $maxMemberBytes-byte actual expanded safety limit" }; ' +
'if ($copied -gt $remaining) { ' +
'throw "archive exceeds the $maxExpandedBytes-byte aggregate actual expanded safety limit" }; ' +
'$target.Write($buffer, 0, $count) } ' +
'} catch { $target.Dispose(); ' +
'Remove-Item -LiteralPath $targetPath -Force -ErrorAction SilentlyContinue; throw ' +
'} finally { $target.Dispose(); $source.Dispose() }; ' +
'if ($copied -ne $entry.Length) { ' +
'Remove-Item -LiteralPath $targetPath -Force -ErrorAction SilentlyContinue; ' +
'throw "archive member $extractName actual size $copied does not match declared size $($entry.Length)" }; ' +
'$actualExpanded = $actualExpanded + $copied ' +
'} } finally { $extractZip.Dispose() }',
].join('; ');
const encoded = Buffer.from(script, 'utf16le').toString('base64');
execFileSync('powershell', [
'-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded,
], {
env: {
...process.env,
CBM_NPM_ARCHIVE_PATH: archivePath,
CBM_NPM_DEST_PATH: destPath,
CBM_NPM_REQUIRED_NAMES: requiredNames.join('|'),
CBM_NPM_EXTRACT_NAMES: extractNames.join('|'),
},
stdio: 'inherit',
windowsHide: true,
});
try {
execFileSync(shell, [
'-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded,
], {
env: {
...process.env,
CBM_NPM_ARCHIVE_PATH: archivePath,
CBM_NPM_DEST_PATH: destPath,
CBM_NPM_REQUIRED_NAMES: requiredNames.join('|'),
CBM_NPM_EXTRACT_NAMES: extractNames.join('|'),
CBM_NPM_MAX_MEMBERS: String(limits.members),
CBM_NPM_MAX_MEMBER_BYTES: String(limits.memberBytes),
CBM_NPM_MAX_EXPANDED_BYTES: String(limits.expandedBytes),
},
encoding: 'utf8',
stdio: ['ignore', 'inherit', 'pipe'],
windowsHide: true,
});
} catch (err) {
// Surface the script's own reason (for example which limit was hit)
// instead of a bare "Command failed".
const detail = err && err.stderr ? String(err.stderr).trim() : '';
throw new Error(detail ? `zip extraction failed: ${detail}` : err.message);
}
}
// Fetch checksums.txt and verify the archive hash.
@@ -592,12 +790,12 @@ async function main() {
const tmpArchive = path.join(tmpDir, `cbm.${ext}`);
try {
await download(url, tmpArchive);
await download(url, tmpArchive, MAX_RELEASE_ARCHIVE_BYTES);
await verifyChecksum(tmpArchive, archive);
// Validate the complete archive namespace, then extract only executables.
if (ext === 'tar.gz') {
extractExactTarArchive(
await extractExactTarArchive(
tmpArchive, tmpDir, archiveNames, binName,
);
} else {
@@ -674,9 +872,13 @@ if (require.main === module || module.parent == null) {
}
module.exports = {
DEFAULT_ARCHIVE_LIMITS,
UNIX_ARCHIVE_NAMES,
WINDOWS_ARCHIVE_NAMES,
WINDOWS_BINARY_NAME,
download,
extractExactTarArchive,
extractZipOnWindows,
installWindowsBinaryAtomically,
validateExactTarMemberListing,
windowsBinaryReady,
+126
View File
@@ -0,0 +1,126 @@
'use strict';
// Small synthetic release archives for the wrapper tests.
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
// The npm wrapper takes the zip path whenever Node reports win32 (see
// getPlatform and `ext` in install.js), so the tar path is unreachable on a
// Windows host and the tar cases would test nothing a user can reach there.
// They cannot even build their fixtures on the Windows runner: the first
// `tar` on its PATH is Git for Windows' GNU tar, which reads a drive-letter
// path such as C:\... as a remote host ("tar (child): Cannot connect to C:
// resolve failed"; every tar case failed that way in the first Windows run),
// while Windows' own bsdtar accepts it. Under WSL Node is a Linux binary,
// takes the tar path with POSIX paths, and these cases run there.
const TAR_PATH_SKIP = process.platform === 'win32'
? 'the npm wrapper never takes the tar path on win32 (it installs the zip asset)'
: false;
// Deterministic, poorly compressible bytes (xorshift32), so a fixture of a
// few hundred KiB still spans several pipe chunks after gzip.
function patternBytes(length, seed = 0x9e3779b9) {
const out = Buffer.alloc(length);
let state = seed >>> 0;
for (let index = 0; index < length; index += 1) {
state ^= state << 13;
state >>>= 0;
state ^= state >>> 17;
state ^= state << 5;
state >>>= 0;
out[index] = state & 0xff;
}
return out;
}
// Writes entries ({ name, data }) into a staging directory under `root` and
// packs them with the system tar, the producer the release itself uses.
function writeTarGz(root, archiveName, entries) {
const stage = fs.mkdtempSync(path.join(root, 'stage-'));
for (const entry of entries) {
fs.writeFileSync(path.join(stage, entry.name), entry.data);
}
const archive = path.join(root, archiveName);
execFileSync(
'tar',
['-czf', archive, '-C', stage, ...entries.map((entry) => entry.name)],
{
env: { ...process.env, COPYFILE_DISABLE: '1' },
stdio: ['ignore', 'ignore', 'inherit'],
windowsHide: true,
},
);
return archive;
}
const CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n += 1) {
let c = n;
for (let k = 0; k < 8; k += 1) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
table[n] = c;
}
return table;
})();
function crc32(buffer) {
let crc = -1;
for (const byte of buffer) {
crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
}
return (crc ^ -1) >>> 0;
}
// entries: [{ name, data, declaredSize = data.length }]; stored (no
// compression). Hand-rolled so the directory can claim a size that differs
// from the bytes the entry carries, which no zip writer would produce.
function buildZip(entries) {
const locals = [];
const centrals = [];
let offset = 0;
for (const entry of entries) {
const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data);
const name = Buffer.from(entry.name, 'utf8');
const declaredSize = entry.declaredSize === undefined
? data.length
: entry.declaredSize;
const crc = crc32(data);
const local = Buffer.alloc(30 + name.length);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(data.length, 18);
local.writeUInt32LE(declaredSize, 22);
local.writeUInt16LE(name.length, 26);
name.copy(local, 30);
const central = Buffer.alloc(46 + name.length);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(20, 4);
central.writeUInt16LE(20, 6);
central.writeUInt32LE(crc, 16);
central.writeUInt32LE(data.length, 20);
central.writeUInt32LE(declaredSize, 24);
central.writeUInt16LE(name.length, 28);
central.writeUInt32LE(offset, 42);
name.copy(central, 46);
locals.push(local, data);
centrals.push(central);
offset += local.length + data.length;
}
const directory = Buffer.concat(centrals);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(entries.length, 8);
end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...locals, directory, end]);
}
module.exports = { TAR_PATH_SKIP, buildZip, patternBytes, writeTarGz };
+350
View File
@@ -0,0 +1,350 @@
'use strict';
const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { Readable } = require('node:stream');
const test = require('node:test');
const vm = require('node:vm');
const {
DEFAULT_ARCHIVE_LIMITS,
UNIX_ARCHIVE_NAMES,
WINDOWS_ARCHIVE_NAMES,
WINDOWS_BINARY_NAME,
extractExactTarArchive,
extractZipOnWindows,
} = require('../install.js');
const {
TAR_PATH_SKIP, buildZip, patternBytes, writeTarGz,
} = require('./archive-fixtures.js');
const EXECUTABLE = 'codebase-memory-mcp';
// Spans several pipe chunks, so an over-limit member is cut off mid-stream.
const LARGE_EXECUTABLE = patternBytes(300 * 1024);
function withScratch(callback) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-npm-archive-test-'));
return Promise.resolve()
.then(() => callback(root))
.finally(() => fs.rmSync(root, { recursive: true, force: true }));
}
function limitsWith(overrides) {
return { ...DEFAULT_ARCHIVE_LIMITS, ...overrides };
}
function releaseEntries(names, executableData) {
return names.map((name) => ({
name,
data: executableData !== undefined && (name === EXECUTABLE || name === WINDOWS_BINARY_NAME)
? executableData
: `payload of ${name}`,
}));
}
function makeDestination(root) {
const destination = path.join(root, 'extract');
fs.mkdirSync(destination);
return destination;
}
// Stands in for the system tar listing where the archive itself is damaged
// on purpose and the real listing would fail before the writer runs.
function fakeTarListing(names) {
return (command, args) => {
assert.equal(command, 'tar');
assert.equal(args[0], '-tzf');
return `${names.join('\n')}\n`;
};
}
function neverLists() {
throw new Error('the listing must not run');
}
test('tar extraction refuses an archive larger than the compressed limit', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const archive = writeTarGz(root, 'release.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES));
const destination = makeDestination(root);
await assert.rejects(
extractExactTarArchive(
archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE,
neverLists, limitsWith({ compressedBytes: 16 }),
),
/16-byte compressed safety limit/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('tar extraction refuses an exact namespace wider than the member limit', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const archive = writeTarGz(root, 'release.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES));
const destination = makeDestination(root);
await assert.rejects(
extractExactTarArchive(
archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE,
neverLists, limitsWith({ members: 2 }),
),
/2-member safety limit/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('tar extraction stops an over-limit member in the counted writer and leaves no file', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const archive = writeTarGz(
root, 'release.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES, LARGE_EXECUTABLE),
);
const destination = makeDestination(root);
// The real listing passes (names only); the limit trips while tar is
// still streaming the executable into the writer.
await assert.rejects(
extractExactTarArchive(
archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE,
undefined, limitsWith({ memberBytes: 64 * 1024 }),
),
/"codebase-memory-mcp" exceeds the 65536-byte expanded safety limit/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('tar extraction leaves a pre-existing target untouched', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const archive = writeTarGz(root, 'release.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES));
const destination = makeDestination(root);
const target = path.join(destination, EXECUTABLE);
fs.writeFileSync(target, 'keep');
await assert.rejects(
extractExactTarArchive(archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE),
/EEXIST/,
);
assert.equal(fs.readFileSync(target, 'utf8'), 'keep');
}));
test('tar extraction leaves no file when tar fails mid-stream', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const complete = writeTarGz(
root, 'complete.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES, LARGE_EXECUTABLE),
);
const bytes = fs.readFileSync(complete);
const archive = path.join(root, 'truncated.tar.gz');
fs.writeFileSync(archive, bytes.subarray(0, Math.floor(bytes.length * 0.6)));
const destination = makeDestination(root);
await assert.rejects(
extractExactTarArchive(
archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE,
fakeTarListing(UNIX_ARCHIVE_NAMES),
),
// Non-zero exit, and tar's own diagnostic text after the colon.
/tar exited with status [1-9]\d* while extracting codebase-memory-mcp: \S/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('tar extraction rejects an empty executable', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const archive = writeTarGz(
root, 'release.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES, Buffer.alloc(0)),
);
const destination = makeDestination(root);
await assert.rejects(
extractExactTarArchive(archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE),
/archive member codebase-memory-mcp is empty/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('tar extraction installs the executable byte-identical with the executable bit set', { skip: TAR_PATH_SKIP }, () =>
withScratch(async (root) => {
const archive = writeTarGz(
root, 'release.tar.gz', releaseEntries(UNIX_ARCHIVE_NAMES, LARGE_EXECUTABLE),
);
const destination = makeDestination(root);
await extractExactTarArchive(archive, destination, UNIX_ARCHIVE_NAMES, EXECUTABLE);
const target = path.join(destination, EXECUTABLE);
assert.ok(fs.readFileSync(target).equals(LARGE_EXECUTABLE));
if (process.platform !== 'win32') {
// Windows has no mode bits; everywhere else the file must be runnable.
assert.equal(fs.statSync(target).mode & 0o111, 0o111);
}
assert.deepEqual(fs.readdirSync(destination), [EXECUTABLE]);
}));
function loadInstallerWithHttps(fakeHttps) {
const installPath = path.join(__dirname, '..', 'install.js');
const source = fs.readFileSync(installPath, 'utf8');
const sandbox = {
Buffer,
URL,
__dirname: path.dirname(installPath),
__filename: installPath,
clearTimeout,
console,
exports: {},
// A parent keeps the postinstall entry point from running on load.
module: { exports: {}, parent: {} },
process,
require: (specifier) => {
if (specifier === './package.json') return { version: '0.0.0-test' };
if (specifier === 'https') return fakeHttps;
return require(specifier);
},
setTimeout,
};
vm.runInNewContext(source, sandbox, { filename: installPath });
return sandbox.module.exports;
}
// Answers every request with one HTTP 200 response shaped by `configure`.
function fakeHttpsServing(configure) {
return {
get(url, callback) {
const request = new EventEmitter();
request.destroy = (err) => { if (err) request.emit('error', err); };
setImmediate(() => {
const response = new Readable({ read() {} });
response.statusCode = 200;
response.headers = {};
configure(response);
callback(response);
});
return request;
},
};
}
test('download refuses a response whose declared length exceeds the limit', () =>
withScratch(async (root) => {
const { download } = loadInstallerWithHttps(fakeHttpsServing((response) => {
response.headers['content-length'] = '9';
response.push(null);
}));
const destination = path.join(root, 'release.tar.gz');
await assert.rejects(
download('https://example.invalid/release.tar.gz', destination, 8),
/8-byte safety limit/,
);
assert.equal(fs.existsSync(destination), false);
}));
test('download refuses a body that exceeds the limit and removes the partial file', () =>
withScratch(async (root) => {
const { download } = loadInstallerWithHttps(fakeHttpsServing((response) => {
response.push(Buffer.alloc(1024, 0x78));
response.push(null);
}));
const destination = path.join(root, 'release.tar.gz');
await assert.rejects(
download('https://example.invalid/release.tar.gz', destination, 8),
/8-byte safety limit/,
);
assert.equal(fs.existsSync(destination), false);
}));
test('download within the limit stores the body', () =>
withScratch(async (root) => {
const { download } = loadInstallerWithHttps(fakeHttpsServing((response) => {
response.headers['content-length'] = '7';
response.push('payload');
response.push(null);
}));
const destination = path.join(root, 'release.tar.gz');
await download('https://example.invalid/release.tar.gz', destination, 1024);
assert.equal(fs.readFileSync(destination, 'utf8'), 'payload');
}));
// The Windows path runs a constant PowerShell program through powershell.exe,
// which only a Windows host provides (pwsh is not a wrapper dependency, and
// no PowerShell is installed on the Unix wrapper hosts), so these cases run
// in the Windows wrapper leg and are skipped elsewhere.
const WINDOWS_ONLY = process.platform === 'win32'
? false
: 'zip extraction runs through powershell.exe, which this host does not provide';
test('Windows zip extraction refuses an archive with more members than the limit', { skip: WINDOWS_ONLY }, () =>
withScratch(async (root) => {
const archive = path.join(root, 'members.zip');
fs.writeFileSync(archive, buildZip([
{ name: 'one', data: 'a' },
{ name: 'two', data: 'b' },
{ name: 'three', data: 'c' },
]));
const destination = makeDestination(root);
assert.throws(
() => extractZipOnWindows(
archive, destination, ['one', 'two', 'three'], ['one'],
limitsWith({ members: 2 }),
),
/2-member safety limit/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('Windows zip extraction refuses a member whose declared size exceeds the limit', { skip: WINDOWS_ONLY }, () =>
withScratch(async (root) => {
const archive = path.join(root, 'member.zip');
fs.writeFileSync(archive, buildZip([
{ name: WINDOWS_BINARY_NAME, data: Buffer.alloc(65, 0x78) },
]));
const destination = makeDestination(root);
assert.throws(
() => extractZipOnWindows(
archive, destination, [WINDOWS_BINARY_NAME], [WINDOWS_BINARY_NAME],
limitsWith({ memberBytes: 64 }),
),
/64-byte expanded safety limit/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('Windows zip extraction stops a member that yields more bytes than it declares', { skip: WINDOWS_ONLY }, () =>
withScratch(async (root) => {
const archive = path.join(root, 'longer.zip');
fs.writeFileSync(archive, buildZip([
{ name: WINDOWS_BINARY_NAME, data: Buffer.alloc(600, 0x78), declaredSize: 10 },
]));
const destination = makeDestination(root);
assert.throws(
() => extractZipOnWindows(
archive, destination, [WINDOWS_BINARY_NAME], [WINDOWS_BINARY_NAME],
limitsWith({ memberBytes: 64 }),
),
/64-byte actual expanded safety limit/,
);
assert.deepEqual(fs.readdirSync(destination), []);
}));
test('Windows zip extraction within the limits installs only the executable', { skip: WINDOWS_ONLY }, () =>
withScratch(async (root) => {
const archive = path.join(root, 'release.zip');
fs.writeFileSync(archive, buildZip(releaseEntries(WINDOWS_ARCHIVE_NAMES)));
const destination = makeDestination(root);
extractZipOnWindows(
archive, destination, WINDOWS_ARCHIVE_NAMES, [WINDOWS_BINARY_NAME],
);
assert.equal(
fs.readFileSync(path.join(destination, WINDOWS_BINARY_NAME), 'utf8'),
`payload of ${WINDOWS_BINARY_NAME}`,
);
assert.deepEqual(fs.readdirSync(destination), [WINDOWS_BINARY_NAME]);
}));
+30 -15
View File
@@ -13,6 +13,7 @@ const {
installWindowsBinaryAtomically,
validateExactTarMemberListing,
} = require('../install.js');
const { TAR_PATH_SKIP, writeTarGz } = require('./archive-fixtures.js');
function exactUnixListing(extra = []) {
return [...UNIX_ARCHIVE_NAMES, ...extra].join('\n') + '\n';
@@ -33,23 +34,37 @@ test('Unix archive validation rejects traversal and unexpected members', () => {
);
});
test('Unix extraction requests only the validated root executable', () => {
const calls = [];
const runner = (command, args) => {
calls.push({ command, args: [...args] });
return calls.length === 1 ? exactUnixListing() : Buffer.alloc(0);
};
test('Unix extraction lists through the system tar and writes only the root executable', { skip: TAR_PATH_SKIP }, async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-npm-extract-test-'));
try {
const archive = writeTarGz(
root, 'release.tar.gz',
UNIX_ARCHIVE_NAMES.map((name) => ({ name, data: `member:${name}` })),
);
const destination = path.join(root, 'extract');
fs.mkdirSync(destination);
const calls = [];
const runner = (command, args) => {
calls.push({ command, args: [...args] });
return exactUnixListing();
};
extractExactTarArchive(
'/tmp/release.tar.gz', '/tmp/extract', UNIX_ARCHIVE_NAMES,
'codebase-memory-mcp', runner,
);
await extractExactTarArchive(
archive, destination, UNIX_ARCHIVE_NAMES, 'codebase-memory-mcp', runner,
);
assert.deepEqual(calls[0].args, ['-tzf', '/tmp/release.tar.gz']);
assert.deepEqual(
calls[1].args,
['-xzf', '/tmp/release.tar.gz', '-C', '/tmp/extract', 'codebase-memory-mcp'],
);
// The listing runner sees the namespace query only; the executable is
// written by the counted `tar -xzOf` writer, never by `tar -x` into the
// tree, so the companions never touch the disk.
assert.deepEqual(calls.map((call) => call.args), [['-tzf', archive]]);
assert.equal(
fs.readFileSync(path.join(destination, 'codebase-memory-mcp'), 'utf8'),
'member:codebase-memory-mcp',
);
assert.deepEqual(fs.readdirSync(destination), ['codebase-memory-mcp']);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
function writeBinary(directory, tag) {
+3 -3
View File
@@ -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
+205 -23
View File
@@ -1,5 +1,6 @@
"""Downloads codebase-memory-mcp on first run, then runs its native entry point."""
import collections
import errno
import hashlib
import json
@@ -42,6 +43,22 @@ _MAX_REDIRECTS = 5
_NETWORK_TIMEOUT_SECONDS = 120
_CANDIDATE_TIMEOUT_SECONDS = 15
_MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024
# Release archive resource limits. Keep in sync with the Go wrapper
# (pkg/go/cmd/codebase-memory-mcp/main.go) and the npm wrapper (install.js).
_MAX_RELEASE_ARCHIVE_BYTES = 256 * 1024 * 1024
_MAX_ARCHIVE_MEMBERS = 64
_MAX_ARCHIVE_MEMBER_BYTES = 256 * 1024 * 1024
_MAX_ARCHIVE_EXPANDED_BYTES = 512 * 1024 * 1024
_ARCHIVE_COPY_CHUNK_BYTES = 64 * 1024
_ArchiveLimits = collections.namedtuple(
"_ArchiveLimits", "compressed_bytes members member_bytes expanded_bytes"
)
_DEFAULT_ARCHIVE_LIMITS = _ArchiveLimits(
compressed_bytes=_MAX_RELEASE_ARCHIVE_BYTES,
members=_MAX_ARCHIVE_MEMBERS,
member_bytes=_MAX_ARCHIVE_MEMBER_BYTES,
expanded_bytes=_MAX_ARCHIVE_EXPANDED_BYTES,
)
_REDIRECT_CODES = frozenset({301, 302, 303, 307, 308})
_RUNTIME_LOCK_NAME = ".codebase-memory-mcp-runtime.lock"
_RUNTIME_LOCK_WAIT_SECONDS = 45
@@ -113,27 +130,50 @@ def _download_https(url: str, dest: str, max_bytes: int = 0) -> None:
with response:
_validate_url_scheme(response.geturl())
declared = (response.headers.get("Content-Length") or "").strip()
# Only plain ASCII digits are a length (str.isdigit also accepts
# characters that int() rejects); anything else is left to the
# byte counter below.
if max_bytes and re.fullmatch(r"[0-9]+", declared):
if int(declared) > max_bytes:
raise RuntimeError(
f"download exceeds the {max_bytes}-byte safety limit"
)
deadline = time.monotonic() + _NETWORK_TIMEOUT_SECONDS
total = 0
with open(dest, "wb") as out:
while True:
if time.monotonic() >= deadline:
raise TimeoutError(
f"download hop timed out: {current_url}"
)
chunk = response.read(65536)
if not chunk:
return
total += len(chunk)
if max_bytes and total > max_bytes:
raise RuntimeError(
f"download exceeds the {max_bytes}-byte safety limit"
)
out.write(chunk)
try:
with open(dest, "wb") as out:
while True:
if time.monotonic() >= deadline:
raise TimeoutError(
f"download hop timed out: {current_url}"
)
chunk = response.read(65536)
if not chunk:
return
total += len(chunk)
if max_bytes and total > max_bytes:
raise RuntimeError(
f"download exceeds the {max_bytes}-byte "
f"safety limit"
)
out.write(chunk)
except BaseException:
# Never leave a partial download behind for a later step to
# mistake for the complete asset.
_remove_quietly(dest)
raise
raise RuntimeError("too many redirects")
def _remove_quietly(path) -> None:
try:
os.unlink(path)
except OSError:
pass
def _verify_candidate(path: Path) -> None:
"""Require a staged native candidate to execute successfully."""
try:
@@ -196,33 +236,157 @@ def _validate_archive_names(names, archive_names, casefold: bool = False):
)
def _validate_archive_limits(limits) -> None:
if (
limits.compressed_bytes <= 0
or limits.members <= 0
or limits.member_bytes <= 0
or limits.expanded_bytes <= 0
):
sys.exit("codebase-memory-mcp: invalid archive resource safety limits")
def _require_compressed_archive_within_limit(archive_path: str, limits) -> None:
status = os.stat(archive_path)
if not stat.S_ISREG(status.st_mode):
sys.exit("codebase-memory-mcp: release archive is not a regular file")
if status.st_size > limits.compressed_bytes:
sys.exit(
f"codebase-memory-mcp: release archive exceeds the "
f"{limits.compressed_bytes}-byte compressed safety limit"
)
def _require_member_count_within_limit(count: int, limits) -> None:
if count > limits.members:
sys.exit(
f"codebase-memory-mcp: archive exceeds the {limits.members}-member "
f"safety limit"
)
def _account_declared_archive_member(
name: str, size: int, declared_expanded: int, limits
) -> int:
"""Check one member's declared size; return the new declared total."""
if size < 0:
sys.exit(
f"codebase-memory-mcp: archive member has a negative declared "
f"size: {name!r}"
)
if size > limits.member_bytes:
sys.exit(
f"codebase-memory-mcp: archive member {name!r} exceeds the "
f"{limits.member_bytes}-byte expanded safety limit"
)
if declared_expanded > limits.expanded_bytes - size:
sys.exit(
f"codebase-memory-mcp: archive exceeds the {limits.expanded_bytes}-byte "
f"aggregate expanded safety limit"
)
return declared_expanded + size
def _copy_archive_member_within_limits(
source, output, name: str, declared_size: int, actual_expanded: int, limits
) -> int:
"""Copy a member while counting bytes; return the new actual total.
Reads stop one byte past the smaller of the member and remaining aggregate
limits, so a member that yields more than it declares can never fill the
disk. The caller removes the target on failure.
"""
remaining = limits.expanded_bytes - actual_expanded
copy_limit = min(limits.member_bytes, remaining)
copied = 0
while True:
wanted = min(_ARCHIVE_COPY_CHUNK_BYTES, copy_limit + 1 - copied)
if wanted <= 0:
break
chunk = source.read(wanted)
if not chunk:
break
copied += len(chunk)
if copied > copy_limit:
break
output.write(chunk)
if copied > limits.member_bytes:
sys.exit(
f"codebase-memory-mcp: archive member {name!r} exceeds the "
f"{limits.member_bytes}-byte actual expanded safety limit"
)
if copied > remaining:
sys.exit(
f"codebase-memory-mcp: archive exceeds the {limits.expanded_bytes}-byte "
f"aggregate actual expanded safety limit"
)
if copied != declared_size:
sys.exit(
f"codebase-memory-mcp: archive member {name!r} actual size {copied} "
f"does not match declared size {declared_size}"
)
return actual_expanded + copied
def _write_archive_member_within_limits(
source, target: str, name: str, declared_size: int, actual_expanded: int, limits
) -> int:
try:
with open(target, "xb") as output:
return _copy_archive_member_within_limits(
source, output, name, declared_size, actual_expanded, limits
)
except BaseException:
_remove_quietly(target)
raise
def _safe_extract_tar(
tf, dest: str, archive_names=(), extract_names=(), ui: bool = False
tf,
dest: str,
archive_names=(),
extract_names=(),
ui: bool = False,
limits=_DEFAULT_ARCHIVE_LIMITS,
):
"""Validate a tar namespace, then extract only its authenticated runtime set."""
_validate_archive_limits(limits)
members = tf.getmembers()
_require_member_count_within_limit(len(members), limits)
declared_expanded = 0
for member in members:
if not member.isfile():
sys.exit(
f"codebase-memory-mcp: refusing unsafe tar entry "
f"(not a regular root file: {member.name!r})"
)
declared_expanded = _account_declared_archive_member(
member.name, member.size, declared_expanded, limits
)
_validate_archive_names([member.name for member in members], archive_names)
runtime_names = list(extract_names)
by_name = {member.name: member for member in members}
dest_abs = os.path.abspath(dest)
actual_expanded = 0
for name in runtime_names:
source = tf.extractfile(by_name[name])
if source is None:
sys.exit(f"codebase-memory-mcp: could not read archive member: {name}")
target = os.path.join(dest_abs, name)
with source, open(target, "xb") as output:
shutil.copyfileobj(source, output)
with source:
actual_expanded = _write_archive_member_within_limits(
source, target, name, by_name[name].size, actual_expanded, limits
)
return tuple(runtime_names)
def _safe_extract_zip(
zf, dest: str, archive_names=(), extract_names=(), ui: bool = False
zf,
dest: str,
archive_names=(),
extract_names=(),
ui: bool = False,
limits=_DEFAULT_ARCHIVE_LIMITS,
):
"""Extract a zipfile after validating its Windows-style namespace.
@@ -230,9 +394,16 @@ def _safe_extract_zip(
members before extraction prevents archive order from selecting the binary
that a portable package-manager shim eventually executes.
"""
_validate_archive_limits(limits)
dest_abs = os.path.abspath(dest)
names = []
for info in zf.infolist():
infos = zf.infolist()
_require_member_count_within_limit(len(infos), limits)
declared_expanded = 0
for info in infos:
declared_expanded = _account_declared_archive_member(
info.filename, info.file_size, declared_expanded, limits
)
raw_name = info.filename
name = raw_name.replace("\\", "/")
segments_name = name[:-1] if name.endswith("/") else name
@@ -266,10 +437,18 @@ def _safe_extract_zip(
# Extract only the validated runtime files. This avoids relying on
# platform-specific zip path rewriting and always creates regular files.
runtime_names = list(extract_names)
actual_expanded = 0
for name in runtime_names:
target = os.path.join(dest_abs, name)
with zf.open(name) as source, open(target, "xb") as output:
shutil.copyfileobj(source, output)
with zf.open(name) as source:
actual_expanded = _write_archive_member_within_limits(
source,
target,
name,
zf.getinfo(name).file_size,
actual_expanded,
limits,
)
return tuple(runtime_names)
@@ -1179,7 +1358,7 @@ def _download(version: str) -> Path:
with tempfile.TemporaryDirectory() as tmp:
tmp_archive = os.path.join(tmp, f"cbm.{ext}")
try:
_download_https(url, tmp_archive)
_download_https(url, tmp_archive, _MAX_RELEASE_ARCHIVE_BYTES)
except (OSError, RuntimeError, urllib.error.URLError) as e:
sys.exit(
f"codebase-memory-mcp: download failed ({e})\n"
@@ -1188,6 +1367,9 @@ def _download(version: str) -> Path:
)
_verify_checksum(tmp_archive, archive, version)
_require_compressed_archive_within_limit(
tmp_archive, _DEFAULT_ARCHIVE_LIMITS
)
bin_name = (
_WINDOWS_BINARY_NAME if os_name == "windows" else "codebase-memory-mcp"
+294
View File
@@ -1,5 +1,6 @@
import errno
import hashlib
import io
import json
import os
import stat
@@ -835,3 +836,296 @@ _cli._publish_runtime_set(
False,
)
class _FakeHttpsResponse:
"""Minimal stand-in for the opener's response: headers, geturl, read."""
def __init__(self, body: bytes, headers=None):
self._body = body
self._offset = 0
self.headers = dict(headers or {})
def __enter__(self):
return self
def __exit__(self, *exc_info):
return False
def geturl(self):
return "https://example.invalid/release.tar.gz"
def read(self, size=-1):
if size is None or size < 0:
size = len(self._body) - self._offset
chunk = self._body[self._offset : self._offset + size]
self._offset += len(chunk)
return chunk
def _limits_with(**overrides):
return _cli._DEFAULT_ARCHIVE_LIMITS._replace(**overrides)
def _write_tar_gz(archive, entries):
with tarfile.open(archive, "w:gz") as tf:
for name, data in entries:
info = tarfile.TarInfo(name)
info.size = len(data)
tf.addfile(info, io.BytesIO(data))
def _write_zip(archive, entries):
with zipfile.ZipFile(archive, "w") as zf:
for name, data in entries:
zf.writestr(name, data)
def _release_entries(names):
return [(name, f"payload of {name}".encode()) for name in names]
class ArchiveLimitTests(unittest.TestCase):
URL = "https://example.invalid/release.tar.gz"
def _download(self, response, destination, max_bytes):
with mock.patch.object(_cli._HTTPS_OPENER, "open", return_value=response):
_cli._download_https(self.URL, destination, max_bytes)
def test_download_rejects_a_declared_length_over_the_limit(self):
with tempfile.TemporaryDirectory() as root:
destination = os.path.join(root, "release.tar.gz")
response = _FakeHttpsResponse(b"", {"Content-Length": "9"})
with self.assertRaises(RuntimeError) as raised:
self._download(response, destination, 8)
self.assertIn("8-byte safety limit", str(raised.exception))
self.assertFalse(os.path.exists(destination))
def test_download_rejects_a_body_over_the_limit_and_removes_the_partial_file(
self,
):
with tempfile.TemporaryDirectory() as root:
destination = os.path.join(root, "release.tar.gz")
response = _FakeHttpsResponse(b"x" * 1024)
with self.assertRaises(RuntimeError) as raised:
self._download(response, destination, 8)
self.assertIn("8-byte safety limit", str(raised.exception))
self.assertFalse(os.path.exists(destination))
def test_download_within_the_limit_stores_the_body(self):
with tempfile.TemporaryDirectory() as root:
destination = os.path.join(root, "release.tar.gz")
response = _FakeHttpsResponse(b"payload", {"Content-Length": "7"})
self._download(response, destination, 1024)
with open(destination, "rb") as stored:
self.assertEqual(stored.read(), b"payload")
def test_download_counts_bytes_when_the_declared_length_is_not_a_number(self):
# A superscript two passes str.isdigit but not int(); such values and
# plain junk must fall through to the byte counter, never crash.
for declared in ("²", "abc", "", "1e3", "-1"):
with self.subTest(declared=declared), tempfile.TemporaryDirectory() as root:
destination = os.path.join(root, "release.tar.gz")
response = _FakeHttpsResponse(b"x" * 1024, {"Content-Length": declared})
with self.assertRaises(RuntimeError) as raised:
self._download(response, destination, 8)
self.assertIn("8-byte safety limit", str(raised.exception))
self.assertFalse(os.path.exists(destination))
with tempfile.TemporaryDirectory() as root:
destination = os.path.join(root, "release.tar.gz")
response = _FakeHttpsResponse(b"payload", {"Content-Length": "²"})
self._download(response, destination, 1024)
with open(destination, "rb") as stored:
self.assertEqual(stored.read(), b"payload")
def test_unix_tar_rejects_more_members_than_the_limit(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "members.tar.gz"
_write_tar_gz(archive, [("one", b"a"), ("two", b"b"), ("three", b"c")])
destination = Path(root) / "extract"
destination.mkdir()
with tarfile.open(archive) as tf, self.assertRaises(SystemExit) as raised:
_cli._safe_extract_tar(
tf,
str(destination),
("one", "two", "three"),
("one",),
limits=_limits_with(members=2),
)
self.assertIn("2-member safety limit", str(raised.exception))
self.assertFalse((destination / "one").exists())
def test_unix_tar_rejects_a_member_declared_over_the_limit(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "member.tar.gz"
_write_tar_gz(archive, [("codebase-memory-mcp", b"x" * 65)])
destination = Path(root) / "extract"
destination.mkdir()
with tarfile.open(archive) as tf, self.assertRaises(SystemExit) as raised:
_cli._safe_extract_tar(
tf,
str(destination),
("codebase-memory-mcp",),
("codebase-memory-mcp",),
limits=_limits_with(member_bytes=64),
)
self.assertIn(
"'codebase-memory-mcp' exceeds the 64-byte expanded safety limit",
str(raised.exception),
)
self.assertFalse((destination / "codebase-memory-mcp").exists())
def test_unix_tar_rejects_a_declared_aggregate_over_the_limit(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "aggregate.tar.gz"
_write_tar_gz(archive, [("one", b"a" * 40), ("two", b"b" * 40)])
destination = Path(root) / "extract"
destination.mkdir()
with tarfile.open(archive) as tf, self.assertRaises(SystemExit) as raised:
_cli._safe_extract_tar(
tf,
str(destination),
("one", "two"),
("one",),
limits=_limits_with(member_bytes=64, expanded_bytes=64),
)
self.assertIn(
"64-byte aggregate expanded safety limit", str(raised.exception)
)
def test_unix_tar_within_the_limits_extracts_only_the_executable(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "release.tar.gz"
_write_tar_gz(archive, _release_entries(_cli._UNIX_ARCHIVE_NAMES))
destination = Path(root) / "extract"
destination.mkdir()
with tarfile.open(archive) as tf:
extracted = _cli._safe_extract_tar(
tf,
str(destination),
_cli._UNIX_ARCHIVE_NAMES,
("codebase-memory-mcp",),
)
self.assertEqual(extracted, ("codebase-memory-mcp",))
self.assertEqual(
(destination / "codebase-memory-mcp").read_bytes(),
b"payload of codebase-memory-mcp",
)
self.assertEqual(os.listdir(destination), ["codebase-memory-mcp"])
def test_archive_copy_stops_a_member_that_yields_more_than_the_limit(self):
source = io.BytesIO(b"x" * 100)
output = io.BytesIO()
with self.assertRaises(SystemExit) as raised:
_cli._copy_archive_member_within_limits(
source,
output,
"member",
100,
0,
_limits_with(member_bytes=64, expanded_bytes=1024),
)
self.assertIn(
"'member' exceeds the 64-byte actual expanded safety limit",
str(raised.exception),
)
# Reading stopped one byte past the limit; nothing beyond it was kept.
self.assertEqual(source.tell(), 65)
self.assertLessEqual(len(output.getvalue()), 64)
def test_archive_copy_rejects_a_member_that_yields_more_than_it_declares(self):
source = io.BytesIO(b"x" * 100)
with self.assertRaises(SystemExit) as raised:
_cli._copy_archive_member_within_limits(
source,
io.BytesIO(),
"member",
10,
0,
_limits_with(member_bytes=1024, expanded_bytes=1024),
)
self.assertIn(
"'member' actual size 100 does not match declared size 10",
str(raised.exception),
)
def test_archive_copy_rejects_an_aggregate_over_the_actual_limit(self):
with self.assertRaises(SystemExit) as raised:
_cli._copy_archive_member_within_limits(
io.BytesIO(b"abcd"),
io.BytesIO(),
"member",
4,
3,
_limits_with(member_bytes=10, expanded_bytes=5),
)
self.assertIn(
"5-byte aggregate actual expanded safety limit", str(raised.exception)
)
def test_archive_member_write_removes_the_partial_file_on_failure(self):
with tempfile.TemporaryDirectory() as root:
target = os.path.join(root, "codebase-memory-mcp")
with self.assertRaises(SystemExit):
_cli._write_archive_member_within_limits(
io.BytesIO(b"x" * 100),
target,
"codebase-memory-mcp",
10,
0,
_limits_with(member_bytes=1024, expanded_bytes=1024),
)
self.assertFalse(os.path.exists(target))
def test_windows_zip_rejects_more_members_than_the_limit(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "members.zip"
_write_zip(archive, [("one", b"a"), ("two", b"b"), ("three", b"c")])
destination = Path(root) / "extract"
destination.mkdir()
with zipfile.ZipFile(archive) as zf, self.assertRaises(SystemExit) as raised:
_cli._safe_extract_zip(
zf,
str(destination),
("one", "two", "three"),
("one",),
limits=_limits_with(members=2),
)
self.assertIn("2-member safety limit", str(raised.exception))
def test_windows_zip_rejects_a_member_declared_over_the_limit(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "member.zip"
_write_zip(archive, [(_cli._WINDOWS_BINARY_NAME, b"x" * 65)])
destination = Path(root) / "extract"
destination.mkdir()
with zipfile.ZipFile(archive) as zf, self.assertRaises(SystemExit) as raised:
_cli._safe_extract_zip(
zf,
str(destination),
(_cli._WINDOWS_BINARY_NAME,),
(_cli._WINDOWS_BINARY_NAME,),
limits=_limits_with(member_bytes=64),
)
self.assertIn("64-byte expanded safety limit", str(raised.exception))
self.assertFalse((destination / _cli._WINDOWS_BINARY_NAME).exists())
def test_windows_zip_within_the_limits_extracts_only_the_executable(self):
with tempfile.TemporaryDirectory() as root:
archive = Path(root) / "release.zip"
_write_zip(archive, _release_entries(_cli._WINDOWS_ARCHIVE_NAMES))
destination = Path(root) / "extract"
destination.mkdir()
with zipfile.ZipFile(archive) as zf:
extracted = _cli._safe_extract_zip(
zf,
str(destination),
_cli._WINDOWS_ARCHIVE_NAMES,
(_cli._WINDOWS_BINARY_NAME,),
)
self.assertEqual(extracted, (_cli._WINDOWS_BINARY_NAME,))
self.assertEqual(
(destination / _cli._WINDOWS_BINARY_NAME).read_bytes(),
b"payload of codebase-memory-mcp.exe",
)
self.assertEqual(os.listdir(destination), [_cli._WINDOWS_BINARY_NAME])
+4
View File
@@ -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)",
+1 -1
View File
@@ -52,7 +52,7 @@ src/git/git_context.c 18
src/main.c 32
src/mcp/compact_out.c 39
src/mcp/index_supervisor.c 8
src/mcp/mcp.c 784
src/mcp/mcp.c 778
src/pipeline/artifact.c 38
src/pipeline/fqn.c 23
src/pipeline/lsp_resolve.h 4
+90 -26
View File
@@ -1,5 +1,5 @@
# codebase-memory-mcp setup script (Windows)
# Default: download pre-built native Windows binary
# Default: install the pre-built native Windows binary through install.ps1
# -FromSource: build from source inside WSL (requires Go + gcc in WSL)
param(
@@ -123,7 +123,7 @@ if ($Help) {
Write-Host ""
Write-Host "Usage: .\setup-windows.ps1 [-FromSource] [-Help]"
Write-Host ""
Write-Host " Default: Download pre-built Windows binary"
Write-Host " Default: Download the pre-built Windows binary through install.ps1"
Write-Host " -FromSource: Build from source inside WSL (requires Go 1.23+ and gcc in WSL)"
Write-Host ""
exit 0
@@ -225,7 +225,7 @@ if ($FromSource) {
exit 1
}
# Configure — WSL binary needs wsl.exe wrapper
# Configure -- WSL binary needs wsl.exe wrapper
$mcpConfig = [ordered]@{
type = "stdio"
command = "wsl.exe"
@@ -243,41 +243,105 @@ if ($FromSource) {
Write-Host " wsl.exe -- rm -rf ~/.cache/codebase-memory-mcp/"
} else {
# --- Download pre-built native Windows binary ---
Write-Host "Fetching latest release..." -ForegroundColor White
# --- Download + install through install.ps1 ---
#
# install.ps1 is the one implementation of "fetch a release and install
# it": it downloads checksums.txt next to the archive, verifies the
# archive's SHA-256 against it, validates the zip layout and only then
# runs the binary's own `install`. This script used to carry a second
# copy of that download, which did not keep up with the installer. It
# now fetches install.ps1 from the same origin and branch it is itself
# served from and hands over to it, so there is exactly one install path.
#
# CBM_DOWNLOAD_URL (the installers' download-base override, for local
# testing) also moves the installer fetch: install.ps1 is then taken from
# "$env:CBM_DOWNLOAD_URL/install.ps1".
$installerUrl = "https://raw.githubusercontent.com/$Repo/main/install.ps1"
if ($env:CBM_DOWNLOAD_URL) {
$installerUrl = $env:CBM_DOWNLOAD_URL.TrimEnd('/') + "/install.ps1"
}
$releaseUrl = "https://api.github.com/repos/$Repo/releases/latest"
$release = Invoke-RestMethod -Uri $releaseUrl -Headers @{ "User-Agent" = "codebase-memory-mcp-setup" }
$tag = $release.tag_name
if (-not $tag) {
Write-Fail "Could not determine latest release."
Write-Host " Check: https://github.com/$Repo/releases"
# Same transport rule as install.ps1: HTTPS, or plain HTTP for a loopback
# authority only (the local test fixture). No redirects are followed: both
# origins serve the installer directly.
try { $installerUri = [Uri]$installerUrl } catch { $installerUri = $null }
$loopbackHttp = (
$installerUri -and $installerUri.IsAbsoluteUri -and
$installerUri.Scheme -eq "http" -and $installerUri.IsLoopback -and
[string]::IsNullOrEmpty($installerUri.UserInfo)
)
if (-not $installerUri -or -not $installerUri.IsAbsoluteUri -or
($installerUri.Scheme -ne "https" -and -not $loopbackHttp) -or
-not [string]::IsNullOrEmpty($installerUri.UserInfo)) {
Write-Fail "Refusing non-HTTPS installer URL: $installerUrl"
exit 1
}
Write-Ok "Latest release: $tag"
$asset = "codebase-memory-mcp-windows-amd64.zip"
$downloadUrl = "https://github.com/$Repo/releases/download/$tag/$asset"
# TLS 1.2+ for the fetch (older Windows PowerShell defaults to TLS 1.0,
# which GitHub rejects). TLS 1.3 only where schannel can negotiate it; see
# the note in install.ps1.
$protocols = [Net.SecurityProtocolType]::Tls12
if ([Environment]::OSVersion.Version.Build -ge 20348 -and
([enum]::GetNames([Net.SecurityProtocolType]) -contains 'Tls13')) {
$protocols = $protocols -bor [Net.SecurityProtocolType]::Tls13
}
[Net.ServicePointManager]::SecurityProtocol = $protocols
Write-Host "Downloading $asset..." -ForegroundColor White
# Create install directory
if (-not (Test-Path $InstallDir)) {
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
# A fresh staging directory of its own with an owner-only DACL, the
# way install.ps1 stages its own download. The ACL is best effort: a
# filesystem that cannot carry one must not fail the install.
$stageDir = Join-Path ([System.IO.Path]::GetTempPath()) "cbm-setup-$(Get-Random)"
New-Item -ItemType Directory -Path $stageDir -Force | Out-Null
try {
$stageAcl = New-Object System.Security.AccessControl.DirectorySecurity
$stageAcl.SetAccessRuleProtection($true, $false)
$stageOwner = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User
$stageAcl.SetOwner($stageOwner)
$stageAcl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(
$stageOwner, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')))
Set-Acl -Path $stageDir -AclObject $stageAcl -ErrorAction Stop
} catch {
Write-Host " note: could not harden the staging directory ACL: $($_.Exception.Message)"
}
$tmpZip = Join-Path $env:TEMP $asset
Invoke-WebRequest -Uri $downloadUrl -OutFile $tmpZip -UseBasicParsing
$installer = Join-Path $stageDir "install.ps1"
$failure = $null
try {
Write-Host "Fetching install.ps1..." -ForegroundColor White
Invoke-WebRequest -Uri $installerUrl -OutFile $installer -UseBasicParsing -MaximumRedirection 0
if (-not (Test-Path -LiteralPath $installer -PathType Leaf) -or
(Get-Item -LiteralPath $installer).Length -eq 0) {
throw "fetched an empty install.ps1 from $installerUrl"
}
Write-Ok "install.ps1 fetched"
# Extract
Expand-Archive -Path $tmpZip -DestinationPath $InstallDir -Force
Remove-Item $tmpZip -Force
Write-Host ""
Write-Host "Installing through install.ps1..." -ForegroundColor White
# The installer configures nothing (--skip-config): agent configuration
# stays this script's interactive step below. It runs in a child host
# of the same PowerShell so its exit code is unambiguous and its global
# settings do not leak into this session. The pre-seeded exit code
# keeps a child that fails to start from reading as success.
$hostExe = (Get-Process -Id $PID).Path
$global:LASTEXITCODE = 1
& $hostExe -NoProfile -ExecutionPolicy Bypass -File $installer "--dir=$InstallDir" --skip-config
if ($LASTEXITCODE -ne 0) {
throw "install.ps1 exited with $LASTEXITCODE"
}
} catch {
$failure = "$_"
} finally {
Remove-Item -Recurse -Force $stageDir -ErrorAction SilentlyContinue
}
if ($failure) {
Write-Fail "Installation through install.ps1 failed: $failure"
exit 1
}
$binaryPath = Join-Path $InstallDir "$BinaryName.exe"
if (-not (Test-Path $binaryPath)) {
Write-Fail "Binary not found at $binaryPath after extraction"
Write-Fail "Binary not found at $binaryPath after installation"
exit 1
}
Write-Ok "Installed to $binaryPath"
+61 -65
View File
@@ -2,14 +2,14 @@
set -euo pipefail
# codebase-memory-mcp setup script (macOS + Linux)
# Default: download pre-built binary from GitHub Release
# Default: install the latest pre-built binary through install.sh
# --from-source: build from source (requires Go + C compiler)
REPO="DeusData/codebase-memory-mcp"
INSTALL_DIR="$HOME/.local/bin"
BINARY_NAME="codebase-memory-mcp"
SOURCE_DIR="$HOME/.local/share/codebase-memory-mcp"
CLEANUP_DIR="" # set by download_binary for EXIT trap
CLEANUP_DIR="" # set by install_release for EXIT trap
# --- Colors ---
@@ -43,7 +43,7 @@ for arg in "$@"; do
--help|-h)
echo "Usage: $0 [--from-source]"
echo ""
echo " Default: Download pre-built binary from GitHub Release"
echo " Default: Download the pre-built binary through install.sh"
echo " --from-source: Clone and build from source (requires Go 1.23+ and a C compiler)"
exit 0
;;
@@ -51,36 +51,6 @@ for arg in "$@"; do
esac
done
# --- Platform detection ---
detect_platform() {
local os arch
os=$(uname -s)
arch=$(uname -m)
case "$os" in
Darwin) os="darwin" ;;
Linux) os="linux" ;;
*) die "Unsupported OS: $os. Use WSL2 on Windows." ;;
esac
case "$arch" in
arm64|aarch64) arch="arm64" ;;
x86_64|amd64)
# On macOS, uname -m returns x86_64 under Rosetta even on Apple Silicon.
# Check the actual hardware to pick the right binary.
if [ "$os" = "darwin" ] && sysctl -n hw.optional.arm64 2>/dev/null | grep -q '1'; then
arch="arm64"
else
arch="amd64"
fi
;;
*) die "Unsupported architecture: $arch" ;;
esac
echo "${os}-${arch}"
}
# --- Prerequisite checks ---
check_download_tool() {
@@ -133,46 +103,74 @@ check_git() {
ok "Git found"
}
# --- Download binary ---
# --- Download + install through install.sh ---
#
# install.sh is the one implementation of "fetch a release and install it": it
# downloads checksums.txt next to the archive, verifies the archive's SHA-256
# against it, checks the archive layout, and only then runs the binary's own
# `install`. This script used to carry a second copy of that download,
# which did not keep up with the installer. It now fetches install.sh from the
# same origin and branch it is itself served from and hands over to it, so
# there is exactly one install path.
#
# CBM_DOWNLOAD_URL (the installers' download-base override, for local testing)
# also moves the installer fetch: install.sh is then taken from
# "$CBM_DOWNLOAD_URL/install.sh".
fetch() {
local url="$1" tool="$2"
if [ "$tool" = "curl" ]; then
curl -fsSL "$url"
INSTALLER_URL="https://raw.githubusercontent.com/${REPO}/main/install.sh"
if [ -n "${CBM_DOWNLOAD_URL:-}" ]; then
INSTALLER_URL="${CBM_DOWNLOAD_URL%/}/install.sh"
fi
# Same transport rule as install.sh: HTTPS everywhere; plain HTTP only for an
# exact loopback authority (the local test fixture), with redirects disabled
# there so a fixture cannot bounce the fetch to the network.
is_loopback_http_url() {
[[ "$1" =~ ^http://(localhost|127\.0\.0\.1|\[::1\])(:[0-9]+)?([/?\#].*)?$ ]]
}
fetch_installer() {
local url="$1" destination="$2" tool="$3"
if is_loopback_http_url "$url"; then
if [ "$tool" = "curl" ]; then
curl -fsS --noproxy '*' --proto '=http' -o "$destination" "$url"
else
wget -q --no-proxy --max-redirect=0 -O "$destination" "$url"
fi
elif [[ "$url" == https://* ]]; then
if [ "$tool" = "curl" ]; then
curl -fsSL --max-redirs 5 --proto '=https' --proto-redir '=https' \
-o "$destination" "$url"
else
wget -q --https-only --max-redirect=5 -O "$destination" "$url"
fi
else
wget -qO- "$url"
die "Refusing non-HTTPS installer URL: $url"
fi
}
download_binary() {
local platform="$1" tool="$2"
install_release() {
local tool="$1"
echo ""
echo "${BOLD}Fetching latest release...${RESET}"
local tag
tag=$(fetch "https://api.github.com/repos/${REPO}/releases/latest" "$tool" | grep '"tag_name"' | head -1 | sed 's/.*"tag_name": *"//;s/".*//')
if [ -z "$tag" ]; then
die "Could not determine latest release. Check https://github.com/${REPO}/releases"
fi
ok "Latest release: $tag"
local asset="codebase-memory-mcp-${platform}.tar.gz"
local url="https://github.com/${REPO}/releases/download/${tag}/${asset}"
echo "${BOLD}Downloading ${asset}...${RESET}"
echo "${BOLD}Fetching install.sh...${RESET}"
CLEANUP_DIR=$(mktemp -d)
trap 'rm -rf "$CLEANUP_DIR"' EXIT
local tmpdir="$CLEANUP_DIR"
local installer="$CLEANUP_DIR/install.sh"
fetch "$url" "$tool" > "${tmpdir}/${asset}"
tar -xzf "${tmpdir}/${asset}" -C "$tmpdir"
fetch_installer "$INSTALLER_URL" "$installer" "$tool" ||
die "Could not fetch install.sh from ${INSTALLER_URL}"
[ -s "$installer" ] || die "Fetched an empty install.sh from ${INSTALLER_URL}"
ok "install.sh fetched"
mkdir -p "$INSTALL_DIR"
mv "${tmpdir}/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}"
chmod +x "${INSTALL_DIR}/${BINARY_NAME}"
ok "Installed to ${INSTALL_DIR}/${BINARY_NAME}"
echo ""
echo "${BOLD}Installing through install.sh...${RESET}"
# The installer configures nothing (--skip-config): agent configuration
# stays this script's interactive step below. stdin is detached so that,
# when this script itself arrives through `curl | bash`, nothing the
# installer runs can read the rest of this script as its input.
bash "$installer" --dir "$INSTALL_DIR" --skip-config </dev/null ||
die "install.sh failed (see the messages above)"
}
# --- Build from source ---
@@ -297,11 +295,9 @@ echo ""
if [ "$FROM_SOURCE" = true ]; then
build_from_source
else
platform=$(detect_platform)
ok "Platform: ${platform}"
tool=$(check_download_tool)
ok "Download tool: ${tool}"
download_binary "$platform" "$tool"
install_release "$tool"
fi
# Verify binary
+70 -20
View File
@@ -116,6 +116,16 @@ copy_smoke_binary() {
cp "$BINARY" "$destination"
}
# A fixture home that belongs to a Claude Code user. An empty ~/.claude is not
# evidence of one (#1180: other tools create that directory, and install then
# configured a client the user never had); the user config Claude Code itself
# writes is. Same seed as test_mark_claude_code_installed in tests/test_cli.c.
mark_claude_code_installed() {
local home="$1"
mkdir -p "$home/.claude"
echo '{}' > "$home/.claude.json"
}
# Retire this run's private account daemon (if one is running) and wait until
# it reports not-running. Install/uninstall flows leave an ephemeral daemon
# draining asynchronously whose mapped generation backing and open logs
@@ -2126,27 +2136,33 @@ sys.exit(0 if ok else 1)
fi
echo "OK 8w-ii: Kiro MCP + steering + isolated exact-tool graph agent"
# 8x: Hermes Agent YAML MCP mapping
# 8x: Hermes Agent YAML MCP mapping. Native Windows Hermes keeps its home in
# %LOCALAPPDATA%\hermes (#1180); the stub-only FAKE_HOME has no legacy ~/.hermes.
if [[ "$BINARY" == *.exe ]]; then
HERMES_HOME_DIR="$FAKE_HOME/AppData/Local/hermes"
else
HERMES_HOME_DIR="$FAKE_HOME/.hermes"
fi
HERMES_CMD=$(sed -n '/^ codebase-memory-mcp:/{n;s/^ *command: *//p;}' \
"$FAKE_HOME/.hermes/config.yaml" 2>/dev/null | head -1)
if ! grep -q '^mcp_servers:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
! grep -q '^ codebase-memory-mcp:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
"$HERMES_HOME_DIR/config.yaml" 2>/dev/null | head -1)
if ! grep -q '^mcp_servers:' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
! grep -q '^ codebase-memory-mcp:' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
! quoted_path_value_matches "$HERMES_CMD" "$SELF_PATH"; then
echo "FAIL 8x: Hermes MCP mapping missing or malformed"
exit 1
fi
echo "OK 8x: Hermes Agent MCP"
if ! grep -q '^name: codebase-memory$' "$FAKE_HOME/.hermes/skills/codebase-memory/SKILL.md" 2>/dev/null ||
! grep -q 'delegate_task' "$FAKE_HOME/.hermes/skills/codebase-memory/SKILL.md" 2>/dev/null ||
! grep -q '`context`' "$FAKE_HOME/.hermes/skills/codebase-memory/SKILL.md" 2>/dev/null; then
if ! grep -q '^name: codebase-memory$' "$HERMES_HOME_DIR/skills/codebase-memory/SKILL.md" 2>/dev/null ||
! grep -q 'delegate_task' "$HERMES_HOME_DIR/skills/codebase-memory/SKILL.md" 2>/dev/null ||
! grep -q '`context`' "$HERMES_HOME_DIR/skills/codebase-memory/SKILL.md" 2>/dev/null; then
echo "FAIL 8x-i: Hermes delegation skill missing"
exit 1
fi
echo "OK 8x-i: Hermes durable delegation skill"
if ! grep -q '^hooks:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
! grep -q '^ pre_llm_call:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
! grep -q 'hook-augment' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
! grep -q -- '--dialect hermes' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null; then
if ! grep -q '^hooks:' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
! grep -q '^ pre_llm_call:' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
! grep -q 'hook-augment' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
! grep -q -- '--dialect hermes' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null; then
echo "FAIL 8x-ii: Hermes pre_llm_call context hook missing"
exit 1
fi
@@ -3148,8 +3164,8 @@ fi
echo "OK 9l: JSON agents, lifecycle hooks, and Kilo cleaned; foreign settings preserved"
# 9m: YAML/TOML new agents are cleaned.
if grep -q '^ codebase-memory-mcp:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
grep -q '^ pre_llm_call:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||
if grep -q '^ codebase-memory-mcp:' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
grep -q '^ pre_llm_call:' "$HERMES_HOME_DIR/config.yaml" 2>/dev/null ||
grep -q '^ codebase-memory-mcp:' "$GOOSE_CFG" 2>/dev/null ||
grep -q 'codebase-memory-mcp' "$FAKE_HOME/.grok/config.toml" 2>/dev/null ||
grep -q '^name = "codebase-memory-mcp"' "$FAKE_HOME/.vibe/config.toml" 2>/dev/null; then
@@ -3203,7 +3219,7 @@ echo "OK 9m-i: durable instruction blocks removed"
# 9n: Skills removed (consolidated skill dir)
if [ -d "$FAKE_HOME/.claude/skills/codebase-memory" ] ||
[ -d "$FAKE_HOME/.hermes/skills/codebase-memory" ] ||
[ -d "$HERMES_HOME_DIR/skills/codebase-memory" ] ||
[ -d "$FAKE_HOME/.agents/skills/codebase-memory" ] ||
[ -d "$FAKE_HOME/.qoder/skills/codebase-memory" ] ||
[ -d "$CUSTOM_KIMI_HOME/skills/codebase-memory" ] ||
@@ -3281,9 +3297,40 @@ echo "OK 9b-1: install with minimal agents exits cleanly"
retire_account_daemon "9b-1-cleanup"
smoke_rmtree "$EMPTY_HOME"
# 9b-1b (#1180): an empty ~/.claude directory is not a Claude Code install.
# The empty home above is this venue's control: where it showed no Claude Code,
# the same home plus a bare ~/.claude must not be configured for it either.
#
# SKIP_WHITELIST: a venue with a claude executable (a developer machine) detects
# Claude Code in every home, so there is nothing for the bare directory to
# change. Narrowing PATH for this one install does not make such a venue
# claude-free: with HOME as the scanned home the product also probes fixed
# locations (/usr/local/bin, /opt/homebrew/bin). A venue without one, such as
# the Linux test image, runs the check.
if grep -q 'Detected agents:.* Claude-Code' <<<"$INSTALL_OUT"; then
echo "SKIP 9b-1b: a claude executable is installed in this venue (whitelisted above)"
else
BARE_HOME=$(smoke_mktemp_dir)
mkdir -p "$BARE_HOME/.claude" "$BARE_HOME/.local/bin"
BARE_RC=0
BARE_OUT=$(HOME="$BARE_HOME" LOCALAPPDATA="$BARE_HOME/AppData/Local" "$BINARY" install -y 2>&1) || BARE_RC=$?
if [ "$BARE_RC" -ge 128 ] ||
! grep -q 'Detected agents:' <<<"$BARE_OUT" ||
grep -q 'Detected agents:.* Claude-Code' <<<"$BARE_OUT" ||
[ -e "$BARE_HOME/.claude.json" ] ||
[ -n "$(ls -A "$BARE_HOME/.claude" 2>/dev/null)" ]; then
echo "FAIL 9b-1b: a bare ~/.claude directory was configured as a Claude Code install"
exit 1
fi
echo "OK 9b-1b: a bare ~/.claude directory is not configured as Claude Code"
retire_account_daemon "9b-1b-cleanup"
smoke_rmtree "$BARE_HOME"
fi
# 9b-2: Install twice (idempotent)
IDEM_HOME=$(smoke_mktemp_dir)
mkdir -p "$IDEM_HOME/.claude" "$IDEM_HOME/.local/bin"
mkdir -p "$IDEM_HOME/.local/bin"
mark_claude_code_installed "$IDEM_HOME"
copy_smoke_binary "$IDEM_HOME/.local/bin/codebase-memory-mcp"
run_no_crash 9b-2 env HOME="$IDEM_HOME" LOCALAPPDATA="$IDEM_HOME/AppData/Local" "$BINARY" install -y
IDEM_INSTALLER="$BINARY"
@@ -3307,7 +3354,8 @@ smoke_rmtree "$IDEM_HOME"
# 9b-3: Uninstall without prior install
CLEAN_HOME=$(smoke_mktemp_dir)
mkdir -p "$CLEAN_HOME/.claude" "$CLEAN_HOME/.local/bin"
mkdir -p "$CLEAN_HOME/.local/bin"
mark_claude_code_installed "$CLEAN_HOME"
UNINSTALL_RC=0
UNINSTALL_OUT=$(HOME="$CLEAN_HOME" "$BINARY" uninstall -y -n 2>&1) || UNINSTALL_RC=$?
if [ "$UNINSTALL_RC" -ge 128 ]; then
@@ -3331,7 +3379,8 @@ smoke_rmtree "$CORRUPT_HOME"
# 9b-8: Double uninstall
DBL_HOME=$(smoke_mktemp_dir)
mkdir -p "$DBL_HOME/.claude" "$DBL_HOME/.local/bin"
mkdir -p "$DBL_HOME/.local/bin"
mark_claude_code_installed "$DBL_HOME"
copy_smoke_binary "$DBL_HOME/.local/bin/codebase-memory-mcp"
run_no_crash 9b-8-install env HOME="$DBL_HOME" "$BINARY" install -y
DBL_UNINSTALLER="$BINARY"
@@ -3828,7 +3877,7 @@ if [ "$DL_OS" != "windows" ] && [ -f "$REPO_ROOT/install.sh" ]; then
echo "--- Phase 13: install.sh E2E ---"
INSTALL_TEST_HOME=$(smoke_mktemp_dir)
INSTALL_TEST_DIR=$(smoke_mktemp_dir)
mkdir -p "$INSTALL_TEST_HOME/.claude"
mark_claude_code_installed "$INSTALL_TEST_HOME"
mkdir -p "$INSTALL_TEST_HOME/.local/bin"
# 13a: run install.sh with local URL + isolated HOME
@@ -3865,7 +3914,8 @@ if [ "$DL_OS" != "windows" ] && [ -f "$REPO_ROOT/install.sh" ]; then
echo "OK 13d: no signing needed ($DL_OS)"
fi
# 13e: agent configs created (at least Claude Code since we made ~/.claude)
# 13e: agent configs created (at least Claude Code: the fixture home is a
# Claude Code user's)
if [ -f "$INSTALL_TEST_HOME/.claude.json" ] && grep -q 'codebase-memory-mcp' "$INSTALL_TEST_HOME/.claude.json" 2>/dev/null; then
echo "OK 13e: agent configs created by install.sh"
else
@@ -3892,7 +3942,7 @@ elif [ -f "$REPO_ROOT/install.ps1" ] && command -v powershell.exe &>/dev/null; t
echo "--- Phase 13: install.ps1 E2E (Windows) ---"
PS1_TEST_HOME=$(smoke_mktemp_dir)
PS1_TEST_DIR=$(smoke_mktemp_dir)
mkdir -p "$PS1_TEST_HOME/.claude"
mark_claude_code_installed "$PS1_TEST_HOME"
# Convert MSYS paths to Windows paths for PowerShell
if command -v cygpath &>/dev/null; then
+9
View File
@@ -338,6 +338,9 @@ bash "$ROOT/tests/test_version_metadata_contract.sh"
echo "=== Step 0y: VM leg verdict contract ==="
bash "$ROOT/tests/test_vm_verdict_contract.sh"
echo "=== Step 0z: setup scripts install through the installers' verified path ==="
bash "$ROOT/tests/test_setup_scripts_contract.sh"
# Verify compiler supports target arch
verify_compiler "$CC"
@@ -357,6 +360,12 @@ else
make -f Makefile.cbm test-par ${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"}
fi
# Step 3a: the runner must ignore an inherited git repository environment
# (#2003: the pre-commit hook exports GIT_DIR, which overrides `git -C` and
# pointed fixture git commands at the committer's real repository).
echo "=== Step 3a: inherited git environment isolation (#2003) ==="
bash "$ROOT/tests/test_git_env_isolation_contract.sh" "$ROOT/$BUILD_DIR/test-runner"
# Step 4: C++ large-TU index-hang regression guard (#410). Runs the PROD binary
# in a subprocess with a wall-clock timeout — a hang must fail, not block the run.
# Opt-in via CBM_RUN_HANG_TEST=1 (it needs the prod binary, which the ASan unit
+10 -10
View File
@@ -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
44bade69b14ac382b08835965eeec5f0fd6e54ccb7a80da21c0161128a10503f 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
@@ -89,11 +89,11 @@ c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/v
02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/c/tree_sitter/array.h
c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/c/tree_sitter/parser.h
778fb7d63b8c1844da315648c02f325c4713a6f4a5d19644fd413421422776d3 internal/cbm/vendored/grammars/c_sharp/LICENSE
720746e4d6bdbe1ba76f83a4c157a8ec3ce20c30a6b4744f30ca3993e55b8469 internal/cbm/vendored/grammars/c_sharp/parser.c
83dad602517523bc185e195d9446a92f73786364661bc87b564e5206ca52d6be internal/cbm/vendored/grammars/c_sharp/scanner.c
115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/c_sharp/tree_sitter/alloc.h
8c814560c31d0157013bc3399a9282fc5049d06790a36f55115373d6c3abe16b internal/cbm/vendored/grammars/c_sharp/tree_sitter/array.h
c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/c_sharp/tree_sitter/parser.h
0a2651e49de7c7237c535c41a132a7ec0424da79d12f197f1df3edd7d6ea4427 internal/cbm/vendored/grammars/c_sharp/parser.c
00920daa0fdf3050d441475e8effe996b60ee8acc1bdbcbbc4c83d56a6987705 internal/cbm/vendored/grammars/c_sharp/scanner.c
b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/c_sharp/tree_sitter/alloc.h
31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/c_sharp/tree_sitter/array.h
180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/c_sharp/tree_sitter/parser.h
108bfb047e0d45962dcadedfce730c86c278bc2a67f6939df405a706bec27e20 internal/cbm/vendored/grammars/cairo/LICENSE
1631b184694158672da430675d3c3990c6db48eafb9e888b769866dc9be0092b internal/cbm/vendored/grammars/cairo/parser.c
681bd8135f2381810e4c15d6ff103622d1150e5ab9474d66b3b33a9c9a83fde2 internal/cbm/vendored/grammars/cairo/scanner.c
@@ -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
+161 -46
View File
@@ -1504,7 +1504,11 @@ static const char skill_content[] =
"| Text search | `search_code` or Grep |\n"
"\n"
"## Exploration Workflow\n"
"1. `list_projects` — check if project is indexed\n"
/* #1690: a guessed repo or folder name misses the project whenever the
* checkout directory differs from it; the root_path is what identifies it. */
"1. `list_projects` — pick the project whose `root_path` contains your working directory; "
"pass its `name` (or the absolute directory itself) as `project`, never a repo or folder "
"name\n"
"2. `get_graph_schema` — understand node/edge types\n"
"3. `search_graph(label=\"Function\", name_pattern=\".*Pattern.*\")` — find code\n"
"4. `get_code_snippet(qualified_name=\"project.path.FuncName\")` — read source\n"
@@ -2774,10 +2778,41 @@ static void cbm_kiro_home_dir(const char *home_dir, char *out, size_t out_sz) {
cbm_env_home_dir("KIRO_HOME", home_dir, ".kiro", out, out_sz);
}
static void cbm_hermes_home_dir(const char *home_dir, char *out, size_t out_sz) {
cbm_env_home_dir("HERMES_HOME", home_dir, ".hermes", out, out_sz);
/* #1180: native Windows Hermes -- the install.ps1 CLI, the MSIX package and
* the Desktop app -- defaults HERMES_HOME to %LOCALAPPDATA%\hermes and keeps a
* legacy ~/.hermes only while the new directory is absent (hermes-agent
* website/docs/user-guide/windows-native.md "Data layout";
* apps/desktop/electron/data-paths.mjs resolveDesktopHermesHome). Probing
* only ~/.hermes missed those installs and aimed config.yaml at a home Hermes
* never reads. Other platforms use ~/.hermes. */
static void cbm_hermes_home_dir_for(const char *home_dir, bool windows, char *out, size_t out_sz) {
const char *fallback = ".hermes";
if (windows) {
char native[CLI_BUF_1K];
char legacy[CLI_BUF_1K];
snprintf(native, sizeof(native), "%s/AppData/Local/hermes", home_dir);
snprintf(legacy, sizeof(legacy), "%s/.hermes", home_dir);
if (dir_exists(native) || !dir_exists(legacy)) {
fallback = "AppData/Local/hermes";
}
}
cbm_env_home_dir("HERMES_HOME", home_dir, fallback, out, out_sz);
}
static void cbm_hermes_home_dir(const char *home_dir, char *out, size_t out_sz) {
#ifdef _WIN32
cbm_hermes_home_dir_for(home_dir, true, out, out_sz);
#else
cbm_hermes_home_dir_for(home_dir, false, out, out_sz);
#endif
}
#ifdef CBM_CLI_ENABLE_TEST_API
void cbm_hermes_home_dir_for_testing(const char *home_dir, bool windows, char *out, size_t out_sz) {
cbm_hermes_home_dir_for(home_dir, windows, out, out_sz);
}
#endif
static void cbm_qwen_home_dir(const char *home_dir, char *out, size_t out_sz) {
cbm_env_home_dir("QWEN_HOME", home_dir, ".qwen", out, out_sz);
}
@@ -3079,6 +3114,53 @@ static int cbm_resolve_released_hook_command(const char *script_name, char *out,
return written > 0 && (size_t)written < out_sz ? CLI_OK : CLI_ERR;
}
/* #1180: a bare ~/.claude directory is not a Claude Code install -- other
* tools create it -- and treating it as one wrote hooks, skills and MCP
* entries for a client the user never installed. Claude Code itself leaves
* its user config .claude.json (under CLAUDE_CONFIG_DIR when set), its
* settings.json, or the claude CLI. */
static bool cbm_claude_code_detected(const char *home_dir) {
char dir[CLI_BUF_1K];
char path[CLI_BUF_1K];
cbm_claude_config_dir(home_dir, dir, sizeof(dir));
int written = snprintf(path, sizeof(path), "%s/settings.json", dir);
if (dir[0] && written > 0 && (size_t)written < sizeof(path) && cbm_file_exists(path)) {
return true;
}
cbm_claude_user_root(home_dir, dir, sizeof(dir));
written = snprintf(path, sizeof(path), "%s/.claude.json", dir);
if (dir[0] && written > 0 && (size_t)written < sizeof(path) && cbm_file_exists(path)) {
return true;
}
return cbm_agent_cli_exists("claude", home_dir);
}
/* OpenCode keeps its data (auth, logs, sessions; the global config itself on
* older installs) in ~/.local/share/opencode on every OS --
* %USERPROFILE%\.local\share\opencode on Windows (opencode.ai/docs/
* troubleshooting, "Storage"). The CLI and the Desktop app's bundled
* opencode-cli server both create it, so it identifies an install that has
* no config file, no ~/.config/opencode and no `opencode` on PATH
* (#1167, #1180). */
static bool cbm_opencode_detected(const char *home_dir) {
char path[CLI_BUF_1K];
cbm_opencode_config_path(home_dir, path, sizeof(path));
if (cbm_file_exists(path) || cbm_agent_cli_exists("opencode", home_dir)) {
return true;
}
snprintf(path, sizeof(path), "%s/.config/opencode", home_dir);
if (dir_exists(path)) {
return true;
}
char env_buf[CLI_BUF_1K];
const char *config_dir = cbm_safe_getenv("OPENCODE_CONFIG_DIR", env_buf, sizeof(env_buf), NULL);
if (config_dir && config_dir[0] && dir_exists(config_dir)) {
return true;
}
snprintf(path, sizeof(path), "%s/.local/share/opencode", home_dir);
return dir_exists(path);
}
cbm_detected_agents_t cbm_detect_agents(const char *home_dir) {
cbm_detected_agents_t agents;
memset(&agents, 0, sizeof(agents));
@@ -3088,8 +3170,7 @@ cbm_detected_agents_t cbm_detect_agents(const char *home_dir) {
char path[CLI_BUF_1K];
cbm_claude_config_dir(home_dir, path, sizeof(path));
agents.claude_code = path[0] != '\0' && dir_exists(path);
agents.claude_code = cbm_claude_code_detected(home_dir);
cbm_codex_config_dir(home_dir, path, sizeof(path));
agents.codex = path[0] != '\0' && dir_exists(path);
@@ -3103,18 +3184,7 @@ cbm_detected_agents_t cbm_detect_agents(const char *home_dir) {
cbm_zed_config_dir(home_dir, path, sizeof(path));
agents.zed = dir_exists(path);
cbm_opencode_config_path(home_dir, path, sizeof(path));
agents.opencode = cbm_file_exists(path) || cbm_agent_cli_exists("opencode", home_dir);
if (!agents.opencode) {
snprintf(path, sizeof(path), "%s/.config/opencode", home_dir);
agents.opencode = dir_exists(path);
}
if (!agents.opencode) {
char env_buf[CLI_BUF_1K];
const char *config_dir =
cbm_safe_getenv("OPENCODE_CONFIG_DIR", env_buf, sizeof(env_buf), NULL);
agents.opencode = config_dir && config_dir[0] && dir_exists(config_dir);
}
agents.opencode = cbm_opencode_detected(home_dir);
agents.aider = cbm_agent_cli_exists("aider", home_dir);
@@ -3274,6 +3344,9 @@ static const char agent_instructions_content[] =
"### Session resets and subagents\n"
"- At session start or after compaction, confirm the nearest graph project and generation with "
"`list_projects` or `index_status`, then choose Scout, Verify, or Auditor.\n"
"- The graph project is the `list_projects` entry whose `root_path` contains your working "
"directory; pass its `name` (or the absolute directory itself) as `project`, never a repo or "
"folder name.\n"
"- Before spawning a subagent, query the graph and coverage in the parent. Pass the tier, "
"project, generation/freshness, bounded scope, queries and pagination state, qualified "
"symbols, "
@@ -3679,6 +3752,8 @@ static const char aider_instructions_content[] =
"First use in a repo: codebase-memory-mcp cli index_repository '{\"repo_path\":\"<abs "
"path>\"}'\n"
"List indexed projects (for <name>): codebase-memory-mcp cli list_projects '{}'\n"
"<name> is the entry whose root_path contains your working directory; pass it (or the "
"absolute directory itself), never a repo or folder name.\n"
"\n"
"## When to fall back to grep/glob\n"
"- Searching for string literals, error messages, config values\n"
@@ -3841,8 +3916,11 @@ int cbm_upsert_codex_mcp(const char *binary_path, const char *config_path) {
}
int cbm_remove_codex_mcp(const char *config_path) {
/* #2228: only our table goes; foreign tables found between the markers
* (Codex Desktop appends below a block that ends the file) stay. */
if (!config_path ||
cbm_toml_remove_managed_block(config_path, CODEX_MCP_BEGIN, CODEX_MCP_END) != 0) {
cbm_toml_remove_managed_block_owned(config_path, CODEX_MCP_BEGIN, CODEX_MCP_END,
CODEX_CMM_SECTION "\n") != 0) {
return CLI_ERR;
}
return cbm_remove_codex_legacy_mcp(config_path) >= 0 ? CLI_OK : CLI_ERR;
@@ -4466,7 +4544,8 @@ static int cbm_upsert_grok_mcp(const char *binary_path, const char *config_path)
static int cbm_remove_grok_mcp_owned(const char *binary_path, const char *config_path) {
(void)binary_path;
if (!config_path ||
cbm_toml_remove_managed_block(config_path, GROK_MCP_BEGIN, GROK_MCP_END) != 0) {
cbm_toml_remove_managed_block_owned(config_path, GROK_MCP_BEGIN, GROK_MCP_END,
GROK_CMM_SECTION "\n") != 0) {
return CLI_ERR;
}
return cbm_remove_grok_legacy_mcp(config_path) >= 0 ? CLI_OK : CLI_ERR;
@@ -5032,7 +5111,8 @@ static int cbm_upsert_kimi_context_hook(const char *config_path, const char *bin
}
static int cbm_remove_kimi_context_hook(const char *config_path) {
return cbm_toml_remove_managed_block(config_path, KIMI_HOOK_BEGIN, KIMI_HOOK_END) == 0
return cbm_toml_remove_managed_block_owned(config_path, KIMI_HOOK_BEGIN, KIMI_HOOK_END,
"[[hooks]]\n") == 0
? CLI_OK
: CLI_ERR;
}
@@ -7450,6 +7530,11 @@ bool cbm_config_watcher_enabled(cbm_config_t *cfg) {
return cbm_config_get_bool(cfg, CBM_CONFIG_WATCHER_ENABLED, true);
}
/* Opt-in tree polling of non-git roots (#1948); see cli.h. */
bool cbm_config_watch_non_git(cbm_config_t *cfg) {
return cbm_config_get_bool(cfg, CBM_CONFIG_WATCH_NON_GIT, false);
}
bool cbm_config_load_index_policy(cbm_config_t *cfg, cbm_index_resource_policy_t *policy,
char *error, size_t error_size) {
if (!cfg || !policy) {
@@ -7490,6 +7575,8 @@ static const config_key_def_t CONFIG_KEYS[] = {
{CBM_CONFIG_AUTO_WATCH, "true", "Register background git watcher on session connect"},
{CBM_CONFIG_WATCHER_ENABLED, "true",
"Run the background watcher thread (auto-reindex); false to disable"},
{CBM_CONFIG_WATCH_NON_GIT, "false",
"Also poll non-git project roots for changes (file-tree scan); off by default"},
{CBM_CONFIG_UI_LANG, "auto", "Pin graph UI language: en, zh, or auto"},
{CBM_CONFIG_UI_ENABLED, "false", "Serve the graph UI on a loopback HTTP port"},
{CBM_CONFIG_UI_PORT, "9749", "Port for the graph UI listener when enabled"},
@@ -12856,6 +12943,41 @@ static int cli_uninstall_activate(void *opaque) {
return CLI_OK;
}
/* A generic auto-answer is not consent to erase project indexes. An explicit
* --delete-indexes takes precedence even over --no; otherwise only a separate
* interactive answer can select deletion. This helper decides and reports,
* but all deletion remains in the final guarded uninstall activation. */
static bool uninstall_decide_index_deletion(const char *home, bool requested, bool dry_run) {
int index_count = count_db_indexes(home);
if (index_count <= 0) {
return false;
}
printf("\nFound %d index(es):\n", index_count);
cbm_list_indexes(home);
bool delete_indexes = requested;
if (!requested) {
bool can_ask = g_auto_answer == 0;
#ifdef _WIN32
can_ask = can_ask && _isatty(_fileno(stdin));
#else
can_ask = can_ask && isatty(fileno(stdin));
#endif
delete_indexes = can_ask && prompt_yn("Delete these indexes? (default: no)");
}
if (!delete_indexes) {
const char *cache_dir = get_cache_dir(home);
printf("Indexes kept in %s. To remove them, uninstall with --delete-indexes "
"or delete the project .db files there.\n",
cache_dir ? cache_dir : "the cache directory");
return false;
}
if (dry_run) {
printf("(dry-run — indexes would be deleted)\n");
return false;
}
return true;
}
int cbm_cmd_uninstall(int argc, char **argv) {
/* `uninstall --help` used to UNINSTALL.
*
@@ -12869,20 +12991,25 @@ int cbm_cmd_uninstall(int argc, char **argv) {
* cannot auto-confirm the destruction we are trying to prevent. */
for (int i = 0; i < argc; i++) {
if (argv && argv[i] && (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)) {
printf("Usage: codebase-memory-mcp uninstall [options]\n\n"
"Removes the codebase-memory-mcp binary, its agent configurations and,\n"
"with confirmation, its indexes. THIS IS DESTRUCTIVE.\n\n"
"Options:\n"
" --dry-run Show what would be removed, change nothing\n"
" --dir=PATH Uninstall from a custom install directory\n"
" -y, --yes Do not prompt for confirmation\n"
" -h, --help Show this help and exit\n\n"
"Run with --dry-run first if you are unsure.\n");
printf(
"Usage: codebase-memory-mcp uninstall [options]\n\n"
"Removes the codebase-memory-mcp binary and its agent configurations.\n"
"THIS IS DESTRUCTIVE. Project indexes are kept by default. An interactive\n"
"terminal is asked separately; the default answer is to keep them.\n\n"
"Options:\n"
" --dry-run Show what would be removed, change nothing\n"
" --dir=PATH Uninstall from a custom install directory\n"
" --delete-indexes Also delete every project index (overrides --no)\n"
" -y, --yes Do not prompt; indexes are kept unless explicitly deleted\n"
" -n, --no Decline prompts; --delete-indexes still takes precedence\n"
" -h, --help Show this help and exit\n\n"
"Run with --dry-run first if you are unsure.\n");
return CLI_OK;
}
}
parse_auto_answer(argc, argv);
bool dry_run = false;
bool delete_indexes_requested = false;
/* An install into a custom --dir must be removable from that same dir:
* without this, anyone who installed outside ~/.local/bin has no supported
* uninstall path at all. Mirrors cbm_cmd_install's parsing. */
@@ -12895,6 +13022,8 @@ int cbm_cmd_uninstall(int argc, char **argv) {
}
if (strcmp(argv[i], "--dry-run") == 0) {
dry_run = true;
} else if (strcmp(argv[i], "--delete-indexes") == 0) {
delete_indexes_requested = true;
} else if (strncmp(argv[i], "--dir=", SLEN("--dir=")) == 0) {
requested_bin_dir = argv[i] + SLEN("--dir=");
if (!requested_bin_dir[0]) {
@@ -12926,23 +13055,9 @@ int cbm_cmd_uninstall(int argc, char **argv) {
agent_uninstall_failures_reset();
cbm_detected_agents_t agents = cbm_detect_agents(home);
/* Confirm index removal outside the startup lock, but defer the mutation
* until the final guarded activation. Dry-run never removes indexes. */
bool delete_indexes = false;
int index_count = count_db_indexes(home);
if (index_count > 0) {
printf("\nFound %d index(es):\n", index_count);
cbm_list_indexes(home);
if (prompt_yn("Delete these indexes?")) {
if (dry_run) {
printf("(dry-run — indexes would be deleted)\n");
} else {
delete_indexes = true;
}
} else {
printf("Indexes kept.\n");
}
}
/* Decide outside the startup lock; mutate only in the final guarded
* activation. Dry-run never authorizes actual index removal. */
bool delete_indexes = uninstall_decide_index_deletion(home, delete_indexes_requested, dry_run);
char bin_path_storage[CLI_BUF_1K];
const char *bin_path = bin_path_storage;
+16 -3
View File
@@ -182,11 +182,11 @@ int cbm_remove_zed_mcp_owned(const char *binary_path, const char *config_path);
/* Detected coding agents on the system. */
typedef struct {
bool claude_code; /* ~/.claude/ exists */
bool claude_code; /* settings.json, .claude.json, or claude CLI exists */
bool codex; /* $CODEX_HOME or ~/.codex exists */
bool gemini; /* Gemini settings or executable exists */
bool zed; /* platform-specific Zed config dir exists */
bool opencode; /* opencode on PATH or config exists */
bool opencode; /* opencode on PATH, config, or data dir exists */
bool antigravity; /* Antigravity CLI config or executable exists */
bool aider; /* aider on PATH */
bool kilocode; /* KiloCode globalStorage dir exists */
@@ -197,7 +197,7 @@ typedef struct {
bool openclaw; /* ~/.openclaw/ exists */
bool kiro; /* ~/.kiro/ exists */
bool junie; /* ~/.junie/ exists */
bool hermes; /* ~/.hermes/ or hermes CLI exists */
bool hermes; /* Hermes home (Windows: %LOCALAPPDATA%\hermes) or CLI */
bool openhands; /* ~/.openhands/ or openhands CLI exists */
bool cline; /* ~/.cline/ or cline CLI exists */
bool warp; /* Warp footprint or oz/oz-preview/warp-cli exists */
@@ -217,6 +217,13 @@ cbm_detected_agents_t cbm_detect_agents(const char *home_dir);
/* Install or refresh every detected agent integration below home. */
int cbm_install_agent_configs(const char *home, const char *binary_path, bool force, bool dry_run);
#ifdef CBM_CLI_ENABLE_TEST_API
/* #1180: the Hermes home as resolved on Windows (`windows`) or elsewhere, so
* the %LOCALAPPDATA%\hermes default and its legacy ~/.hermes fallback are
* exercised on every host. */
void cbm_hermes_home_dir_for_testing(const char *home_dir, bool windows, char *out, size_t out_sz);
#endif
#ifdef CBM_CLI_ENABLE_TEST_API
/* #1558: client-selector vocabulary, exposed so a test can prove every token
* resolves and an unknown one is rejected. */
@@ -446,6 +453,7 @@ bool cbm_config_load_index_policy(cbm_config_t *cfg, cbm_index_resource_policy_t
#define CBM_CONFIG_AUTO_WATCH "auto_watch"
#define CBM_CONFIG_UI_LANG "ui-lang"
#define CBM_CONFIG_WATCHER_ENABLED "watcher_enabled"
#define CBM_CONFIG_WATCH_NON_GIT "watch_non_git"
/* #1558: the graph UI's loopback listener. Stored in the UI config file rather
* than the key-value store, but surfaced through `config` so it is findable. */
#define CBM_CONFIG_UI_ENABLED "ui_enabled"
@@ -460,6 +468,11 @@ bool cbm_config_load_index_policy(cbm_config_t *cfg, cbm_index_resource_policy_t
* the watcher. */
bool cbm_config_watcher_enabled(cbm_config_t *cfg);
/* Whether the watcher also polls NON-GIT project roots (default false, #1948).
* Non-git roots are otherwise never refreshed after their first index. Read
* once at daemon startup, like watcher_enabled. NULL-safe (NULL → false). */
bool cbm_config_watch_non_git(cbm_config_t *cfg);
/* ── Binary activation safety ─────────────────────────────────── */
typedef void *cbm_cli_activation_lock_t;
+707 -171
View File
@@ -149,6 +149,10 @@ typedef struct {
static int toml_managed_block_conflicts(const char *existing, size_t existing_len,
size_t exclude_start, size_t exclude_end, const char *block,
size_t block_len);
static int toml_managed_rewrite(const char *existing, size_t existing_len,
const toml_line_t *begin_line, const toml_line_t *end_line,
const char *begin_marker, const char *end_marker, const char *owned,
size_t owned_len, int install, toml_buffer_t *output);
static void toml_buffer_dispose(toml_buffer_t *buffer) {
if (!buffer) {
@@ -1067,15 +1071,20 @@ int cbm_toml_escape_basic_string(const char *input, char *out, size_t out_size)
return TOML_EDIT_OK;
}
static int toml_managed_body_valid(const char *body, const char *begin_marker,
const char *end_marker, size_t *body_len) {
return body && toml_bounded_length(body, TOML_EDIT_MAX_BYTES, body_len) == TOML_EDIT_OK &&
toml_text_is_safe(body, *body_len, 1) &&
!toml_contains_marker_line(body, *body_len, begin_marker, end_marker) &&
toml_validate_lexical_strings(body, *body_len) == TOML_EDIT_OK;
}
int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marker,
const char *end_marker, const char *block) {
size_t block_len = 0U;
if (!toml_valid_path(file_path) || !toml_valid_marker(begin_marker) ||
!toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0 || !block ||
toml_bounded_length(block, TOML_EDIT_MAX_BYTES, &block_len) != TOML_EDIT_OK ||
!toml_text_is_safe(block, block_len, 1) ||
toml_contains_marker_line(block, block_len, begin_marker, end_marker) ||
toml_validate_lexical_strings(block, block_len) != TOML_EDIT_OK) {
!toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0 ||
!toml_managed_body_valid(block, begin_marker, end_marker, &block_len)) {
return TOML_EDIT_ERR;
}
@@ -1104,23 +1113,26 @@ int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marke
}
toml_buffer_t output = {0};
size_t prefix_len = has_pair ? begin_line.start : existing_len;
if (has_pair && prefix_len == 0U && existing_len >= 3U && (unsigned char)existing[0] == 0xefU &&
(unsigned char)existing[1] == 0xbbU && (unsigned char)existing[2] == 0xbfU) {
prefix_len = 3U;
}
const char *newline = toml_newline_style(existing, existing_len);
size_t payload_start = existing_len >= 3U && (unsigned char)existing[0] == 0xefU &&
(unsigned char)existing[1] == 0xbbU &&
(unsigned char)existing[2] == 0xbfU
? 3U
: 0U;
if (toml_buffer_append(&output, existing, prefix_len) != TOML_EDIT_OK ||
(!has_pair && existing_len > payload_start && existing[existing_len - 1] != '\n' &&
toml_buffer_append_cstr(&output, newline) != TOML_EDIT_OK) ||
toml_append_managed(&output, begin_marker, end_marker, block, newline) != TOML_EDIT_OK ||
(has_pair && toml_buffer_append(&output, existing + end_line.full_end,
existing_len - end_line.full_end) != TOML_EDIT_OK)) {
int built = TOML_EDIT_OK;
if (has_pair) {
/* #2228: rebuild the span around the block, keeping what it holds that
* is not ours instead of discarding the whole span. */
built = toml_managed_rewrite(existing, existing_len, &begin_line, &end_line, begin_marker,
end_marker, block, block_len, 1, &output);
} else if (toml_buffer_append(&output, existing, existing_len) != TOML_EDIT_OK ||
(existing_len > payload_start && existing[existing_len - 1] != '\n' &&
toml_buffer_append_cstr(&output, newline) != TOML_EDIT_OK) ||
toml_append_managed(&output, begin_marker, end_marker, block, newline) !=
TOML_EDIT_OK) {
built = TOML_EDIT_ERR;
}
if (built != TOML_EDIT_OK) {
toml_buffer_dispose(&output);
free(existing);
return TOML_EDIT_ERR;
@@ -1133,10 +1145,14 @@ int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marke
return result;
}
int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marker,
const char *end_marker) {
/* owned == NULL removes the whole span (the historical contract); otherwise
* only the tables it declares go and the rest of the span stays (#2228). */
static int toml_remove_managed(const char *file_path, const char *begin_marker,
const char *end_marker, const char *owned) {
size_t owned_len = 0U;
if (!toml_valid_path(file_path) || !toml_valid_marker(begin_marker) ||
!toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0) {
!toml_valid_marker(end_marker) || strcmp(begin_marker, end_marker) == 0 ||
(owned && !toml_managed_body_valid(owned, begin_marker, end_marker, &owned_len))) {
return TOML_EDIT_ERR;
}
char *existing = NULL;
@@ -1187,9 +1203,14 @@ int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marke
(unsigned char)existing[1] == 0xbbU && (unsigned char)existing[2] == 0xbfU) {
prefix_len = 3U;
}
if (toml_buffer_append(&output, existing, prefix_len) != TOML_EDIT_OK ||
toml_buffer_append(&output, existing + end_line.full_end,
existing_len - end_line.full_end) != TOML_EDIT_OK) {
int built = owned ? toml_managed_rewrite(existing, existing_len, &begin_line, &end_line,
begin_marker, end_marker, owned, owned_len, 0, &output)
: toml_buffer_append(&output, existing, prefix_len) == TOML_EDIT_OK &&
toml_buffer_append(&output, existing + end_line.full_end,
existing_len - end_line.full_end) == TOML_EDIT_OK
? TOML_EDIT_OK
: TOML_EDIT_ERR;
if (built != TOML_EDIT_OK) {
toml_buffer_dispose(&output);
free(existing);
return TOML_EDIT_ERR;
@@ -1201,6 +1222,17 @@ int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marke
return result;
}
int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marker,
const char *end_marker) {
return toml_remove_managed(file_path, begin_marker, end_marker, NULL);
}
int cbm_toml_remove_managed_block_owned(const char *file_path, const char *begin_marker,
const char *end_marker, const char *owned_tables) {
return owned_tables ? toml_remove_managed(file_path, begin_marker, end_marker, owned_tables)
: TOML_EDIT_ERR;
}
static int toml_hex_digit(unsigned char ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
@@ -1845,6 +1877,428 @@ static int toml_managed_block_conflicts(const char *existing, size_t existing_le
return multiline_state == TOML_STRING_NONE ? TOML_EDIT_OK : TOML_EDIT_ERR;
}
/* ── #2228: content found between the managed markers ─────────────────
*
* The span between our markers does not only hold what we wrote. A client
* that appends tables at the end of the file (Codex Desktop does) puts them
* INSIDE the markers whenever our closing marker is the last line, and users
* add keys to our own table. Rewriting or removing the whole span deleted
* all of that.
*
* The span is read as TOML sections -- the lines before its first header
* (the lead) and one section per header -- and each is classified against
* the tables the block declares:
* owned a declared table; the k-th [[element]] of a declared array.
* Keys the block writes are ours; every other key, comment and
* blank line in it is the user's and stays in the table.
* attached a sub-table of a declared table: part of our entry, kept with
* it on install and removed with it on uninstall.
* foreign anything else: moved byte for byte, in order, to just after
* the closing marker (install) or left in place (removal).
* lead moved above the opening marker, where it keeps the table it
* belongs to. A block that itself starts with bare keys owns the
* lead, which is then replaced exactly as before.
* Whatever cannot be attributed safely is refused and the file is left
* untouched: a second copy of a declared table, an undeclared [[element]]
* of a declared array, a child of a declared array element, an unparsable
* line in an owned table, a user key colliding with one the block writes, a
* move that would hand the keys below the block to another table, or a
* result whose tables would conflict with the block. */
#define TOML_MANAGED_MAX_TABLES 16U
enum {
TOML_SPAN_LEAD = -1,
TOML_SPAN_FOREIGN = 0,
TOML_SPAN_OWNED = 1,
TOML_SPAN_ATTACHED = 2,
};
typedef struct {
size_t start;
size_t body;
size_t end;
toml_header_t header;
} toml_section_t;
typedef struct {
const char *data;
size_t lead_end;
size_t span_end;
const char *owned;
size_t owned_len;
size_t owned_first;
} toml_managed_span_t;
/* End of the section whose body starts at pos: the next header line outside
* a multiline string, or len. */
static int toml_section_end(const char *data, size_t pos, size_t len, size_t *end) {
size_t cursor = pos;
toml_line_t line;
int multiline_state = TOML_STRING_NONE;
while (toml_next_line(data, len, &cursor, &line)) {
if (multiline_state == TOML_STRING_NONE) {
toml_header_t header;
if (toml_parse_header(data, &line, "", &header) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
int present = header.present;
toml_header_dispose(&header);
if (present) {
*end = line.start;
return TOML_EDIT_OK;
}
}
if (toml_scan_line_strings(data, &line, &multiline_state) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
}
*end = len;
return multiline_state == TOML_STRING_NONE ? TOML_EDIT_OK : TOML_EDIT_ERR;
}
/* The section whose header line starts at pos. */
static int toml_section_at(const char *data, size_t pos, size_t len, toml_section_t *section) {
memset(section, 0, sizeof(*section));
section->start = pos;
size_t cursor = pos;
toml_line_t line;
if (!toml_next_line(data, len, &cursor, &line) ||
toml_parse_header(data, &line, "", &section->header) != TOML_EDIT_OK ||
!section->header.present ||
toml_section_end(data, line.full_end, len, &section->end) != TOML_EDIT_OK) {
toml_header_dispose(&section->header);
return TOML_EDIT_ERR;
}
section->body = line.full_end;
return TOML_EDIT_OK;
}
static int toml_lines_significant(const char *data, size_t start, size_t end) {
size_t cursor = start;
toml_line_t line;
while (toml_next_line(data, end, &cursor, &line)) {
if (!toml_line_is_blank_or_comment(data, &line)) {
return 1;
}
}
return 0;
}
/* Declared table `table` (1-based) of the block, or the number of declared
* tables in *count when table is 0. */
static int toml_declared_table(const toml_managed_span_t *span, size_t table, size_t *count,
toml_section_t *out) {
size_t pos = span->owned_first;
size_t index = 0U;
while (pos < span->owned_len) {
toml_section_t declared;
if (++index > TOML_MANAGED_MAX_TABLES ||
toml_section_at(span->owned, pos, span->owned_len, &declared) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
if (index == table) {
*out = declared;
return TOML_EDIT_OK;
}
pos = declared.end;
toml_header_dispose(&declared.header);
}
if (count) {
*count = index;
}
return table == 0U ? TOML_EDIT_OK : TOML_EDIT_ERR;
}
/* Classify one span header. seen[] marks the declared tables the span has
* already supplied, so a second copy is refused instead of guessed at. */
static int toml_managed_classify(const toml_managed_span_t *span, const toml_header_t *header,
unsigned char *seen, int *kind, size_t *table) {
size_t exact = 0U;
int exact_taken = 0;
size_t parent = 0U;
size_t parent_depth = 0U;
int result = TOML_EDIT_OK;
size_t pos = span->owned_first;
for (size_t index = 1U; pos < span->owned_len && result == TOML_EDIT_OK; ++index) {
toml_section_t declared;
if (toml_section_at(span->owned, pos, span->owned_len, &declared) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
pos = declared.end;
const toml_key_path_t *path = &declared.header.path;
if (toml_key_path_equal(path, &header->path)) {
if (declared.header.array != header->array) {
result = TOML_EDIT_ERR;
} else if (!seen[index] && exact == 0U) {
exact = index;
} else {
exact_taken = 1;
}
} else if (toml_key_path_has_prefix(&header->path, path)) {
if (declared.header.array) {
result = TOML_EDIT_ERR;
} else if (path->count > parent_depth) {
parent = index;
parent_depth = path->count;
}
}
toml_header_dispose(&declared.header);
}
if (result != TOML_EDIT_OK || (exact == 0U && exact_taken)) {
return TOML_EDIT_ERR;
}
if (exact != 0U) {
seen[exact] = 1U;
}
*kind = exact != 0U ? TOML_SPAN_OWNED : parent != 0U ? TOML_SPAN_ATTACHED : TOML_SPAN_FOREIGN;
*table = exact != 0U ? exact : parent;
return TOML_EDIT_OK;
}
/* Sets *written when the declared table assigns key; a key that only shares
* a dotted prefix with one it assigns would redefine it and is refused. */
static int toml_declared_writes_key(const toml_managed_span_t *span, const toml_section_t *declared,
const toml_key_path_t *key, int *written) {
*written = 0;
size_t cursor = declared->body;
toml_line_t line;
int multiline_state = TOML_STRING_NONE;
while (toml_next_line(span->owned, declared->end, &cursor, &line)) {
if (multiline_state == TOML_STRING_NONE) {
toml_assignment_t assignment;
if (toml_parse_assignment(span->owned, &line, &assignment) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
int equal = assignment.present && toml_key_path_equal(&assignment.key, key);
int collides = assignment.present && !equal &&
(toml_key_path_has_prefix(&assignment.key, key) ||
toml_key_path_has_prefix(key, &assignment.key));
toml_assignment_dispose(&assignment);
if (collides) {
return TOML_EDIT_ERR;
}
*written |= equal;
}
if (toml_scan_line_strings(span->owned, &line, &multiline_state) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
}
return TOML_EDIT_OK;
}
static size_t toml_line_first_char(const char *data, const toml_line_t *line) {
size_t pos = line->start;
while (pos < line->content_end && (data[pos] == ' ' || data[pos] == '\t')) {
pos++;
}
return pos;
}
/* Is this line, outside any multiline string, one the user owns? Comments
* are; an assignment is unless the declared table writes its key. */
static int toml_line_is_users(const toml_managed_span_t *span, const toml_section_t *declared,
const toml_line_t *line, int *users) {
if (span->data[toml_line_first_char(span->data, line)] == '#') {
*users = 1;
return TOML_EDIT_OK;
}
toml_assignment_t assignment;
int written = 0;
if (toml_parse_assignment(span->data, line, &assignment) != TOML_EDIT_OK ||
!assignment.present ||
toml_declared_writes_key(span, declared, &assignment.key, &written) != TOML_EDIT_OK) {
toml_assignment_dispose(&assignment);
return TOML_EDIT_ERR;
}
toml_assignment_dispose(&assignment);
*users = !written;
return TOML_EDIT_OK;
}
/* The lines of an owned section the block does not write, with the blank
* lines between them; blank lines before a replaced key or at the end of the
* section go with the section. */
static int toml_append_user_lines(const toml_managed_span_t *span, const toml_section_t *section,
size_t table, toml_buffer_t *output) {
toml_section_t declared;
if (toml_declared_table(span, table, NULL, &declared) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
size_t cursor = section->body;
toml_line_t line;
int multiline_state = TOML_STRING_NONE;
int keep = 0;
size_t blank_start = SIZE_MAX;
int result = TOML_EDIT_OK;
while (result == TOML_EDIT_OK && toml_next_line(span->data, section->end, &cursor, &line)) {
if (multiline_state == TOML_STRING_NONE) {
if (toml_line_first_char(span->data, &line) == line.content_end) {
blank_start = blank_start == SIZE_MAX ? line.start : blank_start;
continue;
}
result = toml_line_is_users(span, &declared, &line, &keep);
if (!keep) {
blank_start = SIZE_MAX;
}
}
if (result == TOML_EDIT_OK && keep) {
size_t from = blank_start == SIZE_MAX ? line.start : blank_start;
blank_start = SIZE_MAX;
result = toml_buffer_append(output, span->data + from, line.full_end - from);
}
if (result == TOML_EDIT_OK &&
toml_scan_line_strings(span->data, &line, &multiline_state) != TOML_EDIT_OK) {
result = TOML_EDIT_ERR;
}
}
toml_header_dispose(&declared.header);
return result == TOML_EDIT_OK && multiline_state == TOML_STRING_NONE ? TOML_EDIT_OK
: TOML_EDIT_ERR;
}
/* One pass over the span's tables in file order. Appends each section of
* want_kind (and, unless foreign, of declared table want_table): foreign and
* attached sections verbatim, an owned one as its user lines. Also reports
* how many sections are foreign and the kind of the last one. */
static int toml_managed_span_pass(const toml_managed_span_t *span, int want_kind, size_t want_table,
toml_buffer_t *output, size_t *foreign, int *last_kind) {
unsigned char seen[TOML_MANAGED_MAX_TABLES + 1U] = {0};
*foreign = 0U;
*last_kind = TOML_SPAN_LEAD;
size_t pos = span->lead_end;
while (pos < span->span_end) {
toml_section_t section;
int kind = TOML_SPAN_FOREIGN;
size_t table = 0U;
if (toml_section_at(span->data, pos, span->span_end, &section) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
int result = toml_managed_classify(span, &section.header, seen, &kind, &table);
toml_header_dispose(&section.header);
pos = section.end;
*foreign += kind == TOML_SPAN_FOREIGN;
*last_kind = kind;
if (result == TOML_EDIT_OK && kind == want_kind &&
(kind == TOML_SPAN_FOREIGN || table == want_table)) {
result = kind == TOML_SPAN_OWNED
? toml_append_user_lines(span, &section, table, output)
: toml_buffer_append(output, span->data + section.start,
section.end - section.start);
}
if (result != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
}
return TOML_EDIT_OK;
}
/* The declared tables of an install, each followed by what the span keeps
* for it: the user lines of its owned section, then its attached tables. */
static int toml_append_managed_tables(const toml_managed_span_t *span, size_t tables,
const char *newline, toml_buffer_t *output) {
size_t foreign = 0U;
int last_kind = TOML_SPAN_LEAD;
if (toml_append_normalized_text(output, span->owned, span->owned_first, newline) !=
TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
for (size_t table = 1U; table <= tables; ++table) {
toml_section_t declared;
if (toml_declared_table(span, table, NULL, &declared) != TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
toml_header_dispose(&declared.header);
if (toml_append_normalized_text(output, span->owned + declared.start,
declared.end - declared.start, newline) != TOML_EDIT_OK ||
(output->data[output->len - 1U] != '\n' &&
toml_buffer_append_cstr(output, newline) != TOML_EDIT_OK) ||
toml_managed_span_pass(span, TOML_SPAN_OWNED, table, output, &foreign, &last_kind) !=
TOML_EDIT_OK ||
toml_managed_span_pass(span, TOML_SPAN_ATTACHED, table, output, &foreign, &last_kind) !=
TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
}
return output->len == 0U || output->data[output->len - 1U] == '\n' ||
toml_buffer_append_cstr(output, newline) == TOML_EDIT_OK
? TOML_EDIT_OK
: TOML_EDIT_ERR;
}
/* Rebuild existing with its managed span rewritten around `owned` (install)
* or removed (uninstall), keeping everything the span holds that is not
* ours. `owned` is the block on install and the declaration of our tables on
* removal. */
static int toml_managed_rewrite(const char *existing, size_t existing_len,
const toml_line_t *begin_line, const toml_line_t *end_line,
const char *begin_marker, const char *end_marker, const char *owned,
size_t owned_len, int install, toml_buffer_t *output) {
toml_managed_span_t span = {
.data = existing,
.span_end = end_line->start,
.owned = owned,
.owned_len = owned_len,
};
size_t tables = 0U;
size_t tail_lead_end = existing_len;
if (toml_section_end(owned, 0U, owned_len, &span.owned_first) != TOML_EDIT_OK ||
toml_declared_table(&span, 0U, &tables, NULL) != TOML_EDIT_OK ||
toml_section_end(existing, begin_line->full_end, span.span_end, &span.lead_end) !=
TOML_EDIT_OK ||
toml_section_end(existing, end_line->full_end, existing_len, &tail_lead_end) !=
TOML_EDIT_OK) {
return TOML_EDIT_ERR;
}
toml_buffer_t moved = {0};
size_t foreign = 0U;
int last_kind = TOML_SPAN_LEAD;
if (toml_managed_span_pass(&span, TOML_SPAN_FOREIGN, 0U, &moved, &foreign, &last_kind) !=
TOML_EDIT_OK ||
(foreign != 0U && last_kind != TOML_SPAN_FOREIGN &&
toml_lines_significant(existing, end_line->full_end, tail_lead_end))) {
toml_buffer_dispose(&moved);
return TOML_EDIT_ERR;
}
size_t prefix_len = begin_line->start;
if (prefix_len == 0U && existing_len >= 3U && (unsigned char)existing[0] == 0xefU &&
(unsigned char)existing[1] == 0xbbU && (unsigned char)existing[2] == 0xbfU) {
prefix_len = 3U;
}
const char *newline = toml_newline_style(existing, existing_len);
int keep_lead = !toml_lines_significant(owned, 0U, span.owned_first);
size_t block_start = 0U;
size_t block_end = 0U;
int result = toml_buffer_append(output, existing, prefix_len) == TOML_EDIT_OK &&
(!keep_lead ||
toml_buffer_append(output, existing + begin_line->full_end,
span.lead_end - begin_line->full_end) == TOML_EDIT_OK)
? TOML_EDIT_OK
: TOML_EDIT_ERR;
if (result == TOML_EDIT_OK && install) {
block_start = output->len;
result =
toml_buffer_append_cstr(output, begin_marker) == TOML_EDIT_OK &&
toml_buffer_append_cstr(output, newline) == TOML_EDIT_OK &&
toml_append_managed_tables(&span, tables, newline, output) == TOML_EDIT_OK &&
toml_buffer_append_cstr(output, end_marker) == TOML_EDIT_OK &&
toml_buffer_append_cstr(output, newline) == TOML_EDIT_OK
? TOML_EDIT_OK
: TOML_EDIT_ERR;
block_end = output->len;
}
if (result == TOML_EDIT_OK &&
(toml_buffer_append(output, moved.data, moved.len) != TOML_EDIT_OK ||
toml_buffer_append(output, existing + end_line->full_end,
existing_len - end_line->full_end) != TOML_EDIT_OK ||
(install && toml_managed_block_conflicts(output->data, output->len, block_start, block_end,
owned, owned_len) != TOML_EDIT_OK))) {
result = TOML_EDIT_ERR;
}
toml_buffer_dispose(&moved);
return result;
}
static int toml_finish_target_table(toml_target_table_t *current, toml_table_scan_t *result) {
if (!current->active) {
return TOML_EDIT_OK;
@@ -2516,10 +2970,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 +3195,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;
}
+19 -6
View File
@@ -24,18 +24,31 @@ int cbm_toml_escape_basic_string(const char *input, char *out, size_t out_size);
*
* Insert or replace one managed, line-delimited block. block is the body
* between the two marker lines. Duplicate or unbalanced markers are rejected
* without changing the file. */
* without changing the file. An existing span keeps what is not ours (#2228):
* keys and comments the block does not write stay in the tables it declares,
* with those tables' sub-tables; lines before the span's first table move
* above the block and any other table moves, byte for byte and in order, to
* just after it. Content whose ownership is ambiguous fails closed. */
int cbm_toml_upsert_managed_block(const char *file_path, const char *begin_marker,
const char *end_marker, const char *block);
/* Removes the whole span between the markers. */
int cbm_toml_remove_managed_block(const char *file_path, const char *begin_marker,
const char *end_marker);
/* Removes the markers and only the tables owned_tables declares (e.g. the
* block's header lines), with their keys and sub-tables; every other line of
* the span stays in place. Ambiguous ownership fails closed (#2228). */
int cbm_toml_remove_managed_block_owned(const char *file_path, const char *begin_marker,
const char *end_marker, const char *owned_tables);
/* 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);
+20 -8
View File
@@ -59,8 +59,9 @@
*
* Observability (#858): a fired deadline is otherwise indistinguishable from
* "no matches", so the handler first write()s a pre-formatted breadcrumb to
* ~/.cache/codebase-memory-mcp/logs/hook-augment-timeouts.log (fd and message
* prepared at arm time — only async-signal-safe write/_exit in the handler). */
* <cache_dir>/logs/hook-augment-timeouts.log (by default
* ~/.cache/codebase-memory-mcp/logs; fd and message prepared at arm time —
* only async-signal-safe write/_exit in the handler). */
#ifndef _WIN32
#define HA_DEADLINE_DEFAULT_MS 2000 /* in-process budget; see ha_deadline_ms() */
#define HA_DEADLINE_MIN_MS 50
@@ -103,20 +104,31 @@ static void ha_deadline_exit(int sig) {
_exit(0);
}
/* Whether snprintf wrote the whole string into a buffer of `cap` bytes. */
static bool ha_fits(int written, size_t cap) {
return written > 0 && (size_t)written < cap;
}
static void ha_open_crumb_log(int deadline_ms) {
const char *override = getenv("CBM_HOOK_TIMEOUT_LOG"); /* tests + power users */
char path[CBM_SZ_1K];
/* A path cut off at the buffer names some other file, and O_CREAT would
* create it. Such a path means no breadcrumb; the hook itself runs on. */
if (override && override[0]) {
snprintf(path, sizeof(path), "%s", override);
} else {
const char *home = getenv("HOME");
if (!home || !home[0]) {
if (!ha_fits(snprintf(path, sizeof(path), "%s", override), sizeof(path))) {
return;
}
} else {
/* <cache_dir>/logs, where every cbm component logs: the cache dir is
* CBM_CACHE_DIR, else HOME (then USERPROFILE) + the default. */
const char *cache = cbm_resolve_cache_dir();
char dir[CBM_SZ_1K];
snprintf(dir, sizeof(dir), "%s/.cache/codebase-memory-mcp/logs", home);
if (!cache || !ha_fits(snprintf(dir, sizeof(dir), "%s/logs", cache), sizeof(dir)) ||
!ha_fits(snprintf(path, sizeof(path), "%s/hook-augment-timeouts.log", dir),
sizeof(path))) {
return;
}
cbm_mkdir_p_ex(dir, 0755, CBM_MKDIR_FOLLOW_OWNED);
snprintf(path, sizeof(path), "%s/hook-augment-timeouts.log", dir);
}
g_ha_crumb_fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (g_ha_crumb_fd < 0) {
+263 -25
View File
@@ -12,6 +12,8 @@
#include "foundation/platform.h"
#include "foundation/limits.h"
#include "foundation/log.h"
#include "foundation/hash_table.h"
#include "foundation/mem_core.h"
enum {
CYP_BUF_16 = 16,
@@ -2594,6 +2596,12 @@ static const char *resolve_condition_value(const cbm_condition_t *c, binding_t *
return n->name ? n->name : "";
}
/* Set when an `=~` or inline-property pattern was refused by the regex
* wrapper's compile-size guard during the CURRENT execution; cbm_cypher_execute
* turns it into result->warning so an empty result can be told from "no such
* name". Reset at the start of every execution. */
static _Thread_local bool g_cypher_regex_refused = false;
/* Evaluate a comparison operator between actual and expected strings. */
static bool eval_comparison_op(const char *op, const char *actual, const char *expected) {
if (strcmp(op, "=") == 0) {
@@ -2604,7 +2612,11 @@ static bool eval_comparison_op(const char *op, const char *actual, const char *e
}
if (strcmp(op, "=~") == 0) {
cbm_regex_t re;
if (cbm_regcomp(&re, expected, CBM_REG_EXTENDED | CBM_REG_NOSUB) != 0) {
int comp_rc = cbm_regcomp(&re, expected, CBM_REG_EXTENDED | CBM_REG_NOSUB);
if (comp_rc != 0) {
if (comp_rc == CBM_REG_ETOOBIG) {
g_cypher_regex_refused = true;
}
return false;
}
int rc = cbm_regexec(&re, actual, 0, NULL, 0);
@@ -2766,6 +2778,96 @@ static bool eval_where(const cbm_where_clause_t *w, binding_t *b) {
return is_and;
}
/* Three-valued WHERE evaluation for the early (seed-row) pass in
* execute_single: only the first MATCH alias is bound there, so a leaf on
* any other alias is UNKNOWN rather than true. The two-valued evaluator
* returns true for an unbound alias, which NOT / XOR then invert -- pruning
* every seed before relationship expansion (distilled from PR #1245). The
* full evaluation reruns after expansion (Step 3), so the early pass only has
* to prune on a definite false. Allocation-free, O(expression nodes). */
typedef enum { CYP_PARTIAL_FALSE = 0, CYP_PARTIAL_TRUE, CYP_PARTIAL_UNKNOWN } cyp_partial_t;
static cyp_partial_t partial_and(cyp_partial_t l, cyp_partial_t r) {
if (l == CYP_PARTIAL_FALSE || r == CYP_PARTIAL_FALSE) {
return CYP_PARTIAL_FALSE;
}
return (l == CYP_PARTIAL_TRUE && r == CYP_PARTIAL_TRUE) ? CYP_PARTIAL_TRUE
: CYP_PARTIAL_UNKNOWN;
}
static cyp_partial_t partial_or(cyp_partial_t l, cyp_partial_t r) {
if (l == CYP_PARTIAL_TRUE || r == CYP_PARTIAL_TRUE) {
return CYP_PARTIAL_TRUE;
}
return (l == CYP_PARTIAL_FALSE && r == CYP_PARTIAL_FALSE) ? CYP_PARTIAL_FALSE
: CYP_PARTIAL_UNKNOWN;
}
/* A condition whose alias is not bound yet is UNKNOWN; a literal-only LHS
* (func condition with no variable arg) has nothing to wait for. */
static cyp_partial_t eval_condition_partial(const cbm_condition_t *c, binding_t *b) {
if (c->variable && !binding_get(b, c->variable) && !binding_get_edge(b, c->variable)) {
return CYP_PARTIAL_UNKNOWN;
}
return eval_condition(c, b) ? CYP_PARTIAL_TRUE : CYP_PARTIAL_FALSE;
}
static cyp_partial_t eval_expr_partial(const cbm_expr_t *e, // NOLINT(misc-no-recursion)
binding_t *b) {
if (!e) {
return CYP_PARTIAL_TRUE;
}
if (e->type == EXPR_CONDITION) {
return eval_condition_partial(&e->cond, b);
}
cyp_partial_t left = eval_expr_partial(e->left, b);
if (e->type == EXPR_NOT) {
if (left == CYP_PARTIAL_UNKNOWN) {
return CYP_PARTIAL_UNKNOWN;
}
return left == CYP_PARTIAL_TRUE ? CYP_PARTIAL_FALSE : CYP_PARTIAL_TRUE;
}
/* Same short-circuits as eval_expr: a definite left decides AND / OR. */
if (e->type == EXPR_AND && left == CYP_PARTIAL_FALSE) {
return CYP_PARTIAL_FALSE;
}
if (e->type == EXPR_OR && left == CYP_PARTIAL_TRUE) {
return CYP_PARTIAL_TRUE;
}
cyp_partial_t right = eval_expr_partial(e->right, b);
if (e->type == EXPR_AND) {
return partial_and(left, right);
}
if (e->type == EXPR_OR) {
return partial_or(left, right);
}
/* EXPR_XOR */
if (left == CYP_PARTIAL_UNKNOWN || right == CYP_PARTIAL_UNKNOWN) {
return CYP_PARTIAL_UNKNOWN;
}
return left != right ? CYP_PARTIAL_TRUE : CYP_PARTIAL_FALSE;
}
static cyp_partial_t eval_where_partial(const cbm_where_clause_t *w, binding_t *b) {
if (!w) {
return CYP_PARTIAL_TRUE;
}
if (w->root) {
return eval_expr_partial(w->root, b);
}
/* Legacy flat evaluation */
if (w->count == 0) {
return CYP_PARTIAL_TRUE;
}
bool is_and = (w->op && strcmp(w->op, "AND") == 0) != 0;
cyp_partial_t result = is_and ? CYP_PARTIAL_TRUE : CYP_PARTIAL_FALSE;
for (int i = 0; i < w->count; i++) {
cyp_partial_t r = eval_condition_partial(&w->conditions[i], b);
result = is_and ? partial_and(result, r) : partial_or(result, r);
}
return result;
}
/* Check if a string value looks like a regex pattern. */
static bool looks_like_regex(const char *s) {
if (!s) {
@@ -2784,13 +2886,17 @@ static bool check_inline_props(const cbm_node_t *n, const cbm_prop_filter_t *pro
const char *actual = node_prop(n, props[i].key, store);
if (looks_like_regex(props[i].value)) {
cbm_regex_t re;
if (cbm_regcomp(&re, props[i].value, CBM_REG_EXTENDED | CBM_REG_NOSUB) == 0) {
int comp_rc = cbm_regcomp(&re, props[i].value, CBM_REG_EXTENDED | CBM_REG_NOSUB);
if (comp_rc == 0) {
bool matched = cbm_regexec(&re, actual, 0, NULL, 0) == 0;
cbm_regfree(&re);
if (!matched) {
return false;
}
} else if (strcmp(actual, props[i].value) != 0) {
if (comp_rc == CBM_REG_ETOOBIG) {
g_cypher_regex_refused = true;
}
return false;
}
} else if (strcmp(actual, props[i].value) != 0) {
@@ -2837,6 +2943,104 @@ static void rb_add_row(result_builder_t *rb, const char **values) {
rb->rows[rb->row_count++] = row;
}
/* ── DISTINCT while projecting (#1364) ─────────────────────────────
*
* RETURN DISTINCT used to project up to the engine row cap and only then drop
* duplicates, so a value first seen past the cap never reached the result: on
* a 150k-edge index `RETURN DISTINCT type(r)` lost its one HAS_BRANCH edge.
* The projection loops now de-duplicate as they go, so the cap counts DISTINCT
* rows. Memory stays bounded by the cap: only admitted rows are remembered;
* rows past the cap are probed (no insert) solely to decide `truncated`. */
typedef struct {
CBMHashTable *seen; /* row key -> the same heap key; NULL = not DISTINCT */
} rb_distinct_t;
static void rb_distinct_init(rb_distinct_t *d, bool distinct) {
d->seen = distinct ? cbm_ht_create(CBM_SZ_64) : NULL;
}
static void rb_distinct_free_key(const char *key, void *value, void *userdata) {
(void)key;
(void)userdata;
cbm_free(CBM_MEM_CLASS_OTHER, value);
}
static void rb_distinct_free(rb_distinct_t *d) {
if (d->seen) {
cbm_ht_foreach(d->seen, rb_distinct_free_key, NULL);
cbm_ht_free(d->seen);
d->seen = NULL;
}
}
/* Length-prefixed row key ("<len>:<value>" per column), so no value content
* can make two different rows collide. NULL projects as "" (as rb_add_row). */
static char *rb_distinct_row_key(const char **vals, int n) {
size_t total = SKIP_ONE;
for (int i = 0; i < n; i++) {
total += (vals[i] ? strlen(vals[i]) : 0) + CBM_SZ_32;
}
char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, total);
if (!key) {
return NULL;
}
size_t pos = 0;
key[0] = '\0';
for (int i = 0; i < n; i++) {
const char *v = vals[i] ? vals[i] : "";
int w = snprintf(key + pos, total - pos, "%zu:%s", strlen(v), v);
if (w > 0) {
pos += (size_t)w;
}
}
return key;
}
/* Admission for one projected row. Returns false for a row DISTINCT already
* holds. On true, *key_out is the key to hand to rb_distinct_keep (NULL when
* not DISTINCT, or when the key allocation failed — the row is then admitted
* without de-duplication rather than dropped). */
static bool rb_distinct_is_new(const rb_distinct_t *d, const char **vals, int n, char **key_out) {
*key_out = NULL;
if (!d->seen) {
return true;
}
char *key = rb_distinct_row_key(vals, n);
if (!key) {
return true;
}
if (cbm_ht_has(d->seen, key)) {
cbm_free(CBM_MEM_CLASS_OTHER, key);
return false;
}
*key_out = key;
return true;
}
static void rb_distinct_keep(rb_distinct_t *d, char *key) {
if (key) {
cbm_ht_set(d->seen, key, key);
}
}
/* Add one projected row under a row cap, de-duplicating when DISTINCT.
* Returns false once a NEW row arrives with the cap already full: the caller
* stops there, and flags truncation when the cap is the engine budget. A
* duplicate past the cap is neither kept nor evidence of truncation. */
static bool rb_add_row_capped(result_builder_t *rb, rb_distinct_t *d, const char **vals, int cap) {
char *key = NULL;
if (!rb_distinct_is_new(d, vals, rb->col_count, &key)) {
return true;
}
if (rb->row_count >= cap) {
cbm_free(CBM_MEM_CLASS_OTHER, key);
return false;
}
rb_distinct_keep(d, key);
rb_add_row(rb, vals);
return true;
}
/* ── Main execution ─────────────────────────────────────────────── */
/* Hard ceiling: queries returning more than this trigger an error instead of data.
@@ -4359,14 +4563,20 @@ static void execute_return_star_after_with(cbm_query_t *q, binding_t *bindings,
cols[i] = resolve_item_alias(&wc->items[i], name_bufs[i], sizeof(name_bufs[i]));
}
rb_set_columns(rb, cols, col_n);
for (int bi = 0; bi < bind_count && rb->row_count < max_rows; bi++) {
rb_distinct_t seen;
rb_distinct_init(&seen, q->ret && q->ret->distinct);
for (int bi = 0; bi < bind_count; bi++) {
const char *vals[CYP_MAX_VARS];
for (int i = 0; i < col_n; i++) {
cbm_node_t *vn = binding_get(&bindings[bi], cols[i]);
vals[i] = vn && vn->name ? vn->name : "";
}
rb_add_row(rb, vals);
if (!rb_add_row_capped(rb, &seen, vals, max_rows)) {
g_cypher_truncated = true;
break;
}
}
rb_distinct_free(&seen);
}
static void execute_return_star(cbm_query_t *q, binding_t *bindings, int bind_count, int max_rows,
@@ -4381,19 +4591,22 @@ static void execute_return_star(cbm_query_t *q, binding_t *bindings, int bind_co
int projection_cap = max_rows;
bool cap_is_engine_budget = true;
cbm_return_clause_t *ret = q->ret;
if (ret && ret->limit >= 0 && ret->limit <= max_rows && !ret->distinct &&
ret->order_key_count == 0 && ret->skip <= 0) {
projection_cap = ret->limit;
if (ret && ret->limit >= 0 && ret->limit <= max_rows && ret->order_key_count == 0 &&
ret->skip <= 0) {
projection_cap = ret->limit; /* DISTINCT: the cap counts distinct rows (#1364) */
cap_is_engine_budget = false;
}
for (int bi = 0; bi < bind_count && rb->row_count < projection_cap; bi++) {
rb_distinct_t seen;
rb_distinct_init(&seen, ret && ret->distinct);
for (int bi = 0; bi < bind_count; bi++) {
const char *vals[CBM_SZ_128];
project_star_row(&bindings[bi], vars, vc, vals);
rb_add_row(rb, vals);
}
if (cap_is_engine_budget && bind_count > projection_cap) {
g_cypher_truncated = true;
if (!rb_add_row_capped(rb, &seen, vals, projection_cap)) {
g_cypher_truncated = g_cypher_truncated || cap_is_engine_budget;
break;
}
}
rb_distinct_free(&seen);
}
/* Format an aggregate value into buf based on function name */
@@ -4662,22 +4875,25 @@ static void execute_return_simple(cbm_return_clause_t *ret, binding_t *bindings,
int max_rows, result_builder_t *rb) {
int proj_cap = max_rows;
bool cap_is_engine_budget = true;
if (ret->limit >= 0 && !ret->distinct && ret->order_key_count == 0 && ret->skip <= 0) {
proj_cap = ret->limit;
if (ret->limit >= 0 && ret->order_key_count == 0 && ret->skip <= 0) {
proj_cap = ret->limit; /* DISTINCT: the cap counts distinct rows (#1364) */
cap_is_engine_budget = false;
}
for (int bi = 0; bi < bind_count && rb->row_count < proj_cap; bi++) {
rb_distinct_t seen;
rb_distinct_init(&seen, ret->distinct);
for (int bi = 0; bi < bind_count; bi++) {
const char *vals[CBM_SZ_32];
char func_bufs[CBM_SZ_32][CBM_SZ_512];
for (int ci = 0; ci < ret->count; ci++) {
vals[ci] =
project_item(&bindings[bi], &ret->items[ci], func_bufs[ci], sizeof(func_bufs[ci]));
}
rb_add_row(rb, vals);
}
if (cap_is_engine_budget && bind_count > proj_cap) {
g_cypher_truncated = true;
if (!rb_add_row_capped(rb, &seen, vals, proj_cap)) {
g_cypher_truncated = g_cypher_truncated || cap_is_engine_budget;
break;
}
}
rb_distinct_free(&seen);
}
/* Build default 3-column headers (name, qualified_name, label) per variable */
@@ -4822,9 +5038,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++) {
@@ -5016,7 +5235,9 @@ static void execute_return_clause(cbm_query_t *q, cbm_return_clause_t *ret, bind
}
}
if (ret->distinct) {
/* The simple and star projections de-duplicate while projecting (#1364);
* only aggregate rows still need the post-pass. */
if (ret->distinct && has_agg && !ret->star) {
rb_apply_distinct(rb);
}
rb_apply_order_by(rb, ret);
@@ -5135,7 +5356,11 @@ static int execute_single(cbm_store_t *store, cbm_query_t *q, const char *projec
/* Build initial bindings with early WHERE */
int bind_cap = scan_count > max_rows ? scan_count : (max_rows > 0 ? max_rows : SKIP_ONE);
binding_t *bindings = malloc((bind_cap + SKIP_ONE) * sizeof(binding_t));
binding_t *bindings = malloc(((size_t)bind_cap + SKIP_ONE) * sizeof(binding_t));
if (!bindings) {
cbm_store_free_nodes(scanned, scan_count);
return CBM_NOT_FOUND; /* initial binding array refused */
}
int bind_count = 0;
const char *var_name = pat0->nodes[0].variable ? pat0->nodes[0].variable : CYP_ANON_HEAD_VAR;
@@ -5146,7 +5371,7 @@ static int execute_single(cbm_store_t *store, cbm_query_t *q, const char *projec
binding_t b = {0};
b.store = store;
binding_set(&b, var_name, &scanned[i]);
bool pass = !q->where || eval_where(q->where, &b);
bool pass = eval_where_partial(q->where, &b) != CYP_PARTIAL_FALSE;
if (pass) {
bindings[bind_count++] = b;
} else {
@@ -5444,8 +5669,11 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projec
g_cypher_depth_clamped = 0;
g_cypher_trail_truncated = 0;
g_cypher_truncated = false;
g_cypher_regex_refused = false;
cypher_deadline_arm(); /* #601: start the wall-clock budget for this query */
if (max_rows <= 0) {
/* max_rows sizes the initial binding array: non-positive means the
* ceiling, and nothing above the ceiling is ever materialized anyway. */
if (max_rows <= 0 || max_rows > CYPHER_RESULT_CEILING) {
max_rows = CYPHER_RESULT_CEILING;
}
@@ -5531,8 +5759,8 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projec
/* Any internal ceiling that prevented exhaustive evaluation: a candidate or
* traversal budget, or a variable-length range clamped to the engine cap. */
out->truncated = g_cypher_truncated || g_cypher_trail_truncated != 0;
char wbuf[CBM_SZ_512] = "";
if (g_cypher_depth_clamped > 0 || g_cypher_trail_truncated) {
char wbuf[CBM_SZ_256];
if (g_cypher_depth_clamped > 0 && g_cypher_trail_truncated) {
snprintf(wbuf, sizeof(wbuf),
"variable-length hop range clamped to the engine ceiling (%d) and "
@@ -5547,6 +5775,16 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projec
snprintf(wbuf, sizeof(wbuf),
"variable-length traversal budget was exhausted — results may be partial");
}
}
/* A refused `=~` or property pattern matched nothing: say so, once per
* query, next to any traversal warning. */
if (g_cypher_regex_refused) {
size_t used = strlen(wbuf);
snprintf(wbuf + used, sizeof(wbuf) - used,
"%sa =~ or property " CBM_REG_ETOOBIG_REASON " — the comparison matched nothing",
used ? "; " : "");
}
if (wbuf[0]) {
out->warning = heap_strdup(wbuf);
}
+2 -1
View File
@@ -334,7 +334,8 @@ typedef struct {
} cbm_cypher_result_t;
/* Execute a Cypher query against a store.
* max_rows: limit on output rows (0 = use virtual ceiling of 100k).
* max_rows: limit on output rows; 0 or any value above the 100k ceiling uses
* the ceiling.
* project: project name filter (NULL = all projects).
* Returns -1 on error (check out->error for message). */
int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *project, int max_rows,
+9
View File
@@ -1349,6 +1349,15 @@ static char *application_job_failure_response(const cbm_index_worker_result_t *r
(void)snprintf(message, sizeof(message),
"index worker containment failed (%s); inspect log: %s",
cbm_proc_outcome_str(result->outcome), log_path ? log_path : "unavailable");
} else if (result && result->response_missing) {
/* #1300: name the silent clean exit, where it stopped, and the log. */
const char *log = log_path ? log_path
: result->worker_log[0] ? result->worker_log
: "unavailable";
(void)snprintf(message, sizeof(message),
"index worker exited cleanly (exit 0) without writing a response; the "
"index was not published; last phase reached: %s; inspect log: %s",
result->last_phase[0] ? result->last_phase : "unknown", log);
} else if (result) {
(void)snprintf(message, sizeof(message),
"index worker ended with %s (exit=%d, signal=%d); inspect log: %s",
+6
View File
@@ -609,6 +609,12 @@ static bool host_state_prepare(host_state_t *host, const cbm_daemon_ipc_endpoint
if (watcher_enabled) {
host->watch_store = cbm_store_open_memory();
host->watcher = cbm_watcher_new(host->watch_store, host_watcher_index, host);
/* #1948: non-git roots stay unwatched unless watch_non_git opts in.
* Same read-once-at-startup contract as watcher_enabled. */
if (host->watcher && cbm_config_watch_non_git(host->runtime_config)) {
cbm_watcher_set_poll_non_git(host->watcher, true);
cbm_log_info("watcher.non_git", "mode", "tree_poll");
}
} else {
cbm_log_info("watcher.disabled", "reason", "config");
}
+18
View File
@@ -7078,3 +7078,21 @@ int cbm_daemon_ipc_receive_frame(cbm_daemon_ipc_connection_t *connection, uint32
return cbm_daemon_ipc_receive_frame_bounded(connection, timeout_ms, CBM_DAEMON_MAX_FRAME_SIZE,
frame_out, payload_out);
}
int cbm_daemon_ipc_receive_frame_after_failed_send(cbm_daemon_ipc_connection_t *connection,
uint32_t timeout_ms, uint32_t max_payload_length,
cbm_daemon_frame_t *frame_out,
uint8_t **payload_out) {
if (!connection) {
return cbm_daemon_ipc_receive_frame_bounded(NULL, timeout_ms, max_payload_length, frame_out,
payload_out);
}
/* The poison came from the failed send alone (nothing was read yet), and it
* guards the OUTBOUND frame boundary; the inbound one is intact. Lift it for
* this one receive, then restore it so no later send can reuse the stream. */
atomic_store_explicit(&connection->poisoned, false, memory_order_release);
int received = cbm_daemon_ipc_receive_frame_bounded(connection, timeout_ms, max_payload_length,
frame_out, payload_out);
atomic_store_explicit(&connection->poisoned, true, memory_order_release);
return received;
}
+16
View File
@@ -75,6 +75,22 @@ int cbm_daemon_ipc_receive_frame_bounded(cbm_daemon_ipc_connection_t *connection
uint32_t timeout_ms, uint32_t max_payload_length,
cbm_daemon_frame_t *frame_out, uint8_t **payload_out);
/* Bounded receive of an answer the peer queued before it closed, on a
* connection whose send just failed. A daemon at capacity or stopping answers
* from its accept loop without reading the request and closes at once; when
* that close lands before the client's first send, the send fails (EPIPE) and
* poisons the connection although the complete answer is still queued for
* reading -- POSIX keeps it readable after the peer's close (a Windows server
* close discards it, so there this fails like any other receive). A failed
* send consumes no inbound bytes, so the inbound frame boundary is intact;
* call this ONLY before anything was read from the connection. The connection
* stays poisoned for sends afterwards. Returns like
* cbm_daemon_ipc_receive_frame_bounded. */
int cbm_daemon_ipc_receive_frame_after_failed_send(cbm_daemon_ipc_connection_t *connection,
uint32_t timeout_ms, uint32_t max_payload_length,
cbm_daemon_frame_t *frame_out,
uint8_t **payload_out);
/* Narrow crash/fault seams for publication-state and retry-state tests. They
* are inert unless a test installs a hook/failure count in its own process. */
typedef enum {
+72 -8
View File
@@ -76,8 +76,26 @@ 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);
}
/* Connection-cap seams (flaky-ledger item 12): see runtime.h. */
static atomic_bool runtime_hold_peer_waits_seam;
void cbm_daemon_runtime_hold_peer_waits_for_testing(bool hold) {
atomic_store(&runtime_hold_peer_waits_seam, hold);
}
static _Atomic(cbm_daemon_runtime_hello_hook_t) runtime_hello_hook_seam;
void cbm_daemon_runtime_set_hello_hook_for_testing(cbm_daemon_runtime_hello_hook_t hook) {
atomic_store(&runtime_hello_hook_seam, hook);
}
static void runtime_hello_point(cbm_daemon_runtime_hello_point_t point) {
cbm_daemon_runtime_hello_hook_t hook = atomic_load(&runtime_hello_hook_seam);
if (hook) {
hook(point);
}
}
#define RUNTIME_HELLO_POINT(point) runtime_hello_point(CBM_DAEMON_RUNTIME_HELLO_POINT_##point)
#else
static void runtime_note_peer_image_hash(void) {}
#define RUNTIME_HELLO_POINT(point) ((void)0)
#endif
#ifdef _WIN32
@@ -1989,6 +2007,29 @@ static void runtime_worker_handle_activation_shutdown(cbm_daemon_runtime_worker_
runtime_worker_finish(worker);
}
/* The first frame is due within the request deadline. Under the item-12 seam a
* connection that never sends one holds its slot until it closes; stop still
* interrupts the wait like any other worker receive. */
static uint32_t runtime_first_frame_timeout_ms(const cbm_daemon_runtime_service_t *service) {
#ifdef CBM_ENABLE_TEST_SEAMS
if (atomic_load(&runtime_hold_peer_waits_seam)) {
return CBM_DAEMON_IPC_WAIT_FOREVER;
}
#endif
return service->request_timeout_ms;
}
/* Under the same seam an inline rejection's drain ends only on the peer's
* close, never on the 250 ms bound (the drain only waits on Windows). */
static uint32_t runtime_reject_drain_timeout_ms(void) {
#ifdef CBM_ENABLE_TEST_SEAMS
if (atomic_load(&runtime_hold_peer_waits_seam)) {
return CBM_DAEMON_IPC_WAIT_FOREVER;
}
#endif
return RUNTIME_REJECT_DRAIN_TIMEOUT_MS;
}
static void *runtime_connection_worker(void *opaque) {
cbm_daemon_runtime_worker_t *worker = opaque;
cbm_daemon_runtime_service_t *service = worker->service;
@@ -1998,7 +2039,7 @@ static void *runtime_connection_worker(void *opaque) {
char requested_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
int received = cbm_daemon_ipc_receive_frame_bounded(
worker->connection, service->request_timeout_ms,
worker->connection, runtime_first_frame_timeout_ms(service),
CBM_DAEMON_ACTIVATION_SHUTDOWN_REQUEST_SIZE, &frame, &payload);
if (received != 1 || frame.type != CBM_DAEMON_FRAME_REQUEST) {
free(payload);
@@ -2274,14 +2315,19 @@ static cbm_daemon_runtime_worker_t *runtime_find_free_worker_locked(
return NULL;
}
/* Answers WITHOUT reading the peer's HELLO, so on POSIX (where the drain is a
* no-op) the close can land before the peer has even sent it; the client reads
* this answer after its failed send (cbm_daemon_runtime_client_connect). */
static void runtime_reject_inline(cbm_daemon_ipc_connection_t *connection, const char *message) {
cbm_daemon_runtime_connect_result_t result;
runtime_result_rejected(&result, message);
RUNTIME_HELLO_POINT(DAEMON_REJECTING);
(void)runtime_send_hello_response(connection, &result);
/* Same Windows named-pipe discard hazard as runtime_worker_finish: the
* peer must get to read the rejection before the handle closes. */
cbm_daemon_ipc_connection_drain(connection, RUNTIME_REJECT_DRAIN_TIMEOUT_MS);
cbm_daemon_ipc_connection_drain(connection, runtime_reject_drain_timeout_ms());
cbm_daemon_ipc_connection_close(connection);
RUNTIME_HELLO_POINT(DAEMON_REJECTED);
}
static void runtime_accept_connection(cbm_daemon_runtime_service_t *service,
@@ -3063,21 +3109,39 @@ cbm_daemon_runtime_client_t *cbm_daemon_runtime_client_connect(
return NULL;
}
cbm_daemon_ipc_connection_t *connection = cbm_daemon_ipc_connect(endpoint, timeout_ms);
if (!connection || !cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST,
CBM_DAEMON_RUNTIME_OP_HELLO, request,
(uint32_t)sizeof(request))) {
cbm_daemon_ipc_connection_close(connection);
if (!connection) {
return NULL;
}
RUNTIME_HELLO_POINT(CLIENT_CONNECTED);
bool hello_sent =
cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST, CBM_DAEMON_RUNTIME_OP_HELLO,
request, (uint32_t)sizeof(request));
RUNTIME_HELLO_POINT(CLIENT_SENT);
cbm_daemon_frame_t frame = {0};
uint8_t *payload = NULL;
int received = cbm_daemon_ipc_receive_frame_bounded(
connection, timeout_ms, CBM_DAEMON_RENDEZVOUS_RESPONSE_SIZE, &frame, &payload);
/* A daemon at capacity or stopping answers from its accept loop without
* reading this HELLO and closes at once. When that close lands first, the
* send fails (EPIPE) with the whole answer already queued here: read it,
* or the caller gets a bare transport error and bootstrap classifies by
* lock state instead of by the daemon's own "capacity" / "stopping". */
int received =
hello_sent
? cbm_daemon_ipc_receive_frame_bounded(
connection, timeout_ms, CBM_DAEMON_RENDEZVOUS_RESPONSE_SIZE, &frame, &payload)
: cbm_daemon_ipc_receive_frame_after_failed_send(
connection, timeout_ms, CBM_DAEMON_RENDEZVOUS_RESPONSE_SIZE, &frame, &payload);
bool valid = received == 1 && frame.type == CBM_DAEMON_FRAME_RESPONSE &&
frame.flags == CBM_DAEMON_RUNTIME_OP_HELLO &&
frame.length == CBM_DAEMON_RENDEZVOUS_RESPONSE_SIZE &&
runtime_hello_response_decode(payload, result_out);
free(payload);
if (!hello_sent && (!valid || result_out->status != CBM_DAEMON_RUNTIME_CONNECT_REJECTED)) {
/* Only a rejection can answer a HELLO the daemon never received;
* anything else stays the plain send failure it always was. */
memset(result_out, 0, sizeof(*result_out));
cbm_daemon_ipc_connection_close(connection);
return NULL;
}
if (received != 1) {
/* The kernel completed the pipe/socket connect, so a server process
* exists, yet the HELLO went unanswered. Name that holder: a dead
+21
View File
@@ -471,6 +471,27 @@ void cbm_daemon_runtime_set_containment_hook_for_testing(
* in test time. UINT32_MAX restores the production constant; any other value
* (0 = expire immediately) overrides. Process-global; reset it after use. */
void cbm_daemon_runtime_service_set_ephemeral_linger_timeout_for_testing(uint32_t timeout_ms);
/* Connection-cap seams (flaky-ledger item 12). While held, the two bounded
* waits on a peer in the connection-cap path end only on that peer: a
* connection that has not sent its first frame keeps its worker slot until it
* closes (or the service stops) instead of until the request deadline, and an
* inline rejection's drain (Windows; a no-op on POSIX) lasts until the peer
* closes instead of 250 ms. A "slow hello" becomes a state the test releases,
* not a window it races. Process-global; reset it after use. */
void cbm_daemon_runtime_hold_peer_waits_for_testing(bool hold);
/* The four points that order a HELLO against an inline accept-loop rejection.
* The hook runs on the client thread for the CLIENT_* points and on the accept
* thread for the DAEMON_* points (never under the service mutex), so a test can
* pin either order: daemon answers after the HELLO is on the wire, or the
* daemon has answered and closed before the HELLO is sent. NULL removes it. */
typedef enum {
CBM_DAEMON_RUNTIME_HELLO_POINT_CLIENT_CONNECTED = 0, /* transport up, HELLO not sent */
CBM_DAEMON_RUNTIME_HELLO_POINT_CLIENT_SENT, /* HELLO send attempted */
CBM_DAEMON_RUNTIME_HELLO_POINT_DAEMON_REJECTING, /* inline rejection not yet written */
CBM_DAEMON_RUNTIME_HELLO_POINT_DAEMON_REJECTED, /* inline rejection written + closed */
} cbm_daemon_runtime_hello_point_t;
typedef void (*cbm_daemon_runtime_hello_hook_t)(cbm_daemon_runtime_hello_point_t point);
void cbm_daemon_runtime_set_hello_hook_for_testing(cbm_daemon_runtime_hello_hook_t hook);
#endif
#endif /* CBM_DAEMON_RUNTIME_H */
+22 -5
View File
@@ -549,8 +549,23 @@ static void file_list_add_ignored(file_list_t *fl, const char *rel_path, const c
fl->ignored_count++;
}
/* Nanosecond mtime from a stat result, per platform. Windows' wide_stat only
* carries whole seconds, so the value is seconds scaled to ns there. */
#define DISCOVER_NS_PER_SEC 1000000000LL
static int64_t discover_stat_mtime_ns(const struct stat *st) {
#ifdef __APPLE__
return ((int64_t)st->st_mtimespec.tv_sec * DISCOVER_NS_PER_SEC) +
(int64_t)st->st_mtimespec.tv_nsec;
#elif defined(_WIN32)
return (int64_t)st->st_mtime * DISCOVER_NS_PER_SEC;
#else
return ((int64_t)st->st_mtim.tv_sec * DISCOVER_NS_PER_SEC) + (int64_t)st->st_mtim.tv_nsec;
#endif
}
static void fl_add(file_list_t *fl, const char *abs_path, const char *rel_path, CBMLanguage lang,
int64_t size) {
const struct stat *st) {
int64_t size = (int64_t)st->st_size;
if (fl->max_files >= 0 && fl->count >= fl->max_files) {
fl->limit_exceeded = true;
return;
@@ -605,6 +620,7 @@ static void fl_add(file_list_t *fl, const char *abs_path, const char *rel_path,
fi->rel_path = relative_copy;
fi->language = lang;
fi->size = size;
fi->mtime_ns = discover_stat_mtime_ns(st);
}
/* ── Recursive walk ─────────────────────────────── */
@@ -939,9 +955,10 @@ static void walk_dir_process_file(const char *abs_path, const char *rel_path, co
const cbm_discover_opts_t *opts,
const gitignore_link_t *ignore_chain,
const cbm_gitignore_t *global_gi,
const cbm_gitignore_t *cbmignore, off_t size, file_list_t *out) {
const cbm_gitignore_t *cbmignore, const struct stat *st,
file_list_t *out) {
const char *skip_reason =
file_skip_reason(name, rel_path, opts, ignore_chain, global_gi, cbmignore, size);
file_skip_reason(name, rel_path, opts, ignore_chain, global_gi, cbmignore, st->st_size);
if (skip_reason) {
/* Deliberately not indexed (#963) — record so callers can surface it.
* Unsupported-language files below are NOT recorded: "no grammar for
@@ -954,7 +971,7 @@ static void walk_dir_process_file(const char *abs_path, const char *rel_path, co
if (lang == CBM_LANG_COUNT) {
return;
}
fl_add(out, abs_path, rel_path, lang, size);
fl_add(out, abs_path, rel_path, lang, st);
}
typedef struct {
@@ -1066,7 +1083,7 @@ static void walk_dir_process_entry(cbm_dirent_t *entry, const walk_frame_t *fram
}
} else if (S_ISREG(st.st_mode)) {
walk_dir_process_file(abs_path, rel_path, entry->name, opts, frame->ignore_chain, global_gi,
cbmignore, st.st_size, out);
cbmignore, &st, out);
}
}
+1
View File
@@ -147,6 +147,7 @@ typedef struct {
char *rel_path; /* relative to repo root (heap-allocated) */
CBMLanguage language; /* detected language */
int64_t size; /* file size in bytes */
int64_t mtime_ns; /* modification time, ns (whole seconds on Windows) */
} cbm_file_info_t;
typedef struct {
+250
View File
@@ -3,12 +3,254 @@
*
* POSIX: direct wrappers around <regex.h>.
* Windows: vendored TRE regex library (BSD-licensed).
*
* Both backends expand bounded repetition at compile time, so cbm_regcomp
* sizes a pattern first (the compile-size guard below) and refuses one whose
* compiled form would be too large, before the platform compiler allocates
* anything.
*/
#include "foundation/constants.h"
#include "foundation/compat_regex.h"
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
/* ── Compile-size guard (shared by both backends) ─────────────────
*
* The platform compilers expand `X{m,n}` into n copies of X, so nested
* intervals multiply: `((((a){20}){20}){20}){20}` is 160,000 expanded atoms
* from 25 bytes of pattern. A K-way alternation additionally costs about K^2
* position-set entries on the TRE-derived backends (macOS libc and the vendored
* TRE), because every union node copies its branches' sets.
*
* Measured on macOS libc with REG_EXTENDED|REG_NOSUB: the nested shape costs
* about 0.6 KB of heap per expanded atom, 1.1 KB with submatch tracking on,
* 1.7 KB with REG_ICASE and 2.3 KB with both; a K-way alternation adds about
* 70 B x K^2 on top of its branches (twice that under REG_ICASE), and an
* alternation under an interval pays that for every copy, about 1 KB per unit
* with REG_NOSUB and 2.8 KB with REG_ICASE plus submatches. glibc costs about
* 0.45 KB per atom and expands intervals the same way.
*
* cbm_regcomp_estimate_units() counts expanded atoms in one linear pass with
* saturating arithmetic and charges a K-way alternation K^2/8 units, the
* measured ratio between the two costs. With CBM_REGEX_COMPILE_BUDGET_UNITS =
* 32768 the heaviest accepted compile is a repeated alternation at about 30 MB
* with REG_NOSUB and about 90 MB under the ICASE-plus-submatch flag set no
* call site uses; the nested shape tops out at 13^4 = 28,561 units, about
* 16 MB. `(\w{1,100}){1,20}` (2,000 units) and an alternation of 500 short
* names (31,250 units plus its letters) remain accepted. */
enum { REGEX_GROUP_DEPTH_MAX = 64 };
typedef struct {
uint64_t total; /* units of this group so far; includes `last` */
uint64_t last; /* units of the element a following quantifier applies to */
uint64_t branches; /* alternatives in this group: 1 + the number of '|' */
} regex_frame_t;
static uint64_t regex_sat_add(uint64_t a, uint64_t b) {
return a > UINT64_MAX - b ? UINT64_MAX : a + b;
}
static uint64_t regex_sat_mul(uint64_t a, uint64_t b) {
if (a == 0 || b == 0) {
return 0;
}
return a > UINT64_MAX / b ? UINT64_MAX : a * b;
}
static void regex_frame_atom(regex_frame_t *f, uint64_t units) {
f->total = regex_sat_add(f->total, units);
f->last = units;
}
/* An interval applies to the last element: n copies of it replace the one. */
static void regex_frame_repeat_last(regex_frame_t *f, uint64_t copies) {
uint64_t grown = regex_sat_mul(f->last, copies);
f->total = regex_sat_add(f->total - f->last, grown);
f->last = grown;
}
/* Units a closed group contributes to its parent: its content plus the K^2/8
* alternation share, never less than one atom. */
static uint64_t regex_frame_units(const regex_frame_t *f) {
uint64_t alternation = regex_sat_mul(f->branches, f->branches) / 8;
uint64_t units = regex_sat_add(f->total, alternation);
return units ? units : 1;
}
/* Skip the bracket expression opening at p[i] == '['. Returns the index just
* past its closing ']', or the end of the string when it is unterminated.
* Nothing inside is an operator: `[]a]`, `[^]a]` and `[[:alpha:]]` are each
* one atom, and a brace inside brackets never opens an interval. */
static size_t regex_skip_bracket(const char *p, size_t i) {
size_t j = i + 1;
if (p[j] == '^') {
j++;
}
if (p[j] == ']') {
j++;
}
while (p[j] && p[j] != ']') {
if (p[j] == '[' && (p[j + 1] == ':' || p[j + 1] == '=' || p[j + 1] == '.')) {
char close = p[j + 1];
size_t k = j + 2;
while (p[k] && !(p[k] == close && p[k + 1] == ']')) {
k++;
}
j = p[k] ? k + 2 : k;
} else {
j++;
}
}
return p[j] ? j + 1 : j;
}
static bool regex_parse_digits(const char *p, size_t *i, uint64_t *value) {
bool any = false;
*value = 0;
while (p[*i] >= '0' && p[*i] <= '9') {
*value = regex_sat_add(regex_sat_mul(*value, 10), (uint64_t)(p[*i] - '0'));
(*i)++;
any = true;
}
return any;
}
/* Parse the interval body that starts at p[i], just past the opening brace
* (`{` in extended syntax, `\{` in basic). On success stores the number of
* copies the compiler will make (the upper bound, or the lower bound for
* `{m,}`, at least 1) and the index just past the closing brace. Anything that
* is not an interval leaves the brace to be counted as a literal, which is what
* the backends that accept it do; the others reject the pattern. */
static bool regex_parse_interval(const char *p, size_t i, bool extended, uint64_t *copies,
size_t *end) {
uint64_t lower = 0;
uint64_t upper = 0;
bool has_lower = regex_parse_digits(p, &i, &lower);
bool has_upper = false;
if (p[i] == ',') {
i++;
has_upper = regex_parse_digits(p, &i, &upper);
} else {
if (!has_lower) {
return false;
}
upper = lower;
has_upper = true;
}
if (extended) {
if (p[i] != '}') {
return false;
}
i++;
} else {
if (p[i] != '\\' || p[i + 1] != '}') {
return false;
}
i += 2;
}
uint64_t n = has_upper ? upper : lower;
if (has_upper && lower > upper) {
n = lower; /* `{5,3}` is rejected by the backends; count the larger bound */
}
*copies = n ? n : 1;
*end = i;
return true;
}
uint64_t cbm_regcomp_estimate_units(const char *pattern, int flags) {
const bool extended = (flags & CBM_REG_EXTENDED) != 0;
regex_frame_t frames[REGEX_GROUP_DEPTH_MAX];
int depth = 0;
frames[0] = (regex_frame_t){0, 0, 1};
size_t i = 0;
while (pattern[i]) {
char c = pattern[i];
if (c == '[') {
i = regex_skip_bracket(pattern, i);
regex_frame_atom(&frames[depth], 1);
continue;
}
/* In extended syntax the bare characters operate and `\x` is one
* literal; in basic syntax only `\(`, `\)`, `\{`, `\|`, `\+`, `\?` and
* a bare `*` operate. */
char op = 0;
size_t len = 1;
if (c == '\\') {
len = pattern[i + 1] ? 2 : 1;
if (!extended && len == 2 && strchr("(){|+?", pattern[i + 1])) {
op = pattern[i + 1];
}
} else if (extended ? strchr("(){|*+?", c) != NULL : c == '*') {
op = c;
}
regex_frame_t *f = &frames[depth];
switch (op) {
case '(':
if (depth + 1 >= REGEX_GROUP_DEPTH_MAX) {
return UINT64_MAX;
}
frames[++depth] = (regex_frame_t){0, 0, 1};
break;
case ')':
if (depth == 0) {
regex_frame_atom(f, 1); /* unmatched: a literal where accepted */
break;
}
depth--;
regex_frame_atom(&frames[depth], regex_frame_units(f));
break;
case '|':
f->branches = regex_sat_add(f->branches, 1);
f->last = 0;
break;
case '{': {
uint64_t copies = 0;
size_t end = 0;
if (regex_parse_interval(pattern, i + len, extended, &copies, &end)) {
regex_frame_repeat_last(f, copies);
i = end;
continue;
}
regex_frame_atom(f, 1);
break;
}
case '*':
case '+':
case '?':
break; /* unbounded or optional repetition is not expanded */
default:
regex_frame_atom(f, 1);
break;
}
i += len;
}
while (depth > 0) {
regex_frame_t *f = &frames[depth];
depth--;
regex_frame_atom(&frames[depth], regex_frame_units(f));
}
return regex_frame_units(&frames[0]);
}
/* Refuse a pattern before the platform compiler sees it. */
static int regex_compile_guard(const char *pattern, int flags) {
size_t len = 0;
while (len <= (size_t)CBM_REGEX_PATTERN_MAX_BYTES && pattern[len]) {
len++;
}
if (len > (size_t)CBM_REGEX_PATTERN_MAX_BYTES) {
return CBM_REG_ETOOBIG;
}
if (cbm_regcomp_estimate_units(pattern, flags) > (uint64_t)CBM_REGEX_COMPILE_BUDGET_UNITS) {
return CBM_REG_ETOOBIG;
}
return CBM_REG_OK;
}
#ifdef _WIN32
/* ── Windows: use vendored TRE regex ─────────────────────────── */
@@ -31,6 +273,10 @@ static int translate_flags_tre(int flags) {
}
int cbm_regcomp(cbm_regex_t *r, const char *pattern, int flags) {
int refused = regex_compile_guard(pattern, flags);
if (refused != CBM_REG_OK) {
return refused;
}
regex_t *re = (regex_t *)r->opaque;
int rc = tre_regcomp(re, pattern, translate_flags_tre(flags));
return rc == 0 ? CBM_REG_OK : rc;
@@ -88,6 +334,10 @@ static int translate_flags(int flags) {
}
int cbm_regcomp(cbm_regex_t *r, const char *pattern, int flags) {
int refused = regex_compile_guard(pattern, flags);
if (refused != CBM_REG_OK) {
return refused;
}
regex_t *re = (regex_t *)r->opaque;
int rc = regcomp(re, pattern, translate_flags(flags));
return rc == 0 ? CBM_REG_OK : rc;
+37 -1
View File
@@ -11,6 +11,7 @@
#include "foundation/constants.h"
#include <stddef.h>
#include <stdint.h>
/* ── Flags ────────────────────────────────────────────────────── */
@@ -23,6 +24,29 @@
#define CBM_REG_OK 0
#define CBM_REG_NOMATCH (-1)
/* cbm_regcomp refused the pattern before compiling it: longer than
* CBM_REGEX_PATTERN_MAX_BYTES, or its compiled form would exceed
* CBM_REGEX_COMPILE_BUDGET_UNITS (see cbm_regcomp_estimate_units). Well above
* every platform compile error code, which are small positive integers. */
#define CBM_REG_ETOOBIG 100
/* Reason text for a CBM_REG_ETOOBIG refusal, for user-facing error messages. */
#define CBM_REG_ETOOBIG_REASON \
"regex pattern too large to compile: reduce nested {m,n} repetition or alternation"
/* ── Compile-size guard ───────────────────────────────────────── */
enum {
/* Longest pattern cbm_regcomp hands to the platform compiler. Bounds only
* the sizing pass: a pattern without repetition costs one unit per atom,
* so the unit budget below already bounds its compiled size. Equal to the
* budget, so a realistic pattern is only ever refused for its cost. */
CBM_REGEX_PATTERN_MAX_BYTES = CBM_SZ_32K,
/* Largest estimated compiled size, in units of one expanded atom, that
* cbm_regcomp accepts. Bounds what bounded repetition and alternation can
* expand a pattern into. compat_regex.c documents the measured bytes per
* unit and what the budget admits. */
CBM_REGEX_COMPILE_BUDGET_UNITS = CBM_SZ_32K
};
/* ── Types ────────────────────────────────────────────────────── */
@@ -40,9 +64,21 @@ typedef struct {
/* ── Functions ────────────────────────────────────────────────── */
/* Compile a regular expression. Returns CBM_REG_OK on success, non-zero on error. */
/* Compile a regular expression. Returns CBM_REG_OK on success, non-zero on error:
* CBM_REG_ETOOBIG when the pattern is refused before compilation (nothing to
* free), otherwise the platform compiler's error code. */
int cbm_regcomp(cbm_regex_t *r, const char *pattern, int flags);
/* Estimated size of the compiled form of pattern, in units of one expanded
* atom: an atom costs 1, concatenation and alternation add, a group costs its
* content, and an interval `{m}`, `{m,}`, `{m,n}` multiplies the element it
* applies to by the number of copies the compiler makes (the upper bound; m for
* `{m,}`; at least 1), so nested intervals multiply. `*`, `+` and `?` do not
* multiply. A K-way alternation adds K*K/8 for its position sets. Arithmetic
* saturates at UINT64_MAX; a group nesting deeper than the pass tracks returns
* UINT64_MAX. Honors CBM_REG_EXTENDED (basic syntax otherwise). */
uint64_t cbm_regcomp_estimate_units(const char *pattern, int flags);
/* Execute compiled regex against str. nmatch/matches may be 0/NULL.
* eflags: 0 or combination of platform-specific exec flags.
* Returns CBM_REG_OK on match, CBM_REG_NOMATCH on no match. */
+7 -7
View File
@@ -8,8 +8,8 @@
* - parse_or_expr, parse_xor_expr, parse_and_expr, parse_not_expr
* - parse_atom_expr, parse_post_where, cbm_parse
*
* Cypher expression evaluator (bounded by WHERE clause depth ~5):
* - eval_expr
* Cypher expression evaluators (bounded by WHERE clause depth ~5):
* - eval_expr, eval_expr_partial
*
* Glob pattern matcher (bounded by pattern nesting ~3):
* - glob_match, glob_match_star, glob_match_doublestar
@@ -25,9 +25,9 @@
* To add a function: add it below AND add NOLINT(misc-no-recursion) on
* the function definition line. The lint gate verifies both match.
*/
#define CBM_RECURSION_WHITELIST \
"parse_or_expr", "parse_xor_expr", "parse_and_expr", "parse_not_expr", "parse_atom_expr", \
"parse_post_where", "cbm_parse", "eval_expr", "glob_match", "glob_match_star", \
"glob_match_doublestar", "glob_match_doublestar_slash", "glob_match_doublestar_any", \
"parse_bool_expr", "parse_bool_atom", "r_collect_imports", \
#define CBM_RECURSION_WHITELIST \
"parse_or_expr", "parse_xor_expr", "parse_and_expr", "parse_not_expr", "parse_atom_expr", \
"parse_post_where", "cbm_parse", "eval_expr", "eval_expr_partial", "glob_match", \
"glob_match_star", "glob_match_doublestar", "glob_match_doublestar_slash", \
"glob_match_doublestar_any", "parse_bool_expr", "parse_bool_atom", "r_collect_imports", \
"find_first_descendant_by_kind", "find_first_descendant_of"
+62 -3
View File
@@ -30,6 +30,9 @@
#include <spawn.h>
#endif
extern char **environ;
#ifdef __linux__
#include <sys/syscall.h> /* SYS_close_range: raw syscall, see cbm_posix_close_fds_from */
#endif
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
@@ -1069,6 +1072,64 @@ static void cbm_posix_reset_child_signals(void) {
(void)sigprocmask(SIG_SETMASK, &empty, NULL);
}
/* Close every descriptor >= lowfd in the fork+exec child (#1484).
*
* The portable answer is a close() per possible descriptor, which costs
* O(RLIMIT_NOFILE) syscalls: at nofile=524288 that is ~0.8 s between fork and
* exec for EVERY spawn, independent of how many descriptors are actually open.
* The kernel can do the same in one call:
* - Linux >= 5.9: close_range(lowfd, ~0U, 0). Issued as a raw syscall, not
* through the libc wrapper: the static musl release build has no wrapper
* and the glibc wrapper only exists from 2.34, while the syscall number is
* 436 on the supported x86-64 and AArch64 targets. Other architectures
* use their header's number, or the loop if no number is available.
* An older kernel answers
* ENOSYS (or EPERM under a seccomp filter that predates it) and we fall back.
* - FreeBSD/OpenBSD/NetBSD/DragonFly: closefrom(lowfd).
* - otherwise (and on fallback): the bounded close() loop.
* macOS never reaches this on its primary path: posix_spawn's
* CLOEXEC_DEFAULT does the closing (see cbm_posix_spawn_apple).
*
* Runs between fork and exec, so it is async-signal-safe: raw syscalls and
* close() only, no allocation, no stdio. Returns the strategy that did the
* work so the test seam can assert which one ran. */
#if defined(__linux__) && !defined(SYS_close_range) && (defined(__x86_64__) || defined(__aarch64__))
#define SYS_close_range 436
#endif
#ifdef CBM_ENABLE_TEST_SEAMS
static bool g_force_close_range_enosys = false;
#endif
static cbm_fd_close_strategy_t cbm_posix_close_fds_from(int lowfd, long max_fd) {
#if defined(__linux__) && defined(SYS_close_range)
bool range_unavailable = false;
#ifdef CBM_ENABLE_TEST_SEAMS
range_unavailable = g_force_close_range_enosys;
#endif
if (!range_unavailable && syscall(SYS_close_range, (unsigned int)lowfd, ~0U, 0U) == 0) {
return CBM_FD_CLOSE_RANGE;
}
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
(void)max_fd;
closefrom(lowfd);
return CBM_FD_CLOSEFROM;
#endif
for (int fd = lowfd; fd < max_fd; fd++) {
(void)close(fd);
}
return CBM_FD_CLOSE_LOOP;
}
#ifdef CBM_ENABLE_TEST_SEAMS
void cbm_subprocess_force_close_range_enosys_for_testing(bool force) {
g_force_close_range_enosys = force;
}
cbm_fd_close_strategy_t cbm_subprocess_close_fds_from_for_testing(int lowfd, long max_fd) {
return cbm_posix_close_fds_from(lowfd, max_fd);
}
#endif
/* fork+exec child setup. On Apple this runs ONLY for the exec-failure
* fallback (see cbm_posix_spawn_apple), which preserves the documented
* "bogus binary => child exits 127" contract across platforms. */
@@ -1090,9 +1151,7 @@ static void cbm_posix_child_exec(cbm_subprocess_t *process, int input, int outpu
if (output > STDERR_FILENO) {
(void)close(output);
}
for (int fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
(void)close(fd);
}
(void)cbm_posix_close_fds_from(STDERR_FILENO + 1, max_fd);
if (process->envp) {
environ = process->envp; /* execvp passes environ to the new image */
}
+17
View File
@@ -193,4 +193,21 @@ void cbm_subprocess_force_spawn_eagain_for_testing(int attempts);
int cbm_subprocess_pending_spawn_eagain_for_testing(void);
#endif
/* How the POSIX fork+exec child closed its inherited descriptors (#1484). */
typedef enum {
CBM_FD_CLOSE_RANGE = 1, /* Linux close_range(2): one syscall */
CBM_FD_CLOSEFROM, /* BSD closefrom(3): one call */
CBM_FD_CLOSE_LOOP /* close() per descriptor up to _SC_OPEN_MAX: O(RLIMIT_NOFILE) */
} cbm_fd_close_strategy_t;
#if defined(CBM_ENABLE_TEST_SEAMS) && !defined(_WIN32)
/* Run the child's close-inherited-descriptors step in the CALLING process for
* descriptors >= lowfd (callers pick a lowfd above everything they need) and
* report which strategy did the work. Test builds only. */
cbm_fd_close_strategy_t cbm_subprocess_close_fds_from_for_testing(int lowfd, long max_fd);
/* Make the close_range fast path behave as if the kernel lacked it (ENOSYS),
* so the fallback loop is exercised deterministically. Test builds only. */
void cbm_subprocess_force_close_range_enosys_for_testing(bool force);
#endif
#endif /* CBM_SUBPROCESS_H */
+44 -7
View File
@@ -6,6 +6,7 @@
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/constants.h"
#include "foundation/platform.h"
#include "foundation/sha256.h"
@@ -239,6 +240,22 @@ static bool ws_is_windows_user_programs_tree(const char *path) {
return true;
}
/* strncmp that treats "/" and "\" as the same character. On Windows a
* canonical path arrives with backslashes from the resolver and with forward
* slashes from callers that normalize, and both spell one directory. Stops at
* the end of either string like strncmp does. */
static bool ws_prefix_equal(const char *a, const char *b, size_t len) {
for (size_t i = 0; i < len; i++) {
if (a[i] != b[i] && !(ws_is_sep(a[i]) && ws_is_sep(b[i]))) {
return false;
}
if (a[i] == '\0') {
break;
}
}
return true;
}
/* True when b is a or lives under a. Compares on a separator boundary so
* "/a/bc" is not treated as living under "/a/b". */
static bool ws_is_ancestor_or_equal(const char *a, const char *b) {
@@ -249,7 +266,7 @@ static bool ws_is_ancestor_or_equal(const char *a, const char *b) {
while (la > 1 && ws_is_sep(a[la - 1])) {
la--;
}
if (strncmp(a, b, la) != 0) {
if (!ws_prefix_equal(a, b, la)) {
return false;
}
return b[la] == '\0' || ws_is_sep(b[la]);
@@ -600,14 +617,34 @@ bool cbm_workspace_root_allowed(const char *canonical_path, const char *home_dir
/* ── Environment helpers ──────────────────────────────────────────────────── */
/* Callers should not each re-derive these; a caller that resolved the home
* directory differently would classify the same path differently. */
* directory differently would classify the same path differently.
*
* The value is the CANONICAL form of $HOME (then %USERPROFILE%), through the
* same resolver callers apply to the path they classify. The policy compares
* the two byte for byte, and a home reached through a link — "/home" kept on
* another volume, a macOS firmlink, a HOME that is itself a link — differs
* from its resolved form, so the raw value would never match and the home
* rule would not fire. A home that cannot be resolved (it does not exist)
* falls back to the raw value, which is all the comparison could use anyway.
*
* Storage is per thread and recomputed on every call, as cbm_resolve_cache_dir
* does: no lock, a changed environment is seen at once, and the pointer stays
* valid until the next call on the same thread. */
const char *cbm_workspace_home_dir(void) {
const char *home = getenv("HOME");
if (home && home[0]) {
return home;
static CBM_TLS char resolved[CBM_SZ_4K];
char raw[CBM_SZ_4K];
const char *home = cbm_safe_getenv("HOME", raw, sizeof(raw), NULL);
if (!home || !home[0]) {
home = cbm_safe_getenv("USERPROFILE", raw, sizeof(raw), NULL);
}
home = getenv("USERPROFILE");
return (home && home[0]) ? home : NULL;
if (!home || !home[0]) {
return NULL;
}
if (!cbm_canonical_path(home, resolved, sizeof(resolved))) {
memcpy(resolved, raw, strlen(raw) + 1);
}
cbm_normalize_path_sep(resolved);
return resolved;
}
const char *cbm_workspace_cache_dir(void) {
+1 -1
View File
@@ -1107,7 +1107,7 @@ static void print_help(void) {
"[--dir=<path>] [--skip-config]\n");
printf(" [--clients=<tokens>] Run "
"'install --clients' to list tokens\n");
printf(" codebase-memory-mcp uninstall [-y|-n] [--dry-run]\n");
printf(" codebase-memory-mcp uninstall [-y|-n] [--dry-run] [--delete-indexes]\n");
printf(" codebase-memory-mcp update [-y|-n]\n");
printf(" codebase-memory-mcp config <list|get|set|reset>\n");
printf(" codebase-memory-mcp --version Print version\n");
+84
View File
@@ -359,6 +359,7 @@ typedef enum {
WORKER_RESPONSE_READ_OK = 0,
WORKER_RESPONSE_READ_ERROR,
WORKER_RESPONSE_READ_TOO_LARGE,
WORKER_RESPONSE_READ_EMPTY, /* the pre-created file was never written (#1300) */
} worker_response_read_status_t;
/* Read at most one daemon-application payload. The worker is already reaped,
@@ -384,6 +385,14 @@ static char *slurp_worker_response(const char *path, worker_response_read_status
(void)fclose(f);
return NULL;
}
if (n == 0) {
/* The supervisor creates the response file before spawning, so an
* empty file is a worker that never wrote its result. Reading it as
* "" made that a successful run with an empty response (#1300). */
*status_out = WORKER_RESPONSE_READ_EMPTY;
(void)fclose(f);
return NULL;
}
if (fseek(f, 0, SEEK_SET) != 0) {
(void)fclose(f);
return NULL;
@@ -405,6 +414,67 @@ static char *slurp_worker_response(const char *path, worker_response_read_status
return buf;
}
enum {
WORKER_LOG_TAIL_BYTES = 64 * 1024, /* last-phase scan window: bounded, never the whole log */
WORKER_LOG_LINE_CAP = 1024,
};
/* Copy the event name of one structured log line ("level=... msg=<event> ..."
* or {"level":...,"event":"<event>",...}) into out. False for any other line
* (plain stderr text, a truncated fragment). */
static bool worker_log_line_event(const char *line, char *out, size_t out_size) {
static const char text_key[] = " msg=";
static const char json_key[] = "\"event\":\"";
const char *start = NULL;
char stop = ' ';
if (strncmp(line, "level=", strlen("level=")) == 0) {
const char *msg = strstr(line, text_key);
start = msg ? msg + strlen(text_key) : NULL;
} else if (strncmp(line, "{\"level\":", strlen("{\"level\":")) == 0) {
const char *event = strstr(line, json_key);
start = event ? event + strlen(json_key) : NULL;
stop = '"';
}
if (!start) {
return false;
}
size_t length = 0;
while (start[length] && start[length] != stop && start[length] != '\n' &&
start[length] != '\r') {
length++;
}
if (length == 0 || length >= out_size) {
return false;
}
memcpy(out, start, length);
out[length] = '\0';
return true;
}
/* #1300: the last structured event the worker logged before it exited — the
* phase it reached. Scans only the log's final WORKER_LOG_TAIL_BYTES. */
static void worker_log_last_phase(const char *log_path, char *out, size_t out_size) {
(void)snprintf(out, out_size, "%s", "unknown");
FILE *log = cbm_fopen(log_path, "rb");
if (!log) {
return;
}
if (fseek(log, 0, SEEK_END) == 0) {
long size = ftell(log);
long from = size > WORKER_LOG_TAIL_BYTES ? size - WORKER_LOG_TAIL_BYTES : 0;
if (size >= 0 && fseek(log, from, SEEK_SET) == 0) {
char line[WORKER_LOG_LINE_CAP];
char event[CBM_SZ_128];
while (fgets(line, sizeof(line), log)) {
if (worker_log_line_event(line, event, sizeof(event))) {
(void)snprintf(out, out_size, "%s", event);
}
}
}
}
(void)fclose(log);
}
enum {
INDEX_WORKER_PATH_CAP = CBM_SZ_4K,
INDEX_WORKER_ARGV_CAP = 17,
@@ -634,6 +704,10 @@ static void worker_terminal_log(cbm_index_worker_handle_t *handle) {
} else if (handle->result.cancellation_requested) {
cbm_log_warn("index.supervisor.worker_cancelled", "outcome",
cbm_proc_outcome_str(handle->result.outcome), "log", handle->log_path);
} else if (handle->result.response_missing) {
/* #1300: keep and name the log — it is the only record of the run. */
cbm_log_error("index.supervisor.no_response", "exit_code", exit_text, "last_phase",
handle->result.last_phase, "log", handle->log_path);
} else if (handle->result.outcome == CBM_PROC_CLEAN && !cbm_profile_active) {
(void)cbm_unlink(handle->log_path);
} else if (handle->result.outcome == CBM_PROC_CLEAN) {
@@ -828,6 +902,16 @@ cbm_index_worker_poll_t cbm_index_worker_poll(cbm_index_worker_handle_t *handle,
handle->result.response_rejected = true;
handle->result.outcome = CBM_PROC_EXIT_NONZERO;
handle->result.exit_code = -1;
} else if (!handle->result.response) {
/* #1300: a clean exit that wrote no response. The outcome stays
* CLEAN (the disposition is FALLBACK: an explicit error, no
* in-process fallback and no recovery re-run of a worker that did
* not crash); the log and the last phase it reached are kept. */
handle->result.response_missing = true;
worker_log_last_phase(handle->log_path, handle->result.last_phase,
sizeof(handle->result.last_phase));
(void)snprintf(handle->result.worker_log, sizeof(handle->result.worker_log), "%s",
handle->log_path);
}
}
(void)cbm_unlink(handle->response_path);
+8
View File
@@ -147,6 +147,14 @@ typedef struct {
bool forced;
bool tree_quiesced;
bool supervision_failed;
/* #1300: the worker exited CLEAN but wrote no response (an empty or
* unreadable response file). A contained failure, never a success: the
* response stays NULL, the worker log is retained and named, and
* last_phase is the last structured event that log recorded ("unknown"
* when it holds none), so the report says where the run stopped. */
bool response_missing;
char last_phase[128];
char worker_log[4096];
bool response_rejected; /* clean worker exceeded the bounded response protocol */
char *response; /* worker result only after a contained, uncancelled CLEAN exit;
* borrowed for async polls, caller-owned from the sync wrapper */
+613 -140
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -244,6 +244,12 @@ char *cbm_mcp_handle_tool(cbm_mcp_server_t *srv, const char *tool_name, const ch
/* ── Supervised background index (RSS isolation, #832) ────────── */
/* #1300: the explicit error response for a worker that exited cleanly without
* writing a response (worker_result->response_missing). Names the retained
* worker log and the last phase it reached; caller frees. */
char *cbm_mcp_index_worker_no_response_failure(const char *args,
const cbm_index_worker_result_t *worker_result);
/* One shared policy gate for supervised-index callers. Only an explicitly safe
* terminal can yield a result or enter crash/hang recovery; cancellation,
* failed tree containment, and unavailable worker startup are terminal. The
+5
View File
@@ -29,6 +29,11 @@ void cbm_mcp_server_set_auto_index_count_test_hook(cbm_mcp_server_t *srv,
void cbm_mcp_server_set_search_scan_command_for_test(cbm_mcp_server_t *srv, const char *command);
void cbm_mcp_server_set_search_scan_timeout_for_test(cbm_mcp_server_t *srv, uint64_t timeout_ms,
bool override_set);
/* Parent directory for search_code's private cbm-search-XXXXXX scratch
* (NULL restores cbm_tmpdir()). Tests point it at a private directory so a
* scratch count cannot see other processes' entries in the shared temp dir.
* The server borrows dir until it is reset or the server is freed. */
void cbm_mcp_server_set_search_scratch_dir_for_test(cbm_mcp_server_t *srv, const char *dir);
/* Release only the constructor-created pristine in-memory store. Public
* cbm_mcp_server_new(NULL) semantics remain unchanged; daemon sessions use
+403
View File
@@ -0,0 +1,403 @@
/*
* laravel_routing.c — Laravel 11+ framework route mounts (#1146).
*
* See laravel_routing.h for the contract. bootstrap/app.php is parsed with
* the same PHP grammar the extractor uses; only named `withRouting(...)`
* arguments whose values are plain literals (or `__DIR__`/`dirname(__DIR__)`
* concatenations and `base_path()` calls over literals) are trusted.
*/
#include "pipeline/laravel_routing.h"
#include "cbm.h"
#include "lang_specs.h"
#include "service_patterns.h"
#include "tree_sitter/api.h"
#include "foundation/compat_fs.h"
#include "foundation/constants.h"
#include "foundation/mem_core.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
enum {
LR_PATH_MAX = CBM_SZ_512, /* repo-relative path buffer */
LR_KEY_MAX = CBM_SZ_32, /* named-argument key */
LR_PREFIX_MAX = CBM_SZ_128, /* apiPrefix literal */
LR_SEG_MAX = CBM_SZ_64, /* path segments tracked while normalising */
LR_SOURCE_MAX = CBM_SZ_256 * CBM_SZ_1K, /* bootstrap/app.php read cap */
};
static const char LR_BOOTSTRAP_REL[] = "bootstrap/app.php";
/* Copy a node's source text into buf. False when it does not fit. */
static bool lr_node_text(const char *src, TSNode node, char *buf, size_t buf_sz) {
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 = end > start ? (size_t)(end - start) : 0;
if (len >= buf_sz) {
return false;
}
memcpy(buf, src + start, len);
buf[len] = '\0';
return true;
}
static bool lr_node_is(TSNode node, const char *type) {
return !ts_node_is_null(node) && strcmp(ts_node_type(node), type) == 0;
}
static bool lr_node_text_is(const char *src, TSNode node, const char *text) {
char buf[LR_KEY_MAX];
return lr_node_text(src, node, buf, sizeof(buf)) && strcmp(buf, text) == 0;
}
/* A plain string literal: '...' or "..." whose only children are
* string_content (no interpolation, no escapes). Writes the unquoted value. */
static bool lr_string_literal(const char *src, TSNode node, char *buf, size_t buf_sz) {
if (!lr_node_is(node, "string") && !lr_node_is(node, "encapsed_string")) {
return false;
}
size_t pos = 0;
buf[0] = '\0';
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode part = ts_node_named_child(node, i);
if (!lr_node_is(part, "string_content") ||
!lr_node_text(src, part, buf + pos, buf_sz - pos)) {
return false;
}
pos += strlen(buf + pos);
}
return true;
}
/* The value expression of a call argument: its first named child that is
* neither the `name:` label nor a comment. */
static TSNode lr_arg_value(TSNode arg, TSNode label) {
uint32_t nc = ts_node_named_child_count(arg);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(arg, i);
if ((ts_node_is_null(label) || !ts_node_eq(child, label)) &&
!lr_node_is(child, "comment")) {
return child;
}
}
TSNode none = {0};
return none;
}
/* The single literal argument of `fn('...')` when the callee is `fn`. */
static bool lr_call_literal_arg(const char *src, TSNode call, const char *fn, char *buf,
size_t buf_sz) {
if (!lr_node_is(call, "function_call_expression") ||
!lr_node_text_is(src, ts_node_child_by_field_name(call, TS_FIELD("function")), fn)) {
return false;
}
TSNode args = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
if (ts_node_is_null(args) || ts_node_named_child_count(args) != SKIP_ONE) {
return false;
}
TSNode arg = ts_node_named_child(args, 0);
TSNode val = lr_arg_value(arg, ts_node_child_by_field_name(arg, TS_FIELD("name")));
return lr_string_literal(src, val, buf, buf_sz);
}
/* `dirname(__DIR__)` — the application base directory. */
static bool lr_is_dirname_dir(const char *src, TSNode node) {
if (!lr_node_is(node, "function_call_expression") ||
!lr_node_text_is(src, ts_node_child_by_field_name(node, TS_FIELD("function")), "dirname")) {
return false;
}
TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
if (ts_node_is_null(args) || ts_node_named_child_count(args) != SKIP_ONE) {
return false;
}
TSNode arg = ts_node_named_child(args, 0);
TSNode val = lr_arg_value(arg, ts_node_child_by_field_name(arg, TS_FIELD("name")));
return lr_node_is(val, "name") && lr_node_text_is(src, val, "__DIR__");
}
/* Resolve "." and ".." segments of a '/'-joined path in place. False when the
* path climbs above the repository root. */
static bool lr_normalize(char *path) {
size_t seg_start[LR_SEG_MAX];
int depth = 0;
size_t out = 0;
const char *p = path;
while (*p) {
const char *slash = strchr(p, '/');
size_t len = slash ? (size_t)(slash - p) : strlen(p);
if (len == PAIR_LEN && p[0] == '.' && p[SKIP_ONE] == '.') {
if (depth == 0) {
return false;
}
out = seg_start[--depth];
} else if (len > 0 && !(len == SKIP_ONE && p[0] == '.')) {
if (depth == LR_SEG_MAX) {
return false;
}
size_t at = out > 0 ? out + SKIP_ONE : 0;
seg_start[depth++] = out;
if (out > 0) {
path[out] = '/';
}
memmove(path + at, p, len);
out = at + len;
}
p += len + (slash ? SKIP_ONE : 0);
}
path[out] = '\0';
return true;
}
/* Resolve one `api:` path expression of the app rooted at app_dir to a
* normalised repo-relative path:
* __DIR__ . '/../routes/api.php' (relative to bootstrap/)
* dirname(__DIR__) . '/routes/api.php' (relative to the app base)
* base_path('routes/api.php') (relative to the app base) */
static bool lr_route_file_path(const char *src, TSNode expr, const char *app_dir, char *out,
size_t out_sz) {
char lit[LR_PATH_MAX];
const char *base_suffix = NULL;
if (lr_node_is(expr, "binary_expression")) {
TSNode op = ts_node_child_by_field_name(expr, TS_FIELD("operator"));
TSNode left = ts_node_child_by_field_name(expr, TS_FIELD("left"));
if (!lr_node_text_is(src, op, ".") ||
!lr_string_literal(src, ts_node_child_by_field_name(expr, TS_FIELD("right")), lit,
sizeof(lit))) {
return false;
}
if (lr_node_is(left, "name") && lr_node_text_is(src, left, "__DIR__")) {
base_suffix = "bootstrap";
} else if (lr_is_dirname_dir(src, left)) {
base_suffix = "";
} else {
return false;
}
} else if (lr_call_literal_arg(src, expr, "base_path", lit, sizeof(lit))) {
base_suffix = "";
} else {
return false;
}
int n = snprintf(out, out_sz, "%s/%s/%s", app_dir, base_suffix, lit);
return n > 0 && (size_t)n < out_sz && lr_normalize(out);
}
/* Does the `api:` value (one path or an array of paths) name rel_path? */
static bool lr_api_names_file(const char *src, TSNode value, const char *app_dir,
const char *rel_path) {
char resolved[LR_PATH_MAX];
if (!lr_node_is(value, "array_creation_expression")) {
return lr_route_file_path(src, value, app_dir, resolved, sizeof(resolved)) &&
strcmp(resolved, rel_path) == 0;
}
uint32_t nc = ts_node_named_child_count(value);
for (uint32_t i = 0; i < nc; i++) {
TSNode elem = ts_node_named_child(value, i);
uint32_t ec = ts_node_named_child_count(elem);
if (!lr_node_is(elem, "array_element_initializer") || ec == 0) {
continue;
}
TSNode path_expr = ts_node_named_child(elem, ec - SKIP_ONE); /* value of `k => v` too */
if (lr_route_file_path(src, path_expr, app_dir, resolved, sizeof(resolved)) &&
strcmp(resolved, rel_path) == 0) {
return true;
}
}
return false;
}
/* Evaluate the named arguments of a withRouting(...) call. */
static bool lr_eval_with_routing(const char *src, TSNode call, const char *app_dir,
const char *rel_path, char *out, size_t out_sz) {
TSNode args = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
char prefix[LR_PREFIX_MAX] = "api"; /* ApplicationBuilder::withRouting default */
bool prefix_known = true;
bool mounted = false;
uint32_t nc = ts_node_is_null(args) ? 0 : ts_node_named_child_count(args);
for (uint32_t i = 0; i < nc; i++) {
TSNode arg = ts_node_named_child(args, i);
if (lr_node_is(arg, "comment")) {
continue;
}
TSNode label = ts_node_child_by_field_name(arg, TS_FIELD("name"));
char key[LR_KEY_MAX];
/* Positional arguments would need the parameter order modelled, and a
* `using:` callback replaces the web/api registration entirely. */
if (!lr_node_is(arg, "argument") || ts_node_is_null(label) ||
!lr_node_text(src, label, key, sizeof(key)) || strcmp(key, "using") == 0) {
return false;
}
TSNode value = lr_arg_value(arg, label);
if (strcmp(key, "api") == 0) {
mounted = lr_api_names_file(src, value, app_dir, rel_path);
} else if (strcmp(key, "apiPrefix") == 0) {
prefix_known = lr_string_literal(src, value, prefix, sizeof(prefix));
}
}
if (!mounted || !prefix_known) {
return false;
}
/* Laravel trims the group prefix of '/' on both ends. */
const char *start = prefix;
size_t len = strlen(prefix);
while (*start == '/') {
start++;
len--;
}
while (len > 0 && start[len - SKIP_ONE] == '/') {
len--;
}
int n = snprintf(out, out_sz, "/%.*s", (int)len, start);
return len > 0 && n > 0 && (size_t)n < out_sz;
}
/* First `->withRouting(...)` call in the tree (iterative pre-order walk). */
static TSNode lr_find_with_routing(const char *src, TSNode root) {
TSNode found = {0};
TSTreeCursor cur = ts_tree_cursor_new(root);
bool more = true;
while (more) {
TSNode node = ts_tree_cursor_current_node(&cur);
if ((lr_node_is(node, "member_call_expression") ||
lr_node_is(node, "nullsafe_member_call_expression")) &&
lr_node_text_is(src, ts_node_child_by_field_name(node, TS_FIELD("name")),
"withRouting")) {
found = node;
break;
}
if (ts_tree_cursor_goto_first_child(&cur)) {
continue;
}
while (!ts_tree_cursor_goto_next_sibling(&cur)) {
if (!ts_tree_cursor_goto_parent(&cur)) {
more = false;
break;
}
}
}
ts_tree_cursor_delete(&cur);
return found;
}
static bool lr_mount_from_bootstrap(const char *src, uint32_t len, const char *app_dir,
const char *rel_path, char *out, size_t out_sz) {
const TSLanguage *php = cbm_ts_language(CBM_LANG_PHP);
TSParser *parser = php ? ts_parser_new() : NULL;
if (!parser) {
return false;
}
bool mounted = false;
TSTree *tree =
ts_parser_set_language(parser, php) ? ts_parser_parse_string(parser, NULL, src, len) : NULL;
if (tree) {
TSNode call = lr_find_with_routing(src, ts_tree_root_node(tree));
mounted = !ts_node_is_null(call) &&
lr_eval_with_routing(src, call, app_dir, rel_path, out, out_sz);
ts_tree_delete(tree);
}
ts_parser_delete(parser);
return mounted;
}
/* Read <repo>/<app_dir>/bootstrap/app.php. NULL when absent or unreadable. */
static char *lr_read_bootstrap(const char *repo_path, const char *app_dir, uint32_t *out_len) {
char path[CBM_SZ_4K];
int n = snprintf(path, sizeof(path), "%s/%s%s%s", repo_path, app_dir, app_dir[0] ? "/" : "",
LR_BOOTSTRAP_REL);
if (n <= 0 || (size_t)n >= sizeof(path)) {
return NULL;
}
FILE *f = cbm_fopen(path, "rb");
if (!f) {
return NULL;
}
(void)fseek(f, 0, SEEK_END);
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
char *buf = (size > 0 && size <= (long)LR_SOURCE_MAX)
? cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)size + SKIP_ONE)
: NULL;
if (buf) {
size_t nread = fread(buf, SKIP_ONE, (size_t)size, f);
buf[nread] = '\0';
*out_len = (uint32_t)nread;
}
(void)fclose(f);
return buf;
}
bool cbm_laravel_api_mount(const char *repo_path, const char *rel_path, char *out, size_t out_sz) {
if (!out || out_sz == 0) {
return false;
}
out[0] = '\0';
size_t rel_len = rel_path ? strlen(rel_path) : 0;
if (!repo_path || rel_len < sizeof(".php") || rel_len >= LR_PATH_MAX ||
strcmp(rel_path + rel_len - (sizeof(".php") - SKIP_ONE), ".php") != 0) {
return false;
}
/* Walk the file's ancestor directories nearest-first; the nearest one
* holding bootstrap/app.php is the Laravel app that owns the file. */
char app_dir[LR_PATH_MAX];
memcpy(app_dir, rel_path, rel_len + SKIP_ONE);
char *slash = strrchr(app_dir, '/');
for (;;) {
if (slash) {
*slash = '\0';
} else {
app_dir[0] = '\0';
}
uint32_t len = 0;
char *src = lr_read_bootstrap(repo_path, app_dir, &len);
if (src) {
bool mounted = lr_mount_from_bootstrap(src, len, app_dir, rel_path, out, out_sz);
cbm_free(CBM_MEM_CLASS_EXTRACT, src);
if (!mounted) {
out[0] = '\0';
}
return mounted;
}
if (!app_dir[0]) {
return false;
}
slash = strrchr(app_dir, '/');
}
}
void cbm_laravel_file_route_mount(const char *repo_path, const char *rel_path, CBMLanguage lang,
const CBMFileResult *result, char *out, size_t out_sz) {
if (!out || out_sz == 0) {
return;
}
out[0] = '\0';
if (lang != CBM_LANG_PHP || !result) {
return;
}
for (int i = 0; i < result->calls.count; i++) {
const CBMCall *call = &result->calls.items[i];
if (call->callee_name && call->first_string_arg && call->first_string_arg[0] == '/' &&
cbm_service_pattern_route_method(call->callee_name) != NULL) {
(void)cbm_laravel_api_mount(repo_path, rel_path, out, out_sz);
return;
}
}
}
const char *cbm_laravel_mount_route(const char *mount, const char *path, char *buf, size_t buf_sz) {
if (!mount || !mount[0] || !path || !buf || buf_sz == 0) {
return path;
}
const char *rel = path;
while (*rel == '/') {
rel++;
}
int n =
rel[0] ? snprintf(buf, buf_sz, "%s/%s", mount, rel) : snprintf(buf, buf_sz, "%s", mount);
return (n > 0 && (size_t)n < buf_sz) ? buf : path;
}
+48
View File
@@ -0,0 +1,48 @@
#ifndef CBM_LARAVEL_ROUTING_H
#define CBM_LARAVEL_ROUTING_H
/*
* laravel_routing.h — Laravel 11+ framework route mounts (#1146).
*
* Laravel 11+ registers route files in bootstrap/app.php:
*
* Application::configure(basePath: dirname(__DIR__))
* ->withRouting(web: __DIR__.'/../routes/web.php',
* api: __DIR__.'/../routes/api.php',
* apiPrefix: 'api')
*
* and mounts every file passed as `api:` under `apiPrefix` (default 'api');
* the `web:` file gets no prefix. The prefix is declared in a DIFFERENT file
* than the routes, so per-file extraction cannot compose it the way it does
* the in-file `Route::prefix()->group()` chain (#952). The route passes ask
* here once per PHP file that registers routes and prepend the mount to every
* Route path minted from that file.
*
* Only what bootstrap/app.php states as source fact is used: the nearest
* ancestor bootstrap/app.php must name the file under `api:`, and a given
* `apiPrefix:` must be a string literal. A non-literal prefix, positional
* arguments or a `using:` callback leave the paths untouched — nothing is
* inferred from file names.
*/
#include "cbm.h"
#include <stdbool.h>
#include <stddef.h>
/* Write the mount ("/api", "/v1/api") under which the Laravel app that owns
* rel_path serves its routes into out and return true. Returns false with
* out = "" when rel_path is not mounted under a known, non-empty prefix. */
bool cbm_laravel_api_mount(const char *repo_path, const char *rel_path, char *out, size_t out_sz);
/* Per-file entry for the route passes: probes cbm_laravel_api_mount only for
* a PHP file that registers at least one path-shaped route; out = "" for
* every other file, so no other language pays a lookup. */
void cbm_laravel_file_route_mount(const char *repo_path, const char *rel_path, CBMLanguage lang,
const CBMFileResult *result, char *out, size_t out_sz);
/* Compose mount + route path: "/api" + "/users/me" -> "/api/users/me",
* "/api" + "/" -> "/api". Returns path unchanged when mount is empty or the
* composed path does not fit buf. */
const char *cbm_laravel_mount_route(const char *mount, const char *path, char *buf, size_t buf_sz);
#endif /* CBM_LARAVEL_ROUTING_H */
+14 -2
View File
@@ -22,6 +22,7 @@
#define CBM_PIPELINE_LSP_RESOLVE_H
#include "cbm.h"
#include "callable_sig.h" /* cbm_qn_callable_base_len — leaf splitters skip the suffix */
#include "graph_buffer/graph_buffer.h"
#include "foundation/constants.h"
@@ -64,7 +65,10 @@ static inline const char *cbm_lsp_bare_segment(const char *name) {
return name;
}
const char *seg = name;
for (const char *p = name; *p; p++) {
/* Scan the base only: a callable identity suffix (#2061) belongs to the
* leaf and may itself contain ':' (Swift labels) or '>' (generics). */
const char *end = name + cbm_qn_callable_base_len(name);
for (const char *p = name; p < end; p++) {
/* '.' (dotted QN / Java-style member) and ':' (C++ `::`, last colon
* wins) are member/scope separators. '>' is only a separator when it
* closes the `->` arrow (preceded by '-'); a bare '>' closes a template
@@ -86,7 +90,15 @@ static inline const char *cbm_pipeline_qn_class_method_tail(const char *qn) {
if (!qn) {
return NULL;
}
const char *last = strrchr(qn, '.');
/* The last '.' of the BASE QN: a callable identity suffix (#2061) never
* contains '.', so this is the historical strrchr for every QN. */
const char *last = NULL;
size_t base_len = cbm_qn_callable_base_len(qn);
for (size_t i = 0; i < base_len; i++) {
if (qn[i] == '.') {
last = qn + i;
}
}
if (!last || last == qn) {
return NULL;
}
+48 -14
View File
@@ -19,6 +19,7 @@ enum { PC_RING = 4, PC_RING_MASK = 3, PC_SIG_SCAN = 15, PC_REGEX_GRP = 2 };
#include <stdint.h>
#include "pipeline/pipeline_internal.h"
#include "pipeline/lsp_resolve.h"
#include "pipeline/laravel_routing.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
#include "foundation/compat.h"
@@ -374,23 +375,29 @@ bool cbm_pipeline_http_client_call_url(const cbm_gbuf_t *gbuf, const char *proje
return n > 0 && (size_t)n < out_sz;
}
/* Handle a route registration call: create Route node + HANDLES edge. */
/* Handle a route registration call: create Route node + HANDLES edge.
* route_mount is the framework mount of the registering file ("/api" for a
* Laravel 11+ `withRouting(api: ...)` file, #1146) or "". */
static void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *call,
const cbm_gbuf_node_t *source_node, const char *module_qn,
const char **imp_keys, const char **imp_vals, int imp_count) {
const char **imp_keys, const char **imp_vals, int imp_count,
const char *route_mount) {
const char *method = cbm_service_pattern_route_method(call->callee_name);
char mounted[CBM_SZ_256];
const char *path =
cbm_laravel_mount_route(route_mount, call->first_string_arg, mounted, sizeof(mounted));
char route_qn[CBM_ROUTE_QN_SIZE];
char cpath[CBM_SZ_256];
snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", method ? method : "ANY",
cbm_route_canon_path(call->first_string_arg, cpath, sizeof(cpath)));
cbm_route_canon_path(path, cpath, sizeof(cpath)));
char route_props[CBM_SZ_256];
snprintf(route_props, sizeof(route_props), "{\"method\":\"%s\"}", method ? method : "ANY");
int64_t route_id = cbm_gbuf_upsert_node(ctx->gbuf, "Route", call->first_string_arg, route_qn,
"", 0, 0, route_props);
int64_t route_id =
cbm_gbuf_upsert_node(ctx->gbuf, "Route", path, route_qn, "", 0, 0, route_props);
char esc_cn[CBM_SZ_256]; /* sliced source text: escape quotes/newlines */
char esc_fa[CBM_SZ_256];
cbm_json_escape(esc_cn, sizeof(esc_cn), call->callee_name);
cbm_json_escape(esc_fa, sizeof(esc_fa), call->first_string_arg);
cbm_json_escape(esc_fa, sizeof(esc_fa), path);
char props[CBM_SZ_512];
snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"url_path\":\"%s\",\"via\":\"route_registration\"}", esc_cn,
@@ -588,10 +595,11 @@ static void emit_classified_edge(cbm_pipeline_ctx_t *ctx, const CBMCall *call,
const cbm_gbuf_node_t *source, const cbm_gbuf_node_t *target,
const cbm_resolution_t *res, const char *module_qn,
const char **imp_keys, const char **imp_vals, int imp_count,
bool suppress_plain_calls) {
bool suppress_plain_calls, const char *route_mount) {
cbm_svc_kind_t svc = cbm_service_pattern_match(res->qualified_name);
if (svc == CBM_SVC_ROUTE_REG && call->first_string_arg && call->first_string_arg[0] == '/') {
handle_route_registration(ctx, call, source, module_qn, imp_keys, imp_vals, imp_count);
handle_route_registration(ctx, call, source, module_qn, imp_keys, imp_vals, imp_count,
route_mount);
return;
}
if (svc == CBM_SVC_HTTP || svc == CBM_SVC_ASYNC) {
@@ -645,7 +653,8 @@ static const cbm_gbuf_node_t *calls_find_source(cbm_pipeline_ctx_t *ctx, const c
/* 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 CBMFileResult *result,
const char *rel, const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count, CBMLanguage lang) {
const char **imp_vals, int imp_count, CBMLanguage lang,
const CBMImportArray *imports, const char *route_mount) {
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) {
@@ -674,7 +683,7 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
res.strategy = lsp->strategy;
res.candidate_count = 1;
emit_classified_edge(ctx, call, source_node, target_node, &res, module_qn, imp_keys,
imp_vals, imp_count, false);
imp_vals, imp_count, false, route_mount);
return SKIP_ONE;
}
}
@@ -766,7 +775,7 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
if (cbm_service_pattern_route_method(call->callee_name) != NULL && call->first_string_arg &&
call->first_string_arg[0] == '/') {
handle_route_registration(ctx, call, source_node, module_qn, imp_keys, imp_vals,
imp_count);
imp_count, route_mount);
return SKIP_ONE;
}
cbm_svc_kind_t esvc = cbm_service_pattern_match(call->callee_name);
@@ -847,7 +856,14 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
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
@@ -877,10 +893,23 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
* Store.commit() call to a JS function named commit (or a Bash main
* to a Python main). Drop that weak cross-language edge. */
if (cbm_suppress_cross_language_suffix_match(lang, target_node->file_path, res.strategy)) {
/* Refusing the binding leaves the callee unresolved, and an
* unresolved route-registration callee is still a registration:
* `Route::get('/x', ...)` beside a JS `get`, `app.get('/x', h)`
* beside a Python `get`. Give it the same Route the #952
* unresolved-callee fallback above mints, and nothing else. Dropping
* the whole call lost every GET registration in a mixed-language repo
* while POST (no `post` to collide with) survived. */
if (cbm_service_pattern_route_method(call->callee_name) != NULL && call->first_string_arg &&
call->first_string_arg[0] == '/') {
handle_route_registration(ctx, call, source_node, module_qn, imp_keys, imp_vals,
imp_count, route_mount);
return SKIP_ONE;
}
return 0;
}
emit_classified_edge(ctx, call, source_node, target_node, &res, module_qn, imp_keys, imp_vals,
imp_count, drop_plain_call);
imp_count, drop_plain_call, route_mount);
return SKIP_ONE;
}
@@ -1031,6 +1060,11 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
char *module_qn = cbm_pipeline_fqn_module_dir(ctx->project_name, rel,
pc_module_is_dir(files[i].language));
/* Framework mount of this file's routes (Laravel 11+ withRouting, #1146). */
char route_mount[CBM_SZ_128];
cbm_laravel_file_route_mount(ctx->repo_path, rel, files[i].language, result, route_mount,
sizeof(route_mount));
/* Resolve each call */
for (int c = 0; c < result->calls.count; c++) {
CBMCall *call = &result->calls.items[c];
@@ -1039,7 +1073,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
}
total_calls++;
if (resolve_single_call(ctx, call, result, rel, module_qn, imp_keys, imp_vals,
imp_count, files[i].language)) {
imp_count, files[i].language, &result->imports, route_mount)) {
resolved++;
} else {
unresolved++;
+67 -5
View File
@@ -22,6 +22,7 @@ enum { PD_JSON_FIELD_OVERHEAD = 6 };
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
#include "foundation/mem_core.h" /* cbm_alloc/cbm_free: the grown properties buffer */
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/limits.h"
@@ -321,16 +322,74 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
}
}
/* Process one definition: create node, register, DEFINES + DEFINES_METHOD edges. */
static void process_def(cbm_pipeline_ctx_t *ctx, const CBMDefinition *def, const char *rel) {
/* A def's properties buffer: CBM_SZ_2K for every other field plus the whole
* serialized docstring field, which has no length cap (a field that does not
* fit is dropped whole). Returns `stack` for a def without a docstring, or
* when the larger buffer cannot be allocated. Twin of pass_parallel.c -- keep
* both in sync. */
static char *pd_props_buf(const CBMDefinition *def, char *stack, size_t *size) {
if (!def->docstring || !def->docstring[0]) {
return stack;
}
size_t need =
*size + strlen("docstring") + def_json_escaped_len(def->docstring) + PD_JSON_FIELD_OVERHEAD;
char *buf = cbm_alloc(CBM_MEM_CLASS_GBUF_STRING, need);
if (!buf) {
return stack;
}
*size = need;
return buf;
}
/* Add a file's own doc (Go package comment, Rust inner docs) to its File
* node as "docstring". Twin of pass_parallel.c -- keep both in sync. */
static void pd_add_file_doc(const cbm_gbuf_node_t *file_node, const char *doc) {
if (!file_node || !doc || !doc[0]) {
return;
}
const char *old = file_node->properties_json ? file_node->properties_json : "{}";
size_t olen = strlen(old);
if (olen < PAIR_LEN || old[olen - SKIP_ONE] != '}') {
return; /* not a JSON object -- leave it untouched */
}
size_t cap = olen + strlen("docstring") + def_json_escaped_len(doc) + PD_JSON_FIELD_OVERHEAD +
PD_ESC_SPACE + SKIP_ONE;
char *neu = cbm_alloc(CBM_MEM_CLASS_GBUF_STRING, cap);
if (!neu) {
return;
}
size_t pos = olen - SKIP_ONE; /* without the closing brace */
memcpy(neu, old, pos);
neu[pos] = '\0';
append_json_string(neu, cap, &pos, "docstring", doc);
if (olen == PAIR_LEN && pos > PAIR_LEN) { /* "{}": drop the leading comma */
memmove(neu + SKIP_ONE, neu + PAIR_LEN, pos - SKIP_ONE);
pos--;
}
neu[pos++] = '}';
neu[pos] = '\0';
(void)cbm_gbuf_node_set_properties_json((cbm_gbuf_node_t *)file_node, neu);
cbm_free(CBM_MEM_CLASS_GBUF_STRING, neu);
}
/* Process one definition: create node, register, DEFINES + DEFINES_METHOD edges.
* `file_doc`, the file's own doc (passed with its first def only), goes on the
* File node. */
static void process_def(cbm_pipeline_ctx_t *ctx, const CBMDefinition *def, const char *rel,
const char *file_doc) {
if (!def->qualified_name || !def->name) {
return;
}
char props[CBM_SZ_2K];
build_def_props(props, sizeof(props), def);
char stack[CBM_SZ_2K];
size_t props_size = sizeof(stack);
char *props = pd_props_buf(def, stack, &props_size);
build_def_props(props, props_size, def);
int64_t node_id = cbm_gbuf_upsert_node(
ctx->gbuf, def->label ? def->label : "Function", def->name, def->qualified_name,
def->file_path ? def->file_path : rel, (int)def->start_line, (int)def->end_line, props);
if (props != stack) {
cbm_free(CBM_MEM_CLASS_GBUF_STRING, props);
}
/* Registry membership is defined ONCE by cbm_label_is_registry_symbol
* (helpers.c): callables + type-like containers (INHERITS/IMPLEMENTS/method/
* field resolution), Variable/Field (READS/WRITES resolution), and Table/View
@@ -341,6 +400,7 @@ static void process_def(cbm_pipeline_ctx_t *ctx, const CBMDefinition *def, const
}
char *file_qn = cbm_pipeline_fqn_compute(ctx->project_name, rel, "__file__");
const cbm_gbuf_node_t *file_node = cbm_gbuf_find_by_qn(ctx->gbuf, file_qn);
pd_add_file_doc(file_node, file_doc);
if (file_node && node_id > 0) {
cbm_gbuf_insert_edge(ctx->gbuf, file_node->id, node_id, "DEFINES", "{}");
}
@@ -860,8 +920,10 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
}
/* Create nodes for each definition */
const char *file_doc = result->module_doc; /* goes with the first def */
for (int d = 0; d < result->defs.count; d++) {
process_def(ctx, &result->defs.items[d], rel);
process_def(ctx, &result->defs.items[d], rel, file_doc);
file_doc = NULL;
total_defs++;
}
+9 -1
View File
@@ -6,6 +6,7 @@
#include "foundation/compat_fs.h"
#include "foundation/constants.h"
#include "foundation/str_util.h"
#include "callable_sig.h"
#include <stdio.h>
#include <stdlib.h>
@@ -425,7 +426,14 @@ static void collect_prod_defs(cbm_pipeline_ctx_t *ctx, ens_prod_def_t ***defs_ou
char class_qn[CBM_SZ_256];
class_qn[0] = '\0';
if (xd->qualified_name) {
const char *dot = strrchr(xd->qualified_name, '.');
/* Owner = base QN minus its leaf (#2061 suffixes hold no '.'). */
const char *dot = NULL;
size_t base_len = cbm_qn_callable_base_len_named(xd->qualified_name, xd->name);
for (size_t i = 0; i < base_len; i++) {
if (xd->qualified_name[i] == '.') {
dot = xd->qualified_name + i;
}
}
if (dot) {
int len = (int)(dot - xd->qualified_name);
if (len > 0 && len < CBM_SZ_256) {
+144 -3
View File
@@ -19,6 +19,7 @@
#include "result_spill.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/lsp_resolve.h"
#include "callable_sig.h"
#include "lsp/go_lsp.h"
#include "lsp/c_lsp.h"
#include "lsp/py_lsp.h"
@@ -273,12 +274,20 @@ static const char *pxc_join_base_qns(CBMArena *arena, const char *const *bases,
static bool pxc_is_jvm_lang(CBMLanguage lang);
/* Leaf of the BASE QN: a callable identity suffix (#2061) never contains
* '.', so this equals the historical strrchr split for every QN. */
static const char *pxc_last_component(const char *qn) {
if (!qn) {
return NULL;
}
const char *dot = strrchr(qn, '.');
return dot ? dot + 1 : qn;
const char *leaf = qn;
size_t base_len = cbm_qn_callable_base_len(qn);
for (size_t i = 0; i < base_len; i++) {
if (qn[i] == '.') {
leaf = qn + i + 1;
}
}
return leaf;
}
/* Every return is arena-owned: the fallback spelling is a copy, never the
@@ -377,7 +386,9 @@ static const char *pxc_qn_leaf(const char *name) {
return NULL;
}
const char *leaf = name;
for (const char *p = name; *p; p++) {
/* Base only: a callable identity suffix (#2061) may carry ':' labels. */
const char *end = name + cbm_qn_callable_base_len(name);
for (const char *p = name; p < end; p++) {
if (*p == '.' || *p == ':' || *p == '/' || *p == '\\') {
leaf = p + 1;
}
@@ -529,6 +540,132 @@ static void pxc_fold_go_struct_fields(CBMArena *arena, const CBMFileResult *resu
}
}
/* Python annotation text -> the one type name it declares, or NULL. Strips a
* string-literal forward reference and unwraps `Optional[X]`, `X | None` and
* `None | X`; anything else with brackets, commas or a real union (generics,
* Callable, Union[A, B]) names no single receiver type and is dropped. */
static const char *pxc_py_annotation_type_name(CBMArena *arena, const char *text) {
if (!text) {
return NULL;
}
while (*text == ' ') {
text++;
}
size_t n = strlen(text);
while (n > 0 && text[n - 1] == ' ') {
n--;
}
if (n >= 2 && (text[0] == '"' || text[0] == '\'') && text[n - 1] == text[0]) {
text++;
n -= 2;
}
static const char *const optional_prefixes[] = {"Optional[", "typing.Optional["};
for (size_t i = 0; i < sizeof(optional_prefixes) / sizeof(optional_prefixes[0]); i++) {
size_t plen = strlen(optional_prefixes[i]);
if (n > plen + 1 && strncmp(text, optional_prefixes[i], plen) == 0 && text[n - 1] == ']') {
text += plen;
n -= plen + 1;
break;
}
}
static const char none_tail[] = " | None";
static const char none_head[] = "None | ";
const size_t none_len = sizeof(none_tail) - 1;
if (n > none_len && strncmp(text + n - none_len, none_tail, none_len) == 0) {
n -= none_len;
} else if (n > none_len && strncmp(text, none_head, none_len) == 0) {
text += none_len;
n -= none_len;
}
if (n == 0) {
return NULL;
}
for (size_t i = 0; i < n; i++) {
char c = text[i];
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '.';
if (!ok) {
return NULL;
}
}
return cbm_arena_strndup(arena, text, n);
}
/* Python: fold the file's annotated instance fields (result->field_types,
* #1277) into their class defs' field_defs as "name:QN|name:QN", the format
* py_register_lsp_defs reads. Each annotation resolves through the same
* registry + import map, and the same weak-strategy and type-like vetoes, as
* the file's base classes (pxc_resolve_base_qn): a field whose type is not a
* confidently-known project type is left out rather than guessed. Linear in
* the file: one hash of the file's class defs, one pass over its fields. */
typedef struct {
int owner; /* index into defs[], or -1 */
const char *type_qn;
} pxc_py_field_t;
static void pxc_fold_py_field_types(CBMArena *arena, const CBMFileResult *result, CBMLSPDef *defs,
int start, int end, const cbm_registry_t *reg,
const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count) {
int nf = result ? result->field_types.count : 0;
if (!arena || nf == 0 || !defs || start >= end || !reg) {
return;
}
CBMHashTable *by_qn = cbm_ht_create((uint32_t)(end - start));
pxc_py_field_t *fields = (pxc_py_field_t *)cbm_arena_alloc(arena, (size_t)nf * sizeof(*fields));
/* Per class def: exact buffer size, then the write cursor into it. */
size_t *lens = (size_t *)cbm_arena_alloc(arena, (size_t)(end - start) * sizeof(size_t));
size_t *used = (size_t *)cbm_arena_alloc(arena, (size_t)(end - start) * sizeof(size_t));
if (!by_qn || !fields || !lens || !used) {
cbm_ht_free(by_qn); /* NULL-safe */
return;
}
memset(lens, 0, (size_t)(end - start) * sizeof(size_t));
memset(used, 0, (size_t)(end - start) * sizeof(size_t));
for (int si = start; si < end; si++) {
if (defs[si].label && strcmp(defs[si].label, "Class") == 0 && defs[si].qualified_name) {
cbm_ht_set(by_qn, defs[si].qualified_name, &defs[si]);
}
}
for (int f = 0; f < nf; f++) {
const CBMFieldType *ft = &result->field_types.items[f];
fields[f].owner = -1;
fields[f].type_qn = NULL;
CBMLSPDef *owner = ft->class_qn ? (CBMLSPDef *)cbm_ht_get(by_qn, ft->class_qn) : NULL;
const char *name = owner ? pxc_py_annotation_type_name(arena, ft->type_text) : NULL;
const char *qn =
name ? pxc_resolve_base_qn(reg, name, module_qn, imp_keys, imp_vals, imp_count) : NULL;
if (!qn || !ft->field_name || !ft->field_name[0]) {
continue;
}
fields[f].owner = (int)(owner - defs);
fields[f].type_qn = qn;
/* "name:QN" plus one byte for the '|' or the NUL after it. */
lens[fields[f].owner - start] += strlen(ft->field_name) + 1 + strlen(qn) + 1;
}
cbm_ht_free(by_qn);
for (int si = start; si < end; si++) {
char *buf = lens[si - start] ? (char *)cbm_arena_alloc(arena, lens[si - start]) : NULL;
if (buf) {
buf[0] = '\0';
}
defs[si].field_defs = buf;
}
for (int f = 0; f < nf; f++) {
char *buf = fields[f].owner >= 0 ? (char *)defs[fields[f].owner].field_defs : NULL;
if (!buf) {
continue;
}
int slot = fields[f].owner - start;
int wrote =
snprintf(buf + used[slot], lens[slot] - used[slot], "%s%s:%s", used[slot] ? "|" : "",
result->field_types.items[f].field_name, fields[f].type_qn);
if (wrote > 0) {
used[slot] += (size_t)wrote;
}
}
}
/* Carry one Rust type-level impl independently of any method definition.
* `impl Trait for Type {}` is semantically meaningful even when the block is
* empty (the trait may provide defaults), so attaching the relation only to
@@ -634,6 +771,10 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are
idx++;
}
}
if (files[fi].language == CBM_LANG_PYTHON) {
pxc_fold_py_field_types(arena, fr, defs, file_start, idx, base_reg, def_modules[fi],
imp_keys, imp_vals, imp_count);
}
cbm_pxc_free_import_map(imp_keys, imp_vals, imp_count); /* NULL-safe */
if (files[fi].language == CBM_LANG_GO) {
pxc_fold_go_struct_fields(arena, fr, defs, file_start, idx);
+159 -39
View File
@@ -74,6 +74,7 @@ enum { PP_CSHARP_M_PREFIX_LEN = 2 };
#include "foundation/platform.h" /* cbm_resolve_cache_dir */
#include "pipeline/pass_lsp_cross.h" /* cbm_pxc_* helpers for fused cross-file LSP */
#include "pipeline/lsp_resolve.h"
#include "pipeline/laravel_routing.h"
#include "lsp/rust_cargo.h"
#include "helpers.h" /* cbm_kind_in_set_free_cache — per-worker-thread cache teardown */
#include "pipeline/worker_pool.h"
@@ -697,15 +698,39 @@ typedef struct {
* to the response/logfile — this only throttles the stderr noise). */
enum { PP_OVERSIZED_WARN_MAX = 32 };
/* A def's properties buffer: CBM_SZ_2K for every other field plus the whole
* serialized docstring field, which has no length cap (a field that does not
* fit is dropped whole). Returns `stack` for a def without a docstring, or
* when the larger buffer cannot be allocated. Twin of pass_definitions.c --
* keep both in sync. */
static char *pp_props_buf(const CBMDefinition *def, char *stack, size_t *size) {
if (!def->docstring || !def->docstring[0]) {
return stack;
}
size_t need =
*size + strlen("docstring") + pp_json_escaped_len(def->docstring) + PP_JSON_FIELD_OVERHEAD;
char *buf = cbm_alloc(CBM_MEM_CLASS_GBUF_STRING, need);
if (!buf) {
return stack;
}
*size = need;
return buf;
}
/* Insert one definition node (and its route if present) into the local gbuf. */
static void insert_def_into_gbuf(extract_worker_state_t *ws, const cbm_file_info_t *fi,
CBMDefinition *def) {
char props[CBM_SZ_2K];
build_def_props(props, sizeof(props), def);
char stack[CBM_SZ_2K];
size_t props_size = sizeof(stack);
char *props = pp_props_buf(def, stack, &props_size);
build_def_props(props, props_size, def);
int64_t func_id =
cbm_gbuf_upsert_node(ws->local_gbuf, def->label ? def->label : "Function", def->name,
def->qualified_name, def->file_path ? def->file_path : fi->rel_path,
(int)def->start_line, (int)def->end_line, props);
if (props != stack) {
cbm_free(CBM_MEM_CLASS_GBUF_STRING, props);
}
ws->nodes_created++;
if (def->route_path && def->route_path[0] != '\0') {
const char *rm = def->route_method ? def->route_method : "ANY";
@@ -1692,6 +1717,37 @@ static int register_and_link_def(cbm_pipeline_ctx_t *ctx, const CBMDefinition *d
return edges;
}
/* Add a file's own doc (Go package comment, Rust inner docs) to its File
* node as "docstring". Twin of pass_definitions.c -- keep both in sync. */
static void pp_add_file_doc(const cbm_gbuf_node_t *file_node, const char *doc) {
if (!file_node || !doc || !doc[0]) {
return;
}
const char *old = file_node->properties_json ? file_node->properties_json : "{}";
size_t olen = strlen(old);
if (olen < PAIR_LEN || old[olen - SKIP_ONE] != '}') {
return; /* not a JSON object -- leave it untouched */
}
size_t cap = olen + strlen("docstring") + pp_json_escaped_len(doc) + PP_JSON_FIELD_OVERHEAD +
PP_ESC_SPACE + SKIP_ONE;
char *neu = cbm_alloc(CBM_MEM_CLASS_GBUF_STRING, cap);
if (!neu) {
return;
}
size_t pos = olen - SKIP_ONE; /* without the closing brace */
memcpy(neu, old, pos);
neu[pos] = '\0';
append_json_string(neu, cap, &pos, "docstring", doc);
if (olen == PAIR_LEN && pos > PAIR_LEN) { /* "{}": drop the leading comma */
memmove(neu + SKIP_ONE, neu + PAIR_LEN, pos - SKIP_ONE);
pos--;
}
neu[pos++] = '}';
neu[pos] = '\0';
(void)cbm_gbuf_node_set_properties_json((cbm_gbuf_node_t *)file_node, neu);
cbm_free(CBM_MEM_CLASS_GBUF_STRING, neu);
}
/* Create IMPORTS edges for one file's imports (parallel path). */
static int create_imports_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result,
const char *rel, CBMHashTable *namespace_map) {
@@ -1826,6 +1882,7 @@ int cbm_build_registry_from_cache(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
const cbm_gbuf_node_t *file_node = cbm_gbuf_find_by_qn(ctx->gbuf, file_qn);
int64_t file_node_id = file_node ? file_node->id : 0;
free(file_qn);
pp_add_file_doc(file_node, result->module_doc);
for (int d = 0; d < result->defs.count; d++) {
defines_edges +=
register_and_link_def(ctx, &result->defs.items[d], file_node_id, &reg_entries);
@@ -2209,13 +2266,18 @@ static void emit_normal_calls_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *sour
}
/* Classify a resolved call by library identity and emit the appropriate edge. */
/* Create Route node + CALLS + HANDLES edges for a route registration call. */
/* Create Route node + CALLS + HANDLES edges for a route registration call.
* route_mount is the framework mount of the registering file ("/api" for a
* Laravel 11+ `withRouting(api: ...)` file, #1146) or "". */
static void emit_route_registration(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const CBMCall *call, const char *route_path,
const char *handler_ref, const char *module_qn,
const cbm_registry_t *registry, const cbm_gbuf_t *main_gbuf,
const char **ik, const char **iv, int ic) {
const char **ik, const char **iv, int ic,
const char *route_mount) {
const char *method = cbm_service_pattern_route_method(call->callee_name);
char mounted[CBM_SZ_256];
route_path = cbm_laravel_mount_route(route_mount, route_path, mounted, sizeof(mounted));
char rqn[CBM_ROUTE_QN_SIZE];
char cpath[CBM_SZ_256];
snprintf(rqn, sizeof(rqn), "__route__%s__%s", method ? method : "ANY",
@@ -2441,40 +2503,43 @@ static void emit_grpc_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source, cons
cbm_gbuf_insert_edge(gbuf, source->id, route_id, "GRPC_CALLS", props);
}
/* Emit GRAPHQL_CALLS edge. Extract operation from first string arg if available. */
/* Emit GRAPHQL_CALLS edge. The Route is keyed by the operation NAME only
* (#598), never by the operation text:
* named operation -> __graphql__<Name> name "<Name>"
* anonymous query/mutation/ -> __graphql__<type>__anonymous name "(anonymous <type>)"
* subscription (incl. the `{ ... }` query shorthand)
* no GraphQL document -> __graphql__operation__anonymous name "(anonymous operation)"
* (URL, variable, missing string argument)
* Keys are bounded by the GraphQL Name grammar and deterministic. */
static void emit_graphql_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source, const CBMCall *call,
const cbm_resolution_t *res) {
const char *op = call->first_string_arg;
if (!op || !op[0]) {
op = call->callee_name;
}
/* Try to extract a query/mutation name from the operation string */
char op_name[CBM_SZ_256];
snprintf(op_name, sizeof(op_name), "%s", op);
/* Trim leading whitespace and "query "/"mutation " prefix */
const char *p = op_name;
while (*p == ' ' || *p == '\t' || *p == '\n') {
p++;
}
if (strncmp(p, "query ", CBM_SZ_6) == 0) {
p += CBM_SZ_6;
} else if (strncmp(p, "mutation ", CBM_SZ_8) == 0) {
p += CBM_SZ_8;
const char *op_type = "operation";
char op_name[CBM_SZ_128];
bool named = cbm_service_pattern_graphql_operation(call->first_string_arg, &op_type, op_name,
sizeof(op_name));
char route_name[CBM_SZ_256];
char route_qn[CBM_SZ_256];
if (named) {
snprintf(route_name, sizeof(route_name), "%s", op_name);
snprintf(route_qn, sizeof(route_qn), "__graphql__%s", op_name);
} else {
snprintf(route_name, sizeof(route_name), "(anonymous %s)", op_type);
snprintf(route_qn, sizeof(route_qn), "__graphql__%s__anonymous", op_type);
}
char route_qn[CBM_SZ_512];
snprintf(route_qn, sizeof(route_qn), "__graphql__%s", p);
int64_t route_id =
cbm_gbuf_upsert_node(gbuf, "Route", p, route_qn, "", 0, 0, "{\"source\":\"graphql\"}");
int64_t route_id = cbm_gbuf_upsert_node(gbuf, "Route", route_name, route_qn, "", 0, 0,
"{\"source\":\"graphql\"}");
char esc_c[CBM_SZ_256];
char esc_op[CBM_SZ_512];
cbm_json_escape(esc_c, sizeof(esc_c), call->callee_name);
cbm_json_escape(esc_op, sizeof(esc_op), p);
cbm_json_escape(esc_op, sizeof(esc_op), route_name);
char props[CBM_SZ_1K];
snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"operation\":\"%s\",\"confidence\":%.2f}",
esc_c, esc_op, res->confidence);
snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"operation\":\"%s\",\"operation_type\":\"%s\","
"\"confidence\":%.2f}",
esc_c, esc_op, op_type, res->confidence);
cbm_gbuf_insert_edge(gbuf, source->id, route_id, "GRAPHQL_CALLS", props);
}
@@ -2526,7 +2591,7 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const cbm_resolution_t *res, const char *module_qn,
const cbm_registry_t *registry, const cbm_gbuf_t *main_gbuf,
const char **imp_keys, const char **imp_vals, int imp_count,
bool suppress_plain_calls) {
bool suppress_plain_calls, const char *route_mount) {
cbm_svc_kind_t svc = cbm_service_pattern_match(res->qualified_name);
const char *arg = call->first_string_arg;
@@ -2553,7 +2618,8 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const char *route_path = find_route_path_in_args(call, &handler_ref);
if (route_path) {
emit_route_registration(gbuf, source, call, route_path, handler_ref, module_qn,
registry, main_gbuf, imp_keys, imp_vals, imp_count);
registry, main_gbuf, imp_keys, imp_vals, imp_count,
route_mount);
return;
}
/* No path found — fall through to normal CALLS edge */
@@ -2561,9 +2627,13 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
bool has_url = (arg && arg[0] != '\0' && (arg[0] == '/' || strstr(arg, "://") != NULL));
bool has_topic = (arg && arg[0] != '\0' && svc == CBM_SVC_ASYNC && strlen(arg) > PP_ESC_SPACE);
/* Set when this call already has its HTTP_CALLS edge from the service
* patterns (typed with the verb its callee names). */
bool http_edge_emitted = false;
if ((svc == CBM_SVC_HTTP || svc == CBM_SVC_ASYNC) && (has_url || has_topic)) {
emit_http_async_service_edge(gbuf, source, call, res, svc, arg);
http_edge_emitted = svc == CBM_SVC_HTTP;
} else if (svc == CBM_SVC_GRPC) {
emit_grpc_edge(gbuf, source, call, res);
} else if (svc == CBM_SVC_GRAPHQL) {
@@ -2576,7 +2646,43 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
emit_normal_calls_edge(gbuf, source, target, call, res);
}
detect_url_in_args(gbuf, source, call);
/* The arg-URL heuristic is for calls no service pattern knows (a local
* fetch wrapper). On a classified HTTP call it only minted a method-less
* __route__ANY__ twin of the typed edge, which cross-repo matching then
* bound to server handlers of any method. */
if (!http_edge_emitted) {
detect_url_in_args(gbuf, source, call);
}
}
/* The #725 guard refuses a suffix_match binding across a language boundary,
* which leaves the callee unresolved. An unresolved callee the route
* classifier recognises is still a registration: `Route::get('/x', ...)`
* beside a JS `get`, `app.get('/x', h)` beside a Python `get`. Emit exactly
* the Route + CALLS + HANDLES that the unresolved-callee (callee_suffix)
* fallback in resolve_file_calls emits for it, classified by callee name the
* same way emit_service_edge classifies that fallback, and nothing else: no
* CALLS edge to the refused target and no URL-argument scan. Dropping the
* whole call lost every GET registration in a mixed-language repo while POST
* (no `post` to collide with) survived. Mirrors pass_calls.c. */
static void emit_xlang_refused_route(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const CBMCall *call, const char *module_qn,
const cbm_registry_t *registry, const cbm_gbuf_t *main_gbuf,
const char **imp_keys, const char **imp_vals, int imp_count,
const char *route_mount) {
if (cbm_service_pattern_route_method(call->callee_name) == NULL) {
return;
}
cbm_svc_kind_t svc = cbm_service_pattern_match(call->callee_name);
if (svc != CBM_SVC_NONE && svc != CBM_SVC_ROUTE_REG) {
return;
}
const char *handler_ref = NULL;
const char *route_path = find_route_path_in_args(call, &handler_ref);
if (route_path) {
emit_route_registration(gbuf, source, call, route_path, handler_ref, module_qn, registry,
main_gbuf, imp_keys, imp_vals, imp_count, route_mount);
}
}
/* Find the source node for an edge: enclosing function or file node. */
@@ -2827,6 +2933,10 @@ static const CBMResolvedCall *lsp_idx_lookup(const CBMHashTable *index, const CB
static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CBMFileResult *result,
const char *rel, const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count, CBMLanguage lang) {
/* Framework mount of this file's routes (Laravel 11+ withRouting, #1146). */
char route_mount[CBM_SZ_128];
cbm_laravel_file_route_mount(rc->repo_path, rel, lang, result, route_mount,
sizeof(route_mount));
/* Two occurrence-aware indexes preserve the authoritative matcher's
* primary ordering without restoring its O(calls × resolutions) scan:
* exact caller+leaf+span first, then the legacy caller+leaf fallback.
@@ -3025,7 +3135,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
/* Dynamic-language weak-member suppression (#592/#606/#1276). The
* receiver-aware guard must NOT drop this call here: doing so would also
* skip the #523 callee-name service bypass below, emit_service_edge's
* route/gRPC/config branches, and its unconditional detect_url_in_args
* route/gRPC/config branches, and its detect_url_in_args
* (which classifies verb-suffix HTTP clients like api.patch('/x')).
* Instead, defer to the emit path and suppress ONLY the plain-CALLS
* fall-through (emit_normal_calls_edge), so every service edge stays
@@ -3052,7 +3162,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
@@ -3089,7 +3206,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
.strategy = "service_pattern"};
emit_service_edge(ws->local_edge_buf, source_node, source_node, call, &svc_res,
module_qn, rc->registry, rc->main_gbuf, imp_keys, imp_vals,
imp_count, false);
imp_count, false, route_mount);
continue;
}
}
@@ -3106,7 +3223,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
* 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, rust_external);
imp_count, rust_external, route_mount);
} 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
@@ -3140,7 +3257,10 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
if (target_node && source_node->id != target_node->id &&
cbm_suppress_cross_language_suffix_match(lang, target_node->file_path, res.strategy)) {
/* #725: same guard as pass_calls.c — do not emit a suffix_match
* CALLS edge across a language boundary. */
* CALLS edge across a language boundary. A route registration
* behind the refused binding still gets its Route. */
emit_xlang_refused_route(ws->local_edge_buf, source_node, call, module_qn, rc->registry,
rc->main_gbuf, imp_keys, imp_vals, imp_count, route_mount);
continue;
}
if (!target_node || source_node->id == target_node->id) {
@@ -3158,7 +3278,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
if (url_or_topic) {
emit_service_edge(ws->local_edge_buf, source_node, NULL, call, &res, module_qn,
rc->registry, rc->main_gbuf, imp_keys, imp_vals, imp_count,
false);
false, route_mount);
ws->calls_resolved++;
}
}
@@ -3167,7 +3287,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
_rc_t0 = extract_now_ns();
emit_service_edge(ws->local_edge_buf, source_node, target_node, call, &res, module_qn,
rc->registry, rc->main_gbuf, imp_keys, imp_vals, imp_count,
drop_plain_call);
drop_plain_call, route_mount);
atomic_fetch_add_explicit(&rc->time_ns_rc_emit, extract_now_ns() - _rc_t0,
memory_order_relaxed);
ws->calls_resolved++;
+346 -10
View File
@@ -440,9 +440,12 @@ static void parse_pyproject_toml(const char *source, int source_len, const char
}
}
/* Extract PSR-4 autoload entries from composer.json root. */
static void extract_psr4(yyjson_val *root, const char *dir, cbm_pkg_entries_t *entries) {
yyjson_val *autoload = yyjson_obj_get(root, "autoload");
/* Extract PSR-4 entries from one composer.json autoload section ("autoload"
* or "autoload-dev": composer registers both, so test namespaces such as
* Tests\ map to their directory as well). */
static void extract_psr4(yyjson_val *root, const char *section, const char *dir,
cbm_pkg_entries_t *entries) {
yyjson_val *autoload = yyjson_obj_get(root, section);
if (!yyjson_is_obj(autoload)) {
return;
}
@@ -459,6 +462,12 @@ static void extract_psr4(yyjson_val *root, const char *dir, cbm_pkg_entries_t *e
}
const char *ns_prefix = yyjson_get_str(key);
const char *ns_dir = yyjson_get_str(val);
while (ns_dir[0] == '.' && ns_dir[SKIP_ONE] == '/') {
ns_dir += PAIR_LEN; /* "./src/" names src/ */
}
if (strcmp(ns_dir, ".") == 0) {
ns_dir = ""; /* "." names the manifest's own directory */
}
char ns_entry[PKGMAP_PATH_BUF];
if (dir[0]) {
snprintf(ns_entry, sizeof(ns_entry), "%s/%s", dir, ns_dir);
@@ -497,7 +506,8 @@ static void parse_composer_json(const char *source, int source_len, const char *
}
}
extract_psr4(root, dir, entries);
extract_psr4(root, "autoload", dir, entries);
extract_psr4(root, "autoload-dev", dir, entries);
free(dir);
yyjson_doc_free(doc);
@@ -987,6 +997,12 @@ bool cbm_pkgmap_try_parse(const char *basename, const char *rel_path, const char
/* ── Merge: per-worker entries → hash table ────────────────────── */
/* A composer.json `autoload.psr-4` key: a namespace prefix ending in '\\'. */
static bool pkgmap_is_psr4_prefix(const char *pkg_name) {
size_t n = pkg_name ? strlen(pkg_name) : 0;
return n > 0 && pkg_name[n - SKIP_ONE] == '\\';
}
CBMHashTable *cbm_pkgmap_build(cbm_pkg_entries_t *worker_entries, int worker_count,
const char *project_name) {
/* Count total entries */
@@ -1004,8 +1020,14 @@ CBMHashTable *cbm_pkgmap_build(cbm_pkg_entries_t *worker_entries, int worker_cou
for (int w = 0; w < worker_count; w++) {
cbm_pkg_entries_t *we = &worker_entries[w];
for (int i = 0; i < we->count; i++) {
/* Convert entry_rel to QN: project.dir.parts */
char *qn = cbm_pipeline_fqn_module(project_name, we->items[i].entry_rel);
/* Convert entry_rel to QN: project.dir.parts. A PSR-4 namespace
* prefix (key ends in '\\') keeps its repo-relative DIRECTORY
* instead: its readers map `Prefix\Sub\Class` onto a file path
* (<dir>/Sub/Class.php), which a dotted QN cannot express (#1186). */
const char *entry_rel = we->items[i].entry_rel;
char *qn = pkgmap_is_psr4_prefix(we->items[i].pkg_name)
? cbm_strndup(entry_rel, strlen(entry_rel))
: cbm_pipeline_fqn_module(project_name, entry_rel);
if (!qn) {
continue;
}
@@ -1355,7 +1377,8 @@ static char *resolve_dot_prefix(CBMHashTable *map, const char *module_path,
}
/* Try backslash-based prefix matching (PHP PSR-4: App\\Controllers\\Foo).
* Returns heap QN or NULL. */
* The map value of a PSR-4 prefix is its repo-relative directory (see
* cbm_pkgmap_build). Returns heap QN or NULL. */
static char *resolve_backslash_prefix(CBMHashTable *map, const char *module_path,
const char *project_name) {
char *buf = strdup(module_path);
@@ -1375,7 +1398,8 @@ static char *resolve_backslash_prefix(CBMHashTable *map, const char *module_path
}
const char *subpath = module_path + (size_t)(bs - buf) + SKIP_ONE;
char path_result[PKGMAP_PATH_BUF];
snprintf(path_result, sizeof(path_result), "%s/%s", base_dir, subpath);
snprintf(path_result, sizeof(path_result), "%s%s%s", base_dir, base_dir[0] ? "/" : "",
subpath);
for (char *c = path_result; *c; c++) {
if (*c == '\\') {
*c = '/';
@@ -1543,6 +1567,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
@@ -1818,6 +2049,91 @@ static const cbm_gbuf_node_t *resolve_sibling_file(const cbm_pipeline_ctx_t *ctx
return found;
}
/* ── PHP PSR-4 class imports (#1186) ──────────────────────────────── */
typedef enum {
PSR4_NOT_APPLICABLE = 0, /* no composer psr-4 prefix covers the import */
PSR4_RESOLVED, /* the class file exists: *out is its File node */
PSR4_UNRESOLVED, /* a prefix covers it but no class file exists */
} psr4_outcome_t;
/* The File node at exactly `rel_path`, or NULL. Looked up through the name
* index (File nodes are named by basename) and matched on the full path, so
* a same-named file in another directory never qualifies. */
static const cbm_gbuf_node_t *psr4_file_node(const cbm_pipeline_ctx_t *ctx, const char *rel_path) {
const cbm_gbuf_node_t **hits = NULL;
int hit_count = 0;
if (cbm_gbuf_find_by_name(ctx->gbuf, path_leaf(rel_path), &hits, &hit_count) != 0 || !hits) {
return NULL;
}
for (int i = 0; i < hit_count; i++) {
const cbm_gbuf_node_t *n = hits[i];
if (n && n->label && strcmp(n->label, "File") == 0 && n->file_path &&
strcmp(n->file_path, rel_path) == 0) {
return n;
}
}
return NULL;
}
/* Resolve a PHP class import `use A\B\C;` the way composer's PSR-4 autoloader
* does: for every autoload.psr-4 prefix covering the name, longest first, the
* class lives in exactly <prefix-dir>/<rest>.php with sub-namespaces as
* subdirectories; the first existing file wins. When a prefix covers the name
* but no such file exists the import is UNRESOLVED: it must never fall through
* to the namespace bucket, which binds it to whichever file of the namespace
* came first. `use function` / `use const` name namespace members, not class
* files, so they are not applicable. */
static psr4_outcome_t resolve_php_psr4_class(const cbm_pipeline_ctx_t *ctx,
const char *source_file_qn, const CBMImport *imp,
const cbm_gbuf_node_t **out) {
*out = NULL;
CBMHashTable *pkgmap = cbm_pipeline_get_pkgmap();
if (!pkgmap || imp->kind != CBM_IMPORT_KIND_DEFAULT) {
return PSR4_NOT_APPLICABLE;
}
const char *name = imp->module_path;
if (name[0] == '\\') {
name++; /* fully qualified `use \App\X;` */
}
char key[PKGMAP_PATH_BUF];
size_t name_len = strlen(name);
if (name_len == 0 || name_len >= sizeof(key) || !strchr(name, '\\')) {
return PSR4_NOT_APPLICABLE;
}
bool covered = false;
/* Right to left: each '\' ends a candidate prefix, longest first. */
for (size_t cut = name_len - SKIP_ONE; cut > 0; cut--) {
if (name[cut - SKIP_ONE] != '\\') {
continue;
}
memcpy(key, name, cut);
key[cut] = '\0';
const char *dir = (const char *)cbm_ht_get(pkgmap, key);
if (!dir) {
continue;
}
covered = true;
char rel[PKGMAP_PATH_BUF];
int w = snprintf(rel, sizeof(rel), "%s%s%s.php", dir, dir[0] ? "/" : "", name + cut);
if (w <= 0 || (size_t)w >= sizeof(rel)) {
continue;
}
for (char *c = rel; *c; c++) {
if (*c == '\\') {
*c = '/';
}
}
const cbm_gbuf_node_t *file = psr4_file_node(ctx, rel);
if (file && (!source_file_qn || !file->qualified_name ||
strcmp(file->qualified_name, source_file_qn) != 0)) {
*out = file;
return PSR4_RESOLVED;
}
}
return covered ? PSR4_UNRESOLVED : PSR4_NOT_APPLICABLE;
}
const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_t *ctx,
const char *source_rel,
const char *source_file_qn,
@@ -1835,6 +2151,18 @@ const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_t
return header_target;
}
/* PHP class imports covered by a composer psr-4 prefix name exactly one
* file; when it is absent the import stays unresolved (#1186). */
const cbm_gbuf_node_t *psr4_target = NULL;
switch (resolve_php_psr4_class(ctx, source_file_qn, imp, &psr4_target)) {
case PSR4_RESOLVED:
return psr4_target;
case PSR4_UNRESOLVED:
return NULL;
case PSR4_NOT_APPLICABLE:
break;
}
/* Strategy 1: module-path resolution → existing node (Python/TS/Go).
* No label filter here: directory-module languages (Go/Java packages)
* legitimately resolve straight to a Folder node -- that's the intended,
@@ -1882,8 +2210,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 +2361,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 +2387,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;
+9 -1
View File
@@ -23,6 +23,7 @@
#include "foundation/compat_fs.h"
#include "foundation/limits.h"
#include "cbm.h"
#include "callable_sig.h"
#include <stdio.h>
#include <stdlib.h>
@@ -356,7 +357,14 @@ static void go_index_add(go_method_index_t *ix, const char *name, int type_index
static void go_index_visit_node(const cbm_gbuf_node_t *node, void *userdata) {
go_method_index_t *ix = userdata;
const char *qn = node->qualified_name;
const char *dot = qn ? strrchr(qn, '.') : NULL;
/* Last '.' of the base QN (a callable identity suffix never holds one). */
const char *dot = NULL;
size_t base_len = cbm_qn_callable_base_len_named(qn, node->name);
for (size_t i = 0; qn && i < base_len; i++) {
if (qn[i] == '.') {
dot = qn + i;
}
}
if (!dot || dot == qn || !dot[SKIP_ONE]) {
return;
}
+9
View File
@@ -433,6 +433,15 @@ static void find_alias_files(const char *abs_dir, const char *rel_dir, alias_con
if (cbm_pipeline_relpath_is_excluded(child_rel, excluded_dirs, excluded_count)) {
continue;
}
/* A link is not followed, as discovery does not follow one. is_dir is
* also true for a junction or a directory symbolic link on Windows,
* and either can lead out of the repository. A child whose metadata
* cannot be read is skipped the same way. */
cbm_path_info_t child_info;
if (cbm_path_info_utf8(child_abs, &child_info) != CBM_PATH_INFO_OK ||
child_info.is_symlink) {
continue;
}
find_alias_files(child_abs, child_rel, out, count, max_count, depth + 1, excluded_dirs,
excluded_count);
}
+13 -6
View File
@@ -1156,7 +1156,8 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c
(size_t)r->string_refs.count * sizeof(CBMStringRef) +
(size_t)r->impl_traits.count * sizeof(CBMImplTrait) +
(size_t)r->infra_bindings.count * sizeof(CBMInfraBinding) +
(size_t)r->channels.count * sizeof(CBMChannel);
(size_t)r->channels.count * sizeof(CBMChannel) +
(size_t)r->field_types.count * sizeof(CBMFieldType);
cap_other += (size_t)r->imports.cap * sizeof(CBMImport) +
(size_t)r->resolved_calls.cap * sizeof(CBMResolvedCall) +
(size_t)r->throws.cap * sizeof(CBMThrow) +
@@ -1165,7 +1166,8 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c
(size_t)r->string_refs.cap * sizeof(CBMStringRef) +
(size_t)r->impl_traits.cap * sizeof(CBMImplTrait) +
(size_t)r->infra_bindings.cap * sizeof(CBMInfraBinding) +
(size_t)r->channels.cap * sizeof(CBMChannel);
(size_t)r->channels.cap * sizeof(CBMChannel) +
(size_t)r->field_types.cap * sizeof(CBMFieldType);
n_defs += (size_t)r->defs.count;
n_calls += (size_t)r->calls.count;
n_usages += (size_t)r->usages.count;
@@ -2267,10 +2269,15 @@ int cbm_pipeline_publish_staged(char *stage_path, const cbm_pipeline_generation_
free(stage_path);
return CBM_PIPELINE_PERSIST_FAILED;
}
bool ok = cbm_store_exec(store, "PRAGMA synchronous=FULL;") == CBM_STORE_OK;
ok = ok && cbm_store_delete_file_hashes(store, generation->project) == CBM_STORE_OK &&
cbm_store_upsert_file_hash_batch(store, generation->manifest,
generation->manifest_count) == CBM_STORE_OK;
/* No synchronous=FULL for these writes (#1419): the stage is private until
* the atomic rename and a crash discards it, so an fsync per WAL commit
* protects nothing here. The store's NORMAL level is SQLite's
* corruption-safe setting under WAL, and cbm_store_seal_for_atomic_publish()
* raises this connection to FULL for the checkpoint that makes the
* published file durable. */
bool ok = cbm_store_delete_file_hashes(store, generation->project) == CBM_STORE_OK &&
cbm_store_upsert_file_hash_batch(store, generation->manifest,
generation->manifest_count) == CBM_STORE_OK;
/* LSP surfaces belong to the generation: written inside the same staging
* store, before the atomic rename, so graph and surface data can never
* publish separately. The delete guards the incremental path, whose
+10
View File
@@ -334,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
+24
View File
@@ -102,6 +102,25 @@ static const char *itoa_buf(int v) {
return buf[idx];
}
/* #1300: the purge of stale per-file nodes can run for a long time on a large
* persisted graph (reported: hundreds of files against ~268k stored hashes),
* and it logged nothing between incremental.edge_snapshot and
* incremental.purge — a stall there and a clean exit left no trace of where
* the run was. Progress is counts only: a ceiling stride keeps it to at most
* INCR_PURGE_PROGRESS_STEPS lines plus the final one, never one per file. */
enum { INCR_PURGE_PROGRESS_STEPS = 20 };
static void incr_purge_progress(int done, int total, struct timespec start) {
int stride = (total + INCR_PURGE_PROGRESS_STEPS - SKIP_ONE) / INCR_PURGE_PROGRESS_STEPS;
if (stride < SKIP_ONE) {
stride = SKIP_ONE;
}
if (done % stride == 0 || done == total) {
cbm_log_info("incremental.purge.progress", "files_done", itoa_buf(done), "files_total",
itoa_buf(total), "elapsed_ms", itoa_buf((int)elapsed_ms(start)));
}
}
static const char *incr_mode_name(int mode) {
switch (mode) {
case CBM_MODE_FULL:
@@ -2688,12 +2707,17 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
/* Step 2: Purge stale nodes */
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
int purge_total = ci + deleted_count;
cbm_log_info("incremental.purge.start", "changed", itoa_buf(ci), "deleted",
itoa_buf(deleted_count));
for (int i = 0; i < ci; i++) {
cbm_gbuf_delete_by_file(existing, changed_files[i].rel_path);
incr_purge_progress(i + SKIP_ONE, purge_total, t);
}
for (int i = 0; i < deleted_count; i++) {
cbm_gbuf_delete_by_file(existing, deleted[i]);
free(deleted[i]);
incr_purge_progress(ci + i + SKIP_ONE, purge_total, t);
}
free(deleted);
cbm_log_info("incremental.purge", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
+17
View File
@@ -300,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);
+30 -4
View File
@@ -30,6 +30,7 @@ enum { REG_MAX_CANDIDATES = 256 };
#include "foundation/hash_table.h"
#include "foundation/dyn_array.h"
#include "foundation/platform.h"
#include "callable_sig.h" /* cbm_qn_callable_base_len_named: overloads share the name key */
#include <math.h>
#include <stdio.h>
@@ -695,6 +696,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;
@@ -943,15 +960,24 @@ void cbm_registry_add(cbm_registry_t *r, const char *name, const char *qualified
* their dotted form would only widen the bucket the scorer walks.
*
* `name` is NULL or empty only for callers that have no symbol name to
* give; those have the derived key and nothing else. */
* give; those have the derived key and nothing else.
*
* A signature-qualified callable (#2061) is indexed by its bare `name` in
* place of the derived key, so every overload shares one bucket; any other
* QN keeps its historical last-segment key. */
const char *derived = simple_name(qualified_name);
index_under_name(r, derived, owned_qn);
const char *primary =
name && cbm_qn_callable_base_len_named(owned_qn, name) < strlen(owned_qn) ? name : derived;
index_under_name(r, primary, owned_qn);
/* '#' is a QN fence, and extract_defs.c's rust_cfg_qualified_name is the
* only thing in the tree that mints one today. A grammar that starts
* minting a '#' opts into this second key by doing so, whatever it means by
* the fence: its symbols become reachable under the passed name as well,
* and they share that name's bucket with everything else filed under it. */
if (name && name[0] && strchr(derived, '#') && strcmp(name, derived) != 0) {
* and they share that name's bucket with everything else filed under it.
* The passed name is compared with the key already written: a
* signature-qualified callable is filed under `name` already, and its
* capped suffix may carry a '#' of its own. */
if (name && name[0] && strchr(derived, '#') && strcmp(name, primary) != 0) {
index_under_name(r, name, owned_qn);
}
}
+232 -44
View File
@@ -78,6 +78,8 @@ enum {
#include "foundation/compat.h"
#include "foundation/log.h"
#include "foundation/compat_regex.h"
#include "callable_sig.h" /* cbm_qn_callable_base_len: base-match tier */
#include "foundation/mem_core.h" /* cbm_alloc: pattern buffers */
#include "foundation/str_util.h"
#define XXH_INLINE_ALL
@@ -539,6 +541,16 @@ int64_t cbm_store_resolve_mmap_size(void) {
return (int64_t)parsed;
}
/* #1419: page cache for read-write on-disk connections, in SQLite's negative
* KiB form. sqlite_writer.c gives every index 64 KiB pages, so SQLite's
* default 2000 KiB holds only ~31 of them, while a delta's purge and patch
* dirty pages across the node and edge tables and all of their indexes. The
* transaction then spills dirty pages into the WAL and rewrites them over and
* over (5.2 GiB of WAL writes for a one-line change on a 294 MB django index).
* 64 MiB = 1024 pages, the budget bulk mode already used; the cache only grows
* as pages are touched. Query connections keep the default. */
static const char ST_WRITE_CACHE_SQL[] = "PRAGMA cache_size = -65536;";
/* Configure connection pragmas.
* in_memory — :memory: DB (synchronous OFF, no journal file).
* read_only — query-only connection opened SQLITE_OPEN_READONLY. Runs
@@ -594,8 +606,9 @@ static int configure_pragmas(cbm_store_t *s, bool in_memory, bool read_only) {
* cbm_store_checkpoint's SIGBUS note), so without a size limit the -wal
* file only ever grows; journal_size_limit truncates it back to N bytes
* on the next successful
* reset. N is far above the healthy WAL (~4 MiB under the default
* 1000-page autocheckpoint), so normal indexing never triggers
* reset. N is far above the healthy WAL (~64 MiB: the default
* 1000-page autocheckpoint at the 64 KiB page size sqlite_writer.c
* gives every index), so normal indexing never triggers
* truncate/regrow churn — it only fires after abnormal growth.
* Shared/live paths do NOT use a TRUNCATE checkpoint: truncating the WAL
* to zero can raise SIGBUS in a sibling process that has the DB mmap'd
@@ -604,6 +617,10 @@ static int configure_pragmas(cbm_store_t *s, bool in_memory, bool read_only) {
if (rc != CBM_STORE_OK) {
return rc;
}
rc = exec_sql(s, ST_WRITE_CACHE_SQL);
if (rc != CBM_STORE_OK) {
return rc;
}
char mmap_sql[ST_BUF_64];
snprintf(mmap_sql, sizeof(mmap_sql), "PRAGMA mmap_size = %lld;",
(long long)cbm_store_resolve_mmap_size());
@@ -719,9 +736,12 @@ static void sqlite_regexp(sqlite3_context *ctx, int argc, sqlite3_value **argv)
sqlite3_result_error_nomem(ctx);
return;
}
if (cbm_regcomp(re, pattern, CBM_REG_EXTENDED | CBM_REG_NOSUB) != 0) {
int rc = cbm_regcomp(re, pattern, CBM_REG_EXTENDED | CBM_REG_NOSUB);
if (rc != 0) {
free(re);
sqlite3_result_error(ctx, "invalid regex", CBM_NOT_FOUND);
sqlite3_result_error(ctx,
rc == CBM_REG_ETOOBIG ? CBM_REG_ETOOBIG_REASON : "invalid regex",
CBM_NOT_FOUND);
return;
}
sqlite3_set_auxdata(ctx, 0, re, regex_free_cb);
@@ -747,9 +767,12 @@ static void sqlite_iregexp(sqlite3_context *ctx, int argc, sqlite3_value **argv)
sqlite3_result_error_nomem(ctx);
return;
}
if (cbm_regcomp(re, pattern, CBM_REG_EXTENDED | CBM_REG_NOSUB | CBM_REG_ICASE) != 0) {
int rc = cbm_regcomp(re, pattern, CBM_REG_EXTENDED | CBM_REG_NOSUB | CBM_REG_ICASE);
if (rc != 0) {
free(re);
sqlite3_result_error(ctx, "invalid regex", CBM_NOT_FOUND);
sqlite3_result_error(ctx,
rc == CBM_REG_ETOOBIG ? CBM_REG_ETOOBIG_REASON : "invalid regex",
CBM_NOT_FOUND);
return;
}
sqlite3_set_auxdata(ctx, 0, re, regex_free_cb);
@@ -1811,12 +1834,12 @@ int cbm_store_begin_bulk(cbm_store_t *s) {
* because the in-memory rollback journal is lost on crash.
* WAL mode is crash-safe: uncommitted WAL entries are simply discarded
* on the next open. Performance is preserved via synchronous=OFF and a
* larger cache, which are safe with WAL. */
* 64 MiB cache, which are safe with WAL. */
int rc = exec_sql(s, "PRAGMA synchronous = OFF;");
if (rc != CBM_STORE_OK) {
return rc;
}
return exec_sql(s, "PRAGMA cache_size = -65536;"); /* CBM_SZ_64 MB */
return exec_sql(s, ST_WRITE_CACHE_SQL);
}
int cbm_store_end_bulk(cbm_store_t *s) {
@@ -1824,7 +1847,8 @@ int cbm_store_end_bulk(cbm_store_t *s) {
if (rc != CBM_STORE_OK) {
return rc;
}
return exec_sql(s, "PRAGMA cache_size = -2000;"); /* default ~2 MB */
/* Back to the read-write cache, not SQLite's 2000 KiB default (#1419). */
return exec_sql(s, ST_WRITE_CACHE_SQL);
}
int cbm_store_drop_indexes(cbm_store_t *s) {
@@ -4389,47 +4413,22 @@ int cbm_store_find_nodes_by_file_overlap(cbm_store_t *s, const char *project, co
/* ── FindNodesByQNSuffix ───────────────────────────────────────── */
int cbm_store_find_nodes_by_qn_suffix(cbm_store_t *s, const char *project, const char *suffix,
cbm_node_t **out, int *count) {
*out = NULL;
*count = 0;
if (!s || !s->db) {
return CBM_STORE_ERR;
}
/* Match QNs ending with ".suffix" or exactly equal to suffix */
char like_pattern[CBM_SZ_512];
snprintf(like_pattern, sizeof(like_pattern), "%%.%s", suffix);
const char *sql_with_project =
"SELECT id, project, label, name, qualified_name, file_path, "
"start_line, end_line, properties FROM nodes "
"WHERE project = ?1 AND (qualified_name LIKE ?2 OR qualified_name = ?3)";
const char *sql_any = "SELECT id, project, label, name, qualified_name, file_path, "
"start_line, end_line, properties FROM nodes "
"WHERE (qualified_name LIKE ?1 OR qualified_name = ?2)";
sqlite3_stmt *stmt = NULL;
int rc =
sqlite3_prepare_v2(s->db, project ? sql_with_project : sql_any, CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "qn_suffix prepare");
return CBM_STORE_ERR;
}
if (project) {
bind_text(stmt, SKIP_ONE, project);
bind_text(stmt, ST_COL_2, like_pattern);
bind_text(stmt, ST_COL_3, suffix);
} else {
bind_text(stmt, SKIP_ONE, like_pattern);
bind_text(stmt, ST_COL_2, suffix);
}
/* Row filter on the raw qualified_name + name columns (NULL keeps every row). */
typedef bool (*store_qn_keep_fn)(const char *qn, const char *name, const void *arg);
/* Step `stmt` (columns as scan_node reads them) into a node array, keeping the
* rows `keep` accepts. Finalizes `stmt`. */
static int store_collect_nodes(cbm_store_t *s, sqlite3_stmt *stmt, store_qn_keep_fn keep,
const void *keep_arg, cbm_node_t **out, int *count) {
int cap = ST_INIT_CAP_8;
int n = 0;
cbm_node_t *nodes = malloc(cap * sizeof(cbm_node_t));
int scan_rc8;
while ((scan_rc8 = sqlite3_step(stmt)) == SQLITE_ROW) {
if (keep && !keep((const char *)sqlite3_column_text(stmt, CBM_SZ_4),
(const char *)sqlite3_column_text(stmt, CBM_SZ_3), keep_arg)) {
continue;
}
if (n >= cap) {
cap *= ST_GROWTH;
nodes = safe_realloc(nodes, cap * sizeof(cbm_node_t));
@@ -4452,6 +4451,195 @@ int cbm_store_find_nodes_by_qn_suffix(cbm_store_t *s, const char *project, const
return CBM_STORE_OK;
}
/* "%." + text + tail with LIKE's wildcards ('%', '_') and the escape
* character escaped, for `LIKE ? ESCAPE '\'`. Heap-owned. The caller's text
* is matched literally at any length: a fixed 512-byte buffer used to
* truncate a long suffix into a pattern that matched nothing, and an
* unescaped '_' in `my_func` also matched `myXfunc`. */
static char *store_like_dot_suffix(const char *text, const char *tail) {
size_t n = strlen(text);
size_t tail_len = strlen(tail);
char *pat = cbm_alloc(CBM_MEM_CLASS_STORE, (2 * n) + tail_len + ST_COL_3); /* "%." + NUL */
if (!pat) {
return NULL;
}
size_t k = 0;
pat[k++] = '%';
pat[k++] = '.';
for (size_t i = 0; i < n; i++) {
if (text[i] == '%' || text[i] == '_' || text[i] == '\\') {
pat[k++] = '\\';
}
pat[k++] = text[i];
}
memcpy(pat + k, tail, tail_len + SKIP_ONE);
return pat;
}
int cbm_store_find_nodes_by_qn_suffix(cbm_store_t *s, const char *project, const char *suffix,
cbm_node_t **out, int *count) {
*out = NULL;
*count = 0;
if (!s || !s->db || !suffix) {
return CBM_STORE_ERR;
}
/* Match QNs ending with ".suffix" or exactly equal to suffix */
char *like_pattern = store_like_dot_suffix(suffix, "");
if (!like_pattern) {
return CBM_STORE_ERR;
}
const char *sql_with_project =
"SELECT id, project, label, name, qualified_name, file_path, "
"start_line, end_line, properties FROM nodes "
"WHERE project = ?1 AND (qualified_name LIKE ?2 ESCAPE '\\' OR qualified_name = ?3)";
const char *sql_any = "SELECT id, project, label, name, qualified_name, file_path, "
"start_line, end_line, properties FROM nodes "
"WHERE (qualified_name LIKE ?1 ESCAPE '\\' OR qualified_name = ?2)";
sqlite3_stmt *stmt = NULL;
int rc =
sqlite3_prepare_v2(s->db, project ? sql_with_project : sql_any, CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
cbm_free(CBM_MEM_CLASS_STORE, like_pattern);
store_set_error_sqlite(s, "qn_suffix prepare");
return CBM_STORE_ERR;
}
if (project) {
bind_text(stmt, SKIP_ONE, project);
bind_text(stmt, ST_COL_2, like_pattern);
bind_text(stmt, ST_COL_3, suffix);
} else {
bind_text(stmt, SKIP_ONE, like_pattern);
bind_text(stmt, ST_COL_2, suffix);
}
rc = store_collect_nodes(s, stmt, NULL, NULL, out, count);
cbm_free(CBM_MEM_CLASS_STORE, like_pattern);
return rc;
}
/* ── FindNodesByQNBase ─────────────────────────────────────────── */
typedef struct {
const char *base;
size_t len;
bool suffix;
} store_qn_base_arg_t;
/* ASCII case-insensitive equality: SQLite's LIKE folds exactly ASCII. */
static bool store_ascii_ieq(const char *a, const char *b, size_t n) {
for (size_t i = 0; i < n; i++) {
unsigned char x = (unsigned char)a[i];
unsigned char y = (unsigned char)b[i];
if (x >= 'A' && x <= 'Z') {
x = (unsigned char)(x - 'A' + 'a');
}
if (y >= 'A' && y <= 'Z') {
y = (unsigned char)(y - 'A' + 'a');
}
if (x != y) {
return false;
}
}
return true;
}
/* Keep a row whose QN carries a callable identity suffix (#2061) over `base`:
* its base QN equals `base` (exact) or ends with "." + `base` (suffix mode,
* ASCII case-insensitive like the LIKE suffix tier). An unsuffixed QN never
* qualifies, so this tier finds nothing until a language mints suffixes. */
static bool store_qn_base_keep(const char *qn, const char *name, const void *argp) {
const store_qn_base_arg_t *arg = argp;
if (!qn || !name) {
return false;
}
size_t base_len = cbm_qn_callable_base_len_named(qn, name);
if (qn[base_len] == '\0') {
return false;
}
if (!arg->suffix) {
return base_len == arg->len && memcmp(qn, arg->base, arg->len) == 0;
}
return base_len > arg->len && qn[base_len - arg->len - SKIP_ONE] == '.' &&
store_ascii_ieq(qn + base_len - arg->len, arg->base, arg->len);
}
/* Exact mode reads the qualified_name index range [base "(", base "="): a
* suffix starts with '(' (0x28) or '<' (0x3C). Suffix mode needs the leading
* wildcard, like the suffix tier it follows. Both bounds are heap-owned. */
static bool store_qn_base_bounds(const char *base, bool suffix_match, char **lo, char **hi) {
if (suffix_match) {
*lo = store_like_dot_suffix(base, "(%");
*hi = store_like_dot_suffix(base, "<%");
} else {
size_t n = strlen(base);
*lo = cbm_alloc(CBM_MEM_CLASS_STORE, n + ST_COL_2);
*hi = cbm_alloc(CBM_MEM_CLASS_STORE, n + ST_COL_2);
if (*lo && *hi) {
memcpy(*lo, base, n);
memcpy(*hi, base, n);
(*lo)[n] = '(';
(*hi)[n] = '=';
(*lo)[n + SKIP_ONE] = '\0';
(*hi)[n + SKIP_ONE] = '\0';
}
}
if (*lo && *hi) {
return true;
}
cbm_free(CBM_MEM_CLASS_STORE, *lo);
cbm_free(CBM_MEM_CLASS_STORE, *hi);
return false;
}
int cbm_store_find_nodes_by_qn_base(cbm_store_t *s, const char *project, const char *base,
bool suffix_match, cbm_node_t **out, int *count) {
*out = NULL;
*count = 0;
if (!s || !s->db || !base || !base[0]) {
return CBM_STORE_ERR;
}
static const char *const sql[2][2] = {
/* [suffix_match][has project] */
{"SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, "
"properties FROM nodes WHERE qualified_name >= ?1 AND qualified_name < ?2",
"SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, "
"properties FROM nodes WHERE project = ?1 AND qualified_name >= ?2 AND "
"qualified_name < ?3"},
{"SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, "
"properties FROM nodes WHERE (qualified_name LIKE ?1 ESCAPE '\\' OR "
"qualified_name LIKE ?2 ESCAPE '\\')",
"SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, "
"properties FROM nodes WHERE project = ?1 AND (qualified_name LIKE ?2 ESCAPE '\\' OR "
"qualified_name LIKE ?3 ESCAPE '\\')"},
};
char *lo = NULL;
char *hi = NULL;
if (!store_qn_base_bounds(base, suffix_match, &lo, &hi)) {
return CBM_STORE_ERR;
}
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(s->db, sql[suffix_match ? 1 : 0][project ? 1 : 0], CBM_NOT_FOUND, &stmt,
NULL) != SQLITE_OK) {
cbm_free(CBM_MEM_CLASS_STORE, lo);
cbm_free(CBM_MEM_CLASS_STORE, hi);
store_set_error_sqlite(s, "qn_base prepare");
return CBM_STORE_ERR;
}
int col = SKIP_ONE;
if (project) {
bind_text(stmt, col++, project);
}
bind_text(stmt, col++, lo);
bind_text(stmt, col, hi);
store_qn_base_arg_t arg = {base, strlen(base), suffix_match};
int rc = store_collect_nodes(s, stmt, store_qn_base_keep, &arg, out, count);
cbm_free(CBM_MEM_CLASS_STORE, lo);
cbm_free(CBM_MEM_CLASS_STORE, hi);
return rc;
}
/* ── NodeDegree ────────────────────────────────────────────────── */
void cbm_store_node_degree(cbm_store_t *s, int64_t node_id, int *in_deg, int *out_deg) {
+10 -2
View File
@@ -105,6 +105,13 @@ int cbm_store_find_nodes_by_file_overlap(cbm_store_t *s, const char *project, co
int cbm_store_find_nodes_by_qn_suffix(cbm_store_t *s, const char *project, const char *suffix,
cbm_node_t **out, int *count);
/* Find callables whose signature-qualified QN (#2061) has `base` as its base
* QN (exact), or a base ending with "." + `base` (suffix_match). QNs without
* a callable identity suffix never match: this is the tier that lets a bare
* QN name every overload. */
int cbm_store_find_nodes_by_qn_base(cbm_store_t *s, const char *project, const char *base,
bool suffix_match, cbm_node_t **out, int *count);
/* Get CALLS degree of a node (inbound and outbound). */
void cbm_store_node_degree(cbm_store_t *s, int64_t node_id, int *in_deg, int *out_deg);
@@ -427,11 +434,12 @@ int cbm_store_rollback(cbm_store_t *s);
/* ── Bulk write optimization ────────────────────────────────────── */
/* Tune pragmas for bulk write throughput (synchronous=OFF, large cache).
/* Tune pragmas for bulk write throughput (synchronous=OFF, 64 MiB cache).
* WAL journal mode is preserved throughout for crash safety. */
int cbm_store_begin_bulk(cbm_store_t *s);
/* Restore normal pragmas (synchronous=NORMAL, default cache) after bulk writes. */
/* Restore normal pragmas (synchronous=NORMAL, the 64 MiB read-write cache)
* after bulk writes. */
int cbm_store_end_bulk(cbm_store_t *s);
/* Drop user indexes for faster bulk inserts. */
+124 -24
View File
@@ -2,7 +2,10 @@
* watcher.c — Git-based file change watcher.
*
* Strategy: git status + HEAD tracking (the most reliable approach).
* For non-git projects, the watcher skips polling (no fsnotify/dirmtime yet).
* Non-git projects are NOT polled by default. With the opt-in
* cbm_watcher_set_poll_non_git(w, true) (config key `watch_non_git`, #1948)
* they are polled with a tree signature instead: the indexer's own discovery
* walk (same ignore rules), folded over (relative path, size, mtime).
*
*
* Per-project state tracks:
@@ -32,6 +35,7 @@
#include "foundation/str_util.h"
#include "foundation/subprocess.h"
#include "pipeline/artifact.h" /* CBM_ARTIFACT_DIR: the indexer's own output directory */
#include "discover/discover.h" /* cbm_discover: the non-git tree signature (#1948) */
#ifdef _WIN32
#include "foundation/win_utf8.h"
#define WIN32_LEAN_AND_MEAN
@@ -61,7 +65,8 @@ typedef struct {
cbm_subprocess_t *active_git;
/* Room for Git's 64-hex SHA-256 object ID plus newline/NUL while reading. */
char last_head[CBM_SZ_128]; /* git HEAD hash (committed baseline) */
bool is_git; /* false → skip polling */
bool is_git; /* false → tree-polled if tree_poll, else skipped */
bool tree_poll; /* non-git root polled by tree signature (#1948) */
bool baseline_done; /* true after first poll */
int missing_root_count; /* consecutive polls where root was missing (ENOENT/ENOTDIR) */
uint64_t first_missing_ms; /* cbm_now_ms() of the streak's first miss (0 = no streak) */
@@ -73,8 +78,14 @@ typedef struct {
* are committed only after a SUCCESSFUL reindex (busy-skips and failed
* runs retry); check_changes stages its observations in the pending_*
* fields. 0 = clean tree. */
uint64_t last_dirty_sig; /* committed dirty-state signature */
uint64_t pending_dirty_sig; /* observed at check time */
uint64_t last_dirty_sig; /* committed dirty-state signature */
uint64_t pending_dirty_sig; /* observed at check time */
/* Non-git tree signature (#1948), same commit discipline as the dirty
* signature. 0 = unknown: the baseline never adopts the tree as already
* indexed, so the first poll reindexes once (at-least-once, like a tree
* that is already dirty at a git baseline). Signatures are never 0. */
uint64_t last_tree_sig;
uint64_t pending_tree_sig;
char pending_head[CBM_SZ_128]; /* HEAD observed at check time */
/* Consecutive hard index failures (index_fn < 0). A hard error is
* usually persistent — a poisoned coordination endpoint, an unreadable
@@ -106,6 +117,9 @@ struct cbm_watcher {
cbm_watcher_project_pruned_fn project_pruned;
void *mutation_context;
atomic_int stopped;
/* Opt-in (#1948): poll non-git roots by tree signature. Default false —
* non-git roots are not watched. Read at each project's baseline. */
atomic_bool poll_non_git;
/* Deferred-free list: freed after the next poll_once. */
project_state_t **pending_free;
int pending_free_count;
@@ -851,6 +865,46 @@ static watcher_git_status_t git_file_count(cbm_watcher_t *w, project_state_t *st
return WATCHER_GIT_OK;
}
/* ── Non-git tree signature (#1948) ─────────────────────────────── */
static int tree_entry_cmp(const void *a, const void *b) {
const cbm_file_info_t *fa = a;
const cbm_file_info_t *fb = b;
return strcmp(fa->rel_path, fb->rel_path);
}
/* Signature of a non-git tree: FNV-1a over every file the INDEXER would
* discover (cbm_discover, full mode — the same skip lists, .gitignore stack
* and .cbmignore), folding each (relative path, size, mtime) in path order so
* readdir order cannot change the value. Adding, deleting, renaming or editing
* an indexable file yields a new signature; touching anything discovery skips
* does not. That includes everything cbm writes itself: the .codebase-memory
* artifact directory is a built-in skip and the cache directory is pruned by
* absolute path, so a successful reindex can never look like a new change
* (the runaway history in init_baseline and #1953). Never returns 0 in
* *sig_out, which stays reserved for "unknown". */
static bool tree_signature(const char *root_path, uint64_t *sig_out, int *count_out) {
cbm_discover_opts_t opts = {.mode = CBM_MODE_FULL};
cbm_file_info_t *files = NULL;
int count = 0;
if (cbm_discover(root_path, &opts, &files, &count) != 0) {
return false;
}
if (count > 1) {
qsort(files, (size_t)count, sizeof(*files), tree_entry_cmp);
}
uint64_t h = SIG_FNV_OFFSET;
for (int i = 0; i < count; i++) {
h = sig_fold(h, files[i].rel_path, strlen(files[i].rel_path) + SKIP_ONE);
h = sig_fold(h, &files[i].size, sizeof(files[i].size));
h = sig_fold(h, &files[i].mtime_ns, sizeof(files[i].mtime_ns));
}
cbm_discover_free(files, count);
*sig_out = h ? h : 1;
*count_out = count;
return true;
}
/* ── Project state lifecycle ────────────────────────────────────── */
static void state_free(project_state_t *s);
@@ -1042,9 +1096,16 @@ cbm_watcher_t *cbm_watcher_new(cbm_store_t *store, cbm_index_fn index_fn, void *
cbm_mutex_init(&w->projects_lock);
cbm_mutex_init(&w->coordination_lock);
atomic_init(&w->stopped, 0);
atomic_init(&w->poll_non_git, false);
return w;
}
void cbm_watcher_set_poll_non_git(cbm_watcher_t *w, bool enabled) {
if (w) {
atomic_store_explicit(&w->poll_non_git, enabled, memory_order_release);
}
}
void cbm_watcher_free(cbm_watcher_t *w) {
if (!w) {
return;
@@ -1238,8 +1299,10 @@ static bool init_baseline(cbm_watcher_t *w, project_state_t *s) {
* A directory is only really git-managed here if it carries its own .git,
* or the ancestor repository actually tracks something inside it. A
* genuine sub-package of a monorepo passes the second test; a scratch or
* gitignored folder sitting under a repo fails both and is polled as a
* plain directory instead. */
* gitignored folder sitting under a repo fails both and is treated as a
* non-git root: NOT polled by default, or polled by its own tree signature
* when the watch_non_git opt-in is on (#1948). Either way the ancestor's
* dirty state never reaches it. */
if (s->is_git && !git_has_own_dot_git(s->root_path)) {
bool tracked = false;
watcher_git_status_t tracked_status = git_tracks_anything_here(w, s, &tracked);
@@ -1282,6 +1345,14 @@ static bool init_baseline(cbm_watcher_t *w, project_state_t *s) {
s->interval_ms = cbm_watcher_poll_interval_ms(s->file_count);
cbm_log_info("watcher.baseline", "project", s->project_name, "strategy", "git", "files",
s->file_count > 0 ? "yes" : "0");
} else if (atomic_load_explicit(&w->poll_non_git, memory_order_acquire)) {
/* #1948 opt-in. last_tree_sig stays 0 ("unknown"): nothing records
* which tree state the DB holds (edits made while the daemon was down
* are exactly the silent-staleness case), so the first poll reindexes
* once and the signature gates every poll after it. The interval is
* sized from the file count of each signature walk. */
s->tree_poll = true;
cbm_log_info("watcher.baseline", "project", s->project_name, "strategy", "tree");
} else {
cbm_log_info("watcher.baseline", "project", s->project_name, "strategy", "none");
}
@@ -1295,13 +1366,31 @@ static bool init_baseline(cbm_watcher_t *w, project_state_t *s) {
* poll_project commits them only after a SUCCESSFUL reindex so that
* busy-skips and failed runs retry instead of silently losing the change
* (#937). Observations are staged in the pending_* fields. */
/* Non-git leg of check_changes (#1948). A failed walk reports "no verdict"
* (false) so the committed baseline is kept and a later poll retries. */
static bool check_tree_changes(project_state_t *s, bool *changed_out) {
uint64_t sig = 0;
int file_count = 0;
if (!tree_signature(s->root_path, &sig, &file_count)) {
cbm_log_warn("watcher.tree_walk_failed", "project", s->project_name, "path", s->root_path);
/* Retry at the regular cadence, not on every run-loop tick. */
s->next_poll_ns = now_ns() + ((int64_t)s->interval_ms * US_PER_MS);
return false;
}
s->pending_tree_sig = sig;
s->file_count = file_count;
s->interval_ms = cbm_watcher_poll_interval_ms(file_count);
*changed_out = sig != s->last_tree_sig;
return true;
}
static bool check_changes(cbm_watcher_t *w, project_state_t *s, bool *changed_out) {
if (!changed_out) {
return false;
}
*changed_out = false;
if (!s->is_git) {
return true;
return s->tree_poll ? check_tree_changes(s, changed_out) : true;
}
bool changed = false;
@@ -1416,6 +1505,28 @@ static void prune_missing_project(cbm_watcher_t *w, project_state_t *s) {
free(root_path);
}
/* After a SUCCESSFUL reindex, commit the baselines OBSERVED AT CHECK TIME —
* the state whose reindex just succeeded. A commit/edit landing during the
* reindex is deliberately not absorbed: the next poll sees it as a new delta
* (at-least-once, never lost). */
static void commit_baselines(cbm_watcher_t *w, project_state_t *s) {
if (!s->is_git) {
/* Tree strategy (#1948): the walk already refreshed the file count. */
s->last_tree_sig = s->pending_tree_sig;
return;
}
if (s->pending_head[0] != '\0') {
snprintf(s->last_head, sizeof(s->last_head), "%s", s->pending_head);
}
s->last_dirty_sig = s->pending_dirty_sig;
/* Refresh file count for interval */
int file_count = 0;
if (git_file_count(w, s, &file_count) == WATCHER_GIT_OK) {
s->file_count = file_count;
s->interval_ms = cbm_watcher_poll_interval_ms(s->file_count);
}
}
static void poll_project(const char *key, void *val, void *ud) {
(void)key;
poll_ctx_t *ctx = ud;
@@ -1468,8 +1579,9 @@ static void poll_project(const char *key, void *val, void *ud) {
return;
}
/* Skip non-git projects */
if (!s->is_git) {
/* Non-git projects are skipped unless the watch_non_git opt-in turned on
* tree polling for them at baseline (#1948). */
if (!s->is_git && !s->tree_poll) {
return;
}
@@ -1495,26 +1607,14 @@ static void poll_project(const char *key, void *val, void *ud) {
* not admit an index callback after that ownership boundary. */
return;
}
cbm_log_info("watcher.changed", "project", s->project_name, "strategy", "git");
cbm_log_info("watcher.changed", "project", s->project_name, "strategy",
s->is_git ? "git" : "tree");
if (ctx->w->index_fn) {
int rc = ctx->w->index_fn(s->project_name, s->root_path, ctx->w->user_data);
if (rc == 0) {
ctx->reindexed++;
s->index_failures = 0;
/* Commit the baselines OBSERVED AT CHECK TIME — the state whose
* reindex just succeeded. A commit/edit landing during the
* reindex is deliberately not absorbed: the next poll sees it
* as a new delta (at-least-once, never lost). */
if (s->pending_head[0] != '\0') {
snprintf(s->last_head, sizeof(s->last_head), "%s", s->pending_head);
}
s->last_dirty_sig = s->pending_dirty_sig;
/* Refresh file count for interval */
int file_count = 0;
if (git_file_count(ctx->w, s, &file_count) == WATCHER_GIT_OK) {
s->file_count = file_count;
s->interval_ms = cbm_watcher_poll_interval_ms(s->file_count);
}
commit_baselines(ctx->w, s);
} else if (rc > 0) {
/* Busy-skip: baseline stays uncommitted, next poll retries. */
cbm_log_info("watcher.index.retry", "project", s->project_name);
+12
View File
@@ -4,6 +4,7 @@
* Polls indexed projects for git changes (HEAD movement or dirty working tree)
* and triggers re-indexing via a callback. Uses adaptive polling intervals
* based on project size (5s base + 1s per 500 files, capped at 60s).
* Non-git roots are not polled unless cbm_watcher_set_poll_non_git() opts in.
*
* Depends on: foundation, store (for project metadata)
*/
@@ -59,6 +60,17 @@ void cbm_watcher_set_project_mutation_guard(cbm_watcher_t *w,
cbm_watcher_project_mutation_end_fn end,
cbm_watcher_project_pruned_fn pruned, void *context);
/* Opt in to polling NON-GIT project roots (#1948; default off — non-git roots
* are not watched). When on, a non-git root is polled on the same adaptive
* cadence by a tree signature: the indexer's own discovery walk (same skip
* lists, .gitignore and .cbmignore rules), folded over each file's (relative
* path, size, mtime). A changed signature triggers index_fn; the first poll
* after baseline reindexes once, since nothing records which tree state the
* index holds. Paths discovery skips — including cbm's own .codebase-memory
* artifact directory and cache directory — never change the signature.
* Read at each project's baseline, so set it before registering projects. */
void cbm_watcher_set_poll_non_git(cbm_watcher_t *w, bool enabled);
/* ── Watch list management ──────────────────────────────────────── */
/* Add a project to the watch list. root_path is copied. Returns true only when
+3
View File
@@ -26,6 +26,7 @@ int tf_fail_count = 0;
int tf_skip_count = 0;
#include "test_framework.h"
#include "test_helpers.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 */
@@ -139,6 +140,8 @@ int main(void) {
* loudly instead of reaching it. */
cbm_daemon_bootstrap_forbid_default_runtime_for_test(true);
#endif
/* #2003: fixture git commands must never reach the caller's repository. */
th_clear_git_repo_env();
/* 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
+115
View File
@@ -15350,6 +15350,10 @@ TEST(registry_overlay_chain_iterates_and_copies_on_write) {
memset(&t, 0, sizeof(t));
t.qualified_name = "pkg.T";
t.short_name = "T";
const char *field_names[] = {"untyped", "typed", NULL};
const CBMType *field_types[] = {NULL, cbm_type_named(&arena, "pkg.Value"), NULL};
t.field_names = field_names;
t.field_types = field_types;
cbm_registry_add_type(&base, t);
cbm_registry_finalize(&base);
base.read_only = true;
@@ -15414,6 +15418,10 @@ TEST(registry_overlay_chain_iterates_and_copies_on_write) {
CBMRegisteredType *wt = cbm_registry_type_for_update(&overlay, "pkg.T");
ASSERT_NOT_NULL(wt);
ASSERT_EQ(overlay.type_count, 1);
/* A missing type for an earlier named field must not truncate the copy. */
bool field_slots_preserved = wt->field_types && wt->field_types != field_types &&
wt->field_types[0] == NULL &&
wt->field_types[1] == field_types[1] && wt->field_types[2] == NULL;
cbm_registry_all_types_chain(&overlay, &ti);
seen = 0;
while (cbm_type_short_iter_next(&ti) >= 0) {
@@ -15430,6 +15438,7 @@ TEST(registry_overlay_chain_iterates_and_copies_on_write) {
cbm_arena_destroy(&scratch);
cbm_arena_destroy(&arena);
ASSERT_TRUE(field_slots_preserved);
PASS();
}
@@ -15804,6 +15813,111 @@ TEST(seal_py_shared_registry_readonly_fields) {
PASS();
}
/* #1277: the production resolver receives a writable overlay, so refining an
* existing field must detach its pointer array from the sealed fallback. */
TEST(seal_py_overlay_existing_field_keeps_shared_type) {
CBMArena arena;
cbm_arena_init(&arena);
CBMLSPDef defs[4] = {0};
defs[0].qualified_name = "test.mod.Foo";
defs[0].short_name = "Foo";
defs[0].label = "Class";
defs[0].def_module_qn = "test.mod";
defs[0].field_defs = "x:test.contracts.Contract";
defs[1].qualified_name = "test.mod.Foo.m";
defs[1].short_name = "m";
defs[1].label = "Method";
defs[1].receiver_type = "test.mod.Foo";
defs[1].def_module_qn = "test.mod";
defs[2].qualified_name = "test.contracts.Contract";
defs[2].short_name = "Contract";
defs[2].label = "Class";
defs[2].def_module_qn = "test.contracts";
defs[3].qualified_name = "test.contracts.Contract.process_batch";
defs[3].short_name = "process_batch";
defs[3].label = "Method";
defs[3].receiver_type = "test.contracts.Contract";
defs[3].def_module_qn = "test.contracts";
for (int i = 0; i < 4; i++) {
defs[i].lang = CBM_LANG_PYTHON;
}
CBMTypeRegistry *reg = cbm_py_build_cross_registry(&arena, defs, 4);
ASSERT_NOT_NULL(reg);
ASSERT_TRUE(reg->read_only);
const CBMRegisteredType *base = cbm_registry_lookup_type(reg, "test.mod.Foo");
ASSERT_NOT_NULL(base);
ASSERT_NOT_NULL(base->field_names);
ASSERT_NOT_NULL(base->field_types);
const char **names_before = base->field_names;
const CBMType **types_before = base->field_types;
const CBMType *type_before = base->field_types[0];
ASSERT_NOT_NULL(type_before);
ASSERT_NULL(base->field_types[1]);
CBMArena scratch;
cbm_arena_init(&scratch);
CBMTypeRegistry overlay;
cbm_registry_init(&overlay, &scratch);
overlay.fallback = reg;
const char *writer = "class Foo:\n"
" def m(self):\n"
" self.x = 1\n";
CBMResolvedCallArray out = {0};
cbm_run_py_lsp_cross_with_registry(&scratch, writer, (int)strlen(writer), "test.mod", &overlay,
NULL, NULL, 0, NULL, &out, NULL);
/* Observe while scratch is live, then release both arenas before any
* failure assertion so the regression also fails cleanly under LSan. */
bool shared_names_unchanged = base->field_names == names_before;
bool shared_types_unchanged = base->field_types == types_before;
bool shared_element_unchanged = base->field_types[0] == type_before;
bool shared_terminator_unchanged = base->field_types[1] == NULL;
const CBMRegisteredType *refined = cbm_registry_lookup_type(&overlay, "test.mod.Foo");
bool local_refined = refined && refined != base && refined->field_types &&
refined->field_types != types_before && refined->field_types[0] &&
refined->field_types[0] != type_before &&
refined->field_types[0]->kind == CBM_TYPE_BUILTIN &&
refined->field_types[1] == NULL;
cbm_arena_destroy(&scratch);
/* Never read a corrupted shared pointer after scratch destruction. When
* intact, a later file must still see the original Contract field. */
int hits = 0;
if (shared_names_unchanged && shared_types_unchanged && shared_element_unchanged &&
shared_terminator_unchanged && local_refined) {
cbm_arena_init(&scratch);
cbm_registry_init(&overlay, &scratch);
overlay.fallback = reg;
const char *reader = "from mod import Foo\n\n"
"def run(foo: Foo):\n"
" foo.x.process_batch()\n";
const char *import_names[] = {"Foo"};
const char *import_qns[] = {"test.mod.Foo"};
memset(&out, 0, sizeof(out));
cbm_run_py_lsp_cross_with_registry(&scratch, reader, (int)strlen(reader), "test.reader",
&overlay, import_names, import_qns, 1, NULL, &out, NULL);
for (int i = 0; i < out.count; i++) {
const CBMResolvedCall *call = &out.items[i];
if (call->caller_qn && call->callee_qn &&
strcmp(call->caller_qn, "test.reader.run") == 0 &&
strcmp(call->callee_qn, "test.contracts.Contract.process_batch") == 0 &&
call->kind == CBM_RESOLVED_INVOCATION &&
call->confidence >= CBM_LSP_CONFIDENCE_FLOOR) {
hits++;
}
}
cbm_arena_destroy(&scratch);
}
cbm_arena_destroy(&arena);
ASSERT_TRUE(shared_names_unchanged);
ASSERT_TRUE(shared_types_unchanged);
ASSERT_TRUE(shared_element_unchanged);
ASSERT_TRUE(shared_terminator_unchanged);
ASSERT_TRUE(local_refined);
ASSERT_EQ(hits, 1);
PASS();
}
TEST(seal_cs_shared_registry_readonly) {
CBMArena arena;
cbm_arena_init(&arena);
@@ -16402,6 +16516,7 @@ SUITE(c_lsp) {
RUN_TEST(registry_overlay_chain_iterates_and_copies_on_write);
RUN_TEST(clsp_method_return_refinement_is_copy_on_write);
RUN_TEST(seal_py_shared_registry_readonly_fields);
RUN_TEST(seal_py_overlay_existing_field_keeps_shared_type);
RUN_TEST(seal_cs_shared_registry_readonly);
RUN_TEST(seal_ts_shared_registry_readonly);
RUN_TEST(seal_go_shared_registry_readonly);
+348
View File
@@ -0,0 +1,348 @@
/*
* test_callable_sig.c — golden tables for the signature-qualified callable
* identity builder and its inverse (#2061, plumbing: no language enabled).
*/
#include "test_framework.h"
#include "callable_sig.h"
#include "lang_specs.h"
#include "foundation/arena.h"
#include "pipeline/pipeline.h"
#include "pipeline/lsp_resolve.h"
#include "tree_sitter/api.h"
#include <string.h>
typedef struct {
CBMLanguage lang;
CBMCallableIdentity mode;
const char *source;
const char *kind; /* node kind of the callable */
int nth; /* 0-based occurrence of `kind` in preorder */
const char *expected;
} sig_case_t;
static bool find_nth(TSNode n, const char *kind, int *left, TSNode *out) {
if (strcmp(ts_node_type(n), kind) == 0) {
if (*left == 0) {
*out = n;
return true;
}
(*left)--;
}
uint32_t count = ts_node_child_count(n);
for (uint32_t i = 0; i < count; i++) {
if (find_nth(ts_node_child(n, i), kind, left, out)) {
return true;
}
}
return false;
}
/* Parse `source`, build the nth `kind` node's suffix in `mode`; the returned
* string is arena-owned (NULL when absent). */
static const char *sig_of(CBMArena *a, CBMLanguage lang, CBMCallableIdentity mode,
const char *source, const char *kind, int nth) {
TSParser *parser = ts_parser_new();
ts_parser_set_language(parser, cbm_ts_language(lang));
TSTree *tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source));
TSNode node = {0};
int left = nth;
const char *sig = NULL;
if (tree && find_nth(ts_tree_root_node(tree), kind, &left, &node)) {
sig = cbm_callable_sig_mode(a, node, source, lang, mode);
}
ts_tree_delete(tree);
ts_parser_delete(parser);
return sig;
}
static const sig_case_t k_cases[] = {
/* Java: generics kept, qualifiers and annotations dropped, varargs = []. */
{CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED,
"class A { <T extends Comparable<T>> void work(final java.util.List<String> xs, int[] a, "
"String... rest) {} }",
"method_declaration", 0, "(List<String>,int[],String[])"},
{CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED, "class A { void f(@Ann Map<K, V> m, int a[]){} }",
"method_declaration", 0, "(Map<K,V>,int[])"},
{CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED,
"class A { void f(\n @Ann Map< K ,\n V > m, /* c */ int a [ ]\n) {} }", "method_declaration",
0, "(Map<K,V>,int[])"},
{CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED, "class A { A(int x){} void g(){} }",
"constructor_declaration", 0, "(int)"},
{CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED, "class A { A(int x){} void g(){} }",
"method_declaration", 0, "()"},
/* C#: generic arity, ref/out, params inlined by the grammar, tuple names
* dropped, operators and indexers. */
{CBM_LANG_CSHARP, CBM_CALLABLE_ID_TYPED,
"class A { public void Work<T, U>(ref int x, out string y, params object[] rest, int? n = 3, "
"List<Dictionary<string,int>> m, (int a, string b) t, this Foo z) {} }",
"method_declaration", 0,
"<T,U>(ref int,out string,object[],int?,List<Dictionary<string,int>>,(int,string),Foo)"},
{CBM_LANG_CSHARP, CBM_CALLABLE_ID_TYPED,
"class A { public static A operator +(A a, A b) => a; }", "operator_declaration", 0, "(A,A)"},
{CBM_LANG_CSHARP, CBM_CALLABLE_ID_TYPED, "class A { int this[int i] { get => 0; } }",
"indexer_declaration", 0, "(int)"},
/* C++: template kinds, declarator markers, top-level cv dropped, arrays
* decay, function pointers, C variadic, packs, cvref, operators. */
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED,
"struct S { template <typename T, int N = 3> void work(const std::vector<T> & v, "
"int (*cb)(int), unsigned long x, ...) const && noexcept; };",
"template_declaration", 0,
"<typename,int>(const vector<T>&,int(*)(int),unsigned long,~)const&&"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED, "struct S { S& operator=(S&&) &; };", "field_declaration",
0, "(S&&)&"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED, "struct S { bool operator()(int) volatile; };",
"field_declaration", 0, "(int)volatile"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED,
"struct S { template<class... Args> void emplace(Args&&... args); };", "template_declaration",
0, "<typename~>(Args&&~)"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED, "void n::S::arr(int a[10], char *const p, int q) {}",
"function_definition", 0, "(int*,char*,int)"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED,
"void w(\n const int a , // trailing\n char const * /* c */ const p\n);",
"declaration", 0, "(int,const char*)"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED, "void v(void);", "declaration", 0, "()"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED, "void f(int (*(*g)(int x))(double), void h(char *s));",
"declaration", 0, "(int(*(*)(int))(double),void(*)(char*))"},
{CBM_LANG_CPP, CBM_CALLABLE_ID_TYPED,
"template <class T> struct S { void f(int); };\ntemplate <class T> void S<T>::f(int x) {}",
"function_definition", 0, "(int)"},
/* Kotlin: extension receiver, vararg, function types, nullable,
* qualified types, suspend. */
{CBM_LANG_KOTLIN, CBM_CALLABLE_ID_TYPED,
"class A {\n fun <T : Comparable<T>> String.work(vararg xs: Int, f: (Int) -> Unit, "
"m: Map<String, List<Int>>? = null, @Ann q: kotlin.collections.List<*>) {}\n}",
"function_declaration", 0, "(this:String,Int~,(Int)=>Unit,Map<String,List<Int>>?,List<*>)"},
{CBM_LANG_KOTLIN, CBM_CALLABLE_ID_TYPED, "fun top(x: Int) = x", "function_declaration", 0,
"(Int)"},
{CBM_LANG_KOTLIN, CBM_CALLABLE_ID_TYPED, "class A { constructor(x: Int) {} }",
"secondary_constructor", 0, "(Int)"},
/* Swift: labels + types (the #2061 Alamofire shape), variadic, inout,
* attributes dropped, qualified types, init/subscript/operators. */
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_LABELED_TYPED,
"class Session {\n func upload<T: Encodable>(_ data: Data, to url: URLConvertible, method: "
"HTTPMethod = .post, headers: [String: String]? = nil, handler: @escaping (Int) -> Void, "
"xs: Int..., io: inout Swift.Int, t: (a: Int, String)) -> UploadRequest { }\n}",
"function_declaration", 0,
"(_:Data,to:URLConvertible,method:HTTPMethod,headers:[String:String]?,handler:(Int)=>Void,"
"xs:Int~,io:inout Int,t:(a:Int,String))"},
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_LABELED_TYPED,
"class Session {\n func upload(_ data: Data, with request: URLRequest) {}\n}",
"function_declaration", 0, "(_:Data,with:URLRequest)"},
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_LABELED_TYPED, "class C { init(frame: CGRect) {} }",
"init_declaration", 0, "(frame:CGRect)"},
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_LABELED_TYPED,
"class C { subscript(index i: Int) -> Int { return 0 } }", "subscript_declaration", 0,
"(index:Int)"},
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_LABELED_TYPED,
"class C { static func + (l: C, r: C) -> C { l } }", "function_declaration", 0, "(l:C,r:C)"},
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_LABELED_TYPED, "func extra() {}", "function_declaration", 0,
"()"},
/* Scala: every clause flattened, by-name and repeated parameters. */
{CBM_LANG_SCALA, CBM_CALLABLE_ID_TYPED,
"class A {\n def work[T <: AnyRef](xs: List[T], n: => Int, rest: String*)(implicit ord: "
"Ordering[T]): Unit = {}\n}",
"function_definition", 0, "(List[T],=>Int,String*,Ordering[T])"},
{CBM_LANG_SCALA, CBM_CALLABLE_ID_TYPED,
"class A {\n def f(g: (Int, String) => scala.collection.immutable.Map[String, Int]): Unit\n}",
"function_declaration", 0, "((Int,String)=>Map[String,Int])"},
/* Objective-C: the selector's keyword labels. */
{CBM_LANG_OBJC, CBM_CALLABLE_ID_LABELED,
"@implementation Foo\n- (instancetype)initWithFrame:(CGRect)frame style:(NSInteger)style "
"{ return self; }\n@end",
"method_definition", 0, "(_:style:)"},
{CBM_LANG_OBJC, CBM_CALLABLE_ID_LABELED, "@implementation Foo\n- (void)run { }\n@end",
"method_definition", 0, "()"},
{CBM_LANG_OBJC, CBM_CALLABLE_ID_LABELED,
"@implementation Foo\n- (void)setX:(int)x :(int)y {}\n@end", "method_definition", 0, "(_:_:)"},
{CBM_LANG_OBJC, CBM_CALLABLE_ID_LABELED,
"@implementation Foo\n+ (id)make:(int)a, ... { return nil; }\n@end", "method_definition", 0,
"(_:~)"},
/* ARITY (dynamic tier-2 languages), shown on a Swift declaration. */
{CBM_LANG_SWIFT, CBM_CALLABLE_ID_ARITY, "class C { func upload(_ data: Data, to url: URL) {} }",
"function_declaration", 0, "(2)"},
};
TEST(callable_sig_golden_table) {
for (size_t i = 0; i < sizeof(k_cases) / sizeof(k_cases[0]); i++) {
const sig_case_t *tc = &k_cases[i];
CBMArena a;
cbm_arena_init(&a);
const char *sig = sig_of(&a, tc->lang, tc->mode, tc->source, tc->kind, tc->nth);
if (!sig || strcmp(sig, tc->expected) != 0) {
printf(" case %zu: got %s, want %s\n", i, sig ? sig : "(null)", tc->expected);
}
ASSERT_NOT_NULL(sig);
ASSERT_STR_EQ(sig, tc->expected);
ASSERT_TRUE(strlen(sig) <= CBM_CALLABLE_SIG_MAX);
/* Contract: no separator a leaf splitter uses, and the inverse
* recovers the base from a real-shaped QN. */
ASSERT_NULL(strchr(sig, '.'));
ASSERT_NULL(strstr(sig, "::"));
ASSERT_NULL(strstr(sig, "->"));
char *qn = cbm_arena_sprintf(&a, "proj.pkg.Cls.name%s", sig);
ASSERT_EQ(cbm_qn_callable_base_len(qn), strlen("proj.pkg.Cls.name"));
cbm_arena_destroy(&a);
}
PASS();
}
/* Long signatures cap at CBM_CALLABLE_SIG_MAX with a hash of the FULL
* suffix: deterministic, still distinct, still invertible. */
TEST(callable_sig_cap_keeps_identity) {
char src_a[4096];
char src_b[4096];
size_t n = (size_t)snprintf(src_a, sizeof(src_a), "class A { void f(");
for (int i = 0; i < 30; i++) {
n += (size_t)snprintf(src_a + n, sizeof(src_a) - n, "%sVeryLongParameterTypeName%d p%d",
i ? ", " : "", i, i);
}
memcpy(src_b, src_a, n);
snprintf(src_a + n, sizeof(src_a) - n, ", int last) {} }");
snprintf(src_b + n, sizeof(src_b) - n, ", long last) {} }");
CBMArena a;
cbm_arena_init(&a);
const char *sa =
sig_of(&a, CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED, src_a, "method_declaration", 0);
const char *sa2 =
sig_of(&a, CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED, src_a, "method_declaration", 0);
const char *sb =
sig_of(&a, CBM_LANG_JAVA, CBM_CALLABLE_ID_TYPED, src_b, "method_declaration", 0);
ASSERT_NOT_NULL(sa);
ASSERT_NOT_NULL(sb);
ASSERT_TRUE(strlen(sa) <= CBM_CALLABLE_SIG_MAX);
ASSERT_TRUE(strlen(sb) <= CBM_CALLABLE_SIG_MAX);
ASSERT_STR_EQ(sa, sa2);
ASSERT_STR_NEQ(sa, sb); /* they differ only past the cap: the hash tells */
ASSERT_TRUE(strncmp(sa, "(VeryLongParameterTypeName0,", 28) == 0);
const char *hash = strchr(sa, '#');
ASSERT_NOT_NULL(hash);
ASSERT_EQ(strlen(hash), (size_t)18); /* "#" + 16 hex + ")" */
char *qn = cbm_arena_sprintf(&a, "p.A.f%s", sa);
ASSERT_EQ(cbm_qn_callable_base_len(qn), strlen("p.A.f"));
cbm_arena_destroy(&a);
PASS();
}
/* PR1 is plumbing: no language mints a suffix yet. */
TEST(callable_sig_every_language_is_none) {
CBMArena a;
cbm_arena_init(&a);
const char *src = "class A { void f(int x) {} }";
for (int lang = 0; lang < CBM_LANG_COUNT; lang++) {
ASSERT_EQ(cbm_callable_identity((CBMLanguage)lang), CBM_CALLABLE_ID_NONE);
}
TSParser *parser = ts_parser_new();
ts_parser_set_language(parser, cbm_ts_language(CBM_LANG_JAVA));
TSTree *tree = ts_parser_parse_string(parser, NULL, src, (uint32_t)strlen(src));
TSNode m = {0};
int left = 0;
ASSERT_TRUE(find_nth(ts_tree_root_node(tree), "method_declaration", &left, &m));
ASSERT_NULL(cbm_callable_sig(&a, m, src, CBM_LANG_JAVA));
ts_tree_delete(tree);
ts_parser_delete(parser);
cbm_arena_destroy(&a);
PASS();
}
/* The inverse is the identity on every historical QN shape. */
TEST(callable_sig_base_len_unsuffixed_is_full) {
static const char *const qns[] = {
"proj.pkg.Cls.method",
"proj.S.operator()",
"proj.S.operator<",
"proj.S.operator<=>",
"proj.S.operator->",
"proj.S.operator>>",
"proj.S.operator&&",
"proj.app/(auth)",
"proj.Makefile.$(OBJ)",
"proj.f.(anon)",
"",
"proj.x.list<int>",
"proj.x.make_const",
"a::b::c",
"proj.~Dtor",
"(x)",
"proj.Makefile.foo$(EXT)",
"proj.lib/(group)/page",
"proj.C.+",
"proj.A.unary_!",
};
for (size_t i = 0; i < sizeof(qns) / sizeof(qns[0]); i++) {
ASSERT_EQ(cbm_qn_callable_base_len(qns[i]), strlen(qns[i]));
}
ASSERT_EQ(cbm_qn_callable_base_len(NULL), (size_t)0);
PASS();
}
TEST(callable_sig_base_len_suffixed) {
static const struct {
const char *qn;
const char *base;
} rows[] = {
{"p.S.work(int,String)", "p.S.work"},
{"p.S.work()", "p.S.work"},
{"p.S.operator()()", "p.S.operator()"},
{"p.S.operator()(int)const", "p.S.operator()"},
{"p.S.operator<<typename>(T)", "p.S.operator<"},
{"p.S.operator<=>(S)", "p.S.operator<=>"},
{"p.S.operator->()", "p.S.operator->"},
{"p.S.f<typename,int>(const vector<T>&,int(*)(int))const&&", "p.S.f"},
{"p.C.Work<T,U>(ref int)", "p.C.Work"},
{"p.Session.upload(_:Data,to:URL)", "p.Session.upload"},
{"p.K.work(this:String,(Int)=>Unit)", "p.K.work"},
{"p.O.initWithFrame(_:style:)", "p.O.initWithFrame"},
{"p.C.+(l:C,r:C)", "p.C.+"},
{"p.A.unary_!()", "p.A.unary_!"},
{"p.S.operator/(S)", "p.S.operator/"},
{"p.S.~S()", "p.S.~S"},
{"p.J.f(VeryLong0,#0123456789abcdef)", "p.J.f"},
};
for (size_t i = 0; i < sizeof(rows) / sizeof(rows[0]); i++) {
ASSERT_EQ(cbm_qn_callable_base_len(rows[i].qn), strlen(rows[i].base));
}
PASS();
}
/* The leaf splitters look only at the base: Swift labels carry ':' and a
* suffix may carry '>' — neither is a separator. */
TEST(callable_sig_leaf_splitters_skip_suffix) {
const char *swift = "p.Session.upload(_:Data,to:URL)";
ASSERT_STR_EQ(cbm_lsp_bare_segment(swift), "upload(_:Data,to:URL)");
ASSERT_STR_EQ(cbm_pipeline_qn_class_method_tail(swift), "Session.upload(_:Data,to:URL)");
/* Unsuffixed spellings are unchanged. */
ASSERT_STR_EQ(cbm_lsp_bare_segment("Math::square"), "square");
ASSERT_STR_EQ(cbm_lsp_bare_segment("p->run"), "run");
ASSERT_STR_EQ(cbm_lsp_bare_segment("identity<int>"), "identity<int>");
ASSERT_STR_EQ(cbm_pipeline_qn_class_method_tail("p.q.Cls.m"), "Cls.m");
PASS();
}
/* The registry's by-name bucket is the base leaf, so every overload of a
* signature-qualified callable is found by its bare name; an unsuffixed QN
* keeps its historical key (last '.' or "::" segment). */
TEST(callable_sig_registry_by_name_uses_base_leaf) {
cbm_registry_t *r = cbm_registry_new();
cbm_registry_add(r, "upload", "p.Session.upload(_:Data,to:URL)", "Method");
cbm_registry_add(r, "upload", "p.Session.upload(_:Data,with:URLRequest)", "Method");
cbm_registry_add(r, "square", "p.Math::square", "Function");
const char **out = NULL;
int count = 0;
cbm_registry_find_by_name(r, "upload", &out, &count);
ASSERT_EQ(count, 2);
count = 0;
cbm_registry_find_by_name(r, "square", &out, &count);
ASSERT_EQ(count, 1);
cbm_registry_free(r);
PASS();
}
SUITE(callable_sig) {
RUN_TEST(callable_sig_golden_table);
RUN_TEST(callable_sig_cap_keeps_identity);
RUN_TEST(callable_sig_every_language_is_none);
RUN_TEST(callable_sig_base_len_unsuffixed_is_full);
RUN_TEST(callable_sig_base_len_suffixed);
RUN_TEST(callable_sig_leaf_splitters_skip_suffix);
RUN_TEST(callable_sig_registry_by_name_uses_base_leaf);
}
+1077 -8
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More