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
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ codegen/layout/directions.json -text
tests/fixtures/layout/** -text
# The address-in-prose cases (serial 123), the same bytes as the npm SDK's copy (the test holds its sha256).
tests/fixtures/address-in-prose.json -text
# The name finder's shared cases, the same bytes as the npm SDK's copy (both tests hold its sha256).
tests/fixtures/name-finder.cases.json -text
# The Kanka door's tables and wording, the same bytes as the npm SDK's copy (both tests hold its sha256).
src/onlyworlds/convert/kanka.json -text
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

## 0.141.0 (2026-11-23)

- **`name_finder(elements, case=...)`**: a world's element names found in prose. It reads the names once and answers `find(text)`, which lists every `NameFound` (`start`, `end`, `element`) in order, `element` being the object that was passed in, so a tool can mark the words that are elements. It finds and never writes. `case` must be given, `"exact"` or `"folded"` (simple case folding, Unicode 15.1), with no default; `names` gives the names an element is found by, by default its `name` alone. The rule: a whole name only, where the character on each side is not a letter, a combining mark, a decimal digit or an underscore in any script (so `Kira's` holds the name and `Kiran` does not); trimmed, three characters at least; the longest whole name where several start at one place; a name two elements share is never answered, nor anything inside it; nothing inside an address or a Markdown link. Limits: text is compared as written, with no Unicode normalisation; a space in a name matches that one space; in a script written without spaces between words a name is whole only between punctuation or spaces. The work for one text is at most its length times the longest name's length, whatever the number of names, with no pattern that backtracks. The npm SDK's `nameFinder` (4.194.0) is the same rule on the same file of cases (`tests/fixtures/name-finder.cases.json`, 47 cases, each want written by hand); the two differ only in what `start` and `end` count, code points here and UTF-16 units there.
- The README said that finding where an address starts in a text was the caller's work; `find_ow_links` does it, and the Addresses section now says so.
- `draught()`'s docstring said the server had sent the compact packet by default since 2026-11-02. The REST route's default is `false` until 2027-05-02, when it becomes `true`; the MCP tool `get_draught` defaults to `true` already. The docstring now says so.

## 0.140.0 (2026-11-22)

- **The schema pin moves to `v0.34.1-dist.145`** (canonical 00.34.01 unchanged, no schema file moved, `_schema.py` changes only its provenance lines). The charter page's rule 4 now names the `description` as the text an AI follows, the Charter's and each skill Object's, whole as the world holds it; a leading Charter whose `description` holds nothing gives that reader no house rules. The charter fixture gains four cases, each a newer marked Charter with an empty `description` beside an older one with text: the newer leads and its `skill` is empty. `charter_of` already answered all four so; no answer on an existing case moves.
Expand Down
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,30 @@ reading = parse_ow_link(text) # AddressReading: form, world, world_is_slug, typ
# a refusal raises AddressError: err.reason is the profile's name ("bad_id", "uppercase", ...)
```

A field that holds an address is text: never fetch or resolve it on the server. `parse_ow_link` reads one string whole, so `ow://object/<id>.` is refused. In prose, `read_ow_link_at(text, index)` reads the address that starts at `index` and answers an `AddressAt` (`reading`, `end`: the index just past it) or `None`; the address continues past its id only with `@` and a moment and `?lens=` and a lens, so a full stop, another query key and a fragment are left as prose. Finding where an address starts is yours. The profile: [`profiles/address.md`](https://github.com/OnlyWorlds/schema-dist/blob/main/profiles/address.md), with its fixture, which is this module's test.
A field that holds an address is text: never fetch or resolve it on the server. `parse_ow_link` reads one string whole, so `ow://object/<id>.` is refused. In prose, `read_ow_link_at(text, index)` reads the address that starts at `index` and answers an `AddressAt` (`reading`, `end`: the index just past it) or `None`; the address continues past its id only with `@` and a moment and `?lens=` and a lens, so a full stop, another query key and a fragment are left as prose. `find_ow_links(text)` finds every address in a text, each an `AddressFound` (`start`, `end`, `reading`). The profile: [`profiles/address.md`](https://github.com/OnlyWorlds/schema-dist/blob/main/profiles/address.md), with its fixture, which is this module's test.

### Names in prose

`name_finder` reads a world's element names once and answers a function that finds them in any text, so a tool can show which words are elements: a mark for a reader, a suggestion, a link a person chooses to make. It finds and never writes.

```python
from onlyworlds import name_finder

elements = [{"id": "a1", "name": "Iron Gate"}, {"id": "b2", "name": "Kira"}]
find = name_finder(elements, case="exact") # once per world
found = find("Kira's watch ends at the Iron Gate.")
# [NameFound(start=0, end=4, element=elements[1]), NameFound(start=25, end=34, element=elements[0])]
```

`case` must be given: `"exact"` for a page that marks names unasked, `"folded"` (case ignored) for an editor that only suggests. The rule, the same in the npm SDK's `nameFinder`:

- A whole name only: the character on each side is not a letter, a combining mark, a decimal digit or an underscore, in any script. `Kira's` and `Kira-led` hold the name; `Kiran` does not.
- A name is trimmed and is three characters at least. Where several names start at one place, the longest whole one is taken.
- A name two elements share is never answered, and nothing inside it is: the text stays plain there.
- Nothing is read inside an address or a Markdown link `[label](target)`.
- Every mention is answered, in order. `element` is the object you passed in; `start` and `end` count code points (the npm SDK counts UTF-16 units).

`names` gives the names an element is found by, such as a tool's own aliases: `name_finder(elements, case="folded", names=lambda el: [el["name"], *el.get("aliases", [])])`. Which elements go in is yours to choose. Three limits: text is compared as written, with no Unicode normalisation; a space in a name matches that one space; and in a script written without spaces between words (Chinese, Japanese, Thai) a name is whole only between punctuation or spaces. The work for one text is at most its length times the longest name's length, whatever the number of names.

### Open with

Expand Down
3 changes: 3 additions & 0 deletions src/onlyworlds/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@
thread_of,
unread_for,
)
from .name_finder import NameFound, name_finder
from .names import type_word
from .openers import Opener, Tool, ToolOpen, openers_for
from .push import Patch, PushPlan, PushResult, plan_push, push, verify_level
Expand Down Expand Up @@ -236,6 +237,7 @@
"MapSpaceMap",
"MapSpaceOutline",
"MapSpacePin",
"NameFound",
"Opener",
"Patch",
"PreconditionFailed",
Expand Down Expand Up @@ -314,6 +316,7 @@
"layout_of",
"lenses_in_use",
"map_space",
"name_finder",
"note_of",
"openers_for",
"out_degree_of",
Expand Down
2 changes: 1 addition & 1 deletion src/onlyworlds/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.140.0"
__version__ = "0.141.0"
200 changes: 200 additions & 0 deletions src/onlyworlds/name_finder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
"""Element names found in prose: ``name_finder`` reads a world's names once and answers a function that finds
them in any text. It finds and never writes: what a tool does with a found name (a mark for a reader, a
suggestion, a link a person chooses to make) is the tool's.

A rule of this package and the npm SDK's ``nameFinder``, not of the standard: both run one file of cases
(``tests/fixtures/name-finder.cases.json``, the same bytes in both repositories)."""

from __future__ import annotations

import unicodedata
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
from typing import Any, Literal

from .address import find_ow_links
from .room import _WHITE_SPACE
from .worldfile import simple_case_fold

__all__ = ["NameFound", "name_finder"]

_NAME_MIN = 3
"""A name shorter than this many characters (code points, after its white space is trimmed) is never looked for."""

_ASCII_WORD = frozenset("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_")


@dataclass(frozen=True)
class NameFound[T]:
"""One name found in a text: ``start`` and ``end`` in the text (code points; the npm SDK's ``nameFinder``
counts UTF-16 units), and ``element``, the same object ``name_finder`` was given."""

start: int
end: int
element: T


class _Hit[T]:
__slots__ = ("element", "id", "shared")

def __init__(self, id: str, element: T) -> None:
self.id = id
self.element = element
self.shared = False


class _Node[T]:
__slots__ = ("hit", "next")

def __init__(self) -> None:
self.next: dict[str, _Node[T]] = {}
self.hit: _Hit[T] | None = None


def _in_a_word(ch: str) -> bool:
"""A letter of any script, a combining mark, a decimal digit or an underscore: beside one, a name is inside a
word."""
if ch < "\x80":
return ch in _ASCII_WORD
return ch.isalpha() or unicodedata.category(ch) == "Nd" or unicodedata.category(ch).startswith("M")


def _markdown_links(text: str) -> list[tuple[int, int]]:
"""Every Markdown link ``[label](target)`` as ``(start, end)``: a ``[``, a label up to the first ``]``, a ``(``
right after it, a target up to the first ``)``. One pass: each bracket and parenthesis is searched for once."""
spans: list[tuple[int, int]] = []
close = -2
paren = -2
opened = text.find("[")
while opened != -1:
if close <= opened:
close = text.find("]", opened + 1)
if close == -1:
break
if not text.startswith("(", close + 1):
opened = text.find("[", opened + 1)
continue
if paren < close + 2:
paren = text.find(")", close + 2)
if paren == -1:
break
spans.append((opened, paren + 1))
opened = text.find("[", paren + 1)
return spans


def _passed_over(text: str) -> list[tuple[int, int]]:
"""The stretches no name is read in: every address and every Markdown link, in order, none overlapping."""
spans = _markdown_links(text)
spans.extend((a.start, a.end) for a in find_ow_links(text))
spans.sort()
out: list[tuple[int, int]] = []
for start, end in spans:
if out and start < out[-1][1]:
if end > out[-1][1]:
out[-1] = (out[-1][0], end)
else:
out.append((start, end))
return out


def name_finder[T: Mapping[str, Any]](
elements: Iterable[T],
*,
case: Literal["exact", "folded"],
names: Callable[[T], Iterable[object]] | None = None,
) -> Callable[[str], list[NameFound[T]]]:
"""A finder of a world's element names in prose: read the names once, then call the answer on each text.

``elements`` is any iterable of mappings with a string ``id`` and a ``name``. ``case`` must be given: ``"exact"``
(a name as written) or ``"folded"`` (simple case folding, Unicode 15.1, the fold the ``.owworld`` reader uses);
there is no default, so a tool never gets the other rule by leaving it out. ``names`` gives the names an element
is found by, by default its ``name`` alone; a value that is not a string is passed over.

The answer, ``find(text)``, lists every ``NameFound`` (``start``, ``end``, ``element``) in order, none
overlapping:

- A whole name only: the character on each side of it is not a letter, a combining mark, a decimal digit or an
underscore, in any script. So ``Kira's`` and ``Kira-led`` hold the name ``Kira``, and ``Kiran`` does not.
- A name is trimmed of white space and is three characters at least; a shorter one is never looked for.
- Where several names start at one place, the longest whole one is taken (``Iron Gate`` over ``Iron``).
- A name two elements share is never answered, and nothing inside it is: the text stays plain there. One
element listed twice, or found by two of its own names, is one element.
- Nothing is read inside an address (what ``find_ow_links`` finds) or a Markdown link ``[label](target)``, and
no name is read across the edge of one.
- Text is compared as written: no Unicode normalisation, and a space in a name matches that one space.

``element`` in an answer is the object that was passed in. Nothing given is changed. The work for one text is
at most its length times the longest name's length, whatever the number of names, with no pattern that
backtracks. ``start`` and ``end`` count code points (the npm SDK's ``nameFinder`` counts UTF-16 units). A
``case`` that is neither word, a ``names`` that cannot be called, an element without a string ``id``, or a
``text`` that is not a string is a ``TypeError``."""
if case not in ("exact", "folded"):
raise TypeError(f"name_finder: case is 'exact' or 'folded'; got {case!r}.")
if names is not None and not callable(names):
raise TypeError("name_finder: names is a function from an element to its names.")
if isinstance(elements, (str, bytes, Mapping)) or not isinstance(elements, Iterable):
raise TypeError("name_finder: elements is an iterable of mappings with an id and a name.")
folded = case == "folded"
root: _Node[T] = _Node()
for element in elements:
if not isinstance(element, Mapping) or not isinstance(element.get("id"), str) or element["id"] == "":
raise TypeError("name_finder: every element is a mapping with a string id.")
for raw in names(element) if names is not None else (element.get("name"),):
if not isinstance(raw, str):
continue
name = raw.strip(_WHITE_SPACE)
if len(name) < _NAME_MIN:
continue
node = root
for ch in simple_case_fold(name) if folded else name:
child = node.next.get(ch)
if child is None:
child = node.next[ch] = _Node()
node = child
if node.hit is None:
node.hit = _Hit(element["id"], element)
elif node.hit.id != element["id"]:
node.hit.shared = True

def find(text: str) -> list[NameFound[T]]:
if not isinstance(text, str):
raise TypeError("name_finder: text must be a string")
found: list[NameFound[T]] = []
firsts = root.next
if not firsts:
return found
spans = _passed_over(text)
hay = simple_case_fold(text) if folded else text
length = len(text)
span = 0
i = 0
while i < length:
if span < len(spans) and i >= spans[span][0]:
i = spans[span][1]
span += 1
continue
if hay[i] in firsts and (i == 0 or not _in_a_word(text[i - 1])):
limit = spans[span][0] if span < len(spans) else length
node = root
j = i
best: _Hit[T] | None = None
best_end = -1
while j < limit:
child = node.next.get(hay[j])
if child is None:
break
node = child
j += 1
if node.hit is not None and (j >= length or not _in_a_word(text[j])):
best = node.hit
best_end = j
if best is not None:
if not best.shared:
found.append(NameFound(i, best_end, best.element))
i = best_end
continue
i += 1
return found

return find
Loading
Loading