Commit Graph
1930 Commits
Author SHA1 Message Date
Martin Vogel 426676b60b fix(graph): typedef'd C aggregates get nodes; member access binds by object type
Two defects that fed each other, fixed together because the first alone would
let the new Field nodes attract bare-name calls.

1. An anonymous aggregate under a typedef had no nodes.
`typedef struct { ... } X;` produced no Class node and none of its members a
Field node: the struct_specifier carries no name of its own, and
extract_class_def gave up on it. That is the dominant C spelling of a type
(37 of the 38 structs in internal/cbm/cbm.h). The enclosing type_definition
now names the aggregate through its declarator; only a plain type_identifier
declarator counts, since a pointer, array or function typedef names another
type. Applies to struct, union and enum specifiers in C and C++ (`.h` is
classified C++).

2. A C member access was resolved by its bare member name.
The member half of `a.b` / `a->b` reached the short-name registry as `b`,
which returned whichever Field (or function, or variable) was called `b`: on
this repository 9,150 USAGE and 2,810 WRITES edges onto Fields from C
sources, 3,976 of the USAGE edges onto a name several structs share.

The C LSP already types the object of a field_expression. It now publishes
the owner as a FIELD_REFERENCE row, one per (enclosing function, object type,
field): the pipeline edge is function -> Field, so a row per occurrence would
only add a record per member access. The usage and read/write resolvers
(sequential and parallel) join those rows by function and member name; a C
member name with no typed owner binds nothing.

Four things had to hold for the owner to be found:
- the cross-file registry folded Field defs into their owning type for Go
  only, so every C/C++ struct from another file (every header) registered
  with zero fields. The fold now covers C and C++;
- c_register_lsp_defs kept the first 63 fields of a type. It is sized from
  the list now: a cap there silently dropped edges onto later fields;
- a struct is registered under the header that declares it while the use
  site knows its short name. The owner type resolves as written, then
  module-qualified, then by short name from this module, a directly included
  header, or as the single candidate. Two same-named structs with no
  evidence between them resolve to nothing;
- the parallel resolver ran the cross-file pass only for files with
  unqualified call sites. A C member access or member call that still has no
  owner now requests it too.

Calls landing on a Field follow the same rule (cbm_call_onto_field_policy):
dropped across languages (the #1928 reference rule; a Bash `command` or a
Python `sorted()` is not a C struct member), dropped for a bare C call
(`socket(...)`, a function-pointer parameter), and bound by owner for a C or
C++ member call. Bare C++ calls and every other language are unchanged.

Measured on this repository, old binary vs new:
  C/H Class nodes                                         155 -> 1000
  C/H Field nodes                                        1047 -> 5478
  enumerators of formerly anonymous enums                +911 Variable nodes
  USAGE onto the new types, enums and constants          +23k edges
  USAGE -> Field from .c, owner type named in the file  58.1% -> 97.6%
  USAGE onto a non-Field, name only used as a member      146 -> 0
  WRITES -> Field from .c                                2981 -> 6534
  CALLS                                       159 removed, 3 added
  index wall time unchanged within noise; peak footprint +2.8%
  full macOS suite: 8309 passed, 0 failed, 10 skipped

Tests: extract_c_anonymous_typedef_aggregate_is_named_by_its_typedef,
pipeline_c_member_access_binds_field_by_object_type (+ _parallel),
call_onto_field_follows_language_and_shape,
c_member_access_binds_by_owner_only. Each was RED on the unchanged tree; the
pipeline tests are RED again with the call policy neutralized.

Not in this change: a function-pointer member declared inline
(`void (*f)(int);`) has no Field node; a `p->f()` call is not resolved (the
registry splits on `.` and `::` only); inline functions in `.h` files keep
the bare-name member binding; designated initializers are not typed.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-02 00:53:42 +02:00
Martin Vogel dd304b53e4 fix(daemon): keep an inline rejection that beats the client's HELLO
daemon_runtime_connection_cap_covers_slow_hello_and_stopping_is_terminal
failed ASSERT(capacity_rejected) seven times (TSan macos-14 x3, LSan
macOS x1, macos-15-intel x1, local plain macOS x2) and passed on rerun.
Two interleavings fail it; each was forced and fails 3 of 3.

1. Production race. At capacity (and while stopping) the accept loop
   answers a new connection WITHOUT reading its HELLO and closes it at
   once; on POSIX the reject drain is a no-op. A Unix-socket connect
   completes from the listen backlog, so the client can still be between
   connect() and its HELLO send when that close lands. The send then
   fails with EPIPE, cbm_daemon_runtime_client_connect returned a zeroed
   result (status ERROR, empty message), and the complete 810-byte
   rejection sat unread in the client's receive buffer. Forced by
   holding the client before its send until the daemon had closed:
   overflow status=0 message="", 810 bytes pending,
   active_connections=2, active_clients=1. A standalone AF_UNIX probe
   on macOS shows the same: send rc=-1 errno=EPIPE, then recv returns
   the 810 bytes, then EOF. Bootstrap then
   classified the attempt by lock state instead of by the daemon's own
   "capacity" / "stopping" answer, and the user-visible reason was lost.

2. Test window. The slow-hello connection held its slot only until the
   daemon's first-frame deadline (request_timeout_ms, 2000 ms in the
   fixture). A runner stalled that long freed the slot, and the
   active_connections == 2 conjunct read 1. Forced by waiting for that
   expiry before the overflow probe: freed after 2002 ms, capacity
   still reported, active_connections=1.

Fix: when the HELLO send fails, the client reads the answer anyway
through the new cbm_daemon_ipc_receive_frame_after_failed_send. A failed
send consumes no inbound bytes, so the inbound frame boundary is intact.
The function lifts the send-side poison for that one receive and
restores it afterwards. Only a REJECTED answer is accepted in that
state; anything else stays the plain send failure it always was. On
Windows a server close discards unread pipe data, so this path just
fails there as before. The bounded drain-before-close remains that
platform's mechanism.

Test rebuild (no timeout raised, no retry):
- cbm_daemon_runtime_hold_peer_waits_for_testing: the slow hello keeps
  its slot until the test closes it, and the Windows reject drain ends
  on the peer's close, not after 250 ms. Both counts are held states
  when they are read.
- cbm_daemon_runtime_set_hello_hook_for_testing: four points
  (client connected / sent, daemon rejecting / rejected) let a test pin
  the order. The existing test now pins "daemon answers after the HELLO
  is on the wire", which every platform delivers. The new
  daemon_runtime_capacity_rejection_survives_daemon_close_before_hello
  pins "daemon answered and closed before the HELLO" (POSIX only; it is
  compile-gated because Windows discards that data by design). Both
  assert that the pin really happened, and print the overflow result on
  failure.
- The waits end on guaranteed events (HELLO sent; rejection closed or a
  third slot admitted, the latter held by the seam), never on a bound.

Proof (macOS arm64, ASan/UBSan test-runner):
- forced late HELLO, current client: RED 3/3, identical signature;
  with the fix GREEN 3/3; fix reverted: RED 3/3 again;
- forced 6000 ms stall before the overflow probe (3x the deadline that
  freed the slot): slot still held, both tests GREEN 3/3;
- both pinned orders, 200 iterations each in one process: 400 passed;
- daemon_runtime suite alone, 50 sequential runs: 50 x 51 passed,
  0 failed;
- daemon_runtime under TSan (the venue of 3 sightings): 51 passed, no
  ThreadSanitizer report;
- daemon_ipc 54 passed (2 Linux-only platform skips), daemon_application
  67 passed; lint-ci clean.
Not run here: the Linux and Windows legs (the Windows path is
compile-gated and reasoned from the drain's documented contract).

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-02 00:52:13 +02:00
Martin Vogel 46a8f57f18 fix(ui): index job carries the resolved root, not the request spelling
POST /api/index resolves the root_path of the request into a 4 KB buffer,
but the index job kept the original request string in a 1 KB field. The
job, the worker log lines, the 202 reply and /api/index-status therefore
reported the request spelling instead of the resolved root, and a path
past 1023 bytes reached the daemon cut off.

Store the resolved path in the job, give the field the capacity of the
buffer it is copied from, and answer 400 for a path that would not fit
instead of storing a shortened one. The status listing's escape buffer
follows the new field size.

The job's downstream, application_background_index, re-resolves what it
receives, so a resolved input is a fixed point there and the daemon keys
the job by the same string the route worked with.

Tests drive the live route: a root outside a configured allowed root is
answered 403 and no job starts; a root spelled through a ".." segment is
stored and forwarded in resolved form; a root past 1 KB is either refused
or forwarded whole. The last case reaches the accepted branch on Linux
(PATH_MAX 4096); on macOS the path cannot resolve and the refusal branch
is asserted.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-02 00:42:05 +02:00
Martin Vogel fc70534e81 Merge pull request #2425 from DeusData/fix/trace-path-qn-fallback-leak
fix(mcp): free the empty name-lookup result before trace_path's QN fallback
2026-10-02 00:06:01 +02:00
Martin Vogel 7ddbe66542 fix(routes): compose the Laravel 11+ withRouting api prefix into Route paths (#1146)
Laravel 11+ registers its route files in bootstrap/app.php through
Application::configure()->withRouting(web: ..., api: ..., apiPrefix: ...)
and mounts every file passed as `api:` under `apiPrefix` (default 'api').
That prefix lives in a different file than the routes, so per-file
extraction -- which already composes the in-file Route::prefix()->group()
chain (#952) -- minted `GET /users/me` for a route Laravel serves at
`GET /api/users/me`. The Route qualified_name is the join key for
cross-repo HTTP matching, so real callers of /api/... never linked, and an
api route could silently merge with a same-path web route.

Fix: a small Laravel mount resolver, src/pipeline/laravel_routing.c. For
each PHP file that registers a path-shaped route, both route passes (the
sequential calls pass and the parallel resolver) look up the nearest
ancestor bootstrap/app.php once, parse it with the PHP grammar, and, when
its withRouting(api: ...) names that file, prepend the apiPrefix to every
Route minted from it. Only source facts are used: an `api:` entry must be a
__DIR__ / dirname(__DIR__) concatenation or a base_path() call over a
string literal (single path or array), and a given apiPrefix must be a
string literal. A non-literal apiPrefix, positional arguments or a
`using:` callback leave the paths untouched, the `web:` file is never
prefixed, and nothing is inferred from file names. The lookup keys only on
the repo path and the file path, so full, incremental and delta runs
compose the same identity.

Proof (origin/main 1f9b4db1 vs this change, same machine):
- krayin/laravel-crm @03ebedd7: GET /user -> GET /api/user; the other
  four Route nodes are unchanged.
- filamentphp/demo @d5b618a1: GET /user -> GET /api/user.
- laravelio/laravel.io @24be4893: the api.php POST '/' inside
  prefix('articles') was merged into web.php's POST /articles node; it is
  now its own POST /api/articles (39 -> 40 Route nodes, every web route
  unchanged).
- Cross-repo: a TypeScript client calling axios.get('/api/users/me') and
  axios.post('/api/orders') against a Laravel 11 server:
  CROSS_HTTP_CALLS 0 -> 2.

Tests (edge_types_probe): default api prefix plus the composed
qualified_name, a custom multi-segment apiPrefix with the array form of
`api:`, the `web:` file stays unprefixed, a Laravel <= 10
RouteServiceProvider control stays as it is, a non-literal apiPrefix is
left alone, and the parallel resolver with the app in a monorepo
subdirectory. The four bug tests were RED 3x before the fix, pass with
it, and go RED again with only the composition reverted.

Fixes #1146

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 22:57:48 +02:00
Martin Vogel bedbc0ac00 Merge pull request #2345 from DeusData/fix/issue-2127
fix(pipeline): never bind an external Python import to a same-named project symbol (#2127)
2026-10-01 22:38:18 +02:00
Martin Vogel 50a6a67b89 Streamline local agent controls and preserve proactive chat
Separate agent configuration from chat visibility, keep chat compact, and
resume selection explanations after manual questions. Restore project
conversations locally for 24 hours with bounded storage and clear history.

Move daemon configuration into System and report persisted index metadata
and live watcher registration alongside its configuration control.

Validated with 303 focused frontend tests, TypeScript/Vite production build,
160 native watcher/HTTP tests, regression checks, and local browser checks.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 20:24:06 +02:00
Martin Vogel 402dd7c59b fix(artifact): create .gitattributes through the UTF-8 path layer
Follow-up to the #1171 fix. Exporting an artifact from a repository under
a CJK path on Windows wrote graph.db.zst and artifact.json, but the
.codebase-memory/.gitattributes file carrying the merge=ours protection
was silently missing.

Root cause: ensure_gitattributes() created the file with the raw POSIX
open(O_WRONLY | O_CREAT | O_EXCL). On Windows that is the ANSI CRT, so a
repo path with characters outside the active code page fails with ENOENT.
The failure was only logged, and the warning itself was malformed: it
passed printf-style arguments to the key/value logger, which printed the
literal "msg=artifact.gitattributes.open_path=%s_err=%s <path>=<error>".

Fix: create the file with cbm_fopen(path, "wbx") (_wfopen on Windows).
The "x" mode keeps the O_CREAT | O_EXCL create-only-if-absent semantics,
so an existing (possibly user-edited) .gitattributes is never rewritten.
Binary mode writes the same LF bytes on every platform. The warning now
uses the logger's key/value form (path=..., err=...).

Test: artifact::artifact_roundtrip_non_ascii_paths now reads
.gitattributes back from the CJK repo through cbm_fopen and asserts the
merge=ours line. It also replaces the file with user content, exports
again, and asserts the content is unchanged. On the Windows VM the
assertion failed 3 of 3 without the fix and passes 3 of 3 with it. The
no-overwrite check fails if the mode loses its "x".

Refs #1171

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 19:59:02 +02:00
Martin Vogel dab9187ca5 fix(extract): capture complete doc comments across languages
extract_docstring() took only the single comment node directly before a
definition. Multi-line `//` and `///` docs therefore kept just their last
line (in C# usually `/// </summary>`); docs above attributes, exports and
wrapper declarations were lost; fields, variables and modules never got a
doc; Perl POD was never stored; and every doc was cut at 500 bytes.

Capture the full documentation comment instead:
- contiguous same-style comment runs; Go comment groups with go/ast
  directive lines (`//go:`, `//line`, `//export`, ...) stripped
- docs above Rust attributes, JS/TS export statements and wrapper
  declarations (arrow and function expressions, class fields,
  assignments, ambient declarations) and C# top-level statements
- docs for fields, variables, constants and enum members, found with a
  memoised linear walk
- Go package comments and Rust `//!` docs on the File node
- Perl POD sections that name a sub (`=head`/`=item <name>`)
- Rust impl methods, Kotlin KDoc folded into package_header or sibling
  gaps, C `typedef struct/enum/union` declarations
- a doc comment wins over an intervening plain `//`; runs detached by a
  blank line and runs made only of divider lines are not docs
- no 500-byte cut; the properties buffer grows with the docstring, so a
  long doc no longer pushes other properties out

Measured on nine real-world corpora (Go, C#, Java, TypeScript, Rust, C,
PHP, Perl, Kotlin): full-doc capture Go 35% -> 99.999%, C# 10% -> 99.8%,
Java 74% -> 99.99%, Rust 7% -> 99.9%, C 67% -> 99.2%, Kotlin 70% ->
99.96%, TypeScript sources 42% -> 100%, named-sub Perl POD 0% -> 100%.
Node sets and all non-semantic edges are unchanged; index time stays
within run-to-run noise.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 19:48:10 +02:00
Martin Vogel 28e24c6e51 Merge pull request #2324 from DeusData/fix/issue-1720
fix(install): adopt the Codex MCP table after Codex rewrites it (#1720)
2026-10-01 19:19:10 +02:00
Martin Vogel ea7e01e91e Merge pull request #2445 from DeusData/fix/cypher-optional-join-overflow
fix(cypher): grow the OPTIONAL fallback buffer in the rel cross-join
2026-10-01 19:18:59 +02:00
Martin Vogel bc66208be6 style(cross-repo): narrow the scope of the status edge total
CI's cppcheck flags `total` in the cross-repo status writer
(variableScope): it is only read inside the `len < cap` branch. Move
the declaration into that branch. No behaviour change.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 19:11:51 +02:00
Martin Vogel 41b1aeacfe fix(mcp): resolve the root owner for unnamed index status polls
With #2134, an unnamed index_repository of a root that another indexed
project already owns adopts that owner's name, and the daemon keys the
job by it (application_index_project_key reads the forwarded "name").
The unnamed status poll that the #2144 async reply asks for ("the same
repo_path and status: true") still derived its key from the path alone
in index_status_project_key. For an owned root it never found the job
it had just started and answered "no index job or index is known for
project '<path-derived>'"; an ambiguous root got that same misleading
answer instead of the loud error the start returns.

index_status_project_key now runs the start path's
index_root_owner_resolve on the same canonical repo_path: an explicit
name still wins, a single other owner is the key, several owners fail
with the same error naming them, otherwise the path-derived key stays.
The status error buffer grows to hold that owner list.

The daemon's other readers of the key (job dedupe in
application_job_subscribe_locked, the synchronous cut-short marker set
and taken around application_index_run_sync) derive it from the
forwarded args, which already carry the owner name, so they agree with
the start; status was the only reader that diverged.

Refs #2134, #2144

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 00:30:20 +02:00
Martin Vogel 5538355530 chore(lint): clang-format the callable_sig.h include comment in store.c
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 00:10:39 +02:00
Martin Vogel 11867dfa74 feat(identity): callable identity plumbing, no language enabled (#2061)
Overloads that share a base QN (Java/C#/C++/Kotlin/Swift/Scala/ObjC) merge
into one graph node today, and that node collects the CALLS of every
overload. The agreed cure is one signature-qualified callable identity for
all overloading languages:

    callable_qn := base_qn [<tparams>] (params) [cvref]

This change lands the plumbing with every language still at
CBM_CALLABLE_ID_NONE, so the graph is byte-identical; each language is
switched on later in its own change (with its index-format bump).

- internal/cbm/callable_sig.{c,h}: the per-language mode side table
  (NONE|TYPED|LABELED_TYPED|LABELED|ARITY; kept out of CBMLangSpec like
  cbm_string_dispatch_suffixes, since ~160 positional rows would otherwise
  all need the member under -Wmissing-field-initializers), the shared
  builder cbm_callable_sig[_mode] for the def and the call-scope QN, and
  the inverse cbm_qn_callable_base_len[_named]. Suffix contract: no '.',
  '::' or '->'; whitespace-normalized; comments/annotations/attributes
  dropped; qualified types keep their last segment; '->' spelled '=>';
  variadic '[]' (Java) / '~'; C++ top-level cv dropped, arrays decay,
  cvref kept; <= 200 bytes, longer ones keep whole leading entries and end
  in '#<fnv1a64 of the full suffix>)'. The builder is iterative (cursor
  walk, bounded declarator loop) and self-checks against the inverse.
- The inverse is anchored to the node's bare name wherever the name is
  known: real QNs already end in ')' without being callables (a Java field
  whose name is its declarator `X = f()`, make `$(VAR)` targets), and only
  the anchor makes the inverse exact on them.
- Leaf splitters strip a suffix first (no-op today): registry by-name key
  (indexed by the bare name for a suffixed callable), cbm_lsp_bare_segment,
  cbm_pipeline_qn_class_method_tail, pxc_last_component, pxc_qn_leaf,
  go_index_visit_node, collect_prod_defs, sg_qn_prefix_len.
- New unused fields: CBMDefinition.qn_sig_off, CBMResolvedCall.callee_sig
  (relocated by result compaction), CBMRegisteredFunc.sig, CBMLSPDef.sig.
  The lsp_surface codec is unchanged (no format bump in this change).
- get_code_snippet and trace_path gain base-QN tiers
  (cbm_store_find_nodes_by_qn_base) that find nothing until suffixes exist.
- store: cbm_store_find_nodes_by_qn_suffix built its LIKE pattern in a
  512-byte buffer (a long suffix was truncated into a pattern that matched
  nothing) and did not escape '_'/'%' (`my_func` also matched `myXfunc`).
  The pattern is now heap-built, escaped, and matched with ESCAPE '\'.

Proof: full sorted node+edge+lsp_surface dumps are byte-identical before
and after on 7 corpora (this repo, elasticsearch libs, Exposed, dotnet
System.Linq, System.Collections, coreclr/gc, a C corpus).

Refs #2061

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-10-01 00:10:39 +02:00
Martin Vogel eb99608357 fix(store): cut WAL write amplification on 64 KiB-page indexes (#1419)
Every index is written with 64 KiB pages (sqlite_writer.c), but read-write
connections kept SQLite's default 2000 KiB page cache, which holds about 31
of those pages. A closure-repair delta purges and patches rows across the
node and edge tables and all of their indexes, so the transaction kept
spilling dirty pages into the WAL and rewriting them in place. A one-line
body change on a 294 MB django index wrote 5.2 GiB to the WAL (about 75k
in-place page rewrites) and 5.7 GiB of logical writes in total. Read-write
on-disk connections now use a 64 MiB cache (1024 pages, the budget bulk mode
already used), and end_bulk restores that instead of the 2000 KiB default.
Query connections keep the default.

cbm_pipeline_publish_staged also forced synchronous=FULL on the private
staging database, so every metadata and FTS commit fsynced the WAL. A crash
before the atomic rename discards the stage, and
cbm_store_seal_for_atomic_publish() still raises the connection to FULL for
the TRUNCATE checkpoint and DELETE-mode switch that make the published file
durable, so those per-commit fsyncs protected nothing. The commits now run at
the store's NORMAL level, which SQLite documents as corruption-safe under
WAL. No corruption or atomicity guarantee changes: the live database is
still only replaced by a sealed, integrity-checked file via rename.

Measured on macOS, main vs this change, same machine and corpora:
- django one-line edit (closure repair): WAL writes 5.2 GiB -> 0.52 GiB,
  logical writes 5.76 GiB -> 1.08 GiB, WAL fsyncs 13 -> 8
- django full index: WAL writes 58 MiB -> 47.5 MiB, WAL fsyncs 9 -> 2
- php (65 MB index) one-line edit: WAL writes 82.5 MiB -> 32.3 MiB, spill
  rewrites 468 -> 0
- kubernetes (1.7 GB index) full index: WAL writes 669 MiB -> 390 MiB, WAL
  fsyncs 13 -> 6

The comments that put a healthy WAL at ~4 MiB assumed 4 KiB pages; at 64 KiB
the 1000-page autocheckpoint is ~64 MiB, still well under the 256 MiB
journal_size_limit.

Tests: store_pragmas/store_role_pragmas_issue1419 pins the effective pragmas
of each store role (read-write, bulk, seal, query), and
pipeline_semantic_manifest_repro/
pipeline_staged_publish_commits_below_full_sync_issue1419 reads the effective
synchronous level from a WAL hook on every connection that a full index plus
a closure-repair reindex opens, and requires that no commit runs at FULL.

Refs #1419

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 23:52:06 +02:00
Martin Vogel 492ae13557 chore(lint): release the #2127 import-filter strings through safe_free
The memory-core ratchet flagged src/pipeline/pass_pkgmap.c growing by 2 raw
allocator sites (82 -> 84). Both are frees of strings returned by
cbm_pipeline_fqn_compute and cbm_pipeline_resolve_module, which the core
never counted, so they now go through safe_free as the rest of the codebase
does rather than raw free or cbm_free. Behaviour is unchanged;
pass_pkgmap.c is back at its baseline of 82.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 23:41:55 +02:00
Martin Vogel 5acd91a39e fix(pipeline): never bind an external Python import to a same-named project symbol (#2127)
`from unittest.mock import patch` names a module outside the project.
Strategy 1 of cbm_pipeline_resolve_import_node cannot resolve it, so the
Strategy-3 symbol-name fallback bound the import to the only project
definition whose leaf is `patch` -- a REST view's PkgConfigView.patch --
and every `patch(...)` call became an import_map CALLS edge at confidence
0.95. Once that IMPORTS edge is gone the same call falls through to the
weak short-name strategies (unique_name 0.75, suffix_match), which bind it
again; `mock.patch(...)`, `json.loads(...)`, `os.path.join(...)` reached
project methods the same way, because the member guard exempts
import-rooted receivers.

Two per-language (Python-only) rules, both keyed on the import's module
chain rather than on any spelling list:

- Import side (pass_pkgmap.c, shared by both drivers): for an import
  whose module is not in the project, a Strategy-3 hit must spell the
  import's module chain as an ordered subsequence of its QN (a sys.path
  root or src/ layout the resolver missed still qualifies), and whatever
  names a module (an enclosing path segment, any segment of a plain
  `import x`) may only bind a Module/File node. Imports of project
  modules are unchanged (they may re-export from anywhere).
- Call side (pass_calls.c + pass_parallel.c, identical gates): a call
  whose root identifier is bound by an external import (no IMPORTS edge
  materialized it) and whose weak-strategy target contradicts that
  import's chain is not emitted as a plain CALLS edge. import_map /
  same_module / lsp_* edges are never touched.

django/django (parallel pipeline): CALLS 62,430 -> 60,123, TESTS
29,872 -> 28,571, IMPORTS 16,068 -> 15,491. Removed CALLS are
member calls through stdlib imports (1,900: os.path.join ->
defaultfilters.join, json.loads -> signing.loads, mock.patch ->
RedirectView.patch) and bare calls of stdlib names (398: date ->
defaultfilters.date, urlsplit -> MultiPartParser.parse); a random
25-edge sample was 25/25 false. Six IMPORTS are re-targeted to the real
definition (template_tests.utils.setup, multiple_database TestRouter,
pr_quality errors.Message).

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 23:41:55 +02:00
Martin Vogel 6eb33534f6 fix(daemon): explain foreign-owned cache ancestors and warn on network filesystems (#1717)
A cache root whose resolved path runs through a directory owned by another
non-root account (typical on shared/HPC filesystems where ~/.cache is a
symlink into a shared tree) is refused by the private-directory walk. The
refusal itself is correct: the owner of an ancestor can rename or replace
everything below it after the walk, so it could redirect the cache. But
posix_directory_transition_secure() set no validation detail, so the caller
printed "ancestry component validation failed (errno 17)" -- a stale EEXIST
from mkdirat() that named neither the directory nor the reason.

- The refusal now names the directory, its owner uid and account name, the
  caller's uid, and the remedy (a location with a self/root-owned ancestry,
  e.g. via CBM_CACHE_DIR). The path is shortened from the left so the
  remedy always fits the 384-byte detail buffer.
- On Linux the account name is read from /etc/passwd, not getpwuid(). The
  release binary is statically linked against glibc, and getpwuid() there
  loads the host's NSS modules at runtime, which can crash on a glibc
  version mismatch (a real risk on sssd/LDAP cluster hosts). Accounts that
  exist only in a directory service are shown by uid.
- New advice-only check: on Linux, a cache root on NFS, CIFS, SMB2, Lustre
  or GPFS (statfs f_type) logs one daemon.cache_root_network_fs warning per
  process. SQLite WAL is unreliable on network filesystems. Nothing is
  refused.
- docs/CONFIGURATION.md gains a "Shared / HPC filesystems" section.

The ownership policy is unchanged, and there is still no override (same
stance as #1830).

Test seams: one seam reports a directory (matched by dev/ino) as
foreign-owned, and another supplies the statfs magic. The refusal, the
message and the once-per-process warning are therefore testable without
root and on every platform.

Refs #1717

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 23:33:54 +02:00
Martin Vogel abf00764a7 fix(mcp): resolve a directory project arg to its owning project (#1690)
An agent in a checkout whose directory name differs from the repository
name (git clone .../repo_name.git some_name) could not find the indexed
project. The installed skill only said "list_projects - check if project
is indexed", so Codex and Copilot guessed the project from the repo name,
got "project not found" and stopped using the graph. Passing the working
directory did not help whenever it was not exactly the indexed root: a
path was only ever turned into the path-DERIVED name, which misses a
checkout indexed under an explicit name (the stored identity, see #1660)
and every directory below an indexed root.

Fix:
- mcp: a path-shaped project keeps the derived name when an index exists
  under it (unchanged fast path); otherwise it resolves to the indexed
  project whose stored root_path owns the directory. The deepest owning
  root wins; two projects owning that root stay unresolved, so the
  not-found error lists every project instead of guessing. Reuses the
  list_projects identity reader and the canonical-path containment helpers.
- mcp: the project-not-found hint says how to pick the project (the name
  whose root_path contains the working directory, or that absolute
  directory; never a repo or folder name), so an agent that guessed can
  recover.
- cli: the SKILL.md every skill client installs (Codex, Copilot and the
  rest), the shared agent instructions and the Aider CLI instructions say
  the same thing.

Proof (dev binary, synthetic HOME; repo_name cloned as some_name and
indexed by path; a second checkout other_dir indexed with name=my-alias):
  before: project=<other_dir>        -> project not found
          project=<some_name>/pkg    -> project not found
  after:  project=<other_dir>        -> my-alias (index_status agrees)
          project=<some_name>/pkg    -> the some_name project
  unchanged: the checkout root path and the explicit name resolve; the
  unindexed sibling some_name_x stays not found; a guessed "repo_name"
  stays not found and now carries the how-to-pick hint.

Tests:
- mcp tool_project_path_resolves_owning_project_issue1690: an explicitly
  named root and its subdirectory resolve; normal naming and similar
  names (some_name2, some_name_x) are not confused; two owners of one
  root are never guessed; a guessed repo name gets the hint. RED 3x
  before, green after, RED again when the production change is reverted
  (the hint check also goes RED on its own revert).
- cli cli_guidance_resolves_project_by_root_path_issue1690: pins the
  instruction in the skill, agent-instructions and Aider variants.

Fixes #1690

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 23:14:32 +02:00
Martin Vogel e4f9735dea feat(cross-repo): report run status and skipped legacy stores (#2133)
Two follow-ups to the #2133 wildcard fix, both about what cross-repo
intelligence tells the caller.

1. "Never run" vs "ran, no links". An empty CROSS_* set used to mean
   either one, and no output surface could tell them apart. Every run now
   records a marker in the SOURCE store's store_meta
   (key cross_repo_last_run:<project>, same per-project key pattern as
   coverage_shadow_fp:<project>) once the previous CROSS_* generation has
   been cleaned: last_run_at, outcome (complete|cancelled|failed),
   targets, projects_scanned, total_cross_edges, skipped_projects.
   index_status and the UI layout (next to linked_projects) now carry a
   `cross_repo` object: {"status":"never_run"} or {"status":"ran", ...}.
   The marker lives beside the edges it describes, so a reindex that
   rebuilds the store drops both together. No new database files and no
   new freshness key.

   New store API cbm_store_meta_get/put. put seeds a missing store_meta
   through the generation path, because creating the table without
   db_uid/mutation_gen would make cbm_store_generation() report malformed
   metadata.

2. ["*"] skips a pre-#768 store (since #2343) but only logged it. The
   result now names each one, and the MCP response lists them:
   skipped_projects: [{name, reason:"pre_768_schema",
   hint:"reindex this project"}] (only emitted when non-empty). The
   cross_repo.project_unusable log line is unchanged.

cr_project_exists() is split into cr_project_state() (usable / missing /
legacy) so that the enumerator can tell a legacy store apart from a
foreign .db file. New allocations go through mem_core.

Refs #2133
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 22:40:38 +02:00
Martin Vogel c06ceb1638 feat(watcher): opt-in polling of non-git project roots (#1948)
A project indexed from a directory that is not a git repository was never
refreshed after its first index: init_baseline classified it is_git=false
and poll_project/check_changes returned early for it forever, so the graph
silently went stale. The comment in init_baseline even claimed such folders
were "polled as a plain directory", which was never true.

Add an opt-in config key, watch_non_git (default false, read once at daemon
startup like watcher_enabled). When on, a non-git root is polled on the
existing adaptive cadence (cbm_watcher_poll_interval_ms) by a tree
signature: the indexer's own cbm_discover walk (same skip lists, .gitignore
stack and .cbmignore), sorted by path and folded over (relative path, size,
mtime). A changed signature takes the existing reindex path with the same
commit-after-success discipline as the #937 dirty signature. The baseline
leaves the signature "unknown", so the first poll reindexes once
(at-least-once, covering edits made while the daemon was down).

Runaway guard: only files discovery would index enter the signature, so
cbm's own .codebase-memory output (built-in skip) and the cache directory
(pruned by absolute path) can never make a finished reindex look like a
new change; a scratch folder under an unrelated dirty repository is polled
on its own files and never inherits the ancestor's dirty state.

cbm_file_info_t gains mtime_ns, filled from the stat discovery already
performs, so the signature needs no second stat per file and stays
UTF-8-correct on Windows (discovery's wide stat).

Docs: README and docs/CONFIGURATION.md now say non-git roots are not
watched by default and document watch_non_git. The staleness signal in
index_status is left to #1561's freshness object. Refs #1948.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 22:27:19 +02:00
Martin Vogel e81fd499f8 fix(install): adopt the Codex MCP table after Codex rewrites it (#1720)
Codex rewrites its [mcp_servers] tables whenever it edits MCP servers
itself (`codex mcp add`, its MCP settings, wrappers such as Orca that
drive it) and drops comment decor on the way. From our managed block it
keeps the table but loses the begin marker, omits `args = []`, and leaves
the end marker as an orphan below whichever table follows. Reproduced
with codex-cli 0.153.4: after `codex mcp add orca -- /bin/echo hi` the
file holds an unmarked

  [mcp_servers.codebase-memory-mcp]
  command = ".../codebase-memory-mcp"
  env_vars = ["CBM_CACHE_DIR", "CBM_RUNTIME_DIR"]

and a stray `# <<< codebase-memory-mcp MCP <<<` under [mcp_servers.orca].

Every later install then failed with op=mcp_install on a table cbm itself
had written, twice over: cbm_toml_remove_legacy_table refused the orphan
marker as malformed, and its owned-shape check predated env_vars (#1562,
#1664), so even without the orphan the table counted as foreign.

cbm_toml_remove_legacy_table now drops a lone orphaned marker line in the
same atomic write (we are the only author of those markers, #1558; only
that line is removed, nothing is guessed) and treats env_vars naming only
CBM_CACHE_DIR / CBM_RUNTIME_DIR as part of the owned shape. A table with
any other key or forwarded name is still foreign and left byte-identical,
and a foreign table keeps the file untouched, orphan included. The scan is
split into toml_strip_legacy_table + toml_legacy_classify_assignment so
the entry point reads the file, heals, strips and writes once.

The same helper backs the Grok Build install, which gains the same
self-heal.

Tests: cli_upsert_codex_mcp_adopts_codex_rewritten_table uses the exact
bytes Codex produced; config_toml_legacy_remove_adopts_owned_env_vars_only
pins the env_vars boundary (owned names adopted, any other name foreign).

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 22:27:19 +02:00
Martin Vogel 1f0daaa915 fix(mcp): keep #2134 root-owner reuse out of cross-repo mode; portable test path
Linux, MSan, TSan and diag CI failed in mcp_mutation_guard:
tool_cross_repo_missing_inputs_fail_without_creating_ghost_databases
ASSERT(source_failed). handle_index_repository resolved the root owner
before dispatching cross-repo-intelligence mode. That test registers its
named target with the source's own root, so the unindexed source adopted
existing-cross-target as its project (log: index.root_owner_reused
project=existing-cross-target), and the missing source was no longer
reported. Cross-repo mode reads an existing source index and never writes
one, so the #2134 reuse now runs only on the re-index path, after that
dispatch. macOS CI stayed green because cbm_tmpdir() is /tmp, a symlink
to /private/tmp there, so the canonical repo_path never equalled the
fixture's stored root; with the fixture path canonicalized, the failure
reproduced 3/3 on macOS and passes 3/3 with this change.

The #2134 test itself called realpath() into a 1 KiB buffer. glibc's
FORTIFY check aborts on that ("buffer overflow detected", a SIGABRT of the
mcp suite on the ubuntu 2/3 shards), and MinGW has no realpath at all
(Windows compile error). It now uses cbm_canonical_path with a 4 KiB
buffer, the same canonicalizer production uses.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 22:26:34 +02:00
Martin Vogel b94afb4421 chore(lint): route the #2134 root-owner scratch through the memory core
The memory-core ratchet flagged src/mcp/mcp.c growing by 10 raw allocator
sites (784 -> 794) from index_root_owner_resolve and its caller. The owner
list buffer, which this code allocates and frees itself, now uses
cbm_realloc/cbm_free (class other). Strings handed over by other APIs
(cbm_project_name_from_path, heap_strdup, the index argument strings) are
released through safe_free, as elsewhere in the file, so no memory the core
never counted reaches cbm_free. Behaviour is unchanged; mcp.c is back at its
baseline of 784.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 22:26:15 +02:00
Martin Vogel 155d147e78 fix(mcp): reuse the project that owns a root on unnamed re-index (#2134)
index_repository without `name` derived the project key from the path
alone. When the root had first been indexed under an explicit name, a
later unnamed re-index forked a second index (same root_path,
path-derived name) and left the original untouched, so the stale index
kept being served while the call reported success.

Resolve the key from the indexes on disk before any work starts:
- the path-derived project exists -> keep it (unchanged behavior);
- exactly one other project owns the canonical root -> adopt its name
  and update it in place, so existing indexes are never orphaned;
- several projects own the root -> fail loudly, name them and ask for
  `name` instead of guessing or forking again;
- none -> first index under the derived name, as before.

The resolved name is written into the args handed to the daemon job
coordinator and the supervised worker, so the project lease key and the
index actually written stay the same project.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-30 22:26:15 +02:00
Martin Vogel 0f52d30c29 Merge pull request #2412 from DeusData/fix/activation-unknown-daemon-is-foreign
fix(cli): never stop a daemon whose cache is not confirmed as ours
2026-09-30 22:21:59 +02:00
Martin Vogel f4ff01b10b Merge pull request #2410 from DeusData/fix/test-runner-isolate-runtime-dir
fix(test): isolate the C test runners' daemon runtime
2026-09-30 22:21:48 +02:00
Martin Vogel 48acb559e6 Merge pull request #2405 from DeusData/fix/internal-db-enumeration
fix(cli): never treat internal cache stores as project indexes
2026-09-30 22:21:11 +02:00
Martin Vogel 083bc99d80 Merge pull request #2404 from DeusData/fix/issue-2118
fix(mcp): annotate get_file_outline and ingest_traces as read-only (#2118)
2026-09-30 22:21:06 +02:00
Martin Vogel d0ec2313d9 Merge pull request #2394 from DeusData/fix/issue-2184-post-extraction-budget
fix(pipeline): spill before the post-extraction phases when they would cross the budget (#2184)
2026-09-30 22:20:56 +02:00
Martin Vogel 6d19350e37 Merge pull request #2358 from DeusData/fix/issue-2311
docs(pipeline): CBM_EXTRACT_BUDGET is a CPU-time parse budget, not bytes (#2311)
2026-09-30 22:20:51 +02:00
Martin Vogel cb251ed472 Merge pull request #2357 from DeusData/fix/issue-2144
feat(mcp): opt-in async index_repository with status polling (#2144)
2026-09-30 22:20:46 +02:00
Martin Vogel 029919c660 Merge pull request #2355 from DeusData/fix/issue-2209
fix(install): Hermes hook edit no longer refuses unrelated YAML sections (#2209)
2026-09-30 22:20:30 +02:00
Martin Vogel 372aff2b5c Merge pull request #2351 from DeusData/fix/issue-2208
fix(cypher): carry the real node through WITH, not a name-only stub (#2208)
2026-09-30 22:20:14 +02:00
Martin Vogel 6746f43549 Merge pull request #2343 from DeusData/fix/issue-2133
fix(cross-repo): a pre-#768 store no longer aborts ["*"] or wipes edges (#2133)
2026-09-30 22:19:37 +02:00
Martin Vogel 94097f0727 Merge pull request #2341 from DeusData/fix/git-spawn-local-env
fix(git): clear git's repository-local env for cbm's own git children (#2003)
2026-09-30 22:19:32 +02:00
Martin Vogel 9df483f0af Merge pull request #2338 from DeusData/fix/issue-2044
fix(install): accept a Codex hook binary path that contains a space (#2044)
2026-09-30 22:19:27 +02:00
Martin Vogel 30a410b398 Merge pull request #2335 from DeusData/fix/issue-1955
fix(daemon): hash a verified peer image copy once, not on every HELLO (#1955)
2026-09-30 22:19:22 +02:00
Martin Vogel 78795ad76a Merge pull request #2339 from DeusData/fix/issue-2053
fix(rust): never let a std-typed receiver bind a same-named project method (#2053)
2026-09-30 22:19:17 +02:00
Martin Vogel 5910c47a97 Merge pull request #2332 from DeusData/fix/issue-1916
fix(pipeline): compose axios.create baseURL into HTTP_CALLS (#1916)
2026-09-30 22:19:12 +02:00
Martin Vogel e2f9fcc399 Merge pull request #2334 from DeusData/fix/issue-1951
fix(mcp): translate Git-root paths for subdirectory projects in detect_changes (#1951)
2026-09-30 22:19:07 +02:00
Martin Vogel 7821a1babb Merge pull request #2331 from DeusData/fix/issue-1827
fix(mcp): resolve projects by their non-ASCII folder name (#1827)
2026-09-30 22:19:02 +02:00
Martin Vogel 0cff5dbe7c Merge pull request #2325 from DeusData/fix/issue-1735
fix(discover): skip Laravel's compiled Blade view cache by default (#1735)
2026-09-30 22:18:38 +02:00
Martin Vogel e9a3d18fbd Merge pull request #2322 from DeusData/fix/issue-1687
fix(daemon): name the WSL DrvFs remedy when a /mnt/<drive> cache is refused (#1687)
2026-09-30 22:18:33 +02:00
Martin Vogel 2bed1c8c4a Merge pull request #2319 from DeusData/fix/issue-1459
fix(cross-repo): skip CROSS_HTTP_CALLS for calls the caller serves itself (#1459)
2026-09-30 22:18:22 +02:00
Martin Vogel aa53278b29 Merge pull request #2318 from DeusData/fix/issue-1133
fix(cross-repo): fail explicitly when zero target projects resolve (#1133)
2026-09-30 22:17:47 +02:00
Martin Vogel 2fabaa2b87 fix(cypher): grow the OPTIONAL fallback buffer in the rel cross-join
An OPTIONAL MATCH with a relationship, whose start and terminal
variables are not bound by an earlier MATCH and whose start node
pattern matches no node, is joined in cross_join_with_rels() with an
empty candidate list. That path sized its output for a single binding,
but the OPTIONAL fallback then kept one row per existing binding with a
plain indexed store, so every row after the first was written past the
end of the allocation.

Route the fallback through binding_out_append(), the growing writer
that the expansion branch of the same function and the other OPTIONAL
fallbacks already use. The node-only join (cross_join_nodes) was fixed
earlier by sizing its buffer for the fallback rows; the relationship
variant kept the unchecked store.

Add a cypher regression test that runs such a query over four bound
functions and asserts one row per function with the optional variables
unbound. Before this change the test runner reported a
heap-buffer-overflow in cross_join_with_rels under ASan.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-29 02:28:48 +02:00
Martin Vogel e548d971b3 fix(mcp): free the empty name-lookup result before trace_path's QN fallback
handle_trace_call_path first looks the function up by bare name
(cbm_store_find_nodes_by_name). find_nodes_generic allocates its
initial 16-slot array before stepping the statement and hands it back
even when zero rows match. When the bare name misses and the
qualified_name fallback then resolves the node, the handler overwrote
`nodes` with a fresh one-element array, leaking the empty 1 KB array
on every trace_path call made with a qualified name - for the whole
lifetime of the daemon. The malloc-failure branch of the fallback lost
the same array.

Release the zero-row array before the fallback replaces the pointer.
The other find_nodes_* callers (get_code_snippet outline, search_code
grep classification, detect_changes seeding, Cypher label scans)
already free the container on zero rows; the not-found path in this
handler did too.

Proof (macOS leak lane, Homebrew clang 22.1.8,
`make -f Makefile.cbm test-lsan LSAN_SUITES=mcp`):
- with the new test, without the fix: 322 passed, then
  "ERROR: LeakSanitizer: detected memory leaks - Direct leak of 1024
  byte(s) in 1 object(s) allocated from find_nodes_generic store.c:2771
  <- handle_trace_call_path mcp.c:9176 <-
  test_tool_trace_call_path_qn_fallback_frees_name_miss", exit 1
  (the only leak in the suite).
- with the fix: 322 passed, 4 skipped, no leak report, exit 0.

The new test pins its own precondition (the bare-name lookup of the
qualified name returns zero rows) and that the trace resolves through
the fallback, so it keeps exercising this path. LSan (default-on under
Linux ASan, test-lsan on macOS) turns any regression red.

Found while attributing CI on #2305.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-29 00:54:37 +02:00
Martin Vogel 92910147ab Merge pull request #2181 from AmirF194/fix/510-enclosing-gitignore-not-inherited
fix(discover): honor an enclosing repo's .gitignore for a git-less subfolder
2026-09-29 00:32:20 +02:00