From 0bd5d1ce06e1662f3b8cad70b5e9234dff8c9251 Mon Sep 17 00:00:00 2001 From: Piers Date: Thu, 21 May 2026 21:58:19 +1000 Subject: [PATCH] =?UTF-8?q?DD-338=20A.1=20=E2=80=94=20syncthing=20scope=3D?= =?UTF-8?q?=20arg=20+=20sort-before-return=20+=20=5Fmeta=20envelope=20on?= =?UTF-8?q?=203=20read=20tools?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Combined Track 1 + Track 2 + Track 3 single-PR (heaviest A.1 spec, only top-5 blade in both scope AND determinism gap). Track 1: scope= arg with env-var folder-ID list indirection (SYNCTHING_{WORK,PERSONAL,FAMILY,HOME,INFRASTRUCTURE}_FOLDERS comma-separated; per-instance _ override). Server-side from blade-process perspective (Syncthing REST has no native folder filter; blade-internal filter IS the over-fetch boundary per DD-333). Track 2: canonical sort on device.deviceID + folder id tie-breaker on replication_report (fixes sort-key collision case). Track 3: structured _meta envelope (canonical JSON-tail wire shape per architect amendment 2026-05-21) with matched_total / returned / filtered_by / redactions / latency_ms; filtered_by alphabetised for hash reproducibility. Touched tools: syncthing_list_devices, syncthing_folder_status, syncthing_replication_report. Other 35 tools unchanged. scope=public raises through the standard error path (folders are not public in Syncthing's model). Unconfigured scope passes through with a honest scope=_unconfigured redaction. Tests: 120 pass (97 baseline + 23 new). Determinism check is N=5 byte-equal (modulo latency_ms) per tool. Co-Authored-By: Claude Opus 4.7 --- pyproject.toml | 2 +- src/syncthing_mcp/formatters.py | 57 +++++++++ src/syncthing_mcp/models.py | 63 +++++++++ src/syncthing_mcp/tools/devices.py | 56 +++++++- src/syncthing_mcp/tools/folders.py | 80 +++++++++++- tests/conftest.py | 22 ++++ tests/test_models.py | 53 ++++++++ tests/test_tools_devices.py | 90 ++++++++++++- tests/test_tools_folders.py | 197 ++++++++++++++++++++++++++++- uv.lock | 2 +- 10 files changed, 605 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c8efaed..3a66b63 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "syncthing-blade-mcp" -version = "0.4.0" +version = "0.5.0" description = "MCP server for Syncthing — token-efficient replication management, multi-instance, safe disk-space reclamation." requires-python = ">=3.11" dependencies = [ diff --git a/src/syncthing_mcp/formatters.py b/src/syncthing_mcp/formatters.py index c930d86..933bef3 100644 --- a/src/syncthing_mcp/formatters.py +++ b/src/syncthing_mcp/formatters.py @@ -32,6 +32,63 @@ def fmt(data: Any, *, concise: bool = True) -> str: return json.dumps(data, indent=2) +# --------------------------------------------------------------------------- +# DD-338 Phase A.1 — Track 3 — _meta envelope (JSON tail block) +# --------------------------------------------------------------------------- +# +# Architect amendment 2026-05-21 — canonical wire shape is JSON tail block, +# not pipe-delimited. Single line appended after \n\n. Assembler regex: +# \n\n_meta: (\{.*\})$ +# Required fields: matched_total, returned, filtered_by, latency_ms. +# Optional: redactions, next_cursor, error_notes. +# filtered_by is sorted alphabetically for hash reproducibility. +# --------------------------------------------------------------------------- + + +def meta_envelope( + *, + matched_total: int, + returned: int, + filtered_by: list[str] | None = None, + redactions: list[str] | None = None, + latency_ms: int, +) -> str: + """Render the canonical JSON-tail _meta envelope line. + + Returns the literal line ``_meta: {"matched_total": ..., ...}`` — caller + is responsible for joining it to the payload with ``\\n\\n``. + """ + fb = sorted(filtered_by) if filtered_by else [] + rd = list(redactions) if redactions else [] + payload = { + "matched_total": matched_total, + "returned": returned, + "filtered_by": fb, + "redactions": rd, + "latency_ms": latency_ms, + } + return "_meta: " + json.dumps(payload, separators=(",", ":")) + + +def append_meta( + payload: str, + *, + matched_total: int, + returned: int, + filtered_by: list[str] | None = None, + redactions: list[str] | None = None, + latency_ms: int, +) -> str: + """Append the _meta envelope tail line to a serialized payload.""" + return payload + "\n\n" + meta_envelope( + matched_total=matched_total, + returned=returned, + filtered_by=filtered_by, + redactions=redactions, + latency_ms=latency_ms, + ) + + def short_id(device_id: str) -> str: """Truncate a Syncthing device ID to its first block.""" return device_id[:SHORT_ID_LEN] if device_id else "" diff --git a/src/syncthing_mcp/models.py b/src/syncthing_mcp/models.py index 13edf0e..45128a3 100644 --- a/src/syncthing_mcp/models.py +++ b/src/syncthing_mcp/models.py @@ -1,8 +1,62 @@ """Pydantic input models for Syncthing MCP tools.""" +from __future__ import annotations + +import logging +import os + from pydantic import BaseModel, ConfigDict, Field +# --------------------------------------------------------------------------- +# DD-278 scope-tag vocabulary (Phase A.1 — Track 1) +# --------------------------------------------------------------------------- + +_VALID_SCOPES = frozenset({"work", "personal", "family", "home", "infrastructure"}) + +_log = logging.getLogger(__name__) + + +def _resolve_scope_folders( + scope: str | None, + instance: str | None, +) -> tuple[set[str] | None, list[str]]: + """Resolve a DD-278 scope value to a Syncthing folder-ID set. + + Returns ``(folder_id_set, redactions)``. ``folder_id_set is None`` means + no scope filter applies (caller iterates the full set). An empty set + means filter matches no folders (caller returns empty result). The + ``redactions`` list documents degradations for the ``_meta`` envelope. + + Env-var lookup order (per-instance variant takes precedence): + + 1. ``SYNCTHING__FOLDERS_`` (when ``instance`` is set) + 2. ``SYNCTHING__FOLDERS`` + + ``scope=public`` raises ``ValueError`` (folders cannot be public in + Syncthing's model). ``scope=None`` returns ``(None, [])`` — back-compat. + """ + if scope is None: + return None, [] + if scope == "public": + raise ValueError("scope=public is not applicable to Syncthing folders") + if scope not in _VALID_SCOPES: + _log.warning("scope=%r not in DD-278 vocabulary; treating as unconfigured", scope) + return None, [f"scope={scope}_unconfigured"] + + scope_upper = scope.upper() + raw: str | None = None + if instance: + raw = os.environ.get(f"SYNCTHING_{scope_upper}_FOLDERS_{instance.upper()}") + if raw is None: + raw = os.environ.get(f"SYNCTHING_{scope_upper}_FOLDERS") + if raw is None: + return None, [f"scope={scope}_unconfigured"] + + folder_ids = {fid.strip() for fid in raw.split(",") if fid.strip()} + return folder_ids, [] + + # --------------------------------------------------------------------------- # Read-oriented base models (include concise toggle for token efficiency) # --------------------------------------------------------------------------- @@ -19,6 +73,15 @@ class ReadParams(BaseModel): True, description="Compact output (default). Set false for full details.", ) + scope: str | None = Field( + None, + description=( + "DD-278 scope filter — work|personal|family|home|infrastructure. " + "Resolved to a Syncthing folder-ID set via env var " + "SYNCTHING__FOLDERS (comma-separated) with per-instance " + "override SYNCTHING__FOLDERS_. Omit for no filter." + ), + ) class FolderReadParams(ReadParams): diff --git a/src/syncthing_mcp/tools/devices.py b/src/syncthing_mcp/tools/devices.py index 9518566..772b822 100644 --- a/src/syncthing_mcp/tools/devices.py +++ b/src/syncthing_mcp/tools/devices.py @@ -1,9 +1,17 @@ """Device listing, completion, connection, and stats tools.""" +import time from typing import Any -from syncthing_mcp.formatters import fmt, format_bytes, format_connection, format_device, truncate -from syncthing_mcp.models import DeviceReadParams, ReadParams +from syncthing_mcp.formatters import ( + append_meta, + fmt, + format_bytes, + format_connection, + format_device, + truncate, +) +from syncthing_mcp.models import DeviceReadParams, ReadParams, _resolve_scope_folders from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.server import mcp @@ -19,13 +27,42 @@ from syncthing_mcp.server import mcp }, ) async def syncthing_list_devices(params: ReadParams) -> str: - """All configured devices with connection status and last seen time.""" + """All configured devices with connection status and last seen time. + + Accepts DD-278 ``scope=`` filter. Device set is filtered to devices that + share at least one folder with the scoped folder set (devices have no + intrinsic scope tag in Syncthing's model). + """ + start = time.perf_counter() try: + scope_set, redactions = _resolve_scope_folders(params.scope, params.instance) client = get_instance(params.instance) config = await client._get("/rest/config") connections = await client._get("/rest/system/connections") stats = await client._get("/rest/stats/device") conn_data = connections.get("connections", {}) + + all_devices = config.get("devices", []) + matched_total = len(all_devices) + filtered_by: list[str] = [] + + if scope_set is not None: + # Devices in any folder whose id ∈ scope_set + scoped_device_ids: set[str] = set() + for f in config.get("folders", []): + if f.get("id") in scope_set: + for d in f.get("devices", []): + did = d.get("deviceID") + if did: + scoped_device_ids.add(did) + devices = [d for d in all_devices if d.get("deviceID") in scoped_device_ids] + filtered_by.append(f"scope={params.scope}") + else: + devices = list(all_devices) + + # Track 2 — canonical sort by deviceID ascending (stable key). + devices.sort(key=lambda d: d.get("deviceID", "")) + result = [ format_device( dev, @@ -33,9 +70,18 @@ async def syncthing_list_devices(params: ReadParams) -> str: stats.get(dev["deviceID"]), concise=params.concise, ) - for dev in config.get("devices", []) + for dev in devices ] - return fmt(result, concise=params.concise) + payload = fmt(result, concise=params.concise) + latency_ms = int((time.perf_counter() - start) * 1000) + return append_meta( + payload, + matched_total=matched_total, + returned=len(result), + filtered_by=filtered_by, + redactions=redactions, + latency_ms=latency_ms, + ) except Exception as e: return handle_error_global(e) diff --git a/src/syncthing_mcp/tools/folders.py b/src/syncthing_mcp/tools/folders.py index 9db4c15..eb33259 100644 --- a/src/syncthing_mcp/tools/folders.py +++ b/src/syncthing_mcp/tools/folders.py @@ -1,8 +1,10 @@ """Folder status, completion, replication, operations, and file-level query tools.""" +import time from typing import Any from syncthing_mcp.formatters import ( + append_meta, fmt, format_bytes, format_completion, @@ -18,6 +20,7 @@ from syncthing_mcp.models import ( FolderWriteParams, ReadParams, RemoteNeedInput, + _resolve_scope_folders, ) from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.server import mcp @@ -40,8 +43,37 @@ from syncthing_mcp.server import mcp ) async def syncthing_folder_status(params: FolderReadParams) -> str: """Detailed status for a folder — file counts, bytes, sync state. - Note: expensive call on the Syncthing side. Use sparingly.""" + Note: expensive call on the Syncthing side. Use sparingly. + + Accepts DD-278 ``scope=`` filter as a membership precondition. When + ``scope`` is set and configured, ``folder_id`` must be in the scoped + folder set; otherwise the call refuses with a single-line error and + ``_meta.redactions=["folder_outside_scope"]``. + """ + start = time.perf_counter() try: + scope_set, redactions = _resolve_scope_folders(params.scope, params.instance) + filtered_by: list[str] = [] + if params.scope is not None: + filtered_by.append(f"scope={params.scope}") + + if scope_set is not None and params.folder_id not in scope_set: + error_payload = fmt( + {"error": f"folder_id '{params.folder_id}' not in scope={params.scope} folder set"}, + concise=params.concise, + ) + latency_ms = int((time.perf_counter() - start) * 1000) + return append_meta( + error_payload, + matched_total=0, + returned=0, + filtered_by=filtered_by, + redactions=[*redactions, "folder_outside_scope"], + latency_ms=latency_ms, + ) + + filtered_by.append(f"folder={params.folder_id}") + client = get_instance(params.instance) status = await client._get("/rest/db/status", params={"folder": params.folder_id}) stats = await client._get("/rest/stats/folder") @@ -54,7 +86,16 @@ async def syncthing_folder_status(params: FolderReadParams) -> str: if not params.concise: data["lastScan"] = folder_stats.get("lastScan", "") data["lastFile"] = folder_stats.get("lastFile", {}) - return fmt(data, concise=params.concise) + payload = fmt(data, concise=params.concise) + latency_ms = int((time.perf_counter() - start) * 1000) + return append_meta( + payload, + matched_total=1, + returned=1, + filtered_by=filtered_by, + redactions=redactions, + latency_ms=latency_ms, + ) except Exception as e: return handle_error_global(e) @@ -145,8 +186,19 @@ async def syncthing_folder_completion(params: FolderReadParams) -> str: ) async def syncthing_replication_report(params: ReadParams) -> str: """Replication analysis for ALL folders. Shows safe-to-remove flag and - reclaimable space. Primary tool for disk-space cleanup decisions.""" + reclaimable space. Primary tool for disk-space cleanup decisions. + + Accepts DD-278 ``scope=`` filter. Folder set is filtered to ids that + appear in the scoped folder set; unconfigured scope passes through with + a redaction. + """ + start = time.perf_counter() try: + scope_set, redactions = _resolve_scope_folders(params.scope, params.instance) + filtered_by: list[str] = [] + if params.scope is not None: + filtered_by.append(f"scope={params.scope}") + client = get_instance(params.instance) config = await client._get("/rest/config") connections = await client._get("/rest/system/connections") @@ -158,7 +210,13 @@ async def syncthing_replication_report(params: ReadParams) -> str: for d in config.get("devices", []) } - folders = config.get("folders", []) + all_folders = config.get("folders", []) + matched_total = len(all_folders) + if scope_set is not None: + folders = [f for f in all_folders if f.get("id") in scope_set] + else: + folders = list(all_folders) + report = [] total_reclaimable = 0 @@ -204,12 +262,15 @@ async def syncthing_replication_report(params: ReadParams) -> str: total_reclaimable += fstatus.get("localBytes", 0) report.append(entry) + # Track 2 — preserve safe-first + bytes-desc ordering; add id tiebreaker + # so two folders with identical (safe, localBytes) sort deterministically. report.sort(key=lambda x: ( -int(x.get("safe", x.get("safeToRemove", False)) or False), -x.get("localBytes", 0) if "localBytes" in x else 0, + x.get("id", ""), )) - return fmt({ + payload = fmt({ "instance": client.name, "summary": { "total": len(report), @@ -218,6 +279,15 @@ async def syncthing_replication_report(params: ReadParams) -> str: }, "folders": report, }, concise=params.concise) + latency_ms = int((time.perf_counter() - start) * 1000) + return append_meta( + payload, + matched_total=matched_total, + returned=len(report), + filtered_by=filtered_by, + redactions=redactions, + latency_ms=latency_ms, + ) except Exception as e: return handle_error_global(e) diff --git a/tests/conftest.py b/tests/conftest.py index b32651b..8651665 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ import json import os +import re from unittest.mock import patch import pytest @@ -11,6 +12,27 @@ from httpx import Response from syncthing_mcp.client import SyncthingClient +# --------------------------------------------------------------------------- +# DD-338 _meta envelope test helper (Phase A.1 — Track 3) +# --------------------------------------------------------------------------- + +_META_REGEX = re.compile(r"\n\n_meta: (\{.*\})$", re.DOTALL) + + +def split_meta(text: str) -> tuple[str, dict]: + """Split a tool's return string into (payload, _meta dict). + + Matches the assembler regex documented in the DD-338 spec amendment: + \\n\\n_meta: (\\{.*\\})$ + """ + m = _META_REGEX.search(text) + if not m: + raise AssertionError(f"_meta envelope not found in:\n{text!r}") + payload = text[: m.start()] + meta = json.loads(m.group(1)) + return payload, meta + + # --------------------------------------------------------------------------- # Common Syncthing API response fixtures # --------------------------------------------------------------------------- diff --git a/tests/test_models.py b/tests/test_models.py index a939b0e..8b6ab8b 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -12,6 +12,7 @@ from syncthing_mcp.models import ( FolderNeedInput, PauseFolderInput, SetIgnoresInput, + _resolve_scope_folders, ) @@ -109,3 +110,55 @@ class TestFolderNeedInput: def test_per_page_max(self): with pytest.raises(ValidationError): FolderNeedInput(folder_id="f1", per_page=501) + + +# --------------------------------------------------------------------------- +# DD-338 Phase A.1 — Track 1 — _resolve_scope_folders helper +# --------------------------------------------------------------------------- + + +class TestResolveScopeFolders: + def test_none_scope_returns_none(self): + s, r = _resolve_scope_folders(None, None) + assert s is None + assert r == [] + + def test_public_raises(self): + with pytest.raises(ValueError, match="public"): + _resolve_scope_folders("public", None) + + def test_unknown_scope_treated_as_unconfigured(self): + s, r = _resolve_scope_folders("bogus", None) + assert s is None + assert r == ["scope=bogus_unconfigured"] + + def test_configured_env_var(self, monkeypatch): + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1, fld2,fld3") + s, r = _resolve_scope_folders("work", None) + assert s == {"fld1", "fld2", "fld3"} + assert r == [] + + def test_empty_env_var_matches_nothing(self, monkeypatch): + monkeypatch.setenv("SYNCTHING_PERSONAL_FOLDERS", "") + s, r = _resolve_scope_folders("personal", None) + # Empty env still counts as configured but yields empty set + assert s == set() + assert r == [] + + def test_unconfigured_in_vocab_redacts(self, monkeypatch): + monkeypatch.delenv("SYNCTHING_FAMILY_FOLDERS", raising=False) + s, r = _resolve_scope_folders("family", None) + assert s is None + assert r == ["scope=family_unconfigured"] + + def test_per_instance_env_takes_precedence(self, monkeypatch): + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld-default") + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS_VIKING", "fld-viking1,fld-viking2") + s, _ = _resolve_scope_folders("work", "viking") + assert s == {"fld-viking1", "fld-viking2"} + + def test_per_instance_falls_back_to_base(self, monkeypatch): + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld-default") + monkeypatch.delenv("SYNCTHING_WORK_FOLDERS_VOYAGER", raising=False) + s, _ = _resolve_scope_folders("work", "voyager") + assert s == {"fld-default"} diff --git a/tests/test_tools_devices.py b/tests/test_tools_devices.py index e184695..4d77df9 100644 --- a/tests/test_tools_devices.py +++ b/tests/test_tools_devices.py @@ -4,13 +4,19 @@ import json import pytest -from syncthing_mcp.models import DeviceInput, EmptyInput +from syncthing_mcp.models import DeviceInput, EmptyInput, ReadParams from syncthing_mcp.registry import reload_instances from tests.conftest import ( BASE_URL, DEVICE_ID_LOCAL, DEVICE_ID_REMOTE, + DEVICE_ID_REMOTE2, + FOLDER_ID, make_completion, + make_config, + make_connections, + make_stats_device, + split_meta, ) @@ -25,12 +31,92 @@ class TestListDevices: async def test_returns_devices(self, mock_api): from syncthing_mcp.tools.devices import syncthing_list_devices - result = json.loads(await syncthing_list_devices(EmptyInput())) + payload, _meta = split_meta(await syncthing_list_devices(EmptyInput())) + result = json.loads(payload) assert len(result) == 2 names = {d["name"] for d in result} assert "local-dev" in names assert "remote-dev" in names + # DD-338 Phase A.1 — Track 3 — _meta envelope baseline + async def test_meta_envelope_no_scope_baseline(self, mock_api): + from syncthing_mcp.tools.devices import syncthing_list_devices + + _payload, meta = split_meta(await syncthing_list_devices(EmptyInput())) + assert meta["matched_total"] == 2 + assert meta["returned"] == 2 + assert meta["filtered_by"] == [] + assert meta["redactions"] == [] + assert isinstance(meta["latency_ms"], int) + + # DD-338 Phase A.1 — Track 1 — scope=work filters by folder membership + async def test_scope_work_filters_by_folder_membership(self, mock_api, monkeypatch): + from syncthing_mcp.tools.devices import syncthing_list_devices + + # Devices A/B/C in folder fld1; A in fld2; only B in fld3 + cfg = { + "folders": [ + {"id": "fld1", "label": "f1", "devices": [ + {"deviceID": DEVICE_ID_LOCAL}, + {"deviceID": DEVICE_ID_REMOTE}, + ]}, + {"id": "fld2", "label": "f2", "devices": [ + {"deviceID": DEVICE_ID_REMOTE2}, + ]}, + ], + "devices": [ + {"deviceID": DEVICE_ID_LOCAL, "name": "alpha"}, + {"deviceID": DEVICE_ID_REMOTE, "name": "beta"}, + {"deviceID": DEVICE_ID_REMOTE2, "name": "gamma"}, + ], + } + mock_api.get("/rest/config").respond(json=cfg) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1") + + payload, meta = split_meta(await syncthing_list_devices(ReadParams(scope="work"))) + result = json.loads(payload) + # Devices in fld1 = LOCAL + REMOTE + names = {d["name"] for d in result} + assert names == {"alpha", "beta"} + assert meta["matched_total"] == 3 + assert meta["returned"] == 2 + assert meta["filtered_by"] == ["scope=work"] + assert meta["redactions"] == [] + + # DD-338 Phase A.1 — Track 1 — unconfigured scope passes through w/ redaction + async def test_scope_work_unconfigured_redacts(self, mock_api, monkeypatch): + from syncthing_mcp.tools.devices import syncthing_list_devices + + monkeypatch.delenv("SYNCTHING_WORK_FOLDERS", raising=False) + payload, meta = split_meta(await syncthing_list_devices(ReadParams(scope="work"))) + result = json.loads(payload) + assert len(result) == 2 # unfiltered fallthrough + assert meta["redactions"] == ["scope=work_unconfigured"] + + # DD-338 Phase A.1 — Track 1 — scope=public raises through error path + async def test_scope_public_raises(self, mock_api): + from syncthing_mcp.tools.devices import syncthing_list_devices + + # ValueError surfaces via handle_error_global as a plain string + out = await syncthing_list_devices(ReadParams(scope="public")) + assert out.startswith("Error:") + assert "public" in out + + # DD-338 Phase A.1 — Track 2 — sort-before-return deterministic across N=5 + async def test_deterministic_n5(self, mock_api): + from syncthing_mcp.tools.devices import syncthing_list_devices + + # Strip the latency_ms from _meta because it varies per call. + results = [] + for _ in range(5): + out = await syncthing_list_devices(EmptyInput()) + payload, meta = split_meta(out) + meta.pop("latency_ms") + results.append((payload, json.dumps(meta, sort_keys=True))) + first = results[0] + for r in results[1:]: + assert r == first, "byte-equality (modulo latency_ms) broken" + class TestDeviceCompletion: async def test_fully_synced(self, mock_api): diff --git a/tests/test_tools_folders.py b/tests/test_tools_folders.py index 8702619..07a3fc6 100644 --- a/tests/test_tools_folders.py +++ b/tests/test_tools_folders.py @@ -11,7 +11,9 @@ from syncthing_mcp.models import ( FileInfoInput, FolderInput, FolderNeedInput, + FolderReadParams, PauseFolderInput, + ReadParams, ) from syncthing_mcp.registry import reload_instances from tests.conftest import ( @@ -25,6 +27,7 @@ from tests.conftest import ( make_db_status, make_stats_folder, make_system_status, + split_meta, ) @@ -40,11 +43,91 @@ class TestFolderStatus: from syncthing_mcp.tools.folders import syncthing_folder_status mock_api.get("/rest/db/status").respond(json=make_db_status()) - result = json.loads(await syncthing_folder_status(FolderInput(folder_id=FOLDER_ID))) + payload, _meta = split_meta( + await syncthing_folder_status(FolderInput(folder_id=FOLDER_ID)) + ) + result = json.loads(payload) assert result["folder"] == FOLDER_ID assert result["state"] == "idle" assert result["globalSize"] is not None + # DD-338 Phase A.1 — Track 3 — _meta baseline + async def test_meta_envelope_no_scope_baseline(self, mock_api): + from syncthing_mcp.tools.folders import syncthing_folder_status + + mock_api.get("/rest/db/status").respond(json=make_db_status()) + _payload, meta = split_meta( + await syncthing_folder_status(FolderInput(folder_id=FOLDER_ID)) + ) + assert meta["matched_total"] == 1 + assert meta["returned"] == 1 + assert meta["filtered_by"] == [f"folder={FOLDER_ID}"] + assert meta["redactions"] == [] + + # DD-338 Phase A.1 — Track 1 — scope membership match + async def test_scope_membership_match(self, mock_api, monkeypatch): + from syncthing_mcp.tools.folders import syncthing_folder_status + + mock_api.get("/rest/db/status").respond(json=make_db_status()) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", FOLDER_ID) + payload, meta = split_meta( + await syncthing_folder_status( + FolderReadParams(folder_id=FOLDER_ID, scope="work") + ) + ) + result = json.loads(payload) + assert result["folder"] == FOLDER_ID + # filtered_by is sorted alphabetically by meta_envelope + assert sorted(meta["filtered_by"]) == [f"folder={FOLDER_ID}", "scope=work"] + assert meta["matched_total"] == 1 + assert meta["returned"] == 1 + + # DD-338 Phase A.1 — Track 1 — scope membership mismatch refuses + async def test_scope_membership_mismatch_refuses(self, mock_api, monkeypatch): + from syncthing_mcp.tools.folders import syncthing_folder_status + + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "some-other-folder") + payload, meta = split_meta( + await syncthing_folder_status( + FolderReadParams(folder_id=FOLDER_ID, scope="work") + ) + ) + result = json.loads(payload) + assert "error" in result + assert "folder_outside_scope" in meta["redactions"] + assert meta["matched_total"] == 0 + assert meta["returned"] == 0 + + # DD-338 Phase A.1 — Track 1 — unconfigured scope passes through + async def test_scope_unconfigured_passthrough(self, mock_api, monkeypatch): + from syncthing_mcp.tools.folders import syncthing_folder_status + + mock_api.get("/rest/db/status").respond(json=make_db_status()) + monkeypatch.delenv("SYNCTHING_WORK_FOLDERS", raising=False) + payload, meta = split_meta( + await syncthing_folder_status( + FolderReadParams(folder_id=FOLDER_ID, scope="work") + ) + ) + result = json.loads(payload) + assert result["folder"] == FOLDER_ID # pass-through, not refused + assert "scope=work_unconfigured" in meta["redactions"] + + # DD-338 Phase A.1 — Track 2 — deterministic N=5 + async def test_deterministic_n5(self, mock_api): + from syncthing_mcp.tools.folders import syncthing_folder_status + + mock_api.get("/rest/db/status").respond(json=make_db_status()) + results = [] + for _ in range(5): + out = await syncthing_folder_status(FolderInput(folder_id=FOLDER_ID)) + payload, meta = split_meta(out) + meta.pop("latency_ms") + results.append((payload, json.dumps(meta, sort_keys=True))) + first = results[0] + for r in results[1:]: + assert r == first + class TestFolderCompletion: async def test_fully_replicated(self, mock_api): @@ -75,7 +158,8 @@ class TestReplicationReport: mock_api.get("/rest/db/status").respond(json=make_db_status()) mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) - result = json.loads(await syncthing_replication_report(EmptyInput())) + payload, _meta = split_meta(await syncthing_replication_report(EmptyInput())) + result = json.loads(payload) assert result["summary"]["safe"] == 1 assert result["folders"][0]["safe"] is True @@ -84,9 +168,116 @@ class TestReplicationReport: mock_api.get("/rest/db/status").respond(json=make_db_status()) mock_api.get("/rest/db/completion").respond(json=make_completion(50.0)) - result = json.loads(await syncthing_replication_report(EmptyInput())) + payload, _meta = split_meta(await syncthing_replication_report(EmptyInput())) + result = json.loads(payload) assert result["summary"]["safe"] == 0 + # DD-338 Phase A.1 — Track 3 — _meta baseline + async def test_meta_envelope_no_scope_baseline(self, mock_api): + from syncthing_mcp.tools.folders import syncthing_replication_report + + mock_api.get("/rest/db/status").respond(json=make_db_status()) + mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) + _payload, meta = split_meta(await syncthing_replication_report(EmptyInput())) + assert meta["matched_total"] == 1 + assert meta["returned"] == 1 + assert meta["filtered_by"] == [] + assert meta["redactions"] == [] + + # DD-338 Phase A.1 — Track 1 — scope filters folder set + async def test_scope_work_filters_folder_set(self, mock_api, monkeypatch): + from syncthing_mcp.tools.folders import syncthing_replication_report + + # 5 folders; SYNCTHING_WORK_FOLDERS=fld1,fld3 → expect 2 returned. + cfg = { + "folders": [ + {"id": f"fld{i}", "label": f"f{i}", "devices": [ + {"deviceID": DEVICE_ID_LOCAL}, + {"deviceID": DEVICE_ID_REMOTE}, + ]} + for i in range(1, 6) + ], + "devices": [ + {"deviceID": DEVICE_ID_LOCAL, "name": "local"}, + {"deviceID": DEVICE_ID_REMOTE, "name": "remote"}, + ], + } + mock_api.get("/rest/config").respond(json=cfg) + mock_api.get("/rest/db/status").respond(json=make_db_status()) + mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1,fld3") + + payload, meta = split_meta( + await syncthing_replication_report(ReadParams(scope="work")) + ) + result = json.loads(payload) + ids = sorted(f["id"] for f in result["folders"]) + assert ids == ["fld1", "fld3"] + assert meta["matched_total"] == 5 + assert meta["returned"] == 2 + assert meta["filtered_by"] == ["scope=work"] + + # DD-338 Phase A.1 — Track 1 — unconfigured scope redacts but passes through + async def test_scope_unconfigured_redacts(self, mock_api, monkeypatch): + from syncthing_mcp.tools.folders import syncthing_replication_report + + mock_api.get("/rest/db/status").respond(json=make_db_status()) + mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) + monkeypatch.delenv("SYNCTHING_WORK_FOLDERS", raising=False) + payload, meta = split_meta( + await syncthing_replication_report(ReadParams(scope="work")) + ) + result = json.loads(payload) + assert len(result["folders"]) == 1 # unfiltered fallthrough + assert meta["redactions"] == ["scope=work_unconfigured"] + + # DD-338 Phase A.1 — Track 1 — scope=public raises through error path + async def test_scope_public_raises(self, mock_api): + from syncthing_mcp.tools.folders import syncthing_replication_report + + out = await syncthing_replication_report(ReadParams(scope="public")) + assert out.startswith("Error:") + assert "public" in out + + # DD-338 Phase A.1 — Track 2 — deterministic N=5 with tie-breaker fixture + async def test_deterministic_n5_with_tiebreaker(self, mock_api): + from syncthing_mcp.tools.folders import syncthing_replication_report + + # Two folders with identical localBytes → id tie-breaker must apply. + cfg = { + "folders": [ + {"id": "z-folder", "label": "z", "devices": [ + {"deviceID": DEVICE_ID_LOCAL}, + {"deviceID": DEVICE_ID_REMOTE}, + ]}, + {"id": "a-folder", "label": "a", "devices": [ + {"deviceID": DEVICE_ID_LOCAL}, + {"deviceID": DEVICE_ID_REMOTE}, + ]}, + ], + "devices": [ + {"deviceID": DEVICE_ID_LOCAL, "name": "local"}, + {"deviceID": DEVICE_ID_REMOTE, "name": "remote"}, + ], + } + mock_api.get("/rest/config").respond(json=cfg) + mock_api.get("/rest/db/status").respond(json=make_db_status()) + mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) + + results = [] + for _ in range(5): + out = await syncthing_replication_report(EmptyInput()) + payload, meta = split_meta(out) + meta.pop("latency_ms") + results.append((payload, json.dumps(meta, sort_keys=True))) + first = results[0] + for r in results[1:]: + assert r == first + # Tie-breaker by id ascending; a-folder before z-folder + result = json.loads(first[0]) + ids = [f["id"] for f in result["folders"]] + assert ids == ["a-folder", "z-folder"] + class TestPauseFolder: async def test_pause(self, mock_api): diff --git a/uv.lock b/uv.lock index 1d5d5c0..31aca7e 100644 --- a/uv.lock +++ b/uv.lock @@ -770,7 +770,7 @@ wheels = [ [[package]] name = "syncthing-blade-mcp" -version = "0.3.0" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "httpx" },