Why: in a mixed-language repo the registry resolves the bare name of a
route-registration callee (`Route::get`, `$router->get`, `app.get`)
before either resolver classifies the call, and with imports in play it
binds `get` by suffix_match to a same-named definition in another
language (a JS `get`, a Python `get`). The #725 guard rightly refuses
that binding, but it dropped the whole call, so the callee-suffix route
classification never ran. Every GET registration vanished while
POST/PUT/DELETE (nothing named `post` to collide with) survived:
krayin/laravel-crm minted 1 GET Route for its 126 `Route::get` calls:
all 126 were bound (suffix_match, 19 candidates) to `get` in a vendored
Chart.js copy under resources/assets/js and refused.
Fix: a refused binding leaves the callee unresolved, so at the #725
guard both resolvers now give a route-registration callee exactly the
Route the unresolved-callee fallback mints for it, and nothing else.
Sequential: the #952 fallback's predicate + handle_route_registration.
Parallel: emit_xlang_refused_route classifies by callee the way
emit_service_edge classifies the callee_suffix fallback and emits only
emit_route_registration. The guard, its strategies and its per-language
scope are unchanged: no CALLS edge to the refused target, no URL
argument scan, every other refused call is still dropped.
Proof (fresh index per run, macOS arm64, origin/main 1f9b4db1):
- krayin/laravel-crm 03ebedd7 with the pending Laravel slashless,
handler and withRouting-prefix patches applied: GET Routes 1 -> 126,
CALLS->Route 130 -> 257, HANDLES 1 -> 4. New GET CALLS per route file
equal the `Route::get(` count in all 14 files; 0 edges removed; 0 new
edges into non-Route nodes.
- krayin on origin/main alone: GET 1 -> 2 (before the slashless patch
only the two `Route::get('/', ...)` paths are classifiable).
- Suppression intact: code CALLS unchanged (krayin 16,439; BookStack
a09aa8aa 34,292) and cross-language suffix_match CALLS stay 0.
- Side effect: PHP test-client verb calls (`$this->get('/x')`) that the
guard had hidden now get the same route classification main already
gives their unhidden siblings (BookStack +43 on 544, krayin +1). That
classification is pre-existing and separate.
Tests: edge_types_probe routes_laravel_get_survives_xlang_guard,
routes_express_get_survives_xlang_guard and their _parallel twins.
Each fixture also asserts that a bare or member `get` call bound across
languages still yields no CALLS edge and no Route. RED 3x before, green
after; reverting either resolver re-reds exactly its own two tests.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Why: the activation rendezvous is per OS account, so an install or update
run under another HOME / CBM_CACHE_DIR (a sandbox, a second profile) meets
the account's live daemon at the same endpoint. The daemon's
activation-shutdown handler verifies only the requester's build, never its
cache, so the CLI's scope decision is the only thing that tells "my daemon"
from "someone else's". That decision drained the cohort unless the active
cache was positively DIFFERENT: a busy session group (another activation or
a session start held it, so the active identity was never read) and an
unreadable active cache both fell through to "ours", printed "Stopping
active CBM sessions" and shut the daemon and every session behind it down.
Fix (user decision 2026-09-28, "unknown = foreign, keep it"): only a
positive match may drain. cli_activation_resolve_scope returns
CLI_ACTIVATION_SCOPE_ACTIVE only for an OK admission (exact identity, cache
included, or an empty group) or for a conflict whose cache fingerprint
equals this activation's. BUSY and a blank active cache now return the new
CLI_ACTIVATION_SCOPE_UNCONFIRMED, handled like a foreign cohort: no lock is
taken, no drain request is sent, the mutation proceeds, and the audit log
records "quiesce_skipped: active cohort ownership unconfirmed (...)". A
read-only status probe names the daemon that was left (pid, version) and
the notice says how to stop it: close its sessions, then run
`codebase-memory-mcp daemon stop`. The confirmed paths are unchanged: a
normal self-upgrade still drains its own daemon, a clearly foreign cache is
still left alone.
Proof (product binaries; private CBM_RUNTIME_DIR; an own permanent test
daemon started from the same build under a host HOME/cache; a sandbox
HOME/cache on the same runtime dir; the cohort maintenance gate held by a
second process, i.e. a busy session group):
- origin/main: "Stopping active CBM sessions and operations for
install...", the test daemon was stopped (daemon status: not running),
and the install still failed (rc=1 after 23 s, "could not be stopped
safely").
- this change: "Leaving the running CBM daemon untouched (pid 76713,
version dev): this install could not confirm that it serves the cache
this install targets (the session group was busy, so its cache identity
could not be read)." The test daemon kept running with the same pid and
the install completed (rc=0, 10 s).
A lifetime record whose cache field is zeroed is refused (UNSAFE) by both
builds with the daemon kept; that path never drained and is unchanged.
Tests (cli suite; fixture daemon in a private runtime dir; sandbox HOME):
- cli_install_foreign_home_unreadable_cohort_cache_keeps_host_daemon
(the new seam cbm_cli_set_activation_scope_cache_unreadable_for_test
blanks the observed active cache fingerprint)
- cli_install_foreign_home_busy_cohort_keeps_host_daemon (the maintenance
gate is held through the product's own lock-directory handle)
Both were RED 3x on origin/main for the right reason (the host daemon was
drained: ASSERT(host_serving)), are green with the fix, and turn RED again
when the fix is reverted. Controls stay green:
cli_install_into_host_namespace_still_drains_host_cohort (confirmed same
cache: drained, as before) and
cli_install_{skip_binary,binary}_into_foreign_home_never_drains_host_cohort
(clearly different cache: kept, as before).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Why: the test runner isolated HOME and CBM_CACHE_DIR but not
CBM_RUNTIME_DIR, and neither of the first two moves the daemon
rendezvous. Its key is a constant product hash (cbm_daemon_rendezvous_key,
"c888acc3ae367a1e"), and with no explicit parent and CBM_RUNTIME_DIR unset
cbm_daemon_bootstrap_endpoint_new falls back to the account-wide default
parent (/private/tmp on macOS, /tmp on Linux, LocalAppData on Windows).
Every endpoint a test resolved without an explicit parent was therefore
byte-identical to the developer's live daemon socket
(/private/tmp/cbm-daemon-<uid>/cbm-c888acc3ae367a1e.sock), whatever HOME
said.
The only in-runner product caller is CLI activation
(cli_activation_production_context_init, reached from cbm_cmd_install,
cbm_cmd_uninstall and update). Only a process-global seam kept it off the
default: SUITE(cli) sets that seam on entry and clears it on exit. On the
default endpoint, activation admits into the live daemon's cohort. When
the cohort is ours or busy, or the active cache fingerprint is unreadable,
activation prints "Stopping active CBM sessions" and drains them. That is
the same class of failure as an old binary's install, which stopped a
user daemon and six MCP sessions. One test outside SUITE(cli), or one
fixture that drops the variable, was enough to reach it.
daemon_bootstrap_runtime_dir_env_relocates_rendezvous did exactly that:
it restored by unsetting CBM_RUNTIME_DIR.
Fix:
- tests/test_main.c: tf_setup_cache_sentinel creates a fresh per-run
runtime parent (th_secure_runtime_parent_new "run", under /tmp on POSIX
and LocalAppData on Windows) and sets CBM_RUNTIME_DIR to it for the
whole run. It replaces any inherited value, the rule
scripts/test-runtime.sh applies to the shell harness. The existing
atexit cleanup removes the directory.
- src/daemon/bootstrap.c, CBM_ENABLE_TEST_SEAMS only: once a test runner
arms the guard, an endpoint request with no explicit parent and no
CBM_RUNTIME_DIR is refused with a stderr diagnostic instead of
resolving the default. No product binary arms it.
- tests/repro/repro_main.c arms the same guard. No reproduction needs the
rendezvous.
- tests/test_daemon_bootstrap.c: the relocation test restores the value
it found instead of unsetting it.
- tests/test_helpers.h: th_secure_runtime_base() names the anchor that
th_secure_runtime_parent_new already used.
Proof:
- Before, on origin/main 1f9b4db1: runner_isolation is RED 3/3 at its
first assertion (CBM_RUNTIME_DIR is NULL during the run).
- After: green 3/3. The endpoint resolved through the product resolver
lies inside /private/tmp/cbm-runtime-run-XXXXXX/, never at
/private/tmp/cbm-daemon-<uid>. All 43 activation-guard scopes logged
by the suites below are fixture or cli-suite directories, and the
guard never fired. The per-run directory is gone after exit, and the
live daemon and its runtime directory are unchanged.
- Revert: dropping the setenv gives RED (value is NULL). Disarming the
guard gives RED (refused_without).
Tests:
- runner_isolation: runner_isolation_daemon_runtime_dir_is_private,
runner_isolation_refuses_default_daemon_runtime
- Green on macOS: cli (328), mcp + mcp_mutation_guard (344),
daemon_runtime + daemon_application (106), daemon + daemon_version +
daemon_frontend + daemon_bootstrap + daemon_ipc (117), runner_isolation
+ activation_transaction + version_cohort + project_lock +
index_supervisor + private_file_lock + lock_registry (73). All skips
are existing Windows- or Linux-only platform skips.
- make -f Makefile.cbm lint-ci passes. test-repro-runner builds.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Why: arming the hook-augment deadline opens its breadcrumb log with
O_CREAT. The path came from raw getenv("HOME") as
"%s/.cache/codebase-memory-mcp/logs" in 1 KiB buffers with no length
check. A HOME near 1 KiB therefore created a file at the cut-off name
(".../logs/hook-augme") on every hook call, and a longer one created a
cut-off directory. The hook also ignored CBM_CACHE_DIR, which every
other cbm component honours for its cache and logs. The index skip log
had the same defect in its CBM_INDEX_LOG override: an override longer
than 1 KiB was copied in unchecked and opened "wb", which created or
truncated the file at its cut-off prefix and reported that name as the
run's logfile.
Fix: the breadcrumb log now resolves through cbm_resolve_cache_dir()
(CBM_CACHE_DIR, else HOME, else USERPROFILE, plus the default) to
<cache_dir>/logs/hook-augment-timeouts.log. Every snprintf into the
1 KiB buffers is checked, including the one for the CBM_HOOK_TIMEOUT_LOG
override. A path that does not fit means no breadcrumb, and the logs
directory is created only for a path that fits. The hook still exits 0
(it never fails the agent's hook call) and allocates nothing new. The
CBM_INDEX_LOG override gets the same check: an override that does not
fit writes no logfile and warns index.logfile_path_too_long, and the
index still completes. With a normal HOME the log stays where it was.
Proof (dev binary, synthetic roots, isolated CBM_RUNTIME_DIR, no-op
Bash payload on stdin; "created" = find over the synthetic root minus
the pre-made HOME/cache chains):
- 980-byte HOME. Before: exit 0, plus three directories and a file at
the cut-off name <HOME>/.cache/codebase-memory-mcp/logs/hook-augme
(1023 bytes). After: exit 0, nothing created.
- CBM_CACHE_DIR=<root>/cache. Before: the log landed under HOME.
After: <root>/cache/logs/hook-augment-timeouts.log.
- 1000-byte CBM_CACHE_DIR. After: exit 0, nothing created.
- Normal HOME: <HOME>/.cache/codebase-memory-mcp/logs/
hook-augment-timeouts.log before and after.
- 1096-byte CBM_INDEX_LOG via `cli index_repository`. Before: a file
at the 1023-byte cut-off name, reported as the logfile. After: status
indexed, skipped_count 1, no logfile, nothing written.
Tests: RED 3x on the unfixed code for the reasons above, green with
the fix, RED again with the fix reverted:
- cli: cli_hook_augment_log_long_home_creates_no_cut_path,
cli_hook_augment_log_honours_cache_dir, plus the positive control
cli_hook_augment_log_default_location_unchanged (green before and
after).
- index_resilience: index_long_log_override_writes_no_cut_path.
The fixtures sit under link-resolved temp roots: the kernel bounds the
expanded path, so under macOS's /tmp -> /private/tmp link a near-1 KiB
path can be neither created nor probed, and the bug stays hidden.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Every HTTP client call the service patterns classify -- `axios.get(url)`,
an `axios.create()` instance's `.post(url, body)` -- got two HTTP_CALLS
edges from the parallel resolver: the typed one, carrying the verb its
callee names (`__route__GET__/api/x`), and a method-less
`__route__ANY__/api/x` twin (via=arg_url) for the same call site. On
microsoft/healthcare-ai-model-evaluator that was 59 of 129 HTTP_CALLS. The
twin never matches a handler in-repo, because ANY never meets a GET route.
Cross-repo, it matches any method, so the call site also bound to handlers
of the wrong method (`addDataSet` POST -> GetAll).
Root cause: emit_service_edge ran detect_url_in_args unconditionally
after its classification branch. That heuristic exists for calls no
service pattern knows, such as a local fetch wrapper
`callApi('/api/orders')`. On a call the HTTP branch had already
classified, it only re-derived the same URL without the method.
Fix: emit_service_edge now skips detect_url_in_args when its HTTP branch
emitted the call's HTTP_CALLS edge. Nothing else changes:
- unclassified calls (wrappers, `dev.load('/api/x')`) keep their arg_url
edge;
- route registrations still return before it;
- ASYNC, gRPC, GraphQL, tRPC and CONFIG calls behave as before.
The sequential resolver has no arg_url heuristic on main, so it needs no
change.
Proof (release binary, macOS arm64, microsoft/healthcare-ai-model-evaluator
@00348ac9, in-repo, before -> after):
- HTTP_CALLS 129 -> 70. The 59 removed edges are all arg_url twins of a
typed edge that the same caller keeps, to the same path.
- The typed HTTP_CALLS set is identical: 61 edges, same digest.
- The other 21 edge types are identical.
- Route nodes 111 -> 69: the orphaned ANY twins.
- The 9 arg_url edges left are appConfig.getPath UI paths, a separate
defect.
Six sampled removals were checked against the client source, including
trialService.ts:39 `axiosInstance.get(`/api/trials/get-done`)` and
modelService.ts:21 `axiosInstance.put(`/api/models/${model.id}`)`. Each is
one call site whose verb matches the kept typed edge.
Cross-repo (frontend/ -> backend/ indexed as two projects, then the
cross-repo-intelligence mode, which runs cbm_cross_repo_match): main has no
ASP.NET attribute routes yet, so CROSS_HTTP_CALLS is 0 -> 0 there. On the
pending ASP.NET route stack (fix/aspnet-route-case-inrepo, 8e734ee5), with
this change on top:
- CROSS_HTTP_CALLS 118 -> 60;
- all 58 typed links are identical;
- the 58 removed links were all ANY twins. 57 duplicated the typed link and
one was the wrong-method `addDataSet` ANY -> GetAll;
- the two method-less `fetch('/api/auth/config')` links stay;
- in-repo HANDLES 123 and DATA_FLOWS 58 are unchanged.
Tests:
- pipeline_typed_http_call_has_no_arg_url_twin (parallel resolver):
axios-instance GET/POST and direct axios.delete each keep exactly one
typed edge, with no ANY edge, while a local fetch wrapper keeps its
arg_url edge. RED 3/3 before the fix, green after, RED again on revert.
- pipeline_typed_http_call_has_no_arg_url_twin_sequential pins the same
contract on the sequential resolver, so that arg_url moving there (#2235)
cannot bring the twin back.
- pipeline_tsjs_receiver_parallel_keeps_service_edges counted the twin
(">= 3 HTTP_CALLS: axios.get -> 2 edges"). It now asserts exactly one typed
GET for axios.get, the dev.load arg_url edge that the weak-member guard
must keep, and 2 HTTP_CALLS in total. It also goes RED on revert.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Add focused galaxy tracing, edge filters, organic cluster layouts and cached
graph exploration with compact architecture and impact summaries.
Make the browser-local agent explain the current selection proactively,
and add a Config panel with persisted daemon overrides, shared browser
preferences and a reference for external configuration inputs.
Validation: 182 focused frontend tests and TypeScript passed. Reused the
recorded production build and 485 passing native checks on unchanged
source. The pre-existing capped-layout loading-note test failure remains
documented separately; the full local CI ladder was waived.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Three detection defects kept `codebase-memory-mcp install` from
configuring agents people run, and made it configure one they never
installed.
OpenCode without a config file or a CLI on PATH (#1167, #1180).
OpenCode was detected only from its global config file or directory,
OPENCODE_CONFIG_DIR, or an `opencode` found on PATH. It now also counts
as installed when its data directory exists: ~/.local/share/opencode on
every OS, %USERPROFILE%\.local\share\opencode on Windows
(opencode.ai/docs/troubleshooting, "Storage"; the same page names it as
the global config location of older installs). The OpenCode CLI and the
Desktop app both create it -- the Desktop's bundled opencode-cli server
uses the same XDG paths (anomalyco/opencode packages/core/src/global.ts
creates the config and data dirs at startup;
packages/desktop/src/main/sidecar.ts only redirects XDG_STATE_HOME) --
so detection no longer depends on PATH. The install target
~/.config/opencode/opencode.json(c) -- %USERPROFILE%\.config\opencode
on Windows per the same docs page -- is unchanged and right for CLI and
Desktop alike. A PATH longer than 4 KB, which hides every CLI from
find_in_path(), is handled separately by PR #2381.
Hermes home on Windows (#1180). Native Windows Hermes -- the install.ps1
CLI, the MSIX package and the Desktop app -- defaults HERMES_HOME to
%LOCALAPPDATA%\hermes and falls back to a legacy ~/.hermes only while
that directory is absent (NousResearch/hermes-agent
website/docs/user-guide/windows-native.md, "Data layout";
apps/desktop/electron/data-paths.mjs, resolveDesktopHermesHome). cbm
probed and wrote ~/.hermes only, so a Desktop install was never detected
and a Hermes found on PATH got its config.yaml and skill in a home it
never reads. On Windows the home now resolves to
<home>/AppData/Local/hermes unless only ~/.hermes exists, using the
home-derived AppData convention of the existing Zed, goose, Kilo and VS
Code probes; detection, install and uninstall all follow it. HERMES_HOME
still wins, and macOS/Linux keep ~/.hermes.
Claude Code from a bare ~/.claude (#1180). Any ~/.claude directory
counted as a Claude Code install, so a user who only had the folder got
hooks, skills and MCP entries for a client they never installed.
Detection now needs what Claude Code itself leaves behind: settings.json
in the config dir, .claude.json in the home (in CLAUDE_CONFIG_DIR when
set), or the claude CLI.
Proof on macOS against synthetic HOME/cache/runtime dirs with a minimal
PATH (`install --dry-run --skip-binary`, then a config-only install):
bare ~/.claude main: Claude-Code fix: none
~/.local/share/opencode only main: none fix: OpenCode
In the OpenCode case the fixed install writes the codebase-memory-mcp
entry to ~/.config/opencode/opencode.json; main writes nothing. Controls
(a launched Desktop layout, a real Claude user) are detected by both.
The Windows Hermes home is covered by a platform-parameterised resolver
test that runs on every host plus a _WIN32-bound end-to-end detection
and plan test.
Tests (cli suite, 335 passed): seven new tests; five fail on main three
times out of three (the _WIN32-bound Hermes test and the look-alike
control are green on macOS by design). Reverting the Claude+Hermes half
and the OpenCode data-dir probe separately turns exactly their own tests
red. Nine existing Claude fixtures that used a bare ~/.claude as the
install marker now write .claude.json; two Hermes tests and smoke-test
8x expect %LOCALAPPDATA%\hermes on Windows.
Refs #1167Fixes#1180
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
cbm_toml_upsert_managed_block and cbm_toml_remove_managed_block treated
everything between the "# >>> codebase-memory-mcp MCP >>>" markers as
ours: install replaced the whole span with the fresh block, uninstall
deleted it, and the conflict check skipped that same span. When our block
ended ~/.codex/config.toml, Codex Desktop appended its own tables below it
while the closing marker stayed the last line, so [mcp_servers.node_repl],
[desktop] and the [marketplaces.*] tables sat inside the markers. The
0.10.4 -> 0.11.0 upgrade deleted all of them, together with the
startup_timeout_sec the user had added to our own table.
The span is now read as TOML sections, each classified against the tables
the block declares:
- owned: a declared table (the k-th [[element]] of a declared array). The
keys the block writes are replaced; every other key, comment and blank
line in it stays in the table.
- attached: a sub-table of a declared table, such as
[mcp_servers.codebase-memory-mcp.env]. It is part of our server entry
and stays with it; outside the markers it would collide with the next
install.
- foreign: any other table, moved byte for byte and in order to just after
the closing marker, so from then on the markers bracket only our entry
and later appends land outside them.
- lead: lines above the span's first table, moved above the opening
marker, where they keep the table they belong to.
Uninstall of the Codex, Grok and Kimi blocks goes through the new
cbm_toml_remove_managed_block_owned with the header each block declares:
it removes our table with its keys and sub-tables and leaves everything
else in place. cbm_toml_remove_managed_block keeps the historical
whole-span contract.
Content whose ownership cannot be decided fails closed with the file
untouched: a second copy of a declared table, an undeclared extra
[[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,
and a rewritten file whose tables conflict with the block.
Preserving was chosen over failing closed on every foreign table because
Codex keeps appending below a closing marker that ends the file. A
refusing installer would block every later install and uninstall until
the user hand-edits the TOML, and a hand edit is itself the likeliest way
to lose those tables. Moving whole sections keeps every byte and every
key's table, and the shapes that cannot be attributed still refuse.
Without foreign content the output is byte-identical to the old rewrite.
Fixes#2228
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Distilled from #1245 by Andrew Hundt (d030c8f4).
cbm_mcp_get_int_arg read integer arguments with yyjson_is_int and
yyjson_get_int, and the int cast inside get_int truncates. A client
sending {"limit": 4294967297} -- 2^32 + 1 -- got back 1: the low word of
the value, silently, as a bound. The same read serves limit and offset
on the query tools, so an oversized page request became a page of one.
The argument is now read as a 64-bit signed or unsigned integer and only
accepted if it fits in int; anything outside the range takes the
caller's default, exactly as a non-integer does. In-range values and
non-integer JSON behave as before. One difference from the upstream
hunk: the unsigned comparison casts INT_MAX explicitly rather than
relying on the implicit conversion.
RED before the fix:
mcp_get_int_arg FAIL tests/test_mcp.c:1777: val == 1, expected 17 == 17
The test now covers 2^32 + 1, its negative, INT_MAX + 1 and INT64_MIN
each returning a distinct default, and INT_MAX, INT_MIN and -7 passing
through unchanged.
GREEN after: mcp 318 passed, 4 skipped (the Windows-only skips);
mcp cli daemon_application 692 passed, 0 failed.
Co-authored-by: Andrew Hundt <ATHundt@gmail.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Distilled from #1245 by Andrew Hundt (upstream b835b5e8), re-derived on
main's cypher.c rather than cherry-picked -- the file has moved ~9k lines
since the branch point.
The WHERE clause runs twice: once early, on seed rows where only the
first alias is bound, to prune; and once late, when every alias is bound,
to decide. The early pass used the same two-valued evaluator as the late
one. That evaluator answers "true" for a comparison on an alias it cannot
see -- the permissive default that makes the late pass work -- but NOT and
XOR invert whatever they are given, so
MATCH (a)-[:CALLS]->(b) WHERE NOT b.name CONTAINS "x"
evaluated NOT(true) on every seed and pruned every row. Zero results, no
error, for a query that is correct.
The early pass now uses a three-valued evaluator. A condition on an alias
that is not yet bound is UNKNOWN; NOT of UNKNOWN stays UNKNOWN; AND and OR
short-circuit only on a definite operand; XOR with any UNKNOWN operand is
UNKNOWN. Only a definite FALSE prunes. The late pass is unchanged and
still gives the final two-valued answer, so nothing that was correct
before changes.
Three deliberate differences from the upstream diff:
- the unbound-alias rule lives in one leaf, eval_condition_partial, so
the expression-tree path and main's legacy flat AND/OR path cannot
drift apart;
- that leaf guards c->variable == NULL. On main a condition whose left
side is a function of literals, coalesce(0, 1) >= 2, carries no
variable at all; the upstream version would have passed NULL to
strcmp;
- the flat path keeps main's rule that an empty condition list is true.
RED before the fix, all four with row_count == 0, expected 1:
cypher_exec_where_not_on_relationship_target,
cypher_exec_where_mixed_alias_and, ..._or, ..._xor. GREEN after: cypher
208 passed; cypher + mcp 526 passed, 4 skipped (the Windows-only skips).
eval_expr_partial recurses and is added to CBM_RECURSION_WHITELIST.
Co-authored-by: Andrew Hundt <ATHundt@gmail.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
The cache directory holds two internal SQLite stores next to the project
indexes: the user's settings (_config.db) and the cross-repo store
(_cross_repo.db). cbm_list_indexes, cbm_remove_indexes and
count_db_indexes matched every "*.db" there. As a result:
- install --reset-indexes and uninstall (when index deletion is confirmed)
deleted the user's config (every `config set` value silently reverted
to its default) and the cross-repo store along with the indexes;
- the "Found N index(es)" listing and count over-reported by up to two.
pass_cross_repo.c already excluded both stores by exact filename, but in
its own copy of the check. Centralise the rule in foundation/str_util:
cbm_is_internal_cache_db() (exact names, so a real project whose name
starts with "_" or contains "config" is still an index) and
cbm_is_project_index_db(). Every enumeration of the cache directory's
.db files (list, count, remove, cross-repo target scan) now calls it, and
cbm_config_open() builds its path from the same CBM_CONFIG_DB_FILENAME
constant.
Proof on a real isolated cache (one indexed Go repo, `config set
auto_index true`, a _cross_repo.db present):
before: "Found 3 index(es)", "Removed 3 index(es)", cache left empty,
`config get auto_index` -> false
after: "Found 1 index(es)", "Removed 1 index(es)", _config.db and
_cross_repo.db kept, `config get auto_index` -> true
Test: cli::cli_index_enumeration_skips_internal_cache_dbs (RED on main,
green with the fix, RED again on revert).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
v0.11.0 corrected the ten query tools reported in #2118, but two entries
in TOOL_ANNOTATIONS still advertised the wrong behaviour in tools/list:
- get_file_outline was {readOnlyHint:false, destructiveHint:true}. It was
added after the read-only split and kept a conservative default, yet it
reads through the same non-mutating resolve_store() query path as
search_graph and friends and never writes.
- ingest_traces was {readOnlyHint:false, idempotentHint:false}. Its
handler only parses and counts the traces array (edge creation is not
implemented), so it writes nothing and is idempotent.
Clients that gate auto-approval on these hints prompted for, or skipped,
two safe tools. Both are now read-only, non-destructive and idempotent.
The handlers that write user-visible state (index_repository, manage_adr,
delete_project) keep their annotations unchanged.
A new test walks the registered tool list (cbm_mcp_tool_count /
cbm_mcp_tool_name) rather than a mirrored table and asserts that only an
explicit mutator allowlist may clear readOnlyHint and only its destructive
subset may set destructiveHint, so a newly added tool cannot inherit a
wrong default unnoticed. The exact-value table test is updated to match.
Refs #2118
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Spill mode was entered only DURING extraction, when the charge crossed
budget - budget/16, and the final sweep at extraction end ran only if that
latch had already fired. A run that ended extraction just under the latch
kept every result in memory, and the phases that cannot spill -- registry
build, cross-LSP prepare (all_defs, per-language registries, surface rows,
module index) and resolve (edges into the graph buffer, cross-LSP appends
into the cached results) -- then grew the process well past the budget.
openclaw at 8 workers with a 4079 MB budget: 3678 MB charged at extraction
end, 4076 after registry build, 4933 after cross-LSP prepare, 5829 in
resolve (+43 %). The same repo at 18 workers latched during extraction and
stayed under budget.
Extraction end now projects the post-extraction growth from the result
counts (defs, calls + usages, files) and enters spill mode when charged +
growth would cross the latch, so the existing final sweep parks every
cached result before registry build. The per-unit costs (1280 B/def,
160 B/ref, 8 KiB/file) are fitted on the measured charge growth from the
parallel_extract to the parallel_resolve mark on five local corpora
(go, django, kotlin, rust, php) and cover openclaw; the model under-reads by
at most 7 % (inside the budget/16 margin) and over-reads by up to 46 %, the
safe side: a spill never changes graph content. The decision is a pure
function of counts (no RSS-window sampling) and is logged as
mem.post_extract.projection.
A charge test seam (cbm_mem_set_charged_for_tests) pins cbm_mem_charged(),
which otherwise reads the process footprint, so the "ended just under the
latch" case is testable deterministically.
Proof (release build, M5 Pro, CBM_WORKERS=8, peak charged = the budget
metric's high-water mark):
go, CBM_MEM_BUDGET_MB=2000 before: extract 1348 -> registry 1497 ->
lsp_prepare 2168 -> resolve 2660 MB (+33 % over budget, no spill)
after: projection charged 1335 + growth 1909 > line 1875 -> spill,
21,882 results parked; extract 413 -> registry 558 -> lsp_prepare 1151
-> resolve 1297, semantic 1746 MB peak: every phase under budget.
Node/edge dumps byte-identical (335,191 nodes / 1,813,857 edges); wall
29.2 s vs 29.0 s.
go, 40000 MB (generous): decision=keep, no spill, identical dumps, wall
27.4 s vs 27.5 s.
django, 400 MB: resolve mark 455 -> 277 MB after the spill, dumps
identical; the remaining peak (476 MB) is the semantic pass's retained
set on top of the graph floor, which this change does not address.
Refs #2184
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Upgrading from v0.10.8 to v0.11.0 on a machine with OpenCode reported all
three OpenCode subagent profiles as "preserved modified profile" plus an
op=agent_install error each, and the activation stopped ("one or more agent
configurations failed; the published/current executable was kept"), although
nobody had edited those files.
Root cause: #1933 (v0.11.0) added the tool_search / tool_search_regex
permissions to the rendered OpenCode profile. Install and uninstall recognise
a profile as ours only when it matches the current rendering or one of the
known released renderings (the other access mode, the v0.9.1-rc.1 Codex
shape, the pre-tier Verify file). The v0.10.8 OpenCode shape was not in that
set, so cbm_text_migrate_owned_document classified the untouched v0.10.8
files as user-modified. Reproduced end to end: install with the v0.10.8
release binary, then install with v0.11.0/main, into an isolated HOME; the
three profiles are 1729/1880/1910 bytes, the same sizes as in the report.
cbm_render_graph_profile_opencode_v0108() renders the pre-#1933 shape
(both access modes), and install/uninstall now list it as a released
rendering, so those files are upgraded in place and uninstall removes them
as owned. A profile the user actually edited is still preserved. The
released-list assembly that install and uninstall duplicated moves into one
helper, and the two legacy renderers share one implementation (cli.c drops
three raw free sites; the memory-core baseline is tightened 173 -> 170).
The Codex and OpenCode op=mcp_install errors in the same report do not
reproduce from a pristine v0.10.8 config and depend on the reporter's own
config.toml / opencode.json; they are not addressed here.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
A client refused because another CBM build owns the account daemon printed
only "Close all CBM sessions and commands, then retry." The reporter had a
0.10.3 daemon kept alive by a running Codex session while starting 0.11.0
from a terminal, and nothing in the message said which process that was,
that an agent session held it, or that `daemon stop` exists.
The refusal itself is correct and stays unchanged: session-managed daemons
serving live sessions must never be killed by a newer client, and
cbm_daemon_conflict_format() is validated byte-for-byte across generations
on the HELLO wire, so its text cannot change without breaking old/new
daemon pairs.
The fix adds a separate, client-side remedy sentence built from the
cross-build STATUS probe (cbm_daemon_conflict_remedy_format): active daemon
pid, version, permanent vs session-managed, "already stopping", the pids of
the CBM sessions holding it, the likely cause (another editor or agent
launched a different install; compare `which -a codebase-memory-mcp` with
each client's MCP config) and `daemon stop` once no session uses it. When
STATUS does not answer, the remedy points at `daemon status`.
It is appended on every user-facing conflict exit: the MCP/CLI bootstrap
path (after the older-permanent auto-drain policy declines), the one-shot
CLI exact-build cohort refusal and the MCP client cohort refusal (the path
the reporter hit). Hooks skip the extra probe to keep their fail-open
budget. The probe uses the `daemon status` budget (3 s): the daemon hashes
the ~300 MB peer image before answering, which overran the 1 s connect
budget in the real-binary proof.
No identity or admission check changes; STATUS is already the
authenticated, cross-build observability op behind `daemon status`.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Distilled from #1789 by Ulises Millan Guerrero, unchanged except for the
five openspec/ scaffolding files that could not land.
The indexing pipeline already logged its own phase error when artifact
export failed after publication, but the MCP failure path returned the
generic "Pipeline failed. Check repo_path" regardless. A caller whose
export failed was told to check a repository path that was fine, while the
one log line naming the real phase sat somewhere they were not looking.
The fix carries the failing phase out of the pipeline and into the MCP
error, so the message names artifact export when that is what failed. The
existing fail-hard contract is preserved -- this changes what the caller is
told, not whether the run fails.
Why this is a distill rather than the original: five of the nine files in
on main, no other contributor uses it, and adopting a spec framework is a
project-level decision rather than something that rides in on a bug fix.
That was explained on 2026-09-02 and the code half was approved on merit
the same day; the scaffolding is the only reason it did not land then.
Co-authored-by: Ulises Millan Guerrero <ulises.millanguerrero@gmail.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
cbm_registry_add takes the symbol's `name`, discards it, and derives the
bare-name lookup key from the QN's last dot segment. That makes the QN's tail
load-bearing for the by-name index every language shares, and for one grammar
the tail is not a name anybody writes. rust_cfg_qualified_name mints a
`#[cfg(test)]` twin as "proj.lib.add#cfg(test)"; simple_name() has no '#'
handling, so that function is filed under the whole string "add#cfg(test)",
which no bare `add` callee can reach, leaving a test-only twin of a resolved
function absent from the by-name index entirely.
The caller always knows the name, because it is the argument. So the index
takes a second key from it, only where the derived key carries a fence:
const char *derived = simple_name(qualified_name);
index_under_name(r, derived, owned_qn);
if (name && name[0] && strchr(derived, '#') && strcmp(name, derived) != 0) {
index_under_name(r, name, owned_qn);
}
The gate keys on the fence rather than on the file's language, and that is the
part worth reviewing. It makes "unchanged for every other grammar" checkable:
the derived key is written unconditionally exactly as before, and every by-name
lookup keys through simple_name(), which splits on '.' and "::" only. A passed
name that differs from the derived key by anything other than a fence is
therefore a key no lookup can reach, so adding it would only widen the bucket
the scorer walks. A grammar that mints no '#' sees no new key at all.
Two of the rows a language gate would have had to cover turn out not to reach
this function. Registry membership is decided by cbm_label_is_registry_symbol
at all three production callers (pass_definitions.c, pass_parallel.c,
pipeline_incremental.c), and it admits neither "Module" nor "Section". So a
file's Module node never registers, and neither does a Markdown heading. What
does register, under label "Class", is the dotted-name direction:
grammar def->name QN tail
HCL resource.aws_instance.web web
TOML tool.poetry.dependencies dependencies
INI tool.isort isort
These are why the derived key stays unconditional. `instance =
aws_instance.web.id` reaches the block through the tail `web`, so re-keying the
index on the passed name would drop that edge outright. The fence gate leaves
all three byte-identical.
`name` is NULL or empty only for callers that have no symbol name to give;
those have the derived key and nothing else.
tests/test_registry.c: registry_indexes_by_passed_name_not_qn_tail resolves a
bare `add` against a cfg-fenced QN and is the reproducer, failing without this
commit. registry_indexes_a_dotted_name_under_its_tail_too pins the unconditional
derived key for the HCL and Module shapes.
tests/test_pipeline.c: pipeline_hcl_block_reference_resolves_to_its_block indexes
a two-resource Terraform file end to end and asserts the surviving USAGE edge.
The latter two pass without this commit and are guards: what would break them is
re-keying the by-name index, and an HCL block name is dotted where its QN tail is
not, so they pin the shape that regression would take.
A throwaway probe walked tests/grammar_cases.h (one fixture per grammar, all 162)
comparing def->name with simple_name(def->qualified_name), then targeted fixtures
for the dotted shapes above. HCL is the only fixture-level mismatch among
registry-eligible labels; TOML and INI mismatch on targeted fixtures. XML
namespaced elements (`ns:root`) do not mismatch, because ':' is not a QN
separator.
Signed-off-by: Chad <4307099+BobbieBarker@users.noreply.github.com>
cppcheck 2.20 (the version the lint job pins) reports
knownConditionTrueFalse on two comparators in src/mcp/mcp.c whose
tie-breakers compare one strcmp result after another, each call with
inline "x ? x : \"\"" fallbacks. Neither function differs between these trees; which of
them is flagged depends on the rest of the lint source list. With
scripts/lint.sh --ci and cppcheck 2.20.0 built from source:
- main itself fails on search_result_cmp ("file_order != 0 is always
false");
- adding one more language grammar and its sources moves the finding
to project_record_compare ("by_root != 0 is always false");
- carrying each comparator's order in one variable instead still fails,
now as redundantAssignment on project_record_compare.
Both comparators now call nullable_strcmp(), which orders NULL like ""
exactly as the inline fallbacks did. lint-cppcheck passes again on
main and with the additional sources. Comparison order and results are
unchanged for every input.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Sarlette <282189207+SarletteD@users.noreply.github.com>
When a call resolved to a GraphQL client, emit_graphql_edge named the
Route after the whole first string argument, stripping only a leading
"query " or "mutation " (the mutation strip was also one byte short, so
names kept a leading space). An anonymous `query { ... }` therefore became
one long Route, and even a named operation carried its variables and
selection set in the name ("GetUser($id: ID!) { user(id: $id) { name } }").
Every distinct operation text minted its own Route node, and names were
cut off at 256 bytes.
Add cbm_service_pattern_graphql_operation(), a small GraphQL document
scanner. It skips comments, strings, block strings, `${...}` template
interpolations and leading fragment definitions, and reports the first
operation's type and name without copying any operation text. Routes are
now keyed as follows:
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, bare word, no string argument)
Keys are deterministic and bounded by the GraphQL Name grammar. The
GRAPHQL_CALLS edge keeps "operation" (now the Route name) and gains
"operation_type". The old fallback to the callee name ("client.query")
is gone: a callee is not an operation.
The sequential path (pass_calls.c) emits no GRAPHQL_CALLS at all, so it
had no copy of this logic to fix.
Proof on graphql-python/gql (374a70df, Python GraphQL client, index-only):
GraphQL Routes 170 -> 16, longest QN 266 -> 34 bytes, 106 -> 0 Routes
carrying operation text. GRAPHQL_CALLS 2643 -> 1158 with the same 984
distinct callers: edges are one per (caller, operation) pair, so calls
that used to hit distinct text-keyed Routes now share their operation's
Route.
Tests (edge_types_probe): graphql_route_keyed_by_operation_name_issue598
asserts the exact GraphQL Route set (QN + name) on the parallel path.
graphql_operation_identity_parser_issue598 covers braces inside comments,
strings and interpolations, fragments before the operation, anonymous
operations with variables, name truncation and non-document arguments.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
RETURN DISTINCT projected up to the engine row cap (max_rows, 100k by
default) and only then removed duplicates in rb_apply_distinct. A value
that first appeared past the cap was never seen. On a 150k-edge index
`MATCH ()-[r]->() RETURN DISTINCT type(r)` returned 21 of 22 types:
HAS_BRANCH, a single edge, was missing, and the result was flagged
truncated:true / engine_limit.
The projection loops (plain RETURN, RETURN *, RETURN * after WITH) now
de-duplicate while projecting, through a hash set of length-prefixed row
keys. The cap therefore counts distinct rows. Memory stays bounded by the
cap: only admitted rows are remembered. Once the cap is full, the rest of
the bindings are only probed (no insert), to decide whether a new
distinct row exists, which is when `truncated` is set. An explicit LIMIT
on DISTINCT now also counts distinct rows and can stop the projection
early. ORDER BY and SKIP/LIMIT keep running after DISTINCT on the
already-distinct rows. The O(n^2) post-pass remains only for aggregate
rows, which are distinct by group key.
Proof on django (55,377 nodes / 294,528 edges, 23 edge types in
get_graph_schema), same index, before vs after:
before: 22 types, HAS_BRANCH missing, truncated:true engine_limit
after: 23 types, truncated:false (same 5.3 s wall time)
Test: cypher_return_distinct_counts_distinct_rows_against_cap_issue1364
(rare type past a max_rows=5 cap; ORDER BY, SKIP/LIMIT and LIMIT variants;
more distinct rows than the cap still reports truncated).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
The supervisor creates the worker's response file before spawning it. A
worker that exited 0 without writing that file left it empty, and
slurp_worker_response read the empty file as "" with status OK. The run
then counted as a SUCCESS with an empty response (the daemon marked the
job successful). The clean-exit branch of worker_terminal_log also
deleted the worker log, the only record of where the run stopped. Only
an oversized response was treated as a failure.
- index_supervisor: an empty response file is WORKER_RESPONSE_READ_EMPTY.
A clean exit with no readable response sets response_missing, keeps the
worker log, records its path, and records the last structured event
the log holds (text or JSON format, last 64 KiB) as last_phase. It is
logged as index.supervisor.no_response with the log path and the last
phase. The outcome stays CLEAN, so the disposition is FALLBACK: an
explicit error, with no in-process fallback and no recovery re-run of a
worker that did not crash.
- mcp: cbm_mcp_index_worker_no_response_failure builds the error
(reason "no_response", last_phase, worker_log, hint). It is used for
the first attempt and for a recovery run.
- daemon application: the job failure message says the worker exited
cleanly without writing a response, and gives the last phase and the
log to inspect.
- pipeline_incremental: the legacy per-file purge loop now logs
incremental.purge.start (changed/deleted counts) and
incremental.purge.progress. Progress lines carry counts only, use a
ceiling stride (at most ~20 lines plus the final one) and never log one
line per file. Before this, nothing was logged between
incremental.edge_snapshot and incremental.purge.
Tests (RED before, green after, RED on revert):
- index_supervisor_clean_exit_without_response_is_named_failure_issue1300
(a real worker subprocess logs a phase and exits 0 without a response)
- daemon_application_clean_exit_without_response_is_named_failure_issue1300
- incr_purge_reports_bounded_progress_issue1300
- index_supervisor_clean_exit_without_response_response_issue1300 (the
contract of the response builder)
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
With persistence=true, indexing a repository under a CJK path on Windows
made the worker exit nonzero and no .codebase-memory/graph.db.zst was
written, while an ASCII junction to the same directory worked.
Root cause: write_file_atomic() -- used for artifact.json, graph.db.zst
and the import temp db -- opened its temp file with the raw CRT fopen()
and published it with MoveFileExA(). Both go through the ANSI code page,
so a repo path containing characters outside it cannot be opened. The
same file had two more ANSI calls on the same flow: cbm_artifact_exists()
used stat() on the repo path, and the import published the cache db with
CRT rename(), which is ANSI and also fails when the destination exists.
Fix: use the repo's UTF-8 helpers -- cbm_fopen() for the temp file,
cbm_rename_replace() (MoveFileExW, write-through, replace-existing) for
both publishes, and a cbm_fopen() probe for the non-empty existence
check. rename_temp now reports errno on every platform (cbm_rename_replace
translates the Win32 error).
Test: artifact::artifact_roundtrip_non_ascii_paths exports from a CJK
repo directory, checks cbm_artifact_exists(), and imports twice into a
CJK cache directory (the second import replaces the existing db).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
watcher_unwatch_drains_pending_free failed three times on macos-14 CI
with `index_call_count == 0, expected 1` at its dirty-poll precondition.
That precondition needs every git subprocess of one poll (rev-parse
HEAD, status, submodule foreach) to succeed. A transient probe failure
(spawn refused under runner load, a non-zero exit) makes that poll a
fail-closed no-op by design: #937 leaves the baseline uncommitted and
the next poll retries. Several of those paths return without a log
line, which matches the CI output exactly: watch, baseline, FAIL, with
no watcher.changed and no watcher.git.failed. Holding a spawn failure
with cbm_subprocess_force_spawn_eagain_for_testing reproduces that
output deterministically. This is a test race, not a production defect.
The precondition was also unrelated to the contract under test. A poll
that stopped draining would neither crash nor leak, because
cbm_watcher_free frees the same deferred list. So the old test could not
see a broken drain at all.
Add a test-only seam, cbm_watcher_test_pending_free_count, and assert
the stable states the watcher holds: 0 parked before unwatch, 1 after,
0 after the next poll with no index work, and still 0 after a further
poll. No assertion depends on a git probe succeeding. Dirty-poll
reindexing stays covered by watcher_detects_dirty_worktree and
watcher_modify_tracked_file.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Resolve the RUN_TEST list conflict in tests/test_daemon_application.c by keeping both sides' new tests.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
The comment on CBM_EXTRACT_BUDGET called it a "maximum byte budget", but
every call site passes it as cbm_extract_file*()'s timeout_micros, which
cbm.c converts to nanoseconds and uses as a per-thread CPU-time deadline
(5 s) with a 12x wall-clock ceiling as a backstop for a stuck parse. No
code path uses the value with the wrong unit; only the documentation was
wrong.
Correct the constant's comment, and bring the timeout_micros description
in cbm.h up to date (CPU time + wall backstop, not a plain timeout) and
back onto cbm_extract_file(), from which later additions had separated it.
No behavior change; the budget value is unchanged.
Reported-by: BobbieBarker
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
index_repository blocks until the whole index completes. MCP clients with
a per-call deadline (Copilot for IntelliJ) give up on a large repository;
their cancel drops the daemon job's last subscriber, the daemon cancels
the worker, and every retry starts over, so the index never finishes.
Add an opt-in async mode and a status query to the same tool; the default
synchronous behaviour is unchanged:
- async: true starts the project's index job in the daemon, or joins the
one already running for it, and returns at once with its state. The
application holds one subscriber reference for an async job until its
terminal publish, so the request returning, the client cancelling or
the starting session closing no longer cancels it. Only daemon shutdown
(or the final session of a non-permanent generation) ends it. Async
requests never queue behind the physical job limit; a full daemon
answers busy. async/status are stripped from the worker args, so an
async request coalesces with an identical synchronous one.
- status: true reports the running or last job for the project
(queued/running/cancelling/succeeded/failed/cancelled, started_at,
finished_at, error summary) from a small per-project record kept in the
daemon's job registry after the job itself is reaped. An unknown
project is an error; a project indexed before this daemon generation
reports idle. No freshness key is added: index_status keeps the #1561
freshness object.
- async + status together, non-boolean values, and async with
cross-repo-intelligence are refused. In-process servers (index worker,
embedders) refuse both modes: nothing there outlives the call.
- On a temporary (non-permanent) daemon, async is refused when the
request arrives on the one-shot `cli` tool channel and that session is
the daemon's only live session: the daemon would stop and cancel the
job the moment the command exits. The error points at `daemon start`
(or an open MCP session). A long-lived MCP session stays a valid host
even when it is the only one, which is the IDE case this exists for;
status stays allowed everywhere. The daemon lifecycle is unchanged.
- New allocations go through the memory core (cbm_alloc/cbm_calloc/
cbm_mem_strdup/cbm_free); blocks returned by non-core APIs are released
with safe_free, so no file's raw allocator count grows.
- A cut-short synchronous call now offers the async alternative: in the
cancellation text the daemon or frontend delivers (including the
-32800 reply to a cancelled index_repository), and, because a timed-out
client never reads that reply, as a notice on the next index_repository
or status call for the project.
- The tool description and schema, the CLI help and the README explain
the flags, the deadline problem and the polling pattern.
No server-side timeout or budget is introduced.
Tests (deterministic, held fake worker, bounded observation waits):
async returns before completion and status observes running then
succeeded; an async job survives its session closing while a sync job in
the same shape is still cancelled; validation errors; the cancellation
reply and the next-call notice carry the advice; a lone one-shot client
of a temporary daemon is refused async while status and an MCP session
on the same daemon are allowed; in-process refusal; schema; notice
helper.
Refs #2031Fixes#2144
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
`install` on a Hermes Agent config wrote the mcp_servers entry and the skill,
then failed op=pre_llm_hook_install on the same config.yaml. The stock Hermes
config (cli-config.yaml.example) reproduces it on its own.
Root cause: the nested-sequence editor behind the hooks.pre_llm_call item
validated EVERY line of the document and refused any flow collection or block
scalar anywhere. The stock config carries flow sequences in sections the hook
edit never reads or rewrites (`platform_toolsets:` -> `cli: [hermes-cli]`,
reporters' `plugins:` -> `enabled: [...]`). The mapping-entry editor that
writes mcp_servers into the same file already treats other top-level sections
as opaque user content, which is why that op succeeded.
Fix: yaml_sequence_validate_document now validates only the top-level section
the edit descends into (the first sequence_path key). The root mapping is
still validated at parse time, so section boundaries stay sound. An absent
section is appended as a new top-level key and touches no existing line.
Inside the edited `hooks` subtree the fail-closed rules are unchanged. This
also unblocks uninstall (op=pre_llm_hook_uninstall), which shares the analyzer.
Tests: new config_yaml_edit case with foreign flow sequences plus `|`/`>`
block scalars (install, byte-idempotent reinstall, remove). The two #1924
"still refuses" pins now place the unsupported construct inside `hooks:`,
where the refusal still applies byte-identically.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
The --show-prefix reader added a raw free(), growing src/mcp/mcp.c past
its memory-core ratchet (784 -> 785). HEAD, base and prefix now share
detect_read_rev_parse_line (read, drop a trailing CR, validate, copy,
free), which removes the two per-record frees in handle_detect_changes;
mcp.c is at 783. Validation and read order are unchanged.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
pc_module_var added a third compute-QN / find_by_qn / free sequence to
pass_calls.c, growing its memory-core ratchet (23 -> 24). Route all three
through pc_find_by_computed_qn, which leaves 22 raw sites, and ratchet the
pass_calls.c baseline down to match.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
normalize_project_arg now decides once which of the selector and its
normalized form to keep and releases the other through the single existing
free(), instead of a separate encode_bare_project_arg with two more raw
frees. cbm_project_name_sanitize drops its redundant "root" early return:
NULL and "" already reach the empty-after-trim "root" return. Behaviour is
unchanged; mcp.c and fqn.c are back at their baselines (784 / 23).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
The no_targets early return added a second raw free(project) next to the
existing result.failed one, growing src/mcp/mcp.c past its memory-core
ratchet (784 -> 785). Fold both into one branch that picks the message;
no_targets still takes precedence and both texts are unchanged.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
A 4.7 MB binary Godot resource (piko_walk_mesh.res) never finished
indexing: `.res` maps to ReScript, so the resource was parsed as ReScript
source and the definitions pass spun. Three defects, each fixed:
1. Quadratic usage walk (the hang). The ReScript `let` binding check
(is_first_named_part_of, shared with Julia, Typst, Elm, PureScript
and Nickel) climbed from every named leaf with ts_node_parent, which
descends from the root and scans each level's children. A binary
file parses into a flat error tree (~170k root children per MB), so
each climb cost O(root children) and the file O(n^2): 1 MB spent
46 s in cbm_extract_unified, 4.7 MB never returned. The check now
climbs the unified walk's own cursor (O(1) per hop), like the other
occurrence classifiers; the node-based climb stays only for callers
outside the walk. 1 MB: 46 s -> 0.03 s; 4.7 MB: 2.2 s end to end.
2. Quadratic lexing in error recovery. tree-sitter retries the lexer at
every byte of an unparseable stretch with every external token
valid; the ReScript scanner's template-string loop then ran to the
next backtick/$/backslash/NUL (end of file if none) and discarded
the result. That cost O(n^2) inside lexing, where the parse budget's
progress callback never runs, so such files were dropped by the
5 s CPU budget instead of parsed -- plain text too (100 KB of
non-ReScript text: 15 s -> 0.18 s). Local scanner patch: skip the
template branch when NEWLINE is also valid, which only the ERROR
state allows. Valid files parse to identical trees. Recorded in
vendored/grammars/MANIFEST.md.
3. Binary content parsed as source. `.res` is also Godot's binary
resource format and the Windows compiled-resource format. Following
the .m/.cls/.frm/.inc/.cfc precedent, cbm_disambiguate_res reads the
first 4 KB and reports a file holding a NUL byte as unsupported;
ReScript text never contains one.
Tests (deterministic work counters, no clocks):
- extraction::extract_rescript_let_bindings_use_the_walk_cursor --
zero root-descending parent hops at 128 and 1024 statements
(before: 515 / 4099).
- complexity::complexity_rescript_error_recovery_lexing_is_linear --
lexer bytes pulled through a chunked TSInput, 4 KB vs 8 KB, ratio
must be linear (before 3.99, after 2.00).
- language::lang_res_binary_resource_unsupported and
lang_res_rescript_stays_rescript.
Fixes#2176
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
A node variable carried in scope through WITH (`WITH f`, `WITH f AS g`,
`WITH f, count(r) AS refs`) was projected as a scalar virtual var: the
node's name in .name and the variable name in .qualified_name (used as
the owned storage for the binding's name), start_line 0. RETURN
f.qualified_name therefore returned the literal variable name "f" and
f.start_line "0"; only f.name was right. The aggregate path tagged the
stub with the node id so node_prop could re-fetch some fields, but the
re-fetch only ran for empty string fields, so the non-empty
qualified_name and the numeric start_line never reached it.
The aggregate path also grouped a node by its display name, so several
same-named functions collapsed into one row carrying one node's
properties and the summed count.
Fix:
- A bare, bound node item in WITH is now carried as a deep copy of the
node, bound under its AST-owned alias, on both the simple and the
aggregate path; every property then resolves exactly as it does
without the WITH. Unbound OPTIONAL vars and scalar items stay scalar.
- Aggregate WITH groups node items by node id, not name.
- Scalar virtual vars keep their owned alias string in .project (never
exposed as a property) instead of .qualified_name, so
n.qualified_name / keys(n) no longer return the variable name.
- WITH ... ORDER BY g.<prop> resolves the property on the carried node.
- The node_prop stub re-fetch heuristic is removed: nothing produces
id-tagged stubs anymore.
Tests (cypher suite): cypher_issue2208_with_agg_carried_node_props,
cypher_issue2208_with_agg_groups_by_node_identity,
cypher_issue2208_with_simple_carried_node_props.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
cross-repo-intelligence with target_projects ["*"] failed with "cross-repo
source or target project is missing, invalid, or not indexed" while naming
the same live targets worked.
Root cause: the wildcard enumerator and the pre-write validation both used
cr_project_exists(), which only does a read-only open plus the exact-project
check. A store indexed before the #768 edges.local_name_gen column passes
that (it still serves queries, so list_projects shows it), but the matcher's
read-write open (store init_schema) refuses it until a reindex. One such
legacy store anywhere in the cache therefore made every ["*"] run fail, and
it failed only after delete_cross_edges() had already removed the source's
previous CROSS_* generation, so a failed run was also destructive.
Fix: the #768 probe moves into cbm_store_edges_schema_current() (init_schema
now calls it too, one definition), and cr_project_exists() additionally
requires it. The wildcard skips a legacy store (logged as
cross_repo.project_unusable with the project name); naming one still fails,
but during validation, before any write. The probe is read-only, so the
legacy store is left untouched for its reindex.
Refs #2133
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>