Metadata-Version: 2.5
Name: golded-ftn-msg
Version: 1.4.0
Summary: Reader and writer for explicit FTSC and Opus 190-byte MSG areas
Project-URL: Repository, https://github.com/golded-dev/golded-ftn-msg-python
Project-URL: Issues, https://github.com/golded-dev/golded-ftn-msg-python/issues
Project-URL: Changelog, https://github.com/golded-dev/golded-ftn-msg-python/blob/main/CHANGELOG.md
Author: GoldED.dev contributors
License-Expression: MIT
License-File: LICENSE
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: golded-ftn<2,>=1.4.0
Description-Content-Type: text/markdown

# golded-ftn-msg

Repository: [`golded-ftn-msg-python`](https://github.com/golded-dev/golded-ftn-msg-python).
The distribution remains `golded-ftn-msg`; imports use `golded_ftn_msg`.
The source is public on GitHub. [Version 1.4.0 is available on PyPI](https://pypi.org/project/golded-ftn-msg/1.4.0/).

Install with Python 3.12 or newer:

```sh
python -m pip install golded-ftn-msg==1.4.0
```

Read and write explicit FTSC and Opus `.MSG` areas with a 190-byte header.
New messages default to `N.MSG`. Pass `MsgWriterOptions(extension_case="lower")`
to create `N.msg` instead. Open and read already use the casing that is on disk;
two files with the same number and different casings are still rejected.
Python 3.12 or newer. MIT licensed.

The public API exports `MsgReader`, `MsgWriter` and `MsgSession`. Message values, options and
protocols come from `golded-ftn>=1.4.0,<2`.

```python
from pathlib import Path

from golded_ftn import MessagePatch, OutgoingMessage
from golded_ftn_msg import MsgReader, MsgWriter

area = Path("messages")
writer = MsgWriter()
writer.create(area)
with writer.open(area) as session:
    added = session.append(
        OutgoingMessage(
            from_name="Alice", to_name="Bob", subject="Hello", body_text="First line"
        )
    )
    current = session.read(added.identity.msgno)
    session.update(current.identity, MessagePatch(subject="Revised"), current.revision)
assert list(MsgReader().read(area))[-1].subject == "Revised"
```

## Installation

For local development, keep the two repositories beside each other:

```text
golded-dev/
  golded-ftn-python/
  golded-ftn-msg-python/
```

```sh
cd golded-ftn-msg-python
uv sync --locked
uv run pytest
```

Development uses built dependency wheels, with no local source overrides. Wheel and sdist dependency
metadata contains the version constraint only. To install local built wheels:

```sh
uv build ../golded-ftn-python --out-dir /tmp/golded-wheels
uv build --out-dir /tmp/golded-wheels
uv pip install /tmp/golded-wheels/*.whl
```

## Behaviour and limits

`MsgReader(header_format="ftsc")` is the default. Use `MsgReader("opus")`
explicitly for Opus areas; there is no automatic header detection. Opus bytes
176–183 contain DOS written/arrived timestamps rather than zone/point words.
The written timestamp supplies a naive date with two-second precision, using
1980–2107; zero or invalid written timestamps fall back to the textual date.
Addresses use header net/node plus INTL/FMPT/TOPT, without treating timestamp
bits as address metadata. Opus provenance uses `source_type="opus"`; FTSC
provenance remains `"msg"`. Use `MsgWriter().create(path, header_format="opus")` and
`MsgWriter().open(path, header_format="opus")` for Opus writing. Selection is
explicit on each operation; it does not detect or convert an existing variant.
`write(..., header_format="opus")` uses the same selection.

New Opus `posted_at` values must be naive, 1980–2069, without microseconds and
with even seconds. The DOS fields can encode 1980–2107, but the textual MSG date
and GoldED's read path impose the narrower writer range. Odd seconds are rejected,
not rounded. None writes zero DOS written words and an empty textual date.
New arrived words are zero because `OutgoingMessage` has no arrival date field.
Updates preserve arrived words and unknown header bytes; only a posted_at patch
changes written words and textual date. Existing invalid/zero written words retain
the reader's textual fallback. Zones/points use INTL/FMPT/TOPT. A nonzero zone
requires both addresses or a consistent INTL declaration; incomplete representation
is rejected before mutation. The candidate GoldED profile is described below.

The reader accepts positive numeric filenames with case-insensitive `.msg`
extensions. It sorts numerically and rejects duplicate message numbers. By
default it streams one file at a time; pass `ReaderOptions(eager=True)` to parse
every message before yielding. Filesystem errors identify missing or invalid
area paths. Malformed message files raise `ParserException` with the file path
and original cause.

Text decoding is strict, using the core charset helpers and CP850 fallback.
Kludges remain in the normalized body; mojibake is never repaired automatically.
Dates use English month names and the 1970–2069 two-digit year window. Invalid
reader dates become `None`. Header addresses and INTL/FMPT/TOPT must agree.
Provenance records the actual file path and message number; offsets are unknown.

`MsgWriter.create(path)` initializes a new area. A context-managed `open(path)`
session provides `read`, `append`, `update` and `delete`. Updates and deletes
require the revision returned by a consistent session read. Unrelated message
changes do not invalidate that revision. Unknown header bytes and controls survive
updates; attribute-only updates preserve the original text bytes. The revision
contains format/base/message identity, the physical filename number and SHA-256
over the raw file. Omitted patch fields stay unchanged; explicit `None` clears
only representable optional values. `control_lines` replaces general controls;
omitted MSGID, addresses and routing retain their structured fields. Body-only
changes preserve controls and routing. Conflicting metadata is rejected.

Appends publish a complete temporary file without replacing an existing number.
The next number is the first free integer after the highest existing numeric
`.msg` / `.MSG` name. Updates replace the complete file; deletes remove it.
Each operation rolls back I/O failures where possible; a failed rollback
poisons the session. The legacy `write` convenience method returns the number
of completed appends. Earlier operations remain committed if a later one fails.

## GoldED compatibility profile

Candidate interoperability is bounded to GoldED source commit `d7449053bd674df54c4a442c92dce8c06ad7b586`,
version 3.1.0, native macOS arm64/GCC 16 and Ubuntu 24.04 aarch64/GCC 13.
The suite release manifest pins the resulting binaries and records actual checks.
Other GoldED versions, Windows and network filesystems are not qualified.

Writers default to offline operation. Explicit `concurrent=True` opts into the
tested read/write/refresh/lastread/stale-save profile, not a general multiwriter
guarantee. Standalone readers still need a stable base; a session read uses its
format lock. MSG/Opus and Goldbase have no shared GoldED writer lock: stale-save
detection cannot close a race between comparison and a foreign write. Keep
same-message edits serialized. Goldbase is outside the Python C1 profile.

Use format-specific WriterOptions extension_case="lower" for newly created
Unix bases used by GoldED; preserve existing casing and reject ambiguous twins.
Hudson scan queues belong in the configured system directory. Recovery sessions
have a durable journal protocol; ordinary open() sessions only roll back handled
I/O failures. UNKNOWN outcomes retain artifacts for operator reconciliation.

Header names allow 35 encoded bytes; subjects allow 71. Encoding is strict.
Header fields reject nulls and line breaks. Dates must be naive, have no
microseconds, and fall within 1970–2069. Address components and attributes must
fit unsigned 16-bit fields. Domain addresses are unsupported.

The writer preserves body kludges, quoting and routing, and adds missing declared
control lines, charset and address kludges. Conflicting metadata is rejected.
An external MSGID may be supplied; synthetic hash IDs cannot become MSGID.
MSGID is never generated automatically. Provenance is not serialized. Body lines
use CR and end with one null byte.

## Development

```sh
uv sync --locked
uv run pytest
uv run ruff check .
uv run ruff format --check .
uv run mypy
uv run python -m mypy.stubtest golded_ftn_msg
uv build
uv run twine check dist/*
uv run python scripts/verify_distribution.py
```

See [writer source notes](docs/writer-sources.md) for the original GoldED layout,
locking limits and the distinction between source evidence and build tests.

## Archive mode

Strict reading remains the default. For damaged archives, opt in explicitly:

```python
from golded_ftn import ReaderIssue, ReaderOptions
from golded_ftn_msg import MsgReader

issues: list[ReaderIssue] = []
options = ReaderOptions(archive_mode=True, on_issue=issues.append)
# Replace "messages" with the actual archive directory.
messages = list(MsgReader("opus").read("messages", options))
```

Archive mode requires a callback. It skips malformed message files with a
`record_parse_error` issue and continues to later files. If declared ASCII cannot
decode a message, it tries the configured fallback strictly and reports
`ascii_decode_fallback` after successful parsing. Invalid UTF-8 and address
conflicts are skipped, never repaired. Original charset controls remain unchanged.
Duplicate numeric filenames make identity ambiguous: the reader reports
`duplicate_message_number` with action `stopped` before reading any messages.
Callback exceptions propagate. `ReaderIssue` carries the source identity, action,
code and a description without message contents. Recovery includes the failed
ASCII byte offset; record errors without a known location use `None`.

This package does not discover areas, provide a database, or integrate with Nornir.

See [CONTRIBUTING.md](CONTRIBUTING.md), [SECURITY.md](SECURITY.md), and the
[release checklist](docs/release.md).

## Candidate 1.4.0

Add recoverable FTSC/Opus sessions and existing-case filename handling. Remove the private numbering sidecar; use the qualified GoldED locking profile. Preserve stale-revision checks and offline defaults.

Linux and macOS, Python 3.12–3.14, are the release targets. Windows is outside
this candidate's test and compatibility promises. See [release preparation](docs/release.md).
