Files
syncthing-blade-mcp/tests/test_a2_catB.py
T
PiersandClaude Opus 4.7 14ce0cafa1 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>
2026-05-23 15:27:19 +10:00

342 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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