Metadata-Version: 2.4
Name: medre-adapter-matrix
Version: 0.1.0
Summary: matrix transport adapter for MEDRE
License-Expression: MIT
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: medre<0.2.0,>=0.1.0
Requires-Dist: mindroom-nio[e2e]==1.3.0
Provides-Extra: test
Requires-Dist: pytest==9.2.0; extra == "test"
Requires-Dist: pytest-asyncio==1.5.0; extra == "test"
Requires-Dist: pytest-timeout==2.4.0; extra == "test"
Requires-Dist: jsonschema==4.26.0; extra == "test"
Requires-Dist: packaging==26.3; extra == "test"
Provides-Extra: e2e
Requires-Dist: mindroom-nio[e2e]==1.3.0; extra == "e2e"
Dynamic: license-file

# medre-adapter-matrix

**Matrix provider for MEDRE.** This separately installed distribution owns its
transport SDK, configuration, native codec and offline fake. MEDRE core owns
routing, storage, lifecycle and delivery evidence.

## Install from Git

Use [uv](https://docs.astral.sh/uv/getting-started/installation/) and Git. For
a first trial, MEDRE can manage this provider in its persistent tool environment:

```bash
uv tool install 'git+https://github.com/jeremiah-k/medre.git@main'
medre adapters install matrix
medre adapters
```

Matrix requires Python 3.12+ and includes its durable SQLite/crypto backend.
The `matrix[e2e]` spelling remains a compatible installation alias.
The released mindroom-nio store requires POSIX file leases; Windows
production sessions require a provider release with Windows lease support.

On Windows, the package-changing command prints a uv command to run **after**
`medre.exe` exits, rather than replacing an executable still in use.
The `main` branch is useful for trials; pin exact core and adapter commits for
repeatable operation. Use the [MEDRE Getting Started guide](https://github.com/jeremiah-k/medre/blob/main/docs/ops/getting-started.md)
for fake smoke, guided route creation and native setup. Use the
[adapter-source guide](https://github.com/jeremiah-k/medre/blob/main/docs/ops/adapter-installation.md)
for a locked uv deployment project, private Git, local checkouts, index sources,
and the same-environment requirement. Neither MEDRE nor the provider installs
packages during runtime startup.

## Startup readiness

After authentication and configured room joins, startup waits up to
`initial_sync_timeout_seconds` (45 seconds by default) for the first acknowledged
sync. A pending long poll is logged as startup progress. Login alone never
establishes healthy readiness. On expiry, startup returns with degraded health
and the existing sync owner keeps recovering; a later acknowledgement publishes
healthy current state automatically. Native sync failure or reconnect exits
the wait immediately with its actual health.

Set the wait to `0` to report pending health immediately. The runtime's
`adapter_start_timeout_seconds` bounds the complete adapter start, including
login, joins, and this wait. Allow additional runtime budget for slow services;
its cancellation still closes the partially started session. See
[durable sync](docs/spec/durable-sync.md#startup-readiness) for the contract.

## Message presentation

Supported Matrix HTML maps to bounded canonical text spans when its visible text
matches the plain body. Outbound content escapes text and links and keeps relay
attribution outside source styles. Unsupported or inconsistent markup retains
plain presentation. See the [presentation contract](docs/spec/relay-attribution.md#text-presentation)
for reply, edit, truncation, and block-boundary behavior.

## Browser-approved Matrix login

For an OAuth-enabled homeserver, authorize MEDRE from your browser instead of
providing its account password. The provider includes the crypto backend;
select the adapter whose persistent device store should be prepared:

```bash
medre adapter matrix auth login --oauth \
  --user @relay:example.org --adapter-id matrix
medre adapter matrix auth status
```

Use the configured adapter key for `--adapter-id`. The command displays the
verification address and a short code. Approve only the login you initiated.
Homeserver discovery follows Matrix delegation; `--homeserver` can select an
explicit server. `--client-id` supports an existing public client registration
when dynamic registration is unavailable. Without `--adapter-id`, the command
only establishes credentials and does not load the E2EE SDK.

Keep credentials out of the runtime YAML so its missing authentication fields
resolve from MEDRE's credential sidecar. Runtime requests automatically renew
OAuth tokens, including SDK retry attempts. Repeating the login command resumes
the saved device session and retries signing instead of allocating another
device. Password options cannot be combined with `--oauth`.

The browser may request a separate signing-key approval. A matching account
identity is reused across devices; a missing local identity for an account that
already has signing keys requires restoring the original store. Deliberately
replacing lost or conflicting account keys requires `--reset-cross-signing`:

```bash
medre adapter matrix auth login --oauth --adapter-id matrix --reset-cross-signing
```

A reset can require other clients to verify the account identity again. It is
not part of routine login. Signing failures retain OAuth credentials and E2EE
state so setup can be retried. Own-device signing does not verify other users
or restore historical encrypted room keys.

Stop bridges using this account before changing sessions. To revoke a saved
password or OAuth session and then authenticate again, use:

```bash
medre adapter matrix auth logout
```

Logout preserves the crypto store and account-signing sidecar. Back them up
securely together. Password login remains available on supporting homeservers
through the existing interactive or `--password-stdin` commands.

## Packaging and provenance

This distribution registers the `medre.adapters` entry point and retains the
import namespace `medre.adapters.matrix`. Its original adapter source history
was extracted from MEDRE commit `e59c29dd31a95860d1cdbc19e531896616627a68`;
Git author and committer identities remain preserved. Runtime configuration and
adapter discovery do not depend on this repository's distribution name.

## Restart and offline messages

The SDK persists captured responses, crypto state, recovery and its upstream
cursor. MEDRE admits committed records before acknowledging their SDK batch.
Restart replays unacknowledged records through native-ID deduplication. History
provenance and recovery losses remain explicit; neither a saved cursor nor a
connected client establishes successful delivery.

Inbound events whose origin server timestamp predates the adapter's start by
more than `startup_backlog_suppress_seconds` (default 60 seconds, `0` disables)
are startup history and are suppressed on every delivery path — live sync,
durable catch-up, or gap recovery — using the same transport-neutral
`should_suppress_startup_backlog` policy the Meshtastic adapter applies. The
check precedes decode, so messages, reactions, and edits are equally covered,
and suppressed events count under `inbound_suppressed_stale` in diagnostics.
The window covers homeserver federation lag and minor clock drift so events
sent moments before startup still flow.

## Ownership and imports

This distribution owns Matrix's transport implementation, configuration models,
runtime wrapper, fake adapter, native addressing behavior, SDK requirements,
and protocol/SDK tests. MEDRE core owns generic events, routing, lifecycle,
storage, evidence, configuration orchestration, and installed-package discovery.

| Surface         | Adapter-owned import                                       |
| --------------- | ---------------------------------------------------------- |
| Config models   | `medre.config.adapters.matrix`                             |
| Runtime wrapper | `medre.config.adapters.matrix_runtime.MatrixRuntimeConfig` |
| SDK-free fake   | `medre.adapters.fakes.matrix.FakeMatrixAdapter`            |

Import the runtime wrapper from this distribution directly. Core has no named
wrapper compatibility bridge or transport SDK extras. The supported MEDRE
interface range and native SDK pins are declared in this project's
`pyproject.toml`; use a matching core revision during pre-release development.
Community adapter authors can use their own distribution names, import packages,
and hosting sources with the same `medre.adapters` entry-point contract.

MEDRE-authored adapter source is [MIT-licensed](LICENSE). This grant does
not relicense installed dependencies. Their license terms still apply to any
combined deployment or redistribution. See [dependency license notes](DEPENDENCY_LICENSES.md).

## Offline samples and diagnostics

This distribution contributes native fake values and an opaque conversation
address to `medre config sample`. Core includes only installed contributors;
a single contributor gets two fake instances for offline routing. Native
packet simulation methods remain adapter-specific. Run-session canonical
callback injection uses `AdapterContract.publish_inbound(event)`.

`medre adapters check --config bridge.yaml` distinguishes missing distributions
from broken/conflicting entry points. Basic CLI help and unrelated healthy
providers remain available when another provider fails discovery.

Matrix configures the core-owned `medre adapter matrix` parser. Optional CLI
registration failures are reported as `broken CLI contribution` without
disabling generic help, preflight, healthy commands, or runtime discovery.

Durable sync restores the SDK's persisted membership and encryption projection.
A fresh store obtains its initial state from the homeserver; existing stores keep
their device identity and pending batches. See the
[durable sync contract](docs/spec/durable-sync.md) for adoption and rollback limits.

Stopped-state maintenance derives this adapter's capture inventory from a
provider-owned declaration shipped in this distribution; the durable store and
token sidecar are declared honestly rather than guessed. See the
[stopped-state declaration contract](docs/spec/stopped-state.md).

Matrix event `content.medre` carries versioned canonical provenance and selected
metadata. `metadata_embedding_mode` is destination-specific: `off` omits the
MEDRE namespace, `minimal` carries event/actor identity, `safe` adds native
message references and normalized metadata, and `full` also includes provider
native and custom metadata. Full mode exports those details deliberately;
configuration and SDK objects are never embedded.

Outbound Matrix content carries no legacy `meshtastic_*` fields; the embedded
MEDRE namespace is the only relay metadata surface, and selecting
`metadata_embedding_mode: off` yields content without it. Embedded provenance
is an untrusted relay hint, not delivery evidence or authorization to operate
on another message. The wire contract is
[matrix-embedded-metadata.schema.json](docs/schemas/matrix-embedded-metadata.schema.json).

## Tests

Protocol and SDK contract tests live in this repository with adapter-owned
helpers. Cross-adapter routing and lifecycle tests remain in MEDRE. Run the
following from this repository in a fresh virtual environment, with a matching
MEDRE checkout at any location. Set `MEDRE_CORE` to that checkout path.

```bash
# SDK-free fake tier: core dev supplies test tooling; skip this adapter's SDK deps.
python -m pip install -e "${MEDRE_CORE:?Set MEDRE_CORE to the core checkout}[dev]"
python -m pip install --no-deps -e .
python -m pytest -q

# Native SDK tier: this distribution supplies its own SDK pins.
python -m pip install -e '.[test,e2e]'
python -m pytest -v -m "matrix_sdk and not local_integration and not soak and not live and not hardware and not docker"
```

The default pytest selection excludes SDK, service, hardware, local integration,
and soak tiers. Installing SDKs afterward leaves the same environment SDK-enabled;
use a fresh environment for a new SDK-free proof.

## Fake smoke sources

The fake provides a synchronous `make_event(text=..., event_kind=...)` returning
a canonical event with its own adapter instance ID. After installing all
providers referenced by a fake bridge config, exercise a source with:

```bash
medre smoke --config bridge.yaml --source-adapter ADAPTER_ID --json
```

Use the configured instance ID, which may differ from the transport name. Each
normal smoke tests one source; inspect `source_candidates` and
`coverage_scope: single_source` in its report. Eligible sources must have started
and provide the helper. A pass requires delivery for every matched configured
route target, including targets unavailable after construction or startup.
Factory errors fail the smoke and trigger runtime cleanup. The result proves
fake direct-pipeline behavior; native callbacks and recipient delivery have
separate qualification tiers.

## Coordinated CI

The repository CI installs MEDRE core and this adapter. Its fake job omits
native SDK dependencies; its SDK job installs this distribution's declared pins.
CI resolves MEDRE `main` once per run by default. Keep the repository Actions variable
`MEDRE_CORE_REF` unset so pull-request checks retain that baseline. Qualify a
candidate pair with a one-run dispatch and a full core commit SHA:

```bash
gh workflow run test.yml --ref ADAPTER_BRANCH -f core_ref=FULL_CORE_COMMIT_SHA
gh workflow run test.yml --ref ADAPTER_BRANCH -f core_ref=FULL_CORE_COMMIT_SHA -f sdk_ref=FULL_SDK_COMMIT_SHA
```

Record both revisions with the result. The candidate run does not replace the
adapter PR's checks against core `main`. Follow the
[coordinated-change policy](https://github.com/jeremiah-k/medre/blob/main/docs/dev/coordinated-changes.md)
for dependency order and merged compatibility pins.

A manual `sdk_ref` selects a full commit from `jeremiah-k/mindroom-nio` for
installed-SDK jobs. The candidate is installed within the locked core constraints;
its package version must satisfy the adapter's declared dependency. CI checks
package consistency and installed-source provenance, and records the exact SDK
commit. Default jobs retain the released SDK pin. Candidate-source runs qualify
an experiment; they do not change deployment dependencies or compatibility pins.

Core's compatibility matrix tests each selected adapter at the exact commit
recorded in its manifest, along with cross-adapter behavior. In a coordinated
checkout containing the selected sibling repos, run from MEDRE:

```bash
python scripts/ci/adapter_matrix.py --check-local
# Once all adapter changes are committed:
python scripts/ci/adapter_matrix.py --sync-local
```

The helper validates clean sibling checkouts and their entry points, and compares
Python distribution names using normalized case/separator spelling. Synchronizing
updates the manifest atomically without fetching or installing packages. Review
the manifest diff, merge adapter commits into their default branches first, then publish
the core pin update and run `python scripts/ci/adapter_matrix.py --check-merged`. A failed write preserves the original manifest and cleans up the temporary
file. Deployment projects should separately lock their chosen complete
package graph.

Standalone CI records the exact core and adapter SHAs tested against its
configured core baseline. MEDRE core CI qualifies the pinned compatibility
pair; a standalone green result does not qualify another core revision.
SDK qualification extras come from the selected core compatibility manifest,
while SDK versions remain authoritative in this adapter's package metadata.

## Provider contract and quality

The [registration reference](https://github.com/jeremiah-k/medre/blob/main/docs/dev/adapter-registration.md)
documents every hook, its loading phase, and the minimal fake constructor/event
calls. Shared native-metadata helpers are public under `medre.adapters.metadata`.
Conformance tests use `medre.testing`; SDK pin checks read this distribution's
installed metadata while this repository chooses its SDK qualification extras.
The fake constructor and explicit-keyword event factory are checked in the
SDK-free tier. Native schemas and validated examples live in `docs/schemas` here.

This repository declares its own Ruff/Black policy. CI checks all Python source
and tests, plus commit whitespace, alongside the fake/native qualification tiers.
The native adapter package includes its own `py.typed` marker.

## Default relay attribution

Matrix output defaults to `[sender/origin]: message`, preserving the full sender
name. An absent origin renders `[sender]: message`. Set `relay_prefix: ""` to
disable attribution or supply a custom generic template. Omitted/null selects
the automatic policy; MMRelay wire metadata keeps the original unprefixed text.

## Device verification

E2EE setup uses the adapter's persistent store and checks its own device's
server-visible signing chain. A fresh device uploads its keys before reusing
the account signing identity; ordinary login does not require rotating that
identity. Keep the E2EE store when renewing credentials. A cross-signing reset
replaces account identity material and can require verification in other clients.

## Peer-device verification policy

`verification_policy` is an optional peer-device **send authorization** gate.
The `permissive` default sends encrypted messages without scanning the local
peer-device trust store or emitting trust-gap warnings. This is normal bridge
operation for trusted rooms, not a trust verdict or a delivery receipt.
Own-device cross-signing is handled independently during identity setup and
runtime verification and does not establish trust in other users' devices.

Operators may explicitly select `strict`: then encrypted sends require an
affirmative local nio trust view for every recipient device, complete room
membership, and SDK enforcement with `ignore_unverified_devices=False`.
Unknown/unverified peers cause a retryable, pre-handoff refusal. MEDRE does
not currently offer an operator peer-verification workflow, and verification
performed in a different Matrix client does not automatically populate
MEDRE's local device store. Do not enable `strict` unless local peer trust
can be established independently. No automatic verification or plaintext
downgrade occurs.

The policy applies only to encrypted sends — crypto active and the room
affirmatively encrypted. Plaintext delivery, ephemeral typing, and redactions
are outside its scope. For the opt-in gate, a recipient missing from the
local device store counts as a trust gap. The default does not inspect that
store. The adapter's own current device is handled by cross-signing, not
peer-device authorization.

Pre-release decision note: `permissive` is the default for compatibility, and
`strict` is NOT scheduled to become the default until a separate,
independently qualified peer-verification workflow exists. Flipping that
default is a deliberate, separately reviewed change; do not rely on the
current default for assurance.

Neither mode proves delivery. A refused send is never delivered, but an
encrypted send that passes the policy — even to fully verified devices — is
only homeserver acceptance of the Megolm ciphertext. It is not a delivery
receipt: nobody can observe from the send whether a peer device received,
decrypted, or read the message.

## Transient typing

Routes can explicitly opt in with `forward_typing: true` when both endpoints
support typing and map concrete conversations. The adapter projects Matrix's
complete ephemeral user lists into core actor leases, excludes its own relay
user, and sends the aggregate indicator as the configured relay account.

Typing is separate from message encryption and discloses activity even in
encrypted rooms. The same configured-room, joined-room and encryption-safety
guards apply to outbound requests. Indicators use finite native timeouts and
best-effort clears; they create no canonical event, outbox row or receipt.
Unchanged composition can expire after core's 30-second freshness bound unless
another native observation arrives. Message forwarding alone does not opt in. The [typing contract](docs/spec/transient-typing.md)
defines native scope and live-sync behavior.

## Encryption readiness

Install the Matrix provider with its declared dependencies. The durable SDK
requires its SQLite crypto backend even with encryption_mode: plaintext;
plaintext policy continues refusing encrypted-room delivery. Missing backend
dependencies fail production startup instead of silently selecting ordinary sync.

Encryption readiness and own-device cross-signing are separate diagnostics.
Installing dependencies or authenticating does not recover lost account signing
keys. Runtime never resets that identity. To inspect the actual selected store:

```bash
medre adapter matrix auth status --adapter-id matrix --config ~/medre/bridge.yaml
```

If a signing file exists but cannot be read, check ownership/read permissions
first. Preserve a private backup before manually moving a confirmed unusable
file aside; import refuses replacement. Rerun status after the destination is
absent. SDK/path inspection failures require diagnosis before assuming keys are
missing.

If the signing file is missing, stop the bridge and locate an existing SDK
account-signing JSON for the same Matrix account (for example in an MMRelay
store or a backup). Do not copy tokens or device databases between applications.
Validate and import that backup using the existing MEDRE credentials:

```bash
medre adapter matrix auth restore-signing --adapter-id matrix \
  --config ~/medre/bridge.yaml \
  --from ~/.mmrelay/matrix/store/@bot:example.com_cross_signing.json
```

The command verifies the token's account/device and matches the backup's keys
against the existing server identity before writing anything. Publication
requires an absent destination and filesystem hard-link support; an existing
file is never replaced. The source backup remains unchanged. A post-publication
filesystem error can leave the complete file present: inspect status before
retrying. Restart the bridge to sign its own device using the restored keys.
A readable local file alone does not prove server/device verification. Import
restores account-signing keys, not historical encrypted-room message keys.

Ordinary login preserves account signing keys and cannot reconstruct missing
private material. Only when no matching backup exists should an operator
consider authenticated login with --reset-cross-signing; it replaces the account
identity and requires verification again in other clients. Stop the running
bridge before using `medre diagnostics --refresh-health`, which opens adapters.

The opt-in `test_matrix_durable_runtime_live.py` proof takes explicit local
homeserver accounts through environment variables. It runs the real MEDRE
runtime with durable storage and a fake destination across a restart, and
fails when native ingress fails. `MATRIX_ENCRYPTED=1` selects genuine Megolm
traffic; use fresh account/device stores for each independent run. The core
Synapse Docker starter can provision the isolated accounts.
