DD-338 Phase A.2 (narrowed) — syncthing list_folders + recent_changes cat-B scope= promotion
Wire the existing A.1 _resolve_scope_folders substrate into the two
remaining cat-B tools surfaced by the spec's Phase 0 audit:
* syncthing_list_folders — filter config.folders to the resolved
SYNCTHING_<SCOPE>_FOLDERS[_<INSTANCE>] set; honest matched_total /
returned / filtered_by counts via the existing append_meta envelope
(already shipped for domain_hints in A.2.dom.c).
* syncthing_recent_changes — filter the /rest/events stream to events
whose data.folderID is in the scoped set; gain _meta envelope via
append_meta. Events without a folderID (system-level events) drop out
under an active scope filter — system events do not partition by
folder scope.
OQ-4 resolution (Syncthing event key): events carry `data.folderID` not
`data.folder` (confirmed at branch checkout against the existing concise
projection at tools/system.py:158 + Syncthing 1.27.x REST schema). Filter
keys on `e.get("data", {}).get("folderID")`.
Reuses A.1 substrate verbatim — no greenfield scope mechanism.
Tests: +15 cases in tests/test_a2_catB.py (7 list_folders + 8
recent_changes), incl. determinism harnesses (N=5 byte-equal modulo
latency_ms). 1 modified existing recent_changes test in
test_tools_system.py to use split_meta after the envelope addition.
Suite: 133 → 151 (all green).
Per architect amendment 2026-05-23: spec narrowed from 34-tool sweep to
this 2-tool cat-B promotion. The 32 cat-A (honest scope_none) + cat-D
(write verb) tools in the original spec are already conformant via
pack-spec v4.4.0's honest-declaration path; no edits to those rows.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
4 files changed
+405
-14
No files matched your search
@@ -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_<SCOPE>_FOLDERS[_<INSTANCE>]`` 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,
|
||||
)
|
||||
|
||||
@@ -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_<SCOPE>_FOLDERS[_<INSTANCE>]`` 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)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user