grix-connector 3.17.1 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +28 -0
  2. package/dist/adapter/acp/acp-adapter.js +15 -14
  3. package/dist/adapter/claude/claude-adapter.js +21 -21
  4. package/dist/adapter/claude/skill-scanner.js +2 -2
  5. package/dist/adapter/codex/codex-bridge.js +8 -8
  6. package/dist/adapter/codex/codex-trust.js +4 -4
  7. package/dist/adapter/codex/config-overrides.js +1 -0
  8. package/dist/adapter/codex/raw-capture-hook.js +1 -0
  9. package/dist/adapter/opencode/opencode-adapter.js +3 -3
  10. package/dist/adapter/opencode/opencode-transport.js +4 -4
  11. package/dist/adapter/openhuman/openhuman-adapter.js +2 -2
  12. package/dist/adapter/pi/pi-adapter.js +1 -1
  13. package/dist/audit/adapters/codex/codex-audit-adapter.js +1 -1
  14. package/dist/audit/core/audit-options.js +1 -1
  15. package/dist/audit/core/audit-session-registry.js +3 -3
  16. package/dist/audit/core/replay-finalizer.js +1 -1
  17. package/dist/audit/integration/bridge-audit-controller.js +1 -1
  18. package/dist/audit/query/audit-local-actions.js +1 -1
  19. package/dist/audit/raw-capture/adapter-hook.js +0 -0
  20. package/dist/audit/raw-capture/attribution.js +2 -0
  21. package/dist/audit/raw-capture/body-source.js +1 -0
  22. package/dist/audit/raw-capture/capture-relay.js +13 -0
  23. package/dist/audit/raw-capture/redaction.js +1 -0
  24. package/dist/audit/raw-capture/types.js +1 -0
  25. package/dist/audit/storage/file-audit-replay-store.js +2 -2
  26. package/dist/audit/worker/audit-recorder-worker-entry.js +1 -1
  27. package/dist/bridge/bridge.js +9 -9
  28. package/dist/bridge/send-controller.js +3 -3
  29. package/dist/core/aibot/client.js +2 -2
  30. package/dist/core/aibot/connection-handle.js +1 -1
  31. package/dist/core/files/file-serve.js +2 -2
  32. package/dist/core/log/packet-log.js +2 -2
  33. package/dist/core/mcp/tools.js +1 -1
  34. package/dist/core/persistence/session-binding-store.js +1 -1
  35. package/dist/core/persistence/stop-result-outbox.js +2 -0
  36. package/dist/core/persistence/terminal-commit-token-store.js +2 -0
  37. package/dist/core/persistence/terminal-outbox.js +2 -0
  38. package/dist/core/provider-quota/index.js +1 -1
  39. package/dist/core/provider-quota/kiro.js +1 -1
  40. package/dist/core/provider-quota/openai-codex.js +2 -0
  41. package/dist/core/provider-quota/presentation.js +1 -1
  42. package/dist/core/provider-quota/providers.js +2 -2
  43. package/dist/core/proxy/relay-state-sync.js +1 -0
  44. package/dist/default-skills/grix-agent-dispatch/SKILL.md +17 -14
  45. package/dist/default-skills/grix-audit-data/SKILL.md +4 -2
  46. package/dist/default-skills/grix-chat-state/SKILL.md +11 -3
  47. package/dist/default-skills/grix-query/SKILL.md +4 -2
  48. package/dist/default-skills/index.js +1 -1
  49. package/dist/grix.js +7 -7
  50. package/dist/kimi-plugins/grix-layer/SKILL.md +68 -0
  51. package/dist/kimi-plugins/grix-layer/SYSTEM.md +16 -0
  52. package/dist/kimi-plugins/grix-layer/kimi.plugin.json +10 -0
  53. package/dist/kimi-plugins/grix-layer/references/gateway-architecture.md +153 -0
  54. package/dist/kimi-plugins/grix-layer/scripts/gateway.mjs +31 -0
  55. package/dist/kimi-plugins/grix-layer/scripts/lib/architecture-map.mjs +305 -0
  56. package/dist/kimi-plugins/grix-layer/scripts/lib/downstream-client.mjs +133 -0
  57. package/dist/kimi-plugins/grix-layer/scripts/lib/navigation-service.mjs +762 -0
  58. package/dist/kimi-plugins/grix-layer/scripts/lib/normalizers.mjs +202 -0
  59. package/dist/kimi-plugins/grix-layer/scripts/lib/policy.mjs +78 -0
  60. package/dist/kimi-plugins/grix-layer/scripts/lib/response-budget.mjs +83 -0
  61. package/dist/kimi-plugins/grix-layer/scripts/lib/tool-server.mjs +106 -0
  62. package/dist/kimi-plugins/index.js +3 -0
  63. package/dist/manager-share-config.js +1 -1
  64. package/dist/manager.js +2 -2
  65. package/dist/mcp/stream-http/security.js +1 -1
  66. package/dist/service/service-manager.js +3 -3
  67. package/openclaw-plugin/index.js +56 -36
  68. package/openclaw-plugin/skills/grix-query/SKILL.md +6 -2
  69. package/package.json +8 -3
@@ -0,0 +1,16 @@
1
+ # Layered code discovery
2
+
3
+ For any task that requires understanding, locating, diagnosing, reviewing, or
4
+ modifying implementation code, you MUST invoke the `locate-code-by-layer`
5
+ Skill before using file reads, Grep, Glob, or shell commands for discovery.
6
+
7
+ Use `mcp__codebase-navigator__locate_code` with the complete problem and any
8
+ known symbol, path, or exact error. Follow its `status` and `next_action`;
9
+ refine with the same `locator_id`. After `located`, read only the first
10
+ recommended file and exact line range, then form a concrete hypothesis.
11
+
12
+ Never call or configure raw codebase-memory graph tools. They are private
13
+ downstream dependencies of `codebase-navigator`. Repository-wide search is
14
+ forbidden for implementation discovery. Narrow shell search is allowed only
15
+ for exact literals, logs, generated files, documentation, scripts, or paths
16
+ the Gateway explicitly reports as uncovered.
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "grix-layer",
3
+ "version": "1.0.0",
4
+ "description": "Token-bounded, architecture-first code discovery for Grix Kimi agents",
5
+ "systemPromptPath": "./SYSTEM.md",
6
+ "interface": {
7
+ "displayName": "Grix Layer",
8
+ "shortDescription": "Bounded code discovery through codebase-navigator"
9
+ }
10
+ }
@@ -0,0 +1,153 @@
1
+ # Codebase Navigator Gateway
2
+
3
+ ## Purpose
4
+
5
+ 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.
6
+
7
+ ```mermaid
8
+ flowchart LR
9
+ A[Agent] -->|3 bounded MCP tools| G[JS Codebase Navigator]
10
+ G --> D[Codebase dependency check]
11
+ D --> P[Project and index resolver]
12
+ P --> M[Cached architecture map]
13
+ P -->|architecture empty or file hint| E[One bounded exact search]
14
+ M --> C[Layer classifier]
15
+ C --> S[Scoped symbol search]
16
+ C -->|refinement literal| E
17
+ E -->|no exact hit| S
18
+ E -->|exact symbol metadata| B
19
+ S --> V[One-hop relation verifier]
20
+ V --> B[Response budget filter]
21
+ B -->|symbols and line ranges only| A
22
+ D -. private stdio .-> R[codebase-memory-mcp analysis profile]
23
+ P -. private calls .-> R
24
+ M -. private calls .-> R
25
+ S -. private calls .-> R
26
+ E -. private call .-> R
27
+ V -. private calls .-> R
28
+ ```
29
+
30
+ 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.
31
+
32
+ ## Public MCP surface
33
+
34
+ | Tool | Use | Hard behavior |
35
+ | --- | --- | --- |
36
+ | `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 |
37
+ | `refine_location` | Resolve a returned ambiguity | Session-bound, index-bound, maximum two refinements; one exact compact search inside the selected layer |
38
+ | `get_project_outline` | Inspect compact layers | Use only when architecture is uncertain |
39
+
40
+ Raw downstream tools are absent from the public tool list.
41
+
42
+ ## Budgets
43
+
44
+ - Public response: 8 KiB maximum.
45
+ - Candidates: 3.
46
+ - Recommended reads: 2.
47
+ - Related symbols: 5.
48
+ - Architecture layers: 7.
49
+ - Modules in an outline: 12.
50
+ - Search scopes per layer: 3.
51
+ - Internal search results per scope: 20; discarded after ranking.
52
+ - 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.
53
+ - Relation depth: exactly one hop and one direction.
54
+ - Locator lifetime: 15 minutes; maximum two refinements.
55
+ - Downstream MCP message: 4 MiB safety ceiling.
56
+
57
+ 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.
58
+
59
+ ## Architecture maps
60
+
61
+ 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:
62
+
63
+ `~/.cache/codebase-navigator/maps`
64
+
65
+ The directory and files use owner-only permissions. Cache entries contain paths and layer metadata, not source.
66
+
67
+ 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.
68
+
69
+ For nonstandard repositories, add `.codebase-navigator.json` at the indexed project root:
70
+
71
+ ```json
72
+ {
73
+ "style": "hexagonal",
74
+ "layers": [
75
+ {
76
+ "id": "inbound",
77
+ "purpose": "HTTP and message entry adapters",
78
+ "paths": ["src/adapters/inbound"],
79
+ "keywords": ["route", "request", "consumer"]
80
+ },
81
+ {
82
+ "id": "domain",
83
+ "purpose": "Core rules and entities",
84
+ "paths": ["src/domain"],
85
+ "keywords": ["policy", "entity", "validation"]
86
+ }
87
+ ]
88
+ }
89
+ ```
90
+
91
+ Keep configured paths repository-relative. The Gateway reads at most 64 KiB and accepts at most seven layers and three search paths per layer.
92
+
93
+ ## Installation
94
+
95
+ Install dependencies in the skill directory:
96
+
97
+ ```bash
98
+ npm install
99
+ ```
100
+
101
+ Configure only this MCP server for ordinary Agents:
102
+
103
+ ```json
104
+ {
105
+ "mcpServers": {
106
+ "codebase-navigator": {
107
+ "command": "node",
108
+ "args": ["/absolute/path/to/locate-code-by-layer/scripts/gateway.mjs"]
109
+ }
110
+ }
111
+ }
112
+ ```
113
+
114
+ 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.
115
+
116
+ 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.
117
+
118
+ Treat other startup failures separately and ask before changing configuration or permissions:
119
+
120
+ - `dependency_misconfigured`: the configured `CODEBASE_MEMORY_BINARY` cannot be found;
121
+ - `dependency_not_executable`: the binary exists but cannot be executed;
122
+ - `dependency_unhealthy`: the process was found but startup or MCP handshake failed.
123
+
124
+ Do not offer a reinstall for every startup error and do not expose raw downstream stderr, which may contain source paths or code.
125
+
126
+ ## First-time indexing
127
+
128
+ 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.
129
+
130
+ 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.
131
+
132
+ ## Status handling
133
+
134
+ | Status | Agent action |
135
+ | --- | --- |
136
+ | `located` | Read only the returned line ranges |
137
+ | `ambiguous` | Select one layer or candidate with `refine_location` |
138
+ | `architecture_uncertain` | Follow `next_action`: refine the returned locator when present; otherwise inspect the outline |
139
+ | `insufficient_coverage` | Add one narrow hint; if `progress` is `unchanged`, provide an exact symbol/path or report the gap |
140
+ | `dependency_missing` | Explain the dependency and ask whether to install it; `next_action` is `offer_install` |
141
+ | `dependency_misconfigured` | Repair `CODEBASE_MEMORY_BINARY`; `next_action` is `repair_dependency_config` |
142
+ | `dependency_not_executable` | Repair executable permissions or configuration; `next_action` is `repair_dependency_permissions` |
143
+ | `dependency_unhealthy` | Diagnose startup or MCP handshake health; `next_action` is `repair_dependency` |
144
+ | `not_indexed` | Ask whether to index the project outside this read-only Gateway; `next_action` is `offer_index` |
145
+ | `stale_index` | Ask whether to refresh the index and start a new locator; `next_action` is `offer_index_refresh` |
146
+ | `needs_user_input` | Ask for a symbol, error, or path clue |
147
+ | `internal_error` | Inspect Gateway stderr; raw downstream content is intentionally suppressed |
148
+
149
+ ## Agent prompt
150
+
151
+ Use this concise policy in Agent configuration:
152
+
153
+ > 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.
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
4
+ import { DownstreamClient } from "./lib/downstream-client.mjs";
5
+ import { NavigationService } from "./lib/navigation-service.mjs";
6
+ import { createToolServer } from "./lib/tool-server.mjs";
7
+
8
+ const downstream = new DownstreamClient();
9
+ const service = new NavigationService({ downstream });
10
+ const handle = serveStdio(() => createToolServer(service), {
11
+ onerror(error) {
12
+ process.stderr.write(`[codebase-navigator] ${error.message}\n`);
13
+ },
14
+ });
15
+
16
+ let closing = false;
17
+ async function close() {
18
+ if (closing) return;
19
+ closing = true;
20
+ await Promise.allSettled([handle.close(), downstream.close()]);
21
+ }
22
+
23
+ process.once("SIGINT", async () => {
24
+ await close();
25
+ process.exitCode = 130;
26
+ });
27
+ process.once("SIGTERM", async () => {
28
+ await close();
29
+ process.exitCode = 143;
30
+ });
31
+ process.once("beforeExit", close);
@@ -0,0 +1,305 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile, rename, writeFile, chmod } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import {
6
+ LIMITS,
7
+ compactText,
8
+ isPathInside,
9
+ normalizeRepoPath,
10
+ uniqueBy,
11
+ } from "./policy.mjs";
12
+
13
+ const LAYER_DEFINITIONS = [
14
+ {
15
+ id: "presentation",
16
+ purpose: "界面、页面、模板、视图和用户交互",
17
+ pathTokens: ["view", "views", "ui", "web", "page", "pages", "component", "components", "template", "templates"],
18
+ keywords: ["界面", "页面", "显示", "按钮", "表单", "模板", "view", "ui", "page", "component", "render"],
19
+ },
20
+ {
21
+ id: "controller",
22
+ purpose: "请求入口、路由、控制器和输入适配",
23
+ pathTokens: ["controller", "controllers", "route", "routes", "handler", "handlers", "endpoint", "endpoints", "api", "mcp", "cli", "protocol", "server"],
24
+ keywords: ["接口", "请求", "路由", "控制器", "参数", "工具注册", "controller", "route", "handler", "endpoint", "http", "api", "mcp", "cli", "protocol"],
25
+ },
26
+ {
27
+ id: "application",
28
+ purpose: "用例编排、应用服务和业务流程",
29
+ pathTokens: ["application", "app", "service", "services", "usecase", "usecases", "command", "commands", "pipeline", "daemon", "indexer", "parser", "parsers", "analysis"],
30
+ keywords: ["业务流程", "用例", "服务", "编排", "索引", "解析", "service", "usecase", "command", "workflow", "application", "pipeline", "daemon", "indexer", "parser"],
31
+ },
32
+ {
33
+ id: "domain",
34
+ purpose: "领域模型、核心规则和实体",
35
+ pathTokens: ["domain", "model", "models", "entity", "entities", "aggregate", "core", "foundation", "cbm", "graph", "graph_buffer"],
36
+ keywords: ["领域", "模型", "实体", "规则", "校验", "图谱", "domain", "model", "entity", "aggregate", "policy", "graph"],
37
+ },
38
+ {
39
+ id: "data",
40
+ purpose: "持久化、仓储、数据库访问和数据映射",
41
+ pathTokens: ["repository", "repositories", "dao", "data", "database", "db", "persistence", "store", "storage"],
42
+ keywords: ["数据库", "持久化", "仓储", "查询", "保存", "repository", "dao", "database", "sql", "storage"],
43
+ },
44
+ {
45
+ id: "integration",
46
+ purpose: "外部系统、客户端、消息和基础设施适配",
47
+ pathTokens: ["infrastructure", "infra", "adapter", "adapters", "bridge", "client", "clients", "integration", "gateway", "transport"],
48
+ keywords: ["外部", "第三方", "消息", "客户端", "适配器", "会话", "身份", "注入", "infrastructure", "adapter", "bridge", "client", "integration", "transport", "session", "identity", "inject"],
49
+ },
50
+ {
51
+ id: "shared",
52
+ purpose: "跨层公共代码、配置和通用工具",
53
+ pathTokens: ["shared", "common", "util", "utils", "config", "internal", "lib", "pkg"],
54
+ keywords: ["公共", "配置", "工具", "通用", "shared", "common", "util", "config", "helper"],
55
+ },
56
+ ];
57
+
58
+ const IGNORED_PATH = /(^|\/)(test|tests|spec|specs|fixture|fixtures|example|examples|docs?)(\/|$)/i;
59
+
60
+ function segments(folder) {
61
+ return normalizeRepoPath(folder).toLowerCase().split("/").filter(Boolean);
62
+ }
63
+
64
+ function scopePriority(folder) {
65
+ const first = folder.split("/")[0]?.toLowerCase();
66
+ const roots = ["src", "app", "lib", "cmd", "packages", "internal", "pkg"];
67
+ const rootRank = roots.indexOf(first);
68
+ return (rootRank < 0 ? roots.length : rootRank) * 100 + folder.split("/").length;
69
+ }
70
+
71
+ function inferStyle(layers) {
72
+ const ids = new Set(layers.filter((layer) => layer.paths.length).map((layer) => layer.id));
73
+ if (ids.has("controller") && ids.has("domain") && ids.has("presentation")) return "mvc";
74
+ if (ids.has("application") && ids.has("domain") && ids.has("integration")) return "clean";
75
+ if (ids.has("presentation") && ids.has("application")) return "frontend-feature";
76
+ return "layered";
77
+ }
78
+
79
+ function architecturePaths(architecture, folders) {
80
+ const rows = [
81
+ ...(architecture?.layers ?? []),
82
+ ...(architecture?.packages ?? []),
83
+ ...(architecture?.boundaries ?? []),
84
+ ];
85
+ const explicit = rows
86
+ .flatMap((row) => [
87
+ row?.path,
88
+ row?.file_path,
89
+ row?.directory,
90
+ row?.package,
91
+ row?.name,
92
+ ])
93
+ .map(normalizeRepoPath)
94
+ .filter((value) => value.includes("/"));
95
+ const names = rows
96
+ .flatMap((row) => [row?.name, row?.package, row?.from, row?.to])
97
+ .map(normalizeRepoPath)
98
+ .filter((value) => value && !value.includes("/") && !/^test/i.test(value));
99
+ const sourceRoots = folders.filter((folder) =>
100
+ /^(src|app|lib|internal|pkg|cmd|packages)$/i.test(folder),
101
+ );
102
+ const derived = names.flatMap((name) => {
103
+ const existing = folders.filter((folder) => folder.split("/").at(-1) === name);
104
+ return [...existing, ...sourceRoots.map((root) => `${root}/${name}`)];
105
+ });
106
+ return [...explicit, ...derived];
107
+ }
108
+
109
+ function chooseModules(folders) {
110
+ const modules = folders
111
+ .filter((folder) => !IGNORED_PATH.test(folder))
112
+ .filter((folder) => folder.split("/").length <= 4)
113
+ .map((folder) => ({
114
+ id: folder.replaceAll("/", ":"),
115
+ path: folder,
116
+ name: folder.split("/").at(-1),
117
+ }));
118
+ return uniqueBy(modules, (module) => module.path).slice(0, LIMITS.modules);
119
+ }
120
+
121
+ export function buildArchitectureMap({
122
+ project,
123
+ fingerprint,
124
+ folders = [],
125
+ architecture = {},
126
+ override = undefined,
127
+ }) {
128
+ if (override?.layers?.length) {
129
+ return {
130
+ version: 1,
131
+ project,
132
+ fingerprint,
133
+ style: compactText(override.style || "declared", 40),
134
+ source: "project-config",
135
+ layers: override.layers.slice(0, LIMITS.layers).map((layer) => ({
136
+ id: compactText(layer.id, 40),
137
+ purpose: compactText(layer.purpose, 140),
138
+ paths: (layer.paths ?? []).map(normalizeRepoPath).filter(Boolean).slice(0, LIMITS.searchScopes),
139
+ keywords: (layer.keywords ?? []).map((item) => compactText(item, 40)).slice(0, 20),
140
+ modules: (layer.modules ?? []).slice(0, LIMITS.modules),
141
+ })),
142
+ };
143
+ }
144
+
145
+ const available = uniqueBy(
146
+ [...folders, ...architecturePaths(architecture, folders)]
147
+ .map(normalizeRepoPath)
148
+ .filter(Boolean),
149
+ (value) => value,
150
+ );
151
+ const layers = LAYER_DEFINITIONS.map((definition) => {
152
+ const matching = available.filter((folder) => {
153
+ const parts = segments(folder);
154
+ return definition.pathTokens.some((token) => parts.includes(token));
155
+ });
156
+ const shortest = matching
157
+ .sort((a, b) => scopePriority(a) - scopePriority(b) || a.localeCompare(b))
158
+ .slice(0, LIMITS.searchScopes);
159
+ return {
160
+ id: definition.id,
161
+ purpose: definition.purpose,
162
+ paths: shortest,
163
+ keywords: definition.keywords,
164
+ modules: chooseModules(
165
+ available.filter((folder) => shortest.some((scope) => folder.startsWith(`${scope}/`))),
166
+ ),
167
+ };
168
+ }).filter((layer) => layer.paths.length);
169
+
170
+ return {
171
+ version: 1,
172
+ project,
173
+ fingerprint,
174
+ style: inferStyle(layers),
175
+ source: "inferred",
176
+ layers: layers.slice(0, LIMITS.layers),
177
+ };
178
+ }
179
+
180
+ export function classifyProblem(map, { problem, knownSymbol = "", fileHint = "" }) {
181
+ const text = `${problem} ${knownSymbol} ${fileHint}`.toLowerCase();
182
+ const scored = map.layers.map((layer) => {
183
+ let score = 0;
184
+ const reasons = [];
185
+ for (const keyword of layer.keywords ?? []) {
186
+ if (keyword && text.includes(keyword.toLowerCase())) {
187
+ score += keyword.length > 4 ? 3 : 2;
188
+ reasons.push(`keyword:${keyword}`);
189
+ }
190
+ }
191
+ for (const scope of layer.paths ?? []) {
192
+ const scopeText = scope.toLowerCase();
193
+ if (fileHint && scopeText && fileHint.toLowerCase().includes(scopeText)) {
194
+ score += 8;
195
+ reasons.push(`path:${scope}`);
196
+ }
197
+ const leaf = scopeText.split("/").at(-1);
198
+ if (leaf && text.includes(leaf)) {
199
+ score += 4;
200
+ reasons.push(`module:${leaf}`);
201
+ }
202
+ }
203
+ return { layer, score, reasons: reasons.slice(0, 3) };
204
+ }).sort((a, b) => b.score - a.score || a.layer.id.localeCompare(b.layer.id));
205
+
206
+ const top = scored[0];
207
+ const second = scored[1];
208
+ const confident = Boolean(
209
+ top && top.score > 0 && (!second || top.score >= second.score + 2 || top.score >= 7),
210
+ );
211
+ return {
212
+ confident,
213
+ selected: confident ? top : undefined,
214
+ choices: scored.slice(0, 4).map(({ layer, score, reasons }) => ({
215
+ id: layer.id,
216
+ purpose: layer.purpose,
217
+ paths: layer.paths,
218
+ score,
219
+ reasons,
220
+ })),
221
+ };
222
+ }
223
+
224
+ export function architectureSummary(map) {
225
+ return {
226
+ project: map.project,
227
+ style: map.style,
228
+ source: map.source,
229
+ layers: map.layers.map((layer) => ({
230
+ id: layer.id,
231
+ purpose: layer.purpose,
232
+ paths: layer.paths,
233
+ modules: (layer.modules ?? []).slice(0, 5),
234
+ })),
235
+ };
236
+ }
237
+
238
+ export function fingerprintFor(status) {
239
+ return createHash("sha256")
240
+ .update(
241
+ JSON.stringify([
242
+ status.project,
243
+ status.indexedAt,
244
+ status.headSha,
245
+ status.nodes,
246
+ status.edges,
247
+ ]),
248
+ )
249
+ .digest("hex")
250
+ .slice(0, 20);
251
+ }
252
+
253
+ export async function loadProjectOverride(rootPath) {
254
+ if (!rootPath) return undefined;
255
+ const absoluteRoot = path.resolve(rootPath);
256
+ const configPath = path.resolve(absoluteRoot, ".codebase-navigator.json");
257
+ if (!isPathInside(absoluteRoot, configPath)) return undefined;
258
+ try {
259
+ const text = await readFile(configPath, "utf8");
260
+ if (Buffer.byteLength(text, "utf8") > 64 * 1024) return undefined;
261
+ return JSON.parse(text);
262
+ } catch {
263
+ return undefined;
264
+ }
265
+ }
266
+
267
+ export class ArchitectureCache {
268
+ constructor(cacheDir = process.env.CODEBASE_NAVIGATOR_CACHE_DIR ||
269
+ path.join(os.homedir(), ".cache", "codebase-navigator", "maps")) {
270
+ this.cacheDir = cacheDir;
271
+ this.memory = new Map();
272
+ }
273
+
274
+ key(project, fingerprint) {
275
+ return `${project}:${fingerprint}`;
276
+ }
277
+
278
+ file(project, fingerprint) {
279
+ const safe = createHash("sha256").update(this.key(project, fingerprint)).digest("hex");
280
+ return path.join(this.cacheDir, `${safe}.json`);
281
+ }
282
+
283
+ async get(project, fingerprint) {
284
+ const key = this.key(project, fingerprint);
285
+ if (this.memory.has(key)) return this.memory.get(key);
286
+ try {
287
+ const value = JSON.parse(await readFile(this.file(project, fingerprint), "utf8"));
288
+ this.memory.set(key, value);
289
+ return value;
290
+ } catch {
291
+ return undefined;
292
+ }
293
+ }
294
+
295
+ async set(map) {
296
+ const key = this.key(map.project, map.fingerprint);
297
+ this.memory.set(key, map);
298
+ await mkdir(this.cacheDir, { recursive: true, mode: 0o700 });
299
+ const target = this.file(map.project, map.fingerprint);
300
+ const temporary = `${target}.${process.pid}.tmp`;
301
+ await writeFile(temporary, `${JSON.stringify(map)}\n`, { mode: 0o600 });
302
+ await chmod(temporary, 0o600);
303
+ await rename(temporary, target);
304
+ }
305
+ }
@@ -0,0 +1,133 @@
1
+ import { Client } from "@modelcontextprotocol/client";
2
+ import {
3
+ StdioClientTransport,
4
+ getDefaultEnvironment,
5
+ } from "@modelcontextprotocol/client/stdio";
6
+ import { LIMITS, NavigatorError, byteLength } from "./policy.mjs";
7
+
8
+ function parsePayload(result) {
9
+ if (result?.structuredContent && typeof result.structuredContent === "object") {
10
+ return result.structuredContent;
11
+ }
12
+ const texts = (result?.content ?? [])
13
+ .filter((item) => item?.type === "text" && typeof item.text === "string")
14
+ .map((item) => item.text);
15
+ for (const text of texts.toReversed()) {
16
+ try {
17
+ return JSON.parse(text);
18
+ } catch {
19
+ // Some codebase-memory versions add a short notice beside the JSON result.
20
+ }
21
+ }
22
+ throw new NavigatorError("invalid_downstream_response", "图谱服务没有返回结构化 JSON。");
23
+ }
24
+
25
+ export function classifyConnectionError(error, { configuredCommand = false } = {}) {
26
+ if (error instanceof NavigatorError) return error;
27
+ const systemCode = error?.code ?? error?.cause?.code;
28
+ const details = {
29
+ dependency: "codebase-memory-mcp",
30
+ requires_user_confirmation: true,
31
+ };
32
+ if (systemCode === "ENOENT") {
33
+ if (configuredCommand) {
34
+ return new NavigatorError(
35
+ "dependency_misconfigured",
36
+ "CODEBASE_MEMORY_BINARY 指向的 Codebase 可执行文件不存在,请修正配置后重试。",
37
+ details,
38
+ );
39
+ }
40
+ return new NavigatorError(
41
+ "dependency_missing",
42
+ "未找到 codebase-memory-mcp;此技能需要先安装 Codebase,安装前必须征得用户确认。",
43
+ details,
44
+ );
45
+ }
46
+ if (systemCode === "EACCES" || systemCode === "EPERM") {
47
+ return new NavigatorError(
48
+ "dependency_not_executable",
49
+ "Codebase 可执行文件没有执行权限,请修正文件权限或 CODEBASE_MEMORY_BINARY 配置。",
50
+ details,
51
+ );
52
+ }
53
+ return new NavigatorError(
54
+ "dependency_unhealthy",
55
+ "Codebase 已找到,但 MCP 进程启动或握手失败,请检查安装与运行环境后重试。",
56
+ details,
57
+ );
58
+ }
59
+
60
+ export class DownstreamClient {
61
+ constructor(options = {}) {
62
+ const environmentCommand = process.env.CODEBASE_MEMORY_BINARY?.trim() || undefined;
63
+ this.command = options.command ?? environmentCommand ?? "codebase-memory-mcp";
64
+ this.configuredCommand = options.configuredCommand ?? Boolean(environmentCommand);
65
+ this.cwd = options.cwd ?? process.cwd();
66
+ this.timeoutMs = options.timeoutMs ?? LIMITS.requestTimeoutMs;
67
+ this.client = undefined;
68
+ this.transport = undefined;
69
+ this.connecting = undefined;
70
+ }
71
+
72
+ async connect() {
73
+ if (this.client) return;
74
+ if (this.connecting) return this.connecting;
75
+ this.connecting = (async () => {
76
+ const env = getDefaultEnvironment();
77
+ for (const key of ["CBM_CACHE_DIR", "CBM_EMBEDDING_PROVIDER", "CBM_EMBEDDING_MODEL"]) {
78
+ if (process.env[key]) env[key] = process.env[key];
79
+ }
80
+ const transport = new StdioClientTransport({
81
+ command: this.command,
82
+ args: ["--tool-profile=analysis"],
83
+ cwd: this.cwd,
84
+ env,
85
+ stderr: "pipe",
86
+ maxBufferSize: LIMITS.downstreamMessageBytes,
87
+ });
88
+ transport.stderr?.on("data", () => {
89
+ // Intentionally discard downstream diagnostics: they can contain source paths or code.
90
+ });
91
+ const client = new Client({ name: "codebase-navigator-gateway", version: "0.1.0" });
92
+ try {
93
+ await client.connect(transport);
94
+ } catch (error) {
95
+ try {
96
+ await transport.close();
97
+ } catch {
98
+ // Preserve the actionable startup failure instead of a cleanup error.
99
+ }
100
+ throw classifyConnectionError(error, { configuredCommand: this.configuredCommand });
101
+ }
102
+ this.transport = transport;
103
+ this.client = client;
104
+ })();
105
+ try {
106
+ await this.connecting;
107
+ } finally {
108
+ this.connecting = undefined;
109
+ }
110
+ }
111
+
112
+ async call(name, args = {}) {
113
+ await this.connect();
114
+ const result = await this.client.callTool(
115
+ { name, arguments: args },
116
+ { timeout: this.timeoutMs },
117
+ );
118
+ if (result?.isError) {
119
+ throw new NavigatorError("downstream_error", `图谱工具 ${name} 调用失败。`);
120
+ }
121
+ if (byteLength(result) > LIMITS.downstreamMessageBytes) {
122
+ throw new NavigatorError("downstream_budget_exceeded", `图谱工具 ${name} 返回超出内部预算。`);
123
+ }
124
+ return parsePayload(result);
125
+ }
126
+
127
+ async close() {
128
+ const transport = this.transport;
129
+ this.client = undefined;
130
+ this.transport = undefined;
131
+ if (transport) await transport.close();
132
+ }
133
+ }