battlemap-mcp 1.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. battlemap_mcp/__init__.py +3 -0
  2. battlemap_mcp/__main__.py +6 -0
  3. battlemap_mcp/arrangement.py +107 -0
  4. battlemap_mcp/asset_packs.py +254 -0
  5. battlemap_mcp/asset_search.py +195 -0
  6. battlemap_mcp/bridge_client.py +584 -0
  7. battlemap_mcp/bridge_payload/battlemap-mcp-bridge/LICENSE +22 -0
  8. battlemap_mcp/bridge_payload/battlemap-mcp-bridge/icons/mcp_bridge.png +0 -0
  9. battlemap_mcp/bridge_payload/battlemap-mcp-bridge/mcp_bridge.ddmod +9 -0
  10. battlemap_mcp/bridge_payload/battlemap-mcp-bridge/scripts/tools/mcp_bridge.gd +9405 -0
  11. battlemap_mcp/cli.py +606 -0
  12. battlemap_mcp/client_config.py +367 -0
  13. battlemap_mcp/colors.py +78 -0
  14. battlemap_mcp/companion_update.py +511 -0
  15. battlemap_mcp/cropping.py +138 -0
  16. battlemap_mcp/errors.py +103 -0
  17. battlemap_mcp/floorplan.py +382 -0
  18. battlemap_mcp/geometry.py +72 -0
  19. battlemap_mcp/handshake.py +149 -0
  20. battlemap_mcp/image_import.py +225 -0
  21. battlemap_mcp/installer.py +1075 -0
  22. battlemap_mcp/layout.py +612 -0
  23. battlemap_mcp/lifecycle.py +264 -0
  24. battlemap_mcp/mapfile.py +479 -0
  25. battlemap_mcp/pack_contents.py +367 -0
  26. battlemap_mcp/placement.py +708 -0
  27. battlemap_mcp/preflight.py +64 -0
  28. battlemap_mcp/safe_fetch.py +535 -0
  29. battlemap_mcp/scene.py +284 -0
  30. battlemap_mcp/server.py +7017 -0
  31. battlemap_mcp/shared_walls.py +98 -0
  32. battlemap_mcp/signed_manifest.py +518 -0
  33. battlemap_mcp/skill_updates.py +570 -0
  34. battlemap_mcp/skills.py +147 -0
  35. battlemap_mcp/skills_payload/_shared/build-loop.md +522 -0
  36. battlemap_mcp/skills_payload/_shared/review-rubric.md +21 -0
  37. battlemap_mcp/skills_payload/_shared/style-bible.md +23 -0
  38. battlemap_mcp/skills_payload/battlemap-art-direction/SKILL.md +71 -0
  39. battlemap_mcp/skills_payload/battlemap-composition-audit/SKILL.md +91 -0
  40. battlemap_mcp/skills_payload/battlemap-environments/SKILL.md +294 -0
  41. battlemap_mcp/skills_payload/battlemap-interiors/SKILL.md +284 -0
  42. battlemap_mcp/skills_payload/battlemap-lighting-hierarchy/SKILL.md +145 -0
  43. battlemap_mcp/skills_payload/battlemap-material-language/SKILL.md +236 -0
  44. battlemap_mcp/skills_payload/battlemap-visual-review/SKILL.md +37 -0
  45. battlemap_mcp/skills_payload/battlemap-vtt-rebuild/SKILL.md +212 -0
  46. battlemap_mcp/skills_payload/skill-index.json +68 -0
  47. battlemap_mcp/skills_payload/skills-sequence.json +1 -0
  48. battlemap_mcp/snapping.py +265 -0
  49. battlemap_mcp/state_paths.py +49 -0
  50. battlemap_mcp/timing.py +85 -0
  51. battlemap_mcp/update_staging.py +1003 -0
  52. battlemap_mcp/updates.py +304 -0
  53. battlemap_mcp/user_settings.py +105 -0
  54. battlemap_mcp/uvtt.py +665 -0
  55. battlemap_mcp/validation.py +288 -0
  56. battlemap_mcp-1.5.0.dist-info/METADATA +147 -0
  57. battlemap_mcp-1.5.0.dist-info/RECORD +61 -0
  58. battlemap_mcp-1.5.0.dist-info/WHEEL +4 -0
  59. battlemap_mcp-1.5.0.dist-info/entry_points.txt +2 -0
  60. battlemap_mcp-1.5.0.dist-info/licenses/LICENSE +22 -0
  61. battlemap_mcp-1.5.0.dist-info/licenses/NOTICE.md +25 -0
@@ -0,0 +1,3 @@
1
+ """Dungeondraft MCP server package."""
2
+
3
+ __version__ = "1.5.0"
@@ -0,0 +1,6 @@
1
+ """Module entry point for portable MCP client registration."""
2
+
3
+ from battlemap_mcp.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,107 @@
1
+ """Two layout habits that a render shows and no element count does.
2
+
3
+ Rigid placement: objects all at their default size and squared to the grid.
4
+ A room arranged that way reads as a showroom rather than a place in use, and
5
+ every placement call reports success, so nothing says so until someone looks.
6
+
7
+ A small footprint: a building in the middle of a mostly untouched map. At play
8
+ scale the eye lands on the empty ground first.
9
+
10
+ Both are advice, never failures. A shelf squared to its wall is correct, and a
11
+ lone ruin on an open plain can be the point. So neither changes an `ok`, and
12
+ each note says what to do rather than what went wrong.
13
+
14
+ Pure functions over what the bridge already returns; nothing here touches the map.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from .geometry import WOXELS_PER_TILE
20
+
21
+ SCALE_TOLERANCE = 0.01
22
+ ANGLE_TOLERANCE = 1.0
23
+
24
+ BATCH_MINIMUM = 6
25
+ BATCH_RIGID_SHARE = 0.9
26
+ SCENE_MINIMUM = 10
27
+ SCENE_RIGID_SHARE = 0.75
28
+ FOOTPRINT_SHARE = 0.4
29
+
30
+
31
+ def is_rigid(scale: float | None, rotation: float | None) -> bool:
32
+ """Default size and a quarter-turn rotation, within rounding."""
33
+ scale = 1.0 if scale is None else float(scale)
34
+ rotation = 0.0 if rotation is None else float(rotation)
35
+ off_quarter = abs(((rotation + 45.0) % 90.0) - 45.0)
36
+ return abs(scale - 1.0) <= SCALE_TOLERANCE and off_quarter <= ANGLE_TOLERANCE
37
+
38
+
39
+ def rigid_share(entries: list[dict]) -> float:
40
+ if not entries:
41
+ return 0.0
42
+ rigid = sum(is_rigid(e.get("scale"), e.get("rotation")) for e in entries)
43
+ return rigid / len(entries)
44
+
45
+
46
+ def batch_note(entries: list[dict]) -> str | None:
47
+ """A note for a place_objects result, or None when the batch varies enough."""
48
+ if len(entries) < BATCH_MINIMUM or rigid_share(entries) < BATCH_RIGID_SHARE:
49
+ return None
50
+ return (
51
+ f"All {len(entries)} objects in this batch sit at scale 1.0 and on quarter "
52
+ "turns, which reads as a showroom rather than a place in use. Keep "
53
+ "wall-hugging fixtures square, and give the rest a slightly different "
54
+ "scale (about 0.85-1.15) and a few degrees of turn; modify_object "
55
+ "adjusts placed objects."
56
+ )
57
+
58
+
59
+ def _extent(objects: list[dict], walls: list[dict], lights: list[dict]) -> tuple | None:
60
+ points: list[tuple[float, float]] = []
61
+ for element in [*objects, *lights]:
62
+ position = element.get("position")
63
+ if position:
64
+ points.append((float(position[0]), float(position[1])))
65
+ for wall in walls:
66
+ points += [(float(p[0]), float(p[1])) for p in wall.get("points") or []]
67
+ if not points:
68
+ return None
69
+ xs, ys = [p[0] for p in points], [p[1] for p in points]
70
+ return min(xs), min(ys), max(xs), max(ys)
71
+
72
+
73
+ def review(
74
+ map_size: tuple[float, float],
75
+ objects: list[dict],
76
+ walls: list[dict],
77
+ lights: list[dict],
78
+ ) -> dict:
79
+ """validate_scene's arrangement section: two measures and any advice."""
80
+ notes: list[str] = []
81
+ share = rigid_share(objects)
82
+ if len(objects) >= SCENE_MINIMUM and share >= SCENE_RIGID_SHARE:
83
+ notes.append(
84
+ f"{round(share * 100)}% of objects sit at scale 1.0 on quarter turns. "
85
+ "Beyond fixtures that belong squared to a wall, vary scale slightly "
86
+ "and turn pieces a few degrees so the space reads as used."
87
+ )
88
+ extent = _extent(objects, walls, lights)
89
+ map_area = float(map_size[0]) * float(map_size[1])
90
+ coverage = None
91
+ if extent and map_area > 0:
92
+ width = max(extent[2] - extent[0], WOXELS_PER_TILE)
93
+ height = max(extent[3] - extent[1], WOXELS_PER_TILE)
94
+ coverage = min(1.0, width * height / map_area)
95
+ if coverage < FOOTPRINT_SHARE:
96
+ notes.append(
97
+ f"What is built covers about {round(coverage * 100)}% of the map. "
98
+ "Extend the scene's surroundings toward the edges, or plan the "
99
+ "map size before laying out: set_map_size keeps the top-left "
100
+ "origin and does not move what is already placed."
101
+ )
102
+ return {
103
+ "rigid_share": round(share, 3),
104
+ "objects": len(objects),
105
+ "footprint_share": None if coverage is None else round(coverage, 3),
106
+ "notes": notes,
107
+ }
@@ -0,0 +1,254 @@
1
+ """Give a map the asset packs it is allowed to use.
2
+
3
+ The manifest is written into the map FILE rather than onto the live map:
4
+ Dungeondraft's own documentation calls `Header` safe to read and dangerous to
5
+ modify, so nothing here touches a running editor. The map is prepared on disk
6
+ and then opened, which is the same path Dungeondraft takes when it loads any
7
+ map someone else made.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import stat
18
+ import sys
19
+ import tempfile
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from . import mapfile
24
+
25
+ # Fields a manifest entry carries. Read off maps Dungeondraft itself wrote:
26
+ # every entry has the first four, and packs that ship colour overrides add the
27
+ # fifth. Anything else in pack.json is not part of a map's manifest.
28
+ ENTRY_FIELDS = ("name", "id", "version", "author")
29
+ OPTIONAL_FIELDS = ("keywords", "allow_3rd_party_mapping_software_to_read", "custom_color_overrides")
30
+
31
+
32
+ def manifest_entry(pack: dict[str, Any]) -> dict[str, Any]:
33
+ """One asset_manifest entry from a pack's own pack.json metadata."""
34
+ entry: dict[str, Any] = {field: pack.get(field, "") for field in ENTRY_FIELDS}
35
+ for field in OPTIONAL_FIELDS:
36
+ if field in pack:
37
+ entry[field] = pack[field]
38
+ return entry
39
+
40
+
41
+ def build_manifest(packs: list[dict[str, Any]], wanted: list[str] | None = None) -> list[dict]:
42
+ """Manifest entries for `wanted` pack ids, or for every pack when None.
43
+
44
+ Order follows the installed list so a prepared map is reproducible, and an
45
+ id is never included twice — a duplicate entry is how a map ends up with the
46
+ same pack listed under two versions.
47
+ """
48
+ chosen = []
49
+ seen: set[str] = set()
50
+ for pack in packs:
51
+ pack_id = str(pack.get("id", ""))
52
+ if not pack_id or pack_id in seen:
53
+ continue
54
+ if wanted is not None and pack_id not in wanted:
55
+ continue
56
+ seen.add(pack_id)
57
+ chosen.append(manifest_entry(pack))
58
+ return chosen
59
+
60
+
61
+ def unknown_ids(packs: list[dict[str, Any]], wanted: list[str]) -> list[str]:
62
+ """Requested ids that are not installed — asking for one is a caller error."""
63
+ installed = {str(pack.get("id", "")) for pack in packs}
64
+ return [pack_id for pack_id in wanted if pack_id not in installed]
65
+
66
+
67
+ def merge_manifest(existing: list[dict], adding: list[dict]) -> list[dict]:
68
+ """The packs a prepared map should include: what it already had, plus new ones."""
69
+ merged = [dict(entry) for entry in existing if isinstance(entry, dict)]
70
+ have = {str(entry.get("id", "")) for entry in merged}
71
+ for entry in adding:
72
+ if str(entry.get("id", "")) not in have:
73
+ have.add(str(entry.get("id", "")))
74
+ merged.append(dict(entry))
75
+ return merged
76
+
77
+
78
+ def publish_new_file(temporary: Path, destination: Path) -> None:
79
+ """Give a finished temporary file the new name `destination`.
80
+
81
+ Raises FileExistsError, and changes nothing, if that name is taken, even
82
+ by a file that appeared a moment ago: `os.rename` (Windows) and a hard
83
+ link (POSIX) both fail on an existing name, where `os.replace` would not.
84
+ Where the filesystem has no hard links (exFAT, some network shares) the
85
+ link raises some other OSError (EPERM, ENOTSUP, EXDEV); then the
86
+ destination is created O_CREAT | O_EXCL (refusing an existing name or a
87
+ planted symlink, as the link would), copied into, and given the
88
+ temporary's permission bits. A copy that fails is removed, so a failure
89
+ leaves no partial file under the final name.
90
+
91
+ The caller still removes `temporary`: only a rename consumes it.
92
+ """
93
+ if sys.platform == "win32":
94
+ os.rename(temporary, destination)
95
+ return
96
+ try:
97
+ os.link(temporary, destination, follow_symlinks=False)
98
+ return
99
+ except FileExistsError:
100
+ raise
101
+ except OSError:
102
+ pass
103
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
104
+ fd = os.open(destination, flags, 0o600)
105
+ try:
106
+ with os.fdopen(fd, "wb") as handle, temporary.open("rb") as data:
107
+ # A filesystem without permission bits may refuse this.
108
+ with contextlib.suppress(OSError):
109
+ os.fchmod(handle.fileno(), stat.S_IMODE(temporary.stat().st_mode))
110
+ shutil.copyfileobj(data, handle)
111
+ handle.flush()
112
+ os.fsync(handle.fileno())
113
+ except BaseException:
114
+ destination.unlink(missing_ok=True)
115
+ raise
116
+
117
+
118
+ def _publish_new_file(destination: Path, payload: bytes, *, like: Path) -> None:
119
+ """Create `destination` holding `payload`, never replacing a file.
120
+
121
+ Save directories can be shared, so anyone who can write there can plant
122
+ names in advance. A predictable temporary ("<name>.preparing") written with
123
+ `write_text` follows a symlink planted at that name and truncates whatever
124
+ it points at, before any rename happens. So the temporary is created with
125
+ `mkstemp` — an unpredictable name opened O_CREAT|O_EXCL, which refuses an
126
+ existing entry, symlinks included — and written through that descriptor,
127
+ never reopened by path.
128
+
129
+ `publish_new_file` then gives it the final name without clobbering. The
130
+ copy takes the source map's permission bits, so a map shared with other
131
+ users stays readable by them.
132
+ """
133
+ fd, temporary = tempfile.mkstemp(
134
+ dir=destination.parent, prefix=f".{destination.name}.", suffix=".preparing"
135
+ )
136
+ try:
137
+ with os.fdopen(fd, "wb") as handle:
138
+ if hasattr(os, "fchmod"):
139
+ os.fchmod(handle.fileno(), stat.S_IMODE(like.stat().st_mode))
140
+ handle.write(payload)
141
+ handle.flush()
142
+ os.fsync(handle.fileno())
143
+ try:
144
+ publish_new_file(Path(temporary), destination)
145
+ except FileExistsError as exc:
146
+ raise ValueError(f"{destination.name} already exists; refusing to replace it") from exc
147
+ finally:
148
+ # Only the file mkstemp created. After a successful hard link this
149
+ # removes the extra name; after a successful rename it is already gone.
150
+ if os.path.lexists(temporary):
151
+ os.unlink(temporary)
152
+
153
+
154
+ _DECODER = json.JSONDecoder()
155
+ # A string or a bracket: enough to find where an object or array ends
156
+ # without decoding it, which would build the whole `world` a second time.
157
+ _TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[{}\[\]]')
158
+
159
+
160
+ def _skip(text: str, at: int) -> int:
161
+ """The first index at or after `at` that is not JSON whitespace."""
162
+ while at < len(text) and text[at] in " \t\n\r":
163
+ at += 1
164
+ return at
165
+
166
+
167
+ def _value_end(text: str, at: int) -> int:
168
+ """Where the JSON value starting at `at` ends."""
169
+ if text[at] not in "{[":
170
+ return _DECODER.raw_decode(text, at)[1]
171
+ depth = 0
172
+ for token in _TOKEN.finditer(text, at):
173
+ mark = token.group()
174
+ if mark in "{[":
175
+ depth += 1
176
+ elif mark in "}]":
177
+ depth -= 1
178
+ if depth == 0:
179
+ return token.end()
180
+ raise ValueError("unterminated JSON value")
181
+
182
+
183
+ def _members(text: str, start: int) -> list[tuple[str, int, int]]:
184
+ """(key, value start, value end) of each member of the object at `start`.
185
+
186
+ Only called on text json.loads has already accepted, so the layout is
187
+ known to be valid JSON.
188
+ """
189
+ members: list[tuple[str, int, int]] = []
190
+ at = _skip(text, start + 1)
191
+ while text[at] != "}":
192
+ key, at = _DECODER.raw_decode(text, at)
193
+ at = _skip(text, at) + 1 # past ':'
194
+ at = _skip(text, at)
195
+ end = _value_end(text, at)
196
+ members.append((key, at, end))
197
+ at = _skip(text, end)
198
+ if text[at] == ",":
199
+ at = _skip(text, at + 1)
200
+ return members
201
+
202
+
203
+ def _with_manifest(text: str, manifest: list[dict]) -> str:
204
+ """`text` with only the header's asset_manifest value replaced.
205
+
206
+ Re-serialising the whole map changed bytes the caller never asked to
207
+ change: line endings, number spellings, and every non-ASCII character,
208
+ an emoji becoming a surrogate-pair escape Godot 3.4 does not recombine.
209
+ The last of duplicate keys is edited, as json.loads reads the last.
210
+ """
211
+ top = _skip(text, 0)
212
+ header = [m for m in _members(text, top) if m[0] == "header"][-1]
213
+ found = [m for m in _members(text, header[1]) if m[0] == "asset_manifest"]
214
+ value = json.dumps(manifest, ensure_ascii=False)
215
+ if found:
216
+ _key, start, end = found[-1]
217
+ return text[:start] + value + text[end:]
218
+ opening = header[1] + 1
219
+ separator = "" if text[_skip(text, opening)] == "}" else ", "
220
+ return text[:opening] + f'"asset_manifest": {value}{separator}' + text[opening:]
221
+
222
+
223
+ def prepare_map_file(source: Path, destination: Path, manifest: list[dict]) -> dict[str, Any]:
224
+ """Write a copy of `source` whose header includes `manifest`.
225
+
226
+ Only the header's asset_manifest changes; every other byte of the map is
227
+ carried across untouched, so the geometry, terrain and objects of the map
228
+ being copied are preserved exactly."""
229
+ if source.resolve() == destination.resolve():
230
+ raise ValueError(
231
+ f"refusing to write the prepared map onto its own source ({source.name}); "
232
+ "this prepares a COPY — choose a different filename"
233
+ )
234
+ # Bytes, not read_text: universal newlines would turn CRLF into LF.
235
+ text = source.read_bytes().decode("utf-8")
236
+ data = mapfile.loads(text)
237
+ header = data.get("header") if isinstance(data, dict) else None
238
+ if not isinstance(header, dict):
239
+ raise ValueError(f"{source.name} has no header object; is it a Dungeondraft map?")
240
+ existing = [e for e in (header.get("asset_manifest") or []) if isinstance(e, dict)]
241
+ final = merge_manifest(existing, manifest)
242
+
243
+ _publish_new_file(destination, _with_manifest(text, final).encode("utf-8"), like=source)
244
+
245
+ kept = [str(e.get("id", "")) for e in existing]
246
+ return {
247
+ "source": str(source),
248
+ "path": str(destination),
249
+ "packs_before": len(existing),
250
+ "packs_after": len(final),
251
+ "pack_ids": [entry["id"] for entry in final],
252
+ "kept_from_source": kept,
253
+ "added": [str(e["id"]) for e in final if str(e.get("id", "")) not in set(kept)],
254
+ }
@@ -0,0 +1,195 @@
1
+ """Ranked matching over asset paths, for callers whose words are not the filenames.
2
+
3
+ A brief says "double door", "round table", "flower bush"; the library says
4
+ `door_double_01`, `round_table_02`, `bush_flower_03`. A contiguous substring
5
+ test misses all three, and the caller gets an empty result with no hint that a
6
+ perfectly good asset is sitting there under a different word order.
7
+
8
+ What this can and cannot do is worth being precise about, because the gap is
9
+ easy to oversell:
10
+
11
+ - it fixes word ORDER and separators ("double door" -> door_double_01)
12
+ - it tolerates TYPOS ("tavren" -> tavern)
13
+ - it does NOT do synonyms. "mug" will not find `tankard`, and "tableware" will
14
+ not find `food_bread_01`. Nothing here understands what a word means, so a
15
+ caller that draws a blank should search a broader term or list the category.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from dataclasses import dataclass
22
+ from difflib import SequenceMatcher
23
+
24
+ MATCH_MODES = ("substring", "tokens", "fuzzy")
25
+ DEFAULT_MIN_SCORE = 0.55
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class AssetMatch:
30
+ """One asset path with the score that kept it and the terms that hit."""
31
+
32
+ path: str
33
+ score: float
34
+ matched: tuple[str, ...]
35
+
36
+
37
+ def _stem(path: str) -> str:
38
+ """The filename without directories or extension, lowercased."""
39
+ tail = path.rsplit("/", 1)[-1]
40
+ return tail.rsplit(".", 1)[0].lower()
41
+
42
+
43
+ def _words(text: str) -> list[str]:
44
+ """Split on the separators asset names actually use, not just whitespace."""
45
+ cleaned = "".join(character if character.isalnum() else " " for character in text.lower())
46
+ return [word for word in cleaned.split() if word]
47
+
48
+
49
+ def _haystack(path: str) -> str:
50
+ """A normalized form of the whole path, so directory words count too.
51
+
52
+ `res://textures/objects/furniture/tables/round_table_01.png` carries
53
+ "furniture" and "tables" in its directories; a caller searching "furniture
54
+ table" means exactly that, and dropping the directories would lose it.
55
+ """
56
+ return " ".join(_words(path.replace("res://", "")))
57
+
58
+
59
+ def searchable_text(path: str, extra: str = "") -> str:
60
+ """The words a 'tokens' search looks for its terms in: the path's, then extra's.
61
+
62
+ Precompute this to prefilter a large catalogue: a path can only match in
63
+ 'tokens' mode if every query word is a substring of it.
64
+ """
65
+ haystack = _haystack(path)
66
+ return f"{haystack} {' '.join(_words(extra))}" if extra else haystack
67
+
68
+
69
+ def query_words(query: str) -> list[str]:
70
+ """The words of a query, split the way paths are."""
71
+ return _words(query)
72
+
73
+
74
+ def _similarity(query: str, candidate: str) -> float:
75
+ return SequenceMatcher(None, query, candidate).ratio()
76
+
77
+
78
+ def score_path(path: str, query: str, mode: str, extra: str = "") -> AssetMatch | None:
79
+ """Score one path, or None when it does not qualify under this mode.
80
+
81
+ extra: more words that describe the asset, such as its pack's tags. They
82
+ count as hits, but the ranking still compares the query with the filename.
83
+ """
84
+ terms = _words(query)
85
+ if not terms:
86
+ return AssetMatch(path, 1.0, ())
87
+ haystack = searchable_text(path, extra)
88
+ stem = _stem(path)
89
+ stem_words = _words(stem)
90
+
91
+ if mode == "substring":
92
+ needle = query.lower()
93
+ found = needle in path.lower() or needle in extra.lower()
94
+ return AssetMatch(path, 1.0, (needle,)) if found else None
95
+
96
+ if mode == "tokens":
97
+ # Every term must appear somewhere in the path, in any order. Rank by
98
+ # how closely the stem resembles the query so the most on-the-nose
99
+ # filename comes first rather than an arbitrary directory hit.
100
+ hits = tuple(term for term in terms if term in haystack)
101
+ if len(hits) != len(terms):
102
+ return None
103
+ return AssetMatch(path, _similarity(" ".join(terms), " ".join(stem_words)), hits)
104
+
105
+ # fuzzy: best resemblance to the stem or the whole path, plus credit for any
106
+ # term that lands exactly. Without the exact-term credit, a long path can
107
+ # out-score a short precise one purely by having more characters to align.
108
+ hits = tuple(term for term in terms if term in haystack)
109
+ best = max(
110
+ _similarity(" ".join(terms), " ".join(stem_words)),
111
+ _similarity(" ".join(terms), haystack),
112
+ )
113
+ if hits:
114
+ best = max(best, len(hits) / len(terms))
115
+ return AssetMatch(path, best, hits)
116
+
117
+
118
+ def rank_assets(
119
+ paths: list[str],
120
+ query: str,
121
+ *,
122
+ mode: str = "substring",
123
+ min_score: float = DEFAULT_MIN_SCORE,
124
+ ) -> list[AssetMatch]:
125
+ """Return qualifying assets, best first.
126
+
127
+ Ties break on the shorter path, so `door_01` precedes
128
+ `door_01_decorated_variant` when both score the same.
129
+ """
130
+ if mode not in MATCH_MODES:
131
+ raise ValueError(f"mode must be one of {MATCH_MODES}, got {mode!r}")
132
+ floor = 0.0 if mode != "fuzzy" else min_score
133
+ matches = []
134
+ for path in paths:
135
+ match = score_path(path, query, mode)
136
+ if match is not None and match.score >= floor:
137
+ matches.append(match)
138
+ matches.sort(key=lambda m: (-m.score, len(m.path), m.path))
139
+ return matches
140
+
141
+
142
+ # Words that name the SAME thing, so a blank under one is worth retrying under
143
+ # another. The bar is equivalence, not relatedness: a desk is not a table and a
144
+ # sconce is not a lantern, and swapping one for the other turns an honest
145
+ # "nothing found" into a confident wrong asset. Spelling variants count; a
146
+ # narrower or broader word does not. Keep a pair out unless a builder asking
147
+ # for one would accept the other without a second thought.
148
+ EQUIVALENT_WORDS: tuple[tuple[str, ...], ...] = (
149
+ ("rug", "carpet"),
150
+ ("bookshelf", "bookcase"),
151
+ ("bookshelves", "bookcases"),
152
+ ("column", "pillar"),
153
+ ("couch", "sofa"),
154
+ ("wardrobe", "armoire"),
155
+ ("pail", "bucket"),
156
+ ("barrel", "cask"),
157
+ ("coffin", "casket"),
158
+ ("curtain", "drape"),
159
+ ("candelabra", "candelabrum"),
160
+ ("armor", "armour"),
161
+ ("gray", "grey"),
162
+ ("color", "colour"),
163
+ ("jewelry", "jewellery"),
164
+ ("center", "centre"),
165
+ ("theater", "theatre"),
166
+ )
167
+ # How many rewordings one blank term may cost. Each is a bridge round trip.
168
+ MAX_EQUIVALENT_QUERIES = 3
169
+
170
+ _EQUIVALENTS: dict[str, tuple[str, ...]] = {
171
+ word: tuple(other for other in group if other != word)
172
+ for group in EQUIVALENT_WORDS
173
+ for word in group
174
+ }
175
+
176
+
177
+ def equivalent_queries(query: str) -> list[str]:
178
+ """The query reworded with true equivalents, one word swapped at a time.
179
+
180
+ "red rug" gives ["red carpet"]. A plural is matched by its singular and
181
+ replaced by the singular, which a substring search still finds the plural
182
+ with. Words with no equivalent are left alone; a query with none gives [].
183
+ """
184
+ lowered = query.lower()
185
+ out: list[str] = []
186
+ # Swap the word in place, so the separators the caller chose survive: a
187
+ # substring search for "rug_red" has to become "carpet_red", not "carpet red".
188
+ for found in re.finditer(r"[a-z0-9]+", lowered):
189
+ word = found.group()
190
+ key = word if word in _EQUIVALENTS else word[:-1] if word.endswith("s") else ""
191
+ for other in _EQUIVALENTS.get(key, ()):
192
+ reworded = lowered[: found.start()] + other + lowered[found.end() :]
193
+ if reworded not in out:
194
+ out.append(reworded)
195
+ return out[:MAX_EQUIVALENT_QUERIES]