Skip to content

refactor(airc-transport): split lan_tcp::adapter into module (one concern per file) - #680

Merged
joelteply merged 1 commit into
rust-rewritefrom
refactor/lan-tcp-adapter-module
May 19, 2026
Merged

joelteply merged 1 commit into
rust-rewritefrom
refactor/lan-tcp-adapter-module

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

`adapter.rs` was ~900 lines after multi-peer. Splits into 5 files, one concern per file (CBAR substrate doctrine):

File LOC What
`error.rs` 90 `LanTcpError` + `Display` / `Error` / `From` impls
`inner.rs` 63 `Inner` struct + `SubscriberHandle` + `OutboundTx` type + constants
`connection.rs` 166 per-connection lifecycle: `handle_`, `resolve_peer_from_`, `install_and_spawn_loops`, `read_loop`, `write_loop`
`dispatch.rs` 76 `dispatch_to_subscribers` + `subscription_matches_with_cursor`
`mod.rs` 507 (~250 of it tests) `LanTcpAdapter` struct + public `new` / `listen` / `connect` / `connected_peers` + `Transport` impl + integration tests

All internal items exposed to siblings via `pub(super)`. No public API changes.

Test plan

  • `cargo fmt -p airc-transport` — clean
  • `cargo clippy -p airc-transport --all-targets -- -D warnings` — clean
  • `cargo test -p airc-transport` — 35 pass / 0 fail (no regressions)

Targets `rust-rewrite` directly. One PR open at a time.

🤖 Generated with Claude Code

…cern per file)

adapter.rs was ~900 lines after the multi-peer changes. Splits into:

  * error.rs (90 LOC) — LanTcpError + Display/Error/From impls
  * inner.rs (63 LOC) — Inner struct + SubscriberHandle + OutboundTx
                       type + per-connection constants
  * connection.rs (166 LOC) — per-connection lifecycle: handle_*,
                              resolve_peer_from_*, install_and_spawn_loops,
                              read_loop, write_loop
  * dispatch.rs (76 LOC) — dispatch_to_subscribers +
                          subscription_matches_with_cursor
  * mod.rs (507 LOC, ~250 tests) — LanTcpAdapter public surface +
                                   Transport impl + integration tests

All-private internals exposed to siblings via `pub(super)`. No public
API changes; tests pass unchanged (35 tests in airc-transport).

Tests: 35 pass, clippy clean (-D warnings), fmt clean.

Targets rust-rewrite directly. One concern per file.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@joelteply
joelteply merged commit f6f097b into rust-rewrite May 19, 2026
1 check passed
@joelteply
joelteply deleted the refactor/lan-tcp-adapter-module branch May 19, 2026 02:33
joelteply added a commit that referenced this pull request May 19, 2026
… hell (#684)

* feat(airc-blobs): Phase 1 scaffold — ContentAddressedStore trait + ContentHash + MediaRef (#653)

First slice of #652 Phase 1 (airc-rust substrate). Adds the
`airc-blobs` workspace member: trait + types layer for content-addressed
blob storage. Frame bodies stay small on the wire; large bodies (audio
segments, images, file attachments, model weights) live in the blob
store and frames carry `MediaRef` pointers.

## Scope (PR-1)

- `crates/airc-blobs/` workspace member
- `ContentHash` newtype around SHA-256 — wire format is 64-char
  lowercase hex (matches sha256sum / openssl dgst -sha256 output).
  Newtype catches "passed bytes where hash expected" mistakes a bare
  `[u8; 32]` would miss.
- `MediaRef { hash, size_bytes, mime? }` — pointer type carried in
  frames. None mime serializes omitted (wire-efficient default for
  the common case).
- `BlobError` — typed: NotFound / HashMismatch / CapacityExceeded / Io.
  No silent failure paths; backends surface IO vs corruption vs
  not-found distinctly so callers can act differently per kind.
- `ContentAddressedStore` trait — put / get / exists / delete.
  `exists` has a default impl falling back to `get` so backends can
  override with a cheap presence-check.

## NOT in this PR (Phase 1 follow-ups per #652)

- Filesystem-backed `FsStore` (sha256-addressed paths)
- Chunked upload/download with resume
- Per-room encryption-at-rest
- GC + retention policy

Each ships independently against this trait. Encryption + chunking
compose as wrappers around any `ContentAddressedStore` impl without
trait changes.

## Discipline

- Content-addressed identity: SHA-256 of bytes is the only identity.
  Two identical uploads dedupe naturally; tamper-evident.
- All errors typed via `thiserror`. No silent fallthrough.
- Hex encoding (not base64): grep / `sha256sum` workflows just work.
- `exists` default impl correctness-preserved by InMemoryStore test;
  backends override for speed without breaking the contract.
- `delete` is idempotent — absent hash is Ok, not Err.

## Tests (16, all passing)

ContentHash (9): known SHA-256 test vectors ("hello world",
""), hex round-trip, length boundary rejection, non-hex rejection,
case-insensitive parsing (sha256sum vs openssl), Display lowercase,
serde JSON round-trip, invalid-hex deserialize error, PartialEq.

MediaRef (2): serde round-trip, None mime omission.

ContentAddressedStore via InMemoryStore (4): put-get round-trip,
exists default-impl matches get, delete idempotent (incl. double-delete),
BlobError Display includes hash context.

Sibling concern (1): blob_error_display_includes_context.

## Refs

- Parent: airc#652 (META tracking, Phase 1 foundation crates)
- Design: airc#651 (airc-rust substrate design)
- Branch target: `airc-rust` integration branch (not `main`)
- claude-tab-1 invited parallel claims on Phase 1 crates 2026-05-18 20:31Z;
  they're on airc-core, I'm on airc-blobs.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-blobs): FsStore — filesystem-backed sha256-addressed content store (#655)

Stacks on airc#653 (PR-1 scaffold). Adds the first concrete
ContentAddressedStore impl per #652 Phase 1 airc-blobs item 1
("filesystem-backed content store, sha256-addressed").

## What this ships

- `crates/airc-blobs/src/fs.rs` — `FsStore` struct + impl
- Path layout: `<root>/<aa>/<bbcc..>.blob` where `aa` is first 2 hex
  chars of the sha256 (256 fan-out dirs at top level, keeps inode
  counts manageable at scale). Standard sha256sum-style CDN layout —
  external tools (find, ls, rsync) just work.
- Atomic writes: `<final>.tmp.<pid>.<nanos>` sibling first, then
  `rename` atomically into place. A crash mid-write leaves the `.tmp`
  sibling, not a partial blob.
- `put` is idempotent: if the final path already exists, returns the
  hash without rewriting (dedupe-friendly + race-safe for concurrent
  writers).
- `get` re-verifies on-disk bytes against the claimed hash. Disk
  bitrot or external tampering surfaces as typed `HashMismatch`, not
  silent bad bytes.
- `exists` overrides the trait default with a cheap path check
  (skips reading the file).
- `delete` is idempotent — absent hash is `Ok`, not `Err`.
- All errors typed via `BlobError` (NotFound / HashMismatch / Io).
  No silent failure paths.

## Tests (12 new — full crate now 28 passing)

- new_creates_root_dir
- put_get_round_trip
- path_for_uses_two_char_fanout (pins on-disk layout vs sha256sum
  known-vector)
- put_is_idempotent_for_identical_bytes (dedupe path)
- get_missing_returns_not_found (distinct from Io errors)
- exists_reflects_storage_state (override path)
- delete_removes_blob
- delete_absent_is_idempotent (incl. double-delete)
- get_detects_corruption (on-disk tampering surfaces HashMismatch)
- empty_bytes_round_trip (boundary)
- large_blob_round_trip (1 MiB byte-pattern roundtrip)
- two_blobs_in_same_fanout_bucket_coexist (hash search for
  prefix-colliding inputs, verifies fan-out dir reuse)

## NOT in this PR (remaining Phase 1 airc-blobs items per #652)

- Chunked upload/download with resume
- Per-room encryption-at-rest (composes around FsStore as a wrapper)
- GC + retention policy

## Discipline

- Re-verification on every read costs O(n) CPU but catches bitrot
  + tampering. Caller can construct a "fast-path skip-verify" wrapper
  if it becomes a hot-path bottleneck; bias toward correctness here.
- Synchronous I/O for now (std::fs). Async fs::tokio wrapper is a
  follow-up that composes around any `ContentAddressedStore` impl
  via spawn_blocking.
- `path_for` is pure — testable without I/O. Layout pin test would
  catch any silent path-shape drift.

## Refs

- airc#653 — PR-1 scaffold (MERGED)
- airc#652 — Phase 1 META tracking
- claude-tab-1 parallel-claim invitation 2026-05-18 20:31Z

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-core): Identity struct + modular split (one concern per file) (#654)

* feat(airc-core): add Identity struct mirroring Python airc identity fields

PR-1 of the airc-core refactor stack per AIRC-RUST-SUBSTRATE.md +
the audit broadcast on #cambriantech.

The existing airc-core had bare newtype IDs (PeerId, ClientId, etc.)
but no Identity struct carrying the rich display fields the Python+bash
airc has been using: name, pronouns, role, bio, status, fingerprint,
integrations.

This commit ports the existing shape one-to-one — same six fields,
same defaults, same "/away" semantics, same UX-prompt heuristic
(is_complete = pronouns + role + bio all set). Per Joel's direction:
don't redesign, just port; we figured most of this out in the current
version.

API:
  - Identity::new(name) — fresh identity with all other fields default
  - Identity::is_complete() — UX heuristic for "should we nudge user
    to fill in pronouns/role/bio"
  - Identity::set_status(s) / .is_away() — IRC /away-style lifecycle
  - Serde derives — forward-compat (missing fields default to empty
    rather than fail deserialization)
  - integrations: BTreeMap<String, String> — consumer-registered
    cross-system identity binding (continuum persona ref, OpenClaw
    user id, GitHub login, etc.). airc never interprets values; just
    persists + transports. Deterministic key order via BTreeMap so
    serde encoding is stable across consumers.

Tests: 5 new cases:
  - new() sets name + defaults other fields
  - is_complete() requires pronouns + role + bio (mirrors Python heuristic)
  - away-status lifecycle including empty-string clears
  - serde round-trip with backward-compat (only-nick input deserializes)
  - integrations map handles multi-consumer namespacing without collision

9/9 airc-core tests pass total (4 existing + 5 new).

This is the first of ~7-8 small atomic PRs landing the audit gaps
called out on #cambriantech. Next up: Body enum (Json|Binary), then
EventFrame distinction, MediaRef split, Subscription, Control variants,
module split.

Targets `airc-rust` integration branch, not canary directly, per
Joel's branch-shape direction.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(airc-core): split lib.rs into per-concern modules

Per Joel's direction: "good modules, broken down into concerns / as
small a file as possible from the start / many files per module".

The previous lib.rs had grown to 490 LOC after the Identity addition.
Splitting it now (before more types land) so the small-file discipline
is baked in from the start of the airc-rust phase, not retrofitted
after the file balloons. CBAR substrate doctrine applied to airc-core
itself.

Module layout — one concern per file:

  - src/lib.rs        —  42 LOC, just module declarations + re-exports
  - src/ids.rs        —  50 LOC, newtype identifier wrappers
  - src/identity.rs   — 186 LOC, Identity struct + tests
  - src/transcript.rs —  92 LOC, TranscriptEvent + TranscriptKind + MentionTarget
  - src/cursor.rs     — 175 LOC, paging cursors + page_recent / page_before
  - src/receipt.rs    —  40 LOC, ReceiptKind + Receipt
  - src/attachment.rs —  72 LOC, AttachmentManifest
  - src/filter.rs     — 105 LOC, SelfFilter + filter_self_echoes

Largest module is identity.rs at 186 LOC (the most semantic surface);
median is ~92 LOC. All under the "thousands of lines" anti-pattern the
CBAR-substrate doctrine warns against.

Public API surface unchanged — every type that was previously at the
crate root is re-exported from lib.rs so `use airc_core::Identity;`
keeps working. Internal cross-module references use explicit module
paths (e.g. `crate::ids::PeerId`) so refactor visibility is preserved.

9/9 existing tests pass after the split. Tests move with their types
(Identity tests in identity.rs, paging tests in cursor.rs, filter tests
in filter.rs, attachment tests in attachment.rs).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-core): Body enum (Json | Binary) — opaque payload primitive (#656)

feat(airc-core): add Body enum (Json | Binary) — opaque payload primitive

PR-2 of the airc-core refactor stack. Replaces TranscriptEvent.body's
text-only `Option<String>` shape with a typed `Body` enum that supports
both JSON payloads and raw binary, per the audit broadcast and the
substrate design doc.

Why both variants:
  - Json(serde_json::Value) for the bulk of traffic — chat text wrapped
    as {"text": "..."}, typed events, RPC commands with correlation
    IDs, signaling envelopes, anything structured.
  - Binary(Vec<u8>) for consumers that need to avoid JSON overhead —
    game-state diffs at high tick rate, pre-encoded media frames,
    custom binary command formats, future fast-UDP consumers.

Tagged enum (`{"kind": "json", "value": ...}` / `{"kind": "binary",
"value": [...]}`) — both variants round-trip cleanly through any serde
format including JSON. Zero airc-rust users means we don't need legacy
bare-string backward-compat; the Python+bash airc keeps its own shape
until cutover, and airc-rust starts with the correct primitive.

TDD cadence (red-green visible):
  - Initially designed as untagged enum; test caught the "Binary array
    indistinguishable from Json(Array)" edge case at red phase
  - Pivoted to tagged enum based on Joel's "build correctly / zero
    users" directive — accepts the loss of legacy compat for protocol
    correctness
  - All 7 Body tests pass; full airc-core suite 16/16

Migration: TranscriptEvent.body changes from `Option<String>` to
`Option<Body>`. Test helpers in cursor.rs and filter.rs updated to use
`Body::text(...)` for plain chat strings.

Helpers on Body:
  - Body::text(s) — canonical chat shape (`Body::Json({"text": s})`)
  - body.as_text() — extract text from either canonical shape OR
    the legacy bare-string Json(String) form (forward-compat for
    future migration-bridge consumers)

Tests:
  - json_body_roundtrips_through_serde
  - binary_body_roundtrips_through_serde (was red under untagged; now green)
  - text_helper_constructs_canonical_chat_shape
  - as_text_returns_none_for_binary_body
  - as_text_returns_none_for_json_without_text_field
  - json_array_of_ints_stays_json_not_binary (edge case the tagged
    form makes unambiguous)
  - missing_kind_discriminator_is_a_parse_error (fail-loud, no silent
    default)

Stacks on `feat/airc-core-identity` (#654) — body.rs module added,
lib.rs re-exports updated, TranscriptEvent migrated.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-blobs): GC + retention policy — age-based + capacity-based (#660)

Stacks on airc#653 (scaffold) + airc#655 (FsStore). Adds the
remaining Phase 1 airc-blobs item per #652: "GC + retention policy".

## What this ships

- `crates/airc-blobs/src/gc.rs` — `RetentionPolicy` + `GcReport` +
  `gc::run` async-free walker
- `RetentionPolicy { max_age, max_bytes }` — both optional. Default
  is "report-only" (no deletions), useful for monitoring.
- `gc::run(root, policy)` — walks the FsStore layout, applies
  age-based deletion first, then capacity-based oldest-first
  deletion if total bytes still exceed `max_bytes`.
- `GcReport { scanned, deleted, bytes_freed, bytes_remaining }` —
  observability for operators.

## Discipline

- **Advisory, not reference-tracked.** GC trusts operator policy.
  Reference tracking (which blobs are live-referenced by frames /
  in-flight cache state) is a higher layer; this GC does NOT consult
  it. Operators set `max_age` long enough that anything still in
  flight has been delivered + acknowledged.
- **Race-resistant.** delete-of-absent is already Ok in FsStore;
  concurrent put + gc cannot corrupt state.
- **Ignores .tmp.* files.** FsStore writes go to .tmp siblings then
  rename. GC walks only `*.blob` files, skipping in-flight writes.
- **Capacity GC sorts by mtime ascending.** Oldest-first ensures
  the cap is satisfied with minimum churn (LRU-style).
- **Missing root is no-op, not error.** Store hasn't been used yet —
  not a failure state.

## Tests (7 new — full crate now 35 passing)

- gc_empty_store_is_noop
- gc_missing_root_is_noop
- gc_age_deletes_only_older_than_cutoff (mtime cutoff math)
- gc_capacity_deletes_oldest_first (LRU behavior)
- gc_capacity_stops_when_under_cap (no over-delete)
- gc_default_policy_is_report_only (monitoring use-case)
- gc_ignores_tmp_files (concurrent-put safety)

## NOT in this PR

- **Chunked upload/download with resume** — last remaining Phase 1
  airc-blobs item. Independent of GC; ships as a separate PR.
- **Per-room encryption-at-rest** — composes around any
  `ContentAddressedStore` impl as a wrapper.

## Refs

- airc#653 — PR-1 scaffold (MERGED)
- airc#655 — FsStore (MERGED)
- airc#652 — Phase 1 META tracking

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-core): convert ID newtypes from String to UUIDv4

PR-1 of the airc-core UUID migration per the substrate design doc's
"Identifiers — UUIDv4 everywhere" section. Locks the mesh-native
identifier discipline at compile time: every runtime ID is now a
typed UUIDv4 wrapper, not a bare String.

Changes:
  - Cargo.toml: add `uuid = { version = "1", features = ["v4", "serde"] }`
  - ids.rs: rewrite as macro-generated UUIDv4 newtypes —
    EventId(Uuid), RoomId(Uuid), PeerId(Uuid), ClientId(Uuid),
    FileId(Uuid). Each gets `::new()` (UUIDv4 random), `::from_u128()`
    (deterministic for tests), `::from_uuid()`, `::as_uuid()`,
    `Default`, `Display`.
  - ContentHash stays as `pub struct ContentHash(pub String)` —
    content addressing has different requirements (deterministic +
    payload-derived) than runtime ids; UUIDs would defeat both
    properties.
  - transcript.rs: `event_id.clone()` → `event_id` (now Copy)
  - cursor.rs + filter.rs: test helpers use `EventId::from_u128(N)`
    + named locals so assertions reference UUIDs directly instead
    of string literals.
  - attachment.rs: test uses deterministic UUID for FileId; serde
    assert updated to expect canonical hyphenated UUID string on
    the wire.

7 new ids.rs tests pin the contract:
  - new_event_id_is_random_uuidv4
  - from_u128_is_deterministic_for_tests
  - serde_roundtrips_via_hyphenated_string
  - display_uses_hyphenated_lowercase
  - malformed_uuid_string_fails_parse (fail-loud at envelope deserialize)
  - all_id_newtypes_share_the_uuidv4_contract
  - content_hash_is_not_uuid_typed (pins the discipline distinction)

Wire shape unchanged: serde encodes Uuid as canonical hyphenated
string, so JSON envelopes stay human-readable and cross-language
parsers work. Backward-compat with Python+bash airc envelopes that
happen to carry UUID-shaped strings already; non-UUID strings now
fail to parse (fail-loud over silent String coercion).

Full airc-core: 23/23 tests pass (was 16; +7 from ids.rs). Clippy
`--all-targets --all-features -- -D warnings`: 0 warnings. cargo
fmt --check: 0 diffs. Conforms to the rust.yml gates landing in #661.

Stacks on the rust-rewrite integration branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-core): envelope Headers dictionary + HeaderFilter predicate

Adds the HTTP-style headers primitive the substrate design doc calls
for, wired through TranscriptEvent so the substrate can route, filter,
retain, and diagnose without ever parsing consumer JSON.

  * crates/airc-core/src/headers.rs (new)
    - `pub type Headers = BTreeMap<String, String>` — deterministic
      ordering for stable diffs / cursors / replay records.
    - `HeaderFilter` enum: Any / Exact / Prefix / All / AnyOf — match
      predicate consumers can express for subscription fan-out without
      handing the substrate a closure.
  * TranscriptEvent: `pub headers: Headers` field with serde(default).
    Legacy events without headers deserialize cleanly to empty map.
  * Re-exports `Headers` and `HeaderFilter` at crate root so consumers
    say `use airc_core::Headers;` and don't need to know the split.
  * cursor + filter test helpers updated to set `headers: Default::default()`
    so the existing transcript-event fixtures keep compiling.

Namespace discipline (forge.*, openclaw.*, hermes.*, continuum.*, x-*)
is consumer-side convention — airc never interprets keys. The
`HeaderFilter::Prefix` variant lets the substrate route on namespaces
without becoming the namespace registry.

Tests: 25 pass, clippy clean (-D warnings), fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-protocol): wire-level envelope, Frame, signature, subscription, LiftPolicy

New crate `airc-protocol` — the substrate's protocol layer between
typed primitives (airc-core) and transport (airc-transport, coming
PR-2). Defines the contract every adapter speaks.

  * envelope.rs — Envelope + Frame + FrameKind {Message, Event, Control}.
    ChannelId alias for RoomId so cross-system docs (OpenClaw, Hermes,
    OpenCode) read clean without renaming the underlying type.
    Three-field identity model from PR #665 surfaces here as
    `sender: PeerId` (durable, mesh-stable) + `sender_client: ClientId`
    (per-tab/session disambiguation).

  * media.rs — MediaRef (file_id, content_hash, mime?, size?, caption?).
    REFERENCE-ONLY: blobs live in airc-blobs on disk. Wire envelope
    never inlines bytes. Per the `feedback_blobs_never_in_db` rule —
    previous incident inlined images in DB rows and killed systems;
    same discipline applies to wire messages.

  * signature.rs — Signature::{Ed25519, Unsigned} with policy-gated
    verification. Three security shapes pinned:
      - Unsigned + Strict → MissingSignature (no silent passes)
      - Ed25519 + unknown signer → UnknownSigner (fail-closed)
      - reply_to field/header mismatch → ReplyToMismatch (validated
        BEFORE signature check)
    AllowUnsigned policy is for dev / bring-up; Ed25519 frames are
    still verified against the registry even there. Per Joel's steer:
    no `verify() -> Ok(())` shortcut; production fails closed.
    Ed25519 byte-level crypto lands in PR-3 alongside key registry
    plumbing; PR-1 pins the contract.

  * canonical.rs — canonical_signed_bytes() via ciborium with
    deterministic CBOR + BTreeMap-sorted headers. Pinned by tests:
    same envelope → same bytes; signature field excluded (no chicken-
    and-egg); headers insertion order doesn't matter; field changes DO
    change bytes (sanity inverse).

  * headers_keys.rs — substrate-owned `airc.*` constants
    (HEADER_AIRC_TRACE_ID, _REPLY_TO, _PRIORITY, _DEADLINE) +
    HEADER_FORGE_BODY_HINT for the contract-hint convention. Adapters
    reference by symbol, not stringly.

  * subscription.rs — Subscription predicate (channel? + from_cursor? +
    kinds? + headers_filter). AND-composed, allocation-cheap, no
    closures (serde-friendly for cross-process forwarding). The
    fan-out hot path.

  * policy.rs — LiftPolicy trait + SizeThresholdPolicy (default 16 KiB),
    NeverLift, AlwaysLift. Per Joel's "abstract it" steer: the lift
    decision is a pluggable trait so any layer (bridge daemon, browser
    SDK, server, CLI) plugs its own. As an outside caller you can't
    tell whether a body was sent inline or via blob-ref — the
    substrate's transparent about it.

Adds dependency: ciborium 0.2 (canonical CBOR encoding).

Tests: 34 pass, clippy clean (-D warnings), fmt clean.

Stacked on feat/airc-core-headers (PR #666) because the envelope
imports airc_core::Headers. PR-2 (airc-transport trait + local-fs
adapter) lands on top of this.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-transport): Transport trait + LocalFsAdapter (same-Mac wire)

New crate `airc-transport` — the wire layer between airc-protocol
envelopes and bytes-on-disk-or-wire. First adapter: `LocalFsAdapter`,
which directly retires gh-polling for multi-agent same-Mac chat
(Codex / Claude Code / vHSM sessions all sharing one ~/.airc-style
directory). Substrate's goal is FAST + portable + AI-first: this is
the FAST half landing.

`Transport` trait — async, single contract every adapter (local-fs,
lan-tcp, tailscale, gh-gist-legacy) implements. Two methods only:

  * send(Frame) — durability depends on frame.kind
  * subscribe(Subscription) -> FrameStream — fan-out with lag policy

Delivery semantics formalized per Codex's feedback so the Codex bridge
can rely on them:

  * Message / Control: durable. fsync'd on send; receive-side
    backpressure (slow consumer slows the wire, no frames lost).
  * Event: interrupt-style. Written to disk WITHOUT fsync (visible to
    same-machine readers immediately, no crash-survival guarantee);
    receive-side lossy past per-subscriber buffer (drop on full,
    wire keeps moving). turn/steer, turn/interrupt, presence
    transitions, typing indicators ride this kind.

LocalFsAdapter — `<wire-dir>/frames.jsonl` append-only log:

  * Cross-process safety via `fs2::FileExt::lock_exclusive` (per
    Codex's review): the kernel-level flock serializes all writers
    regardless of frame size, replacing the prior O_APPEND-PIPE_BUF
    gamble. Critical section runs in spawn_blocking to avoid stalling
    the async runtime.
  * Durability branch on FrameKind: Messages/Control fsync, Events skip.
  * Reader: tokio-based byte-offset tail with 50ms poll. Partial
    in-flight lines are NOT consumed; re-read once the newline arrives.
  * Cursor replay: from_cursor=None means "live only" (skip to EOF on
    attach); Some(cursor) replays strictly-after that anchor.
  * Subscription fan-out: each subscriber gets its own mpsc; no
    cross-talk. Per-subscriber lag policy isolates slow consumers.

Tests: 10 pass, clippy clean (-D warnings), fmt clean.

  * send_then_subscribe_with_cursor_replays_frame — base round-trip
  * live_subscription_skips_past_frames — None cursor = live-only
  * subscription_channel_filter_routes_correctly — channel fan-out
  * two_subscribers_both_receive — fan-out parity
  * drop_stream_stops_tail_task — resource discipline
  * send_is_durable_when_returning_ok — durability contract
  * from_cursor_drops_frames_at_or_before_anchor — replay semantics
  * events_are_lossy_when_subscriber_lags — Codex's lag policy
  * messages_are_not_dropped_under_subscriber_lag — durability under load
  * flock_serializes_concurrent_in_process_senders — flock correctness

Stacked on feat/airc-protocol-envelope (PR #667). PR-3 (lan-tcp
adapter for same-LAN AI peers) lands next; once that's in we can
retire gh-polling as default.

Deps added: tokio (fs/io/rt/sync/time/macros), async-trait, futures,
fs2, tempfile (dev).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(airc-transport): tail_loop recovers from frames.jsonl truncation/recreation

Codex's #668 review finding: if a subscriber's offset has advanced
(e.g. it has been reading live frames) and then frames.jsonl is
truncated, recreated, or deleted under it, the loop's `len > offset`
check stays false until the new file grows past the old offset.
The subscriber silently misses every new frame in the interim — a
pure stall, no error surfaced.

Two recovery branches now in tail_loop:

  * `NotFound` on metadata: file deleted (logrotate, manual cleanup,
    teardown). Reset offset = 0 so when a writer recreates the file
    we read from the start instead of waiting for it to grow past
    the stale offset.

  * `len < offset` on metadata: file is shorter than our position —
    truncation or in-place recreation. Same recovery: offset = 0.

Two new tests pin both paths:

  * `truncation_recovers_offset_to_start` — subscribe live, advance
    offset, truncate the file, send a fresh frame; assert it is
    received within 2s.

  * `deletion_then_recreation_recovers_offset` — same shape but with
    `tokio::fs::remove_file`; assert recovery after the next send
    recreates the log.

Tests: 12 pass (was 10), clippy clean (-D warnings), fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-protocol): real Ed25519 signing + verify (closes PR-1 stub)

PR-1 shipped Signature::Ed25519 + the policy dispatcher but left
verify() as a stub that returned Ok(()) once the registry had a key.
This PR wires the actual ed25519-dalek byte-level verify + adds the
send side (PeerKeypair).

Per Codex's PR-3 steer (and Joel's "always go most-capable"):
  * no plaintext production paths
  * no silent-pass shortcuts
  * Strict policy fails closed on every failure mode
  * crypto choice = Ed25519 (sub-50µs verify, deterministic sign,
    standard ecosystem, fits the per-frame budget)

New module: crates/airc-protocol/src/keypair.rs

  * PeerKeypair::generate() — fresh random from OsRng
  * PeerKeypair::from_secret_bytes(&[u8;32]) — persistence restore
  * PeerKeypair::secret_bytes() / public_bytes() / verifying_key()
  * PeerKeypair::sign_envelope(envelope, signer, key_id) — produces
    Signature::Ed25519 over canonical_signed_bytes(envelope)
  * Debug impl redacts the secret (pinned by test)
  * Storage is in-memory only; persistence (SQLCipher, keychain,
    hardware enclave) is the integrator's responsibility — substrate
    just signs and verifies.

Wired in signature.rs:

  * PeerKeyRegistry storage changed from raw [u8;32] to parsed
    VerifyingKey — pre-validate once at enrol time so verify() in
    the hot path doesn't re-parse on every frame.
  * enrol() now returns Result<(), KeyError>; refuses invalid
    Ed25519 points (garbage / wrong-curve) at enrolment rather
    than at verify time.
  * verify() dispatches Signature::Ed25519 to a verify_ed25519
    helper: registry lookup -> canonical-encode -> ed25519_dalek
    Verifier::verify. Lookup miss = UnknownSigner; crypto mismatch
    = BadSignature.

Tests added (keypair.rs):

  * sign_then_verify_with_enrolled_key_passes_under_strict — base
  * tampered_envelope_after_signing_fails_bad_signature — body
  * tampered_lamport_fails_bad_signature — ordering field
  * tampered_headers_fail_bad_signature — header injection
  * tampered_reply_to_fails_bad_signature — threading field
  * wrong_pubkey_in_registry_fails_bad_signature — evil twin pubkey
  * unenrolled_signer_fails_unknown_signer — fail-closed empty registry
  * key_rotation_via_key_id_works — two keys per peer, both verify
  * keypair_secret_roundtrips_through_bytes — persistence contract
  * debug_redacts_secret — no secret in Debug output

The PR-1 stub test ("ed25519_with_registered_signer_passes_pr1_stub")
is rewritten as ed25519_with_garbage_signature_fails_bad_signature —
asserts that an all-zero signature against a real pubkey fails
BadSignature (the correct stronger contract now that crypto is wired).

Tests: 44 pass (was 34 in PR-1), clippy clean (-D warnings), fmt clean.

Deps added: ed25519-dalek = "2", rand = "0.8" (for OsRng::fill_bytes).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-transport): TLS peer-pinning infrastructure (cert gen + verifiers)

PR-3b of the substrate stack. Pins the cryptographic foundation for
the secure LAN transport (PR-3c lands the LanTcpAdapter itself).

Per Codex's review of the original PR-3 sketch + Joel's "always
go most-capable" steer: no plaintext path, no opt-in unsafe bind,
no PKI bridge. The substrate's PeerKeyRegistry IS the trust anchor.

New module: crates/airc-transport/src/lan_tcp/

  * cert.rs — bidirectional cert <-> Ed25519 pubkey bridge:
      - generate_self_signed_cert(keypair, peer_id) takes a substrate
        PeerKeypair and produces a (CertificateDer, PrivateKeyDer)
        pair via rcgen, with the substrate's Ed25519 SigningKey going
        through PKCS#8 DER as the round-trip format. The TLS cert's
        subject pubkey IS the substrate's Ed25519 pubkey by
        construction — peer-pinning becomes meaningful.
      - extract_ed25519_pubkey(cert_der) parses a received X.509
        cert, validates the SPKI algorithm is Ed25519 (OID
        1.3.101.112), and returns the 32-byte pubkey for registry
        lookup.

  * verifier.rs — rustls trait impls for peer-pinning:
      - PinnedServerVerifier (client-side) takes an expected_peer
        and the registry. Accepts the server cert iff its pubkey
        resolves (via find_peer) to the expected PeerId. Wrong peer
        / unknown pubkey / non-Ed25519 / malformed cert → reject.
      - PinnedClientVerifier (server-side) accepts any cert whose
        pubkey is enrolled in the registry for any peer. Caller
        binds the connection to the resolved PeerId post-handshake.
      - supported_verify_schemes() returns ONLY Ed25519 — no
        algorithm-downgrade surface.
      - verify_tls12_signature returns Err unconditionally —
        substrate is TLS 1.3 + Ed25519 only, no legacy path.

Modified: crates/airc-protocol/src/signature.rs

  * Adds PeerKeyRegistry::find_peer(pubkey) -> Option<(PeerId, u32)>
    so the server-side verifier can reverse-lookup a cert's pubkey
    to a peer identity. Pure-data helper; iteration order is
    non-deterministic but we only care about ANY-match presence.

Adapter pattern stays clean: Transport trait is the contract; gh-gist
(future), local-fs (PR-2), lan-tcp (PR-3c) all sit on top of it.
Dropping any one = deleting that adapter file. No coupling.

Tests: 24 pass (12 existing local-fs + 4 cert + 8 verifier), clippy
clean (-D warnings), fmt clean.

  * cert::tests::generated_cert_carries_the_keypair_pubkey
  * cert::tests::two_keypairs_produce_different_pubkeys_in_certs
  * cert::tests::malformed_cert_bytes_return_invalid_cert_error
  * cert::tests::cert_round_trips_through_der_bytes
  * verifier::tests::server_verifier_accepts_expected_peer_cert
  * verifier::tests::server_verifier_rejects_wrong_peer_cert
  * verifier::tests::server_verifier_rejects_unenrolled_cert
  * verifier::tests::server_verifier_rejects_malformed_cert
  * verifier::tests::client_verifier_accepts_any_enrolled_peer
  * verifier::tests::client_verifier_rejects_unenrolled_peer
  * verifier::tests::verifiers_only_accept_ed25519_scheme
  * verifier::tests::supported_schemes_helper_returns_only_ed25519

Deps added: rustls 0.23 (ring backend), tokio-rustls 0.26, rcgen 0.14
(ed25519 + pem features), rustls-pki-types 1, x509-parser 0.18,
ed25519-dalek pkcs8 feature.

NOTE: js-sys / wasm-bindgen appear in `cargo fetch` output as
transitive deps of `getrandom` and `ring` but are gated behind
cfg(target_arch = "wasm32") — they are NOT linked into native builds
(verified via cargo tree --target=x86_64-apple-darwin).

PR-3c (next) wires LanTcpAdapter using these verifiers — TLS 1.3
over TCP with mutual auth, manual listen/connect API, length-
prefixed JSON frames, FrameKind-aware delivery semantics inherited
from the Transport trait.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-transport): LanTcpAdapter — TLS-wrapped TCP with peer-pinned mTLS

PR-3c lands the Transport impl using PR-3b's cert+verifier
infrastructure. Two AI peers on the same LAN can now talk over
mutual-TLS-authenticated TCP with no plaintext path and no CA.

MVP scope:
  * Point-to-peer: one active connection per adapter
    (PR-3d expands to N-peer fan-out)
  * Multi-subscriber fan-out (one adapter, many subscribers)
  * Length-prefixed JSON frames (u32 BE prefix + payload)
  * Mutual TLS 1.3 via tls_config builders
  * Post-handshake peer identity bound from cert pubkey via
    PeerKeyRegistry::find_peer
  * FrameKind delivery split inherited from Transport trait:
    Message/Control durable+backpressure, Event lossy
  * Per-frame size cap (16MB) defends against hostile peers

New files: crates/airc-transport/src/lan_tcp/
  * tls_config.rs — build_server_config + build_client_config:
    composes the substrate's PeerKeypair (via PKCS#8 DER → rcgen)
    with the pinning verifiers from PR-3b into rustls Server/Client
    Configs. TLS 1.3 only. Ed25519 only.

  * adapter.rs — LanTcpAdapter:
      - LanTcpAdapter::new(self_peer_id, keypair, registry)
      - listen(bind_addr) spawns accept loop, accepts ONE peer
      - connect(addr, expected_peer) dials + completes mTLS
      - Transport::send broadcasts to the (single MVP) connection
      - Transport::subscribe registers a SubscriberHandle, returns
        a filtered FrameStream
      - Read loop dispatches to subscribers per kind-aware lag
        policy (same shape as local-fs)
      - Dead subscribers GCd by next dispatch pass

Refactor: error.rs

  * Removed the prior stub LanTcpError (DEV-PREVIEW shape from
    the pre-pivot plan). The real LanTcpError now lives in
    adapter.rs with the right variants:
      Io, Json, TlsConfig, TlsHandshake, PeerNotInRegistry,
      FrameTooLarge, NotConnected, AlreadyHasConnection.

Tests: 29 pass (12 local-fs + 12 cert/verifier + 2 tls_config + 3
adapter), clippy clean (-D warnings), fmt clean.

  * two_paired_peers_round_trip_a_message — full e2e: Alice
    listens, Bob dials, both enrolled. Bob receives Alice's
    Message frame via subscribe within 3s.

  * unenrolled_peer_cannot_handshake — stranger NOT in Alice's
    registry tries to connect; Alice's PinnedClientVerifier
    rejects; Alice's adapter never installs a connection;
    alice.send() returns NotConnected. Pins the security
    guarantee: TLS handshake rejection ⇒ zero frames flow.

  * send_without_connection_returns_not_connected — typed error
    before listen/connect.

Deferred to follow-ups (per Joel's "robustness next" cue):
  * Multi-peer concurrent connections (PR-3d)
  * Reconnect / retry
  * Per-frame Ed25519 signing wiring on the send path (sign as
    you serialize; the substrate's verify() is ready to receive
    signed frames since PR-3a)
  * mDNS / discovery (separate concern)

Stacked on feat/airc-transport-tls-pinning (PR #670).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-transport): SignedTransport<T> — per-frame Ed25519 sign + verify wrapper

Composition pattern: wrap any Transport with per-frame signing on
send + verification on receive. The substrate's identity (PR-3a's
PeerKeypair) finally rides on every wire. TLS gives channel
confidentiality; per-frame signing gives identity-bound,
replay-resistant, audit-able envelopes.

New: crates/airc-transport/src/signed.rs

  * SignedTransport<T: Transport> wraps any inner adapter.
  * send() canonical-encodes envelope, signs with the wrapper's
    PeerKeypair, sets Signature::Ed25519, delegates to inner.
  * subscribe() chains a `.then(verify)` onto the inner stream;
    frames that fail verify surface as SignedError::Verify with the
    underlying VerificationError variant.
  * SignedError<E> enum: Inner(E) | Sign(CanonicalError) |
    Verify(VerificationError).
  * with_key_id(u32) builder for rotation.

Tests do the talking. 4 new integration tests:

  * signed_local_fs_round_trips_a_signed_frame — Alice + Bob both
    wrap LocalFsAdapter on the same dir. Alice sends; Bob receives
    a frame whose Signature is Ed25519 (not Unsigned), signer = Alice.

  * unenrolled_signer_is_rejected_under_strict — Mallory holds her
    own keypair but is NOT in Alice/Bob's registry. Mallory signs
    + writes to the wire; Bob (Strict) sees the frame from the
    inner local-fs but verify() rejects with UnknownSigner.

  * unsigned_under_allow_unsigned_passes_through — dev escape
    hatch: AllowUnsigned policy accepts signed frames too.

  * tampered_frame_after_signing_is_rejected — the security
    crown jewel. Alice's signed frame is received cleanly. Then
    a tampered version (modified header, new lamport) is written
    directly to the wire by a raw LocalFsAdapter (simulating an
    attacker with wire access). Bob receives + verify() rejects
    with BadSignature.

Tests: 33 pass (29 prior + 4 SignedTransport), clippy clean
(-D warnings), fmt clean.

Wrapper is opt-in — adapters stay simple; integrators that want
authenticated frames compose SignedTransport over them. This is
the same Transport-trait pluggability Joel asked for re gh
adapters: every layer is swappable.

Stacked on feat/airc-transport-lan-tcp-adapter (PR #671).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): airc-rs binary — first Rust replacement for Python airc

New crate `airc-cli` with the binary `airc-rs`. Wires the substrate
into a real CLI so the Rust path is reachable from the command line.
Step 1 of the Python deletion: prove the substrate works without any
Python on either end.

Subcommands (MVP):
  * init — generate or load identity, print peer spec for sharing
  * send / listen — local-fs same-Mac chat (LocalFsAdapter wrapped
    in SignedTransport, Strict policy)
  * lan-send / lan-listen — secure LAN chat (LanTcpAdapter wrapped
    in SignedTransport, TLS 1.3 + Ed25519 peer-pinning)

Modules:
  * cli.rs — clap-derive argument parsing
  * identity.rs — load_or_generate(path) for the keypair file
    (32-byte secret, owner-only perms on Unix)
  * registry.rs — parse `--peer <uuid>:<base64-pubkey>` flags into
    a PeerKeyRegistry. format_peer_spec() prints the same shape for
    `init` to emit.
  * commands.rs — subcommand handlers; small + direct
  * main.rs — clap dispatch + crypto provider install

Identity store: MVP is plain 32-byte secret file. Documented as
inadequate for production (SQLCipher / OS keychain / hardware
enclave is the real plan); fine for cross-process e2e demos.

Pairing: MVP is manual `--peer` flags. Real pairing flow (QR / invite
URL / signed enrolment) comes later.

Live demo:

  $ airc-rs --identity-file /tmp/alice.key init
  peer_id:   07e7ad58-ba56-4535-b4e5-a161a110e487
  peer_spec: 07e7ad58-…:Wi-NZWat3kYD9MhQ7JqMEPZ7i_HKUD-xTi8IIMDF6BY

  # share peer_spec out-of-band, then:
  $ airc-rs --identity-file /tmp/bob.key \
      --peer-id <bob> --peer <alice-spec> \
      listen --wire /tmp/wire --replay

  $ airc-rs --identity-file /tmp/alice.key \
      --peer-id <alice> --peer <bob-spec> \
      send --wire /tmp/wire \
      --channel 00000000-0000-0000-0000-000000000001 \
      "hello"

Two terminals, no Python. Substrate handles signing, verification,
delivery, replay.

Tests: 8 unit tests pass (identity round-trip + registry parsing),
clippy clean (-D warnings), fmt clean, `airc-rs init` smoke-tested.

Deps added: clap 4 (derive + env), base64 0.22, rustls 0.23 (for
the one-time crypto-provider install at main()).

Stacked on feat/airc-transport-signed-wrapper (PR #672).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(airc-cli): e2e — two airc-rs subprocesses chat over the substrate

Spawns two real `airc-rs` subprocesses (Alice + Bob) and asserts
they exchange a message via the substrate. This is the proof:
the Rust path replaces Python end-to-end, no shortcuts.

Two tests:

  * two_airc_rs_processes_chat_over_local_fs — Alice runs
    `airc-rs listen --wire …`. Bob runs `airc-rs send --wire …
    "hello from bob over rust substrate"`. The literal message
    body must appear on Alice's stdout within 6s.

  * listen_rejects_unenrolled_signer — Mallory signs + writes
    to the shared wire but isn't in Alice's peer list. Alice's
    listen process surfaces "verification failed" on stderr;
    no message appears on stdout. Pins the security guarantee
    through the CLI surface.

The headline test exercises the full stack:
  identity load → registry build → LocalFsAdapter → SignedTransport
  (Ed25519 sign on send) → wire I/O → SignedTransport (verify on
  receive) → CLI stdout print.

If this test passes, `airc-rs` is a functional Python replacement
for chat.

Tests: workspace total 147 pass / 0 fail. CLI e2e adds 2.
clippy clean (-D warnings), fmt clean.

Stacked on feat/airc-cli-minimal (PR #673).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): daemon mode — Unix socket IPC + typed Request/Response

Long-running daemon that holds substrate state for short-lived CLI
calls. Replaces the Python `airc` daemon model in Rust, with elegant
+ extensible discipline per Joel's steer:

  * Typed wire protocol — Request/Response are serde enums tagged
    by `op` / `kind`. Adding an op = add a variant + add a match
    arm in handlers::dispatch. Compiler enforces exhaustiveness.
  * One concern per file — ipc/{mod,request,response,client}.rs,
    daemon/{mod,state,handlers,server}.rs.
  * Composition over inheritance — DaemonState lazily caches
    SignedTransport<LocalFsAdapter> per wire directory; no
    monolithic god struct.
  * No silent fallbacks — daemon enforces VerificationPolicy::Strict
    on every send.

Subcommands added:
  * `daemon`   — run the daemon (foreground; foregrounding to
                 background is the integrator's job: nohup, launchd,
                 systemd — substrate stays portable)
  * `ping`     — liveness probe
  * `status`   — peer_id + uptime
  * `msg`      — send via daemon (fast — no per-call substrate
                 setup, daemon reuses its SignedTransport)
  * `stop`     — graceful shutdown

Wire protocol = newline-delimited JSON over Unix socket. One
request, one response, connection closes. Debuggable with
`socat - UNIX-CONNECT:…`. No extra schema toolchain.

Modules:
  * ipc/request.rs — Request enum (Ping, Status, Send, Stop)
  * ipc/response.rs — Response enum (Pong, Status, Ok, Error)
  * ipc/client.rs — DaemonClient with typed convenience methods
                    (ping/status/send/stop) wrapping the generic
                    call(). ClientError distinguishes NotConnected
                    vs Io vs Codec vs daemon-side error.
  * daemon/state.rs — DaemonState owns keypair, registry, lazy
                     transport cache, shutdown Notify.
  * daemon/handlers.rs — dispatch() match. Adding an op here is
                        the only place that touches both Request
                        and Response types.
  * daemon/server.rs — UnixListener + accept loop. Cleans up
                      stale sockets but REFUSES to steal a live
                      one (returns AddrInUse instead).

Tests: 21 unit + 2 e2e CLI subprocess = 23 in airc-cli. Workspace
total now ~168 tests passing.

  * ping_returns_pong, status_carries_peer_id_and_uptime,
    stop_signals_shutdown_and_returns_ok,
    send_dispatches_against_local_fs_transport (handler-level)
  * client_ping_round_trips_via_real_socket,
    status_returns_peer_id (real Unix socket integration)
  * second_daemon_refuses_to_steal_live_socket
    (pins the no-stealing contract)

clippy clean (-D warnings), fmt clean.

Default socket path: $HOME/.airc-rs/daemon.sock (overridable via
--socket on each command).

Stacked on feat/airc-cli-e2e-integration (PR #674).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(airc-transport): LAN-TCP readiness race + subscribers-lock-during-await

Addresses Codex's #671 review findings:

1. LanTcpAdapter::connect() returns before send-ready (lan_tcp/
   adapter.rs:324 in the original)

   The previous implementation spawned a task to install the
   outbound channel into Inner::connection AFTER connect() returned.
   Callers (including the CLI) papered over the race with
   sleep(150ms). That's not production-grade — a slow scheduler or
   contended Mutex could push the install past any fixed delay.

   Fix: rename `spawn_connection_loops` to `install_and_spawn_loops`
   and await the channel install INLINE before spawning the I/O
   loops. handle_client_connection + handle_server_connection now
   await this and return Ok only when the connection is send-ready.
   connect() awaits handle_client_connection synchronously.

   CLI sleep(150ms) hack removed from run_lan_send.

2. dispatch_to_subscribers held subscribers Mutex across .send().await

   Classic concurrency anti-pattern: a slow Message/Control
   subscriber blocked dispatch to all others AND blocked new
   subscribers registering.

   Fix: snapshot matching senders under lock, drop lock, then
   await sends outside the critical section. mpsc::Sender clones
   are Arc-cheap; the frame clone was already happening
   per-subscriber. Dead subscribers reaped under a brief lock at
   the end.

Tests: 33 transport + 23 cli all pass (no regressions). clippy
clean (-D warnings), fmt clean. The existing tests
(two_paired_peers_round_trip_a_message, two_subscribers_both_receive)
still cover the corrected paths.

Stacked on feat/airc-cli-daemon (PR #675).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): daemon Subscribe + Inbox — buffered consume-once reads (#678)

The receive half of the daemon: subscribe to a wire, buffer recent
frames in a ring buffer, hand them out via Inbox calls. Closes the
loop on the Python-replacement story — short-lived CLI calls now
have a daemon-backed inbox to read from.

New ops:
  * Subscribe { wire } — idempotent. First call spawns a drain task
    that pulls from SignedTransport::subscribe + pushes verified
    frames into the wire's InboxBuffer. Subsequent calls are no-ops.
  * Inbox { wire, since_lamport?, limit? } — return buffered frames
    with lamport > since (or everything if since is None), capped at
    limit (default 32). Response carries newest_lamport so the
    client threads it back next call for consume-once semantics.

New types:
  * InboxBuffer — bounded VecDeque, drops oldest at capacity 1024
    (default — can be promoted to config later).
  * Frame retained verified only. Verification failures from the
    inner SignedTransport are dropped (Future: surface a counter
    in Status).

CLI: `airc-rs inbox --wire <path> [--since-lamport N] [--limit N]`
prints the frames and the new cursor to thread back.

Integration test: subscribe_then_send_then_inbox_round_trips
exercises the full daemon receive path:
  1. SubscribeRequest{wire} via socket → daemon spawns drain task
  2. SendRequest{wire, channel, text} via socket → daemon signs +
     writes to local-fs (same wire)
  3. drain task verifies + pushes into the InboxBuffer
  4. InboxRequest{wire} returns 1 frame; second call with
     since_lamport=newest returns 0

Tests: 22 unit + 2 e2e CLI subprocess. clippy clean (-D warnings),
fmt clean.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* style(airc-blobs): apply current rustfmt rules (#677)

Pre-existing fmt drift from when PRs #653/#655/#660 landed under
an older rustfmt configuration. `cargo fmt -p airc-blobs` reformats
4 files (whitespace + line break only — no semantic change).

Catching this here so the workspace stays `cargo fmt -- --check`
clean and future PRs don't surface the noise.

cargo test -p airc-blobs: still passes (no test changes).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-transport): multi-peer LanTcpAdapter (#679)

LanTcpAdapter goes from one-peer-only to N concurrent connections.
A LAN room with three or more peers now works directly on the
substrate.

What changed:

  * Inner::connection: Mutex<Option<OutboundTx>>
    → Inner::connections: Mutex<HashMap<PeerId, OutboundTx>>
  * listen() spawns an accept LOOP (was: accept-once). Each accepted
    handshake spawns its own connection task; the read loop adds
    the peer to `connections` on bind and removes on disconnect.
  * connect() can be called multiple times (different expected_peer).
    Duplicate calls to the same peer return AlreadyConnectedTo(peer).
  * send() broadcasts to all connected peers — snapshot under lock,
    drop lock, dispatch outside (same pattern as
    dispatch_to_subscribers). Returns NoActivePeers if there are
    no connections; otherwise Ok if at least one peer received.
  * New: connected_peers() snapshot getter for diagnostics + tests.

Error variant renames (was misnamed for single-peer model):
  * AlreadyHasConnection → AlreadyConnectedTo(PeerId)
  * NotConnected → NoActivePeers
  * + new AlreadyListening for double-listen() refusal

Tests (33 → 35 pass, clippy clean (-D warnings), fmt clean):
  * three_peers_all_connect_and_alice_broadcasts — Alice listens;
    Bob + Charlie connect; Alice.connected_peers() reports both;
    Alice.send() broadcasts and both streams receive the frame.
  * connect_to_same_peer_twice_returns_typed_error — duplicate
    connect → AlreadyConnectedTo(peer).

NOTE: adapter.rs is now ~900 lines and needs a module split into
crates/airc-transport/src/lan_tcp/adapter/{mod,error,inner,
connection,dispatch}.rs. That's a separate follow-up PR (per the
one-PR-at-a-time rule) so this stays focused on the multi-peer
feature.

Targets rust-rewrite directly. No stacking.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(airc-transport): split lan_tcp::adapter into module (one concern per file) (#680)

adapter.rs was ~900 lines after the multi-peer changes. Splits into:

  * error.rs (90 LOC) — LanTcpError + Display/Error/From impls
  * inner.rs (63 LOC) — Inner struct + SubscriberHandle + OutboundTx
                       type + per-connection constants
  * connection.rs (166 LOC) — per-connection lifecycle: handle_*,
                              resolve_peer_from_*, install_and_spawn_loops,
                              read_loop, write_loop
  * dispatch.rs (76 LOC) — dispatch_to_subscribers +
                          subscription_matches_with_cursor
  * mod.rs (507 LOC, ~250 tests) — LanTcpAdapter public surface +
                                   Transport impl + integration tests

All-private internals exposed to siblings via `pub(super)`. No public
API changes; tests pass unchanged (35 tests in airc-transport).

Tests: 35 pass, clippy clean (-D warnings), fmt clean.

Targets rust-rewrite directly. One concern per file.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): persisted identity state — stable peer_id + client_id (#681)

`airc-rs init` now creates a persistent identity under `<home>`
(default `$HOME/.airc-rs`). Subsequent CLI calls load it
automatically — no `--peer-id` flag, no `--identity-file` flag, no
nil-Uuid default ambiguity. Per Codex's framing: persisted identity
state, not just nicer flags.

What changes:

  * `LocalIdentity` (new in identity.rs) bundles
    `{ keypair, peer_id, client_id }` and persists to:
      - `<home>/identity.key`  — 32-byte Ed25519 secret (0600 Unix)
      - `<home>/identity.json` — `{ version, peer_id, client_id, created_at_ms }` (0600 Unix)

  * `load_or_generate(home)`:
      - both files present → load
      - both absent → generate + save
      - one present + one absent → IdentityError::PartialState
        (refuses to invent a new peer_id over an existing key;
        silent rotation would break enrolled peers).

  * CLI surface simplifies:
      - REMOVED `--identity-file` and `--peer-id` flags
      - NEW `--home <dir>` flag (env AIRC_RS_HOME), default
        `$HOME/.airc-rs`
      - Socket default is now `<home>/daemon.sock`
      - Frames use the persisted `client_id` (was: regenerated on
        every CLI call — broke multi-tab disambiguation)

  * `airc-rs init` is the only command that intentionally creates
    identity from scratch. All others auto-load (or auto-create on
    first run); never silently regenerate over a partial state.

  * `VerificationPolicy::Strict` is the only policy in CLI paths —
    no `AllowUnsigned` opt-in remains.

New tests:

  * identity::tests::load_or_generate_creates_both_files_and_reuses_them
    — same peer_id across re-runs (the core persistence pin).
  * identity::tests::refuses_partial_state_when_only_key_exists /
    only_json_exists — silent rotation prevented.
  * identity::tests::refuses_bad_key_length — key length mismatch
    surfaces typed error.
  * identity::tests::refuses_unknown_schema_version — forward-
    compat refusal.
  * identity::tests::key_and_state_files_are_owner_only_on_unix —
    0600 perms pinned.
  * e2e::rerun_init_returns_same_peer_id — pins persistence at the
    binary surface.

Tests: 25 unit + 3 e2e CLI subprocess. clippy clean (-D warnings),
fmt clean.

Next PR: persistent `peers.json` so `--peer` disappears too. Then
mDNS. (Skipping GhGistAdapter per Joel's direction — don't keep
Python alive as a comfort path.)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): persistent peer registry — peers.json + daemon AddPeer/ListPeers (#682)

feat(airc-cli): persistent peer registry (peers.json) + daemon AddPeer/ListPeers

Closes the second ergonomic step after persisted identity. Peers are
now persisted to `<home>/peers.json` (0600 on Unix) and unioned with
ad-hoc `--peer` flags at runtime. The CLI gets `airc-rs peer add
<spec>` and `airc-rs peer list`; the daemon gets matching AddPeer +
ListPeers ops so the in-memory registry stays in sync without a
restart.

New module: peers_store.rs
  * StoredPeer { peer_id, pubkey_b64, added_at_ms }
  * load(home) / add(home, peer_id, pubkey) / save(home, peers)
  * Versioned schema (refuses unknown versions)
  * Idempotent: same peer_id+pubkey is a no-op; same peer_id with a
    new pubkey REPLACES (rotation).

New CLI commands:
  * `airc-rs peer add <spec> [--socket]` — write peers.json + tell
    daemon via AddPeer if running (best-effort; falls back cleanly).
  * `airc-rs peer list` — print enroled peers from peers.json.

New daemon ops:
  * Request::AddPeer { peer_id, pubkey_b64 } — decode + enrol into
    the running registry. CLI writes peers.json itself, so on next
    daemon restart the same peers are loaded; this op covers the
    "daemon running, want it to see new peer NOW" case.
  * Request::ListPeers → Response::Peers — daemon reads peers.json
    (same file the CLI writes) and returns the entries.

Wiring:
  * `build_combined_registry(home, identity, adhoc)` unions
    persistent peers from `<home>/peers.json` with `--peer` adhoc
    flags. Self always enroled. Adhoc wins on duplicate peer_id.
  * DaemonState gains `home: PathBuf` so handlers can reach
    peers.json without re-deriving the path.

Tests: 32 unit + 3 e2e pass. New unit tests cover load/save
round-trip, idempotent add, rotation, schema-version refusal,
multiple peers, and 0600 permissions on Unix.

Stays on target — one focused PR to rust-rewrite.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): cross-platform daemon — Unix sockets + Windows named pipes (#683)

airc-rs now builds + runs the daemon on Mac, Linux, AND Windows. The
existing Python airc worked on Windows via Git Bash; the Rust path
now runs as a native Windows binary.

New module: ipc/transport.rs
  * IpcListener — Unix(UnixListener) | Windows(NamedPipeServer)
  * IpcStream — Unix(UnixStream) | WindowsServer(NamedPipeServer)
                | WindowsClient(NamedPipeClient)
  * AsyncRead + AsyncWrite blanket impls so daemon/server.rs and
    ipc/client.rs use one abstraction; the cfg-gated arms compile out
    on the other platform.

Path conventions:
  * Unix: filesystem socket at <home>/daemon.sock
  * Windows: named pipe at \\.\pipe\airc-rs-<home>
    Multi-home setups get distinct pipes via sanitised parent-dir
    + filename, so concurrent daemons coexist on one machine.

Default home directory now handles native Windows:
  * $HOME (Unix; also Git Bash on Windows) → <home>/.airc-rs
  * %USERPROFILE% (native Windows cmd/PowerShell) → <userprofile>/.airc-rs
  * Fallback ./.airc-rs

Dropped env-var noise per friction feedback:
  * --home no longer reads AIRC_RS_HOME (it had become magic-knob
    parameter pollution)
  * clap "env" feature dropped from Cargo.toml

Refactor highlights:
  * daemon/server.rs: UnixListener → IpcListener::bind; UnixStream
    → IpcStream; cleanup_stale_socket is now Unix-only (Windows
    named pipes self-clean + first_pipe_instance prevents duplicate
    binders at the OS layer).
  * ipc/client.rs: UnixStream::connect → IpcStream::connect.
  * tokio features extended with net + io-util + sync (needed for
    NamedPipeServer + NamedPipeClient).

Tests: 33 unit + 3 e2e pass on Mac. Verified `cargo check
--target x86_64-pc-windows-gnu` is clean on the full crate tree
(after `brew install mingw-w64` to provide the cross-linker; not
required for native Windows builds).

Targets rust-rewrite.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(airc-cli): per-user room state — drop --wire/--channel parameter hell

Standard send/listen/msg/inbox calls no longer take --wire or --channel.
They read <home>/room.json — the persisted current room — and use its
(wire, channel). Switch rooms with `airc-rs room <name>`; same name on
two peers yields the same channel UUID via UUIDv5(namespace, name), so
they don't need to share the UUID out-of-band.

State is per-user already: <home> defaults to $HOME/.airc-rs (Unix) or
%USERPROFILE%/.airc-rs (Windows), so room.json is automatically scoped
per user-account.

`airc-rs init` auto-creates the default room. `airc-rs room` (no args)
prints the current room. `airc-rs room <name>` switches. `--wire <path>`
overrides the per-home default wire dir — used by local-fs e2e tests
that need two processes on one machine to share a wire.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(airc-blobs): clear clippy warnings that block #684 CI gate

- gc.rs: collapsible_if — merge nested age+delete check via &&
- gc.rs: unused stale `old_path` placeholder before the actual
  `store_path_for` assignment
- lib.rs: doc_lazy_continuation on the `exists` contract doc

Pre-existing in airc-blobs; surfaced now because PR #661 (rust CI
gates) turned `cargo clippy --workspace -- -D warnings` into a
required check. Folding into #684 instead of opening a side PR so
this branch can land.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant