Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

## 0.142.0 (2026-11-23)

- **The doctor names what it could not read.** On a folder, `Report.unread` (and `unread` in `--json`, after `written`) lists each file the folder reader did not read as an element, with why: a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. The prose report puts the list first, and any entry makes the exit code 1. Until now the doctor said nothing: with one element file cut off mid-write it reported the other elements as the whole world and listed every link to the unread one under "a link to an element that is not there". A dot-prefixed file is not listed. The API door's list is always empty.
- **A file nested too deep is skipped, not a traceback.** An element file or a `world.json` holding a value nested 100,000 deep made `read_folder` raise `RecursionError` on Windows and on Python 3.12 and 3.13, which nothing caught: the doctor and `pack` stopped with a traceback. Python 3.14 on Linux read the same file whole, and left the depth to whatever walked the value next. A value nested more than 200 deep is now refused on every platform, as a file that cannot be read ("nested more than 200 deep"), the way a file that is not JSON is. The archive reader and the Kanka and LegendKeeper doors parse their files through the same reader. A number of more than 4,300 digits was already skipped; its reason now says so in plain words in place of Python's advice about an interpreter setting.
- Not changed: `python -m onlyworlds.lint` reads element files through the schema distribution's own checker, which still stops on a file nested that deep.
- `KindLayout` and `AroundLayout` say in their docstrings that the `version` key is deprecated: it is always 1, the layout profile's mark carries no such key, and it leaves when the npm SDK's does, at its 5.0. Until now only a source comment said so, so `help()` and an editor's hover showed nothing. No behaviour changes.
- A test holds the address parser's length check on a moment: a run of more than 4,300 digits after `@` is refused as `bad_moment` before `int()` can raise on it, and the readers of prose pass over it.

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ for finding in report.findings:

It looks for links to elements that are not there, Events that end before they start, elements with no links in or out, two elements of one type whose names collide once case, character width, spacing and punctuation are folded (a name shared across types, such as a Location and its Pin, is not one), stubs never filled (a known-of element older than `--days`, or an element with no text in any of its type's text fields, on every type but map, marker, pin and relation), and a charter Law untouched after `--changes` changes in the feed. On a folder it also checks `world.json`: a `format_version` older than this package's (flag 9), and an `api_key` in a `world.json` that git tracks (flag 10). On both doors it reads the world's own house rules (flag 11, the checks profile: `x_checks_rules` on the world's Charter, the newest Law with supertype Charter that carries the mark `x_charter_of`, applied by `onlyworlds.apply_checks`) and names every element a rule finds short, with each rule's scoped and short counts, and every rule it cannot apply, with why; an older marked Charter is a finding, its rules not applied; a Law with supertype Charter and no mark is lore, not a Charter and not a finding, and its rules are never applied. Flag 14 names a marked Guide or Domain whose links name an element that is not in the world or a hidden one (every other reader is served the Guide or Domain without it; not through a guest key, and the hidden half only through a key that is served hidden elements). On a spine world (one where an element carries an `x_spine_` key), flag 13 reads each element with `read_spine_element` and names an off-list supertype on a listed type, every value the reader drops and a probe not in the probe form; then, on a source world, it checks that each row (an Object, Construct, Location or Law of a listed kind, the Charter too) is kept by exactly one Seat (a Title with supertype `Seat`, through its field for the row's type; any other Title neither owns nor counts), that every `x_spine_depends_on` id is in the world (not through a guest key), that a `legacy` or `provenance` row has an Event with supertype `Retirement` that names it in `x_spine_retires` and links it through its typed field where the type has one (`objects`, `constructs`, `locations`; an Event has no `laws` field, so a Law's retirement is attributed by the key alone; only through a key that sees every element, hidden ones too), that no row is still at `gone` (its retirement is unfinished), and that no two rows of one row type share a name once trimmed and folded for case (a Seat or any other element is outside that rule). Whether a probe passes and `x_spine_probed` are not checked, and the report says so. A projection (a public world built from a spine, each row naming its keeping Seat in `x_spine_owner`) is marked on its World with `x_spine_projection`, `{source, at}`: `source` the projected-from world's id as a string, a UUID that is no element's id in this world, and `at` the ISO 8601 time of the last rebuild, which must parse; each is a finding on the world otherwise. On a projection only the projection's own checks run: every row must carry `x_spine_owner` (the keeping Seat's name in the source, which need match nothing in the projection) and no element may be hidden; the source's checks do not run there, and the report names each. On an unmarked world `x_spine_owner` is a finding (the projection's third check), and a malformed mark is a finding on the world, which is then read as unmarked. Each check says how much it could compare, and one it cannot run (a folder has no change feed; nothing records whether a message was read) is listed with the reason, never counted as clean. A finding on a message or a room thing (supertype Message, Board, Work item, Spec, Heart, Vote or Sitting) is marked `"kind": "message"` and listed last, outside the count of things to look at. `--json` prints the same report for a tool, and `--packet` prints the findings as work packets (the `packet` extension profile: a Relation with supertype `Work item`, its elements with a reason each under `x_packet_elements`, a JSON array, empty when clean) for a tool that lands them in a world or a parlor. The exit code is 0 when there is nothing to look at, 1 when there is (a message finding too), 2 when nothing could be read.

On a folder, the report names first what it could not read as an element (`report.unread`, each a `file` and a `why`): a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. Every check ran on the rest, so an element in such a file counts as not there and a link to it reads as a link to a missing element; any unread file makes the exit code 1. A dot-prefixed file is a tool's litter and is not listed.

The API door reads the key from `OW_API_KEY` and the PIN from `OW_API_PIN`, or from the toolkit's `ONLYWORLDS_API_KEY` and `ONLYWORLDS_API_PIN` when those are not set.

## The lint
Expand Down
62 changes: 62 additions & 0 deletions src/onlyworlds/_outside_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""``json.loads`` for text this package did not write: a world folder's file, an archive, another tool's export.

Two inputs that are JSON by the grammar make ``json.loads`` do something its callers do not expect.

A value nested very deep: where the interpreter's own limit is met first, ``json.loads`` raises
``RecursionError``, which is no ``ValueError``, so every reader that catches "not JSON" let it through as
a traceback. Where the limit is higher (Python 3.14 on Linux reads 100,000 levels), the value comes back
whole and the next recursive walk over it fails instead. So the depth is refused here by one number,
``MAX_DEPTH``, the same on every platform.

An integer of more than 4,300 digits: a plain ``ValueError`` whose message advises a Python setting.

Here both are a ``ValueError`` in plain words, so a caller's ``except ValueError`` reads either as a file
it cannot read, and says why."""

from __future__ import annotations

import json
import sys
from typing import Any

#: The deepest nesting read: a value at the top is depth 0, an object or array there depth 1, what it holds
#: depth 2. No world data comes near it; every supported interpreter parses this deep.
MAX_DEPTH = 200

_TOO_DEEP = f"nested more than {MAX_DEPTH} deep"


def _int(text: str) -> int:
limit = sys.get_int_max_str_digits()
if limit and len(text.lstrip("-")) > limit:
raise ValueError(f"a number of more than {limit} digits")
return int(text)


def _too_deep(value: Any) -> bool:
"""Whether any object or array sits deeper than ``MAX_DEPTH``. A loop with its own stack, never recursion."""
stack: list[tuple[Any, int]] = [(value, 1)]
while stack:
item, depth = stack.pop()
if isinstance(item, dict):
children: Any = item.values()
elif isinstance(item, list):
children = item
else:
continue
if depth > MAX_DEPTH:
return True
stack.extend((child, depth + 1) for child in children if isinstance(child, (dict, list)))
return False


def loads(text: str, **kwargs: Any) -> Any:
"""``json.loads(text, **kwargs)``, with the two cases above raised as ``ValueError``."""
kwargs.setdefault("parse_int", _int)
try:
value = json.loads(text, **kwargs)
except RecursionError:
raise ValueError(_TOO_DEEP) from None
if _too_deep(value):
raise ValueError(_TOO_DEEP)
return value
2 changes: 1 addition & 1 deletion src/onlyworlds/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.141.0"
__version__ = "0.142.0"
43 changes: 40 additions & 3 deletions src/onlyworlds/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@
7. a message unread by its addressee after N days;
8. a charter (a Law with supertype Charter) untouched after N changes;

On the folder door the report also says what it did not read as an element (``Report.unread``, each a
``file`` and a ``why``, printed before any finding): a file the folder reader skipped (not JSON, not an
object, no ``id``), a second file of one id, a directory that is no type's. Every flag runs on the rest,
so an element in such a file counts as not there; any entry makes the exit code 1. It is no flag and has
no number. A dot-prefixed file is a tool's litter and is not listed.

and two from the file side, on the folder door only: (9) a ``format_version`` older than
this package's ``FORMAT_VERSION``; (10) an ``api_key`` in ``world.json``'s ``api`` block
when ``world.json`` is tracked by git.
Expand Down Expand Up @@ -313,6 +319,10 @@ class Report:
compared: dict[str, dict[str, Any]] = field(default_factory=dict)
#: always 0: the doctor never writes
written: int = 0
#: the folder door: what the folder reader did not read as an element, each ``{file, why}``
#: (a file that is not JSON, not an object or has no id; a second file of one id; a directory
#: that is no type's). Every flag ran on the rest. Always empty on the API door.
unread: list[dict[str, str]] = field(default_factory=list)

def as_dict(self) -> dict[str, Any]:
return {
Expand All @@ -322,12 +332,13 @@ def as_dict(self) -> dict[str, Any]:
"findings": self.findings,
"compared": self.compared,
"written": self.written,
"unread": self.unread,
}

@property
def exit_code(self) -> int:
"""1 for any finding, a message-shaped one too; 0 for none."""
return 1 if self.findings else 0
"""1 for any finding, a message-shaped one too, or any unread file; 0 for none."""
return 1 if self.findings or self.unread else 0

@property
def to_look_at(self) -> list[dict[str, Any]]:
Expand Down Expand Up @@ -1240,7 +1251,26 @@ def doctor_folder(folder: Folder, *, days: int = 14, changes: int = 50, now: _dt
run.skip("8", "no feed in a folder")
run.skip(PROPOSALS_FLAG, "proposals are kept on the server, not in a folder")
_file_side(run, folder)
return run.done()
report = run.done()
report.unread = _unread(folder)
return report


def _unread(folder: Folder) -> list[dict[str, str]]:
"""What ``read_folder`` did not read as an element, by path: every flag ran without it, so an
element in such a file counts as not there and a link to it reads as a link to a missing element.
A dot-prefixed file is a tool's litter, never an element, and is not listed."""

def rel(path: Path) -> str:
return path.relative_to(folder.root).as_posix()

out = [{"file": rel(s.path), "why": s.reason} for s in folder.skipped if not s.path.name.startswith(".")]
out += [
{"file": rel(d.ignored), "why": f"its id {d.id} is also in {rel(d.kept)}, which was read"}
for d in folder.duplicates
]
out += [{"file": rel(d) + "/", "why": "not a type directory"} for d in folder.ignored_dirs]
return sorted(out, key=lambda x: x["file"])


# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -1493,6 +1523,13 @@ def _lines(report: Report) -> Iterable[str]:
f"{len(report.not_run)} could not run, {report.written} things written"
+ (f" ({len(messages)} on messages and room things, listed last)" if messages else "")
)
if report.unread:
n = len(report.unread)
yield ""
yield f"Not read ({n}): everything below is about the rest of the folder"
yield " An element in one of these counts as not there, and a link to it reads as a link to a missing element."
for item in report.unread:
yield f" - {item['file']}: {item['why']}"
yield from _by_flag(report.to_look_at)
yield ""
yield "What was checked"
Expand Down
4 changes: 2 additions & 2 deletions src/onlyworlds/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

from __future__ import annotations

import json
import os
import re
import shutil
Expand All @@ -26,6 +25,7 @@
from pathlib import Path
from typing import Any, Literal

from . import _outside_json
from ._jsonfmt import encode
from ._schema import ELEMENT_TYPES

Expand Down Expand Up @@ -445,7 +445,7 @@ def _reject_constant(token: str) -> Any:

def _load_json(path: Path) -> Any:
text = path.read_bytes().decode("utf-8-sig")
return json.loads(text, parse_constant=_reject_constant)
return _outside_json.loads(text, parse_constant=_reject_constant)


def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder:
Expand Down
3 changes: 2 additions & 1 deletion src/onlyworlds/kanka.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@
from pathlib import Path
from typing import Any

from . import _outside_json
from ._made import MadeName, _counts, _lines
from ._schema import FIELD_KINDS, LINK_TARGETS
from ._version import __version__
Expand Down Expand Up @@ -829,7 +830,7 @@ def __init__(self, files: Mapping[str, Callable[[], bytes]], source: Path, notes

def _json(self, rel: str) -> Any:
try:
return json.loads(self.files[rel]().decode("utf-8-sig"))
return _outside_json.loads(self.files[rel]().decode("utf-8-sig"))
except (ValueError, UnicodeDecodeError) as exc:
self.report.notes.append(_NOTE["not_json"].format(rel=rel, error=type(exc).__name__))
return None
Expand Down
5 changes: 3 additions & 2 deletions src/onlyworlds/legendkeeper.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@
from pathlib import Path
from typing import Any, Protocol

from . import _outside_json
from ._jsonfmt import encode
from ._made import ANY_TYPE, MadeName, _counts, _lines
from ._schema import ELEMENT_TYPES, FIELD_KINDS, LINK_TARGETS
Expand Down Expand Up @@ -629,7 +630,7 @@ def _json_or_text(text: str) -> Any:
or an object cannot ride a key-value row otherwise), else the text itself."""
if text[:1] in "[{":
try:
return json.loads(text)
return _outside_json.loads(text)
except ValueError:
pass
return text
Expand Down Expand Up @@ -935,7 +936,7 @@ def __init__(self, path: str | os.PathLike[str], project_id: str | None = None)
raise FileNotFoundError(f"{self.path}: no such export file")
raw = _export_bytes(self.path)
try:
data = json.loads(raw.decode("utf-8-sig"))
data = _outside_json.loads(raw.decode("utf-8-sig"))
except ValueError: # UnicodeDecodeError and JSONDecodeError both
raise ValueError(f"{self.path}: not a LegendKeeper export (not UTF-8 JSON)") from None
if not isinstance(data, dict) or not isinstance(data.get("resources"), list):
Expand Down
4 changes: 3 additions & 1 deletion src/onlyworlds/lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
from types import ModuleType
from typing import Any

from . import _outside_json

_WALK = Path(__file__).resolve().parent / "_walk"


Expand Down Expand Up @@ -71,7 +73,7 @@ def lint(folder: str | Path) -> Any:

def _linked(src: Path) -> bool:
try:
world = json.loads((src / "world.json").read_text(encoding="utf-8"))
world = _outside_json.loads((src / "world.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return False
return isinstance(world, dict) and bool(world.get("api"))
Expand Down
10 changes: 5 additions & 5 deletions src/onlyworlds/worldfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
from __future__ import annotations

import io
import json
import os
import re
import shutil
Expand All @@ -73,6 +72,7 @@
from pathlib import Path
from typing import IO, Any, Literal, NoReturn

from . import _outside_json
from ._casefold import FOLD_RUNS
from ._jsonfmt import encode
from ._nfc import CLASS_RUNS, DECOMPOSITIONS, EXCLUSIONS
Expand Down Expand Up @@ -556,7 +556,7 @@ def _reject_constant(token: str) -> Any:
def _parse_world(data: bytes) -> dict[str, Any]:
text = data.decode("utf-8", errors="replace").removeprefix(_BOM)
try:
meta = json.loads(text, parse_constant=_reject_constant)
meta = _outside_json.loads(text, parse_constant=_reject_constant)
except ValueError:
_refuse("not_a_world")
if not isinstance(meta, dict):
Expand Down Expand Up @@ -812,7 +812,7 @@ def unreadable(why: str) -> NoReturn:
)

try:
doc = json.loads(raw.decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant)
doc = _outside_json.loads(raw.decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant)
except ValueError: # not UTF-8, or not JSON
unreadable("is not JSON")
if not isinstance(doc, list) or not all(isinstance(e, dict) for e in doc):
Expand Down Expand Up @@ -843,7 +843,7 @@ def _hidden_element_file(rel: str, src: Path) -> bool:
if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"):
return False
try:
body = json.loads(src.read_bytes().decode("utf-8-sig"))
body = _outside_json.loads(src.read_bytes().decode("utf-8-sig"))
except (UnicodeDecodeError, ValueError):
return False
return isinstance(body, dict) and is_hidden(body)
Expand All @@ -864,7 +864,7 @@ def _without_author_fields(rel: str, src: Path) -> bytes | None:
if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"):
return None
try:
body = json.loads(src.read_bytes().decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant)
body = _outside_json.loads(src.read_bytes().decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant)
except ValueError: # not UTF-8, or not JSON
return None
if not isinstance(body, dict) or not any(k in body for k in _AUTHOR_FIELDS):
Expand Down
Loading
Loading