# Codebase Navigator Gateway

## Purpose

The Gateway is a JavaScript MCP server that sits between an Agent and `codebase-memory-mcp`. The Agent cannot see or invoke raw graph tools. The Gateway performs deterministic routing, bounds every fan-out, discards raw graph payloads, and returns only a small location packet.

```mermaid
flowchart LR
    A[Agent] -->|3 bounded MCP tools| G[JS Codebase Navigator]
    G --> D[Codebase dependency check]
    D --> P[Project and index resolver]
    P --> M[Cached architecture map]
    P -->|architecture empty or file hint| E[One bounded exact search]
    M --> C[Layer classifier]
    C --> S[Scoped symbol search]
    C -->|refinement literal| E
    E -->|no exact hit| S
    E -->|exact symbol metadata| B
    S --> V[One-hop relation verifier]
    V --> B[Response budget filter]
    B -->|symbols and line ranges only| A
    D -. private stdio .-> R[codebase-memory-mcp analysis profile]
    P -. private calls .-> R
    M -. private calls .-> R
    S -. private calls .-> R
    E -. private call .-> R
    V -. private calls .-> R
```

The Gateway has no embedded LLM. Layer selection is explainable and deterministic. When confidence is low, it returns a short list of choices for the calling Agent instead of widening the graph search.

## Public MCP surface

| Tool | Use | Hard behavior |
| --- | --- | --- |
| `locate_code` | Default entry for a bug, feature, or navigation question | Use one exact hinted search when architecture is empty or a file hint is present; otherwise classify a layer and search at most three scopes |
| `refine_location` | Resolve a returned ambiguity | Session-bound, index-bound, maximum two refinements; one exact compact search inside the selected layer |
| `get_project_outline` | Inspect compact layers | Use only when architecture is uncertain |

Raw downstream tools are absent from the public tool list.

## Budgets

- Public response: 8 KiB maximum.
- Candidates: 3.
- Recommended reads: 2.
- Related symbols: 5.
- Architecture layers: 7.
- Modules in an outline: 12.
- Search scopes per layer: 3.
- Internal search results per scope: 20; discarded after ranking.
- Exact hinted/refinement search: one call, compact metadata only, 5 results maximum, zero source context. A file hint limits the path filter; an empty architecture uses a bounded project-wide exact search.
- Relation depth: exactly one hop and one direction.
- Locator lifetime: 15 minutes; maximum two refinements.
- Downstream MCP message: 4 MiB safety ceiling.

The Gateway never auto-paginates, never requests an all-aspects architecture dump, never traces both directions, and never returns source code. If a refinement leaves the graph candidate signature unchanged, it stops and returns `progress: unchanged` instead of repeating the same candidate packet.

## Architecture maps

Maps are inferred from indexed folders and the explicit `layers`, `packages`, `boundaries`, `entry_points`, and `languages` architecture aspects. The result is cached by project and index fingerprint under:

`~/.cache/codebase-navigator/maps`

The directory and files use owner-only permissions. Cache entries contain paths and layer metadata, not source.

Keep the built-in layer vocabulary platform-neutral. Put repository-, product-, protocol-, or framework-specific routing terms in the optional project override instead of hard-coding them into the Gateway.

For nonstandard repositories, add `.codebase-navigator.json` at the indexed project root:

```json
{
  "style": "hexagonal",
  "layers": [
    {
      "id": "inbound",
      "purpose": "HTTP and message entry adapters",
      "paths": ["src/adapters/inbound"],
      "keywords": ["route", "request", "consumer"]
    },
    {
      "id": "domain",
      "purpose": "Core rules and entities",
      "paths": ["src/domain"],
      "keywords": ["policy", "entity", "validation"]
    }
  ]
}
```

Keep configured paths repository-relative. The Gateway reads at most 64 KiB and accepts at most seven layers and three search paths per layer.

## Installation

Grix-managed Kimi sessions receive this Gateway through the connector's authenticated loopback HTTP MCP endpoint. Do not add a plugin-level stdio MCP entry for those sessions: Kimi 0.38 routes stdio children through its Bash-only ACP runtime.

For standalone Agents that execute MCP children locally, configure the stdio server directly:

Install dependencies in the skill directory:

```bash
npm install
```

Configure only this MCP server:

```json
{
  "mcpServers": {
    "codebase-navigator": {
      "command": "node",
      "args": ["/absolute/path/to/locate-code-by-layer/scripts/gateway.mjs"]
    }
  }
}
```

Ensure `codebase-memory-mcp` is on `PATH`, or set `CODEBASE_MEMORY_BINARY` to its absolute executable path. Do not also expose the raw codebase-memory server to the same Agent.

The Gateway does not install this dependency. If startup reports `dependency_missing`, the Agent must explain that Codebase is required and ask the user whether to install it. Only after explicit approval may the Agent use the official Codebase installation workflow and verify that the MCP process starts successfully.

Treat other startup failures separately and ask before changing configuration or permissions:

- `dependency_misconfigured`: the configured `CODEBASE_MEMORY_BINARY` cannot be found;
- `dependency_not_executable`: the binary exists but cannot be executed;
- `dependency_unhealthy`: the process was found but startup or MCP handshake failed.

Do not offer a reinstall for every startup error and do not expose raw downstream stderr, which may contain source paths or code.

## First-time indexing

The Gateway detects index state but remains read-only. When the current directory is not contained by any indexed project, it returns `not_indexed` even if exactly one unrelated indexed project exists. It never falls back to that unrelated project.

For `not_indexed`, the Agent must identify the intended project root and ask whether the user wants an index created with the official Codebase tooling. For `stale_index`, ask whether the existing index should be refreshed. Creating or refreshing an index requires explicit approval; after the operation succeeds, start a new locator rather than reusing the old one.

## Status handling

| Status | Agent action |
| --- | --- |
| `located` | Read only the returned line ranges |
| `ambiguous` | Select one layer or candidate with `refine_location` |
| `architecture_uncertain` | Follow `next_action`: refine the returned locator when present; otherwise inspect the outline |
| `insufficient_coverage` | Add one narrow hint; if `progress` is `unchanged`, provide an exact symbol/path or report the gap |
| `dependency_missing` | Explain the dependency and ask whether to install it; `next_action` is `offer_install` |
| `dependency_misconfigured` | Repair `CODEBASE_MEMORY_BINARY`; `next_action` is `repair_dependency_config` |
| `dependency_not_executable` | Repair executable permissions or configuration; `next_action` is `repair_dependency_permissions` |
| `dependency_unhealthy` | Diagnose startup or MCP handshake health; `next_action` is `repair_dependency` |
| `not_indexed` | Ask whether to index the project outside this read-only Gateway; `next_action` is `offer_index` |
| `stale_index` | Ask whether to refresh the index and start a new locator; `next_action` is `offer_index_refresh` |
| `needs_user_input` | Ask for a symbol, error, or path clue |
| `internal_error` | Inspect Gateway stderr; raw downstream content is intentionally suppressed |

## Agent prompt

Use this concise policy in Agent configuration:

> For code discovery, use only `codebase-navigator`. Start with `locate_code`; refine only a returned locator. Read only `recommended_reads`. For a location-only request, stop at the first direct match. Never call raw codebase-memory tools, auto-page results, perform broad repository search, or read whole source files. If Codebase is missing, ask before installing it. Ask before repairing dependency configuration or permissions. If the index is missing or stale, ask before creating or refreshing it. Never perform these mutations without explicit user approval.
