| 1 | import re |
| 2 | |
| 3 | |
| 4 | def safe_path_component(name) -> str: |
| 5 | """Sanitize an LLM-derived identifier for use as a filesystem path component. |
| 6 | |
| 7 | Identifiers come from model output over user-supplied story text, so they may |
| 8 | contain separators or traversal sequences; keep word characters (including |
| 9 | CJK), dashes, dots and spaces, replace everything else, and strip leading |
| 10 | dots so the result can never escape or hide within the working directory. |
| 11 | """ |
| 12 | cleaned = re.sub(r"[^\w\-. ]", "_", str(name)) |
| 13 | cleaned = cleaned.strip().lstrip(".") |
| 14 | return cleaned or "unnamed" |
| 15 |