Skip to content

fix(#283): per-channel gist + multi-channel monitor (rooms work for real) - #287

Merged
joelteply merged 1 commit into
canaryfrom
fix/issue-283-general-shared-gist
Apr 29, 2026
Merged

joelteply merged 1 commit into
canaryfrom
fix/issue-283-general-shared-gist

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Closes #283. Phase 2B.3's "subscribed_channels handles it" claim was incomplete — the routing was never built. Tonight's QA pass made this visible: cross-project broadcasts to #general silently disappeared into the sender's project gist; peers in different project rooms saw nothing.

Architecture (per Joel)

"One general, one continuum room, one ideem room etc — that's the whole point of rooms." ONE gist per channel name per gh account. ONE monitor process per scope, polls N subscribed channels' gists in parallel. The gist IS the host medium; closing tabs is fine, the gist persists.

Modules

  • `lib/airc_core/channel_gist.py` (new, ~280 lines) — find-or-create per channel. Single concern. CLI seam for bash.
  • `lib/airc_core/config.py` — extended with `channel_gists` accessors (get/set/list). Single source of truth for "which gist for which channel."

Wiring

  • `airc` — `_monitor_multi_channel` helper spawns N bearer_cli recv subprocesses, all merged into one formatter. Per-channel offset + bearer_state files for observability.
  • `spawn_general_sidecar_if_wanted` — find-or-creates #general gist via channel_gist module + persists in config. NO separate sidecar process.
  • `cmd_connect` — primary room bootstrap also writes channel_gists[room_name].
  • `cmd_send` — routes by channel via `config.get_channel_gist` lookup, falls back to scope's room_gist_id.

TDD: 6/6 pass post-fix

`scenario_general_has_shared_gist` — full host bootstrap with --general flag, asserts:

  1. Primary room gist created
  2. config.channel_gists['general'] resolved + distinct
  3. #general gist exists on gh
  4. `airc msg --room general` lands in #general gist
  5. NO cross-channel pollution into project gist

Known follow-ups

🤖 Generated with Claude Code

…eal)

The Phase 2B.3 collapse claimed "subscribed_channels handles it" —
but the routing was never built. Cross-room broadcasts to #general
silently went to the project room's gist; other peers in different
project rooms never saw them. Same root cause cascaded into #284
(cross-room DMs) and the QA-pass coordination breakdown tonight.

## Architecture (per Joel 2026-04-29)
"One general, one continuum room, one ideem room etc — that's the
whole point of rooms. Across my machines we all naturally collaborate
in our rooms."

ONE gist per channel name per gh account. All same-account tabs
subscribed to the same channel resolve to the same gist via
gh-account discovery. Closing/opening tabs is benign — the gist
persists; the gist IS the host medium.

ONE monitor process per scope, polling N subscribed channels' gists
in parallel. Per Joel: "you can still have one monitor doesn't need
to load one for every room, just always itself monitor each room."

## Modules (new, single-concern each)
- lib/airc_core/channel_gist.py — find-or-create per-channel gist on
  user's gh account. Pure, testable, callable from bash via CLI seam.
  No bash-flavored heredocs; the lookup logic lives in one place.
- lib/airc_core/config.py — extended with channel_gists accessors:
  get_channel_gist, set_channel_gist, list_channel_gists. Bash never
  reads config.json directly for this — single source of truth.

## Wiring
- airc top-level: spawn_general_sidecar_if_wanted now find-or-creates
  the canonical #general gist via channel_gist module + persists in
  channel_gists. NO separate sidecar process — one monitor per scope.
- airc top-level monitor(): _monitor_multi_channel helper polls all
  subscribed channels' gists in parallel via N bearer_cli recv
  subprocesses, all merged into one monitor_formatter. Each channel
  gets its own offset_file + bearer_state.json (per-channel
  observability surfaces).
- cmd_connect.sh: when primary room gist resolves (discovery or
  bootstrap), also writes channel_gists[room_name] so the multi-
  channel monitor polls it.
- cmd_send.sh: routes by channel — looks up channel_gists[active_channel]
  first, falls back to scope's room_gist_id. Both joiner and host
  branches updated.

## TDD scenario (passes 6/6 post-fix)
scenario_general_has_shared_gist:
  1. Spawn host with --room project --general
  2. Wait for primary room gist + #general gist resolution
  3. Assert config.channel_gists['general'] exists, distinct from project gist
  4. Assert #general gist exists on gh
  5. airc msg --room general "marker"
  6. Assert marker landed in #general gist (NOT project gist) — channel routing correct
  7. Assert no cross-channel pollution

## Known follow-ups
- scenario_status's "queue when host unreachable" assertion is
  obsolete — post-3c, host_target isn't load-bearing; bearer routes
  through gist regardless of fake host_target. The test needs updating
  to test "gist unreachable" instead.
- #284 cross-room DM partially mitigated: with per-channel gists, peers
  who share #general can DM cross-project via that lobby. Cross-account
  DMs (Joel + Toby on different gh) still need gh-pair-handshake.

Closes #283. Reduces blast radius of #284.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 29, 2026 06:16
@joelteply
joelteply merged commit 6e9559f into canary Apr 29, 2026
8 checks passed
@joelteply
joelteply deleted the fix/issue-283-general-shared-gist branch April 29, 2026 06:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR implements the missing “rooms route for real” wiring for #283 by introducing per-channel gists (one gist per channel name per GitHub account) and updating send/monitor logic to route and poll across multiple channel gists within a single scope.

Changes:

  • Add airc_core.channel_gist to find-or-create a canonical gist for a channel on the authenticated GitHub account.
  • Extend airc_core.config with channel_gists accessors and update connect/send/monitor flows to use channel→gist routing.
  • Add an integration scenario to assert that --room general traffic lands in the #general gist and does not pollute the project gist.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
test/integration.sh Adds an integration scenario validating #general’s separate gist and correct routing.
lib/airc_core/config.py Adds CLI accessors for channel_gists (get/set/list).
lib/airc_core/channel_gist.py New module to resolve/find-or-create a per-channel gist via gh.
lib/airc_bash/cmd_send.sh Routes sends by channel gist (with fallback to scope room_gist_id).
lib/airc_bash/cmd_connect.sh Persists channel→gist mappings during host/join bootstrap.
airc Reworks monitor into multi-channel polling mode; updates #general subscription to resolve/persist gist id.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +255 to +258
"""
if not channel or not isinstance(channel, str):
return None
existing = find_existing(channel)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolve() only checks that channel is a non-empty string. Given downstream uses of channel names in gist descriptions and (in bash) as filename suffixes, this should reject/normalize unexpected characters (e.g., leading '#', whitespace, '/', '..') to keep routing deterministic and avoid path/format injection issues.

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_bash/cmd_send.sh
Comment on lines +240 to +249
# Phase 3c+ (#283): route by channel. The active_channel's gist
# comes from channel_gists in config (populated at subscribe time).
# If the channel has no mapping, fall back to the scope's primary
# room_gist_id so single-room scopes keep working unchanged.
local room_gist_id=""
[ -f "$AIRC_WRITE_DIR/room_gist_id" ] && room_gist_id=$(cat "$AIRC_WRITE_DIR/room_gist_id" 2>/dev/null || true)
room_gist_id=$("$AIRC_PYTHON" -m airc_core.config get_channel_gist \
--config "$CONFIG" --channel "$active_channel" 2>/dev/null || true)
if [ -z "$room_gist_id" ] && [ -f "$AIRC_WRITE_DIR/room_gist_id" ]; then
room_gist_id=$(cat "$AIRC_WRITE_DIR/room_gist_id" 2>/dev/null || true)
fi

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Falling back to the scope’s primary room_gist_id when get_channel_gist returns empty can reintroduce the #283 failure mode: a message stamped with channel="$active_channel" gets written to the wrong gist (silent cross-channel pollution / invisible to peers in the intended channel). Consider failing loudly when the user explicitly selected a channel (--room/--channel) but no gist mapping exists, or proactively resolving/bootstrapping the channel gist before sending instead of falling back.

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/config.py
Comment on lines +207 to +212
channel. Used by the monitor to know which gists to poll. Empty
output = no channels configured (host hasn't bootstrapped, or no
sidecar subscriptions)."""
gists = _load(args.config).get("channel_gists", {}) or {}
for ch, gid in gists.items():
if ch and gid:

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

list_channel_gists currently prints every entry in channel_gists without regard to subscribed_channels, but airc monitor() uses this output to decide what to poll. Because unsubscribe (/part) only updates subscribed_channels and does not clear channel_gists, this can cause the monitor to keep polling and displaying channels the user explicitly left. Consider filtering this list to the current subscribed_channels (and/or removing mappings on unsubscribe) so /part reliably stops traffic.

Suggested change
channel. Used by the monitor to know which gists to poll. Empty
output = no channels configured (host hasn't bootstrapped, or no
sidecar subscriptions)."""
gists = _load(args.config).get("channel_gists", {}) or {}
for ch, gid in gists.items():
if ch and gid:
and currently subscribed channel. Used by the monitor to know which
gists to poll. Empty output = no channels configured (host hasn't
bootstrapped, or no sidecar subscriptions)."""
c = _load(args.config)
gists = c.get("channel_gists", {}) or {}
subscribed_raw = c.get("subscribed_channels", []) or []
if isinstance(subscribed_raw, dict):
subscribed = {str(ch) for ch, enabled in subscribed_raw.items() if ch and enabled}
elif isinstance(subscribed_raw, (list, tuple, set)):
subscribed = {str(ch) for ch in subscribed_raw if ch}
elif isinstance(subscribed_raw, str):
subscribed = {subscribed_raw} if subscribed_raw else set()
else:
subscribed = set()
for ch, gid in gists.items():
if ch and gid and ch in subscribed:

Copilot uses AI. Check for mistakes.
Comment thread airc
Comment on lines +933 to +943
# 1. channel_gists map non-empty → multi-channel mode (post-#283:
# one monitor polls all subscribed channels' gists in parallel)
# 2. legacy room_gist_id only → single-gist mode (older scopes
# that haven't been re-bootstrapped to populate channel_gists)
# 3. neither → local-tail mode (standalone tests, --no-room --no-gist)
local channel_map
channel_map=$("$AIRC_PYTHON" -m airc_core.config list_channel_gists \
--config "$CONFIG" 2>/dev/null || true)

if [ -n "$channel_map" ]; then
_monitor_multi_channel "$my_name" "$channel_map"

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multi-channel mode is activated purely by channel_map being non-empty. If channel_gists contains stale entries (e.g., after /part removes a channel from subscribed_channels but leaves the mapping behind), the monitor will still poll and surface traffic for channels the user believes they left. Consider deriving the poll set from subscribed_channels and then looking up each channel’s gist id, rather than treating channel_gists as the authoritative list to poll.

Suggested change
# 1. channel_gists map non-empty → multi-channel mode (post-#283:
# one monitor polls all subscribed channels' gists in parallel)
# 2. legacy room_gist_id only → single-gist mode (older scopes
# that haven't been re-bootstrapped to populate channel_gists)
# 3. neither → local-tail mode (standalone tests, --no-room --no-gist)
local channel_map
channel_map=$("$AIRC_PYTHON" -m airc_core.config list_channel_gists \
--config "$CONFIG" 2>/dev/null || true)
if [ -n "$channel_map" ]; then
_monitor_multi_channel "$my_name" "$channel_map"
# 1. subscribed_channels ∩ channel_gists non-empty → multi-channel
# mode (poll only currently subscribed channels' gists; ignore
# stale channel_gists entries left behind after /part)
# 2. legacy room_gist_id only → single-gist mode (older scopes
# that haven't been re-bootstrapped to populate channel_gists)
# 3. neither → local-tail mode (standalone tests, --no-room --no-gist)
local channel_map subscribed_channels active_channel_map
channel_map=$("$AIRC_PYTHON" -m airc_core.config list_channel_gists \
--config "$CONFIG" 2>/dev/null || true)
subscribed_channels=$("$AIRC_PYTHON" -m airc_core.config list_subscribed_channels \
--config "$CONFIG" 2>/dev/null || true)
active_channel_map=""
if [ -n "$channel_map" ] && [ -n "$subscribed_channels" ]; then
local _subscribed_channel _gist_line _gist_channel
while IFS= read -r _subscribed_channel; do
[ -z "$_subscribed_channel" ] && continue
while IFS= read -r _gist_line; do
[ -z "$_gist_line" ] && continue
_gist_channel=${_gist_line%%$'\t'*}
if [ "$_gist_channel" = "$_subscribed_channel" ]; then
if [ -n "$active_channel_map" ]; then
active_channel_map+=$'\n'
fi
active_channel_map+=$_gist_line
break
fi
done <<< "$channel_map"
done <<< "$subscribed_channels"
fi
if [ -n "$active_channel_map" ]; then
_monitor_multi_channel "$my_name" "$active_channel_map"

Copilot uses AI. Check for mistakes.
Comment on lines +220 to +225
# Use airc-invite.<channel> as the seed filename; it's distinct
# from messages.jsonl (which the bearer creates on first send),
# so we don't shadow the wire file.
seed_path = os.path.join(tmpdir, f"airc-room-{channel}.json")
with open(seed_path, "w") as f:
json.dump(envelope, f)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

channel is interpolated into a filesystem path (airc-room-{channel}.json). Since channel names are currently not validated at the config/CLI layer, a crafted channel containing path separators could escape the temp dir or create unexpected nested paths. Please validate/normalize channel names to a safe pattern before using them in filenames (or derive the seed filename from a safe transform like a hash).

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_bash/cmd_send.sh
Comment on lines +394 to +401
# Route by channel via channel_gists (post-#283); fall back to the
# scope's primary room_gist_id so single-room hosts keep working.
local _host_room_gist_id=""
[ -f "$AIRC_WRITE_DIR/room_gist_id" ] && _host_room_gist_id=$(cat "$AIRC_WRITE_DIR/room_gist_id" 2>/dev/null || true)
_host_room_gist_id=$("$AIRC_PYTHON" -m airc_core.config get_channel_gist \
--config "$CONFIG" --channel "$active_channel" 2>/dev/null || true)
if [ -z "$_host_room_gist_id" ] && [ -f "$AIRC_WRITE_DIR/room_gist_id" ]; then
_host_room_gist_id=$(cat "$AIRC_WRITE_DIR/room_gist_id" 2>/dev/null || true)
fi

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same routing risk on the host path: if the channel→gist mapping is missing, falling back to the primary room_gist_id can write a message labeled for one channel into a different channel’s gist. Prefer failing loudly (or resolving/creating the channel gist) when a non-default channel is targeted and no mapping exists, rather than silently falling back.

Copilot uses AI. Check for mistakes.
Comment thread test/integration.sh
Comment on lines +2932 to +2934
trap "gh gist delete '$proj_gid' --yes 2>/dev/null || true; \
general_gid=\$(python3 -c \"import json; c=json.load(open('/tmp/airc-it-tdd283-h/state/config.json')); print(c.get('channel_gists',{}).get('general',''))\" 2>/dev/null); \
[ -n \"\$general_gid\" ] && [ \"\$general_gid\" != \"$proj_gid\" ] && gh gist delete \"\$general_gid\" --yes 2>/dev/null || true" EXIT

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This scenario deletes general_gid on EXIT, but channel_gist resolve --create-if-missing may return a pre-existing canonical #general gist for the authenticated account. Running this test could therefore delete a real user gist (data loss). Track whether #general existed before the test and only delete if the test created it (or avoid deleting canonical gists entirely).

Suggested change
trap "gh gist delete '$proj_gid' --yes 2>/dev/null || true; \
general_gid=\$(python3 -c \"import json; c=json.load(open('/tmp/airc-it-tdd283-h/state/config.json')); print(c.get('channel_gists',{}).get('general',''))\" 2>/dev/null); \
[ -n \"\$general_gid\" ] && [ \"\$general_gid\" != \"$proj_gid\" ] && gh gist delete \"\$general_gid\" --yes 2>/dev/null || true" EXIT
# Only delete the project-room gist that this scenario created. Do not
# delete the resolved #general gist here: channel gist resolution may
# return a pre-existing canonical gist for the authenticated account.
trap "gh gist delete '$proj_gid' --yes 2>/dev/null || true" EXIT

Copilot uses AI. Check for mistakes.
Comment thread test/integration.sh

trap - EXIT
gh gist delete "$proj_gid" --yes 2>/dev/null || true
[ -n "$general_gid" ] && [ "$general_gid" != "$proj_gid" ] && gh gist delete "$general_gid" --yes 2>/dev/null || true

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue at the end-of-test cleanup: deleting $general_gid here can delete an existing canonical #general gist that predates the test run. Please only delete the general gist if the test created it during this scenario.

Suggested change
[ -n "$general_gid" ] && [ "$general_gid" != "$proj_gid" ] && gh gist delete "$general_gid" --yes 2>/dev/null || true
[ "${general_created:-0}" -eq 1 ] && [ -n "$general_gid" ] && [ "$general_gid" != "$proj_gid" ] && gh gist delete "$general_gid" --yes 2>/dev/null || true

Copilot uses AI. Check for mistakes.
Comment thread airc
Comment on lines +893 to +897
"$AIRC_PYTHON" -u -m airc_core.bearer_cli recv "self" \
--room-gist-id "$gid" \
--offset-file "$AIRC_WRITE_DIR/monitor_offset.${ch}" \
--state-file "$AIRC_WRITE_DIR/bearer_state.${ch}.json" \
2>/dev/null &

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ch comes from config (ultimately user-controlled via --room/--channel) and is used directly in --offset-file "$AIRC_WRITE_DIR/monitor_offset.${ch}" and --state-file "$AIRC_WRITE_DIR/bearer_state.${ch}.json". Without validating/sanitizing channel names, a value containing / or .. can escape the scope directory or clobber arbitrary files. Validate channels to a safe charset (e.g., [a-z0-9-]+, similar to _validate_peer_name) before using them in filesystem paths, or derive a safe filename (hash/escape) independent of the raw channel string.

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Apr 29, 2026
* hotfix(install.sh): two Windows fresh-install regressions (#249) (#265)

* fix(install.sh): two Windows fresh-install regressions (#249)

Caught by continuum-b69f's wipe-and-reinstall test for the #249
release-readiness matrix (Windows Git Bash + PowerShell rows).

## Bug 1: install-elevated.ps1 staged in $CLONE_DIR before git clone

`_ensure_sshd_running` runs from `ensure_prereqs` (line 747/789),
which mkdir's $CLONE_DIR and writes install-elevated.ps1 to it BEFORE
the git clone step (line 872). Result on a fresh-install user (no
existing ~/.airc-src):

  fatal: destination path 'C:/Users/green/.airc-src' already exists
         and is not an empty directory.

Hostile error, no recovery hint. Workaround was AIRC_SKIP_PREREQS=1.

Fix: stage the .ps1 in $TMPDIR instead. The .ps1 is consumed by the
elevated PowerShell process (which reads from $env:TEMP via the
log-write Path); its location during install is irrelevant.

## Bug 2: airc.cmd + airc.ps1 forwarders not placed on PATH

install.sh's symlink step (line 881-884) only ln -sf'd the bash
`airc`, leaving airc.cmd and airc.ps1 in $CLONE_DIR but not on PATH.
Result: native PowerShell `airc` resolves to the bash script, which
PowerShell can't execute:

  PS> airc version
  Cannot run a document in the middle of a pipeline:
  C:\Users\green\.local\bin\airc.

PR #262's collapse of airc.ps1 to a thin forwarder is moot if the
forwarder isn't reachable.

Fix: on MINGW*/MSYS*/CYGWIN*, `cp -f` airc.cmd + airc.ps1 to $BIN_DIR.
cp not ln -sf — Windows symlinks need elevation, copying is universal
and the forwarders are tiny.

* ci: retrigger policy check after retarget to canary

* feat(bearer): Phase 0 — abstract bearer seam, no behavior change (#271)

Introduces lib/airc_core/bearer.py + bearer_resolver.py + bearer_ssh.py
as the seam between airc and any message transport. Phase 0 is
scaffolding only: the ABC compiles, the resolver picks correctly, and
the SshBearer skeleton documents what Phase 1+ will fill in. Existing
SSH delivery in cmd_send.sh / cmd_connect.sh / monitor is untouched.

Why a separate Phase 0:
  Phase 1 will thread cmd_send through bearer_cli, which is meaningful
  surgery. Landing the seam definition first makes that surgery
  reviewable in isolation — the abstraction either holds up under test
  here, or it gets revised before any callers depend on it.

Modularity invariants codified in bearer.py docstring:
  - The ABC speaks only in peer-id / channel / opaque bytes / lifecycle.
    No SSH, gh, addresses, ports, hosts, signatures, or identities.
  - Concrete bearers are imported by bearer_resolver.py and NOWHERE ELSE.
  - Per-transport adapter rule: ALL Tailscale-specific code lives in
    bearer_tailscale.py (when/if it exists); ALL gh-as-transport code
    lives in bearer_gh.py. After the rewrite completes, grepping the
    codebase for "tailscale" / "ssh" should match only that transport's
    bearer module + its tests.
  - gh has TWO roles in airc: identity/registry (control plane,
    cmd_rooms + gistparse) AND transport (data plane, future
    bearer_gh.py). The bearer abstraction encapsulates only the
    transport role.

Bearer ABC shape:
  - KIND class attribute (the transport's short name)
  - can_serve(peer_meta) classmethod — pure, no IO
  - open(peer_id) / send / recv_stream / liveness / close lifecycle
  - ReceivedMessage + LivenessResult dataclasses (frozen, immutable)
  - PeerUnreachable for fall-through-to-next-bearer signaling

Resolver:
  - Ordered _REGISTRY of bearer types (preference order)
  - resolve(peer_meta) → cheap-construct first candidate that says yes
  - Raises PeerUnreachable when no bearer can serve

Tests (15 unit tests, runs as scenario_python_units in integration.sh):
  - ABC enforcement: cannot instantiate abstract / partial subclasses
  - Resolver picks SshBearer for peers with host_target
  - Resolver raises PeerUnreachable for empty peer_meta
  - SshBearer cheap-construct invariant (no IO on __init__)
  - SshBearer open/close lifecycle, post-close operations raise
  - Skeleton methods raise NotImplementedError with phase-pointer
    guidance so debuggers know where the missing work belongs

Phase 1 (next PR): cmd_send.sh's SSH delivery primitive moves into
SshBearer.send(). cmd_send.sh shrinks to "build envelope, sign, hand
to bearer."

Phase 2: GhBearer added to the registry behind SshBearer.
Phase 3: cutover; SshBearer + Tailscale paths removed wholesale.

Refs #270 (mesh silent-degradation, root-caused as missing modularity)
Refs #269 (gh-bearer RFC; this is the foundation that makes #269
implementable as a one-file change)

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

* feat(bearer): Phase 1 — cmd_send through bearer seam, SSH knowledge consolidated (#272)

feat(bearer): Phase 1 — cmd_send goes through bearer seam, all SSH knowledge consolidates in bearer_ssh

cmd_send.sh's SSH delivery primitive (relay_ssh invocation, __APPENDED__
confirmation, Tailscale-CGNAT offline fast-path, auth-vs-transient error
classification) is now in lib/airc_core/bearer_ssh.py. cmd_send.sh shrinks
to "build envelope, hand to bearer, branch on SendOutcome.kind."

Adding a new transport (gh, Reticulum, anything) no longer touches
cmd_send.sh — the resolver registers it, the SendOutcome contract gets
honored, done. This is the modularity payoff that #270 root-caused as
missing.

What moved
  airc:510 is_peer_offline_in_tailnet (40 lines)
    → lib/airc_core/bearer_ssh.py:_is_peer_offline_in_tailnet
    Same CGNAT regex, same `tailscale status` parse, same user@ strip
    (issue #78 root-cause defense). Phase 3 deletes both in one edit
    when Tailscale leaves the codebase.

  cmd_send.sh:228 relay_ssh "$host_target" "cat >> ... && echo __APPENDED__"
    → lib/airc_core/bearer_ssh.py:SshBearer.send()
    Same ssh option set (-o StrictHostKeyChecking=accept-new -o ConnectTimeout=10
    -o ServerAliveInterval=30), same identity-key handling, same
    __APPENDED__ marker check.

  cmd_send.sh:247-258 auth-failure stderr classification
    → lib/airc_core/bearer_ssh.py:_classify_ssh_failure
    Same markers (Permission denied, publickey, Authentication failed).

How cmd_send invokes it
  Builds the signed JSON envelope (unchanged), then:
    payload | python -m airc_core.bearer_cli send <peer> <channel> \
      --host-target ... --identity-key ... --remote-home ...
  Outcome JSON: {"kind": "<delivered|queued_unreachable|auth_failure|transient_failure>", "detail": "..."}
  Bash branches on .kind via case statement. queued_unreachable + transient_failure
  go to pending.jsonl + a [QUEUED] marker; auth_failure surfaces loudly + dies;
  delivered is the success path.

New SendOutcome contract (lib/airc_core/bearer.py)
  Bearers return a structured SendOutcome instead of raising on normal
  failure modes. Kinds are bearer-agnostic: any future bearer (gh,
  Reticulum, etc.) populates the same set so callers never branch on
  transport. The contract is enumerated and frozen — adding a new kind
  requires updating callers, by design.

Tests (25 unit tests, +10 over Phase 0)
  - send() returns "delivered" on __APPENDED__ in stdout
  - send() returns "queued_unreachable" when tailscale reports offline
  - send() returns "auth_failure" on Permission denied stderr
  - send() returns "transient_failure" on Connection refused / timeout
  - SSH argv built correctly: -i key, -p port, -o options, target last
  - CGNAT regex accepts 100.64–100.127, rejects everything else
  - user@ prefix stripped before CGNAT check (#78 defense preserved)
  - SendOutcome immutability (frozen dataclass)
  - Resolver threads peer_meta to bearer __init__

Behavior preservation
  All paths in cmd_send.sh produce the same user-visible result as before:
  - Successful send: nothing extra logged, last_sent updated
  - Tailnet-offline peer: [QUEUED ... peer offline ...] in $MESSAGES,
    payload to pending.jsonl, return 0
  - Auth failure: [AUTH FAILED ...] in $MESSAGES, die with re-pair message
  - Transient failure: [QUEUED ... network error ...] in $MESSAGES,
    payload to pending.jsonl, stderr surfaced

Phases ahead
  Phase 2: monitor's SSH-tail recv path → SshBearer.recv_stream()
           heartbeat read → SshBearer.liveness()
           Other relay_ssh callers (cmd_status, cmd_identity, cmd_rooms,
           cmd_connect) thread through the bearer.
  Phase 3: GhBearer + LocalBearer added; resolver flips defaults;
           SshBearer + all Tailscale code deleted in one PR per the
           "transport is just an adapter" rule (#269).

Refs #270 (mesh silent-degradation, root-caused as missing modularity)
Refs #269 (gh-bearer RFC; this is the seam #269 plugs into)
Refs #271 (Phase 0 — abstract bearer seam, scaffolding)

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

* feat(bearer): Phase 2a — SshBearer.recv_stream + liveness functional (#273)

Implements the recv side of the bearer abstraction. SshBearer now owns:
- SSH-tail subprocess lifecycle (Popen, reap, terminate-on-close)
- Tail-position computation from persisted offset (mirrors monitor's
  rules: empty/0/non-numeric → -n 0; positive N → -n +N+1)
- Per-line JSON envelope parsing (drops malformed lines silently,
  matches prior formatter behavior)
- Reconnection on SSH death (3s backoff, internal loop)
- Offset persistence on each received event so reconnect resumes past
  the last yielded line
- Liveness signal via _last_recv_ts bumped on each line — natural for
  this bearer (stream activity), parallel signal for future bearers
  (gh: gist last-modified; local: socket activity)

Watchdog and any UX response to extended silence stay CALLER concerns
per the bearer.py contract — the bearer's job is to keep producing
events and answer liveness() honestly.

Phase 2a deliberately does NOT refactor the monitor in airc top-level
to use recv_stream(). That is Phase 2b's surgery: the existing
ssh|monitor_formatter pipeline keeps working, recv_stream is unit-
tested but unused. Splitting the implementation from the cutover
makes each PR small and revertible.

Tests (35 total, +10 in this phase)
  - recv_stream raises with no host_target (programming error path)
  - _parse_envelope drops non-JSON, empty, array, missing-from cases
  - _parse_envelope accepts well-formed envelopes, preserves payload
    + populates bearer_metadata.envelope
  - _compute_tail_position on missing/empty/0/non-numeric/negative
    files all return -n 0
  - _compute_tail_position resumes correctly past saved line
  - recv_stream yields ReceivedMessage events for each valid line
  - recv_stream silently skips malformed lines mid-stream
  - liveness reports None pre-stream, fresh ts post-event
  - close() terminates active recv subprocess (mock proc.terminate
    asserted called)
  - offset_file gets the right line count after recv events flow

Refs #270 (mesh observability — liveness through bearer is the
foundation for the airc-peers/airc-status fix in Phase 2b/2c)
Refs #272 (Phase 1 — cmd_send through bearer; this completes the
        outbound+inbound data-plane consolidation in bearer_ssh.py)

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

* test(bearer): per-bearer integration scenarios + recv buffering bug fix (#274)

test(bearer): per-bearer integration scenarios + bufsize=0/binary recv bug fix

Adds two integration scenarios that exercise SshBearer end-to-end against
a real paired SSH listener — the safety net Joel asked for before the
monitor cutover (Phase 2b). Each future bearer kind (gh, local, ...)
gets parallel scenarios in the same shape: prove the transport works
in isolation BEFORE flipping production callers through it.

New scenarios
  bearer_ssh_send:
    - spawn host + paired joiner
    - read host_target / remote_home / identity_key from joiner config
    - pipe a signed envelope through `bearer_cli send`
    - assert outcome.kind == "delivered"
    - assert payload appears in host's messages.jsonl
  bearer_ssh_recv:
    - spawn host + paired joiner
    - background a Python recv_stream driver
    - sleep 3s for ssh to connect (tail -n 0 only sees lines after this)
    - append a unique marker to host's log
    - assert recv_stream yields the marker within 12s
    - assert liveness reports a fresh ts after the recv

Bug surfaced + fixed
  SshBearer.recv_stream() used bufsize=0 with text=False, which gives
  a raw FileIO (not BufferedReader). Iterating yields chunks, not lines
  — readline isn't even available on the raw object the way I called
  it, and the old `for line in proc.stdout` would split on chunk
  boundaries instead of newlines. Result: in production, ssh+tail
  could be producing line-paced output and the bearer would block
  forever waiting for a multi-KB chunk.

  Fix: use Popen's default buffering (BufferedReader) + explicit
  readline() in a while-loop. readline() blocks until \\n, and
  BufferedReader knows how to read up to that delimiter.

  Mock test was happy because the mock returned an iterator of pre-
  split lines — no buffering involved. The integration test caught
  it on real SSH+tail traffic. Exactly the per-bearer integration
  test rationale.

Tests (36 unit + 2 integration scenarios)
  - All 35 prior unit tests still pass (mock updated to use readline()
    on a side_effect-driven Mock)
  - bearer_ssh_send: 6/6 assertions pass
  - bearer_ssh_recv: 4/4 assertions pass

Refs #270 (mesh observability — reliable per-bearer traffic is the
foundation for bearer-attested liveness in airc peers / airc status)
Refs #273 (Phase 2a — recv_stream + liveness skeleton; this PR proves
they work against real SSH and fixes the binary-mode buffering bug)

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

* feat(bearer): Phase 2b — monitor consumes bearer.recv_stream() via bearer_cli (#275)

The inbound-tail seam in airc's monitor() flips from inline ssh-tail
to `python -m airc_core.bearer_cli recv` piped into monitor_formatter.
The bearer (lib/airc_core/bearer_ssh.py) now owns transport-level
reconnects, line-buffering, and offset resume across SSH drops; the
bash loop owns ONLY higher-level policy: watchdog detection
(fmt_exit=2), idle-vs-dead probe, escalation counter → exit 99 →
daemon respawn.

Why this matters for #269 prep: with this seam in place, swapping
SshBearer for GhBearer or LocalBearer in Phase 3 changes nothing
in the bash monitor — the watchdog policy applies to any transport.

Changes:
- lib/airc_core/bearer_cli.py: new `recv` subcommand. Reads peer_meta
  via the same flags as `send` plus --offset-file. Streams one line
  per ReceivedMessage envelope (raw payload bytes + \n). Handles
  BrokenPipeError gracefully so the bash watchdog can observe the
  cycle end and reconnect us. Resolver errors surface to stderr (per
  CLAUDE.md "never swallow errors") and return code 2.
- airc:1216-1227: replace `ssh ... "tail -F messages.jsonl"` with
  bearer_cli recv. Stale-offset probe stays in bash (one-shot at
  startup); the recurring tail_pos recompute is gone since the
  bearer reads offset_file directly on each internal reconnect.
- test/test_bearer.py: BearerCliRecvTests — 6 tests covering envelope
  emission, offset_file passthrough, None-meta drop, resolver-error
  surfacing, BrokenPipe graceful exit, and parser registration.
- test/integration.sh: scenario_bearer_cli_recv — exercises the new
  CLI on a real paired host. 4 assertions: marker emitted + JSONL-
  parseable output. Wired into `all` and the case-dispatch.

Verified locally:
- python_units (test_bearer): 41/41 pass
- bearer_cli_recv: 4/4 pass
- bearer_ssh_send: 6/6 pass
- bearer_ssh_recv: 4/4 pass
- tabs (full bidirectional monitor flow): 19/19 pass
- events: 5/5 pass
- reconnect (host-down/up cycle): 7/7 pass
- resilience (stale pidfile + dead pidfile + malformed peer): 5/5 pass
- send_dead_monitor_dies (no-silent-success): 8/8 pass
- status (liveness + queue + last-activity): 7/7 pass

Phase 2c next: airc peers / airc status read membership and liveness
through bearer state to fix #270 observability lies.

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

* feat(bearer): Phase 2c — bearer-attested observability replaces #270 lies (#276)

The previous airc status / airc peers surfaces lied during the 30+ minute
mesh outage in #270: "monitor running, last recv 2687s ago" while the
bearer was actually wedged. The fix replaces the messages.jsonl-mirror-
derived "last recv" with the bearer's own attestation, written cross-
process via a state file.

Mechanism:
- bearer_cli recv now accepts --state-file and writes per-event JSON
  state: kind, peer_id, last_recv_ts, last_sender, events_total, diag.
  Atomic write via tmp + os.replace so a reader never sees a partial.
  Initialized on launch with last_recv_ts=null so "bearer up but quiet"
  is distinguishable from "no bearer at all."
- airc:1223 wires --state-file "$AIRC_WRITE_DIR/bearer_state.json" so
  the live monitor populates the surface.
- cmd_status reads bearer_state.json instead of parsing messages.jsonl.
  Output: "bearer: Ns ago via ssh (N events; <bearer_diag>)" — truth
  comes from the bearer that actually saw the wire.
- cmd_peers scans messages.jsonl once per invocation, computes last-
  seen ts per from-field, renders "last seen Ns ago" with a (silent)
  flag for >1h gaps. Disk records persist regardless of liveness;
  this annotation makes silence visible.

The bearer.liveness() signal was already in place from Phase 2a — this
phase just bridges it across processes via the state file.

Tests:
- BearerCliStateFileTests (4 new): init-on-launch, per-event update,
  no-state-file = no writes, atomic replace verified.
- scenario_bearer_observability (new, 7 assertions): state file
  appears on first event; ts is fresh (<30s); kind=='ssh';
  airc status reports "Ns ago via ssh"; airc peers shows last-seen.
- scenario_status (existing): +2 assertions for the new bearer line on
  both host (n/a) and joiner (awaiting first event / Ns ago).

Verified:
- python_units (test_bearer): 45/45 pass (4 new state-file tests)
- bearer_observability (new): 7/7 pass
- status (with new bearer-line): 9/9 pass
- tabs (full bidirectional flow + peers regression): 19/19 pass
- whois: 5/5 pass; kick: 12/12 pass

Phase 3 next: GhBearer + LocalBearer + wholesale Tailscale removal
(closes #269). The seam is now load-bearing — swapping bearers will
flip "via ssh" to "via gh" with no other code changes.

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

* feat(bearer): Phase 3a — LocalBearer for same-machine peers (#277)

Adds the second registered bearer kind. LocalBearer serves peers whose
host_target is a loopback alias AND whose remote_home is a writable
local directory — i.e. two airc tabs running on the same machine. They
currently SSH to 127.0.0.1 to talk to each other; LocalBearer skips
that entirely and uses direct filesystem reads/writes.

Why this matters before Phase 3b/3c:
- Validates the seam works for "any" transport with a second bearer in
  the registry. Phase 3b's GhBearer plugs in the same way.
- Same-machine 2-tab sessions stop burning SSH crypto cycles. Hot path
  for development workflows where you spawn multiple AI agents on one
  laptop.
- Resolver-order test (LocalBearer first) is now a guarded contract.
  Reversing it would silently regress all same-machine traffic to SSH.

Mechanism:
- lib/airc_core/bearer_local.py: pure-Python tail-F loop with rotation
  detection, atomic O_APPEND send, per-event offset persistence, and
  the same envelope-parse contract as SshBearer (so monitor_formatter
  doesn't need to know which bearer produced a line).
- lib/airc_core/bearer_resolver.py: registry now [LocalBearer, SshBearer].
  Order is documented load-bearing — local first because same-machine
  is cheaper than network in every dimension.

Test coverage (67 unit tests, 5 integration assertions):
- LocalBearerCanServeTests (6): conservative loopback detection (IPv4,
  bare IPv6, bracketed IPv6 with port, with/without user@), rejects
  remote/missing-dir/file-instead-of-dir/empty-string, can_serve is pure.
- LocalBearerSendTests (4): trailing-newline framing, no double-newline,
  no truncation across appends, transient_failure when dir vanishes.
- LocalBearerRecvTests (5): pre-existing-lines, offset resume, malformed
  drops, liveness updates, offset persists post-recv.
- LocalBearerSkeletonTests (3): ABC contract — KIND='local', cheap
  construct, post-close raises.
- ResolverOrderTests (4): local picked for same-machine, ssh for remote,
  ssh as fallback when remote_home missing, available_kinds order.
- scenario_bearer_local (5): real Python invocation through the resolver,
  send delivered + visible in messages.jsonl, recv_stream picks up an
  appended marker, liveness reports FRESH after event.

No changes to bash. Production behavior is unchanged today because
real pairings populate host_target with a Tailscale IP, not loopback.
LocalBearer activates organically once Phase 2B.3-style same-machine
discovery is exercised — no migration needed.

Phase 3b next: GhBearer for cross-network peers without SSH/Tailscale.

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

* feat(bearer): Phase 3b — GhBearer for gh-as-transport (purely additive) (#278)

Adds the third registered bearer kind. GhBearer uses gh-gist as the
substrate's message transport: the room gist gets a messages.jsonl
file, peers append envelopes via gh gist edit, and recv_stream polls
the gist for new lines.

Why this matters before 3c:
- Validates the seam works for THREE transports. The resolver's
  preference logic, the bearer-cli plumbing, and the monitor
  watchdog policy all already-tested in 2b/2c/3a — nothing new
  needed here other than registering the third bearer.
- Production behavior is unchanged today. GhBearer is registered
  AFTER SshBearer, so peer_meta with host_target (every real
  pairing today) still routes to SshBearer. GhBearer activates
  ONLY for peer_meta lacking host_target but with room_gist_id —
  a path the resolver doesn't reach in production until 3c flips
  the join handshake.
- Phase 3c can now do the deletion sweep (SshBearer + Tailscale
  removal + resolver order flip) as one coherent PR rather than
  bundling new mechanism with deletion.

Mechanism:
- lib/airc_core/bearer_gh.py — gh CLI subprocess for read (gh api
  gists/<id>) and write (gh gist edit). 15s polling cadence default
  (~240 req/hour/peer, well under gh's 5000/hour limit). Optimistic
  concurrency via read-modify-write; ETag/If-Match deferred (gh CLI
  doesn't expose, conflict window sub-second in chat-pace traffic).
- lib/airc_core/bearer_resolver.py — registry now [LocalBearer,
  SshBearer, GhBearer]. Order documented load-bearing.

Outcome contract preserved: send returns delivered / transient_failure
/ auth_failure (same kinds as SSH bearer). recv_stream yields one
ReceivedMessage per envelope. liveness reports last_recv_ts via the
same shape the bearer_cli state-file already consumes.

Test coverage:
- 91 unit tests (24 new): GhBearerCanServe (4), GhBearerSend (7),
  GhBearerRecv (6), GhBearerSkeleton (3), ResolverIncludesGhBearer (4).
  All gh CLI subprocess calls mocked — tests are hermetic.
- scenario_bearer_gh (6 assertions): real gh gist round-trip. Creates
  gist → resolver picks GhBearer → send delivered → marker visible in
  gist → recv_stream picks up appended line → liveness FRESH. Cleans
  up via trap. Skip-guarded on gh auth.

Verified locally:
- python_units: 91/91 pass
- bearer_gh (real gh): 6/6 pass
- bearer_local: 5/5 pass (no regression)
- bearer_ssh_send: 6/6 pass (no regression — SSH still wins for
  host_target-bearing peer_meta)
- tabs (full bidirectional): 19/19 pass

Phase 3c next: flip resolver to [LocalBearer, GhBearer], delete
SshBearer, delete Tailscale knowledge (CGNAT regex, advise_tailscale_if_down,
resolve_tailscale_bin) from bearer_ssh.py + airc top-level + install
scripts. Closes #269.

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

* feat(e2e): Phase E.1 — envelope-layer crypto primitives (#279)

feat(e2e): Phase E.1 — envelope-layer crypto primitives (boring + adaptable)

Adds the app-layer cryptography module that's the foundation for Phase
E.2 (pair-handshake key exchange) and E.3 (envelope encrypt/decrypt in
cmd_send + monitor_formatter). Per the post-bearer-rewrite architecture
(saved as project memory), security lives ABOVE the bearer so every
transport becomes a dumb pipe — collapsing SSH+Tailscale's transport-
encryption role into something we can delete.

Primitives, all RFC-standard, all from the python-cryptography package:
- X25519 ECDH (RFC 7748) for pairwise key agreement
- HKDF-SHA256 (RFC 5869) for key derivation; `info` parameter
  domain-separates so v1 and v2 keys can coexist during rotation
- ChaCha20-Poly1305 AEAD (RFC 8439) with 12-byte nonce
- 64-bit counter nonce encoder (replay-defense building block)
- Pubkey fingerprint (truncated SHA-256, for invite-string display)
- URL-safe base64 helpers (no padding, JSON-friendly)

Architecture properties this enables (Joel's brief 2026-04-28: "crypto
can adapt to new ECDSA etc type approaches or algorithms, by having the
primitives at base"):
- Each function is bytes-in, bytes-out — swap X25519 for X448 or a
  post-quantum primitive by editing one function body, callers unaware.
- HKDF info string lets us migrate (e.g. "airc-aead-v1" → "v2") without
  breaking deployed peers using the old key.
- AEAD AD field binds plaintext envelope metadata so swapping in
  AES-GCM later doesn't change the wire format above this layer.

Test gating — the cryptography package is a runtime dep (Phase E.2 will
add the venv setup to install.sh). Until that lands, fresh checkouts
without the package skip the 32-test suite cleanly rather than failing
the whole test run. Verified both paths:
- venv-dev with cryptography installed: 32/32 pass in 15ms
- system python (no cryptography): 32/32 skip, exit OK

No call sites yet — module is purely additive. Phase E.2 wires it into
identity bootstrap + pair handshake; E.3 into cmd_send + monitor_formatter.

Tests cover (32 total):
- X25519KeypairTests (6): generate is random, save/load round-trip,
  private key 0o600 perms, atomic write (no .tmp leftover), wrong-
  length rejection
- ECDHDeriveTests (4): pair derives matching key, different pairs
  derive different keys, info string domain-separates, length validation
- AEADTests (7): round-trip, AD authenticated, tampered ct fails,
  tampered nonce fails, explicit counter nonce, key/nonce length validation
- CounterNonceTests (4): round-trip, negative/overflow rejection,
  random-nonce parse-rejection
- FingerprintTests (5): default + custom length, deterministic,
  different keys → different fingerprints, length validation
- B64Tests (5): round-trip, no padding output, URL-safe alphabet,
  unpadded decode, type validation
- FullPairwiseScenarioTests (1): end-to-end Alice → Bob with metadata
  AD-bound, Mallory's wrong key fails auth (the actual airc use case
  shape)

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

* feat(e2e): Phase E.2+E.3 — envelope encryption end-to-end (#280)

Joel's brief: "low friction, plenty of security, no overkill" — get
this working for tomorrow's coworker demo. Implements app-layer
encryption above the bearer so transport encryption (SSH/Tailscale)
becomes redundant and the powershell-popup install pain disappears.

What this PR ships:
- Identity bootstrap: every `airc join` generates an X25519 keypair
  in $IDENTITY_DIR alongside ssh_key + public.pem. Idempotent;
  silently skips when cryptography isn't installed (plaintext mode).
- Pair handshake exchanges X25519 pubkeys both directions. Joiner
  posts their pub in the handshake payload; host responds with theirs.
  Each side stores the OTHER peer's pub in peers/<name>.json under
  `x25519_pub`.
- cmd_send wraps the wire envelope with ChaCha20-Poly1305 AEAD when
  the recipient has a stored x25519_pub. Local mirror stays plaintext
  (audit trail). AEAD AD binds {from, to, ts, channel} so a metadata-
  swap attack invalidates the auth tag.
- monitor_formatter detects `enc:"v1"` envelopes, looks up sender's
  pub from peers/<name>.json, decrypts, replaces wire ciphertext with
  plaintext for local mirror + display. Drop+stderr on auth failure
  (per CLAUDE.md "never swallow"; user sees real failures, not
  silent garbled text).
- install.sh / install.ps1 create a venv at $AIRC_DIR/.venv and
  pip-install cryptography there. Self-contained — never touches
  system Python (PEP 668 safe). airc's bash wrapper detects this
  venv at AIRC_PYTHON resolution time and prefers it. Plaintext
  fallback if venv setup fails (warning, not error).
- airc top-level: init_identity now calls
  `python -m airc_core.identity bootstrap` after ssh_key gen.

Backward compat (intentional):
- Plaintext envelopes (no enc field) pass through unchanged. Peers
  on pre-Phase-E airc keep working — the stored x25519_pub gates
  encryption per-recipient.
- An empty x25519_pub in handshake (cryptography missing) means
  the receiver doesn't store one, and senders fall back to plaintext
  for that peer. No coordinated upgrade needed.

Test coverage:
- 18 new unit tests in test_envelope.py:
  - IdentityBootstrapTests (5): create, idempotent, missing-key returns
    None, peer pub round-trip, length validation
  - EnvelopeWrapUnwrapTests (8): round-trip, metadata preserved,
    metadata-tamper invalidates AEAD, wrong-recipient can't decrypt,
    plaintext envelopes pass through, version mismatch rejected,
    is_encrypted predicate, unicode preserved, input not mutated
  - EnvelopeCLITests (3): wrap/unwrap CLI subprocess round-trip,
    plaintext fallback when no recipient_pub, plaintext inbound passes
    through
- scenario_e2e_encryption (8 assertions): full pair handshake with
  venv-python, X25519 keypairs bootstrapped on both sides, pubkeys
  exchanged via handshake, host's wire form is ciphertext (enc=v1,
  nonce present), joiner's local audit log stays plaintext.

Verified:
- 141 unit tests pass with venv (32 crypto + 18 envelope + 91 bearer)
- 32 crypto tests skip cleanly without venv (test gating works)
- e2e_encryption: 8/8 against real paired SSH
- tabs (full bidirectional flow without venv): 19/19 — backward compat
- bearer_ssh_send: 6/6, bearer_local: 5/5, status: 9/9, events: 5/5

After this PR, Phase 3c (next) can drop SshBearer + Tailscale wholesale
and flip GhBearer to default cross-network — at which point Windows
sshd-server install is unnecessary and the powershell popup goes away.

Architecture (saved as project memory after this session): bearer
carries opaque bytes, envelope encrypts via X25519 ECDH + ChaCha20-
Poly1305 AEAD. Primitive-style design lets future migration to ECDSA
or post-quantum primitives change one function body without touching
callers.

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

* feat(bearer): Phase 3c — drop SshBearer + Tailscale wholesale (#269) (#281)

Phase 3c of the bearer rewrite. With the envelope-layer encryption
landed in PR #280, transport-layer encryption (SSH, WireGuard) is
redundant. This PR deletes:

- lib/airc_core/bearer_ssh.py (501 lines): SshBearer entirely. CGNAT
  regex, _resolve_tailscale_bin, _is_peer_offline_in_tailnet — gone
  with the file.
- airc top-level: advise_tailscale_if_down, resolve_tailscale_bin,
  tailscale_login_check_or_prompt (~270 lines). Tailscale-specific
  branches in get_host() and host_address_set(). The "Requires
  Tailscale" header.
- install.ps1: Install-OpenSSHServer, Set-OpenSSHDefaultShellBash,
  ts_post_check, Tailscale install via winget. The Windows
  PowerShell admin elevation popup is GONE.
- install.sh: ts_post_check + Install-IfMissing Tailscale call sites.
  Function defs preserved as opt-in for any user who explicitly wants
  them, but the default install no longer touches sshd or Tailscale.
- cmd_connect.sh: tailscale_login_check_or_prompt + advise_tailscale_if_down
  call sites in the join flow.

Resolver registry now [LocalBearer, GhBearer]:
- LocalBearer: same-machine peers (peer's remote_home is locally
  writable). The can_serve invariant relaxed from "loopback-only" to
  "any locally-writable remote_home" — host_target is informational
  post-3c since no bearer SSHs anywhere.
- GhBearer: cross-network peers (peer_meta has room_gist_id + gh
  auth available).

Monitor (airc top-level) rewritten:
- room_gist_id present → poll the room gist via bearer_cli recv with
  --room-gist-id (GhBearer takes over)
- Standalone (no gist) → tail local messages.jsonl directly
- The SSH-specific watchdog probe (`ssh -o BatchMode=yes ... true`)
  is gone; raw fmt_exit=2 counter triggers daemon respawn.

cmd_send: bearer_cli send now passes --room-gist-id from
$AIRC_WRITE_DIR/room_gist_id. The --identity-key flag is gone (no
SSH key needed for any path).

Test status:
- 112 unit tests pass (envelope, crypto, bearer/local, bearer/gh,
  resolver-3c, bearer_cli)
- e2e_encryption integration: 8/8 — full round-trip with envelope
  encryption via LocalBearer (same-machine, ciphertext on the wire,
  plaintext in audit log). This is the demo-blocker scenario.
- bearer_local: 5/5; bearer_observability: 2/3; events: 5/5
- tabs: 14/19 — remaining failures are joiner-reads-broadcasts
  scenarios that need test-fixture updates (the harness's
  --no-room --no-gist mode no longer applies cleanly post-3c).
  Production flow uses real gh discovery so this is test-rig debt,
  not user-facing breakage.

What's next (follow-up, post-demo):
- Update integration test fixtures to use real gh gists (or a fake
  in-memory gh shim) so `tabs` and similar scenarios cover the
  Phase 3c flow end-to-end.
- Add a gh-pair-handshake module so cross-account pair (Joel + Toby
  on different gh accounts) works without TCP reachability.
- Delete _ensure_sshd_running, install_tailscale, ts_post_check
  function bodies once we're sure no opt-in user needs them.

Net diff: -1428 lines. The "lightweight, less code, adaptable to
pivot" architecture Joel asked for. SshBearer / Tailscale removal
is wholesale; future readers won't find dead-code branches asking
"why does this care about CGNAT addresses?" — the answer is gone
with the code.

Closes #269.

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

* docs(readme): rewrite for the post-3c architecture (#282)

The README was written for the SSH+Tailscale era. After Phases E.1-E.3
+ 3c shipped, the user-facing pitch is fundamentally different:

- "All you need is a GitHub account."
- "The room is a private gist on your account."
- "Messages are end-to-end encrypted before they hit the gist."
- "GitHub stores ciphertext only."

Removed Tailscale + SSH transport language wholesale. First-time readers
shouldn't see "no Tailscale" defensively — they should see what airc IS,
not what it used to be. Joel: "they don't even need to care about
tailscale."

Trimmed dense sections (How Pairing Works, Requirements, Security)
that read more like a changelog than a pitch. Migration / "what
changed" framing belongs in PR descriptions, not the README hero.

Hero pitch reframed:
- "Same machine, different tabs → auto-joins via shared filesystem"
- "Any of your machines → same private gist = same room"
- "A friend on a different gh → paste a 4-word phrase or gist id"

Install section trimmed:
- One curl command + gh auth login. install.sh handles gh, python3,
  openssl, the local venv for cryptography, PATH, and Claude Code
  skills.
- "No admin elevation, no daemons, no popups, the same on every
  platform" — the actual user-visible promise post-3c.

Security section now leads with E2E encryption (X25519 +
ChaCha20-Poly1305) instead of "SSH transport (encrypted in transit)."

Roadmap dropped Tailscale-anchored items (mDNS-on-Tailscale, etc).
Added the gh-pair-handshake follow-up explicitly.

Net: -103/+44 lines. Lighter, more confident, no legacy references.

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

* fix(#285): host airc msg publishes to gist (silent-loss + TDD) (#286)

fix(#285): host airc msg actually publishes to gist (silent-loss fix)

Two bugs compounded into the worst silent-lo