Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(code-tools): add code navigation endpoints (#2671)
AutoCoderecced9930a7b
diff --git a/examples/opencode-plugin/index.mjs b/examples/opencode-plugin/index.mjsindex 5fd9e6fa1..f08230651 100644--- a/examples/opencode-plugin/index.mjs+++ b/examples/opencode-plugin/index.mjs@@ -3,6 +3,7 @@ import { fileURLToPath } from "url"import { initializeRuntime } from "./lib/runtime.mjs"import { createRepoContext } from "./lib/repo-context.mjs"import { createMemorySessionManager } from "./lib/memory-session.mjs"+import { createCodeTools } from "./lib/code-tools.mjs"import { createMemoryTools } from "./lib/memory-tools.mjs"import { createMemoryRecall } from "./lib/memory-recall.mjs"import { initLogger, loadConfig, log, resolveDataDir } from "./lib/utils.mjs"@@ -26,6 +27,7 @@ export async function OpenVikingPlugin({ client, directory }) {const sessionManager = createMemorySessionManager({ config, pluginRoot: dataDir })const recall = createMemoryRecall({ config })const tools = createMemoryTools({ config, sessionManager, projectDirectory: directory })+ const codeTools = createCodeTools({ config })await sessionManager.init()@@ -42,7 +44,7 @@ export async function OpenVikingPlugin({ client, directory }) {}},- tool: tools,+ tool: { ...tools, ...codeTools },"experimental.chat.system.transform": (_input, output) => {const prompt = repoContext.getRepoSystemPrompt()@@ -58,6 +60,16 @@ export async function OpenVikingPlugin({ client, directory }) {}},+ "experimental.session.compacting": async (input) => {+ log("INFO", "compaction", "OpenCode session compacting", {+ opencode_session: input.sessionID,+ })+ await sessionManager.flushSession(input.sessionID, {+ commit: true,+ reason: "experimental.session.compacting",+ })+ },+stop: async () => {await sessionManager.flushAll({ commit: true })log("INFO", "plugin", "OpenViking plugin stopped")diff --git a/examples/opencode-plugin/lib/code-tools.mjs b/examples/opencode-plugin/lib/code-tools.mjsnew file mode 100644index 000000000..5b8d47636--- /dev/null+++ b/examples/opencode-plugin/lib/code-tools.mjs@@ -0,0 +1,134 @@+import { tool } from "@opencode-ai/plugin"+import { effectivePeerId, log, makeRequest, unwrapResponse, validateVikingUri } from "./utils.mjs"++const z = tool.schema++const CODE_TOOL_ENDPOINTS = {+ search: "/api/v1/code/search",+ outline: "/api/v1/code/outline",+ expand: "/api/v1/code/expand",+}++function codeToolRequestOptions(kind, { uri, query, symbol, actorPeerId, abortSignal }) {+ const body = { uri }+ if (kind === "search") body.query = query+ if (kind === "expand") body.symbol = symbol++ return {+ method: "POST",+ endpoint: CODE_TOOL_ENDPOINTS[kind],+ body,+ abortSignal,+ actorPeerId,+ }+}++export function createCodeTools({ config }) {+ const actorPeerId = effectivePeerId(config)+ return {+ codesearch: tool({+ description:+ "Search AST-supported symbol names (classes, functions, methods) by substring across a confirmed viking:// code repository or source subtree. " ++ "Use only after you have evidence that the uri contains supported source files. " ++ "Use when you do not know which file contains a symbol. " ++ "Do not use for general memory search, documentation-only resources, plain text notes, chat/session history, or local filesystem paths. " ++ "Returns structured results: symbol name, class context, file URI, line range. " ++ "Typical workflow: verify code repo with ls/glob/add_resource output, then codesearch, codeoutline, codeexpand.",+ args: {+ query: z.string().describe("Symbol name substring to search for (case-insensitive)."),+ uri: z+ .string()+ .describe(+ "Viking URI for a confirmed ingested code repository or source subtree. Do not pass a local path or an unverified viking:// directory.",+ ),+ },+ async execute(args, context) {+ const validationError = validateVikingUri(args.uri, "codesearch")+ if (validationError) return validationError+ try {+ const response = await makeRequest(config, {+ ...codeToolRequestOptions("search", {+ uri: args.uri,+ query: args.query,+ actorPeerId,+ abortSignal: context.abort,+ }),+ })+ return unwrapResponse(response)+ } catch (error) {+ log("ERROR", "codesearch", "Search failed", { error: error?.message, args })+ return `Error: ${error.message}`+ }+ },+ }),++ codeoutline: tool({+ description:+ "Show the symbol structure of a confirmed viking:// source file: classes, functions, methods, and line spans. " ++ "Use only for source files inside an ingested code repository, after you know the exact viking:// file URI. " ++ "Do not use on directories, documentation-only files, plain text notes, or files that are not supported source code. " ++ "Use read instead when you need the full file content.",+ args: {+ uri: z+ .string()+ .describe(+ "Viking URI of a confirmed supported source file, e.g. viking://resources/myproject/src/main.py.",+ ),+ },+ async execute(args, context) {+ const validationError = validateVikingUri(args.uri, "codeoutline")+ if (validationError) return validationError+ try {+ const response = await makeRequest(config, {+ ...codeToolRequestOptions("outline", {+ uri: args.uri,+ actorPeerId,+ abortSignal: context.abort,+ }),+ })+ return unwrapResponse(response)+ } catch (error) {+ log("ERROR", "codeoutline", "Outline failed", { error: error?.message, uri: args.uri })+ return `Error: ${error.message}`+ }+ },+ }),++ codeexpand: tool({+ description:+ "Return the full source of one named symbol from a confirmed viking:// source file. " ++ "Use only after codeoutline or other evidence shows the symbol exists in that file. " ++ "Do not use for broad exploration, non-code files, documentation, chat/session history, or unverified viking:// resources. " ++ "Accepts 'bar' (top-level function or class) or 'Foo.bar' (method inside class Foo). " ++ "For multiple symbols from the same file, read may be more efficient.",+ args: {+ uri: z+ .string()+ .describe("Viking URI of the confirmed supported source file containing the symbol."),+ symbol: z+ .string()+ .describe(+ "Symbol name: 'foo' for top-level, 'Foo.bar' for a method inside class Foo.",+ ),+ },+ async execute(args, context) {+ const validationError = validateVikingUri(args.uri, "codeexpand")+ if (validationError) return validationError+ try {+ const response = await makeRequest(config, {+ ...codeToolRequestOptions("expand", {+ uri: args.uri,+ symbol: args.symbol,+ actorPeerId,+ abortSignal: context.abort,+ }),+ })+ return unwrapResponse(response)+ } catch (error) {+ log("ERROR", "codeexpand", "Expand failed", { error: error?.message, args })+ return `Error: ${error.message}`+ }+ },+ }),+ }+}diff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjsindex 967658035..fd3eba675 100644--- a/examples/opencode-plugin/lib/memory-session.mjs+++ b/examples/opencode-plugin/lib/memory-session.mjs@@ -518,6 +518,27 @@ export function createMemorySessionManager({ config, pluginRoot }) {await saveSessionMap()}+ async function flushSession(opencodeSessionId, { commit = false, reason = "manual" } = {}) {+ const mapping = sessionMap.get(opencodeSessionId)+ if (!mapping) return false++ await flushPendingMessages(opencodeSessionId, mapping)+ if (commit) {+ if (mapping.commitInFlight) {+ monitorBackgroundCommit(mapping, opencodeSessionId)+ } else if (mapping.capturedMessages.size > 0) {+ log("INFO", "session", "Committing OpenViking session at lifecycle boundary", {+ opencode_session: opencodeSessionId,+ openviking_session: mapping.ovSessionId,+ reason,+ })+ await startBackgroundCommit(mapping, opencodeSessionId)+ }+ }+ await saveSessionMap()+ return true+ }+async function commitSession(sessionId, opencodeSessionId, abortSignal) {let mapping = opencodeSessionId ? sessionMap.get(opencodeSessionId) : undefinedif (!mapping || mapping.ovSessionId !== sessionId) {@@ -546,6 +567,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {getMappedSessionId,commitSession,flushAll,+ flushSession,}function createSessionMapping(ovSessionId) {diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.jsonindex d2c6b655d..85fdf7995 100644--- a/examples/opencode-plugin/package.json+++ b/examples/opencode-plugin/package.json@@ -16,7 +16,8 @@"INSTALL-ZH.md"],"scripts": {- "check": "node --check index.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memadd-local.mjs && node --check lib/memory-tools.mjs && node --check lib/memory-recall.mjs && node --check lib/utils.mjs"+ "check": "node --check index.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memadd-local.mjs && node --check lib/memory-tools.mjs && node --check lib/code-tools.mjs && node --check lib/memory-recall.mjs && node --check lib/utils.mjs && node --check tests/code-tools-request-options.test.mjs",+ "test": "node --test tests/*.test.mjs"},"dependencies": {"@opencode-ai/plugin": "^1.14.37"diff --git a/examples/opencode-plugin/tests/code-tools-request-options.test.mjs b/examples/opencode-plugin/tests/code-tools-request-options.test.mjsnew file mode 100644index 000000000..7503c4d0e--- /dev/null+++ b/examples/opencode-plugin/tests/code-tools-request-options.test.mjs@@ -0,0 +1,27 @@+import test from "node:test"+import assert from "node:assert/strict"+import { readFile } from "node:fs/promises"+import { fileURLToPath } from "node:url"+import { dirname, join } from "node:path"++const testDir = dirname(fileURLToPath(import.meta.url))+const codeToolsPath = join(testDir, "../lib/code-tools.mjs")++test("code tools propagate actorPeerId to every code request", async () => {+ const source = await readFile(codeToolsPath, "utf8")++ assert.match(source, /import \{ effectivePeerId,/)+ assert.match(source, /const actorPeerId = effectivePeerId\(config\)/)+ assert.equal((source.match(/actorPeerId,\n\s+abortSignal: context\.abort/g) ?? []).length, 3)+})++test("code tool descriptions restrict use to confirmed viking code repositories", async () => {+ const source = await readFile(codeToolsPath, "utf8")++ assert.match(source, /confirmed viking:\/\/ code repository or source subtree/)+ assert.match(source, /evidence that the uri contains supported source files/)+ assert.match(source, /Do not use for general memory search/)+ assert.match(source, /documentation-only resources/)+ assert.match(source, /chat\/session history/)+ assert.match(source, /local filesystem paths/)+})diff --git a/openviking/parse/parsers/code/ast/code_tools.py b/openviking/parse/parsers/code/ast/code_tools.pyindex 4873b8623..f43b5b20c 100644--- a/openviking/parse/parsers/code/ast/code_tools.py+++ b/openviking/parse/parsers/code/ast/code_tools.py@@ -18,6 +18,38 @@ from openviking.parse.parsers.code.ast.skeleton import (_compact_params,)+CODE_SEARCH_FILE_CAP = 200+CODE_SEARCH_CONCURRENCY = 10+++def _entry_field(entry, key: str, fallback_key: str, default):+ """Read a field from ls entries that may be dicts (camelCase) or objects (snake_case)."""+ if isinstance(entry, dict):+ return entry.get(key, default)+ return getattr(entry, fallback_key, default)+++def filter_code_uris(entries) -> tuple[list[str], bool]:+ """Pick file entries whose extension is supported by the AST extractor, capped at 200.++ Returns (uris, capped) where capped is True when the 200-file limit was hit+ and there may be more matching files beyond the cap.+ """+ extractor = get_extractor()+ uris: list[str] = []+ for e in entries:+ is_dir = _entry_field(e, "isDir", "is_dir", False)+ if is_dir:+ continue+ entry_uri = _entry_field(e, "uri", "uri", "")+ if not entry_uri:+ continue+ if extractor.supports(entry_uri):+ uris.append(entry_uri)+ if len(uris) > CODE_SEARCH_FILE_CAP:+ return uris[:CODE_SEARCH_FILE_CAP], True+ return uris, False+def _line_span(item) -> str:if item.line_start and item.line_end:diff --git a/openviking/parse/parsers/code/ast/extractor.py b/openviking/parse/parsers/code/ast/extractor.pyindex fee68b992..127794ebe 100644--- a/openviking/parse/parsers/code/ast/extractor.py+++ b/openviking/parse/parsers/code/ast/extractor.py@@ -65,8 +65,17 @@ class ASTExtractor:self._cache: Dict[str, Optional[LanguageExtractor]] = {}def _detect_language(self, file_name: str) -> Optional[str]:- suffix = Path(file_name).suffix.lower()- return _EXT_MAP.get(suffix)+ path = Path(file_name)+ lang = _EXT_MAP.get(path.suffix.lower())+ if lang is not None:+ return lang+ # Viking resource convention: a file uploaded as <NAME.ext> is stored as a+ # directory <NAME.ext>/ containing the content under a "<NAME>.md" body+ # (e.g. foo.py/foo.md). When the file's own suffix is unsupported (.md),+ # fall back to the parent directory's suffix to recover the language.+ if path.suffix.lower() == ".md" and path.parent.name:+ return _EXT_MAP.get(Path(path.parent.name).suffix.lower())+ return Nonedef _get_extractor(self, lang: Optional[str]) -> Optional[LanguageExtractor]:if lang is None or lang not in _EXTRACTOR_REGISTRY:diff --git a/openviking/parse/parsers/markdown.py b/openviking/parse/parsers/markdown.pyindex c53d6cfad..71a43f55e 100644--- a/openviking/parse/parsers/markdown.py+++ b/openviking/parse/parsers/markdown.py@@ -30,6 +30,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Unionfrom openviking.parse.accessors.mime_types import IANA_MEDIA_TYPE_TO_EXTENSIONfrom openviking.parse.base import NodeType, ParseResult, ResourceNode, create_parse_resultfrom openviking.parse.parsers.base_parser import BaseParser+from openviking.parse.parsers.code.ast.extractor import get_extractorfrom openviking.parse.parsers.constants import (CODE_EXTENSIONS,DOCUMENTATION_EXTENSIONS,@@ -359,7 +360,14 @@ class MarkdownParser(BaseParser):else "Document",)doc_name = self._sanitize_for_path(doc_title)- root_dir = f"{temp_uri}/{doc_name}"+ # Preserve code source filenames as the temp document directory.+ # This yields foo.py/foo.md, allowing AST language detection to recover+ # ".py" from the parent directory while keeping the markdown body name tidy.+ source_name = kwargs.get("source_name")+ root_name = (+ source_name if source_name and get_extractor().supports(source_name) else doc_name+ )+ root_dir = f"{temp_uri}/{self._sanitize_for_path(root_name)}"# Find all headingsheadings = self._find_headings(content)@@ -619,7 +627,7 @@ class MarkdownParser(BaseParser):# Copy each local image next to the markdown file, deduplicating namesused_names: set[str] = set()file_mappings: Dict[str, str] = {} # original_path_str -> unique_filename- for origin_link, resolved_path in zip(origin_images_links, local_images):+ for origin_link, resolved_path in zip(origin_images_links, local_images, strict=False):try:if not await asyncio.to_thread(resolved_path.exists):logger.warning(f"[MarkdownParser] Image file not found: {resolved_path}")diff --git a/openviking/server/app.py b/openviking/server/app.pyindex bdea7a580..f221b289b 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -31,6 +31,7 @@ from openviking.server.profile_middleware import create_profile_http_middlewarefrom openviking.server.routers import (admin_router,bot_router,+ code_router,console_router,content_router,debug_router,@@ -524,6 +525,7 @@ def create_app(app.include_router(content_router)app.include_router(console_router)app.include_router(search_router)+ app.include_router(code_router)app.include_router(relations_router)app.include_router(privacy_configs_router)app.include_router(skills_router)diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 965ffcc6c..3a7cc027c 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -32,11 +32,12 @@ from starlette.responses import JSONResponsefrom starlette.types import ASGIApp, Receive, Scope, Sendfrom openviking.parse.parsers.code.ast.code_tools import (+ CODE_SEARCH_CONCURRENCY,expand_symbol,+ filter_code_uris,outline_file,search_symbols,)-from openviking.parse.parsers.code.ast.extractor import get_extractorfrom openviking.server.auth import normalize_actor_peer_header, resolve_identityfrom openviking.server.dependencies import get_server_config, get_servicefrom openviking.server.identity import RequestContext@@ -54,6 +55,9 @@ from openviking_cli.exceptions import (from openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_logger+# Backwards-compatible alias for existing tests that import this private name.+_filter_code_uris = filter_code_uris+logger = get_logger(__name__)# ---------------------------------------------------------------------------@@ -787,10 +791,6 @@ async def forget(uri: str, recursive: bool = False) -> str:# -- code navigation --------------------------------------------------------_CODE_SEARCH_FILE_CAP = 200-_CODE_SEARCH_CONCURRENCY = 10--def _require_viking_uri(uri: str) -> Optional[str]:"""Return error message if uri is not a viking:// URI, else None."""if not isinstance(uri, str) or not uri.startswith("viking://"):@@ -801,42 +801,16 @@ def _require_viking_uri(uri: str) -> Optional[str]:return None-def _entry_field(entry, key: str, fallback_key: str, default):- """ls entries are dicts (camelCase) or objects (snake_case); read both."""- if isinstance(entry, dict):- return entry.get(key, default)- return getattr(entry, fallback_key, default)---def _filter_code_uris(entries) -> tuple[list[str], bool]:- """Pick file entries whose extension is supported by the AST extractor, capped.-- Returns (uris, capped) where capped is True when the 200-file limit was hit- and there may be more matching files beyond the cap.- """- extractor = get_extractor()- uris: list[str] = []- for e in entries:- is_dir = _entry_field(e, "isDir", "is_dir", False)- if is_dir:- continue- entry_uri = _entry_field(e, "uri", "uri", "")- if not entry_uri:- continue- if extractor.supports(entry_uri):- uris.append(entry_uri)- if len(uris) > _CODE_SEARCH_FILE_CAP:- return uris[:_CODE_SEARCH_FILE_CAP], True- return uris, False--@mcp.tool()async def code_outline(uri: str) -> str:- """Show a file's symbol structure — classes, functions, methods, and their line ranges.- Returns a structural map without reading implementation bodies.+ """Show a confirmed viking:// source file's symbol structure: classes, functions,+ methods, and line ranges. Returns a structural map without reading implementation bodies.++ Use only for source files inside an ingested code repository, after you know the exact+ viking:// file URI. Do not use on directories, documentation-only files, plain text notes,+ chat/session history, or files that are not supported source code.- Use to survey a file before deciding what to read. More efficient than reading the whole- file when you only need to locate a method or understand a file's API surface.+ Use read instead when you need the full file content.Typical workflow: code_search → code_outline → code_expand.uri must be a viking:// file URI (not a directory)."""@@ -856,13 +830,17 @@ async def code_outline(uri: str) -> str:@mcp.tool()async def code_search(query: str, uri: str) -> str:- """Search symbol names (class / function / method) by substring across a viking://- directory. Returns structured results: symbol type, class context, file URI, line range.+ """Search AST-supported symbol names (class / function / method) by substring across a+ confirmed viking:// code repository or source subtree. Returns structured results:+ symbol type, class context, file URI, line range.- Use when you don't know which file contains the symbol you're looking for. Returns- structural context (class ownership, location) that raw text search does not provide.+ Use only after you have evidence that the uri contains supported source files. If you have+ not confirmed that this is an ingested code repository, first use ls/glob/read or+ add_resource output to verify it.- Skip if you already know the exact file; use code_outline or Read directly.+ Do not use for general memory search, documentation-only resources, plain text notes,+ chat/session history, or local filesystem paths. Skip if you already know the exact file;+ use code_outline or read directly.Scans up to 200 source files. Narrow uri to a subdirectory for deeper coverage.uri is required to avoid accidentally walking the entire VikingFS."""@@ -879,11 +857,11 @@ async def code_search(query: str, uri: str) -> str:except Exception as exc:return f"Error: failed to list {uri}: {exc}"- code_uris, capped = _filter_code_uris(entries or [])+ code_uris, capped = filter_code_uris(entries or [])if not code_uris:return f"No supported source files found under {uri}"- semaphore = asyncio.Semaphore(_CODE_SEARCH_CONCURRENCY)+ semaphore = asyncio.Semaphore(CODE_SEARCH_CONCURRENCY)async def _read(u: str) -> Optional[tuple[str, str]]:async with semaphore:@@ -906,11 +884,13 @@ async def code_search(query: str, uri: str) -> str:@mcp.tool()async def code_expand(uri: str, symbol: str) -> str:- """Return the full source of a single named symbol (function, class, or method).+ """Return the full source of a single named symbol from a confirmed viking:// source file.Reads only that symbol's body, avoiding the overhead of reading an entire file.- Use when you need the implementation of one specific symbol. For reading multiple- symbols from the same file, Read is often more efficient.+ Use only after code_outline or other evidence shows the symbol exists in that file.+ Do not use for broad exploration, non-code files, documentation, chat/session history,+ or unverified viking:// resources. For reading multiple symbols from the same file,+ read is often more efficient.`symbol` accepts 'bar' (top-level) or 'Foo.bar' (method).uri must be a viking:// file URI."""diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.pyindex 1d3508688..ded23d489 100644--- a/openviking/server/routers/__init__.py+++ b/openviking/server/routers/__init__.py@@ -4,6 +4,7 @@from openviking.server.routers.admin import router as admin_routerfrom openviking.server.routers.bot import router as bot_router+from openviking.server.routers.code import router as code_routerfrom openviking.server.routers.console import router as console_routerfrom openviking.server.routers.content import router as content_routerfrom openviking.server.routers.debug import router as debug_router@@ -26,6 +27,7 @@ from openviking.server.routers.webdav import router as webdav_router__all__ = ["admin_router","bot_router",+ "code_router","system_router","resources_router","filesystem_router",diff --git a/openviking/server/routers/code.py b/openviking/server/routers/code.pynew file mode 100644index 000000000..a361f0a2c--- /dev/null+++ b/openviking/server/routers/code.py@@ -0,0 +1,127 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Code navigation endpoints for OpenViking HTTP Server."""++import asyncio++from fastapi import APIRouter, Depends+from pydantic import BaseModel++from openviking.parse.parsers.code.ast.code_tools import (+ CODE_SEARCH_CONCURRENCY,+ expand_symbol,+ filter_code_uris,+ outline_file,+ search_symbols,+)+from openviking.server.auth import get_request_context+from openviking.server.dependencies import get_service+from openviking.server.identity import RequestContext+from openviking.server.models import Response+from openviking_cli.utils import get_logger++logger = get_logger(__name__)++router = APIRouter(prefix="/api/v1/code", tags=["code"])++_ERROR_NOT_VIKING = (+ "Error: only viking:// URIs are supported; "+ "use add_resource to ingest local code as a viking:// resource first."+)+++class CodeOutlineRequest(BaseModel):+ uri: str+++class CodeSearchRequest(BaseModel):+ uri: str+ query: str+++class CodeExpandRequest(BaseModel):+ uri: str+ symbol: str++[email protected]("/outline")+async def code_outline_endpoint(+ request: CodeOutlineRequest,+ _ctx: RequestContext = Depends(get_request_context),+):+ if not request.uri.startswith("viking://"):+ return Response(status="ok", result=_ERROR_NOT_VIKING).model_dump(exclude_none=True)+ service = get_service()+ content = await service.fs.read(request.uri, ctx=_ctx)+ if not isinstance(content, str):+ return Response(+ status="ok", result=f"Error: {request.uri} is not text"+ ).model_dump(exclude_none=True)+ return Response(status="ok", result=outline_file(content, request.uri)).model_dump(+ exclude_none=True+ )++[email protected]("/search")+async def code_search_endpoint(+ request: CodeSearchRequest,+ _ctx: RequestContext = Depends(get_request_context),+):+ if not request.uri.startswith("viking://"):+ return Response(status="ok", result=_ERROR_NOT_VIKING).model_dump(exclude_none=True)+ if not request.query:+ return Response(status="ok", result="Error: empty query").model_dump(exclude_none=True)+ service = get_service()+ entries = await service.fs.ls(request.uri, ctx=_ctx, recursive=True, output="original")+ code_uris, capped = filter_code_uris(entries or [])+ if not code_uris:+ return Response(+ status="ok",+ result=f"No supported source files found under {request.uri}",+ ).model_dump(exclude_none=True)++ semaphore = asyncio.Semaphore(CODE_SEARCH_CONCURRENCY)++ async def _read_one(uri: str):+ async with semaphore:+ try:+ body = await service.fs.read(uri, ctx=_ctx)+ except Exception as exc:+ logger.warning("code_search: read failed for %s: %s", uri, exc)+ return None, uri+ return ((body, uri) if isinstance(body, str) else None), uri++ fetched = await asyncio.gather(*[_read_one(u) for u in code_uris])+ files = [pair for pair, _uri in fetched if pair is not None]+ failed_reads = len(fetched) - len(files)+ if failed_reads == len(code_uris):+ return Response(+ status="ok",+ result=f"Error: failed to read all {len(code_uris)} source files under {request.uri}",+ ).model_dump(exclude_none=True)+ result = search_symbols(request.query, files)+ if failed_reads:+ result += f"\n\n(warning: skipped {failed_reads} unreadable source file(s))"+ if capped:+ result += "\n\n(scanning stopped at 200-file cap; narrow uri to search more)"+ return Response(status="ok", result=result).model_dump(exclude_none=True)++[email protected]("/expand")+async def code_expand_endpoint(+ request: CodeExpandRequest,+ _ctx: RequestContext = Depends(get_request_context),+):+ if not request.uri.startswith("viking://"):+ return Response(status="ok", result=_ERROR_NOT_VIKING).model_dump(exclude_none=True)+ if not request.symbol:+ return Response(status="ok", result="Error: empty symbol").model_dump(exclude_none=True)+ service = get_service()+ content = await service.fs.read(request.uri, ctx=_ctx)+ if not isinstance(content, str):+ return Response(+ status="ok", result=f"Error: {request.uri} is not text"+ ).model_dump(exclude_none=True)+ return Response(+ status="ok", result=expand_symbol(content, request.uri, request.symbol)+ ).model_dump(exclude_none=True)diff --git a/tests/parse/test_ast_extractor.py b/tests/parse/test_ast_extractor.pyindex 97b54d9ef..5c2f132d2 100644--- a/tests/parse/test_ast_extractor.py+++ b/tests/parse/test_ast_extractor.py@@ -1434,3 +1434,21 @@ class TestASTExtractorDispatch:verbose = self.extractor.extract_skeleton("m.py", code, verbose=True)assert "Detail here." not in compactassert "Detail here." in verbose++ def test_viking_resource_md_uses_parent_extension(self):+ # Viking add-resource stores `foo.py` as directory `foo.py/` with body+ # `foo.py/foo.md`. Language detection must fall back to the parent+ # directory's suffix so code tools recognise the original language.+ code = "def foo(x):\n return x\n"+ viking_uri = "viking://resources/test-code.py/test-code.md"+ assert self.extractor.supports(viking_uri)+ assert self.extractor._detect_language(viking_uri) == "python"+ text = self.extractor.extract_skeleton(viking_uri, code)+ assert text is not None+ assert "def foo" in text++ def test_plain_markdown_still_unsupported(self):+ # A genuine markdown file (no language-bearing parent) must not be+ # treated as code.+ assert not self.extractor.supports("notes.md")+ assert not self.extractor.supports("viking://resources/notes.md")diff --git a/tests/parse/test_code_tools.py b/tests/parse/test_code_tools.pyindex 55a2333b2..36a98c47f 100644--- a/tests/parse/test_code_tools.py+++ b/tests/parse/test_code_tools.py@@ -379,3 +379,63 @@ class TestExpandSymbol:def test_expand_qualified_missing_class(self):out = expand_symbol(PY_SAMPLE, "greeter.py", "NoSuchClass.greet")assert "symbol 'NoSuchClass.greet' not found" in out+++# ---------------------------------------------------------------------------+# filter_code_uris+# ---------------------------------------------------------------------------++from types import SimpleNamespace # noqa: E402++from openviking.parse.parsers.code.ast.code_tools import ( # noqa: E402+ CODE_SEARCH_FILE_CAP,+ filter_code_uris,+)+++class TestFilterCodeUris:+ def test_keeps_supported_extensions(self):+ entries = [+ {"uri": "viking://r/a.py", "isDir": False},+ {"uri": "viking://r/b.md", "isDir": False},+ {"uri": "viking://r/c.ts", "isDir": False},+ {"uri": "viking://r/d.txt", "isDir": False},+ ]+ uris, capped = filter_code_uris(entries)+ assert uris == ["viking://r/a.py", "viking://r/c.ts"]+ assert capped is False++ def test_skips_directories(self):+ entries = [+ {"uri": "viking://r/sub", "isDir": True},+ {"uri": "viking://r/a.py", "isDir": False},+ ]+ uris, capped = filter_code_uris(entries)+ assert uris == ["viking://r/a.py"]+ assert capped is False++ def test_object_entries_snake_case(self):+ entries = [+ SimpleNamespace(uri="viking://r/a.py", is_dir=False),+ SimpleNamespace(uri="viking://r/sub", is_dir=True),+ ]+ uris, capped = filter_code_uris(entries)+ assert uris == ["viking://r/a.py"]+ assert capped is False++ def test_exactly_200_not_capped(self):+ entries = [{"uri": f"viking://r/f{i}.py", "isDir": False} for i in range(200)]+ uris, capped = filter_code_uris(entries)+ assert len(uris) == 200+ assert capped is False++ def test_201_files_triggers_cap(self):+ entries = [{"uri": f"viking://r/f{i}.py", "isDir": False} for i in range(201)]+ uris, capped = filter_code_uris(entries)+ assert len(uris) == CODE_SEARCH_FILE_CAP+ assert capped is True++ def test_empty_entries(self):+ uris, capped = filter_code_uris([])+ assert uris == []+ assert capped is Falsediff --git a/tests/parse/test_markdown_filename_collision.py b/tests/parse/test_markdown_filename_collision.pyindex dc6b7ca4a..1ff44a254 100644--- a/tests/parse/test_markdown_filename_collision.py+++ b/tests/parse/test_markdown_filename_collision.py@@ -42,3 +42,44 @@ class TestGenerateMergedFilenameCollision:"""Empty sections list should return 'merged'."""parser = self._make_parser()assert parser._generate_merged_filename([]) == "merged"+++class TestMarkdownSourceNameLayout:+ def _make_parser(self) -> MarkdownParser:+ return MarkdownParser(ParserConfig())++ async def test_non_code_source_name_uses_stemmed_root(self):+ parser = self._make_parser()++ layout = await parser._compute_layout(+ "hello world\n",+ "viking://temp/test",+ source_name="aa.txt",+ )++ assert layout.root_dir == "viking://temp/test/aa"+ assert any(op.uri == "viking://temp/test/aa/aa.md" for op in layout.ops)++ async def test_code_source_name_preserves_extension_in_root(self):+ parser = self._make_parser()++ layout = await parser._compute_layout(+ "def foo():\n return 1\n",+ "viking://temp/test",+ source_name="foo.py",+ )++ assert layout.root_dir == "viking://temp/test/foo.py"+ assert any(op.uri == "viking://temp/test/foo.py/foo.md" for op in layout.ops)++ async def test_unsupported_code_source_name_uses_stemmed_root(self):+ parser = self._make_parser()++ layout = await parser._compute_layout(+ "echo hello\n",+ "viking://temp/test",+ source_name="script.sh",+ )++ assert layout.root_dir == "viking://temp/test/script"+ assert any(op.uri == "viking://temp/test/script/script.md" for op in layout.ops)diff --git a/tests/server/test_api_code.py b/tests/server/test_api_code.pynew file mode 100644index 000000000..614b72391--- /dev/null+++ b/tests/server/test_api_code.py@@ -0,0 +1,309 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for /api/v1/code/* endpoints."""++import pytest++from openviking_cli.exceptions import PermissionDeniedError++PY_SAMPLE = '''"""Module top doc."""+++class Greeter:+ def greet(self, who: str) -> str:+ return f"Hello {who}"+++def make_greeter() -> Greeter:+ return Greeter()+'''+++# ---------------------------------------------------------------------------+# /api/v1/code/outline+# ---------------------------------------------------------------------------+++class TestCodeOutlineEndpoint:+ async def test_success(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/outline", json={"uri": "viking://resources/greeter.py"}+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "class Greeter" in body["result"]+ assert "def make_greeter" in body["result"]++ async def test_invalid_uri(self, client):+ resp = await client.post("/api/v1/code/outline", json={"uri": "/tmp/foo.py"})+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert body["result"].startswith("Error:")+ assert "viking://" in body["result"]++ async def test_read_permission_denied_uses_error_response(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ raise PermissionDeniedError("denied")++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/outline", json={"uri": "viking://resources/x.py"}+ )+ assert resp.status_code == 403+ body = resp.json()+ assert body["status"] == "error"+ assert body["error"]["code"] == "PERMISSION_DENIED"++ async def test_unsupported_language(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return "# just a markdown heading"++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/outline", json={"uri": "viking://resources/notes.md"}+ )+ assert resp.status_code == 200+ assert resp.json()["result"].startswith("Error: unsupported language")++ async def test_non_text_content(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return b"\x00\x01binary"++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/outline", json={"uri": "viking://resources/x.py"}+ )+ assert resp.status_code == 200+ assert "is not text" in resp.json()["result"]+++# ---------------------------------------------------------------------------+# /api/v1/code/search+# ---------------------------------------------------------------------------+++class TestCodeSearchEndpoint:+ async def test_success(self, client, service, monkeypatch):+ async def fake_ls(uri, ctx=None, recursive=False, output=None, **_):+ return [+ {"uri": "viking://r/a.py", "isDir": False},+ {"uri": "viking://r/sub", "isDir": True},+ ]++ async def fake_read(uri, ctx=None, **_):+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "ls", fake_ls)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": "greet"}+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "Greeter" in body["result"]+ assert "viking://r/a.py" in body["result"]++ async def test_invalid_uri(self, client):+ resp = await client.post(+ "/api/v1/code/search", json={"uri": "/tmp/dir", "query": "foo"}+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["result"].startswith("Error:")+ assert "viking://" in body["result"]++ async def test_empty_query(self, client):+ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": ""}+ )+ assert resp.status_code == 200+ assert resp.json()["result"] == "Error: empty query"++ async def test_no_code_files(self, client, service, monkeypatch):+ async def fake_ls(uri, ctx=None, recursive=False, output=None, **_):+ return [{"uri": "viking://r/notes.md", "isDir": False}]++ monkeypatch.setattr(service.fs, "ls", fake_ls)++ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": "foo"}+ )+ assert resp.status_code == 200+ assert "No supported source files" in resp.json()["result"]++ async def test_ls_permission_denied_uses_error_response(self, client, service, monkeypatch):+ async def fake_ls(uri, ctx=None, recursive=False, output=None, **_):+ raise PermissionDeniedError("denied")++ monkeypatch.setattr(service.fs, "ls", fake_ls)++ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": "foo"}+ )+ assert resp.status_code == 403+ body = resp.json()+ assert body["status"] == "error"+ assert body["error"]["code"] == "PERMISSION_DENIED"++ async def test_file_cap_warning(self, client, service, monkeypatch):+ async def fake_ls(uri, ctx=None, recursive=False, output=None, **_):+ return [{"uri": f"viking://r/f{i}.py", "isDir": False} for i in range(250)]++ async def fake_read(uri, ctx=None, **_):+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "ls", fake_ls)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": "greet"}+ )+ assert resp.status_code == 200+ assert "200-file cap" in resp.json()["result"]++ async def test_partial_read_failure_skipped(self, client, service, monkeypatch):+ async def fake_ls(uri, ctx=None, recursive=False, output=None, **_):+ return [+ {"uri": "viking://r/a.py", "isDir": False},+ {"uri": "viking://r/b.py", "isDir": False},+ ]++ async def fake_read(uri, ctx=None, **_):+ if uri.endswith("b.py"):+ raise RuntimeError("denied")+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "ls", fake_ls)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": "greet"}+ )+ assert resp.status_code == 200+ assert "viking://r/a.py" in resp.json()["result"]++ async def test_all_read_failures_reported(self, client, service, monkeypatch):+ async def fake_ls(uri, ctx=None, recursive=False, output=None, **_):+ return [+ {"uri": "viking://r/a.py", "isDir": False},+ {"uri": "viking://r/b.py", "isDir": False},+ ]++ async def fake_read(uri, ctx=None, **_):+ raise RuntimeError("denied")++ monkeypatch.setattr(service.fs, "ls", fake_ls)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/search", json={"uri": "viking://r", "query": "greet"}+ )+ assert resp.status_code == 200+ assert resp.json()["result"] == (+ "Error: failed to read all 2 source files under viking://r"+ )+++# ---------------------------------------------------------------------------+# /api/v1/code/expand+# ---------------------------------------------------------------------------+++class TestCodeExpandEndpoint:+ async def test_success(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/expand",+ json={"uri": "viking://r/a.py", "symbol": "make_greeter"},+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "def make_greeter" in body["result"]+ assert "(make_greeter)" in body["result"]++ async def test_qualified_symbol(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/expand",+ json={"uri": "viking://r/a.py", "symbol": "Greeter.greet"},+ )+ assert resp.status_code == 200+ assert "def greet" in resp.json()["result"]++ async def test_invalid_uri(self, client):+ resp = await client.post(+ "/api/v1/code/expand", json={"uri": "/tmp/x.py", "symbol": "foo"}+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["result"].startswith("Error:")+ assert "viking://" in body["result"]++ async def test_empty_symbol(self, client):+ resp = await client.post(+ "/api/v1/code/expand", json={"uri": "viking://r/x.py", "symbol": ""}+ )+ assert resp.status_code == 200+ assert resp.json()["result"] == "Error: empty symbol"++ async def test_missing_symbol(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return PY_SAMPLE++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/expand",+ json={"uri": "viking://r/a.py", "symbol": "nonexistent"},+ )+ assert resp.status_code == 200+ assert "not found" in resp.json()["result"]++ async def test_read_permission_denied_uses_error_response(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ raise PermissionDeniedError("denied")++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/expand",+ json={"uri": "viking://r/a.py", "symbol": "Greeter"},+ )+ assert resp.status_code == 403+ body = resp.json()+ assert body["status"] == "error"+ assert body["error"]["code"] == "PERMISSION_DENIED"++ async def test_non_text_content(self, client, service, monkeypatch):+ async def fake_read(uri, ctx=None, **_):+ return b"\x00binary"++ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/code/expand",+ json={"uri": "viking://r/a.py", "symbol": "Greeter"},+ )+ assert resp.status_code == 200+ assert "is not text" in resp.json()["result"]