- name
- codesage-retrieval
- description
- Route semantic and structural code queries through CodeSage. Use for definitions, references, dependencies, impact, features, context, history, risk, test selection, edit checks, and stack traces.
# CodeSage retrieval
<!-- Generated by bin/render-guidance.py from references/help.json. -->
## Establish the project boundary
Use indexed retrieval when `.codesage/index.db` exists and `codesage status` succeeds in the repository under work. Otherwise use `rg`; onboard only when authorized. `help` works in any existing absolute directory. `edit_check` works in a Git repository without an index.
Pass the absolute repository root as `project` on every project-scoped MCP call. Keep repositories separate. The operator tool `daemon_stats` has daemon scope and no project argument. Reuse the global MCP registration; do not create duplicate project registrations. After upgrading, refresh the plugin and start a new host session if newly advertised tools are unavailable.
## Choose by intent and target
Use CodeSage for behavior discovery and code-graph questions. Use `find_symbol` for definitions and `find_references` for structural uses. Use `rg` for literal occurrences, including configuration keys, test names, error messages, documentation, and generated files. Identifier spelling does not choose the tool: every occurrence of `TIMEOUT` needs literal search; its definition needs a symbol query. Prefer the smallest query that answers the question.
Entity tools take `target`, or `targets` for file sets. `trace_call_path` takes `from` and `to`. Accepted forms depend on the tool: `sym:`, `file:`, `dir:`, `chunk:`, and `feat_` handles, indexed paths, `path:line`, qualified or bare names, `route:METHOD path`, and `cmd:name`. Use `help` to check a tool's allowed forms. Prefer returned handles and candidate choices. A handle identifies the intended entity, but name-based union tools can still return uses or similarity seeds shared by several definitions. Do not supply disagreeing legacy and current argument spellings.
## Read freshness by evidence type
Inspect `index.structural`, `index.dirty_paths`, and completeness before acting on structural facts. Structural MCP queries can overlay changes to already indexed files with limits of 50 files and 2 MiB of source, and a cooperative 500 ms preparation budget. A successful overlay reports `index.structural: "overlay"`; changed definitions and source are current within that measured scope. The overlay does not discover newly untracked files. A bound or failure falls back to indexed facts with `index.structural: "dirty"` and `index.overlay.reason`; `index.overlay.checked_all: false` means even the dirty-file scan is incomplete. Follow the recovery command `codesage index` when the overlay cannot cover the required scope.
An overlay does not refresh embeddings, historical observations, or feature membership. Read `index.semantic`, `index.history`, and `index.features` independently. `feature_bundle` can return current source while its selected feature membership remains indexed. Historical co-change observations survive uncommitted source edits because they describe indexed commits; new commits and renames need `codesage git-index` when current history is required. Risk combines those historical observations with structural evidence.
`session_start` and `session_end` compare current structural state, including a successful bounded overlay; inspect their freshness disclosures before trusting the comparison. `edit_check` deliberately compares against pinned Git HEAD and reports working-file divergence. An overlay never changes that contract. A bounded zero or unknown freshness is not proof of freshness.
## Interpret uncertainty
`counts_floor: true` means found evidence is a lower bound; zero means no modelled evidence was found, not proof of absence. Follow both the outer `completeness` and preserved `completeness.prior` limitations. `found: false` means no matching target or path was found in the reported scope; inspect candidates, freshness, and recovery before broadening the claim.
Search `confidence` measures separation in one ranked page, not correctness or a probability that code exists. The legacy coupling `confidence` and `reverse_confidence` fields mean historical conditional co-change fractions; prefer `p_cochange` and `p_reverse`. Risk scores are composite signals, not calibrated failure probabilities. An unscored field is unknown, not zero risk.
## Build the complete patch file set
For patch risk, test selection, and rehearsal, inspect `git status --short --untracked-files=all`, the staged diff, and the unstaged diff. Include all staged, unstaged, and relevant untracked files in the intended patch, deleted paths, and both sides of renames. Inspect unrelated work before excluding it. For a branch review, also inspect the merge-base diff. Bare `git diff --name-only` misses staged and untracked files.
Use the same explicit repository-relative path array for `assess_risk_diff`, `recommend_tests`, and `review_rehearsal`. Put the most important files first for `recommend_tests`: inputs share a bounded walk budget in request order. Read `unwalked_files`, `partial_files`, and `unmodelled`; the suggested subset never replaces required repository suites.
For CLI fallbacks, run from the target repository with individually quoted arguments. Preserve Git's NUL-delimited output if automating collection. Never turn paths into shell source, pipe newline-separated filenames, or use unquoted command substitution. Do not invoke file-set commands with an empty array. In Bash, after constructing the actual `files` array:
```bash
codesage risk-diff -- "${files[@]}"
codesage tests-for -- "${files[@]}"
codesage rehearse -- "${files[@]}"
```
## Account for cost
Start with one focused structural query. `help` and `edit_check` need no index or model. Indexed definitions, references, dependencies, entity cards, and exact-target bundles need no embedding inference, but graph walks, snapshots, and risk can still consume bounded work. `search` and text-target `export_context` require embeddings and may load models or run a reranker. Prefer `feature_bundle` when the mapped slice already supplies the required scope.
Read `cost.ms` and `cost.bytes` on actual responses. Ask `help` for `price_list` to see measured daemon-lifetime latency histograms and sample counts. Those measurements span projects and outcomes; they are observations, not predictions. Missing telemetry reads unknown. Response `budget_tokens` uses an approximate byte conversion, not a tokenizer measurement. Larger response budgets cannot repair a capped graph walk.
## Use recovery and operator paths
Ask `help` with `tool` and optionally `field` for input/output semantics, with `code` for an error, or with `intent` for an ordered investigation recipe. The intents are `review`, `fix_bug`, `rename`, `add_feature`, `before_commit`, and `debug_failure`. Use `tool: "daemon"` to discover operator tools and commands. Recipes supply explicit bindings and stopping conditions; they are plans, not automation or new authority.
When MCP is unavailable, use `codesage --help` and the relevant command's `--help` from the target repository. If daemon startup is the suspected failure, `codesage mcp --direct` exercises the single-process stdio path; do not register it as a second persistent server. Plugin review workflows remain `/codesage-review`, `/codesage-triage`, `/codesage-revalidate`, and `/codesage-report`. Read the selected command's workflow before use; a missing finding never proves a fix.
## Tool selection
| Tool | Use and boundary |
|---|---|
| `mcp__codesage__help` | Explain tool or field semantics, recovery, investigation recipes, and measured daemon latency. Use when arguments or evidence need interpretation; use describe for facts about code. Requires an absolute existing project directory, without an index or model. Select tool=daemon for operator tools. |
| `mcp__codesage__describe` | Inspect one indexed file, symbol, feature, or directory: facts, dependencies, tests, risk, and follow-up calls. Use project_overview for project orientation or export_context for source bundles. Ambiguous targets return candidates; unavailable sections disclose recovery. |
| `mcp__codesage__project_overview` | Orient once at session start: languages, freshness, features, entrypoints, risk, boundaries, and test conventions. Uses structural facts and indexed history without model inference. Use describe for one entity; use search to locate behavior. Inspect freshness and overlay evidence before relying on results. |
| `mcp__codesage__review_rehearsal` | Review an explicit patch file set before committing: ranked objections about risk, tests, cycles, boundaries, and scope, with evidence and suggested checks. Use assess_risk_diff for risk alone. Inspect each objection against the actual patch; this read-only analysis does not run tests. |
| `mcp__codesage__edit_check` | Check a complete replacement declaration against pinned Git HEAD before writing. Reports signature changes, proven incompatible callers where supported, and explicit unknowns. Requires Git, without an index. Use find_references for broader caller discovery. Does not compile, write source, or establish safety. |
| `mcp__codesage__find_symbol` | Locate indexed definitions by name or target, with source locations, kinds, and author rationale. Use find_references for uses of a symbol; use search when its name is unknown. Inspect ambiguous matches before choosing a definition. |
| `mcp__codesage__find_references` | Find indexed calls, imports, and other references to a symbol. Results are name-based evidence and may combine same-named definitions; missing rows do not prove absence. Use find_symbol for definitions or impact_analysis for transitive dependents. |
| `mcp__codesage__find_similar` | Find structurally similar functions or methods before applying a fix across copies. Matches AST shape, ignoring identifiers and literals; same-named definitions share the seed set. Use search for semantic similarity or find_symbol for exact definitions. Test files are excluded. |
| `mcp__codesage__list_dependencies` | List a file's immediate imports and importers. Use for direct file dependencies; use find_references for symbol uses or impact_analysis for transitive dependents. Results describe indexed relationships, not an exhaustive runtime dependency graph. |
| `mcp__codesage__search` | Locate code by behavior or intent using embeddings and optional reranking. Use find_symbol for known definitions or find_references for known uses. Path filtering has approximate recall. Ranking confidence describes score separation, not correctness or proof of absence. |
| `mcp__codesage__trace_call_path` | Trace a forward call chain between two symbols through resolved indexed edges. Use impact_analysis for reverse dependents or from_trace for an observed stack trace. Missing paths do not prove absence; bounded searches may omit paths or shorter alternatives. |
| `mcp__codesage__from_trace` | Map a pasted stack trace or sanitizer report to indexed source locations. Frames disclose resolved, ambiguous, or unresolved matches. Use trace_call_path to investigate graph paths between symbols; use find_references for callers. Paste the original trace without rewriting it. |
| `mcp__codesage__impact_analysis` | Find transitive callers and importers affected by changing a symbol or file. Walks reverse indexed references. Use list_dependencies for immediate file imports or find_references for individual uses. Missing dependents do not prove absence; inspect completeness before treating the result as exhaustive. |
| `mcp__codesage__export_context` | Bundle source and definitions for an entity or free-form question, optionally with callers and callees. Exact entities resolve before model inference; text uses semantic search. Use describe for a compact fact card or feature_bundle for a mapped feature. Resolve ambiguity with returned handles. |
| `mcp__codesage__find_coupling` | Find files that historically change with one file, ranked by decayed co-change evidence. Use recommend_tests for patch test selection or assess_risk for a combined risk score. Missing history is unmeasured; recurring pairs offer stronger evidence than one-off changes. |
| `mcp__codesage__assess_risk` | Assess one file's change risk from history and structural signals. Missing history leaves a partial score, not evidence of safety. Use assess_risk_batch for independent file scores or assess_risk_diff for patch rollups. Inspect the evidence before deciding which checks to run. |
| `mcp__codesage__assess_risk_diff` | Aggregate risk across an explicit patch file set, including hotspots, test gaps, unscored files, and touched import cycles. Use assess_risk_batch for independent scores without patch rollups. Touched cycles may predate the patch; compare the base before claiming a new cycle. |
| `mcp__codesage__assess_risk_batch` | Score each file in a set independently, without patch aggregation. Use assess_risk for one file or assess_risk_diff for patch rollups and touched cycles. Inspect each file's unscored marker; missing history does not imply low risk. |
| `mcp__codesage__recommend_tests` | Recommend tests for changed files using naming conventions, co-change history, and bounded graph reachability. Put priority inputs first because they share a walk budget. Use assess_risk_diff for patch risk. These recommendations are a lower bound, not permission to skip required suites. |
| `mcp__codesage__session_start` | Save current structural state before authorized edits, using a distinct session_id for concurrent sessions. Reusing an ID replaces its baseline. Inspect index.structural for overlay or dirty fallback. Pair with session_end to inspect graph changes. Use project_overview for orientation without persisting a snapshot. |
| `mcp__codesage__list_features` | Discover mapped behavior slices, filtered by kind, language, or tag. Each feature groups entrypoints, owned files, context, tests, and trust boundaries. Use find_feature to locate a file's features or feature_bundle to read a selected slice. |
| `mcp__codesage__find_feature` | Find mapped features containing a file as entrypoint, owned code, context, or test. An empty result means no mapped feature claims the file. Use list_features to discover slices or feature_bundle to read a matched feature. |
| `mcp__codesage__feature_bundle` | Read source and definitions for a mapped feature's entrypoints, owned files, tests, and context. Use list_features or find_feature to discover the feature; use export_context for other targets. Inspect found and completeness before treating an empty bundle as a missing feature. |
| `mcp__codesage__session_end` | Compare current structural state with a session_start baseline: cycles, risk changes, and added or removed files. Inspect index.structural for overlay or dirty fallback. Requires the matching saved session_id; the baseline remains available for repeated comparisons. Use review_rehearsal for patch objections without a baseline. |
## Recovery ladder
### empty
No matching evidence was found in the indexed scope; this does not prove absence.
1. Inspect index freshness and completeness first.
2. Check the target spelling and scope with find_symbol or describe; use returned candidate handles.
3. For literal occurrences or unsupported syntax, search the working tree with rg.
4. Stop when the evidence answers the question; otherwise report the unmeasured scope.
### floor
Counts are lower bounds from modelled or name-based edges. Zero means none found, not none exist.
1. Inspect completeness.recover.reason and ambiguous definitions.
2. Split references by from_file or resolved to handle; inspect source for dynamic or indirect calls.
3. Stop when the requested claim is supported, or retain the lower-bound qualification.
### bounded
An analysis or walk stopped at a time, depth, or work cap.
1. Follow completeness.recover when it gives a call or CLI command, supplying required target arguments for a command synopsis.
2. Narrow the target or split the file set before retrying.
3. Stop if the same bound recurs; inspect source and disclose the remaining scope.
### truncated
Existing rows or payload content were omitted from the delivered response.
1. Inspect total and returned in completeness.recover.
2. Use the supplied recovery arguments only with the same tool; page only when that tool accepts offset.
3. Narrow the target or request a larger supported budget. A walk cap cannot be fixed by a larger response budget.
4. Stop after the required evidence has been retained; do not interpret a shortened page as exhaustive.
### partial
Some inputs, index coverage, or retrieval stages were unavailable.
1. Inspect completeness.recover and per-input reason lists.
2. Reindex when missing or stale index coverage is the cause; investigate lexical_lookup_failed before relying on identifier search ranking.
3. Retry only the affected inputs and retain the missing-scope qualification until measured.
### clamped
At least one requested parameter was adjusted to an allowed value.
1. Compare requested and applied values in completeness.recover.
2. Split the input or use the documented broader CLI surface if the applied cap cannot answer the question.
3. Stop when the applied bounds are sufficient for the intended claim.
### unscored
Evidence needed to compute a score or section was unavailable; absence of a score is not low risk.
1. Inspect the section's recover and the top-level completeness.recover.
2. Run codesage git-index when history is missing, or follow the specific section recovery when a deadline stopped it.
3. Stop when measured, or label that section unscored.
### stale
The response's index or referenced files may differ from the current working tree or HEAD.
1. Inspect index.structural, files_behind, files_behind_bounded, semantic, and dirty_paths.
2. Read changed source before acting. Run codesage index from the project when current indexed facts are needed.
3. Repeat the focused query and verify freshness. A bounded zero or unknown freshness is not proof of freshness.
## Detailed semantics and recipes
The [shared help catalog](references/help.json) is the authored source for this generated skill, tool descriptions, detailed tool semantics, error recovery, and recipes. MCP help embeds the same catalog and obtains field schemas from the live registrations. Edit the catalog and run `python3 plugins/codesage-tools/bin/render-guidance.py --write` from the source checkout; `--check` detects drift. Recover until the requested claim is supported, or report the specific remaining unknown.
Auf GitHub ansehen