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
fix(compile): salvage partial output on timeout and iteration limits (#3948)
Jiajie - He/him/his3577f77423f2
diff --git a/bot/tests/test_compile.py b/bot/tests/test_compile.pyindex b4218a3d6..89274bc9a 100644--- a/bot/tests/test_compile.py+++ b/bot/tests/test_compile.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom types import SimpleNamespaceimport pytest-from vikingbot.agent.loop import AgentLoop+from vikingbot.agent.loop import AgentIterationLimitExceeded, AgentLoopfrom vikingbot.agent.tools.base import Tool, ToolContextfrom vikingbot.agent.tools.compile import CompileScopedTool, SubmitWikiBundleToolfrom vikingbot.agent.tools.registry import ToolRegistry@@ -15,6 +15,7 @@ from vikingbot.compile.models import (CompileFailure,CompileLimits,CompileRequest,+ CompileResult,CompileTask,SanitizedCompileRequest,WikiBundleDraft,@@ -23,7 +24,16 @@ from vikingbot.compile.models import (from vikingbot.compile.renderer import WikiRenderer, content_hash, wiki_page_path_from_titlefrom vikingbot.compile.service import BotCompileService, CompileCapabilitiesfrom vikingbot.compile.store import CompileTaskStore-from vikingbot.config.schema import DirectBackendConfig, SandboxBackend, SessionKey+from vikingbot.config.schema import (+ DirectBackendConfig,+ SandboxBackend,+ SandboxConfig,+ SandboxMode,+ SessionKey,+)+from vikingbot.sandbox import SandboxManager+from vikingbot.sandbox.backends.srt import SrtBackend+from vikingbot.sandbox.base import SandboxFileInfofrom openviking.core.skill_loader import SkillLoaderfrom openviking.session.memory.utils.memory_file_utils import MemoryFileUtils@@ -107,12 +117,44 @@ def test_compile_bundle_schema_distinguishes_wiki_pages_and_artifact_files():def test_compile_limit_defaults_match_the_resource_envelope():limits = CompileLimits()- assert limits.concurrent_tasks == 2+ assert limits.concurrent_tasks == 10+ assert limits.accepted_tasks == 40+ assert limits.accepted_tasks_per_principal == 10+ assert limits.queue_wait_seconds == 60 * 60+ assert limits.task_runtime_seconds == 40 * 60+ assert limits.salvage_grace_seconds == 120+ assert limits.cleanup_grace_seconds == 40assert limits.target_inventory_entries == 2000assert limits.target_catalog_pages == 10+ assert limits.output_pages == 128+ assert limits.output_files == 128+ assert limits.output_operations == 256assert DirectBackendConfig().allow_compile_exec is False+def test_compile_request_schema_defers_runtime_max_but_requires_positive_finite_seconds():+ request = CompileRequest.model_validate(+ {+ "from": ["viking://resources/source"],+ "to": "viking://resources/wiki",+ "skill": "viking://agent/skills/wiki",+ "runtime_timeout_seconds": 24 * 60 * 60,+ }+ )+ assert request.runtime_timeout_seconds == 24 * 60 * 60++ for invalid in (0, float("inf"), float("nan")):+ with pytest.raises(ValueError):+ CompileRequest.model_validate(+ {+ "from": ["viking://resources/source"],+ "to": "viking://resources/wiki",+ "skill": "viking://agent/skills/wiki",+ "runtime_timeout_seconds": invalid,+ }+ )++def test_wiki_page_requires_exactly_one_body_source():body = _page(1, "One")body.pop("body_markdown")@@ -321,6 +363,38 @@ def test_renderer_creates_okf_pages_links_and_citations():assert "[1] [source](viking://resources/source)" in first["content"]+def test_renderer_preserves_existing_link_and_keeps_relationship():+ bundle = WikiBundleDraft.model_validate(+ {+ "pages": [+ _page(+ 1,+ "Overview",+ body_markdown='Read [Details](./details.md "details") next.',+ ),+ _page(2, "Details"),+ ],+ "links": [{"f": 1, "t": 2, "match_text": "Details"}],+ }+ )++ rendered = WikiRenderer().render(+ bundle=bundle,+ target_uri="viking://resources/wiki",+ source_roots={"src_1": "viking://resources/source"},+ catalog_uris=set(),+ existing_raw={},+ )+ operations = {operation["uri"]: operation["content"] for operation in rendered.operations}++ assert (+ operations["viking://resources/wiki/overview.md"].count('[Details](./details.md "details")')+ == 1+ )+ assert "- [Overview](./overview.md)" in operations["viking://resources/wiki/details.md"]+ assert rendered.link_count == 0++def test_wiki_page_title_path_normalizes_spaced_dashes_only():assert (wiki_page_path_from_title("Experimental Designs - Residual Networks")@@ -418,6 +492,37 @@ def test_renderer_adds_raw_text_and_workspace_binary_to_same_bundle():assert rendered.wiki_uris == ["viking://resources/wiki/overview.md"]+async def test_compile_rejects_combined_output_operation_overflow():+ limits = CompileLimits(output_pages=2, output_files=2, output_operations=3)+ bundle_data = {+ "pages": [_page(1, "One"), _page(2, "Two")],+ "files": [+ {"path": "one.txt", "content": "one"},+ {"path": "two.txt", "content": "two"},+ ],+ }+ tool = SubmitWikiBundleTool(+ source_ids={"src_1"},+ catalog_uris=set(),+ target_uri="viking://resources/wiki",+ limits=limits,+ )++ result = await tool.execute(ToolContext(), **bundle_data)++ assert "combined output operation limit exceeded" in result+ bundle = WikiBundleDraft.model_validate(bundle_data)+ with pytest.raises(ValueError, match="combined output operation limit"):+ WikiRenderer(limits).render(+ bundle=bundle,+ target_uri="viking://resources/wiki",+ source_roots={"src_1": "viking://resources/source"},+ catalog_uris=set(),+ existing_raw={},+ )++def test_renderer_accepts_minimal_okf_artifact_with_unknown_fields():content = ("---\n"@@ -758,6 +863,51 @@ async def test_submit_tool_rejects_protected_anchor_and_path_collision():assert tool.bundle is not None and tool.bundle.pages == []+async def test_submit_tool_accepts_existing_link_only_when_target_matches():+ tool = SubmitWikiBundleTool(+ source_ids={"src_1"},+ catalog_uris=set(),+ target_uri="viking://resources/wiki",+ limits=CompileLimits(),+ )+ context = ToolContext()++ accepted = await tool.execute(+ context,+ pages=[+ _page(1, "One", body_markdown="参见 [L2 行为标签库](./two.md)。"),+ _page(2, "Two"),+ ],+ links=[{"f": 1, "t": 2, "match_text": "行为标签库"}],+ )+ assert accepted.startswith("Wiki bundle accepted")+ assert tool.bundle is not None and len(tool.bundle.links) == 1++ accepted = await tool.execute(+ context,+ pages=[+ _page(1, "One", body_markdown="See [Version](./foo(1).md)."),+ _page(2, "Version", path_hint="foo(1).md"),+ ],+ links=[{"f": 1, "t": 2, "match_text": "Version"}],+ )+ assert accepted.startswith("Wiki bundle accepted")+ assert tool.bundle is not None and len(tool.bundle.links) == 1++ rejected = await tool.execute(+ context,+ pages=[+ _page(1, "One", body_markdown="参见 [行为标签库](./three.md)。"),+ _page(2, "Two"),+ _page(3, "Three"),+ ],+ links=[{"f": 1, "t": 2, "match_text": "行为标签库"}],+ )+ assert "unsatisfied anchor '行为标签库'" in rejected+ assert tool.bundle is None++@pytest.mark.asyncioasync def test_submit_tool_checks_size_before_parsing_okf_artifact():tool = SubmitWikiBundleTool(@@ -869,8 +1019,8 @@ async def test_submit_tool_reports_all_invalid_links():)assert result.startswith("Error: Invalid Wiki bundle: 2 invalid link(s):")- assert "links[0] from page 1 has non-linkable anchor 'Missing One'" in result- assert "links[1] from page 1 has non-linkable anchor 'Missing Two'" in result+ assert "links[0] from page 1 has unsatisfied anchor 'Missing One'" in result+ assert "links[1] from page 1 has unsatisfied anchor 'Missing Two'" in resultassert tool.bundle is None@@ -1277,6 +1427,42 @@ async def test_structured_wrapper_delegates_to_only_existing_loop_without_fallbaassert iterations == 1+ ("iteration", "error"),+ [(1, ValueError), (50, AgentIterationLimitExceeded)],+)+async def test_structured_wrapper_distinguishes_iteration_exhaustion(iteration, error):+ registry = ToolRegistry()+ registry.register(+ SubmitWikiBundleTool(+ source_ids=set(),+ catalog_uris=set(),+ target_uri="viking://resources/wiki",+ limits=CompileLimits(),+ )+ )++ class FakeLoop:+ max_iterations = 50++ async def _run_agent_loop(self, **kwargs):+ del kwargs+ return None, None, [], {}, iteration++ with pytest.raises(error):+ await AgentLoop.run_structured_task(+ FakeLoop(),+ system_prompt="system",+ user_prompt="user",+ session_key=SessionKey(type="compile", channel_id="cmp", chat_id="cmp"),+ tool_registry=registry,+ openviking_tool_names=set(),+ stop_tool_names=["submit_wiki_bundle"],+ openviking_connection=None,+ )++@pytest.mark.asyncioasync def test_request_normalization_uses_default_reason_and_canonical_skill(monkeypatch):class Client:@@ -1320,6 +1506,7 @@ async def test_request_normalization_uses_default_reason_and_canonical_skill(mon"to": "viking://resources/wiki","skill": "viking://agent/skills/wiki/SKILL.md","reason": " ",+ "runtime_timeout_seconds": 20 * 60,}),connection={"api_key": "secret"},@@ -1328,6 +1515,7 @@ async def test_request_normalization_uses_default_reason_and_canonical_skill(monassert normalized.to == "viking://resources/wiki"assert normalized.skill == "viking://agent/skills/wiki"assert normalized.reason == DEFAULT_COMPILE_REASON+ assert normalized.runtime_timeout_seconds == 20 * 60Client.created.clear()Client.skill_content = "---\nname: wiki\n---\nCompile it"@@ -1346,6 +1534,34 @@ async def test_request_normalization_uses_default_reason_and_canonical_skill(monassert Client.created == set()+async def test_request_normalization_rejects_runtime_above_server_limit_before_io(monkeypatch):+ async def create_client(**kwargs):+ raise AssertionError(f"client must not be created: {kwargs}")++ monkeypatch.setattr("vikingbot.compile.service.VikingClient.create", create_client)+ service = object.__new__(BotCompileService)+ service.config = None+ service.limits = CompileLimits(task_runtime_seconds=10)++ with pytest.raises(CompileFailure) as raised:+ await service._normalize_request(+ CompileRequest.model_validate(+ {+ "from": ["viking://resources/source"],+ "to": "viking://resources/wiki",+ "skill": "viking://agent/skills/wiki",+ "runtime_timeout_seconds": 11,+ }+ ),+ connection={"api_key": "secret"},+ )++ assert raised.value.code == "RESOURCE_EXHAUSTED"+ assert raised.value.stage == "queued"+ assert "server limit of 10 seconds" in str(raised.value)++def test_compile_target_accepts_only_exact_skill_namespaces():directory = {"isDir": True}@@ -1474,7 +1690,9 @@ async def test_execute_skill_target_skips_recursive_catalog_and_completes(self.bot_data_path = tmp_pathself.workspace_path = tmp_path / "host-workspace"self.skills = []- self.sandbox = SimpleNamespace(mode=None, model_copy=lambda *, deep: SimpleNamespace(mode=None))+ self.sandbox = SimpleNamespace(+ mode=None, model_copy=lambda *, deep: SimpleNamespace(mode=None)+ )def model_copy(self, *, update):copy = TaskConfig()@@ -2197,6 +2415,33 @@ def _sanitized_compile_request() -> SanitizedCompileRequest:)+class _FakeWorkspaceSandbox:+ def __init__(+ self,+ files: dict[str, bytes],+ *,+ sizes: dict[str, int] | None = None,+ ):+ self.files = files+ self.sizes = sizes or {}+ self.reads: list[tuple[str, int | None]] = []++ async def list_files(self, path=".", *, max_entries):+ assert path == "."+ inventory = {name: len(payload) for name, payload in self.files.items()}+ inventory.update(self.sizes)+ assert len(inventory) <= max_entries+ return [SandboxFileInfo(path=name, size=size) for name, size in inventory.items()]++ async def read_file_bytes(self, path, *, max_bytes=None):+ self.reads.append((path, max_bytes))+ if path not in self.files:+ raise AssertionError(f"metadata-only file must not be read: {path}")+ payload = self.files[path]+ assert max_bytes is None or len(payload) <= max_bytes+ return payload++@pytest.mark.parametrize(("backend", "allow_compile_exec", "expected"),[@@ -2447,6 +2692,734 @@ async def test_compile_queue_wait_has_a_deadline(tmp_path: Path):assert service._target_locks == {}+async def test_compile_uses_request_runtime_timeout(monkeypatch, tmp_path: Path):+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.AIOSANDBOX,+ )+ request = _sanitized_compile_request().model_copy(update={"runtime_timeout_seconds": 0.01})+ task = CompileTask(+ task_id="cmp_runtime",+ principal_scope="owner",+ sanitized_request=request,+ status="accepted",+ stage="queued",+ created_at=utc_now(),+ updated_at=utc_now(),+ )+ await service.store.create(task)+ observed = []++ async def execute(*args, runtime_deadline, **kwargs):+ del args, kwargs+ observed.append(runtime_deadline - asyncio.get_running_loop().time())+ await asyncio.Event().wait()++ monkeypatch.setattr(service, "_execute_task", execute)+ await service._run_task(task.task_id, request, {"api_key": "secret"})++ failed = await service.store.get(task.task_id)+ assert observed and 0 < observed[0] <= 0.02+ assert failed is not None and failed.status == "failed"+ assert failed.error is not None and failed.error.code == "DEADLINE_EXCEEDED"+++async def test_timeout_salvage_copies_workspace_and_repairs_links(tmp_path: Path):+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.DIRECT,+ )+ files = {+ "__compile_staging__/wiki_pages/home.md": b"# Home\n",+ "__compile_staging__/wiki_pages/guide/topic.md": "\n".join(+ [+ "[Home](home.md#top)",+ "[Meta](meta/readme.md)",+ "[Existing](../existing.md)",+ "[Missing](missing.md)",+ "",+ '[Titled](../meta/title.md "Title")',+ "[Paren](../meta/foo(1).md)",+ "[Web](https://example.com)",+ "[Source](viking://resources/source)",+ "[Anchor](#local)",+ "`[Code](missing.md)`",+ ]+ ).encode(),+ "meta/readme.md": b"# Meta\n",+ "meta/title.md": b"# Title\n",+ "meta/foo(1).md": b"# Paren\n",+ "meta/events.jsonl": b"",+ "artifact.bin": b"\x00\x01",+ "home.md": b"# Artifact Home\n",+ "roadmap.md": b"[Roadmap](future.md)\n",+ "caseonly.md": b"case mismatch",+ "Foo.md": b"first",+ "foo.md": b"duplicate",+ "bad#name.txt": b"unsafe URI",+ "__compile_staging__/work/notes.txt": b"notes",+ "__compile_staging__/tmp/check.txt": b"check",+ "skills/wiki/SKILL.md": b"do not copy",+ "sandboxes/cmp-srt-settings.json": b'{"filesystem": "/private/host/path"}',+ }++ class Client:+ operations = []++ async def tree(self, uri, *, node_limit):+ assert uri == "viking://resources/wiki"+ assert node_limit == service.limits.target_inventory_entries + 1+ return [+ {"uri": f"{uri}/existing.md", "isDir": False, "size": 1},+ {"uri": f"{uri}/CaseOnly.md", "isDir": False, "size": 8},+ {"uri": f"{uri}/meta/events.jsonl", "isDir": False, "size": 3},+ ]++ async def download_bytes(self, uri):+ return {+ "viking://resources/wiki/CaseOnly.md": b"old case",+ "viking://resources/wiki/meta/events.jsonl": b"old",+ }[uri]++ async def batch_write(self, *, root_uri, operations, wait):+ assert root_uri == "viking://resources/wiki"+ assert wait is False+ self.operations = operations+ updated = [+ operation["uri"]+ for operation in operations+ if operation["precondition"]["kind"] == "replace_if_hash"+ ]+ created = [+ operation["uri"]+ for operation in operations+ if operation["precondition"]["kind"] == "create_if_absent"+ ]+ return {"created": created, "updated": updated, "unchanged": []}++ client = Client()+ sandbox = _FakeWorkspaceSandbox(files)+ result = await service._salvage_workspace(+ client=client,+ request=_sanitized_compile_request(),+ sandbox=sandbox,+ workspace_baseline={"sandboxes/cmp-srt-settings.json"},+ )++ assert result is not None+ payloads = {+ operation["uri"].removeprefix("viking://resources/wiki/"): base64.b64decode(+ operation["content_base64"]+ )+ for operation in client.operations+ }+ assert "skills/wiki/SKILL.md" not in payloads+ assert "empty" not in payloads+ assert "__compile_staging__/wiki_pages/home.md" not in payloads+ assert payloads["home.md"] == b"# Artifact Home\n"+ assert payloads["roadmap.md"] == b"[Roadmap](future.md)\n"+ assert payloads["artifact.bin"] == b"\x00\x01"+ assert payloads["CaseOnly.md"] == b"case mismatch"+ assert payloads["meta/events.jsonl"] == b""+ assert "__compile_staging__/work/notes.txt" not in payloads+ assert "__compile_staging__/tmp/check.txt" not in payloads+ assert "sandboxes/cmp-srt-settings.json" not in payloads+ assert "sandboxes/cmp-srt-settings.json" not in {path for path, _limit in sandbox.reads}+ assert sum(path.casefold() == "foo.md" for path in payloads) == 1+ assert "bad#name.txt" not in payloads+ topic = payloads["guide/topic.md"].decode()+ assert "[Home](../home.md#top)" in topic+ assert "[Meta](../meta/readme.md)" in topic+ assert "[Existing](../existing.md)" in topic+ assert "Missing\nMissing image" in topic+ assert '[Titled](../meta/title.md "Title")' in topic+ assert "[Paren](../meta/foo(1).md)" in topic+ assert "[Web](https://example.com)" in topic+ assert "[Source](viking://resources/source)" in topic+ assert "[Anchor](#local)" in topic+ assert "`[Code](missing.md)`" in topic+ assert result.warnings and "partial output" in result.warnings[0]+ assert any("Skipped" in warning for warning in result.warnings)+++ "content",+ [+ '[Missing](missing.md "title")',+ "[Missing](missing(1).md)",+ ],+)+def test_timeout_salvage_removes_unresolved_complex_markdown_links(content: str):+ assert (+ BotCompileService._repair_salvaged_markdown(+ content,+ source_path="guide/topic.md",+ known_paths={"guide/topic.md"},+ )+ == "Missing"+ )+++def test_timeout_salvage_preserves_existing_escaped_parenthesis_link():+ content = r"[Paren](../meta/foo\(1\).md)"++ assert (+ BotCompileService._repair_salvaged_markdown(+ content,+ source_path="guide/topic.md",+ known_paths={"meta/foo(1).md"},+ )+ == content+ )+++async def test_timeout_salvage_ignores_preexisting_srt_settings(tmp_path: Path):+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.SRT,+ )+ settings_path = "sandboxes/cmp-srt-settings.json"++ class Client:+ async def tree(self, uri, *, node_limit):+ raise AssertionError(f"target must not be read: {uri}, {node_limit}")++ result = await service._salvage_workspace(+ client=Client(),+ request=_sanitized_compile_request(),+ sandbox=_FakeWorkspaceSandbox({}, sizes={settings_path: 128}),+ workspace_baseline={settings_path},+ )++ assert result is None+++async def test_srt_settings_created_by_manager_are_in_the_workspace_baseline(+ monkeypatch, tmp_path: Path+):+ async def start_without_process(self):+ self.workspace.mkdir(parents=True, exist_ok=True)++ monkeypatch.setattr(SrtBackend, "start", start_without_process)+ config = SimpleNamespace(+ sandbox=SandboxConfig(backend=SandboxBackend.SRT, mode=SandboxMode.PER_SESSION),+ skills=[],+ )+ manager = SandboxManager(config, tmp_path / "workspaces", tmp_path / "source")+ session_key = SessionKey(type="compile", channel_id="cmp", chat_id="cmp")++ sandbox = await manager.get_sandbox(session_key)+ baseline = {+ entry.path+ for entry in await sandbox.list_files(max_entries=CompileLimits().target_inventory_entries)+ }++ workspace_id = manager.to_workspace_id(session_key)+ assert baseline == {f"sandboxes/{workspace_id}-srt-settings.json"}+++async def test_timeout_salvage_skips_oversized_file_before_reading(tmp_path: Path):+ limits = CompileLimits(output_total_bytes=4)+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.AIOSANDBOX,+ limits=limits,+ )++ class Client:+ operations = []++ async def tree(self, uri, *, node_limit):+ del node_limit+ return [+ {+ "uri": f"{uri}/existing.txt",+ "isDir": False,+ "size": 1024 * 1024 * 1024,+ }+ ]++ async def download_bytes(self, uri):+ raise AssertionError(f"oversized target must not be downloaded: {uri}")++ async def batch_write(self, *, root_uri, operations, wait):+ del root_uri, wait+ self.operations = operations+ return {+ "created": [operation["uri"] for operation in operations],+ "updated": [],+ "unchanged": [],+ }++ sandbox = _FakeWorkspaceSandbox(+ {"existing.txt": b"ok", "small.txt": b"ok"},+ sizes={"huge.bin": 1024 * 1024 * 1024},+ )+ client = Client()+ result = await service._salvage_workspace(+ client=client,+ request=_sanitized_compile_request(),+ sandbox=sandbox,+ workspace_baseline=set(),+ )++ assert result is not None+ assert sandbox.reads == [+ ("existing.txt", limits.output_total_bytes),+ ("small.txt", limits.output_total_bytes - 2),+ ]+ assert [operation["uri"] for operation in client.operations] == [+ "viking://resources/wiki/small.txt"+ ]+ assert any("Skipped 2" in warning for warning in result.warnings)+++async def test_timeout_salvage_grace_returns_when_cancellation_is_suppressed(+ monkeypatch, tmp_path: Path+):+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.AIOSANDBOX,+ limits=CompileLimits(salvage_grace_seconds=0.01),+ )+ request = _sanitized_compile_request()+ task = CompileTask(+ task_id="cmp_stubborn_salvage",+ principal_scope="owner",+ sanitized_request=request,+ status="running",+ stage="agent",+ created_at=utc_now(),+ updated_at=utc_now(),+ )+ await service.store.create(task)+ cancelled = asyncio.Event()+ release = asyncio.Event()++ async def stubborn_salvage(**kwargs):+ del kwargs+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancelled.set()+ await release.wait()++ monkeypatch.setattr(service, "_salvage_workspace", stubborn_salvage)+ loop = asyncio.get_running_loop()+ started_at = loop.time()+ try:+ with pytest.raises(CompileFailure) as raised:+ await asyncio.wait_for(+ service._complete_salvaged_task(+ task_id=task.task_id,+ client=object(),+ request=request,+ sandbox=object(),+ workspace_baseline=set(),+ reason="reached its runtime deadline",+ failure_code="DEADLINE_EXCEEDED",+ ),+ timeout=0.2,+ )+ assert raised.value.code == "DEADLINE_EXCEEDED"+ assert raised.value.stage == "salvaging"+ assert "grace limit" in str(raised.value)+ assert loop.time() - started_at < 0.2+ await asyncio.wait_for(cancelled.wait(), timeout=0.1)+ finally:+ release.set()+ await asyncio.sleep(0)+++async def test_salvage_keeps_its_grace_period_when_parent_runtime_expires(+ monkeypatch, tmp_path: Path+):+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.AIOSANDBOX,+ limits=CompileLimits(salvage_grace_seconds=0.2),+ )+ request = _sanitized_compile_request()+ task = CompileTask(+ task_id="cmp_cancelled_salvage",+ principal_scope="owner",+ sanitized_request=request,+ status="running",+ stage="agent",+ created_at=utc_now(),+ updated_at=utc_now(),+ )+ await service.store.create(task)+ started = asyncio.Event()++ async def salvage(**kwargs):+ del kwargs+ started.set()+ await asyncio.sleep(0.02)+ return CompileResult(+ from_=request.from_,+ to=request.to,+ skill=request.skill,+ created=[f"{request.to}/partial.md"],+ )++ monkeypatch.setattr(service, "_salvage_workspace", salvage)+ runner = asyncio.create_task(+ service._complete_salvaged_task(+ task_id=task.task_id,+ client=object(),+ request=request,+ sandbox=object(),+ workspace_baseline=set(),+ reason="reached its iteration limit",+ failure_code="AGENT_OUTPUT_INVALID",+ )+ )+ await started.wait()+ runner.cancel()+ await asyncio.wait_for(runner, timeout=0.2)++ completed = await service.store.get(task.task_id)+ assert completed is not None+ assert completed.status == "completed"+ assert completed.stage == "salvaged"+++async def test_cleanup_grace_releases_execution_slot_and_target_lock(tmp_path: Path):+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.DIRECT,+ limits=CompileLimits(+ concurrent_tasks=1,+ cleanup_grace_seconds=0.01,+ task_runtime_seconds=1,+ ),+ )+ request = _sanitized_compile_request()+ cleanup_started = asyncio.Event()+ cleanup_cancelled = asyncio.Event()+ release_cleanup = asyncio.Event()+ cleanup_finished = asyncio.Event()+ second_started = asyncio.Event()++ class StubbornManager:+ async def cleanup_session(self, session_key):+ del session_key+ cleanup_started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cleanup_cancelled.set()+ await release_cleanup.wait()+ cleanup_finished.set()++ async def execute(task_id, _request, connection, *, runtime_deadline):+ del connection, runtime_deadline+ if task_id == "cmp_first":+ await service._cleanup_execution_resources(+ sandbox_manager=StubbornManager(),+ session_key=SessionKey(type="compile", channel_id=task_id, chat_id=task_id),+ client=None,+ workspace_parent=tmp_path / task_id,+ )+ else:+ second_started.set()++ service._execute_task = execute+ first = asyncio.create_task(service._run_task("cmp_first", request, {}))+ await cleanup_started.wait()+ second = asyncio.create_task(service._run_task("cmp_second", request, {}))+ try:+ await asyncio.wait_for(cleanup_cancelled.wait(), timeout=0.2)+ await asyncio.wait_for(second_started.wait(), timeout=0.2)+ await asyncio.gather(first, second)+ assert service._semaphore._value == 1+ assert service._target_locks == {}+ finally:+ release_cleanup.set()+ await asyncio.wait_for(cleanup_finished.wait(), timeout=0.2)+++async def test_timeout_salvage_respects_combined_output_operation_limit(tmp_path: Path):+ limits = CompileLimits(output_pages=2, output_files=2, output_operations=3)+ service = _compile_service(+ tmp_path,+ auth_mode="api_key",+ backend=SandboxBackend.DIRECT,+ limits=limits,+ )+ files = {+ "a.txt": b"a",+ "b.txt": b"b",+ "__compile_staging__/wiki_pages/c.md": b"c",+ "__compile_staging__/wiki_pages/d.md": b"d",+ }++ class Client:+ operations = []++ async def tree(self, uri, *, node_limit):+ del uri, node_limit+ return []++ async def batch_write(self, *, root_uri, operations, wait):+ del root_uri, wait+ self.operations = operations+ return {+ "created": [operation["uri"] for operation in operations],+ "updated": [],+ "unchanged": [],+ }++ client = Client()+ result = await service._salvage_workspace(+ client=client,+ request=_sanitized_compile_request(),+ sandbox=_FakeWorkspaceSandbox(files),+ workspace_baseline=set(),+ )++ assert result is not None+ assert len(client.operations) == limits.output_operations+ assert result.warnings and any("Skipped 1" in warning for warning in result.warnings)++[email protected]("cutoff", ["runtime", "iterations", "accepted", "rendering"])+async def test_compile_cutoff_salvages_before_workspace_cleanup(+ monkeypatch, tmp_path: Path, cutoff: str+):+ observed = []+ remote_files = {}++ sandbox = _FakeWorkspaceSandbox(remote_files)++ class TaskConfig:+ def __init__(self):+ self.bot_data_path = tmp_path+ self.workspace_path = tmp_path / "host-workspace"+ self.skills = []+ self.sandbox = SimpleNamespace(+ mode=None, model_copy=lambda *, deep: SimpleNamespace(mode=None)+ )++ def model_copy(self, *, update):+ copy = TaskConfig()+ for key, value in update.items():+ setattr(copy, key, value)+ return copy++ class FakeSandboxManager:+ def __init__(self, config, workspace_parent, workspace_path):+ del config, workspace_path+ self.workspace = workspace_parent / "workspace"+ self.workspace.mkdir(parents=True)++ def get_workspace_path(self, session_key):+ del session_key+ return self.workspace++ async def get_sandbox(self, session_key):+ del session_key+ return sandbox++ async def cleanup_session(self, session_key):+ del session_key+ observed.append("cleanup")++ class FakeSkillsLoader:+ def __init__(self, workspace, *, builtin_skills_dir):+ del workspace, builtin_skills_dir++ def load_skills_for_context(self, names):+ assert names == ["wiki"]+ return "Write Wiki pages."++ def _get_skill_meta(self, name):+ assert name == "wiki"+ return {}++ class FakeRequestLoop:+ def __init__(self, **kwargs):+ self.workspace = kwargs["workspace"]++ async def run_structured_task(self, **kwargs):+ del kwargs+ remote_files["output.md"] = b"partial"+ if cutoff == "iterations":+ raise AgentIterationLimitExceeded(1)+ if cutoff == "accepted":+ submit_tool.bundle = WikiBundleDraft.model_validate({"pages": []})+ await asyncio.Event().wait()+ if cutoff == "rendering":+ return (+ WikiBundleDraft.model_validate(+ {+ "pages": [+ _page(+ 1,+ "Guide",+ update_uri="viking://resources/wiki/guide.md",+ path_hint=None,+ )+ ]+ }+ ),+ [],+ {},+ 1,+ )+ await asyncio.Event().wait()++ class Client:+ async def get_skill(self, skill_name, *, target_uri):+ assert skill_name == "wiki"+ assert target_uri == "viking://agent/skills"+ return {+ "root_uri": "viking://agent/skills/wiki",+ "content": "---\nname: wiki\ndescription: Write Wiki\n---\nWrite it.",+ "files": [],+ }++ async def read_raw(self, uri):+ assert cutoff == "rendering"+ assert uri == "viking://resources/wiki/guide.md"+ await asyncio.Event().wait()++ async def close(self):+ return None++ async def create_client(**kwargs):+ del kwargs+ return Client()++ async def no_op(*args, **kwargs):+ del args, kwargs++ async def build_sources(*args, **kwargs):+ del args, kwargs+ return []++ async def build_catalog(*args, **kwargs):+ del args, kwargs+ return [], {}++ async def salvage(*, client, request, sandbox, workspace_baseline, reason):+ del client+ assert workspace_baseline == set()+ assert request.to == "viking://resources/wiki"+ assert await sandbox.read_file_bytes("output.md") == b"partial"+ assert ("runtime deadline" if cutoff == "runtime" else "1-iteration limit") in reason+ observed.append("salvage")+ return CompileResult(+ **{+ "from": request.from_,+ "to": request.to,+ "skill": request.skill,+ "created": [f"{request.to}/output.md"],+ "page_count": 1,+ "warnings": ["partial output"],+ }+ )++ monkeypatch.setattr("vikingbot.compile.service.SandboxManager", FakeSandboxManager)+ monkeypatch.setattr("vikingbot.compile.service.SkillsLoader", FakeSkillsLoader)+ monkeypatch.setattr("vikingbot.compile.service.AgentLoop", FakeRequestLoop)+ monkeypatch.setattr("vikingbot.compile.service.VikingClient.create", create_client)++ host_loop = SimpleNamespace(+ config=TaskConfig(),+ bus=None,+ provider=None,+ model=None,+ temperature=0,+ max_iterations=1,+ memory_window=1,+ brave_api_key=None,+ exa_api_key=None,+ gen_image_model=None,+ exec_config=None,+ )+ service = BotCompileService(agent_loop=host_loop)+ monkeypatch.setattr(service, "_materialize_skill", no_op)+ monkeypatch.setattr(service, "_check_requirements", no_op)+ monkeypatch.setattr(service, "_build_sources", build_sources)+ monkeypatch.setattr(service, "_build_catalog", build_catalog)+ submit_tool = SimpleNamespace(file_payloads=[])+ registry = SimpleNamespace(get=lambda name: submit_tool)+ monkeypatch.setattr(+ service, "_build_compile_registry", lambda *args, **kwargs: (registry, set())+ )+ monkeypatch.setattr(service, "_salvage_workspace", salvage)++ request = _sanitized_compile_request()+ task = CompileTask(+ task_id=f"cmp_{cutoff}",+ principal_scope="owner",+ sanitized_request=request,+ status="accepted",+ stage="queued",+ created_at=utc_now(),+ updated_at=utc_now(),+ )+ await service.store.create(task)+ loop = asyncio.get_running_loop()+ execute = service._execute_task(+ task.task_id,+ request,+ {"api_key": "secret"},+ runtime_deadline=loop.time()+ + (0.01 if cutoff in {"runtime", "accepted", "rendering"} else 60),+ )+ if cutoff in {"accepted", "rendering"}:+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(execute, timeout=0.01)+ elif cutoff == "runtime":+ await asyncio.wait_for(execute, timeout=0.01)+ else:+ await execute++ completed = await service.store.get(task.task_id)+ assert completed is not None+ if cutoff in {"accepted", "rendering"}:+ assert completed.status == "running"+ assert completed.stage == cutoff.replace("accepted", "agent")+ assert completed.result is None+ assert observed == ["cleanup"]+ return+ assert completed.status == "completed"+ assert completed.stage == "salvaged"+ assert completed.result is not None+ assert completed.result.created == ["viking://resources/wiki/output.md"]+ assert observed == ["salvage", "cleanup"]+ assert not (tmp_path / "compile_workspaces" / task.task_id).exists()++ await service._fail(+ task.task_id,+ CompileFailure("INTERNAL", "late cleanup failure", stage="salvaging"),+ )+ still_completed = await service.store.get(task.task_id)+ assert still_completed is not None+ assert still_completed.status == "completed"+ assert still_completed.result is not None++@pytest.mark.asyncioasync def test_task_store_restart_marks_nonterminal_without_persisting_connection(tmp_path: Path):store = CompileTaskStore(tmp_path)diff --git a/bot/tests/test_sandbox_file_access.py b/bot/tests/test_sandbox_file_access.pynew file mode 100644index 000000000..87bdacdab--- /dev/null+++ b/bot/tests/test_sandbox_file_access.py@@ -0,0 +1,213 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Regression tests for bounded local and remote sandbox file access."""++import json+from pathlib import Path+from types import SimpleNamespace++import pytest+from vikingbot.sandbox.backends.aiosandbox import AioSandboxBackend+from vikingbot.sandbox.backends.direct import DirectBackend+from vikingbot.sandbox.backends.opensandbox import OpenSandboxBackend+from vikingbot.sandbox.base import SandboxFileInfo+++def _direct_backend(workspace: Path) -> DirectBackend:+ return DirectBackend(SimpleNamespace(restrict_workspaces={}), "test", workspace)+++async def test_local_workspace_listing_and_reads_are_bounded(tmp_path: Path):+ backend = _direct_backend(tmp_path)+ await backend.start()+ (tmp_path / ".hidden").write_bytes(b"h")+ (tmp_path / "nested").mkdir()+ (tmp_path / "nested" / "artifact.bin").write_bytes(b"artifact")++ assert await backend.list_files(max_entries=3) == [+ SandboxFileInfo(path=".hidden", size=1),+ SandboxFileInfo(path="nested/artifact.bin", size=8),+ ]+ assert await backend.read_file_bytes("nested/artifact.bin", max_bytes=8) == b"artifact"+ with pytest.raises(ValueError, match="7-byte read limit"):+ await backend.read_file_bytes("nested/artifact.bin", max_bytes=7)+ with pytest.raises(ValueError, match="inventory exceeds 2 entries"):+ await backend.list_files(max_entries=2)+++class _AioFileClient:+ def __init__(self, *, truncated=False):+ self.list_calls = []+ self.glob_calls = []+ self.download_calls = []+ self.truncated = truncated+ self.entries = {+ "/home/gem": [+ SimpleNamespace(name="artifact.bin", is_directory=False, size=6),+ SimpleNamespace(name="nested", is_directory=True, size=0),+ ],+ "/home/gem/nested": [+ SimpleNamespace(name="page.md", is_directory=False, size=4),+ ],+ }++ async def list_path(self, **kwargs):+ self.list_calls.append(kwargs)+ return SimpleNamespace(data=SimpleNamespace(files=self.entries[kwargs["path"]]))++ async def glob_files(self, **kwargs):+ self.glob_calls.append(kwargs)+ return SimpleNamespace(+ data=SimpleNamespace(+ files=[+ SimpleNamespace(+ path="/home/gem",+ is_directory=True,+ size=0,+ ),+ SimpleNamespace(+ path="/home/gem/artifact.bin",+ is_directory=False,+ size=6,+ ),+ SimpleNamespace(+ path="/home/gem/nested",+ is_directory=True,+ size=0,+ ),+ SimpleNamespace(+ path="/home/gem/nested/page.md",+ is_directory=False,+ size=4,+ ),+ ],+ total_count=5 if self.truncated else 4,+ truncated=self.truncated,+ )+ )++ async def download_file(self, *, path):+ self.download_calls.append(path)+ yield b"abc"+ yield b"def"+++def _aio_backend(tmp_path: Path, file_client: _AioFileClient) -> AioSandboxBackend:+ config = SimpleNamespace(+ backends=SimpleNamespace(aiosandbox=SimpleNamespace(base_url="http://sandbox"))+ )+ backend = AioSandboxBackend(config, "test", tmp_path)+ backend._client = SimpleNamespace(file=file_client)+ return backend+++async def test_aiosandbox_lists_and_streams_from_remote_workspace(tmp_path: Path):+ files = _AioFileClient()+ backend = _aio_backend(tmp_path, files)++ assert await backend.list_files(max_entries=3) == [+ SandboxFileInfo(path="artifact.bin", size=6),+ SandboxFileInfo(path="nested/page.md", size=4),+ ]+ assert files.glob_calls == [+ {+ "path": "/home/gem",+ "pattern": "**",+ "include_hidden": True,+ "files_only": False,+ "include_metadata": True,+ "max_results": 4,+ "sort_by": "path",+ },+ ]+ assert await backend.read_file_bytes("artifact.bin", max_bytes=6) == b"abcdef"+ with pytest.raises(ValueError, match="5-byte read limit"):+ await backend.read_file_bytes("artifact.bin", max_bytes=5)+ assert files.download_calls == ["/home/gem/artifact.bin", "/home/gem/artifact.bin"]+++async def test_aiosandbox_inventory_uses_the_remote_result_limit(tmp_path: Path):+ files = _AioFileClient(truncated=True)+ backend = _aio_backend(tmp_path, files)++ with pytest.raises(ValueError, match="inventory exceeds 3 entries"):+ await backend.list_files(max_entries=3)+ assert files.glob_calls[0]["max_results"] == 4+++class _OpenSandboxFiles:+ def __init__(self):+ self.read_calls = []++ async def read_bytes_stream(self, path, *, range_header):+ self.read_calls.append((path, range_header))+ payload = b"abcdef"++ async def chunks():+ yield payload[:3]+ yield payload[3:]++ return chunks()+++class _OpenSandboxCommands:+ def __init__(self, *, overflow=False):+ self.overflow = overflow+ self.calls = []++ async def run(self, command, *, opts):+ self.calls.append((command, opts))+ payload = {+ "overflow": self.overflow,+ "files": [["artifact.bin", 6], ["nested/page.md", 4]],+ }+ return SimpleNamespace(+ error=None,+ logs=SimpleNamespace(stdout=[SimpleNamespace(text=json.dumps(payload))]),+ )+++def _opensandbox_vke_backend(+ tmp_path: Path,+ file_client: _OpenSandboxFiles,+ commands: _OpenSandboxCommands,+) -> OpenSandboxBackend:+ backend = object.__new__(OpenSandboxBackend)+ backend._workspace = tmp_path+ backend._is_vke = True+ backend._sandbox = SimpleNamespace(files=file_client, commands=commands)+ return backend+++async def test_opensandbox_vke_uses_bounded_remote_inventory_and_range_reads(tmp_path: Path):+ files = _OpenSandboxFiles()+ commands = _OpenSandboxCommands()+ backend = _opensandbox_vke_backend(tmp_path, files, commands)++ assert await backend.list_files(max_entries=2) == [+ SandboxFileInfo(path="artifact.bin", size=6),+ SandboxFileInfo(path="nested/page.md", size=4),+ ]+ assert "python3 -c" in commands.calls[0][0]+ assert "limit = 2" in commands.calls[0][0]+ assert await backend.read_file_bytes("artifact.bin", max_bytes=6) == b"abcdef"+ with pytest.raises(ValueError, match="5-byte read limit"):+ await backend.read_file_bytes("artifact.bin", max_bytes=5)+ assert files.read_calls == [+ ("/workspace/artifact.bin", "bytes=0-6"),+ ("/workspace/artifact.bin", "bytes=0-5"),+ ]+++async def test_opensandbox_vke_inventory_stops_at_the_remote_limit(tmp_path: Path):+ commands = _OpenSandboxCommands(overflow=True)+ backend = _opensandbox_vke_backend(tmp_path, _OpenSandboxFiles(), commands)++ with pytest.raises(ValueError, match="inventory exceeds 1 entries"):+ await backend.list_files(max_entries=1)+ assert "limit = 1" in commands.calls[0][0]diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex f47326dc7..a5b04303e 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -86,6 +86,16 @@ class _PlainTextFinal:content: str | None = None+class AgentIterationLimitExceeded(RuntimeError):+ """A structured task used every available AgentLoop iteration without submitting."""++ def __init__(self, max_iterations: int):+ self.max_iterations = max_iterations+ super().__init__(+ f"Agent reached its {max_iterations}-iteration limit without submitting a valid bundle"+ )++class AgentLoop:"""The agent loop is the core processing engine.@@ -1335,6 +1345,8 @@ class AgentLoop:submit_tool = tool_registry.get("submit_wiki_bundle")bundle = getattr(submit_tool, "bundle", None)if bundle is None:+ if iteration >= self.max_iterations:+ raise AgentIterationLimitExceeded(self.max_iterations)raise ValueError("AGENT_OUTPUT_INVALID: Agent did not submit a valid Wiki bundle")return bundle, tools_used, token_usage, iterationdiff --git a/bot/vikingbot/agent/tools/compile.py b/bot/vikingbot/agent/tools/compile.pyindex d368eb843..f9930b1fc 100644--- a/bot/vikingbot/agent/tools/compile.py+++ b/bot/vikingbot/agent/tools/compile.py@@ -279,8 +279,9 @@ class SubmitWikiBundleTool(Tool):match_schema = link_def.get("properties", {}).get("match_text")if isinstance(match_schema, dict):match_schema["description"] = (- "Exact anchor text that must appear in the source page draft body outside "- "frontmatter, code, existing Markdown links, and Citations."+ "Exact anchor text that must either appear in the source page draft body "+ "outside frontmatter, code, existing Markdown links, and Citations, or "+ "already be part of a Markdown link to the target page.")schema.pop("title", None)return schema@@ -474,6 +475,8 @@ class SubmitWikiBundleTool(Tool):raise ValueError("page limit exceeded")if len(bundle.files) > self.limits.output_files:raise ValueError("file limit exceeded")+ if len(bundle.pages) + len(bundle.files) > self.limits.output_operations:+ raise ValueError("combined output operation limit exceeded")if not bundle.pages and bundle.links:raise ValueError("empty bundle must not contain links")if target_type == "skill" and (bundle.pages or bundle.links):@@ -490,6 +493,7 @@ class SubmitWikiBundleTool(Tool):"using workspace_path instead of inline content")page_ids: set[int] = set()+ page_uris: dict[int, str] = {}final_uris: set[str] = set()total_bytes = 0for page in bundle.pages:@@ -532,6 +536,7 @@ class SubmitWikiBundleTool(Tool):if final_uri in final_uris:raise ValueError(f"duplicate final Wiki path: {final_uri}")final_uris.add(final_uri)+ page_uris[page.page_id] = final_uritotal_bytes += len(page.body_markdown.encode("utf-8"))file_payloads: list[bytes | None] = []@@ -600,18 +605,16 @@ class SubmitWikiBundleTool(Tool):link_errors.append(f"{prefix} match_text is required")continuesource_page = page_by_id[link.f]- if (- LinkRenderer._find_match_span(- source_page.body_markdown,- link.match_text,- LinkRenderer.protected_markdown_spans(source_page.body_markdown),- )- is None+ if not LinkRenderer.can_render_link(+ source_page.body_markdown,+ link.match_text,+ page_uris[link.f],+ page_uris[link.t],):link_errors.append(- f"{prefix} from page {link.f} has non-linkable anchor "- f"{link.match_text!r}; remove the link or use exact unprotected "- "text from that page body"+ f"{prefix} from page {link.f} has unsatisfied anchor "+ f"{link.match_text!r}; use exact unprotected text or an existing "+ f"Markdown link to page {link.t}")if link_errors:raise ValueError(f"{len(link_errors)} invalid link(s): " + "; ".join(link_errors))diff --git a/bot/vikingbot/compile/models.py b/bot/vikingbot/compile/models.pyindex 8ad1e3583..e863f6073 100644--- a/bot/vikingbot/compile/models.py+++ b/bot/vikingbot/compile/models.py@@ -34,14 +34,17 @@ class CompileLimits(BaseModel):tool_uri_count: int = 32tool_result_bytes: int = 1024 * 1024tool_total_result_bytes: int = 8 * 1024 * 1024- output_pages: int = 64- output_files: int = 64+ output_pages: int = 128+ output_files: int = 128+ output_operations: int = 256output_total_bytes: int = 4 * 1024 * 1024- concurrent_tasks: int = 2- accepted_tasks: int = 16- accepted_tasks_per_principal: int = 4- queue_wait_seconds: float = 5 * 60- task_runtime_seconds: float = 30 * 60+ concurrent_tasks: int = 10+ accepted_tasks: int = 40+ accepted_tasks_per_principal: int = 10+ queue_wait_seconds: float = 60 * 60+ task_runtime_seconds: float = 40 * 60+ salvage_grace_seconds: float = 120+ cleanup_grace_seconds: float = 40terminal_task_retention_seconds: float = 24 * 60 * 60terminal_task_records: int = 1000@@ -53,6 +56,11 @@ class CompileRequest(BaseModel):to: str = Field(min_length=1)reason: str | None = Noneskill: str = Field(min_length=1)+ runtime_timeout_seconds: float | None = Field(+ default=None,+ gt=0,+ allow_inf_nan=False,+ )openviking_connection: OpenVikingConnection | None = None_principal_scope: str = PrivateAttr(default="local")@@ -64,6 +72,11 @@ class SanitizedCompileRequest(BaseModel):to: strreason: strskill: str+ runtime_timeout_seconds: float | None = Field(+ default=None,+ gt=0,+ allow_inf_nan=False,+ )class WikiPageDraft(BaseModel):diff --git a/bot/vikingbot/compile/renderer.py b/bot/vikingbot/compile/renderer.pyindex 17a5c8332..f14b99960 100644--- a/bot/vikingbot/compile/renderer.py+++ b/bot/vikingbot/compile/renderer.py@@ -370,6 +370,8 @@ class WikiRenderer:raise ValueError("Wiki bundle exceeds the page limit")if len(bundle.files) > self.limits.output_files:raise ValueError("Wiki bundle exceeds the file limit")+ if len(bundle.pages) + len(bundle.files) > self.limits.output_operations:+ raise ValueError("Wiki bundle exceeds the combined output operation limit")if not bundle.pages and bundle.links:raise ValueError("an empty Wiki bundle cannot contain links")target_type = context_type_for_uri(target_uri)@@ -453,13 +455,14 @@ class WikiRenderer:raise ValueError(f"WikiLink references an unknown page_id: f={link.f}, t={link.t}")if not link.match_text:raise ValueError("WikiLink match_text is required")- if LinkRenderer._find_match_span(+ if not LinkRenderer.can_render_link(source_page.body_markdown,link.match_text,- LinkRenderer.protected_markdown_spans(source_page.body_markdown),- ) is None:+ page_uris[link.f][0],+ page_uris[link.t][0],+ ):raise ValueError(- f"WikiLink match_text is not a linkable body anchor: {link.match_text!r}"+ f"WikiLink match_text is not a satisfiable body anchor: {link.match_text!r}")resolved_links = resolve_wiki_links(bundle.links, page_uris, strict=True)diff --git a/bot/vikingbot/compile/service.py b/bot/vikingbot/compile/service.pyindex 7a448c981..8b7e8bbec 100644--- a/bot/vikingbot/compile/service.py+++ b/bot/vikingbot/compile/service.py@@ -3,7 +3,9 @@from __future__ import annotationsimport asyncio+import base64import json+import posixpathimport reimport shleximport shutil@@ -16,11 +18,16 @@ from typing import Any, Mappingfrom loguru import logger-from openviking.core.namespace import classify_uri, uri_parts+from openviking.core.namespace import classify_uri, relative_uri_path, uri_partsfrom openviking.core.skill_loader import SkillLoader-from openviking.utils.path_safety import sanitize_relative_viking_path+from openviking.session.memory.utils.link_renderer import LinkRenderer, MarkdownLink+from openviking.utils.path_safety import (+ safe_join_viking_uri,+ sanitize_relative_viking_path,+ validate_safe_viking_uri_path,+)from openviking_cli.exceptions import OpenVikingError-from vikingbot.agent.loop import AgentLoop+from vikingbot.agent.loop import AgentIterationLimitExceeded, AgentLoopfrom vikingbot.agent.skills import SkillsLoaderfrom vikingbot.agent.tools.compile import CompileScopedTool, SubmitWikiBundleToolfrom vikingbot.agent.tools.registry import ToolRegistry@@ -42,6 +49,7 @@ from vikingbot.compile.models import ()from vikingbot.compile.renderer import (WikiRenderer,+ content_hash,has_unclosed_frontmatter,validate_declared_okf_markdown,)@@ -49,6 +57,7 @@ from vikingbot.compile.store import CompileTaskStorefrom vikingbot.config.schema import SandboxBackend, SandboxMode, SessionKeyfrom vikingbot.openviking_mount.ov_server import VikingClientfrom vikingbot.sandbox import SandboxManager+from vikingbot.sandbox.base import SandboxBackend as WorkspaceSandbox_OV_READ_TOOLS = frozenset({@@ -71,7 +80,7 @@ _COMPILE_ISOLATED_EXEC_BACKENDS = frozenset(_SKILL_EXCLUDED_FILES = frozenset({".abstract.md", ".overview.md", ".relations.json", ".source.json"})-_CATALOG_EXCLUDED_FILES = _SKILL_EXCLUDED_FILES+_CATALOG_EXCLUDED_FILES = _SKILL_EXCLUDED_FILES_CATALOG_FRONTMATTER_LINES = 128_TARGET_CATALOG_QUERY_CHARS = 40_000_REQUIREMENT_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$")@@ -86,6 +95,47 @@ _WORKSPACE_SUBMISSION_RULE_WITHOUT_EXEC = ()+def _consume_background_result(future: asyncio.Future[Any], *, label: str) -> None:+ try:+ future.result()+ except asyncio.CancelledError:+ pass+ except Exception as exc:+ logger.warning("Compile {} failed after its grace deadline: {}", label, exc)+++async def _await_with_hard_timeout(+ awaitable: Awaitable[Any],+ *,+ timeout: float,+ label: str,+) -> Any:+ """Give bounded fallback work its full grace period, but never wait past it."""+ future = asyncio.ensure_future(awaitable)+ deadline = asyncio.get_running_loop().time() + timeout+ while True:+ remaining = max(0.0, deadline - asyncio.get_running_loop().time())+ try:+ done, _pending = await asyncio.wait({future}, timeout=remaining)+ except asyncio.CancelledError:+ # The task runtime may expire while an iteration-limit salvage is+ # already underway. Preserve the independent grace period.+ continue+ except BaseException:+ future.cancel()+ future.add_done_callback(+ lambda completed: _consume_background_result(completed, label=label)+ )+ raise+ if future in done:+ return future.result()+ future.cancel()+ future.add_done_callback(+ lambda completed: _consume_background_result(completed, label=label)+ )+ raise asyncio.TimeoutError++@dataclass(frozen=True)class CompileCapabilities:exec_enabled: bool@@ -252,6 +302,16 @@ class BotCompileService:*,connection: Mapping[str, Any],) -> SanitizedCompileRequest:+ if (+ request.runtime_timeout_seconds is not None+ and request.runtime_timeout_seconds > self.limits.task_runtime_seconds+ ):+ raise CompileFailure(+ "RESOURCE_EXHAUSTED",+ "Compile runtime_timeout_seconds exceeds the server limit of "+ f"{self.limits.task_runtime_seconds:g} seconds.",+ stage="queued",+ )raw_sources = [str(value).strip() for value in request.from_]if not raw_sources or any(not value for value in raw_sources):raise CompileFailure(@@ -333,6 +393,7 @@ class BotCompileService:"to": target,"reason": (request.reason or "").strip() or DEFAULT_COMPILE_REASON,"skill": canonical_skill,+ "runtime_timeout_seconds": request.runtime_timeout_seconds,})@@ -452,9 +513,19 @@ class BotCompileService:returntry:+ runtime_timeout = min(+ request.runtime_timeout_seconds or self.limits.task_runtime_seconds,+ self.limits.task_runtime_seconds,+ )+ runtime_deadline = asyncio.get_running_loop().time() + runtime_timeoutawait asyncio.wait_for(- self._execute_task(task_id, request, connection),- timeout=self.limits.task_runtime_seconds,+ self._execute_task(+ task_id,+ request,+ connection,+ runtime_deadline=runtime_deadline,+ ),+ timeout=runtime_timeout,)except asyncio.TimeoutError:task = await self.store.get(task_id)@@ -485,8 +556,11 @@ class BotCompileService:task_id: str,request: SanitizedCompileRequest,connection: dict[str, Any],+ *,+ runtime_deadline: float | None = None,) -> None:capabilities = self._compile_capabilities()+ target_type = classify_uri(request.to).context_typesession_key = SessionKey(type="compile", channel_id=task_id, chat_id=task_id)task_config = self.config.model_copy(update={@@ -499,6 +573,10 @@ class BotCompileService:sandbox_manager = SandboxManager(task_config, workspace_parent, task_config.workspace_path)workspace = sandbox_manager.get_workspace_path(session_key)client: VikingClient | None = None+ sandbox: WorkspaceSandbox | None = None+ workspace_baseline: set[str] | None = None+ submit_tool: Any = None+ salvage_allowed = Falsetry:await self._set_state(task_id, status="running", stage="loading_skill")client = await VikingClient.create(connection=connection, config=self.config)@@ -531,10 +609,14 @@ class BotCompileService:workspace=workspace,skill_name=skill_name,)+ sandbox = (+ await sandbox_manager.get_sandbox(session_key)+ if target_type == "resource"+ else None+ )await self._set_state(task_id, status="running", stage="collecting_context")sources = await self._build_sources(client, request.from_)- target_type = classify_uri(request.to).context_typeis_skill_target = target_type == "skill"if is_skill_target:catalog: list[dict[str, Any]] = []@@ -589,11 +671,12 @@ class BotCompileService:)workspace_baseline = ({- path.relative_to(workspace).as_posix()- for path in workspace.rglob("*")- if path.is_file()+ entry.path+ for entry in await sandbox.list_files(+ max_entries=self.limits.target_inventory_entries+ )}- if target_type == "resource"+ if sandbox is not Noneelse None)registry, ov_names = self._build_compile_registry(@@ -607,6 +690,7 @@ class BotCompileService:wiki_uri_resolver=resolve_wiki_uri,capabilities=capabilities,)+ submit_tool = registry.get("submit_wiki_bundle")system_prompt, user_prompt = self._build_prompts(request=request,skill_name=skill_name,@@ -623,6 +707,7 @@ class BotCompileService:)await self._set_state(task_id, status="running", stage="agent")+ salvage_allowed = Truetry:bundle, _tools, _usage, _iterations = await request_loop.run_structured_task(system_prompt=system_prompt,@@ -633,11 +718,27 @@ class BotCompileService:stop_tool_names=["submit_wiki_bundle"],openviking_connection=connection,)+ except AgentIterationLimitExceeded as exc:+ salvage_allowed = False+ if target_type != "resource":+ raise CompileFailure("AGENT_OUTPUT_INVALID", str(exc), stage="agent") from exc+ assert sandbox is not None+ await self._complete_salvaged_task(+ task_id=task_id,+ client=client,+ request=request,+ sandbox=sandbox,+ workspace_baseline=workspace_baseline,+ reason=f"reached its {exc.max_iterations}-iteration limit",+ failure_code="AGENT_OUTPUT_INVALID",+ )+ returnexcept ValueError as exc:+ salvage_allowed = Falseraise CompileFailure("AGENT_OUTPUT_INVALID", str(exc), stage="agent") from exc+ salvage_allowed = Falseawait self._set_state(task_id, status="running", stage="rendering")- submit_tool = registry.get("submit_wiki_bundle")file_payloads = list(getattr(submit_tool, "file_payloads", []))if is_skill_target:await self._set_state(task_id, status="committing", stage="writing")@@ -775,11 +876,383 @@ class BotCompileService:task.error = Noneawait self.store.update(task_id, complete)+ except asyncio.CancelledError:+ if (+ runtime_deadline is None+ or asyncio.get_running_loop().time() < runtime_deadline+ or client is None+ or target_type != "resource"+ or not salvage_allowed+ or getattr(submit_tool, "bundle", None) is not None+ ):+ raise+ task = await self.store.get(task_id)+ if task is None or task.status in TERMINAL_STATUSES or task.stage != "agent":+ raise+ assert sandbox is not None+ await self._complete_salvaged_task(+ task_id=task_id,+ client=client,+ request=request,+ sandbox=sandbox,+ workspace_baseline=workspace_baseline,+ reason="reached its runtime deadline",+ failure_code="DEADLINE_EXCEEDED",+ )finally:- await sandbox_manager.cleanup_session(session_key)- if client is not None:- await client.close()- shutil.rmtree(workspace_parent, ignore_errors=True)+ await self._cleanup_execution_resources(+ sandbox_manager=sandbox_manager,+ session_key=session_key,+ client=client,+ workspace_parent=workspace_parent,+ )++ async def _cleanup_execution_resources(+ self,+ *,+ sandbox_manager: SandboxManager,+ session_key: SessionKey,+ client: VikingClient | None,+ workspace_parent: Path,+ ) -> None:+ async def cleanup() -> None:+ try:+ await sandbox_manager.cleanup_session(session_key)+ finally:+ try:+ if client is not None:+ await client.close()+ finally:+ await asyncio.to_thread(+ shutil.rmtree,+ workspace_parent,+ ignore_errors=True,+ )++ try:+ await _await_with_hard_timeout(+ cleanup(),+ timeout=self.limits.cleanup_grace_seconds,+ label="cleanup",+ )+ except asyncio.TimeoutError:+ logger.warning(+ "Compile cleanup exceeded its {}-second grace limit",+ self.limits.cleanup_grace_seconds,+ )++ async def _complete_salvaged_task(+ self,+ *,+ task_id: str,+ client: VikingClient,+ request: SanitizedCompileRequest,+ sandbox: WorkspaceSandbox,+ workspace_baseline: set[str] | None,+ reason: str,+ failure_code: str,+ ) -> None:+ async def salvage_and_complete() -> CompileResult | None:+ await self._set_state(task_id, status="committing", stage="salvaging")+ result = await self._salvage_workspace(+ client=client,+ request=request,+ sandbox=sandbox,+ workspace_baseline=workspace_baseline,+ reason=reason,+ )+ if result is None:+ return None++ def complete(task: CompileTask) -> None:+ if task.status in TERMINAL_STATUSES:+ return+ task.status = "completed"+ task.stage = "salvaged"+ task.result = result+ task.error = None++ await self.store.update(task_id, complete)+ return result++ try:+ result = await _await_with_hard_timeout(+ salvage_and_complete(),+ timeout=self.limits.salvage_grace_seconds,+ label="salvage",+ )+ except asyncio.TimeoutError as exc:+ raise CompileFailure(+ failure_code,+ f"Compile {reason} and fallback saving exceeded its "+ f"{self.limits.salvage_grace_seconds:g}-second grace limit.",+ stage="salvaging",+ ) from exc+ except Exception as exc:+ raise CompileFailure(+ failure_code,+ f"Compile {reason} and fallback saving failed: {exc}",+ stage="salvaging",+ ) from exc+ if result is None:+ raise CompileFailure(+ failure_code,+ f"Compile {reason} before producing files to save.",+ stage="agent",+ )++ async def _salvage_workspace(+ self,+ *,+ client: VikingClient,+ request: SanitizedCompileRequest,+ sandbox: WorkspaceSandbox,+ workspace_baseline: set[str] | None,+ reason: str = "reached its runtime deadline",+ ) -> CompileResult | None:+ files: dict[str, bytes] = {}+ page_paths: set[str] = set()+ total_bytes = 0+ skipped_files = 0+ page_files = 0+ artifact_files = 0+ output_keys: set[str] = set()+ staging_prefix = f"{COMPILE_STAGING_ROOT}/"+ wiki_prefix = f"{COMPILE_WIKI_PAGE_ROOT}/"+ baseline = workspace_baseline or set()+ entries = sorted(+ await sandbox.list_files(max_entries=self.limits.target_inventory_entries),+ key=lambda entry: (+ entry.path.startswith(staging_prefix),+ entry.path,+ ),+ )+ for entry in entries:+ relative = entry.path+ if relative in baseline:+ continue+ if relative.split("/", 1)[0].casefold() == "skills":+ continue+ is_page = relative.startswith(wiki_prefix)+ if relative.startswith(staging_prefix) and not is_page:+ continue+ output_path = relative.removeprefix(wiki_prefix)+ try:+ output_path = sanitize_relative_viking_path(output_path)+ validate_safe_viking_uri_path(safe_join_viking_uri(request.to, output_path))+ except ValueError:+ skipped_files += 1+ continue+ output_key = output_path.casefold()+ if (+ output_key in output_keys+ or (is_page and page_files >= self.limits.output_pages)+ or (not is_page and artifact_files >= self.limits.output_files)+ or len(files) >= self.limits.output_operations+ or entry.size < 0+ or entry.size > self.limits.output_total_bytes - total_bytes+ ):+ skipped_files += 1+ continue+ try:+ payload = await sandbox.read_file_bytes(+ relative,+ max_bytes=self.limits.output_total_bytes - total_bytes,+ )+ except Exception:+ skipped_files += 1+ continue+ files[output_path] = payload+ output_keys.add(output_key)+ total_bytes += len(payload)+ page_files += is_page+ artifact_files += not is_page+ if is_page:+ page_paths.add(output_path)++ if not files:+ return None++ entries = await client.tree(+ request.to,+ node_limit=self.limits.target_inventory_entries + 1,+ )+ if len(entries) > self.limits.target_inventory_entries:+ raise ValueError(+ f"Compile target inventory exceeds {self.limits.target_inventory_entries} entries"+ )+ existing: dict[str, str] = {}+ existing_by_case: dict[str, list[str]] = {}+ existing_sizes: dict[str, int] = {}+ for entry in entries:+ if not isinstance(entry, Mapping) or entry.get("isDir", entry.get("is_dir", False)):+ continue+ uri = str(entry.get("uri") or "").rstrip("/")+ relative = relative_uri_path(request.to, uri)+ if relative:+ existing[relative] = uri+ existing_by_case.setdefault(relative.casefold(), []).append(uri)+ size = entry.get("size")+ if isinstance(size, int) and size >= 0:+ existing_sizes[uri] = size++ known_paths = {*files, *existing}+ for path in page_paths:+ payload = files[path]+ try:+ content = payload.decode("utf-8")+ except UnicodeDecodeError:+ continue+ repaired = self._repair_salvaged_markdown(+ content, source_path=path, known_paths=known_paths+ ).encode("utf-8")+ repaired_total = total_bytes - len(payload) + len(repaired)+ if repaired_total <= self.limits.output_total_bytes:+ files[path] = repaired+ total_bytes = repaired_total++ operations = []+ saved_page_paths = set(page_paths)+ for path, payload in files.items():+ existing_uri = existing.get(path)+ if existing_uri is None:+ matches = existing_by_case.get(path.casefold(), [])+ existing_uri = matches[0] if len(matches) == 1 else None+ if existing_uri is None:+ uri = safe_join_viking_uri(request.to, path).rstrip("/")+ precondition = {"kind": "create_if_absent"}+ else:+ uri = existing_uri+ size = existing_sizes.get(uri)+ if size is None:+ stat = await client.stat(uri)+ size = stat.get("size")+ if not isinstance(size, int) or size < 0 or size > self.limits.output_total_bytes:+ skipped_files += 1+ saved_page_paths.discard(path)+ continue+ current = await client.download_bytes(uri)+ precondition = {+ "kind": "replace_if_hash",+ "base_hash": content_hash(current),+ }+ operations.append(+ {+ "uri": uri,+ "content_base64": base64.b64encode(payload).decode("ascii"),+ "precondition": precondition,+ }+ )++ if not operations:+ return None+ batch_result = await client.batch_write(+ root_uri=request.to,+ operations=operations,+ wait=False,+ )+ warnings = [+ f"Compile {reason}; workspace files were saved before cleanup. "+ "This partial output did not pass the normal bundle validation."+ ]+ if skipped_files:+ warnings.append(+ f"Skipped {skipped_files} unsafe, duplicate, unreadable, or over-limit file(s)."+ )+ return CompileResult(+ from_=request.from_,+ to=request.to,+ skill=request.skill,+ created=list(batch_result.get("created", [])),+ updated=list(batch_result.get("updated", [])),+ unchanged=list(batch_result.get("unchanged", [])),+ page_count=len(saved_page_paths),+ warnings=warnings,+ )++ @staticmethod+ def _repair_salvaged_markdown(+ content: str,+ *,+ source_path: str,+ known_paths: set[str],+ ) -> str:+ known = {path for path in known_paths if path}+ paths_by_name: dict[str, set[str]] = {}+ for path in known:+ paths_by_name.setdefault(posixpath.basename(path).casefold(), set()).add(path)++ links = list(LinkRenderer.iter_markdown_links(content))+ link_spans = {(link.start, link.end) for link in links}+ protected = [+ span+ for span in LinkRenderer.protected_markdown_spans(content)+ if span not in link_spans+ ]+ source_dir = posixpath.dirname(source_path)++ def replace(link: MarkdownLink, *, image: bool) -> str:+ start = link.start - int(image)+ original = content[start : link.end]+ if any(+ not (link.end <= span_start or start >= span_end)+ for span_start, span_end in protected+ ):+ return original++ target = link.target.strip()+ if (+ not target+ or target.startswith(("#", "?", "/"))+ or re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", target)+ ):+ return original+ if target.startswith("<") and target.endswith(">"):+ target = target[1:-1]++ suffix_at = min(+ (index for token in "#?" if (index := target.find(token)) >= 0),+ default=len(target),+ )+ raw_path, suffix = target[:suffix_at], target[suffix_at:]+ normalized_path = LinkRenderer.normalize_markdown_target(raw_path)+ resolved = posixpath.normpath(posixpath.join(source_dir, normalized_path))+ if resolved in known:+ return original++ name = posixpath.basename(normalized_path)+ names = {name.casefold()}+ if not posixpath.splitext(name)[1]:+ names.add(f"{name}.md".casefold())+ candidates = {+ path+ for name in names+ for path in paths_by_name.get(name, set())+ if path.casefold() != source_path.casefold()+ }+ if len(candidates) != 1:+ return link.text+ candidate = next(iter(candidates))++ corrected = posixpath.relpath(candidate, source_dir or ".")+ if corrected == ".":+ return link.text+ if "/" not in corrected and not corrected.startswith("."):+ corrected = f"./{corrected}"+ corrected = corrected.replace(" ", "%20").replace("(", "%28").replace(")", "%29")+ image_marker = "!" if image else ""+ return f"{image_marker}[{link.text}]({corrected}{suffix})"++ result: list[str] = []+ position = 0+ for link in links:+ image = link.start > 0 and content[link.start - 1] == "!"+ start = link.start - int(image)+ result.append(content[position:start])+ result.append(replace(link, image=image))+ position = link.end+ result.append(content[position:])+ return "".join(result)@staticmethodasync def _tag_wiki_files(@@ -1389,6 +1862,8 @@ Selected Skill:async def _fail(self, task_id: str, failure: CompileFailure) -> None:def mutate(task: CompileTask) -> None:+ if task.status in TERMINAL_STATUSES:+ returntask.status = "failed"task.stage = failure.stagetask.result = Nonediff --git a/bot/vikingbot/sandbox/__init__.py b/bot/vikingbot/sandbox/__init__.pyindex 692e88641..d8faecd88 100644--- a/bot/vikingbot/sandbox/__init__.py+++ b/bot/vikingbot/sandbox/__init__.py@@ -2,10 +2,11 @@from vikingbot.sandbox.base import (SandboxBackend,- SandboxError,- SandboxNotStartedError,SandboxDisabledError,+ SandboxError,SandboxExecutionError,+ SandboxFileInfo,+ SandboxNotStartedError,UnsupportedBackendError,)from vikingbot.sandbox.manager import SandboxManager@@ -17,5 +18,6 @@ __all__ = ["SandboxNotStartedError","SandboxDisabledError","SandboxExecutionError",+ "SandboxFileInfo","UnsupportedBackendError",]diff --git a/bot/vikingbot/sandbox/backends/aiosandbox.py b/bot/vikingbot/sandbox/backends/aiosandbox.pyindex 525fb4082..9fef8f5b0 100644--- a/bot/vikingbot/sandbox/backends/aiosandbox.py+++ b/bot/vikingbot/sandbox/backends/aiosandbox.py@@ -1,5 +1,6 @@"""AIO Sandbox backend implementation using agent-sandbox SDK."""+import posixpathfrom pathlib import Pathfrom typing import Any@@ -7,7 +8,7 @@ from loguru import loggerfrom vikingbot.config.schema import SandboxConfig, SessionKeyfrom vikingbot.sandbox.backends import register_backend-from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError+from vikingbot.sandbox.base import SandboxBackend, SandboxFileInfo, SandboxNotStartedError@register_backend("aiosandbox")@@ -101,17 +102,38 @@ class AioSandboxBackend(SandboxBackend):"""Get the current working directory inside the sandbox."""return "/home/gem"+ def _sandbox_path(self, path: str) -> str:+ if path.startswith("/"):+ return path+ relative = self._normalize_workspace_path(path)+ return self.sandbox_cwd if not relative else f"{self.sandbox_cwd}/{relative}"++ async def _list_path(self, path: str) -> list[Any]:+ if not self._client:+ raise SandboxNotStartedError()+ result = await self._client.file.list_path(+ path=self._sandbox_path(path),+ recursive=False,+ show_hidden=True,+ include_size=True,+ )+ data = getattr(result, "data", result)+ return list(getattr(data, "files", None) or [])++ @staticmethod+ def _file_info_size(file_info: Any, path: str) -> int:+ size = getattr(file_info, "size", None)+ if not isinstance(size, int) or size < 0:+ raise IOError(f"Sandbox did not report a valid file size: {path}")+ return size+async def read_file(self, path: str) -> str:"""Read file from AIO Sandbox using SDK."""if not self._client:raise SandboxNotStartedError()try:- sandbox_path = path- if not path.startswith("/"):- sandbox_path = f"/home/gem/{path}"-- result = await self._client.file.read_file(file=sandbox_path)+ result = await self._client.file.read_file(file=self._sandbox_path(path))if hasattr(result, "data") and hasattr(result.data, "content"):return result.data.contentreturn str(result)@@ -125,11 +147,9 @@ class AioSandboxBackend(SandboxBackend):raise SandboxNotStartedError()try:- sandbox_path = path- if not path.startswith("/"):- sandbox_path = f"/home/gem/{path}"-- result = await self._client.file.write_file(file=sandbox_path, content=content)+ result = await self._client.file.write_file(+ file=self._sandbox_path(path), content=content+ )if not result.success:raise Exception(f"Write failed: {result.message}")except Exception as e:@@ -138,25 +158,83 @@ class AioSandboxBackend(SandboxBackend):async def list_dir(self, path: str) -> list[tuple[str, bool]]:"""List directory in AIO Sandbox using SDK."""- if not self._client:- raise SandboxNotStartedError()-try:- sandbox_path = path- if not path.startswith("/"):- sandbox_path = f"/home/gem/{path}"-- # Use find_files with "*" glob to list directory- result = await self._client.file.find_files(path=sandbox_path, glob="*")-- items = []- if hasattr(result, "data") and hasattr(result.data, "files"):- for file_info in result.data.files:- if hasattr(file_info, "name") and hasattr(file_info, "type"):- is_dir = file_info.type == "directory"- items.append((file_info.name, is_dir))-- return items+ return sorted(+ (+ (str(file_info.name), bool(file_info.is_directory))+ for file_info in await self._list_path(path)+ ),+ key=lambda item: item[0],+ )except Exception as e:logger.error(f"[AioSandbox] Failed to list directory {path}: {e}")raise++ async def list_files(+ self,+ path: str = ".",+ *,+ max_entries: int,+ ) -> list[SandboxFileInfo]:+ """Recursively enumerate the remote AIO workspace with a server-side bound."""+ if not self._client:+ raise SandboxNotStartedError()+ self._validate_max_entries(max_entries)+ root = self._normalize_workspace_path(path)+ sandbox_root = self._sandbox_path(root or ".")+ result = await self._client.file.glob_files(+ path=sandbox_root,+ pattern="**",+ include_hidden=True,+ files_only=False,+ include_metadata=True,+ max_results=max_entries + 1,+ sort_by="path",+ )+ data = getattr(result, "data", result)+ entries = list(getattr(data, "files", None) or [])+ total_count = getattr(data, "total_count", None)+ normalized_entries = []+ for entry in entries:+ remote_path = str(getattr(entry, "path", ""))+ if not remote_path.startswith("/"):+ remote_path = posixpath.join(sandbox_root, remote_path)+ normalized_entries.append((entry, posixpath.normpath(remote_path)))+ root_entries = sum(remote_path == sandbox_root for _, remote_path in normalized_entries)+ if (+ bool(getattr(data, "truncated", False))+ or len(entries) - root_entries > max_entries+ or (isinstance(total_count, int) and total_count - root_entries > max_entries)+ ):+ raise ValueError(f"Sandbox workspace inventory exceeds {max_entries} entries")++ workspace_prefix = self.sandbox_cwd.rstrip("/") + "/"+ root_prefix = sandbox_root.rstrip("/") + "/"+ files: list[SandboxFileInfo] = []+ seen: set[str] = set()+ for file_info, remote_path in normalized_entries:+ if remote_path != sandbox_root and not remote_path.startswith(root_prefix):+ raise IOError("Sandbox returned a path outside the requested workspace root")+ if remote_path == self.sandbox_cwd.rstrip("/"):+ continue+ if not remote_path.startswith(workspace_prefix):+ raise IOError("Sandbox returned a path outside the workspace")+ relative = self._normalize_workspace_path(remote_path.removeprefix(workspace_prefix))+ if not relative or relative in seen or bool(getattr(file_info, "is_directory", False)):+ continue+ seen.add(relative)+ files.append(+ SandboxFileInfo(+ path=relative,+ size=self._file_info_size(file_info, relative),+ )+ )+ return sorted(files, key=lambda item: item.path)++ async def read_file_bytes(self, path: str, *, max_bytes: int | None = None) -> bytes:+ """Stream bytes from the remote workspace, retaining at most limit + 1 bytes."""+ if not self._client:+ raise SandboxNotStartedError()+ self._validate_max_bytes(max_bytes)+ stream = self._client.file.download_file(path=self._sandbox_path(path))+ return await self._collect_stream_bytes(stream, path, max_bytes)diff --git a/bot/vikingbot/sandbox/backends/direct.py b/bot/vikingbot/sandbox/backends/direct.pyindex 565754a00..87aafbb0e 100644--- a/bot/vikingbot/sandbox/backends/direct.py+++ b/bot/vikingbot/sandbox/backends/direct.py@@ -102,17 +102,14 @@ class DirectBackend(SandboxBackend):"""Get the current working directory (uses actual host cwd)."""return str(self._workspace)- async def read_file_bytes(self, path: str) -> bytes:+ async def read_file_bytes(self, path: str, *, max_bytes: int | None = None) -> bytes:+ self._validate_max_bytes(max_bytes)sandbox_path = Path(path)if not sandbox_path.is_absolute():sandbox_path = self._workspace / pathself._check_path_restriction(sandbox_path)- if not sandbox_path.exists():- raise FileNotFoundError(f"File not found: {path}")- if not sandbox_path.is_file():- raise IOError(f"Not a file: {path}")- return await asyncio.to_thread(sandbox_path.read_bytes)+ return await asyncio.to_thread(self._read_local_bytes, sandbox_path, path, max_bytes)async def read_file(self, path: str) -> str:data = await self.read_file_bytes(path)diff --git a/bot/vikingbot/sandbox/backends/opensandbox.py b/bot/vikingbot/sandbox/backends/opensandbox.pyindex cd54893ba..d21720c75 100644--- a/bot/vikingbot/sandbox/backends/opensandbox.py+++ b/bot/vikingbot/sandbox/backends/opensandbox.py@@ -2,7 +2,10 @@import asyncioimport atexit+import jsonimport os+import posixpath+import shleximport subprocessimport timefrom datetime import timedelta@@ -14,7 +17,7 @@ from loguru import loggerfrom vikingbot.config.schema import SandboxConfig, SessionKeyfrom vikingbot.sandbox.backends import register_backend-from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError+from vikingbot.sandbox.base import SandboxBackend, SandboxFileInfo, SandboxNotStartedError# Global to track the opensandbox-server process_OSB_SERVER_PROCESS: "subprocess.Popen | None" = None@@ -293,6 +296,12 @@ class OpenSandboxBackend(SandboxBackend):def sandbox_cwd(self) -> str:return "/workspace"+ def _sandbox_path(self, path: str) -> str:+ if path.startswith("/"):+ return path+ relative = self._normalize_workspace_path(path)+ return self.sandbox_cwd if not relative else f"{self.sandbox_cwd}/{relative}"+async def read_file(self, path: str) -> str:"""Read file from OpenSandbox."""if not self._sandbox:@@ -301,10 +310,7 @@ class OpenSandboxBackend(SandboxBackend):# In VKE environment, use SDK API; in local, use base implementation (host mount)if self._is_vke:try:- sandbox_path = path- if not path.startswith("/"):- sandbox_path = f"/workspace/{path}"- return await self._sandbox.files.read_file(sandbox_path)+ return await self._sandbox.files.read_file(self._sandbox_path(path))except Exception as e:logger.error(f"[OpenSandbox] Failed to read file {path}: {e}")raise@@ -319,10 +325,7 @@ class OpenSandboxBackend(SandboxBackend):# In VKE environment, use SDK API; in local, use base implementation (host mount)if self._is_vke:try:- sandbox_path = path- if not path.startswith("/"):- sandbox_path = f"/workspace/{path}"- await self._sandbox.files.write_file(sandbox_path, content, mode=0o644)+ await self._sandbox.files.write_file(self._sandbox_path(path), content, mode=0o644)except Exception as e:logger.error(f"[OpenSandbox] Failed to write file {path}: {e}")raise@@ -360,3 +363,110 @@ class OpenSandboxBackend(SandboxBackend):raiseelse:return await super().list_dir(path)++ async def list_files(+ self,+ path: str = ".",+ *,+ max_entries: int,+ ) -> list[SandboxFileInfo]:+ """List remote VKE files without materializing an unbounded search response."""+ if not self._is_vke:+ return await super().list_files(path, max_entries=max_entries)+ if not self._sandbox:+ raise SandboxNotStartedError()+ self._validate_max_entries(max_entries)+ root = self._normalize_workspace_path(path)+ sandbox_root = self._sandbox_path(root or ".").rstrip("/")++ # OpenSandbox's search API returns one fully materialized JSON array and+ # has no server-side result limit. Traverse in the sandbox so both the+ # walk and the response stop at the service-owned inventory bound.+ script = "\n".join(+ [+ "import json, os",+ f"root = {sandbox_root!r}",+ f"limit = {max_entries}",+ f"pending = [({root!r}, root)]",+ "files = []",+ "visited = 0",+ "overflow = False",+ "while pending and not overflow:",+ " relative_dir, directory = pending.pop()",+ " try:",+ " entries = os.scandir(directory)",+ " except FileNotFoundError:",+ " continue",+ " with entries:",+ " for entry in entries:",+ " visited += 1",+ " if visited > limit:",+ " overflow = True",+ " break",+ " relative = os.path.join(relative_dir, entry.name)",+ " try:",+ " if entry.is_dir(follow_symlinks=False):",+ " pending.append((relative, entry.path))",+ " elif entry.is_file(follow_symlinks=False):",+ " size = entry.stat(follow_symlinks=False).st_size",+ " files.append((relative, size))",+ " except FileNotFoundError:",+ " pass",+ 'print(json.dumps({"overflow": overflow, "files": files}, separators=(",", ":")))',+ ]+ )++ from opensandbox.models.execd import RunCommandOpts++ execution = await self._sandbox.commands.run(+ f"python3 -c {shlex.quote(script)}",+ opts=RunCommandOpts(timeout=timedelta(seconds=30)),+ )+ if execution.error:+ raise IOError(f"Sandbox workspace inventory failed: {execution.error.value}")+ stdout = "".join(message.text for message in execution.logs.stdout)+ try:+ inventory = json.loads(stdout)+ overflow = inventory["overflow"]+ entries = inventory["files"]+ except (json.JSONDecodeError, KeyError, TypeError) as exc:+ raise IOError("Sandbox returned an invalid workspace inventory") from exc+ if not isinstance(overflow, bool) or not isinstance(entries, list):+ raise IOError("Sandbox returned an invalid workspace inventory")+ if overflow:+ raise ValueError(f"Sandbox workspace inventory exceeds {max_entries} entries")++ workspace_prefix = self.sandbox_cwd.rstrip("/") + "/"+ files: list[SandboxFileInfo] = []+ seen: set[str] = set()+ for entry in entries:+ if not isinstance(entry, list) or len(entry) != 2:+ raise IOError("Sandbox returned an invalid workspace inventory")+ remote_path, size = entry+ if not isinstance(remote_path, str):+ raise IOError("Sandbox returned an invalid workspace inventory")+ remote_path = posixpath.normpath(posixpath.join(self.sandbox_cwd, remote_path))+ if not remote_path.startswith(workspace_prefix):+ raise IOError("Sandbox returned a path outside the workspace")+ relative = remote_path.removeprefix(workspace_prefix)+ relative = self._normalize_workspace_path(relative)+ if not relative or relative in seen:+ continue+ if not isinstance(size, int) or size < 0:+ raise IOError(f"Sandbox did not report a valid file size: {relative}")+ seen.add(relative)+ files.append(SandboxFileInfo(path=relative, size=size))+ return sorted(files, key=lambda item: item.path)++ async def read_file_bytes(self, path: str, *, max_bytes: int | None = None) -> bytes:+ if not self._is_vke:+ return await super().read_file_bytes(path, max_bytes=max_bytes)+ if not self._sandbox:+ raise SandboxNotStartedError()+ self._validate_max_bytes(max_bytes)+ range_header = None if max_bytes is None else f"bytes=0-{max_bytes}"+ stream = await self._sandbox.files.read_bytes_stream(+ self._sandbox_path(path),+ range_header=range_header,+ )+ return await self._collect_stream_bytes(stream, path, max_bytes)diff --git a/bot/vikingbot/sandbox/base.py b/bot/vikingbot/sandbox/base.pyindex 891de5bcd..c4d775bca 100644--- a/bot/vikingbot/sandbox/base.py+++ b/bot/vikingbot/sandbox/base.py@@ -1,11 +1,24 @@"""Abstract interface for sandbox backends."""import asyncio+import os+import posixpathfrom abc import ABC, abstractmethod+from collections import deque+from collections.abc import AsyncIterator+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any+@dataclass(frozen=True)+class SandboxFileInfo:+ """A regular file in the sandbox workspace."""++ path: str+ size: int++class SandboxBackend(ABC):"""Abstract base class for sandbox backends."""@@ -74,11 +87,80 @@ class SandboxBackend(ABC):return self.workspace / path.lstrip("/")return self.workspace / path- async def read_file_bytes(self, path: str) -> bytes:+ @staticmethod+ def _normalize_workspace_path(path: str) -> str:+ """Normalize a workspace-relative path used by bounded file APIs."""+ value = str(path)+ if value in {"", ".", "./"}:+ return ""+ candidate = Path(value)+ if candidate.is_absolute() or ".." in candidate.parts:+ raise ValueError(f"Path must be relative to the sandbox workspace: {path}")+ return candidate.as_posix().removeprefix("./")++ @staticmethod+ def _join_workspace_path(directory: str, name: str) -> str:+ if not name or name in {".", ".."} or "/" in name:+ raise IOError(f"Invalid sandbox directory entry: {name!r}")+ return posixpath.join(directory, name) if directory else name++ @staticmethod+ def _validate_max_bytes(max_bytes: int | None) -> None:+ if max_bytes is not None and max_bytes < 0:+ raise ValueError("max_bytes must be non-negative")++ @staticmethod+ def _validate_max_entries(max_entries: int) -> None:+ if max_entries <= 0:+ raise ValueError("max_entries must be positive")++ @staticmethod+ def _read_local_bytes(path: Path, original_path: str, max_bytes: int | None) -> bytes:+ if not path.exists():+ raise FileNotFoundError(f"File not found: {original_path}")+ if not path.is_file():+ raise IOError(f"Not a file: {original_path}")+ with path.open("rb") as stream:+ data = stream.read() if max_bytes is None else stream.read(max_bytes + 1)+ if max_bytes is not None and len(data) > max_bytes:+ raise ValueError(f"File exceeds the {max_bytes}-byte read limit: {original_path}")+ return data++ @staticmethod+ async def _collect_stream_bytes(+ stream: AsyncIterator[bytes],+ original_path: str,+ max_bytes: int | None,+ ) -> bytes:+ """Collect a byte stream while retaining at most ``max_bytes + 1`` bytes."""+ limit = None if max_bytes is None else max_bytes + 1+ data = bytearray()+ try:+ async for chunk in stream:+ if limit is None:+ data.extend(chunk)+ continue+ remaining = limit - len(data)+ if remaining <= 0:+ break+ data.extend(chunk[:remaining])+ if len(data) >= limit:+ break+ finally:+ close = getattr(stream, "aclose", None)+ if close is not None:+ await close()+ if max_bytes is not None and len(data) > max_bytes:+ raise ValueError(f"File exceeds the {max_bytes}-byte read limit: {original_path}")+ return bytes(data)++ async def read_file_bytes(self, path: str, *, max_bytes: int | None = None) -> bytes:"""Read file bytes from sandbox (default implementation: host filesystem).Args:path: Path to file (absolute or relative to sandbox_cwd)+ max_bytes: Optional hard read limit. At most ``max_bytes + 1``+ bytes are read before an oversized file is rejected.Returns:File content as bytes@@ -88,13 +170,62 @@ class SandboxBackend(ABC):IOError: If read failsPermissionError: If path outside workspace and restriction is enabled"""+ self._validate_max_bytes(max_bytes)sandbox_path = self._resolve_path(path)self._check_path_restriction(sandbox_path)- if not sandbox_path.exists():- raise FileNotFoundError(f"File not found: {path}")- if not sandbox_path.is_file():- raise IOError(f"Not a file: {path}")- return await asyncio.to_thread(sandbox_path.read_bytes)+ return await asyncio.to_thread(self._read_local_bytes, sandbox_path, path, max_bytes)++ async def list_files(+ self,+ path: str = ".",+ *,+ max_entries: int,+ ) -> list[SandboxFileInfo]:+ """Recursively list regular files without unbounded workspace traversal.++ Returned paths are relative to the sandbox workspace, including ``path``+ when a subdirectory is requested. Directories and files both consume the+ inventory budget so a deep directory-only tree is bounded as well.+ """+ self._validate_max_entries(max_entries)+ root = self._normalize_workspace_path(path)+ root_path = self._resolve_path(root)+ self._check_path_restriction(root_path)++ def inventory() -> list[SandboxFileInfo]:+ pending = deque([(root, root_path)])+ files: list[SandboxFileInfo] = []+ visited = 0+ while pending:+ directory, local_directory = pending.popleft()+ try:+ stream = os.scandir(local_directory)+ except FileNotFoundError:+ continue+ with stream:+ for entry in stream:+ visited += 1+ if visited > max_entries:+ raise ValueError(+ f"Sandbox workspace inventory exceeds {max_entries} entries"+ )+ relative = self._join_workspace_path(directory, entry.name)+ try:+ if entry.is_dir(follow_symlinks=False):+ pending.append((relative, Path(entry.path)))+ elif entry.is_file(follow_symlinks=False):+ files.append(+ SandboxFileInfo(+ path=relative,+ size=entry.stat(follow_symlinks=False).st_size,+ )+ )+ except FileNotFoundError:+ # The Agent may still be writing while salvage takes its snapshot.+ continue+ return sorted(files, key=lambda item: item.path)++ return await asyncio.to_thread(inventory)async def read_file(self, path: str) -> str:"""Read file from sandbox (default implementation: host filesystem).diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex e14a39f6c..156b689ef 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -164,6 +164,8 @@ struct CompileCreateRequest<'a> {skill: &'a str,#[serde(skip_serializing_if = "Option::is_none")]reason: Option<&'a str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ runtime_timeout_seconds: Option<f64>,}// ============ HttpClient ============@@ -356,12 +358,14 @@ impl HttpClient {to: &str,skill: &str,reason: Option<&str>,+ runtime_timeout_seconds: Option<f64>,) -> Result<CompileAccepted> {let body = CompileCreateRequest {from_uris,to,skill,reason,+ runtime_timeout_seconds,};self.post("/bot/v1/compile", &body).await}@@ -2267,7 +2271,9 @@ mod tests {tokio::spawn(async move {let (mut stream, _) = listener.accept().await.expect("request should arrive");let mut buffer = vec![0; 4096];- let _ = stream.read(&mut buffer).await.expect("request should read");+ let read = stream.read(&mut buffer).await.expect("request should read");+ let request = String::from_utf8_lossy(&buffer[..read]);+ assert!(request.contains(r#""runtime_timeout_seconds":86400.0"#));let body = r#"{"status":"ok","result":{"task_id":"cmp_1","status":"accepted","to":"viking://resources/wiki"}}"#;let response = format!("HTTP/1.1 202 Accepted\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",@@ -2295,6 +2301,7 @@ mod tests {"viking://resources/wiki","viking://agent/skills/wiki",None,+ Some(86_400.0),).await.expect("202 response body should deserialize");diff --git a/crates/ov_cli/src/commands/compile.rs b/crates/ov_cli/src/commands/compile.rsindex 753a3bcf5..34084cd7a 100644--- a/crates/ov_cli/src/commands/compile.rs+++ b/crates/ov_cli/src/commands/compile.rs@@ -14,6 +14,7 @@ pub async fn run(reason: Option<String>,wait: bool,timeout: Option<f64>,+ runtime_timeout: Option<f64>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -28,7 +29,7 @@ pub async fn run(.map(str::trim).filter(|value| !value.is_empty());let accepted = client- .create_compile(&sources, to.trim(), skill.trim(), reason)+ .create_compile(&sources, to.trim(), skill.trim(), reason, runtime_timeout).await?;if !wait {render_accepted(&accepted, output_format, compact);diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 352567110..9a6112b49 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -1080,6 +1080,13 @@ enum Commands {value_name = "seconds")]timeout: Option<f64>,+ /// Server-side runtime limit in seconds; reaching it saves partial resource output+ #[arg(+ long = "runtime-timeout",+ value_parser = config::parse_positive_timeout,+ value_name = "seconds"+ )]+ runtime_timeout: Option<f64>,},// --- Status & Observability ---@@ -3438,6 +3445,7 @@ async fn main() {reason,wait,timeout,+ runtime_timeout,} => {let client = ctx.get_client();commands::compile::run(@@ -3448,6 +3456,7 @@ async fn main() {reason,wait,timeout,+ runtime_timeout,ctx.output_format,ctx.compact,)@@ -3836,6 +3845,8 @@ mod tests {"--wait","--timeout","10",+ "--runtime-timeout",+ "86400",]).expect("compile flags should parse");match cli.command {@@ -3845,6 +3856,7 @@ mod tests {reason,wait,timeout,+ runtime_timeout,..} => {assert_eq!(from_uris.len(), 3);@@ -3852,6 +3864,7 @@ mod tests {assert!(reason.is_none());assert!(wait);assert_eq!(timeout, Some(10.0));+ assert_eq!(runtime_timeout, Some(86_400.0));}_ => panic!("expected compile command"),}diff --git a/docs/design/ov-compile-design.md b/docs/design/ov-compile-design.mdindex afc98cc0a..e8813c5c3 100644--- a/docs/design/ov-compile-design.md+++ b/docs/design/ov-compile-design.md@@ -48,12 +48,14 @@ ov compile \| `--reason` | 可选,本次整理任务的描述 || `--wait` | 可选,等待任务完成 || `--timeout` | 可选,仅与 `--wait` 一起使用;只限制 CLI 等待时间,不取消任务 |+| `--runtime-timeout` | 可选,正数且有限的服务端运行时限;只能缩短服务端最大值(默认 40 分钟) |参数在 OpenViking 用户身份下 canonicalize 后满足以下约束:- `from` 必须是一个或多个可读目录;重复项去重,空项报错;- `to` 必须是可写的 resource 或 memory 目录,不能是 namespace 根、文件、Skill 目录或 OpenViking 派生目录;- `skill` 必须解析为 Skill root,目录 URI 和其 `SKILL.md` URI 视为同一个 Skill;+- `runtime_timeout_seconds` 省略时使用服务端最大值,显式值不得超过该上限;- `from`、`to` 和 `skill` 的权限最终仍由 OpenViking Server 校验,CLI 不根据 URI 文本推断权限。`--reason` 为空时,VikingBot 使用以下默认任务描述:@@ -186,6 +188,8 @@ VikingBot 负责规范化参数并计算实际任务描述:effective_reason = (request.reason or "").strip() or DEFAULT_COMPILE_REASON```+可选的 `runtime_timeout_seconds` 必须为正数且有限,并且只能缩短 `CompileLimits.task_runtime_seconds` 定义的服务端最大值(默认 2400 秒);超限请求在创建任务时以 `RESOURCE_EXHAUSTED` 拒绝。+### 4.2 查询任务```http@@ -208,8 +212,8 @@ GET /bot/v1/compile/{task_id}| --- | --- || `accepted` | `queued` || `running` | `loading_skill`、`collecting_context`、`agent`、`rendering` |-| `committing` | `writing`、`refreshing` |-| `completed` | `completed` |+| `committing` | `writing`、`refreshing`、`salvaging` |+| `completed` | `completed`、`salvaged` || `failed` | 失败时所在阶段 |完成结果:@@ -347,7 +351,7 @@ await agent_loop.run_structured_task(BotCompileService 使用当前 provider/config、`workspace=task_workspace` 和 task-local `SandboxManager` 创建 request-local `AgentLoop`。`run_structured_task()` 用显式的 system/user prompt 建立 messages 后委托给 `_run_agent_loop()`;后者增加可选 `tool_registry` 和 `openviking_tool_names` 参数,并以选定 registry 同时生成 definitions 和执行工具。只有名称属于 `openviking_tool_names` 的现有 OV adapter 才在 `ToolContext`/post-call hook 中收到用户 connection;file 和 shell tool 收到 `None`。普通 chat 未传这些参数时仍使用 `self.tools` 和现有 connection 行为。-该入口不使用普通 chat history、自动 memory/experience recall 或普通最终回答。只有 `submit_wiki_bundle` 成功执行并保存合法 bundle 后才能结束;参数校验或领域校验返回 `Error:` 时继续同一 loop 修复。只有自然语言而没有 submit 时,wrapper 追加提交提醒后继续;达到 iteration limit 时直接返回 `AGENT_OUTPUT_INVALID`,不执行现有聊天路径的“禁用工具后再回答一次”。模型调用、工具执行和 token usage 仍沿用现有实现。+该入口不使用普通 chat history、自动 memory/experience recall 或普通最终回答。只有 `submit_wiki_bundle` 成功执行并保存合法 bundle 后才能结束;参数校验或领域校验返回 `Error:` 时继续同一 loop 修复。只有自然语言而没有 submit 时,wrapper 追加提交提醒后继续;达到 `bot.agents.max_tool_iterations` 配置的 iteration limit(默认 50)时,不执行现有聊天路径的“禁用工具后再回答一次”。Resource 目标会先在独立、受限的 salvage 阶段尝试保存符合条件的 workspace 产物:存在可保存产物时任务以 `completed/salvaged` 结束,否则返回 `AGENT_OUTPUT_INVALID`;Memory 和 Skill 目标直接返回 `AGENT_OUTPUT_INVALID`。模型调用、工具执行和 token usage 仍沿用现有实现。现有 `_run_agent_loop()` 的 stop 判定需要从“出现 stop tool name”改成“该 stop tool 的结果通过 `_is_tool_result_success()`”;这是 structured task 正确重试的必要条件,默认聊天未传 `stop_tool_names`,行为不变。@@ -389,7 +393,7 @@ class WikiBundleDraft(BaseModel):- `pages` 非空时,每个页面至少引用一个 `source_id`,且必须来自本次请求的来源描述;- Agent 不提供最终文件 URI,也不能直接写入 OpenViking。-Pydantic model 使用 `extra="forbid"`;字段校验和 CompileLimits 都在 `submit_wiki_bundle` 内执行。校验失败时,工具将错误返回给 Agent 修复。达到迭代上限仍未提交合法结果时,任务失败。+Pydantic model 使用 `extra="forbid"`;字段校验和 CompileLimits 都在 `submit_wiki_bundle` 内执行。校验失败时,工具将错误返回给 Agent 修复。达到迭代上限仍未提交合法结果时,Resource 目标按上述规则尝试 salvage;其他目标或没有合格 workspace 产物的 Resource 任务失败。页面数量由 reason、Skill 和材料决定。高层总结可以只生成一个页面,`link_count=0` 是合法结果。@@ -548,11 +552,11 @@ task_id, principal_scope, sanitized_request, status, stage, timestamps, result,Bot 当前没有通用的持久化后台任务管理器,因此这里实现一个最小 JSON task store,使用 per-task lock 和临时文件原子替换。进程内以有界的 `asyncio.Task` 集合和 semaphore 承载 accepted task;全局和单 principal admission 在任务创建前计数,超限同步返回 `RESOURCE_EXHAUSTED`。现有 `SessionManager` 继续只管理 chat JSONL,不承载 Compile 状态。-`sanitized_request` 只包含 canonical `from/to/skill` 和 effective reason;`openviking_connection` 仅由运行中 `asyncio.Task` 持有,不进入 JSON、异常详情或日志。+`sanitized_request` 只包含 canonical `from/to/skill`、effective reason 和可选的 `runtime_timeout_seconds`;`openviking_connection` 仅由运行中 `asyncio.Task` 持有,不进入 JSON、异常详情或日志。运行中任务目录可以保存有大小限制的 Skill 快照、catalog 和 draft,但不能保存用户凭证。任务进入终态后删除 workspace、Skill snapshot 和 draft;task/result/error JSON 最长保留 24 小时且最多保留 1,000 条,启动和任务结束时都会清理。-VikingBot 使用独立的 compile 并发限制,并对同一 canonical 目标目录串行执行。accepted task 最多排队 5 分钟,取得 target lock 和全局执行 slot 后才开始计算 30 分钟 runtime。该锁只减少同一 Bot 进程内的浪费;跨进程或人工写入冲突仍由 batch-write 的 tree lock 和 content hash 检查解决。v1 task store 以单个 VikingBot gateway 进程为部署边界,不承诺多副本共享 task 查询。+VikingBot 使用独立的 compile 并发限制,并对同一 canonical 目标目录串行执行。accepted task 最多排队 60 分钟,取得 target lock 和全局执行 slot 后才开始计算 runtime;服务端最大值和缺省值均为 40 分钟,客户端只能请求更短的时限,超限请求以 `RESOURCE_EXHAUSTED` 拒绝。只有 Agent 阶段的 runtime deadline 和迭代上限允许 salvage;salvage 与 cleanup 各自受独立的短 grace deadline 约束,rendering/writing/refreshing 阶段超时直接失败。该锁只减少同一 Bot 进程内的浪费;跨进程或人工写入冲突仍由 batch-write 的 tree lock 和 content hash 检查解决。v1 task store 以单个 VikingBot gateway 进程为部署边界,不承诺多副本共享 task 查询。VikingBot 启动时把 store 中所有非终态任务统一标记为 `BOT_RESTARTED`,包括处于 committing 的任务;因为 API key 不落盘,重启后不能安全恢复原任务。用户可以重新提交,batch-write 通过最终 content hash 跳过已落盘内容并继续收敛。@@ -567,12 +571,13 @@ v1 先使用集中定义、可测试的 `CompileLimits`,不把常量散落在| target inventory entries / relevance catalog pages | 2,000 / 10 || initial prompt characters | 200,000 || tool URI count / 单次结果 / 任务累计结果 | 32 / 1 MiB / 8 MiB |-| output pages / 最终总大小 | 64 / 4 MiB |-| concurrent Compile tasks / task runtime | 2 / 30 min |-| accepted tasks(全局 / 单 principal)/ queue wait | 16 / 4 / 5 min |+| output pages / files / combined operations / 最终总大小 | 128 / 128 / 256 / 4 MiB |+| concurrent Compile tasks / task runtime maximum and default | 10 / 40 min |+| salvage / cleanup grace | 120 sec / 40 sec |+| accepted tasks(全局 / 单 principal)/ queue wait | 40 / 10 / 60 min || terminal task retention / records | 24 h / 1,000 |-OpenViking batch-write 自己还要设置独立的 request 上限,至少覆盖 Compile 的 64 pages / 4 MiB,但不能信任 Bot 已经做过限制。超限统一返回 `RESOURCE_EXHAUSTED`。+OpenViking batch-write 自己还要设置独立的 request 上限,至少覆盖 Compile 的 256 combined operations / 4 MiB,但不能信任 Bot 已经做过限制。超限统一返回 `RESOURCE_EXHAUSTED`。## 11. 错误处理@@ -643,7 +648,7 @@ bot/vikingbot/compile/- Bot proxy 的创建/GET 查询身份转交、未启用 Bot 的 503 和上游错误;- Skill 复用现有 parser/loader、相对引用、requirements 和路径逃逸检查;`allowed-tools` 可正常解析但不影响 Compile 工具集合;- request registry 固定包含本地核心工具、scope-guarded OpenViking 只读工具和 `submit_wiki_bundle`,不包含 message/cron/spawn/Web/image/MCP/OV write,用户 connection 只进入 OV read adapter;-- Agent structured wrapper 复用原 loop;失败 submit 不停止、plain text 会修复、iteration limit 不额外生成普通回答,普通 chat 行为不回归;+- Agent structured wrapper 复用原 loop;失败 submit 不停止、plain text 会修复、iteration limit 不额外生成普通回答,Resource 目标只 salvage 合格产物,普通 chat 行为不回归;- OpenViking 工具的 URI scope、缺省全库参数和数量/单次/累计输出上限,并确认没有注册第二组 source tools;- 非法 bundle 的 loop 内修复、空 bundle no-op 和最终失败;- 单页面零 link、多页面互链和已有页面更新;diff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.mdindex 28f72f7ec..56848f5ad 100644--- a/docs/en/api/12-content.md+++ b/docs/en/api/12-content.md@@ -352,7 +352,7 @@ Each operation contains:**Notes**-- A request supports at most 128 operations, 8 MiB per file, and 16 MiB total.+- A request supports at most 256 operations, 8 MiB per file, and 16 MiB total.- All targets must be files below `root_uri`, use the same context type, and have unique canonical URIs.- Resource targets may use any safe file extension; Memory targets retain the text extension allowlist and do not accept binary content.- Every non-idempotent precondition is checked under the target tree lock before the first new write. A mismatch returns `409 Conflict`.diff --git a/docs/en/api/24-vikingbot.md b/docs/en/api/24-vikingbot.mdindex 3bbe81007..9b154240b 100644--- a/docs/en/api/24-vikingbot.md+++ b/docs/en/api/24-vikingbot.md@@ -145,6 +145,7 @@ Start an asynchronous, Skill-driven Compile task. VikingBot loads the selected S| `to` | string | Yes | - | Target Resource or Memory directory, or a supported Skill namespace || `skill` | string | Yes | - | Skill directory or its `SKILL.md` URI || `reason` | string | No | Skill-driven default | Additional instructions for this Compile run |+| `runtime_timeout_seconds` | number | No | 2400 | Positive finite runtime limit no greater than the server maximum (2400 seconds by default) |**HTTP API**@@ -175,7 +176,7 @@ ov compile \--wait```-`--wait` polls the status endpoint until the task reaches a terminal state. `--timeout` limits only the local wait and does not cancel the server task.+`--wait` polls the status endpoint until the task reaches a terminal state. `--timeout` limits only the local wait and does not cancel the server task. `--runtime-timeout` sets `runtime_timeout_seconds` for this run and can only shorten the server-owned runtime maximum; an excessive value is rejected with `429 RESOURCE_EXHAUSTED`. Reaching that deadline while the Agent is running, or reaching the configured AgentLoop iteration limit (`bot.agents.max_tool_iterations`, 50 by default), attempts to save eligible partial Resource output within a separate short grace period. The task fails if there is no eligible output to save; non-Resource targets and deadlines in later stages do not use this fallback.The `direct` backend runs Compile `exec` commands with the Bot host's permissions. `bot.sandbox.backends.direct.allow_compile_exec` defaults to `false`, so Compile omits `exec` while ordinary Wiki and artifact generation can still run through file tools. A Skill that declares `requires.bins` or `requires.env` fails with `SKILL_CAPABILITY_UNAVAILABLE` before any command probe runs. Setting the option to `true` is an explicit unsafe opt-in; isolated backends with filesystem and network policies are recommended for CLI-dependent Skills. Admission overflow returns `429 RESOURCE_EXHAUSTED`.@@ -242,8 +243,8 @@ Task lifecycle values are:|--------|----------------|| `accepted` | `queued` || `running` | `loading_skill`, `collecting_context`, `agent`, `rendering` |-| `committing` | `writing`, `refreshing` |-| `completed` | `completed` |+| `committing` | `writing`, `refreshing`, `salvaging` |+| `completed` | `completed`, `salvaged` || `failed` | Stage where the failure occurred; the response contains `error.code` and `error.message` |### feedback()diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.mdindex d1e6dbdf5..3d8eb2076 100644--- a/docs/zh/api/12-content.md+++ b/docs/zh/api/12-content.md@@ -352,7 +352,7 @@ openviking write viking://resources/docs/api.md \**说明**-- 单次请求最多包含 128 个 operation,单文件不超过 8 MiB,总内容不超过 16 MiB。+- 单次请求最多包含 256 个 operation,单文件不超过 8 MiB,总内容不超过 16 MiB。- 所有目标必须是 `root_uri` 下的文件、属于同一 context type,且 canonical URI 不能重复。- Resource 目标允许任意安全文件扩展名;Memory 目标仍使用文本扩展名白名单,且不接受二进制内容。- 系统会在目标 tree lock 内、首次产生新写入之前检查所有非幂等前置条件;不满足时返回 `409 Conflict`。diff --git a/docs/zh/api/24-vikingbot.md b/docs/zh/api/24-vikingbot.mdindex 476249606..d91e1ca85 100644--- a/docs/zh/api/24-vikingbot.md+++ b/docs/zh/api/24-vikingbot.md@@ -142,6 +142,7 @@ data: {"event":"response","data":{"content":"当前知识库包含……","respo| `to` | string | 是 | - | 目标 Resource 或 Memory 目录,或受支持的 Skill namespace || `skill` | string | 是 | - | Skill 目录或其 `SKILL.md` URI || `reason` | string | 否 | Skill 驱动的默认值 | 本次 Compile 的补充指令 |+| `runtime_timeout_seconds` | number | 否 | 2400 | 正数且有限,且不得超过服务端最大运行时限(默认 2400 秒) |**HTTP API**@@ -172,7 +173,7 @@ ov compile \--wait```-`--wait` 会轮询状态接口,直到任务进入终态。`--timeout` 只限制本地等待时间,不会取消服务端任务。+`--wait` 会轮询状态接口,直到任务进入终态。`--timeout` 只限制本地等待时间,不会取消服务端任务;`--runtime-timeout` 用于设置本次任务的 `runtime_timeout_seconds`,只能缩短服务端拥有的最大运行时限,超限请求会以 `429 RESOURCE_EXHAUSTED` 拒绝。在 Agent 执行期间达到该时限,或达到配置的 AgentLoop 迭代上限(`bot.agents.max_tool_iterations`,默认 50)时,会在独立的短 grace period 内尝试保存符合条件的 Resource 阶段性产物;没有可保存产物时任务失败,非 Resource 目标以及后续阶段超时不使用该 fallback。`direct` backend 会以 Bot 宿主机权限执行 Compile 的 `exec` 命令。`bot.sandbox.backends.direct.allow_compile_exec` 默认为 `false`,此时 Compile 不会暴露 `exec`,但普通 Wiki 和产物文件整理仍可通过文件工具运行。声明了 `requires.bins` 或 `requires.env` 的 Skill 会在执行任何命令探测前以 `SKILL_CAPABILITY_UNAVAILABLE` 失败。将该选项设为 `true` 是明确的不安全 opt-in;依赖 CLI 的 Skill 推荐使用具备文件系统和网络策略的隔离 backend。超过 admission 上限时返回 `429 RESOURCE_EXHAUSTED`。@@ -239,8 +240,8 @@ curl http://localhost:1933/bot/v1/compile/cmp_01abc \|--------|------------|| `accepted` | `queued` || `running` | `loading_skill`、`collecting_context`、`agent`、`rendering` |-| `committing` | `writing`、`refreshing` |-| `completed` | `completed` |+| `committing` | `writing`、`refreshing`、`salvaging` |+| `completed` | `completed`、`salvaged` || `failed` | 失败发生时的 Stage;响应包含 `error.code` 和 `error.message` |### feedback()diff --git a/openviking/service/__init__.py b/openviking/service/__init__.pyindex 46090c8fe..d7dbeb019 100644--- a/openviking/service/__init__.py+++ b/openviking/service/__init__.py@@ -7,14 +7,47 @@ Provides business logic decoupled from transport layer,enabling reuse across HTTP Server and CLI."""-from openviking.service.core import OpenVikingService-from openviking.service.debug_service import ComponentStatus, DebugService, SystemStatus-from openviking.service.fs_service import FSService-from openviking.service.pack_service import PackService-from openviking.service.relation_service import RelationService-from openviking.service.resource_service import ResourceService-from openviking.service.search_service import SearchService-from openviking.service.session_service import SessionService+from importlib import import_module+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from openviking.service.core import OpenVikingService+ from openviking.service.debug_service import ComponentStatus, DebugService, SystemStatus+ from openviking.service.fs_service import FSService+ from openviking.service.pack_service import PackService+ from openviking.service.relation_service import RelationService+ from openviking.service.resource_service import ResourceService+ from openviking.service.search_service import SearchService+ from openviking.service.session_service import SessionService++_EXPORTS = {+ "OpenVikingService": ("openviking.service.core", "OpenVikingService"),+ "ComponentStatus": ("openviking.service.debug_service", "ComponentStatus"),+ "DebugService": ("openviking.service.debug_service", "DebugService"),+ "SystemStatus": ("openviking.service.debug_service", "SystemStatus"),+ "FSService": ("openviking.service.fs_service", "FSService"),+ "PackService": ("openviking.service.pack_service", "PackService"),+ "RelationService": ("openviking.service.relation_service", "RelationService"),+ "ResourceService": ("openviking.service.resource_service", "ResourceService"),+ "SearchService": ("openviking.service.search_service", "SearchService"),+ "SessionService": ("openviking.service.session_service", "SessionService"),+}+++def __getattr__(name: str) -> Any:+ try:+ module_name, attr_name = _EXPORTS[name]+ except KeyError as exc:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from exc++ value = getattr(import_module(module_name), attr_name)+ globals()[name] = value+ return value+++def __dir__() -> list[str]:+ return sorted(list(globals().keys()) + list(__all__))+__all__ = ["OpenVikingService",diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 8ee7a9e5e..52c62e5cd 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -314,7 +314,7 @@ class FSService:if context_type != "resource":return Noneparent = VikingURI(uri).parent- return parent.uri if parent else None+ return parent.uri if parent and parent.scope else None@staticmethoddef _memory_overview_parent_uri(uri: str, context_type: str) -> Optional[str]:diff --git a/openviking/session/memory/utils/link_renderer.py b/openviking/session/memory/utils/link_renderer.pyindex eb0250f29..a193fdbd1 100644--- a/openviking/session/memory/utils/link_renderer.py+++ b/openviking/session/memory/utils/link_renderer.py@@ -1,17 +1,30 @@+import posixpathimport re-from typing import Dict, List, Optional+from dataclasses import dataclass+from typing import Callable, Dict, Iterator, List, Optional+from urllib.parse import unquotefrom openviking.core.namespace import uri_parts+@dataclass(frozen=True, slots=True)+class MarkdownLink:+ start: int+ end: int+ text: str+ target: str++class LinkRenderer:"""Renders and strips local markdown links in memory file content based on StoredLink metadata."""- # Target may contain spaces (e.g. `[Frank Ocean](entities/frank ocean.md)`).- # Markdown permits literal spaces in destinations, though they are not portable- # across renderers; `render_links` therefore percent-encodes spaces in generated- # targets so they round-trip cleanly. We accept both forms when matching.- _RELATIVE_LINK_RE = re.compile(r"\[(?P<text>[^\]]+)\]\((?P<target>[^)]+)\)")+ _LINK_START_RE = re.compile(r"\[(?P<text>[^\]]+)\]\(")+ _LINK_TITLE_SUFFIX_RE = re.compile(+ r"""\s+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*\Z""",+ re.DOTALL,+ )+ _BACKSLASH_ESCAPE_RE = re.compile(r"\\([!\"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~])")+ _MAX_LINK_PAREN_DEPTH = 32_MEMORY_FIELDS_RE = re.compile(r"(\n\n<!--\s*MEMORY_FIELDS\s*\n)", re.DOTALL)_CJK_RE = re.compile(r"[㐀-䶿一-鿿豈-]")_ASCII_WORD_CHAR_RE = re.compile(r"[A-Za-z0-9_]")@@ -24,10 +37,96 @@ class LinkRenderer:def _is_ascii_word_char(char: str) -> bool:return bool(char and LinkRenderer._ASCII_WORD_CHAR_RE.fullmatch(char))+ @staticmethod+ def _parse_inline_markdown_link(+ content: str, destination_start: int+ ) -> Optional[tuple[str, int]]:+ """Return the destination and end offset for one inline Markdown link."""+ while destination_start < len(content) and content[destination_start].isspace():+ destination_start += 1++ position = destination_start+ depth = 0+ quote = ""+ angle_end: Optional[int] = None+ in_angle = position < len(content) and content[position] == "<"+ while position < len(content):+ char = content[position]+ if char == "\\" and position + 1 < len(content):+ position += 2+ continue+ if in_angle:+ if char == "\n" or (char == "<" and position != destination_start):+ return None+ if char == ">":+ in_angle = False+ angle_end = position + 1+ position += 1+ continue+ if quote:+ if char == quote:+ quote = ""+ position += 1+ continue+ if (+ depth == 0+ and char in {'"', "'"}+ and position > destination_start+ and content[position - 1].isspace()+ ):+ quote = char+ elif char == "(":+ depth += 1+ if depth > LinkRenderer._MAX_LINK_PAREN_DEPTH:+ return None+ elif char == ")":+ if depth:+ depth -= 1+ else:+ raw_target = content[destination_start:position]+ if angle_end is not None:+ suffix = raw_target[angle_end - destination_start :]+ if suffix.strip() and not LinkRenderer._LINK_TITLE_SUFFIX_RE.fullmatch(+ suffix+ ):+ return None+ target = raw_target[: angle_end - destination_start]+ else:+ stripped = raw_target.strip()+ title = LinkRenderer._LINK_TITLE_SUFFIX_RE.search(stripped)+ target = stripped[: title.start()].rstrip() if title else stripped+ return target, position + 1+ position += 1+ return None++ @staticmethod+ def iter_markdown_links(content: str) -> Iterator[MarkdownLink]:+ """Yield parsed inline Markdown links with their source spans."""+ position = 0+ while opener := LinkRenderer._LINK_START_RE.search(content, position):+ parsed = LinkRenderer._parse_inline_markdown_link(content, opener.end())+ if parsed is None:+ position = opener.start() + 1+ continue+ target, end = parsed+ yield MarkdownLink(opener.start(), end, opener.group("text"), target)+ position = end++ @staticmethod+ def _replace_markdown_links(content: str, replacement: Callable[[MarkdownLink], str]) -> str:+ result: List[str] = []+ position = 0+ for link in LinkRenderer.iter_markdown_links(content):+ result.append(content[position : link.start])+ result.append(replacement(link))+ position = link.end+ result.append(content[position:])+ return "".join(result)+@staticmethoddef protected_markdown_spans(content: str) -> List[tuple[int, int]]:"""Return spans where Compile must never insert a generated WikiLink."""- spans = [(m.start(), m.end()) for m in LinkRenderer._RELATIVE_LINK_RE.finditer(content)]+ spans = [(link.start, link.end) for link in LinkRenderer.iter_markdown_links(content)]spans.extend((m.start(), m.end())for m in re.finditer(r"(?ms)^(?:```|~~~).*?^(?:```|~~~)[ \t]*$", content)@@ -51,11 +150,14 @@ class LinkRenderer:# inside one is already linked, so wrapping it again would produce a broken# nested link like "[[Frank](..) Ocean](..)"; skip those candidates.linked_spans = protected_spans or [- (m.start(), m.end()) for m in LinkRenderer._RELATIVE_LINK_RE.finditer(content)+ (link.start, link.end) for link in LinkRenderer.iter_markdown_links(content)]def _overlaps_protected_span(start: int, end: int) -> bool:- return any(not (end <= span_start or start >= span_end) for span_start, span_end in linked_spans)+ return any(+ not (end <= span_start or start >= span_end)+ for span_start, span_end in linked_spans+ )if LinkRenderer._contains_cjk(match_text):for match in re.finditer(escaped, content):@@ -79,6 +181,52 @@ class LinkRenderer:return start, endreturn None+ @staticmethod+ def normalize_markdown_target(target: str) -> str:+ """Decode and normalize a parsed Markdown link destination."""+ target = unquote(target.strip())+ if target.startswith("<") and target.endswith(">"):+ target = target[1:-1]+ target = LinkRenderer._BACKSLASH_ESCAPE_RE.sub(r"\1", target)+ target = target.split("#", 1)[0]+ return target.rstrip("/") if "://" in target else posixpath.normpath(target)++ @staticmethod+ def can_render_link(+ content: str,+ match_text: str,+ source_uri: str,+ target_uri: str,+ ) -> bool:+ """Return whether rendering can insert or preserve the requested link."""+ protected_spans = LinkRenderer.protected_markdown_spans(content)+ if LinkRenderer._find_match_span(content, match_text, protected_spans) is not None:+ return True++ markdown_links = list(LinkRenderer.iter_markdown_links(content))+ link_spans = {(link.start, link.end) for link in markdown_links}+ non_link_protected = [span for span in protected_spans if span not in link_spans]+ relative_target = LinkRenderer.relative_path(source_uri, target_uri)+ expected_targets = {+ LinkRenderer.normalize_markdown_target(target_uri),+ LinkRenderer.normalize_markdown_target(+ relative_target if relative_target is not None else target_uri+ ),+ }++ for link in markdown_links:+ if link.start > 0 and content[link.start - 1] == "!":+ continue+ if any(+ not (link.end <= start or link.start >= end) for start, end in non_link_protected+ ):+ continue+ if LinkRenderer._find_match_span(link.text, match_text) is None:+ continue+ if LinkRenderer.normalize_markdown_target(link.target) in expected_targets:+ return True+ return False+@staticmethoddef render_links(content: str, source_uri: str, links: List[Dict]) -> str:"""Replace match_text in content with relative markdown links.@@ -130,11 +278,7 @@ class LinkRenderer:# would otherwise be ambiguous). We accept the literal-space form when# matching existing links, but always emit the encoded form when# generating new ones.- encoded_target = (- link_target.replace(" ", "%20")- .replace("(", "%28")- .replace(")", "%29")- )+ encoded_target = link_target.replace(" ", "%20").replace("(", "%28").replace(")", "%29")rendered = f"[{content[start:end]}]({encoded_target})"replacements.append((start, end, rendered))@@ -152,23 +296,25 @@ class LinkRenderer:External links, viking:// links, anchor links, and absolute-path links are preserved."""- def _replace_link(m: re.Match) -> str:- target = m.group("target")+ def _replace_link(link: MarkdownLink) -> str:+ target = link.target+ if target.startswith("<") and target.endswith(">"):+ target = target[1:-1]if target.startswith("#"):- return m.group(0)+ return content[link.start : link.end]if target.startswith("/"):- return m.group(0)+ return content[link.start : link.end]if "://" in target:- return m.group(0)- return m.group("text")+ return content[link.start : link.end]+ return link.text- return LinkRenderer._RELATIVE_LINK_RE.sub(_replace_link, content)+ return LinkRenderer._replace_markdown_links(content, _replace_link)@staticmethoddef strip_all_links(content: str) -> str:"""Remove markdown links regardless of target scheme, keeping only link text."""- return LinkRenderer._RELATIVE_LINK_RE.sub(lambda m: m.group("text"), content)+ return LinkRenderer._replace_markdown_links(content, lambda link: link.text)@staticmethoddef relative_path(source_uri: str, target_uri: str) -> Optional[str]:diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex 5a74a7406..fe129a327 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -40,8 +40,8 @@ from openviking.storage.viking_fs import VikingFSfrom openviking.telemetry import get_current_telemetryfrom openviking.telemetry.request_wait_tracker import get_request_wait_trackerfrom openviking.telemetry.resource_summary import build_queue_status_payload-from openviking.utils.path_safety import validate_safe_viking_uri_pathfrom openviking.utils.embedding_utils import vectorize_file+from openviking.utils.path_safety import validate_safe_viking_uri_pathfrom openviking.utils.tags import normalize_search_tagsfrom openviking_cli.exceptions import (AlreadyExistsError,@@ -71,7 +71,7 @@ _CREATE_ALLOWED_EXTENSIONS = frozenset(".ts",})-_BATCH_MAX_OPERATIONS = 128+_BATCH_MAX_OPERATIONS = 256_BATCH_MAX_FILE_BYTES = 8 * 1024 * 1024_BATCH_MAX_TOTAL_BYTES = 16 * 1024 * 1024_SHA256_PREFIX = "sha256:"diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.pyindex dfc04ceb7..43580cfaf 100644--- a/openviking/storage/queuefs/semantic_processor.py+++ b/openviking/storage/queuefs/semantic_processor.py@@ -292,6 +292,12 @@ class SemanticProcessor(DequeueHandlerBase):assert data is not Nonemsg = SemanticMsg.from_dict(data)+ if VikingURI(msg.uri).parent is None:+ logger.warning("Skipping semantic generation for root URI: %s", msg.uri)+ if msg.telemetry_id and msg.id:+ get_request_wait_tracker().mark_semantic_done(msg.telemetry_id, msg.id)+ self.report_success()+ return Noneif is_semantic_msg_stale(msg):logger.info("Skipping stale semantic message: uri=%s version=%s",diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 9b2142b9b..67e4d9e08 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -68,7 +68,6 @@ GATEWAY_TOKEN_HEADER = "X-Gateway-Token"_SESSION_CONFIG_UNSET = object()-def _image_mime_type(file_name: str = "") -> str:mime_type, _ = mimetypes.guess_type(file_name or "")if mime_type and mime_type.startswith("image/"):@@ -518,6 +517,12 @@ class AsyncHTTPClient:retry_headers[GATEWAY_TOKEN_HEADER] = self._gateway_tokenreturn await self._send_http_request(method, url, retry_headers, request_kwargs)+ def _wait_request_kwargs(self, *, wait: bool, timeout: Optional[float]) -> Dict[str, Any]:+ if not wait or timeout is None:+ return {}+ read_timeout = max(self._timeout, timeout + 30.0)+ return {"timeout": httpx.Timeout(self._timeout, read=read_timeout)}+async def close(self) -> None:if self._http:try:@@ -1207,6 +1212,7 @@ class AsyncHTTPClient:"timeout": timeout,"telemetry": telemetry,},+ **self._wait_request_kwargs(wait=wait, timeout=timeout),)return self._handle_response_data(response).get("result", {})diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex 71be10072..857bc5e44 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -961,6 +961,24 @@ async def test_rm_uses_delete_request_with_timeout_when_provided():)+async def test_batch_write_http_timeout_outlives_server_wait_timeout():+ client = AsyncHTTPClient(url="http://localhost:1933", timeout=180.0)+ client._request = AsyncMock(return_value=object())+ client._handle_response_data = lambda _response: {"result": {}}++ await client.batch_write(+ "viking://resources/wiki",+ [],+ wait=True,+ timeout=300.0,+ )++ request_timeout = client._request.await_args.kwargs["timeout"]+ assert request_timeout.read == 330.0+ assert request_timeout.connect == 180.0++@pytest.mark.asyncioasync def test_link_normalizes_single_and_multiple_target_uris():client = AsyncHTTPClient(url="http://localhost:1933")diff --git a/tests/server/test_content_batch_write.py b/tests/server/test_content_batch_write.pyindex 225023b0c..476628760 100644--- a/tests/server/test_content_batch_write.py+++ b/tests/server/test_content_batch_write.py@@ -11,6 +11,7 @@ from openviking_cli.exceptions import (InvalidArgumentError,NotFoundError,OpenVikingError,+ ResourceExhaustedError,)from openviking_cli.session.user_id import UserIdentifier@@ -81,6 +82,46 @@ def _hash_bytes(value):return "sha256:" + hashlib.sha256(value).hexdigest()+async def test_batch_accepts_256_operations_and_rejects_257(monkeypatch):+ root = "viking://resources/wiki"+ vfs = _VFS(root)+ coordinator = ContentWriteCoordinator(vfs)++ async def refresh(**kwargs):+ del kwargs+ return None++ monkeypatch.setattr(coordinator, "_refresh_batch", refresh)+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)++ def operations(prefix, count):+ return [+ {+ "uri": f"{root}/{prefix}-{index}.txt",+ "content": "x",+ "precondition": {"kind": "create_if_absent"},+ }+ for index in range(count)+ ]++ result = await coordinator.batch_write(+ root_uri=root,+ operations=operations("allowed", 256),+ ctx=ctx,+ wait=False,+ )+ assert len(result["created"]) == 256++ with pytest.raises(ResourceExhaustedError, match="at most 256 operations"):+ await coordinator.batch_write(+ root_uri=root,+ operations=operations("overflow", 257),+ ctx=ctx,+ wait=False,+ )++@pytest.mark.asyncioasync def test_batch_checks_all_preconditions_before_any_write(monkeypatch):root = "viking://resources/wiki"diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.pyindex 39f282d01..941b31d5e 100644--- a/tests/service/test_fs_service.py+++ b/tests/service/test_fs_service.py@@ -279,6 +279,24 @@ async def test_resource_rm_without_wait_only_queues_refresh(request_context):assert result["semantic_status"] == "queued"+async def test_resource_scope_rm_does_not_refresh_global_root(request_context):+ service = FSService(viking_fs=_FakeVikingFS())+ service._enqueue_delete_refresh = AsyncMock()+ service._wait_for_refresh = AsyncMock()++ result = await service.rm(+ "viking://resources",+ ctx=request_context,+ recursive=True,+ wait=True,+ )++ service._enqueue_delete_refresh.assert_not_awaited()+ service._wait_for_refresh.assert_not_awaited()+ assert "semantic_root_uri" not in result++@pytest.mark.asyncioasync def test_resource_rm_deactivates_watch_tasks(request_context):viking_fs = _FakeVikingFS()diff --git a/tests/storage/test_memory_semantic_stall.py b/tests/storage/test_memory_semantic_stall.pyindex fb2000a7e..d58d9882a 100644--- a/tests/storage/test_memory_semantic_stall.py+++ b/tests/storage/test_memory_semantic_stall.py@@ -41,6 +41,17 @@ def _build_data(msg: SemanticMsg) -> dict:return msg.to_dict()+async def test_root_semantic_message_is_acknowledged_without_processing():+ processor = SemanticProcessor()+ success = MagicMock()+ processor.set_callbacks(success, MagicMock(), MagicMock())++ await processor.on_dequeue(_build_data(_make_msg(uri="viking://", context_type="resource")))++ success.assert_called_once_with()++@pytest.mark.asyncioasync def test_memory_empty_dir_still_reports_success():"""When viking_fs.ls returns an empty list, report_success() must be called."""diff --git a/tests/storage/test_queue_manager.py b/tests/storage/test_queue_manager.pyindex 30a65b3a8..ec12526a8 100644--- a/tests/storage/test_queue_manager.py+++ b/tests/storage/test_queue_manager.py@@ -2,9 +2,27 @@# SPDX-License-Identifier: AGPL-3.0"""Focused tests for QueueManager concurrency selection."""+import os+import subprocess+import sys+from openviking.storage.queuefs.queue_manager import QueueManager+def test_queuefs_package_imports_in_a_clean_process(tmp_path) -> None:+ env = os.environ.copy()+ env["OPENVIKING_CONFIG_FILE"] = str(tmp_path / "missing-ov.conf")++ subprocess.run(+ [sys.executable, "-c", "from openviking.storage.queuefs import QueueManager"],+ cwd=tmp_path,+ env=env,+ check=True,+ capture_output=True,+ text=True,+ )++def test_queue_concurrency_uses_separate_configured_values() -> None:manager = QueueManager(agfs=object(),diff --git a/tests/test_link_renderer.py b/tests/test_link_renderer.pyindex b77efbcf0..e6afc54df 100644--- a/tests/test_link_renderer.py+++ b/tests/test_link_renderer.py@@ -63,6 +63,105 @@ class TestRelativePath:assert result == ""+class TestLinkSatisfaction:+ source_uri = "viking://resources/wiki/overview.md"+ target_uri = "viking://resources/wiki/tags.md"++ def test_unprotected_anchor_can_be_linked(self):+ assert LinkRenderer.can_render_link(+ "Read the behavior tags.",+ "behavior tags",+ self.source_uri,+ self.target_uri,+ )++ def test_existing_link_to_target_is_already_satisfied(self):+ assert LinkRenderer.can_render_link(+ "参见 [L2 行为标签库](./tags.md)。",+ "行为标签库",+ self.source_uri,+ self.target_uri,+ )++ def test_existing_link_with_title_is_already_satisfied(self):+ assert LinkRenderer.can_render_link(+ 'See [Tags](./tags.md "details").',+ "Tags",+ self.source_uri,+ self.target_uri,+ )++ def test_existing_link_with_angle_destination_and_title_is_satisfied(self):+ assert LinkRenderer.can_render_link(+ "See [Tags](<./tags.md> 'details').",+ "Tags",+ self.source_uri,+ self.target_uri,+ )++ def test_existing_link_with_balanced_parentheses_is_satisfied(self):+ assert LinkRenderer.can_render_link(+ "See [Version](../meta/foo(1).md).",+ "Version",+ "viking://resources/wiki/guide/overview.md",+ "viking://resources/wiki/meta/foo(1).md",+ )++ def test_existing_link_with_escaped_parentheses_is_satisfied(self):+ assert LinkRenderer.can_render_link(+ r"See [Version](../meta/foo\(1\).md).",+ "Version",+ "viking://resources/wiki/guide/overview.md",+ "viking://resources/wiki/meta/foo(1).md",+ )++ def test_literal_space_destination_with_title_remains_supported(self):+ assert LinkRenderer.can_render_link(+ 'See [Tag Notes](./tag notes.md "details").',+ "Tag Notes",+ self.source_uri,+ "viking://resources/wiki/tag notes.md",+ )++ def test_equivalent_encoded_target_with_fragment_is_satisfied(self):+ assert LinkRenderer.can_render_link(+ "See [ByteDance](../concepts/byte%20dance.md#facts).",+ "ByteDance",+ "viking://resources/wiki/sections/overview.md",+ "viking://resources/wiki/concepts/byte dance.md",+ )++ def test_existing_link_to_other_target_is_not_satisfied(self):+ assert not LinkRenderer.can_render_link(+ "参见 [行为标签库](./other.md)。",+ "行为标签库",+ self.source_uri,+ self.target_uri,+ )++ def test_title_and_parentheses_do_not_hide_wrong_targets(self):+ assert not LinkRenderer.can_render_link(+ 'See [Tags](./other.md "details").',+ "Tags",+ self.source_uri,+ self.target_uri,+ )+ assert not LinkRenderer.can_render_link(+ "See [Version](../meta/foo(2).md).",+ "Version",+ "viking://resources/wiki/guide/overview.md",+ "viking://resources/wiki/meta/foo(1).md",+ )++ def test_link_syntax_in_code_is_not_satisfied(self):+ assert not LinkRenderer.can_render_link(+ "`[行为标签库](./tags.md)`",+ "行为标签库",+ self.source_uri,+ self.target_uri,+ )++class TestRenderLinks:def test_single_link(self):content = "Caroline attended a support group meeting."@@ -329,6 +428,25 @@ class TestRenderLinks:)assert result == content+ def test_skip_match_inside_existing_link_with_parenthesized_target(self):+ content = "See [Version](../meta/foo(1).md)."+ links = [+ {+ "from_uri": "viking://resources/wiki/guide/overview.md",+ "to_uri": "viking://resources/wiki/meta/foo(1).md",+ "weight": 1.0,+ "match_text": "Version",+ }+ ]++ result = LinkRenderer.render_links(+ content,+ "viking://resources/wiki/guide/overview.md",+ links,+ )++ assert result == content+def test_render_link_with_space_in_target_is_percent_encoded(self):# Generated links should escape spaces in their target so the markdown# link is portable across renderers. We always emit `%20`, while still@@ -408,6 +526,21 @@ class TestStripLinks:result = LinkRenderer.strip_links(content)assert result == "See Frank Ocean for details."+ def test_strip_relative_link_with_title(self):+ content = 'See [Tags](./tags.md "details") for details.'+ result = LinkRenderer.strip_links(content)+ assert result == "See Tags for details."++ def test_strip_relative_link_with_parentheses_in_target(self):+ content = "See [Version](../meta/foo(1).md) for details."+ result = LinkRenderer.strip_links(content)+ assert result == "See Version for details."++ def test_keep_angle_bracket_external_link_with_title(self):+ content = 'Visit [docs](<https://example.com/docs> "Documentation").'+ result = LinkRenderer.strip_links(content)+ assert result == content+def test_keep_absolute_link(self):content = "Visit [docs](https://example.com/docs) for more."result = LinkRenderer.strip_links(content)