Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

35.9 KB
Raw Blame
/*
 * pipeline.h — Indexing pipeline orchestrator.
 *
 * Orchestrates multi-pass indexing of a repository:
 *   1. Structure: Project/Folder/Package/File nodes
 *   2. Definitions: Extract + write nodes + build registry
 *   3. Imports: Resolve import edges
 *   4. Calls: Call resolution (registry + LSP)
 *   5. Usages: Usage/type_ref edges
 *   6. Semantic: Inherits/decorates/implements
 *   7. Post: Tests, communities, HTTP links, config, git history
 *
 * Depends on: foundation, extraction, lsp, store, graph_buffer, discover
 */
#ifndef CBM_PIPELINE_H
#define CBM_PIPELINE_H

#include <stdbool.h>
#include <stdint.h>
#include <stdatomic.h>

#include "discover/discover.h"     /* cbm_ignored_file_t (#963) */
#include "foundation/constants.h"  /* CBM_SZ_512 */
#include "foundation/hash_table.h" /* CBMHashTable (#1355 pkgmap lookup) */

/* Forward declarations */
typedef struct cbm_store cbm_store_t;
typedef struct cbm_gbuf cbm_gbuf_t;

/* ── Opaque handle ──────────────────────────────────────────────── */

typedef struct cbm_pipeline cbm_pipeline_t;

/* ── Index mode ─────────────────────────────────────────────────── */

#ifndef CBM_INDEX_MODE_T_DEFINED
#define CBM_INDEX_MODE_T_DEFINED
typedef enum {
    /* All modes run the LSP type-aware call/usage resolution (per-file +
     * cross-file). The mode only controls file discovery breadth and whether
     * SIMILAR_TO / SEMANTICALLY_RELATED edges are computed. */
    CBM_MODE_FULL = 0,     /* Full: everything including SIMILAR_TO + SEMANTICALLY_RELATED */
    CBM_MODE_MODERATE = 1, /* Moderate: fast discovery + SIMILAR_TO + SEMANTICALLY_RELATED */
    CBM_MODE_FAST = 2,     /* Fast: skip non-essential files, no similarity/semantic edges */
} cbm_index_mode_t;
#endif

/* ── Pipeline lifecycle ─────────────────────────────────────────── */

/* Create a new pipeline. Caller owns the result. */
cbm_pipeline_t *cbm_pipeline_new(const char *repo_path, const char *db_path, cbm_index_mode_t mode);

/* Enable persistent artifact export (.codebase-memory/graph.db.zst).
 * When enabled, the pipeline writes a compressed artifact after indexing. */
void cbm_pipeline_set_persistence(cbm_pipeline_t *p, bool enabled);

/* Apply a validated discovery resource policy. The value is copied. */
void cbm_pipeline_set_resource_policy(cbm_pipeline_t *p, const cbm_index_resource_policy_t *policy);

/* Publication gate. cbm_pipeline_run calls it once, after the last
 * pre-publication check and immediately before the serving database is
 * touched (never for a live no-op, which replaces nothing). Returning false
 * aborts the run with CBM_PIPELINE_ABORT_PRESERVE_DB and the previous
 * generation stays exactly as it was. A supervised index worker uses it to
 * claim publication from its supervisor (see the publication fence in
 * mcp/index_supervisor.h). NULL removes the gate. */
typedef bool (*cbm_pipeline_publish_gate_fn)(void *context);
void cbm_pipeline_set_publish_gate(cbm_pipeline_t *p, cbm_pipeline_publish_gate_fn gate,
                                   void *context);

/* Doc -> code candidates (the doc_candidates setting). Never set, the index
 * mode decides: on for full, off for moderate and fast. The setter makes an
 * explicit choice that wins in every mode. Off skips scoring documentation
 * sections against code and leaves the project with no doc_link_candidates
 * rows; nodes and edges are unchanged. On in fast mode scores them without
 * fast's skipped SIMILAR_TO / SEMANTICALLY_RELATED edges. The scoring grows
 * with sections x functions, which is the cost on very large repositories.
 * enabled() reports the effective choice for the pipeline's current mode. */
void cbm_pipeline_set_doc_candidates_enabled(cbm_pipeline_t *p, bool enabled);
bool cbm_pipeline_doc_candidates_enabled(const cbm_pipeline_t *p);

/* Copy the exact discovery violation from the most recent run. */
void cbm_pipeline_get_resource_violation(const cbm_pipeline_t *p,
                                         cbm_index_resource_violation_t *violation);
/* Mark work that runs without a waiting user. Background pipelines reserve
 * CPU headroom; foreground pipelines retain the initial-index all-core policy. */
void cbm_pipeline_set_background(cbm_pipeline_t *p, bool background);

/* Resolve the worker policy for this pipeline, including environment and
 * crash-recovery overrides. */
int cbm_pipeline_worker_count(const cbm_pipeline_t *p);

/* Background width from the foreground width and the headroom width: the
 * headroom, floored at two whenever the foreground width is two or more so an
 * automatic refresh keeps the parallel route. */
int cbm_pipeline_background_worker_width(int foreground, int headroom);

#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
void cbm_pipeline_worker_count_test_reset(void);
int cbm_pipeline_worker_count_test_last(void);
#endif

/* Snapshot of the artifact export failure of the last cbm_pipeline_run, or ""
 * when the run succeeded / did not reach post-publish export. Used to
 * truthfully attribute a failed run to the persistence export (#1665) instead
 * of the generic pipeline-error hint. Valid until the next cbm_pipeline_run or
 * cbm_pipeline_free(). Returns "" for NULL p. */
const char *cbm_pipeline_export_error(const cbm_pipeline_t *p);

/* Free a pipeline and all its internal state. NULL-safe. */
void cbm_pipeline_free(cbm_pipeline_t *p);

/* Run the full indexing pipeline. Discovers files, extracts, resolves, and
 * dumps to SQLite. Returns 0 on success and non-zero on failure.
 *
 * Treating any non-zero as "the run failed" is always correct. Callers that
 * need to know whether the PREVIOUS generation survived can distinguish the
 * failures by value: the run publishes by renaming a fully validated staging
 * database over the destination, so every abort before that rename leaves the
 * existing database in place. */
#define CBM_PIPELINE_ABORT_PRESERVE_DB (-2) /* aborted pre-publication; previous DB intact */
#define CBM_PIPELINE_PERSIST_FAILED (-4)    /* staging/rollback failure during publication */
/* Resident memory stayed above the budget after back-pressure and one
 * confirmation cycle: the run stops before publication, no partial graph is
 * written, the previous DB is intact (#1997 #832). Distinct from the cancel
 * sentinel so callers can name the cause instead of "pipeline failed". */
#define CBM_PIPELINE_ABORT_OVER_BUDGET (-5)
/* Opt-in discovery/resource policy breach: fail the attempt, keep serving DB. */
#define CBM_PIPELINE_RESOURCE_LIMIT (-6)
int cbm_pipeline_run(cbm_pipeline_t *p);

/* Request cancellation of a running pipeline (thread-safe). */
void cbm_pipeline_cancel(cbm_pipeline_t *p);

/* Bind cancellation to a caller-owned atomic flag. The flag must outlive the
 * pipeline and should be initialized before binding. This lets a long-lived
 * daemon request cancellation without retaining/dereferencing a pipeline
 * pointer that its request thread may concurrently retire. */
void cbm_pipeline_bind_cancel_flag(cbm_pipeline_t *p, atomic_int *cancelled);

/* Get the project name derived from repo_path. Returned string is
 * owned by the pipeline. Valid until cbm_pipeline_free(). */
const char *cbm_pipeline_project_name(const cbm_pipeline_t *p);

/* Override the derived project name with a sanitized user-provided label. */
bool cbm_pipeline_set_project_name(cbm_pipeline_t *p, const char *name);

/* Get the index mode (CBM_MODE_FULL, CBM_MODE_MODERATE, CBM_MODE_FAST). */
int cbm_pipeline_get_mode(const cbm_pipeline_t *p);

/* Get the list of directory subtrees skipped during discovery (#411).
 * *out receives a borrowed array of rel-path strings (owned by the pipeline,
 * valid until cbm_pipeline_free()); *count receives its length. Both are set
 * to NULL/0 when p is NULL or nothing was excluded. Do not free. */
void cbm_pipeline_get_excluded(const cbm_pipeline_t *p, char ***out, int *count);

bool cbm_pipeline_had_format_migration(const cbm_pipeline_t *p);

/* Committed node/edge counts captured at dump time (-1 when dump did not run).
 * Nodes are the #334 plausibility-gate axis; edges are informational only. */
void cbm_pipeline_get_committed_counts(const cbm_pipeline_t *p, int *nodes, int *edges);

/* ── Per-file indexing failures (Stage 2 / Track B) ─────────────── */

/* One source file that was skipped during indexing. All strings are owned by
 * the pipeline (copied on record, freed in cbm_pipeline_free). A skip is the
 * expected, handled outcome of a bad/oversized file — indexing continues and
 * the run still reports status "indexed"; these are surfaced (not errors that
 * fail the run) via MCP `skipped[]` / the CLI / a per-run logfile. */
typedef struct {
    char *path;   /* repo-relative path of the skipped file */
    char *reason; /* human-readable cause (e.g. "oversized (712 MB > 512 MB)",
                   * "parse timeout", "read failed"). For phase "parse_partial"
                   * this carries the 1-based line-range list ("12-40,88-90")
                   * of the unparseable regions. */
    char *phase;  /* "read" | "extract" | "oversized" | "parse_partial".
                   * "parse_partial" (#963) is NOT a skip: the file WAS indexed
                   * but contains tree-sitter ERROR/MISSING regions whose
                   * constructs are absent from the graph (best-effort signal —
                   * absence of the flag is NOT a completeness guarantee). The
                   * MCP layer reports it separately from skipped[]. "cross_lsp"
                   * is a RESERVED phase string for Track C's crash-attribution
                   * signal and is intentionally NOT emitted today (the
                   * cross-LSP passes are best-effort/void with no genuine
                   * per-file failure). */
} cbm_file_error_t;

/* Record a skipped file. path/reason/phase are copied. NULL-safe on p.
 *
 * NOT thread-safe: call it from the sequential extraction pass, or from the
 * parallel merge step (never from inside a parallel worker — workers collect
 * into per-worker lists and merge sequentially). */
void cbm_pipeline_add_file_error(cbm_pipeline_t *p, const char *path, const char *reason,
                                 const char *phase);

/* Borrowed accessor for the recorded skips (owned by the pipeline, valid until
 * cbm_pipeline_free()). out and count are set to NULL and 0 when p is NULL or
 * nothing was skipped. Do not free. */
void cbm_pipeline_get_file_errors(const cbm_pipeline_t *p, cbm_file_error_t **out, int *count);

/* Borrowed accessor for the individually-ignored files captured during
 * discovery (#963 "purposely not indexed" — by design, not failures). count
 * is the stored (capped) length, total the uncapped number seen. Do not
 * free. */
void cbm_pipeline_get_ignored(const cbm_pipeline_t *p, cbm_ignored_file_t **out, int *count,
                              int *total);

/* ── Index lock (prevents concurrent pipeline runs on same DB) ──── */

/* Try to acquire the global index lock. Returns true if acquired,
 * false if another pipeline is already running (non-blocking).
 * Use this in the watcher — skip reindex if busy. */
bool cbm_pipeline_try_lock(void);

/* Acquire the global index lock, blocking until available.
 * Use this in MCP handler and autoindex — wait for busy watcher to finish. */
void cbm_pipeline_lock(void);

/* Release the global index lock. */
void cbm_pipeline_unlock(void);

/* ── FQN helpers (used by passes and external callers) ──────────── */

/* Compute a qualified name: project.dir.parts.name
 * Strips extension, converts / to ., drops __init__ and index.
 * Caller must free() the returned string. */
char *cbm_pipeline_fqn_compute(const char *project, const char *rel_path, const char *name);

/* Module QN: project.dir.parts (no name). Caller must free(). */
char *cbm_pipeline_fqn_module(const char *project, const char *rel_path);

/* Length of the prefix cbm_pipeline_fqn_compute(project, rel_path, name) puts
 * before a symbol `name` (the joining dot excluded): the QN prefix every
 * definition of that file carries, __init__ / index already dropped. Computed
 * without allocating; 0 when unavailable. */
size_t cbm_pipeline_fqn_symbol_prefix_len(const char *project, const char *rel_path);

/* Language-aware module QN. When `module_is_dir` is true (Java/Go package
 * semantics) the module is derived from the CONTAINING DIRECTORY (the filename
 * stem is dropped), so it agrees with the extraction-side def QNs; when false
 * it is exactly cbm_pipeline_fqn_module(). Caller must free(). */
char *cbm_pipeline_fqn_module_dir(const char *project, const char *rel_path, bool module_is_dir);

/* Folder QN: project.dir.parts. Caller must free(). */
char *cbm_pipeline_fqn_folder(const char *project, const char *rel_dir);

/* Resolve an import specifier that uses a relative path (./foo, ../bar, .foo,
 * or an unqualified local name like "foo.h") against the importing file's
 * path.  Returns a malloc'd normalized relative path without extension
 * (e.g. "src/api/helpers") suitable for passing to cbm_pipeline_fqn_module,
 * or NULL if the specifier is not a relative path (bare module names like
 * "lodash", "django", "github.com/foo/bar" return NULL — the caller should
 * treat those as external/unresolvable). Handles ".", "..", and leading
 * dot-only segments used by Python relative imports. */
char *cbm_pipeline_resolve_relative_import(const char *source_rel, const char *module_path);

/* Derive project name from an absolute path.
 * Replaces / and : with -, collapses --, trims leading -.
 * Caller must free() the returned string. */
char *cbm_project_name_from_path(const char *abs_path);

/* The name-mapping half of cbm_project_name_from_path, WITHOUT path
 * canonicalization: maps any string to the stored project-name form (unsafe
 * ASCII -> '-', non-ASCII bytes -> two hex digits, dash/dot collapse, trim,
 * #624 length cap). Lets a selector such as a bare non-ASCII folder name be
 * encoded exactly like the segment it came from (#1827). Caller frees. */
char *cbm_project_name_sanitize(const char *name_path);

/* ── Function Registry ──────────────────────────────────────────── */

typedef struct cbm_registry cbm_registry_t;

typedef struct {
    const char *qualified_name; /* borrowed from registry */
    const char *strategy;       /* resolution strategy name */
    double confidence;          /* 0.0–1.0 */
    int candidate_count;
} cbm_resolution_t;

/* Create/free a function registry. */
cbm_registry_t *cbm_registry_new(void);
void cbm_registry_free(cbm_registry_t *r);

/* Register a function/method/class. All strings are copied. The entry's
 * language is unknown, so name-based resolution never filters it out. */
void cbm_registry_add(cbm_registry_t *r, const char *name, const char *qualified_name,
                      const char *label);

/* As cbm_registry_add, recording `lang`: the DETECTED language of the file
 * that defines the symbol (CBM_LANG_COUNT = unknown), which the cross-language
 * veto (cbm_registry_name_guess_vetoed) checks against the caller. Detects no
 * function-local symbols: that needs the defining file's module QN, see
 * cbm_registry_add_lang_in_module. */
void cbm_registry_add_lang(cbm_registry_t *r, const char *name, const char *qualified_name,
                           const char *label, CBMLanguage lang);

/* As cbm_registry_add_lang. A Python symbol declared inside a function body of
 * its own file (cbm_registry_qn_is_function_local, bounded by
 * `module_prefix_len`: cbm_pipeline_fqn_symbol_prefix_len of the defining file)
 * is registered for exact lookups only, never offered to the short-name
 * strategies. The three graph
 * registration sites (pass_definitions.c, pass_parallel.c,
 * pipeline_incremental.c) all register through this, so full and incremental
 * indexes agree. 0 = no local detection. */
void cbm_registry_add_lang_in_module(cbm_registry_t *r, const char *name,
                                     const char *qualified_name, const char *label,
                                     CBMLanguage lang, size_t module_prefix_len);

/* Register a symbol for exact (qualified-name) lookups only: it is never
 * offered to the short-name strategies (unique_name, suffix_match,
 * field_type_hint, fuzzy). For a generated member (cbm_def_props_generated),
 * which the source never spells, so only a type-aware resolver that knows its
 * owner may bind it. The three graph registration sites route such a symbol
 * here instead of cbm_registry_add_lang_in_module. */
void cbm_registry_add_qn_only(cbm_registry_t *r, const char *qualified_name, const char *label);

/* True when a definition's extra_props (key, value, ..., NULL) carry the
 * generated-member key (cbm.h CBM_PROP_GENERATED), e.g. a Java record's
 * implicit accessor. Pure; unit-tested in test_registry.c. */
bool cbm_def_props_generated(const char *const *extra_props);

/* The stored-node twin of cbm_def_props_generated, for the incremental
 * registry seed: true when a node's properties JSON carries that key as a
 * string property. Pure; unit-tested in test_registry.c. */
bool cbm_node_props_generated(const char *properties_json);

/* True when code in `caller` can call a symbol defined in `target` by bare
 * name: same language, same interop family (JS/TS + script hosts, C/C++/CUDA/
 * ObjC, JVM, .NET, ...; the table lives in registry.c), or Swift with the C
 * family. An unknown language (CBM_LANG_COUNT) on either side is compatible. */
bool cbm_lang_resolution_compatible(CBMLanguage caller, CBMLanguage target);

/* Language of a synthetic definition source minted by a language's own LSP
 * layer ("<python-builtins>" -> Python, "<kotlin-builtins>" -> Kotlin);
 * CBM_LANG_COUNT for anything else. */
CBMLanguage cbm_registry_synthetic_path_language(const char *file_path);

/* True when a proper prefix of `qualified_name` longer than
 * `module_prefix_len` (cbm_pipeline_fqn_symbol_prefix_len of the defining file)
 * is a registered Function or Method, i.e. the symbol was declared inside a
 * function body of its own file. False when module_prefix_len is 0. */
bool cbm_registry_qn_is_function_local(const cbm_registry_t *r, const char *qualified_name,
                                       size_t module_prefix_len);

/* Python bare-name lexical lookup: the def or class named `callee_name` bound
 * in the nearest function scope enclosing `scope_qn` (the caller's QN),
 * skipping class bodies, stopping at the caller's module (`module_qn`).
 * Strategy "lexical_scope"; qualified_name is NULL when no such local exists. */
cbm_resolution_t cbm_registry_resolve_lexical(const cbm_registry_t *r, const char *callee_name,
                                              const char *scope_qn, const char *module_qn);

/* Resolve a callee name using prioritized strategies.
 * import_map: NULL-terminated array of {local_name, resolved_qn} pairs, or NULL.
 * Returns result with qualified_name="" if unresolved.
 * Never returns a data relation (Table/View): relations are lineage-only
 * registry members and common table names (users, orders, config) collide with
 * code identifiers in every language, so the default resolve vetoes them
 * centrally instead of relying on per-consumer label checks. */
cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *callee_name,
                                      const char *module_qn, const char **import_map_keys,
                                      const char **import_map_vals, int import_map_count);

/* Cross-language veto for a CALLS resolution made by a caller written in
 * `caller_lang` (its file's detected language). True when `res` is a
 * name-only answer (qualified_suffix, unique_name, suffix_match, the
 * parallel field_type_hint re-pick, or same_module: two files of different
 * languages with the same path stem share a module QN) whose target's recorded language the
 * caller cannot call (cbm_lang_resolution_compatible): a JS call must never
 * bind a Python symbol by spelling alone. Callers treat a vetoed answer as
 * EMPTY before their empty-resolution fallbacks (route registration, HTTP
 * clients), so those still classify the call. A veto, not a re-pick: the
 * strategy chain is unchanged. Import-map and lsp_* answers are never
 * vetoed; CBM_LANG_COUNT never vetoes. pass_calls.c and pass_parallel.c
 * MUST apply it identically. Pure; unit-tested in test_registry.c. */
bool cbm_registry_name_guess_vetoed(const cbm_registry_t *r, CBMLanguage caller_lang,
                                    const cbm_resolution_t *res);

/* Relation-permitting resolve for SQL FROM/JOIN lineage usages ONLY — the one
 * consumer allowed to bind Table/View targets. Uncached (the per-file resolve
 * cache stores the default variant's relation-vetoed answers). */
cbm_resolution_t cbm_registry_resolve_lineage(const cbm_registry_t *r, const char *callee_name,
                                              const char *module_qn, const char **import_map_keys,
                                              const char **import_map_vals, int import_map_count);

/* Per-file memoization cache for is_import_reachable. Thread-local —
 * each resolve worker owns its own cache. Call _begin at the start
 * of resolve_file_calls (or any per-file resolve loop) and _end at
 * the end. The cache MUST be invalidated between files because
 * is_import_reachable's truth depends on the file's import_vals. */
void cbm_registry_reach_cache_begin(int estimated_capacity);
void cbm_registry_reach_cache_end(void);

/* Per-file import-map prefix → module-QN hash. Turns the linear
 * strcmp scan inside resolve_import_map into O(1). Keys/values are
 * BORROWED — caller must keep the import_map arrays alive for the
 * cache lifetime. Invalidate between files via _end. */
void cbm_registry_import_map_cache_begin(const char **keys, const char **vals, int count);
void cbm_registry_import_map_cache_end(void);

/* Per-file full-result cache for cbm_registry_resolve. The same
 * callee_name appears in many call sites within a file; module_qn
 * is constant per file so each name resolves identically. First
 * lookup does the full strategy chain; repeats are O(1) hash hits.
 * This eliminates ~75% of the resolve-chain work on K8s where the
 * same names ("Get", "Add", "New", etc) appear hundreds of times. */
void cbm_registry_resolve_cache_begin(int estimated_capacity);
void cbm_registry_resolve_cache_end(void);

/* Check if a qualified name exists in the registry. */
bool cbm_registry_exists(const cbm_registry_t *r, const char *qn);

/* True if `name` is one of the curated Perl core builtins (perlfunc). Used by
 * the call-resolution passes to suppress generic-resolver CALLS edges from Perl
 * builtin invocations (push/shift/keys/...) to project subs that merely share
 * the name. Perl-scoped: callers gate on the file language. */
bool cbm_perl_is_builtin(const char *name);

/* Decide whether a resolved Perl call edge is generic-resolver noise to drop
 * (#476): true only for Perl, only for a builtin/method call, and only when the
 * match used a weak short-name strategy — high-confidence same_module/import_map
 * matches are kept. Pure; unit-tested in test_registry.c. */
bool cbm_perl_suppress_generic_match(bool is_perl, bool is_method, const char *callee_name,
                                     const char *strategy);

/* Decide whether a resolved member-call edge is weak-strategy noise to drop
 * (#592/#606/#1276): true only when the CALLER's per-language gate says the
 * guard applies (`enabled`), only for a member call with an unresolved receiver
 * (is_method), and only when the match used a weak short-name strategy
 * (suffix_match / unique_name / field_type_hint / fuzzy).
 * Explicit drop-list keeps every lsp_* / import / same-module / qualified match.
 * The language set lives at the call sites (pass_calls.c / pass_parallel.c) and
 * must be identical in both, or the sequential and parallel resolvers diverge.
 * Pure; unit-tested in test_registry.c. */
bool cbm_suppress_weak_member_match(bool enabled, bool is_method, const char *strategy);

/* True if `name` is a method of a Python builtin type (str/bytes/list/dict/set/
 * file) or a builtin function seen as an attribute call. A language fact, kept
 * as a sorted table like the Perl builtins. */
bool cbm_python_is_builtin_member(const char *name);

/* The member guard's exemption: a Python member call whose receiver is an
 * attribute chain rooted at self/cls (an object the class owns), whose callee has
 * exactly one project definition (strategy unique_name) and is not a builtin
 * type's own method keeps its edge. Combine at the call sites as
 * `suppress && !exempt`; both pass_calls.c and pass_parallel.c must do the same.
 * Pure; unit-tested in test_registry.c. */
bool cbm_weak_member_unique_name_exempt(bool is_python, bool receiver_is_self_attribute,
                                        const char *callee_name, const char *strategy);

/* Bare-call counterpart of the guard above. True when a resolved BARE call edge
 * binds a callee that is shadowed by an enclosing parameter, and the match came
 * from a weak short-name strategy — so the edge is fabricated by construction
 * (`def f(run): run()` must not bind an unrelated `SatoriLive.run`). Shares the
 * member guard's drop-list, so lsp_* / import / same-module matches are kept.
 * Deliberately keyed on the SCOPE FACT, not on the callee's spelling. The
 * language set lives at the call sites (pass_calls.c / pass_parallel.c) and must
 * be identical in both, or the sequential and parallel resolvers diverge.
 * Pure; unit-tested in test_registry.c. */
bool cbm_suppress_weak_local_binding_call(bool enabled, bool callee_is_locally_bound,
                                          const char *strategy);
/* #1355: drop a project-wide same-name guess (suffix_match / unique_name /
 * field_type_hint / fuzzy) for a BARE call whose name the calling file binds to
 * a NON-RELATIVE (package) import that resolved to nothing in the graph —
 * `import { eq } from "drizzle-orm"` must not make `eq(...)` a CALLS edge to an
 * unrelated project `eq`. A name the import map does bind, a relative
 * specifier, a member/qualified callee, and every import-/receiver-aware
 * strategy are all kept. `indexed_packages` is the pipeline package map: a
 * specifier naming a package the tree itself declares (a workspace sibling)
 * counts as in-tree and is kept too; NULL disables that check.
 * `declared_packages` is the pipeline namespace map and does the same job for
 * package-path specifiers, which have no in-tree/external shape of their own:
 * `import org.example.util.assertThing` is kept when some indexed file
 * declares `package org.example.util`; NULL disables that check.
 * Pure; unit-tested in test_registry.c. */
bool cbm_suppress_external_import_shadow(const char *callee_name, const char *strategy,
                                         const CBMImportArray *file_imports,
                                         const char **import_map_keys, int import_map_count,
                                         const CBMHashTable *indexed_packages,
                                         const CBMHashTable *declared_packages);

/* Go analog of the TS/JS guard, same failure class: a selector call whose
 * receiver the Go LSP could not type must not be bound by a receiver-blind
 * short-name strategy. Drops suffix_match / fuzzy always, and unique_name only
 * when its confidence is import-unreachability-penalized (the stdlib/vendor
 * hijack shape). field_type_hint is deliberately NOT dropped for Go — struct
 * fields carry declared types, so the hint is receiver-aware there. */
bool cbm_go_suppress_weak_method_match(bool is_go, bool is_method, const char *strategy,
                                       double confidence);

/* A bare Go `init` (a call or reference that is not the member half of a
 * selector) is always a local name: Go forbids referring to a package init
 * function, and a method or field needs a selector. True when such a name
 * resolved onto a Function (every Go Function named init is a package init;
 * any registry strategy) or onto a Method or Field found by a weak short-name
 * strategy. lsp_* answers are kept. Go only. Pure; unit-tested in
 * test_registry.c; wired in pass_calls.c, pass_usages.c and pass_parallel.c. */
bool cbm_go_suppress_bare_init_bind(bool is_go, bool is_member, const char *name,
                                    const char *strategy, const char *target_label);

/* Import-binding counterpart (#2127). True when the callee's root identifier
 * is bound by an import of this file whose module chain contradicts the
 * resolved target (`from unittest.mock import patch; patch()` must not bind a
 * project `PkgConfigView.patch`), and the match came from a weak short-name
 * strategy. Same drop-list as the guards above; the language set lives at the
 * call sites and must be identical in pass_calls.c and pass_parallel.c.
 * Pure; unit-tested in test_registry.c. */
bool cbm_suppress_weak_import_bound_call(bool enabled, bool import_binding_contradicts,
                                         const char *strategy);

/* #725: drop a suffix_match CALLS edge when the caller language and the
 * target file's language disagree. unique_name (candidates == 1) is #1572
 * and is left alone; same_module / import_map / lsp_* are kept. JS/TS/TSX
 * are one family so a .ts helper calling a .tsx function is not dropped.
 * Pure; unit-tested in test_registry.c. */
bool cbm_suppress_cross_language_suffix_match(CBMLanguage caller_lang, const char *target_file_path,
                                              const char *strategy);

/* #1928: USAGE/WRITES/READS analog of the CALLS guard above. Reference edges
 * resolved by the short-name registry carry no import-closure evidence, so a
 * cross-language binding is a bare-name collision for EVERY strategy — drop
 * it whenever the caller's language and the target file's language disagree
 * (JS/TS family members and the C/C++ header family excepted). Pure;
 * unit-tested in test_registry.c. */
bool cbm_suppress_cross_language_ref(CBMLanguage caller_lang, const char *target_file_path);

/* #1942/#2666: a bare Go or C reference can never denote a struct field —
 * field access is always a selector expression (or, in C, a designator), and
 * the member half of one is recorded as is_member_access. Drops a
 * READS/WRITES/USAGE bind whose target is a Field when the reference was not
 * the member half of a selector. Go and C only: other OO languages (and C++,
 * which every `.h` is parsed as) legitimately reference their own members
 * bare inside method bodies. Pure; unit-tested in test_registry.c. */
bool cbm_suppress_bare_field_ref(CBMLanguage lang, bool is_member_access, const char *target_label);

/* What to do with a call whose registry resolution landed on a Field node.
 * Pure; unit-tested in test_registry.c. */
typedef enum {
    CBM_FIELD_CALL_KEEP = 0, /* not a Field target, or a language this rule leaves alone */
    CBM_FIELD_CALL_DROP,     /* a Field can never be this call's target */
    CBM_FIELD_CALL_BY_OWNER, /* C/C++ member call: the object's type names the Field */
} cbm_field_call_policy_t;
cbm_field_call_policy_t cbm_call_onto_field_policy(CBMLanguage caller_lang, const char *callee_text,
                                                   const char *target_label,
                                                   const char *target_file_path);

/* True for a C/C++ call spelled through an arrow (`p->open(fd)`). The
 * short-name registry splits a callee on `.` and `::` only, so such a call
 * comes back from it unresolved; the caller then asks the object's type for
 * the member, as for a dot call. Pure; unit-tested in test_registry.c. */
bool cbm_c_arrow_member_call(CBMLanguage caller_lang, const char *callee_text);

/* True when a reference is the member half of a C `a.b` / `a->b`. Such a
 * reference binds through the C LSP's field-owner rows (the type of `a`); with
 * no typed owner it binds only cbm_registry_unique_field_qn(). C only. Pure;
 * unit-tested in test_registry.c. */
bool cbm_c_member_binds_by_owner(bool is_c, bool is_member_access);

/* True when a file's member accesses follow the C member rule above: every C
 * file, and every `.h`. A `.h` is parsed as C++ because it may be either, and
 * `a.b` / `a->b` means the same in both: the type of `a` names `b`. Without it
 * the inline functions of a C header kept binding members by bare name. Other
 * C++ files are left to their own resolution. Pure; unit-tested in
 * test_registry.c. */
bool cbm_c_member_rule_file(CBMLanguage lang, const char *rel_path);

/* The QN of the Field `member_name` names when exactly one Field in the
 * registry carries that name (symbols of other labels are not candidates for
 * a member); NULL when none or several do. */
const char *cbm_registry_unique_field_qn(const cbm_registry_t *r, const char *member_name);

/* A Java call expression never names data: `p.x()` is a method invocation
 * whatever `x` spells elsewhere in the project. Drops a CALLS bind whose
 * target is a Variable or Field. Java only — Kotlin properties and C function
 * pointers are callable names that are not methods. Pure; unit-tested in
 * test_registry.c. */
bool cbm_java_suppress_call_to_data_member(bool is_java, const char *target_label);

/* Get the label of a qualified name, or NULL if not found. */
const char *cbm_registry_label_of(const cbm_registry_t *r, const char *qn);

/* A read, a write or a plain value reference never denotes a call: when `qn`
 * is a Method whose class body also declares a same-named field (the extractor
 * fences that field as `<qn>#field`), the field is the target. Returns the
 * field's QN, else `qn`. Pure; unit-tested in test_registry.c. */
const char *cbm_registry_value_target(const cbm_registry_t *r, const char *qn);

/* Find all QNs with a given simple name. Sets *out and *count.
 * Caller does NOT free the array (owned by registry). */
int cbm_registry_find_by_name(const cbm_registry_t *r, const char *name, const char ***out,
                              int *count);

bool cbm_registry_has_type_named(const cbm_registry_t *r, const char *name);

/* Return total number of entries. */
int cbm_registry_size(const cbm_registry_t *r);

/* Find all qualified names ending with ".suffix".
 * Sets *out to heap-allocated array of borrowed string pointers.
 * Caller must free(*out) but NOT the individual strings.
 * Returns count of matches. */
int cbm_registry_find_ending_with(const cbm_registry_t *r, const char *suffix, const char ***out);

/* Check if candidate QN's module prefix is reachable via any import value. */
bool cbm_registry_is_import_reachable(const char *candidate_qn, const char **import_vals,
                                      int import_count);

/* Fuzzy resolve: match callee by bare function name (last segment after dots).
 * Returns result with ok=true if found, ok=false if not.
 * Lower confidence than Resolve (0.40 single, 0.30 multiple). */
typedef struct {
    cbm_resolution_t result;
    bool ok;
} cbm_fuzzy_result_t;

cbm_fuzzy_result_t cbm_registry_fuzzy_resolve(const cbm_registry_t *r, const char *callee_name,
                                              const char *module_qn, const char **import_map_keys,
                                              const char **import_map_vals, int import_map_count);

const char *cbm_confidence_band(double score);

/* ── Git diff hunks (pass_gitdiff.c) ──────────────────────────────
 * Public (unlike the rest of pipeline_internal.h) because detect_changes
 * (src/mcp/mcp.c) scopes seed detection to changed line ranges, not just
 * changed files. */

typedef struct {
    char path[CBM_SZ_512];
    int start_line;
    int end_line;
} cbm_changed_hunk_t;

/* Parse `git diff --unified=0` output into per-hunk (path, start_line,
 * end_line) entries — end_line is the last new-side line the hunk touches.
 * Returns count written to out (capped at max_out). */
int cbm_parse_hunks(const char *output, cbm_changed_hunk_t *out, int max_out);

#endif /* CBM_PIPELINE_H */