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
20 changes: 17 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ consumer in `src/study_builder/contract.py` must continue to verify:
- a supported header contract and `success: true` footer.

Never use a `utf8` convenience field as the authoritative value. Decode `base64`,
verify it, then create the public text projection. Unknown additive fields must be
verify it, then create the public text projection. Prefer the optional
`normalized_raw` and `normalized_stripped` byte envelopes from GetBible SWORD 0.4.0;
validate them as strict UTF-8 without reapplying the source encoding or stripping
U+FEFF. A nonnull normalized strip requires a nonnull normalized source. Continue
validating the legacy byte envelopes and projection availability even when they are
not used for display. Unknown additive fields must be
retained in the internal source record. Validated entries remain disk-backed and
writers stream them; do not restore whole-module entry or commentary collections in
memory. Composed documents are streamed from the documents they embed, never built
Expand Down Expand Up @@ -94,8 +99,17 @@ named `html`) is not guaranteed to be HTML; it can still contain source markup.
Never use that name to infer its format. These rules apply to dictionaries and
commentaries alike; shared projection changes need both resources' smoke builds.
Preserve source wording and scripts without per-entry replacements or language
filters. Every text is normalised the same way. Module bytes UTF-8 cannot read are
decoded as Windows-1252, never replaced. Public schemas and paths stay unchanged.
filters. Every text is normalised the same way. An explicit null normalized source
must not fall back to guessed decoding: retain its warning diagnostics, fail that
module's display projection, and continue independent modules. A null normalized
strip still permits source-aware rendering from valid normalized source. Never
substitute unsafe legacy render/strip output for these new projections. The previous
Windows-1252 compatibility decoder applies only to older streams omitting both
normalized fields. SWORD keys have their own index/verse encoding, independent of
the source body. Retain the existing key compatibility decoder for UTF-8/single-byte
modules so their IDs and URLs stay stable; do not apply SCSU or UTF-16 body decoding
to those keys. This does not relax normalized source-body decoding. Public
schemas and paths stay unchanged.

Dictionary Strong's keys remain compatible with Bible API v3 (`G3056`, `H0430`).
Repeated dictionary keys retain the unsuffixed direct path for their first
Expand Down
37 changes: 29 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ same sources every other GetBible service reads.

## Extraction dependency

`conf/getbiblesword.json` pins release `v0.1.1`, contract
`conf/getbiblesword.json` pins release `v0.4.0`, contract
`getbiblesword.ndjson/v1`, and the exact x86-64/ARM64 Linux asset names and
SHA-256 digests. On first use the builder:

Expand All @@ -46,7 +46,7 @@ SHA-256 digests. On first use the builder:
3. verifies it against the SHA-256 digest committed in the manifest;
4. safely extracts only `usr/bin/getbiblesword`;
5. checks the executable's reported version and contract;
6. caches it under `.work/tools/getbiblesword/0.1.1/`.
6. caches it under `.work/tools/getbiblesword/0.4.0/`.

The `getbible/getbiblesword` repository and its pinned release are public, so
installation requires no repository token or GitHub API request. The automated
Expand Down Expand Up @@ -99,13 +99,16 @@ and independently checks all of the rules that protect publication:
- `getbiblesword.ndjson/v1` header and extract command;
- canonical top-level member order and zero-based monotonic sequence values;
- base64 decoding, byte size, SHA-256, and matching UTF-8 convenience fields;
- strict UTF-8 in normalized projections and their source/strip relationship;
- legacy projection availability and byte envelopes, even when not selected for display;
- entry/configuration ordinals and module classification;
- artifact identifiers, chunk indexes, reconstructed size, and SHA-256;
- exact stream SHA-256 over every line before the footer, including LF;
- exact footer record/entry/artifact/byte counts and `success: true`.

Raw bytes remain authoritative. The adapter derives the public plain text only
after verification and retains the original contract records internally.
after verification and retains the original contract records internally, including
legacy projections, official attributes, annotation segments, and additive fields.
Validated entries are held in a compressed, disk-backed spool. Commentary entries
are then normalized into disk-backed chapter buckets, collapsed so that a comment
attached to a verse range is stored once rather than once per verse, and emitted in
Expand Down Expand Up @@ -324,12 +327,19 @@ clients that would otherwise read every word individually.

## Plain text

Every document is plain text. For ThML, TEI, and OSIS modules, the builder projects the
verified source markup into readable text. SWORD's stripped projections can discard
Every document is plain text. GetBible SWORD 0.4.0 supplies `normalized_raw`, source
markup strictly decoded to UTF-8, and `normalized_stripped`, SWORD's plain-text view
of that source. The builder verifies each byte envelope and reads these projections
as UTF-8 without reapplying the module's original encoding. The original source bytes
remain in the validated record.

For ThML, TEI, and OSIS modules, the builder projects the verified UTF-8 source markup
into readable text. SWORD's stripped projections can discard
line breaks and character references: a TEI `<lb/>` can disappear between words, and
a Greek letter written as `&#x03B1;` can be lost. The source-aware projections preserve
paragraphs, line breaks, senses, notes, reference labels, and Unicode characters for
both dictionaries and commentaries. Other source formats retain SWORD's stripped text.
both dictionaries and commentaries. Other source formats use the verified normalized
stripped text.

Character references are decoded once, when markup is read. Text that is already plain
is only whitespace-normalised, so literal ampersands and entity-like examples are not
Expand All @@ -344,8 +354,19 @@ space between words, no leading or trailing space on a line, and at most one bla
line between blocks. Standalone documents and the corresponding entries embedded in
complete downloads contain identical text.

Bytes the module wrote in Windows-1252 — the `’` of "David’s", the non-breaking space of
"1 Chronicles" — are read as such rather than replaced with `�`.
An explicitly unavailable `normalized_raw` is reported as a module failure after
stream verification; the builder preserves its diagnostics and continues independent
modules under the existing recovery policy. It does not guess another encoding.
If only `normalized_stripped` is unavailable, the source-aware readers can still
derive text from the intact source. Legacy render/strip output cannot override that
decision. Older v1 streams omitting both normalized fields retain the previous decoder
and its Windows-1252 compatibility behavior.

The extractor does not normalize SWORD index or verse keys. The builder retains its
existing key decoder for UTF-8 and single-byte modules, including legacy index bytes,
to preserve published dictionary IDs and URLs. SCSU and UTF-16 body encodings are not
applied to ASCII or UTF-8 lookup keys. This key compatibility rule does not affect the
strict normalized source-body decoding. The upgrade adds no public fields or API version.

## Scripture references

Expand Down
12 changes: 6 additions & 6 deletions conf/getbiblesword.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"repository": "getbible/getbiblesword",
"version": "0.1.1",
"tag": "v0.1.1",
"version": "0.4.0",
"tag": "v0.4.0",
"contract": "getbiblesword.ndjson/v1",
"assets": {
"linux-x86_64": {
"name": "getbiblesword-0.1.1-linux-x86_64.tar.gz",
"sha256": "ef8f698e77918be439a39973f6d3d2307951ec6054bee389f4f3ef0c148a063d"
"name": "getbiblesword-0.4.0-linux-x86_64.tar.gz",
"sha256": "58f8c1d1c0e23af0e121ce8ec192ab5d8d3da5fba9f832d7c678eceba5c7fbf5"
},
"linux-arm64": {
"name": "getbiblesword-0.1.1-linux-arm64.tar.gz",
"sha256": "e90ab9afd69ff7d6204cf93121bfa6a22bd97d6a312a1e2cdb400e5ae89c821b"
"name": "getbiblesword-0.4.0-linux-arm64.tar.gz",
"sha256": "03476d274f09638653cb770b304483b57fb49532499a37765cce89fed9c4e968"
}
}
}
8 changes: 8 additions & 0 deletions schemas/getbiblesword-ndjson-v1.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@
"properties": {
"type": { "const": "entry" },
"key": { "$ref": "#/$defs/byteValue" },
"normalized_raw": {
"description": "Optional UTF-8 source markup projection; null when the declared encoding cannot be decoded strictly. Never replaces authoritative raw bytes.",
"oneOf": [{ "$ref": "#/$defs/byteValue" }, { "type": "null" }]
},
"normalized_stripped": {
"description": "Optional SWORD stripText projection of normalized_raw, encoded in UTF-8; null when unavailable.",
"oneOf": [{ "$ref": "#/$defs/byteValue" }, { "type": "null" }]
},
"raw": { "$ref": "#/$defs/byteValue" }
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/study_builder/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,11 @@ class ContentProjectionError(ValueError):

def public_content(entry: dict[str, Any], *, source_type: str = "") -> dict[str, str]:
"""Project a validated contract entry onto the unchanged v1 text-only shape."""
if error := entry.get("_text_error"):
raise ContentProjectionError(
f"Entry {entry.get('key', 'unknown')!r} "
f"({source_type or 'unspecified SourceType'}): {error}"
)
projector = {"thml": thml_text, "tei": tei_text, "osis": osis_text}.get(
source_type.strip().casefold()
)
Expand Down
107 changes: 93 additions & 14 deletions src/study_builder/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,38 @@ def _text(value: Any, context: str, encoding: str = "") -> str:
return decode_module_text(decode_byte_value(value, context), encoding)


def _normalized_text(value: Any, context: str) -> str:
"""Validate an extractor UTF-8 projection without reapplying its source codec."""
payload = decode_byte_value(value, context)
try:
# A BOM in this projection is source content, not a decoding instruction.
return payload.decode("utf-8", errors="strict")
except UnicodeDecodeError as error:
raise ContractError(f"{context} must contain valid UTF-8") from error


def _normalized_entry_key(value: Any, context: str, encoding: str) -> str:
"""Read SWORD's index/verse key independently of the source-body encoding.

SWORD generates verse keys and uses UTF-8 dictionary key operations even when
the body is SCSU or UTF-16. The new extractor does not normalize keys, so keep
the existing key decoder for previously supported UTF-8/single-byte modules.
Real indexes such as Easton's contain legacy bytes despite declaring UTF-8;
changing their decoding would change existing dictionary IDs and URLs.
"""
payload = decode_byte_value(value, context)
declared = encoding.strip().casefold().replace("_", "-")
if declared in _UTF8_ENCODINGS | _SINGLE_BYTE_ENCODINGS:
return decode_module_text(payload, encoding)
try:
return payload.decode("utf-8", errors="strict")
except UnicodeDecodeError as error:
raise ContractError(
f"{context} is not a supported UTF-8 SWORD key; "
f"the source-body encoding {encoding!r} cannot be applied to index keys"
) from error


class GetBibleSwordContractReader:
def __init__(self, schema_path: Path, expected_contract: str) -> None:
schema = read_json(schema_path)
Expand Down Expand Up @@ -364,10 +396,64 @@ def _adapt_module(

@staticmethod
def _adapt_entry(record: dict[str, Any], sequence: int, encoding: str = "") -> dict[str, Any]:
key = _text(record["key"], f"record[{sequence}].key", encoding)
raw = _text(record["raw"], f"record[{sequence}].raw", encoding)
rendered = record.get("rendered_default")
stripped = record.get("stripped")
context = f"record[{sequence}]"
available = record.get("projections_available")
if not isinstance(available, bool):
raise ContractError(f"{context}.projections_available must be a boolean")
for name in ("rendered_default", "stripped"):
if name not in record:
raise ContractError(f"{context}.{name} is missing")
if available:
# Unused legacy projections must still satisfy the byte contract.
decode_byte_value(record[name], f"{context}.{name}")
elif record[name] is not None:
raise ContractError(
f"{context}.{name} must be null when projections are unavailable"
)
normalized = "normalized_raw" in record or "normalized_stripped" in record
text_error: dict[str, str] = {}
if normalized:
key = _normalized_entry_key(record["key"], f"{context}.key", encoding)
projections = {
name: (
_normalized_text(record[name], f"{context}.{name}")
if record.get(name) is not None
else None
)
for name in ("normalized_raw", "normalized_stripped")
}
raw = projections["normalized_raw"]
plain = projections["normalized_stripped"]
if plain is not None and raw is None:
raise ContractError(f"{context}.normalized_stripped requires normalized_raw")
if raw is None:
# Null is a declared decoding failure, not permission to guess a
# codec. Defer display failure until after complete verification
# so the pipeline retains the extractor's warning diagnostics.
text_error["_text_error"] = (
"entry.encoding.unavailable: the extractor could not decode the source "
f"using Encoding={encoding or 'Latin-1 (default)'!r}; "
"normalized_raw is unavailable and the original bytes are retained"
)
raw = raw or ""
plain = plain or ""
# Legacy render/strip results have no UTF-8 guarantee. Never let an
# unsafe fallback override an explicitly unavailable projection.
rendered = ""
else:
# Older NDJSON v1 streams may omit both optional projections.
key = _text(record["key"], f"{context}.key", encoding)
raw = _text(record["raw"], f"{context}.raw", encoding)
rendered = (
_text(record["rendered_default"], f"{context}.rendered_default", encoding)
if record.get("rendered_default") is not None
else ""
)
plain = (
_text(record["stripped"], f"{context}.stripped", encoding)
if record.get("stripped") is not None
else ""
)
scope = record.get("scope") or {}
verse: dict[str, Any] = {}
if scope.get("type") == "verse_key":
Expand All @@ -386,18 +472,11 @@ def _adapt_entry(record: dict[str, Any], sequence: int, encoding: str = "") -> d
# Historical internal name: rendered_default can still be source
# markup when the extractor has no display filter installed. Select
# the public projection using SourceType, never this field's name.
"html": (
_text(rendered, f"record[{sequence}].rendered_default", encoding)
if rendered is not None
else ""
),
"plain": (
_text(stripped, f"record[{sequence}].stripped", encoding)
if stripped is not None
else ""
),
"html": rendered,
"plain": plain,
"verse": verse,
"_getbiblesword": record,
**text_error,
}

@staticmethod
Expand Down
29 changes: 19 additions & 10 deletions tests/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,24 @@
from study_builder.engine import EngineManifest, GetBibleSwordManager


def test_manifest_pins_release_and_architectures(project_root: Path, monkeypatch) -> None:
@pytest.mark.parametrize(
("architecture", "sha256"),
[
("x86_64", "58f8c1d1c0e23af0e121ce8ec192ab5d8d3da5fba9f832d7c678eceba5c7fbf5"),
("arm64", "03476d274f09638653cb770b304483b57fb49532499a37765cce89fed9c4e968"),
],
)
def test_manifest_pins_release_and_architectures(
project_root: Path, monkeypatch, architecture: str, sha256: str
) -> None:
manifest = EngineManifest.load(project_root / "conf/getbiblesword.json")
assert manifest.version == "0.1.1"
assert manifest.tag == "v0.1.1"
assert manifest.version == "0.4.0"
assert manifest.tag == "v0.4.0"
monkeypatch.setattr("study_builder.engine.platform.system", lambda: "Linux")
monkeypatch.setattr("study_builder.engine.platform.machine", lambda: "x86_64")
monkeypatch.setattr("study_builder.engine.platform.machine", lambda: architecture)
asset = manifest.platform_asset()
assert asset.name == "getbiblesword-0.1.1-linux-x86_64.tar.gz"
assert asset.sha256 == "ef8f698e77918be439a39973f6d3d2307951ec6054bee389f4f3ef0c148a063d"
assert asset.name == f"getbiblesword-0.4.0-linux-{architecture}.tar.gz"
assert asset.sha256 == sha256


def test_release_asset_url_is_scoped_to_pinned_repository(
Expand All @@ -31,13 +40,13 @@ def test_release_asset_url_is_scoped_to_pinned_repository(
manager = GetBibleSwordManager(project_root / "conf/getbiblesword.json", tmp_path)
manager._validate_asset_url(
"https://github.com/getbible/getbiblesword/releases/download/"
"v0.1.1/getbiblesword-0.1.1-linux-x86_64.tar.gz",
"getbiblesword-0.1.1-linux-x86_64.tar.gz",
"v0.4.0/getbiblesword-0.4.0-linux-x86_64.tar.gz",
"getbiblesword-0.4.0-linux-x86_64.tar.gz",
)
with pytest.raises(RuntimeError, match="outside github.com"):
manager._validate_asset_url(
"https://example.com/archive.tar.gz",
"getbiblesword-0.1.1-linux-x86_64.tar.gz",
"getbiblesword-0.4.0-linux-x86_64.tar.gz",
)


Expand Down Expand Up @@ -72,7 +81,7 @@ def get_bytes(self, url, headers=None):
def download(self, url, target, expected_sha256=None, headers=None):
self.urls.append(url)
assert url.startswith(
"https://github.com/getbible/getbiblesword/releases/download/v0.1.1/"
"https://github.com/getbible/getbiblesword/releases/download/v0.4.0/"
)
assert "api.github.com" not in url
assert expected_sha256 == archive_sha256
Expand Down
Loading