diff --git a/src/syncthing_mcp/tools/instances.py b/src/syncthing_mcp/tools/instances.py index ff6fb23..f568f1c 100644 --- a/src/syncthing_mcp/tools/instances.py +++ b/src/syncthing_mcp/tools/instances.py @@ -4,7 +4,7 @@ import time from typing import Any from syncthing_mcp.formatters import append_meta, fmt, format_folder -from syncthing_mcp.models import ReadParams +from syncthing_mcp.models import ReadParams, _resolve_scope_folders from syncthing_mcp.registry import ( get_all_instances, get_instance, @@ -66,15 +66,28 @@ async def syncthing_list_instances(params: ReadParams) -> str: async def syncthing_list_folders(params: ReadParams) -> str: """All configured folders with labels, types, and device counts. + DD-338 A.2 — accepts ``scope=work|personal|family|home|infrastructure`` + mapped to ``SYNCTHING__FOLDERS[_]`` env var; filters + ``config.folders`` to the resolved folder-ID set via the A.1 + ``_resolve_scope_folders`` substrate. ``scope=public`` raises. + DD-338 A.2.dom.c — emits per-record ``domain_hints`` in the ``_meta`` envelope when the user has configured matching patterns via the BladeConfigStore. """ 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") - folders = config.get("folders", []) + all_folders = config.get("folders", []) + matched_total = len(all_folders) + filtered_by: list[str] = [] + if scope_set is not None: + folders = [f for f in all_folders if f.get("id") in scope_set] + filtered_by.append(f"scope={params.scope}") + else: + folders = all_folders if params.concise: result = [format_folder(f, concise=True) for f in folders] else: @@ -104,10 +117,10 @@ async def syncthing_list_folders(params: ReadParams) -> str: latency_ms = int((time.perf_counter() - start) * 1000) return append_meta( payload, - matched_total=len(folders), + matched_total=matched_total, returned=len(result), - filtered_by=[], - redactions=[], + filtered_by=filtered_by, + redactions=redactions, latency_ms=latency_ms, domain_hints=domain_hints, ) diff --git a/src/syncthing_mcp/tools/system.py b/src/syncthing_mcp/tools/system.py index d8dd2d4..2939872 100644 --- a/src/syncthing_mcp/tools/system.py +++ b/src/syncthing_mcp/tools/system.py @@ -1,11 +1,12 @@ """System status, health, errors, log, restart, and upgrade tools.""" +import time from typing import Any import httpx -from syncthing_mcp.formatters import fmt, format_bytes, truncate -from syncthing_mcp.models import ReadParams, WriteParams +from syncthing_mcp.formatters import append_meta, fmt, format_bytes, truncate +from syncthing_mcp.models import ReadParams, WriteParams, _resolve_scope_folders from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.server import mcp @@ -138,10 +139,21 @@ async def syncthing_system_log(params: ReadParams) -> str: }, ) async def syncthing_recent_changes(params: ReadParams) -> str: - """Recent file change events (local and remote) across all folders.""" + """Recent file change events (local and remote) across all folders. + + DD-338 A.2 — accepts ``scope=work|personal|family|home|infrastructure`` + mapped to ``SYNCTHING__FOLDERS[_]`` env var; filters the + event stream to events whose ``data.folderID`` is in the scoped folder + set via the A.1 ``_resolve_scope_folders`` substrate. ``scope=public`` + raises. Events with missing/empty ``folderID`` are filtered out when + a scope filter is active (system-level events do not partition by + folder scope). + """ + start = time.perf_counter() try: + scope_set, redactions = _resolve_scope_folders(params.scope, params.instance) client = get_instance(params.instance) - events = await client._get( + events_raw = await client._get( "/rest/events", params={ "events": "LocalChangeDetected,RemoteChangeDetected", @@ -149,8 +161,16 @@ async def syncthing_recent_changes(params: ReadParams) -> str: "timeout": "0", }, ) - if not isinstance(events, list): - events = [] + if not isinstance(events_raw, list): + events_raw = [] + matched_total = len(events_raw) + filtered_by: list[str] = [] + if scope_set is not None: + events_raw = [ + e for e in events_raw + if (e.get("data", {}).get("folderID") or "") in scope_set + ] + filtered_by.append(f"scope={params.scope}") if params.concise: events = [ { @@ -159,14 +179,25 @@ async def syncthing_recent_changes(params: ReadParams) -> str: "path": e.get("data", {}).get("path", ""), "action": e.get("data", {}).get("action", ""), } - for e in events + for e in events_raw ] + else: + events = events_raw data: dict[str, Any] = { "instance": client.name, "count": len(events), "events": events, } - return truncate(fmt(data, concise=params.concise)) + payload = truncate(fmt(data, concise=params.concise)) + latency_ms = int((time.perf_counter() - start) * 1000) + return append_meta( + payload, + matched_total=matched_total, + returned=len(events), + filtered_by=filtered_by, + redactions=redactions, + latency_ms=latency_ms, + ) except Exception as e: return handle_error_global(e) diff --git a/tests/test_a2_catB.py b/tests/test_a2_catB.py new file mode 100644 index 0000000..032c7ec --- /dev/null +++ b/tests/test_a2_catB.py @@ -0,0 +1,341 @@ +"""Tests for DD-338 Phase A.2 cat-B scope= promotions. + +Covers: +- ``syncthing_list_folders`` — scope filter over ``config.folders`` via the + A.1 ``_resolve_scope_folders`` substrate. +- ``syncthing_recent_changes`` — scope filter over the event stream's + ``data.folderID`` key. + +Each tool gets ≥6 cases per the spec: + 1. happy-path scope filter + 2. env-unset redaction passthrough + 3. unknown scope passthrough with redaction + 4. scope=None back-compat baseline + 5. scope=public raises through error path + 6. _meta envelope shape check +Plus a determinism harness (N=5 byte-equal) for each. +""" + +import json + +import pytest +import respx + +from syncthing_mcp.models import ReadParams +from syncthing_mcp.registry import reload_instances +from tests.conftest import ( + BASE_URL, + DEVICE_ID_LOCAL, + DEVICE_ID_REMOTE, + FOLDER_ID, + make_completion, + make_connections, + make_db_status, + make_stats_device, + make_stats_folder, + make_system_status, + make_version, + split_meta, +) + + +@pytest.fixture(autouse=True) +def _setup(single_instance_env): + reload_instances() + yield + reload_instances() + + +def _multi_folder_config() -> dict: + """Config with 5 folders, used for filter assertions.""" + return { + "folders": [ + { + "id": f"fld{i}", + "label": f"f{i}", + "path": f"/data/f{i}", + "type": "sendreceive", + "paused": False, + "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"}, + ], + } + + +# --------------------------------------------------------------------------- +# syncthing_list_folders cat-B promotion +# --------------------------------------------------------------------------- + + +class TestListFoldersScope: + async def test_scope_work_filters(self, mock_api, monkeypatch): + from syncthing_mcp.tools.instances import syncthing_list_folders + + mock_api.get("/rest/config").respond(json=_multi_folder_config()) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1,fld3") + + payload, meta = split_meta( + await syncthing_list_folders(ReadParams(scope="work")) + ) + result = json.loads(payload) + ids = sorted(f["id"] for f in result) + assert ids == ["fld1", "fld3"] + assert meta["matched_total"] == 5 + assert meta["returned"] == 2 + assert meta["filtered_by"] == ["scope=work"] + assert meta["redactions"] == [] + + async def test_scope_unconfigured_redacts(self, mock_api, monkeypatch): + from syncthing_mcp.tools.instances import syncthing_list_folders + + mock_api.get("/rest/config").respond(json=_multi_folder_config()) + monkeypatch.delenv("SYNCTHING_WORK_FOLDERS", raising=False) + + payload, meta = split_meta( + await syncthing_list_folders(ReadParams(scope="work")) + ) + result = json.loads(payload) + # Unconfigured fallthrough — all 5 folders returned + assert len(result) == 5 + assert meta["matched_total"] == 5 + assert meta["returned"] == 5 + assert meta["filtered_by"] == [] + assert meta["redactions"] == ["scope=work_unconfigured"] + + async def test_unknown_scope_redacts(self, mock_api, monkeypatch): + from syncthing_mcp.tools.instances import syncthing_list_folders + + mock_api.get("/rest/config").respond(json=_multi_folder_config()) + payload, meta = split_meta( + await syncthing_list_folders(ReadParams(scope="garbage")) + ) + result = json.loads(payload) + assert len(result) == 5 + assert meta["redactions"] == ["scope=garbage_unconfigured"] + assert meta["filtered_by"] == [] + + async def test_scope_none_baseline(self, mock_api): + from syncthing_mcp.tools.instances import syncthing_list_folders + + mock_api.get("/rest/config").respond(json=_multi_folder_config()) + payload, meta = split_meta( + await syncthing_list_folders(ReadParams()) + ) + result = json.loads(payload) + assert len(result) == 5 + assert meta["matched_total"] == 5 + assert meta["returned"] == 5 + assert meta["filtered_by"] == [] + assert meta["redactions"] == [] + + async def test_scope_public_raises(self, mock_api): + from syncthing_mcp.tools.instances import syncthing_list_folders + + out = await syncthing_list_folders(ReadParams(scope="public")) + assert out.startswith("Error:") + assert "public" in out + + async def test_meta_envelope_shape(self, mock_api): + from syncthing_mcp.tools.instances import syncthing_list_folders + + mock_api.get("/rest/config").respond(json=_multi_folder_config()) + _payload, meta = split_meta( + await syncthing_list_folders(ReadParams()) + ) + # Required keys per A.1 envelope contract + assert set(meta.keys()) >= { + "matched_total", + "returned", + "filtered_by", + "redactions", + "latency_ms", + } + assert isinstance(meta["matched_total"], int) + assert isinstance(meta["returned"], int) + assert isinstance(meta["filtered_by"], list) + assert isinstance(meta["redactions"], list) + assert isinstance(meta["latency_ms"], int) + + async def test_deterministic_n5(self, mock_api, monkeypatch): + from syncthing_mcp.tools.instances import syncthing_list_folders + + mock_api.get("/rest/config").respond(json=_multi_folder_config()) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1,fld3") + + results = [] + for _ in range(5): + out = await syncthing_list_folders(ReadParams(scope="work")) + 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 + + +# --------------------------------------------------------------------------- +# syncthing_recent_changes cat-B promotion +# --------------------------------------------------------------------------- + + +def _events_fixture() -> list[dict]: + """5 ItemFinished-ish events across 4 folders + 1 with no folderID.""" + return [ + { + "id": 1, + "type": "LocalChangeDetected", + "data": {"folderID": "fld1", "path": "a.txt", "action": "modified"}, + }, + { + "id": 2, + "type": "RemoteChangeDetected", + "data": {"folderID": "fld2", "path": "b.txt", "action": "added"}, + }, + { + "id": 3, + "type": "LocalChangeDetected", + "data": {"folderID": "fld3", "path": "c.txt", "action": "deleted"}, + }, + { + "id": 4, + "type": "RemoteChangeDetected", + "data": {"folderID": "fld4", "path": "d.txt", "action": "modified"}, + }, + { + "id": 5, + "type": "LocalChangeDetected", + "data": {"path": "system.log"}, # no folderID + }, + ] + + +class TestRecentChangesScope: + async def test_scope_work_filters(self, mock_api, monkeypatch): + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1,fld3") + + payload, meta = split_meta( + await syncthing_recent_changes(ReadParams(scope="work")) + ) + result = json.loads(payload) + assert result["count"] == 2 + folder_ids = sorted(e["folder"] for e in result["events"]) + assert folder_ids == ["fld1", "fld3"] + assert meta["matched_total"] == 5 + assert meta["returned"] == 2 + assert meta["filtered_by"] == ["scope=work"] + assert meta["redactions"] == [] + + async def test_scope_unconfigured_redacts(self, mock_api, monkeypatch): + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + monkeypatch.delenv("SYNCTHING_WORK_FOLDERS", raising=False) + + payload, meta = split_meta( + await syncthing_recent_changes(ReadParams(scope="work")) + ) + result = json.loads(payload) + # Unconfigured fallthrough — all 5 events returned + assert result["count"] == 5 + assert meta["matched_total"] == 5 + assert meta["returned"] == 5 + assert meta["filtered_by"] == [] + assert meta["redactions"] == ["scope=work_unconfigured"] + + async def test_unknown_scope_redacts(self, mock_api): + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + payload, meta = split_meta( + await syncthing_recent_changes(ReadParams(scope="garbage")) + ) + result = json.loads(payload) + assert result["count"] == 5 + assert meta["redactions"] == ["scope=garbage_unconfigured"] + assert meta["filtered_by"] == [] + + async def test_scope_none_baseline(self, mock_api): + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + payload, meta = split_meta( + await syncthing_recent_changes(ReadParams()) + ) + result = json.loads(payload) + assert result["count"] == 5 + assert meta["matched_total"] == 5 + assert meta["returned"] == 5 + assert meta["filtered_by"] == [] + assert meta["redactions"] == [] + + async def test_scope_public_raises(self, mock_api): + from syncthing_mcp.tools.system import syncthing_recent_changes + + out = await syncthing_recent_changes(ReadParams(scope="public")) + assert out.startswith("Error:") + assert "public" in out + + async def test_meta_envelope_shape(self, mock_api): + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + _payload, meta = split_meta( + await syncthing_recent_changes(ReadParams()) + ) + assert set(meta.keys()) >= { + "matched_total", + "returned", + "filtered_by", + "redactions", + "latency_ms", + } + assert isinstance(meta["matched_total"], int) + assert isinstance(meta["returned"], int) + assert isinstance(meta["filtered_by"], list) + assert isinstance(meta["redactions"], list) + assert isinstance(meta["latency_ms"], int) + + async def test_no_folderid_filtered_out_under_scope(self, mock_api, monkeypatch): + """Event #5 carries no ``folderID`` — under an active scope filter, + it MUST drop out (system events do not partition by folder scope).""" + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + monkeypatch.setenv( + "SYNCTHING_INFRASTRUCTURE_FOLDERS", "fld1,fld2,fld3,fld4" + ) + payload, meta = split_meta( + await syncthing_recent_changes(ReadParams(scope="infrastructure")) + ) + result = json.loads(payload) + # Event #5 (no folderID) dropped; fld1–fld4 kept = 4 + assert result["count"] == 4 + assert meta["matched_total"] == 5 + assert meta["returned"] == 4 + + async def test_deterministic_n5(self, mock_api, monkeypatch): + from syncthing_mcp.tools.system import syncthing_recent_changes + + mock_api.get("/rest/events").respond(json=_events_fixture()) + monkeypatch.setenv("SYNCTHING_WORK_FOLDERS", "fld1,fld3") + + results = [] + for _ in range(5): + out = await syncthing_recent_changes(ReadParams(scope="work")) + 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 diff --git a/tests/test_tools_system.py b/tests/test_tools_system.py index 0a26115..f6069e3 100644 --- a/tests/test_tools_system.py +++ b/tests/test_tools_system.py @@ -18,6 +18,7 @@ from tests.conftest import ( make_db_status, make_system_status, make_version, + split_meta, ) @@ -81,8 +82,13 @@ class TestRecentChanges: mock_api.get("/rest/events").respond(json=[ {"id": 1, "type": "LocalChangeDetected", "data": {"path": "file.txt"}} ]) - result = json.loads(await syncthing_recent_changes(EmptyInput())) + payload, meta = split_meta(await syncthing_recent_changes(EmptyInput())) + result = json.loads(payload) assert result["count"] == 1 + assert meta["matched_total"] == 1 + assert meta["returned"] == 1 + assert meta["filtered_by"] == [] + assert meta["redactions"] == [] class TestRestartRequired: