From 36ec7122747e1a63678b6a2455943cb4e76d9b28 Mon Sep 17 00:00:00 2001 From: Titus Date: Fri, 27 Nov 2026 22:00:59 +0100 Subject: [PATCH 1/2] okf: write Open Knowledge Format 0.3, pinned at 527e81a in its new repository The spec moved to open-knowledge-format/open-knowledge-format (the old address is marked deprecated) and to version 0.3. The root index now says okf_version "0.3" and carries the bundle metadata of section 8.1: the world's name as title and a one-sentence description. Neither of 0.3's breaking changes reaches the export (no path fields, no trust frontmatter). A string YAML 1.2's core schema reads as a number (1e5, 0o17, 1.5e3) is now quoted. superseded_by and license join the keys an OnlyWorlds field is renamed past. OKF's reference parser and viewer at the new pin read the export, and its v0.3 validator finds the example world's bundle conformant with --strict. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/onlyworlds/okf.py | 62 ++++++++++++++++++++++++++++++++----------- tests/test_okf.py | 30 ++++++++++++++++++--- 3 files changed, 74 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 9b3aeab..4d715bf 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ Every door names an element from the export's own text where it can. Where it ca ## Export to OKF -A world folder can be exported as a valid [Open Knowledge Format](https://github.com/open-knowledge-format/open-knowledge-format) (OKF) 0.2 bundle, as the spec stands at one pinned commit (`onlyworlds.okf.OKF_COMMIT`): one markdown file per element, with its fields in the frontmatter, its text under headings and its links (in-prose `ow://` references included) as markdown links, plus an index per type. This needs PyYAML, which the rest of the package does not: +A world folder can be exported as a valid [Open Knowledge Format](https://github.com/open-knowledge-format/open-knowledge-format) (OKF) 0.3 bundle, as the spec stands at one pinned commit (`onlyworlds.okf.OKF_COMMIT`): one markdown file per element, with its fields in the frontmatter, its text under headings and its links (in-prose `ow://` references included) as markdown links, plus an index per type and a root index carrying the world's name as the bundle's `title`. This needs PyYAML, which the rest of the package does not: ```bash pip install "onlyworlds[okf]" diff --git a/src/onlyworlds/okf.py b/src/onlyworlds/okf.py index 7572de3..71aeb64 100644 --- a/src/onlyworlds/okf.py +++ b/src/onlyworlds/okf.py @@ -4,16 +4,18 @@ or ``export_okf(folder, out_dir, hidden=False)``. Needs PyYAML: ``pip install "onlyworlds[okf]"``. -Writes OUT-DIR (which must not exist yet) as a bundle in Google Cloud's Open -Knowledge Format (OKF) v0.2, as specified at one pinned commit: +Writes OUT-DIR (which must not exist yet) as a bundle in the Open Knowledge +Format (OKF) v0.3, as specified at one pinned commit: - repo: https://github.com/GoogleCloudPlatform/open-knowledge-format - commit: ad30107c31c06aec8a7d5636e0d1058118604e6f (SPEC.md "Version 0.2", - 2026-08-21, the ISO 8601 timestamp edit) + repo: https://github.com/open-knowledge-format/open-knowledge-format + commit: 527e81aff55992be21507e97004286789126f88c (SPEC.md "Version 0.3", + 2026-11-18) The bundle: - index.md root index; frontmatter `okf_version: "0.2"` + index.md root index; frontmatter `okf_version: "0.3"`, + the world's name as `title` and a + `description` of the bundle (§8.1) world.md the World as a concept (`type: OnlyWorlds World`), carrying the bundle metadata /index.md one per element type present @@ -32,8 +34,10 @@ named once, in world.md's `onlyworlds_export` block. - scalar fields sit in the frontmatter under their OnlyWorlds names: `id`, `supertype`, `subtype`, `image_url` and every integer field. A field - whose name OKF defines (§4.1, §5, §10: `status` and the like) would be - written as `ow_`; no frontmatter field needs it today. + whose name OKF defines (§4.1, §5, §8.1, §10: `status` and the like) would + be written as `ow_`; no frontmatter field needs it today. These are + OnlyWorlds' names, not `x-onlyworlds-` ones: §4.1 says a producer SHOULD + prefix its own keys, and a consumer MUST NOT reject keys it does not know. - every link field is in the frontmatter, keyed by its OnlyWorlds field name, as bundle-absolute paths (`location: /location/barovia--1a2b3c4d.md`, a list for a multi link; `element` for a pin's generic link), so the kind @@ -43,7 +47,8 @@ `## ` headings in schema order, and every link again as a markdown link in a bullet (`- **location**: [Barovia](../location/....md)`), so viewers that draw the link graph from bodies draw it. Body links are - relative: the reference viewer at the pinned commit skips `/` links. A + relative: §6 makes both forms valid, and the reference viewer at v0.2 + skipped `/` links. A text line markdown would read as a heading (`#`, or a `===`/`---` underline) is escaped with a backslash, so text cannot make a section; so is a line that already begins with a backslash, so a reader removes @@ -163,16 +168,17 @@ __all__ = ["EXPORTER", "OKF_COMMIT", "OKF_VERSION", "FolderError", "OkfReport", "build_bundle", "export_okf", "main"] EXPORTER = f"onlyworlds-py/{__version__}" -OKF_VERSION = "0.2" -OKF_REPO = "https://github.com/GoogleCloudPlatform/open-knowledge-format" -OKF_COMMIT = "ad30107c31c06aec8a7d5636e0d1058118604e6f" +OKF_VERSION = "0.3" +OKF_REPO = "https://github.com/open-knowledge-format/open-knowledge-format" +OKF_COMMIT = "527e81aff55992be21507e97004286789126f88c" -# Frontmatter keys OKF v0.2 gives a meaning (SPEC §4.1, §5, §10, §12). An +# Frontmatter keys OKF v0.3 gives a meaning (SPEC §4.1, §5, §8.1, §10, §12). An # OnlyWorlds field of the same name is written as `ow_`. OKF_KEYS = frozenset( { "type", "title", "description", "resource", "tags", "sources", "usage_window", "generated", "verified", - "status", "stale_after", "runtime", "parameters", "computation", "executor", "attester", "okf_version", + "status", "superseded_by", "stale_after", "runtime", "parameters", "computation", "executor", "attester", + "okf_version", "license", } ) # fmt: skip WORLD_DROPPED = ("api", *WIRE_TO_DISK_WORLD_KEYS) @@ -215,6 +221,16 @@ class OkfReport: # --- YAML: block style, line-break-bearing strings double-quoted on one line # (the breaks escaped), so no frontmatter line can read as the closing `---`. +# OKF reads frontmatter by YAML 1.2's core schema (§4) and PyYAML writes 1.1, +# which leaves some strings plain that 1.2 reads as a number (`1e5`, `0o17`): +# those are quoted. + +_YAML12_NOT_STR = re.compile( + r"[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+" + r"|[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?" + r"|[-+]?\.(inf|Inf|INF)|\.(nan|NaN|NAN)" + r"|true|True|TRUE|false|False|FALSE|null|Null|NULL|~" +) class _Dumper(yaml.SafeDumper): @@ -222,7 +238,12 @@ class _Dumper(yaml.SafeDumper): def _str_rep(dumper: yaml.SafeDumper, value: str) -> yaml.ScalarNode: - style = '"' if any(c in value for c in LINE_BREAKS) else None + if any(c in value for c in LINE_BREAKS): + style: str | None = '"' + elif _YAML12_NOT_STR.fullmatch(value): + style = "'" + else: + style = None return dumper.represent_scalar("tag:yaml.org,2002:str", value, style=style) @@ -602,8 +623,17 @@ def noted(msg: str) -> None: files["world.md"] = world_doc( folder.world, folder.time_current, len(elements), paths, names, report, noted, hidden_ids ) + world_name = str(folder.world.get("name") or "").strip() + bundle_meta: dict[str, Any] = {} + if world_name: + bundle_meta["title"] = world_name + bundle_meta["description"] = ( + f"An OnlyWorlds world{f', {_one_line(world_name)},' if world_name else ''} as knowledge: " + f"{len(elements)} element{'s' if len(elements) != 1 else ''}, one concept each, " + "in a directory for each element type." + ) root = [ - f'---\nokf_version: "{OKF_VERSION}"\n---\n', + f'---\nokf_version: "{OKF_VERSION}"\n{_frontmatter(bundle_meta)}---\n', "# World\n", index_entry( str(folder.world.get("name") or "World"), diff --git a/tests/test_okf.py b/tests/test_okf.py index c1fa929..3edb887 100644 --- a/tests/test_okf.py +++ b/tests/test_okf.py @@ -3,7 +3,7 @@ Ported from schema-dist's walk/test_okf_export.py (branch okf-exporter, 8d0f92f): the same 24 tests, on the package's reader and generated schema tables. Needs PyYAML (the ``okf`` extra; the dev group has it); without it the module skips. OKF's reference parser and viewer -(github.com/GoogleCloudPlatform/open-knowledge-format at the commit okf.py pins) run too when importable: +(github.com/open-knowledge-format/open-knowledge-format at the commit okf.py pins) run too when importable: put a checkout's ``src/`` on OKF_REFERENCE_SRC; otherwise those checks skip and say so. """ @@ -246,7 +246,14 @@ def test_every_link_names_the_right_element(bundle: Bundle) -> None: def test_indexes(bundle: Bundle) -> None: root = bundle.files["index.md"].decode("utf-8") - assert root.startswith('---\nokf_version: "0.2"\n---\n') + assert root.startswith('---\nokf_version: "0.3"\ntitle: Hyperion\ndescription: ') + meta, _ = split(root) + assert meta == { + "okf_version": "0.3", + "title": "Hyperion", + "description": f"An OnlyWorlds world, Hyperion, as knowledge: {len(bundle.sources)} elements, " + "one concept each, in a directory for each element type.", + } assert "* [OnlyWorlds Character](character/index.md) - 3 elements" in root assert bundle.files["character/index.md"].startswith(b"# OnlyWorlds Character\n") listed = [] @@ -297,7 +304,7 @@ def test_reference_parser_and_viewer(bundle: Bundle, tmp_path: Path) -> None: for rel, data in bundle.files.items(): doc = OKFDocument.parse(data.decode("utf-8")) if rel.endswith("index.md"): - allowed = {"okf_version"} if rel == "index.md" else set() + allowed = {"okf_version", "title", "description"} if rel == "index.md" else set() assert set(doc.frontmatter) <= allowed, rel else: doc.validate() @@ -419,6 +426,23 @@ def test_2_2_every_line_break_is_quoted(world: World) -> None: assert doc.frontmatter["description"] == text +def test_strings_yaml_1_2_reads_as_numbers_are_quoted(world: World) -> None: + """OKF reads frontmatter by YAML 1.2's core schema (§4); PyYAML's 1.1 rules would write these plain.""" + world.edit( + "elements/character/the-consul--*.json", + lambda b: b.update(name="1e5", supertype="0o17", subtype="1.5e3", description="+.5"), + ) + code, err = world.run() + assert code == 0, err + path = next(world.out.glob("character/1e5--*.md")) + text = path.read_text(encoding="utf-8") + for line in ("title: '1e5'", "supertype: '0o17'", "subtype: '1.5e3'", "description: '+.5'"): + assert f"\n{line}\n" in text, line + fm, _ = split(text) + assert (fm["title"], fm["supertype"], fm["subtype"], fm["description"]) == ("1e5", "0o17", "1.5e3", "+.5") + assert "\nid: " in text and "\nid: '" not in text # an ordinary string stays plain + + def test_2_3_unreadable_files_are_noted_and_skipped(world: World) -> None: chars = world.src / "elements" / "character" (chars / ".atlas-cache.json").write_text("[]", encoding="utf-8") From 1eae5355eb830467a3952986bd88a52b379a2a02 Mon Sep 17 00:00:00 2001 From: Titus Date: Fri, 27 Nov 2026 22:01:10 +0100 Subject: [PATCH 2/2] 0.158.0: ApiError.limit names the size limit a write passed, with three predicates keel will name the limit behind its three size refusals in a new envelope key, limit, a key of the API document's info.x-ow-limits; the code stays invalid_request. ApiError reads it as an open string and gains is_element_too_large, is_element_too_many_links and is_extensions_too_large, as the npm SDK's 4.219.0. The wire test allows limit on the error envelope once the document declares it, and then requires it read and each predicate's name in info.x-ow-limits. Also the 0.158.0 entry for the OKF 0.3 export. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +++++++ src/onlyworlds/_version.py | 2 +- src/onlyworlds/errors.py | 32 ++++++++++++++++++++++++++++++++ tests/test_client.py | 34 ++++++++++++++++++++++++++++++++++ tests/test_wire.py | 18 +++++++++++++++--- 5 files changed, 89 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdf1db4..e115024 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.158.0 (2026-11-27) + +- **`ApiError.limit` names the size limit a write passed, and three predicates read it**: `is_element_too_large` (`element_bytes`), `is_element_too_many_links` (`element_link_ids`) and `is_extensions_too_large` (`extensions_bytes`). keel will add `limit` to these three 422 `invalid_request` refusals, a key of the API document's `info.x-ow-limits`, where the number and its unit are; the code, `param` and the sentence stay as they are. `limit` is an open string, so a value this release does not know is read and no predicate claims it. Until keel sends the key, `limit` is None and the predicates are False: read the sentence as before. As the npm SDK's `err.limit` (4.219.0). The wire test allows `limit` on the document's error envelope once it is declared, and then requires it read and each predicate's name to be a key of `info.x-ow-limits`. +- **`onlyworlds.okf` writes Open Knowledge Format 0.3.** The pin moves to the spec's version 0.3 (`OKF_COMMIT` 527e81a, 2026-11-18) in the repository where OKF now lives, `open-knowledge-format/open-knowledge-format` (`OKF_REPO`; the old address is marked deprecated, and the old pin still resolves there). The root `index.md` now says `okf_version: "0.3"` and carries the bundle metadata of the spec's §8.1: the world's name as `title`, and a `description` of the bundle in one sentence. Neither of 0.3's two breaking changes reaches what the exporter writes: it writes no path fields and no trust frontmatter. Its own frontmatter keys keep their OnlyWorlds names (0.3 advises an `x-` prefix, and a reader must accept keys it does not know), so a bundle reads as before. The keys an OnlyWorlds field would be renamed past (`ow_`) gain 0.3's `superseded_by` and `license`; no field has either name today. +- **A string YAML 1.2 would read as a number is quoted.** OKF reads frontmatter by YAML 1.2's core schema, and PyYAML's 1.1 rules wrote a name such as `1e5`, `0o17` or `1.5e3` plain, which a 1.2 reader takes for a number. Such a value is now written in single quotes; every other value is written as before. +- Held: OKF's reference parser and viewer at the new pin read the export (the `okf-reference` job), and its v0.3 validator, `skills/okf-generate/scripts/validate.py`, finds the bundle of the example world Hyperion conformant with `--strict`: 0 errors and 0 warnings, 36 notes that the keys carry no `x-` prefix. + ## 0.157.0 (2026-11-27) - **The Kanka door reads Kanka 4.0's exports.** A Character whose `entity.status_id` is 3, the `dead` row of the character statuses every Kanka campaign shares, gets `[Deceased] ` before `physicality`, as `is_dead` does; neither the 3.15 nor the 4.0 export writes `is_dead`. A campaign's own statuses are not in the export, so only the shared one reads as dead, and a `status_id` that is set is still kept as `x_kanka_status_id`. A family's `pivotMembers`, where 4.0 lists its people, is kept as `x_kanka_pivot_members` with its reason in the report, on any module. Races and families now read as proven on a real export, and the report names an export version other than 3.15 or 4.0. Exports of 3.15 come out as before. diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 317612e..fca4025 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.157.0" +__version__ = "0.158.0" diff --git a/src/onlyworlds/errors.py b/src/onlyworlds/errors.py index 7835f5d..1a380bd 100644 --- a/src/onlyworlds/errors.py +++ b/src/onlyworlds/errors.py @@ -280,6 +280,38 @@ def strings(value: Any) -> list[str]: "allowed_fields": strings(raw_error.get("allowed_fields")), } + @property + def limit(self) -> str | None: + """Which size limit a write passed, from the envelope's ``limit``: a key of the API + document's ``info.x-ow-limits``, where its number and unit are. Set on a 422 + ``invalid_request`` only, and only for the limits keel names this way (an element's size, its + links, its extension fields); a full world, a file too large or a request body too large keep + their own codes. An open string: more values may come. None for any other error, or when the + server sends none (as the npm SDK's ``err.limit``).""" + if self.status != 422: + return None + raw_error = _envelope(self.response.body).get("error") + value = raw_error.get("limit") if isinstance(raw_error, dict) else None + return value if isinstance(value, str) else None + + @property + def is_element_too_large(self) -> bool: + """A write would make the element larger than an element may be (422, ``limit`` + ``element_bytes``). Nothing is saved.""" + return self.limit == "element_bytes" + + @property + def is_element_too_many_links(self) -> bool: + """A write would give the element more link ids, across all its link fields, than it may + hold (422, ``limit`` ``element_link_ids``). Nothing is saved.""" + return self.limit == "element_link_ids" + + @property + def is_extensions_too_large(self) -> bool: + """A write would put an element's or the World's extension fields past their cap (422, + ``limit`` ``extensions_bytes``). Nothing is saved.""" + return self.limit == "extensions_bytes" + @property def is_busy(self) -> bool: """keel's admission control turned the request away (503 ``server_busy``); see ``retry_after``.""" diff --git a/tests/test_client.py b/tests/test_client.py index f02b330..cb8643f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -724,6 +724,40 @@ def test_resync_reason_reads_the_409_envelope() -> None: assert ApiError("POST", "bulk/", jresp(409, other)).resync_reason is None +def test_limit_names_the_size_limit_a_422_passed() -> None: + """keel's size refusals keep the code ``invalid_request`` and name their limit in ``limit``.""" + flags = { + "element_bytes": "is_element_too_large", + "element_link_ids": "is_element_too_many_links", + "extensions_bytes": "is_extensions_too_large", + } + for limit, flag in flags.items(): + body = { + "error": { + "type": "invalid_request", + "code": "invalid_request", + "message": "m", + "param": None, + "doc_url": "https://x/invalid_request", + "limit": limit, + } + } + e = ApiError("POST", "character/", jresp(422, body)) + assert (e.code, e.limit) == ("invalid_request", limit) + assert {f: getattr(e, f) for f in flags.values()} == {f: f == flag for f in flags.values()}, limit + # an open string: a value the package does not know is read, and no predicate claims it + later = {"error": {"type": "invalid_request", "code": "invalid_request", "limit": "element_fields"}} + unknown = ApiError("POST", "character/", jresp(422, later)) + assert unknown.limit == "element_fields" + assert not any(getattr(unknown, f) for f in flags.values()) + plain = ApiError("POST", "character/", env(422, "invalid_request", "invalid_request")) + assert (plain.limit, plain.is_element_too_large) == (None, False) + # never off a 422 + resync = {"error": {"type": "invalid_request", "code": "resync_required", "limit": "element_bytes"}} + off = ApiError("GET", "changes/", jresp(409, resync)) + assert (off.limit, off.is_element_too_large) == (None, False) + + def test_retry_after_is_strict() -> None: assert parse_retry_after("5") == 5.0 and parse_retry_after(" 30 ") == 30.0 for bad in ["1.5", "-1", "+5", "5.0", "soon", "", None]: diff --git a/tests/test_wire.py b/tests/test_wire.py index 015751f..62e15eb 100644 --- a/tests/test_wire.py +++ b/tests/test_wire.py @@ -487,10 +487,10 @@ def test_every_key_of_the_error_envelope_reaches_apierror(doc: dict[str, Any]) - five = {"type", "code", "message", "param", "doc_url"} # With the hidden mark on, a 409 resync_required's envelope also carries `reason`; an AI use's # 422 answer_not_parsed carries `refusals`; a 422 on a read's `fields` list carries - # `unknown_fields`, `types_with_field` and `allowed_fields`. Each is allowed only when declared, - # and then read. + # `unknown_fields`, `types_with_field` and `allowed_fields`; a 422 for a size limit carries + # `limit`, a key of info.x-ow-limits. Each is allowed only when declared, and then read. fields_keys = ("unknown_fields", "types_with_field", "allowed_fields") - assert set(err["properties"]) - five <= {"reason", "refusals", *fields_keys} + assert set(err["properties"]) - five <= {"reason", "refusals", "limit", *fields_keys} assert five <= set(err["properties"]) declared = [k for k in fields_keys if k in err["properties"]] if declared: @@ -545,6 +545,18 @@ def test_every_key_of_the_error_envelope_reaches_apierror(doc: dict[str, Any]) - } } assert ApiError("GET", "x", jresp(409, resync)).resync_reason == "role" + if "limit" in err["properties"]: + limits = doc["info"].get("x-ow-limits", {}) + flags = { + "element_bytes": "is_element_too_large", + "element_link_ids": "is_element_too_many_links", + "extensions_bytes": "is_extensions_too_large", + } + for name, flag in flags.items(): + assert name in limits, f"{name} is not a key of info.x-ow-limits" + sized = {"error": {"type": "invalid_request", "code": "invalid_request", "message": "m", "limit": name}} + sized_err = ApiError("POST", "x", jresp(422, sized)) + assert (sized_err.limit, getattr(sized_err, flag)) == (name, True), name first_type = err["properties"]["type"]["enum"][0] body = {"error": {"type": first_type, "code": "probe", "message": "m", "param": "p", "doc_url": "https://x/e"}} e = ApiError("GET", "x", jresp(422, body))